gridstack.js 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  1. /**
  2. * gridstack.js 0.3.0-dev
  3. * http://troolee.github.io/gridstack.js/
  4. * (c) 2014-2016 Pavel Reznikov, Dylan Weiss
  5. * gridstack.js may be freely distributed under the MIT license.
  6. * @preserve
  7. */
  8. (function(factory) {
  9. if (typeof define === 'function' && define.amd) {
  10. define(['jquery', 'lodash'], factory);
  11. } else if (typeof exports !== 'undefined') {
  12. try { jQuery = require('jquery'); } catch (e) {}
  13. try { _ = require('lodash'); } catch (e) {}
  14. factory(jQuery, _);
  15. } else {
  16. factory(jQuery, _);
  17. }
  18. })(function($, _) {
  19. var scope = window;
  20. var obsolete = function(f, oldName, newName) {
  21. var wrapper = function() {
  22. console.warn('gridstack.js: Function `' + oldName + '` is deprecated as of v0.2.5 and has been replaced ' +
  23. 'with `' + newName + '`. It will be **completely** removed in v1.0.');
  24. return f.apply(this, arguments);
  25. };
  26. wrapper.prototype = f.prototype;
  27. return wrapper;
  28. };
  29. var obsoleteOpts = function(oldName, newName) {
  30. console.warn('gridstack.js: Option `' + oldName + '` is deprecated as of v0.2.5 and has been replaced with `' +
  31. newName + '`. It will be **completely** removed in v1.0.');
  32. };
  33. var Utils = {
  34. isIntercepted: function(a, b) {
  35. return !(a.x + a.width <= b.x || b.x + b.width <= a.x || a.y + a.height <= b.y || b.y + b.height <= a.y);
  36. },
  37. sort: function(nodes, dir, width) {
  38. width = width || _.chain(nodes).map(function(node) { return node.x + node.width; }).max().value();
  39. dir = dir != -1 ? 1 : -1;
  40. return _.sortBy(nodes, function(n) { return dir * (n.x + n.y * width); });
  41. },
  42. createStylesheet: function(id) {
  43. var style = document.createElement('style');
  44. style.setAttribute('type', 'text/css');
  45. style.setAttribute('data-gs-style-id', id);
  46. if (style.styleSheet) {
  47. style.styleSheet.cssText = '';
  48. } else {
  49. style.appendChild(document.createTextNode(''));
  50. }
  51. document.getElementsByTagName('head')[0].appendChild(style);
  52. return style.sheet;
  53. },
  54. removeStylesheet: function(id) {
  55. $('STYLE[data-gs-style-id=' + id + ']').remove();
  56. },
  57. insertCSSRule: function(sheet, selector, rules, index) {
  58. if (typeof sheet.insertRule === 'function') {
  59. sheet.insertRule(selector + '{' + rules + '}', index);
  60. } else if (typeof sheet.addRule === 'function') {
  61. sheet.addRule(selector, rules, index);
  62. }
  63. },
  64. toBool: function(v) {
  65. if (typeof v == 'boolean') {
  66. return v;
  67. }
  68. if (typeof v == 'string') {
  69. v = v.toLowerCase();
  70. return !(v === '' || v == 'no' || v == 'false' || v == '0');
  71. }
  72. return Boolean(v);
  73. },
  74. _collisionNodeCheck: function(n) {
  75. return n != this.node && Utils.isIntercepted(n, this.nn);
  76. },
  77. _didCollide: function(bn) {
  78. return Utils.isIntercepted({x: this.n.x, y: this.newY, width: this.n.width, height: this.n.height}, bn);
  79. },
  80. _isAddNodeIntercepted: function(n) {
  81. return Utils.isIntercepted({x: this.x, y: this.y, width: this.node.width, height: this.node.height}, n);
  82. },
  83. parseHeight: function(val) {
  84. var height = val;
  85. var heightUnit = 'px';
  86. if (height && _.isString(height)) {
  87. var match = height.match(/^(-[0-9]+\.[0-9]+|[0-9]*\.[0-9]+|-[0-9]+|[0-9]+)(px|em|rem|vh|vw)?$/);
  88. if (!match) {
  89. throw new Error('Invalid height');
  90. }
  91. heightUnit = match[2] || 'px';
  92. height = parseFloat(match[1]);
  93. }
  94. return {height: height, unit: heightUnit};
  95. }
  96. };
  97. // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  98. Utils.is_intercepted = obsolete(Utils.isIntercepted, 'is_intercepted', 'isIntercepted');
  99. Utils.create_stylesheet = obsolete(Utils.createStylesheet, 'create_stylesheet', 'createStylesheet');
  100. Utils.remove_stylesheet = obsolete(Utils.removeStylesheet, 'remove_stylesheet', 'removeStylesheet');
  101. Utils.insert_css_rule = obsolete(Utils.insertCSSRule, 'insert_css_rule', 'insertCSSRule');
  102. // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
  103. /**
  104. * @class GridStackDragDropPlugin
  105. * Base class for drag'n'drop plugin.
  106. */
  107. function GridStackDragDropPlugin(grid) {
  108. this.grid = grid;
  109. }
  110. GridStackDragDropPlugin.registeredPlugins = [];
  111. GridStackDragDropPlugin.registerPlugin = function(pluginClass) {
  112. GridStackDragDropPlugin.registeredPlugins.push(pluginClass);
  113. };
  114. GridStackDragDropPlugin.prototype.resizable = function(el, opts) {
  115. return this;
  116. };
  117. GridStackDragDropPlugin.prototype.draggable = function(el, opts) {
  118. return this;
  119. };
  120. GridStackDragDropPlugin.prototype.droppable = function(el, opts) {
  121. return this;
  122. };
  123. GridStackDragDropPlugin.prototype.isDroppable = function(el) {
  124. return false;
  125. };
  126. GridStackDragDropPlugin.prototype.on = function(el, eventName, callback) {
  127. return this;
  128. };
  129. var idSeq = 0;
  130. var GridStackEngine = function(width, onchange, floatMode, height, items) {
  131. this.width = width;
  132. this.float = floatMode || false;
  133. this.height = height || 0;
  134. this.nodes = items || [];
  135. this.onchange = onchange || function() {};
  136. this._updateCounter = 0;
  137. this._float = this.float;
  138. this._addedNodes = [];
  139. this._removedNodes = [];
  140. };
  141. GridStackEngine.prototype.batchUpdate = function() {
  142. this._updateCounter = 1;
  143. this.float = true;
  144. };
  145. GridStackEngine.prototype.commit = function() {
  146. if (this._updateCounter !== 0) {
  147. this._updateCounter = 0;
  148. this.float = this._float;
  149. this._packNodes();
  150. this._notify();
  151. }
  152. };
  153. // For Meteor support: https://github.com/troolee/gridstack.js/pull/272
  154. GridStackEngine.prototype.getNodeDataByDOMEl = function(el) {
  155. return _.find(this.nodes, function(n) { return el.get(0) === n.el.get(0); });
  156. };
  157. GridStackEngine.prototype._fixCollisions = function(node) {
  158. var self = this;
  159. this._sortNodes(-1);
  160. var nn = node;
  161. var hasLocked = Boolean(_.find(this.nodes, function(n) { return n.locked; }));
  162. if (!this.float && !hasLocked) {
  163. nn = {x: 0, y: node.y, width: this.width, height: node.height};
  164. }
  165. while (true) {
  166. var collisionNode = _.find(this.nodes, _.bind(Utils._collisionNodeCheck, {node: node, nn: nn}));
  167. if (typeof collisionNode == 'undefined') {
  168. return;
  169. }
  170. this.moveNode(collisionNode, collisionNode.x, node.y + node.height,
  171. collisionNode.width, collisionNode.height, true);
  172. }
  173. };
  174. GridStackEngine.prototype.isAreaEmpty = function(x, y, width, height) {
  175. var nn = {x: x || 0, y: y || 0, width: width || 1, height: height || 1};
  176. var collisionNode = _.find(this.nodes, _.bind(function(n) {
  177. return Utils.isIntercepted(n, nn);
  178. }, this));
  179. return collisionNode === null || typeof collisionNode === 'undefined';
  180. };
  181. GridStackEngine.prototype._sortNodes = function(dir) {
  182. this.nodes = Utils.sort(this.nodes, dir, this.width);
  183. };
  184. GridStackEngine.prototype._packNodes = function() {
  185. this._sortNodes();
  186. if (this.float) {
  187. _.each(this.nodes, _.bind(function(n, i) {
  188. if (n._updating || typeof n._origY == 'undefined' || n.y == n._origY) {
  189. return;
  190. }
  191. var newY = n.y;
  192. while (newY >= n._origY) {
  193. var collisionNode = _.chain(this.nodes)
  194. .find(_.bind(Utils._didCollide, {n: n, newY: newY}))
  195. .value();
  196. if (!collisionNode) {
  197. n._dirty = true;
  198. n.y = newY;
  199. }
  200. --newY;
  201. }
  202. }, this));
  203. } else {
  204. _.each(this.nodes, _.bind(function(n, i) {
  205. if (n.locked) {
  206. return;
  207. }
  208. while (n.y > 0) {
  209. var newY = n.y - 1;
  210. var canBeMoved = i === 0;
  211. if (i > 0) {
  212. var collisionNode = _.chain(this.nodes)
  213. .take(i)
  214. .find(_.bind(Utils._didCollide, {n: n, newY: newY}))
  215. .value();
  216. canBeMoved = typeof collisionNode == 'undefined';
  217. }
  218. if (!canBeMoved) {
  219. break;
  220. }
  221. n._dirty = n.y != newY;
  222. n.y = newY;
  223. }
  224. }, this));
  225. }
  226. };
  227. GridStackEngine.prototype._prepareNode = function(node, resizing) {
  228. node = _.defaults(node || {}, {width: 1, height: 1, x: 0, y: 0});
  229. node.x = parseInt('' + node.x);
  230. node.y = parseInt('' + node.y);
  231. node.width = parseInt('' + node.width);
  232. node.height = parseInt('' + node.height);
  233. node.autoPosition = node.autoPosition || false;
  234. node.noResize = node.noResize || false;
  235. node.noMove = node.noMove || false;
  236. if (node.width > this.width) {
  237. node.width = this.width;
  238. } else if (node.width < 1) {
  239. node.width = 1;
  240. }
  241. if (node.height < 1) {
  242. node.height = 1;
  243. }
  244. if (node.x < 0) {
  245. node.x = 0;
  246. }
  247. if (node.x + node.width > this.width) {
  248. if (resizing) {
  249. node.width = this.width - node.x;
  250. } else {
  251. node.x = this.width - node.width;
  252. }
  253. }
  254. if (node.y < 0) {
  255. node.y = 0;
  256. }
  257. return node;
  258. };
  259. GridStackEngine.prototype._notify = function() {
  260. var args = Array.prototype.slice.call(arguments, 0);
  261. args[0] = typeof args[0] === 'undefined' ? [] : [args[0]];
  262. args[1] = typeof args[1] === 'undefined' ? true : args[1];
  263. if (this._updateCounter) {
  264. return;
  265. }
  266. var deletedNodes = args[0].concat(this.getDirtyNodes());
  267. this.onchange(deletedNodes, args[1]);
  268. };
  269. GridStackEngine.prototype.cleanNodes = function() {
  270. if (this._updateCounter) {
  271. return;
  272. }
  273. _.each(this.nodes, function(n) {n._dirty = false; });
  274. };
  275. GridStackEngine.prototype.getDirtyNodes = function() {
  276. return _.filter(this.nodes, function(n) { return n._dirty; });
  277. };
  278. GridStackEngine.prototype.addNode = function(node, triggerAddEvent) {
  279. node = this._prepareNode(node);
  280. if (typeof node.maxWidth != 'undefined') { node.width = Math.min(node.width, node.maxWidth); }
  281. if (typeof node.maxHeight != 'undefined') { node.height = Math.min(node.height, node.maxHeight); }
  282. if (typeof node.minWidth != 'undefined') { node.width = Math.max(node.width, node.minWidth); }
  283. if (typeof node.minHeight != 'undefined') { node.height = Math.max(node.height, node.minHeight); }
  284. node._id = ++idSeq;
  285. node._dirty = true;
  286. if (node.autoPosition) {
  287. this._sortNodes();
  288. for (var i = 0;; ++i) {
  289. var x = i % this.width;
  290. var y = Math.floor(i / this.width);
  291. if (x + node.width > this.width) {
  292. continue;
  293. }
  294. if (!_.find(this.nodes, _.bind(Utils._isAddNodeIntercepted, {x: x, y: y, node: node}))) {
  295. node.x = x;
  296. node.y = y;
  297. break;
  298. }
  299. }
  300. }
  301. this.nodes.push(node);
  302. if (typeof triggerAddEvent != 'undefined' && triggerAddEvent) {
  303. this._addedNodes.push(_.clone(node));
  304. }
  305. this._fixCollisions(node);
  306. this._packNodes();
  307. this._notify();
  308. return node;
  309. };
  310. GridStackEngine.prototype.removeNode = function(node, detachNode) {
  311. detachNode = typeof detachNode === 'undefined' ? true : detachNode;
  312. this._removedNodes.push(_.clone(node));
  313. node._id = null;
  314. this.nodes = _.without(this.nodes, node);
  315. this._packNodes();
  316. this._notify(node, detachNode);
  317. };
  318. GridStackEngine.prototype.canMoveNode = function(node, x, y, width, height) {
  319. if (!this.isNodeChangedPosition(node, x, y, width, height)) {
  320. return false;
  321. }
  322. var hasLocked = Boolean(_.find(this.nodes, function(n) { return n.locked; }));
  323. if (!this.height && !hasLocked) {
  324. return true;
  325. }
  326. var clonedNode;
  327. var clone = new GridStackEngine(
  328. this.width,
  329. null,
  330. this.float,
  331. 0,
  332. _.map(this.nodes, function(n) {
  333. if (n == node) {
  334. clonedNode = $.extend({}, n);
  335. return clonedNode;
  336. }
  337. return $.extend({}, n);
  338. }));
  339. if (typeof clonedNode === 'undefined') {
  340. return true;
  341. }
  342. clone.moveNode(clonedNode, x, y, width, height);
  343. var res = true;
  344. if (hasLocked) {
  345. res &= !Boolean(_.find(clone.nodes, function(n) {
  346. return n != clonedNode && Boolean(n.locked) && Boolean(n._dirty);
  347. }));
  348. }
  349. if (this.height) {
  350. res &= clone.getGridHeight() <= this.height;
  351. }
  352. return res;
  353. };
  354. GridStackEngine.prototype.canBePlacedWithRespectToHeight = function(node) {
  355. if (!this.height) {
  356. return true;
  357. }
  358. var clone = new GridStackEngine(
  359. this.width,
  360. null,
  361. this.float,
  362. 0,
  363. _.map(this.nodes, function(n) { return $.extend({}, n); }));
  364. clone.addNode(node);
  365. return clone.getGridHeight() <= this.height;
  366. };
  367. GridStackEngine.prototype.isNodeChangedPosition = function(node, x, y, width, height) {
  368. if (typeof x != 'number') { x = node.x; }
  369. if (typeof y != 'number') { y = node.y; }
  370. if (typeof width != 'number') { width = node.width; }
  371. if (typeof height != 'number') { height = node.height; }
  372. if (typeof node.maxWidth != 'undefined') { width = Math.min(width, node.maxWidth); }
  373. if (typeof node.maxHeight != 'undefined') { height = Math.min(height, node.maxHeight); }
  374. if (typeof node.minWidth != 'undefined') { width = Math.max(width, node.minWidth); }
  375. if (typeof node.minHeight != 'undefined') { height = Math.max(height, node.minHeight); }
  376. if (node.x == x && node.y == y && node.width == width && node.height == height) {
  377. return false;
  378. }
  379. return true;
  380. };
  381. GridStackEngine.prototype.moveNode = function(node, x, y, width, height, noPack) {
  382. if (!this.isNodeChangedPosition(node, x, y, width, height)) {
  383. return node;
  384. }
  385. if (typeof x != 'number') { x = node.x; }
  386. if (typeof y != 'number') { y = node.y; }
  387. if (typeof width != 'number') { width = node.width; }
  388. if (typeof height != 'number') { height = node.height; }
  389. if (typeof node.maxWidth != 'undefined') { width = Math.min(width, node.maxWidth); }
  390. if (typeof node.maxHeight != 'undefined') { height = Math.min(height, node.maxHeight); }
  391. if (typeof node.minWidth != 'undefined') { width = Math.max(width, node.minWidth); }
  392. if (typeof node.minHeight != 'undefined') { height = Math.max(height, node.minHeight); }
  393. if (node.x == x && node.y == y && node.width == width && node.height == height) {
  394. return node;
  395. }
  396. var resizing = node.width != width;
  397. node._dirty = true;
  398. node.x = x;
  399. node.y = y;
  400. node.width = width;
  401. node.height = height;
  402. node.lastTriedX = x;
  403. node.lastTriedY = y;
  404. node.lastTriedWidth = width;
  405. node.lastTriedHeight = height;
  406. node = this._prepareNode(node, resizing);
  407. this._fixCollisions(node);
  408. if (!noPack) {
  409. this._packNodes();
  410. this._notify();
  411. }
  412. return node;
  413. };
  414. GridStackEngine.prototype.getGridHeight = function() {
  415. return _.reduce(this.nodes, function(memo, n) { return Math.max(memo, n.y + n.height); }, 0);
  416. };
  417. GridStackEngine.prototype.beginUpdate = function(node) {
  418. _.each(this.nodes, function(n) {
  419. n._origY = n.y;
  420. });
  421. node._updating = true;
  422. };
  423. GridStackEngine.prototype.endUpdate = function() {
  424. _.each(this.nodes, function(n) {
  425. n._origY = n.y;
  426. });
  427. var n = _.find(this.nodes, function(n) { return n._updating; });
  428. if (n) {
  429. n._updating = false;
  430. }
  431. };
  432. var GridStack = function(el, opts) {
  433. var self = this;
  434. var oneColumnMode, isAutoCellHeight;
  435. opts = opts || {};
  436. this.container = $(el);
  437. // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  438. if (typeof opts.handle_class !== 'undefined') {
  439. opts.handleClass = opts.handle_class;
  440. obsoleteOpts('handle_class', 'handleClass');
  441. }
  442. if (typeof opts.item_class !== 'undefined') {
  443. opts.itemClass = opts.item_class;
  444. obsoleteOpts('item_class', 'itemClass');
  445. }
  446. if (typeof opts.placeholder_class !== 'undefined') {
  447. opts.placeholderClass = opts.placeholder_class;
  448. obsoleteOpts('placeholder_class', 'placeholderClass');
  449. }
  450. if (typeof opts.placeholder_text !== 'undefined') {
  451. opts.placeholderText = opts.placeholder_text;
  452. obsoleteOpts('placeholder_text', 'placeholderText');
  453. }
  454. if (typeof opts.cell_height !== 'undefined') {
  455. opts.cellHeight = opts.cell_height;
  456. obsoleteOpts('cell_height', 'cellHeight');
  457. }
  458. if (typeof opts.vertical_margin !== 'undefined') {
  459. opts.verticalMargin = opts.vertical_margin;
  460. obsoleteOpts('vertical_margin', 'verticalMargin');
  461. }
  462. if (typeof opts.min_width !== 'undefined') {
  463. opts.minWidth = opts.min_width;
  464. obsoleteOpts('min_width', 'minWidth');
  465. }
  466. if (typeof opts.static_grid !== 'undefined') {
  467. opts.staticGrid = opts.static_grid;
  468. obsoleteOpts('static_grid', 'staticGrid');
  469. }
  470. if (typeof opts.is_nested !== 'undefined') {
  471. opts.isNested = opts.is_nested;
  472. obsoleteOpts('is_nested', 'isNested');
  473. }
  474. if (typeof opts.always_show_resize_handle !== 'undefined') {
  475. opts.alwaysShowResizeHandle = opts.always_show_resize_handle;
  476. obsoleteOpts('always_show_resize_handle', 'alwaysShowResizeHandle');
  477. }
  478. // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
  479. opts.itemClass = opts.itemClass || 'grid-stack-item';
  480. var isNested = this.container.closest('.' + opts.itemClass).length > 0;
  481. this.opts = _.defaults(opts || {}, {
  482. width: parseInt(this.container.attr('data-gs-width')) || 12,
  483. height: parseInt(this.container.attr('data-gs-height')) || 0,
  484. itemClass: 'grid-stack-item',
  485. placeholderClass: 'grid-stack-placeholder',
  486. placeholderText: '',
  487. handle: '.grid-stack-item-content',
  488. handleClass: null,
  489. cellHeight: 60,
  490. verticalMargin: 20,
  491. auto: true,
  492. minWidth: 768,
  493. float: false,
  494. staticGrid: false,
  495. _class: 'grid-stack-instance-' + (Math.random() * 10000).toFixed(0),
  496. animate: Boolean(this.container.attr('data-gs-animate')) || false,
  497. alwaysShowResizeHandle: opts.alwaysShowResizeHandle || false,
  498. resizable: _.defaults(opts.resizable || {}, {
  499. autoHide: !(opts.alwaysShowResizeHandle || false),
  500. handles: 'se'
  501. }),
  502. draggable: _.defaults(opts.draggable || {}, {
  503. handle: (opts.handleClass ? '.' + opts.handleClass : (opts.handle ? opts.handle : '')) ||
  504. '.grid-stack-item-content',
  505. scroll: false,
  506. appendTo: 'body'
  507. }),
  508. disableDrag: opts.disableDrag || false,
  509. disableResize: opts.disableResize || false,
  510. rtl: 'auto',
  511. removable: false,
  512. removeTimeout: 2000,
  513. verticalMarginUnit: 'px',
  514. cellHeightUnit: 'px',
  515. oneColumnModeClass: opts.oneColumnModeClass || 'grid-stack-one-column-mode',
  516. ddPlugin: null
  517. });
  518. if (this.opts.ddPlugin === false) {
  519. this.opts.ddPlugin = GridStackDragDropPlugin;
  520. } else if (this.opts.ddPlugin === null) {
  521. this.opts.ddPlugin = _.first(GridStackDragDropPlugin.registeredPlugins) || GridStackDragDropPlugin;
  522. }
  523. this.dd = new this.opts.ddPlugin(this);
  524. if (this.opts.rtl === 'auto') {
  525. this.opts.rtl = this.container.css('direction') === 'rtl';
  526. }
  527. if (this.opts.rtl) {
  528. this.container.addClass('grid-stack-rtl');
  529. }
  530. this.opts.isNested = isNested;
  531. isAutoCellHeight = this.opts.cellHeight === 'auto';
  532. if (isAutoCellHeight) {
  533. self.cellHeight(self.cellWidth(), true);
  534. } else {
  535. this.cellHeight(this.opts.cellHeight, true);
  536. }
  537. this.verticalMargin(this.opts.verticalMargin, true);
  538. this.container.addClass(this.opts._class);
  539. this._setStaticClass();
  540. if (isNested) {
  541. this.container.addClass('grid-stack-nested');
  542. }
  543. this._initStyles();
  544. this.grid = new GridStackEngine(this.opts.width, function(nodes, detachNode) {
  545. detachNode = typeof detachNode === 'undefined' ? true : detachNode;
  546. var maxHeight = 0;
  547. _.each(nodes, function(n) {
  548. if (detachNode && n._id === null) {
  549. if (n.el) {
  550. n.el.remove();
  551. }
  552. } else {
  553. n.el
  554. .attr('data-gs-x', n.x)
  555. .attr('data-gs-y', n.y)
  556. .attr('data-gs-width', n.width)
  557. .attr('data-gs-height', n.height);
  558. maxHeight = Math.max(maxHeight, n.y + n.height);
  559. }
  560. });
  561. self._updateStyles(maxHeight + 10);
  562. }, this.opts.float, this.opts.height);
  563. if (this.opts.auto) {
  564. var elements = [];
  565. var _this = this;
  566. this.container.children('.' + this.opts.itemClass + ':not(.' + this.opts.placeholderClass + ')')
  567. .each(function(index, el) {
  568. el = $(el);
  569. elements.push({
  570. el: el,
  571. i: parseInt(el.attr('data-gs-x')) + parseInt(el.attr('data-gs-y')) * _this.opts.width
  572. });
  573. });
  574. _.chain(elements).sortBy(function(x) { return x.i; }).each(function(i) {
  575. self._prepareElement(i.el);
  576. }).value();
  577. }
  578. this.setAnimation(this.opts.animate);
  579. this.placeholder = $(
  580. '<div class="' + this.opts.placeholderClass + ' ' + this.opts.itemClass + '">' +
  581. '<div class="placeholder-content">' + this.opts.placeholderText + '</div></div>').hide();
  582. this._updateContainerHeight();
  583. this._updateHeightsOnResize = _.throttle(function() {
  584. self.cellHeight(self.cellWidth(), false);
  585. }, 100);
  586. this.onResizeHandler = function() {
  587. if (isAutoCellHeight) {
  588. self._updateHeightsOnResize();
  589. }
  590. if (self._isOneColumnMode()) {
  591. if (oneColumnMode) {
  592. return;
  593. }
  594. self.container.addClass(self.opts.oneColumnModeClass);
  595. oneColumnMode = true;
  596. self.grid._sortNodes();
  597. _.each(self.grid.nodes, function(node) {
  598. self.container.append(node.el);
  599. if (self.opts.staticGrid) {
  600. return;
  601. }
  602. if (node.noMove || self.opts.disableDrag) {
  603. self.dd.draggable(node.el, 'disable');
  604. }
  605. if (node.noResize || self.opts.disableResize) {
  606. self.dd.resizable(node.el, 'disable');
  607. }
  608. node.el.trigger('resize');
  609. });
  610. } else {
  611. if (!oneColumnMode) {
  612. return;
  613. }
  614. self.container.removeClass(self.opts.oneColumnModeClass);
  615. oneColumnMode = false;
  616. if (self.opts.staticGrid) {
  617. return;
  618. }
  619. _.each(self.grid.nodes, function(node) {
  620. if (!node.noMove && !self.opts.disableDrag) {
  621. self.dd.draggable(node.el, 'enable');
  622. }
  623. if (!node.noResize && !self.opts.disableResize) {
  624. self.dd.resizable(node.el, 'enable');
  625. }
  626. node.el.trigger('resize');
  627. });
  628. }
  629. };
  630. $(window).resize(this.onResizeHandler);
  631. this.onResizeHandler();
  632. if (!self.opts.staticGrid && typeof self.opts.removable === 'string') {
  633. var trashZone = $(self.opts.removable);
  634. if (!this.dd.isDroppable(trashZone)) {
  635. this.dd.droppable(trashZone, {
  636. accept: '.' + self.opts.itemClass
  637. });
  638. }
  639. this.dd
  640. .on(trashZone, 'dropover', function(event, ui) {
  641. var el = $(ui.draggable);
  642. var node = el.data('_gridstack_node');
  643. if (node._grid !== self) {
  644. return;
  645. }
  646. self._setupRemovingTimeout(el);
  647. })
  648. .on(trashZone, 'dropout', function(event, ui) {
  649. var el = $(ui.draggable);
  650. var node = el.data('_gridstack_node');
  651. if (node._grid !== self) {
  652. return;
  653. }
  654. self._clearRemovingTimeout(el);
  655. });
  656. }
  657. if (!self.opts.staticGrid && self.opts.acceptWidgets) {
  658. var draggingElement = null;
  659. var onDrag = function(event, ui) {
  660. var el = draggingElement;
  661. var node = el.data('_gridstack_node');
  662. var pos = self.getCellFromPixel(ui.offset, true);
  663. var x = Math.max(0, pos.x);
  664. var y = Math.max(0, pos.y);
  665. if (!node._added) {
  666. node._added = true;
  667. node.el = el;
  668. node.x = x;
  669. node.y = y;
  670. self.grid.cleanNodes();
  671. self.grid.beginUpdate(node);
  672. self.grid.addNode(node);
  673. self.container.append(self.placeholder);
  674. self.placeholder
  675. .attr('data-gs-x', node.x)
  676. .attr('data-gs-y', node.y)
  677. .attr('data-gs-width', node.width)
  678. .attr('data-gs-height', node.height)
  679. .show();
  680. node.el = self.placeholder;
  681. node._beforeDragX = node.x;
  682. node._beforeDragY = node.y;
  683. self._updateContainerHeight();
  684. } else {
  685. if (!self.grid.canMoveNode(node, x, y)) {
  686. return;
  687. }
  688. self.grid.moveNode(node, x, y);
  689. self._updateContainerHeight();
  690. }
  691. };
  692. this.dd
  693. .droppable(self.container, {
  694. accept: function(el) {
  695. el = $(el);
  696. var node = el.data('_gridstack_node');
  697. if (node && node._grid === self) {
  698. return false;
  699. }
  700. return el.is(self.opts.acceptWidgets === true ? '.grid-stack-item' : self.opts.acceptWidgets);
  701. }
  702. })
  703. .on(self.container, 'dropover', function(event, ui) {
  704. var offset = self.container.offset();
  705. var el = $(ui.draggable);
  706. var cellWidth = self.cellWidth();
  707. var cellHeight = self.cellHeight();
  708. var origNode = el.data('_gridstack_node');
  709. var width = origNode ? origNode.width : (Math.ceil(el.outerWidth() / cellWidth));
  710. var height = origNode ? origNode.height : (Math.ceil(el.outerHeight() / cellHeight));
  711. draggingElement = el;
  712. var node = self.grid._prepareNode({width: width, height: height, _added: false, _temporary: true});
  713. el.data('_gridstack_node', node);
  714. el.data('_gridstack_node_orig', origNode);
  715. el.on('drag', onDrag);
  716. })
  717. .on(self.container, 'dropout', function(event, ui) {
  718. var el = $(ui.draggable);
  719. el.unbind('drag', onDrag);
  720. var node = el.data('_gridstack_node');
  721. node.el = null;
  722. self.grid.removeNode(node);
  723. self.placeholder.detach();
  724. self._updateContainerHeight();
  725. el.data('_gridstack_node', el.data('_gridstack_node_orig'));
  726. })
  727. .on(self.container, 'drop', function(event, ui) {
  728. self.placeholder.detach();
  729. var node = $(ui.draggable).data('_gridstack_node');
  730. node._grid = self;
  731. var el = $(ui.draggable).clone(false);
  732. el.data('_gridstack_node', node);
  733. $(ui.draggable).remove();
  734. node.el = el;
  735. self.placeholder.hide();
  736. el
  737. .attr('data-gs-x', node.x)
  738. .attr('data-gs-y', node.y)
  739. .attr('data-gs-width', node.width)
  740. .attr('data-gs-height', node.height)
  741. .addClass(self.opts.itemClass)
  742. .removeAttr('style')
  743. .enableSelection()
  744. .removeData('draggable')
  745. .removeClass('ui-draggable ui-draggable-dragging ui-draggable-disabled')
  746. .unbind('drag', onDrag);
  747. self.container.append(el);
  748. self._prepareElementsByNode(el, node);
  749. self._updateContainerHeight();
  750. self._triggerChangeEvent();
  751. self.grid.endUpdate();
  752. });
  753. }
  754. };
  755. GridStack.prototype._triggerChangeEvent = function(forceTrigger) {
  756. var elements = this.grid.getDirtyNodes();
  757. var hasChanges = false;
  758. var eventParams = [];
  759. if (elements && elements.length) {
  760. eventParams.push(elements);
  761. hasChanges = true;
  762. }
  763. if (hasChanges || forceTrigger === true) {
  764. this.container.trigger('change', eventParams);
  765. }
  766. };
  767. GridStack.prototype._triggerAddEvent = function() {
  768. if (this.grid._addedNodes && this.grid._addedNodes.length > 0) {
  769. this.container.trigger('added', [_.map(this.grid._addedNodes, _.clone)]);
  770. this.grid._addedNodes = [];
  771. }
  772. };
  773. GridStack.prototype._triggerRemoveEvent = function() {
  774. if (this.grid._removedNodes && this.grid._removedNodes.length > 0) {
  775. this.container.trigger('removed', [_.map(this.grid._removedNodes, _.clone)]);
  776. this.grid._removedNodes = [];
  777. }
  778. };
  779. GridStack.prototype._initStyles = function() {
  780. if (this._stylesId) {
  781. Utils.removeStylesheet(this._stylesId);
  782. }
  783. this._stylesId = 'gridstack-style-' + (Math.random() * 100000).toFixed();
  784. this._styles = Utils.createStylesheet(this._stylesId);
  785. if (this._styles !== null) {
  786. this._styles._max = 0;
  787. }
  788. };
  789. GridStack.prototype._updateStyles = function(maxHeight) {
  790. if (this._styles === null || typeof this._styles === 'undefined') {
  791. return;
  792. }
  793. var prefix = '.' + this.opts._class + ' .' + this.opts.itemClass;
  794. var self = this;
  795. var getHeight;
  796. if (typeof maxHeight == 'undefined') {
  797. maxHeight = this._styles._max;
  798. this._initStyles();
  799. this._updateContainerHeight();
  800. }
  801. if (!this.opts.cellHeight) { // The rest will be handled by CSS
  802. return ;
  803. }
  804. if (this._styles._max !== 0 && maxHeight <= this._styles._max) {
  805. return ;
  806. }
  807. if (!this.opts.verticalMargin || this.opts.cellHeightUnit === this.opts.verticalMarginUnit) {
  808. getHeight = function(nbRows, nbMargins) {
  809. return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
  810. self.opts.cellHeightUnit;
  811. };
  812. } else {
  813. getHeight = function(nbRows, nbMargins) {
  814. if (!nbRows || !nbMargins) {
  815. return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
  816. self.opts.cellHeightUnit;
  817. }
  818. return 'calc(' + ((self.opts.cellHeight * nbRows) + self.opts.cellHeightUnit) + ' + ' +
  819. ((self.opts.verticalMargin * nbMargins) + self.opts.verticalMarginUnit) + ')';
  820. };
  821. }
  822. if (this._styles._max === 0) {
  823. Utils.insertCSSRule(this._styles, prefix, 'min-height: ' + getHeight(1, 0) + ';', 0);
  824. }
  825. if (maxHeight > this._styles._max) {
  826. for (var i = this._styles._max; i < maxHeight; ++i) {
  827. Utils.insertCSSRule(this._styles,
  828. prefix + '[data-gs-height="' + (i + 1) + '"]',
  829. 'height: ' + getHeight(i + 1, i) + ';',
  830. i
  831. );
  832. Utils.insertCSSRule(this._styles,
  833. prefix + '[data-gs-min-height="' + (i + 1) + '"]',
  834. 'min-height: ' + getHeight(i + 1, i) + ';',
  835. i
  836. );
  837. Utils.insertCSSRule(this._styles,
  838. prefix + '[data-gs-max-height="' + (i + 1) + '"]',
  839. 'max-height: ' + getHeight(i + 1, i) + ';',
  840. i
  841. );
  842. Utils.insertCSSRule(this._styles,
  843. prefix + '[data-gs-y="' + i + '"]',
  844. 'top: ' + getHeight(i, i) + ';',
  845. i
  846. );
  847. }
  848. this._styles._max = maxHeight;
  849. }
  850. };
  851. GridStack.prototype._updateContainerHeight = function() {
  852. if (this.grid._updateCounter) {
  853. return;
  854. }
  855. var height = this.grid.getGridHeight();
  856. this.container.attr('data-gs-current-height', height);
  857. if (!this.opts.cellHeight) {
  858. return ;
  859. }
  860. if (!this.opts.verticalMargin) {
  861. this.container.css('height', (height * (this.opts.cellHeight)) + this.opts.cellHeightUnit);
  862. } else if (this.opts.cellHeightUnit === this.opts.verticalMarginUnit) {
  863. this.container.css('height', (height * (this.opts.cellHeight + this.opts.verticalMargin) -
  864. this.opts.verticalMargin) + this.opts.cellHeightUnit);
  865. } else {
  866. this.container.css('height', 'calc(' + ((height * (this.opts.cellHeight)) + this.opts.cellHeightUnit) +
  867. ' + ' + ((height * (this.opts.verticalMargin - 1)) + this.opts.verticalMarginUnit) + ')');
  868. }
  869. };
  870. GridStack.prototype._isOneColumnMode = function() {
  871. return (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) <=
  872. this.opts.minWidth;
  873. };
  874. GridStack.prototype._setupRemovingTimeout = function(el) {
  875. var self = this;
  876. var node = $(el).data('_gridstack_node');
  877. if (node._removeTimeout || !self.opts.removable) {
  878. return;
  879. }
  880. node._removeTimeout = setTimeout(function() {
  881. el.addClass('grid-stack-item-removing');
  882. node._isAboutToRemove = true;
  883. }, self.opts.removeTimeout);
  884. };
  885. GridStack.prototype._clearRemovingTimeout = function(el) {
  886. var node = $(el).data('_gridstack_node');
  887. if (!node._removeTimeout) {
  888. return;
  889. }
  890. clearTimeout(node._removeTimeout);
  891. node._removeTimeout = null;
  892. el.removeClass('grid-stack-item-removing');
  893. node._isAboutToRemove = false;
  894. };
  895. GridStack.prototype._prepareElementsByNode = function(el, node) {
  896. if (typeof $.ui === 'undefined') {
  897. return;
  898. }
  899. var self = this;
  900. var cellWidth;
  901. var cellHeight;
  902. var dragOrResize = function(event, ui) {
  903. var x = Math.round(ui.position.left / cellWidth);
  904. var y = Math.floor((ui.position.top + cellHeight / 2) / cellHeight);
  905. var width;
  906. var height;
  907. if (event.type != 'drag') {
  908. width = Math.round(ui.size.width / cellWidth);
  909. height = Math.round(ui.size.height / cellHeight);
  910. }
  911. if (event.type == 'drag') {
  912. if (x < 0 || x >= self.grid.width || y < 0) {
  913. if (self.opts.removable === true) {
  914. self._setupRemovingTimeout(el);
  915. }
  916. x = node._beforeDragX;
  917. y = node._beforeDragY;
  918. self.placeholder.detach();
  919. self.placeholder.hide();
  920. self.grid.removeNode(node);
  921. self._updateContainerHeight();
  922. node._temporaryRemoved = true;
  923. } else {
  924. self._clearRemovingTimeout(el);
  925. if (node._temporaryRemoved) {
  926. self.grid.addNode(node);
  927. self.placeholder
  928. .attr('data-gs-x', x)
  929. .attr('data-gs-y', y)
  930. .attr('data-gs-width', width)
  931. .attr('data-gs-height', height)
  932. .show();
  933. self.container.append(self.placeholder);
  934. node.el = self.placeholder;
  935. node._temporaryRemoved = false;
  936. }
  937. }
  938. } else if (event.type == 'resize') {
  939. if (x < 0) {
  940. return;
  941. }
  942. }
  943. // width and height are undefined if not resizing
  944. var lastTriedWidth = typeof width !== 'undefined' ? width : node.lastTriedWidth;
  945. var lastTriedHeight = typeof height !== 'undefined' ? height : node.lastTriedHeight;
  946. if (!self.grid.canMoveNode(node, x, y, width, height) ||
  947. (node.lastTriedX === x && node.lastTriedY === y &&
  948. node.lastTriedWidth === lastTriedWidth && node.lastTriedHeight === lastTriedHeight)) {
  949. return;
  950. }
  951. node.lastTriedX = x;
  952. node.lastTriedY = y;
  953. node.lastTriedWidth = width;
  954. node.lastTriedHeight = height;
  955. self.grid.moveNode(node, x, y, width, height);
  956. self._updateContainerHeight();
  957. };
  958. var onStartMoving = function(event, ui) {
  959. self.container.append(self.placeholder);
  960. var o = $(this);
  961. self.grid.cleanNodes();
  962. self.grid.beginUpdate(node);
  963. cellWidth = self.cellWidth();
  964. var strictCellHeight = Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
  965. cellHeight = self.container.height() / parseInt(self.container.attr('data-gs-current-height'));
  966. self.placeholder
  967. .attr('data-gs-x', o.attr('data-gs-x'))
  968. .attr('data-gs-y', o.attr('data-gs-y'))
  969. .attr('data-gs-width', o.attr('data-gs-width'))
  970. .attr('data-gs-height', o.attr('data-gs-height'))
  971. .show();
  972. node.el = self.placeholder;
  973. node._beforeDragX = node.x;
  974. node._beforeDragY = node.y;
  975. self.dd.resizable(el, 'option', 'minWidth', cellWidth * (node.minWidth || 1));
  976. self.dd.resizable(el, 'option', 'minHeight', strictCellHeight * (node.minHeight || 1));
  977. if (event.type == 'resizestart') {
  978. o.find('.grid-stack-item').trigger('resizestart');
  979. }
  980. };
  981. var onEndMoving = function(event, ui) {
  982. var o = $(this);
  983. if (!o.data('_gridstack_node')) {
  984. return;
  985. }
  986. var forceNotify = false;
  987. self.placeholder.detach();
  988. node.el = o;
  989. self.placeholder.hide();
  990. if (node._isAboutToRemove) {
  991. forceNotify = true;
  992. el.removeData('_gridstack_node');
  993. el.remove();
  994. } else {
  995. self._clearRemovingTimeout(el);
  996. if (!node._temporaryRemoved) {
  997. o
  998. .attr('data-gs-x', node.x)
  999. .attr('data-gs-y', node.y)
  1000. .attr('data-gs-width', node.width)
  1001. .attr('data-gs-height', node.height)
  1002. .removeAttr('style');
  1003. } else {
  1004. o
  1005. .attr('data-gs-x', node._beforeDragX)
  1006. .attr('data-gs-y', node._beforeDragY)
  1007. .attr('data-gs-width', node.width)
  1008. .attr('data-gs-height', node.height)
  1009. .removeAttr('style');
  1010. node.x = node._beforeDragX;
  1011. node.y = node._beforeDragY;
  1012. self.grid.addNode(node);
  1013. }
  1014. }
  1015. self._updateContainerHeight();
  1016. self._triggerChangeEvent(forceNotify);
  1017. self.grid.endUpdate();
  1018. var nestedGrids = o.find('.grid-stack');
  1019. if (nestedGrids.length && event.type == 'resizestop') {
  1020. nestedGrids.each(function(index, el) {
  1021. $(el).data('gridstack').onResizeHandler();
  1022. });
  1023. o.find('.grid-stack-item').trigger('resizestop');
  1024. }
  1025. };
  1026. this.dd
  1027. .draggable(el, {
  1028. start: onStartMoving,
  1029. stop: onEndMoving,
  1030. drag: dragOrResize
  1031. })
  1032. .resizable(el, {
  1033. start: onStartMoving,
  1034. stop: onEndMoving,
  1035. resize: dragOrResize
  1036. });
  1037. if (node.noMove || this._isOneColumnMode() || this.opts.disableDrag) {
  1038. this.dd.draggable(el, 'disable');
  1039. }
  1040. if (node.noResize || this._isOneColumnMode() || this.opts.disableResize) {
  1041. this.dd.resizable(el, 'disable');
  1042. }
  1043. el.attr('data-gs-locked', node.locked ? 'yes' : null);
  1044. };
  1045. GridStack.prototype._prepareElement = function(el, triggerAddEvent) {
  1046. triggerAddEvent = typeof triggerAddEvent != 'undefined' ? triggerAddEvent : false;
  1047. var self = this;
  1048. el = $(el);
  1049. el.addClass(this.opts.itemClass);
  1050. var node = self.grid.addNode({
  1051. x: el.attr('data-gs-x'),
  1052. y: el.attr('data-gs-y'),
  1053. width: el.attr('data-gs-width'),
  1054. height: el.attr('data-gs-height'),
  1055. maxWidth: el.attr('data-gs-max-width'),
  1056. minWidth: el.attr('data-gs-min-width'),
  1057. maxHeight: el.attr('data-gs-max-height'),
  1058. minHeight: el.attr('data-gs-min-height'),
  1059. autoPosition: Utils.toBool(el.attr('data-gs-auto-position')),
  1060. noResize: Utils.toBool(el.attr('data-gs-no-resize')),
  1061. noMove: Utils.toBool(el.attr('data-gs-no-move')),
  1062. locked: Utils.toBool(el.attr('data-gs-locked')),
  1063. el: el,
  1064. id: el.attr('data-gs-id'),
  1065. _grid: self
  1066. }, triggerAddEvent);
  1067. el.data('_gridstack_node', node);
  1068. this._prepareElementsByNode(el, node);
  1069. };
  1070. GridStack.prototype.setAnimation = function(enable) {
  1071. if (enable) {
  1072. this.container.addClass('grid-stack-animate');
  1073. } else {
  1074. this.container.removeClass('grid-stack-animate');
  1075. }
  1076. };
  1077. GridStack.prototype.addWidget = function(el, x, y, width, height, autoPosition, minWidth, maxWidth,
  1078. minHeight, maxHeight, id) {
  1079. el = $(el);
  1080. if (typeof x != 'undefined') { el.attr('data-gs-x', x); }
  1081. if (typeof y != 'undefined') { el.attr('data-gs-y', y); }
  1082. if (typeof width != 'undefined') { el.attr('data-gs-width', width); }
  1083. if (typeof height != 'undefined') { el.attr('data-gs-height', height); }
  1084. if (typeof autoPosition != 'undefined') { el.attr('data-gs-auto-position', autoPosition ? 'yes' : null); }
  1085. if (typeof minWidth != 'undefined') { el.attr('data-gs-min-width', minWidth); }
  1086. if (typeof maxWidth != 'undefined') { el.attr('data-gs-max-width', maxWidth); }
  1087. if (typeof minHeight != 'undefined') { el.attr('data-gs-min-height', minHeight); }
  1088. if (typeof maxHeight != 'undefined') { el.attr('data-gs-max-height', maxHeight); }
  1089. if (typeof id != 'undefined') { el.attr('data-gs-id', id); }
  1090. this.container.append(el);
  1091. this._prepareElement(el, true);
  1092. this._triggerAddEvent();
  1093. this._updateContainerHeight();
  1094. this._triggerChangeEvent(true);
  1095. return el;
  1096. };
  1097. GridStack.prototype.makeWidget = function(el) {
  1098. el = $(el);
  1099. this._prepareElement(el, true);
  1100. this._triggerAddEvent();
  1101. this._updateContainerHeight();
  1102. this._triggerChangeEvent(true);
  1103. return el;
  1104. };
  1105. GridStack.prototype.willItFit = function(x, y, width, height, autoPosition) {
  1106. var node = {x: x, y: y, width: width, height: height, autoPosition: autoPosition};
  1107. return this.grid.canBePlacedWithRespectToHeight(node);
  1108. };
  1109. GridStack.prototype.removeWidget = function(el, detachNode) {
  1110. detachNode = typeof detachNode === 'undefined' ? true : detachNode;
  1111. el = $(el);
  1112. var node = el.data('_gridstack_node');
  1113. // For Meteor support: https://github.com/troolee/gridstack.js/pull/272
  1114. if (!node) {
  1115. node = this.grid.getNodeDataByDOMEl(el);
  1116. }
  1117. this.grid.removeNode(node, detachNode);
  1118. el.removeData('_gridstack_node');
  1119. this._updateContainerHeight();
  1120. if (detachNode) {
  1121. el.remove();
  1122. }
  1123. this._triggerChangeEvent(true);
  1124. this._triggerRemoveEvent();
  1125. };
  1126. GridStack.prototype.removeAll = function(detachNode) {
  1127. _.each(this.grid.nodes, _.bind(function(node) {
  1128. this.removeWidget(node.el, detachNode);
  1129. }, this));
  1130. this.grid.nodes = [];
  1131. this._updateContainerHeight();
  1132. };
  1133. GridStack.prototype.destroy = function(detachGrid) {
  1134. $(window).off('resize', this.onResizeHandler);
  1135. this.disable();
  1136. if (typeof detachGrid != 'undefined' && !detachGrid) {
  1137. this.removeAll(false);
  1138. this.container.removeData('gridstack');
  1139. } else {
  1140. this.container.remove();
  1141. }
  1142. Utils.removeStylesheet(this._stylesId);
  1143. if (this.grid) {
  1144. this.grid = null;
  1145. }
  1146. };
  1147. GridStack.prototype.resizable = function(el, val) {
  1148. var self = this;
  1149. el = $(el);
  1150. el.each(function(index, el) {
  1151. el = $(el);
  1152. var node = el.data('_gridstack_node');
  1153. if (typeof node == 'undefined' || node === null || typeof $.ui === 'undefined') {
  1154. return;
  1155. }
  1156. node.noResize = !(val || false);
  1157. if (node.noResize || self._isOneColumnMode()) {
  1158. self.dd.resizable(el, 'disable');
  1159. } else {
  1160. self.dd.resizable(el, 'enable');
  1161. }
  1162. });
  1163. return this;
  1164. };
  1165. GridStack.prototype.movable = function(el, val) {
  1166. var self = this;
  1167. el = $(el);
  1168. el.each(function(index, el) {
  1169. el = $(el);
  1170. var node = el.data('_gridstack_node');
  1171. if (typeof node == 'undefined' || node === null || typeof $.ui === 'undefined') {
  1172. return;
  1173. }
  1174. node.noMove = !(val || false);
  1175. if (node.noMove || self._isOneColumnMode()) {
  1176. self.dd.draggable(el, 'disable');
  1177. el.removeClass('ui-draggable-handle');
  1178. } else {
  1179. self.dd.draggable(el, 'enable');
  1180. el.addClass('ui-draggable-handle');
  1181. }
  1182. });
  1183. return this;
  1184. };
  1185. GridStack.prototype.enableMove = function(doEnable, includeNewWidgets) {
  1186. this.movable(this.container.children('.' + this.opts.itemClass), doEnable);
  1187. if (includeNewWidgets) {
  1188. this.opts.disableDrag = !doEnable;
  1189. }
  1190. };
  1191. GridStack.prototype.enableResize = function(doEnable, includeNewWidgets) {
  1192. this.resizable(this.container.children('.' + this.opts.itemClass), doEnable);
  1193. if (includeNewWidgets) {
  1194. this.opts.disableResize = !doEnable;
  1195. }
  1196. };
  1197. GridStack.prototype.disable = function() {
  1198. this.movable(this.container.children('.' + this.opts.itemClass), false);
  1199. this.resizable(this.container.children('.' + this.opts.itemClass), false);
  1200. this.container.trigger('disable');
  1201. };
  1202. GridStack.prototype.enable = function() {
  1203. this.movable(this.container.children('.' + this.opts.itemClass), true);
  1204. this.resizable(this.container.children('.' + this.opts.itemClass), true);
  1205. this.container.trigger('enable');
  1206. };
  1207. GridStack.prototype.locked = function(el, val) {
  1208. el = $(el);
  1209. el.each(function(index, el) {
  1210. el = $(el);
  1211. var node = el.data('_gridstack_node');
  1212. if (typeof node == 'undefined' || node === null) {
  1213. return;
  1214. }
  1215. node.locked = (val || false);
  1216. el.attr('data-gs-locked', node.locked ? 'yes' : null);
  1217. });
  1218. return this;
  1219. };
  1220. GridStack.prototype.maxHeight = function(el, val) {
  1221. el = $(el);
  1222. el.each(function(index, el) {
  1223. el = $(el);
  1224. var node = el.data('_gridstack_node');
  1225. if (typeof node === 'undefined' || node === null) {
  1226. return;
  1227. }
  1228. if (!isNaN(val)) {
  1229. node.maxHeight = (val || false);
  1230. el.attr('data-gs-max-height', val);
  1231. }
  1232. });
  1233. return this;
  1234. };
  1235. GridStack.prototype.minHeight = function(el, val) {
  1236. el = $(el);
  1237. el.each(function(index, el) {
  1238. el = $(el);
  1239. var node = el.data('_gridstack_node');
  1240. if (typeof node === 'undefined' || node === null) {
  1241. return;
  1242. }
  1243. if (!isNaN(val)) {
  1244. node.minHeight = (val || false);
  1245. el.attr('data-gs-min-height', val);
  1246. }
  1247. });
  1248. return this;
  1249. };
  1250. GridStack.prototype.maxWidth = function(el, val) {
  1251. el = $(el);
  1252. el.each(function(index, el) {
  1253. el = $(el);
  1254. var node = el.data('_gridstack_node');
  1255. if (typeof node === 'undefined' || node === null) {
  1256. return;
  1257. }
  1258. if (!isNaN(val)) {
  1259. node.maxWidth = (val || false);
  1260. el.attr('data-gs-max-width', val);
  1261. }
  1262. });
  1263. return this;
  1264. };
  1265. GridStack.prototype.minWidth = function(el, val) {
  1266. el = $(el);
  1267. el.each(function(index, el) {
  1268. el = $(el);
  1269. var node = el.data('_gridstack_node');
  1270. if (typeof node === 'undefined' || node === null) {
  1271. return;
  1272. }
  1273. if (!isNaN(val)) {
  1274. node.minWidth = (val || false);
  1275. el.attr('data-gs-min-width', val);
  1276. }
  1277. });
  1278. return this;
  1279. };
  1280. GridStack.prototype._updateElement = function(el, callback) {
  1281. el = $(el).first();
  1282. var node = el.data('_gridstack_node');
  1283. if (typeof node == 'undefined' || node === null) {
  1284. return;
  1285. }
  1286. var self = this;
  1287. self.grid.cleanNodes();
  1288. self.grid.beginUpdate(node);
  1289. callback.call(this, el, node);
  1290. self._updateContainerHeight();
  1291. self._triggerChangeEvent();
  1292. self.grid.endUpdate();
  1293. };
  1294. GridStack.prototype.resize = function(el, width, height) {
  1295. this._updateElement(el, function(el, node) {
  1296. width = (width !== null && typeof width != 'undefined') ? width : node.width;
  1297. height = (height !== null && typeof height != 'undefined') ? height : node.height;
  1298. this.grid.moveNode(node, node.x, node.y, width, height);
  1299. });
  1300. };
  1301. GridStack.prototype.move = function(el, x, y) {
  1302. this._updateElement(el, function(el, node) {
  1303. x = (x !== null && typeof x != 'undefined') ? x : node.x;
  1304. y = (y !== null && typeof y != 'undefined') ? y : node.y;
  1305. this.grid.moveNode(node, x, y, node.width, node.height);
  1306. });
  1307. };
  1308. GridStack.prototype.update = function(el, x, y, width, height) {
  1309. this._updateElement(el, function(el, node) {
  1310. x = (x !== null && typeof x != 'undefined') ? x : node.x;
  1311. y = (y !== null && typeof y != 'undefined') ? y : node.y;
  1312. width = (width !== null && typeof width != 'undefined') ? width : node.width;
  1313. height = (height !== null && typeof height != 'undefined') ? height : node.height;
  1314. this.grid.moveNode(node, x, y, width, height);
  1315. });
  1316. };
  1317. GridStack.prototype.verticalMargin = function(val, noUpdate) {
  1318. if (typeof val == 'undefined') {
  1319. return this.opts.verticalMargin;
  1320. }
  1321. var heightData = Utils.parseHeight(val);
  1322. if (this.opts.verticalMarginUnit === heightData.unit && this.opts.height === heightData.height) {
  1323. return ;
  1324. }
  1325. this.opts.verticalMarginUnit = heightData.unit;
  1326. this.opts.verticalMargin = heightData.height;
  1327. if (!noUpdate) {
  1328. this._updateStyles();
  1329. }
  1330. };
  1331. GridStack.prototype.cellHeight = function(val, noUpdate) {
  1332. if (typeof val == 'undefined') {
  1333. if (this.opts.cellHeight) {
  1334. return this.opts.cellHeight;
  1335. }
  1336. var o = this.container.children('.' + this.opts.itemClass).first();
  1337. return Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
  1338. }
  1339. var heightData = Utils.parseHeight(val);
  1340. if (this.opts.cellHeightUnit === heightData.heightUnit && this.opts.height === heightData.height) {
  1341. return ;
  1342. }
  1343. this.opts.cellHeightUnit = heightData.unit;
  1344. this.opts.cellHeight = heightData.height;
  1345. if (!noUpdate) {
  1346. this._updateStyles();
  1347. }
  1348. };
  1349. GridStack.prototype.cellWidth = function() {
  1350. return Math.round(this.container.outerWidth() / this.opts.width);
  1351. };
  1352. GridStack.prototype.getCellFromPixel = function(position, useOffset) {
  1353. var containerPos = (typeof useOffset != 'undefined' && useOffset) ?
  1354. this.container.offset() : this.container.position();
  1355. var relativeLeft = position.left - containerPos.left;
  1356. var relativeTop = position.top - containerPos.top;
  1357. var columnWidth = Math.floor(this.container.width() / this.opts.width);
  1358. var rowHeight = Math.floor(this.container.height() / parseInt(this.container.attr('data-gs-current-height')));
  1359. return {x: Math.floor(relativeLeft / columnWidth), y: Math.floor(relativeTop / rowHeight)};
  1360. };
  1361. GridStack.prototype.batchUpdate = function() {
  1362. this.grid.batchUpdate();
  1363. };
  1364. GridStack.prototype.commit = function() {
  1365. this.grid.commit();
  1366. this._updateContainerHeight();
  1367. };
  1368. GridStack.prototype.isAreaEmpty = function(x, y, width, height) {
  1369. return this.grid.isAreaEmpty(x, y, width, height);
  1370. };
  1371. GridStack.prototype.setStatic = function(staticValue) {
  1372. this.opts.staticGrid = (staticValue === true);
  1373. this.enableMove(!staticValue);
  1374. this.enableResize(!staticValue);
  1375. this._setStaticClass();
  1376. };
  1377. GridStack.prototype._setStaticClass = function() {
  1378. var staticClassName = 'grid-stack-static';
  1379. if (this.opts.staticGrid === true) {
  1380. this.container.addClass(staticClassName);
  1381. } else {
  1382. this.container.removeClass(staticClassName);
  1383. }
  1384. };
  1385. GridStack.prototype._updateNodeWidths = function(oldWidth, newWidth) {
  1386. this.grid._sortNodes();
  1387. this.grid.batchUpdate();
  1388. var node = {};
  1389. for (var i = 0; i < this.grid.nodes.length; i++) {
  1390. node = this.grid.nodes[i];
  1391. this.update(node.el, Math.round(node.x * newWidth / oldWidth), undefined,
  1392. Math.round(node.width * newWidth / oldWidth), undefined);
  1393. }
  1394. this.grid.commit();
  1395. };
  1396. GridStack.prototype.setGridWidth = function(gridWidth,doNotPropagate) {
  1397. this.container.removeClass('grid-stack-' + this.opts.width);
  1398. if (doNotPropagate !== true) {
  1399. this._updateNodeWidths(this.opts.width, gridWidth);
  1400. }
  1401. this.opts.width = gridWidth;
  1402. this.grid.width = gridWidth;
  1403. this.container.addClass('grid-stack-' + gridWidth);
  1404. };
  1405. // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  1406. GridStackEngine.prototype.batch_update = obsolete(GridStackEngine.prototype.batchUpdate);
  1407. GridStackEngine.prototype._fix_collisions = obsolete(GridStackEngine.prototype._fixCollisions,
  1408. '_fix_collisions', '_fixCollisions');
  1409. GridStackEngine.prototype.is_area_empty = obsolete(GridStackEngine.prototype.isAreaEmpty,
  1410. 'is_area_empty', 'isAreaEmpty');
  1411. GridStackEngine.prototype._sort_nodes = obsolete(GridStackEngine.prototype._sortNodes,
  1412. '_sort_nodes', '_sortNodes');
  1413. GridStackEngine.prototype._pack_nodes = obsolete(GridStackEngine.prototype._packNodes,
  1414. '_pack_nodes', '_packNodes');
  1415. GridStackEngine.prototype._prepare_node = obsolete(GridStackEngine.prototype._prepareNode,
  1416. '_prepare_node', '_prepareNode');
  1417. GridStackEngine.prototype.clean_nodes = obsolete(GridStackEngine.prototype.cleanNodes,
  1418. 'clean_nodes', 'cleanNodes');
  1419. GridStackEngine.prototype.get_dirty_nodes = obsolete(GridStackEngine.prototype.getDirtyNodes,
  1420. 'get_dirty_nodes', 'getDirtyNodes');
  1421. GridStackEngine.prototype.add_node = obsolete(GridStackEngine.prototype.addNode,
  1422. 'add_node', 'addNode, ');
  1423. GridStackEngine.prototype.remove_node = obsolete(GridStackEngine.prototype.removeNode,
  1424. 'remove_node', 'removeNode');
  1425. GridStackEngine.prototype.can_move_node = obsolete(GridStackEngine.prototype.canMoveNode,
  1426. 'can_move_node', 'canMoveNode');
  1427. GridStackEngine.prototype.move_node = obsolete(GridStackEngine.prototype.moveNode,
  1428. 'move_node', 'moveNode');
  1429. GridStackEngine.prototype.get_grid_height = obsolete(GridStackEngine.prototype.getGridHeight,
  1430. 'get_grid_height', 'getGridHeight');
  1431. GridStackEngine.prototype.begin_update = obsolete(GridStackEngine.prototype.beginUpdate,
  1432. 'begin_update', 'beginUpdate');
  1433. GridStackEngine.prototype.end_update = obsolete(GridStackEngine.prototype.endUpdate,
  1434. 'end_update', 'endUpdate');
  1435. GridStackEngine.prototype.can_be_placed_with_respect_to_height =
  1436. obsolete(GridStackEngine.prototype.canBePlacedWithRespectToHeight,
  1437. 'can_be_placed_with_respect_to_height', 'canBePlacedWithRespectToHeight');
  1438. GridStack.prototype._trigger_change_event = obsolete(GridStack.prototype._triggerChangeEvent,
  1439. '_trigger_change_event', '_triggerChangeEvent');
  1440. GridStack.prototype._init_styles = obsolete(GridStack.prototype._initStyles,
  1441. '_init_styles', '_initStyles');
  1442. GridStack.prototype._update_styles = obsolete(GridStack.prototype._updateStyles,
  1443. '_update_styles', '_updateStyles');
  1444. GridStack.prototype._update_container_height = obsolete(GridStack.prototype._updateContainerHeight,
  1445. '_update_container_height', '_updateContainerHeight');
  1446. GridStack.prototype._is_one_column_mode = obsolete(GridStack.prototype._isOneColumnMode,
  1447. '_is_one_column_mode','_isOneColumnMode');
  1448. GridStack.prototype._prepare_element = obsolete(GridStack.prototype._prepareElement,
  1449. '_prepare_element', '_prepareElement');
  1450. GridStack.prototype.set_animation = obsolete(GridStack.prototype.setAnimation,
  1451. 'set_animation', 'setAnimation');
  1452. GridStack.prototype.add_widget = obsolete(GridStack.prototype.addWidget,
  1453. 'add_widget', 'addWidget');
  1454. GridStack.prototype.make_widget = obsolete(GridStack.prototype.makeWidget,
  1455. 'make_widget', 'makeWidget');
  1456. GridStack.prototype.will_it_fit = obsolete(GridStack.prototype.willItFit,
  1457. 'will_it_fit', 'willItFit');
  1458. GridStack.prototype.remove_widget = obsolete(GridStack.prototype.removeWidget,
  1459. 'remove_widget', 'removeWidget');
  1460. GridStack.prototype.remove_all = obsolete(GridStack.prototype.removeAll,
  1461. 'remove_all', 'removeAll');
  1462. GridStack.prototype.min_height = obsolete(GridStack.prototype.minHeight,
  1463. 'min_height', 'minHeight');
  1464. GridStack.prototype.min_width = obsolete(GridStack.prototype.minWidth,
  1465. 'min_width', 'minWidth');
  1466. GridStack.prototype._update_element = obsolete(GridStack.prototype._updateElement,
  1467. '_update_element', '_updateElement');
  1468. GridStack.prototype.cell_height = obsolete(GridStack.prototype.cellHeight,
  1469. 'cell_height', 'cellHeight');
  1470. GridStack.prototype.cell_width = obsolete(GridStack.prototype.cellWidth,
  1471. 'cell_width', 'cellWidth');
  1472. GridStack.prototype.get_cell_from_pixel = obsolete(GridStack.prototype.getCellFromPixel,
  1473. 'get_cell_from_pixel', 'getCellFromPixel');
  1474. GridStack.prototype.batch_update = obsolete(GridStack.prototype.batchUpdate,
  1475. 'batch_update', 'batchUpdate');
  1476. GridStack.prototype.is_area_empty = obsolete(GridStack.prototype.isAreaEmpty,
  1477. 'is_area_empty', 'isAreaEmpty');
  1478. GridStack.prototype.set_static = obsolete(GridStack.prototype.setStatic,
  1479. 'set_static', 'setStatic');
  1480. GridStack.prototype._set_static_class = obsolete(GridStack.prototype._setStaticClass,
  1481. '_set_static_class', '_setStaticClass');
  1482. // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
  1483. scope.GridStackUI = GridStack;
  1484. scope.GridStackUI.Utils = Utils;
  1485. scope.GridStackUI.Engine = GridStackEngine;
  1486. scope.GridStackUI.GridStackDragDropPlugin = GridStackDragDropPlugin;
  1487. $.fn.gridstack = function(opts) {
  1488. return this.each(function() {
  1489. var o = $(this);
  1490. if (!o.data('gridstack')) {
  1491. o
  1492. .data('gridstack', new GridStack(this, opts));
  1493. }
  1494. });
  1495. };
  1496. return scope.GridStackUI;
  1497. });