goldenlayout.js 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237
  1. (function($){var lm={"config":{},"container":{},"controls":{},"errors":{},"items":{},"utils":{}};
  2. lm.utils.F = function() {
  3. };
  4. lm.utils.extend = function( subClass, superClass ) {
  5. subClass.prototype = lm.utils.createObject( superClass.prototype );
  6. subClass.prototype.contructor = subClass;
  7. };
  8. lm.utils.createObject = function( prototype ) {
  9. if( typeof Object.create === 'function' ) {
  10. return Object.create( prototype );
  11. } else {
  12. lm.utils.F.prototype = prototype;
  13. return new lm.utils.F();
  14. }
  15. };
  16. lm.utils.objectKeys = function( object ) {
  17. var keys, key;
  18. if( typeof Object.keys === 'function' ) {
  19. return Object.keys( object );
  20. } else {
  21. keys = [];
  22. for( key in object ) {
  23. keys.push( key );
  24. }
  25. return keys;
  26. }
  27. };
  28. lm.utils.getHashValue = function( key ) {
  29. var matches = location.hash.match( new RegExp( key + '=([^&]*)' ) );
  30. return matches ? matches[ 1 ] : null;
  31. };
  32. lm.utils.getQueryStringParam = function( param ) {
  33. if( window.location.hash ) {
  34. return lm.utils.getHashValue( param );
  35. } else if( !window.location.search ) {
  36. return null;
  37. }
  38. var keyValuePairs = window.location.search.substr( 1 ).split( '&' ),
  39. params = {},
  40. pair,
  41. i;
  42. for( i = 0; i < keyValuePairs.length; i++ ) {
  43. pair = keyValuePairs[ i ].split( '=' );
  44. params[ pair[ 0 ] ] = pair[ 1 ];
  45. }
  46. return params[ param ] || null;
  47. };
  48. lm.utils.copy = function( target, source ) {
  49. for( var key in source ) {
  50. target[ key ] = source[ key ];
  51. }
  52. return target;
  53. };
  54. /**
  55. * This is based on Paul Irish's shim, but looks quite odd in comparison. Why?
  56. * Because
  57. * a) it shouldn't affect the global requestAnimationFrame function
  58. * b) it shouldn't pass on the time that has passed
  59. *
  60. * @param {Function} fn
  61. *
  62. * @returns {void}
  63. */
  64. lm.utils.animFrame = function( fn ) {
  65. return ( window.requestAnimationFrame ||
  66. window.webkitRequestAnimationFrame ||
  67. window.mozRequestAnimationFrame ||
  68. function( callback ) {
  69. window.setTimeout( callback, 1000 / 60 );
  70. })( function() {
  71. fn();
  72. } );
  73. };
  74. lm.utils.indexOf = function( needle, haystack ) {
  75. if( !( haystack instanceof Array ) ) {
  76. throw new Error( 'Haystack is not an Array' );
  77. }
  78. if( haystack.indexOf ) {
  79. return haystack.indexOf( needle );
  80. } else {
  81. for( var i = 0; i < haystack.length; i++ ) {
  82. if( haystack[ i ] === needle ) {
  83. return i;
  84. }
  85. }
  86. return -1;
  87. }
  88. };
  89. if( typeof /./ != 'function' && typeof Int8Array != 'object' ) {
  90. lm.utils.isFunction = function( obj ) {
  91. return typeof obj == 'function' || false;
  92. };
  93. } else {
  94. lm.utils.isFunction = function( obj ) {
  95. return toString.call( obj ) === '[object Function]';
  96. };
  97. }
  98. lm.utils.fnBind = function( fn, context, boundArgs ) {
  99. if( Function.prototype.bind !== undefined ) {
  100. return Function.prototype.bind.apply( fn, [ context ].concat( boundArgs || [] ) );
  101. }
  102. var bound = function() {
  103. // Join the already applied arguments to the now called ones (after converting to an array again).
  104. var args = ( boundArgs || [] ).concat( Array.prototype.slice.call( arguments, 0 ) );
  105. // If not being called as a constructor
  106. if( !(this instanceof bound) ) {
  107. // return the result of the function called bound to target and partially applied.
  108. return fn.apply( context, args );
  109. }
  110. // If being called as a constructor, apply the function bound to self.
  111. fn.apply( this, args );
  112. };
  113. // Attach the prototype of the function to our newly created function.
  114. bound.prototype = fn.prototype;
  115. return bound;
  116. };
  117. lm.utils.removeFromArray = function( item, array ) {
  118. var index = lm.utils.indexOf( item, array );
  119. if( index === -1 ) {
  120. throw new Error( 'Can\'t remove item from array. Item is not in the array' );
  121. }
  122. array.splice( index, 1 );
  123. };
  124. lm.utils.now = function() {
  125. if( typeof Date.now === 'function' ) {
  126. return Date.now();
  127. } else {
  128. return ( new Date() ).getTime();
  129. }
  130. };
  131. lm.utils.getUniqueId = function() {
  132. return ( Math.random() * 1000000000000000 )
  133. .toString( 36 )
  134. .replace( '.', '' );
  135. };
  136. /**
  137. * A basic XSS filter. It is ultimately up to the
  138. * implementing developer to make sure their particular
  139. * applications and usecases are save from cross site scripting attacks
  140. *
  141. * @param {String} input
  142. * @param {Boolean} keepTags
  143. *
  144. * @returns {String} filtered input
  145. */
  146. lm.utils.filterXss = function( input, keepTags ) {
  147. var output = input
  148. .replace( /javascript/gi, 'j&#97;vascript' )
  149. .replace( /expression/gi, 'expr&#101;ssion' )
  150. .replace( /onload/gi, 'onlo&#97;d' )
  151. .replace( /script/gi, '&#115;cript' )
  152. .replace( /onerror/gi, 'on&#101;rror' );
  153. if( keepTags === true ) {
  154. return output;
  155. } else {
  156. return output
  157. .replace( />/g, '&gt;' )
  158. .replace( /</g, '&lt;' );
  159. }
  160. };
  161. /**
  162. * Removes html tags from a string
  163. *
  164. * @param {String} input
  165. *
  166. * @returns {String} input without tags
  167. */
  168. lm.utils.stripTags = function( input ) {
  169. return $.trim( input.replace( /(<([^>]+)>)/ig, '' ) );
  170. };
  171. /**
  172. * A generic and very fast EventEmitter
  173. * implementation. On top of emitting the
  174. * actual event it emits an
  175. *
  176. * lm.utils.EventEmitter.ALL_EVENT
  177. *
  178. * event for every event triggered. This allows
  179. * to hook into it and proxy events forwards
  180. *
  181. * @constructor
  182. */
  183. lm.utils.EventEmitter = function() {
  184. this._mSubscriptions = {};
  185. this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ] = [];
  186. /**
  187. * Listen for events
  188. *
  189. * @param {String} sEvent The name of the event to listen to
  190. * @param {Function} fCallback The callback to execute when the event occurs
  191. * @param {[Object]} oContext The value of the this pointer within the callback function
  192. *
  193. * @returns {void}
  194. */
  195. this.on = function( sEvent, fCallback, oContext ) {
  196. if( !lm.utils.isFunction( fCallback ) ) {
  197. throw new Error( 'Tried to listen to event ' + sEvent + ' with non-function callback ' + fCallback );
  198. }
  199. if( !this._mSubscriptions[ sEvent ] ) {
  200. this._mSubscriptions[ sEvent ] = [];
  201. }
  202. this._mSubscriptions[ sEvent ].push( { fn: fCallback, ctx: oContext } );
  203. };
  204. /**
  205. * Emit an event and notify listeners
  206. *
  207. * @param {String} sEvent The name of the event
  208. * @param {Mixed} various additional arguments that will be passed to the listener
  209. *
  210. * @returns {void}
  211. */
  212. this.emit = function( sEvent ) {
  213. var i, ctx, args;
  214. args = Array.prototype.slice.call( arguments, 1 );
  215. if( this._mSubscriptions[ sEvent ] ) {
  216. for( i = 0; i < this._mSubscriptions[ sEvent ].length; i++ ) {
  217. ctx = this._mSubscriptions[ sEvent ][ i ].ctx || {};
  218. this._mSubscriptions[ sEvent ][ i ].fn.apply( ctx, args );
  219. }
  220. }
  221. args.unshift( sEvent );
  222. for( i = 0; i < this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ].length; i++ ) {
  223. ctx = this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ][ i ].ctx || {};
  224. this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ][ i ].fn.apply( ctx, args );
  225. }
  226. };
  227. /**
  228. * Removes a listener for an event, or all listeners if no callback and context is provided.
  229. *
  230. * @param {String} sEvent The name of the event
  231. * @param {Function} fCallback The previously registered callback method (optional)
  232. * @param {Object} oContext The previously registered context (optional)
  233. *
  234. * @returns {void}
  235. */
  236. this.unbind = function( sEvent, fCallback, oContext ) {
  237. if( !this._mSubscriptions[ sEvent ] ) {
  238. throw new Error( 'No subscribtions to unsubscribe for event ' + sEvent );
  239. }
  240. var i, bUnbound = false;
  241. for( i = 0; i < this._mSubscriptions[ sEvent ].length; i++ ) {
  242. if
  243. (
  244. ( !fCallback || this._mSubscriptions[ sEvent ][ i ].fn === fCallback ) &&
  245. ( !oContext || oContext === this._mSubscriptions[ sEvent ][ i ].ctx )
  246. ) {
  247. this._mSubscriptions[ sEvent ].splice( i, 1 );
  248. bUnbound = true;
  249. }
  250. }
  251. if( bUnbound === false ) {
  252. throw new Error( 'Nothing to unbind for ' + sEvent );
  253. }
  254. };
  255. /**
  256. * Alias for unbind
  257. */
  258. this.off = this.unbind;
  259. /**
  260. * Alias for emit
  261. */
  262. this.trigger = this.emit;
  263. };
  264. /**
  265. * The name of the event that's triggered for every other event
  266. *
  267. * usage
  268. *
  269. * myEmitter.on( lm.utils.EventEmitter.ALL_EVENT, function( eventName, argsArray ){
  270. * //do stuff
  271. * });
  272. *
  273. * @type {String}
  274. */
  275. lm.utils.EventEmitter.ALL_EVENT = '__all';
  276. lm.utils.DragListener = function( eElement, nButtonCode ) {
  277. lm.utils.EventEmitter.call( this );
  278. this._eElement = $( eElement );
  279. this._oDocument = $( document );
  280. this._eBody = $( document.body );
  281. this._nButtonCode = nButtonCode || 0;
  282. /**
  283. * The delay after which to start the drag in milliseconds
  284. */
  285. this._nDelay = 200;
  286. /**
  287. * The distance the mouse needs to be moved to qualify as a drag
  288. */
  289. this._nDistance = 10;//TODO - works better with delay only
  290. this._nX = 0;
  291. this._nY = 0;
  292. this._nOriginalX = 0;
  293. this._nOriginalY = 0;
  294. this._bDragging = false;
  295. this._fMove = lm.utils.fnBind( this.onMouseMove, this );
  296. this._fUp = lm.utils.fnBind( this.onMouseUp, this );
  297. this._fDown = lm.utils.fnBind( this.onMouseDown, this );
  298. this._eElement.on( 'mousedown touchstart', this._fDown );
  299. };
  300. lm.utils.DragListener.timeout = null;
  301. lm.utils.copy( lm.utils.DragListener.prototype, {
  302. destroy: function() {
  303. this._eElement.unbind( 'mousedown touchstart', this._fDown );
  304. },
  305. onMouseDown: function( oEvent ) {
  306. oEvent.preventDefault();
  307. if( oEvent.button == 0 || oEvent.type === "touchstart" ) {
  308. var coordinates = this._getCoordinates( oEvent );
  309. this._nOriginalX = coordinates.x;
  310. this._nOriginalY = coordinates.y;
  311. this._oDocument.on( 'mousemove touchmove', this._fMove );
  312. this._oDocument.one( 'mouseup touchend', this._fUp );
  313. this._timeout = setTimeout( lm.utils.fnBind( this._startDrag, this ), this._nDelay );
  314. }
  315. },
  316. onMouseMove: function( oEvent ) {
  317. if( this._timeout != null ) {
  318. oEvent.preventDefault();
  319. var coordinates = this._getCoordinates( oEvent );
  320. this._nX = coordinates.x - this._nOriginalX;
  321. this._nY = coordinates.y - this._nOriginalY;
  322. if( this._bDragging === false ) {
  323. if(
  324. Math.abs( this._nX ) > this._nDistance ||
  325. Math.abs( this._nY ) > this._nDistance
  326. ) {
  327. clearTimeout( this._timeout );
  328. this._startDrag();
  329. }
  330. }
  331. if( this._bDragging ) {
  332. this.emit( 'drag', this._nX, this._nY, oEvent );
  333. }
  334. }
  335. },
  336. onMouseUp: function( oEvent ) {
  337. if( this._timeout != null ) {
  338. clearTimeout( this._timeout );
  339. this._eBody.removeClass( 'lm_dragging' );
  340. this._eElement.removeClass( 'lm_dragging' );
  341. this._oDocument.find( 'iframe' ).css( 'pointer-events', '' );
  342. this._oDocument.unbind( 'mousemove touchmove', this._fMove );
  343. if( this._bDragging === true ) {
  344. this._bDragging = false;
  345. this.emit( 'dragStop', oEvent, this._nOriginalX + this._nX );
  346. }
  347. }
  348. },
  349. _startDrag: function() {
  350. this._bDragging = true;
  351. this._eBody.addClass( 'lm_dragging' );
  352. this._eElement.addClass( 'lm_dragging' );
  353. this._oDocument.find( 'iframe' ).css( 'pointer-events', 'none' );
  354. this.emit( 'dragStart', this._nOriginalX, this._nOriginalY );
  355. },
  356. _getCoordinates: function( event ) {
  357. event = event.originalEvent && event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event;
  358. return {
  359. x: event.pageX,
  360. y: event.pageY
  361. };
  362. }
  363. } );
  364. /**
  365. * The main class that will be exposed as GoldenLayout.
  366. *
  367. * @public
  368. * @constructor
  369. * @param {GoldenLayout config} config
  370. * @param {[DOM element container]} container Can be a jQuery selector string or a Dom element. Defaults to body
  371. *
  372. * @returns {VOID}
  373. */
  374. lm.LayoutManager = function( config, container ) {
  375. if( !$ || typeof $.noConflict !== 'function' ) {
  376. var errorMsg = 'jQuery is missing as dependency for GoldenLayout. ';
  377. errorMsg += 'Please either expose $ on GoldenLayout\'s scope (e.g. window) or add "jquery" to ';
  378. errorMsg += 'your paths when using RequireJS/AMD';
  379. throw new Error( errorMsg );
  380. }
  381. lm.utils.EventEmitter.call( this );
  382. this.isInitialised = false;
  383. this._isFullPage = false;
  384. this._resizeTimeoutId = null;
  385. this._components = { 'lm-react-component': lm.utils.ReactComponentHandler };
  386. this._itemAreas = [];
  387. this._resizeFunction = lm.utils.fnBind( this._onResize, this );
  388. this._unloadFunction = lm.utils.fnBind( this._onUnload, this );
  389. this._maximisedItem = null;
  390. this._maximisePlaceholder = $( '<div class="lm_maximise_place"></div>' );
  391. this._creationTimeoutPassed = false;
  392. this._subWindowsCreated = false;
  393. this._dragSources = [];
  394. this._updatingColumnsResponsive = false;
  395. this._firstLoad = true;
  396. this.width = null;
  397. this.height = null;
  398. this.root = null;
  399. this.openPopouts = [];
  400. this.selectedItem = null;
  401. this.isSubWindow = false;
  402. this.eventHub = new lm.utils.EventHub( this );
  403. this.config = this._createConfig( config );
  404. this.container = container;
  405. this.dropTargetIndicator = null;
  406. this.transitionIndicator = null;
  407. this.tabDropPlaceholder = $( '<div class="lm_drop_tab_placeholder"></div>' );
  408. if( this.isSubWindow === true ) {
  409. $( 'body' ).css( 'visibility', 'hidden' );
  410. }
  411. this._typeToItem = {
  412. 'column': lm.utils.fnBind( lm.items.RowOrColumn, this, [ true ] ),
  413. 'row': lm.utils.fnBind( lm.items.RowOrColumn, this, [ false ] ),
  414. 'stack': lm.items.Stack,
  415. 'component': lm.items.Component
  416. };
  417. };
  418. /**
  419. * Hook that allows to access private classes
  420. */
  421. lm.LayoutManager.__lm = lm;
  422. /**
  423. * Takes a GoldenLayout configuration object and
  424. * replaces its keys and values recursively with
  425. * one letter codes
  426. *
  427. * @static
  428. * @public
  429. * @param {Object} config A GoldenLayout config object
  430. *
  431. * @returns {Object} minified config
  432. */
  433. lm.LayoutManager.minifyConfig = function( config ) {
  434. return ( new lm.utils.ConfigMinifier() ).minifyConfig( config );
  435. };
  436. /**
  437. * Takes a configuration Object that was previously minified
  438. * using minifyConfig and returns its original version
  439. *
  440. * @static
  441. * @public
  442. * @param {Object} minifiedConfig
  443. *
  444. * @returns {Object} the original configuration
  445. */
  446. lm.LayoutManager.unminifyConfig = function( config ) {
  447. return ( new lm.utils.ConfigMinifier() ).unminifyConfig( config );
  448. };
  449. lm.utils.copy( lm.LayoutManager.prototype, {
  450. /**
  451. * Register a component with the layout manager. If a configuration node
  452. * of type component is reached it will look up componentName and create the
  453. * associated component
  454. *
  455. * {
  456. * type: "component",
  457. * componentName: "EquityNewsFeed",
  458. * componentState: { "feedTopic": "us-bluechips" }
  459. * }
  460. *
  461. * @public
  462. * @param {String} name
  463. * @param {Function} constructor
  464. *
  465. * @returns {void}
  466. */
  467. registerComponent: function( name, constructor ) {
  468. if( typeof constructor !== 'function' ) {
  469. throw new Error( 'Please register a constructor function' );
  470. }
  471. if( this._components[ name ] !== undefined ) {
  472. throw new Error( 'Component ' + name + ' is already registered' );
  473. }
  474. this._components[ name ] = constructor;
  475. },
  476. /**
  477. * Creates a layout configuration object based on the the current state
  478. *
  479. * @public
  480. * @returns {Object} GoldenLayout configuration
  481. */
  482. toConfig: function( root ) {
  483. var config, next, i;
  484. if( this.isInitialised === false ) {
  485. throw new Error( 'Can\'t create config, layout not yet initialised' );
  486. }
  487. if( root && !( root instanceof lm.items.AbstractContentItem ) ) {
  488. throw new Error( 'Root must be a ContentItem' );
  489. }
  490. /*
  491. * settings & labels
  492. */
  493. config = {
  494. settings: lm.utils.copy( {}, this.config.settings ),
  495. dimensions: lm.utils.copy( {}, this.config.dimensions ),
  496. labels: lm.utils.copy( {}, this.config.labels )
  497. };
  498. /*
  499. * Content
  500. */
  501. config.content = [];
  502. next = function( configNode, item ) {
  503. var key, i;
  504. for( key in item.config ) {
  505. if( key !== 'content' ) {
  506. configNode[ key ] = item.config[ key ];
  507. }
  508. }
  509. if( item.contentItems.length ) {
  510. configNode.content = [];
  511. for( i = 0; i < item.contentItems.length; i++ ) {
  512. configNode.content[ i ] = {};
  513. next( configNode.content[ i ], item.contentItems[ i ] );
  514. }
  515. }
  516. };
  517. if( root ) {
  518. next( config, { contentItems: [ root ] } );
  519. } else {
  520. next( config, this.root );
  521. }
  522. /*
  523. * Retrieve config for subwindows
  524. */
  525. this._$reconcilePopoutWindows();
  526. config.openPopouts = [];
  527. for( i = 0; i < this.openPopouts.length; i++ ) {
  528. config.openPopouts.push( this.openPopouts[ i ].toConfig() );
  529. }
  530. /*
  531. * Add maximised item
  532. */
  533. config.maximisedItemId = this._maximisedItem ? '__glMaximised' : null;
  534. return config;
  535. },
  536. /**
  537. * Returns a previously registered component
  538. *
  539. * @public
  540. * @param {String} name The name used
  541. *
  542. * @returns {Function}
  543. */
  544. getComponent: function( name ) {
  545. if( this._components[ name ] === undefined ) {
  546. throw new lm.errors.ConfigurationError( 'Unknown component "' + name + '"' );
  547. }
  548. return this._components[ name ];
  549. },
  550. /**
  551. * Creates the actual layout. Must be called after all initial components
  552. * are registered. Recurses through the configuration and sets up
  553. * the item tree.
  554. *
  555. * If called before the document is ready it adds itself as a listener
  556. * to the document.ready event
  557. *
  558. * @public
  559. *
  560. * @returns {void}
  561. */
  562. init: function() {
  563. /**
  564. * Create the popout windows straight away. If popouts are blocked
  565. * an error is thrown on the same 'thread' rather than a timeout and can
  566. * be caught. This also prevents any further initilisation from taking place.
  567. */
  568. if( this._subWindowsCreated === false ) {
  569. this._createSubWindows();
  570. this._subWindowsCreated = true;
  571. }
  572. /**
  573. * If the document isn't ready yet, wait for it.
  574. */
  575. if( document.readyState === 'loading' || document.body === null ) {
  576. $( document ).ready( lm.utils.fnBind( this.init, this ) );
  577. return;
  578. }
  579. /**
  580. * If this is a subwindow, wait a few milliseconds for the original
  581. * page's js calls to be executed, then replace the bodies content
  582. * with GoldenLayout
  583. */
  584. if( this.isSubWindow === true && this._creationTimeoutPassed === false ) {
  585. setTimeout( lm.utils.fnBind( this.init, this ), 7 );
  586. this._creationTimeoutPassed = true;
  587. return;
  588. }
  589. if( this.isSubWindow === true ) {
  590. this._adjustToWindowMode();
  591. }
  592. this._setContainer();
  593. this.dropTargetIndicator = new lm.controls.DropTargetIndicator( this.container );
  594. this.transitionIndicator = new lm.controls.TransitionIndicator();
  595. this.updateSize();
  596. this._create( this.config );
  597. this._bindEvents();
  598. this.isInitialised = true;
  599. this._adjustColumnsResponsive();
  600. this.emit( 'initialised' );
  601. },
  602. /**
  603. * Updates the layout managers size
  604. *
  605. * @public
  606. * @param {[int]} width height in pixels
  607. * @param {[int]} height width in pixels
  608. *
  609. * @returns {void}
  610. */
  611. updateSize: function( width, height ) {
  612. if( arguments.length === 2 ) {
  613. this.width = width;
  614. this.height = height;
  615. } else {
  616. this.width = this.container.width();
  617. this.height = this.container.height();
  618. }
  619. if( this.isInitialised === true ) {
  620. this.root.callDownwards( 'setSize', [ this.width, this.height ] );
  621. if( this._maximisedItem ) {
  622. this._maximisedItem.element.width( this.container.width() );
  623. this._maximisedItem.element.height( this.container.height() );
  624. this._maximisedItem.callDownwards( 'setSize' );
  625. }
  626. this._adjustColumnsResponsive();
  627. }
  628. },
  629. /**
  630. * Destroys the LayoutManager instance itself as well as every ContentItem
  631. * within it. After this is called nothing should be left of the LayoutManager.
  632. *
  633. * @public
  634. * @returns {void}
  635. */
  636. destroy: function() {
  637. if( this.isInitialised === false ) {
  638. return;
  639. }
  640. this._onUnload();
  641. $( window ).off( 'resize', this._resizeFunction );
  642. $( window ).off( 'unload beforeunload', this._unloadFunction );
  643. this.root.callDownwards( '_$destroy', [], true );
  644. this.root.contentItems = [];
  645. this.tabDropPlaceholder.remove();
  646. this.dropTargetIndicator.destroy();
  647. this.transitionIndicator.destroy();
  648. this.eventHub.destroy();
  649. this._dragSources.forEach( function( dragSource ) {
  650. dragSource._dragListener.destroy();
  651. dragSource._element = null;
  652. dragSource._itemConfig = null;
  653. dragSource._dragListener = null;
  654. } );
  655. this._dragSources = [];
  656. },
  657. /**
  658. * Recursively creates new item tree structures based on a provided
  659. * ItemConfiguration object
  660. *
  661. * @public
  662. * @param {Object} config ItemConfig
  663. * @param {[ContentItem]} parent The item the newly created item should be a child of
  664. *
  665. * @returns {lm.items.ContentItem}
  666. */
  667. createContentItem: function( config, parent ) {
  668. var typeErrorMsg, contentItem;
  669. if( typeof config.type !== 'string' ) {
  670. throw new lm.errors.ConfigurationError( 'Missing parameter \'type\'', config );
  671. }
  672. if( config.type === 'react-component' ) {
  673. config.type = 'component';
  674. config.componentName = 'lm-react-component';
  675. }
  676. if( !this._typeToItem[ config.type ] ) {
  677. typeErrorMsg = 'Unknown type \'' + config.type + '\'. ' +
  678. 'Valid types are ' + lm.utils.objectKeys( this._typeToItem ).join( ',' );
  679. throw new lm.errors.ConfigurationError( typeErrorMsg );
  680. }
  681. /**
  682. * We add an additional stack around every component that's not within a stack anyways.
  683. */
  684. if(
  685. // If this is a component
  686. config.type === 'component' &&
  687. // and it's not already within a stack
  688. !( parent instanceof lm.items.Stack ) &&
  689. // and we have a parent
  690. !!parent &&
  691. // and it's not the topmost item in a new window
  692. !( this.isSubWindow === true && parent instanceof lm.items.Root )
  693. ) {
  694. config = {
  695. type: 'stack',
  696. width: config.width,
  697. height: config.height,
  698. content: [ config ]
  699. };
  700. }
  701. contentItem = new this._typeToItem[ config.type ]( this, config, parent );
  702. return contentItem;
  703. },
  704. /**
  705. * Creates a popout window with the specified content and dimensions
  706. *
  707. * @param {Object|lm.itemsAbstractContentItem} configOrContentItem
  708. * @param {[Object]} dimensions A map with width, height, left and top
  709. * @param {[String]} parentId the id of the element this item will be appended to
  710. * when popIn is called
  711. * @param {[Number]} indexInParent The position of this item within its parent element
  712. * @returns {lm.controls.BrowserPopout}
  713. */
  714. createPopout: function( configOrContentItem, dimensions, parentId, indexInParent ) {
  715. var config = configOrContentItem,
  716. isItem = configOrContentItem instanceof lm.items.AbstractContentItem,
  717. self = this,
  718. windowLeft,
  719. windowTop,
  720. offset,
  721. parent,
  722. child,
  723. browserPopout;
  724. parentId = parentId || null;
  725. if( isItem ) {
  726. config = this.toConfig( configOrContentItem ).content;
  727. parentId = lm.utils.getUniqueId();
  728. /**
  729. * If the item is the only component within a stack or for some
  730. * other reason the only child of its parent the parent will be destroyed
  731. * when the child is removed.
  732. *
  733. * In order to support this we move up the tree until we find something
  734. * that will remain after the item is being popped out
  735. */
  736. parent = configOrContentItem.parent;
  737. child = configOrContentItem;
  738. while( parent.contentItems.length === 1 && !parent.isRoot ) {
  739. parent = parent.parent;
  740. child = child.parent;
  741. }
  742. parent.addId( parentId );
  743. if( isNaN( indexInParent ) ) {
  744. indexInParent = lm.utils.indexOf( child, parent.contentItems );
  745. }
  746. } else {
  747. if( !( config instanceof Array ) ) {
  748. config = [ config ];
  749. }
  750. }
  751. if( !dimensions && isItem ) {
  752. windowLeft = window.screenX || window.screenLeft;
  753. windowTop = window.screenY || window.screenTop;
  754. offset = configOrContentItem.element.offset();
  755. dimensions = {
  756. left: windowLeft + offset.left,
  757. top: windowTop + offset.top,
  758. width: configOrContentItem.element.width(),
  759. height: configOrContentItem.element.height()
  760. };
  761. }
  762. if( !dimensions && !isItem ) {
  763. dimensions = {
  764. left: window.screenX || window.screenLeft + 20,
  765. top: window.screenY || window.screenTop + 20,
  766. width: 500,
  767. height: 309
  768. };
  769. }
  770. if( isItem ) {
  771. configOrContentItem.remove();
  772. }
  773. browserPopout = new lm.controls.BrowserPopout( config, dimensions, parentId, indexInParent, this );
  774. browserPopout.on( 'initialised', function() {
  775. self.emit( 'windowOpened', browserPopout );
  776. } );
  777. browserPopout.on( 'closed', function() {
  778. self._$reconcilePopoutWindows();
  779. } );
  780. this.openPopouts.push( browserPopout );
  781. return browserPopout;
  782. },
  783. /**
  784. * Attaches DragListener to any given DOM element
  785. * and turns it into a way of creating new ContentItems
  786. * by 'dragging' the DOM element into the layout
  787. *
  788. * @param {jQuery DOM element} element
  789. * @param {Object|Function} itemConfig for the new item to be created, or a function which will provide it
  790. *
  791. * @returns {void}
  792. */
  793. createDragSource: function( element, itemConfig ) {
  794. this.config.settings.constrainDragToContainer = false;
  795. var dragSource = new lm.controls.DragSource( $( element ), itemConfig, this );
  796. this._dragSources.push( dragSource );
  797. return dragSource;
  798. },
  799. /**
  800. * Programmatically selects an item. This deselects
  801. * the currently selected item, selects the specified item
  802. * and emits a selectionChanged event
  803. *
  804. * @param {lm.item.AbstractContentItem} item#
  805. * @param {[Boolean]} _$silent Wheather to notify the item of its selection
  806. * @event selectionChanged
  807. *
  808. * @returns {VOID}
  809. */
  810. selectItem: function( item, _$silent ) {
  811. if( this.config.settings.selectionEnabled !== true ) {
  812. throw new Error( 'Please set selectionEnabled to true to use this feature' );
  813. }
  814. if( item === this.selectedItem ) {
  815. return;
  816. }
  817. if( this.selectedItem !== null ) {
  818. this.selectedItem.deselect();
  819. }
  820. if( item && _$silent !== true ) {
  821. item.select();
  822. }
  823. this.selectedItem = item;
  824. this.emit( 'selectionChanged', item );
  825. },
  826. /*************************
  827. * PACKAGE PRIVATE
  828. *************************/
  829. _$maximiseItem: function( contentItem ) {
  830. if( this._maximisedItem !== null ) {
  831. this._$minimiseItem( this._maximisedItem );
  832. }
  833. this._maximisedItem = contentItem;
  834. this._maximisedItem.addId( '__glMaximised' );
  835. contentItem.element.addClass( 'lm_maximised' );
  836. contentItem.element.after( this._maximisePlaceholder );
  837. this.root.element.prepend( contentItem.element );
  838. contentItem.element.width( this.container.width() );
  839. contentItem.element.height( this.container.height() );
  840. contentItem.callDownwards( 'setSize' );
  841. this._maximisedItem.emit( 'maximised' );
  842. this.emit( 'stateChanged' );
  843. },
  844. _$minimiseItem: function( contentItem ) {
  845. contentItem.element.removeClass( 'lm_maximised' );
  846. contentItem.removeId( '__glMaximised' );
  847. this._maximisePlaceholder.after( contentItem.element );
  848. this._maximisePlaceholder.remove();
  849. contentItem.parent.callDownwards( 'setSize' );
  850. this._maximisedItem = null;
  851. contentItem.emit( 'minimised' );
  852. this.emit( 'stateChanged' );
  853. },
  854. /**
  855. * This method is used to get around sandboxed iframe restrictions.
  856. * If 'allow-top-navigation' is not specified in the iframe's 'sandbox' attribute
  857. * (as is the case with codepens) the parent window is forbidden from calling certain
  858. * methods on the child, such as window.close() or setting document.location.href.
  859. *
  860. * This prevented GoldenLayout popouts from popping in in codepens. The fix is to call
  861. * _$closeWindow on the child window's gl instance which (after a timeout to disconnect
  862. * the invoking method from the close call) closes itself.
  863. *
  864. * @packagePrivate
  865. *
  866. * @returns {void}
  867. */
  868. _$closeWindow: function() {
  869. window.setTimeout( function() {
  870. window.close();
  871. }, 1 );
  872. },
  873. _$getArea: function( x, y ) {
  874. var i, area, smallestSurface = Infinity, mathingArea = null;
  875. for( i = 0; i < this._itemAreas.length; i++ ) {
  876. area = this._itemAreas[ i ];
  877. if(
  878. x > area.x1 &&
  879. x < area.x2 &&
  880. y > area.y1 &&
  881. y < area.y2 &&
  882. smallestSurface > area.surface
  883. ) {
  884. smallestSurface = area.surface;
  885. mathingArea = area;
  886. }
  887. }
  888. return mathingArea;
  889. },
  890. _$createRootItemAreas: function() {
  891. var areaSize = 50;
  892. var sides = { y2: 0, x2: 0, y1: 'y2', x1: 'x2' };
  893. for( side in sides ) {
  894. var area = this.root._$getArea();
  895. area.side = side;
  896. if( sides [ side ] )
  897. area[ side ] = area[ sides [ side ] ] - areaSize;
  898. else
  899. area[ side ] = areaSize;
  900. with( area )
  901. surface = ( x2 - x1 ) * ( y2 - y1 );
  902. this._itemAreas.push( area );
  903. }
  904. },
  905. _$calculateItemAreas: function() {
  906. var i, area, allContentItems = this._getAllContentItems();
  907. this._itemAreas = [];
  908. /**
  909. * If the last item is dragged out, highlight the entire container size to
  910. * allow to re-drop it. allContentItems[ 0 ] === this.root at this point
  911. *
  912. * Don't include root into the possible drop areas though otherwise since it
  913. * will used for every gap in the layout, e.g. splitters
  914. */
  915. if( allContentItems.length === 1 ) {
  916. this._itemAreas.push( this.root._$getArea() );
  917. return;
  918. }
  919. this._$createRootItemAreas();
  920. for( i = 0; i < allContentItems.length; i++ ) {
  921. if( !( allContentItems[ i ].isStack ) ) {
  922. continue;
  923. }
  924. area = allContentItems[ i ]._$getArea();
  925. if( area === null ) {
  926. continue;
  927. } else if( area instanceof Array ) {
  928. this._itemAreas = this._itemAreas.concat( area );
  929. } else {
  930. this._itemAreas.push( area );
  931. var header = {};
  932. lm.utils.copy( header, area );
  933. lm.utils.copy( header, area.contentItem._contentAreaDimensions.header.highlightArea );
  934. with( header )
  935. surface = ( x2 - x1 ) * ( y2 - y1 );
  936. this._itemAreas.push( header );
  937. }
  938. }
  939. },
  940. /**
  941. * Takes a contentItem or a configuration and optionally a parent
  942. * item and returns an initialised instance of the contentItem.
  943. * If the contentItem is a function, it is first called
  944. *
  945. * @packagePrivate
  946. *
  947. * @param {lm.items.AbtractContentItem|Object|Function} contentItemOrConfig
  948. * @param {lm.items.AbtractContentItem} parent Only necessary when passing in config
  949. *
  950. * @returns {lm.items.AbtractContentItem}
  951. */
  952. _$normalizeContentItem: function( contentItemOrConfig, parent ) {
  953. if( !contentItemOrConfig ) {
  954. throw new Error( 'No content item defined' );
  955. }
  956. if( lm.utils.isFunction( contentItemOrConfig ) ) {
  957. contentItemOrConfig = contentItemOrConfig();
  958. }
  959. if( contentItemOrConfig instanceof lm.items.AbstractContentItem ) {
  960. return contentItemOrConfig;
  961. }
  962. if( $.isPlainObject( contentItemOrConfig ) && contentItemOrConfig.type ) {
  963. var newContentItem = this.createContentItem( contentItemOrConfig, parent );
  964. newContentItem.callDownwards( '_$init' );
  965. return newContentItem;
  966. } else {
  967. throw new Error( 'Invalid contentItem' );
  968. }
  969. },
  970. /**
  971. * Iterates through the array of open popout windows and removes the ones
  972. * that are effectively closed. This is necessary due to the lack of reliably
  973. * listening for window.close / unload events in a cross browser compatible fashion.
  974. *
  975. * @packagePrivate
  976. *
  977. * @returns {void}
  978. */
  979. _$reconcilePopoutWindows: function() {
  980. var openPopouts = [], i;
  981. for( i = 0; i < this.openPopouts.length; i++ ) {
  982. if( this.openPopouts[ i ].getWindow().closed === false ) {
  983. openPopouts.push( this.openPopouts[ i ] );
  984. } else {
  985. this.emit( 'windowClosed', this.openPopouts[ i ] );
  986. }
  987. }
  988. if( this.openPopouts.length !== openPopouts.length ) {
  989. this.emit( 'stateChanged' );
  990. this.openPopouts = openPopouts;
  991. }
  992. },
  993. /***************************
  994. * PRIVATE
  995. ***************************/
  996. /**
  997. * Returns a flattened array of all content items,
  998. * regardles of level or type
  999. *
  1000. * @private
  1001. *
  1002. * @returns {void}
  1003. */
  1004. _getAllContentItems: function() {
  1005. var allContentItems = [];
  1006. var addChildren = function( contentItem ) {
  1007. allContentItems.push( contentItem );
  1008. if( contentItem.contentItems instanceof Array ) {
  1009. for( var i = 0; i < contentItem.contentItems.length; i++ ) {
  1010. addChildren( contentItem.contentItems[ i ] );
  1011. }
  1012. }
  1013. };
  1014. addChildren( this.root );
  1015. return allContentItems;
  1016. },
  1017. /**
  1018. * Binds to DOM/BOM events on init
  1019. *
  1020. * @private
  1021. *
  1022. * @returns {void}
  1023. */
  1024. _bindEvents: function() {
  1025. if( this._isFullPage ) {
  1026. $( window ).resize( this._resizeFunction );
  1027. }
  1028. $( window ).on( 'unload beforeunload', this._unloadFunction );
  1029. },
  1030. /**
  1031. * Debounces resize events
  1032. *
  1033. * @private
  1034. *
  1035. * @returns {void}
  1036. */
  1037. _onResize: function() {
  1038. clearTimeout( this._resizeTimeoutId );
  1039. this._resizeTimeoutId = setTimeout( lm.utils.fnBind( this.updateSize, this ), 100 );
  1040. },
  1041. /**
  1042. * Extends the default config with the user specific settings and applies
  1043. * derivations. Please note that there's a seperate method (AbstractContentItem._extendItemNode)
  1044. * that deals with the extension of item configs
  1045. *
  1046. * @param {Object} config
  1047. * @static
  1048. * @returns {Object} config
  1049. */
  1050. _createConfig: function( config ) {
  1051. var windowConfigKey = lm.utils.getQueryStringParam( 'gl-window' );
  1052. if( windowConfigKey ) {
  1053. this.isSubWindow = true;
  1054. config = localStorage.getItem( windowConfigKey );
  1055. config = JSON.parse( config );
  1056. config = ( new lm.utils.ConfigMinifier() ).unminifyConfig( config );
  1057. localStorage.removeItem( windowConfigKey );
  1058. }
  1059. config = $.extend( true, {}, lm.config.defaultConfig, config );
  1060. var nextNode = function( node ) {
  1061. for( var key in node ) {
  1062. if( key !== 'props' && typeof node[ key ] === 'object' ) {
  1063. nextNode( node[ key ] );
  1064. }
  1065. else if( key === 'type' && node[ key ] === 'react-component' ) {
  1066. node.type = 'component';
  1067. node.componentName = 'lm-react-component';
  1068. }
  1069. }
  1070. }
  1071. nextNode( config );
  1072. if( config.settings.hasHeaders === false ) {
  1073. config.dimensions.headerHeight = 0;
  1074. }
  1075. return config;
  1076. },
  1077. /**
  1078. * This is executed when GoldenLayout detects that it is run
  1079. * within a previously opened popout window.
  1080. *
  1081. * @private
  1082. *
  1083. * @returns {void}
  1084. */
  1085. _adjustToWindowMode: function() {
  1086. var popInButton = $( '<div class="lm_popin" title="' + this.config.labels.popin + '">' +
  1087. '<div class="lm_icon"></div>' +
  1088. '<div class="lm_bg"></div>' +
  1089. '</div>' );
  1090. popInButton.click( lm.utils.fnBind( function() {
  1091. this.emit( 'popIn' );
  1092. }, this ) );
  1093. document.title = lm.utils.stripTags( this.config.content[ 0 ].title );
  1094. $( 'head' ).append( $( 'body link, body style, template, .gl_keep' ) );
  1095. this.container = $( 'body' )
  1096. .html( '' )
  1097. .css( 'visibility', 'visible' )
  1098. .append( popInButton );
  1099. /*
  1100. * This seems a bit pointless, but actually causes a reflow/re-evaluation getting around
  1101. * slickgrid's "Cannot find stylesheet." bug in chrome
  1102. */
  1103. var x = document.body.offsetHeight; // jshint ignore:line
  1104. /*
  1105. * Expose this instance on the window object
  1106. * to allow the opening window to interact with
  1107. * it
  1108. */
  1109. window.__glInstance = this;
  1110. },
  1111. /**
  1112. * Creates Subwindows (if there are any). Throws an error
  1113. * if popouts are blocked.
  1114. *
  1115. * @returns {void}
  1116. */
  1117. _createSubWindows: function() {
  1118. var i, popout;
  1119. for( i = 0; i < this.config.openPopouts.length; i++ ) {
  1120. popout = this.config.openPopouts[ i ];
  1121. this.createPopout(
  1122. popout.content,
  1123. popout.dimensions,
  1124. popout.parentId,
  1125. popout.indexInParent
  1126. );
  1127. }
  1128. },
  1129. /**
  1130. * Determines what element the layout will be created in
  1131. *
  1132. * @private
  1133. *
  1134. * @returns {void}
  1135. */
  1136. _setContainer: function() {
  1137. var container = $( this.container || 'body' );
  1138. if( container.length === 0 ) {
  1139. throw new Error( 'GoldenLayout container not found' );
  1140. }
  1141. if( container.length > 1 ) {
  1142. throw new Error( 'GoldenLayout more than one container element specified' );
  1143. }
  1144. if( container[ 0 ] === document.body ) {
  1145. this._isFullPage = true;
  1146. $( 'html, body' ).css( {
  1147. height: '100%',
  1148. margin: 0,
  1149. padding: 0,
  1150. overflow: 'hidden'
  1151. } );
  1152. }
  1153. this.container = container;
  1154. },
  1155. /**
  1156. * Kicks of the initial, recursive creation chain
  1157. *
  1158. * @param {Object} config GoldenLayout Config
  1159. *
  1160. * @returns {void}
  1161. */
  1162. _create: function( config ) {
  1163. var errorMsg;
  1164. if( !( config.content instanceof Array ) ) {
  1165. if( config.content === undefined ) {
  1166. errorMsg = 'Missing setting \'content\' on top level of configuration';
  1167. } else {
  1168. errorMsg = 'Configuration parameter \'content\' must be an array';
  1169. }
  1170. throw new lm.errors.ConfigurationError( errorMsg, config );
  1171. }
  1172. if( config.content.length > 1 ) {
  1173. errorMsg = 'Top level content can\'t contain more then one element.';
  1174. throw new lm.errors.ConfigurationError( errorMsg, config );
  1175. }
  1176. this.root = new lm.items.Root( this, { content: config.content }, this.container );
  1177. this.root.callDownwards( '_$init' );
  1178. if( config.maximisedItemId === '__glMaximised' ) {
  1179. this.root.getItemsById( config.maximisedItemId )[ 0 ].toggleMaximise();
  1180. }
  1181. },
  1182. /**
  1183. * Called when the window is closed or the user navigates away
  1184. * from the page
  1185. *
  1186. * @returns {void}
  1187. */
  1188. _onUnload: function() {
  1189. if( this.config.settings.closePopoutsOnUnload === true ) {
  1190. for( var i = 0; i < this.openPopouts.length; i++ ) {
  1191. this.openPopouts[ i ].close();
  1192. }
  1193. }
  1194. },
  1195. /**
  1196. * Adjusts the number of columns to be lower to fit the screen and still maintain minItemWidth.
  1197. *
  1198. * @returns {void}
  1199. */
  1200. _adjustColumnsResponsive: function() {
  1201. // If there is no min width set, or not content items, do nothing.
  1202. if( !this._useResponsiveLayout() || this._updatingColumnsResponsive || !this.config.dimensions || !this.config.dimensions.minItemWidth || this.root.contentItems.length === 0 || !this.root.contentItems[ 0 ].isRow ) {
  1203. this._firstLoad = false;
  1204. return;
  1205. }
  1206. this._firstLoad = false;
  1207. // If there is only one column, do nothing.
  1208. var columnCount = this.root.contentItems[ 0 ].contentItems.length;
  1209. if( columnCount <= 1 ) {
  1210. return;
  1211. }
  1212. // If they all still fit, do nothing.
  1213. var minItemWidth = this.config.dimensions.minItemWidth;
  1214. var totalMinWidth = columnCount * minItemWidth;
  1215. if( totalMinWidth <= this.width ) {
  1216. return;
  1217. }
  1218. // Prevent updates while it is already happening.
  1219. this._updatingColumnsResponsive = true;
  1220. // Figure out how many columns to stack, and put them all in the first stack container.
  1221. var finalColumnCount = Math.max( Math.floor( this.width / minItemWidth ), 1 );
  1222. var stackColumnCount = columnCount - finalColumnCount;
  1223. var rootContentItem = this.root.contentItems[ 0 ];
  1224. var firstStackContainer = this._findAllStackContainers()[ 0 ];
  1225. for( var i = 0; i < stackColumnCount; i++ ) {
  1226. // Stack from right.
  1227. var column = rootContentItem.contentItems[ rootContentItem.contentItems.length - 1 ];
  1228. rootContentItem.removeChild( column );
  1229. this._addChildContentItemsToContainer( firstStackContainer, column );
  1230. }
  1231. this._updatingColumnsResponsive = false;
  1232. },
  1233. /**
  1234. * Determines if responsive layout should be used.
  1235. *
  1236. * @returns {bool} - True if responsive layout should be used; otherwise false.
  1237. */
  1238. _useResponsiveLayout: function() {
  1239. return this.config.settings && ( this.config.settings.responsiveMode == 'always' || ( this.config.settings.responsiveMode == 'onload' && this._firstLoad ) );
  1240. },
  1241. /**
  1242. * Adds all children of a node to another container recursively.
  1243. * @param {object} container - Container to add child content items to.
  1244. * @param {object} node - Node to search for content items.
  1245. * @returns {void}
  1246. */
  1247. _addChildContentItemsToContainer: function( container, node ) {
  1248. if( node.type === 'stack' ) {
  1249. node.contentItems.forEach( function( item ) {
  1250. container.addChild( item );
  1251. } );
  1252. }
  1253. else {
  1254. node.contentItems.forEach( lm.utils.fnBind( function( item ) {
  1255. this._addChildContentItemsToContainer( container, item );
  1256. }, this ) );
  1257. }
  1258. },
  1259. /**
  1260. * Finds all the stack containers.
  1261. * @returns {array} - The found stack containers.
  1262. */
  1263. _findAllStackContainers: function() {
  1264. var stackContainers = [];
  1265. this._findAllStackContainersRecursive( stackContainers, this.root );
  1266. return stackContainers;
  1267. },
  1268. /**
  1269. * Finds all the stack containers.
  1270. *
  1271. * @param {array} - Set of containers to populate.
  1272. * @param {object} - Current node to process.
  1273. *
  1274. * @returns {void}
  1275. */
  1276. _findAllStackContainersRecursive: function( stackContainers, node ) {
  1277. node.contentItems.forEach( lm.utils.fnBind( function( item ) {
  1278. if( item.type == 'stack' ) {
  1279. stackContainers.push( item );
  1280. }
  1281. else if( !item.isComponent ) {
  1282. this._findAllStackContainersRecursive( stackContainers, item );
  1283. }
  1284. }, this ) );
  1285. }
  1286. } );
  1287. /**
  1288. * Expose the Layoutmanager as the single entrypoint using UMD
  1289. */
  1290. (function() {
  1291. /* global define */
  1292. if( typeof define === 'function' && define.amd ) {
  1293. define( [ 'jquery' ], function( jquery ) {
  1294. $ = jquery;
  1295. return lm.LayoutManager;
  1296. } ); // jshint ignore:line
  1297. } else if( typeof exports === 'object' ) {
  1298. module.exports = lm.LayoutManager;
  1299. } else {
  1300. window.GoldenLayout = lm.LayoutManager;
  1301. }
  1302. })();
  1303. lm.config.itemDefaultConfig = {
  1304. isClosable: true,
  1305. reorderEnabled: true,
  1306. title: ''
  1307. };
  1308. lm.config.defaultConfig = {
  1309. openPopouts: [],
  1310. settings: {
  1311. hasHeaders: true,
  1312. constrainDragToContainer: true,
  1313. reorderEnabled: true,
  1314. selectionEnabled: false,
  1315. popoutWholeStack: false,
  1316. blockedPopoutsThrowError: true,
  1317. closePopoutsOnUnload: true,
  1318. showPopoutIcon: true,
  1319. showMaximiseIcon: true,
  1320. showCloseIcon: true,
  1321. responsiveMode: 'onload' // Can be onload, always, or none.
  1322. },
  1323. dimensions: {
  1324. borderWidth: 5,
  1325. minItemHeight: 10,
  1326. minItemWidth: 10,
  1327. headerHeight: 20,
  1328. dragProxyWidth: 300,
  1329. dragProxyHeight: 200
  1330. },
  1331. labels: {
  1332. close: 'close',
  1333. maximise: 'maximise',
  1334. minimise: 'minimise',
  1335. popout: 'open in new window',
  1336. popin: 'pop in',
  1337. tabDropdown: 'additional tabs'
  1338. }
  1339. };
  1340. lm.container.ItemContainer = function( config, parent, layoutManager ) {
  1341. lm.utils.EventEmitter.call( this );
  1342. this.width = null;
  1343. this.height = null;
  1344. this.title = config.componentName;
  1345. this.parent = parent;
  1346. this.layoutManager = layoutManager;
  1347. this.isHidden = false;
  1348. this._config = config;
  1349. this._element = $( [
  1350. '<div class="lm_item_container">',
  1351. '<div class="lm_content"></div>',
  1352. '</div>'
  1353. ].join( '' ) );
  1354. this._contentElement = this._element.find( '.lm_content' );
  1355. };
  1356. lm.utils.copy( lm.container.ItemContainer.prototype, {
  1357. /**
  1358. * Get the inner DOM element the container's content
  1359. * is intended to live in
  1360. *
  1361. * @returns {DOM element}
  1362. */
  1363. getElement: function() {
  1364. return this._contentElement;
  1365. },
  1366. /**
  1367. * Hide the container. Notifies the containers content first
  1368. * and then hides the DOM node. If the container is already hidden
  1369. * this should have no effect
  1370. *
  1371. * @returns {void}
  1372. */
  1373. hide: function() {
  1374. this.emit( 'hide' );
  1375. this.isHidden = true;
  1376. this._element.hide();
  1377. },
  1378. /**
  1379. * Shows a previously hidden container. Notifies the
  1380. * containers content first and then shows the DOM element.
  1381. * If the container is already visible this has no effect.
  1382. *
  1383. * @returns {void}
  1384. */
  1385. show: function() {
  1386. this.emit( 'show' );
  1387. this.isHidden = false;
  1388. this._element.show();
  1389. // call shown only if the container has a valid size
  1390. if( this.height != 0 || this.width != 0 ) {
  1391. this.emit( 'shown' );
  1392. }
  1393. },
  1394. /**
  1395. * Set the size from within the container. Traverses up
  1396. * the item tree until it finds a row or column element
  1397. * and resizes its items accordingly.
  1398. *
  1399. * If this container isn't a descendant of a row or column
  1400. * it returns false
  1401. * @todo Rework!!!
  1402. * @param {Number} width The new width in pixel
  1403. * @param {Number} height The new height in pixel
  1404. *
  1405. * @returns {Boolean} resizeSuccesful
  1406. */
  1407. setSize: function( width, height ) {
  1408. var rowOrColumn = this.parent,
  1409. rowOrColumnChild = this,
  1410. totalPixel,
  1411. percentage,
  1412. direction,
  1413. newSize,
  1414. delta,
  1415. i;
  1416. while( !rowOrColumn.isColumn && !rowOrColumn.isRow ) {
  1417. rowOrColumnChild = rowOrColumn;
  1418. rowOrColumn = rowOrColumn.parent;
  1419. /**
  1420. * No row or column has been found
  1421. */
  1422. if( rowOrColumn.isRoot ) {
  1423. return false;
  1424. }
  1425. }
  1426. direction = rowOrColumn.isColumn ? "height" : "width";
  1427. newSize = direction === "height" ? height : width;
  1428. totalPixel = this[ direction ] * ( 1 / ( rowOrColumnChild.config[ direction ] / 100 ) );
  1429. percentage = ( newSize / totalPixel ) * 100;
  1430. delta = ( rowOrColumnChild.config[ direction ] - percentage ) / (rowOrColumn.contentItems.length - 1);
  1431. for( i = 0; i < rowOrColumn.contentItems.length; i++ ) {
  1432. if( rowOrColumn.contentItems[ i ] === rowOrColumnChild ) {
  1433. rowOrColumn.contentItems[ i ].config[ direction ] = percentage;
  1434. } else {
  1435. rowOrColumn.contentItems[ i ].config[ direction ] += delta;
  1436. }
  1437. }
  1438. rowOrColumn.callDownwards( 'setSize' );
  1439. return true;
  1440. },
  1441. /**
  1442. * Closes the container if it is closable. Can be called by
  1443. * both the component within at as well as the contentItem containing
  1444. * it. Emits a close event before the container itself is closed.
  1445. *
  1446. * @returns {void}
  1447. */
  1448. close: function() {
  1449. if( this._config.isClosable ) {
  1450. this.emit( 'close' );
  1451. this.parent.close();
  1452. }
  1453. },
  1454. /**
  1455. * Returns the current state object
  1456. *
  1457. * @returns {Object} state
  1458. */
  1459. getState: function() {
  1460. return this._config.componentState;
  1461. },
  1462. /**
  1463. * Merges the provided state into the current one
  1464. *
  1465. * @param {Object} state
  1466. *
  1467. * @returns {void}
  1468. */
  1469. extendState: function( state ) {
  1470. this.setState( $.extend( true, this.getState(), state ) );
  1471. },
  1472. /**
  1473. * Notifies the layout manager of a stateupdate
  1474. *
  1475. * @param {serialisable} state
  1476. */
  1477. setState: function( state ) {
  1478. this._config.componentState = state;
  1479. this.parent.emitBubblingEvent( 'stateChanged' );
  1480. },
  1481. /**
  1482. * Set's the components title
  1483. *
  1484. * @param {String} title
  1485. */
  1486. setTitle: function( title ) {
  1487. this.parent.setTitle( title );
  1488. },
  1489. /**
  1490. * Set's the containers size. Called by the container's component.
  1491. * To set the size programmatically from within the container please
  1492. * use the public setSize method
  1493. *
  1494. * @param {[Int]} width in px
  1495. * @param {[Int]} height in px
  1496. *
  1497. * @returns {void}
  1498. */
  1499. _$setSize: function( width, height ) {
  1500. if( width !== this.width || height !== this.height ) {
  1501. this.width = width;
  1502. this.height = height;
  1503. this._contentElement.width( this.width ).height( this.height );
  1504. this.emit( 'resize' );
  1505. }
  1506. }
  1507. } );
  1508. /**
  1509. * Pops a content item out into a new browser window.
  1510. * This is achieved by
  1511. *
  1512. * - Creating a new configuration with the content item as root element
  1513. * - Serializing and minifying the configuration
  1514. * - Opening the current window's URL with the configuration as a GET parameter
  1515. * - GoldenLayout when opened in the new window will look for the GET parameter
  1516. * and use it instead of the provided configuration
  1517. *
  1518. * @param {Object} config GoldenLayout item config
  1519. * @param {Object} dimensions A map with width, height, top and left
  1520. * @param {String} parentId The id of the element the item will be appended to on popIn
  1521. * @param {Number} indexInParent The position of this element within its parent
  1522. * @param {lm.LayoutManager} layoutManager
  1523. */
  1524. lm.controls.BrowserPopout = function( config, dimensions, parentId, indexInParent, layoutManager ) {
  1525. lm.utils.EventEmitter.call( this );
  1526. this.isInitialised = false;
  1527. this._config = config;
  1528. this._dimensions = dimensions;
  1529. this._parentId = parentId;
  1530. this._indexInParent = indexInParent;
  1531. this._layoutManager = layoutManager;
  1532. this._popoutWindow = null;
  1533. this._id = null;
  1534. this._createWindow();
  1535. };
  1536. lm.utils.copy( lm.controls.BrowserPopout.prototype, {
  1537. toConfig: function() {
  1538. if( this.isInitialised === false ) {
  1539. throw new Error( 'Can\'t create config, layout not yet initialised' );
  1540. return;
  1541. }
  1542. return {
  1543. dimensions: {
  1544. width: this.getGlInstance().width,
  1545. height: this.getGlInstance().height,
  1546. left: this._popoutWindow.screenX || this._popoutWindow.screenLeft,
  1547. top: this._popoutWindow.screenY || this._popoutWindow.screenTop
  1548. },
  1549. content: this.getGlInstance().toConfig().content,
  1550. parentId: this._parentId,
  1551. indexInParent: this._indexInParent
  1552. };
  1553. },
  1554. getGlInstance: function() {
  1555. return this._popoutWindow.__glInstance;
  1556. },
  1557. getWindow: function() {
  1558. return this._popoutWindow;
  1559. },
  1560. close: function() {
  1561. if( this.getGlInstance() ) {
  1562. this.getGlInstance()._$closeWindow();
  1563. } else {
  1564. try {
  1565. this.getWindow().close();
  1566. } catch( e ) {
  1567. }
  1568. }
  1569. },
  1570. /**
  1571. * Returns the popped out item to its original position. If the original
  1572. * parent isn't available anymore it falls back to the layout's topmost element
  1573. */
  1574. popIn: function() {
  1575. var childConfig,
  1576. parentItem,
  1577. index = this._indexInParent;
  1578. if( this._parentId ) {
  1579. /*
  1580. * The $.extend call seems a bit pointless, but it's crucial to
  1581. * copy the config returned by this.getGlInstance().toConfig()
  1582. * onto a new object. Internet Explorer keeps the references
  1583. * to objects on the child window, resulting in the following error
  1584. * once the child window is closed:
  1585. *
  1586. * The callee (server [not server application]) is not available and disappeared
  1587. */
  1588. childConfig = $.extend( true, {}, this.getGlInstance().toConfig() ).content[ 0 ];
  1589. parentItem = this._layoutManager.root.getItemsById( this._parentId )[ 0 ];
  1590. /*
  1591. * Fallback if parentItem is not available. Either add it to the topmost
  1592. * item or make it the topmost item if the layout is empty
  1593. */
  1594. if( !parentItem ) {
  1595. if( this._layoutManager.root.contentItems.length > 0 ) {
  1596. parentItem = this._layoutManager.root.contentItems[ 0 ];
  1597. } else {
  1598. parentItem = this._layoutManager.root;
  1599. }
  1600. index = 0;
  1601. }
  1602. }
  1603. parentItem.addChild( childConfig, this._indexInParent );
  1604. this.close();
  1605. },
  1606. /**
  1607. * Creates the URL and window parameter
  1608. * and opens a new window
  1609. *
  1610. * @private
  1611. *
  1612. * @returns {void}
  1613. */
  1614. _createWindow: function() {
  1615. var checkReadyInterval,
  1616. url = this._createUrl(),
  1617. /**
  1618. * Bogus title to prevent re-usage of existing window with the
  1619. * same title. The actual title will be set by the new window's
  1620. * GoldenLayout instance if it detects that it is in subWindowMode
  1621. */
  1622. title = Math.floor( Math.random() * 1000000 ).toString( 36 ),
  1623. /**
  1624. * The options as used in the window.open string
  1625. */
  1626. options = this._serializeWindowOptions( {
  1627. width: this._dimensions.width,
  1628. height: this._dimensions.height,
  1629. innerWidth: this._dimensions.width,
  1630. innerHeight: this._dimensions.height,
  1631. menubar: 'no',
  1632. toolbar: 'no',
  1633. location: 'no',
  1634. personalbar: 'no',
  1635. resizable: 'yes',
  1636. scrollbars: 'no',
  1637. status: 'no'
  1638. } );
  1639. this._popoutWindow = window.open( url, title, options );
  1640. if( !this._popoutWindow ) {
  1641. if( this._layoutManager.config.settings.blockedPopoutsThrowError === true ) {
  1642. var error = new Error( 'Popout blocked' );
  1643. error.type = 'popoutBlocked';
  1644. throw error;
  1645. } else {
  1646. return;
  1647. }
  1648. }
  1649. $( this._popoutWindow )
  1650. .on( 'load', lm.utils.fnBind( this._positionWindow, this ) )
  1651. .on( 'unload beforeunload', lm.utils.fnBind( this._onClose, this ) );
  1652. /**
  1653. * Polling the childwindow to find out if GoldenLayout has been initialised
  1654. * doesn't seem optimal, but the alternatives - adding a callback to the parent
  1655. * window or raising an event on the window object - both would introduce knowledge
  1656. * about the parent to the child window which we'd rather avoid
  1657. */
  1658. checkReadyInterval = setInterval( lm.utils.fnBind( function() {
  1659. if( this._popoutWindow.__glInstance && this._popoutWindow.__glInstance.isInitialised ) {
  1660. this._onInitialised();
  1661. clearInterval( checkReadyInterval );
  1662. }
  1663. }, this ), 10 );
  1664. },
  1665. /**
  1666. * Serialises a map of key:values to a window options string
  1667. *
  1668. * @param {Object} windowOptions
  1669. *
  1670. * @returns {String} serialised window options
  1671. */
  1672. _serializeWindowOptions: function( windowOptions ) {
  1673. var windowOptionsString = [], key;
  1674. for( key in windowOptions ) {
  1675. windowOptionsString.push( key + '=' + windowOptions[ key ] );
  1676. }
  1677. return windowOptionsString.join( ',' );
  1678. },
  1679. /**
  1680. * Creates the URL for the new window, including the
  1681. * config GET parameter
  1682. *
  1683. * @returns {String} URL
  1684. */
  1685. _createUrl: function() {
  1686. var config = { content: this._config },
  1687. storageKey = 'gl-window-config-' + lm.utils.getUniqueId(),
  1688. urlParts;
  1689. config = ( new lm.utils.ConfigMinifier() ).minifyConfig( config );
  1690. try {
  1691. localStorage.setItem( storageKey, JSON.stringify( config ) );
  1692. } catch( e ) {
  1693. throw new Error( 'Error while writing to localStorage ' + e.toString() );
  1694. }
  1695. urlParts = document.location.href.split( '?' );
  1696. // URL doesn't contain GET-parameters
  1697. if( urlParts.length === 1 ) {
  1698. return urlParts[ 0 ] + '?gl-window=' + storageKey;
  1699. // URL contains GET-parameters
  1700. } else {
  1701. return document.location.href + '&gl-window=' + storageKey;
  1702. }
  1703. },
  1704. /**
  1705. * Move the newly created window roughly to
  1706. * where the component used to be.
  1707. *
  1708. * @private
  1709. *
  1710. * @returns {void}
  1711. */
  1712. _positionWindow: function() {
  1713. this._popoutWindow.moveTo( this._dimensions.left, this._dimensions.top );
  1714. this._popoutWindow.focus();
  1715. },
  1716. /**
  1717. * Callback when the new window is opened and the GoldenLayout instance
  1718. * within it is initialised
  1719. *
  1720. * @returns {void}
  1721. */
  1722. _onInitialised: function() {
  1723. this.isInitialised = true;
  1724. this.getGlInstance().on( 'popIn', this.popIn, this );
  1725. this.emit( 'initialised' );
  1726. },
  1727. /**
  1728. * Invoked 50ms after the window unload event
  1729. *
  1730. * @private
  1731. *
  1732. * @returns {void}
  1733. */
  1734. _onClose: function() {
  1735. setTimeout( lm.utils.fnBind( this.emit, this, [ 'closed' ] ), 50 );
  1736. }
  1737. } );
  1738. /**
  1739. * This class creates a temporary container
  1740. * for the component whilst it is being dragged
  1741. * and handles drag events
  1742. *
  1743. * @constructor
  1744. * @private
  1745. *
  1746. * @param {Number} x The initial x position
  1747. * @param {Number} y The initial y position
  1748. * @param {lm.utils.DragListener} dragListener
  1749. * @param {lm.LayoutManager} layoutManager
  1750. * @param {lm.item.AbstractContentItem} contentItem
  1751. * @param {lm.item.AbstractContentItem} originalParent
  1752. */
  1753. lm.controls.DragProxy = function( x, y, dragListener, layoutManager, contentItem, originalParent ) {
  1754. lm.utils.EventEmitter.call( this );
  1755. this._dragListener = dragListener;
  1756. this._layoutManager = layoutManager;
  1757. this._contentItem = contentItem;
  1758. this._originalParent = originalParent;
  1759. this._area = null;
  1760. this._lastValidArea = null;
  1761. this._dragListener.on( 'drag', this._onDrag, this );
  1762. this._dragListener.on( 'dragStop', this._onDrop, this );
  1763. this.element = $( lm.controls.DragProxy._template );
  1764. if( originalParent && originalParent._side ) {
  1765. this._sided = originalParent._sided;
  1766. this.element.addClass( 'lm_' + originalParent._side );
  1767. if( [ 'right', 'bottom' ].indexOf( originalParent._side ) >= 0 )
  1768. this.element.find( '.lm_content' ).after( this.element.find( '.lm_header' ) );
  1769. }
  1770. this.element.css( { left: x, top: y } );
  1771. this.element.find( '.lm_tab' ).attr( 'title', lm.utils.stripTags( this._contentItem.config.title ) );
  1772. this.element.find( '.lm_title' ).html( this._contentItem.config.title );
  1773. this.childElementContainer = this.element.find( '.lm_content' );
  1774. this.childElementContainer.append( contentItem.element );
  1775. this._updateTree();
  1776. this._layoutManager._$calculateItemAreas();
  1777. this._setDimensions();
  1778. $( document.body ).append( this.element );
  1779. var offset = this._layoutManager.container.offset();
  1780. this._minX = offset.left;
  1781. this._minY = offset.top;
  1782. this._maxX = this._layoutManager.container.width() + this._minX;
  1783. this._maxY = this._layoutManager.container.height() + this._minY;
  1784. this._width = this.element.width();
  1785. this._height = this.element.height();
  1786. this._setDropPosition( x, y );
  1787. };
  1788. lm.controls.DragProxy._template = '<div class="lm_dragProxy">' +
  1789. '<div class="lm_header">' +
  1790. '<ul class="lm_tabs">' +
  1791. '<li class="lm_tab lm_active"><i class="lm_left"></i>' +
  1792. '<span class="lm_title"></span>' +
  1793. '<i class="lm_right"></i></li>' +
  1794. '</ul>' +
  1795. '</div>' +
  1796. '<div class="lm_content"></div>' +
  1797. '</div>';
  1798. lm.utils.copy( lm.controls.DragProxy.prototype, {
  1799. /**
  1800. * Callback on every mouseMove event during a drag. Determines if the drag is
  1801. * still within the valid drag area and calls the layoutManager to highlight the
  1802. * current drop area
  1803. *
  1804. * @param {Number} offsetX The difference from the original x position in px
  1805. * @param {Number} offsetY The difference from the original y position in px
  1806. * @param {jQuery DOM event} event
  1807. *
  1808. * @private
  1809. *
  1810. * @returns {void}
  1811. */
  1812. _onDrag: function( offsetX, offsetY, event ) {
  1813. event = event.originalEvent && event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event;
  1814. var x = event.pageX,
  1815. y = event.pageY,
  1816. isWithinContainer = x > this._minX && x < this._maxX && y > this._minY && y < this._maxY;
  1817. if( !isWithinContainer && this._layoutManager.config.settings.constrainDragToContainer === true ) {
  1818. return;
  1819. }
  1820. this._setDropPosition( x, y );
  1821. },
  1822. /**
  1823. * Sets the target position, highlighting the appropriate area
  1824. *
  1825. * @param {Number} x The x position in px
  1826. * @param {Number} y The y position in px
  1827. *
  1828. * @private
  1829. *
  1830. * @returns {void}
  1831. */
  1832. _setDropPosition: function( x, y ) {
  1833. this.element.css( { left: x, top: y } );
  1834. this._area = this._layoutManager._$getArea( x, y );
  1835. if( this._area !== null ) {
  1836. this._lastValidArea = this._area;
  1837. this._area.contentItem._$highlightDropZone( x, y, this._area );
  1838. }
  1839. },
  1840. /**
  1841. * Callback when the drag has finished. Determines the drop area
  1842. * and adds the child to it
  1843. *
  1844. * @private
  1845. *
  1846. * @returns {void}
  1847. */
  1848. _onDrop: function() {
  1849. this._layoutManager.dropTargetIndicator.hide();
  1850. /*
  1851. * Valid drop area found
  1852. */
  1853. if( this._area !== null ) {
  1854. this._area.contentItem._$onDrop( this._contentItem, this._area );
  1855. /**
  1856. * No valid drop area available at present, but one has been found before.
  1857. * Use it
  1858. */
  1859. } else if( this._lastValidArea !== null ) {
  1860. this._lastValidArea.contentItem._$onDrop( this._contentItem, this._lastValidArea );
  1861. /**
  1862. * No valid drop area found during the duration of the drag. Return
  1863. * content item to its original position if a original parent is provided.
  1864. * (Which is not the case if the drag had been initiated by createDragSource)
  1865. */
  1866. } else if( this._originalParent ) {
  1867. this._originalParent.addChild( this._contentItem );
  1868. /**
  1869. * The drag didn't ultimately end up with adding the content item to
  1870. * any container. In order to ensure clean up happens, destroy the
  1871. * content item.
  1872. */
  1873. } else {
  1874. this._contentItem._$destroy();
  1875. }
  1876. this.element.remove();
  1877. this._layoutManager.emit( 'itemDropped', this._contentItem );
  1878. },
  1879. /**
  1880. * Removes the item from its original position within the tree
  1881. *
  1882. * @private
  1883. *
  1884. * @returns {void}
  1885. */
  1886. _updateTree: function() {
  1887. /**
  1888. * parent is null if the drag had been initiated by a external drag source
  1889. */
  1890. if( this._contentItem.parent ) {
  1891. this._contentItem.parent.removeChild( this._contentItem, true );
  1892. }
  1893. this._contentItem._$setParent( this );
  1894. },
  1895. /**
  1896. * Updates the Drag Proxie's dimensions
  1897. *
  1898. * @private
  1899. *
  1900. * @returns {void}
  1901. */
  1902. _setDimensions: function() {
  1903. var dimensions = this._layoutManager.config.dimensions,
  1904. width = dimensions.dragProxyWidth,
  1905. height = dimensions.dragProxyHeight;
  1906. this.element.width( width );
  1907. this.element.height( height );
  1908. width -= ( this._sided ? dimensions.headerHeight : 0 );
  1909. height -= ( !this._sided ? dimensions.headerHeight : 0 );
  1910. this.childElementContainer.width( width );
  1911. this.childElementContainer.height( height );
  1912. this._contentItem.element.width( width );
  1913. this._contentItem.element.height( height );
  1914. this._contentItem.callDownwards( '_$show' );
  1915. this._contentItem.callDownwards( 'setSize' );
  1916. }
  1917. } );
  1918. /**
  1919. * Allows for any DOM item to create a component on drag
  1920. * start tobe dragged into the Layout
  1921. *
  1922. * @param {jQuery element} element
  1923. * @param {Object} itemConfig the configuration for the contentItem that will be created
  1924. * @param {LayoutManager} layoutManager
  1925. *
  1926. * @constructor
  1927. */
  1928. lm.controls.DragSource = function( element, itemConfig, layoutManager ) {
  1929. this._element = element;
  1930. this._itemConfig = itemConfig;
  1931. this._layoutManager = layoutManager;
  1932. this._dragListener = null;
  1933. this._createDragListener();
  1934. };
  1935. lm.utils.copy( lm.controls.DragSource.prototype, {
  1936. /**
  1937. * Called initially and after every drag
  1938. *
  1939. * @returns {void}
  1940. */
  1941. _createDragListener: function() {
  1942. if( this._dragListener !== null ) {
  1943. this._dragListener.destroy();
  1944. }
  1945. this._dragListener = new lm.utils.DragListener( this._element );
  1946. this._dragListener.on( 'dragStart', this._onDragStart, this );
  1947. this._dragListener.on( 'dragStop', this._createDragListener, this );
  1948. },
  1949. /**
  1950. * Callback for the DragListener's dragStart event
  1951. *
  1952. * @param {int} x the x position of the mouse on dragStart
  1953. * @param {int} y the x position of the mouse on dragStart
  1954. *
  1955. * @returns {void}
  1956. */
  1957. _onDragStart: function( x, y ) {
  1958. var itemConfig = this._itemConfig;
  1959. if( lm.utils.isFunction( itemConfig ) ) {
  1960. itemConfig = itemConfig();
  1961. }
  1962. var contentItem = this._layoutManager._$normalizeContentItem( $.extend( true, {}, itemConfig ) ),
  1963. dragProxy = new lm.controls.DragProxy( x, y, this._dragListener, this._layoutManager, contentItem, null );
  1964. this._layoutManager.transitionIndicator.transitionElements( this._element, dragProxy.element );
  1965. }
  1966. } );
  1967. lm.controls.DropTargetIndicator = function() {
  1968. this.element = $( lm.controls.DropTargetIndicator._template );
  1969. $( document.body ).append( this.element );
  1970. };
  1971. lm.controls.DropTargetIndicator._template = '<div class="lm_dropTargetIndicator"><div class="lm_inner"></div></div>';
  1972. lm.utils.copy( lm.controls.DropTargetIndicator.prototype, {
  1973. destroy: function() {
  1974. this.element.remove();
  1975. },
  1976. highlight: function( x1, y1, x2, y2 ) {
  1977. this.highlightArea( { x1: x1, y1: y1, x2: x2, y2: y2 } );
  1978. },
  1979. highlightArea: function( area ) {
  1980. this.element.css( {
  1981. left: area.x1,
  1982. top: area.y1,
  1983. width: area.x2 - area.x1,
  1984. height: area.y2 - area.y1
  1985. } ).show();
  1986. },
  1987. hide: function() {
  1988. this.element.hide();
  1989. }
  1990. } );
  1991. /**
  1992. * This class represents a header above a Stack ContentItem.
  1993. *
  1994. * @param {lm.LayoutManager} layoutManager
  1995. * @param {lm.item.AbstractContentItem} parent
  1996. */
  1997. lm.controls.Header = function( layoutManager, parent ) {
  1998. lm.utils.EventEmitter.call( this );
  1999. this.layoutManager = layoutManager;
  2000. this.element = $( lm.controls.Header._template );
  2001. if( this.layoutManager.config.settings.selectionEnabled === true ) {
  2002. this.element.addClass( 'lm_selectable' );
  2003. this.element.on( 'click touchstart', lm.utils.fnBind( this._onHeaderClick, this ) );
  2004. }
  2005. this.tabsContainer = this.element.find( '.lm_tabs' );
  2006. this.tabDropdownContainer = this.element.find( '.lm_tabdropdown_list' );
  2007. this.tabDropdownContainer.hide();
  2008. this.controlsContainer = this.element.find( '.lm_controls' );
  2009. this.parent = parent;
  2010. this.parent.on( 'resize', this._updateTabSizes, this );
  2011. this.tabs = [];
  2012. this.activeContentItem = null;
  2013. this.closeButton = null;
  2014. this.tabDropdownButton = null;
  2015. $( document ).mouseup( lm.utils.fnBind( this._hideAdditionalTabsDropdown, this ) );
  2016. this._lastVisibleTabIndex = -1;
  2017. this._tabControlOffset = 10;
  2018. this._createControls();
  2019. };
  2020. lm.controls.Header._template = [
  2021. '<div class="lm_header">',
  2022. '<ul class="lm_tabs"></ul>',
  2023. '<ul class="lm_controls"></ul>',
  2024. '<ul class="lm_tabdropdown_list"></ul>',
  2025. '</div>'
  2026. ].join( '' );
  2027. lm.utils.copy( lm.controls.Header.prototype, {
  2028. /**
  2029. * Creates a new tab and associates it with a contentItem
  2030. *
  2031. * @param {lm.item.AbstractContentItem} contentItem
  2032. * @param {Integer} index The position of the tab
  2033. *
  2034. * @returns {void}
  2035. */
  2036. createTab: function( contentItem, index ) {
  2037. var tab, i;
  2038. //If there's already a tab relating to the
  2039. //content item, don't do anything
  2040. for( i = 0; i < this.tabs.length; i++ ) {
  2041. if( this.tabs[ i ].contentItem === contentItem ) {
  2042. return;
  2043. }
  2044. }
  2045. tab = new lm.controls.Tab( this, contentItem );
  2046. if( this.tabs.length === 0 ) {
  2047. this.tabs.push( tab );
  2048. this.tabsContainer.append( tab.element );
  2049. return;
  2050. }
  2051. if( index === undefined ) {
  2052. index = this.tabs.length;
  2053. }
  2054. if( index > 0 ) {
  2055. this.tabs[ index - 1 ].element.after( tab.element );
  2056. } else {
  2057. this.tabs[ 0 ].element.before( tab.element );
  2058. }
  2059. this.tabs.splice( index, 0, tab );
  2060. this._updateTabSizes();
  2061. },
  2062. /**
  2063. * Finds a tab based on the contentItem its associated with and removes it.
  2064. *
  2065. * @param {lm.item.AbstractContentItem} contentItem
  2066. *
  2067. * @returns {void}
  2068. */
  2069. removeTab: function( contentItem ) {
  2070. for( var i = 0; i < this.tabs.length; i++ ) {
  2071. if( this.tabs[ i ].contentItem === contentItem ) {
  2072. this.tabs[ i ]._$destroy();
  2073. this.tabs.splice( i, 1 );
  2074. return;
  2075. }
  2076. }
  2077. throw new Error( 'contentItem is not controlled by this header' );
  2078. },
  2079. /**
  2080. * The programmatical equivalent of clicking a Tab.
  2081. *
  2082. * @param {lm.item.AbstractContentItem} contentItem
  2083. */
  2084. setActiveContentItem: function( contentItem ) {
  2085. var i, j, isActive, activeTab;
  2086. for( i = 0; i < this.tabs.length; i++ ) {
  2087. isActive = this.tabs[ i ].contentItem === contentItem;
  2088. this.tabs[ i ].setActive( isActive );
  2089. if( isActive === true ) {
  2090. this.activeContentItem = contentItem;
  2091. this.parent.config.activeItemIndex = i;
  2092. }
  2093. }
  2094. /**
  2095. * If the tab selected was in the dropdown, move everything down one to make way for this one to be the first.
  2096. * This will make sure the most used tabs stay visible.
  2097. */
  2098. if( this._lastVisibleTabIndex !== -1 && this.parent.config.activeItemIndex > this._lastVisibleTabIndex ) {
  2099. activeTab = this.tabs[ this.parent.config.activeItemIndex ];
  2100. for( j = this.parent.config.activeItemIndex; j > 0; j-- ) {
  2101. this.tabs[ j ] = this.tabs[ j - 1 ];
  2102. }
  2103. this.tabs[ 0 ] = activeTab;
  2104. this.parent.config.activeItemIndex = 0;
  2105. }
  2106. this._updateTabSizes();
  2107. this.parent.emitBubblingEvent( 'stateChanged' );
  2108. },
  2109. /**
  2110. * Programmatically operate with header position.
  2111. *
  2112. * @param {string} position one of ('top','left','right','bottom') to set or empty to get it.
  2113. *
  2114. * @returns {string} previous header position
  2115. */
  2116. position: function( position ) {
  2117. var previous = this.parent._header.show;
  2118. if( previous && !this.parent._side )
  2119. previous = 'top';
  2120. if( position !== undefined && this.parent._header.show != position ) {
  2121. this.parent._header.show = position;
  2122. this.parent._setupHeaderPosition();
  2123. }
  2124. return previous;
  2125. },
  2126. /**
  2127. * Programmatically set closability.
  2128. *
  2129. * @package private
  2130. * @param {Boolean} isClosable Whether to enable/disable closability.
  2131. *
  2132. * @returns {Boolean} Whether the action was successful
  2133. */
  2134. _$setClosable: function( isClosable ) {
  2135. if( this.closeButton && this._isClosable() ) {
  2136. this.closeButton.element[ isClosable ? "show" : "hide" ]();
  2137. return true;
  2138. }
  2139. return false;
  2140. },
  2141. /**
  2142. * Destroys the entire header
  2143. *
  2144. * @package private
  2145. *
  2146. * @returns {void}
  2147. */
  2148. _$destroy: function() {
  2149. this.emit( 'destroy', this );
  2150. for( var i = 0; i < this.tabs.length; i++ ) {
  2151. this.tabs[ i ]._$destroy();
  2152. }
  2153. this.element.remove();
  2154. },
  2155. /**
  2156. * get settings from header
  2157. *
  2158. * @returns {string} when exists
  2159. */
  2160. _getHeaderSetting: function( name ) {
  2161. if( name in this.parent._header )
  2162. return this.parent._header[ name ];
  2163. },
  2164. /**
  2165. * Creates the popout, maximise and close buttons in the header's top right corner
  2166. *
  2167. * @returns {void}
  2168. */
  2169. _createControls: function() {
  2170. var closeStack,
  2171. popout,
  2172. label,
  2173. maximiseLabel,
  2174. minimiseLabel,
  2175. maximise,
  2176. maximiseButton,
  2177. tabDropdownLabel,
  2178. showTabDropdown;
  2179. /**
  2180. * Dropdown to show additional tabs.
  2181. */
  2182. showTabDropdown = lm.utils.fnBind( this._showAdditionalTabsDropdown, this );
  2183. tabDropdownLabel = this.layoutManager.config.labels.tabDropdown;
  2184. this.tabDropdownButton = new lm.controls.HeaderButton( this, tabDropdownLabel, 'lm_tabdropdown', showTabDropdown );
  2185. this.tabDropdownButton.element.hide();
  2186. /**
  2187. * Popout control to launch component in new window.
  2188. */
  2189. if( this._getHeaderSetting( 'popout' ) ) {
  2190. popout = lm.utils.fnBind( this._onPopoutClick, this );
  2191. label = this._getHeaderSetting( 'popout' );
  2192. new lm.controls.HeaderButton( this, label, 'lm_popout', popout );
  2193. }
  2194. /**
  2195. * Maximise control - set the component to the full size of the layout
  2196. */
  2197. if( this._getHeaderSetting( 'maximise' ) ) {
  2198. maximise = lm.utils.fnBind( this.parent.toggleMaximise, this.parent );
  2199. maximiseLabel = this._getHeaderSetting( 'maximise' );
  2200. minimiseLabel = this._getHeaderSetting( 'minimise' );
  2201. maximiseButton = new lm.controls.HeaderButton( this, maximiseLabel, 'lm_maximise', maximise );
  2202. this.parent.on( 'maximised', function() {
  2203. maximiseButton.element.attr( 'title', minimiseLabel );
  2204. } );
  2205. this.parent.on( 'minimised', function() {
  2206. maximiseButton.element.attr( 'title', maximiseLabel );
  2207. } );
  2208. }
  2209. /**
  2210. * Close button
  2211. */
  2212. if( this._isClosable() ) {
  2213. closeStack = lm.utils.fnBind( this.parent.remove, this.parent );
  2214. label = this._getHeaderSetting( 'close' );
  2215. this.closeButton = new lm.controls.HeaderButton( this, label, 'lm_close', closeStack );
  2216. }
  2217. },
  2218. /**
  2219. * Shows drop down for additional tabs when there are too many to display.
  2220. *
  2221. * @returns {void}
  2222. */
  2223. _showAdditionalTabsDropdown: function() {
  2224. this.tabDropdownContainer.show();
  2225. },
  2226. /**
  2227. * Hides drop down for additional tabs when there are too many to display.
  2228. *
  2229. * @returns {void}
  2230. */
  2231. _hideAdditionalTabsDropdown: function( e ) {
  2232. this.tabDropdownContainer.hide();
  2233. },
  2234. /**
  2235. * Checks whether the header is closable based on the parent config and
  2236. * the global config.
  2237. *
  2238. * @returns {Boolean} Whether the header is closable.
  2239. */
  2240. _isClosable: function() {
  2241. return this.parent.config.isClosable && this.layoutManager.config.settings.showCloseIcon;
  2242. },
  2243. _onPopoutClick: function() {
  2244. if( this.layoutManager.config.settings.popoutWholeStack === true ) {
  2245. this.parent.popout();
  2246. } else {
  2247. this.activeContentItem.popout();
  2248. }
  2249. },
  2250. /**
  2251. * Invoked when the header's background is clicked (not it's tabs or controls)
  2252. *
  2253. * @param {jQuery DOM event} event
  2254. *
  2255. * @returns {void}
  2256. */
  2257. _onHeaderClick: function( event ) {
  2258. if( event.target === this.element[ 0 ] ) {
  2259. this.parent.select();
  2260. }
  2261. },
  2262. /**
  2263. * Pushes the tabs to the tab dropdown if the available space is not sufficient
  2264. *
  2265. * @returns {void}
  2266. */
  2267. _updateTabSizes: function() {
  2268. if( this.tabs.length === 0 ) {
  2269. return;
  2270. }
  2271. var size = function( val ) {
  2272. return val ? 'width' : 'height';
  2273. }
  2274. this.element.css( size( !this.parent._sided ), '' );
  2275. this.element[ size( this.parent._sided ) ]( this.layoutManager.config.dimensions.headerHeight );
  2276. var availableWidth = this.element.outerWidth() - this.controlsContainer.outerWidth() - this._tabControlOffset,
  2277. totalTabWidth = 0,
  2278. tabElement,
  2279. i,
  2280. showTabDropdown,
  2281. swapTab,
  2282. tabWidth,
  2283. hasVisibleTab = false;
  2284. if( this.parent._sided )
  2285. availableWidth = this.element.outerHeight() - this.controlsContainer.outerHeight() - this._tabControlOffset;
  2286. this._lastVisibleTabIndex = -1;
  2287. for( i = 0; i < this.tabs.length; i++ ) {
  2288. tabElement = this.tabs[ i ].element;
  2289. /*
  2290. * Retain tab width when hidden so it can be restored.
  2291. */
  2292. tabWidth = tabElement.data( 'lastTabWidth' );
  2293. if( !tabWidth ) {
  2294. tabWidth = tabElement.outerWidth() + parseInt( tabElement.css( 'margin-right' ), 10 );
  2295. }
  2296. totalTabWidth += tabWidth;
  2297. // If the tab won't fit, put it in the dropdown for tabs, making sure there is always at least one tab visible.
  2298. if( totalTabWidth > availableWidth && hasVisibleTab ) {
  2299. tabElement.data( 'lastTabWidth', tabWidth );
  2300. this.tabDropdownContainer.append( tabElement );
  2301. }
  2302. else {
  2303. hasVisibleTab = true;
  2304. this._lastVisibleTabIndex = i;
  2305. tabElement.removeData( 'lastTabWidth' );
  2306. this.tabsContainer.append( tabElement );
  2307. }
  2308. }
  2309. /*
  2310. * Show the tab dropdown icon if not all tabs fit.
  2311. */
  2312. showTabDropdown = totalTabWidth > availableWidth;
  2313. this.tabDropdownButton.element[ showTabDropdown ? 'show' : 'hide' ]();
  2314. }
  2315. } );
  2316. lm.controls.HeaderButton = function( header, label, cssClass, action ) {
  2317. this._header = header;
  2318. this.element = $( '<li class="' + cssClass + '" title="' + label + '"></li>' );
  2319. this._header.on( 'destroy', this._$destroy, this );
  2320. this._action = action;
  2321. this.element.on( 'click touchstart', this._action );
  2322. this._header.controlsContainer.append( this.element );
  2323. };
  2324. lm.utils.copy( lm.controls.HeaderButton.prototype, {
  2325. _$destroy: function() {
  2326. this.element.off();
  2327. this.element.remove();
  2328. }
  2329. } );
  2330. lm.controls.Splitter = function( isVertical, size ) {
  2331. this._isVertical = isVertical;
  2332. this._size = size;
  2333. this.element = this._createElement();
  2334. this._dragListener = new lm.utils.DragListener( this.element );
  2335. };
  2336. lm.utils.copy( lm.controls.Splitter.prototype, {
  2337. on: function( event, callback, context ) {
  2338. this._dragListener.on( event, callback, context );
  2339. },
  2340. _$destroy: function() {
  2341. this.element.remove();
  2342. },
  2343. _createElement: function() {
  2344. var element = $( '<div class="lm_splitter"><div class="lm_drag_handle"></div></div>' );
  2345. element.addClass( 'lm_' + ( this._isVertical ? 'vertical' : 'horizontal' ) );
  2346. element[ this._isVertical ? 'height' : 'width' ]( this._size );
  2347. return element;
  2348. }
  2349. } );
  2350. /**
  2351. * Represents an individual tab within a Stack's header
  2352. *
  2353. * @param {lm.controls.Header} header
  2354. * @param {lm.items.AbstractContentItem} contentItem
  2355. *
  2356. * @constructor
  2357. */
  2358. lm.controls.Tab = function( header, contentItem ) {
  2359. this.header = header;
  2360. this.contentItem = contentItem;
  2361. this.element = $( lm.controls.Tab._template );
  2362. this.titleElement = this.element.find( '.lm_title' );
  2363. this.closeElement = this.element.find( '.lm_close_tab' );
  2364. this.closeElement[ contentItem.config.isClosable ? 'show' : 'hide' ]();
  2365. this.isActive = false;
  2366. this.setTitle( contentItem.config.title );
  2367. this.contentItem.on( 'titleChanged', this.setTitle, this );
  2368. this._layoutManager = this.contentItem.layoutManager;
  2369. if(
  2370. this._layoutManager.config.settings.reorderEnabled === true &&
  2371. contentItem.config.reorderEnabled === true
  2372. ) {
  2373. this._dragListener = new lm.utils.DragListener( this.titleElement );
  2374. this._dragListener.on( 'dragStart', this._onDragStart, this );
  2375. }
  2376. this._onTabClickFn = lm.utils.fnBind( this._onTabClick, this );
  2377. this._onCloseClickFn = lm.utils.fnBind( this._onCloseClick, this );
  2378. this.titleElement.on( 'mousedown touchstart', this._onTabClickFn );
  2379. if( this.contentItem.config.isClosable ) {
  2380. this.closeElement.on( 'click touchstart', this._onCloseClickFn );
  2381. } else {
  2382. this.closeElement.remove();
  2383. }
  2384. this.contentItem.tab = this;
  2385. this.contentItem.emit( 'tab', this );
  2386. this.contentItem.layoutManager.emit( 'tabCreated', this );
  2387. if( this.contentItem.isComponent ) {
  2388. this.contentItem.container.tab = this;
  2389. this.contentItem.container.emit( 'tab', this );
  2390. }
  2391. };
  2392. /**
  2393. * The tab's html template
  2394. *
  2395. * @type {String}
  2396. */
  2397. lm.controls.Tab._template = '<li class="lm_tab"><i class="lm_left"></i>' +
  2398. '<span class="lm_title"></span><div class="lm_close_tab"></div>' +
  2399. '<i class="lm_right"></i></li>';
  2400. lm.utils.copy( lm.controls.Tab.prototype, {
  2401. /**
  2402. * Sets the tab's title to the provided string and sets
  2403. * its title attribute to a pure text representation (without
  2404. * html tags) of the same string.
  2405. *
  2406. * @public
  2407. * @param {String} title can contain html
  2408. */
  2409. setTitle: function( title ) {
  2410. this.element.attr( 'title', lm.utils.stripTags( title ) );
  2411. this.titleElement.html( title );
  2412. },
  2413. /**
  2414. * Sets this tab's active state. To programmatically
  2415. * switch tabs, use header.setActiveContentItem( item ) instead.
  2416. *
  2417. * @public
  2418. * @param {Boolean} isActive
  2419. */
  2420. setActive: function( isActive ) {
  2421. if( isActive === this.isActive ) {
  2422. return;
  2423. }
  2424. this.isActive = isActive;
  2425. if( isActive ) {
  2426. this.element.addClass( 'lm_active' );
  2427. } else {
  2428. this.element.removeClass( 'lm_active' );
  2429. }
  2430. },
  2431. /**
  2432. * Destroys the tab
  2433. *
  2434. * @private
  2435. * @returns {void}
  2436. */
  2437. _$destroy: function() {
  2438. this.titleElement.off( 'mousedown touchstart', this._onTabClickFn );
  2439. this.closeElement.off( 'click touchstart', this._onCloseClickFn );
  2440. if( this._dragListener ) {
  2441. this._dragListener.off( 'dragStart', this._onDragStart );
  2442. this._dragListener = null;
  2443. }
  2444. this.element.remove();
  2445. },
  2446. /**
  2447. * Callback for the DragListener
  2448. *
  2449. * @param {Number} x The tabs absolute x position
  2450. * @param {Number} y The tabs absolute y position
  2451. *
  2452. * @private
  2453. * @returns {void}
  2454. */
  2455. _onDragStart: function( x, y ) {
  2456. if( this.contentItem.parent.isMaximised === true ) {
  2457. this.contentItem.parent.toggleMaximise();
  2458. }
  2459. new lm.controls.DragProxy(
  2460. x,
  2461. y,
  2462. this._dragListener,
  2463. this._layoutManager,
  2464. this.contentItem,
  2465. this.header.parent
  2466. );
  2467. },
  2468. /**
  2469. * Callback when the tab is clicked
  2470. *
  2471. * @param {jQuery DOM event} event
  2472. *
  2473. * @private
  2474. * @returns {void}
  2475. */
  2476. _onTabClick: function( event ) {
  2477. // left mouse button or tap
  2478. if( event.button === 0 || event.type === 'touchstart' ) {
  2479. var activeContentItem = this.header.parent.getActiveContentItem();
  2480. if( this.contentItem !== activeContentItem ) {
  2481. this.header.parent.setActiveContentItem( this.contentItem );
  2482. }
  2483. // middle mouse button
  2484. } else if( event.button === 1 && this.contentItem.config.isClosable ) {
  2485. this._onCloseClick( event );
  2486. }
  2487. },
  2488. onClose : function() { return true; },
  2489. /**
  2490. * Callback when the tab's close button is
  2491. * clicked
  2492. *
  2493. * @param {jQuery DOM event} event
  2494. *
  2495. * @private
  2496. * @returns {void}
  2497. */
  2498. _onCloseClick: function( event ) {
  2499. event.stopPropagation();
  2500. if( !this.onClose() ) return;
  2501. this.header.parent.removeChild( this.contentItem );
  2502. }
  2503. } );
  2504. lm.controls.TransitionIndicator = function() {
  2505. this._element = $( '<div class="lm_transition_indicator"></div>' );
  2506. $( document.body ).append( this._element );
  2507. this._toElement = null;
  2508. this._fromDimensions = null;
  2509. this._totalAnimationDuration = 200;
  2510. this._animationStartTime = null;
  2511. };
  2512. lm.utils.copy( lm.controls.TransitionIndicator.prototype, {
  2513. destroy: function() {
  2514. this._element.remove();
  2515. },
  2516. transitionElements: function( fromElement, toElement ) {
  2517. /**
  2518. * TODO - This is not quite as cool as expected. Review.
  2519. */
  2520. return;
  2521. this._toElement = toElement;
  2522. this._animationStartTime = lm.utils.now();
  2523. this._fromDimensions = this._measure( fromElement );
  2524. this._fromDimensions.opacity = 0.8;
  2525. this._element.show().css( this._fromDimensions );
  2526. lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) );
  2527. },
  2528. _nextAnimationFrame: function() {
  2529. var toDimensions = this._measure( this._toElement ),
  2530. animationProgress = ( lm.utils.now() - this._animationStartTime ) / this._totalAnimationDuration,
  2531. currentFrameStyles = {},
  2532. cssProperty;
  2533. if( animationProgress >= 1 ) {
  2534. this._element.hide();
  2535. return;
  2536. }
  2537. toDimensions.opacity = 0;
  2538. for( cssProperty in this._fromDimensions ) {
  2539. currentFrameStyles[ cssProperty ] = this._fromDimensions[ cssProperty ] +
  2540. ( toDimensions[ cssProperty ] - this._fromDimensions[ cssProperty ] ) *
  2541. animationProgress;
  2542. }
  2543. this._element.css( currentFrameStyles );
  2544. lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) );
  2545. },
  2546. _measure: function( element ) {
  2547. var offset = element.offset();
  2548. return {
  2549. left: offset.left,
  2550. top: offset.top,
  2551. width: element.outerWidth(),
  2552. height: element.outerHeight()
  2553. };
  2554. }
  2555. } );
  2556. lm.errors.ConfigurationError = function( message, node ) {
  2557. Error.call( this );
  2558. this.name = 'Configuration Error';
  2559. this.message = message;
  2560. this.node = node;
  2561. };
  2562. lm.errors.ConfigurationError.prototype = new Error();
  2563. /**
  2564. * This is the baseclass that all content items inherit from.
  2565. * Most methods provide a subset of what the sub-classes do.
  2566. *
  2567. * It also provides a number of functions for tree traversal
  2568. *
  2569. * @param {lm.LayoutManager} layoutManager
  2570. * @param {item node configuration} config
  2571. * @param {lm.item} parent
  2572. *
  2573. * @event stateChanged
  2574. * @event beforeItemDestroyed
  2575. * @event itemDestroyed
  2576. * @event itemCreated
  2577. * @event componentCreated
  2578. * @event rowCreated
  2579. * @event columnCreated
  2580. * @event stackCreated
  2581. *
  2582. * @constructor
  2583. */
  2584. lm.items.AbstractContentItem = function( layoutManager, config, parent ) {
  2585. lm.utils.EventEmitter.call( this );
  2586. this.config = this._extendItemNode( config );
  2587. this.type = config.type;
  2588. this.contentItems = [];
  2589. this.parent = parent;
  2590. this.isInitialised = false;
  2591. this.isMaximised = false;
  2592. this.isRoot = false;
  2593. this.isRow = false;
  2594. this.isColumn = false;
  2595. this.isStack = false;
  2596. this.isComponent = false;
  2597. this.layoutManager = layoutManager;
  2598. this._pendingEventPropagations = {};
  2599. this._throttledEvents = [ 'stateChanged' ];
  2600. this.on( lm.utils.EventEmitter.ALL_EVENT, this._propagateEvent, this );
  2601. if( config.content ) {
  2602. this._createContentItems( config );
  2603. }
  2604. };
  2605. lm.utils.copy( lm.items.AbstractContentItem.prototype, {
  2606. /**
  2607. * Set the size of the component and its children, called recursively
  2608. *
  2609. * @abstract
  2610. * @returns void
  2611. */
  2612. setSize: function() {
  2613. throw new Error( 'Abstract Method' );
  2614. },
  2615. /**
  2616. * Calls a method recursively downwards on the tree
  2617. *
  2618. * @param {String} functionName the name of the function to be called
  2619. * @param {[Array]}functionArguments optional arguments that are passed to every function
  2620. * @param {[bool]} bottomUp Call methods from bottom to top, defaults to false
  2621. * @param {[bool]} skipSelf Don't invoke the method on the class that calls it, defaults to false
  2622. *
  2623. * @returns {void}
  2624. */
  2625. callDownwards: function( functionName, functionArguments, bottomUp, skipSelf ) {
  2626. var i;
  2627. if( bottomUp !== true && skipSelf !== true ) {
  2628. this[ functionName ].apply( this, functionArguments || [] );
  2629. }
  2630. for( i = 0; i < this.contentItems.length; i++ ) {
  2631. this.contentItems[ i ].callDownwards( functionName, functionArguments, bottomUp );
  2632. }
  2633. if( bottomUp === true && skipSelf !== true ) {
  2634. this[ functionName ].apply( this, functionArguments || [] );
  2635. }
  2636. },
  2637. /**
  2638. * Removes a child node (and its children) from the tree
  2639. *
  2640. * @param {lm.items.ContentItem} contentItem
  2641. *
  2642. * @returns {void}
  2643. */
  2644. removeChild: function( contentItem, keepChild ) {
  2645. /*
  2646. * Get the position of the item that's to be removed within all content items this node contains
  2647. */
  2648. var index = lm.utils.indexOf( contentItem, this.contentItems );
  2649. /*
  2650. * Make sure the content item to be removed is actually a child of this item
  2651. */
  2652. if( index === -1 ) {
  2653. throw new Error( 'Can\'t remove child item. Unknown content item' );
  2654. }
  2655. /**
  2656. * Call ._$destroy on the content item. This also calls ._$destroy on all its children
  2657. */
  2658. if( keepChild !== true ) {
  2659. this.contentItems[ index ]._$destroy();
  2660. }
  2661. /**
  2662. * Remove the content item from this nodes array of children
  2663. */
  2664. this.contentItems.splice( index, 1 );
  2665. /**
  2666. * Remove the item from the configuration
  2667. */
  2668. this.config.content.splice( index, 1 );
  2669. /**
  2670. * If this node still contains other content items, adjust their size
  2671. */
  2672. if( this.contentItems.length > 0 ) {
  2673. this.callDownwards( 'setSize' );
  2674. /**
  2675. * If this was the last content item, remove this node as well
  2676. */
  2677. } else if( !(this instanceof lm.items.Root) && this.config.isClosable === true ) {
  2678. this.parent.removeChild( this );
  2679. }
  2680. },
  2681. /**
  2682. * Sets up the tree structure for the newly added child
  2683. * The responsibility for the actual DOM manipulations lies
  2684. * with the concrete item
  2685. *
  2686. * @param {lm.items.AbstractContentItem} contentItem
  2687. * @param {[Int]} index If omitted item will be appended
  2688. */
  2689. addChild: function( contentItem, index ) {
  2690. if( index === undefined ) {
  2691. index = this.contentItems.length;
  2692. }
  2693. this.contentItems.splice( index, 0, contentItem );
  2694. if( this.config.content === undefined ) {
  2695. this.config.content = [];
  2696. }
  2697. this.config.content.splice( index, 0, contentItem.config );
  2698. contentItem.parent = this;
  2699. if( contentItem.parent.isInitialised === true && contentItem.isInitialised === false ) {
  2700. contentItem._$init();
  2701. }
  2702. },
  2703. /**
  2704. * Replaces oldChild with newChild. This used to use jQuery.replaceWith... which for
  2705. * some reason removes all event listeners, so isn't really an option.
  2706. *
  2707. * @param {lm.item.AbstractContentItem} oldChild
  2708. * @param {lm.item.AbstractContentItem} newChild
  2709. *
  2710. * @returns {void}
  2711. */
  2712. replaceChild: function( oldChild, newChild, _$destroyOldChild ) {
  2713. newChild = this.layoutManager._$normalizeContentItem( newChild );
  2714. var index = lm.utils.indexOf( oldChild, this.contentItems ),
  2715. parentNode = oldChild.element[ 0 ].parentNode;
  2716. if( index === -1 ) {
  2717. throw new Error( 'Can\'t replace child. oldChild is not child of this' );
  2718. }
  2719. parentNode.replaceChild( newChild.element[ 0 ], oldChild.element[ 0 ] );
  2720. /*
  2721. * Optionally destroy the old content item
  2722. */
  2723. if( _$destroyOldChild === true ) {
  2724. oldChild.parent = null;
  2725. oldChild._$destroy();
  2726. }
  2727. /*
  2728. * Wire the new contentItem into the tree
  2729. */
  2730. this.contentItems[ index ] = newChild;
  2731. newChild.parent = this;
  2732. /*
  2733. * Update tab reference
  2734. */
  2735. if( this.isStack ) {
  2736. this.header.tabs[ index ].contentItem = newChild;
  2737. }
  2738. //TODO This doesn't update the config... refactor to leave item nodes untouched after creation
  2739. if( newChild.parent.isInitialised === true && newChild.isInitialised === false ) {
  2740. newChild._$init();
  2741. }
  2742. this.callDownwards( 'setSize' );
  2743. },
  2744. /**
  2745. * Convenience method.
  2746. * Shorthand for this.parent.removeChild( this )
  2747. *
  2748. * @returns {void}
  2749. */
  2750. remove: function() {
  2751. this.parent.removeChild( this );
  2752. },
  2753. /**
  2754. * Removes the component from the layout and creates a new
  2755. * browser window with the component and its children inside
  2756. *
  2757. * @returns {lm.controls.BrowserPopout}
  2758. */
  2759. popout: function() {
  2760. var browserPopout = this.layoutManager.createPopout( this );
  2761. this.emitBubblingEvent( 'stateChanged' );
  2762. return browserPopout;
  2763. },
  2764. /**
  2765. * Maximises the Item or minimises it if it is already maximised
  2766. *
  2767. * @returns {void}
  2768. */
  2769. toggleMaximise: function( e ) {
  2770. e && e.preventDefault();
  2771. if( this.isMaximised === true ) {
  2772. this.layoutManager._$minimiseItem( this );
  2773. } else {
  2774. this.layoutManager._$maximiseItem( this );
  2775. }
  2776. this.isMaximised = !this.isMaximised;
  2777. this.emitBubblingEvent( 'stateChanged' );
  2778. },
  2779. /**
  2780. * Selects the item if it is not already selected
  2781. *
  2782. * @returns {void}
  2783. */
  2784. select: function() {
  2785. if( this.layoutManager.selectedItem !== this ) {
  2786. this.layoutManager.selectItem( this, true );
  2787. this.element.addClass( 'lm_selected' );
  2788. }
  2789. },
  2790. /**
  2791. * De-selects the item if it is selected
  2792. *
  2793. * @returns {void}
  2794. */
  2795. deselect: function() {
  2796. if( this.layoutManager.selectedItem === this ) {
  2797. this.layoutManager.selectedItem = null;
  2798. this.element.removeClass( 'lm_selected' );
  2799. }
  2800. },
  2801. /**
  2802. * Set this component's title
  2803. *
  2804. * @public
  2805. * @param {String} title
  2806. *
  2807. * @returns {void}
  2808. */
  2809. setTitle: function( title ) {
  2810. this.config.title = title;
  2811. this.emit( 'titleChanged', title );
  2812. this.emit( 'stateChanged' );
  2813. },
  2814. /**
  2815. * Checks whether a provided id is present
  2816. *
  2817. * @public
  2818. * @param {String} id
  2819. *
  2820. * @returns {Boolean} isPresent
  2821. */
  2822. hasId: function( id ) {
  2823. if( !this.config.id ) {
  2824. return false;
  2825. } else if( typeof this.config.id === 'string' ) {
  2826. return this.config.id === id;
  2827. } else if( this.config.id instanceof Array ) {
  2828. return lm.utils.indexOf( id, this.config.id ) !== -1;
  2829. }
  2830. },
  2831. /**
  2832. * Adds an id. Adds it as a string if the component doesn't
  2833. * have an id yet or creates/uses an array
  2834. *
  2835. * @public
  2836. * @param {String} id
  2837. *
  2838. * @returns {void}
  2839. */
  2840. addId: function( id ) {
  2841. if( this.hasId( id ) ) {
  2842. return;
  2843. }
  2844. if( !this.config.id ) {
  2845. this.config.id = id;
  2846. } else if( typeof this.config.id === 'string' ) {
  2847. this.config.id = [ this.config.id, id ];
  2848. } else if( this.config.id instanceof Array ) {
  2849. this.config.id.push( id );
  2850. }
  2851. },
  2852. /**
  2853. * Removes an existing id. Throws an error
  2854. * if the id is not present
  2855. *
  2856. * @public
  2857. * @param {String} id
  2858. *
  2859. * @returns {void}
  2860. */
  2861. removeId: function( id ) {
  2862. if( !this.hasId( id ) ) {
  2863. throw new Error( 'Id not found' );
  2864. }
  2865. if( typeof this.config.id === 'string' ) {
  2866. delete this.config.id;
  2867. } else if( this.config.id instanceof Array ) {
  2868. var index = lm.utils.indexOf( id, this.config.id );
  2869. this.config.id.splice( index, 1 );
  2870. }
  2871. },
  2872. /****************************************
  2873. * SELECTOR
  2874. ****************************************/
  2875. getItemsByFilter: function( filter ) {
  2876. var result = [],
  2877. next = function( contentItem ) {
  2878. for( var i = 0; i < contentItem.contentItems.length; i++ ) {
  2879. if( filter( contentItem.contentItems[ i ] ) === true ) {
  2880. result.push( contentItem.contentItems[ i ] );
  2881. }
  2882. next( contentItem.contentItems[ i ] );
  2883. }
  2884. };
  2885. next( this );
  2886. return result;
  2887. },
  2888. getItemsById: function( id ) {
  2889. return this.getItemsByFilter( function( item ) {
  2890. if( item.config.id instanceof Array ) {
  2891. return lm.utils.indexOf( id, item.config.id ) !== -1;
  2892. } else {
  2893. return item.config.id === id;
  2894. }
  2895. } );
  2896. },
  2897. getItemsByType: function( type ) {
  2898. return this._$getItemsByProperty( 'type', type );
  2899. },
  2900. getComponentsByName: function( componentName ) {
  2901. var components = this._$getItemsByProperty( 'componentName', componentName ),
  2902. instances = [],
  2903. i;
  2904. for( i = 0; i < components.length; i++ ) {
  2905. instances.push( components[ i ].instance );
  2906. }
  2907. return instances;
  2908. },
  2909. /****************************************
  2910. * PACKAGE PRIVATE
  2911. ****************************************/
  2912. _$getItemsByProperty: function( key, value ) {
  2913. return this.getItemsByFilter( function( item ) {
  2914. return item[ key ] === value;
  2915. } );
  2916. },
  2917. _$setParent: function( parent ) {
  2918. this.parent = parent;
  2919. },
  2920. _$highlightDropZone: function( x, y, area ) {
  2921. this.layoutManager.dropTargetIndicator.highlightArea( area );
  2922. },
  2923. _$onDrop: function( contentItem ) {
  2924. this.addChild( contentItem );
  2925. },
  2926. _$hide: function() {
  2927. this._callOnActiveComponents( 'hide' );
  2928. this.element.hide();
  2929. this.layoutManager.updateSize();
  2930. },
  2931. _$show: function() {
  2932. this._callOnActiveComponents( 'show' );
  2933. this.element.show();
  2934. this.layoutManager.updateSize();
  2935. },
  2936. _callOnActiveComponents: function( methodName ) {
  2937. var stacks = this.getItemsByType( 'stack' ),
  2938. activeContentItem,
  2939. i;
  2940. for( i = 0; i < stacks.length; i++ ) {
  2941. activeContentItem = stacks[ i ].getActiveContentItem();
  2942. if( activeContentItem && activeContentItem.isComponent ) {
  2943. activeContentItem.container[ methodName ]();
  2944. }
  2945. }
  2946. },
  2947. /**
  2948. * Destroys this item ands its children
  2949. *
  2950. * @returns {void}
  2951. */
  2952. _$destroy: function() {
  2953. this.emitBubblingEvent( 'beforeItemDestroyed' );
  2954. this.callDownwards( '_$destroy', [], true, true );
  2955. this.element.remove();
  2956. this.emitBubblingEvent( 'itemDestroyed' );
  2957. },
  2958. /**
  2959. * Returns the area the component currently occupies in the format
  2960. *
  2961. * {
  2962. * x1: int
  2963. * xy: int
  2964. * y1: int
  2965. * y2: int
  2966. * contentItem: contentItem
  2967. * }
  2968. */
  2969. _$getArea: function( element ) {
  2970. element = element || this.element;
  2971. var offset = element.offset(),
  2972. width = element.width(),
  2973. height = element.height();
  2974. return {
  2975. x1: offset.left,
  2976. y1: offset.top,
  2977. x2: offset.left + width,
  2978. y2: offset.top + height,
  2979. surface: width * height,
  2980. contentItem: this
  2981. };
  2982. },
  2983. /**
  2984. * The tree of content items is created in two steps: First all content items are instantiated,
  2985. * then init is called recursively from top to bottem. This is the basic init function,
  2986. * it can be used, extended or overwritten by the content items
  2987. *
  2988. * Its behaviour depends on the content item
  2989. *
  2990. * @package private
  2991. *
  2992. * @returns {void}
  2993. */
  2994. _$init: function() {
  2995. var i;
  2996. this.setSize();
  2997. for( i = 0; i < this.contentItems.length; i++ ) {
  2998. this.childElementContainer.append( this.contentItems[ i ].element );
  2999. }
  3000. this.isInitialised = true;
  3001. this.emitBubblingEvent( 'itemCreated' );
  3002. this.emitBubblingEvent( this.type + 'Created' );
  3003. },
  3004. /**
  3005. * Emit an event that bubbles up the item tree.
  3006. *
  3007. * @param {String} name The name of the event
  3008. *
  3009. * @returns {void}
  3010. */
  3011. emitBubblingEvent: function( name ) {
  3012. var event = new lm.utils.BubblingEvent( name, this );
  3013. this.emit( name, event );
  3014. },
  3015. /**
  3016. * Private method, creates all content items for this node at initialisation time
  3017. * PLEASE NOTE, please see addChild for adding contentItems add runtime
  3018. * @private
  3019. * @param {configuration item node} config
  3020. *
  3021. * @returns {void}
  3022. */
  3023. _createContentItems: function( config ) {
  3024. var oContentItem, i;
  3025. if( !( config.content instanceof Array ) ) {
  3026. throw new lm.errors.ConfigurationError( 'content must be an Array', config );
  3027. }
  3028. for( i = 0; i < config.content.length; i++ ) {
  3029. oContentItem = this.layoutManager.createContentItem( config.content[ i ], this );
  3030. this.contentItems.push( oContentItem );
  3031. }
  3032. },
  3033. /**
  3034. * Extends an item configuration node with default settings
  3035. * @private
  3036. * @param {configuration item node} config
  3037. *
  3038. * @returns {configuration item node} extended config
  3039. */
  3040. _extendItemNode: function( config ) {
  3041. for( var key in lm.config.itemDefaultConfig ) {
  3042. if( config[ key ] === undefined ) {
  3043. config[ key ] = lm.config.itemDefaultConfig[ key ];
  3044. }
  3045. }
  3046. return config;
  3047. },
  3048. /**
  3049. * Called for every event on the item tree. Decides whether the event is a bubbling
  3050. * event and propagates it to its parent
  3051. *
  3052. * @param {String} name the name of the event
  3053. * @param {lm.utils.BubblingEvent} event
  3054. *
  3055. * @returns {void}
  3056. */
  3057. _propagateEvent: function( name, event ) {
  3058. if( event instanceof lm.utils.BubblingEvent &&
  3059. event.isPropagationStopped === false &&
  3060. this.isInitialised === true ) {
  3061. /**
  3062. * In some cases (e.g. if an element is created from a DragSource) it
  3063. * doesn't have a parent and is not below root. If that's the case
  3064. * propagate the bubbling event from the top level of the substree directly
  3065. * to the layoutManager
  3066. */
  3067. if( this.isRoot === false && this.parent ) {
  3068. this.parent.emit.apply( this.parent, Array.prototype.slice.call( arguments, 0 ) );
  3069. } else {
  3070. this._scheduleEventPropagationToLayoutManager( name, event );
  3071. }
  3072. }
  3073. },
  3074. /**
  3075. * All raw events bubble up to the root element. Some events that
  3076. * are propagated to - and emitted by - the layoutManager however are
  3077. * only string-based, batched and sanitized to make them more usable
  3078. *
  3079. * @param {String} name the name of the event
  3080. *
  3081. * @private
  3082. * @returns {void}
  3083. */
  3084. _scheduleEventPropagationToLayoutManager: function( name, event ) {
  3085. if( lm.utils.indexOf( name, this._throttledEvents ) === -1 ) {
  3086. this.layoutManager.emit( name, event.origin );
  3087. } else {
  3088. if( this._pendingEventPropagations[ name ] !== true ) {
  3089. this._pendingEventPropagations[ name ] = true;
  3090. lm.utils.animFrame( lm.utils.fnBind( this._propagateEventToLayoutManager, this, [ name, event ] ) );
  3091. }
  3092. }
  3093. },
  3094. /**
  3095. * Callback for events scheduled by _scheduleEventPropagationToLayoutManager
  3096. *
  3097. * @param {String} name the name of the event
  3098. *
  3099. * @private
  3100. * @returns {void}
  3101. */
  3102. _propagateEventToLayoutManager: function( name, event ) {
  3103. this._pendingEventPropagations[ name ] = false;
  3104. this.layoutManager.emit( name, event );
  3105. }
  3106. } );
  3107. /**
  3108. * @param {[type]} layoutManager [description]
  3109. * @param {[type]} config [description]
  3110. * @param {[type]} parent [description]
  3111. */
  3112. lm.items.Component = function( layoutManager, config, parent ) {
  3113. lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
  3114. var ComponentConstructor = layoutManager.getComponent( this.config.componentName ),
  3115. componentConfig = $.extend( true, {}, this.config.componentState || {} );
  3116. componentConfig.componentName = this.config.componentName;
  3117. this.componentName = this.config.componentName;
  3118. if( this.config.title === '' ) {
  3119. this.config.title = this.config.componentName;
  3120. }
  3121. this.isComponent = true;
  3122. this.container = new lm.container.ItemContainer( this.config, this, layoutManager );
  3123. this.instance = new ComponentConstructor( this.container, componentConfig );
  3124. this.element = this.container._element;
  3125. };
  3126. lm.utils.extend( lm.items.Component, lm.items.AbstractContentItem );
  3127. lm.utils.copy( lm.items.Component.prototype, {
  3128. close: function() {
  3129. this.parent.removeChild( this );
  3130. },
  3131. setSize: function() {
  3132. if( this.element.is( ':visible' ) ) {
  3133. // Do not update size of hidden components to prevent unwanted reflows
  3134. this.container._$setSize( this.element.width(), this.element.height() );
  3135. }
  3136. },
  3137. _$init: function() {
  3138. lm.items.AbstractContentItem.prototype._$init.call( this );
  3139. this.container.emit( 'open' );
  3140. },
  3141. _$hide: function() {
  3142. this.container.hide();
  3143. lm.items.AbstractContentItem.prototype._$hide.call( this );
  3144. },
  3145. _$show: function() {
  3146. this.container.show();
  3147. lm.items.AbstractContentItem.prototype._$show.call( this );
  3148. },
  3149. _$shown: function() {
  3150. this.container.shown();
  3151. lm.items.AbstractContentItem.prototype._$shown.call( this );
  3152. },
  3153. _$destroy: function() {
  3154. this.container.emit( 'destroy', this );
  3155. lm.items.AbstractContentItem.prototype._$destroy.call( this );
  3156. },
  3157. /**
  3158. * Dragging onto a component directly is not an option
  3159. *
  3160. * @returns null
  3161. */
  3162. _$getArea: function() {
  3163. return null;
  3164. }
  3165. } );
  3166. lm.items.Root = function( layoutManager, config, containerElement ) {
  3167. lm.items.AbstractContentItem.call( this, layoutManager, config, null );
  3168. this.isRoot = true;
  3169. this.type = 'root';
  3170. this.element = $( '<div class="lm_goldenlayout lm_item lm_root"></div>' );
  3171. this.childElementContainer = this.element;
  3172. this._containerElement = containerElement;
  3173. this._containerElement.append( this.element );
  3174. };
  3175. lm.utils.extend( lm.items.Root, lm.items.AbstractContentItem );
  3176. lm.utils.copy( lm.items.Root.prototype, {
  3177. addChild: function( contentItem ) {
  3178. if( this.contentItems.length > 0 ) {
  3179. throw new Error( 'Root node can only have a single child' );
  3180. }
  3181. contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
  3182. this.childElementContainer.append( contentItem.element );
  3183. lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem );
  3184. this.callDownwards( 'setSize' );
  3185. this.emitBubblingEvent( 'stateChanged' );
  3186. },
  3187. setSize: function( width, height ) {
  3188. width = (typeof width === 'undefined') ? this._containerElement.width() : width;
  3189. height = (typeof height === 'undefined') ? this._containerElement.height() : height;
  3190. this.element.width( width );
  3191. this.element.height( height );
  3192. /*
  3193. * Root can be empty
  3194. */
  3195. if( this.contentItems[ 0 ] ) {
  3196. this.contentItems[ 0 ].element.width( width );
  3197. this.contentItems[ 0 ].element.height( height );
  3198. }
  3199. },
  3200. _$highlightDropZone: function( x, y, area ) {
  3201. this.layoutManager.tabDropPlaceholder.remove();
  3202. lm.items.AbstractContentItem.prototype._$highlightDropZone.apply( this, arguments );
  3203. },
  3204. _$onDrop: function( contentItem, area ) {
  3205. var stack;
  3206. if( contentItem.isComponent ) {
  3207. stack = this.layoutManager.createContentItem( {
  3208. type: 'stack',
  3209. header: contentItem.config.header || {}
  3210. }, this );
  3211. stack._$init();
  3212. stack.addChild( contentItem );
  3213. contentItem = stack;
  3214. }
  3215. if( !this.contentItems.length ) {
  3216. this.addChild( contentItem );
  3217. } else {
  3218. var type = area.side[ 0 ] == 'x' ? 'row' : 'column';
  3219. var dimension = area.side[ 0 ] == 'x' ? 'width' : 'height';
  3220. var insertBefore = area.side[ 1 ] == '2';
  3221. var column = this.contentItems[ 0 ];
  3222. if( !column instanceof lm.items.RowOrColumn || column.type != type ) {
  3223. var rowOrColumn = this.layoutManager.createContentItem( { type: type }, this );
  3224. this.replaceChild( column, rowOrColumn );
  3225. rowOrColumn.addChild( contentItem, insertBefore ? 0 : undefined, true );
  3226. rowOrColumn.addChild( column, insertBefore ? undefined : 0, true );
  3227. column.config[ dimension ] = 50;
  3228. contentItem.config[ dimension ] = 50;
  3229. rowOrColumn.callDownwards( 'setSize' );
  3230. } else {
  3231. var sibbling = column.contentItems[ insertBefore ? 0 : column.contentItems.length - 1 ]
  3232. column.addChild( contentItem, insertBefore ? 0 : undefined, true );
  3233. sibbling.config[ dimension ] *= 0.5;
  3234. contentItem.config[ dimension ] = sibbling.config[ dimension ];
  3235. column.callDownwards( 'setSize' );
  3236. }
  3237. }
  3238. }
  3239. } );
  3240. lm.items.RowOrColumn = function( isColumn, layoutManager, config, parent ) {
  3241. lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
  3242. this.isRow = !isColumn;
  3243. this.isColumn = isColumn;
  3244. this.element = $( '<div class="lm_item lm_' + ( isColumn ? 'column' : 'row' ) + '"></div>' );
  3245. this.childElementContainer = this.element;
  3246. this._splitterSize = layoutManager.config.dimensions.borderWidth;
  3247. this._isColumn = isColumn;
  3248. this._dimension = isColumn ? 'height' : 'width';
  3249. this._splitter = [];
  3250. this._splitterPosition = null;
  3251. this._splitterMinPosition = null;
  3252. this._splitterMaxPosition = null;
  3253. };
  3254. lm.utils.extend( lm.items.RowOrColumn, lm.items.AbstractContentItem );
  3255. lm.utils.copy( lm.items.RowOrColumn.prototype, {
  3256. /**
  3257. * Add a new contentItem to the Row or Column
  3258. *
  3259. * @param {lm.item.AbstractContentItem} contentItem
  3260. * @param {[int]} index The position of the new item within the Row or Column.
  3261. * If no index is provided the item will be added to the end
  3262. * @param {[bool]} _$suspendResize If true the items won't be resized. This will leave the item in
  3263. * an inconsistent state and is only intended to be used if multiple
  3264. * children need to be added in one go and resize is called afterwards
  3265. *
  3266. * @returns {void}
  3267. */
  3268. addChild: function( contentItem, index, _$suspendResize ) {
  3269. var newItemSize, itemSize, i, splitterElement;
  3270. contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
  3271. if( index === undefined ) {
  3272. index = this.contentItems.length;
  3273. }
  3274. if( this.contentItems.length > 0 ) {
  3275. splitterElement = this._createSplitter( Math.max( 0, index - 1 ) ).element;
  3276. if( index > 0 ) {
  3277. this.contentItems[ index - 1 ].element.after( splitterElement );
  3278. splitterElement.after( contentItem.element );
  3279. } else {
  3280. this.contentItems[ 0 ].element.before( splitterElement );
  3281. splitterElement.before( contentItem.element );
  3282. }
  3283. } else {
  3284. this.childElementContainer.append( contentItem.element );
  3285. }
  3286. lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index );
  3287. newItemSize = ( 1 / this.contentItems.length ) * 100;
  3288. if( _$suspendResize === true ) {
  3289. this.emitBubblingEvent( 'stateChanged' );
  3290. return;
  3291. }
  3292. for( i = 0; i < this.contentItems.length; i++ ) {
  3293. if( this.contentItems[ i ] === contentItem ) {
  3294. contentItem.config[ this._dimension ] = newItemSize;
  3295. } else {
  3296. itemSize = this.contentItems[ i ].config[ this._dimension ] *= ( 100 - newItemSize ) / 100;
  3297. this.contentItems[ i ].config[ this._dimension ] = itemSize;
  3298. }
  3299. }
  3300. this.callDownwards( 'setSize' );
  3301. this.emitBubblingEvent( 'stateChanged' );
  3302. },
  3303. /**
  3304. * Removes a child of this element
  3305. *
  3306. * @param {lm.items.AbstractContentItem} contentItem
  3307. * @param {boolean} keepChild If true the child will be removed, but not destroyed
  3308. *
  3309. * @returns {void}
  3310. */
  3311. removeChild: function( contentItem, keepChild ) {
  3312. var removedItemSize = contentItem.config[ this._dimension ],
  3313. index = lm.utils.indexOf( contentItem, this.contentItems ),
  3314. splitterIndex = Math.max( index - 1, 0 ),
  3315. i,
  3316. childItem;
  3317. if( index === -1 ) {
  3318. throw new Error( 'Can\'t remove child. ContentItem is not child of this Row or Column' );
  3319. }
  3320. /**
  3321. * Remove the splitter before the item or after if the item happens
  3322. * to be the first in the row/column
  3323. */
  3324. if( this._splitter[ splitterIndex ] ) {
  3325. this._splitter[ splitterIndex ]._$destroy();
  3326. this._splitter.splice( splitterIndex, 1 );
  3327. }
  3328. /**
  3329. * Allocate the space that the removed item occupied to the remaining items
  3330. */
  3331. for( i = 0; i < this.contentItems.length; i++ ) {
  3332. if( this.contentItems[ i ] !== contentItem ) {
  3333. this.contentItems[ i ].config[ this._dimension ] += removedItemSize / ( this.contentItems.length - 1 );
  3334. }
  3335. }
  3336. lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild );
  3337. if( this.contentItems.length === 1 && this.config.isClosable === true ) {
  3338. childItem = this.contentItems[ 0 ];
  3339. this.contentItems = [];
  3340. this.parent.replaceChild( this, childItem, true );
  3341. } else {
  3342. this.callDownwards( 'setSize' );
  3343. this.emitBubblingEvent( 'stateChanged' );
  3344. }
  3345. },
  3346. /**
  3347. * Replaces a child of this Row or Column with another contentItem
  3348. *
  3349. * @param {lm.items.AbstractContentItem} oldChild
  3350. * @param {lm.items.AbstractContentItem} newChild
  3351. *
  3352. * @returns {void}
  3353. */
  3354. replaceChild: function( oldChild, newChild ) {
  3355. var size = oldChild.config[ this._dimension ];
  3356. lm.items.AbstractContentItem.prototype.replaceChild.call( this, oldChild, newChild );
  3357. newChild.config[ this._dimension ] = size;
  3358. this.callDownwards( 'setSize' );
  3359. this.emitBubblingEvent( 'stateChanged' );
  3360. },
  3361. /**
  3362. * Called whenever the dimensions of this item or one of its parents change
  3363. *
  3364. * @returns {void}
  3365. */
  3366. setSize: function() {
  3367. if( this.contentItems.length > 0 ) {
  3368. this._calculateRelativeSizes();
  3369. this._setAbsoluteSizes();
  3370. }
  3371. this.emitBubblingEvent( 'stateChanged' );
  3372. this.emit( 'resize' );
  3373. },
  3374. /**
  3375. * Invoked recursively by the layout manager. AbstractContentItem.init appends
  3376. * the contentItem's DOM elements to the container, RowOrColumn init adds splitters
  3377. * in between them
  3378. *
  3379. * @package private
  3380. * @override AbstractContentItem._$init
  3381. * @returns {void}
  3382. */
  3383. _$init: function() {
  3384. if( this.isInitialised === true ) return;
  3385. var i;
  3386. lm.items.AbstractContentItem.prototype._$init.call( this );
  3387. for( i = 0; i < this.contentItems.length - 1; i++ ) {
  3388. this.contentItems[ i ].element.after( this._createSplitter( i ).element );
  3389. }
  3390. },
  3391. /**
  3392. * Turns the relative sizes calculated by _calculateRelativeSizes into
  3393. * absolute pixel values and applies them to the children's DOM elements
  3394. *
  3395. * Assigns additional pixels to counteract Math.floor
  3396. *
  3397. * @private
  3398. * @returns {void}
  3399. */
  3400. _setAbsoluteSizes: function() {
  3401. var i,
  3402. sizeData = this._calculateAbsoluteSizes();
  3403. for( i = 0; i < this.contentItems.length; i++ ) {
  3404. if( sizeData.additionalPixel - i > 0 ) {
  3405. sizeData.itemSizes[ i ]++;
  3406. }
  3407. if( this._isColumn ) {
  3408. this.contentItems[ i ].element.width( sizeData.totalWidth );
  3409. this.contentItems[ i ].element.height( sizeData.itemSizes[ i ] );
  3410. } else {
  3411. this.contentItems[ i ].element.width( sizeData.itemSizes[ i ] );
  3412. this.contentItems[ i ].element.height( sizeData.totalHeight );
  3413. }
  3414. }
  3415. },
  3416. /**
  3417. * Calculates the absolute sizes of all of the children of this Item.
  3418. * @returns {object} - Set with absolute sizes and additional pixels.
  3419. */
  3420. _calculateAbsoluteSizes: function() {
  3421. var i,
  3422. totalSplitterSize = (this.contentItems.length - 1) * this._splitterSize,
  3423. totalWidth = this.element.width(),
  3424. totalHeight = this.element.height(),
  3425. totalAssigned = 0,
  3426. additionalPixel,
  3427. itemSize,
  3428. itemSizes = [];
  3429. if( this._isColumn ) {
  3430. totalHeight -= totalSplitterSize;
  3431. } else {
  3432. totalWidth -= totalSplitterSize;
  3433. }
  3434. for( i = 0; i < this.contentItems.length; i++ ) {
  3435. if( this._isColumn ) {
  3436. itemSize = Math.floor( totalHeight * ( this.contentItems[ i ].config.height / 100 ) );
  3437. } else {
  3438. itemSize = Math.floor( totalWidth * (this.contentItems[ i ].config.width / 100) );
  3439. }
  3440. totalAssigned += itemSize;
  3441. itemSizes.push( itemSize );
  3442. }
  3443. additionalPixel = Math.floor( (this._isColumn ? totalHeight : totalWidth) - totalAssigned );
  3444. return {
  3445. itemSizes: itemSizes,
  3446. additionalPixel: additionalPixel,
  3447. totalWidth: totalWidth,
  3448. totalHeight: totalHeight
  3449. };
  3450. },
  3451. /**
  3452. * Calculates the relative sizes of all children of this Item. The logic
  3453. * is as follows:
  3454. *
  3455. * - Add up the total size of all items that have a configured size
  3456. *
  3457. * - If the total == 100 (check for floating point errors)
  3458. * Excellent, job done
  3459. *
  3460. * - If the total is > 100,
  3461. * set the size of items without set dimensions to 1/3 and add this to the total
  3462. * set the size off all items so that the total is hundred relative to their original size
  3463. *
  3464. * - If the total is < 100
  3465. * If there are items without set dimensions, distribute the remainder to 100 evenly between them
  3466. * If there are no items without set dimensions, increase all items sizes relative to
  3467. * their original size so that they add up to 100
  3468. *
  3469. * @private
  3470. * @returns {void}
  3471. */
  3472. _calculateRelativeSizes: function() {
  3473. var i,
  3474. total = 0,
  3475. itemsWithoutSetDimension = [],
  3476. dimension = this._isColumn ? 'height' : 'width';
  3477. for( i = 0; i < this.contentItems.length; i++ ) {
  3478. if( this.contentItems[ i ].config[ dimension ] !== undefined ) {
  3479. total += this.contentItems[ i ].config[ dimension ];
  3480. } else {
  3481. itemsWithoutSetDimension.push( this.contentItems[ i ] );
  3482. }
  3483. }
  3484. /**
  3485. * Everything adds up to hundred, all good :-)
  3486. */
  3487. if( Math.round( total ) === 100 ) {
  3488. this._respectMinItemWidth();
  3489. return;
  3490. }
  3491. /**
  3492. * Allocate the remaining size to the items without a set dimension
  3493. */
  3494. if( Math.round( total ) < 100 && itemsWithoutSetDimension.length > 0 ) {
  3495. for( i = 0; i < itemsWithoutSetDimension.length; i++ ) {
  3496. itemsWithoutSetDimension[ i ].config[ dimension ] = ( 100 - total ) / itemsWithoutSetDimension.length;
  3497. }
  3498. this._respectMinItemWidth();
  3499. return;
  3500. }
  3501. /**
  3502. * If the total is > 100, but there are also items without a set dimension left, assing 50
  3503. * as their dimension and add it to the total
  3504. *
  3505. * This will be reset in the next step
  3506. */
  3507. if( Math.round( total ) > 100 ) {
  3508. for( i = 0; i < itemsWithoutSetDimension.length; i++ ) {
  3509. itemsWithoutSetDimension[ i ].config[ dimension ] = 50;
  3510. total += 50;
  3511. }
  3512. }
  3513. /**
  3514. * Set every items size relative to 100 relative to its size to total
  3515. */
  3516. for( i = 0; i < this.contentItems.length; i++ ) {
  3517. this.contentItems[ i ].config[ dimension ] = ( this.contentItems[ i ].config[ dimension ] / total ) * 100;
  3518. }
  3519. this._respectMinItemWidth();
  3520. },
  3521. /**
  3522. * Adjusts the column widths to respect the dimensions minItemWidth if set.
  3523. * @returns {}
  3524. */
  3525. _respectMinItemWidth: function() {
  3526. var minItemWidth = this.layoutManager.config.dimensions ? (this.layoutManager.config.dimensions.minItemWidth || 0) : 0,
  3527. sizeData = null,
  3528. entriesOverMin = [],
  3529. totalOverMin = 0,
  3530. totalUnderMin = 0,
  3531. remainingWidth = 0,
  3532. itemSize = 0,
  3533. contentItem = null,
  3534. reducePercent,
  3535. reducedWidth,
  3536. allEntries = [],
  3537. entry;
  3538. if( this._isColumn || !minItemWidth || this.contentItems.length <= 1 ) {
  3539. return;
  3540. }
  3541. sizeData = this._calculateAbsoluteSizes();
  3542. /**
  3543. * Figure out how much we are under the min item size total and how much room we have to use.
  3544. */
  3545. for( i = 0; i < this.contentItems.length; i++ ) {
  3546. contentItem = this.contentItems[ i ];
  3547. itemSize = sizeData.itemSizes[ i ];
  3548. if( itemSize < minItemWidth ) {
  3549. totalUnderMin += minItemWidth - itemSize;
  3550. entry = { width: minItemWidth };
  3551. }
  3552. else {
  3553. totalOverMin += itemSize - minItemWidth;
  3554. entry = { width: itemSize };
  3555. entriesOverMin.push( entry );
  3556. }
  3557. allEntries.push( entry );
  3558. }
  3559. /**
  3560. * If there is nothing under min, or there is not enough over to make up the difference, do nothing.
  3561. */
  3562. if( totalUnderMin === 0 || totalUnderMin > totalOverMin ) {
  3563. return;
  3564. }
  3565. /**
  3566. * Evenly reduce all columns that are over the min item width to make up the difference.
  3567. */
  3568. reducePercent = totalUnderMin / totalOverMin;
  3569. remainingWidth = totalUnderMin;
  3570. for( i = 0; i < entriesOverMin.length; i++ ) {
  3571. entry = entriesOverMin[ i ];
  3572. reducedWidth = Math.round( ( entry.width - minItemWidth ) * reducePercent );
  3573. remainingWidth -= reducedWidth;
  3574. entry.width -= reducedWidth;
  3575. }
  3576. /**
  3577. * Take anything remaining from the last item.
  3578. */
  3579. if( remainingWidth !== 0 ) {
  3580. allEntries[ allEntries.length - 1 ].width -= remainingWidth;
  3581. }
  3582. /**
  3583. * Set every items size relative to 100 relative to its size to total
  3584. */
  3585. for( i = 0; i < this.contentItems.length; i++ ) {
  3586. this.contentItems[ i ].config.width = (allEntries[ i ].width / sizeData.totalWidth) * 100;
  3587. }
  3588. },
  3589. /**
  3590. * Instantiates a new lm.controls.Splitter, binds events to it and adds
  3591. * it to the array of splitters at the position specified as the index argument
  3592. *
  3593. * What it doesn't do though is append the splitter to the DOM
  3594. *
  3595. * @param {Int} index The position of the splitter
  3596. *
  3597. * @returns {lm.controls.Splitter}
  3598. */
  3599. _createSplitter: function( index ) {
  3600. var splitter;
  3601. splitter = new lm.controls.Splitter( this._isColumn, this._splitterSize );
  3602. splitter.on( 'drag', lm.utils.fnBind( this._onSplitterDrag, this, [ splitter ] ), this );
  3603. splitter.on( 'dragStop', lm.utils.fnBind( this._onSplitterDragStop, this, [ splitter ] ), this );
  3604. splitter.on( 'dragStart', lm.utils.fnBind( this._onSplitterDragStart, this, [ splitter ] ), this );
  3605. this._splitter.splice( index, 0, splitter );
  3606. return splitter;
  3607. },
  3608. /**
  3609. * Locates the instance of lm.controls.Splitter in the array of
  3610. * registered splitters and returns a map containing the contentItem
  3611. * before and after the splitters, both of which are affected if the
  3612. * splitter is moved
  3613. *
  3614. * @param {lm.controls.Splitter} splitter
  3615. *
  3616. * @returns {Object} A map of contentItems that the splitter affects
  3617. */
  3618. _getItemsForSplitter: function( splitter ) {
  3619. var index = lm.utils.indexOf( splitter, this._splitter );
  3620. return {
  3621. before: this.contentItems[ index ],
  3622. after: this.contentItems[ index + 1 ]
  3623. };
  3624. },
  3625. /**
  3626. * Gets the minimum dimensions for the given item configuration array
  3627. * @param item
  3628. * @private
  3629. */
  3630. _getMinimumDimensions: function( arr ) {
  3631. var minWidth = 0, minHeight = 0;
  3632. for( var i = 0; i < arr.length; ++i ) {
  3633. minWidth = Math.max( arr[ i ].minWidth || 0, minWidth );
  3634. minHeight = Math.max( arr[ i ].minHeight || 0, minHeight );
  3635. }
  3636. return { horizontal: minWidth, vertical: minHeight };
  3637. },
  3638. /**
  3639. * Invoked when a splitter's dragListener fires dragStart. Calculates the splitters
  3640. * movement area once (so that it doesn't need calculating on every mousemove event)
  3641. *
  3642. * @param {lm.controls.Splitter} splitter
  3643. *
  3644. * @returns {void}
  3645. */
  3646. _onSplitterDragStart: function( splitter ) {
  3647. var items = this._getItemsForSplitter( splitter ),
  3648. minSize = this.layoutManager.config.dimensions[ this._isColumn ? 'minItemHeight' : 'minItemWidth' ];
  3649. var beforeMinDim = this._getMinimumDimensions( items.before.config.content );
  3650. var beforeMinSize = this._isColumn ? beforeMinDim.vertical : beforeMinDim.horizontal;
  3651. var afterMinDim = this._getMinimumDimensions( items.after.config.content );
  3652. var afterMinSize = this._isColumn ? afterMinDim.vertical : afterMinDim.horizontal;
  3653. this._splitterPosition = 0;
  3654. this._splitterMinPosition = -1 * ( items.before.element[ this._dimension ]() - (beforeMinSize || minSize) );
  3655. this._splitterMaxPosition = items.after.element[ this._dimension ]() - (afterMinSize || minSize);
  3656. },
  3657. /**
  3658. * Invoked when a splitter's DragListener fires drag. Updates the splitters DOM position,
  3659. * but not the sizes of the elements the splitter controls in order to minimize resize events
  3660. *
  3661. * @param {lm.controls.Splitter} splitter
  3662. * @param {Int} offsetX Relative pixel values to the splitters original position. Can be negative
  3663. * @param {Int} offsetY Relative pixel values to the splitters original position. Can be negative
  3664. *
  3665. * @returns {void}
  3666. */
  3667. _onSplitterDrag: function( splitter, offsetX, offsetY ) {
  3668. var offset = this._isColumn ? offsetY : offsetX;
  3669. if( offset > this._splitterMinPosition && offset < this._splitterMaxPosition ) {
  3670. this._splitterPosition = offset;
  3671. splitter.element.css( this._isColumn ? 'top' : 'left', offset );
  3672. }
  3673. },
  3674. /**
  3675. * Invoked when a splitter's DragListener fires dragStop. Resets the splitters DOM position,
  3676. * and applies the new sizes to the elements before and after the splitter and their children
  3677. * on the next animation frame
  3678. *
  3679. * @param {lm.controls.Splitter} splitter
  3680. *
  3681. * @returns {void}
  3682. */
  3683. _onSplitterDragStop: function( splitter ) {
  3684. var items = this._getItemsForSplitter( splitter ),
  3685. sizeBefore = items.before.element[ this._dimension ](),
  3686. sizeAfter = items.after.element[ this._dimension ](),
  3687. splitterPositionInRange = ( this._splitterPosition + sizeBefore ) / ( sizeBefore + sizeAfter ),
  3688. totalRelativeSize = items.before.config[ this._dimension ] + items.after.config[ this._dimension ];
  3689. items.before.config[ this._dimension ] = splitterPositionInRange * totalRelativeSize;
  3690. items.after.config[ this._dimension ] = ( 1 - splitterPositionInRange ) * totalRelativeSize;
  3691. splitter.element.css( {
  3692. 'top': 0,
  3693. 'left': 0
  3694. } );
  3695. lm.utils.animFrame( lm.utils.fnBind( this.callDownwards, this, [ 'setSize' ] ) );
  3696. }
  3697. } );
  3698. lm.items.Stack = function( layoutManager, config, parent ) {
  3699. lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
  3700. this.element = $( '<div class="lm_item lm_stack"></div>' );
  3701. this._activeContentItem = null;
  3702. var cfg = layoutManager.config;
  3703. this._header = { // defaults' reconstruction from old configuration style
  3704. show: cfg.settings.hasHeaders === true && config.hasHeaders !== false,
  3705. popout: cfg.settings.showPopoutIcon && cfg.labels.popout,
  3706. maximise: cfg.settings.showMaximiseIcon && cfg.labels.maximise,
  3707. close: cfg.settings.showCloseIcon && cfg.labels.close,
  3708. minimise: cfg.labels.minimise,
  3709. };
  3710. if( cfg.header ) // load simplified version of header configuration (https://github.com/deepstreamIO/golden-layout/pull/245)
  3711. lm.utils.copy( this._header, cfg.header );
  3712. if( config.header ) // load from stack
  3713. lm.utils.copy( this._header, config.header );
  3714. if( config.content && config.content[ 0 ] && config.content[ 0 ].header ) // load from component if stack omitted
  3715. lm.utils.copy( this._header, config.content[ 0 ].header );
  3716. this._dropZones = {};
  3717. this._dropSegment = null;
  3718. this._contentAreaDimensions = null;
  3719. this._dropIndex = null;
  3720. this.isStack = true;
  3721. this.childElementContainer = $( '<div class="lm_items"></div>' );
  3722. this.header = new lm.controls.Header( layoutManager, this );
  3723. this.element.append( this.header.element );
  3724. this.element.append( this.childElementContainer );
  3725. this._setupHeaderPosition();
  3726. this._$validateClosability();
  3727. };
  3728. lm.utils.extend( lm.items.Stack, lm.items.AbstractContentItem );
  3729. lm.utils.copy( lm.items.Stack.prototype, {
  3730. setSize: function() {
  3731. var i,
  3732. headerSize = this._header.show ? this.layoutManager.config.dimensions.headerHeight : 0,
  3733. contentWidth = this.element.width() - (this._sided ? headerSize : 0),
  3734. contentHeight = this.element.height() - (!this._sided ? headerSize : 0);
  3735. this.childElementContainer.width( contentWidth );
  3736. this.childElementContainer.height( contentHeight );
  3737. for( i = 0; i < this.contentItems.length; i++ ) {
  3738. this.contentItems[ i ].element.width( contentWidth ).height( contentHeight );
  3739. }
  3740. this.emit( 'resize' );
  3741. this.emitBubblingEvent( 'stateChanged' );
  3742. },
  3743. _$init: function() {
  3744. var i, initialItem;
  3745. if( this.isInitialised === true ) return;
  3746. lm.items.AbstractContentItem.prototype._$init.call( this );
  3747. for( i = 0; i < this.contentItems.length; i++ ) {
  3748. this.header.createTab( this.contentItems[ i ] );
  3749. this.contentItems[ i ]._$hide();
  3750. }
  3751. if( this.contentItems.length > 0 ) {
  3752. initialItem = this.contentItems[ this.config.activeItemIndex || 0 ];
  3753. if( !initialItem ) {
  3754. throw new Error( 'Configured activeItemIndex out of bounds' );
  3755. }
  3756. this.setActiveContentItem( initialItem );
  3757. }
  3758. },
  3759. setActiveContentItem: function( contentItem ) {
  3760. if( lm.utils.indexOf( contentItem, this.contentItems ) === -1 ) {
  3761. throw new Error( 'contentItem is not a child of this stack' );
  3762. }
  3763. if( this._activeContentItem !== null ) {
  3764. this._activeContentItem._$hide();
  3765. }
  3766. this._activeContentItem = contentItem;
  3767. this.header.setActiveContentItem( contentItem );
  3768. contentItem._$show();
  3769. this.emit( 'activeContentItemChanged', contentItem );
  3770. this.emitBubblingEvent( 'stateChanged' );
  3771. },
  3772. getActiveContentItem: function() {
  3773. return this.header.activeContentItem;
  3774. },
  3775. addChild: function( contentItem, index ) {
  3776. contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
  3777. lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index );
  3778. this.childElementContainer.append( contentItem.element );
  3779. this.header.createTab( contentItem, index );
  3780. this.setActiveContentItem( contentItem );
  3781. this.callDownwards( 'setSize' );
  3782. this._$validateClosability();
  3783. this.emitBubblingEvent( 'stateChanged' );
  3784. },
  3785. removeChild: function( contentItem, keepChild ) {
  3786. var index = lm.utils.indexOf( contentItem, this.contentItems );
  3787. lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild );
  3788. this.header.removeTab( contentItem );
  3789. if( this.contentItems.length > 0 ) {
  3790. this.setActiveContentItem( this.contentItems[ Math.max( index - 1, 0 ) ] );
  3791. } else {
  3792. this._activeContentItem = null;
  3793. }
  3794. this._$validateClosability();
  3795. this.emitBubblingEvent( 'stateChanged' );
  3796. },
  3797. /**
  3798. * Validates that the stack is still closable or not. If a stack is able
  3799. * to close, but has a non closable component added to it, the stack is no
  3800. * longer closable until all components are closable.
  3801. *
  3802. * @returns {void}
  3803. */
  3804. _$validateClosability: function() {
  3805. var contentItem,
  3806. isClosable,
  3807. len,
  3808. i;
  3809. isClosable = this.header._isClosable();
  3810. for( i = 0, len = this.contentItems.length; i < len; i++ ) {
  3811. if( !isClosable ) {
  3812. break;
  3813. }
  3814. isClosable = this.contentItems[ i ].config.isClosable;
  3815. }
  3816. this.header._$setClosable( isClosable );
  3817. },
  3818. _$destroy: function() {
  3819. lm.items.AbstractContentItem.prototype._$destroy.call( this );
  3820. this.header._$destroy();
  3821. },
  3822. /**
  3823. * Ok, this one is going to be the tricky one: The user has dropped {contentItem} onto this stack.
  3824. *
  3825. * It was dropped on either the stacks header or the top, right, bottom or left bit of the content area
  3826. * (which one of those is stored in this._dropSegment). Now, if the user has dropped on the header the case
  3827. * is relatively clear: We add the item to the existing stack... job done (might be good to have
  3828. * tab reordering at some point, but lets not sweat it right now)
  3829. *
  3830. * If the item was dropped on the content part things are a bit more complicated. If it was dropped on either the
  3831. * top or bottom region we need to create a new column and place the items accordingly.
  3832. * Unless, of course if the stack is already within a column... in which case we want
  3833. * to add the newly created item to the existing column...
  3834. * either prepend or append it, depending on wether its top or bottom.
  3835. *
  3836. * Same thing for rows and left / right drop segments... so in total there are 9 things that can potentially happen
  3837. * (left, top, right, bottom) * is child of the right parent (row, column) + header drop
  3838. *
  3839. * @param {lm.item} contentItem
  3840. *
  3841. * @returns {void}
  3842. */
  3843. _$onDrop: function( contentItem ) {
  3844. /*
  3845. * The item was dropped on the header area. Just add it as a child of this stack and
  3846. * get the hell out of this logic
  3847. */
  3848. if( this._dropSegment === 'header' ) {
  3849. this._resetHeaderDropZone();
  3850. this.addChild( contentItem, this._dropIndex );
  3851. return;
  3852. }
  3853. /*
  3854. * The stack is empty. Let's just add the element.
  3855. */
  3856. if( this._dropSegment === 'body' ) {
  3857. this.addChild( contentItem );
  3858. return;
  3859. }
  3860. /*
  3861. * The item was dropped on the top-, left-, bottom- or right- part of the content. Let's
  3862. * aggregate some conditions to make the if statements later on more readable
  3863. */
  3864. var isVertical = this._dropSegment === 'top' || this._dropSegment === 'bottom',
  3865. isHorizontal = this._dropSegment === 'left' || this._dropSegment === 'right',
  3866. insertBefore = this._dropSegment === 'top' || this._dropSegment === 'left',
  3867. hasCorrectParent = ( isVertical && this.parent.isColumn ) || ( isHorizontal && this.parent.isRow ),
  3868. type = isVertical ? 'column' : 'row',
  3869. dimension = isVertical ? 'height' : 'width',
  3870. index,
  3871. stack,
  3872. rowOrColumn;
  3873. /*
  3874. * The content item can be either a component or a stack. If it is a component, wrap it into a stack
  3875. */
  3876. if( contentItem.isComponent ) {
  3877. stack = this.layoutManager.createContentItem( {
  3878. type: 'stack',
  3879. header: contentItem.config.header || {}
  3880. }, this );
  3881. stack._$init();
  3882. stack.addChild( contentItem );
  3883. contentItem = stack;
  3884. }
  3885. /*
  3886. * If the item is dropped on top or bottom of a column or left and right of a row, it's already
  3887. * layd out in the correct way. Just add it as a child
  3888. */
  3889. if( hasCorrectParent ) {
  3890. index = lm.utils.indexOf( this, this.parent.contentItems );
  3891. this.parent.addChild( contentItem, insertBefore ? index : index + 1, true );
  3892. this.config[ dimension ] *= 0.5;
  3893. contentItem.config[ dimension ] = this.config[ dimension ];
  3894. this.parent.callDownwards( 'setSize' );
  3895. /*
  3896. * This handles items that are dropped on top or bottom of a row or left / right of a column. We need
  3897. * to create the appropriate contentItem for them to live in
  3898. */
  3899. } else {
  3900. type = isVertical ? 'column' : 'row';
  3901. rowOrColumn = this.layoutManager.createContentItem( { type: type }, this );
  3902. this.parent.replaceChild( this, rowOrColumn );
  3903. rowOrColumn.addChild( contentItem, insertBefore ? 0 : undefined, true );
  3904. rowOrColumn.addChild( this, insertBefore ? undefined : 0, true );
  3905. this.config[ dimension ] = 50;
  3906. contentItem.config[ dimension ] = 50;
  3907. rowOrColumn.callDownwards( 'setSize' );
  3908. }
  3909. },
  3910. /**
  3911. * If the user hovers above the header part of the stack, indicate drop positions for tabs.
  3912. * otherwise indicate which segment of the body the dragged item would be dropped on
  3913. *
  3914. * @param {Int} x Absolute Screen X
  3915. * @param {Int} y Absolute Screen Y
  3916. *
  3917. * @returns {void}
  3918. */
  3919. _$highlightDropZone: function( x, y ) {
  3920. var segment, area;
  3921. for( segment in this._contentAreaDimensions ) {
  3922. area = this._contentAreaDimensions[ segment ].hoverArea;
  3923. if( area.x1 < x && area.x2 > x && area.y1 < y && area.y2 > y ) {
  3924. if( segment === 'header' ) {
  3925. this._dropSegment = 'header';
  3926. this._highlightHeaderDropZone( this._sided ? y : x );
  3927. } else {
  3928. this._resetHeaderDropZone();
  3929. this._highlightBodyDropZone( segment );
  3930. }
  3931. return;
  3932. }
  3933. }
  3934. },
  3935. _$getArea: function() {
  3936. if( this.element.is( ':visible' ) === false ) {
  3937. return null;
  3938. }
  3939. var getArea = lm.items.AbstractContentItem.prototype._$getArea,
  3940. headerArea = getArea.call( this, this.header.element ),
  3941. contentArea = getArea.call( this, this.childElementContainer ),
  3942. contentWidth = contentArea.x2 - contentArea.x1,
  3943. contentHeight = contentArea.y2 - contentArea.y1;
  3944. this._contentAreaDimensions = {
  3945. header: {
  3946. hoverArea: {
  3947. x1: headerArea.x1,
  3948. y1: headerArea.y1,
  3949. x2: headerArea.x2,
  3950. y2: headerArea.y2
  3951. },
  3952. highlightArea: {
  3953. x1: headerArea.x1,
  3954. y1: headerArea.y1,
  3955. x2: headerArea.x2,
  3956. y2: headerArea.y2
  3957. }
  3958. }
  3959. };
  3960. /**
  3961. * If this Stack is a parent to rows, columns or other stacks only its
  3962. * header is a valid dropzone.
  3963. */
  3964. if( this._activeContentItem && this._activeContentItem.isComponent === false ) {
  3965. return headerArea;
  3966. }
  3967. /**
  3968. * Highlight the entire body if the stack is empty
  3969. */
  3970. if( this.contentItems.length === 0 ) {
  3971. this._contentAreaDimensions.body = {
  3972. hoverArea: {
  3973. x1: contentArea.x1,
  3974. y1: contentArea.y1,
  3975. x2: contentArea.x2,
  3976. y2: contentArea.y2
  3977. },
  3978. highlightArea: {
  3979. x1: contentArea.x1,
  3980. y1: contentArea.y1,
  3981. x2: contentArea.x2,
  3982. y2: contentArea.y2
  3983. }
  3984. };
  3985. return getArea.call( this, this.element );
  3986. }
  3987. this._contentAreaDimensions.left = {
  3988. hoverArea: {
  3989. x1: contentArea.x1,
  3990. y1: contentArea.y1,
  3991. x2: contentArea.x1 + contentWidth * 0.25,
  3992. y2: contentArea.y2
  3993. },
  3994. highlightArea: {
  3995. x1: contentArea.x1,
  3996. y1: contentArea.y1,
  3997. x2: contentArea.x1 + contentWidth * 0.5,
  3998. y2: contentArea.y2
  3999. }
  4000. };
  4001. this._contentAreaDimensions.top = {
  4002. hoverArea: {
  4003. x1: contentArea.x1 + contentWidth * 0.25,
  4004. y1: contentArea.y1,
  4005. x2: contentArea.x1 + contentWidth * 0.75,
  4006. y2: contentArea.y1 + contentHeight * 0.5
  4007. },
  4008. highlightArea: {
  4009. x1: contentArea.x1,
  4010. y1: contentArea.y1,
  4011. x2: contentArea.x2,
  4012. y2: contentArea.y1 + contentHeight * 0.5
  4013. }
  4014. };
  4015. this._contentAreaDimensions.right = {
  4016. hoverArea: {
  4017. x1: contentArea.x1 + contentWidth * 0.75,
  4018. y1: contentArea.y1,
  4019. x2: contentArea.x2,
  4020. y2: contentArea.y2
  4021. },
  4022. highlightArea: {
  4023. x1: contentArea.x1 + contentWidth * 0.5,
  4024. y1: contentArea.y1,
  4025. x2: contentArea.x2,
  4026. y2: contentArea.y2
  4027. }
  4028. };
  4029. this._contentAreaDimensions.bottom = {
  4030. hoverArea: {
  4031. x1: contentArea.x1 + contentWidth * 0.25,
  4032. y1: contentArea.y1 + contentHeight * 0.5,
  4033. x2: contentArea.x1 + contentWidth * 0.75,
  4034. y2: contentArea.y2
  4035. },
  4036. highlightArea: {
  4037. x1: contentArea.x1,
  4038. y1: contentArea.y1 + contentHeight * 0.5,
  4039. x2: contentArea.x2,
  4040. y2: contentArea.y2
  4041. }
  4042. };
  4043. return getArea.call( this, this.element );
  4044. },
  4045. _highlightHeaderDropZone: function( x ) {
  4046. var i,
  4047. tabElement,
  4048. tabsLength = this.header.tabs.length,
  4049. isAboveTab = false,
  4050. tabTop,
  4051. tabLeft,
  4052. offset,
  4053. placeHolderLeft,
  4054. headerOffset,
  4055. tabWidth,
  4056. halfX;
  4057. // Empty stack
  4058. if( tabsLength === 0 ) {
  4059. headerOffset = this.header.element.offset();
  4060. this.layoutManager.dropTargetIndicator.highlightArea( {
  4061. x1: headerOffset.left,
  4062. x2: headerOffset.left + 100,
  4063. y1: headerOffset.top + this.header.element.height() - 20,
  4064. y2: headerOffset.top + this.header.element.height()
  4065. } );
  4066. return;
  4067. }
  4068. for( i = 0; i < tabsLength; i++ ) {
  4069. tabElement = this.header.tabs[ i ].element;
  4070. offset = tabElement.offset();
  4071. if( this._sided ) {
  4072. tabLeft = offset.top;
  4073. tabTop = offset.left;
  4074. tabWidth = tabElement.height();
  4075. } else {
  4076. tabLeft = offset.left;
  4077. tabTop = offset.top;
  4078. tabWidth = tabElement.width();
  4079. }
  4080. if( x > tabLeft && x < tabLeft + tabWidth ) {
  4081. isAboveTab = true;
  4082. break;
  4083. }
  4084. }
  4085. if( isAboveTab === false && x < tabLeft ) {
  4086. return;
  4087. }
  4088. halfX = tabLeft + tabWidth / 2;
  4089. if( x < halfX ) {
  4090. this._dropIndex = i;
  4091. tabElement.before( this.layoutManager.tabDropPlaceholder );
  4092. } else {
  4093. this._dropIndex = Math.min( i + 1, tabsLength );
  4094. tabElement.after( this.layoutManager.tabDropPlaceholder );
  4095. }
  4096. if( this._sided ) {
  4097. placeHolderTop = this.layoutManager.tabDropPlaceholder.offset().top;
  4098. this.layoutManager.dropTargetIndicator.highlightArea( {
  4099. x1: tabTop,
  4100. x2: tabTop + tabElement.innerHeight(),
  4101. y1: placeHolderTop,
  4102. y2: placeHolderTop + this.layoutManager.tabDropPlaceholder.width()
  4103. } );
  4104. return;
  4105. }
  4106. placeHolderLeft = this.layoutManager.tabDropPlaceholder.offset().left;
  4107. this.layoutManager.dropTargetIndicator.highlightArea( {
  4108. x1: placeHolderLeft,
  4109. x2: placeHolderLeft + this.layoutManager.tabDropPlaceholder.width(),
  4110. y1: tabTop,
  4111. y2: tabTop + tabElement.innerHeight()
  4112. } );
  4113. },
  4114. _resetHeaderDropZone: function() {
  4115. this.layoutManager.tabDropPlaceholder.remove();
  4116. },
  4117. _setupHeaderPosition: function() {
  4118. var side = [ 'right', 'left', 'bottom' ].indexOf( this._header.show ) >= 0 && this._header.show;
  4119. this.header.element.toggle( !!this._header.show );
  4120. this._side = side;
  4121. this._sided = [ 'right', 'left' ].indexOf( this._side ) >= 0;
  4122. this.element.removeClass( 'lm_left lm_right lm_bottom' );
  4123. if( this._side )
  4124. this.element.addClass( 'lm_' + this._side );
  4125. if( this.element.find( '.lm_header' ).length && this.childElementContainer ) {
  4126. var headerPosition = [ 'right', 'bottom' ].indexOf( this._side ) >= 0 ? 'before' : 'after';
  4127. this.header.element[ headerPosition ]( this.childElementContainer );
  4128. this.callDownwards( 'setSize' );
  4129. }
  4130. },
  4131. _highlightBodyDropZone: function( segment ) {
  4132. var highlightArea = this._contentAreaDimensions[ segment ].highlightArea;
  4133. this.layoutManager.dropTargetIndicator.highlightArea( highlightArea );
  4134. this._dropSegment = segment;
  4135. }
  4136. } );
  4137. lm.utils.BubblingEvent = function( name, origin ) {
  4138. this.name = name;
  4139. this.origin = origin;
  4140. this.isPropagationStopped = false;
  4141. };
  4142. lm.utils.BubblingEvent.prototype.stopPropagation = function() {
  4143. this.isPropagationStopped = true;
  4144. };
  4145. /**
  4146. * Minifies and unminifies configs by replacing frequent keys
  4147. * and values with one letter substitutes
  4148. *
  4149. * @constructor
  4150. */
  4151. lm.utils.ConfigMinifier = function() {
  4152. this._keys = [
  4153. 'settings',
  4154. 'hasHeaders',
  4155. 'constrainDragToContainer',
  4156. 'selectionEnabled',
  4157. 'dimensions',
  4158. 'borderWidth',
  4159. 'minItemHeight',
  4160. 'minItemWidth',
  4161. 'headerHeight',
  4162. 'dragProxyWidth',
  4163. 'dragProxyHeight',
  4164. 'labels',
  4165. 'close',
  4166. 'maximise',
  4167. 'minimise',
  4168. 'popout',
  4169. 'content',
  4170. 'componentName',
  4171. 'componentState',
  4172. 'id',
  4173. 'width',
  4174. 'type',
  4175. 'height',
  4176. 'isClosable',
  4177. 'title',
  4178. 'popoutWholeStack',
  4179. 'openPopouts',
  4180. 'parentId',
  4181. 'activeItemIndex',
  4182. 'reorderEnabled'
  4183. //Maximum 36 entries, do not cross this line!
  4184. ];
  4185. this._values = [
  4186. true,
  4187. false,
  4188. 'row',
  4189. 'column',
  4190. 'stack',
  4191. 'component',
  4192. 'close',
  4193. 'maximise',
  4194. 'minimise',
  4195. 'open in new window'
  4196. ];
  4197. };
  4198. lm.utils.copy( lm.utils.ConfigMinifier.prototype, {
  4199. /**
  4200. * Takes a GoldenLayout configuration object and
  4201. * replaces its keys and values recursively with
  4202. * one letter counterparts
  4203. *
  4204. * @param {Object} config A GoldenLayout config object
  4205. *
  4206. * @returns {Object} minified config
  4207. */
  4208. minifyConfig: function( config ) {
  4209. var min = {};
  4210. this._nextLevel( config, min, '_min' );
  4211. return min;
  4212. },
  4213. /**
  4214. * Takes a configuration Object that was previously minified
  4215. * using minifyConfig and returns its original version
  4216. *
  4217. * @param {Object} minifiedConfig
  4218. *
  4219. * @returns {Object} the original configuration
  4220. */
  4221. unminifyConfig: function( minifiedConfig ) {
  4222. var orig = {};
  4223. this._nextLevel( minifiedConfig, orig, '_max' );
  4224. return orig;
  4225. },
  4226. /**
  4227. * Recursive function, called for every level of the config structure
  4228. *
  4229. * @param {Array|Object} orig
  4230. * @param {Array|Object} min
  4231. * @param {String} translationFn
  4232. *
  4233. * @returns {void}
  4234. */
  4235. _nextLevel: function( from, to, translationFn ) {
  4236. var key, minKey;
  4237. for( key in from ) {
  4238. /**
  4239. * For in returns array indices as keys, so let's cast them to numbers
  4240. */
  4241. if( from instanceof Array ) key = parseInt( key, 10 );
  4242. /**
  4243. * In case something has extended Object prototypes
  4244. */
  4245. if( !from.hasOwnProperty( key ) ) continue;
  4246. /**
  4247. * Translate the key to a one letter substitute
  4248. */
  4249. minKey = this[ translationFn ]( key, this._keys );
  4250. /**
  4251. * For Arrays and Objects, create a new Array/Object
  4252. * on the minified object and recurse into it
  4253. */
  4254. if( typeof from[ key ] === 'object' ) {
  4255. to[ minKey ] = from[ key ] instanceof Array ? [] : {};
  4256. this._nextLevel( from[ key ], to[ minKey ], translationFn );
  4257. /**
  4258. * For primitive values (Strings, Numbers, Boolean etc.)
  4259. * minify the value
  4260. */
  4261. } else {
  4262. to[ minKey ] = this[ translationFn ]( from[ key ], this._values );
  4263. }
  4264. }
  4265. },
  4266. /**
  4267. * Minifies value based on a dictionary
  4268. *
  4269. * @param {String|Boolean} value
  4270. * @param {Array<String|Boolean>} dictionary
  4271. *
  4272. * @returns {String} The minified version
  4273. */
  4274. _min: function( value, dictionary ) {
  4275. /**
  4276. * If a value actually is a single character, prefix it
  4277. * with ___ to avoid mistaking it for a minification code
  4278. */
  4279. if( typeof value === 'string' && value.length === 1 ) {
  4280. return '___' + value;
  4281. }
  4282. var index = lm.utils.indexOf( value, dictionary );
  4283. /**
  4284. * value not found in the dictionary, return it unmodified
  4285. */
  4286. if( index === -1 ) {
  4287. return value;
  4288. /**
  4289. * value found in dictionary, return its base36 counterpart
  4290. */
  4291. } else {
  4292. return index.toString( 36 );
  4293. }
  4294. },
  4295. _max: function( value, dictionary ) {
  4296. /**
  4297. * value is a single character. Assume that it's a translation
  4298. * and return the original value from the dictionary
  4299. */
  4300. if( typeof value === 'string' && value.length === 1 ) {
  4301. return dictionary[ parseInt( value, 36 ) ];
  4302. }
  4303. /**
  4304. * value originally was a single character and was prefixed with ___
  4305. * to avoid mistaking it for a translation. Remove the prefix
  4306. * and return the original character
  4307. */
  4308. if( typeof value === 'string' && value.substr( 0, 3 ) === '___' ) {
  4309. return value[ 3 ];
  4310. }
  4311. /**
  4312. * value was not minified
  4313. */
  4314. return value;
  4315. }
  4316. } );
  4317. /**
  4318. * An EventEmitter singleton that propagates events
  4319. * across multiple windows. This is a little bit trickier since
  4320. * windows are allowed to open childWindows in their own right
  4321. *
  4322. * This means that we deal with a tree of windows. Hence the rules for event propagation are:
  4323. *
  4324. * - Propagate events from this layout to both parents and children
  4325. * - Propagate events from parent to this and children
  4326. * - Propagate events from children to the other children (but not the emitting one) and the parent
  4327. *
  4328. * @constructor
  4329. *
  4330. * @param {lm.LayoutManager} layoutManager
  4331. */
  4332. lm.utils.EventHub = function( layoutManager ) {
  4333. lm.utils.EventEmitter.call( this );
  4334. this._layoutManager = layoutManager;
  4335. this._dontPropagateToParent = null;
  4336. this._childEventSource = null;
  4337. this.on( lm.utils.EventEmitter.ALL_EVENT, lm.utils.fnBind( this._onEventFromThis, this ) );
  4338. this._boundOnEventFromChild = lm.utils.fnBind( this._onEventFromChild, this );
  4339. $( window ).on( 'gl_child_event', this._boundOnEventFromChild );
  4340. };
  4341. /**
  4342. * Called on every event emitted on this eventHub, regardles of origin.
  4343. *
  4344. * @private
  4345. *
  4346. * @param {Mixed}
  4347. *
  4348. * @returns {void}
  4349. */
  4350. lm.utils.EventHub.prototype._onEventFromThis = function() {
  4351. var args = Array.prototype.slice.call( arguments );
  4352. if( this._layoutManager.isSubWindow && args[ 0 ] !== this._dontPropagateToParent ) {
  4353. this._propagateToParent( args );
  4354. }
  4355. this._propagateToChildren( args );
  4356. //Reset
  4357. this._dontPropagateToParent = null;
  4358. this._childEventSource = null;
  4359. };
  4360. /**
  4361. * Called by the parent layout.
  4362. *
  4363. * @param {Array} args Event name + arguments
  4364. *
  4365. * @returns {void}
  4366. */
  4367. lm.utils.EventHub.prototype._$onEventFromParent = function( args ) {
  4368. this._dontPropagateToParent = args[ 0 ];
  4369. this.emit.apply( this, args );
  4370. };
  4371. /**
  4372. * Callback for child events raised on the window
  4373. *
  4374. * @param {DOMEvent} event
  4375. * @private
  4376. *
  4377. * @returns {void}
  4378. */
  4379. lm.utils.EventHub.prototype._onEventFromChild = function( event ) {
  4380. this._childEventSource = event.originalEvent.__gl;
  4381. this.emit.apply( this, event.originalEvent.__glArgs );
  4382. };
  4383. /**
  4384. * Propagates the event to the parent by emitting
  4385. * it on the parent's DOM window
  4386. *
  4387. * @param {Array} args Event name + arguments
  4388. * @private
  4389. *
  4390. * @returns {void}
  4391. */
  4392. lm.utils.EventHub.prototype._propagateToParent = function( args ) {
  4393. var event,
  4394. eventName = 'gl_child_event';
  4395. if( document.createEvent ) {
  4396. event = window.opener.document.createEvent( 'HTMLEvents' );
  4397. event.initEvent( eventName, true, true );
  4398. } else {
  4399. event = window.opener.document.createEventObject();
  4400. event.eventType = eventName;
  4401. }
  4402. event.eventName = eventName;
  4403. event.__glArgs = args;
  4404. event.__gl = this._layoutManager;
  4405. if( document.createEvent ) {
  4406. window.opener.dispatchEvent( event );
  4407. } else {
  4408. window.opener.fireEvent( 'on' + event.eventType, event );
  4409. }
  4410. };
  4411. /**
  4412. * Propagate events to children
  4413. *
  4414. * @param {Array} args Event name + arguments
  4415. * @private
  4416. *
  4417. * @returns {void}
  4418. */
  4419. lm.utils.EventHub.prototype._propagateToChildren = function( args ) {
  4420. var childGl, i;
  4421. for( i = 0; i < this._layoutManager.openPopouts.length; i++ ) {
  4422. childGl = this._layoutManager.openPopouts[ i ].getGlInstance();
  4423. if( childGl && childGl !== this._childEventSource ) {
  4424. childGl.eventHub._$onEventFromParent( args );
  4425. }
  4426. }
  4427. };
  4428. /**
  4429. * Destroys the EventHub
  4430. *
  4431. * @public
  4432. * @returns {void}
  4433. */
  4434. lm.utils.EventHub.prototype.destroy = function() {
  4435. $( window ).off( 'gl_child_event', this._boundOnEventFromChild );
  4436. };
  4437. /**
  4438. * A specialised GoldenLayout component that binds GoldenLayout container
  4439. * lifecycle events to react components
  4440. *
  4441. * @constructor
  4442. *
  4443. * @param {lm.container.ItemContainer} container
  4444. * @param {Object} state state is not required for react components
  4445. */
  4446. lm.utils.ReactComponentHandler = function( container, state ) {
  4447. this._reactComponent = null;
  4448. this._originalComponentWillUpdate = null;
  4449. this._container = container;
  4450. this._initialState = state;
  4451. this._reactClass = this._getReactClass();
  4452. this._container.on( 'open', this._render, this );
  4453. this._container.on( 'destroy', this._destroy, this );
  4454. };
  4455. lm.utils.copy( lm.utils.ReactComponentHandler.prototype, {
  4456. /**
  4457. * Creates the react class and component and hydrates it with
  4458. * the initial state - if one is present
  4459. *
  4460. * By default, react's getInitialState will be used
  4461. *
  4462. * @private
  4463. * @returns {void}
  4464. */
  4465. _render: function() {
  4466. this._reactComponent = ReactDOM.render( this._getReactComponent(), this._container.getElement()[ 0 ] );
  4467. this._originalComponentWillUpdate = this._reactComponent.componentWillUpdate || function() {
  4468. };
  4469. this._reactComponent.componentWillUpdate = this._onUpdate.bind( this );
  4470. if( this._container.getState() ) {
  4471. this._reactComponent.setState( this._container.getState() );
  4472. }
  4473. },
  4474. /**
  4475. * Removes the component from the DOM and thus invokes React's unmount lifecycle
  4476. *
  4477. * @private
  4478. * @returns {void}
  4479. */
  4480. _destroy: function() {
  4481. ReactDOM.unmountComponentAtNode( this._container.getElement()[ 0 ] );
  4482. this._container.off( 'open', this._render, this );
  4483. this._container.off( 'destroy', this._destroy, this );
  4484. },
  4485. /**
  4486. * Hooks into React's state management and applies the componentstate
  4487. * to GoldenLayout
  4488. *
  4489. * @private
  4490. * @returns {void}
  4491. */
  4492. _onUpdate: function( nextProps, nextState ) {
  4493. this._container.setState( nextState );
  4494. this._originalComponentWillUpdate.call( this._reactComponent, nextProps, nextState );
  4495. },
  4496. /**
  4497. * Retrieves the react class from GoldenLayout's registry
  4498. *
  4499. * @private
  4500. * @returns {React.Class}
  4501. */
  4502. _getReactClass: function() {
  4503. var componentName = this._container._config.component;
  4504. var reactClass;
  4505. if( !componentName ) {
  4506. throw new Error( 'No react component name. type: react-component needs a field `component`' );
  4507. }
  4508. reactClass = this._container.layoutManager.getComponent( componentName );
  4509. if( !reactClass ) {
  4510. throw new Error( 'React component "' + componentName + '" not found. ' +
  4511. 'Please register all components with GoldenLayout using `registerComponent(name, component)`' );
  4512. }
  4513. return reactClass;
  4514. },
  4515. /**
  4516. * Copies and extends the properties array and returns the React element
  4517. *
  4518. * @private
  4519. * @returns {React.Element}
  4520. */
  4521. _getReactComponent: function() {
  4522. var defaultProps = {
  4523. glEventHub: this._container.layoutManager.eventHub,
  4524. glContainer: this._container,
  4525. };
  4526. var props = $.extend( defaultProps, this._container._config.props );
  4527. return React.createElement( this._reactClass, props );
  4528. }
  4529. } );})(window.$);