goldenlayout.js 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250
  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. constrainDragToHeader: true,
  1314. reorderEnabled: true,
  1315. selectionEnabled: false,
  1316. popoutWholeStack: false,
  1317. blockedPopoutsThrowError: true,
  1318. closePopoutsOnUnload: true,
  1319. showPopoutIcon: true,
  1320. showMaximiseIcon: true,
  1321. showCloseIcon: true,
  1322. responsiveMode: 'onload' // Can be onload, always, or none.
  1323. },
  1324. dimensions: {
  1325. borderWidth: 5,
  1326. minItemHeight: 10,
  1327. minItemWidth: 10,
  1328. headerHeight: 20,
  1329. dragProxyWidth: 300,
  1330. dragProxyHeight: 200
  1331. },
  1332. labels: {
  1333. close: 'close',
  1334. maximise: 'maximise',
  1335. minimise: 'minimise',
  1336. popout: 'open in new window',
  1337. popin: 'pop in',
  1338. tabDropdown: 'additional tabs'
  1339. }
  1340. };
  1341. lm.container.ItemContainer = function( config, parent, layoutManager ) {
  1342. lm.utils.EventEmitter.call( this );
  1343. this.width = null;
  1344. this.height = null;
  1345. this.title = config.componentName;
  1346. this.parent = parent;
  1347. this.layoutManager = layoutManager;
  1348. this.isHidden = false;
  1349. this._config = config;
  1350. this._element = $( [
  1351. '<div class="lm_item_container">',
  1352. '<div class="lm_content"></div>',
  1353. '</div>'
  1354. ].join( '' ) );
  1355. this._contentElement = this._element.find( '.lm_content' );
  1356. };
  1357. lm.utils.copy( lm.container.ItemContainer.prototype, {
  1358. /**
  1359. * Get the inner DOM element the container's content
  1360. * is intended to live in
  1361. *
  1362. * @returns {DOM element}
  1363. */
  1364. getElement: function() {
  1365. return this._contentElement;
  1366. },
  1367. /**
  1368. * Hide the container. Notifies the containers content first
  1369. * and then hides the DOM node. If the container is already hidden
  1370. * this should have no effect
  1371. *
  1372. * @returns {void}
  1373. */
  1374. hide: function() {
  1375. this.emit( 'hide' );
  1376. this.isHidden = true;
  1377. this._element.hide();
  1378. },
  1379. /**
  1380. * Shows a previously hidden container. Notifies the
  1381. * containers content first and then shows the DOM element.
  1382. * If the container is already visible this has no effect.
  1383. *
  1384. * @returns {void}
  1385. */
  1386. show: function() {
  1387. this.emit( 'show' );
  1388. this.isHidden = false;
  1389. this._element.show();
  1390. // call shown only if the container has a valid size
  1391. if( this.height != 0 || this.width != 0 ) {
  1392. this.emit( 'shown' );
  1393. }
  1394. },
  1395. /**
  1396. * Set the size from within the container. Traverses up
  1397. * the item tree until it finds a row or column element
  1398. * and resizes its items accordingly.
  1399. *
  1400. * If this container isn't a descendant of a row or column
  1401. * it returns false
  1402. * @todo Rework!!!
  1403. * @param {Number} width The new width in pixel
  1404. * @param {Number} height The new height in pixel
  1405. *
  1406. * @returns {Boolean} resizeSuccesful
  1407. */
  1408. setSize: function( width, height ) {
  1409. var rowOrColumn = this.parent,
  1410. rowOrColumnChild = this,
  1411. totalPixel,
  1412. percentage,
  1413. direction,
  1414. newSize,
  1415. delta,
  1416. i;
  1417. while( !rowOrColumn.isColumn && !rowOrColumn.isRow ) {
  1418. rowOrColumnChild = rowOrColumn;
  1419. rowOrColumn = rowOrColumn.parent;
  1420. /**
  1421. * No row or column has been found
  1422. */
  1423. if( rowOrColumn.isRoot ) {
  1424. return false;
  1425. }
  1426. }
  1427. direction = rowOrColumn.isColumn ? "height" : "width";
  1428. newSize = direction === "height" ? height : width;
  1429. totalPixel = this[ direction ] * ( 1 / ( rowOrColumnChild.config[ direction ] / 100 ) );
  1430. percentage = ( newSize / totalPixel ) * 100;
  1431. delta = ( rowOrColumnChild.config[ direction ] - percentage ) / (rowOrColumn.contentItems.length - 1);
  1432. for( i = 0; i < rowOrColumn.contentItems.length; i++ ) {
  1433. if( rowOrColumn.contentItems[ i ] === rowOrColumnChild ) {
  1434. rowOrColumn.contentItems[ i ].config[ direction ] = percentage;
  1435. } else {
  1436. rowOrColumn.contentItems[ i ].config[ direction ] += delta;
  1437. }
  1438. }
  1439. rowOrColumn.callDownwards( 'setSize' );
  1440. return true;
  1441. },
  1442. /**
  1443. * Closes the container if it is closable. Can be called by
  1444. * both the component within at as well as the contentItem containing
  1445. * it. Emits a close event before the container itself is closed.
  1446. *
  1447. * @returns {void}
  1448. */
  1449. close: function() {
  1450. if( this._config.isClosable ) {
  1451. this.emit( 'close' );
  1452. this.parent.close();
  1453. }
  1454. },
  1455. /**
  1456. * Returns the current state object
  1457. *
  1458. * @returns {Object} state
  1459. */
  1460. getState: function() {
  1461. return this._config.componentState;
  1462. },
  1463. /**
  1464. * Merges the provided state into the current one
  1465. *
  1466. * @param {Object} state
  1467. *
  1468. * @returns {void}
  1469. */
  1470. extendState: function( state ) {
  1471. this.setState( $.extend( true, this.getState(), state ) );
  1472. },
  1473. /**
  1474. * Notifies the layout manager of a stateupdate
  1475. *
  1476. * @param {serialisable} state
  1477. */
  1478. setState: function( state ) {
  1479. this._config.componentState = state;
  1480. this.parent.emitBubblingEvent( 'stateChanged' );
  1481. },
  1482. /**
  1483. * Set's the components title
  1484. *
  1485. * @param {String} title
  1486. */
  1487. setTitle: function( title ) {
  1488. this.parent.setTitle( title );
  1489. },
  1490. /**
  1491. * Set's the containers size. Called by the container's component.
  1492. * To set the size programmatically from within the container please
  1493. * use the public setSize method
  1494. *
  1495. * @param {[Int]} width in px
  1496. * @param {[Int]} height in px
  1497. *
  1498. * @returns {void}
  1499. */
  1500. _$setSize: function( width, height ) {
  1501. if( width !== this.width || height !== this.height ) {
  1502. this.width = width;
  1503. this.height = height;
  1504. this._contentElement.width( this.width ).height( this.height );
  1505. this.emit( 'resize' );
  1506. }
  1507. }
  1508. } );
  1509. /**
  1510. * Pops a content item out into a new browser window.
  1511. * This is achieved by
  1512. *
  1513. * - Creating a new configuration with the content item as root element
  1514. * - Serializing and minifying the configuration
  1515. * - Opening the current window's URL with the configuration as a GET parameter
  1516. * - GoldenLayout when opened in the new window will look for the GET parameter
  1517. * and use it instead of the provided configuration
  1518. *
  1519. * @param {Object} config GoldenLayout item config
  1520. * @param {Object} dimensions A map with width, height, top and left
  1521. * @param {String} parentId The id of the element the item will be appended to on popIn
  1522. * @param {Number} indexInParent The position of this element within its parent
  1523. * @param {lm.LayoutManager} layoutManager
  1524. */
  1525. lm.controls.BrowserPopout = function( config, dimensions, parentId, indexInParent, layoutManager ) {
  1526. lm.utils.EventEmitter.call( this );
  1527. this.isInitialised = false;
  1528. this._config = config;
  1529. this._dimensions = dimensions;
  1530. this._parentId = parentId;
  1531. this._indexInParent = indexInParent;
  1532. this._layoutManager = layoutManager;
  1533. this._popoutWindow = null;
  1534. this._id = null;
  1535. this._createWindow();
  1536. };
  1537. lm.utils.copy( lm.controls.BrowserPopout.prototype, {
  1538. toConfig: function() {
  1539. if( this.isInitialised === false ) {
  1540. throw new Error( 'Can\'t create config, layout not yet initialised' );
  1541. return;
  1542. }
  1543. return {
  1544. dimensions: {
  1545. width: this.getGlInstance().width,
  1546. height: this.getGlInstance().height,
  1547. left: this._popoutWindow.screenX || this._popoutWindow.screenLeft,
  1548. top: this._popoutWindow.screenY || this._popoutWindow.screenTop
  1549. },
  1550. content: this.getGlInstance().toConfig().content,
  1551. parentId: this._parentId,
  1552. indexInParent: this._indexInParent
  1553. };
  1554. },
  1555. getGlInstance: function() {
  1556. return this._popoutWindow.__glInstance;
  1557. },
  1558. getWindow: function() {
  1559. return this._popoutWindow;
  1560. },
  1561. close: function() {
  1562. if( this.getGlInstance() ) {
  1563. this.getGlInstance()._$closeWindow();
  1564. } else {
  1565. try {
  1566. this.getWindow().close();
  1567. } catch( e ) {
  1568. }
  1569. }
  1570. },
  1571. /**
  1572. * Returns the popped out item to its original position. If the original
  1573. * parent isn't available anymore it falls back to the layout's topmost element
  1574. */
  1575. popIn: function() {
  1576. var childConfig,
  1577. parentItem,
  1578. index = this._indexInParent;
  1579. if( this._parentId ) {
  1580. /*
  1581. * The $.extend call seems a bit pointless, but it's crucial to
  1582. * copy the config returned by this.getGlInstance().toConfig()
  1583. * onto a new object. Internet Explorer keeps the references
  1584. * to objects on the child window, resulting in the following error
  1585. * once the child window is closed:
  1586. *
  1587. * The callee (server [not server application]) is not available and disappeared
  1588. */
  1589. childConfig = $.extend( true, {}, this.getGlInstance().toConfig() ).content[ 0 ];
  1590. parentItem = this._layoutManager.root.getItemsById( this._parentId )[ 0 ];
  1591. /*
  1592. * Fallback if parentItem is not available. Either add it to the topmost
  1593. * item or make it the topmost item if the layout is empty
  1594. */
  1595. if( !parentItem ) {
  1596. if( this._layoutManager.root.contentItems.length > 0 ) {
  1597. parentItem = this._layoutManager.root.contentItems[ 0 ];
  1598. } else {
  1599. parentItem = this._layoutManager.root;
  1600. }
  1601. index = 0;
  1602. }
  1603. }
  1604. parentItem.addChild( childConfig, this._indexInParent );
  1605. this.close();
  1606. },
  1607. /**
  1608. * Creates the URL and window parameter
  1609. * and opens a new window
  1610. *
  1611. * @private
  1612. *
  1613. * @returns {void}
  1614. */
  1615. _createWindow: function() {
  1616. var checkReadyInterval,
  1617. url = this._createUrl(),
  1618. /**
  1619. * Bogus title to prevent re-usage of existing window with the
  1620. * same title. The actual title will be set by the new window's
  1621. * GoldenLayout instance if it detects that it is in subWindowMode
  1622. */
  1623. title = Math.floor( Math.random() * 1000000 ).toString( 36 ),
  1624. /**
  1625. * The options as used in the window.open string
  1626. */
  1627. options = this._serializeWindowOptions( {
  1628. width: this._dimensions.width,
  1629. height: this._dimensions.height,
  1630. innerWidth: this._dimensions.width,
  1631. innerHeight: this._dimensions.height,
  1632. menubar: 'no',
  1633. toolbar: 'no',
  1634. location: 'no',
  1635. personalbar: 'no',
  1636. resizable: 'yes',
  1637. scrollbars: 'no',
  1638. status: 'no'
  1639. } );
  1640. this._popoutWindow = window.open( url, title, options );
  1641. if( !this._popoutWindow ) {
  1642. if( this._layoutManager.config.settings.blockedPopoutsThrowError === true ) {
  1643. var error = new Error( 'Popout blocked' );
  1644. error.type = 'popoutBlocked';
  1645. throw error;
  1646. } else {
  1647. return;
  1648. }
  1649. }
  1650. $( this._popoutWindow )
  1651. .on( 'load', lm.utils.fnBind( this._positionWindow, this ) )
  1652. .on( 'unload beforeunload', lm.utils.fnBind( this._onClose, this ) );
  1653. /**
  1654. * Polling the childwindow to find out if GoldenLayout has been initialised
  1655. * doesn't seem optimal, but the alternatives - adding a callback to the parent
  1656. * window or raising an event on the window object - both would introduce knowledge
  1657. * about the parent to the child window which we'd rather avoid
  1658. */
  1659. checkReadyInterval = setInterval( lm.utils.fnBind( function() {
  1660. if( this._popoutWindow.__glInstance && this._popoutWindow.__glInstance.isInitialised ) {
  1661. this._onInitialised();
  1662. clearInterval( checkReadyInterval );
  1663. }
  1664. }, this ), 10 );
  1665. },
  1666. /**
  1667. * Serialises a map of key:values to a window options string
  1668. *
  1669. * @param {Object} windowOptions
  1670. *
  1671. * @returns {String} serialised window options
  1672. */
  1673. _serializeWindowOptions: function( windowOptions ) {
  1674. var windowOptionsString = [], key;
  1675. for( key in windowOptions ) {
  1676. windowOptionsString.push( key + '=' + windowOptions[ key ] );
  1677. }
  1678. return windowOptionsString.join( ',' );
  1679. },
  1680. /**
  1681. * Creates the URL for the new window, including the
  1682. * config GET parameter
  1683. *
  1684. * @returns {String} URL
  1685. */
  1686. _createUrl: function() {
  1687. var config = { content: this._config },
  1688. storageKey = 'gl-window-config-' + lm.utils.getUniqueId(),
  1689. urlParts;
  1690. config = ( new lm.utils.ConfigMinifier() ).minifyConfig( config );
  1691. try {
  1692. localStorage.setItem( storageKey, JSON.stringify( config ) );
  1693. } catch( e ) {
  1694. throw new Error( 'Error while writing to localStorage ' + e.toString() );
  1695. }
  1696. urlParts = document.location.href.split( '?' );
  1697. // URL doesn't contain GET-parameters
  1698. if( urlParts.length === 1 ) {
  1699. return urlParts[ 0 ] + '?gl-window=' + storageKey;
  1700. // URL contains GET-parameters
  1701. } else {
  1702. return document.location.href + '&gl-window=' + storageKey;
  1703. }
  1704. },
  1705. /**
  1706. * Move the newly created window roughly to
  1707. * where the component used to be.
  1708. *
  1709. * @private
  1710. *
  1711. * @returns {void}
  1712. */
  1713. _positionWindow: function() {
  1714. this._popoutWindow.moveTo( this._dimensions.left, this._dimensions.top );
  1715. this._popoutWindow.focus();
  1716. },
  1717. /**
  1718. * Callback when the new window is opened and the GoldenLayout instance
  1719. * within it is initialised
  1720. *
  1721. * @returns {void}
  1722. */
  1723. _onInitialised: function() {
  1724. this.isInitialised = true;
  1725. this.getGlInstance().on( 'popIn', this.popIn, this );
  1726. this.emit( 'initialised' );
  1727. },
  1728. /**
  1729. * Invoked 50ms after the window unload event
  1730. *
  1731. * @private
  1732. *
  1733. * @returns {void}
  1734. */
  1735. _onClose: function() {
  1736. setTimeout( lm.utils.fnBind( this.emit, this, [ 'closed' ] ), 50 );
  1737. }
  1738. } );
  1739. /**
  1740. * This class creates a temporary container
  1741. * for the component whilst it is being dragged
  1742. * and handles drag events
  1743. *
  1744. * @constructor
  1745. * @private
  1746. *
  1747. * @param {Number} x The initial x position
  1748. * @param {Number} y The initial y position
  1749. * @param {lm.utils.DragListener} dragListener
  1750. * @param {lm.LayoutManager} layoutManager
  1751. * @param {lm.item.AbstractContentItem} contentItem
  1752. * @param {lm.item.AbstractContentItem} originalParent
  1753. */
  1754. lm.controls.DragProxy = function( x, y, dragListener, layoutManager, contentItem, originalParent ) {
  1755. lm.utils.EventEmitter.call( this );
  1756. this._dragListener = dragListener;
  1757. this._layoutManager = layoutManager;
  1758. this._contentItem = contentItem;
  1759. this._originalParent = originalParent;
  1760. this._area = null;
  1761. this._lastValidArea = null;
  1762. this._dragListener.on( 'drag', this._onDrag, this );
  1763. this._dragListener.on( 'dragStop', this._onDrop, this );
  1764. this.element = $( lm.controls.DragProxy._template );
  1765. if( originalParent && originalParent._side ) {
  1766. this._sided = originalParent._sided;
  1767. this.element.addClass( 'lm_' + originalParent._side );
  1768. if( [ 'right', 'bottom' ].indexOf( originalParent._side ) >= 0 )
  1769. this.element.find( '.lm_content' ).after( this.element.find( '.lm_header' ) );
  1770. }
  1771. this.element.css( { left: x, top: y } );
  1772. this.element.find( '.lm_tab' ).attr( 'title', lm.utils.stripTags( this._contentItem.config.title ) );
  1773. this.element.find( '.lm_title' ).html( this._contentItem.config.title );
  1774. this.childElementContainer = this.element.find( '.lm_content' );
  1775. this.childElementContainer.append( contentItem.element );
  1776. this._updateTree();
  1777. this._layoutManager._$calculateItemAreas();
  1778. this._setDimensions();
  1779. $( document.body ).append( this.element );
  1780. var offset = this._layoutManager.container.offset();
  1781. this._minX = offset.left;
  1782. this._minY = offset.top;
  1783. this._maxX = this._layoutManager.container.width() + this._minX;
  1784. this._maxY = this._layoutManager.container.height() + this._minY;
  1785. this._width = this.element.width();
  1786. this._height = this.element.height();
  1787. this._setDropPosition( x, y );
  1788. };
  1789. lm.controls.DragProxy._template = '<div class="lm_dragProxy">' +
  1790. '<div class="lm_header">' +
  1791. '<ul class="lm_tabs">' +
  1792. '<li class="lm_tab lm_active"><i class="lm_left"></i>' +
  1793. '<span class="lm_title"></span>' +
  1794. '<i class="lm_right"></i></li>' +
  1795. '</ul>' +
  1796. '</div>' +
  1797. '<div class="lm_content"></div>' +
  1798. '</div>';
  1799. lm.utils.copy( lm.controls.DragProxy.prototype, {
  1800. /**
  1801. * Callback on every mouseMove event during a drag. Determines if the drag is
  1802. * still within the valid drag area and calls the layoutManager to highlight the
  1803. * current drop area
  1804. *
  1805. * @param {Number} offsetX The difference from the original x position in px
  1806. * @param {Number} offsetY The difference from the original y position in px
  1807. * @param {jQuery DOM event} event
  1808. *
  1809. * @private
  1810. *
  1811. * @returns {void}
  1812. */
  1813. _onDrag: function( offsetX, offsetY, event ) {
  1814. event = event.originalEvent && event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event;
  1815. var x = event.pageX,
  1816. y = event.pageY,
  1817. isWithinContainer = x > this._minX && x < this._maxX && y > this._minY && y < this._maxY,
  1818. isWithinHeader = x > this._area.x1 && x < this._area.x2 && y > this._area.y1 && y < this._area.y2;
  1819. if( !isWithinContainer && this._layoutManager.config.settings.constrainDragToContainer === true ) {
  1820. return;
  1821. }
  1822. if( !isWithinHeader && this._layoutManager.config.settings.constrainDragToHeader === true ) {
  1823. return;
  1824. }
  1825. this._setDropPosition( x, y );
  1826. },
  1827. /**
  1828. * Sets the target position, highlighting the appropriate area
  1829. *
  1830. * @param {Number} x The x position in px
  1831. * @param {Number} y The y position in px
  1832. *
  1833. * @private
  1834. *
  1835. * @returns {void}
  1836. */
  1837. _setDropPosition: function( x, y ) {
  1838. this.element.css( { left: x, top: y } );
  1839. this._area = this._layoutManager._$getArea( x, y );
  1840. if( this._area !== null ) {
  1841. this._lastValidArea = this._area;
  1842. this._area.contentItem._$highlightDropZone( x, y, this._area );
  1843. }
  1844. },
  1845. /**
  1846. * Callback when the drag has finished. Determines the drop area
  1847. * and adds the child to it
  1848. *
  1849. * @private
  1850. *
  1851. * @returns {void}
  1852. */
  1853. _onDrop: function() {
  1854. this._layoutManager.dropTargetIndicator.hide();
  1855. /*
  1856. * Valid drop area found
  1857. */
  1858. if( this._area !== null ) {
  1859. this._area.contentItem._$onDrop( this._contentItem, this._area );
  1860. /**
  1861. * No valid drop area available at present, but one has been found before.
  1862. * Use it
  1863. */
  1864. } else if( this._lastValidArea !== null ) {
  1865. this._lastValidArea.contentItem._$onDrop( this._contentItem, this._lastValidArea );
  1866. /**
  1867. * No valid drop area found during the duration of the drag. Return
  1868. * content item to its original position if a original parent is provided.
  1869. * (Which is not the case if the drag had been initiated by createDragSource)
  1870. */
  1871. } else if( this._originalParent ) {
  1872. this._originalParent.addChild( this._contentItem );
  1873. /**
  1874. * The drag didn't ultimately end up with adding the content item to
  1875. * any container. In order to ensure clean up happens, destroy the
  1876. * content item.
  1877. */
  1878. } else {
  1879. this._contentItem._$destroy();
  1880. }
  1881. this.element.remove();
  1882. this._layoutManager.emit( 'itemDropped', this._contentItem );
  1883. },
  1884. /**
  1885. * Removes the item from its original position within the tree
  1886. *
  1887. * @private
  1888. *
  1889. * @returns {void}
  1890. */
  1891. _updateTree: function() {
  1892. /**
  1893. * parent is null if the drag had been initiated by a external drag source
  1894. */
  1895. if( this._contentItem.parent ) {
  1896. this._contentItem.parent.removeChild( this._contentItem, true );
  1897. }
  1898. this._contentItem._$setParent( this );
  1899. },
  1900. /**
  1901. * Updates the Drag Proxie's dimensions
  1902. *
  1903. * @private
  1904. *
  1905. * @returns {void}
  1906. */
  1907. _setDimensions: function() {
  1908. var dimensions = this._layoutManager.config.dimensions,
  1909. width = dimensions.dragProxyWidth,
  1910. height = dimensions.dragProxyHeight;
  1911. this.element.width( width );
  1912. this.element.height( height );
  1913. width -= ( this._sided ? dimensions.headerHeight : 0 );
  1914. height -= ( !this._sided ? dimensions.headerHeight : 0 );
  1915. this.childElementContainer.width( width );
  1916. this.childElementContainer.height( height );
  1917. this._contentItem.element.width( width );
  1918. this._contentItem.element.height( height );
  1919. this._contentItem.callDownwards( '_$show' );
  1920. this._contentItem.callDownwards( 'setSize' );
  1921. }
  1922. } );
  1923. /**
  1924. * Allows for any DOM item to create a component on drag
  1925. * start tobe dragged into the Layout
  1926. *
  1927. * @param {jQuery element} element
  1928. * @param {Object} itemConfig the configuration for the contentItem that will be created
  1929. * @param {LayoutManager} layoutManager
  1930. *
  1931. * @constructor
  1932. */
  1933. lm.controls.DragSource = function( element, itemConfig, layoutManager ) {
  1934. this._element = element;
  1935. this._itemConfig = itemConfig;
  1936. this._layoutManager = layoutManager;
  1937. this._dragListener = null;
  1938. this._createDragListener();
  1939. };
  1940. lm.utils.copy( lm.controls.DragSource.prototype, {
  1941. /**
  1942. * Called initially and after every drag
  1943. *
  1944. * @returns {void}
  1945. */
  1946. _createDragListener: function() {
  1947. if( this._dragListener !== null ) {
  1948. this._dragListener.destroy();
  1949. }
  1950. this._dragListener = new lm.utils.DragListener( this._element );
  1951. this._dragListener.on( 'dragStart', this._onDragStart, this );
  1952. this._dragListener.on( 'dragStop', this._createDragListener, this );
  1953. },
  1954. /**
  1955. * Callback for the DragListener's dragStart event
  1956. *
  1957. * @param {int} x the x position of the mouse on dragStart
  1958. * @param {int} y the x position of the mouse on dragStart
  1959. *
  1960. * @returns {void}
  1961. */
  1962. _onDragStart: function( x, y ) {
  1963. var itemConfig = this._itemConfig;
  1964. if( lm.utils.isFunction( itemConfig ) ) {
  1965. itemConfig = itemConfig();
  1966. }
  1967. var contentItem = this._layoutManager._$normalizeContentItem( $.extend( true, {}, itemConfig ) ),
  1968. dragProxy = new lm.controls.DragProxy( x, y, this._dragListener, this._layoutManager, contentItem, null );
  1969. this._layoutManager.transitionIndicator.transitionElements( this._element, dragProxy.element );
  1970. }
  1971. } );
  1972. lm.controls.DropTargetIndicator = function() {
  1973. this.element = $( lm.controls.DropTargetIndicator._template );
  1974. $( document.body ).append( this.element );
  1975. };
  1976. lm.controls.DropTargetIndicator._template = '<div class="lm_dropTargetIndicator"><div class="lm_inner"></div></div>';
  1977. lm.utils.copy( lm.controls.DropTargetIndicator.prototype, {
  1978. destroy: function() {
  1979. this.element.remove();
  1980. },
  1981. highlight: function( x1, y1, x2, y2 ) {
  1982. this.highlightArea( { x1: x1, y1: y1, x2: x2, y2: y2 } );
  1983. },
  1984. highlightArea: function( area ) {
  1985. this.element.css( {
  1986. left: area.x1,
  1987. top: area.y1,
  1988. width: area.x2 - area.x1,
  1989. height: area.y2 - area.y1
  1990. } ).show();
  1991. },
  1992. hide: function() {
  1993. this.element.hide();
  1994. }
  1995. } );
  1996. /**
  1997. * This class represents a header above a Stack ContentItem.
  1998. *
  1999. * @param {lm.LayoutManager} layoutManager
  2000. * @param {lm.item.AbstractContentItem} parent
  2001. */
  2002. lm.controls.Header = function( layoutManager, parent ) {
  2003. lm.utils.EventEmitter.call( this );
  2004. this.layoutManager = layoutManager;
  2005. this.element = $( lm.controls.Header._template );
  2006. if( this.layoutManager.config.settings.selectionEnabled === true ) {
  2007. this.element.addClass( 'lm_selectable' );
  2008. this.element.on( 'click touchstart', lm.utils.fnBind( this._onHeaderClick, this ) );
  2009. }
  2010. this.tabsContainer = this.element.find( '.lm_tabs' );
  2011. this.tabDropdownContainer = this.element.find( '.lm_tabdropdown_list' );
  2012. this.tabDropdownContainer.hide();
  2013. this.controlsContainer = this.element.find( '.lm_controls' );
  2014. this.parent = parent;
  2015. this.parent.on( 'resize', this._updateTabSizes, this );
  2016. this.tabs = [];
  2017. this.activeContentItem = null;
  2018. this.closeButton = null;
  2019. this.tabDropdownButton = null;
  2020. //$( document ).mouseup( lm.utils.fnBind( this._hideAdditionalTabsDropdown, this ) );
  2021. this._lastVisibleTabIndex = -1;
  2022. this._tabControlOffset = 10;
  2023. this._createControls();
  2024. };
  2025. lm.controls.Header._template = [
  2026. '<div class="lm_header">',
  2027. '<ul class="lm_tabs"></ul>',
  2028. '<ul class="lm_controls"></ul>',
  2029. '<ul class="lm_tabdropdown_list"></ul>',
  2030. '</div>'
  2031. ].join( '' );
  2032. lm.utils.copy( lm.controls.Header.prototype, {
  2033. /**
  2034. * Creates a new tab and associates it with a contentItem
  2035. *
  2036. * @param {lm.item.AbstractContentItem} contentItem
  2037. * @param {Integer} index The position of the tab
  2038. *
  2039. * @returns {void}
  2040. */
  2041. createTab: function( contentItem, index ) {
  2042. var tab, i;
  2043. //If there's already a tab relating to the
  2044. //content item, don't do anything
  2045. for( i = 0; i < this.tabs.length; i++ ) {
  2046. if( this.tabs[ i ].contentItem === contentItem ) {
  2047. return;
  2048. }
  2049. }
  2050. tab = new lm.controls.Tab( this, contentItem );
  2051. if( this.tabs.length === 0 ) {
  2052. this.tabs.push( tab );
  2053. this.tabsContainer.append( tab.element );
  2054. return;
  2055. }
  2056. if( index === undefined ) {
  2057. index = this.tabs.length;
  2058. }
  2059. if( index > 0 ) {
  2060. this.tabs[ index - 1 ].element.after( tab.element );
  2061. } else {
  2062. this.tabs[ 0 ].element.before( tab.element );
  2063. }
  2064. this.tabs.splice( index, 0, tab );
  2065. this._updateTabSizes();
  2066. },
  2067. /**
  2068. * Finds a tab based on the contentItem its associated with and removes it.
  2069. *
  2070. * @param {lm.item.AbstractContentItem} contentItem
  2071. *
  2072. * @returns {void}
  2073. */
  2074. removeTab: function( contentItem ) {
  2075. for( var i = 0; i < this.tabs.length; i++ ) {
  2076. if( this.tabs[ i ].contentItem === contentItem ) {
  2077. this.tabs[ i ]._$destroy();
  2078. this.tabs.splice( i, 1 );
  2079. return;
  2080. }
  2081. }
  2082. throw new Error( 'contentItem is not controlled by this header' );
  2083. },
  2084. /**
  2085. * The programmatical equivalent of clicking a Tab.
  2086. *
  2087. * @param {lm.item.AbstractContentItem} contentItem
  2088. */
  2089. setActiveContentItem: function( contentItem ) {
  2090. var i, j, isActive, activeTab;
  2091. for( i = 0; i < this.tabs.length; i++ ) {
  2092. isActive = this.tabs[ i ].contentItem === contentItem;
  2093. this.tabs[ i ].setActive( isActive );
  2094. if( isActive === true ) {
  2095. this.activeContentItem = contentItem;
  2096. this.parent.config.activeItemIndex = i;
  2097. }
  2098. }
  2099. /**
  2100. * If the tab selected was in the dropdown, move everything down one to make way for this one to be the first.
  2101. * This will make sure the most used tabs stay visible.
  2102. */
  2103. if( this._lastVisibleTabIndex !== -1 && this.parent.config.activeItemIndex > this._lastVisibleTabIndex ) {
  2104. activeTab = this.tabs[ this.parent.config.activeItemIndex ];
  2105. for( j = this.parent.config.activeItemIndex; j > 0; j-- ) {
  2106. this.tabs[ j ] = this.tabs[ j - 1 ];
  2107. }
  2108. this.tabs[ 0 ] = activeTab;
  2109. this.parent.config.activeItemIndex = 0;
  2110. }
  2111. this._updateTabSizes();
  2112. this.parent.emitBubblingEvent( 'stateChanged' );
  2113. },
  2114. /**
  2115. * Programmatically operate with header position.
  2116. *
  2117. * @param {string} position one of ('top','left','right','bottom') to set or empty to get it.
  2118. *
  2119. * @returns {string} previous header position
  2120. */
  2121. position: function( position ) {
  2122. var previous = this.parent._header.show;
  2123. if( previous && !this.parent._side )
  2124. previous = 'top';
  2125. if( position !== undefined && this.parent._header.show != position ) {
  2126. this.parent._header.show = position;
  2127. this.parent._setupHeaderPosition();
  2128. }
  2129. return previous;
  2130. },
  2131. /**
  2132. * Programmatically set closability.
  2133. *
  2134. * @package private
  2135. * @param {Boolean} isClosable Whether to enable/disable closability.
  2136. *
  2137. * @returns {Boolean} Whether the action was successful
  2138. */
  2139. _$setClosable: function( isClosable ) {
  2140. if( this.closeButton && this._isClosable() ) {
  2141. this.closeButton.element[ isClosable ? "show" : "hide" ]();
  2142. return true;
  2143. }
  2144. return false;
  2145. },
  2146. /**
  2147. * Destroys the entire header
  2148. *
  2149. * @package private
  2150. *
  2151. * @returns {void}
  2152. */
  2153. _$destroy: function() {
  2154. this.emit( 'destroy', this );
  2155. for( var i = 0; i < this.tabs.length; i++ ) {
  2156. this.tabs[ i ]._$destroy();
  2157. }
  2158. this.element.remove();
  2159. },
  2160. /**
  2161. * get settings from header
  2162. *
  2163. * @returns {string} when exists
  2164. */
  2165. _getHeaderSetting: function( name ) {
  2166. if( name in this.parent._header )
  2167. return this.parent._header[ name ];
  2168. },
  2169. /**
  2170. * Creates the popout, maximise and close buttons in the header's top right corner
  2171. *
  2172. * @returns {void}
  2173. */
  2174. _createControls: function() {
  2175. var closeStack,
  2176. popout,
  2177. label,
  2178. maximiseLabel,
  2179. minimiseLabel,
  2180. maximise,
  2181. maximiseButton,
  2182. tabDropdownLabel,
  2183. showTabDropdown;
  2184. /**
  2185. * Dropdown to show additional tabs.
  2186. */
  2187. showTabDropdown = lm.utils.fnBind( this._showAdditionalTabsDropdown, this );
  2188. tabDropdownLabel = this.layoutManager.config.labels.tabDropdown;
  2189. this.tabDropdownButton = new lm.controls.HeaderButton( this, tabDropdownLabel, 'lm_tabdropdown', showTabDropdown );
  2190. this.tabDropdownButton.element.hide();
  2191. /**
  2192. * Popout control to launch component in new window.
  2193. */
  2194. if( this._getHeaderSetting( 'popout' ) ) {
  2195. popout = lm.utils.fnBind( this._onPopoutClick, this );
  2196. label = this._getHeaderSetting( 'popout' );
  2197. new lm.controls.HeaderButton( this, label, 'lm_popout', popout );
  2198. }
  2199. /**
  2200. * Maximise control - set the component to the full size of the layout
  2201. */
  2202. if( this._getHeaderSetting( 'maximise' ) ) {
  2203. maximise = lm.utils.fnBind( this.parent.toggleMaximise, this.parent );
  2204. maximiseLabel = this._getHeaderSetting( 'maximise' );
  2205. minimiseLabel = this._getHeaderSetting( 'minimise' );
  2206. maximiseButton = new lm.controls.HeaderButton( this, maximiseLabel, 'lm_maximise', maximise );
  2207. this.parent.on( 'maximised', function() {
  2208. maximiseButton.element.attr( 'title', minimiseLabel );
  2209. } );
  2210. this.parent.on( 'minimised', function() {
  2211. maximiseButton.element.attr( 'title', maximiseLabel );
  2212. } );
  2213. }
  2214. /**
  2215. * Close button
  2216. */
  2217. if( this._isClosable() ) {
  2218. closeStack = lm.utils.fnBind( this.parent.remove, this.parent );
  2219. label = this._getHeaderSetting( 'close' );
  2220. this.closeButton = new lm.controls.HeaderButton( this, label, 'lm_close', closeStack );
  2221. }
  2222. },
  2223. /**
  2224. * Shows drop down for additional tabs when there are too many to display.
  2225. *
  2226. * @returns {void}
  2227. */
  2228. _showAdditionalTabsDropdown: function() {
  2229. this.tabDropdownContainer.show();
  2230. },
  2231. /**
  2232. * Hides drop down for additional tabs when there are too many to display.
  2233. *
  2234. * @returns {void}
  2235. */
  2236. _hideAdditionalTabsDropdown: function( e ) {
  2237. this.tabDropdownContainer.hide();
  2238. },
  2239. /**
  2240. * Checks whether the header is closable based on the parent config and
  2241. * the global config.
  2242. *
  2243. * @returns {Boolean} Whether the header is closable.
  2244. */
  2245. _isClosable: function() {
  2246. return this.parent.config.isClosable && this.layoutManager.config.settings.showCloseIcon;
  2247. },
  2248. _onPopoutClick: function() {
  2249. if( this.layoutManager.config.settings.popoutWholeStack === true ) {
  2250. this.parent.popout();
  2251. } else {
  2252. this.activeContentItem.popout();
  2253. }
  2254. },
  2255. /**
  2256. * Invoked when the header's background is clicked (not it's tabs or controls)
  2257. *
  2258. * @param {jQuery DOM event} event
  2259. *
  2260. * @returns {void}
  2261. */
  2262. _onHeaderClick: function( event ) {
  2263. if( event.target === this.element[ 0 ] ) {
  2264. this.parent.select();
  2265. }
  2266. },
  2267. /**
  2268. * Pushes the tabs to the tab dropdown if the available space is not sufficient
  2269. *
  2270. * @returns {void}
  2271. */
  2272. _updateTabSizes: function() {
  2273. if( this.tabs.length === 0 ) {
  2274. return;
  2275. }
  2276. var size = function( val ) {
  2277. return val ? 'width' : 'height';
  2278. }
  2279. this.element.css( size( !this.parent._sided ), '' );
  2280. this.element[ size( this.parent._sided ) ]( this.layoutManager.config.dimensions.headerHeight );
  2281. var availableWidth = this.element.outerWidth() - this.controlsContainer.outerWidth() - this._tabControlOffset,
  2282. totalTabWidth = 0,
  2283. tabElement,
  2284. i,
  2285. showTabDropdown,
  2286. swapTab,
  2287. tabWidth,
  2288. hasVisibleTab = false;
  2289. if( this.parent._sided )
  2290. availableWidth = this.element.outerHeight() - this.controlsContainer.outerHeight() - this._tabControlOffset;
  2291. this._lastVisibleTabIndex = -1;
  2292. for( i = 0; i < this.tabs.length; i++ ) {
  2293. tabElement = this.tabs[ i ].element;
  2294. /*
  2295. * Retain tab width when hidden so it can be restored.
  2296. */
  2297. tabWidth = tabElement.data( 'lastTabWidth' );
  2298. if( !tabWidth ) {
  2299. tabWidth = tabElement.outerWidth() + parseInt( tabElement.css( 'margin-right' ), 10 );
  2300. }
  2301. totalTabWidth += tabWidth;
  2302. // If the tab won't fit, put it in the dropdown for tabs, making sure there is always at least one tab visible.
  2303. if( totalTabWidth > availableWidth && hasVisibleTab ) {
  2304. tabElement.data( 'lastTabWidth', tabWidth );
  2305. this.tabDropdownContainer.append( tabElement );
  2306. }
  2307. else {
  2308. hasVisibleTab = true;
  2309. this._lastVisibleTabIndex = i;
  2310. tabElement.removeData( 'lastTabWidth' );
  2311. this.tabsContainer.append( tabElement );
  2312. }
  2313. }
  2314. /*
  2315. * Show the tab dropdown icon if not all tabs fit.
  2316. */
  2317. showTabDropdown = totalTabWidth > availableWidth;
  2318. this.tabDropdownButton.element[ showTabDropdown ? 'show' : 'hide' ]();
  2319. }
  2320. } );
  2321. lm.controls.HeaderButton = function( header, label, cssClass, action ) {
  2322. this._header = header;
  2323. this.element = $( '<li class="' + cssClass + '" title="' + label + '"></li>' );
  2324. this._header.on( 'destroy', this._$destroy, this );
  2325. this._action = action;
  2326. this.element.on( 'click touchstart', this._action );
  2327. this._header.controlsContainer.append( this.element );
  2328. };
  2329. lm.utils.copy( lm.controls.HeaderButton.prototype, {
  2330. _$destroy: function() {
  2331. this.element.off();
  2332. this.element.remove();
  2333. }
  2334. } );
  2335. lm.controls.Splitter = function( isVertical, size ) {
  2336. this._isVertical = isVertical;
  2337. this._size = size;
  2338. this.element = this._createElement();
  2339. this._dragListener = new lm.utils.DragListener( this.element );
  2340. };
  2341. lm.utils.copy( lm.controls.Splitter.prototype, {
  2342. on: function( event, callback, context ) {
  2343. this._dragListener.on( event, callback, context );
  2344. },
  2345. _$destroy: function() {
  2346. this.element.remove();
  2347. },
  2348. _createElement: function() {
  2349. var element = $( '<div class="lm_splitter"><div class="lm_drag_handle"></div></div>' );
  2350. element.addClass( 'lm_' + ( this._isVertical ? 'vertical' : 'horizontal' ) );
  2351. element[ this._isVertical ? 'height' : 'width' ]( this._size );
  2352. return element;
  2353. }
  2354. } );
  2355. /**
  2356. * Represents an individual tab within a Stack's header
  2357. *
  2358. * @param {lm.controls.Header} header
  2359. * @param {lm.items.AbstractContentItem} contentItem
  2360. *
  2361. * @constructor
  2362. */
  2363. lm.controls.Tab = function( header, contentItem ) {
  2364. this.header = header;
  2365. this.contentItem = contentItem;
  2366. this.element = $( lm.controls.Tab._template );
  2367. this.titleElement = this.element.find( '.lm_title' );
  2368. this.closeElement = this.element.find( '.lm_close_tab' );
  2369. this.closeElement[ contentItem.config.isClosable ? 'show' : 'hide' ]();
  2370. this.isActive = false;
  2371. this.setTitle( contentItem.config.title );
  2372. this.contentItem.on( 'titleChanged', this.setTitle, this );
  2373. this._layoutManager = this.contentItem.layoutManager;
  2374. if(
  2375. this._layoutManager.config.settings.reorderEnabled === true &&
  2376. contentItem.config.reorderEnabled === true
  2377. ) {
  2378. this._dragListener = new lm.utils.DragListener( this.titleElement );
  2379. this._dragListener.on( 'dragStart', this._onDragStart, this );
  2380. }
  2381. this._onTabClickFn = lm.utils.fnBind( this._onTabClick, this );
  2382. this._onCloseClickFn = lm.utils.fnBind( this._onCloseClick, this );
  2383. this.titleElement.on( 'mousedown touchstart', this._onTabClickFn );
  2384. if( this.contentItem.config.isClosable ) {
  2385. this.closeElement.on( 'click touchstart', this._onCloseClickFn );
  2386. } else {
  2387. this.closeElement.remove();
  2388. }
  2389. this.contentItem.tab = this;
  2390. this.contentItem.emit( 'tab', this );
  2391. this.contentItem.layoutManager.emit( 'tabCreated', this );
  2392. if( this.contentItem.isComponent ) {
  2393. this.contentItem.container.tab = this;
  2394. this.contentItem.container.emit( 'tab', this );
  2395. }
  2396. };
  2397. /**
  2398. * The tab's html template
  2399. *
  2400. * @type {String}
  2401. */
  2402. lm.controls.Tab._template = '<li class="lm_tab"><i class="lm_left"></i>' +
  2403. '<span class="lm_title"></span><div class="lm_close_tab"></div>' +
  2404. '<i class="lm_right"></i></li>';
  2405. lm.utils.copy( lm.controls.Tab.prototype, {
  2406. /**
  2407. * Sets the tab's title to the provided string and sets
  2408. * its title attribute to a pure text representation (without
  2409. * html tags) of the same string.
  2410. *
  2411. * @public
  2412. * @param {String} title can contain html
  2413. */
  2414. setTitle: function( title ) {
  2415. this.element.attr( 'title', lm.utils.stripTags( title ) );
  2416. this.titleElement.html( title );
  2417. },
  2418. /**
  2419. * Sets this tab's active state. To programmatically
  2420. * switch tabs, use header.setActiveContentItem( item ) instead.
  2421. *
  2422. * @public
  2423. * @param {Boolean} isActive
  2424. */
  2425. setActive: function( isActive ) {
  2426. if( isActive === this.isActive ) {
  2427. return;
  2428. }
  2429. this.isActive = isActive;
  2430. if( isActive ) {
  2431. this.element.addClass( 'lm_active' );
  2432. } else {
  2433. this.element.removeClass( 'lm_active' );
  2434. }
  2435. },
  2436. /**
  2437. * Destroys the tab
  2438. *
  2439. * @private
  2440. * @returns {void}
  2441. */
  2442. _$destroy: function() {
  2443. this.titleElement.off( 'mousedown touchstart', this._onTabClickFn );
  2444. this.closeElement.off( 'click touchstart', this._onCloseClickFn );
  2445. if( this._dragListener ) {
  2446. this._dragListener.off( 'dragStart', this._onDragStart );
  2447. this._dragListener = null;
  2448. }
  2449. this.element.remove();
  2450. },
  2451. /**
  2452. * Callback for the DragListener
  2453. *
  2454. * @param {Number} x The tabs absolute x position
  2455. * @param {Number} y The tabs absolute y position
  2456. *
  2457. * @private
  2458. * @returns {void}
  2459. */
  2460. _onDragStart: function( x, y ) {
  2461. if( this.contentItem.parent.isMaximised === true ) {
  2462. this.contentItem.parent.toggleMaximise();
  2463. }
  2464. new lm.controls.DragProxy(
  2465. x,
  2466. y,
  2467. this._dragListener,
  2468. this._layoutManager,
  2469. this.contentItem,
  2470. this.header.parent
  2471. );
  2472. },
  2473. /**
  2474. * Callback when the tab is clicked
  2475. *
  2476. * @param {jQuery DOM event} event
  2477. *
  2478. * @private
  2479. * @returns {void}
  2480. */
  2481. _onTabClick: function( event ) {
  2482. // left mouse button or tap
  2483. if( event.button === 0 || event.type === 'touchstart' ) {
  2484. var activeContentItem = this.header.parent.getActiveContentItem();
  2485. if( this.contentItem !== activeContentItem ) {
  2486. this.header.parent.setActiveContentItem( this.contentItem );
  2487. }
  2488. // middle mouse button
  2489. } else if( event.button === 1 && this.contentItem.config.isClosable ) {
  2490. this._onCloseClick( event );
  2491. }
  2492. },
  2493. onClose : function() { return true; },
  2494. /**
  2495. * Callback when the tab's close button is
  2496. * clicked
  2497. *
  2498. * @param {jQuery DOM event} event
  2499. *
  2500. * @private
  2501. * @returns {void}
  2502. */
  2503. _onCloseClick: function( event ) {
  2504. event.stopPropagation();
  2505. if( !this.onClose() ) return;
  2506. this.header.parent.removeChild( this.contentItem );
  2507. }
  2508. } );
  2509. lm.controls.TransitionIndicator = function() {
  2510. this._element = $( '<div class="lm_transition_indicator"></div>' );
  2511. $( document.body ).append( this._element );
  2512. this._toElement = null;
  2513. this._fromDimensions = null;
  2514. this._totalAnimationDuration = 200;
  2515. this._animationStartTime = null;
  2516. };
  2517. lm.utils.copy( lm.controls.TransitionIndicator.prototype, {
  2518. destroy: function() {
  2519. this._element.remove();
  2520. },
  2521. transitionElements: function( fromElement, toElement ) {
  2522. /**
  2523. * TODO - This is not quite as cool as expected. Review.
  2524. */
  2525. return;
  2526. this._toElement = toElement;
  2527. this._animationStartTime = lm.utils.now();
  2528. this._fromDimensions = this._measure( fromElement );
  2529. this._fromDimensions.opacity = 0.8;
  2530. this._element.show().css( this._fromDimensions );
  2531. lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) );
  2532. },
  2533. _nextAnimationFrame: function() {
  2534. var toDimensions = this._measure( this._toElement ),
  2535. animationProgress = ( lm.utils.now() - this._animationStartTime ) / this._totalAnimationDuration,
  2536. currentFrameStyles = {},
  2537. cssProperty;
  2538. if( animationProgress >= 1 ) {
  2539. this._element.hide();
  2540. return;
  2541. }
  2542. toDimensions.opacity = 0;
  2543. for( cssProperty in this._fromDimensions ) {
  2544. currentFrameStyles[ cssProperty ] = this._fromDimensions[ cssProperty ] +
  2545. ( toDimensions[ cssProperty ] - this._fromDimensions[ cssProperty ] ) *
  2546. animationProgress;
  2547. }
  2548. this._element.css( currentFrameStyles );
  2549. lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) );
  2550. },
  2551. _measure: function( element ) {
  2552. var offset = element.offset();
  2553. return {
  2554. left: offset.left,
  2555. top: offset.top,
  2556. width: element.outerWidth(),
  2557. height: element.outerHeight()
  2558. };
  2559. }
  2560. } );
  2561. lm.errors.ConfigurationError = function( message, node ) {
  2562. Error.call( this );
  2563. this.name = 'Configuration Error';
  2564. this.message = message;
  2565. this.node = node;
  2566. };
  2567. lm.errors.ConfigurationError.prototype = new Error();
  2568. /**
  2569. * This is the baseclass that all content items inherit from.
  2570. * Most methods provide a subset of what the sub-classes do.
  2571. *
  2572. * It also provides a number of functions for tree traversal
  2573. *
  2574. * @param {lm.LayoutManager} layoutManager
  2575. * @param {item node configuration} config
  2576. * @param {lm.item} parent
  2577. *
  2578. * @event stateChanged
  2579. * @event beforeItemDestroyed
  2580. * @event itemDestroyed
  2581. * @event itemCreated
  2582. * @event componentCreated
  2583. * @event rowCreated
  2584. * @event columnCreated
  2585. * @event stackCreated
  2586. *
  2587. * @constructor
  2588. */
  2589. lm.items.AbstractContentItem = function( layoutManager, config, parent ) {
  2590. lm.utils.EventEmitter.call( this );
  2591. this.config = this._extendItemNode( config );
  2592. this.type = config.type;
  2593. this.contentItems = [];
  2594. this.parent = parent;
  2595. this.isInitialised = false;
  2596. this.isMaximised = false;
  2597. this.isRoot = false;
  2598. this.isRow = false;
  2599. this.isColumn = false;
  2600. this.isStack = false;
  2601. this.isComponent = false;
  2602. this.layoutManager = layoutManager;
  2603. this._pendingEventPropagations = {};
  2604. this._throttledEvents = [ 'stateChanged' ];
  2605. this.on( lm.utils.EventEmitter.ALL_EVENT, this._propagateEvent, this );
  2606. if( config.content ) {
  2607. this._createContentItems( config );
  2608. }
  2609. };
  2610. lm.utils.copy( lm.items.AbstractContentItem.prototype, {
  2611. /**
  2612. * Set the size of the component and its children, called recursively
  2613. *
  2614. * @abstract
  2615. * @returns void
  2616. */
  2617. setSize: function() {
  2618. throw new Error( 'Abstract Method' );
  2619. },
  2620. /**
  2621. * Calls a method recursively downwards on the tree
  2622. *
  2623. * @param {String} functionName the name of the function to be called
  2624. * @param {[Array]}functionArguments optional arguments that are passed to every function
  2625. * @param {[bool]} bottomUp Call methods from bottom to top, defaults to false
  2626. * @param {[bool]} skipSelf Don't invoke the method on the class that calls it, defaults to false
  2627. *
  2628. * @returns {void}
  2629. */
  2630. callDownwards: function( functionName, functionArguments, bottomUp, skipSelf ) {
  2631. var i;
  2632. if( bottomUp !== true && skipSelf !== true ) {
  2633. this[ functionName ].apply( this, functionArguments || [] );
  2634. }
  2635. for( i = 0; i < this.contentItems.length; i++ ) {
  2636. this.contentItems[ i ].callDownwards( functionName, functionArguments, bottomUp );
  2637. }
  2638. if( bottomUp === true && skipSelf !== true ) {
  2639. this[ functionName ].apply( this, functionArguments || [] );
  2640. }
  2641. },
  2642. /**
  2643. * Removes a child node (and its children) from the tree
  2644. *
  2645. * @param {lm.items.ContentItem} contentItem
  2646. *
  2647. * @returns {void}
  2648. */
  2649. removeChild: function( contentItem, keepChild ) {
  2650. /*
  2651. * Get the position of the item that's to be removed within all content items this node contains
  2652. */
  2653. var index = lm.utils.indexOf( contentItem, this.contentItems );
  2654. /*
  2655. * Make sure the content item to be removed is actually a child of this item
  2656. */
  2657. if( index === -1 ) {
  2658. throw new Error( 'Can\'t remove child item. Unknown content item' );
  2659. }
  2660. /**
  2661. * Call ._$destroy on the content item. This also calls ._$destroy on all its children
  2662. */
  2663. if( keepChild !== true ) {
  2664. this.contentItems[ index ]._$destroy();
  2665. }
  2666. /**
  2667. * Remove the content item from this nodes array of children
  2668. */
  2669. this.contentItems.splice( index, 1 );
  2670. /**
  2671. * Remove the item from the configuration
  2672. */
  2673. this.config.content.splice( index, 1 );
  2674. /**
  2675. * If this node still contains other content items, adjust their size
  2676. */
  2677. if( this.contentItems.length > 0 ) {
  2678. this.callDownwards( 'setSize' );
  2679. /**
  2680. * If this was the last content item, remove this node as well
  2681. */
  2682. } else if( !(this instanceof lm.items.Root) && this.config.isClosable === true ) {
  2683. this.parent.removeChild( this );
  2684. }
  2685. },
  2686. /**
  2687. * Sets up the tree structure for the newly added child
  2688. * The responsibility for the actual DOM manipulations lies
  2689. * with the concrete item
  2690. *
  2691. * @param {lm.items.AbstractContentItem} contentItem
  2692. * @param {[Int]} index If omitted item will be appended
  2693. */
  2694. addChild: function( contentItem, index ) {
  2695. if( index === undefined ) {
  2696. index = this.contentItems.length;
  2697. }
  2698. this.contentItems.splice( index, 0, contentItem );
  2699. if( this.config.content === undefined ) {
  2700. this.config.content = [];
  2701. }
  2702. this.config.content.splice( index, 0, contentItem.config );
  2703. contentItem.parent = this;
  2704. if( contentItem.parent.isInitialised === true && contentItem.isInitialised === false ) {
  2705. contentItem._$init();
  2706. }
  2707. },
  2708. /**
  2709. * Replaces oldChild with newChild. This used to use jQuery.replaceWith... which for
  2710. * some reason removes all event listeners, so isn't really an option.
  2711. *
  2712. * @param {lm.item.AbstractContentItem} oldChild
  2713. * @param {lm.item.AbstractContentItem} newChild
  2714. *
  2715. * @returns {void}
  2716. */
  2717. replaceChild: function( oldChild, newChild, _$destroyOldChild ) {
  2718. newChild = this.layoutManager._$normalizeContentItem( newChild );
  2719. var index = lm.utils.indexOf( oldChild, this.contentItems ),
  2720. parentNode = oldChild.element[ 0 ].parentNode;
  2721. if( index === -1 ) {
  2722. throw new Error( 'Can\'t replace child. oldChild is not child of this' );
  2723. }
  2724. parentNode.replaceChild( newChild.element[ 0 ], oldChild.element[ 0 ] );
  2725. /*
  2726. * Optionally destroy the old content item
  2727. */
  2728. if( _$destroyOldChild === true ) {
  2729. oldChild.parent = null;
  2730. oldChild._$destroy();
  2731. }
  2732. /*
  2733. * Wire the new contentItem into the tree
  2734. */
  2735. this.contentItems[ index ] = newChild;
  2736. newChild.parent = this;
  2737. /*
  2738. * Update tab reference
  2739. */
  2740. if( this.isStack ) {
  2741. this.header.tabs[ index ].contentItem = newChild;
  2742. }
  2743. //TODO This doesn't update the config... refactor to leave item nodes untouched after creation
  2744. if( newChild.parent.isInitialised === true && newChild.isInitialised === false ) {
  2745. newChild._$init();
  2746. }
  2747. this.callDownwards( 'setSize' );
  2748. },
  2749. /**
  2750. * Convenience method.
  2751. * Shorthand for this.parent.removeChild( this )
  2752. *
  2753. * @returns {void}
  2754. */
  2755. remove: function() {
  2756. this.parent.removeChild( this );
  2757. },
  2758. /**
  2759. * Removes the component from the layout and creates a new
  2760. * browser window with the component and its children inside
  2761. *
  2762. * @returns {lm.controls.BrowserPopout}
  2763. */
  2764. popout: function() {
  2765. var browserPopout = this.layoutManager.createPopout( this );
  2766. this.emitBubblingEvent( 'stateChanged' );
  2767. return browserPopout;
  2768. },
  2769. /**
  2770. * Maximises the Item or minimises it if it is already maximised
  2771. *
  2772. * @returns {void}
  2773. */
  2774. toggleMaximise: function( e ) {
  2775. e && e.preventDefault();
  2776. if( this.isMaximised === true ) {
  2777. this.layoutManager._$minimiseItem( this );
  2778. } else {
  2779. this.layoutManager._$maximiseItem( this );
  2780. }
  2781. this.isMaximised = !this.isMaximised;
  2782. this.emitBubblingEvent( 'stateChanged' );
  2783. },
  2784. /**
  2785. * Selects the item if it is not already selected
  2786. *
  2787. * @returns {void}
  2788. */
  2789. select: function() {
  2790. if( this.layoutManager.selectedItem !== this ) {
  2791. this.layoutManager.selectItem( this, true );
  2792. this.element.addClass( 'lm_selected' );
  2793. }
  2794. },
  2795. /**
  2796. * De-selects the item if it is selected
  2797. *
  2798. * @returns {void}
  2799. */
  2800. deselect: function() {
  2801. if( this.layoutManager.selectedItem === this ) {
  2802. this.layoutManager.selectedItem = null;
  2803. this.element.removeClass( 'lm_selected' );
  2804. }
  2805. },
  2806. /**
  2807. * Set this component's title
  2808. *
  2809. * @public
  2810. * @param {String} title
  2811. *
  2812. * @returns {void}
  2813. */
  2814. setTitle: function( title ) {
  2815. this.config.title = title;
  2816. this.emit( 'titleChanged', title );
  2817. this.emit( 'stateChanged' );
  2818. },
  2819. /**
  2820. * Checks whether a provided id is present
  2821. *
  2822. * @public
  2823. * @param {String} id
  2824. *
  2825. * @returns {Boolean} isPresent
  2826. */
  2827. hasId: function( id ) {
  2828. if( !this.config.id ) {
  2829. return false;
  2830. } else if( typeof this.config.id === 'string' ) {
  2831. return this.config.id === id;
  2832. } else if( this.config.id instanceof Array ) {
  2833. return lm.utils.indexOf( id, this.config.id ) !== -1;
  2834. }
  2835. },
  2836. /**
  2837. * Adds an id. Adds it as a string if the component doesn't
  2838. * have an id yet or creates/uses an array
  2839. *
  2840. * @public
  2841. * @param {String} id
  2842. *
  2843. * @returns {void}
  2844. */
  2845. addId: function( id ) {
  2846. if( this.hasId( id ) ) {
  2847. return;
  2848. }
  2849. if( !this.config.id ) {
  2850. this.config.id = id;
  2851. } else if( typeof this.config.id === 'string' ) {
  2852. this.config.id = [ this.config.id, id ];
  2853. } else if( this.config.id instanceof Array ) {
  2854. this.config.id.push( id );
  2855. }
  2856. },
  2857. /**
  2858. * Removes an existing id. Throws an error
  2859. * if the id is not present
  2860. *
  2861. * @public
  2862. * @param {String} id
  2863. *
  2864. * @returns {void}
  2865. */
  2866. removeId: function( id ) {
  2867. if( !this.hasId( id ) ) {
  2868. throw new Error( 'Id not found' );
  2869. }
  2870. if( typeof this.config.id === 'string' ) {
  2871. delete this.config.id;
  2872. } else if( this.config.id instanceof Array ) {
  2873. var index = lm.utils.indexOf( id, this.config.id );
  2874. this.config.id.splice( index, 1 );
  2875. }
  2876. },
  2877. /****************************************
  2878. * SELECTOR
  2879. ****************************************/
  2880. getItemsByFilter: function( filter ) {
  2881. var result = [],
  2882. next = function( contentItem ) {
  2883. for( var i = 0; i < contentItem.contentItems.length; i++ ) {
  2884. if( filter( contentItem.contentItems[ i ] ) === true ) {
  2885. result.push( contentItem.contentItems[ i ] );
  2886. }
  2887. next( contentItem.contentItems[ i ] );
  2888. }
  2889. };
  2890. next( this );
  2891. return result;
  2892. },
  2893. getItemsById: function( id ) {
  2894. return this.getItemsByFilter( function( item ) {
  2895. if( item.config.id instanceof Array ) {
  2896. return lm.utils.indexOf( id, item.config.id ) !== -1;
  2897. } else {
  2898. return item.config.id === id;
  2899. }
  2900. } );
  2901. },
  2902. getItemsByType: function( type ) {
  2903. return this._$getItemsByProperty( 'type', type );
  2904. },
  2905. getComponentsByName: function( componentName ) {
  2906. var components = this._$getItemsByProperty( 'componentName', componentName ),
  2907. instances = [],
  2908. i;
  2909. for( i = 0; i < components.length; i++ ) {
  2910. instances.push( components[ i ].instance );
  2911. }
  2912. return instances;
  2913. },
  2914. /****************************************
  2915. * PACKAGE PRIVATE
  2916. ****************************************/
  2917. _$getItemsByProperty: function( key, value ) {
  2918. return this.getItemsByFilter( function( item ) {
  2919. return item[ key ] === value;
  2920. } );
  2921. },
  2922. _$setParent: function( parent ) {
  2923. this.parent = parent;
  2924. },
  2925. _$highlightDropZone: function( x, y, area ) {
  2926. this.layoutManager.dropTargetIndicator.highlightArea( area );
  2927. },
  2928. _$onDrop: function( contentItem ) {
  2929. this.addChild( contentItem );
  2930. },
  2931. _$hide: function() {
  2932. this._callOnActiveComponents( 'hide' );
  2933. this.element.hide();
  2934. this.layoutManager.updateSize();
  2935. },
  2936. _$show: function() {
  2937. this._callOnActiveComponents( 'show' );
  2938. this.element.show();
  2939. this.layoutManager.updateSize();
  2940. },
  2941. _callOnActiveComponents: function( methodName ) {
  2942. var stacks = this.getItemsByType( 'stack' ),
  2943. activeContentItem,
  2944. i;
  2945. for( i = 0; i < stacks.length; i++ ) {
  2946. activeContentItem = stacks[ i ].getActiveContentItem();
  2947. if( activeContentItem && activeContentItem.isComponent ) {
  2948. activeContentItem.container[ methodName ]();
  2949. }
  2950. }
  2951. },
  2952. /**
  2953. * Destroys this item ands its children
  2954. *
  2955. * @returns {void}
  2956. */
  2957. _$destroy: function() {
  2958. this.emitBubblingEvent( 'beforeItemDestroyed' );
  2959. this.callDownwards( '_$destroy', [], true, true );
  2960. this.element.remove();
  2961. this.emitBubblingEvent( 'itemDestroyed' );
  2962. },
  2963. /**
  2964. * Returns the area the component currently occupies in the format
  2965. *
  2966. * {
  2967. * x1: int
  2968. * xy: int
  2969. * y1: int
  2970. * y2: int
  2971. * contentItem: contentItem
  2972. * }
  2973. */
  2974. _$getArea: function( element ) {
  2975. element = element || this.element;
  2976. var offset = element.offset(),
  2977. width = element.width(),
  2978. height = element.height();
  2979. return {
  2980. x1: offset.left,
  2981. y1: offset.top,
  2982. x2: offset.left + width,
  2983. y2: offset.top + height,
  2984. surface: width * height,
  2985. contentItem: this
  2986. };
  2987. },
  2988. /**
  2989. * The tree of content items is created in two steps: First all content items are instantiated,
  2990. * then init is called recursively from top to bottem. This is the basic init function,
  2991. * it can be used, extended or overwritten by the content items
  2992. *
  2993. * Its behaviour depends on the content item
  2994. *
  2995. * @package private
  2996. *
  2997. * @returns {void}
  2998. */
  2999. _$init: function() {
  3000. var i;
  3001. this.setSize();
  3002. for( i = 0; i < this.contentItems.length; i++ ) {
  3003. this.childElementContainer.append( this.contentItems[ i ].element );
  3004. }
  3005. this.isInitialised = true;
  3006. this.emitBubblingEvent( 'itemCreated' );
  3007. this.emitBubblingEvent( this.type + 'Created' );
  3008. },
  3009. /**
  3010. * Emit an event that bubbles up the item tree.
  3011. *
  3012. * @param {String} name The name of the event
  3013. *
  3014. * @returns {void}
  3015. */
  3016. emitBubblingEvent: function( name ) {
  3017. var event = new lm.utils.BubblingEvent( name, this );
  3018. this.emit( name, event );
  3019. },
  3020. /**
  3021. * Private method, creates all content items for this node at initialisation time
  3022. * PLEASE NOTE, please see addChild for adding contentItems add runtime
  3023. * @private
  3024. * @param {configuration item node} config
  3025. *
  3026. * @returns {void}
  3027. */
  3028. _createContentItems: function( config ) {
  3029. var oContentItem, i;
  3030. if( !( config.content instanceof Array ) ) {
  3031. throw new lm.errors.ConfigurationError( 'content must be an Array', config );
  3032. }
  3033. for( i = 0; i < config.content.length; i++ ) {
  3034. oContentItem = this.layoutManager.createContentItem( config.content[ i ], this );
  3035. this.contentItems.push( oContentItem );
  3036. }
  3037. },
  3038. /**
  3039. * Extends an item configuration node with default settings
  3040. * @private
  3041. * @param {configuration item node} config
  3042. *
  3043. * @returns {configuration item node} extended config
  3044. */
  3045. _extendItemNode: function( config ) {
  3046. for( var key in lm.config.itemDefaultConfig ) {
  3047. if( config[ key ] === undefined ) {
  3048. config[ key ] = lm.config.itemDefaultConfig[ key ];
  3049. }
  3050. }
  3051. return config;
  3052. },
  3053. /**
  3054. * Called for every event on the item tree. Decides whether the event is a bubbling
  3055. * event and propagates it to its parent
  3056. *
  3057. * @param {String} name the name of the event
  3058. * @param {lm.utils.BubblingEvent} event
  3059. *
  3060. * @returns {void}
  3061. */
  3062. _propagateEvent: function( name, event ) {
  3063. if( event instanceof lm.utils.BubblingEvent &&
  3064. event.isPropagationStopped === false &&
  3065. this.isInitialised === true ) {
  3066. /**
  3067. * In some cases (e.g. if an element is created from a DragSource) it
  3068. * doesn't have a parent and is not below root. If that's the case
  3069. * propagate the bubbling event from the top level of the substree directly
  3070. * to the layoutManager
  3071. */
  3072. if( this.isRoot === false && this.parent ) {
  3073. this.parent.emit.apply( this.parent, Array.prototype.slice.call( arguments, 0 ) );
  3074. } else {
  3075. this._scheduleEventPropagationToLayoutManager( name, event );
  3076. }
  3077. }
  3078. },
  3079. /**
  3080. * All raw events bubble up to the root element. Some events that
  3081. * are propagated to - and emitted by - the layoutManager however are
  3082. * only string-based, batched and sanitized to make them more usable
  3083. *
  3084. * @param {String} name the name of the event
  3085. *
  3086. * @private
  3087. * @returns {void}
  3088. */
  3089. _scheduleEventPropagationToLayoutManager: function( name, event ) {
  3090. if( lm.utils.indexOf( name, this._throttledEvents ) === -1 ) {
  3091. this.layoutManager.emit( name, event.origin );
  3092. } else {
  3093. if( this._pendingEventPropagations[ name ] !== true ) {
  3094. this._pendingEventPropagations[ name ] = true;
  3095. lm.utils.animFrame( lm.utils.fnBind( this._propagateEventToLayoutManager, this, [ name, event ] ) );
  3096. }
  3097. }
  3098. },
  3099. /**
  3100. * Callback for events scheduled by _scheduleEventPropagationToLayoutManager
  3101. *
  3102. * @param {String} name the name of the event
  3103. *
  3104. * @private
  3105. * @returns {void}
  3106. */
  3107. _propagateEventToLayoutManager: function( name, event ) {
  3108. this._pendingEventPropagations[ name ] = false;
  3109. this.layoutManager.emit( name, event );
  3110. }
  3111. } );
  3112. /**
  3113. * @param {[type]} layoutManager [description]
  3114. * @param {[type]} config [description]
  3115. * @param {[type]} parent [description]
  3116. */
  3117. lm.items.Component = function( layoutManager, config, parent ) {
  3118. lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
  3119. var ComponentConstructor = layoutManager.getComponent( this.config.componentName ),
  3120. componentConfig = $.extend( true, {}, this.config.componentState || {} );
  3121. componentConfig.componentName = this.config.componentName;
  3122. this.componentName = this.config.componentName;
  3123. if( this.config.title === '' ) {
  3124. this.config.title = this.config.componentName;
  3125. }
  3126. this.isComponent = true;
  3127. this.container = new lm.container.ItemContainer( this.config, this, layoutManager );
  3128. this.instance = new ComponentConstructor( this.container, componentConfig );
  3129. this.element = this.container._element;
  3130. };
  3131. lm.utils.extend( lm.items.Component, lm.items.AbstractContentItem );
  3132. lm.utils.copy( lm.items.Component.prototype, {
  3133. close: function() {
  3134. this.parent.removeChild( this );
  3135. },
  3136. setSize: function() {
  3137. if( this.element.is( ':visible' ) ) {
  3138. // Do not update size of hidden components to prevent unwanted reflows
  3139. this.container._$setSize( this.element.width(), this.element.height() );
  3140. }
  3141. },
  3142. _$init: function() {
  3143. lm.items.AbstractContentItem.prototype._$init.call( this );
  3144. this.container.emit( 'open' );
  3145. },
  3146. _$hide: function() {
  3147. this.container.hide();
  3148. lm.items.AbstractContentItem.prototype._$hide.call( this );
  3149. },
  3150. _$show: function() {
  3151. this.container.show();
  3152. lm.items.AbstractContentItem.prototype._$show.call( this );
  3153. },
  3154. _$shown: function() {
  3155. this.container.shown();
  3156. lm.items.AbstractContentItem.prototype._$shown.call( this );
  3157. },
  3158. _$destroy: function() {
  3159. this.container.emit( 'destroy', this );
  3160. lm.items.AbstractContentItem.prototype._$destroy.call( this );
  3161. },
  3162. /**
  3163. * Dragging onto a component directly is not an option
  3164. *
  3165. * @returns null
  3166. */
  3167. _$getArea: function() {
  3168. return null;
  3169. }
  3170. } );
  3171. lm.items.Root = function( layoutManager, config, containerElement ) {
  3172. lm.items.AbstractContentItem.call( this, layoutManager, config, null );
  3173. this.isRoot = true;
  3174. this.type = 'root';
  3175. this.element = $( '<div class="lm_goldenlayout lm_item lm_root"></div>' );
  3176. this.childElementContainer = this.element;
  3177. this._containerElement = containerElement;
  3178. this._containerElement.append( this.element );
  3179. };
  3180. lm.utils.extend( lm.items.Root, lm.items.AbstractContentItem );
  3181. lm.utils.copy( lm.items.Root.prototype, {
  3182. addChild: function( contentItem ) {
  3183. if( this.contentItems.length > 0 ) {
  3184. throw new Error( 'Root node can only have a single child' );
  3185. }
  3186. contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
  3187. this.childElementContainer.append( contentItem.element );
  3188. lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem );
  3189. this.callDownwards( 'setSize' );
  3190. this.emitBubblingEvent( 'stateChanged' );
  3191. },
  3192. setSize: function( width, height ) {
  3193. width = (typeof width === 'undefined') ? this._containerElement.width() : width;
  3194. height = (typeof height === 'undefined') ? this._containerElement.height() : height;
  3195. this.element.width( width );
  3196. this.element.height( height );
  3197. /*
  3198. * Root can be empty
  3199. */
  3200. if( this.contentItems[ 0 ] ) {
  3201. this.contentItems[ 0 ].element.width( width );
  3202. this.contentItems[ 0 ].element.height( height );
  3203. }
  3204. },
  3205. _$highlightDropZone: function( x, y, area ) {
  3206. this.layoutManager.tabDropPlaceholder.remove();
  3207. lm.items.AbstractContentItem.prototype._$highlightDropZone.apply( this, arguments );
  3208. },
  3209. _$onDrop: function( contentItem, area ) {
  3210. var stack;
  3211. if( contentItem.isComponent ) {
  3212. stack = this.layoutManager.createContentItem( {
  3213. type: 'stack',
  3214. header: contentItem.config.header || {}
  3215. }, this );
  3216. stack._$init();
  3217. stack.addChild( contentItem );
  3218. contentItem = stack;
  3219. }
  3220. if( !this.contentItems.length ) {
  3221. this.addChild( contentItem );
  3222. } else {
  3223. var type = area.side[ 0 ] == 'x' ? 'row' : 'column';
  3224. var dimension = area.side[ 0 ] == 'x' ? 'width' : 'height';
  3225. var insertBefore = area.side[ 1 ] == '2';
  3226. var column = this.contentItems[ 0 ];
  3227. if( !column instanceof lm.items.RowOrColumn || column.type != type ) {
  3228. var rowOrColumn = this.layoutManager.createContentItem( { type: type }, this );
  3229. this.replaceChild( column, rowOrColumn );
  3230. rowOrColumn.addChild( contentItem, insertBefore ? 0 : undefined, true );
  3231. rowOrColumn.addChild( column, insertBefore ? undefined : 0, true );
  3232. column.config[ dimension ] = 50;
  3233. contentItem.config[ dimension ] = 50;
  3234. rowOrColumn.callDownwards( 'setSize' );
  3235. } else {
  3236. var sibbling = column.contentItems[ insertBefore ? 0 : column.contentItems.length - 1 ]
  3237. column.addChild( contentItem, insertBefore ? 0 : undefined, true );
  3238. sibbling.config[ dimension ] *= 0.5;
  3239. contentItem.config[ dimension ] = sibbling.config[ dimension ];
  3240. column.callDownwards( 'setSize' );
  3241. }
  3242. }
  3243. }
  3244. } );
  3245. lm.items.RowOrColumn = function( isColumn, layoutManager, config, parent ) {
  3246. lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
  3247. this.isRow = !isColumn;
  3248. this.isColumn = isColumn;
  3249. this.element = $( '<div class="lm_item lm_' + ( isColumn ? 'column' : 'row' ) + '"></div>' );
  3250. this.childElementContainer = this.element;
  3251. this._splitterSize = layoutManager.config.dimensions.borderWidth;
  3252. this._isColumn = isColumn;
  3253. this._dimension = isColumn ? 'height' : 'width';
  3254. this._splitter = [];
  3255. this._splitterPosition = null;
  3256. this._splitterMinPosition = null;
  3257. this._splitterMaxPosition = null;
  3258. };
  3259. lm.utils.extend( lm.items.RowOrColumn, lm.items.AbstractContentItem );
  3260. lm.utils.copy( lm.items.RowOrColumn.prototype, {
  3261. /**
  3262. * Add a new contentItem to the Row or Column
  3263. *
  3264. * @param {lm.item.AbstractContentItem} contentItem
  3265. * @param {[int]} index The position of the new item within the Row or Column.
  3266. * If no index is provided the item will be added to the end
  3267. * @param {[bool]} _$suspendResize If true the items won't be resized. This will leave the item in
  3268. * an inconsistent state and is only intended to be used if multiple
  3269. * children need to be added in one go and resize is called afterwards
  3270. *
  3271. * @returns {void}
  3272. */
  3273. addChild: function( contentItem, index, _$suspendResize ) {
  3274. var newItemSize, itemSize, i, splitterElement;
  3275. contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
  3276. if( index === undefined ) {
  3277. index = this.contentItems.length;
  3278. }
  3279. if( this.contentItems.length > 0 ) {
  3280. splitterElement = this._createSplitter( Math.max( 0, index - 1 ) ).element;
  3281. if( index > 0 ) {
  3282. this.contentItems[ index - 1 ].element.after( splitterElement );
  3283. splitterElement.after( contentItem.element );
  3284. } else {
  3285. this.contentItems[ 0 ].element.before( splitterElement );
  3286. splitterElement.before( contentItem.element );
  3287. }
  3288. } else {
  3289. this.childElementContainer.append( contentItem.element );
  3290. }
  3291. lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index );
  3292. newItemSize = ( 1 / this.contentItems.length ) * 100;
  3293. if( _$suspendResize === true ) {
  3294. this.emitBubblingEvent( 'stateChanged' );
  3295. return;
  3296. }
  3297. for( i = 0; i < this.contentItems.length; i++ ) {
  3298. if( this.contentItems[ i ] === contentItem ) {
  3299. contentItem.config[ this._dimension ] = newItemSize;
  3300. } else {
  3301. itemSize = this.contentItems[ i ].config[ this._dimension ] *= ( 100 - newItemSize ) / 100;
  3302. this.contentItems[ i ].config[ this._dimension ] = itemSize;
  3303. }
  3304. }
  3305. this.callDownwards( 'setSize' );
  3306. this.emitBubblingEvent( 'stateChanged' );
  3307. },
  3308. /**
  3309. * Removes a child of this element
  3310. *
  3311. * @param {lm.items.AbstractContentItem} contentItem
  3312. * @param {boolean} keepChild If true the child will be removed, but not destroyed
  3313. *
  3314. * @returns {void}
  3315. */
  3316. removeChild: function( contentItem, keepChild ) {
  3317. var removedItemSize = contentItem.config[ this._dimension ],
  3318. index = lm.utils.indexOf( contentItem, this.contentItems ),
  3319. splitterIndex = Math.max( index - 1, 0 ),
  3320. i,
  3321. childItem;
  3322. if( index === -1 ) {
  3323. throw new Error( 'Can\'t remove child. ContentItem is not child of this Row or Column' );
  3324. }
  3325. /**
  3326. * Remove the splitter before the item or after if the item happens
  3327. * to be the first in the row/column
  3328. */
  3329. if( this._splitter[ splitterIndex ] ) {
  3330. this._splitter[ splitterIndex ]._$destroy();
  3331. this._splitter.splice( splitterIndex, 1 );
  3332. }
  3333. /**
  3334. * Allocate the space that the removed item occupied to the remaining items
  3335. */
  3336. for( i = 0; i < this.contentItems.length; i++ ) {
  3337. if( this.contentItems[ i ] !== contentItem ) {
  3338. this.contentItems[ i ].config[ this._dimension ] += removedItemSize / ( this.contentItems.length - 1 );
  3339. }
  3340. }
  3341. lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild );
  3342. if( this.contentItems.length === 1 && this.config.isClosable === true ) {
  3343. childItem = this.contentItems[ 0 ];
  3344. this.contentItems = [];
  3345. this.parent.replaceChild( this, childItem, true );
  3346. } else {
  3347. this.callDownwards( 'setSize' );
  3348. this.emitBubblingEvent( 'stateChanged' );
  3349. }
  3350. },
  3351. /**
  3352. * Replaces a child of this Row or Column with another contentItem
  3353. *
  3354. * @param {lm.items.AbstractContentItem} oldChild
  3355. * @param {lm.items.AbstractContentItem} newChild
  3356. *
  3357. * @returns {void}
  3358. */
  3359. replaceChild: function( oldChild, newChild ) {
  3360. var size = oldChild.config[ this._dimension ];
  3361. lm.items.AbstractContentItem.prototype.replaceChild.call( this, oldChild, newChild );
  3362. newChild.config[ this._dimension ] = size;
  3363. this.callDownwards( 'setSize' );
  3364. this.emitBubblingEvent( 'stateChanged' );
  3365. },
  3366. /**
  3367. * Called whenever the dimensions of this item or one of its parents change
  3368. *
  3369. * @returns {void}
  3370. */
  3371. setSize: function() {
  3372. if( this.contentItems.length > 0 ) {
  3373. this._calculateRelativeSizes();
  3374. this._setAbsoluteSizes();
  3375. }
  3376. this.emitBubblingEvent( 'stateChanged' );
  3377. this.emit( 'resize' );
  3378. },
  3379. /**
  3380. * Invoked recursively by the layout manager. AbstractContentItem.init appends
  3381. * the contentItem's DOM elements to the container, RowOrColumn init adds splitters
  3382. * in between them
  3383. *
  3384. * @package private
  3385. * @override AbstractContentItem._$init
  3386. * @returns {void}
  3387. */
  3388. _$init: function() {
  3389. if( this.isInitialised === true ) return;
  3390. var i;
  3391. lm.items.AbstractContentItem.prototype._$init.call( this );
  3392. for( i = 0; i < this.contentItems.length - 1; i++ ) {
  3393. this.contentItems[ i ].element.after( this._createSplitter( i ).element );
  3394. }
  3395. },
  3396. /**
  3397. * Turns the relative sizes calculated by _calculateRelativeSizes into
  3398. * absolute pixel values and applies them to the children's DOM elements
  3399. *
  3400. * Assigns additional pixels to counteract Math.floor
  3401. *
  3402. * @private
  3403. * @returns {void}
  3404. */
  3405. _setAbsoluteSizes: function() {
  3406. var i,
  3407. sizeData = this._calculateAbsoluteSizes();
  3408. for( i = 0; i < this.contentItems.length; i++ ) {
  3409. if( sizeData.additionalPixel - i > 0 ) {
  3410. sizeData.itemSizes[ i ]++;
  3411. }
  3412. if( this._isColumn ) {
  3413. this.contentItems[ i ].element.width( sizeData.totalWidth );
  3414. this.contentItems[ i ].element.height( sizeData.itemSizes[ i ] );
  3415. } else {
  3416. this.contentItems[ i ].element.width( sizeData.itemSizes[ i ] );
  3417. this.contentItems[ i ].element.height( sizeData.totalHeight );
  3418. }
  3419. }
  3420. },
  3421. /**
  3422. * Calculates the absolute sizes of all of the children of this Item.
  3423. * @returns {object} - Set with absolute sizes and additional pixels.
  3424. */
  3425. _calculateAbsoluteSizes: function() {
  3426. var i,
  3427. totalSplitterSize = (this.contentItems.length - 1) * this._splitterSize,
  3428. totalWidth = this.element.width(),
  3429. totalHeight = this.element.height(),
  3430. totalAssigned = 0,
  3431. additionalPixel,
  3432. itemSize,
  3433. itemSizes = [];
  3434. if( this._isColumn ) {
  3435. totalHeight -= totalSplitterSize;
  3436. } else {
  3437. totalWidth -= totalSplitterSize;
  3438. }
  3439. for( i = 0; i < this.contentItems.length; i++ ) {
  3440. if( this._isColumn ) {
  3441. itemSize = Math.floor( totalHeight * ( this.contentItems[ i ].config.height / 100 ) );
  3442. } else {
  3443. itemSize = Math.floor( totalWidth * (this.contentItems[ i ].config.width / 100) );
  3444. }
  3445. totalAssigned += itemSize;
  3446. itemSizes.push( itemSize );
  3447. }
  3448. additionalPixel = Math.floor( (this._isColumn ? totalHeight : totalWidth) - totalAssigned );
  3449. return {
  3450. itemSizes: itemSizes,
  3451. additionalPixel: additionalPixel,
  3452. totalWidth: totalWidth,
  3453. totalHeight: totalHeight
  3454. };
  3455. },
  3456. /**
  3457. * Calculates the relative sizes of all children of this Item. The logic
  3458. * is as follows:
  3459. *
  3460. * - Add up the total size of all items that have a configured size
  3461. *
  3462. * - If the total == 100 (check for floating point errors)
  3463. * Excellent, job done
  3464. *
  3465. * - If the total is > 100,
  3466. * set the size of items without set dimensions to 1/3 and add this to the total
  3467. * set the size off all items so that the total is hundred relative to their original size
  3468. *
  3469. * - If the total is < 100
  3470. * If there are items without set dimensions, distribute the remainder to 100 evenly between them
  3471. * If there are no items without set dimensions, increase all items sizes relative to
  3472. * their original size so that they add up to 100
  3473. *
  3474. * @private
  3475. * @returns {void}
  3476. */
  3477. _calculateRelativeSizes: function() {
  3478. var i,
  3479. total = 0,
  3480. itemsWithoutSetDimension = [],
  3481. dimension = this._isColumn ? 'height' : 'width';
  3482. for( i = 0; i < this.contentItems.length; i++ ) {
  3483. if( this.contentItems[ i ].config[ dimension ] !== undefined ) {
  3484. total += this.contentItems[ i ].config[ dimension ];
  3485. } else {
  3486. itemsWithoutSetDimension.push( this.contentItems[ i ] );
  3487. }
  3488. }
  3489. /**
  3490. * Everything adds up to hundred, all good :-)
  3491. */
  3492. if( Math.round( total ) === 100 ) {
  3493. this._respectMinItemWidth();
  3494. return;
  3495. }
  3496. /**
  3497. * Allocate the remaining size to the items without a set dimension
  3498. */
  3499. if( Math.round( total ) < 100 && itemsWithoutSetDimension.length > 0 ) {
  3500. for( i = 0; i < itemsWithoutSetDimension.length; i++ ) {
  3501. itemsWithoutSetDimension[ i ].config[ dimension ] = ( 100 - total ) / itemsWithoutSetDimension.length;
  3502. }
  3503. this._respectMinItemWidth();
  3504. return;
  3505. }
  3506. /**
  3507. * If the total is > 100, but there are also items without a set dimension left, assing 50
  3508. * as their dimension and add it to the total
  3509. *
  3510. * This will be reset in the next step
  3511. */
  3512. if( Math.round( total ) > 100 ) {
  3513. for( i = 0; i < itemsWithoutSetDimension.length; i++ ) {
  3514. itemsWithoutSetDimension[ i ].config[ dimension ] = 50;
  3515. total += 50;
  3516. }
  3517. }
  3518. /**
  3519. * Set every items size relative to 100 relative to its size to total
  3520. */
  3521. for( i = 0; i < this.contentItems.length; i++ ) {
  3522. this.contentItems[ i ].config[ dimension ] = ( this.contentItems[ i ].config[ dimension ] / total ) * 100;
  3523. }
  3524. this._respectMinItemWidth();
  3525. },
  3526. /**
  3527. * Adjusts the column widths to respect the dimensions minItemWidth if set.
  3528. * @returns {}
  3529. */
  3530. _respectMinItemWidth: function() {
  3531. var minItemWidth = this.layoutManager.config.dimensions ? (this.layoutManager.config.dimensions.minItemWidth || 0) : 0,
  3532. sizeData = null,
  3533. entriesOverMin = [],
  3534. totalOverMin = 0,
  3535. totalUnderMin = 0,
  3536. remainingWidth = 0,
  3537. itemSize = 0,
  3538. contentItem = null,
  3539. reducePercent,
  3540. reducedWidth,
  3541. allEntries = [],
  3542. entry;
  3543. if( this._isColumn || !minItemWidth || this.contentItems.length <= 1 ) {
  3544. return;
  3545. }
  3546. sizeData = this._calculateAbsoluteSizes();
  3547. /**
  3548. * Figure out how much we are under the min item size total and how much room we have to use.
  3549. */
  3550. for( i = 0; i < this.contentItems.length; i++ ) {
  3551. contentItem = this.contentItems[ i ];
  3552. itemSize = sizeData.itemSizes[ i ];
  3553. if( itemSize < minItemWidth ) {
  3554. totalUnderMin += minItemWidth - itemSize;
  3555. entry = { width: minItemWidth };
  3556. }
  3557. else {
  3558. totalOverMin += itemSize - minItemWidth;
  3559. entry = { width: itemSize };
  3560. entriesOverMin.push( entry );
  3561. }
  3562. allEntries.push( entry );
  3563. }
  3564. /**
  3565. * If there is nothing under min, or there is not enough over to make up the difference, do nothing.
  3566. */
  3567. if( totalUnderMin === 0 || totalUnderMin > totalOverMin ) {
  3568. return;
  3569. }
  3570. /**
  3571. * Evenly reduce all columns that are over the min item width to make up the difference.
  3572. */
  3573. reducePercent = totalUnderMin / totalOverMin;
  3574. remainingWidth = totalUnderMin;
  3575. for( i = 0; i < entriesOverMin.length; i++ ) {
  3576. entry = entriesOverMin[ i ];
  3577. reducedWidth = Math.round( ( entry.width - minItemWidth ) * reducePercent );
  3578. remainingWidth -= reducedWidth;
  3579. entry.width -= reducedWidth;
  3580. }
  3581. /**
  3582. * Take anything remaining from the last item.
  3583. */
  3584. if( remainingWidth !== 0 ) {
  3585. allEntries[ allEntries.length - 1 ].width -= remainingWidth;
  3586. }
  3587. /**
  3588. * Set every items size relative to 100 relative to its size to total
  3589. */
  3590. for( i = 0; i < this.contentItems.length; i++ ) {
  3591. this.contentItems[ i ].config.width = (allEntries[ i ].width / sizeData.totalWidth) * 100;
  3592. }
  3593. },
  3594. /**
  3595. * Instantiates a new lm.controls.Splitter, binds events to it and adds
  3596. * it to the array of splitters at the position specified as the index argument
  3597. *
  3598. * What it doesn't do though is append the splitter to the DOM
  3599. *
  3600. * @param {Int} index The position of the splitter
  3601. *
  3602. * @returns {lm.controls.Splitter}
  3603. */
  3604. _createSplitter: function( index ) {
  3605. var splitter;
  3606. splitter = new lm.controls.Splitter( this._isColumn, this._splitterSize );
  3607. splitter.on( 'drag', lm.utils.fnBind( this._onSplitterDrag, this, [ splitter ] ), this );
  3608. splitter.on( 'dragStop', lm.utils.fnBind( this._onSplitterDragStop, this, [ splitter ] ), this );
  3609. splitter.on( 'dragStart', lm.utils.fnBind( this._onSplitterDragStart, this, [ splitter ] ), this );
  3610. this._splitter.splice( index, 0, splitter );
  3611. return splitter;
  3612. },
  3613. /**
  3614. * Locates the instance of lm.controls.Splitter in the array of
  3615. * registered splitters and returns a map containing the contentItem
  3616. * before and after the splitters, both of which are affected if the
  3617. * splitter is moved
  3618. *
  3619. * @param {lm.controls.Splitter} splitter
  3620. *
  3621. * @returns {Object} A map of contentItems that the splitter affects
  3622. */
  3623. _getItemsForSplitter: function( splitter ) {
  3624. var index = lm.utils.indexOf( splitter, this._splitter );
  3625. return {
  3626. before: this.contentItems[ index ],
  3627. after: this.contentItems[ index + 1 ]
  3628. };
  3629. },
  3630. /**
  3631. * Gets the minimum dimensions for the given item configuration array
  3632. * @param item
  3633. * @private
  3634. */
  3635. _getMinimumDimensions: function( arr ) {
  3636. var minWidth = 0, minHeight = 0;
  3637. for( var i = 0; i < arr.length; ++i ) {
  3638. minWidth = Math.max( arr[ i ].minWidth || 0, minWidth );
  3639. minHeight = Math.max( arr[ i ].minHeight || 0, minHeight );
  3640. }
  3641. return { horizontal: minWidth, vertical: minHeight };
  3642. },
  3643. /**
  3644. * Invoked when a splitter's dragListener fires dragStart. Calculates the splitters
  3645. * movement area once (so that it doesn't need calculating on every mousemove event)
  3646. *
  3647. * @param {lm.controls.Splitter} splitter
  3648. *
  3649. * @returns {void}
  3650. */
  3651. _onSplitterDragStart: function( splitter ) {
  3652. var items = this._getItemsForSplitter( splitter ),
  3653. minSize = this.layoutManager.config.dimensions[ this._isColumn ? 'minItemHeight' : 'minItemWidth' ];
  3654. var beforeMinDim = this._getMinimumDimensions( items.before.config.content );
  3655. var beforeMinSize = this._isColumn ? beforeMinDim.vertical : beforeMinDim.horizontal;
  3656. var afterMinDim = this._getMinimumDimensions( items.after.config.content );
  3657. var afterMinSize = this._isColumn ? afterMinDim.vertical : afterMinDim.horizontal;
  3658. this._splitterPosition = 0;
  3659. this._splitterMinPosition = -1 * ( items.before.element[ this._dimension ]() - (beforeMinSize || minSize) );
  3660. this._splitterMaxPosition = items.after.element[ this._dimension ]() - (afterMinSize || minSize);
  3661. },
  3662. /**
  3663. * Invoked when a splitter's DragListener fires drag. Updates the splitters DOM position,
  3664. * but not the sizes of the elements the splitter controls in order to minimize resize events
  3665. *
  3666. * @param {lm.controls.Splitter} splitter
  3667. * @param {Int} offsetX Relative pixel values to the splitters original position. Can be negative
  3668. * @param {Int} offsetY Relative pixel values to the splitters original position. Can be negative
  3669. *
  3670. * @returns {void}
  3671. */
  3672. _onSplitterDrag: function( splitter, offsetX, offsetY ) {
  3673. var offset = this._isColumn ? offsetY : offsetX;
  3674. if( offset > this._splitterMinPosition && offset < this._splitterMaxPosition ) {
  3675. this._splitterPosition = offset;
  3676. splitter.element.css( this._isColumn ? 'top' : 'left', offset );
  3677. }
  3678. },
  3679. /**
  3680. * Invoked when a splitter's DragListener fires dragStop. Resets the splitters DOM position,
  3681. * and applies the new sizes to the elements before and after the splitter and their children
  3682. * on the next animation frame
  3683. *
  3684. * @param {lm.controls.Splitter} splitter
  3685. *
  3686. * @returns {void}
  3687. */
  3688. _onSplitterDragStop: function( splitter ) {
  3689. var items = this._getItemsForSplitter( splitter ),
  3690. sizeBefore = items.before.element[ this._dimension ](),
  3691. sizeAfter = items.after.element[ this._dimension ](),
  3692. splitterPositionInRange = ( this._splitterPosition + sizeBefore ) / ( sizeBefore + sizeAfter ),
  3693. totalRelativeSize = items.before.config[ this._dimension ] + items.after.config[ this._dimension ];
  3694. items.before.config[ this._dimension ] = splitterPositionInRange * totalRelativeSize;
  3695. items.after.config[ this._dimension ] = ( 1 - splitterPositionInRange ) * totalRelativeSize;
  3696. splitter.element.css( {
  3697. 'top': 0,
  3698. 'left': 0
  3699. } );
  3700. lm.utils.animFrame( lm.utils.fnBind( this.callDownwards, this, [ 'setSize' ] ) );
  3701. }
  3702. } );
  3703. lm.items.Stack = function( layoutManager, config, parent ) {
  3704. lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
  3705. this.element = $( '<div class="lm_item lm_stack"></div>' );
  3706. this._activeContentItem = null;
  3707. var cfg = layoutManager.config;
  3708. this._header = { // defaults' reconstruction from old configuration style
  3709. show: cfg.settings.hasHeaders === true && config.hasHeaders !== false,
  3710. popout: cfg.settings.showPopoutIcon && cfg.labels.popout,
  3711. maximise: cfg.settings.showMaximiseIcon && cfg.labels.maximise,
  3712. close: cfg.settings.showCloseIcon && cfg.labels.close,
  3713. minimise: cfg.labels.minimise,
  3714. };
  3715. if( cfg.header ) // load simplified version of header configuration (https://github.com/deepstreamIO/golden-layout/pull/245)
  3716. lm.utils.copy( this._header, cfg.header );
  3717. if( config.header ) // load from stack
  3718. lm.utils.copy( this._header, config.header );
  3719. if( config.content && config.content[ 0 ] && config.content[ 0 ].header ) // load from component if stack omitted
  3720. lm.utils.copy( this._header, config.content[ 0 ].header );
  3721. this._dropZones = {};
  3722. this._dropSegment = null;
  3723. this._contentAreaDimensions = null;
  3724. this._dropIndex = null;
  3725. this.isStack = true;
  3726. this.childElementContainer = $( '<div class="lm_items"></div>' );
  3727. this.header = new lm.controls.Header( layoutManager, this );
  3728. this.element.append( this.header.element );
  3729. this.element.append( this.childElementContainer );
  3730. this._setupHeaderPosition();
  3731. this._$validateClosability();
  3732. };
  3733. lm.utils.extend( lm.items.Stack, lm.items.AbstractContentItem );
  3734. lm.utils.copy( lm.items.Stack.prototype, {
  3735. setSize: function() {
  3736. var i,
  3737. headerSize = this._header.show ? this.layoutManager.config.dimensions.headerHeight : 0,
  3738. contentWidth = this.element.width() - (this._sided ? headerSize : 0),
  3739. contentHeight = this.element.height() - (!this._sided ? headerSize : 0);
  3740. this.childElementContainer.width( contentWidth );
  3741. this.childElementContainer.height( contentHeight );
  3742. for( i = 0; i < this.contentItems.length; i++ ) {
  3743. this.contentItems[ i ].element.width( contentWidth ).height( contentHeight );
  3744. }
  3745. this.emit( 'resize' );
  3746. this.emitBubblingEvent( 'stateChanged' );
  3747. },
  3748. _$init: function() {
  3749. var i, initialItem;
  3750. if( this.isInitialised === true ) return;
  3751. lm.items.AbstractContentItem.prototype._$init.call( this );
  3752. for( i = 0; i < this.contentItems.length; i++ ) {
  3753. this.header.createTab( this.contentItems[ i ] );
  3754. this.contentItems[ i ]._$hide();
  3755. }
  3756. if( this.contentItems.length > 0 ) {
  3757. initialItem = this.contentItems[ this.config.activeItemIndex || 0 ];
  3758. if( !initialItem ) {
  3759. throw new Error( 'Configured activeItemIndex out of bounds' );
  3760. }
  3761. this.setActiveContentItem( initialItem );
  3762. }
  3763. },
  3764. setActiveContentItem: function( contentItem ) {
  3765. if( lm.utils.indexOf( contentItem, this.contentItems ) === -1 ) {
  3766. throw new Error( 'contentItem is not a child of this stack' );
  3767. }
  3768. if( this._activeContentItem !== null ) {
  3769. this._activeContentItem._$hide();
  3770. }
  3771. this._activeContentItem = contentItem;
  3772. this.header.setActiveContentItem( contentItem );
  3773. contentItem._$show();
  3774. this.emit( 'activeContentItemChanged', contentItem );
  3775. this.emitBubblingEvent( 'stateChanged' );
  3776. },
  3777. getActiveContentItem: function() {
  3778. return this.header.activeContentItem;
  3779. },
  3780. addChild: function( contentItem, index ) {
  3781. contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
  3782. lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index );
  3783. this.childElementContainer.append( contentItem.element );
  3784. this.header.createTab( contentItem, index );
  3785. this.setActiveContentItem( contentItem );
  3786. this.callDownwards( 'setSize' );
  3787. this._$validateClosability();
  3788. this.emitBubblingEvent( 'stateChanged' );
  3789. },
  3790. removeChild: function( contentItem, keepChild ) {
  3791. var index = lm.utils.indexOf( contentItem, this.contentItems );
  3792. var curIndex = lm.utils.indexOf( this._activeContentItem, this.contentItems );
  3793. lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild );
  3794. this.header.removeTab( contentItem );
  3795. if( this.contentItems.length > 0 ) {
  3796. var indexToFocus = index > curIndex ? curIndex : curIndex - 1;
  3797. if (curIndex == index)
  3798. indexToFocus = Math.max( index - 1, 0 );
  3799. this.setActiveContentItem( this.contentItems[ indexToFocus ] );
  3800. } else {
  3801. this._activeContentItem = null;
  3802. }
  3803. this._$validateClosability();
  3804. this.emitBubblingEvent( 'stateChanged' );
  3805. },
  3806. /**
  3807. * Validates that the stack is still closable or not. If a stack is able
  3808. * to close, but has a non closable component added to it, the stack is no
  3809. * longer closable until all components are closable.
  3810. *
  3811. * @returns {void}
  3812. */
  3813. _$validateClosability: function() {
  3814. var contentItem,
  3815. isClosable,
  3816. len,
  3817. i;
  3818. isClosable = this.header._isClosable();
  3819. for( i = 0, len = this.contentItems.length; i < len; i++ ) {
  3820. if( !isClosable ) {
  3821. break;
  3822. }
  3823. isClosable = this.contentItems[ i ].config.isClosable;
  3824. }
  3825. this.header._$setClosable( isClosable );
  3826. },
  3827. _$destroy: function() {
  3828. lm.items.AbstractContentItem.prototype._$destroy.call( this );
  3829. this.header._$destroy();
  3830. },
  3831. /**
  3832. * Ok, this one is going to be the tricky one: The user has dropped {contentItem} onto this stack.
  3833. *
  3834. * It was dropped on either the stacks header or the top, right, bottom or left bit of the content area
  3835. * (which one of those is stored in this._dropSegment). Now, if the user has dropped on the header the case
  3836. * is relatively clear: We add the item to the existing stack... job done (might be good to have
  3837. * tab reordering at some point, but lets not sweat it right now)
  3838. *
  3839. * If the item was dropped on the content part things are a bit more complicated. If it was dropped on either the
  3840. * top or bottom region we need to create a new column and place the items accordingly.
  3841. * Unless, of course if the stack is already within a column... in which case we want
  3842. * to add the newly created item to the existing column...
  3843. * either prepend or append it, depending on wether its top or bottom.
  3844. *
  3845. * Same thing for rows and left / right drop segments... so in total there are 9 things that can potentially happen
  3846. * (left, top, right, bottom) * is child of the right parent (row, column) + header drop
  3847. *
  3848. * @param {lm.item} contentItem
  3849. *
  3850. * @returns {void}
  3851. */
  3852. _$onDrop: function( contentItem ) {
  3853. /*
  3854. * The item was dropped on the header area. Just add it as a child of this stack and
  3855. * get the hell out of this logic
  3856. */
  3857. if( this._dropSegment === 'header' ) {
  3858. this._resetHeaderDropZone();
  3859. this.addChild( contentItem, this._dropIndex );
  3860. return;
  3861. }
  3862. /*
  3863. * The stack is empty. Let's just add the element.
  3864. */
  3865. if( this._dropSegment === 'body' ) {
  3866. this.addChild( contentItem );
  3867. return;
  3868. }
  3869. /*
  3870. * The item was dropped on the top-, left-, bottom- or right- part of the content. Let's
  3871. * aggregate some conditions to make the if statements later on more readable
  3872. */
  3873. var isVertical = this._dropSegment === 'top' || this._dropSegment === 'bottom',
  3874. isHorizontal = this._dropSegment === 'left' || this._dropSegment === 'right',
  3875. insertBefore = this._dropSegment === 'top' || this._dropSegment === 'left',
  3876. hasCorrectParent = ( isVertical && this.parent.isColumn ) || ( isHorizontal && this.parent.isRow ),
  3877. type = isVertical ? 'column' : 'row',
  3878. dimension = isVertical ? 'height' : 'width',
  3879. index,
  3880. stack,
  3881. rowOrColumn;
  3882. /*
  3883. * The content item can be either a component or a stack. If it is a component, wrap it into a stack
  3884. */
  3885. if( contentItem.isComponent ) {
  3886. stack = this.layoutManager.createContentItem( {
  3887. type: 'stack',
  3888. header: contentItem.config.header || {}
  3889. }, this );
  3890. stack._$init();
  3891. stack.addChild( contentItem );
  3892. contentItem = stack;
  3893. }
  3894. /*
  3895. * If the item is dropped on top or bottom of a column or left and right of a row, it's already
  3896. * layd out in the correct way. Just add it as a child
  3897. */
  3898. if( hasCorrectParent ) {
  3899. index = lm.utils.indexOf( this, this.parent.contentItems );
  3900. this.parent.addChild( contentItem, insertBefore ? index : index + 1, true );
  3901. this.config[ dimension ] *= 0.5;
  3902. contentItem.config[ dimension ] = this.config[ dimension ];
  3903. this.parent.callDownwards( 'setSize' );
  3904. /*
  3905. * This handles items that are dropped on top or bottom of a row or left / right of a column. We need
  3906. * to create the appropriate contentItem for them to live in
  3907. */
  3908. } else {
  3909. type = isVertical ? 'column' : 'row';
  3910. rowOrColumn = this.layoutManager.createContentItem( { type: type }, this );
  3911. this.parent.replaceChild( this, rowOrColumn );
  3912. rowOrColumn.addChild( contentItem, insertBefore ? 0 : undefined, true );
  3913. rowOrColumn.addChild( this, insertBefore ? undefined : 0, true );
  3914. this.config[ dimension ] = 50;
  3915. contentItem.config[ dimension ] = 50;
  3916. rowOrColumn.callDownwards( 'setSize' );
  3917. }
  3918. },
  3919. /**
  3920. * If the user hovers above the header part of the stack, indicate drop positions for tabs.
  3921. * otherwise indicate which segment of the body the dragged item would be dropped on
  3922. *
  3923. * @param {Int} x Absolute Screen X
  3924. * @param {Int} y Absolute Screen Y
  3925. *
  3926. * @returns {void}
  3927. */
  3928. _$highlightDropZone: function( x, y ) {
  3929. var segment, area;
  3930. for( segment in this._contentAreaDimensions ) {
  3931. area = this._contentAreaDimensions[ segment ].hoverArea;
  3932. if( area.x1 < x && area.x2 > x && area.y1 < y && area.y2 > y ) {
  3933. if( segment === 'header' ) {
  3934. this._dropSegment = 'header';
  3935. this._highlightHeaderDropZone( this._sided ? y : x );
  3936. } else {
  3937. this._resetHeaderDropZone();
  3938. this._highlightBodyDropZone( segment );
  3939. }
  3940. return;
  3941. }
  3942. }
  3943. },
  3944. _$getArea: function() {
  3945. if( this.element.is( ':visible' ) === false ) {
  3946. return null;
  3947. }
  3948. var getArea = lm.items.AbstractContentItem.prototype._$getArea,
  3949. headerArea = getArea.call( this, this.header.element ),
  3950. contentArea = getArea.call( this, this.childElementContainer ),
  3951. contentWidth = contentArea.x2 - contentArea.x1,
  3952. contentHeight = contentArea.y2 - contentArea.y1;
  3953. this._contentAreaDimensions = {
  3954. header: {
  3955. hoverArea: {
  3956. x1: headerArea.x1,
  3957. y1: headerArea.y1,
  3958. x2: headerArea.x2,
  3959. y2: headerArea.y2
  3960. },
  3961. highlightArea: {
  3962. x1: headerArea.x1,
  3963. y1: headerArea.y1,
  3964. x2: headerArea.x2,
  3965. y2: headerArea.y2
  3966. }
  3967. }
  3968. };
  3969. /**
  3970. * If this Stack is a parent to rows, columns or other stacks only its
  3971. * header is a valid dropzone.
  3972. */
  3973. if( this._activeContentItem && this._activeContentItem.isComponent === false ) {
  3974. return headerArea;
  3975. }
  3976. /**
  3977. * Highlight the entire body if the stack is empty
  3978. */
  3979. if( this.contentItems.length === 0 ) {
  3980. this._contentAreaDimensions.body = {
  3981. hoverArea: {
  3982. x1: contentArea.x1,
  3983. y1: contentArea.y1,
  3984. x2: contentArea.x2,
  3985. y2: contentArea.y2
  3986. },
  3987. highlightArea: {
  3988. x1: contentArea.x1,
  3989. y1: contentArea.y1,
  3990. x2: contentArea.x2,
  3991. y2: contentArea.y2
  3992. }
  3993. };
  3994. return getArea.call( this, this.element );
  3995. }
  3996. this._contentAreaDimensions.left = {
  3997. hoverArea: {
  3998. x1: contentArea.x1,
  3999. y1: contentArea.y1,
  4000. x2: contentArea.x1 + contentWidth * 0.25,
  4001. y2: contentArea.y2
  4002. },
  4003. highlightArea: {
  4004. x1: contentArea.x1,
  4005. y1: contentArea.y1,
  4006. x2: contentArea.x1 + contentWidth * 0.5,
  4007. y2: contentArea.y2
  4008. }
  4009. };
  4010. this._contentAreaDimensions.top = {
  4011. hoverArea: {
  4012. x1: contentArea.x1 + contentWidth * 0.25,
  4013. y1: contentArea.y1,
  4014. x2: contentArea.x1 + contentWidth * 0.75,
  4015. y2: contentArea.y1 + contentHeight * 0.5
  4016. },
  4017. highlightArea: {
  4018. x1: contentArea.x1,
  4019. y1: contentArea.y1,
  4020. x2: contentArea.x2,
  4021. y2: contentArea.y1 + contentHeight * 0.5
  4022. }
  4023. };
  4024. this._contentAreaDimensions.right = {
  4025. hoverArea: {
  4026. x1: contentArea.x1 + contentWidth * 0.75,
  4027. y1: contentArea.y1,
  4028. x2: contentArea.x2,
  4029. y2: contentArea.y2
  4030. },
  4031. highlightArea: {
  4032. x1: contentArea.x1 + contentWidth * 0.5,
  4033. y1: contentArea.y1,
  4034. x2: contentArea.x2,
  4035. y2: contentArea.y2
  4036. }
  4037. };
  4038. this._contentAreaDimensions.bottom = {
  4039. hoverArea: {
  4040. x1: contentArea.x1 + contentWidth * 0.25,
  4041. y1: contentArea.y1 + contentHeight * 0.5,
  4042. x2: contentArea.x1 + contentWidth * 0.75,
  4043. y2: contentArea.y2
  4044. },
  4045. highlightArea: {
  4046. x1: contentArea.x1,
  4047. y1: contentArea.y1 + contentHeight * 0.5,
  4048. x2: contentArea.x2,
  4049. y2: contentArea.y2
  4050. }
  4051. };
  4052. return getArea.call( this, this.element );
  4053. },
  4054. _highlightHeaderDropZone: function( x ) {
  4055. var i,
  4056. tabElement,
  4057. tabsLength = this.header.tabs.length,
  4058. isAboveTab = false,
  4059. tabTop,
  4060. tabLeft,
  4061. offset,
  4062. placeHolderLeft,
  4063. headerOffset,
  4064. tabWidth,
  4065. halfX;
  4066. // Empty stack
  4067. if( tabsLength === 0 ) {
  4068. headerOffset = this.header.element.offset();
  4069. this.layoutManager.dropTargetIndicator.highlightArea( {
  4070. x1: headerOffset.left,
  4071. x2: headerOffset.left + 100,
  4072. y1: headerOffset.top + this.header.element.height() - 20,
  4073. y2: headerOffset.top + this.header.element.height()
  4074. } );
  4075. return;
  4076. }
  4077. for( i = 0; i < tabsLength; i++ ) {
  4078. tabElement = this.header.tabs[ i ].element;
  4079. offset = tabElement.offset();
  4080. if( this._sided ) {
  4081. tabLeft = offset.top;
  4082. tabTop = offset.left;
  4083. tabWidth = tabElement.height();
  4084. } else {
  4085. tabLeft = offset.left;
  4086. tabTop = offset.top;
  4087. tabWidth = tabElement.width();
  4088. }
  4089. if( x > tabLeft && x < tabLeft + tabWidth ) {
  4090. isAboveTab = true;
  4091. break;
  4092. }
  4093. }
  4094. if( isAboveTab === false && x < tabLeft ) {
  4095. return;
  4096. }
  4097. halfX = tabLeft + tabWidth / 2;
  4098. if( x < halfX ) {
  4099. this._dropIndex = i;
  4100. tabElement.before( this.layoutManager.tabDropPlaceholder );
  4101. } else {
  4102. this._dropIndex = Math.min( i + 1, tabsLength );
  4103. tabElement.after( this.layoutManager.tabDropPlaceholder );
  4104. }
  4105. if( this._sided ) {
  4106. placeHolderTop = this.layoutManager.tabDropPlaceholder.offset().top;
  4107. this.layoutManager.dropTargetIndicator.highlightArea( {
  4108. x1: tabTop,
  4109. x2: tabTop + tabElement.innerHeight(),
  4110. y1: placeHolderTop,
  4111. y2: placeHolderTop + this.layoutManager.tabDropPlaceholder.width()
  4112. } );
  4113. return;
  4114. }
  4115. placeHolderLeft = this.layoutManager.tabDropPlaceholder.offset().left;
  4116. this.layoutManager.dropTargetIndicator.highlightArea( {
  4117. x1: placeHolderLeft,
  4118. x2: placeHolderLeft + this.layoutManager.tabDropPlaceholder.width(),
  4119. y1: tabTop,
  4120. y2: tabTop + tabElement.innerHeight()
  4121. } );
  4122. },
  4123. _resetHeaderDropZone: function() {
  4124. this.layoutManager.tabDropPlaceholder.remove();
  4125. },
  4126. _setupHeaderPosition: function() {
  4127. var side = [ 'right', 'left', 'bottom' ].indexOf( this._header.show ) >= 0 && this._header.show;
  4128. this.header.element.toggle( !!this._header.show );
  4129. this._side = side;
  4130. this._sided = [ 'right', 'left' ].indexOf( this._side ) >= 0;
  4131. this.element.removeClass( 'lm_left lm_right lm_bottom' );
  4132. if( this._side )
  4133. this.element.addClass( 'lm_' + this._side );
  4134. if( this.element.find( '.lm_header' ).length && this.childElementContainer ) {
  4135. var headerPosition = [ 'right', 'bottom' ].indexOf( this._side ) >= 0 ? 'before' : 'after';
  4136. this.header.element[ headerPosition ]( this.childElementContainer );
  4137. this.callDownwards( 'setSize' );
  4138. }
  4139. },
  4140. _highlightBodyDropZone: function( segment ) {
  4141. var highlightArea = this._contentAreaDimensions[ segment ].highlightArea;
  4142. this.layoutManager.dropTargetIndicator.highlightArea( highlightArea );
  4143. this._dropSegment = segment;
  4144. }
  4145. } );
  4146. lm.utils.BubblingEvent = function( name, origin ) {
  4147. this.name = name;
  4148. this.origin = origin;
  4149. this.isPropagationStopped = false;
  4150. };
  4151. lm.utils.BubblingEvent.prototype.stopPropagation = function() {
  4152. this.isPropagationStopped = true;
  4153. };
  4154. /**
  4155. * Minifies and unminifies configs by replacing frequent keys
  4156. * and values with one letter substitutes
  4157. *
  4158. * @constructor
  4159. */
  4160. lm.utils.ConfigMinifier = function() {
  4161. this._keys = [
  4162. 'settings',
  4163. 'hasHeaders',
  4164. 'constrainDragToContainer',
  4165. 'constrainDragToHeader',
  4166. 'selectionEnabled',
  4167. 'dimensions',
  4168. 'borderWidth',
  4169. 'minItemHeight',
  4170. 'minItemWidth',
  4171. 'headerHeight',
  4172. 'dragProxyWidth',
  4173. 'dragProxyHeight',
  4174. 'labels',
  4175. 'close',
  4176. 'maximise',
  4177. 'minimise',
  4178. 'popout',
  4179. 'content',
  4180. 'componentName',
  4181. 'componentState',
  4182. 'id',
  4183. 'width',
  4184. 'type',
  4185. 'height',
  4186. 'isClosable',
  4187. 'title',
  4188. 'popoutWholeStack',
  4189. 'openPopouts',
  4190. 'parentId',
  4191. 'activeItemIndex',
  4192. 'reorderEnabled'
  4193. //Maximum 36 entries, do not cross this line!
  4194. ];
  4195. this._values = [
  4196. true,
  4197. false,
  4198. 'row',
  4199. 'column',
  4200. 'stack',
  4201. 'component',
  4202. 'close',
  4203. 'maximise',
  4204. 'minimise',
  4205. 'open in new window'
  4206. ];
  4207. };
  4208. lm.utils.copy( lm.utils.ConfigMinifier.prototype, {
  4209. /**
  4210. * Takes a GoldenLayout configuration object and
  4211. * replaces its keys and values recursively with
  4212. * one letter counterparts
  4213. *
  4214. * @param {Object} config A GoldenLayout config object
  4215. *
  4216. * @returns {Object} minified config
  4217. */
  4218. minifyConfig: function( config ) {
  4219. var min = {};
  4220. this._nextLevel( config, min, '_min' );
  4221. return min;
  4222. },
  4223. /**
  4224. * Takes a configuration Object that was previously minified
  4225. * using minifyConfig and returns its original version
  4226. *
  4227. * @param {Object} minifiedConfig
  4228. *
  4229. * @returns {Object} the original configuration
  4230. */
  4231. unminifyConfig: function( minifiedConfig ) {
  4232. var orig = {};
  4233. this._nextLevel( minifiedConfig, orig, '_max' );
  4234. return orig;
  4235. },
  4236. /**
  4237. * Recursive function, called for every level of the config structure
  4238. *
  4239. * @param {Array|Object} orig
  4240. * @param {Array|Object} min
  4241. * @param {String} translationFn
  4242. *
  4243. * @returns {void}
  4244. */
  4245. _nextLevel: function( from, to, translationFn ) {
  4246. var key, minKey;
  4247. for( key in from ) {
  4248. /**
  4249. * For in returns array indices as keys, so let's cast them to numbers
  4250. */
  4251. if( from instanceof Array ) key = parseInt( key, 10 );
  4252. /**
  4253. * In case something has extended Object prototypes
  4254. */
  4255. if( !from.hasOwnProperty( key ) ) continue;
  4256. /**
  4257. * Translate the key to a one letter substitute
  4258. */
  4259. minKey = this[ translationFn ]( key, this._keys );
  4260. /**
  4261. * For Arrays and Objects, create a new Array/Object
  4262. * on the minified object and recurse into it
  4263. */
  4264. if( typeof from[ key ] === 'object' ) {
  4265. to[ minKey ] = from[ key ] instanceof Array ? [] : {};
  4266. this._nextLevel( from[ key ], to[ minKey ], translationFn );
  4267. /**
  4268. * For primitive values (Strings, Numbers, Boolean etc.)
  4269. * minify the value
  4270. */
  4271. } else {
  4272. to[ minKey ] = this[ translationFn ]( from[ key ], this._values );
  4273. }
  4274. }
  4275. },
  4276. /**
  4277. * Minifies value based on a dictionary
  4278. *
  4279. * @param {String|Boolean} value
  4280. * @param {Array<String|Boolean>} dictionary
  4281. *
  4282. * @returns {String} The minified version
  4283. */
  4284. _min: function( value, dictionary ) {
  4285. /**
  4286. * If a value actually is a single character, prefix it
  4287. * with ___ to avoid mistaking it for a minification code
  4288. */
  4289. if( typeof value === 'string' && value.length === 1 ) {
  4290. return '___' + value;
  4291. }
  4292. var index = lm.utils.indexOf( value, dictionary );
  4293. /**
  4294. * value not found in the dictionary, return it unmodified
  4295. */
  4296. if( index === -1 ) {
  4297. return value;
  4298. /**
  4299. * value found in dictionary, return its base36 counterpart
  4300. */
  4301. } else {
  4302. return index.toString( 36 );
  4303. }
  4304. },
  4305. _max: function( value, dictionary ) {
  4306. /**
  4307. * value is a single character. Assume that it's a translation
  4308. * and return the original value from the dictionary
  4309. */
  4310. if( typeof value === 'string' && value.length === 1 ) {
  4311. return dictionary[ parseInt( value, 36 ) ];
  4312. }
  4313. /**
  4314. * value originally was a single character and was prefixed with ___
  4315. * to avoid mistaking it for a translation. Remove the prefix
  4316. * and return the original character
  4317. */
  4318. if( typeof value === 'string' && value.substr( 0, 3 ) === '___' ) {
  4319. return value[ 3 ];
  4320. }
  4321. /**
  4322. * value was not minified
  4323. */
  4324. return value;
  4325. }
  4326. } );
  4327. /**
  4328. * An EventEmitter singleton that propagates events
  4329. * across multiple windows. This is a little bit trickier since
  4330. * windows are allowed to open childWindows in their own right
  4331. *
  4332. * This means that we deal with a tree of windows. Hence the rules for event propagation are:
  4333. *
  4334. * - Propagate events from this layout to both parents and children
  4335. * - Propagate events from parent to this and children
  4336. * - Propagate events from children to the other children (but not the emitting one) and the parent
  4337. *
  4338. * @constructor
  4339. *
  4340. * @param {lm.LayoutManager} layoutManager
  4341. */
  4342. lm.utils.EventHub = function( layoutManager ) {
  4343. lm.utils.EventEmitter.call( this );
  4344. this._layoutManager = layoutManager;
  4345. this._dontPropagateToParent = null;
  4346. this._childEventSource = null;
  4347. this.on( lm.utils.EventEmitter.ALL_EVENT, lm.utils.fnBind( this._onEventFromThis, this ) );
  4348. this._boundOnEventFromChild = lm.utils.fnBind( this._onEventFromChild, this );
  4349. $( window ).on( 'gl_child_event', this._boundOnEventFromChild );
  4350. };
  4351. /**
  4352. * Called on every event emitted on this eventHub, regardles of origin.
  4353. *
  4354. * @private
  4355. *
  4356. * @param {Mixed}
  4357. *
  4358. * @returns {void}
  4359. */
  4360. lm.utils.EventHub.prototype._onEventFromThis = function() {
  4361. var args = Array.prototype.slice.call( arguments );
  4362. if( this._layoutManager.isSubWindow && args[ 0 ] !== this._dontPropagateToParent ) {
  4363. this._propagateToParent( args );
  4364. }
  4365. this._propagateToChildren( args );
  4366. //Reset
  4367. this._dontPropagateToParent = null;
  4368. this._childEventSource = null;
  4369. };
  4370. /**
  4371. * Called by the parent layout.
  4372. *
  4373. * @param {Array} args Event name + arguments
  4374. *
  4375. * @returns {void}
  4376. */
  4377. lm.utils.EventHub.prototype._$onEventFromParent = function( args ) {
  4378. this._dontPropagateToParent = args[ 0 ];
  4379. this.emit.apply( this, args );
  4380. };
  4381. /**
  4382. * Callback for child events raised on the window
  4383. *
  4384. * @param {DOMEvent} event
  4385. * @private
  4386. *
  4387. * @returns {void}
  4388. */
  4389. lm.utils.EventHub.prototype._onEventFromChild = function( event ) {
  4390. this._childEventSource = event.originalEvent.__gl;
  4391. this.emit.apply( this, event.originalEvent.__glArgs );
  4392. };
  4393. /**
  4394. * Propagates the event to the parent by emitting
  4395. * it on the parent's DOM window
  4396. *
  4397. * @param {Array} args Event name + arguments
  4398. * @private
  4399. *
  4400. * @returns {void}
  4401. */
  4402. lm.utils.EventHub.prototype._propagateToParent = function( args ) {
  4403. var event,
  4404. eventName = 'gl_child_event';
  4405. if( document.createEvent ) {
  4406. event = window.opener.document.createEvent( 'HTMLEvents' );
  4407. event.initEvent( eventName, true, true );
  4408. } else {
  4409. event = window.opener.document.createEventObject();
  4410. event.eventType = eventName;
  4411. }
  4412. event.eventName = eventName;
  4413. event.__glArgs = args;
  4414. event.__gl = this._layoutManager;
  4415. if( document.createEvent ) {
  4416. window.opener.dispatchEvent( event );
  4417. } else {
  4418. window.opener.fireEvent( 'on' + event.eventType, event );
  4419. }
  4420. };
  4421. /**
  4422. * Propagate events to children
  4423. *
  4424. * @param {Array} args Event name + arguments
  4425. * @private
  4426. *
  4427. * @returns {void}
  4428. */
  4429. lm.utils.EventHub.prototype._propagateToChildren = function( args ) {
  4430. var childGl, i;
  4431. for( i = 0; i < this._layoutManager.openPopouts.length; i++ ) {
  4432. childGl = this._layoutManager.openPopouts[ i ].getGlInstance();
  4433. if( childGl && childGl !== this._childEventSource ) {
  4434. childGl.eventHub._$onEventFromParent( args );
  4435. }
  4436. }
  4437. };
  4438. /**
  4439. * Destroys the EventHub
  4440. *
  4441. * @public
  4442. * @returns {void}
  4443. */
  4444. lm.utils.EventHub.prototype.destroy = function() {
  4445. $( window ).off( 'gl_child_event', this._boundOnEventFromChild );
  4446. };
  4447. /**
  4448. * A specialised GoldenLayout component that binds GoldenLayout container
  4449. * lifecycle events to react components
  4450. *
  4451. * @constructor
  4452. *
  4453. * @param {lm.container.ItemContainer} container
  4454. * @param {Object} state state is not required for react components
  4455. */
  4456. lm.utils.ReactComponentHandler = function( container, state ) {
  4457. this._reactComponent = null;
  4458. this._originalComponentWillUpdate = null;
  4459. this._container = container;
  4460. this._initialState = state;
  4461. this._reactClass = this._getReactClass();
  4462. this._container.on( 'open', this._render, this );
  4463. this._container.on( 'destroy', this._destroy, this );
  4464. };
  4465. lm.utils.copy( lm.utils.ReactComponentHandler.prototype, {
  4466. /**
  4467. * Creates the react class and component and hydrates it with
  4468. * the initial state - if one is present
  4469. *
  4470. * By default, react's getInitialState will be used
  4471. *
  4472. * @private
  4473. * @returns {void}
  4474. */
  4475. _render: function() {
  4476. this._reactComponent = ReactDOM.render( this._getReactComponent(), this._container.getElement()[ 0 ] );
  4477. this._originalComponentWillUpdate = this._reactComponent.componentWillUpdate || function() {
  4478. };
  4479. this._reactComponent.componentWillUpdate = this._onUpdate.bind( this );
  4480. if( this._container.getState() ) {
  4481. this._reactComponent.setState( this._container.getState() );
  4482. }
  4483. },
  4484. /**
  4485. * Removes the component from the DOM and thus invokes React's unmount lifecycle
  4486. *
  4487. * @private
  4488. * @returns {void}
  4489. */
  4490. _destroy: function() {
  4491. ReactDOM.unmountComponentAtNode( this._container.getElement()[ 0 ] );
  4492. this._container.off( 'open', this._render, this );
  4493. this._container.off( 'destroy', this._destroy, this );
  4494. },
  4495. /**
  4496. * Hooks into React's state management and applies the componentstate
  4497. * to GoldenLayout
  4498. *
  4499. * @private
  4500. * @returns {void}
  4501. */
  4502. _onUpdate: function( nextProps, nextState ) {
  4503. this._container.setState( nextState );
  4504. this._originalComponentWillUpdate.call( this._reactComponent, nextProps, nextState );
  4505. },
  4506. /**
  4507. * Retrieves the react class from GoldenLayout's registry
  4508. *
  4509. * @private
  4510. * @returns {React.Class}
  4511. */
  4512. _getReactClass: function() {
  4513. var componentName = this._container._config.component;
  4514. var reactClass;
  4515. if( !componentName ) {
  4516. throw new Error( 'No react component name. type: react-component needs a field `component`' );
  4517. }
  4518. reactClass = this._container.layoutManager.getComponent( componentName );
  4519. if( !reactClass ) {
  4520. throw new Error( 'React component "' + componentName + '" not found. ' +
  4521. 'Please register all components with GoldenLayout using `registerComponent(name, component)`' );
  4522. }
  4523. return reactClass;
  4524. },
  4525. /**
  4526. * Copies and extends the properties array and returns the React element
  4527. *
  4528. * @private
  4529. * @returns {React.Element}
  4530. */
  4531. _getReactComponent: function() {
  4532. var defaultProps = {
  4533. glEventHub: this._container.layoutManager.eventHub,
  4534. glContainer: this._container,
  4535. };
  4536. var props = $.extend( defaultProps, this._container._config.props );
  4537. return React.createElement( this._reactClass, props );
  4538. }
  4539. } );})(window.$);