jquery.gridster.min.js 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991
  1. /*! gridster.js - v0.5.6 - 2014-09-25
  2. * http://gridster.net/
  3. * Copyright (c) 2014 ducksboard; Licensed MIT */
  4. ;(function(root, factory) {
  5. if (typeof define === 'function' && define.amd) {
  6. define('gridster-coords', ['jquery'], factory);
  7. } else {
  8. root.GridsterCoords = factory(root.$ || root.jQuery);
  9. }
  10. }(this, function($) {
  11. /**
  12. * Creates objects with coordinates (x1, y1, x2, y2, cx, cy, width, height)
  13. * to simulate DOM elements on the screen.
  14. * Coords is used by Gridster to create a faux grid with any DOM element can
  15. * collide.
  16. *
  17. * @class Coords
  18. * @param {HTMLElement|Object} obj The jQuery HTMLElement or a object with: left,
  19. * top, width and height properties.
  20. * @return {Object} Coords instance.
  21. * @constructor
  22. */
  23. function Coords(obj) {
  24. if (obj[0] && $.isPlainObject(obj[0])) {
  25. this.data = obj[0];
  26. }else {
  27. this.el = obj;
  28. }
  29. this.isCoords = true;
  30. this.coords = {};
  31. this.init();
  32. return this;
  33. }
  34. var fn = Coords.prototype;
  35. fn.init = function(){
  36. this.set();
  37. this.original_coords = this.get();
  38. };
  39. fn.set = function(update, not_update_offsets) {
  40. var el = this.el;
  41. if (el && !update) {
  42. this.data = el.offset();
  43. this.data.width = el.width();
  44. this.data.height = el.height();
  45. }
  46. if (el && update && !not_update_offsets) {
  47. var offset = el.offset();
  48. this.data.top = offset.top;
  49. this.data.left = offset.left;
  50. }
  51. var d = this.data;
  52. typeof d.left === 'undefined' && (d.left = d.x1);
  53. typeof d.top === 'undefined' && (d.top = d.y1);
  54. this.coords.x1 = d.left;
  55. this.coords.y1 = d.top;
  56. this.coords.x2 = d.left + d.width;
  57. this.coords.y2 = d.top + d.height;
  58. this.coords.cx = d.left + (d.width / 2);
  59. this.coords.cy = d.top + (d.height / 2);
  60. this.coords.width = d.width;
  61. this.coords.height = d.height;
  62. this.coords.el = el || false ;
  63. return this;
  64. };
  65. fn.update = function(data){
  66. if (!data && !this.el) {
  67. return this;
  68. }
  69. if (data) {
  70. var new_data = $.extend({}, this.data, data);
  71. this.data = new_data;
  72. return this.set(true, true);
  73. }
  74. this.set(true);
  75. return this;
  76. };
  77. fn.get = function(){
  78. return this.coords;
  79. };
  80. fn.destroy = function() {
  81. this.el.removeData('coords');
  82. delete this.el;
  83. };
  84. //jQuery adapter
  85. $.fn.coords = function() {
  86. if (this.data('coords') ) {
  87. return this.data('coords');
  88. }
  89. var ins = new Coords(this, arguments[0]);
  90. this.data('coords', ins);
  91. return ins;
  92. };
  93. return Coords;
  94. }));
  95. ;(function(root, factory) {
  96. if (typeof define === 'function' && define.amd) {
  97. define('gridster-collision', ['jquery', 'gridster-coords'], factory);
  98. } else {
  99. root.GridsterCollision = factory(root.$ || root.jQuery,
  100. root.GridsterCoords);
  101. }
  102. }(this, function($, Coords) {
  103. var defaults = {
  104. colliders_context: document.body,
  105. overlapping_region: 'C'
  106. // ,on_overlap: function(collider_data){},
  107. // on_overlap_start : function(collider_data){},
  108. // on_overlap_stop : function(collider_data){}
  109. };
  110. /**
  111. * Detects collisions between a DOM element against other DOM elements or
  112. * Coords objects.
  113. *
  114. * @class Collision
  115. * @uses Coords
  116. * @param {HTMLElement} el The jQuery wrapped HTMLElement.
  117. * @param {HTMLElement|Array} colliders Can be a jQuery collection
  118. * of HTMLElements or an Array of Coords instances.
  119. * @param {Object} [options] An Object with all options you want to
  120. * overwrite:
  121. * @param {String} [options.overlapping_region] Determines when collision
  122. * is valid, depending on the overlapped area. Values can be: 'N', 'S',
  123. * 'W', 'E', 'C' or 'all'. Default is 'C'.
  124. * @param {Function} [options.on_overlap_start] Executes a function the first
  125. * time each `collider ` is overlapped.
  126. * @param {Function} [options.on_overlap_stop] Executes a function when a
  127. * `collider` is no longer collided.
  128. * @param {Function} [options.on_overlap] Executes a function when the
  129. * mouse is moved during the collision.
  130. * @return {Object} Collision instance.
  131. * @constructor
  132. */
  133. function Collision(el, colliders, options) {
  134. this.options = $.extend(defaults, options);
  135. this.$element = el;
  136. this.last_colliders = [];
  137. this.last_colliders_coords = [];
  138. this.set_colliders(colliders);
  139. this.init();
  140. }
  141. Collision.defaults = defaults;
  142. var fn = Collision.prototype;
  143. fn.init = function() {
  144. this.find_collisions();
  145. };
  146. fn.overlaps = function(a, b) {
  147. var x = false;
  148. var y = false;
  149. if ((b.x1 >= a.x1 && b.x1 <= a.x2) ||
  150. (b.x2 >= a.x1 && b.x2 <= a.x2) ||
  151. (a.x1 >= b.x1 && a.x2 <= b.x2)
  152. ) { x = true; }
  153. if ((b.y1 >= a.y1 && b.y1 <= a.y2) ||
  154. (b.y2 >= a.y1 && b.y2 <= a.y2) ||
  155. (a.y1 >= b.y1 && a.y2 <= b.y2)
  156. ) { y = true; }
  157. return (x && y);
  158. };
  159. fn.detect_overlapping_region = function(a, b){
  160. var regionX = '';
  161. var regionY = '';
  162. if (a.y1 > b.cy && a.y1 < b.y2) { regionX = 'N'; }
  163. if (a.y2 > b.y1 && a.y2 < b.cy) { regionX = 'S'; }
  164. if (a.x1 > b.cx && a.x1 < b.x2) { regionY = 'W'; }
  165. if (a.x2 > b.x1 && a.x2 < b.cx) { regionY = 'E'; }
  166. return (regionX + regionY) || 'C';
  167. };
  168. fn.calculate_overlapped_area_coords = function(a, b){
  169. var x1 = Math.max(a.x1, b.x1);
  170. var y1 = Math.max(a.y1, b.y1);
  171. var x2 = Math.min(a.x2, b.x2);
  172. var y2 = Math.min(a.y2, b.y2);
  173. return $({
  174. left: x1,
  175. top: y1,
  176. width : (x2 - x1),
  177. height: (y2 - y1)
  178. }).coords().get();
  179. };
  180. fn.calculate_overlapped_area = function(coords){
  181. return (coords.width * coords.height);
  182. };
  183. fn.manage_colliders_start_stop = function(new_colliders_coords, start_callback, stop_callback){
  184. var last = this.last_colliders_coords;
  185. for (var i = 0, il = last.length; i < il; i++) {
  186. if ($.inArray(last[i], new_colliders_coords) === -1) {
  187. start_callback.call(this, last[i]);
  188. }
  189. }
  190. for (var j = 0, jl = new_colliders_coords.length; j < jl; j++) {
  191. if ($.inArray(new_colliders_coords[j], last) === -1) {
  192. stop_callback.call(this, new_colliders_coords[j]);
  193. }
  194. }
  195. };
  196. fn.find_collisions = function(player_data_coords){
  197. var self = this;
  198. var overlapping_region = this.options.overlapping_region;
  199. var colliders_coords = [];
  200. var colliders_data = [];
  201. var $colliders = (this.colliders || this.$colliders);
  202. var count = $colliders.length;
  203. var player_coords = self.$element.coords()
  204. .update(player_data_coords || false).get();
  205. while(count--){
  206. var $collider = self.$colliders ?
  207. $($colliders[count]) : $colliders[count];
  208. var $collider_coords_ins = ($collider.isCoords) ?
  209. $collider : $collider.coords();
  210. var collider_coords = $collider_coords_ins.get();
  211. var overlaps = self.overlaps(player_coords, collider_coords);
  212. if (!overlaps) {
  213. continue;
  214. }
  215. var region = self.detect_overlapping_region(
  216. player_coords, collider_coords);
  217. //todo: make this an option
  218. if (region === overlapping_region || overlapping_region === 'all') {
  219. var area_coords = self.calculate_overlapped_area_coords(
  220. player_coords, collider_coords);
  221. var area = self.calculate_overlapped_area(area_coords);
  222. var collider_data = {
  223. area: area,
  224. area_coords : area_coords,
  225. region: region,
  226. coords: collider_coords,
  227. player_coords: player_coords,
  228. el: $collider
  229. };
  230. if (self.options.on_overlap) {
  231. self.options.on_overlap.call(this, collider_data);
  232. }
  233. colliders_coords.push($collider_coords_ins);
  234. colliders_data.push(collider_data);
  235. }
  236. }
  237. if (self.options.on_overlap_stop || self.options.on_overlap_start) {
  238. this.manage_colliders_start_stop(colliders_coords,
  239. self.options.on_overlap_start, self.options.on_overlap_stop);
  240. }
  241. this.last_colliders_coords = colliders_coords;
  242. return colliders_data;
  243. };
  244. fn.get_closest_colliders = function(player_data_coords){
  245. var colliders = this.find_collisions(player_data_coords);
  246. colliders.sort(function(a, b) {
  247. /* if colliders are being overlapped by the "C" (center) region,
  248. * we have to set a lower index in the array to which they are placed
  249. * above in the grid. */
  250. if (a.region === 'C' && b.region === 'C') {
  251. if (a.coords.y1 < b.coords.y1 || a.coords.x1 < b.coords.x1) {
  252. return - 1;
  253. }else{
  254. return 1;
  255. }
  256. }
  257. if (a.area < b.area) {
  258. return 1;
  259. }
  260. return 1;
  261. });
  262. return colliders;
  263. };
  264. fn.set_colliders = function(colliders) {
  265. if (typeof colliders === 'string' || colliders instanceof $) {
  266. this.$colliders = $(colliders,
  267. this.options.colliders_context).not(this.$element);
  268. }else{
  269. this.colliders = $(colliders);
  270. }
  271. };
  272. //jQuery adapter
  273. $.fn.collision = function(collider, options) {
  274. return new Collision( this, collider, options );
  275. };
  276. return Collision;
  277. }));
  278. ;(function(window, undefined) {
  279. /* Delay, debounce and throttle functions taken from underscore.js
  280. *
  281. * Copyright (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and
  282. * Investigative Reporters & Editors
  283. *
  284. * Permission is hereby granted, free of charge, to any person
  285. * obtaining a copy of this software and associated documentation
  286. * files (the "Software"), to deal in the Software without
  287. * restriction, including without limitation the rights to use,
  288. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  289. * copies of the Software, and to permit persons to whom the
  290. * Software is furnished to do so, subject to the following
  291. * conditions:
  292. *
  293. * The above copyright notice and this permission notice shall be
  294. * included in all copies or substantial portions of the Software.
  295. *
  296. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  297. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  298. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  299. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  300. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  301. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  302. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  303. * OTHER DEALINGS IN THE SOFTWARE.
  304. */
  305. window.delay = function(func, wait) {
  306. var args = Array.prototype.slice.call(arguments, 2);
  307. return setTimeout(function(){ return func.apply(null, args); }, wait);
  308. };
  309. window.debounce = function(func, wait, immediate) {
  310. var timeout;
  311. return function() {
  312. var context = this, args = arguments;
  313. var later = function() {
  314. timeout = null;
  315. if (!immediate) func.apply(context, args);
  316. };
  317. if (immediate && !timeout) func.apply(context, args);
  318. clearTimeout(timeout);
  319. timeout = setTimeout(later, wait);
  320. };
  321. };
  322. window.throttle = function(func, wait) {
  323. var context, args, timeout, throttling, more, result;
  324. var whenDone = debounce(
  325. function(){ more = throttling = false; }, wait);
  326. return function() {
  327. context = this; args = arguments;
  328. var later = function() {
  329. timeout = null;
  330. if (more) func.apply(context, args);
  331. whenDone();
  332. };
  333. if (!timeout) timeout = setTimeout(later, wait);
  334. if (throttling) {
  335. more = true;
  336. } else {
  337. result = func.apply(context, args);
  338. }
  339. whenDone();
  340. throttling = true;
  341. return result;
  342. };
  343. };
  344. })(window);
  345. ;(function(root, factory) {
  346. if (typeof define === 'function' && define.amd) {
  347. define('gridster-draggable', ['jquery'], factory);
  348. } else {
  349. root.GridsterDraggable = factory(root.$ || root.jQuery);
  350. }
  351. }(this, function($) {
  352. var defaults = {
  353. items: 'li',
  354. distance: 1,
  355. limit: true,
  356. offset_left: 0,
  357. autoscroll: true,
  358. ignore_dragging: ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON'], // or function
  359. handle: null,
  360. container_width: 0, // 0 == auto
  361. move_element: true,
  362. helper: false, // or 'clone'
  363. remove_helper: true
  364. // drag: function(e) {},
  365. // start : function(e, ui) {},
  366. // stop : function(e) {}
  367. };
  368. var $window = $(window);
  369. var dir_map = { x : 'left', y : 'top' };
  370. var isTouch = !!('ontouchstart' in window);
  371. var capitalize = function(str) {
  372. return str.charAt(0).toUpperCase() + str.slice(1);
  373. };
  374. var idCounter = 0;
  375. var uniqId = function() {
  376. return ++idCounter + '';
  377. }
  378. /**
  379. * Basic drag implementation for DOM elements inside a container.
  380. * Provide start/stop/drag callbacks.
  381. *
  382. * @class Draggable
  383. * @param {HTMLElement} el The HTMLelement that contains all the widgets
  384. * to be dragged.
  385. * @param {Object} [options] An Object with all options you want to
  386. * overwrite:
  387. * @param {HTMLElement|String} [options.items] Define who will
  388. * be the draggable items. Can be a CSS Selector String or a
  389. * collection of HTMLElements.
  390. * @param {Number} [options.distance] Distance in pixels after mousedown
  391. * the mouse must move before dragging should start.
  392. * @param {Boolean} [options.limit] Constrains dragging to the width of
  393. * the container
  394. * @param {Object|Function} [options.ignore_dragging] Array of node names
  395. * that sould not trigger dragging, by default is `['INPUT', 'TEXTAREA',
  396. * 'SELECT', 'BUTTON']`. If a function is used return true to ignore dragging.
  397. * @param {offset_left} [options.offset_left] Offset added to the item
  398. * that is being dragged.
  399. * @param {Number} [options.drag] Executes a callback when the mouse is
  400. * moved during the dragging.
  401. * @param {Number} [options.start] Executes a callback when the drag
  402. * starts.
  403. * @param {Number} [options.stop] Executes a callback when the drag stops.
  404. * @return {Object} Returns `el`.
  405. * @constructor
  406. */
  407. function Draggable(el, options) {
  408. this.options = $.extend({}, defaults, options);
  409. this.$document = $(document);
  410. this.$container = $(el);
  411. this.$dragitems = $(this.options.items, this.$container);
  412. this.is_dragging = false;
  413. this.player_min_left = 0 + this.options.offset_left;
  414. this.id = uniqId();
  415. this.ns = '.gridster-draggable-' + this.id;
  416. this.init();
  417. }
  418. Draggable.defaults = defaults;
  419. var fn = Draggable.prototype;
  420. fn.init = function() {
  421. var pos = this.$container.css('position');
  422. this.calculate_dimensions();
  423. this.$container.css('position', pos === 'static' ? 'relative' : pos);
  424. this.disabled = false;
  425. this.events();
  426. $(window).bind(this.nsEvent('resize'),
  427. throttle($.proxy(this.calculate_dimensions, this), 200));
  428. };
  429. fn.nsEvent = function(ev) {
  430. return (ev || '') + this.ns;
  431. };
  432. fn.events = function() {
  433. this.pointer_events = {
  434. start: this.nsEvent('touchstart') + ' ' + this.nsEvent('mousedown'),
  435. move: this.nsEvent('touchmove') + ' ' + this.nsEvent('mousemove'),
  436. end: this.nsEvent('touchend') + ' ' + this.nsEvent('mouseup')
  437. };
  438. this.$container.on(this.nsEvent('selectstart'),
  439. $.proxy(this.on_select_start, this));
  440. this.$container.on(this.pointer_events.start, this.options.items,
  441. $.proxy(this.drag_handler, this));
  442. this.$document.on(this.pointer_events.end, $.proxy(function(e) {
  443. this.is_dragging = false;
  444. if (this.disabled) { return; }
  445. this.$document.off(this.pointer_events.move);
  446. if (this.drag_start) {
  447. this.on_dragstop(e);
  448. }
  449. }, this));
  450. };
  451. fn.get_actual_pos = function($el) {
  452. var pos = $el.position();
  453. return pos;
  454. };
  455. fn.get_mouse_pos = function(e) {
  456. if (e.originalEvent && e.originalEvent.touches) {
  457. var oe = e.originalEvent;
  458. e = oe.touches.length ? oe.touches[0] : oe.changedTouches[0];
  459. }
  460. return {
  461. left: e.clientX,
  462. top: e.clientY
  463. };
  464. };
  465. fn.get_offset = function(e) {
  466. e.preventDefault();
  467. var mouse_actual_pos = this.get_mouse_pos(e);
  468. var diff_x = Math.round(
  469. mouse_actual_pos.left - this.mouse_init_pos.left);
  470. var diff_y = Math.round(mouse_actual_pos.top - this.mouse_init_pos.top);
  471. var left = Math.round(this.el_init_offset.left +
  472. diff_x - this.baseX + $(window).scrollLeft() - this.win_offset_x);
  473. var top = Math.round(this.el_init_offset.top +
  474. diff_y - this.baseY + $(window).scrollTop() - this.win_offset_y);
  475. if (this.options.limit) {
  476. if (left > this.player_max_left) {
  477. left = this.player_max_left;
  478. } else if(left < this.player_min_left) {
  479. left = this.player_min_left;
  480. }
  481. }
  482. return {
  483. position: {
  484. left: left,
  485. top: top
  486. },
  487. pointer: {
  488. left: mouse_actual_pos.left,
  489. top: mouse_actual_pos.top,
  490. diff_left: diff_x + ($(window).scrollLeft() - this.win_offset_x),
  491. diff_top: diff_y + ($(window).scrollTop() - this.win_offset_y)
  492. }
  493. };
  494. };
  495. fn.get_drag_data = function(e) {
  496. var offset = this.get_offset(e);
  497. offset.$player = this.$player;
  498. offset.$helper = this.helper ? this.$helper : this.$player;
  499. return offset;
  500. };
  501. fn.set_limits = function(container_width) {
  502. container_width || (container_width = this.$container.width());
  503. this.player_max_left = (container_width - this.player_width +
  504. - this.options.offset_left);
  505. this.options.container_width = container_width;
  506. return this;
  507. };
  508. fn.scroll_in = function(axis, data) {
  509. var dir_prop = dir_map[axis];
  510. var area_size = 50;
  511. var scroll_inc = 30;
  512. var is_x = axis === 'x';
  513. var window_size = is_x ? this.window_width : this.window_height;
  514. var doc_size = is_x ? $(document).width() : $(document).height();
  515. var player_size = is_x ? this.$player.width() : this.$player.height();
  516. var next_scroll;
  517. var scroll_offset = $window['scroll' + capitalize(dir_prop)]();
  518. var min_window_pos = scroll_offset;
  519. var max_window_pos = min_window_pos + window_size;
  520. var mouse_next_zone = max_window_pos - area_size; // down/right
  521. var mouse_prev_zone = min_window_pos + area_size; // up/left
  522. var abs_mouse_pos = min_window_pos + data.pointer[dir_prop];
  523. var max_player_pos = (doc_size - window_size + player_size);
  524. if (abs_mouse_pos >= mouse_next_zone) {
  525. next_scroll = scroll_offset + scroll_inc;
  526. if (next_scroll < max_player_pos) {
  527. $window['scroll' + capitalize(dir_prop)](next_scroll);
  528. this['scroll_offset_' + axis] += scroll_inc;
  529. }
  530. }
  531. if (abs_mouse_pos <= mouse_prev_zone) {
  532. next_scroll = scroll_offset - scroll_inc;
  533. if (next_scroll > 0) {
  534. $window['scroll' + capitalize(dir_prop)](next_scroll);
  535. this['scroll_offset_' + axis] -= scroll_inc;
  536. }
  537. }
  538. return this;
  539. };
  540. fn.manage_scroll = function(data) {
  541. this.scroll_in('x', data);
  542. this.scroll_in('y', data);
  543. };
  544. fn.calculate_dimensions = function(e) {
  545. this.window_height = $window.height();
  546. this.window_width = $window.width();
  547. };
  548. fn.drag_handler = function(e) {
  549. var node = e.target.nodeName;
  550. // skip if drag is disabled, or click was not done with the mouse primary button
  551. if (this.disabled || e.which !== 1 && !isTouch) {
  552. return;
  553. }
  554. if (this.ignore_drag(e)) {
  555. return;
  556. }
  557. var self = this;
  558. var first = true;
  559. this.$player = $(e.currentTarget);
  560. this.el_init_pos = this.get_actual_pos(this.$player);
  561. this.mouse_init_pos = this.get_mouse_pos(e);
  562. this.offsetY = this.mouse_init_pos.top - this.el_init_pos.top;
  563. this.$document.on(this.pointer_events.move, function(mme) {
  564. var mouse_actual_pos = self.get_mouse_pos(mme);
  565. var diff_x = Math.abs(
  566. mouse_actual_pos.left - self.mouse_init_pos.left);
  567. var diff_y = Math.abs(
  568. mouse_actual_pos.top - self.mouse_init_pos.top);
  569. if (!(diff_x > self.options.distance ||
  570. diff_y > self.options.distance)
  571. ) {
  572. return false;
  573. }
  574. if (first) {
  575. first = false;
  576. self.on_dragstart.call(self, mme);
  577. return false;
  578. }
  579. if (self.is_dragging === true) {
  580. self.on_dragmove.call(self, mme);
  581. }
  582. return false;
  583. });
  584. if (!isTouch) { return false; }
  585. };
  586. fn.on_dragstart = function(e) {
  587. e.preventDefault();
  588. if (this.is_dragging) { return this; }
  589. this.drag_start = this.is_dragging = true;
  590. var offset = this.$container.offset();
  591. this.baseX = Math.round(offset.left);
  592. this.baseY = Math.round(offset.top);
  593. this.initial_container_width = this.options.container_width || this.$container.width();
  594. if (this.options.helper === 'clone') {
  595. this.$helper = this.$player.clone()
  596. .appendTo(this.$container).addClass('helper');
  597. this.helper = true;
  598. } else {
  599. this.helper = false;
  600. }
  601. this.win_offset_y = $(window).scrollTop();
  602. this.win_offset_x = $(window).scrollLeft();
  603. this.scroll_offset_y = 0;
  604. this.scroll_offset_x = 0;
  605. this.el_init_offset = this.$player.offset();
  606. this.player_width = this.$player.width();
  607. this.player_height = this.$player.height();
  608. this.set_limits(this.options.container_width);
  609. if (this.options.start) {
  610. this.options.start.call(this.$player, e, this.get_drag_data(e));
  611. }
  612. return false;
  613. };
  614. fn.on_dragmove = function(e) {
  615. var data = this.get_drag_data(e);
  616. this.options.autoscroll && this.manage_scroll(data);
  617. if (this.options.move_element) {
  618. (this.helper ? this.$helper : this.$player).css({
  619. 'position': 'absolute',
  620. 'left' : data.position.left,
  621. 'top' : data.position.top
  622. });
  623. }
  624. var last_position = this.last_position || data.position;
  625. data.prev_position = last_position;
  626. if (this.options.drag) {
  627. this.options.drag.call(this.$player, e, data);
  628. }
  629. this.last_position = data.position;
  630. return false;
  631. };
  632. fn.on_dragstop = function(e) {
  633. var data = this.get_drag_data(e);
  634. this.drag_start = false;
  635. if (this.options.stop) {
  636. this.options.stop.call(this.$player, e, data);
  637. }
  638. if (this.helper && this.options.remove_helper) {
  639. this.$helper.remove();
  640. }
  641. return false;
  642. };
  643. fn.on_select_start = function(e) {
  644. if (this.disabled) { return; }
  645. if (this.ignore_drag(e)) {
  646. return;
  647. }
  648. return false;
  649. };
  650. fn.enable = function() {
  651. this.disabled = false;
  652. };
  653. fn.disable = function() {
  654. this.disabled = true;
  655. };
  656. fn.destroy = function() {
  657. this.disable();
  658. this.$container.off(this.ns);
  659. this.$document.off(this.ns);
  660. $(window).off(this.ns);
  661. $.removeData(this.$container, 'drag');
  662. };
  663. fn.ignore_drag = function(event) {
  664. if (this.options.handle) {
  665. return !$(event.target).is(this.options.handle);
  666. }
  667. if ($.isFunction(this.options.ignore_dragging)) {
  668. return this.options.ignore_dragging(event);
  669. }
  670. return $(event.target).is(this.options.ignore_dragging.join(', '));
  671. };
  672. //jQuery adapter
  673. $.fn.drag = function ( options ) {
  674. return new Draggable(this, options);
  675. };
  676. return Draggable;
  677. }));
  678. ;(function(root, factory) {
  679. if (typeof define === 'function' && define.amd) {
  680. define(['jquery', 'gridster-draggable', 'gridster-collision'], factory);
  681. } else {
  682. root.Gridster = factory(root.$ || root.jQuery, root.GridsterDraggable,
  683. root.GridsterCollision);
  684. }
  685. }(this, function($, Draggable, Collision) {
  686. var defaults = {
  687. namespace: '',
  688. widget_selector: 'li',
  689. widget_margins: [10, 10],
  690. widget_base_dimensions: [400, 225],
  691. extra_rows: 0,
  692. extra_cols: 0,
  693. min_cols: 1,
  694. max_cols: Infinity,
  695. min_rows: 15,
  696. max_size_x: false,
  697. autogrow_cols: false,
  698. autogenerate_stylesheet: true,
  699. avoid_overlapped_widgets: true,
  700. auto_init: true,
  701. serialize_params: function($w, wgd) {
  702. return {
  703. col: wgd.col,
  704. row: wgd.row,
  705. size_x: wgd.size_x,
  706. size_y: wgd.size_y
  707. };
  708. },
  709. collision: {},
  710. draggable: {
  711. items: '.gs-w',
  712. distance: 4,
  713. ignore_dragging: Draggable.defaults.ignore_dragging.slice(0)
  714. },
  715. resize: {
  716. enabled: false,
  717. axes: ['both'],
  718. handle_append_to: '',
  719. handle_class: 'gs-resize-handle',
  720. max_size: [Infinity, Infinity],
  721. min_size: [1, 1]
  722. }
  723. };
  724. /**
  725. * @class Gridster
  726. *
  727. *
  728. *
  729. *
  730. * @uses Draggable
  731. * @uses Collision
  732. * @param {HTMLElement} el The HTMLelement that contains all the widgets.
  733. * @param {Object} [options] An Object with all options you want to
  734. * overwrite:
  735. * @param {HTMLElement|String} [options.widget_selector] Define who will
  736. * be the draggable widgets. Can be a CSS Selector String or a
  737. * collection of HTMLElements
  738. * @param {Array} [options.widget_margins] Margin between widgets.
  739. * The first index for the horizontal margin (left, right) and
  740. * the second for the vertical margin (top, bottom).
  741. * @param {Array} [options.widget_base_dimensions] Base widget dimensions
  742. * in pixels. The first index for the width and the second for the
  743. * height.
  744. * @param {Number} [options.extra_cols] Add more columns in addition to
  745. * those that have been calculated.
  746. * @param {Number} [options.extra_rows] Add more rows in addition to
  747. * those that have been calculated.
  748. * @param {Number} [options.min_cols] The minimum required columns.
  749. * @param {Number} [options.max_cols] The maximum columns possible (set to null
  750. * for no maximum).
  751. * @param {Number} [options.min_rows] The minimum required rows.
  752. * @param {Number} [options.max_size_x] The maximum number of columns
  753. * that a widget can span.
  754. * @param {Boolean} [options.autogenerate_stylesheet] If true, all the
  755. * CSS required to position all widgets in their respective columns
  756. * and rows will be generated automatically and injected to the
  757. * `<head>` of the document. You can set this to false, and write
  758. * your own CSS targeting rows and cols via data-attributes like so:
  759. * `[data-col="1"] { left: 10px; }`
  760. * @param {Boolean} [options.avoid_overlapped_widgets] Avoid that widgets loaded
  761. * from the DOM can be overlapped. It is helpful if the positions were
  762. * bad stored in the database or if there was any conflict.
  763. * @param {Boolean} [options.auto_init] Automatically call gridster init
  764. * method or not when the plugin is instantiated.
  765. * @param {Function} [options.serialize_params] Return the data you want
  766. * for each widget in the serialization. Two arguments are passed:
  767. * `$w`: the jQuery wrapped HTMLElement, and `wgd`: the grid
  768. * coords object (`col`, `row`, `size_x`, `size_y`).
  769. * @param {Object} [options.collision] An Object with all options for
  770. * Collision class you want to overwrite. See Collision docs for
  771. * more info.
  772. * @param {Object} [options.draggable] An Object with all options for
  773. * Draggable class you want to overwrite. See Draggable docs for more
  774. * info.
  775. * @param {Object|Function} [options.draggable.ignore_dragging] Note that
  776. * if you use a Function, and resize is enabled, you should ignore the
  777. * resize handlers manually (options.resize.handle_class).
  778. * @param {Object} [options.resize] An Object with resize config options.
  779. * @param {Boolean} [options.resize.enabled] Set to true to enable
  780. * resizing.
  781. * @param {Array} [options.resize.axes] Axes in which widgets can be
  782. * resized. Possible values: ['x', 'y', 'both'].
  783. * @param {String} [options.resize.handle_append_to] Set a valid CSS
  784. * selector to append resize handles to.
  785. * @param {String} [options.resize.handle_class] CSS class name used
  786. * by resize handles.
  787. * @param {Array} [options.resize.max_size] Limit widget dimensions
  788. * when resizing. Array values should be integers:
  789. * `[max_cols_occupied, max_rows_occupied]`
  790. * @param {Array} [options.resize.min_size] Limit widget dimensions
  791. * when resizing. Array values should be integers:
  792. * `[min_cols_occupied, min_rows_occupied]`
  793. * @param {Function} [options.resize.start] Function executed
  794. * when resizing starts.
  795. * @param {Function} [otions.resize.resize] Function executed
  796. * during the resizing.
  797. * @param {Function} [options.resize.stop] Function executed
  798. * when resizing stops.
  799. *
  800. * @constructor
  801. */
  802. function Gridster(el, options) {
  803. this.options = $.extend(true, {}, defaults, options);
  804. this.$el = $(el);
  805. this.$wrapper = this.$el.parent();
  806. this.$widgets = this.$el.children(
  807. this.options.widget_selector).addClass('gs-w');
  808. this.widgets = [];
  809. this.$changed = $([]);
  810. this.wrapper_width = this.$wrapper.width();
  811. this.min_widget_width = (this.options.widget_margins[0] * 2) +
  812. this.options.widget_base_dimensions[0];
  813. this.min_widget_height = (this.options.widget_margins[1] * 2) +
  814. this.options.widget_base_dimensions[1];
  815. this.generated_stylesheets = [];
  816. this.$style_tags = $([]);
  817. this.options.auto_init && this.init();
  818. }
  819. Gridster.defaults = defaults;
  820. Gridster.generated_stylesheets = [];
  821. /**
  822. * Sorts an Array of grid coords objects (representing the grid coords of
  823. * each widget) in ascending way.
  824. *
  825. * @method sort_by_row_asc
  826. * @param {Array} widgets Array of grid coords objects
  827. * @return {Array} Returns the array sorted.
  828. */
  829. Gridster.sort_by_row_asc = function(widgets) {
  830. widgets = widgets.sort(function(a, b) {
  831. if (!a.row) {
  832. a = $(a).coords().grid;
  833. b = $(b).coords().grid;
  834. }
  835. if (a.row > b.row) {
  836. return 1;
  837. }
  838. return -1;
  839. });
  840. return widgets;
  841. };
  842. /**
  843. * Sorts an Array of grid coords objects (representing the grid coords of
  844. * each widget) placing first the empty cells upper left.
  845. *
  846. * @method sort_by_row_and_col_asc
  847. * @param {Array} widgets Array of grid coords objects
  848. * @return {Array} Returns the array sorted.
  849. */
  850. Gridster.sort_by_row_and_col_asc = function(widgets) {
  851. widgets = widgets.sort(function(a, b) {
  852. if (a.row > b.row || a.row === b.row && a.col > b.col) {
  853. return 1;
  854. }
  855. return -1;
  856. });
  857. return widgets;
  858. };
  859. /**
  860. * Sorts an Array of grid coords objects by column (representing the grid
  861. * coords of each widget) in ascending way.
  862. *
  863. * @method sort_by_col_asc
  864. * @param {Array} widgets Array of grid coords objects
  865. * @return {Array} Returns the array sorted.
  866. */
  867. Gridster.sort_by_col_asc = function(widgets) {
  868. widgets = widgets.sort(function(a, b) {
  869. if (a.col > b.col) {
  870. return 1;
  871. }
  872. return -1;
  873. });
  874. return widgets;
  875. };
  876. /**
  877. * Sorts an Array of grid coords objects (representing the grid coords of
  878. * each widget) in descending way.
  879. *
  880. * @method sort_by_row_desc
  881. * @param {Array} widgets Array of grid coords objects
  882. * @return {Array} Returns the array sorted.
  883. */
  884. Gridster.sort_by_row_desc = function(widgets) {
  885. widgets = widgets.sort(function(a, b) {
  886. if (a.row + a.size_y < b.row + b.size_y) {
  887. return 1;
  888. }
  889. return -1;
  890. });
  891. return widgets;
  892. };
  893. /** Instance Methods **/
  894. var fn = Gridster.prototype;
  895. fn.init = function() {
  896. this.options.resize.enabled && this.setup_resize();
  897. this.generate_grid_and_stylesheet();
  898. this.get_widgets_from_DOM();
  899. this.set_dom_grid_height();
  900. this.set_dom_grid_width();
  901. this.$wrapper.addClass('ready');
  902. this.draggable();
  903. this.options.resize.enabled && this.resizable();
  904. $(window).bind('resize.gridster', throttle(
  905. $.proxy(this.recalculate_faux_grid, this), 200));
  906. };
  907. /**
  908. * Disables dragging.
  909. *
  910. * @method disable
  911. * @return {Class} Returns the instance of the Gridster Class.
  912. */
  913. fn.disable = function() {
  914. this.$wrapper.find('.player-revert').removeClass('player-revert');
  915. this.drag_api.disable();
  916. return this;
  917. };
  918. /**
  919. * Enables dragging.
  920. *
  921. * @method enable
  922. * @return {Class} Returns the instance of the Gridster Class.
  923. */
  924. fn.enable = function() {
  925. this.drag_api.enable();
  926. return this;
  927. };
  928. /**
  929. * Disables drag-and-drop widget resizing.
  930. *
  931. * @method disable
  932. * @return {Class} Returns instance of gridster Class.
  933. */
  934. fn.disable_resize = function() {
  935. this.$el.addClass('gs-resize-disabled');
  936. this.resize_api.disable();
  937. return this;
  938. };
  939. /**
  940. * Enables drag-and-drop widget resizing.
  941. *
  942. * @method enable
  943. * @return {Class} Returns instance of gridster Class.
  944. */
  945. fn.enable_resize = function() {
  946. this.$el.removeClass('gs-resize-disabled');
  947. this.resize_api.enable();
  948. return this;
  949. };
  950. /**
  951. * Add a new widget to the grid.
  952. *
  953. * @method add_widget
  954. * @param {String|HTMLElement} html The string representing the HTML of the widget
  955. * or the HTMLElement.
  956. * @param {Number} [size_x] The nº of rows the widget occupies horizontally.
  957. * @param {Number} [size_y] The nº of columns the widget occupies vertically.
  958. * @param {Number} [col] The column the widget should start in.
  959. * @param {Number} [row] The row the widget should start in.
  960. * @param {Array} [max_size] max_size Maximun size (in units) for width and height.
  961. * @param {Array} [min_size] min_size Minimum size (in units) for width and height.
  962. * @return {HTMLElement} Returns the jQuery wrapped HTMLElement representing.
  963. * the widget that was just created.
  964. */
  965. fn.add_widget = function(html, size_x, size_y, col, row, max_size, min_size) {
  966. var pos;
  967. size_x || (size_x = 1);
  968. size_y || (size_y = 1);
  969. if (!col & !row) {
  970. pos = this.next_position(size_x, size_y);
  971. } else {
  972. pos = {
  973. col: col,
  974. row: row,
  975. size_x: size_x,
  976. size_y: size_y
  977. };
  978. this.empty_cells(col, row, size_x, size_y);
  979. }
  980. var $w = $(html).attr({
  981. 'data-col': pos.col,
  982. 'data-row': pos.row,
  983. 'data-sizex' : size_x,
  984. 'data-sizey' : size_y
  985. }).addClass('gs-w').appendTo(this.$el).hide();
  986. this.$widgets = this.$widgets.add($w);
  987. this.register_widget($w);
  988. this.add_faux_rows(pos.size_y);
  989. //this.add_faux_cols(pos.size_x);
  990. if (max_size) {
  991. this.set_widget_max_size($w, max_size);
  992. }
  993. if (min_size) {
  994. this.set_widget_min_size($w, min_size);
  995. }
  996. this.set_dom_grid_width();
  997. this.set_dom_grid_height();
  998. this.drag_api.set_limits(this.cols * this.min_widget_width);
  999. return $w.fadeIn();
  1000. };
  1001. /**
  1002. * Change widget size limits.
  1003. *
  1004. * @method set_widget_min_size
  1005. * @param {HTMLElement|Number} $widget The jQuery wrapped HTMLElement
  1006. * representing the widget or an index representing the desired widget.
  1007. * @param {Array} min_size Minimum size (in units) for width and height.
  1008. * @return {HTMLElement} Returns instance of gridster Class.
  1009. */
  1010. fn.set_widget_min_size = function($widget, min_size) {
  1011. $widget = typeof $widget === 'number' ?
  1012. this.$widgets.eq($widget) : $widget;
  1013. if (!$widget.length) { return this; }
  1014. var wgd = $widget.data('coords').grid;
  1015. wgd.min_size_x = min_size[0];
  1016. wgd.min_size_y = min_size[1];
  1017. return this;
  1018. };
  1019. /**
  1020. * Change widget size limits.
  1021. *
  1022. * @method set_widget_max_size
  1023. * @param {HTMLElement|Number} $widget The jQuery wrapped HTMLElement
  1024. * representing the widget or an index representing the desired widget.
  1025. * @param {Array} max_size Maximun size (in units) for width and height.
  1026. * @return {HTMLElement} Returns instance of gridster Class.
  1027. */
  1028. fn.set_widget_max_size = function($widget, max_size) {
  1029. $widget = typeof $widget === 'number' ?
  1030. this.$widgets.eq($widget) : $widget;
  1031. if (!$widget.length) { return this; }
  1032. var wgd = $widget.data('coords').grid;
  1033. wgd.max_size_x = max_size[0];
  1034. wgd.max_size_y = max_size[1];
  1035. return this;
  1036. };
  1037. /**
  1038. * Append the resize handle into a widget.
  1039. *
  1040. * @method add_resize_handle
  1041. * @param {HTMLElement} $widget The jQuery wrapped HTMLElement
  1042. * representing the widget.
  1043. * @return {HTMLElement} Returns instance of gridster Class.
  1044. */
  1045. fn.add_resize_handle = function($w) {
  1046. var append_to = this.options.resize.handle_append_to;
  1047. $(this.resize_handle_tpl).appendTo( append_to ? $(append_to, $w) : $w);
  1048. return this;
  1049. };
  1050. /**
  1051. * Change the size of a widget. Width is limited to the current grid width.
  1052. *
  1053. * @method resize_widget
  1054. * @param {HTMLElement} $widget The jQuery wrapped HTMLElement
  1055. * representing the widget.
  1056. * @param {Number} size_x The number of columns that will occupy the widget.
  1057. * By default <code>size_x</code> is limited to the space available from
  1058. * the column where the widget begins, until the last column to the right.
  1059. * @param {Number} size_y The number of rows that will occupy the widget.
  1060. * @param {Function} [callback] Function executed when the widget is removed.
  1061. * @return {HTMLElement} Returns $widget.
  1062. */
  1063. fn.resize_widget = function($widget, size_x, size_y, callback) {
  1064. var wgd = $widget.coords().grid;
  1065. var col = wgd.col;
  1066. var max_cols = this.options.max_cols;
  1067. var old_size_y = wgd.size_y;
  1068. var old_col = wgd.col;
  1069. var new_col = old_col;
  1070. size_x || (size_x = wgd.size_x);
  1071. size_y || (size_y = wgd.size_y);
  1072. if (max_cols !== Infinity) {
  1073. size_x = Math.min(size_x, max_cols - col + 1);
  1074. }
  1075. if (size_y > old_size_y) {
  1076. this.add_faux_rows(Math.max(size_y - old_size_y, 0));
  1077. }
  1078. var player_rcol = (col + size_x - 1);
  1079. if (player_rcol > this.cols) {
  1080. this.add_faux_cols(player_rcol - this.cols);
  1081. }
  1082. var new_grid_data = {
  1083. col: new_col,
  1084. row: wgd.row,
  1085. size_x: size_x,
  1086. size_y: size_y
  1087. };
  1088. this.mutate_widget_in_gridmap($widget, wgd, new_grid_data);
  1089. this.set_dom_grid_height();
  1090. this.set_dom_grid_width();
  1091. if (callback) {
  1092. callback.call(this, new_grid_data.size_x, new_grid_data.size_y);
  1093. }
  1094. return $widget;
  1095. };
  1096. /**
  1097. * Mutate widget dimensions and position in the grid map.
  1098. *
  1099. * @method mutate_widget_in_gridmap
  1100. * @param {HTMLElement} $widget The jQuery wrapped HTMLElement
  1101. * representing the widget to mutate.
  1102. * @param {Object} wgd Current widget grid data (col, row, size_x, size_y).
  1103. * @param {Object} new_wgd New widget grid data.
  1104. * @return {HTMLElement} Returns instance of gridster Class.
  1105. */
  1106. fn.mutate_widget_in_gridmap = function($widget, wgd, new_wgd) {
  1107. var old_size_x = wgd.size_x;
  1108. var old_size_y = wgd.size_y;
  1109. var old_cells_occupied = this.get_cells_occupied(wgd);
  1110. var new_cells_occupied = this.get_cells_occupied(new_wgd);
  1111. var empty_cols = [];
  1112. $.each(old_cells_occupied.cols, function(i, col) {
  1113. if ($.inArray(col, new_cells_occupied.cols) === -1) {
  1114. empty_cols.push(col);
  1115. }
  1116. });
  1117. var occupied_cols = [];
  1118. $.each(new_cells_occupied.cols, function(i, col) {
  1119. if ($.inArray(col, old_cells_occupied.cols) === -1) {
  1120. occupied_cols.push(col);
  1121. }
  1122. });
  1123. var empty_rows = [];
  1124. $.each(old_cells_occupied.rows, function(i, row) {
  1125. if ($.inArray(row, new_cells_occupied.rows) === -1) {
  1126. empty_rows.push(row);
  1127. }
  1128. });
  1129. var occupied_rows = [];
  1130. $.each(new_cells_occupied.rows, function(i, row) {
  1131. if ($.inArray(row, old_cells_occupied.rows) === -1) {
  1132. occupied_rows.push(row);
  1133. }
  1134. });
  1135. this.remove_from_gridmap(wgd);
  1136. if (occupied_cols.length) {
  1137. var cols_to_empty = [
  1138. new_wgd.col, new_wgd.row, new_wgd.size_x, Math.min(old_size_y, new_wgd.size_y), $widget
  1139. ];
  1140. this.empty_cells.apply(this, cols_to_empty);
  1141. }
  1142. if (occupied_rows.length) {
  1143. var rows_to_empty = [new_wgd.col, new_wgd.row, new_wgd.size_x, new_wgd.size_y, $widget];
  1144. this.empty_cells.apply(this, rows_to_empty);
  1145. }
  1146. // not the same that wgd = new_wgd;
  1147. wgd.col = new_wgd.col;
  1148. wgd.row = new_wgd.row;
  1149. wgd.size_x = new_wgd.size_x;
  1150. wgd.size_y = new_wgd.size_y;
  1151. this.add_to_gridmap(new_wgd, $widget);
  1152. $widget.removeClass('player-revert');
  1153. //update coords instance attributes
  1154. $widget.data('coords').update({
  1155. width: (new_wgd.size_x * this.options.widget_base_dimensions[0] +
  1156. ((new_wgd.size_x - 1) * this.options.widget_margins[0]) * 2),
  1157. height: (new_wgd.size_y * this.options.widget_base_dimensions[1] +
  1158. ((new_wgd.size_y - 1) * this.options.widget_margins[1]) * 2)
  1159. });
  1160. $widget.attr({
  1161. 'data-col': new_wgd.col,
  1162. 'data-row': new_wgd.row,
  1163. 'data-sizex': new_wgd.size_x,
  1164. 'data-sizey': new_wgd.size_y
  1165. });
  1166. if (empty_cols.length) {
  1167. var cols_to_remove_holes = [
  1168. empty_cols[0], new_wgd.row,
  1169. empty_cols.length,
  1170. Math.min(old_size_y, new_wgd.size_y),
  1171. $widget
  1172. ];
  1173. this.remove_empty_cells.apply(this, cols_to_remove_holes);
  1174. }
  1175. if (empty_rows.length) {
  1176. var rows_to_remove_holes = [
  1177. new_wgd.col, new_wgd.row, new_wgd.size_x, new_wgd.size_y, $widget
  1178. ];
  1179. this.remove_empty_cells.apply(this, rows_to_remove_holes);
  1180. }
  1181. this.move_widget_up($widget);
  1182. return this;
  1183. };
  1184. /**
  1185. * Move down widgets in cells represented by the arguments col, row, size_x,
  1186. * size_y
  1187. *
  1188. * @method empty_cells
  1189. * @param {Number} col The column where the group of cells begin.
  1190. * @param {Number} row The row where the group of cells begin.
  1191. * @param {Number} size_x The number of columns that the group of cells
  1192. * occupy.
  1193. * @param {Number} size_y The number of rows that the group of cells
  1194. * occupy.
  1195. * @param {HTMLElement} $exclude Exclude widgets from being moved.
  1196. * @return {Class} Returns the instance of the Gridster Class.
  1197. */
  1198. fn.empty_cells = function(col, row, size_x, size_y, $exclude) {
  1199. var $nexts = this.widgets_below({
  1200. col: col,
  1201. row: row - size_y,
  1202. size_x: size_x,
  1203. size_y: size_y
  1204. });
  1205. $nexts.not($exclude).each($.proxy(function(i, w) {
  1206. var wgd = $(w).coords().grid;
  1207. if ( !(wgd.row <= (row + size_y - 1))) { return; }
  1208. var diff = (row + size_y) - wgd.row;
  1209. this.move_widget_down($(w), diff);
  1210. }, this));
  1211. this.set_dom_grid_height();
  1212. return this;
  1213. };
  1214. /**
  1215. * Move up widgets below cells represented by the arguments col, row, size_x,
  1216. * size_y.
  1217. *
  1218. * @method remove_empty_cells
  1219. * @param {Number} col The column where the group of cells begin.
  1220. * @param {Number} row The row where the group of cells begin.
  1221. * @param {Number} size_x The number of columns that the group of cells
  1222. * occupy.
  1223. * @param {Number} size_y The number of rows that the group of cells
  1224. * occupy.
  1225. * @param {HTMLElement} exclude Exclude widgets from being moved.
  1226. * @return {Class} Returns the instance of the Gridster Class.
  1227. */
  1228. fn.remove_empty_cells = function(col, row, size_x, size_y, exclude) {
  1229. var $nexts = this.widgets_below({
  1230. col: col,
  1231. row: row,
  1232. size_x: size_x,
  1233. size_y: size_y
  1234. });
  1235. $nexts.not(exclude).each($.proxy(function(i, widget) {
  1236. this.move_widget_up( $(widget), size_y );
  1237. }, this));
  1238. this.set_dom_grid_height();
  1239. return this;
  1240. };
  1241. /**
  1242. * Get the most left column below to add a new widget.
  1243. *
  1244. * @method next_position
  1245. * @param {Number} size_x The nº of rows the widget occupies horizontally.
  1246. * @param {Number} size_y The nº of columns the widget occupies vertically.
  1247. * @return {Object} Returns a grid coords object representing the future
  1248. * widget coords.
  1249. */
  1250. fn.next_position = function(size_x, size_y) {
  1251. size_x || (size_x = 1);
  1252. size_y || (size_y = 1);
  1253. var ga = this.gridmap;
  1254. var cols_l = ga.length;
  1255. var valid_pos = [];
  1256. var rows_l;
  1257. for (var c = 1; c < cols_l; c++) {
  1258. rows_l = ga[c].length;
  1259. for (var r = 1; r <= rows_l; r++) {
  1260. var can_move_to = this.can_move_to({
  1261. size_x: size_x,
  1262. size_y: size_y
  1263. }, c, r);
  1264. if (can_move_to) {
  1265. valid_pos.push({
  1266. col: c,
  1267. row: r,
  1268. size_y: size_y,
  1269. size_x: size_x
  1270. });
  1271. }
  1272. }
  1273. }
  1274. if (valid_pos.length) {
  1275. return Gridster.sort_by_row_and_col_asc(valid_pos)[0];
  1276. }
  1277. return false;
  1278. };
  1279. /**
  1280. * Remove a widget from the grid.
  1281. *
  1282. * @method remove_widget
  1283. * @param {HTMLElement} el The jQuery wrapped HTMLElement you want to remove.
  1284. * @param {Boolean|Function} silent If true, widgets below the removed one
  1285. * will not move up. If a Function is passed it will be used as callback.
  1286. * @param {Function} callback Function executed when the widget is removed.
  1287. * @return {Class} Returns the instance of the Gridster Class.
  1288. */
  1289. fn.remove_widget = function(el, silent, callback) {
  1290. var $el = el instanceof $ ? el : $(el);
  1291. var wgd = $el.coords().grid;
  1292. // if silent is a function assume it's a callback
  1293. if ($.isFunction(silent)) {
  1294. callback = silent;
  1295. silent = false;
  1296. }
  1297. this.cells_occupied_by_placeholder = {};
  1298. this.$widgets = this.$widgets.not($el);
  1299. var $nexts = this.widgets_below($el);
  1300. this.remove_from_gridmap(wgd);
  1301. $el.fadeOut($.proxy(function() {
  1302. $el.remove();
  1303. if (!silent) {
  1304. $nexts.each($.proxy(function(i, widget) {
  1305. this.move_widget_up( $(widget), wgd.size_y );
  1306. }, this));
  1307. }
  1308. this.set_dom_grid_height();
  1309. if (callback) {
  1310. callback.call(this, el);
  1311. }
  1312. }, this));
  1313. return this;
  1314. };
  1315. /**
  1316. * Remove all widgets from the grid.
  1317. *
  1318. * @method remove_all_widgets
  1319. * @param {Function} callback Function executed for each widget removed.
  1320. * @return {Class} Returns the instance of the Gridster Class.
  1321. */
  1322. fn.remove_all_widgets = function(callback) {
  1323. this.$widgets.each($.proxy(function(i, el){
  1324. this.remove_widget(el, true, callback);
  1325. }, this));
  1326. return this;
  1327. };
  1328. /**
  1329. * Returns a serialized array of the widgets in the grid.
  1330. *
  1331. * @method serialize
  1332. * @param {HTMLElement} [$widgets] The collection of jQuery wrapped
  1333. * HTMLElements you want to serialize. If no argument is passed all widgets
  1334. * will be serialized.
  1335. * @return {Array} Returns an Array of Objects with the data specified in
  1336. * the serialize_params option.
  1337. */
  1338. fn.serialize = function($widgets) {
  1339. $widgets || ($widgets = this.$widgets);
  1340. return $widgets.map($.proxy(function(i, widget) {
  1341. var $w = $(widget);
  1342. return this.options.serialize_params($w, $w.coords().grid);
  1343. }, this)).get();
  1344. };
  1345. /**
  1346. * Returns a serialized array of the widgets that have changed their
  1347. * position.
  1348. *
  1349. * @method serialize_changed
  1350. * @return {Array} Returns an Array of Objects with the data specified in
  1351. * the serialize_params option.
  1352. */
  1353. fn.serialize_changed = function() {
  1354. return this.serialize(this.$changed);
  1355. };
  1356. /**
  1357. * Convert widgets from DOM elements to "widget grid data" Objects.
  1358. *
  1359. * @method dom_to_coords
  1360. * @param {HTMLElement} $widget The widget to be converted.
  1361. */
  1362. fn.dom_to_coords = function($widget) {
  1363. return {
  1364. 'col': parseInt($widget.attr('data-col'), 10),
  1365. 'row': parseInt($widget.attr('data-row'), 10),
  1366. 'size_x': parseInt($widget.attr('data-sizex'), 10) || 1,
  1367. 'size_y': parseInt($widget.attr('data-sizey'), 10) || 1,
  1368. 'max_size_x': parseInt($widget.attr('data-max-sizex'), 10) || false,
  1369. 'max_size_y': parseInt($widget.attr('data-max-sizey'), 10) || false,
  1370. 'min_size_x': parseInt($widget.attr('data-min-sizex'), 10) || false,
  1371. 'min_size_y': parseInt($widget.attr('data-min-sizey'), 10) || false,
  1372. 'el': $widget
  1373. };
  1374. };
  1375. /**
  1376. * Creates the grid coords object representing the widget an add it to the
  1377. * mapped array of positions.
  1378. *
  1379. * @method register_widget
  1380. * @param {HTMLElement|Object} $el jQuery wrapped HTMLElement representing
  1381. * the widget, or an "widget grid data" Object with (col, row, el ...).
  1382. * @return {Boolean} Returns true if the widget final position is different
  1383. * than the original.
  1384. */
  1385. fn.register_widget = function($el) {
  1386. // console.log($el[0].outerHTML);
  1387. var isDOM = $el instanceof jQuery;
  1388. var wgd = isDOM ? this.dom_to_coords($el) : $el;
  1389. var posChanged = false;
  1390. isDOM || ($el = wgd.el);
  1391. var empty_upper_row = this.can_go_widget_up(wgd);
  1392. if (empty_upper_row) {
  1393. wgd.row = empty_upper_row;
  1394. //2019-10-29注释。原因:部件出现交叉重叠,会被遮盖部分内容。
  1395. $el.attr('data-row', empty_upper_row);
  1396. this.$el.trigger('gridster:positionchanged', [wgd]);
  1397. posChanged = true;
  1398. }
  1399. if (this.options.avoid_overlapped_widgets &&
  1400. !this.can_move_to(
  1401. {size_x: wgd.size_x, size_y: wgd.size_y}, wgd.col, wgd.row)
  1402. ) {
  1403. $.extend(wgd, this.next_position(wgd.size_x, wgd.size_y));
  1404. $el.attr({
  1405. 'data-col': wgd.col,
  1406. 'data-row': wgd.row,
  1407. 'data-sizex': wgd.size_x,
  1408. 'data-sizey': wgd.size_y
  1409. });
  1410. posChanged = true;
  1411. }
  1412. // attach Coord object to player data-coord attribute
  1413. $el.data('coords', $el.coords());
  1414. // Extend Coord object with grid position info
  1415. $el.data('coords').grid = wgd;
  1416. this.add_to_gridmap(wgd, $el);
  1417. this.options.resize.enabled && this.add_resize_handle($el);
  1418. return posChanged;
  1419. };
  1420. /**
  1421. * Update in the mapped array of positions the value of cells represented by
  1422. * the grid coords object passed in the `grid_data` param.
  1423. *
  1424. * @param {Object} grid_data The grid coords object representing the cells
  1425. * to update in the mapped array.
  1426. * @param {HTMLElement|Boolean} value Pass `false` or the jQuery wrapped
  1427. * HTMLElement, depends if you want to delete an existing position or add
  1428. * a new one.
  1429. * @method update_widget_position
  1430. * @return {Class} Returns the instance of the Gridster Class.
  1431. */
  1432. fn.update_widget_position = function(grid_data, value) {
  1433. this.for_each_cell_occupied(grid_data, function(col, row) {
  1434. if (!this.gridmap[col]) { return this; }
  1435. this.gridmap[col][row] = value;
  1436. });
  1437. return this;
  1438. };
  1439. /**
  1440. * Remove a widget from the mapped array of positions.
  1441. *
  1442. * @method remove_from_gridmap
  1443. * @param {Object} grid_data The grid coords object representing the cells
  1444. * to update in the mapped array.
  1445. * @return {Class} Returns the instance of the Gridster Class.
  1446. */
  1447. fn.remove_from_gridmap = function(grid_data) {
  1448. return this.update_widget_position(grid_data, false);
  1449. };
  1450. /**
  1451. * Add a widget to the mapped array of positions.
  1452. *
  1453. * @method add_to_gridmap
  1454. * @param {Object} grid_data The grid coords object representing the cells
  1455. * to update in the mapped array.
  1456. * @param {HTMLElement|Boolean} value The value to set in the specified
  1457. * position .
  1458. * @return {Class} Returns the instance of the Gridster Class.
  1459. */
  1460. fn.add_to_gridmap = function(grid_data, value) {
  1461. this.update_widget_position(grid_data, value || grid_data.el);
  1462. if (grid_data.el) {
  1463. var $widgets = this.widgets_below(grid_data.el);
  1464. $widgets.each($.proxy(function(i, widget) {
  1465. this.move_widget_up( $(widget));
  1466. }, this));
  1467. }
  1468. };
  1469. /**
  1470. * Make widgets draggable.
  1471. *
  1472. * @uses Draggable
  1473. * @method draggable
  1474. * @return {Class} Returns the instance of the Gridster Class.
  1475. */
  1476. fn.draggable = function() {
  1477. var self = this;
  1478. var draggable_options = $.extend(true, {}, this.options.draggable, {
  1479. offset_left: this.options.widget_margins[0],
  1480. offset_top: this.options.widget_margins[1],
  1481. container_width: this.cols * this.min_widget_width,
  1482. limit: true,
  1483. start: function(event, ui) {
  1484. self.$widgets.filter('.player-revert')
  1485. .removeClass('player-revert');
  1486. self.$player = $(this);
  1487. self.$helper = $(ui.$helper);
  1488. self.helper = !self.$helper.is(self.$player);
  1489. self.on_start_drag.call(self, event, ui);
  1490. self.$el.trigger('gridster:dragstart');
  1491. },
  1492. stop: function(event, ui) {
  1493. self.on_stop_drag.call(self, event, ui);
  1494. self.$el.trigger('gridster:dragstop');
  1495. },
  1496. drag: throttle(function(event, ui) {
  1497. self.on_drag.call(self, event, ui);
  1498. self.$el.trigger('gridster:drag');
  1499. }, 60)
  1500. });
  1501. this.drag_api = this.$el.drag(draggable_options);
  1502. return this;
  1503. };
  1504. /**
  1505. * Bind resize events to get resize working.
  1506. *
  1507. * @method resizable
  1508. * @return {Class} Returns instance of gridster Class.
  1509. */
  1510. fn.resizable = function() {
  1511. this.resize_api = this.$el.drag({
  1512. items: '.' + this.options.resize.handle_class,
  1513. offset_left: this.options.widget_margins[0],
  1514. container_width: this.container_width,
  1515. move_element: false,
  1516. resize: true,
  1517. limit: this.options.autogrow_cols ? false : true,
  1518. start: $.proxy(this.on_start_resize, this),
  1519. stop: $.proxy(function(event, ui) {
  1520. delay($.proxy(function() {
  1521. this.on_stop_resize(event, ui);
  1522. }, this), 120);
  1523. }, this),
  1524. drag: throttle($.proxy(this.on_resize, this), 60)
  1525. });
  1526. return this;
  1527. };
  1528. /**
  1529. * Setup things required for resizing. Like build templates for drag handles.
  1530. *
  1531. * @method setup_resize
  1532. * @return {Class} Returns instance of gridster Class.
  1533. */
  1534. fn.setup_resize = function() {
  1535. this.resize_handle_class = this.options.resize.handle_class;
  1536. var axes = this.options.resize.axes;
  1537. var handle_tpl = '<span class="' + this.resize_handle_class + ' ' +
  1538. this.resize_handle_class + '-{type}" />';
  1539. this.resize_handle_tpl = $.map(axes, function(type) {
  1540. return handle_tpl.replace('{type}', type);
  1541. }).join('');
  1542. if ($.isArray(this.options.draggable.ignore_dragging)) {
  1543. this.options.draggable.ignore_dragging.push(
  1544. '.' + this.resize_handle_class);
  1545. }
  1546. return this;
  1547. };
  1548. /**
  1549. * This function is executed when the player begins to be dragged.
  1550. *
  1551. * @method on_start_drag
  1552. * @param {Event} event The original browser event
  1553. * @param {Object} ui A prepared ui object with useful drag-related data
  1554. */
  1555. fn.on_start_drag = function(event, ui) {
  1556. this.$helper.add(this.$player).add(this.$wrapper).addClass('dragging');
  1557. this.highest_col = this.get_highest_occupied_cell().col;
  1558. this.$player.addClass('player');
  1559. this.player_grid_data = this.$player.coords().grid;
  1560. this.placeholder_grid_data = $.extend({}, this.player_grid_data);
  1561. this.set_dom_grid_height(this.$el.height() +
  1562. (this.player_grid_data.size_y * this.min_widget_height));
  1563. this.set_dom_grid_width(this.cols);
  1564. var pgd_sizex = this.player_grid_data.size_x;
  1565. var cols_diff = this.cols - this.highest_col;
  1566. if (this.options.autogrow_cols && cols_diff <= pgd_sizex) {
  1567. this.add_faux_cols(Math.min(pgd_sizex - cols_diff, 1));
  1568. }
  1569. var colliders = this.faux_grid;
  1570. var coords = this.$player.data('coords').coords;
  1571. this.cells_occupied_by_player = this.get_cells_occupied(
  1572. this.player_grid_data);
  1573. this.cells_occupied_by_placeholder = this.get_cells_occupied(
  1574. this.placeholder_grid_data);
  1575. this.last_cols = [];
  1576. this.last_rows = [];
  1577. // see jquery.collision.js
  1578. this.collision_api = this.$helper.collision(
  1579. colliders, this.options.collision);
  1580. this.$preview_holder = $('<' + this.$player.get(0).tagName + ' />', {
  1581. 'class': 'preview-holder',
  1582. 'data-row': this.$player.attr('data-row'),
  1583. 'data-col': this.$player.attr('data-col'),
  1584. css: {
  1585. width: coords.width,
  1586. height: coords.height
  1587. }
  1588. }).appendTo(this.$el);
  1589. if (this.options.draggable.start) {
  1590. this.options.draggable.start.call(this, event, ui);
  1591. }
  1592. };
  1593. /**
  1594. * This function is executed when the player is being dragged.
  1595. *
  1596. * @method on_drag
  1597. * @param {Event} event The original browser event
  1598. * @param {Object} ui A prepared ui object with useful drag-related data
  1599. */
  1600. fn.on_drag = function(event, ui) {
  1601. //break if dragstop has been fired
  1602. if (this.$player === null) {
  1603. return false;
  1604. }
  1605. var abs_offset = {
  1606. left: ui.position.left + this.baseX,
  1607. top: ui.position.top + this.baseY
  1608. };
  1609. // auto grow cols
  1610. if (this.options.autogrow_cols) {
  1611. var prcol = this.placeholder_grid_data.col +
  1612. this.placeholder_grid_data.size_x - 1;
  1613. // "- 1" due to adding at least 1 column in on_start_drag
  1614. if (prcol >= this.cols - 1 && this.options.max_cols >= this.cols + 1) {
  1615. this.add_faux_cols(1);
  1616. this.set_dom_grid_width(this.cols + 1);
  1617. this.drag_api.set_limits(this.container_width);
  1618. }
  1619. this.collision_api.set_colliders(this.faux_grid);
  1620. }
  1621. this.colliders_data = this.collision_api.get_closest_colliders(
  1622. abs_offset);
  1623. this.on_overlapped_column_change(
  1624. this.on_start_overlapping_column, this.on_stop_overlapping_column);
  1625. this.on_overlapped_row_change(
  1626. this.on_start_overlapping_row, this.on_stop_overlapping_row);
  1627. if (this.helper && this.$player) {
  1628. this.$player.css({
  1629. 'left': ui.position.left,
  1630. 'top': ui.position.top
  1631. });
  1632. }
  1633. if (this.options.draggable.drag) {
  1634. this.options.draggable.drag.call(this, event, ui);
  1635. }
  1636. };
  1637. /**
  1638. * This function is executed when the player stops being dragged.
  1639. *
  1640. * @method on_stop_drag
  1641. * @param {Event} event The original browser event
  1642. * @param {Object} ui A prepared ui object with useful drag-related data
  1643. */
  1644. fn.on_stop_drag = function(event, ui) {
  1645. this.$helper.add(this.$player).add(this.$wrapper)
  1646. .removeClass('dragging');
  1647. ui.position.left = ui.position.left + this.baseX;
  1648. ui.position.top = ui.position.top + this.baseY;
  1649. this.colliders_data = this.collision_api.get_closest_colliders(
  1650. ui.position);
  1651. this.on_overlapped_column_change(
  1652. this.on_start_overlapping_column,
  1653. this.on_stop_overlapping_column
  1654. );
  1655. this.on_overlapped_row_change(
  1656. this.on_start_overlapping_row,
  1657. this.on_stop_overlapping_row
  1658. );
  1659. this.$player.addClass('player-revert').removeClass('player')
  1660. .attr({
  1661. 'data-col': this.placeholder_grid_data.col,
  1662. 'data-row': this.placeholder_grid_data.row
  1663. }).css({
  1664. 'left': '',
  1665. 'top': ''
  1666. });
  1667. this.$changed = this.$changed.add(this.$player);
  1668. this.cells_occupied_by_player = this.get_cells_occupied(
  1669. this.placeholder_grid_data);
  1670. this.set_cells_player_occupies(
  1671. this.placeholder_grid_data.col, this.placeholder_grid_data.row);
  1672. this.$player.coords().grid.row = this.placeholder_grid_data.row;
  1673. this.$player.coords().grid.col = this.placeholder_grid_data.col;
  1674. if (this.options.draggable.stop) {
  1675. this.options.draggable.stop.call(this, event, ui);
  1676. }
  1677. this.$preview_holder.remove();
  1678. this.$player = null;
  1679. this.$helper = null;
  1680. this.placeholder_grid_data = {};
  1681. this.player_grid_data = {};
  1682. this.cells_occupied_by_placeholder = {};
  1683. this.cells_occupied_by_player = {};
  1684. this.set_dom_grid_height();
  1685. this.set_dom_grid_width();
  1686. if (this.options.autogrow_cols) {
  1687. this.drag_api.set_limits(this.cols * this.min_widget_width);
  1688. }
  1689. };
  1690. /**
  1691. * This function is executed every time a widget starts to be resized.
  1692. *
  1693. * @method on_start_resize
  1694. * @param {Event} event The original browser event
  1695. * @param {Object} ui A prepared ui object with useful drag-related data
  1696. */
  1697. fn.on_start_resize = function(event, ui) {
  1698. this.$resized_widget = ui.$player.closest('.gs-w');
  1699. this.resize_coords = this.$resized_widget.coords();
  1700. this.resize_wgd = this.resize_coords.grid;
  1701. this.resize_initial_width = this.resize_coords.coords.width;
  1702. this.resize_initial_height = this.resize_coords.coords.height;
  1703. this.resize_initial_sizex = this.resize_coords.grid.size_x;
  1704. this.resize_initial_sizey = this.resize_coords.grid.size_y;
  1705. this.resize_initial_col = this.resize_coords.grid.col;
  1706. this.resize_last_sizex = this.resize_initial_sizex;
  1707. this.resize_last_sizey = this.resize_initial_sizey;
  1708. this.resize_max_size_x = Math.min(this.resize_wgd.max_size_x ||
  1709. this.options.resize.max_size[0],
  1710. this.options.max_cols - this.resize_initial_col + 1);
  1711. this.resize_max_size_y = this.resize_wgd.max_size_y ||
  1712. this.options.resize.max_size[1];
  1713. this.resize_min_size_x = (this.resize_wgd.min_size_x ||
  1714. this.options.resize.min_size[0] || 1);
  1715. this.resize_min_size_y = (this.resize_wgd.min_size_y ||
  1716. this.options.resize.min_size[1] || 1);
  1717. this.resize_initial_last_col = this.get_highest_occupied_cell().col;
  1718. this.set_dom_grid_width(this.cols);
  1719. this.resize_dir = {
  1720. right: ui.$player.is('.' + this.resize_handle_class + '-x'),
  1721. bottom: ui.$player.is('.' + this.resize_handle_class + '-y')
  1722. };
  1723. this.$resized_widget.css({
  1724. 'min-width': this.options.widget_base_dimensions[0],
  1725. 'min-height': this.options.widget_base_dimensions[1]
  1726. });
  1727. var nodeName = this.$resized_widget.get(0).tagName;
  1728. this.$resize_preview_holder = $('<' + nodeName + ' />', {
  1729. 'class': 'preview-holder resize-preview-holder',
  1730. 'data-row': this.$resized_widget.attr('data-row'),
  1731. 'data-col': this.$resized_widget.attr('data-col'),
  1732. 'css': {
  1733. 'width': this.resize_initial_width,
  1734. 'height': this.resize_initial_height
  1735. }
  1736. }).appendTo(this.$el);
  1737. this.$resized_widget.addClass('resizing');
  1738. if (this.options.resize.start) {
  1739. this.options.resize.start.call(this, event, ui, this.$resized_widget);
  1740. }
  1741. this.$el.trigger('gridster:resizestart');
  1742. };
  1743. /**
  1744. * This function is executed every time a widget stops being resized.
  1745. *
  1746. * @method on_stop_resize
  1747. * @param {Event} event The original browser event
  1748. * @param {Object} ui A prepared ui object with useful drag-related data
  1749. */
  1750. fn.on_stop_resize = function(event, ui) {
  1751. this.$resized_widget
  1752. .removeClass('resizing')
  1753. .css({
  1754. 'width': '',
  1755. 'height': ''
  1756. });
  1757. delay($.proxy(function() {
  1758. this.$resize_preview_holder
  1759. .remove()
  1760. .css({
  1761. 'min-width': '',
  1762. 'min-height': ''
  1763. });
  1764. if (this.options.resize.stop) {
  1765. this.options.resize.stop.call(this, event, ui, this.$resized_widget);
  1766. }
  1767. this.$el.trigger('gridster:resizestop');
  1768. }, this), 300);
  1769. this.set_dom_grid_width();
  1770. if (this.options.autogrow_cols) {
  1771. this.drag_api.set_limits(this.cols * this.min_widget_width);
  1772. }
  1773. };
  1774. /**
  1775. * This function is executed when a widget is being resized.
  1776. *
  1777. * @method on_resize
  1778. * @param {Event} event The original browser event
  1779. * @param {Object} ui A prepared ui object with useful drag-related data
  1780. */
  1781. fn.on_resize = function(event, ui) {
  1782. var rel_x = (ui.pointer.diff_left);
  1783. var rel_y = (ui.pointer.diff_top);
  1784. var wbd_x = this.options.widget_base_dimensions[0];
  1785. var wbd_y = this.options.widget_base_dimensions[1];
  1786. var margin_x = this.options.widget_margins[0];
  1787. var margin_y = this.options.widget_margins[1];
  1788. var max_size_x = this.resize_max_size_x;
  1789. var min_size_x = this.resize_min_size_x;
  1790. var max_size_y = this.resize_max_size_y;
  1791. var min_size_y = this.resize_min_size_y;
  1792. var autogrow = this.options.autogrow_cols;
  1793. var width;
  1794. var max_width = Infinity;
  1795. var max_height = Infinity;
  1796. var inc_units_x = Math.ceil((rel_x / (wbd_x + margin_x * 2)) - 0.2);
  1797. var inc_units_y = Math.ceil((rel_y / (wbd_y + margin_y * 2)) - 0.2);
  1798. var size_x = Math.max(1, this.resize_initial_sizex + inc_units_x);
  1799. var size_y = Math.max(1, this.resize_initial_sizey + inc_units_y);
  1800. var max_cols = (this.container_width / this.min_widget_width) -
  1801. this.resize_initial_col + 1;
  1802. var limit_width = ((max_cols * this.min_widget_width) - margin_x * 2);
  1803. size_x = Math.max(Math.min(size_x, max_size_x), min_size_x);
  1804. size_x = Math.min(max_cols, size_x);
  1805. width = (max_size_x * wbd_x) + ((size_x - 1) * margin_x * 2);
  1806. max_width = Math.min(width, limit_width);
  1807. min_width = (min_size_x * wbd_x) + ((size_x - 1) * margin_x * 2);
  1808. size_y = Math.max(Math.min(size_y, max_size_y), min_size_y);
  1809. max_height = (max_size_y * wbd_y) + ((size_y - 1) * margin_y * 2);
  1810. min_height = (min_size_y * wbd_y) + ((size_y - 1) * margin_y * 2);
  1811. if (this.resize_dir.right) {
  1812. size_y = this.resize_initial_sizey;
  1813. } else if (this.resize_dir.bottom) {
  1814. size_x = this.resize_initial_sizex;
  1815. }
  1816. if (autogrow) {
  1817. var last_widget_col = this.resize_initial_col + size_x - 1;
  1818. if (autogrow && this.resize_initial_last_col <= last_widget_col) {
  1819. this.set_dom_grid_width(Math.max(last_widget_col + 1, this.cols));
  1820. if (this.cols < last_widget_col) {
  1821. this.add_faux_cols(last_widget_col - this.cols);
  1822. }
  1823. }
  1824. }
  1825. var css_props = {};
  1826. !this.resize_dir.bottom && (css_props.width = Math.max(Math.min(
  1827. this.resize_initial_width + rel_x, max_width), min_width));
  1828. !this.resize_dir.right && (css_props.height = Math.max(Math.min(
  1829. this.resize_initial_height + rel_y, max_height), min_height));
  1830. this.$resized_widget.css(css_props);
  1831. if (size_x !== this.resize_last_sizex ||
  1832. size_y !== this.resize_last_sizey) {
  1833. this.resize_widget(this.$resized_widget, size_x, size_y);
  1834. this.set_dom_grid_width(this.cols);
  1835. this.$resize_preview_holder.css({
  1836. 'width': '',
  1837. 'height': ''
  1838. }).attr({
  1839. 'data-row': this.$resized_widget.attr('data-row'),
  1840. 'data-sizex': size_x,
  1841. 'data-sizey': size_y
  1842. });
  1843. }
  1844. if (this.options.resize.resize) {
  1845. this.options.resize.resize.call(this, event, ui, this.$resized_widget);
  1846. }
  1847. this.$el.trigger('gridster:resize');
  1848. this.resize_last_sizex = size_x;
  1849. this.resize_last_sizey = size_y;
  1850. };
  1851. /**
  1852. * Executes the callbacks passed as arguments when a column begins to be
  1853. * overlapped or stops being overlapped.
  1854. *
  1855. * @param {Function} start_callback Function executed when a new column
  1856. * begins to be overlapped. The column is passed as first argument.
  1857. * @param {Function} stop_callback Function executed when a column stops
  1858. * being overlapped. The column is passed as first argument.
  1859. * @method on_overlapped_column_change
  1860. * @return {Class} Returns the instance of the Gridster Class.
  1861. */
  1862. fn.on_overlapped_column_change = function(start_callback, stop_callback) {
  1863. if (!this.colliders_data.length) {
  1864. return this;
  1865. }
  1866. var cols = this.get_targeted_columns(
  1867. this.colliders_data[0].el.data.col);
  1868. var last_n_cols = this.last_cols.length;
  1869. var n_cols = cols.length;
  1870. var i;
  1871. for (i = 0; i < n_cols; i++) {
  1872. if ($.inArray(cols[i], this.last_cols) === -1) {
  1873. (start_callback || $.noop).call(this, cols[i]);
  1874. }
  1875. }
  1876. for (i = 0; i< last_n_cols; i++) {
  1877. if ($.inArray(this.last_cols[i], cols) === -1) {
  1878. (stop_callback || $.noop).call(this, this.last_cols[i]);
  1879. }
  1880. }
  1881. this.last_cols = cols;
  1882. return this;
  1883. };
  1884. /**
  1885. * Executes the callbacks passed as arguments when a row starts to be
  1886. * overlapped or stops being overlapped.
  1887. *
  1888. * @param {Function} start_callback Function executed when a new row begins
  1889. * to be overlapped. The row is passed as first argument.
  1890. * @param {Function} end_callback Function executed when a row stops being
  1891. * overlapped. The row is passed as first argument.
  1892. * @method on_overlapped_row_change
  1893. * @return {Class} Returns the instance of the Gridster Class.
  1894. */
  1895. fn.on_overlapped_row_change = function(start_callback, end_callback) {
  1896. if (!this.colliders_data.length) {
  1897. return this;
  1898. }
  1899. var rows = this.get_targeted_rows(this.colliders_data[0].el.data.row);
  1900. var last_n_rows = this.last_rows.length;
  1901. var n_rows = rows.length;
  1902. var i;
  1903. for (i = 0; i < n_rows; i++) {
  1904. if ($.inArray(rows[i], this.last_rows) === -1) {
  1905. (start_callback || $.noop).call(this, rows[i]);
  1906. }
  1907. }
  1908. for (i = 0; i < last_n_rows; i++) {
  1909. if ($.inArray(this.last_rows[i], rows) === -1) {
  1910. (end_callback || $.noop).call(this, this.last_rows[i]);
  1911. }
  1912. }
  1913. this.last_rows = rows;
  1914. };
  1915. /**
  1916. * Sets the current position of the player
  1917. *
  1918. * @param {Number} col
  1919. * @param {Number} row
  1920. * @param {Boolean} no_player
  1921. * @method set_player
  1922. * @return {object}
  1923. */
  1924. fn.set_player = function(col, row, no_player) {
  1925. var self = this;
  1926. if (!no_player) {
  1927. this.empty_cells_player_occupies();
  1928. }
  1929. var cell = !no_player ? self.colliders_data[0].el.data : {col: col};
  1930. var to_col = cell.col;
  1931. var to_row = row || cell.row;
  1932. this.player_grid_data = {
  1933. col: to_col,
  1934. row: to_row,
  1935. size_y : this.player_grid_data.size_y,
  1936. size_x : this.player_grid_data.size_x
  1937. };
  1938. this.cells_occupied_by_player = this.get_cells_occupied(
  1939. this.player_grid_data);
  1940. var $overlapped_widgets = this.get_widgets_overlapped(
  1941. this.player_grid_data);
  1942. var constraints = this.widgets_constraints($overlapped_widgets);
  1943. this.manage_movements(constraints.can_go_up, to_col, to_row);
  1944. this.manage_movements(constraints.can_not_go_up, to_col, to_row);
  1945. /* if there is not widgets overlapping in the new player position,
  1946. * update the new placeholder position. */
  1947. if (!$overlapped_widgets.length) {
  1948. var pp = this.can_go_player_up(this.player_grid_data);
  1949. if (pp !== false) {
  1950. to_row = pp;
  1951. }
  1952. this.set_placeholder(to_col, to_row);
  1953. }
  1954. return {
  1955. col: to_col,
  1956. row: to_row
  1957. };
  1958. };
  1959. /**
  1960. * See which of the widgets in the $widgets param collection can go to
  1961. * a upper row and which not.
  1962. *
  1963. * @method widgets_contraints
  1964. * @param {jQuery} $widgets A jQuery wrapped collection of
  1965. * HTMLElements.
  1966. * @return {object} Returns a literal Object with two keys: `can_go_up` &
  1967. * `can_not_go_up`. Each contains a set of HTMLElements.
  1968. */
  1969. fn.widgets_constraints = function($widgets) {
  1970. var $widgets_can_go_up = $([]);
  1971. var $widgets_can_not_go_up;
  1972. var wgd_can_go_up = [];
  1973. var wgd_can_not_go_up = [];
  1974. $widgets.each($.proxy(function(i, w) {
  1975. var $w = $(w);
  1976. var wgd = $w.coords().grid;
  1977. if (this.can_go_widget_up(wgd)) {
  1978. $widgets_can_go_up = $widgets_can_go_up.add($w);
  1979. wgd_can_go_up.push(wgd);
  1980. } else {
  1981. wgd_can_not_go_up.push(wgd);
  1982. }
  1983. }, this));
  1984. $widgets_can_not_go_up = $widgets.not($widgets_can_go_up);
  1985. return {
  1986. can_go_up: Gridster.sort_by_row_asc(wgd_can_go_up),
  1987. can_not_go_up: Gridster.sort_by_row_desc(wgd_can_not_go_up)
  1988. };
  1989. };
  1990. /**
  1991. * Sorts an Array of grid coords objects (representing the grid coords of
  1992. * each widget) in descending way.
  1993. *
  1994. * @method manage_movements
  1995. * @param {jQuery} $widgets A jQuery collection of HTMLElements
  1996. * representing the widgets you want to move.
  1997. * @param {Number} to_col The column to which we want to move the widgets.
  1998. * @param {Number} to_row The row to which we want to move the widgets.
  1999. * @return {Class} Returns the instance of the Gridster Class.
  2000. */
  2001. fn.manage_movements = function($widgets, to_col, to_row) {
  2002. $.each($widgets, $.proxy(function(i, w) {
  2003. var wgd = w;
  2004. var $w = wgd.el;
  2005. var can_go_widget_up = this.can_go_widget_up(wgd);
  2006. if (can_go_widget_up) {
  2007. //target CAN go up
  2008. //so move widget up
  2009. this.move_widget_to($w, can_go_widget_up);
  2010. this.set_placeholder(to_col, can_go_widget_up + wgd.size_y);
  2011. } else {
  2012. //target can't go up
  2013. var can_go_player_up = this.can_go_player_up(
  2014. this.player_grid_data);
  2015. if (!can_go_player_up) {
  2016. // target can't go up
  2017. // player cant't go up
  2018. // so we need to move widget down to a position that dont
  2019. // overlaps player
  2020. var y = (to_row + this.player_grid_data.size_y) - wgd.row;
  2021. this.move_widget_down($w, y);
  2022. this.set_placeholder(to_col, to_row);
  2023. }
  2024. }
  2025. }, this));
  2026. return this;
  2027. };
  2028. /**
  2029. * Determines if there is a widget in the row and col given. Or if the
  2030. * HTMLElement passed as first argument is the player.
  2031. *
  2032. * @method is_player
  2033. * @param {Number|HTMLElement} col_or_el A jQuery wrapped collection of
  2034. * HTMLElements.
  2035. * @param {Number} [row] The column to which we want to move the widgets.
  2036. * @return {Boolean} Returns true or false.
  2037. */
  2038. fn.is_player = function(col_or_el, row) {
  2039. if (row && !this.gridmap[col_or_el]) { return false; }
  2040. var $w = row ? this.gridmap[col_or_el][row] : col_or_el;
  2041. return $w && ($w.is(this.$player) || $w.is(this.$helper));
  2042. };
  2043. /**
  2044. * Determines if the widget that is being dragged is currently over the row
  2045. * and col given.
  2046. *
  2047. * @method is_player_in
  2048. * @param {Number} col The column to check.
  2049. * @param {Number} row The row to check.
  2050. * @return {Boolean} Returns true or false.
  2051. */
  2052. fn.is_player_in = function(col, row) {
  2053. var c = this.cells_occupied_by_player || {};
  2054. return $.inArray(col, c.cols) >= 0 && $.inArray(row, c.rows) >= 0;
  2055. };
  2056. /**
  2057. * Determines if the placeholder is currently over the row and col given.
  2058. *
  2059. * @method is_placeholder_in
  2060. * @param {Number} col The column to check.
  2061. * @param {Number} row The row to check.
  2062. * @return {Boolean} Returns true or false.
  2063. */
  2064. fn.is_placeholder_in = function(col, row) {
  2065. var c = this.cells_occupied_by_placeholder || {};
  2066. return this.is_placeholder_in_col(col) && $.inArray(row, c.rows) >= 0;
  2067. };
  2068. /**
  2069. * Determines if the placeholder is currently over the column given.
  2070. *
  2071. * @method is_placeholder_in_col
  2072. * @param {Number} col The column to check.
  2073. * @return {Boolean} Returns true or false.
  2074. */
  2075. fn.is_placeholder_in_col = function(col) {
  2076. var c = this.cells_occupied_by_placeholder || [];
  2077. return $.inArray(col, c.cols) >= 0;
  2078. };
  2079. /**
  2080. * Determines if the cell represented by col and row params is empty.
  2081. *
  2082. * @method is_empty
  2083. * @param {Number} col The column to check.
  2084. * @param {Number} row The row to check.
  2085. * @return {Boolean} Returns true or false.
  2086. */
  2087. fn.is_empty = function(col, row) {
  2088. if (typeof this.gridmap[col] !== 'undefined') {
  2089. if(typeof this.gridmap[col][row] !== 'undefined' &&
  2090. this.gridmap[col][row] === false
  2091. ) {
  2092. return true;
  2093. }
  2094. return false;
  2095. }
  2096. return true;
  2097. };
  2098. /**
  2099. * Determines if the cell represented by col and row params is occupied.
  2100. *
  2101. * @method is_occupied
  2102. * @param {Number} col The column to check.
  2103. * @param {Number} row The row to check.
  2104. * @return {Boolean} Returns true or false.
  2105. */
  2106. fn.is_occupied = function(col, row) {
  2107. if (!this.gridmap[col]) {
  2108. return false;
  2109. }
  2110. if (this.gridmap[col][row]) {
  2111. return true;
  2112. }
  2113. return false;
  2114. };
  2115. /**
  2116. * Determines if there is a widget in the cell represented by col/row params.
  2117. *
  2118. * @method is_widget
  2119. * @param {Number} col The column to check.
  2120. * @param {Number} row The row to check.
  2121. * @return {Boolean|HTMLElement} Returns false if there is no widget,
  2122. * else returns the jQuery HTMLElement
  2123. */
  2124. fn.is_widget = function(col, row) {
  2125. var cell = this.gridmap[col];
  2126. if (!cell) {
  2127. return false;
  2128. }
  2129. cell = cell[row];
  2130. if (cell) {
  2131. return cell;
  2132. }
  2133. return false;
  2134. };
  2135. /**
  2136. * Determines if there is a widget in the cell represented by col/row
  2137. * params and if this is under the widget that is being dragged.
  2138. *
  2139. * @method is_widget_under_player
  2140. * @param {Number} col The column to check.
  2141. * @param {Number} row The row to check.
  2142. * @return {Boolean} Returns true or false.
  2143. */
  2144. fn.is_widget_under_player = function(col, row) {
  2145. if (this.is_widget(col, row)) {
  2146. return this.is_player_in(col, row);
  2147. }
  2148. return false;
  2149. };
  2150. /**
  2151. * Get widgets overlapping with the player or with the object passed
  2152. * representing the grid cells.
  2153. *
  2154. * @method get_widgets_under_player
  2155. * @return {HTMLElement} Returns a jQuery collection of HTMLElements
  2156. */
  2157. fn.get_widgets_under_player = function(cells) {
  2158. cells || (cells = this.cells_occupied_by_player || {cols: [], rows: []});
  2159. var $widgets = $([]);
  2160. $.each(cells.cols, $.proxy(function(i, col) {
  2161. $.each(cells.rows, $.proxy(function(i, row) {
  2162. if(this.is_widget(col, row)) {
  2163. $widgets = $widgets.add(this.gridmap[col][row]);
  2164. }
  2165. }, this));
  2166. }, this));
  2167. return $widgets;
  2168. };
  2169. /**
  2170. * Put placeholder at the row and column specified.
  2171. *
  2172. * @method set_placeholder
  2173. * @param {Number} col The column to which we want to move the
  2174. * placeholder.
  2175. * @param {Number} row The row to which we want to move the
  2176. * placeholder.
  2177. * @return {Class} Returns the instance of the Gridster Class.
  2178. */
  2179. fn.set_placeholder = function(col, row) {
  2180. var phgd = $.extend({}, this.placeholder_grid_data);
  2181. var $nexts = this.widgets_below({
  2182. col: phgd.col,
  2183. row: phgd.row,
  2184. size_y: phgd.size_y,
  2185. size_x: phgd.size_x
  2186. });
  2187. // Prevents widgets go out of the grid
  2188. var right_col = (col + phgd.size_x - 1);
  2189. if (right_col > this.cols) {
  2190. col = col - (right_col - col);
  2191. }
  2192. var moved_down = this.placeholder_grid_data.row < row;
  2193. var changed_column = this.placeholder_grid_data.col !== col;
  2194. this.placeholder_grid_data.col = col;
  2195. this.placeholder_grid_data.row = row;
  2196. this.cells_occupied_by_placeholder = this.get_cells_occupied(
  2197. this.placeholder_grid_data);
  2198. this.$preview_holder.attr({
  2199. 'data-row' : row,
  2200. 'data-col' : col
  2201. });
  2202. if (moved_down || changed_column) {
  2203. $nexts.each($.proxy(function(i, widget) {
  2204. this.move_widget_up(
  2205. $(widget), this.placeholder_grid_data.col - col + phgd.size_y);
  2206. }, this));
  2207. }
  2208. var $widgets_under_ph = this.get_widgets_under_player(
  2209. this.cells_occupied_by_placeholder);
  2210. if ($widgets_under_ph.length) {
  2211. $widgets_under_ph.each($.proxy(function(i, widget) {
  2212. var $w = $(widget);
  2213. this.move_widget_down(
  2214. $w, row + phgd.size_y - $w.data('coords').grid.row);
  2215. }, this));
  2216. }
  2217. };
  2218. /**
  2219. * Determines whether the player can move to a position above.
  2220. *
  2221. * @method can_go_player_up
  2222. * @param {Object} widget_grid_data The actual grid coords object of the
  2223. * player.
  2224. * @return {Number|Boolean} If the player can be moved to an upper row
  2225. * returns the row number, else returns false.
  2226. */
  2227. fn.can_go_player_up = function(widget_grid_data) {
  2228. var p_bottom_row = widget_grid_data.row + widget_grid_data.size_y - 1;
  2229. var result = true;
  2230. var upper_rows = [];
  2231. var min_row = 10000;
  2232. var $widgets_under_player = this.get_widgets_under_player();
  2233. /* generate an array with columns as index and array with upper rows
  2234. * empty as value */
  2235. this.for_each_column_occupied(widget_grid_data, function(tcol) {
  2236. var grid_col = this.gridmap[tcol];
  2237. var r = p_bottom_row + 1;
  2238. upper_rows[tcol] = [];
  2239. while (--r > 0) {
  2240. if (this.is_empty(tcol, r) || this.is_player(tcol, r) ||
  2241. this.is_widget(tcol, r) &&
  2242. grid_col[r].is($widgets_under_player)
  2243. ) {
  2244. upper_rows[tcol].push(r);
  2245. min_row = r < min_row ? r : min_row;
  2246. } else {
  2247. break;
  2248. }
  2249. }
  2250. if (upper_rows[tcol].length === 0) {
  2251. result = false;
  2252. return true; //break
  2253. }
  2254. upper_rows[tcol].sort(function(a, b) {
  2255. return a - b;
  2256. });
  2257. });
  2258. if (!result) { return false; }
  2259. return this.get_valid_rows(widget_grid_data, upper_rows, min_row);
  2260. };
  2261. /**
  2262. * Determines whether a widget can move to a position above.
  2263. *
  2264. * @method can_go_widget_up
  2265. * @param {Object} widget_grid_data The actual grid coords object of the
  2266. * widget we want to check.
  2267. * @return {Number|Boolean} If the widget can be moved to an upper row
  2268. * returns the row number, else returns false.
  2269. */
  2270. fn.can_go_widget_up = function(widget_grid_data) {
  2271. var p_bottom_row = widget_grid_data.row + widget_grid_data.size_y - 1;
  2272. var result = true;
  2273. var upper_rows = [];
  2274. var min_row = 10000;
  2275. /* generate an array with columns as index and array with topmost rows
  2276. * empty as value */
  2277. this.for_each_column_occupied(widget_grid_data, function(tcol) {
  2278. var grid_col = this.gridmap[tcol];
  2279. upper_rows[tcol] = [];
  2280. var r = p_bottom_row + 1;
  2281. // iterate over each row
  2282. while (--r > 0) {
  2283. if (this.is_widget(tcol, r) && !this.is_player_in(tcol, r)) {
  2284. if (!grid_col[r].is(widget_grid_data.el)) {
  2285. break;
  2286. }
  2287. }
  2288. if (!this.is_player(tcol, r) &&
  2289. !this.is_placeholder_in(tcol, r) &&
  2290. !this.is_player_in(tcol, r)) {
  2291. upper_rows[tcol].push(r);
  2292. }
  2293. if (r < min_row) {
  2294. min_row = r;
  2295. }
  2296. }
  2297. if (upper_rows[tcol].length === 0) {
  2298. result = false;
  2299. return true; //break
  2300. }
  2301. upper_rows[tcol].sort(function(a, b) {
  2302. return a - b;
  2303. });
  2304. });
  2305. if (!result) { return false; }
  2306. return this.get_valid_rows(widget_grid_data, upper_rows, min_row);
  2307. };
  2308. /**
  2309. * Search a valid row for the widget represented by `widget_grid_data' in
  2310. * the `upper_rows` array. Iteration starts from row specified in `min_row`.
  2311. *
  2312. * @method get_valid_rows
  2313. * @param {Object} widget_grid_data The actual grid coords object of the
  2314. * player.
  2315. * @param {Array} upper_rows An array with columns as index and arrays
  2316. * of valid rows as values.
  2317. * @param {Number} min_row The upper row from which the iteration will start.
  2318. * @return {Number|Boolean} Returns the upper row valid from the `upper_rows`
  2319. * for the widget in question.
  2320. */
  2321. fn.get_valid_rows = function(widget_grid_data, upper_rows, min_row) {
  2322. var p_top_row = widget_grid_data.row;
  2323. var p_bottom_row = widget_grid_data.row + widget_grid_data.size_y - 1;
  2324. var size_y = widget_grid_data.size_y;
  2325. var r = min_row - 1;
  2326. var valid_rows = [];
  2327. while (++r <= p_bottom_row ) {
  2328. var common = true;
  2329. $.each(upper_rows, function(col, rows) {
  2330. if ($.isArray(rows) && $.inArray(r, rows) === -1) {
  2331. common = false;
  2332. }
  2333. });
  2334. if (common === true) {
  2335. valid_rows.push(r);
  2336. if (valid_rows.length === size_y) {
  2337. break;
  2338. }
  2339. }
  2340. }
  2341. var new_row = false;
  2342. if (size_y === 1) {
  2343. if (valid_rows[0] !== p_top_row) {
  2344. new_row = valid_rows[0] || false;
  2345. }
  2346. } else {
  2347. if (valid_rows[0] !== p_top_row) {
  2348. new_row = this.get_consecutive_numbers_index(
  2349. valid_rows, size_y);
  2350. }
  2351. }
  2352. return new_row;
  2353. };
  2354. fn.get_consecutive_numbers_index = function(arr, size_y) {
  2355. var max = arr.length;
  2356. var result = [];
  2357. var first = true;
  2358. var prev = -1; // or null?
  2359. for (var i=0; i < max; i++) {
  2360. if (first || arr[i] === prev + 1) {
  2361. result.push(i);
  2362. if (result.length === size_y) {
  2363. break;
  2364. }
  2365. first = false;
  2366. } else {
  2367. result = [];
  2368. first = true;
  2369. }
  2370. prev = arr[i];
  2371. }
  2372. return result.length >= size_y ? arr[result[0]] : false;
  2373. };
  2374. /**
  2375. * Get widgets overlapping with the player.
  2376. *
  2377. * @method get_widgets_overlapped
  2378. * @return {jQuery} Returns a jQuery collection of HTMLElements.
  2379. */
  2380. fn.get_widgets_overlapped = function() {
  2381. var $w;
  2382. var $widgets = $([]);
  2383. var used = [];
  2384. var rows_from_bottom = this.cells_occupied_by_player.rows.slice(0);
  2385. rows_from_bottom.reverse();
  2386. $.each(this.cells_occupied_by_player.cols, $.proxy(function(i, col) {
  2387. $.each(rows_from_bottom, $.proxy(function(i, row) {
  2388. // if there is a widget in the player position
  2389. if (!this.gridmap[col]) { return true; } //next iteration
  2390. var $w = this.gridmap[col][row];
  2391. if (this.is_occupied(col, row) && !this.is_player($w) &&
  2392. $.inArray($w, used) === -1
  2393. ) {
  2394. $widgets = $widgets.add($w);
  2395. used.push($w);
  2396. }
  2397. }, this));
  2398. }, this));
  2399. return $widgets;
  2400. };
  2401. /**
  2402. * This callback is executed when the player begins to collide with a column.
  2403. *
  2404. * @method on_start_overlapping_column
  2405. * @param {Number} col The collided column.
  2406. * @return {jQuery} Returns a jQuery collection of HTMLElements.
  2407. */
  2408. fn.on_start_overlapping_column = function(col) {
  2409. this.set_player(col, false);
  2410. };
  2411. /**
  2412. * A callback executed when the player begins to collide with a row.
  2413. *
  2414. * @method on_start_overlapping_row
  2415. * @param {Number} row The collided row.
  2416. * @return {jQuery} Returns a jQuery collection of HTMLElements.
  2417. */
  2418. fn.on_start_overlapping_row = function(row) {
  2419. this.set_player(false, row);
  2420. };
  2421. /**
  2422. * A callback executed when the the player ends to collide with a column.
  2423. *
  2424. * @method on_stop_overlapping_column
  2425. * @param {Number} col The collided row.
  2426. * @return {jQuery} Returns a jQuery collection of HTMLElements.
  2427. */
  2428. fn.on_stop_overlapping_column = function(col) {
  2429. this.set_player(col, false);
  2430. var self = this;
  2431. this.for_each_widget_below(col, this.cells_occupied_by_player.rows[0],
  2432. function(tcol, trow) {
  2433. self.move_widget_up(this, self.player_grid_data.size_y);
  2434. });
  2435. };
  2436. /**
  2437. * This callback is executed when the player ends to collide with a row.
  2438. *
  2439. * @method on_stop_overlapping_row
  2440. * @param {Number} row The collided row.
  2441. * @return {jQuery} Returns a jQuery collection of HTMLElements.
  2442. */
  2443. fn.on_stop_overlapping_row = function(row) {
  2444. this.set_player(false, row);
  2445. var self = this;
  2446. var cols = this.cells_occupied_by_player.cols;
  2447. for (var c = 0, cl = cols.length; c < cl; c++) {
  2448. this.for_each_widget_below(cols[c], row, function(tcol, trow) {
  2449. self.move_widget_up(this, self.player_grid_data.size_y);
  2450. });
  2451. }
  2452. };
  2453. /**
  2454. * Move a widget to a specific row. The cell or cells must be empty.
  2455. * If the widget has widgets below, all of these widgets will be moved also
  2456. * if they can.
  2457. *
  2458. * @method move_widget_to
  2459. * @param {HTMLElement} $widget The jQuery wrapped HTMLElement of the
  2460. * widget is going to be moved.
  2461. * @return {Class} Returns the instance of the Gridster Class.
  2462. */
  2463. fn.move_widget_to = function($widget, row) {
  2464. var self = this;
  2465. var widget_grid_data = $widget.coords().grid;
  2466. var diff = row - widget_grid_data.row;
  2467. var $next_widgets = this.widgets_below($widget);
  2468. var can_move_to_new_cell = this.can_move_to(
  2469. widget_grid_data, widget_grid_data.col, row, $widget);
  2470. if (can_move_to_new_cell === false) {
  2471. return false;
  2472. }
  2473. this.remove_from_gridmap(widget_grid_data);
  2474. widget_grid_data.row = row;
  2475. this.add_to_gridmap(widget_grid_data);
  2476. $widget.attr('data-row', row);
  2477. this.$changed = this.$changed.add($widget);
  2478. $next_widgets.each(function(i, widget) {
  2479. var $w = $(widget);
  2480. var wgd = $w.coords().grid;
  2481. var can_go_up = self.can_go_widget_up(wgd);
  2482. if (can_go_up && can_go_up !== wgd.row) {
  2483. self.move_widget_to($w, can_go_up);
  2484. }
  2485. });
  2486. return this;
  2487. };
  2488. /**
  2489. * Move up the specified widget and all below it.
  2490. *
  2491. * @method move_widget_up
  2492. * @param {HTMLElement} $widget The widget you want to move.
  2493. * @param {Number} [y_units] The number of cells that the widget has to move.
  2494. * @return {Class} Returns the instance of the Gridster Class.
  2495. */
  2496. fn.move_widget_up = function($widget, y_units) {
  2497. var el_grid_data = $widget.coords().grid;
  2498. var actual_row = el_grid_data.row;
  2499. var moved = [];
  2500. var can_go_up = true;
  2501. y_units || (y_units = 1);
  2502. if (!this.can_go_up($widget)) { return false; } //break;
  2503. this.for_each_column_occupied(el_grid_data, function(col) {
  2504. // can_go_up
  2505. if ($.inArray($widget, moved) === -1) {
  2506. var widget_grid_data = $widget.coords().grid;
  2507. var next_row = actual_row - y_units;
  2508. next_row = this.can_go_up_to_row(
  2509. widget_grid_data, col, next_row);
  2510. if (!next_row) {
  2511. return true;
  2512. }
  2513. var $next_widgets = this.widgets_below($widget);
  2514. this.remove_from_gridmap(widget_grid_data);
  2515. widget_grid_data.row = next_row;
  2516. this.add_to_gridmap(widget_grid_data);
  2517. $widget.attr('data-row', widget_grid_data.row);
  2518. this.$changed = this.$changed.add($widget);
  2519. moved.push($widget);
  2520. $next_widgets.each($.proxy(function(i, widget) {
  2521. this.move_widget_up($(widget), y_units);
  2522. }, this));
  2523. }
  2524. });
  2525. };
  2526. /**
  2527. * Move down the specified widget and all below it.
  2528. *
  2529. * @method move_widget_down
  2530. * @param {jQuery} $widget The jQuery object representing the widget
  2531. * you want to move.
  2532. * @param {Number} y_units The number of cells that the widget has to move.
  2533. * @return {Class} Returns the instance of the Gridster Class.
  2534. */
  2535. fn.move_widget_down = function($widget, y_units) {
  2536. var el_grid_data, actual_row, moved, y_diff;
  2537. if (y_units <= 0) { return false; }
  2538. el_grid_data = $widget.coords().grid;
  2539. actual_row = el_grid_data.row;
  2540. moved = [];
  2541. y_diff = y_units;
  2542. if (!$widget) { return false; }
  2543. if ($.inArray($widget, moved) === -1) {
  2544. var widget_grid_data = $widget.coords().grid;
  2545. var next_row = actual_row + y_units;
  2546. var $next_widgets = this.widgets_below($widget);
  2547. this.remove_from_gridmap(widget_grid_data);
  2548. $next_widgets.each($.proxy(function(i, widget) {
  2549. var $w = $(widget);
  2550. var wd = $w.coords().grid;
  2551. var tmp_y = this.displacement_diff(
  2552. wd, widget_grid_data, y_diff);
  2553. if (tmp_y > 0) {
  2554. this.move_widget_down($w, tmp_y);
  2555. }
  2556. }, this));
  2557. widget_grid_data.row = next_row;
  2558. this.update_widget_position(widget_grid_data, $widget);
  2559. $widget.attr('data-row', widget_grid_data.row);
  2560. this.$changed = this.$changed.add($widget);
  2561. moved.push($widget);
  2562. }
  2563. };
  2564. /**
  2565. * Check if the widget can move to the specified row, else returns the
  2566. * upper row possible.
  2567. *
  2568. * @method can_go_up_to_row
  2569. * @param {Number} widget_grid_data The current grid coords object of the
  2570. * widget.
  2571. * @param {Number} col The target column.
  2572. * @param {Number} row The target row.
  2573. * @return {Boolean|Number} Returns the row number if the widget can move
  2574. * to the target position, else returns false.
  2575. */
  2576. fn.can_go_up_to_row = function(widget_grid_data, col, row) {
  2577. var ga = this.gridmap;
  2578. var result = true;
  2579. var urc = []; // upper_rows_in_columns
  2580. var actual_row = widget_grid_data.row;
  2581. var r;
  2582. /* generate an array with columns as index and array with
  2583. * upper rows empty in the column */
  2584. this.for_each_column_occupied(widget_grid_data, function(tcol) {
  2585. var grid_col = ga[tcol];
  2586. urc[tcol] = [];
  2587. r = actual_row;
  2588. while (r--) {
  2589. if (this.is_empty(tcol, r) &&
  2590. !this.is_placeholder_in(tcol, r)
  2591. ) {
  2592. urc[tcol].push(r);
  2593. } else {
  2594. break;
  2595. }
  2596. }
  2597. if (!urc[tcol].length) {
  2598. result = false;
  2599. return true;
  2600. }
  2601. });
  2602. if (!result) { return false; }
  2603. /* get common rows starting from upper position in all the columns
  2604. * that widget occupies */
  2605. r = row;
  2606. for (r = 1; r < actual_row; r++) {
  2607. var common = true;
  2608. for (var uc = 0, ucl = urc.length; uc < ucl; uc++) {
  2609. if (urc[uc] && $.inArray(r, urc[uc]) === -1) {
  2610. common = false;
  2611. }
  2612. }
  2613. if (common === true) {
  2614. result = r;
  2615. break;
  2616. }
  2617. }
  2618. return result;
  2619. };
  2620. fn.displacement_diff = function(widget_grid_data, parent_bgd, y_units) {
  2621. var actual_row = widget_grid_data.row;
  2622. var diffs = [];
  2623. var parent_max_y = parent_bgd.row + parent_bgd.size_y;
  2624. this.for_each_column_occupied(widget_grid_data, function(col) {
  2625. var temp_y_units = 0;
  2626. for (var r = parent_max_y; r < actual_row; r++) {
  2627. if (this.is_empty(col, r)) {
  2628. temp_y_units = temp_y_units + 1;
  2629. }
  2630. }
  2631. diffs.push(temp_y_units);
  2632. });
  2633. var max_diff = Math.max.apply(Math, diffs);
  2634. y_units = (y_units - max_diff);
  2635. return y_units > 0 ? y_units : 0;
  2636. };
  2637. /**
  2638. * Get widgets below a widget.
  2639. *
  2640. * @method widgets_below
  2641. * @param {HTMLElement} $el The jQuery wrapped HTMLElement.
  2642. * @return {jQuery} A jQuery collection of HTMLElements.
  2643. */
  2644. fn.widgets_below = function($el) {
  2645. var el_grid_data = $.isPlainObject($el) ? $el : $el.coords().grid;
  2646. var self = this;
  2647. var ga = this.gridmap;
  2648. var next_row = el_grid_data.row + el_grid_data.size_y - 1;
  2649. var $nexts = $([]);
  2650. this.for_each_column_occupied(el_grid_data, function(col) {
  2651. self.for_each_widget_below(col, next_row, function(tcol, trow) {
  2652. if (!self.is_player(this) && $.inArray(this, $nexts) === -1) {
  2653. $nexts = $nexts.add(this);
  2654. return true; // break
  2655. }
  2656. });
  2657. });
  2658. return Gridster.sort_by_row_asc($nexts);
  2659. };
  2660. /**
  2661. * Update the array of mapped positions with the new player position.
  2662. *
  2663. * @method set_cells_player_occupies
  2664. * @param {Number} col The new player col.
  2665. * @param {Number} col The new player row.
  2666. * @return {Class} Returns the instance of the Gridster Class.
  2667. */
  2668. fn.set_cells_player_occupies = function(col, row) {
  2669. this.remove_from_gridmap(this.placeholder_grid_data);
  2670. this.placeholder_grid_data.col = col;
  2671. this.placeholder_grid_data.row = row;
  2672. this.add_to_gridmap(this.placeholder_grid_data, this.$player);
  2673. return this;
  2674. };
  2675. /**
  2676. * Remove from the array of mapped positions the reference to the player.
  2677. *
  2678. * @method empty_cells_player_occupies
  2679. * @return {Class} Returns the instance of the Gridster Class.
  2680. */
  2681. fn.empty_cells_player_occupies = function() {
  2682. this.remove_from_gridmap(this.placeholder_grid_data);
  2683. return this;
  2684. };
  2685. fn.can_go_up = function($el) {
  2686. var el_grid_data = $el.coords().grid;
  2687. var initial_row = el_grid_data.row;
  2688. var prev_row = initial_row - 1;
  2689. var ga = this.gridmap;
  2690. var upper_rows_by_column = [];
  2691. var result = true;
  2692. if (initial_row === 1) { return false; }
  2693. this.for_each_column_occupied(el_grid_data, function(col) {
  2694. var $w = this.is_widget(col, prev_row);
  2695. if (this.is_occupied(col, prev_row) ||
  2696. this.is_player(col, prev_row) ||
  2697. this.is_placeholder_in(col, prev_row) ||
  2698. this.is_player_in(col, prev_row)
  2699. ) {
  2700. result = false;
  2701. return true; //break
  2702. }
  2703. });
  2704. return result;
  2705. };
  2706. /**
  2707. * Check if it's possible to move a widget to a specific col/row. It takes
  2708. * into account the dimensions (`size_y` and `size_x` attrs. of the grid
  2709. * coords object) the widget occupies.
  2710. *
  2711. * @method can_move_to
  2712. * @param {Object} widget_grid_data The grid coords object that represents
  2713. * the widget.
  2714. * @param {Object} col The col to check.
  2715. * @param {Object} row The row to check.
  2716. * @param {Number} [max_row] The max row allowed.
  2717. * @return {Boolean} Returns true if all cells are empty, else return false.
  2718. */
  2719. fn.can_move_to = function(widget_grid_data, col, row, max_row) {
  2720. var ga = this.gridmap;
  2721. var $w = widget_grid_data.el;
  2722. var future_wd = {
  2723. size_y: widget_grid_data.size_y,
  2724. size_x: widget_grid_data.size_x,
  2725. col: col,
  2726. row: row
  2727. };
  2728. var result = true;
  2729. //Prevents widgets go out of the grid
  2730. var right_col = col + widget_grid_data.size_x - 1;
  2731. if (right_col > this.cols) {
  2732. return false;
  2733. }
  2734. if (max_row && max_row < row + widget_grid_data.size_y - 1) {
  2735. return false;
  2736. }
  2737. this.for_each_cell_occupied(future_wd, function(tcol, trow) {
  2738. var $tw = this.is_widget(tcol, trow);
  2739. if ($tw && (!widget_grid_data.el || $tw.is($w))) {
  2740. result = false;
  2741. }
  2742. });
  2743. return result;
  2744. };
  2745. /**
  2746. * Given the leftmost column returns all columns that are overlapping
  2747. * with the player.
  2748. *
  2749. * @method get_targeted_columns
  2750. * @param {Number} [from_col] The leftmost column.
  2751. * @return {Array} Returns an array with column numbers.
  2752. */
  2753. fn.get_targeted_columns = function(from_col) {
  2754. var max = (from_col || this.player_grid_data.col) +
  2755. (this.player_grid_data.size_x - 1);
  2756. var cols = [];
  2757. for (var col = from_col; col <= max; col++) {
  2758. cols.push(col);
  2759. }
  2760. return cols;
  2761. };
  2762. /**
  2763. * Given the upper row returns all rows that are overlapping with the player.
  2764. *
  2765. * @method get_targeted_rows
  2766. * @param {Number} [from_row] The upper row.
  2767. * @return {Array} Returns an array with row numbers.
  2768. */
  2769. fn.get_targeted_rows = function(from_row) {
  2770. var max = (from_row || this.player_grid_data.row) +
  2771. (this.player_grid_data.size_y - 1);
  2772. var rows = [];
  2773. for (var row = from_row; row <= max; row++) {
  2774. rows.push(row);
  2775. }
  2776. return rows;
  2777. };
  2778. /**
  2779. * Get all columns and rows that a widget occupies.
  2780. *
  2781. * @method get_cells_occupied
  2782. * @param {Object} el_grid_data The grid coords object of the widget.
  2783. * @return {Object} Returns an object like `{ cols: [], rows: []}`.
  2784. */
  2785. fn.get_cells_occupied = function(el_grid_data) {
  2786. var cells = { cols: [], rows: []};
  2787. var i;
  2788. if (arguments[1] instanceof $) {
  2789. el_grid_data = arguments[1].coords().grid;
  2790. }
  2791. for (i = 0; i < el_grid_data.size_x; i++) {
  2792. var col = el_grid_data.col + i;
  2793. cells.cols.push(col);
  2794. }
  2795. for (i = 0; i < el_grid_data.size_y; i++) {
  2796. var row = el_grid_data.row + i;
  2797. cells.rows.push(row);
  2798. }
  2799. return cells;
  2800. };
  2801. /**
  2802. * Iterate over the cells occupied by a widget executing a function for
  2803. * each one.
  2804. *
  2805. * @method for_each_cell_occupied
  2806. * @param {Object} el_grid_data The grid coords object that represents the
  2807. * widget.
  2808. * @param {Function} callback The function to execute on each column
  2809. * iteration. Column and row are passed as arguments.
  2810. * @return {Class} Returns the instance of the Gridster Class.
  2811. */
  2812. fn.for_each_cell_occupied = function(grid_data, callback) {
  2813. this.for_each_column_occupied(grid_data, function(col) {
  2814. this.for_each_row_occupied(grid_data, function(row) {
  2815. callback.call(this, col, row);
  2816. });
  2817. });
  2818. return this;
  2819. };
  2820. /**
  2821. * Iterate over the columns occupied by a widget executing a function for
  2822. * each one.
  2823. *
  2824. * @method for_each_column_occupied
  2825. * @param {Object} el_grid_data The grid coords object that represents
  2826. * the widget.
  2827. * @param {Function} callback The function to execute on each column
  2828. * iteration. The column number is passed as first argument.
  2829. * @return {Class} Returns the instance of the Gridster Class.
  2830. */
  2831. fn.for_each_column_occupied = function(el_grid_data, callback) {
  2832. for (var i = 0; i < el_grid_data.size_x; i++) {
  2833. var col = el_grid_data.col + i;
  2834. callback.call(this, col, el_grid_data);
  2835. }
  2836. };
  2837. /**
  2838. * Iterate over the rows occupied by a widget executing a function for
  2839. * each one.
  2840. *
  2841. * @method for_each_row_occupied
  2842. * @param {Object} el_grid_data The grid coords object that represents
  2843. * the widget.
  2844. * @param {Function} callback The function to execute on each column
  2845. * iteration. The row number is passed as first argument.
  2846. * @return {Class} Returns the instance of the Gridster Class.
  2847. */
  2848. fn.for_each_row_occupied = function(el_grid_data, callback) {
  2849. for (var i = 0; i < el_grid_data.size_y; i++) {
  2850. var row = el_grid_data.row + i;
  2851. callback.call(this, row, el_grid_data);
  2852. }
  2853. };
  2854. fn._traversing_widgets = function(type, direction, col, row, callback) {
  2855. var ga = this.gridmap;
  2856. if (!ga[col]) { return; }
  2857. var cr, max;
  2858. var action = type + '/' + direction;
  2859. if (arguments[2] instanceof $) {
  2860. var el_grid_data = arguments[2].coords().grid;
  2861. col = el_grid_data.col;
  2862. row = el_grid_data.row;
  2863. callback = arguments[3];
  2864. }
  2865. var matched = [];
  2866. var trow = row;
  2867. var methods = {
  2868. 'for_each/above': function() {
  2869. while (trow--) {
  2870. if (trow > 0 && this.is_widget(col, trow) &&
  2871. $.inArray(ga[col][trow], matched) === -1
  2872. ) {
  2873. cr = callback.call(ga[col][trow], col, trow);
  2874. matched.push(ga[col][trow]);
  2875. if (cr) { break; }
  2876. }
  2877. }
  2878. },
  2879. 'for_each/below': function() {
  2880. for (trow = row + 1, max = ga[col].length; trow < max; trow++) {
  2881. if (this.is_widget(col, trow) &&
  2882. $.inArray(ga[col][trow], matched) === -1
  2883. ) {
  2884. cr = callback.call(ga[col][trow], col, trow);
  2885. matched.push(ga[col][trow]);
  2886. if (cr) { break; }
  2887. }
  2888. }
  2889. }
  2890. };
  2891. if (methods[action]) {
  2892. methods[action].call(this);
  2893. }
  2894. };
  2895. /**
  2896. * Iterate over each widget above the column and row specified.
  2897. *
  2898. * @method for_each_widget_above
  2899. * @param {Number} col The column to start iterating.
  2900. * @param {Number} row The row to start iterating.
  2901. * @param {Function} callback The function to execute on each widget
  2902. * iteration. The value of `this` inside the function is the jQuery
  2903. * wrapped HTMLElement.
  2904. * @return {Class} Returns the instance of the Gridster Class.
  2905. */
  2906. fn.for_each_widget_above = function(col, row, callback) {
  2907. this._traversing_widgets('for_each', 'above', col, row, callback);
  2908. return this;
  2909. };
  2910. /**
  2911. * Iterate over each widget below the column and row specified.
  2912. *
  2913. * @method for_each_widget_below
  2914. * @param {Number} col The column to start iterating.
  2915. * @param {Number} row The row to start iterating.
  2916. * @param {Function} callback The function to execute on each widget
  2917. * iteration. The value of `this` inside the function is the jQuery wrapped
  2918. * HTMLElement.
  2919. * @return {Class} Returns the instance of the Gridster Class.
  2920. */
  2921. fn.for_each_widget_below = function(col, row, callback) {
  2922. this._traversing_widgets('for_each', 'below', col, row, callback);
  2923. return this;
  2924. };
  2925. /**
  2926. * Returns the highest occupied cell in the grid.
  2927. *
  2928. * @method get_highest_occupied_cell
  2929. * @return {Object} Returns an object with `col` and `row` numbers.
  2930. */
  2931. fn.get_highest_occupied_cell = function() {
  2932. var r;
  2933. var gm = this.gridmap;
  2934. var rl = gm[1].length;
  2935. var rows = [], cols = [];
  2936. var row_in_col = [];
  2937. for (var c = gm.length - 1; c >= 1; c--) {
  2938. for (r = rl - 1; r >= 1; r--) {
  2939. if (this.is_widget(c, r)) {
  2940. rows.push(r);
  2941. cols.push(c);
  2942. break;
  2943. }
  2944. }
  2945. }
  2946. return {
  2947. col: Math.max.apply(Math, cols),
  2948. row: Math.max.apply(Math, rows)
  2949. };
  2950. };
  2951. fn.get_widgets_from = function(col, row) {
  2952. var ga = this.gridmap;
  2953. var $widgets = $();
  2954. if (col) {
  2955. $widgets = $widgets.add(
  2956. this.$widgets.filter(function() {
  2957. var tcol = $(this).attr('data-col');
  2958. return (tcol === col || tcol > col);
  2959. })
  2960. );
  2961. }
  2962. if (row) {
  2963. $widgets = $widgets.add(
  2964. this.$widgets.filter(function() {
  2965. var trow = $(this).attr('data-row');
  2966. return (trow === row || trow > row);
  2967. })
  2968. );
  2969. }
  2970. return $widgets;
  2971. };
  2972. /**
  2973. * Set the current height of the parent grid.
  2974. *
  2975. * @method set_dom_grid_height
  2976. * @return {Object} Returns the instance of the Gridster class.
  2977. */
  2978. fn.set_dom_grid_height = function(height) {
  2979. if (typeof height === 'undefined') {
  2980. var r = this.get_highest_occupied_cell().row;
  2981. height = r * this.min_widget_height;
  2982. }
  2983. this.container_height = height;
  2984. this.$el.css('height', this.container_height);
  2985. return this;
  2986. };
  2987. /**
  2988. * Set the current width of the parent grid.
  2989. *
  2990. * @method set_dom_grid_width
  2991. * @return {Object} Returns the instance of the Gridster class.
  2992. */
  2993. fn.set_dom_grid_width = function(cols) {
  2994. if (typeof cols === 'undefined') {
  2995. cols = this.get_highest_occupied_cell().col;
  2996. }
  2997. var max_cols = (this.options.autogrow_cols ? this.options.max_cols :
  2998. this.cols);
  2999. cols = Math.min(max_cols, Math.max(cols, this.options.min_cols));
  3000. this.container_width = cols * this.min_widget_width;
  3001. this.$el.css('width', this.container_width);
  3002. return this;
  3003. };
  3004. /**
  3005. * It generates the neccessary styles to position the widgets.
  3006. *
  3007. * @method generate_stylesheet
  3008. * @param {Number} rows Number of columns.
  3009. * @param {Number} cols Number of rows.
  3010. * @return {Object} Returns the instance of the Gridster class.
  3011. */
  3012. fn.generate_stylesheet = function(opts) {
  3013. var styles = '';
  3014. var max_size_x = this.options.max_size_x || this.cols;
  3015. var max_rows = 0;
  3016. var max_cols = 0;
  3017. var i;
  3018. var rules;
  3019. opts || (opts = {});
  3020. opts.cols || (opts.cols = this.cols);
  3021. opts.rows || (opts.rows = this.rows);
  3022. opts.namespace || (opts.namespace = this.options.namespace);
  3023. opts.widget_base_dimensions ||
  3024. (opts.widget_base_dimensions = this.options.widget_base_dimensions);
  3025. opts.widget_margins ||
  3026. (opts.widget_margins = this.options.widget_margins);
  3027. opts.min_widget_width = (opts.widget_margins[0] * 2) +
  3028. opts.widget_base_dimensions[0];
  3029. opts.min_widget_height = (opts.widget_margins[1] * 2) +
  3030. opts.widget_base_dimensions[1];
  3031. // don't duplicate stylesheets for the same configuration
  3032. var serialized_opts = $.param(opts);
  3033. if ($.inArray(serialized_opts, Gridster.generated_stylesheets) >= 0) {
  3034. return false;
  3035. }
  3036. this.generated_stylesheets.push(serialized_opts);
  3037. Gridster.generated_stylesheets.push(serialized_opts);
  3038. /* generate CSS styles for cols */
  3039. for (i = opts.cols; i >= 0; i--) {
  3040. styles += (opts.namespace + ' [data-col="'+ (i + 1) + '"] { left:' +
  3041. ((i * opts.widget_base_dimensions[0]) +
  3042. (i * opts.widget_margins[0]) +
  3043. ((i + 1) * opts.widget_margins[0])) + 'px; }\n');
  3044. }
  3045. /* generate CSS styles for rows */
  3046. for (i = opts.rows; i >= 0; i--) {
  3047. styles += (opts.namespace + ' [data-row="' + (i + 1) + '"] { top:' +
  3048. ((i * opts.widget_base_dimensions[1]) +
  3049. (i * opts.widget_margins[1]) +
  3050. ((i + 1) * opts.widget_margins[1]) ) + 'px; }\n');
  3051. }
  3052. for (var y = 1; y <= opts.rows; y++) {
  3053. styles += (opts.namespace + ' [data-sizey="' + y + '"] { height:' +
  3054. (y * opts.widget_base_dimensions[1] +
  3055. (y - 1) * (opts.widget_margins[1] * 2)) + 'px; }\n');
  3056. }
  3057. for (var x = 1; x <= max_size_x; x++) {
  3058. styles += (opts.namespace + ' [data-sizex="' + x + '"] { width:' +
  3059. (x * opts.widget_base_dimensions[0] +
  3060. (x - 1) * (opts.widget_margins[0] * 2)) + 'px; }\n');
  3061. }
  3062. this.remove_style_tags();
  3063. return this.add_style_tag(styles);
  3064. };
  3065. /**
  3066. * Injects the given CSS as string to the head of the document.
  3067. *
  3068. * @method add_style_tag
  3069. * @param {String} css The styles to apply.
  3070. * @return {Object} Returns the instance of the Gridster class.
  3071. */
  3072. fn.add_style_tag = function(css) {
  3073. var d = document;
  3074. var tag = d.createElement('style');
  3075. d.getElementsByTagName('head')[0].appendChild(tag);
  3076. tag.setAttribute('type', 'text/css');
  3077. if (tag.styleSheet) {
  3078. tag.styleSheet.cssText = css;
  3079. } else {
  3080. tag.appendChild(document.createTextNode(css));
  3081. }
  3082. this.$style_tags = this.$style_tags.add(tag);
  3083. return this;
  3084. };
  3085. /**
  3086. * Remove the style tag with the associated id from the head of the document
  3087. *
  3088. * @method remove_style_tag
  3089. * @return {Object} Returns the instance of the Gridster class.
  3090. */
  3091. fn.remove_style_tags = function() {
  3092. var all_styles = Gridster.generated_stylesheets;
  3093. var ins_styles = this.generated_stylesheets;
  3094. this.$style_tags.remove();
  3095. Gridster.generated_stylesheets = $.map(all_styles, function(s) {
  3096. if ($.inArray(s, ins_styles) === -1) { return s; }
  3097. });
  3098. };
  3099. /**
  3100. * Generates a faux grid to collide with it when a widget is dragged and
  3101. * detect row or column that we want to go.
  3102. *
  3103. * @method generate_faux_grid
  3104. * @param {Number} rows Number of columns.
  3105. * @param {Number} cols Number of rows.
  3106. * @return {Object} Returns the instance of the Gridster class.
  3107. */
  3108. fn.generate_faux_grid = function(rows, cols) {
  3109. this.faux_grid = [];
  3110. this.gridmap = [];
  3111. var col;
  3112. var row;
  3113. for (col = cols; col > 0; col--) {
  3114. this.gridmap[col] = [];
  3115. for (row = rows; row > 0; row--) {
  3116. this.add_faux_cell(row, col);
  3117. }
  3118. }
  3119. return this;
  3120. };
  3121. /**
  3122. * Add cell to the faux grid.
  3123. *
  3124. * @method add_faux_cell
  3125. * @param {Number} row The row for the new faux cell.
  3126. * @param {Number} col The col for the new faux cell.
  3127. * @return {Object} Returns the instance of the Gridster class.
  3128. */
  3129. fn.add_faux_cell = function(row, col) {
  3130. var coords = $({
  3131. left: this.baseX + ((col - 1) * this.min_widget_width),
  3132. top: this.baseY + (row -1) * this.min_widget_height,
  3133. width: this.min_widget_width,
  3134. height: this.min_widget_height,
  3135. col: col,
  3136. row: row,
  3137. original_col: col,
  3138. original_row: row
  3139. }).coords();
  3140. if (!$.isArray(this.gridmap[col])) {
  3141. this.gridmap[col] = [];
  3142. }
  3143. this.gridmap[col][row] = false;
  3144. this.faux_grid.push(coords);
  3145. return this;
  3146. };
  3147. /**
  3148. * Add rows to the faux grid.
  3149. *
  3150. * @method add_faux_rows
  3151. * @param {Number} rows The number of rows you want to add to the faux grid.
  3152. * @return {Object} Returns the instance of the Gridster class.
  3153. */
  3154. fn.add_faux_rows = function(rows) {
  3155. var actual_rows = this.rows;
  3156. var max_rows = actual_rows + (rows || 1);
  3157. for (var r = max_rows; r > actual_rows; r--) {
  3158. for (var c = this.cols; c >= 1; c--) {
  3159. this.add_faux_cell(r, c);
  3160. }
  3161. }
  3162. this.rows = max_rows;
  3163. if (this.options.autogenerate_stylesheet) {
  3164. this.generate_stylesheet();
  3165. }
  3166. return this;
  3167. };
  3168. /**
  3169. * Add cols to the faux grid.
  3170. *
  3171. * @method add_faux_cols
  3172. * @param {Number} cols The number of cols you want to add to the faux grid.
  3173. * @return {Object} Returns the instance of the Gridster class.
  3174. */
  3175. fn.add_faux_cols = function(cols) {
  3176. var actual_cols = this.cols;
  3177. var max_cols = actual_cols + (cols || 1);
  3178. max_cols = Math.min(max_cols, this.options.max_cols);
  3179. for (var c = actual_cols + 1; c <= max_cols; c++) {
  3180. for (var r = this.rows; r >= 1; r--) {
  3181. this.add_faux_cell(r, c);
  3182. }
  3183. }
  3184. this.cols = max_cols;
  3185. if (this.options.autogenerate_stylesheet) {
  3186. this.generate_stylesheet();
  3187. }
  3188. return this;
  3189. };
  3190. /**
  3191. * Recalculates the offsets for the faux grid. You need to use it when
  3192. * the browser is resized.
  3193. *
  3194. * @method recalculate_faux_grid
  3195. * @return {Object} Returns the instance of the Gridster class.
  3196. */
  3197. fn.recalculate_faux_grid = function() {
  3198. var aw = this.$wrapper.width();
  3199. this.baseX = ($(window).width() - aw) / 2;
  3200. this.baseY = this.$wrapper.offset().top;
  3201. $.each(this.faux_grid, $.proxy(function(i, coords) {
  3202. this.faux_grid[i] = coords.update({
  3203. left: this.baseX + (coords.data.col -1) * this.min_widget_width,
  3204. top: this.baseY + (coords.data.row -1) * this.min_widget_height
  3205. });
  3206. }, this));
  3207. return this;
  3208. };
  3209. /**
  3210. * Get all widgets in the DOM and register them.
  3211. *
  3212. * @method get_widgets_from_DOM
  3213. * @return {Object} Returns the instance of the Gridster class.
  3214. */
  3215. fn.get_widgets_from_DOM = function() {
  3216. var widgets_coords = this.$widgets.map($.proxy(function(i, widget) {
  3217. var $w = $(widget);
  3218. return this.dom_to_coords($w);
  3219. }, this));
  3220. widgets_coords = Gridster.sort_by_row_and_col_asc(widgets_coords);
  3221. var changes = $(widgets_coords).map($.proxy(function(i, wgd) {
  3222. return this.register_widget(wgd) || null;
  3223. }, this));
  3224. if (changes.length) {
  3225. this.$el.trigger('gridster:positionschanged');
  3226. }
  3227. return this;
  3228. };
  3229. /**
  3230. * Calculate columns and rows to be set based on the configuration
  3231. * parameters, grid dimensions, etc ...
  3232. *
  3233. * @method generate_grid_and_stylesheet
  3234. * @return {Object} Returns the instance of the Gridster class.
  3235. */
  3236. fn.generate_grid_and_stylesheet = function() {
  3237. var aw = this.$wrapper.width();
  3238. var max_cols = this.options.max_cols;
  3239. var cols = Math.floor(aw / this.min_widget_width) +
  3240. this.options.extra_cols;
  3241. var actual_cols = this.$widgets.map(function() {
  3242. return $(this).attr('data-col');
  3243. }).get();
  3244. //needed to pass tests with phantomjs
  3245. actual_cols.length || (actual_cols = [0]);
  3246. var min_cols = Math.max.apply(Math, actual_cols);
  3247. this.cols = Math.max(min_cols, cols, this.options.min_cols);
  3248. if (max_cols !== Infinity && max_cols >= min_cols && max_cols < this.cols) {
  3249. this.cols = max_cols;
  3250. }
  3251. // get all rows that could be occupied by the current widgets
  3252. var max_rows = this.options.extra_rows;
  3253. this.$widgets.each(function(i, w) {
  3254. max_rows += (+$(w).attr('data-sizey'));
  3255. });
  3256. this.rows = Math.max(max_rows, this.options.min_rows);
  3257. this.baseX = ($(window).width() - aw) / 2;
  3258. this.baseY = this.$wrapper.offset().top;
  3259. if (this.options.autogenerate_stylesheet) {
  3260. this.generate_stylesheet();
  3261. }
  3262. return this.generate_faux_grid(this.rows, this.cols);
  3263. };
  3264. /**
  3265. * Destroy this gridster by removing any sign of its presence, making it easy to avoid memory leaks
  3266. *
  3267. * @method destroy
  3268. * @param {Boolean} remove If true, remove gridster from DOM.
  3269. * @return {Object} Returns the instance of the Gridster class.
  3270. */
  3271. fn.destroy = function(remove) {
  3272. this.$el.removeData('gridster');
  3273. // remove bound callback on window resize
  3274. $(window).unbind('.gridster');
  3275. if (this.drag_api) {
  3276. this.drag_api.destroy();
  3277. }
  3278. this.remove_style_tags();
  3279. remove && this.$el.remove();
  3280. return this;
  3281. };
  3282. //jQuery adapter
  3283. $.fn.gridster = function(options) {
  3284. return this.each(function() {
  3285. if (! $(this).data('gridster')) {
  3286. $(this).data('gridster', new Gridster( this, options ));
  3287. }
  3288. });
  3289. };
  3290. return Gridster;
  3291. }));