goldenlayout.js 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244
  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._toggleAdditionalTabsDropdownVisiblity, 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. * Toggle visibility of the additional tabs's drop down for when there are too many to display.
  2225. *
  2226. * @returns {void}
  2227. */
  2228. _toggleAdditionalTabsDropdownVisiblity: function() {
  2229. if (this.tabDropdownContainer.is(":visible"))
  2230. this.tabDropdownContainer.hide();
  2231. else
  2232. this.tabDropdownContainer.show();
  2233. },
  2234. /**
  2235. * Checks whether the header is closable based on the parent config and
  2236. * the global config.
  2237. *
  2238. * @returns {Boolean} Whether the header is closable.
  2239. */
  2240. _isClosable: function() {
  2241. return this.parent.config.isClosable && this.layoutManager.config.settings.showCloseIcon;
  2242. },
  2243. _onPopoutClick: function() {
  2244. if( this.layoutManager.config.settings.popoutWholeStack === true ) {
  2245. this.parent.popout();
  2246. } else {
  2247. this.activeContentItem.popout();
  2248. }
  2249. },
  2250. /**
  2251. * Invoked when the header's background is clicked (not it's tabs or controls)
  2252. *
  2253. * @param {jQuery DOM event} event
  2254. *
  2255. * @returns {void}
  2256. */
  2257. _onHeaderClick: function( event ) {
  2258. if( event.target === this.element[ 0 ] ) {
  2259. this.parent.select();
  2260. }
  2261. },
  2262. /**
  2263. * Pushes the tabs to the tab dropdown if the available space is not sufficient
  2264. *
  2265. * @returns {void}
  2266. */
  2267. _updateTabSizes: function() {
  2268. if( this.tabs.length === 0 ) {
  2269. return;
  2270. }
  2271. var size = function( val ) {
  2272. return val ? 'width' : 'height';
  2273. }
  2274. this.element.css( size( !this.parent._sided ), '' );
  2275. this.element[ size( this.parent._sided ) ]( this.layoutManager.config.dimensions.headerHeight );
  2276. var availableWidth = this.element.outerWidth() - this.controlsContainer.outerWidth() - this._tabControlOffset,
  2277. totalTabWidth = 0,
  2278. tabElement,
  2279. i,
  2280. showTabDropdown,
  2281. swapTab,
  2282. tabWidth,
  2283. hasVisibleTab = false;
  2284. if( this.parent._sided )
  2285. availableWidth = this.element.outerHeight() - this.controlsContainer.outerHeight() - this._tabControlOffset;
  2286. this._lastVisibleTabIndex = -1;
  2287. for( i = 0; i < this.tabs.length; i++ ) {
  2288. tabElement = this.tabs[ i ].element;
  2289. /*
  2290. * Retain tab width when hidden so it can be restored.
  2291. */
  2292. tabWidth = tabElement.data( 'lastTabWidth' );
  2293. if( !tabWidth ) {
  2294. tabWidth = tabElement.outerWidth() + parseInt( tabElement.css( 'margin-right' ), 10 );
  2295. }
  2296. totalTabWidth += tabWidth;
  2297. // If the tab won't fit, put it in the dropdown for tabs, making sure there is always at least one tab visible.
  2298. if( totalTabWidth > availableWidth && hasVisibleTab ) {
  2299. tabElement.data( 'lastTabWidth', tabWidth );
  2300. this.tabDropdownContainer.append( tabElement );
  2301. }
  2302. else {
  2303. hasVisibleTab = true;
  2304. this._lastVisibleTabIndex = i;
  2305. tabElement.removeData( 'lastTabWidth' );
  2306. this.tabsContainer.append( tabElement );
  2307. }
  2308. }
  2309. /*
  2310. * Show the tab dropdown icon if not all tabs fit.
  2311. */
  2312. showTabDropdown = totalTabWidth > availableWidth;
  2313. this.tabDropdownButton.element[ showTabDropdown ? 'show' : 'hide' ]();
  2314. }
  2315. } );
  2316. lm.controls.HeaderButton = function( header, label, cssClass, action ) {
  2317. this._header = header;
  2318. this.element = $( '<li class="' + cssClass + '" title="' + label + '"></li>' );
  2319. this._header.on( 'destroy', this._$destroy, this );
  2320. this._action = action;
  2321. this.element.on( 'click touchstart', this._action );
  2322. this._header.controlsContainer.append( this.element );
  2323. };
  2324. lm.utils.copy( lm.controls.HeaderButton.prototype, {
  2325. _$destroy: function() {
  2326. this.element.off();
  2327. this.element.remove();
  2328. }
  2329. } );
  2330. lm.controls.Splitter = function( isVertical, size ) {
  2331. this._isVertical = isVertical;
  2332. this._size = size;
  2333. this.element = this._createElement();
  2334. this._dragListener = new lm.utils.DragListener( this.element );
  2335. };
  2336. lm.utils.copy( lm.controls.Splitter.prototype, {
  2337. on: function( event, callback, context ) {
  2338. this._dragListener.on( event, callback, context );
  2339. },
  2340. _$destroy: function() {
  2341. this.element.remove();
  2342. },
  2343. _createElement: function() {
  2344. var element = $( '<div class="lm_splitter"><div class="lm_drag_handle"></div></div>' );
  2345. element.addClass( 'lm_' + ( this._isVertical ? 'vertical' : 'horizontal' ) );
  2346. element[ this._isVertical ? 'height' : 'width' ]( this._size );
  2347. return element;
  2348. }
  2349. } );
  2350. /**
  2351. * Represents an individual tab within a Stack's header
  2352. *
  2353. * @param {lm.controls.Header} header
  2354. * @param {lm.items.AbstractContentItem} contentItem
  2355. *
  2356. * @constructor
  2357. */
  2358. lm.controls.Tab = function( header, contentItem ) {
  2359. this.header = header;
  2360. this.contentItem = contentItem;
  2361. this.element = $( lm.controls.Tab._template );
  2362. this.titleElement = this.element.find( '.lm_title' );
  2363. this.closeElement = this.element.find( '.lm_close_tab' );
  2364. this.closeElement[ contentItem.config.isClosable ? 'show' : 'hide' ]();
  2365. this.isActive = false;
  2366. this.setTitle( contentItem.config.title );
  2367. this.contentItem.on( 'titleChanged', this.setTitle, this );
  2368. this._layoutManager = this.contentItem.layoutManager;
  2369. if(
  2370. this._layoutManager.config.settings.reorderEnabled === true &&
  2371. contentItem.config.reorderEnabled === true
  2372. ) {
  2373. this._dragListener = new lm.utils.DragListener( this.titleElement );
  2374. this._dragListener.on( 'dragStart', this._onDragStart, this );
  2375. }
  2376. this._onTabClickFn = lm.utils.fnBind( this._onTabClick, this );
  2377. this._onCloseClickFn = lm.utils.fnBind( this._onCloseClick, this );
  2378. this.titleElement.on( 'mousedown touchstart', this._onTabClickFn );
  2379. if( this.contentItem.config.isClosable ) {
  2380. this.closeElement.on( 'click touchstart', this._onCloseClickFn );
  2381. } else {
  2382. this.closeElement.remove();
  2383. }
  2384. this.contentItem.tab = this;
  2385. this.contentItem.emit( 'tab', this );
  2386. this.contentItem.layoutManager.emit( 'tabCreated', this );
  2387. if( this.contentItem.isComponent ) {
  2388. this.contentItem.container.tab = this;
  2389. this.contentItem.container.emit( 'tab', this );
  2390. }
  2391. };
  2392. /**
  2393. * The tab's html template
  2394. *
  2395. * @type {String}
  2396. */
  2397. lm.controls.Tab._template = '<li class="lm_tab"><i class="lm_left"></i>' +
  2398. '<span class="lm_title"></span><div class="lm_close_tab"></div>' +
  2399. '<i class="lm_right"></i></li>';
  2400. lm.utils.copy( lm.controls.Tab.prototype, {
  2401. /**
  2402. * Sets the tab's title to the provided string and sets
  2403. * its title attribute to a pure text representation (without
  2404. * html tags) of the same string.
  2405. *
  2406. * @public
  2407. * @param {String} title can contain html
  2408. */
  2409. setTitle: function( title ) {
  2410. this.element.attr( 'title', lm.utils.stripTags( title ) );
  2411. this.titleElement.html( title );
  2412. },
  2413. /**
  2414. * Sets this tab's active state. To programmatically
  2415. * switch tabs, use header.setActiveContentItem( item ) instead.
  2416. *
  2417. * @public
  2418. * @param {Boolean} isActive
  2419. */
  2420. setActive: function( isActive ) {
  2421. if( isActive === this.isActive ) {
  2422. return;
  2423. }
  2424. this.isActive = isActive;
  2425. if( isActive ) {
  2426. this.element.addClass( 'lm_active' );
  2427. } else {
  2428. this.element.removeClass( 'lm_active' );
  2429. }
  2430. },
  2431. /**
  2432. * Destroys the tab
  2433. *
  2434. * @private
  2435. * @returns {void}
  2436. */
  2437. _$destroy: function() {
  2438. this.titleElement.off( 'mousedown touchstart', this._onTabClickFn );
  2439. this.closeElement.off( 'click touchstart', this._onCloseClickFn );
  2440. if( this._dragListener ) {
  2441. this._dragListener.off( 'dragStart', this._onDragStart );
  2442. this._dragListener = null;
  2443. }
  2444. this.element.remove();
  2445. },
  2446. /**
  2447. * Callback for the DragListener
  2448. *
  2449. * @param {Number} x The tabs absolute x position
  2450. * @param {Number} y The tabs absolute y position
  2451. *
  2452. * @private
  2453. * @returns {void}
  2454. */
  2455. _onDragStart: function( x, y ) {
  2456. if( this.contentItem.parent.isMaximised === true ) {
  2457. this.contentItem.parent.toggleMaximise();
  2458. }
  2459. new lm.controls.DragProxy(
  2460. x,
  2461. y,
  2462. this._dragListener,
  2463. this._layoutManager,
  2464. this.contentItem,
  2465. this.header.parent
  2466. );
  2467. },
  2468. /**
  2469. * Callback when the tab is clicked
  2470. *
  2471. * @param {jQuery DOM event} event
  2472. *
  2473. * @private
  2474. * @returns {void}
  2475. */
  2476. _onTabClick: function( event ) {
  2477. // left mouse button or tap
  2478. if( event.button === 0 || event.type === 'touchstart' ) {
  2479. var activeContentItem = this.header.parent.getActiveContentItem();
  2480. if( this.contentItem !== activeContentItem ) {
  2481. this.header.parent.setActiveContentItem( this.contentItem );
  2482. }
  2483. // middle mouse button
  2484. } else if( event.button === 1 && this.contentItem.config.isClosable ) {
  2485. this._onCloseClick( event );
  2486. }
  2487. },
  2488. onClose : function() { return true; },
  2489. /**
  2490. * Callback when the tab's close button is
  2491. * clicked
  2492. *
  2493. * @param {jQuery DOM event} event
  2494. *
  2495. * @private
  2496. * @returns {void}
  2497. */
  2498. _onCloseClick: function( event ) {
  2499. event.stopPropagation();
  2500. if( !this.onClose() ) return;
  2501. this.header.parent.removeChild( this.contentItem );
  2502. }
  2503. } );
  2504. lm.controls.TransitionIndicator = function() {
  2505. this._element = $( '<div class="lm_transition_indicator"></div>' );
  2506. $( document.body ).append( this._element );
  2507. this._toElement = null;
  2508. this._fromDimensions = null;
  2509. this._totalAnimationDuration = 200;
  2510. this._animationStartTime = null;
  2511. };
  2512. lm.utils.copy( lm.controls.TransitionIndicator.prototype, {
  2513. destroy: function() {
  2514. this._element.remove();
  2515. },
  2516. transitionElements: function( fromElement, toElement ) {
  2517. /**
  2518. * TODO - This is not quite as cool as expected. Review.
  2519. */
  2520. return;
  2521. this._toElement = toElement;
  2522. this._animationStartTime = lm.utils.now();
  2523. this._fromDimensions = this._measure( fromElement );
  2524. this._fromDimensions.opacity = 0.8;
  2525. this._element.show().css( this._fromDimensions );
  2526. lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) );
  2527. },
  2528. _nextAnimationFrame: function() {
  2529. var toDimensions = this._measure( this._toElement ),
  2530. animationProgress = ( lm.utils.now() - this._animationStartTime ) / this._totalAnimationDuration,
  2531. currentFrameStyles = {},
  2532. cssProperty;
  2533. if( animationProgress >= 1 ) {
  2534. this._element.hide();
  2535. return;
  2536. }
  2537. toDimensions.opacity = 0;
  2538. for( cssProperty in this._fromDimensions ) {
  2539. currentFrameStyles[ cssProperty ] = this._fromDimensions[ cssProperty ] +
  2540. ( toDimensions[ cssProperty ] - this._fromDimensions[ cssProperty ] ) *
  2541. animationProgress;
  2542. }
  2543. this._element.css( currentFrameStyles );
  2544. lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) );
  2545. },
  2546. _measure: function( element ) {
  2547. var offset = element.offset();
  2548. return {
  2549. left: offset.left,
  2550. top: offset.top,
  2551. width: element.outerWidth(),
  2552. height: element.outerHeight()
  2553. };
  2554. }
  2555. } );
  2556. lm.errors.ConfigurationError = function( message, node ) {
  2557. Error.call( this );
  2558. this.name = 'Configuration Error';
  2559. this.message = message;
  2560. this.node = node;
  2561. };
  2562. lm.errors.ConfigurationError.prototype = new Error();
  2563. /**
  2564. * This is the baseclass that all content items inherit from.
  2565. * Most methods provide a subset of what the sub-classes do.
  2566. *
  2567. * It also provides a number of functions for tree traversal
  2568. *
  2569. * @param {lm.LayoutManager} layoutManager
  2570. * @param {item node configuration} config
  2571. * @param {lm.item} parent
  2572. *
  2573. * @event stateChanged
  2574. * @event beforeItemDestroyed
  2575. * @event itemDestroyed
  2576. * @event itemCreated
  2577. * @event componentCreated
  2578. * @event rowCreated
  2579. * @event columnCreated
  2580. * @event stackCreated
  2581. *
  2582. * @constructor
  2583. */
  2584. lm.items.AbstractContentItem = function( layoutManager, config, parent ) {
  2585. lm.utils.EventEmitter.call( this );
  2586. this.config = this._extendItemNode( config );
  2587. this.type = config.type;
  2588. this.contentItems = [];
  2589. this.parent = parent;
  2590. this.isInitialised = false;
  2591. this.isMaximised = false;
  2592. this.isRoot = false;
  2593. this.isRow = false;
  2594. this.isColumn = false;
  2595. this.isStack = false;
  2596. this.isComponent = false;
  2597. this.layoutManager = layoutManager;
  2598. this._pendingEventPropagations = {};
  2599. this._throttledEvents = [ 'stateChanged' ];
  2600. this.on( lm.utils.EventEmitter.ALL_EVENT, this._propagateEvent, this );
  2601. if( config.content ) {
  2602. this._createContentItems( config );
  2603. }
  2604. };
  2605. lm.utils.copy( lm.items.AbstractContentItem.prototype, {
  2606. /**
  2607. * Set the size of the component and its children, called recursively
  2608. *
  2609. * @abstract
  2610. * @returns void
  2611. */
  2612. setSize: function() {
  2613. throw new Error( 'Abstract Method' );
  2614. },
  2615. /**
  2616. * Calls a method recursively downwards on the tree
  2617. *
  2618. * @param {String} functionName the name of the function to be called
  2619. * @param {[Array]}functionArguments optional arguments that are passed to every function
  2620. * @param {[bool]} bottomUp Call methods from bottom to top, defaults to false
  2621. * @param {[bool]} skipSelf Don't invoke the method on the class that calls it, defaults to false
  2622. *
  2623. * @returns {void}
  2624. */
  2625. callDownwards: function( functionName, functionArguments, bottomUp, skipSelf ) {
  2626. var i;
  2627. if( bottomUp !== true && skipSelf !== true ) {
  2628. this[ functionName ].apply( this, functionArguments || [] );
  2629. }
  2630. for( i = 0; i < this.contentItems.length; i++ ) {
  2631. this.contentItems[ i ].callDownwards( functionName, functionArguments, bottomUp );
  2632. }
  2633. if( bottomUp === true && skipSelf !== true ) {
  2634. this[ functionName ].apply( this, functionArguments || [] );
  2635. }
  2636. },
  2637. /**
  2638. * Removes a child node (and its children) from the tree
  2639. *
  2640. * @param {lm.items.ContentItem} contentItem
  2641. *
  2642. * @returns {void}
  2643. */
  2644. removeChild: function( contentItem, keepChild ) {
  2645. /*
  2646. * Get the position of the item that's to be removed within all content items this node contains
  2647. */
  2648. var index = lm.utils.indexOf( contentItem, this.contentItems );
  2649. /*
  2650. * Make sure the content item to be removed is actually a child of this item
  2651. */
  2652. if( index === -1 ) {
  2653. throw new Error( 'Can\'t remove child item. Unknown content item' );
  2654. }
  2655. /**
  2656. * Call ._$destroy on the content item. This also calls ._$destroy on all its children
  2657. */
  2658. if( keepChild !== true ) {
  2659. this.contentItems[ index ]._$destroy();
  2660. }
  2661. /**
  2662. * Remove the content item from this nodes array of children
  2663. */
  2664. this.contentItems.splice( index, 1 );
  2665. /**
  2666. * Remove the item from the configuration
  2667. */
  2668. this.config.content.splice( index, 1 );
  2669. /**
  2670. * If this node still contains other content items, adjust their size
  2671. */
  2672. if( this.contentItems.length > 0 ) {
  2673. this.callDownwards( 'setSize' );
  2674. /**
  2675. * If this was the last content item, remove this node as well
  2676. */
  2677. } else if( !(this instanceof lm.items.Root) && this.config.isClosable === true ) {
  2678. this.parent.removeChild( this );
  2679. }
  2680. },
  2681. /**
  2682. * Sets up the tree structure for the newly added child
  2683. * The responsibility for the actual DOM manipulations lies
  2684. * with the concrete item
  2685. *
  2686. * @param {lm.items.AbstractContentItem} contentItem
  2687. * @param {[Int]} index If omitted item will be appended
  2688. */
  2689. addChild: function( contentItem, index ) {
  2690. if( index === undefined ) {
  2691. index = this.contentItems.length;
  2692. }
  2693. this.contentItems.splice( index, 0, contentItem );
  2694. if( this.config.content === undefined ) {
  2695. this.config.content = [];
  2696. }
  2697. this.config.content.splice( index, 0, contentItem.config );
  2698. contentItem.parent = this;
  2699. if( contentItem.parent.isInitialised === true && contentItem.isInitialised === false ) {
  2700. contentItem._$init();
  2701. }
  2702. },
  2703. /**
  2704. * Replaces oldChild with newChild. This used to use jQuery.replaceWith... which for
  2705. * some reason removes all event listeners, so isn't really an option.
  2706. *
  2707. * @param {lm.item.AbstractContentItem} oldChild
  2708. * @param {lm.item.AbstractContentItem} newChild
  2709. *
  2710. * @returns {void}
  2711. */
  2712. replaceChild: function( oldChild, newChild, _$destroyOldChild ) {
  2713. newChild = this.layoutManager._$normalizeContentItem( newChild );
  2714. var index = lm.utils.indexOf( oldChild, this.contentItems ),
  2715. parentNode = oldChild.element[ 0 ].parentNode;
  2716. if( index === -1 ) {
  2717. throw new Error( 'Can\'t replace child. oldChild is not child of this' );
  2718. }
  2719. parentNode.replaceChild( newChild.element[ 0 ], oldChild.element[ 0 ] );
  2720. /*
  2721. * Optionally destroy the old content item
  2722. */
  2723. if( _$destroyOldChild === true ) {
  2724. oldChild.parent = null;
  2725. oldChild._$destroy();
  2726. }
  2727. /*
  2728. * Wire the new contentItem into the tree
  2729. */
  2730. this.contentItems[ index ] = newChild;
  2731. newChild.parent = this;
  2732. /*
  2733. * Update tab reference
  2734. */
  2735. if( this.isStack ) {
  2736. this.header.tabs[ index ].contentItem = newChild;
  2737. }
  2738. //TODO This doesn't update the config... refactor to leave item nodes untouched after creation
  2739. if( newChild.parent.isInitialised === true && newChild.isInitialised === false ) {
  2740. newChild._$init();
  2741. }
  2742. this.callDownwards( 'setSize' );
  2743. },
  2744. /**
  2745. * Convenience method.
  2746. * Shorthand for this.parent.removeChild( this )
  2747. *
  2748. * @returns {void}
  2749. */
  2750. remove: function() {
  2751. this.parent.removeChild( this );
  2752. },
  2753. /**
  2754. * Removes the component from the layout and creates a new
  2755. * browser window with the component and its children inside
  2756. *
  2757. * @returns {lm.controls.BrowserPopout}
  2758. */
  2759. popout: function() {
  2760. var browserPopout = this.layoutManager.createPopout( this );
  2761. this.emitBubblingEvent( 'stateChanged' );
  2762. return browserPopout;
  2763. },
  2764. /**
  2765. * Maximises the Item or minimises it if it is already maximised
  2766. *
  2767. * @returns {void}
  2768. */
  2769. toggleMaximise: function( e ) {
  2770. e && e.preventDefault();
  2771. if( this.isMaximised === true ) {
  2772. this.layoutManager._$minimiseItem( this );
  2773. } else {
  2774. this.layoutManager._$maximiseItem( this );
  2775. }
  2776. this.isMaximised = !this.isMaximised;
  2777. this.emitBubblingEvent( 'stateChanged' );
  2778. },
  2779. /**
  2780. * Selects the item if it is not already selected
  2781. *
  2782. * @returns {void}
  2783. */
  2784. select: function() {
  2785. if( this.layoutManager.selectedItem !== this ) {
  2786. this.layoutManager.selectItem( this, true );
  2787. this.element.addClass( 'lm_selected' );
  2788. }
  2789. },
  2790. /**
  2791. * De-selects the item if it is selected
  2792. *
  2793. * @returns {void}
  2794. */
  2795. deselect: function() {
  2796. if( this.layoutManager.selectedItem === this ) {
  2797. this.layoutManager.selectedItem = null;
  2798. this.element.removeClass( 'lm_selected' );
  2799. }
  2800. },
  2801. /**
  2802. * Set this component's title
  2803. *
  2804. * @public
  2805. * @param {String} title
  2806. *
  2807. * @returns {void}
  2808. */
  2809. setTitle: function( title ) {
  2810. this.config.title = title;
  2811. this.emit( 'titleChanged', title );
  2812. this.emit( 'stateChanged' );
  2813. },
  2814. /**
  2815. * Checks whether a provided id is present
  2816. *
  2817. * @public
  2818. * @param {String} id
  2819. *
  2820. * @returns {Boolean} isPresent
  2821. */
  2822. hasId: function( id ) {
  2823. if( !this.config.id ) {
  2824. return false;
  2825. } else if( typeof this.config.id === 'string' ) {
  2826. return this.config.id === id;
  2827. } else if( this.config.id instanceof Array ) {
  2828. return lm.utils.indexOf( id, this.config.id ) !== -1;
  2829. }
  2830. },
  2831. /**
  2832. * Adds an id. Adds it as a string if the component doesn't
  2833. * have an id yet or creates/uses an array
  2834. *
  2835. * @public
  2836. * @param {String} id
  2837. *
  2838. * @returns {void}
  2839. */
  2840. addId: function( id ) {
  2841. if( this.hasId( id ) ) {
  2842. return;
  2843. }
  2844. if( !this.config.id ) {
  2845. this.config.id = id;
  2846. } else if( typeof this.config.id === 'string' ) {
  2847. this.config.id = [ this.config.id, id ];
  2848. } else if( this.config.id instanceof Array ) {
  2849. this.config.id.push( id );
  2850. }
  2851. },
  2852. /**
  2853. * Removes an existing id. Throws an error
  2854. * if the id is not present
  2855. *
  2856. * @public
  2857. * @param {String} id
  2858. *
  2859. * @returns {void}
  2860. */
  2861. removeId: function( id ) {
  2862. if( !this.hasId( id ) ) {
  2863. throw new Error( 'Id not found' );
  2864. }
  2865. if( typeof this.config.id === 'string' ) {
  2866. delete this.config.id;
  2867. } else if( this.config.id instanceof Array ) {
  2868. var index = lm.utils.indexOf( id, this.config.id );
  2869. this.config.id.splice( index, 1 );
  2870. }
  2871. },
  2872. /****************************************
  2873. * SELECTOR
  2874. ****************************************/
  2875. getItemsByFilter: function( filter ) {
  2876. var result = [],
  2877. next = function( contentItem ) {
  2878. for( var i = 0; i < contentItem.contentItems.length; i++ ) {
  2879. if( filter( contentItem.contentItems[ i ] ) === true ) {
  2880. result.push( contentItem.contentItems[ i ] );
  2881. }
  2882. next( contentItem.contentItems[ i ] );
  2883. }
  2884. };
  2885. next( this );
  2886. return result;
  2887. },
  2888. getItemsById: function( id ) {
  2889. return this.getItemsByFilter( function( item ) {
  2890. if( item.config.id instanceof Array ) {
  2891. return lm.utils.indexOf( id, item.config.id ) !== -1;
  2892. } else {
  2893. return item.config.id === id;
  2894. }
  2895. } );
  2896. },
  2897. getItemsByType: function( type ) {
  2898. return this._$getItemsByProperty( 'type', type );
  2899. },
  2900. getComponentsByName: function( componentName ) {
  2901. var components = this._$getItemsByProperty( 'componentName', componentName ),
  2902. instances = [],
  2903. i;
  2904. for( i = 0; i < components.length; i++ ) {
  2905. instances.push( components[ i ].instance );
  2906. }
  2907. return instances;
  2908. },
  2909. /****************************************
  2910. * PACKAGE PRIVATE
  2911. ****************************************/
  2912. _$getItemsByProperty: function( key, value ) {
  2913. return this.getItemsByFilter( function( item ) {
  2914. return item[ key ] === value;
  2915. } );
  2916. },
  2917. _$setParent: function( parent ) {
  2918. this.parent = parent;
  2919. },
  2920. _$highlightDropZone: function( x, y, area ) {
  2921. this.layoutManager.dropTargetIndicator.highlightArea( area );
  2922. },
  2923. _$onDrop: function( contentItem ) {
  2924. this.addChild( contentItem );
  2925. },
  2926. _$hide: function() {
  2927. this._callOnActiveComponents( 'hide' );
  2928. this.element.hide();
  2929. this.layoutManager.updateSize();
  2930. },
  2931. _$show: function() {
  2932. this._callOnActiveComponents( 'show' );
  2933. this.element.show();
  2934. this.layoutManager.updateSize();
  2935. },
  2936. _callOnActiveComponents: function( methodName ) {
  2937. var stacks = this.getItemsByType( 'stack' ),
  2938. activeContentItem,
  2939. i;
  2940. for( i = 0; i < stacks.length; i++ ) {
  2941. activeContentItem = stacks[ i ].getActiveContentItem();
  2942. if( activeContentItem && activeContentItem.isComponent ) {
  2943. activeContentItem.container[ methodName ]();
  2944. }
  2945. }
  2946. },
  2947. /**
  2948. * Destroys this item ands its children
  2949. *
  2950. * @returns {void}
  2951. */
  2952. _$destroy: function() {
  2953. this.emitBubblingEvent( 'beforeItemDestroyed' );
  2954. this.callDownwards( '_$destroy', [], true, true );
  2955. this.element.remove();
  2956. this.emitBubblingEvent( 'itemDestroyed' );
  2957. },
  2958. /**
  2959. * Returns the area the component currently occupies in the format
  2960. *
  2961. * {
  2962. * x1: int
  2963. * xy: int
  2964. * y1: int
  2965. * y2: int
  2966. * contentItem: contentItem
  2967. * }
  2968. */
  2969. _$getArea: function( element ) {
  2970. element = element || this.element;
  2971. var offset = element.offset(),
  2972. width = element.width(),
  2973. height = element.height();
  2974. return {
  2975. x1: offset.left,
  2976. y1: offset.top,
  2977. x2: offset.left + width,
  2978. y2: offset.top + height,
  2979. surface: width * height,
  2980. contentItem: this
  2981. };
  2982. },
  2983. /**
  2984. * The tree of content items is created in two steps: First all content items are instantiated,
  2985. * then init is called recursively from top to bottem. This is the basic init function,
  2986. * it can be used, extended or overwritten by the content items
  2987. *
  2988. * Its behaviour depends on the content item
  2989. *
  2990. * @package private
  2991. *
  2992. * @returns {void}
  2993. */
  2994. _$init: function() {
  2995. var i;
  2996. this.setSize();
  2997. for( i = 0; i < this.contentItems.length; i++ ) {
  2998. this.childElementContainer.append( this.contentItems[ i ].element );
  2999. }
  3000. this.isInitialised = true;
  3001. this.emitBubblingEvent( 'itemCreated' );
  3002. this.emitBubblingEvent( this.type + 'Created' );
  3003. },
  3004. /**
  3005. * Emit an event that bubbles up the item tree.
  3006. *
  3007. * @param {String} name The name of the event
  3008. *
  3009. * @returns {void}
  3010. */
  3011. emitBubblingEvent: function( name ) {
  3012. var event = new lm.utils.BubblingEvent( name, this );
  3013. this.emit( name, event );
  3014. },
  3015. /**
  3016. * Private method, creates all content items for this node at initialisation time
  3017. * PLEASE NOTE, please see addChild for adding contentItems add runtime
  3018. * @private
  3019. * @param {configuration item node} config
  3020. *
  3021. * @returns {void}
  3022. */
  3023. _createContentItems: function( config ) {
  3024. var oContentItem, i;
  3025. if( !( config.content instanceof Array ) ) {
  3026. throw new lm.errors.ConfigurationError( 'content must be an Array', config );
  3027. }
  3028. for( i = 0; i < config.content.length; i++ ) {
  3029. oContentItem = this.layoutManager.createContentItem( config.content[ i ], this );
  3030. this.contentItems.push( oContentItem );
  3031. }
  3032. },
  3033. /**
  3034. * Extends an item configuration node with default settings
  3035. * @private
  3036. * @param {configuration item node} config
  3037. *
  3038. * @returns {configuration item node} extended config
  3039. */
  3040. _extendItemNode: function( config ) {
  3041. for( var key in lm.config.itemDefaultConfig ) {
  3042. if( config[ key ] === undefined ) {
  3043. config[ key ] = lm.config.itemDefaultConfig[ key ];
  3044. }
  3045. }
  3046. return config;
  3047. },
  3048. /**
  3049. * Called for every event on the item tree. Decides whether the event is a bubbling
  3050. * event and propagates it to its parent
  3051. *
  3052. * @param {String} name the name of the event
  3053. * @param {lm.utils.BubblingEvent} event
  3054. *
  3055. * @returns {void}
  3056. */
  3057. _propagateEvent: function( name, event ) {
  3058. if( event instanceof lm.utils.BubblingEvent &&
  3059. event.isPropagationStopped === false &&
  3060. this.isInitialised === true ) {
  3061. /**
  3062. * In some cases (e.g. if an element is created from a DragSource) it
  3063. * doesn't have a parent and is not below root. If that's the case
  3064. * propagate the bubbling event from the top level of the substree directly
  3065. * to the layoutManager
  3066. */
  3067. if( this.isRoot === false && this.parent ) {
  3068. this.parent.emit.apply( this.parent, Array.prototype.slice.call( arguments, 0 ) );
  3069. } else {
  3070. this._scheduleEventPropagationToLayoutManager( name, event );
  3071. }
  3072. }
  3073. },
  3074. /**
  3075. * All raw events bubble up to the root element. Some events that
  3076. * are propagated to - and emitted by - the layoutManager however are
  3077. * only string-based, batched and sanitized to make them more usable
  3078. *
  3079. * @param {String} name the name of the event
  3080. *
  3081. * @private
  3082. * @returns {void}
  3083. */
  3084. _scheduleEventPropagationToLayoutManager: function( name, event ) {
  3085. if( lm.utils.indexOf( name, this._throttledEvents ) === -1 ) {
  3086. this.layoutManager.emit( name, event.origin );
  3087. } else {
  3088. if( this._pendingEventPropagations[ name ] !== true ) {
  3089. this._pendingEventPropagations[ name ] = true;
  3090. lm.utils.animFrame( lm.utils.fnBind( this._propagateEventToLayoutManager, this, [ name, event ] ) );
  3091. }
  3092. }
  3093. },
  3094. /**
  3095. * Callback for events scheduled by _scheduleEventPropagationToLayoutManager
  3096. *
  3097. * @param {String} name the name of the event
  3098. *
  3099. * @private
  3100. * @returns {void}
  3101. */
  3102. _propagateEventToLayoutManager: function( name, event ) {
  3103. this._pendingEventPropagations[ name ] = false;
  3104. this.layoutManager.emit( name, event );
  3105. }
  3106. } );
  3107. /**
  3108. * @param {[type]} layoutManager [description]
  3109. * @param {[type]} config [description]
  3110. * @param {[type]} parent [description]
  3111. */
  3112. lm.items.Component = function( layoutManager, config, parent ) {
  3113. lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
  3114. var ComponentConstructor = layoutManager.getComponent( this.config.componentName ),
  3115. componentConfig = $.extend( true, {}, this.config.componentState || {} );
  3116. componentConfig.componentName = this.config.componentName;
  3117. this.componentName = this.config.componentName;
  3118. if( this.config.title === '' ) {
  3119. this.config.title = this.config.componentName;
  3120. }
  3121. this.isComponent = true;
  3122. this.container = new lm.container.ItemContainer( this.config, this, layoutManager );
  3123. this.instance = new ComponentConstructor( this.container, componentConfig );
  3124. this.element = this.container._element;
  3125. };
  3126. lm.utils.extend( lm.items.Component, lm.items.AbstractContentItem );
  3127. lm.utils.copy( lm.items.Component.prototype, {
  3128. close: function() {
  3129. this.parent.removeChild( this );
  3130. },
  3131. setSize: function() {
  3132. if( this.element.is( ':visible' ) ) {
  3133. // Do not update size of hidden components to prevent unwanted reflows
  3134. this.container._$setSize( this.element.width(), this.element.height() );
  3135. }
  3136. },
  3137. _$init: function() {
  3138. lm.items.AbstractContentItem.prototype._$init.call( this );
  3139. this.container.emit( 'open' );
  3140. },
  3141. _$hide: function() {
  3142. this.container.hide();
  3143. lm.items.AbstractContentItem.prototype._$hide.call( this );
  3144. },
  3145. _$show: function() {
  3146. this.container.show();
  3147. lm.items.AbstractContentItem.prototype._$show.call( this );
  3148. },
  3149. _$shown: function() {
  3150. this.container.shown();
  3151. lm.items.AbstractContentItem.prototype._$shown.call( this );
  3152. },
  3153. _$destroy: function() {
  3154. this.container.emit( 'destroy', this );
  3155. lm.items.AbstractContentItem.prototype._$destroy.call( this );
  3156. },
  3157. /**
  3158. * Dragging onto a component directly is not an option
  3159. *
  3160. * @returns null
  3161. */
  3162. _$getArea: function() {
  3163. return null;
  3164. }
  3165. } );
  3166. lm.items.Root = function( layoutManager, config, containerElement ) {
  3167. lm.items.AbstractContentItem.call( this, layoutManager, config, null );
  3168. this.isRoot = true;
  3169. this.type = 'root';
  3170. this.element = $( '<div class="lm_goldenlayout lm_item lm_root"></div>' );
  3171. this.childElementContainer = this.element;
  3172. this._containerElement = containerElement;
  3173. this._containerElement.append( this.element );
  3174. };
  3175. lm.utils.extend( lm.items.Root, lm.items.AbstractContentItem );
  3176. lm.utils.copy( lm.items.Root.prototype, {
  3177. addChild: function( contentItem ) {
  3178. if( this.contentItems.length > 0 ) {
  3179. throw new Error( 'Root node can only have a single child' );
  3180. }
  3181. contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
  3182. this.childElementContainer.append( contentItem.element );
  3183. lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem );
  3184. this.callDownwards( 'setSize' );
  3185. this.emitBubblingEvent( 'stateChanged' );
  3186. },
  3187. setSize: function( width, height ) {
  3188. width = (typeof width === 'undefined') ? this._containerElement.width() : width;
  3189. height = (typeof height === 'undefined') ? this._containerElement.height() : height;
  3190. this.element.width( width );
  3191. this.element.height( height );
  3192. /*
  3193. * Root can be empty
  3194. */
  3195. if( this.contentItems[ 0 ] ) {
  3196. this.contentItems[ 0 ].element.width( width );
  3197. this.contentItems[ 0 ].element.height( height );
  3198. }
  3199. },
  3200. _$highlightDropZone: function( x, y, area ) {
  3201. this.layoutManager.tabDropPlaceholder.remove();
  3202. lm.items.AbstractContentItem.prototype._$highlightDropZone.apply( this, arguments );
  3203. },
  3204. _$onDrop: function( contentItem, area ) {
  3205. var stack;
  3206. if( contentItem.isComponent ) {
  3207. stack = this.layoutManager.createContentItem( {
  3208. type: 'stack',
  3209. header: contentItem.config.header || {}
  3210. }, this );
  3211. stack._$init();
  3212. stack.addChild( contentItem );
  3213. contentItem = stack;
  3214. }
  3215. if( !this.contentItems.length ) {
  3216. this.addChild( contentItem );
  3217. } else {
  3218. var type = area.side[ 0 ] == 'x' ? 'row' : 'column';
  3219. var dimension = area.side[ 0 ] == 'x' ? 'width' : 'height';
  3220. var insertBefore = area.side[ 1 ] == '2';
  3221. var column = this.contentItems[ 0 ];
  3222. if( !column instanceof lm.items.RowOrColumn || column.type != type ) {
  3223. var rowOrColumn = this.layoutManager.createContentItem( { type: type }, this );
  3224. this.replaceChild( column, rowOrColumn );
  3225. rowOrColumn.addChild( contentItem, insertBefore ? 0 : undefined, true );
  3226. rowOrColumn.addChild( column, insertBefore ? undefined : 0, true );
  3227. column.config[ dimension ] = 50;
  3228. contentItem.config[ dimension ] = 50;
  3229. rowOrColumn.callDownwards( 'setSize' );
  3230. } else {
  3231. var sibbling = column.contentItems[ insertBefore ? 0 : column.contentItems.length - 1 ]
  3232. column.addChild( contentItem, insertBefore ? 0 : undefined, true );
  3233. sibbling.config[ dimension ] *= 0.5;
  3234. contentItem.config[ dimension ] = sibbling.config[ dimension ];
  3235. column.callDownwards( 'setSize' );
  3236. }
  3237. }
  3238. }
  3239. } );
  3240. lm.items.RowOrColumn = function( isColumn, layoutManager, config, parent ) {
  3241. lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
  3242. this.isRow = !isColumn;
  3243. this.isColumn = isColumn;
  3244. this.element = $( '<div class="lm_item lm_' + ( isColumn ? 'column' : 'row' ) + '"></div>' );
  3245. this.childElementContainer = this.element;
  3246. this._splitterSize = layoutManager.config.dimensions.borderWidth;
  3247. this._isColumn = isColumn;
  3248. this._dimension = isColumn ? 'height' : 'width';
  3249. this._splitter = [];
  3250. this._splitterPosition = null;
  3251. this._splitterMinPosition = null;
  3252. this._splitterMaxPosition = null;
  3253. };
  3254. lm.utils.extend( lm.items.RowOrColumn, lm.items.AbstractContentItem );
  3255. lm.utils.copy( lm.items.RowOrColumn.prototype, {
  3256. /**
  3257. * Add a new contentItem to the Row or Column
  3258. *
  3259. * @param {lm.item.AbstractContentItem} contentItem
  3260. * @param {[int]} index The position of the new item within the Row or Column.
  3261. * If no index is provided the item will be added to the end
  3262. * @param {[bool]} _$suspendResize If true the items won't be resized. This will leave the item in
  3263. * an inconsistent state and is only intended to be used if multiple
  3264. * children need to be added in one go and resize is called afterwards
  3265. *
  3266. * @returns {void}
  3267. */
  3268. addChild: function( contentItem, index, _$suspendResize ) {
  3269. var newItemSize, itemSize, i, splitterElement;
  3270. contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
  3271. if( index === undefined ) {
  3272. index = this.contentItems.length;
  3273. }
  3274. if( this.contentItems.length > 0 ) {
  3275. splitterElement = this._createSplitter( Math.max( 0, index - 1 ) ).element;
  3276. if( index > 0 ) {
  3277. this.contentItems[ index - 1 ].element.after( splitterElement );
  3278. splitterElement.after( contentItem.element );
  3279. } else {
  3280. this.contentItems[ 0 ].element.before( splitterElement );
  3281. splitterElement.before( contentItem.element );
  3282. }
  3283. } else {
  3284. this.childElementContainer.append( contentItem.element );
  3285. }
  3286. lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index );
  3287. newItemSize = ( 1 / this.contentItems.length ) * 100;
  3288. if( _$suspendResize === true ) {
  3289. this.emitBubblingEvent( 'stateChanged' );
  3290. return;
  3291. }
  3292. for( i = 0; i < this.contentItems.length; i++ ) {
  3293. if( this.contentItems[ i ] === contentItem ) {
  3294. contentItem.config[ this._dimension ] = newItemSize;
  3295. } else {
  3296. itemSize = this.contentItems[ i ].config[ this._dimension ] *= ( 100 - newItemSize ) / 100;
  3297. this.contentItems[ i ].config[ this._dimension ] = itemSize;
  3298. }
  3299. }
  3300. this.callDownwards( 'setSize' );
  3301. this.emitBubblingEvent( 'stateChanged' );
  3302. },
  3303. /**
  3304. * Removes a child of this element
  3305. *
  3306. * @param {lm.items.AbstractContentItem} contentItem
  3307. * @param {boolean} keepChild If true the child will be removed, but not destroyed
  3308. *
  3309. * @returns {void}
  3310. */
  3311. removeChild: function( contentItem, keepChild ) {
  3312. var removedItemSize = contentItem.config[ this._dimension ],
  3313. index = lm.utils.indexOf( contentItem, this.contentItems ),
  3314. splitterIndex = Math.max( index - 1, 0 ),
  3315. i,
  3316. childItem;
  3317. if( index === -1 ) {
  3318. throw new Error( 'Can\'t remove child. ContentItem is not child of this Row or Column' );
  3319. }
  3320. /**
  3321. * Remove the splitter before the item or after if the item happens
  3322. * to be the first in the row/column
  3323. */
  3324. if( this._splitter[ splitterIndex ] ) {
  3325. this._splitter[ splitterIndex ]._$destroy();
  3326. this._splitter.splice( splitterIndex, 1 );
  3327. }
  3328. /**
  3329. * Allocate the space that the removed item occupied to the remaining items
  3330. */
  3331. for( i = 0; i < this.contentItems.length; i++ ) {
  3332. if( this.contentItems[ i ] !== contentItem ) {
  3333. this.contentItems[ i ].config[ this._dimension ] += removedItemSize / ( this.contentItems.length - 1 );
  3334. }
  3335. }
  3336. lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild );
  3337. if( this.contentItems.length === 1 && this.config.isClosable === true ) {
  3338. childItem = this.contentItems[ 0 ];
  3339. this.contentItems = [];
  3340. this.parent.replaceChild( this, childItem, true );
  3341. } else {
  3342. this.callDownwards( 'setSize' );
  3343. this.emitBubblingEvent( 'stateChanged' );
  3344. }
  3345. },
  3346. /**
  3347. * Replaces a child of this Row or Column with another contentItem
  3348. *
  3349. * @param {lm.items.AbstractContentItem} oldChild
  3350. * @param {lm.items.AbstractContentItem} newChild
  3351. *
  3352. * @returns {void}
  3353. */
  3354. replaceChild: function( oldChild, newChild ) {
  3355. var size = oldChild.config[ this._dimension ];
  3356. lm.items.AbstractContentItem.prototype.replaceChild.call( this, oldChild, newChild );
  3357. newChild.config[ this._dimension ] = size;
  3358. this.callDownwards( 'setSize' );
  3359. this.emitBubblingEvent( 'stateChanged' );
  3360. },
  3361. /**
  3362. * Called whenever the dimensions of this item or one of its parents change
  3363. *
  3364. * @returns {void}
  3365. */
  3366. setSize: function() {
  3367. if( this.contentItems.length > 0 ) {
  3368. this._calculateRelativeSizes();
  3369. this._setAbsoluteSizes();
  3370. }
  3371. this.emitBubblingEvent( 'stateChanged' );
  3372. this.emit( 'resize' );
  3373. },
  3374. /**
  3375. * Invoked recursively by the layout manager. AbstractContentItem.init appends
  3376. * the contentItem's DOM elements to the container, RowOrColumn init adds splitters
  3377. * in between them
  3378. *
  3379. * @package private
  3380. * @override AbstractContentItem._$init
  3381. * @returns {void}
  3382. */
  3383. _$init: function() {
  3384. if( this.isInitialised === true ) return;
  3385. var i;
  3386. lm.items.AbstractContentItem.prototype._$init.call( this );
  3387. for( i = 0; i < this.contentItems.length - 1; i++ ) {
  3388. this.contentItems[ i ].element.after( this._createSplitter( i ).element );
  3389. }
  3390. },
  3391. /**
  3392. * Turns the relative sizes calculated by _calculateRelativeSizes into
  3393. * absolute pixel values and applies them to the children's DOM elements
  3394. *
  3395. * Assigns additional pixels to counteract Math.floor
  3396. *
  3397. * @private
  3398. * @returns {void}
  3399. */
  3400. _setAbsoluteSizes: function() {
  3401. var i,
  3402. sizeData = this._calculateAbsoluteSizes();
  3403. for( i = 0; i < this.contentItems.length; i++ ) {
  3404. if( sizeData.additionalPixel - i > 0 ) {
  3405. sizeData.itemSizes[ i ]++;
  3406. }
  3407. if( this._isColumn ) {
  3408. this.contentItems[ i ].element.width( sizeData.totalWidth );
  3409. this.contentItems[ i ].element.height( sizeData.itemSizes[ i ] );
  3410. } else {
  3411. this.contentItems[ i ].element.width( sizeData.itemSizes[ i ] );
  3412. this.contentItems[ i ].element.height( sizeData.totalHeight );
  3413. }
  3414. }
  3415. },
  3416. /**
  3417. * Calculates the absolute sizes of all of the children of this Item.
  3418. * @returns {object} - Set with absolute sizes and additional pixels.
  3419. */
  3420. _calculateAbsoluteSizes: function() {
  3421. var i,
  3422. totalSplitterSize = (this.contentItems.length - 1) * this._splitterSize,
  3423. totalWidth = this.element.width(),
  3424. totalHeight = this.element.height(),
  3425. totalAssigned = 0,
  3426. additionalPixel,
  3427. itemSize,
  3428. itemSizes = [];
  3429. if( this._isColumn ) {
  3430. totalHeight -= totalSplitterSize;
  3431. } else {
  3432. totalWidth -= totalSplitterSize;
  3433. }
  3434. for( i = 0; i < this.contentItems.length; i++ ) {
  3435. if( this._isColumn ) {
  3436. itemSize = Math.floor( totalHeight * ( this.contentItems[ i ].config.height / 100 ) );
  3437. } else {
  3438. itemSize = Math.floor( totalWidth * (this.contentItems[ i ].config.width / 100) );
  3439. }
  3440. totalAssigned += itemSize;
  3441. itemSizes.push( itemSize );
  3442. }
  3443. additionalPixel = Math.floor( (this._isColumn ? totalHeight : totalWidth) - totalAssigned );
  3444. return {
  3445. itemSizes: itemSizes,
  3446. additionalPixel: additionalPixel,
  3447. totalWidth: totalWidth,
  3448. totalHeight: totalHeight
  3449. };
  3450. },
  3451. /**
  3452. * Calculates the relative sizes of all children of this Item. The logic
  3453. * is as follows:
  3454. *
  3455. * - Add up the total size of all items that have a configured size
  3456. *
  3457. * - If the total == 100 (check for floating point errors)
  3458. * Excellent, job done
  3459. *
  3460. * - If the total is > 100,
  3461. * set the size of items without set dimensions to 1/3 and add this to the total
  3462. * set the size off all items so that the total is hundred relative to their original size
  3463. *
  3464. * - If the total is < 100
  3465. * If there are items without set dimensions, distribute the remainder to 100 evenly between them
  3466. * If there are no items without set dimensions, increase all items sizes relative to
  3467. * their original size so that they add up to 100
  3468. *
  3469. * @private
  3470. * @returns {void}
  3471. */
  3472. _calculateRelativeSizes: function() {
  3473. var i,
  3474. total = 0,
  3475. itemsWithoutSetDimension = [],
  3476. dimension = this._isColumn ? 'height' : 'width';
  3477. for( i = 0; i < this.contentItems.length; i++ ) {
  3478. if( this.contentItems[ i ].config[ dimension ] !== undefined ) {
  3479. total += this.contentItems[ i ].config[ dimension ];
  3480. } else {
  3481. itemsWithoutSetDimension.push( this.contentItems[ i ] );
  3482. }
  3483. }
  3484. /**
  3485. * Everything adds up to hundred, all good :-)
  3486. */
  3487. if( Math.round( total ) === 100 ) {
  3488. this._respectMinItemWidth();
  3489. return;
  3490. }
  3491. /**
  3492. * Allocate the remaining size to the items without a set dimension
  3493. */
  3494. if( Math.round( total ) < 100 && itemsWithoutSetDimension.length > 0 ) {
  3495. for( i = 0; i < itemsWithoutSetDimension.length; i++ ) {
  3496. itemsWithoutSetDimension[ i ].config[ dimension ] = ( 100 - total ) / itemsWithoutSetDimension.length;
  3497. }
  3498. this._respectMinItemWidth();
  3499. return;
  3500. }
  3501. /**
  3502. * If the total is > 100, but there are also items without a set dimension left, assing 50
  3503. * as their dimension and add it to the total
  3504. *
  3505. * This will be reset in the next step
  3506. */
  3507. if( Math.round( total ) > 100 ) {
  3508. for( i = 0; i < itemsWithoutSetDimension.length; i++ ) {
  3509. itemsWithoutSetDimension[ i ].config[ dimension ] = 50;
  3510. total += 50;
  3511. }
  3512. }
  3513. /**
  3514. * Set every items size relative to 100 relative to its size to total
  3515. */
  3516. for( i = 0; i < this.contentItems.length; i++ ) {
  3517. this.contentItems[ i ].config[ dimension ] = ( this.contentItems[ i ].config[ dimension ] / total ) * 100;
  3518. }
  3519. this._respectMinItemWidth();
  3520. },
  3521. /**
  3522. * Adjusts the column widths to respect the dimensions minItemWidth if set.
  3523. * @returns {}
  3524. */
  3525. _respectMinItemWidth: function() {
  3526. var minItemWidth = this.layoutManager.config.dimensions ? (this.layoutManager.config.dimensions.minItemWidth || 0) : 0,
  3527. sizeData = null,
  3528. entriesOverMin = [],
  3529. totalOverMin = 0,
  3530. totalUnderMin = 0,
  3531. remainingWidth = 0,
  3532. itemSize = 0,
  3533. contentItem = null,
  3534. reducePercent,
  3535. reducedWidth,
  3536. allEntries = [],
  3537. entry;
  3538. if( this._isColumn || !minItemWidth || this.contentItems.length <= 1 ) {
  3539. return;
  3540. }
  3541. sizeData = this._calculateAbsoluteSizes();
  3542. /**
  3543. * Figure out how much we are under the min item size total and how much room we have to use.
  3544. */
  3545. for( i = 0; i < this.contentItems.length; i++ ) {
  3546. contentItem = this.contentItems[ i ];
  3547. itemSize = sizeData.itemSizes[ i ];
  3548. if( itemSize < minItemWidth ) {
  3549. totalUnderMin += minItemWidth - itemSize;
  3550. entry = { width: minItemWidth };
  3551. }
  3552. else {
  3553. totalOverMin += itemSize - minItemWidth;
  3554. entry = { width: itemSize };
  3555. entriesOverMin.push( entry );
  3556. }
  3557. allEntries.push( entry );
  3558. }
  3559. /**
  3560. * If there is nothing under min, or there is not enough over to make up the difference, do nothing.
  3561. */
  3562. if( totalUnderMin === 0 || totalUnderMin > totalOverMin ) {
  3563. return;
  3564. }
  3565. /**
  3566. * Evenly reduce all columns that are over the min item width to make up the difference.
  3567. */
  3568. reducePercent = totalUnderMin / totalOverMin;
  3569. remainingWidth = totalUnderMin;
  3570. for( i = 0; i < entriesOverMin.length; i++ ) {
  3571. entry = entriesOverMin[ i ];
  3572. reducedWidth = Math.round( ( entry.width - minItemWidth ) * reducePercent );
  3573. remainingWidth -= reducedWidth;
  3574. entry.width -= reducedWidth;
  3575. }
  3576. /**
  3577. * Take anything remaining from the last item.
  3578. */
  3579. if( remainingWidth !== 0 ) {
  3580. allEntries[ allEntries.length - 1 ].width -= remainingWidth;
  3581. }
  3582. /**
  3583. * Set every items size relative to 100 relative to its size to total
  3584. */
  3585. for( i = 0; i < this.contentItems.length; i++ ) {
  3586. this.contentItems[ i ].config.width = (allEntries[ i ].width / sizeData.totalWidth) * 100;
  3587. }
  3588. },
  3589. /**
  3590. * Instantiates a new lm.controls.Splitter, binds events to it and adds
  3591. * it to the array of splitters at the position specified as the index argument
  3592. *
  3593. * What it doesn't do though is append the splitter to the DOM
  3594. *
  3595. * @param {Int} index The position of the splitter
  3596. *
  3597. * @returns {lm.controls.Splitter}
  3598. */
  3599. _createSplitter: function( index ) {
  3600. var splitter;
  3601. splitter = new lm.controls.Splitter( this._isColumn, this._splitterSize );
  3602. splitter.on( 'drag', lm.utils.fnBind( this._onSplitterDrag, this, [ splitter ] ), this );
  3603. splitter.on( 'dragStop', lm.utils.fnBind( this._onSplitterDragStop, this, [ splitter ] ), this );
  3604. splitter.on( 'dragStart', lm.utils.fnBind( this._onSplitterDragStart, this, [ splitter ] ), this );
  3605. this._splitter.splice( index, 0, splitter );
  3606. return splitter;
  3607. },
  3608. /**
  3609. * Locates the instance of lm.controls.Splitter in the array of
  3610. * registered splitters and returns a map containing the contentItem
  3611. * before and after the splitters, both of which are affected if the
  3612. * splitter is moved
  3613. *
  3614. * @param {lm.controls.Splitter} splitter
  3615. *
  3616. * @returns {Object} A map of contentItems that the splitter affects
  3617. */
  3618. _getItemsForSplitter: function( splitter ) {
  3619. var index = lm.utils.indexOf( splitter, this._splitter );
  3620. return {
  3621. before: this.contentItems[ index ],
  3622. after: this.contentItems[ index + 1 ]
  3623. };
  3624. },
  3625. /**
  3626. * Gets the minimum dimensions for the given item configuration array
  3627. * @param item
  3628. * @private
  3629. */
  3630. _getMinimumDimensions: function( arr ) {
  3631. var minWidth = 0, minHeight = 0;
  3632. for( var i = 0; i < arr.length; ++i ) {
  3633. minWidth = Math.max( arr[ i ].minWidth || 0, minWidth );
  3634. minHeight = Math.max( arr[ i ].minHeight || 0, minHeight );
  3635. }
  3636. return { horizontal: minWidth, vertical: minHeight };
  3637. },
  3638. /**
  3639. * Invoked when a splitter's dragListener fires dragStart. Calculates the splitters
  3640. * movement area once (so that it doesn't need calculating on every mousemove event)
  3641. *
  3642. * @param {lm.controls.Splitter} splitter
  3643. *
  3644. * @returns {void}
  3645. */
  3646. _onSplitterDragStart: function( splitter ) {
  3647. var items = this._getItemsForSplitter( splitter ),
  3648. minSize = this.layoutManager.config.dimensions[ this._isColumn ? 'minItemHeight' : 'minItemWidth' ];
  3649. var beforeMinDim = this._getMinimumDimensions( items.before.config.content );
  3650. var beforeMinSize = this._isColumn ? beforeMinDim.vertical : beforeMinDim.horizontal;
  3651. var afterMinDim = this._getMinimumDimensions( items.after.config.content );
  3652. var afterMinSize = this._isColumn ? afterMinDim.vertical : afterMinDim.horizontal;
  3653. this._splitterPosition = 0;
  3654. this._splitterMinPosition = -1 * ( items.before.element[ this._dimension ]() - (beforeMinSize || minSize) );
  3655. this._splitterMaxPosition = items.after.element[ this._dimension ]() - (afterMinSize || minSize);
  3656. },
  3657. /**
  3658. * Invoked when a splitter's DragListener fires drag. Updates the splitters DOM position,
  3659. * but not the sizes of the elements the splitter controls in order to minimize resize events
  3660. *
  3661. * @param {lm.controls.Splitter} splitter
  3662. * @param {Int} offsetX Relative pixel values to the splitters original position. Can be negative
  3663. * @param {Int} offsetY Relative pixel values to the splitters original position. Can be negative
  3664. *
  3665. * @returns {void}
  3666. */
  3667. _onSplitterDrag: function( splitter, offsetX, offsetY ) {
  3668. var offset = this._isColumn ? offsetY : offsetX;
  3669. if( offset > this._splitterMinPosition && offset < this._splitterMaxPosition ) {
  3670. this._splitterPosition = offset;
  3671. splitter.element.css( this._isColumn ? 'top' : 'left', offset );
  3672. }
  3673. },
  3674. /**
  3675. * Invoked when a splitter's DragListener fires dragStop. Resets the splitters DOM position,
  3676. * and applies the new sizes to the elements before and after the splitter and their children
  3677. * on the next animation frame
  3678. *
  3679. * @param {lm.controls.Splitter} splitter
  3680. *
  3681. * @returns {void}
  3682. */
  3683. _onSplitterDragStop: function( splitter ) {
  3684. var items = this._getItemsForSplitter( splitter ),
  3685. sizeBefore = items.before.element[ this._dimension ](),
  3686. sizeAfter = items.after.element[ this._dimension ](),
  3687. splitterPositionInRange = ( this._splitterPosition + sizeBefore ) / ( sizeBefore + sizeAfter ),
  3688. totalRelativeSize = items.before.config[ this._dimension ] + items.after.config[ this._dimension ];
  3689. items.before.config[ this._dimension ] = splitterPositionInRange * totalRelativeSize;
  3690. items.after.config[ this._dimension ] = ( 1 - splitterPositionInRange ) * totalRelativeSize;
  3691. splitter.element.css( {
  3692. 'top': 0,
  3693. 'left': 0
  3694. } );
  3695. lm.utils.animFrame( lm.utils.fnBind( this.callDownwards, this, [ 'setSize' ] ) );
  3696. }
  3697. } );
  3698. lm.items.Stack = function( layoutManager, config, parent ) {
  3699. lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
  3700. this.element = $( '<div class="lm_item lm_stack"></div>' );
  3701. this._activeContentItem = null;
  3702. var cfg = layoutManager.config;
  3703. this._header = { // defaults' reconstruction from old configuration style
  3704. show: cfg.settings.hasHeaders === true && config.hasHeaders !== false,
  3705. popout: cfg.settings.showPopoutIcon && cfg.labels.popout,
  3706. maximise: cfg.settings.showMaximiseIcon && cfg.labels.maximise,
  3707. close: cfg.settings.showCloseIcon && cfg.labels.close,
  3708. minimise: cfg.labels.minimise,
  3709. };
  3710. if( cfg.header ) // load simplified version of header configuration (https://github.com/deepstreamIO/golden-layout/pull/245)
  3711. lm.utils.copy( this._header, cfg.header );
  3712. if( config.header ) // load from stack
  3713. lm.utils.copy( this._header, config.header );
  3714. if( config.content && config.content[ 0 ] && config.content[ 0 ].header ) // load from component if stack omitted
  3715. lm.utils.copy( this._header, config.content[ 0 ].header );
  3716. this._dropZones = {};
  3717. this._dropSegment = null;
  3718. this._contentAreaDimensions = null;
  3719. this._dropIndex = null;
  3720. this.isStack = true;
  3721. this.childElementContainer = $( '<div class="lm_items"></div>' );
  3722. this.header = new lm.controls.Header( layoutManager, this );
  3723. this.element.append( this.header.element );
  3724. this.element.append( this.childElementContainer );
  3725. this._setupHeaderPosition();
  3726. this._$validateClosability();
  3727. };
  3728. lm.utils.extend( lm.items.Stack, lm.items.AbstractContentItem );
  3729. lm.utils.copy( lm.items.Stack.prototype, {
  3730. setSize: function() {
  3731. var i,
  3732. headerSize = this._header.show ? this.layoutManager.config.dimensions.headerHeight : 0,
  3733. contentWidth = this.element.width() - (this._sided ? headerSize : 0),
  3734. contentHeight = this.element.height() - (!this._sided ? headerSize : 0);
  3735. this.childElementContainer.width( contentWidth );
  3736. this.childElementContainer.height( contentHeight );
  3737. for( i = 0; i < this.contentItems.length; i++ ) {
  3738. this.contentItems[ i ].element.width( contentWidth ).height( contentHeight );
  3739. }
  3740. this.emit( 'resize' );
  3741. this.emitBubblingEvent( 'stateChanged' );
  3742. },
  3743. _$init: function() {
  3744. var i, initialItem;
  3745. if( this.isInitialised === true ) return;
  3746. lm.items.AbstractContentItem.prototype._$init.call( this );
  3747. for( i = 0; i < this.contentItems.length; i++ ) {
  3748. this.header.createTab( this.contentItems[ i ] );
  3749. this.contentItems[ i ]._$hide();
  3750. }
  3751. if( this.contentItems.length > 0 ) {
  3752. initialItem = this.contentItems[ this.config.activeItemIndex || 0 ];
  3753. if( !initialItem ) {
  3754. throw new Error( 'Configured activeItemIndex out of bounds' );
  3755. }
  3756. this.setActiveContentItem( initialItem );
  3757. }
  3758. },
  3759. setActiveContentItem: function( contentItem ) {
  3760. if( lm.utils.indexOf( contentItem, this.contentItems ) === -1 ) {
  3761. throw new Error( 'contentItem is not a child of this stack' );
  3762. }
  3763. if( this._activeContentItem !== null ) {
  3764. this._activeContentItem._$hide();
  3765. }
  3766. this._activeContentItem = contentItem;
  3767. this.header.setActiveContentItem( contentItem );
  3768. contentItem._$show();
  3769. this.emit( 'activeContentItemChanged', contentItem );
  3770. this.emitBubblingEvent( 'stateChanged' );
  3771. },
  3772. getActiveContentItem: function() {
  3773. return this.header.activeContentItem;
  3774. },
  3775. addChild: function( contentItem, index ) {
  3776. contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
  3777. lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index );
  3778. this.childElementContainer.append( contentItem.element );
  3779. this.header.createTab( contentItem, index );
  3780. this.setActiveContentItem( contentItem );
  3781. this.callDownwards( 'setSize' );
  3782. this._$validateClosability();
  3783. this.emitBubblingEvent( 'stateChanged' );
  3784. },
  3785. removeChild: function( contentItem, keepChild ) {
  3786. var index = lm.utils.indexOf( contentItem, this.contentItems );
  3787. var curIndex = lm.utils.indexOf( this._activeContentItem, this.contentItems );
  3788. lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild );
  3789. this.header.removeTab( contentItem );
  3790. if( this.contentItems.length > 0 ) {
  3791. var indexToFocus = index > curIndex ? curIndex : curIndex - 1;
  3792. if (curIndex == index)
  3793. indexToFocus = Math.max( index - 1, 0 );
  3794. this.setActiveContentItem( this.contentItems[ indexToFocus ] );
  3795. } else {
  3796. this._activeContentItem = null;
  3797. }
  3798. this._$validateClosability();
  3799. this.emitBubblingEvent( 'stateChanged' );
  3800. },
  3801. /**
  3802. * Validates that the stack is still closable or not. If a stack is able
  3803. * to close, but has a non closable component added to it, the stack is no
  3804. * longer closable until all components are closable.
  3805. *
  3806. * @returns {void}
  3807. */
  3808. _$validateClosability: function() {
  3809. var contentItem,
  3810. isClosable,
  3811. len,
  3812. i;
  3813. isClosable = this.header._isClosable();
  3814. for( i = 0, len = this.contentItems.length; i < len; i++ ) {
  3815. if( !isClosable ) {
  3816. break;
  3817. }
  3818. isClosable = this.contentItems[ i ].config.isClosable;
  3819. }
  3820. this.header._$setClosable( isClosable );
  3821. },
  3822. _$destroy: function() {
  3823. lm.items.AbstractContentItem.prototype._$destroy.call( this );
  3824. this.header._$destroy();
  3825. },
  3826. /**
  3827. * Ok, this one is going to be the tricky one: The user has dropped {contentItem} onto this stack.
  3828. *
  3829. * It was dropped on either the stacks header or the top, right, bottom or left bit of the content area
  3830. * (which one of those is stored in this._dropSegment). Now, if the user has dropped on the header the case
  3831. * is relatively clear: We add the item to the existing stack... job done (might be good to have
  3832. * tab reordering at some point, but lets not sweat it right now)
  3833. *
  3834. * If the item was dropped on the content part things are a bit more complicated. If it was dropped on either the
  3835. * top or bottom region we need to create a new column and place the items accordingly.
  3836. * Unless, of course if the stack is already within a column... in which case we want
  3837. * to add the newly created item to the existing column...
  3838. * either prepend or append it, depending on wether its top or bottom.
  3839. *
  3840. * Same thing for rows and left / right drop segments... so in total there are 9 things that can potentially happen
  3841. * (left, top, right, bottom) * is child of the right parent (row, column) + header drop
  3842. *
  3843. * @param {lm.item} contentItem
  3844. *
  3845. * @returns {void}
  3846. */
  3847. _$onDrop: function( contentItem ) {
  3848. /*
  3849. * The item was dropped on the header area. Just add it as a child of this stack and
  3850. * get the hell out of this logic
  3851. */
  3852. if( this._dropSegment === 'header' ) {
  3853. this._resetHeaderDropZone();
  3854. this.addChild( contentItem, this._dropIndex );
  3855. return;
  3856. }
  3857. /*
  3858. * The stack is empty. Let's just add the element.
  3859. */
  3860. if( this._dropSegment === 'body' ) {
  3861. this.addChild( contentItem );
  3862. return;
  3863. }
  3864. /*
  3865. * The item was dropped on the top-, left-, bottom- or right- part of the content. Let's
  3866. * aggregate some conditions to make the if statements later on more readable
  3867. */
  3868. var isVertical = this._dropSegment === 'top' || this._dropSegment === 'bottom',
  3869. isHorizontal = this._dropSegment === 'left' || this._dropSegment === 'right',
  3870. insertBefore = this._dropSegment === 'top' || this._dropSegment === 'left',
  3871. hasCorrectParent = ( isVertical && this.parent.isColumn ) || ( isHorizontal && this.parent.isRow ),
  3872. type = isVertical ? 'column' : 'row',
  3873. dimension = isVertical ? 'height' : 'width',
  3874. index,
  3875. stack,
  3876. rowOrColumn;
  3877. /*
  3878. * The content item can be either a component or a stack. If it is a component, wrap it into a stack
  3879. */
  3880. if( contentItem.isComponent ) {
  3881. stack = this.layoutManager.createContentItem( {
  3882. type: 'stack',
  3883. header: contentItem.config.header || {}
  3884. }, this );
  3885. stack._$init();
  3886. stack.addChild( contentItem );
  3887. contentItem = stack;
  3888. }
  3889. /*
  3890. * If the item is dropped on top or bottom of a column or left and right of a row, it's already
  3891. * layd out in the correct way. Just add it as a child
  3892. */
  3893. if( hasCorrectParent ) {
  3894. index = lm.utils.indexOf( this, this.parent.contentItems );
  3895. this.parent.addChild( contentItem, insertBefore ? index : index + 1, true );
  3896. this.config[ dimension ] *= 0.5;
  3897. contentItem.config[ dimension ] = this.config[ dimension ];
  3898. this.parent.callDownwards( 'setSize' );
  3899. /*
  3900. * This handles items that are dropped on top or bottom of a row or left / right of a column. We need
  3901. * to create the appropriate contentItem for them to live in
  3902. */
  3903. } else {
  3904. type = isVertical ? 'column' : 'row';
  3905. rowOrColumn = this.layoutManager.createContentItem( { type: type }, this );
  3906. this.parent.replaceChild( this, rowOrColumn );
  3907. rowOrColumn.addChild( contentItem, insertBefore ? 0 : undefined, true );
  3908. rowOrColumn.addChild( this, insertBefore ? undefined : 0, true );
  3909. this.config[ dimension ] = 50;
  3910. contentItem.config[ dimension ] = 50;
  3911. rowOrColumn.callDownwards( 'setSize' );
  3912. }
  3913. },
  3914. /**
  3915. * If the user hovers above the header part of the stack, indicate drop positions for tabs.
  3916. * otherwise indicate which segment of the body the dragged item would be dropped on
  3917. *
  3918. * @param {Int} x Absolute Screen X
  3919. * @param {Int} y Absolute Screen Y
  3920. *
  3921. * @returns {void}
  3922. */
  3923. _$highlightDropZone: function( x, y ) {
  3924. var segment, area;
  3925. for( segment in this._contentAreaDimensions ) {
  3926. area = this._contentAreaDimensions[ segment ].hoverArea;
  3927. if( area.x1 < x && area.x2 > x && area.y1 < y && area.y2 > y ) {
  3928. if( segment === 'header' ) {
  3929. this._dropSegment = 'header';
  3930. this._highlightHeaderDropZone( this._sided ? y : x );
  3931. } else {
  3932. this._resetHeaderDropZone();
  3933. this._highlightBodyDropZone( segment );
  3934. }
  3935. return;
  3936. }
  3937. }
  3938. },
  3939. _$getArea: function() {
  3940. if( this.element.is( ':visible' ) === false ) {
  3941. return null;
  3942. }
  3943. var getArea = lm.items.AbstractContentItem.prototype._$getArea,
  3944. headerArea = getArea.call( this, this.header.element ),
  3945. contentArea = getArea.call( this, this.childElementContainer ),
  3946. contentWidth = contentArea.x2 - contentArea.x1,
  3947. contentHeight = contentArea.y2 - contentArea.y1;
  3948. this._contentAreaDimensions = {
  3949. header: {
  3950. hoverArea: {
  3951. x1: headerArea.x1,
  3952. y1: headerArea.y1,
  3953. x2: headerArea.x2,
  3954. y2: headerArea.y2
  3955. },
  3956. highlightArea: {
  3957. x1: headerArea.x1,
  3958. y1: headerArea.y1,
  3959. x2: headerArea.x2,
  3960. y2: headerArea.y2
  3961. }
  3962. }
  3963. };
  3964. /**
  3965. * If this Stack is a parent to rows, columns or other stacks only its
  3966. * header is a valid dropzone.
  3967. */
  3968. if( this._activeContentItem && this._activeContentItem.isComponent === false ) {
  3969. return headerArea;
  3970. }
  3971. /**
  3972. * Highlight the entire body if the stack is empty
  3973. */
  3974. if( this.contentItems.length === 0 ) {
  3975. this._contentAreaDimensions.body = {
  3976. hoverArea: {
  3977. x1: contentArea.x1,
  3978. y1: contentArea.y1,
  3979. x2: contentArea.x2,
  3980. y2: contentArea.y2
  3981. },
  3982. highlightArea: {
  3983. x1: contentArea.x1,
  3984. y1: contentArea.y1,
  3985. x2: contentArea.x2,
  3986. y2: contentArea.y2
  3987. }
  3988. };
  3989. return getArea.call( this, this.element );
  3990. }
  3991. this._contentAreaDimensions.left = {
  3992. hoverArea: {
  3993. x1: contentArea.x1,
  3994. y1: contentArea.y1,
  3995. x2: contentArea.x1 + contentWidth * 0.25,
  3996. y2: contentArea.y2
  3997. },
  3998. highlightArea: {
  3999. x1: contentArea.x1,
  4000. y1: contentArea.y1,
  4001. x2: contentArea.x1 + contentWidth * 0.5,
  4002. y2: contentArea.y2
  4003. }
  4004. };
  4005. this._contentAreaDimensions.top = {
  4006. hoverArea: {
  4007. x1: contentArea.x1 + contentWidth * 0.25,
  4008. y1: contentArea.y1,
  4009. x2: contentArea.x1 + contentWidth * 0.75,
  4010. y2: contentArea.y1 + contentHeight * 0.5
  4011. },
  4012. highlightArea: {
  4013. x1: contentArea.x1,
  4014. y1: contentArea.y1,
  4015. x2: contentArea.x2,
  4016. y2: contentArea.y1 + contentHeight * 0.5
  4017. }
  4018. };
  4019. this._contentAreaDimensions.right = {
  4020. hoverArea: {
  4021. x1: contentArea.x1 + contentWidth * 0.75,
  4022. y1: contentArea.y1,
  4023. x2: contentArea.x2,
  4024. y2: contentArea.y2
  4025. },
  4026. highlightArea: {
  4027. x1: contentArea.x1 + contentWidth * 0.5,
  4028. y1: contentArea.y1,
  4029. x2: contentArea.x2,
  4030. y2: contentArea.y2
  4031. }
  4032. };
  4033. this._contentAreaDimensions.bottom = {
  4034. hoverArea: {
  4035. x1: contentArea.x1 + contentWidth * 0.25,
  4036. y1: contentArea.y1 + contentHeight * 0.5,
  4037. x2: contentArea.x1 + contentWidth * 0.75,
  4038. y2: contentArea.y2
  4039. },
  4040. highlightArea: {
  4041. x1: contentArea.x1,
  4042. y1: contentArea.y1 + contentHeight * 0.5,
  4043. x2: contentArea.x2,
  4044. y2: contentArea.y2
  4045. }
  4046. };
  4047. return getArea.call( this, this.element );
  4048. },
  4049. _highlightHeaderDropZone: function( x ) {
  4050. var i,
  4051. tabElement,
  4052. tabsLength = this.header.tabs.length,
  4053. isAboveTab = false,
  4054. tabTop,
  4055. tabLeft,
  4056. offset,
  4057. placeHolderLeft,
  4058. headerOffset,
  4059. tabWidth,
  4060. halfX;
  4061. // Empty stack
  4062. if( tabsLength === 0 ) {
  4063. headerOffset = this.header.element.offset();
  4064. this.layoutManager.dropTargetIndicator.highlightArea( {
  4065. x1: headerOffset.left,
  4066. x2: headerOffset.left + 100,
  4067. y1: headerOffset.top + this.header.element.height() - 20,
  4068. y2: headerOffset.top + this.header.element.height()
  4069. } );
  4070. return;
  4071. }
  4072. for( i = 0; i < tabsLength; i++ ) {
  4073. tabElement = this.header.tabs[ i ].element;
  4074. offset = tabElement.offset();
  4075. if( this._sided ) {
  4076. tabLeft = offset.top;
  4077. tabTop = offset.left;
  4078. tabWidth = tabElement.height();
  4079. } else {
  4080. tabLeft = offset.left;
  4081. tabTop = offset.top;
  4082. tabWidth = tabElement.width();
  4083. }
  4084. if( x > tabLeft && x < tabLeft + tabWidth ) {
  4085. isAboveTab = true;
  4086. break;
  4087. }
  4088. }
  4089. if( isAboveTab === false && x < tabLeft ) {
  4090. return;
  4091. }
  4092. halfX = tabLeft + tabWidth / 2;
  4093. if( x < halfX ) {
  4094. this._dropIndex = i;
  4095. tabElement.before( this.layoutManager.tabDropPlaceholder );
  4096. } else {
  4097. this._dropIndex = Math.min( i + 1, tabsLength );
  4098. tabElement.after( this.layoutManager.tabDropPlaceholder );
  4099. }
  4100. if( this._sided ) {
  4101. placeHolderTop = this.layoutManager.tabDropPlaceholder.offset().top;
  4102. this.layoutManager.dropTargetIndicator.highlightArea( {
  4103. x1: tabTop,
  4104. x2: tabTop + tabElement.innerHeight(),
  4105. y1: placeHolderTop,
  4106. y2: placeHolderTop + this.layoutManager.tabDropPlaceholder.width()
  4107. } );
  4108. return;
  4109. }
  4110. placeHolderLeft = this.layoutManager.tabDropPlaceholder.offset().left;
  4111. this.layoutManager.dropTargetIndicator.highlightArea( {
  4112. x1: placeHolderLeft,
  4113. x2: placeHolderLeft + this.layoutManager.tabDropPlaceholder.width(),
  4114. y1: tabTop,
  4115. y2: tabTop + tabElement.innerHeight()
  4116. } );
  4117. },
  4118. _resetHeaderDropZone: function() {
  4119. this.layoutManager.tabDropPlaceholder.remove();
  4120. },
  4121. _setupHeaderPosition: function() {
  4122. var side = [ 'right', 'left', 'bottom' ].indexOf( this._header.show ) >= 0 && this._header.show;
  4123. this.header.element.toggle( !!this._header.show );
  4124. this._side = side;
  4125. this._sided = [ 'right', 'left' ].indexOf( this._side ) >= 0;
  4126. this.element.removeClass( 'lm_left lm_right lm_bottom' );
  4127. if( this._side )
  4128. this.element.addClass( 'lm_' + this._side );
  4129. if( this.element.find( '.lm_header' ).length && this.childElementContainer ) {
  4130. var headerPosition = [ 'right', 'bottom' ].indexOf( this._side ) >= 0 ? 'before' : 'after';
  4131. this.header.element[ headerPosition ]( this.childElementContainer );
  4132. this.callDownwards( 'setSize' );
  4133. }
  4134. },
  4135. _highlightBodyDropZone: function( segment ) {
  4136. var highlightArea = this._contentAreaDimensions[ segment ].highlightArea;
  4137. this.layoutManager.dropTargetIndicator.highlightArea( highlightArea );
  4138. this._dropSegment = segment;
  4139. }
  4140. } );
  4141. lm.utils.BubblingEvent = function( name, origin ) {
  4142. this.name = name;
  4143. this.origin = origin;
  4144. this.isPropagationStopped = false;
  4145. };
  4146. lm.utils.BubblingEvent.prototype.stopPropagation = function() {
  4147. this.isPropagationStopped = true;
  4148. };
  4149. /**
  4150. * Minifies and unminifies configs by replacing frequent keys
  4151. * and values with one letter substitutes
  4152. *
  4153. * @constructor
  4154. */
  4155. lm.utils.ConfigMinifier = function() {
  4156. this._keys = [
  4157. 'settings',
  4158. 'hasHeaders',
  4159. 'constrainDragToContainer',
  4160. 'constrainDragToHeader',
  4161. 'selectionEnabled',
  4162. 'dimensions',
  4163. 'borderWidth',
  4164. 'minItemHeight',
  4165. 'minItemWidth',
  4166. 'headerHeight',
  4167. 'dragProxyWidth',
  4168. 'dragProxyHeight',
  4169. 'labels',
  4170. 'close',
  4171. 'maximise',
  4172. 'minimise',
  4173. 'popout',
  4174. 'content',
  4175. 'componentName',
  4176. 'componentState',
  4177. 'id',
  4178. 'width',
  4179. 'type',
  4180. 'height',
  4181. 'isClosable',
  4182. 'title',
  4183. 'popoutWholeStack',
  4184. 'openPopouts',
  4185. 'parentId',
  4186. 'activeItemIndex',
  4187. 'reorderEnabled'
  4188. //Maximum 36 entries, do not cross this line!
  4189. ];
  4190. this._values = [
  4191. true,
  4192. false,
  4193. 'row',
  4194. 'column',
  4195. 'stack',
  4196. 'component',
  4197. 'close',
  4198. 'maximise',
  4199. 'minimise',
  4200. 'open in new window'
  4201. ];
  4202. };
  4203. lm.utils.copy( lm.utils.ConfigMinifier.prototype, {
  4204. /**
  4205. * Takes a GoldenLayout configuration object and
  4206. * replaces its keys and values recursively with
  4207. * one letter counterparts
  4208. *
  4209. * @param {Object} config A GoldenLayout config object
  4210. *
  4211. * @returns {Object} minified config
  4212. */
  4213. minifyConfig: function( config ) {
  4214. var min = {};
  4215. this._nextLevel( config, min, '_min' );
  4216. return min;
  4217. },
  4218. /**
  4219. * Takes a configuration Object that was previously minified
  4220. * using minifyConfig and returns its original version
  4221. *
  4222. * @param {Object} minifiedConfig
  4223. *
  4224. * @returns {Object} the original configuration
  4225. */
  4226. unminifyConfig: function( minifiedConfig ) {
  4227. var orig = {};
  4228. this._nextLevel( minifiedConfig, orig, '_max' );
  4229. return orig;
  4230. },
  4231. /**
  4232. * Recursive function, called for every level of the config structure
  4233. *
  4234. * @param {Array|Object} orig
  4235. * @param {Array|Object} min
  4236. * @param {String} translationFn
  4237. *
  4238. * @returns {void}
  4239. */
  4240. _nextLevel: function( from, to, translationFn ) {
  4241. var key, minKey;
  4242. for( key in from ) {
  4243. /**
  4244. * For in returns array indices as keys, so let's cast them to numbers
  4245. */
  4246. if( from instanceof Array ) key = parseInt( key, 10 );
  4247. /**
  4248. * In case something has extended Object prototypes
  4249. */
  4250. if( !from.hasOwnProperty( key ) ) continue;
  4251. /**
  4252. * Translate the key to a one letter substitute
  4253. */
  4254. minKey = this[ translationFn ]( key, this._keys );
  4255. /**
  4256. * For Arrays and Objects, create a new Array/Object
  4257. * on the minified object and recurse into it
  4258. */
  4259. if( typeof from[ key ] === 'object' ) {
  4260. to[ minKey ] = from[ key ] instanceof Array ? [] : {};
  4261. this._nextLevel( from[ key ], to[ minKey ], translationFn );
  4262. /**
  4263. * For primitive values (Strings, Numbers, Boolean etc.)
  4264. * minify the value
  4265. */
  4266. } else {
  4267. to[ minKey ] = this[ translationFn ]( from[ key ], this._values );
  4268. }
  4269. }
  4270. },
  4271. /**
  4272. * Minifies value based on a dictionary
  4273. *
  4274. * @param {String|Boolean} value
  4275. * @param {Array<String|Boolean>} dictionary
  4276. *
  4277. * @returns {String} The minified version
  4278. */
  4279. _min: function( value, dictionary ) {
  4280. /**
  4281. * If a value actually is a single character, prefix it
  4282. * with ___ to avoid mistaking it for a minification code
  4283. */
  4284. if( typeof value === 'string' && value.length === 1 ) {
  4285. return '___' + value;
  4286. }
  4287. var index = lm.utils.indexOf( value, dictionary );
  4288. /**
  4289. * value not found in the dictionary, return it unmodified
  4290. */
  4291. if( index === -1 ) {
  4292. return value;
  4293. /**
  4294. * value found in dictionary, return its base36 counterpart
  4295. */
  4296. } else {
  4297. return index.toString( 36 );
  4298. }
  4299. },
  4300. _max: function( value, dictionary ) {
  4301. /**
  4302. * value is a single character. Assume that it's a translation
  4303. * and return the original value from the dictionary
  4304. */
  4305. if( typeof value === 'string' && value.length === 1 ) {
  4306. return dictionary[ parseInt( value, 36 ) ];
  4307. }
  4308. /**
  4309. * value originally was a single character and was prefixed with ___
  4310. * to avoid mistaking it for a translation. Remove the prefix
  4311. * and return the original character
  4312. */
  4313. if( typeof value === 'string' && value.substr( 0, 3 ) === '___' ) {
  4314. return value[ 3 ];
  4315. }
  4316. /**
  4317. * value was not minified
  4318. */
  4319. return value;
  4320. }
  4321. } );
  4322. /**
  4323. * An EventEmitter singleton that propagates events
  4324. * across multiple windows. This is a little bit trickier since
  4325. * windows are allowed to open childWindows in their own right
  4326. *
  4327. * This means that we deal with a tree of windows. Hence the rules for event propagation are:
  4328. *
  4329. * - Propagate events from this layout to both parents and children
  4330. * - Propagate events from parent to this and children
  4331. * - Propagate events from children to the other children (but not the emitting one) and the parent
  4332. *
  4333. * @constructor
  4334. *
  4335. * @param {lm.LayoutManager} layoutManager
  4336. */
  4337. lm.utils.EventHub = function( layoutManager ) {
  4338. lm.utils.EventEmitter.call( this );
  4339. this._layoutManager = layoutManager;
  4340. this._dontPropagateToParent = null;
  4341. this._childEventSource = null;
  4342. this.on( lm.utils.EventEmitter.ALL_EVENT, lm.utils.fnBind( this._onEventFromThis, this ) );
  4343. this._boundOnEventFromChild = lm.utils.fnBind( this._onEventFromChild, this );
  4344. $( window ).on( 'gl_child_event', this._boundOnEventFromChild );
  4345. };
  4346. /**
  4347. * Called on every event emitted on this eventHub, regardles of origin.
  4348. *
  4349. * @private
  4350. *
  4351. * @param {Mixed}
  4352. *
  4353. * @returns {void}
  4354. */
  4355. lm.utils.EventHub.prototype._onEventFromThis = function() {
  4356. var args = Array.prototype.slice.call( arguments );
  4357. if( this._layoutManager.isSubWindow && args[ 0 ] !== this._dontPropagateToParent ) {
  4358. this._propagateToParent( args );
  4359. }
  4360. this._propagateToChildren( args );
  4361. //Reset
  4362. this._dontPropagateToParent = null;
  4363. this._childEventSource = null;
  4364. };
  4365. /**
  4366. * Called by the parent layout.
  4367. *
  4368. * @param {Array} args Event name + arguments
  4369. *
  4370. * @returns {void}
  4371. */
  4372. lm.utils.EventHub.prototype._$onEventFromParent = function( args ) {
  4373. this._dontPropagateToParent = args[ 0 ];
  4374. this.emit.apply( this, args );
  4375. };
  4376. /**
  4377. * Callback for child events raised on the window
  4378. *
  4379. * @param {DOMEvent} event
  4380. * @private
  4381. *
  4382. * @returns {void}
  4383. */
  4384. lm.utils.EventHub.prototype._onEventFromChild = function( event ) {
  4385. this._childEventSource = event.originalEvent.__gl;
  4386. this.emit.apply( this, event.originalEvent.__glArgs );
  4387. };
  4388. /**
  4389. * Propagates the event to the parent by emitting
  4390. * it on the parent's DOM window
  4391. *
  4392. * @param {Array} args Event name + arguments
  4393. * @private
  4394. *
  4395. * @returns {void}
  4396. */
  4397. lm.utils.EventHub.prototype._propagateToParent = function( args ) {
  4398. var event,
  4399. eventName = 'gl_child_event';
  4400. if( document.createEvent ) {
  4401. event = window.opener.document.createEvent( 'HTMLEvents' );
  4402. event.initEvent( eventName, true, true );
  4403. } else {
  4404. event = window.opener.document.createEventObject();
  4405. event.eventType = eventName;
  4406. }
  4407. event.eventName = eventName;
  4408. event.__glArgs = args;
  4409. event.__gl = this._layoutManager;
  4410. if( document.createEvent ) {
  4411. window.opener.dispatchEvent( event );
  4412. } else {
  4413. window.opener.fireEvent( 'on' + event.eventType, event );
  4414. }
  4415. };
  4416. /**
  4417. * Propagate events to children
  4418. *
  4419. * @param {Array} args Event name + arguments
  4420. * @private
  4421. *
  4422. * @returns {void}
  4423. */
  4424. lm.utils.EventHub.prototype._propagateToChildren = function( args ) {
  4425. var childGl, i;
  4426. for( i = 0; i < this._layoutManager.openPopouts.length; i++ ) {
  4427. childGl = this._layoutManager.openPopouts[ i ].getGlInstance();
  4428. if( childGl && childGl !== this._childEventSource ) {
  4429. childGl.eventHub._$onEventFromParent( args );
  4430. }
  4431. }
  4432. };
  4433. /**
  4434. * Destroys the EventHub
  4435. *
  4436. * @public
  4437. * @returns {void}
  4438. */
  4439. lm.utils.EventHub.prototype.destroy = function() {
  4440. $( window ).off( 'gl_child_event', this._boundOnEventFromChild );
  4441. };
  4442. /**
  4443. * A specialised GoldenLayout component that binds GoldenLayout container
  4444. * lifecycle events to react components
  4445. *
  4446. * @constructor
  4447. *
  4448. * @param {lm.container.ItemContainer} container
  4449. * @param {Object} state state is not required for react components
  4450. */
  4451. lm.utils.ReactComponentHandler = function( container, state ) {
  4452. this._reactComponent = null;
  4453. this._originalComponentWillUpdate = null;
  4454. this._container = container;
  4455. this._initialState = state;
  4456. this._reactClass = this._getReactClass();
  4457. this._container.on( 'open', this._render, this );
  4458. this._container.on( 'destroy', this._destroy, this );
  4459. };
  4460. lm.utils.copy( lm.utils.ReactComponentHandler.prototype, {
  4461. /**
  4462. * Creates the react class and component and hydrates it with
  4463. * the initial state - if one is present
  4464. *
  4465. * By default, react's getInitialState will be used
  4466. *
  4467. * @private
  4468. * @returns {void}
  4469. */
  4470. _render: function() {
  4471. this._reactComponent = ReactDOM.render( this._getReactComponent(), this._container.getElement()[ 0 ] );
  4472. this._originalComponentWillUpdate = this._reactComponent.componentWillUpdate || function() {
  4473. };
  4474. this._reactComponent.componentWillUpdate = this._onUpdate.bind( this );
  4475. if( this._container.getState() ) {
  4476. this._reactComponent.setState( this._container.getState() );
  4477. }
  4478. },
  4479. /**
  4480. * Removes the component from the DOM and thus invokes React's unmount lifecycle
  4481. *
  4482. * @private
  4483. * @returns {void}
  4484. */
  4485. _destroy: function() {
  4486. ReactDOM.unmountComponentAtNode( this._container.getElement()[ 0 ] );
  4487. this._container.off( 'open', this._render, this );
  4488. this._container.off( 'destroy', this._destroy, this );
  4489. },
  4490. /**
  4491. * Hooks into React's state management and applies the componentstate
  4492. * to GoldenLayout
  4493. *
  4494. * @private
  4495. * @returns {void}
  4496. */
  4497. _onUpdate: function( nextProps, nextState ) {
  4498. this._container.setState( nextState );
  4499. this._originalComponentWillUpdate.call( this._reactComponent, nextProps, nextState );
  4500. },
  4501. /**
  4502. * Retrieves the react class from GoldenLayout's registry
  4503. *
  4504. * @private
  4505. * @returns {React.Class}
  4506. */
  4507. _getReactClass: function() {
  4508. var componentName = this._container._config.component;
  4509. var reactClass;
  4510. if( !componentName ) {
  4511. throw new Error( 'No react component name. type: react-component needs a field `component`' );
  4512. }
  4513. reactClass = this._container.layoutManager.getComponent( componentName );
  4514. if( !reactClass ) {
  4515. throw new Error( 'React component "' + componentName + '" not found. ' +
  4516. 'Please register all components with GoldenLayout using `registerComponent(name, component)`' );
  4517. }
  4518. return reactClass;
  4519. },
  4520. /**
  4521. * Copies and extends the properties array and returns the React element
  4522. *
  4523. * @private
  4524. * @returns {React.Element}
  4525. */
  4526. _getReactComponent: function() {
  4527. var defaultProps = {
  4528. glEventHub: this._container.layoutManager.eventHub,
  4529. glContainer: this._container,
  4530. };
  4531. var props = $.extend( defaultProps, this._container._config.props );
  4532. return React.createElement( this._reactClass, props );
  4533. }
  4534. } );})(window.$);