gridstack.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746
  1. /**
  2. * gridstack.js 1.0.0-dev
  3. * http://troolee.github.io/gridstack.js/
  4. * (c) 2014-2017 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. disableOneColumnMode: opts.disableOneColumnMode || false,
  516. oneColumnModeClass: opts.oneColumnModeClass || 'grid-stack-one-column-mode',
  517. ddPlugin: null
  518. });
  519. if (this.opts.ddPlugin === false) {
  520. this.opts.ddPlugin = GridStackDragDropPlugin;
  521. } else if (this.opts.ddPlugin === null) {
  522. this.opts.ddPlugin = _.first(GridStackDragDropPlugin.registeredPlugins) || GridStackDragDropPlugin;
  523. }
  524. this.dd = new this.opts.ddPlugin(this);
  525. if (this.opts.rtl === 'auto') {
  526. this.opts.rtl = this.container.css('direction') === 'rtl';
  527. }
  528. if (this.opts.rtl) {
  529. this.container.addClass('grid-stack-rtl');
  530. }
  531. this.opts.isNested = isNested;
  532. isAutoCellHeight = this.opts.cellHeight === 'auto';
  533. if (isAutoCellHeight) {
  534. self.cellHeight(self.cellWidth(), true);
  535. } else {
  536. this.cellHeight(this.opts.cellHeight, true);
  537. }
  538. this.verticalMargin(this.opts.verticalMargin, true);
  539. this.container.addClass(this.opts._class);
  540. this._setStaticClass();
  541. if (isNested) {
  542. this.container.addClass('grid-stack-nested');
  543. }
  544. this._initStyles();
  545. this.grid = new GridStackEngine(this.opts.width, function(nodes, detachNode) {
  546. detachNode = typeof detachNode === 'undefined' ? true : detachNode;
  547. var maxHeight = 0;
  548. _.each(nodes, function(n) {
  549. if (detachNode && n._id === null) {
  550. if (n.el) {
  551. n.el.remove();
  552. }
  553. } else {
  554. n.el
  555. .attr('data-gs-x', n.x)
  556. .attr('data-gs-y', n.y)
  557. .attr('data-gs-width', n.width)
  558. .attr('data-gs-height', n.height);
  559. maxHeight = Math.max(maxHeight, n.y + n.height);
  560. }
  561. });
  562. self._updateStyles(maxHeight + 10);
  563. }, this.opts.float, this.opts.height);
  564. if (this.opts.auto) {
  565. var elements = [];
  566. var _this = this;
  567. this.container.children('.' + this.opts.itemClass + ':not(.' + this.opts.placeholderClass + ')')
  568. .each(function(index, el) {
  569. el = $(el);
  570. elements.push({
  571. el: el,
  572. i: parseInt(el.attr('data-gs-x')) + parseInt(el.attr('data-gs-y')) * _this.opts.width
  573. });
  574. });
  575. _.chain(elements).sortBy(function(x) { return x.i; }).each(function(i) {
  576. self._prepareElement(i.el);
  577. }).value();
  578. }
  579. this.setAnimation(this.opts.animate);
  580. this.placeholder = $(
  581. '<div class="' + this.opts.placeholderClass + ' ' + this.opts.itemClass + '">' +
  582. '<div class="placeholder-content">' + this.opts.placeholderText + '</div></div>').hide();
  583. this._updateContainerHeight();
  584. this._updateHeightsOnResize = _.throttle(function() {
  585. self.cellHeight(self.cellWidth(), false);
  586. }, 100);
  587. this.onResizeHandler = function() {
  588. if (isAutoCellHeight) {
  589. self._updateHeightsOnResize();
  590. }
  591. if (self._isOneColumnMode() && !self.opts.disableOneColumnMode) {
  592. if (oneColumnMode) {
  593. return;
  594. }
  595. self.container.addClass(self.opts.oneColumnModeClass);
  596. oneColumnMode = true;
  597. self.grid._sortNodes();
  598. _.each(self.grid.nodes, function(node) {
  599. self.container.append(node.el);
  600. if (self.opts.staticGrid) {
  601. return;
  602. }
  603. self.dd.draggable(node.el, 'disable');
  604. self.dd.resizable(node.el, 'disable');
  605. node.el.trigger('resize');
  606. });
  607. } else {
  608. if (!oneColumnMode) {
  609. return;
  610. }
  611. self.container.removeClass(self.opts.oneColumnModeClass);
  612. oneColumnMode = false;
  613. if (self.opts.staticGrid) {
  614. return;
  615. }
  616. _.each(self.grid.nodes, function(node) {
  617. if (!node.noMove && !self.opts.disableDrag) {
  618. self.dd.draggable(node.el, 'enable');
  619. }
  620. if (!node.noResize && !self.opts.disableResize) {
  621. self.dd.resizable(node.el, 'enable');
  622. }
  623. node.el.trigger('resize');
  624. });
  625. }
  626. };
  627. $(window).resize(this.onResizeHandler);
  628. this.onResizeHandler();
  629. if (!self.opts.staticGrid && typeof self.opts.removable === 'string') {
  630. var trashZone = $(self.opts.removable);
  631. if (!this.dd.isDroppable(trashZone)) {
  632. this.dd.droppable(trashZone, {
  633. accept: '.' + self.opts.itemClass
  634. });
  635. }
  636. this.dd
  637. .on(trashZone, 'dropover', function(event, ui) {
  638. var el = $(ui.draggable);
  639. var node = el.data('_gridstack_node');
  640. if (node._grid !== self) {
  641. return;
  642. }
  643. self._setupRemovingTimeout(el);
  644. })
  645. .on(trashZone, 'dropout', function(event, ui) {
  646. var el = $(ui.draggable);
  647. var node = el.data('_gridstack_node');
  648. if (node._grid !== self) {
  649. return;
  650. }
  651. self._clearRemovingTimeout(el);
  652. });
  653. }
  654. if (!self.opts.staticGrid && self.opts.acceptWidgets) {
  655. var draggingElement = null;
  656. var onDrag = function(event, ui) {
  657. var el = draggingElement;
  658. var node = el.data('_gridstack_node');
  659. var pos = self.getCellFromPixel(ui.offset, true);
  660. var x = Math.max(0, pos.x);
  661. var y = Math.max(0, pos.y);
  662. if (!node._added) {
  663. node._added = true;
  664. node.el = el;
  665. node.x = x;
  666. node.y = y;
  667. self.grid.cleanNodes();
  668. self.grid.beginUpdate(node);
  669. self.grid.addNode(node);
  670. self.container.append(self.placeholder);
  671. self.placeholder
  672. .attr('data-gs-x', node.x)
  673. .attr('data-gs-y', node.y)
  674. .attr('data-gs-width', node.width)
  675. .attr('data-gs-height', node.height)
  676. .show();
  677. node.el = self.placeholder;
  678. node._beforeDragX = node.x;
  679. node._beforeDragY = node.y;
  680. self._updateContainerHeight();
  681. } else {
  682. if (!self.grid.canMoveNode(node, x, y)) {
  683. return;
  684. }
  685. self.grid.moveNode(node, x, y);
  686. self._updateContainerHeight();
  687. }
  688. };
  689. this.dd
  690. .droppable(self.container, {
  691. accept: function(el) {
  692. el = $(el);
  693. var node = el.data('_gridstack_node');
  694. if (node && node._grid === self) {
  695. return false;
  696. }
  697. return el.is(self.opts.acceptWidgets === true ? '.grid-stack-item' : self.opts.acceptWidgets);
  698. }
  699. })
  700. .on(self.container, 'dropover', function(event, ui) {
  701. var offset = self.container.offset();
  702. var el = $(ui.draggable);
  703. var cellWidth = self.cellWidth();
  704. var cellHeight = self.cellHeight();
  705. var origNode = el.data('_gridstack_node');
  706. var width = origNode ? origNode.width : (Math.ceil(el.outerWidth() / cellWidth));
  707. var height = origNode ? origNode.height : (Math.ceil(el.outerHeight() / cellHeight));
  708. draggingElement = el;
  709. var node = self.grid._prepareNode({width: width, height: height, _added: false, _temporary: true});
  710. el.data('_gridstack_node', node);
  711. el.data('_gridstack_node_orig', origNode);
  712. el.on('drag', onDrag);
  713. })
  714. .on(self.container, 'dropout', function(event, ui) {
  715. var el = $(ui.draggable);
  716. el.unbind('drag', onDrag);
  717. var node = el.data('_gridstack_node');
  718. node.el = null;
  719. self.grid.removeNode(node);
  720. self.placeholder.detach();
  721. self._updateContainerHeight();
  722. el.data('_gridstack_node', el.data('_gridstack_node_orig'));
  723. })
  724. .on(self.container, 'drop', function(event, ui) {
  725. self.placeholder.detach();
  726. var node = $(ui.draggable).data('_gridstack_node');
  727. node._grid = self;
  728. var el = $(ui.draggable).clone(false);
  729. el.data('_gridstack_node', node);
  730. var originalNode = $(ui.draggable).data('_gridstack_node_orig');
  731. if (typeof originalNode !== 'undefined') {
  732. originalNode._grid._triggerRemoveEvent();
  733. }
  734. $(ui.draggable).remove();
  735. node.el = el;
  736. self.placeholder.hide();
  737. el
  738. .attr('data-gs-x', node.x)
  739. .attr('data-gs-y', node.y)
  740. .attr('data-gs-width', node.width)
  741. .attr('data-gs-height', node.height)
  742. .addClass(self.opts.itemClass)
  743. .removeAttr('style')
  744. .enableSelection()
  745. .removeData('draggable')
  746. .removeClass('ui-draggable ui-draggable-dragging ui-draggable-disabled')
  747. .unbind('drag', onDrag);
  748. self.container.append(el);
  749. self._prepareElementsByNode(el, node);
  750. self._updateContainerHeight();
  751. self.grid._addedNodes.push(node);
  752. self._triggerAddEvent();
  753. self._triggerChangeEvent();
  754. self.grid.endUpdate();
  755. });
  756. }
  757. };
  758. GridStack.prototype._triggerChangeEvent = function(forceTrigger) {
  759. var elements = this.grid.getDirtyNodes();
  760. var hasChanges = false;
  761. var eventParams = [];
  762. if (elements && elements.length) {
  763. eventParams.push(elements);
  764. hasChanges = true;
  765. }
  766. if (hasChanges || forceTrigger === true) {
  767. this.container.trigger('change', eventParams);
  768. }
  769. };
  770. GridStack.prototype._triggerAddEvent = function() {
  771. if (this.grid._addedNodes && this.grid._addedNodes.length > 0) {
  772. this.container.trigger('added', [_.map(this.grid._addedNodes, _.clone)]);
  773. this.grid._addedNodes = [];
  774. }
  775. };
  776. GridStack.prototype._triggerRemoveEvent = function() {
  777. if (this.grid._removedNodes && this.grid._removedNodes.length > 0) {
  778. this.container.trigger('removed', [_.map(this.grid._removedNodes, _.clone)]);
  779. this.grid._removedNodes = [];
  780. }
  781. };
  782. GridStack.prototype._initStyles = function() {
  783. if (this._stylesId) {
  784. Utils.removeStylesheet(this._stylesId);
  785. }
  786. this._stylesId = 'gridstack-style-' + (Math.random() * 100000).toFixed();
  787. this._styles = Utils.createStylesheet(this._stylesId);
  788. if (this._styles !== null) {
  789. this._styles._max = 0;
  790. }
  791. };
  792. GridStack.prototype._updateStyles = function(maxHeight) {
  793. if (this._styles === null || typeof this._styles === 'undefined') {
  794. return;
  795. }
  796. var prefix = '.' + this.opts._class + ' .' + this.opts.itemClass;
  797. var self = this;
  798. var getHeight;
  799. if (typeof maxHeight == 'undefined') {
  800. maxHeight = this._styles._max;
  801. }
  802. this._initStyles();
  803. this._updateContainerHeight();
  804. if (!this.opts.cellHeight) { // The rest will be handled by CSS
  805. return ;
  806. }
  807. if (this._styles._max !== 0 && maxHeight <= this._styles._max) {
  808. return ;
  809. }
  810. if (!this.opts.verticalMargin || this.opts.cellHeightUnit === this.opts.verticalMarginUnit) {
  811. getHeight = function(nbRows, nbMargins) {
  812. return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
  813. self.opts.cellHeightUnit;
  814. };
  815. } else {
  816. getHeight = function(nbRows, nbMargins) {
  817. if (!nbRows || !nbMargins) {
  818. return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) +
  819. self.opts.cellHeightUnit;
  820. }
  821. return 'calc(' + ((self.opts.cellHeight * nbRows) + self.opts.cellHeightUnit) + ' + ' +
  822. ((self.opts.verticalMargin * nbMargins) + self.opts.verticalMarginUnit) + ')';
  823. };
  824. }
  825. if (this._styles._max === 0) {
  826. Utils.insertCSSRule(this._styles, prefix, 'min-height: ' + getHeight(1, 0) + ';', 0);
  827. }
  828. if (maxHeight > this._styles._max) {
  829. for (var i = this._styles._max; i < maxHeight; ++i) {
  830. Utils.insertCSSRule(this._styles,
  831. prefix + '[data-gs-height="' + (i + 1) + '"]',
  832. 'height: ' + getHeight(i + 1, i) + ';',
  833. i
  834. );
  835. Utils.insertCSSRule(this._styles,
  836. prefix + '[data-gs-min-height="' + (i + 1) + '"]',
  837. 'min-height: ' + getHeight(i + 1, i) + ';',
  838. i
  839. );
  840. Utils.insertCSSRule(this._styles,
  841. prefix + '[data-gs-max-height="' + (i + 1) + '"]',
  842. 'max-height: ' + getHeight(i + 1, i) + ';',
  843. i
  844. );
  845. Utils.insertCSSRule(this._styles,
  846. prefix + '[data-gs-y="' + i + '"]',
  847. 'top: ' + getHeight(i, i) + ';',
  848. i
  849. );
  850. }
  851. this._styles._max = maxHeight;
  852. }
  853. };
  854. GridStack.prototype._updateContainerHeight = function() {
  855. if (this.grid._updateCounter) {
  856. return;
  857. }
  858. var height = this.grid.getGridHeight();
  859. this.container.attr('data-gs-current-height', height);
  860. if (!this.opts.cellHeight) {
  861. return ;
  862. }
  863. if (!this.opts.verticalMargin) {
  864. this.container.css('height', (height * (this.opts.cellHeight)) + this.opts.cellHeightUnit);
  865. } else if (this.opts.cellHeightUnit === this.opts.verticalMarginUnit) {
  866. this.container.css('height', (height * (this.opts.cellHeight + this.opts.verticalMargin) -
  867. this.opts.verticalMargin) + this.opts.cellHeightUnit);
  868. } else {
  869. this.container.css('height', 'calc(' + ((height * (this.opts.cellHeight)) + this.opts.cellHeightUnit) +
  870. ' + ' + ((height * (this.opts.verticalMargin - 1)) + this.opts.verticalMarginUnit) + ')');
  871. }
  872. };
  873. GridStack.prototype._isOneColumnMode = function() {
  874. return (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) <=
  875. this.opts.minWidth;
  876. };
  877. GridStack.prototype._setupRemovingTimeout = function(el) {
  878. var self = this;
  879. var node = $(el).data('_gridstack_node');
  880. if (node._removeTimeout || !self.opts.removable) {
  881. return;
  882. }
  883. node._removeTimeout = setTimeout(function() {
  884. el.addClass('grid-stack-item-removing');
  885. node._isAboutToRemove = true;
  886. }, self.opts.removeTimeout);
  887. };
  888. GridStack.prototype._clearRemovingTimeout = function(el) {
  889. var node = $(el).data('_gridstack_node');
  890. if (!node._removeTimeout) {
  891. return;
  892. }
  893. clearTimeout(node._removeTimeout);
  894. node._removeTimeout = null;
  895. el.removeClass('grid-stack-item-removing');
  896. node._isAboutToRemove = false;
  897. };
  898. GridStack.prototype._prepareElementsByNode = function(el, node) {
  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 || (!self.grid.float && y > self.grid.getGridHeight())) {
  913. if (!node._temporaryRemoved) {
  914. if (self.opts.removable === true) {
  915. self._setupRemovingTimeout(el);
  916. }
  917. x = node._beforeDragX;
  918. y = node._beforeDragY;
  919. self.placeholder.detach();
  920. self.placeholder.hide();
  921. self.grid.removeNode(node);
  922. self._updateContainerHeight();
  923. node._temporaryRemoved = true;
  924. }
  925. } else {
  926. self._clearRemovingTimeout(el);
  927. if (node._temporaryRemoved) {
  928. self.grid.addNode(node);
  929. self.placeholder
  930. .attr('data-gs-x', x)
  931. .attr('data-gs-y', y)
  932. .attr('data-gs-width', width)
  933. .attr('data-gs-height', height)
  934. .show();
  935. self.container.append(self.placeholder);
  936. node.el = self.placeholder;
  937. node._temporaryRemoved = false;
  938. }
  939. }
  940. } else if (event.type == 'resize') {
  941. if (x < 0) {
  942. return;
  943. }
  944. }
  945. // width and height are undefined if not resizing
  946. var lastTriedWidth = typeof width !== 'undefined' ? width : node.lastTriedWidth;
  947. var lastTriedHeight = typeof height !== 'undefined' ? height : node.lastTriedHeight;
  948. if (!self.grid.canMoveNode(node, x, y, width, height) ||
  949. (node.lastTriedX === x && node.lastTriedY === y &&
  950. node.lastTriedWidth === lastTriedWidth && node.lastTriedHeight === lastTriedHeight)) {
  951. return;
  952. }
  953. node.lastTriedX = x;
  954. node.lastTriedY = y;
  955. node.lastTriedWidth = width;
  956. node.lastTriedHeight = height;
  957. self.grid.moveNode(node, x, y, width, height);
  958. self._updateContainerHeight();
  959. };
  960. var onStartMoving = function(event, ui) {
  961. self.container.append(self.placeholder);
  962. var o = $(this);
  963. self.grid.cleanNodes();
  964. self.grid.beginUpdate(node);
  965. cellWidth = self.cellWidth();
  966. var strictCellHeight = Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
  967. cellHeight = self.container.height() / parseInt(self.container.attr('data-gs-current-height'));
  968. self.placeholder
  969. .attr('data-gs-x', o.attr('data-gs-x'))
  970. .attr('data-gs-y', o.attr('data-gs-y'))
  971. .attr('data-gs-width', o.attr('data-gs-width'))
  972. .attr('data-gs-height', o.attr('data-gs-height'))
  973. .show();
  974. node.el = self.placeholder;
  975. node._beforeDragX = node.x;
  976. node._beforeDragY = node.y;
  977. self.dd.resizable(el, 'option', 'minWidth', cellWidth * (node.minWidth || 1));
  978. self.dd.resizable(el, 'option', 'minHeight', strictCellHeight * (node.minHeight || 1));
  979. if (event.type == 'resizestart') {
  980. o.find('.grid-stack-item').trigger('resizestart');
  981. }
  982. };
  983. var onEndMoving = function(event, ui) {
  984. var o = $(this);
  985. if (!o.data('_gridstack_node')) {
  986. return;
  987. }
  988. var forceNotify = false;
  989. self.placeholder.detach();
  990. node.el = o;
  991. self.placeholder.hide();
  992. if (node._isAboutToRemove) {
  993. forceNotify = true;
  994. var gridToNotify = el.data('_gridstack_node')._grid;
  995. gridToNotify._triggerRemoveEvent();
  996. el.removeData('_gridstack_node');
  997. el.remove();
  998. } else {
  999. self._clearRemovingTimeout(el);
  1000. if (!node._temporaryRemoved) {
  1001. o
  1002. .attr('data-gs-x', node.x)
  1003. .attr('data-gs-y', node.y)
  1004. .attr('data-gs-width', node.width)
  1005. .attr('data-gs-height', node.height)
  1006. .removeAttr('style');
  1007. } else {
  1008. o
  1009. .attr('data-gs-x', node._beforeDragX)
  1010. .attr('data-gs-y', node._beforeDragY)
  1011. .attr('data-gs-width', node.width)
  1012. .attr('data-gs-height', node.height)
  1013. .removeAttr('style');
  1014. node.x = node._beforeDragX;
  1015. node.y = node._beforeDragY;
  1016. self.grid.addNode(node);
  1017. }
  1018. }
  1019. self._updateContainerHeight();
  1020. self._triggerChangeEvent(forceNotify);
  1021. self.grid.endUpdate();
  1022. var nestedGrids = o.find('.grid-stack');
  1023. if (nestedGrids.length && event.type == 'resizestop') {
  1024. nestedGrids.each(function(index, el) {
  1025. $(el).data('gridstack').onResizeHandler();
  1026. });
  1027. o.find('.grid-stack-item').trigger('resizestop');
  1028. o.find('.grid-stack-item').trigger('gsresizestop');
  1029. }
  1030. if (event.type == 'resizestop') {
  1031. self.container.trigger('gsresizestop', o);
  1032. }
  1033. };
  1034. this.dd
  1035. .draggable(el, {
  1036. start: onStartMoving,
  1037. stop: onEndMoving,
  1038. drag: dragOrResize
  1039. })
  1040. .resizable(el, {
  1041. start: onStartMoving,
  1042. stop: onEndMoving,
  1043. resize: dragOrResize
  1044. });
  1045. if (node.noMove || (this._isOneColumnMode() && !self.opts.disableOneColumnMode) || this.opts.disableDrag) {
  1046. this.dd.draggable(el, 'disable');
  1047. }
  1048. if (node.noResize || (this._isOneColumnMode() && !self.opts.disableOneColumnMode) || this.opts.disableResize) {
  1049. this.dd.resizable(el, 'disable');
  1050. }
  1051. el.attr('data-gs-locked', node.locked ? 'yes' : null);
  1052. };
  1053. GridStack.prototype._prepareElement = function(el, triggerAddEvent) {
  1054. triggerAddEvent = typeof triggerAddEvent != 'undefined' ? triggerAddEvent : false;
  1055. var self = this;
  1056. el = $(el);
  1057. el.addClass(this.opts.itemClass);
  1058. var node = self.grid.addNode({
  1059. x: el.attr('data-gs-x'),
  1060. y: el.attr('data-gs-y'),
  1061. width: el.attr('data-gs-width'),
  1062. height: el.attr('data-gs-height'),
  1063. maxWidth: el.attr('data-gs-max-width'),
  1064. minWidth: el.attr('data-gs-min-width'),
  1065. maxHeight: el.attr('data-gs-max-height'),
  1066. minHeight: el.attr('data-gs-min-height'),
  1067. autoPosition: Utils.toBool(el.attr('data-gs-auto-position')),
  1068. noResize: Utils.toBool(el.attr('data-gs-no-resize')),
  1069. noMove: Utils.toBool(el.attr('data-gs-no-move')),
  1070. locked: Utils.toBool(el.attr('data-gs-locked')),
  1071. el: el,
  1072. id: el.attr('data-gs-id'),
  1073. _grid: self
  1074. }, triggerAddEvent);
  1075. el.data('_gridstack_node', node);
  1076. this._prepareElementsByNode(el, node);
  1077. };
  1078. GridStack.prototype.setAnimation = function(enable) {
  1079. if (enable) {
  1080. this.container.addClass('grid-stack-animate');
  1081. } else {
  1082. this.container.removeClass('grid-stack-animate');
  1083. }
  1084. };
  1085. GridStack.prototype.addWidget = function(el, x, y, width, height, autoPosition, minWidth, maxWidth,
  1086. minHeight, maxHeight, id) {
  1087. el = $(el);
  1088. if (typeof x != 'undefined') { el.attr('data-gs-x', x); }
  1089. if (typeof y != 'undefined') { el.attr('data-gs-y', y); }
  1090. if (typeof width != 'undefined') { el.attr('data-gs-width', width); }
  1091. if (typeof height != 'undefined') { el.attr('data-gs-height', height); }
  1092. if (typeof autoPosition != 'undefined') { el.attr('data-gs-auto-position', autoPosition ? 'yes' : null); }
  1093. if (typeof minWidth != 'undefined') { el.attr('data-gs-min-width', minWidth); }
  1094. if (typeof maxWidth != 'undefined') { el.attr('data-gs-max-width', maxWidth); }
  1095. if (typeof minHeight != 'undefined') { el.attr('data-gs-min-height', minHeight); }
  1096. if (typeof maxHeight != 'undefined') { el.attr('data-gs-max-height', maxHeight); }
  1097. if (typeof id != 'undefined') { el.attr('data-gs-id', id); }
  1098. this.container.append(el);
  1099. this._prepareElement(el, true);
  1100. this._triggerAddEvent();
  1101. this._updateContainerHeight();
  1102. this._triggerChangeEvent(true);
  1103. return el;
  1104. };
  1105. GridStack.prototype.makeWidget = function(el) {
  1106. el = $(el);
  1107. this._prepareElement(el, true);
  1108. this._triggerAddEvent();
  1109. this._updateContainerHeight();
  1110. this._triggerChangeEvent(true);
  1111. return el;
  1112. };
  1113. GridStack.prototype.willItFit = function(x, y, width, height, autoPosition) {
  1114. var node = {x: x, y: y, width: width, height: height, autoPosition: autoPosition};
  1115. return this.grid.canBePlacedWithRespectToHeight(node);
  1116. };
  1117. GridStack.prototype.removeWidget = function(el, detachNode) {
  1118. detachNode = typeof detachNode === 'undefined' ? true : detachNode;
  1119. el = $(el);
  1120. var node = el.data('_gridstack_node');
  1121. // For Meteor support: https://github.com/troolee/gridstack.js/pull/272
  1122. if (!node) {
  1123. node = this.grid.getNodeDataByDOMEl(el);
  1124. }
  1125. this.grid.removeNode(node, detachNode);
  1126. el.removeData('_gridstack_node');
  1127. this._updateContainerHeight();
  1128. if (detachNode) {
  1129. el.remove();
  1130. }
  1131. this._triggerChangeEvent(true);
  1132. this._triggerRemoveEvent();
  1133. };
  1134. GridStack.prototype.removeAll = function(detachNode) {
  1135. _.each(this.grid.nodes, _.bind(function(node) {
  1136. this.removeWidget(node.el, detachNode);
  1137. }, this));
  1138. this.grid.nodes = [];
  1139. this._updateContainerHeight();
  1140. };
  1141. GridStack.prototype.destroy = function(detachGrid) {
  1142. $(window).off('resize', this.onResizeHandler);
  1143. this.disable();
  1144. if (typeof detachGrid != 'undefined' && !detachGrid) {
  1145. this.removeAll(false);
  1146. this.container.removeData('gridstack');
  1147. } else {
  1148. this.container.remove();
  1149. }
  1150. Utils.removeStylesheet(this._stylesId);
  1151. if (this.grid) {
  1152. this.grid = null;
  1153. }
  1154. };
  1155. GridStack.prototype.resizable = function(el, val) {
  1156. var self = this;
  1157. el = $(el);
  1158. el.each(function(index, el) {
  1159. el = $(el);
  1160. var node = el.data('_gridstack_node');
  1161. if (typeof node == 'undefined' || node === null) {
  1162. return;
  1163. }
  1164. node.noResize = !(val || false);
  1165. if (node.noResize || (self._isOneColumnMode() && !self.opts.disableOneColumnMode)) {
  1166. self.dd.resizable(el, 'disable');
  1167. } else {
  1168. self.dd.resizable(el, 'enable');
  1169. }
  1170. });
  1171. return this;
  1172. };
  1173. GridStack.prototype.movable = function(el, val) {
  1174. var self = this;
  1175. el = $(el);
  1176. el.each(function(index, el) {
  1177. el = $(el);
  1178. var node = el.data('_gridstack_node');
  1179. if (typeof node == 'undefined' || node === null) {
  1180. return;
  1181. }
  1182. node.noMove = !(val || false);
  1183. if (node.noMove || (self._isOneColumnMode() && !self.opts.disableOneColumnMode)) {
  1184. self.dd.draggable(el, 'disable');
  1185. el.removeClass('ui-draggable-handle');
  1186. } else {
  1187. self.dd.draggable(el, 'enable');
  1188. el.addClass('ui-draggable-handle');
  1189. }
  1190. });
  1191. return this;
  1192. };
  1193. GridStack.prototype.enableMove = function(doEnable, includeNewWidgets) {
  1194. this.movable(this.container.children('.' + this.opts.itemClass), doEnable);
  1195. if (includeNewWidgets) {
  1196. this.opts.disableDrag = !doEnable;
  1197. }
  1198. };
  1199. GridStack.prototype.enableResize = function(doEnable, includeNewWidgets) {
  1200. this.resizable(this.container.children('.' + this.opts.itemClass), doEnable);
  1201. if (includeNewWidgets) {
  1202. this.opts.disableResize = !doEnable;
  1203. }
  1204. };
  1205. GridStack.prototype.disable = function() {
  1206. this.movable(this.container.children('.' + this.opts.itemClass), false);
  1207. this.resizable(this.container.children('.' + this.opts.itemClass), false);
  1208. this.container.trigger('disable');
  1209. };
  1210. GridStack.prototype.enable = function() {
  1211. this.movable(this.container.children('.' + this.opts.itemClass), true);
  1212. this.resizable(this.container.children('.' + this.opts.itemClass), true);
  1213. this.container.trigger('enable');
  1214. };
  1215. GridStack.prototype.locked = function(el, val) {
  1216. el = $(el);
  1217. el.each(function(index, el) {
  1218. el = $(el);
  1219. var node = el.data('_gridstack_node');
  1220. if (typeof node == 'undefined' || node === null) {
  1221. return;
  1222. }
  1223. node.locked = (val || false);
  1224. el.attr('data-gs-locked', node.locked ? 'yes' : null);
  1225. });
  1226. return this;
  1227. };
  1228. GridStack.prototype.maxHeight = function(el, val) {
  1229. el = $(el);
  1230. el.each(function(index, el) {
  1231. el = $(el);
  1232. var node = el.data('_gridstack_node');
  1233. if (typeof node === 'undefined' || node === null) {
  1234. return;
  1235. }
  1236. if (!isNaN(val)) {
  1237. node.maxHeight = (val || false);
  1238. el.attr('data-gs-max-height', val);
  1239. }
  1240. });
  1241. return this;
  1242. };
  1243. GridStack.prototype.minHeight = function(el, val) {
  1244. el = $(el);
  1245. el.each(function(index, el) {
  1246. el = $(el);
  1247. var node = el.data('_gridstack_node');
  1248. if (typeof node === 'undefined' || node === null) {
  1249. return;
  1250. }
  1251. if (!isNaN(val)) {
  1252. node.minHeight = (val || false);
  1253. el.attr('data-gs-min-height', val);
  1254. }
  1255. });
  1256. return this;
  1257. };
  1258. GridStack.prototype.maxWidth = function(el, val) {
  1259. el = $(el);
  1260. el.each(function(index, el) {
  1261. el = $(el);
  1262. var node = el.data('_gridstack_node');
  1263. if (typeof node === 'undefined' || node === null) {
  1264. return;
  1265. }
  1266. if (!isNaN(val)) {
  1267. node.maxWidth = (val || false);
  1268. el.attr('data-gs-max-width', val);
  1269. }
  1270. });
  1271. return this;
  1272. };
  1273. GridStack.prototype.minWidth = function(el, val) {
  1274. el = $(el);
  1275. el.each(function(index, el) {
  1276. el = $(el);
  1277. var node = el.data('_gridstack_node');
  1278. if (typeof node === 'undefined' || node === null) {
  1279. return;
  1280. }
  1281. if (!isNaN(val)) {
  1282. node.minWidth = (val || false);
  1283. el.attr('data-gs-min-width', val);
  1284. }
  1285. });
  1286. return this;
  1287. };
  1288. GridStack.prototype._updateElement = function(el, callback) {
  1289. el = $(el).first();
  1290. var node = el.data('_gridstack_node');
  1291. if (typeof node == 'undefined' || node === null) {
  1292. return;
  1293. }
  1294. var self = this;
  1295. self.grid.cleanNodes();
  1296. self.grid.beginUpdate(node);
  1297. callback.call(this, el, node);
  1298. self._updateContainerHeight();
  1299. self._triggerChangeEvent();
  1300. self.grid.endUpdate();
  1301. };
  1302. GridStack.prototype.resize = function(el, width, height) {
  1303. this._updateElement(el, function(el, node) {
  1304. width = (width !== null && typeof width != 'undefined') ? width : node.width;
  1305. height = (height !== null && typeof height != 'undefined') ? height : node.height;
  1306. this.grid.moveNode(node, node.x, node.y, width, height);
  1307. });
  1308. };
  1309. GridStack.prototype.move = function(el, x, y) {
  1310. this._updateElement(el, function(el, node) {
  1311. x = (x !== null && typeof x != 'undefined') ? x : node.x;
  1312. y = (y !== null && typeof y != 'undefined') ? y : node.y;
  1313. this.grid.moveNode(node, x, y, node.width, node.height);
  1314. });
  1315. };
  1316. GridStack.prototype.update = function(el, x, y, width, height) {
  1317. this._updateElement(el, function(el, node) {
  1318. x = (x !== null && typeof x != 'undefined') ? x : node.x;
  1319. y = (y !== null && typeof y != 'undefined') ? y : node.y;
  1320. width = (width !== null && typeof width != 'undefined') ? width : node.width;
  1321. height = (height !== null && typeof height != 'undefined') ? height : node.height;
  1322. this.grid.moveNode(node, x, y, width, height);
  1323. });
  1324. };
  1325. GridStack.prototype.verticalMargin = function(val, noUpdate) {
  1326. if (typeof val == 'undefined') {
  1327. return this.opts.verticalMargin;
  1328. }
  1329. var heightData = Utils.parseHeight(val);
  1330. if (this.opts.verticalMarginUnit === heightData.unit && this.opts.height === heightData.height) {
  1331. return ;
  1332. }
  1333. this.opts.verticalMarginUnit = heightData.unit;
  1334. this.opts.verticalMargin = heightData.height;
  1335. if (!noUpdate) {
  1336. this._updateStyles();
  1337. }
  1338. };
  1339. GridStack.prototype.cellHeight = function(val, noUpdate) {
  1340. if (typeof val == 'undefined') {
  1341. if (this.opts.cellHeight) {
  1342. return this.opts.cellHeight;
  1343. }
  1344. var o = this.container.children('.' + this.opts.itemClass).first();
  1345. return Math.ceil(o.outerHeight() / o.attr('data-gs-height'));
  1346. }
  1347. var heightData = Utils.parseHeight(val);
  1348. if (this.opts.cellHeightUnit === heightData.heightUnit && this.opts.height === heightData.height) {
  1349. return ;
  1350. }
  1351. this.opts.cellHeightUnit = heightData.unit;
  1352. this.opts.cellHeight = heightData.height;
  1353. if (!noUpdate) {
  1354. this._updateStyles();
  1355. }
  1356. };
  1357. GridStack.prototype.cellWidth = function() {
  1358. return Math.round(this.container.outerWidth() / this.opts.width);
  1359. };
  1360. GridStack.prototype.getCellFromPixel = function(position, useOffset) {
  1361. var containerPos = (typeof useOffset != 'undefined' && useOffset) ?
  1362. this.container.offset() : this.container.position();
  1363. var relativeLeft = position.left - containerPos.left;
  1364. var relativeTop = position.top - containerPos.top;
  1365. var columnWidth = Math.floor(this.container.width() / this.opts.width);
  1366. var rowHeight = Math.floor(this.container.height() / parseInt(this.container.attr('data-gs-current-height')));
  1367. return {x: Math.floor(relativeLeft / columnWidth), y: Math.floor(relativeTop / rowHeight)};
  1368. };
  1369. GridStack.prototype.batchUpdate = function() {
  1370. this.grid.batchUpdate();
  1371. };
  1372. GridStack.prototype.commit = function() {
  1373. this.grid.commit();
  1374. this._updateContainerHeight();
  1375. };
  1376. GridStack.prototype.isAreaEmpty = function(x, y, width, height) {
  1377. return this.grid.isAreaEmpty(x, y, width, height);
  1378. };
  1379. GridStack.prototype.setStatic = function(staticValue) {
  1380. this.opts.staticGrid = (staticValue === true);
  1381. this.enableMove(!staticValue);
  1382. this.enableResize(!staticValue);
  1383. this._setStaticClass();
  1384. };
  1385. GridStack.prototype._setStaticClass = function() {
  1386. var staticClassName = 'grid-stack-static';
  1387. if (this.opts.staticGrid === true) {
  1388. this.container.addClass(staticClassName);
  1389. } else {
  1390. this.container.removeClass(staticClassName);
  1391. }
  1392. };
  1393. GridStack.prototype._updateNodeWidths = function(oldWidth, newWidth) {
  1394. this.grid._sortNodes();
  1395. this.grid.batchUpdate();
  1396. var node = {};
  1397. for (var i = 0; i < this.grid.nodes.length; i++) {
  1398. node = this.grid.nodes[i];
  1399. this.update(node.el, Math.round(node.x * newWidth / oldWidth), undefined,
  1400. Math.round(node.width * newWidth / oldWidth), undefined);
  1401. }
  1402. this.grid.commit();
  1403. };
  1404. GridStack.prototype.setGridWidth = function(gridWidth,doNotPropagate) {
  1405. this.container.removeClass('grid-stack-' + this.opts.width);
  1406. if (doNotPropagate !== true) {
  1407. this._updateNodeWidths(this.opts.width, gridWidth);
  1408. }
  1409. this.opts.width = gridWidth;
  1410. this.grid.width = gridWidth;
  1411. this.container.addClass('grid-stack-' + gridWidth);
  1412. };
  1413. // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  1414. GridStackEngine.prototype.batch_update = obsolete(GridStackEngine.prototype.batchUpdate);
  1415. GridStackEngine.prototype._fix_collisions = obsolete(GridStackEngine.prototype._fixCollisions,
  1416. '_fix_collisions', '_fixCollisions');
  1417. GridStackEngine.prototype.is_area_empty = obsolete(GridStackEngine.prototype.isAreaEmpty,
  1418. 'is_area_empty', 'isAreaEmpty');
  1419. GridStackEngine.prototype._sort_nodes = obsolete(GridStackEngine.prototype._sortNodes,
  1420. '_sort_nodes', '_sortNodes');
  1421. GridStackEngine.prototype._pack_nodes = obsolete(GridStackEngine.prototype._packNodes,
  1422. '_pack_nodes', '_packNodes');
  1423. GridStackEngine.prototype._prepare_node = obsolete(GridStackEngine.prototype._prepareNode,
  1424. '_prepare_node', '_prepareNode');
  1425. GridStackEngine.prototype.clean_nodes = obsolete(GridStackEngine.prototype.cleanNodes,
  1426. 'clean_nodes', 'cleanNodes');
  1427. GridStackEngine.prototype.get_dirty_nodes = obsolete(GridStackEngine.prototype.getDirtyNodes,
  1428. 'get_dirty_nodes', 'getDirtyNodes');
  1429. GridStackEngine.prototype.add_node = obsolete(GridStackEngine.prototype.addNode,
  1430. 'add_node', 'addNode, ');
  1431. GridStackEngine.prototype.remove_node = obsolete(GridStackEngine.prototype.removeNode,
  1432. 'remove_node', 'removeNode');
  1433. GridStackEngine.prototype.can_move_node = obsolete(GridStackEngine.prototype.canMoveNode,
  1434. 'can_move_node', 'canMoveNode');
  1435. GridStackEngine.prototype.move_node = obsolete(GridStackEngine.prototype.moveNode,
  1436. 'move_node', 'moveNode');
  1437. GridStackEngine.prototype.get_grid_height = obsolete(GridStackEngine.prototype.getGridHeight,
  1438. 'get_grid_height', 'getGridHeight');
  1439. GridStackEngine.prototype.begin_update = obsolete(GridStackEngine.prototype.beginUpdate,
  1440. 'begin_update', 'beginUpdate');
  1441. GridStackEngine.prototype.end_update = obsolete(GridStackEngine.prototype.endUpdate,
  1442. 'end_update', 'endUpdate');
  1443. GridStackEngine.prototype.can_be_placed_with_respect_to_height =
  1444. obsolete(GridStackEngine.prototype.canBePlacedWithRespectToHeight,
  1445. 'can_be_placed_with_respect_to_height', 'canBePlacedWithRespectToHeight');
  1446. GridStack.prototype._trigger_change_event = obsolete(GridStack.prototype._triggerChangeEvent,
  1447. '_trigger_change_event', '_triggerChangeEvent');
  1448. GridStack.prototype._init_styles = obsolete(GridStack.prototype._initStyles,
  1449. '_init_styles', '_initStyles');
  1450. GridStack.prototype._update_styles = obsolete(GridStack.prototype._updateStyles,
  1451. '_update_styles', '_updateStyles');
  1452. GridStack.prototype._update_container_height = obsolete(GridStack.prototype._updateContainerHeight,
  1453. '_update_container_height', '_updateContainerHeight');
  1454. GridStack.prototype._is_one_column_mode = obsolete(GridStack.prototype._isOneColumnMode,
  1455. '_is_one_column_mode','_isOneColumnMode');
  1456. GridStack.prototype._prepare_element = obsolete(GridStack.prototype._prepareElement,
  1457. '_prepare_element', '_prepareElement');
  1458. GridStack.prototype.set_animation = obsolete(GridStack.prototype.setAnimation,
  1459. 'set_animation', 'setAnimation');
  1460. GridStack.prototype.add_widget = obsolete(GridStack.prototype.addWidget,
  1461. 'add_widget', 'addWidget');
  1462. GridStack.prototype.make_widget = obsolete(GridStack.prototype.makeWidget,
  1463. 'make_widget', 'makeWidget');
  1464. GridStack.prototype.will_it_fit = obsolete(GridStack.prototype.willItFit,
  1465. 'will_it_fit', 'willItFit');
  1466. GridStack.prototype.remove_widget = obsolete(GridStack.prototype.removeWidget,
  1467. 'remove_widget', 'removeWidget');
  1468. GridStack.prototype.remove_all = obsolete(GridStack.prototype.removeAll,
  1469. 'remove_all', 'removeAll');
  1470. GridStack.prototype.min_height = obsolete(GridStack.prototype.minHeight,
  1471. 'min_height', 'minHeight');
  1472. GridStack.prototype.min_width = obsolete(GridStack.prototype.minWidth,
  1473. 'min_width', 'minWidth');
  1474. GridStack.prototype._update_element = obsolete(GridStack.prototype._updateElement,
  1475. '_update_element', '_updateElement');
  1476. GridStack.prototype.cell_height = obsolete(GridStack.prototype.cellHeight,
  1477. 'cell_height', 'cellHeight');
  1478. GridStack.prototype.cell_width = obsolete(GridStack.prototype.cellWidth,
  1479. 'cell_width', 'cellWidth');
  1480. GridStack.prototype.get_cell_from_pixel = obsolete(GridStack.prototype.getCellFromPixel,
  1481. 'get_cell_from_pixel', 'getCellFromPixel');
  1482. GridStack.prototype.batch_update = obsolete(GridStack.prototype.batchUpdate,
  1483. 'batch_update', 'batchUpdate');
  1484. GridStack.prototype.is_area_empty = obsolete(GridStack.prototype.isAreaEmpty,
  1485. 'is_area_empty', 'isAreaEmpty');
  1486. GridStack.prototype.set_static = obsolete(GridStack.prototype.setStatic,
  1487. 'set_static', 'setStatic');
  1488. GridStack.prototype._set_static_class = obsolete(GridStack.prototype._setStaticClass,
  1489. '_set_static_class', '_setStaticClass');
  1490. // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
  1491. scope.GridStackUI = GridStack;
  1492. scope.GridStackUI.Utils = Utils;
  1493. scope.GridStackUI.Engine = GridStackEngine;
  1494. scope.GridStackUI.GridStackDragDropPlugin = GridStackDragDropPlugin;
  1495. $.fn.gridstack = function(opts) {
  1496. return this.each(function() {
  1497. var o = $(this);
  1498. if (!o.data('gridstack')) {
  1499. o
  1500. .data('gridstack', new GridStack(this, opts));
  1501. }
  1502. });
  1503. };
  1504. return scope.GridStackUI;
  1505. });