gridstack 7.2.3 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/README.md +9 -3
  2. package/dist/dd-base-impl.d.ts +20 -20
  3. package/dist/dd-base-impl.js +31 -35
  4. package/dist/dd-base-impl.js.map +1 -1
  5. package/dist/dd-draggable.d.ts +28 -28
  6. package/dist/dd-draggable.js +336 -345
  7. package/dist/dd-draggable.js.map +1 -1
  8. package/dist/dd-droppable.d.ts +26 -26
  9. package/dist/dd-droppable.js +146 -148
  10. package/dist/dd-droppable.js.map +1 -1
  11. package/dist/dd-element.d.ts +27 -27
  12. package/dist/dd-element.js +90 -94
  13. package/dist/dd-element.js.map +1 -1
  14. package/dist/dd-gridstack.d.ts +34 -34
  15. package/dist/dd-gridstack.js +127 -124
  16. package/dist/dd-gridstack.js.map +1 -1
  17. package/dist/dd-manager.d.ts +22 -22
  18. package/dist/dd-manager.js +9 -13
  19. package/dist/dd-manager.js.map +1 -1
  20. package/dist/dd-resizable-handle.d.ts +14 -14
  21. package/dist/dd-resizable-handle.js +102 -105
  22. package/dist/dd-resizable-handle.js.map +1 -1
  23. package/dist/dd-resizable.d.ts +28 -28
  24. package/dist/dd-resizable.js +290 -296
  25. package/dist/dd-resizable.js.map +1 -1
  26. package/dist/dd-touch.d.ts +33 -33
  27. package/dist/dd-touch.js +173 -181
  28. package/dist/dd-touch.js.map +1 -1
  29. package/dist/es5/dd-base-impl.d.ts +20 -20
  30. package/dist/es5/dd-base-impl.js +40 -40
  31. package/dist/es5/dd-base-impl.js.map +1 -1
  32. package/dist/es5/dd-draggable.d.ts +28 -28
  33. package/dist/es5/dd-draggable.js +366 -368
  34. package/dist/es5/dd-draggable.js.map +1 -1
  35. package/dist/es5/dd-droppable.d.ts +26 -26
  36. package/dist/es5/dd-droppable.js +181 -179
  37. package/dist/es5/dd-droppable.js.map +1 -1
  38. package/dist/es5/dd-element.d.ts +27 -27
  39. package/dist/es5/dd-element.js +95 -95
  40. package/dist/es5/dd-element.js.map +1 -1
  41. package/dist/es5/dd-gridstack.d.ts +34 -34
  42. package/dist/es5/dd-gridstack.js +144 -144
  43. package/dist/es5/dd-gridstack.js.map +1 -1
  44. package/dist/es5/dd-manager.d.ts +22 -22
  45. package/dist/es5/dd-manager.js +16 -16
  46. package/dist/es5/dd-manager.js.map +1 -1
  47. package/dist/es5/dd-resizable-handle.d.ts +14 -14
  48. package/dist/es5/dd-resizable-handle.js +105 -106
  49. package/dist/es5/dd-resizable-handle.js.map +1 -1
  50. package/dist/es5/dd-resizable.d.ts +28 -28
  51. package/dist/es5/dd-resizable.js +317 -318
  52. package/dist/es5/dd-resizable.js.map +1 -1
  53. package/dist/es5/dd-touch.d.ts +33 -33
  54. package/dist/es5/dd-touch.js +185 -184
  55. package/dist/es5/dd-touch.js.map +1 -1
  56. package/dist/es5/gridstack-all.js +1 -1
  57. package/dist/es5/gridstack-all.js.LICENSE.txt +1 -1
  58. package/dist/es5/gridstack-all.js.map +1 -1
  59. package/dist/es5/gridstack-engine.d.ts +102 -100
  60. package/dist/es5/gridstack-engine.js +1000 -976
  61. package/dist/es5/gridstack-engine.js.map +1 -1
  62. package/dist/es5/gridstack-poly.js +1 -1
  63. package/dist/es5/gridstack.d.ts +389 -376
  64. package/dist/es5/gridstack.js +2252 -2227
  65. package/dist/es5/gridstack.js.map +1 -1
  66. package/dist/es5/types.d.ts +279 -279
  67. package/dist/es5/types.js +47 -35
  68. package/dist/es5/types.js.map +1 -1
  69. package/dist/es5/utils.d.ts +95 -91
  70. package/dist/es5/utils.js +591 -566
  71. package/dist/es5/utils.js.map +1 -1
  72. package/dist/gridstack-all.js +1 -1
  73. package/dist/gridstack-all.js.LICENSE.txt +1 -1
  74. package/dist/gridstack-all.js.map +1 -1
  75. package/dist/gridstack-engine.d.ts +102 -100
  76. package/dist/gridstack-engine.js +950 -936
  77. package/dist/gridstack-engine.js.map +1 -1
  78. package/dist/gridstack-extra.css +0 -390
  79. package/dist/gridstack-extra.min.css +1 -1
  80. package/dist/gridstack.css +3 -97
  81. package/dist/gridstack.d.ts +389 -376
  82. package/dist/gridstack.js +2155 -2151
  83. package/dist/gridstack.js.map +1 -1
  84. package/dist/gridstack.min.css +1 -1
  85. package/dist/ng/README.md +154 -0
  86. package/dist/ng/gridstack-item.component.d.ts +29 -0
  87. package/dist/ng/gridstack-item.component.js +65 -0
  88. package/dist/ng/gridstack-item.component.js.map +1 -0
  89. package/dist/ng/gridstack.component.d.ts +118 -0
  90. package/dist/ng/gridstack.component.js +245 -0
  91. package/dist/ng/gridstack.component.js.map +1 -0
  92. package/dist/src/gridstack-extra.scss +0 -2
  93. package/dist/src/gridstack.scss +6 -9
  94. package/dist/types.d.ts +279 -279
  95. package/dist/types.js +44 -35
  96. package/dist/types.js.map +1 -1
  97. package/dist/utils.d.ts +95 -91
  98. package/dist/utils.js +539 -524
  99. package/dist/utils.js.map +1 -1
  100. package/{dist → dist_save}/angular/gridstack-item.component.ts +22 -4
  101. package/{dist → dist_save}/angular/gridstack.component.ts +57 -30
  102. package/dist_save/dd-base-impl.d.ts +20 -0
  103. package/dist_save/dd-base-impl.js +36 -0
  104. package/dist_save/dd-base-impl.js.map +1 -0
  105. package/dist_save/dd-draggable.d.ts +28 -0
  106. package/dist_save/dd-draggable.js +343 -0
  107. package/dist_save/dd-draggable.js.map +1 -0
  108. package/dist_save/dd-droppable.d.ts +26 -0
  109. package/dist_save/dd-droppable.js +149 -0
  110. package/dist_save/dd-droppable.js.map +1 -0
  111. package/dist_save/dd-element.d.ts +27 -0
  112. package/dist_save/dd-element.js +95 -0
  113. package/dist_save/dd-element.js.map +1 -0
  114. package/dist_save/dd-gridstack.d.ts +34 -0
  115. package/dist_save/dd-gridstack.js +125 -0
  116. package/dist_save/dd-gridstack.js.map +1 -0
  117. package/dist_save/dd-manager.d.ts +22 -0
  118. package/dist_save/dd-manager.js +14 -0
  119. package/dist_save/dd-manager.js.map +1 -0
  120. package/dist_save/dd-resizable-handle.d.ts +14 -0
  121. package/dist_save/dd-resizable-handle.js +106 -0
  122. package/dist_save/dd-resizable-handle.js.map +1 -0
  123. package/dist_save/dd-resizable.d.ts +28 -0
  124. package/dist_save/dd-resizable.js +294 -0
  125. package/dist_save/dd-resizable.js.map +1 -0
  126. package/dist_save/dd-touch.d.ts +33 -0
  127. package/dist_save/dd-touch.js +183 -0
  128. package/dist_save/dd-touch.js.map +1 -0
  129. package/dist_save/es5/dd-base-impl.d.ts +20 -0
  130. package/dist_save/es5/dd-base-impl.js +41 -0
  131. package/dist_save/es5/dd-base-impl.js.map +1 -0
  132. package/dist_save/es5/dd-draggable.d.ts +28 -0
  133. package/dist_save/es5/dd-draggable.js +366 -0
  134. package/dist_save/es5/dd-draggable.js.map +1 -0
  135. package/dist_save/es5/dd-droppable.d.ts +26 -0
  136. package/dist_save/es5/dd-droppable.js +180 -0
  137. package/dist_save/es5/dd-droppable.js.map +1 -0
  138. package/dist_save/es5/dd-element.d.ts +27 -0
  139. package/dist_save/es5/dd-element.js +96 -0
  140. package/dist_save/es5/dd-element.js.map +1 -0
  141. package/dist_save/es5/dd-gridstack.d.ts +34 -0
  142. package/dist_save/es5/dd-gridstack.js +145 -0
  143. package/dist_save/es5/dd-gridstack.js.map +1 -0
  144. package/dist_save/es5/dd-manager.d.ts +22 -0
  145. package/dist_save/es5/dd-manager.js +17 -0
  146. package/dist_save/es5/dd-manager.js.map +1 -0
  147. package/dist_save/es5/dd-resizable-handle.d.ts +14 -0
  148. package/dist_save/es5/dd-resizable-handle.js +107 -0
  149. package/dist_save/es5/dd-resizable-handle.js.map +1 -0
  150. package/dist_save/es5/dd-resizable.d.ts +28 -0
  151. package/dist_save/es5/dd-resizable.js +316 -0
  152. package/dist_save/es5/dd-resizable.js.map +1 -0
  153. package/dist_save/es5/dd-touch.d.ts +33 -0
  154. package/dist_save/es5/dd-touch.js +186 -0
  155. package/dist_save/es5/dd-touch.js.map +1 -0
  156. package/dist_save/es5/gridstack-all.js +3 -0
  157. package/dist_save/es5/gridstack-all.js.LICENSE.txt +7 -0
  158. package/dist_save/es5/gridstack-all.js.map +1 -0
  159. package/dist_save/es5/gridstack-engine.d.ts +102 -0
  160. package/dist_save/es5/gridstack-engine.js +997 -0
  161. package/dist_save/es5/gridstack-engine.js.map +1 -0
  162. package/dist_save/es5/gridstack-poly.js +356 -0
  163. package/dist_save/es5/gridstack.d.ts +376 -0
  164. package/dist_save/es5/gridstack.js +2238 -0
  165. package/dist_save/es5/gridstack.js.map +1 -0
  166. package/dist_save/es5/types.d.ts +284 -0
  167. package/dist_save/es5/types.js +36 -0
  168. package/dist_save/es5/types.js.map +1 -0
  169. package/dist_save/es5/utils.d.ts +95 -0
  170. package/dist_save/es5/utils.js +590 -0
  171. package/dist_save/es5/utils.js.map +1 -0
  172. package/dist_save/gridstack-all.js +3 -0
  173. package/dist_save/gridstack-all.js.LICENSE.txt +7 -0
  174. package/dist_save/gridstack-all.js.map +1 -0
  175. package/dist_save/gridstack-engine.d.ts +102 -0
  176. package/dist_save/gridstack-engine.js +956 -0
  177. package/dist_save/gridstack-engine.js.map +1 -0
  178. package/dist_save/gridstack-extra.css +433 -0
  179. package/dist_save/gridstack-extra.min.css +1 -0
  180. package/dist_save/gridstack.css +226 -0
  181. package/dist_save/gridstack.d.ts +376 -0
  182. package/dist_save/gridstack.js +2162 -0
  183. package/dist_save/gridstack.js.map +1 -0
  184. package/dist_save/gridstack.min.css +1 -0
  185. package/dist_save/src/gridstack-extra.scss +27 -0
  186. package/dist_save/src/gridstack.scss +131 -0
  187. package/dist_save/types.d.ts +284 -0
  188. package/dist_save/types.js +36 -0
  189. package/dist_save/types.js.map +1 -0
  190. package/dist_save/utils.d.ts +95 -0
  191. package/dist_save/utils.js +548 -0
  192. package/dist_save/utils.js.map +1 -0
  193. package/doc/CHANGES.md +19 -0
  194. package/doc/README.md +17 -1
  195. package/package.json +25 -24
  196. /package/{dist → dist_save}/angular/README.md +0 -0
@@ -1,2228 +1,2253 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
- if (k2 === undefined) k2 = k;
15
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
16
- }) : (function(o, m, k, k2) {
17
- if (k2 === undefined) k2 = k;
18
- o[k2] = m[k];
19
- }));
20
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
21
- for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
22
- };
23
- var __spreadArrays = (this && this.__spreadArrays) || function () {
24
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
25
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
26
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
27
- r[k] = a[j];
28
- return r;
29
- };
30
- Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.GridStack = void 0;
32
- /*!
33
- * GridStack 7.2.3
34
- * https://gridstackjs.com/
35
- *
36
- * Copyright (c) 2021-2022 Alain Dumesny
37
- * see root license https://github.com/gridstack/gridstack.js/tree/master/LICENSE
38
- */
39
- var gridstack_engine_1 = require("./gridstack-engine");
40
- var utils_1 = require("./utils");
41
- var types_1 = require("./types");
42
- /*
43
- * and include D&D by default
44
- * TODO: while we could generate a gridstack-static.js at smaller size - saves about 31k (41k -> 72k)
45
- * I don't know how to generate the DD only code at the remaining 31k to delay load as code depends on Gridstack.ts
46
- * also it caused loading issues in prod - see https://github.com/gridstack/gridstack.js/issues/2039
47
- */
48
- var dd_gridstack_1 = require("./dd-gridstack");
49
- var dd_touch_1 = require("./dd-touch");
50
- var dd_manager_1 = require("./dd-manager");
51
- /** global instance */
52
- var dd = new dd_gridstack_1.DDGridStack;
53
- // export all dependent file as well to make it easier for users to just import the main file
54
- __exportStar(require("./types"), exports);
55
- __exportStar(require("./utils"), exports);
56
- __exportStar(require("./gridstack-engine"), exports);
57
- __exportStar(require("./dd-gridstack"), exports);
58
- /**
59
- * Main gridstack class - you will need to call `GridStack.init()` first to initialize your grid.
60
- * Note: your grid elements MUST have the following classes for the CSS layout to work:
61
- * @example
62
- * <div class="grid-stack">
63
- * <div class="grid-stack-item">
64
- * <div class="grid-stack-item-content">Item 1</div>
65
- * </div>
66
- * </div>
67
- */
68
- var GridStack = /** @class */ (function () {
69
- /**
70
- * Construct a grid item from the given element and options
71
- * @param el
72
- * @param opts
73
- */
74
- function GridStack(el, opts) {
75
- var _this = this;
76
- if (opts === void 0) { opts = {}; }
77
- var _a, _b;
78
- /** @internal */
79
- this._gsEventHandler = {};
80
- /** @internal extra row added when dragging at the bottom of the grid */
81
- this._extraDragRow = 0;
82
- this.el = el; // exposed HTML element to the user
83
- opts = opts || {}; // handles null/undefined/0
84
- if (!el.classList.contains('grid-stack')) {
85
- this.el.classList.add('grid-stack');
86
- }
87
- // if row property exists, replace minRow and maxRow instead
88
- if (opts.row) {
89
- opts.minRow = opts.maxRow = opts.row;
90
- delete opts.row;
91
- }
92
- var rowAttr = utils_1.Utils.toNumber(el.getAttribute('gs-row'));
93
- // flag only valid in sub-grids (handled by parent, not here)
94
- if (opts.column === 'auto') {
95
- delete opts.column;
96
- }
97
- // 'minWidth' legacy support in 5.1
98
- /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
99
- var anyOpts = opts;
100
- if (anyOpts.minWidth !== undefined) {
101
- opts.oneColumnSize = opts.oneColumnSize || anyOpts.minWidth;
102
- delete anyOpts.minWidth;
103
- }
104
- // save original setting so we can restore on save
105
- if (opts.alwaysShowResizeHandle !== undefined) {
106
- opts._alwaysShowResizeHandle = opts.alwaysShowResizeHandle;
107
- }
108
- // elements DOM attributes override any passed options (like CSS style) - merge the two together
109
- var defaults = __assign(__assign({}, utils_1.Utils.cloneDeep(types_1.gridDefaults)), { column: utils_1.Utils.toNumber(el.getAttribute('gs-column')) || types_1.gridDefaults.column, minRow: rowAttr ? rowAttr : utils_1.Utils.toNumber(el.getAttribute('gs-min-row')) || types_1.gridDefaults.minRow, maxRow: rowAttr ? rowAttr : utils_1.Utils.toNumber(el.getAttribute('gs-max-row')) || types_1.gridDefaults.maxRow, staticGrid: utils_1.Utils.toBool(el.getAttribute('gs-static')) || types_1.gridDefaults.staticGrid, draggable: {
110
- handle: (opts.handleClass ? '.' + opts.handleClass : (opts.handle ? opts.handle : '')) || types_1.gridDefaults.draggable.handle,
111
- }, removableOptions: {
112
- accept: opts.itemClass ? '.' + opts.itemClass : types_1.gridDefaults.removableOptions.accept,
113
- } });
114
- if (el.getAttribute('gs-animate')) { // default to true, but if set to false use that instead
115
- defaults.animate = utils_1.Utils.toBool(el.getAttribute('gs-animate'));
116
- }
117
- this.opts = utils_1.Utils.defaults(opts, defaults);
118
- opts = null; // make sure we use this.opts instead
119
- this._initMargin(); // part of settings defaults...
120
- // Now check if we're loading into 1 column mode FIRST so we don't do un-necessary work (like cellHeight = width / 12 then go 1 column)
121
- if (this.opts.column !== 1 && !this.opts.disableOneColumnMode && this._widthOrContainer() <= this.opts.oneColumnSize) {
122
- this._prevColumn = this.getColumn();
123
- this.opts.column = 1;
124
- }
125
- if (this.opts.rtl === 'auto') {
126
- this.opts.rtl = (el.style.direction === 'rtl');
127
- }
128
- if (this.opts.rtl) {
129
- this.el.classList.add('grid-stack-rtl');
130
- }
131
- // check if we're been nested, and if so update our style and keep pointer around (used during save)
132
- var parentGridItem = (_a = utils_1.Utils.closestUpByClass(this.el, types_1.gridDefaults.itemClass)) === null || _a === void 0 ? void 0 : _a.gridstackNode;
133
- if (parentGridItem) {
134
- parentGridItem.subGrid = this;
135
- this.parentGridItem = parentGridItem;
136
- this.el.classList.add('grid-stack-nested');
137
- parentGridItem.el.classList.add('grid-stack-sub-grid');
138
- }
139
- this._isAutoCellHeight = (this.opts.cellHeight === 'auto');
140
- if (this._isAutoCellHeight || this.opts.cellHeight === 'initial') {
141
- // make the cell content square initially (will use resize/column event to keep it square)
142
- this.cellHeight(undefined, false);
143
- }
144
- else {
145
- // append unit if any are set
146
- if (typeof this.opts.cellHeight == 'number' && this.opts.cellHeightUnit && this.opts.cellHeightUnit !== types_1.gridDefaults.cellHeightUnit) {
147
- this.opts.cellHeight = this.opts.cellHeight + this.opts.cellHeightUnit;
148
- delete this.opts.cellHeightUnit;
149
- }
150
- this.cellHeight(this.opts.cellHeight, false);
151
- }
152
- // see if we need to adjust auto-hide
153
- if (this.opts.alwaysShowResizeHandle === 'mobile') {
154
- this.opts.alwaysShowResizeHandle = dd_touch_1.isTouch;
155
- }
156
- this._styleSheetClass = 'grid-stack-instance-' + gridstack_engine_1.GridStackEngine._idSeq++;
157
- this.el.classList.add(this._styleSheetClass);
158
- this._setStaticClass();
159
- var engineClass = this.opts.engineClass || GridStack.engineClass || gridstack_engine_1.GridStackEngine;
160
- this.engine = new engineClass({
161
- column: this.getColumn(),
162
- float: this.opts.float,
163
- maxRow: this.opts.maxRow,
164
- onChange: function (cbNodes) {
165
- var maxH = 0;
166
- _this.engine.nodes.forEach(function (n) { maxH = Math.max(maxH, n.y + n.h); });
167
- cbNodes.forEach(function (n) {
168
- var el = n.el;
169
- if (!el)
170
- return;
171
- if (n._removeDOM) {
172
- if (el)
173
- el.remove();
174
- delete n._removeDOM;
175
- }
176
- else {
177
- _this._writePosAttr(el, n);
178
- }
179
- });
180
- _this._updateStyles(false, maxH); // false = don't recreate, just append if need be
181
- }
182
- });
183
- if (this.opts.auto) {
184
- this.batchUpdate(); // prevent in between re-layout #1535 TODO: this only set float=true, need to prevent collision check...
185
- var elements_1 = [];
186
- var column_1 = this.getColumn();
187
- if (column_1 === 1 && this._prevColumn)
188
- column_1 = this._prevColumn; // do 12 column when reading into 1 column mode
189
- this.getGridItems().forEach(function (el) {
190
- var x = parseInt(el.getAttribute('gs-x'));
191
- var y = parseInt(el.getAttribute('gs-y'));
192
- elements_1.push({
193
- el: el,
194
- // if x,y are missing (autoPosition) add them to end of list - but keep their respective DOM order
195
- i: (Number.isNaN(x) ? 1000 : x) + (Number.isNaN(y) ? 1000 : y) * column_1
196
- });
197
- });
198
- elements_1.sort(function (a, b) { return b.i - a.i; }).forEach(function (e) { return _this._prepareElement(e.el); }); // revert sort so lowest item wins
199
- this.batchUpdate(false);
200
- }
201
- // load any passed in children as well, which overrides any DOM layout done above
202
- if (this.opts.children) {
203
- var children = this.opts.children;
204
- delete this.opts.children;
205
- if (children.length)
206
- this.load(children); // don't load empty
207
- }
208
- this.setAnimation(this.opts.animate);
209
- this._updateStyles();
210
- if (this.opts.column != 12) {
211
- this.el.classList.add('grid-stack-' + this.opts.column);
212
- }
213
- // legacy support to appear 'per grid` options when really global.
214
- if (this.opts.dragIn)
215
- GridStack.setupDragIn(this.opts.dragIn, this.opts.dragInOptions);
216
- delete this.opts.dragIn;
217
- delete this.opts.dragInOptions;
218
- // dynamic grids require pausing during drag to detect over to nest vs push
219
- if (this.opts.subGridDynamic && !dd_manager_1.DDManager.pauseDrag)
220
- dd_manager_1.DDManager.pauseDrag = true;
221
- if (((_b = this.opts.draggable) === null || _b === void 0 ? void 0 : _b.pause) !== undefined)
222
- dd_manager_1.DDManager.pauseDrag = this.opts.draggable.pause;
223
- this._setupRemoveDrop();
224
- this._setupAcceptWidget();
225
- this._updateWindowResizeEvent();
226
- }
227
- /**
228
- * initializing the HTML element, or selector string, into a grid will return the grid. Calling it again will
229
- * simply return the existing instance (ignore any passed options). There is also an initAll() version that support
230
- * multiple grids initialization at once. Or you can use addGrid() to create the entire grid from JSON.
231
- * @param options grid options (optional)
232
- * @param elOrString element or CSS selector (first one used) to convert to a grid (default to '.grid-stack' class selector)
233
- *
234
- * @example
235
- * let grid = GridStack.init();
236
- *
237
- * Note: the HTMLElement (of type GridHTMLElement) will store a `gridstack: GridStack` value that can be retrieve later
238
- * let grid = document.querySelector('.grid-stack').gridstack;
239
- */
240
- GridStack.init = function (options, elOrString) {
241
- if (options === void 0) { options = {}; }
242
- if (elOrString === void 0) { elOrString = '.grid-stack'; }
243
- var el = GridStack.getGridElement(elOrString);
244
- if (!el) {
245
- if (typeof elOrString === 'string') {
246
- console.error('GridStack.initAll() no grid was found with selector "' + elOrString + '" - element missing or wrong selector ?' +
247
- '\nNote: ".grid-stack" is required for proper CSS styling and drag/drop, and is the default selector.');
248
- }
249
- else {
250
- console.error('GridStack.init() no grid element was passed.');
251
- }
252
- return null;
253
- }
254
- if (!el.gridstack) {
255
- el.gridstack = new GridStack(el, utils_1.Utils.cloneDeep(options));
256
- }
257
- return el.gridstack;
258
- };
259
- /**
260
- * Will initialize a list of elements (given a selector) and return an array of grids.
261
- * @param options grid options (optional)
262
- * @param selector elements selector to convert to grids (default to '.grid-stack' class selector)
263
- *
264
- * @example
265
- * let grids = GridStack.initAll();
266
- * grids.forEach(...)
267
- */
268
- GridStack.initAll = function (options, selector) {
269
- if (options === void 0) { options = {}; }
270
- if (selector === void 0) { selector = '.grid-stack'; }
271
- var grids = [];
272
- GridStack.getGridElements(selector).forEach(function (el) {
273
- if (!el.gridstack) {
274
- el.gridstack = new GridStack(el, utils_1.Utils.cloneDeep(options));
275
- delete options.dragIn;
276
- delete options.dragInOptions; // only need to be done once (really a static global thing, not per grid)
277
- }
278
- grids.push(el.gridstack);
279
- });
280
- if (grids.length === 0) {
281
- console.error('GridStack.initAll() no grid was found with selector "' + selector + '" - element missing or wrong selector ?' +
282
- '\nNote: ".grid-stack" is required for proper CSS styling and drag/drop, and is the default selector.');
283
- }
284
- return grids;
285
- };
286
- /**
287
- * call to create a grid with the given options, including loading any children from JSON structure. This will call GridStack.init(), then
288
- * grid.load() on any passed children (recursively). Great alternative to calling init() if you want entire grid to come from
289
- * JSON serialized data, including options.
290
- * @param parent HTML element parent to the grid
291
- * @param opt grids options used to initialize the grid, and list of children
292
- */
293
- GridStack.addGrid = function (parent, opt) {
294
- if (opt === void 0) { opt = {}; }
295
- if (!parent)
296
- return null;
297
- // create the grid element, but check if the passed 'parent' already has grid styling and should be used instead
298
- var el = parent;
299
- if (!parent.classList.contains('grid-stack')) {
300
- var doc = document.implementation.createHTMLDocument(''); // IE needs a param
301
- doc.body.innerHTML = "<div class=\"grid-stack " + (opt.class || '') + "\"></div>";
302
- el = doc.body.children[0];
303
- parent.appendChild(el);
304
- }
305
- // create grid class and load any children
306
- var grid = GridStack.init(opt, el);
307
- return grid;
308
- };
309
- /** call this method to register your engine instead of the default one.
310
- * See instead `GridStackOptions.engineClass` if you only need to
311
- * replace just one instance.
312
- */
313
- GridStack.registerEngine = function (engineClass) {
314
- GridStack.engineClass = engineClass;
315
- };
316
- Object.defineProperty(GridStack.prototype, "placeholder", {
317
- /** @internal create placeholder DIV as needed */
318
- get: function () {
319
- if (!this._placeholder) {
320
- var placeholderChild = document.createElement('div'); // child so padding match item-content
321
- placeholderChild.className = 'placeholder-content';
322
- if (this.opts.placeholderText) {
323
- placeholderChild.innerHTML = this.opts.placeholderText;
324
- }
325
- this._placeholder = document.createElement('div');
326
- this._placeholder.classList.add(this.opts.placeholderClass, types_1.gridDefaults.itemClass, this.opts.itemClass);
327
- this.placeholder.appendChild(placeholderChild);
328
- }
329
- return this._placeholder;
330
- },
331
- enumerable: false,
332
- configurable: true
333
- });
334
- /**
335
- * add a new widget and returns it.
336
- *
337
- * Widget will be always placed even if result height is more than actual grid height.
338
- * You need to use `willItFit()` before calling addWidget for additional check.
339
- * See also `makeWidget()`.
340
- *
341
- * @example
342
- * let grid = GridStack.init();
343
- * grid.addWidget({w: 3, content: 'hello'});
344
- * grid.addWidget('<div class="grid-stack-item"><div class="grid-stack-item-content">hello</div></div>', {w: 3});
345
- *
346
- * @param el GridStackWidget (which can have content string as well), html element, or string definition to add
347
- * @param options widget position/size options (optional, and ignore if first param is already option) - see GridStackWidget
348
- */
349
- GridStack.prototype.addWidget = function (els, options) {
350
- function isGridStackWidget(w) {
351
- return w.el !== undefined || w.x !== undefined || w.y !== undefined || w.w !== undefined || w.h !== undefined || w.content !== undefined ? true : false;
352
- }
353
- var el;
354
- var node;
355
- if (typeof els === 'string') {
356
- var doc = document.implementation.createHTMLDocument(''); // IE needs a param
357
- doc.body.innerHTML = els;
358
- el = doc.body.children[0];
359
- }
360
- else if (arguments.length === 0 || arguments.length === 1 && isGridStackWidget(els)) {
361
- node = options = els;
362
- if (node === null || node === void 0 ? void 0 : node.el) {
363
- el = node.el; // re-use element stored in the node
364
- }
365
- else if (this.opts.addRemoveCB) {
366
- el = this.opts.addRemoveCB(this, options, true);
367
- }
368
- else {
369
- var content = (options === null || options === void 0 ? void 0 : options.content) || '';
370
- var doc = document.implementation.createHTMLDocument(''); // IE needs a param
371
- doc.body.innerHTML = "<div class=\"grid-stack-item " + (this.opts.itemClass || '') + "\"><div class=\"grid-stack-item-content\">" + content + "</div></div>";
372
- el = doc.body.children[0];
373
- }
374
- }
375
- else {
376
- el = els;
377
- }
378
- if (!el)
379
- return;
380
- // Tempting to initialize the passed in opt with default and valid values, but this break knockout demos
381
- // as the actual value are filled in when _prepareElement() calls el.getAttribute('gs-xyz') before adding the node.
382
- // So make sure we load any DOM attributes that are not specified in passed in options (which override)
383
- var domAttr = this._readAttr(el);
384
- options = utils_1.Utils.cloneDeep(options) || {}; // make a copy before we modify in case caller re-uses it
385
- utils_1.Utils.defaults(options, domAttr);
386
- node = this.engine.prepareNode(options);
387
- this._writeAttr(el, options);
388
- if (this._insertNotAppend) {
389
- this.el.prepend(el);
390
- }
391
- else {
392
- this.el.appendChild(el);
393
- }
394
- // similar to makeWidget() that doesn't read attr again and worse re-create a new node and loose any _id
395
- this._prepareElement(el, true, options);
396
- this._updateContainerHeight();
397
- // see if there is a sub-grid to create
398
- if (node.subGrid) {
399
- this.makeSubGrid(node.el, undefined, undefined, false);
400
- }
401
- // if we're adding an item into 1 column (_prevColumn is set only when going to 1) make sure
402
- // we don't override the larger 12 column layout that was already saved. #1985
403
- if (this._prevColumn && this.opts.column === 1) {
404
- this._ignoreLayoutsNodeChange = true;
405
- }
406
- this._triggerAddEvent();
407
- this._triggerChangeEvent();
408
- delete this._ignoreLayoutsNodeChange;
409
- return el;
410
- };
411
- /**
412
- * Convert an existing gridItem element into a sub-grid with the given (optional) options, else inherit them
413
- * from the parent's subGrid options.
414
- * @param el gridItem element to convert
415
- * @param ops (optional) sub-grid options, else default to node, then parent settings, else defaults
416
- * @param nodeToAdd (optional) node to add to the newly created sub grid (used when dragging over existing regular item)
417
- * @returns newly created grid
418
- */
419
- GridStack.prototype.makeSubGrid = function (el, ops, nodeToAdd, saveContent) {
420
- var _a, _b, _c;
421
- if (saveContent === void 0) { saveContent = true; }
422
- var node = el.gridstackNode;
423
- if (!node) {
424
- node = this.makeWidget(el).gridstackNode;
425
- }
426
- if ((_a = node.subGrid) === null || _a === void 0 ? void 0 : _a.el)
427
- return node.subGrid; // already done
428
- // find the template subGrid stored on a parent as fallback...
429
- var subGridTemplate; // eslint-disable-next-line @typescript-eslint/no-this-alias
430
- var grid = this;
431
- while (grid && !subGridTemplate) {
432
- subGridTemplate = (_b = grid.opts) === null || _b === void 0 ? void 0 : _b.subGrid;
433
- grid = (_c = grid.parentGridItem) === null || _c === void 0 ? void 0 : _c.grid;
434
- }
435
- //... and set the create options
436
- ops = utils_1.Utils.cloneDeep(__assign(__assign(__assign({}, (subGridTemplate || {})), { children: undefined }), (ops || node.subGrid)));
437
- node.subGrid = ops;
438
- // if column special case it set, remember that flag and set default
439
- var autoColumn;
440
- if (ops.column === 'auto') {
441
- autoColumn = true;
442
- ops.column = Math.max(node.w || 1, (nodeToAdd === null || nodeToAdd === void 0 ? void 0 : nodeToAdd.w) || 1);
443
- ops.disableOneColumnMode = true; // driven by parent
444
- }
445
- // if we're converting an existing full item, move over the content to be the first sub item in the new grid
446
- // TODO: support this.opts.addRemoveCB for frameworks
447
- var content = node.el.querySelector('.grid-stack-item-content');
448
- var newItem;
449
- var newItemOpt;
450
- if (saveContent) {
451
- this._removeDD(node.el); // remove D&D since it's set on content div
452
- var doc = document.implementation.createHTMLDocument(''); // IE needs a param
453
- doc.body.innerHTML = "<div class=\"grid-stack-item\"></div>";
454
- newItem = doc.body.children[0];
455
- newItem.appendChild(content);
456
- newItemOpt = __assign(__assign({}, node), { x: 0, y: 0 });
457
- utils_1.Utils.removeInternalForSave(newItemOpt);
458
- delete newItemOpt.subGrid;
459
- if (node.content) {
460
- newItemOpt.content = node.content;
461
- delete node.content;
462
- }
463
- doc.body.innerHTML = "<div class=\"grid-stack-item-content\"></div>";
464
- content = doc.body.children[0];
465
- node.el.appendChild(content);
466
- this._prepareDragDropByNode(node); // ... and restore original D&D
467
- }
468
- // if we're adding an additional item, make the container large enough to have them both
469
- if (nodeToAdd) {
470
- var w = autoColumn ? ops.column : node.w;
471
- var h = node.h + nodeToAdd.h;
472
- var style_1 = node.el.style;
473
- style_1.transition = 'none'; // show up instantly so we don't see scrollbar with nodeToAdd
474
- this.update(node.el, { w: w, h: h });
475
- setTimeout(function () { return style_1.transition = null; }); // recover animation
476
- }
477
- var subGrid = node.subGrid = GridStack.addGrid(content, ops);
478
- if (nodeToAdd === null || nodeToAdd === void 0 ? void 0 : nodeToAdd._moving)
479
- subGrid._isTemp = true; // prevent re-nesting as we add over
480
- if (autoColumn)
481
- subGrid._autoColumn = true;
482
- // add the original content back as a child of hte newly created grid
483
- if (saveContent) {
484
- subGrid.addWidget(newItem, newItemOpt);
485
- }
486
- // now add any additional node
487
- if (nodeToAdd) {
488
- if (nodeToAdd._moving) {
489
- // create an artificial event even for the just created grid to receive this item
490
- window.setTimeout(function () { return utils_1.Utils.simulateMouseEvent(nodeToAdd._event, 'mouseenter', subGrid.el); }, 0);
491
- }
492
- else {
493
- subGrid.addWidget(node.el, node);
494
- }
495
- }
496
- return subGrid;
497
- };
498
- /**
499
- * called when an item was converted into a nested grid to accommodate a dragged over item, but then item leaves - return back
500
- * to the original grid-item. Also called to remove empty sub-grids when last item is dragged out (since re-creating is simple)
501
- */
502
- GridStack.prototype.removeAsSubGrid = function (nodeThatRemoved) {
503
- var _this = this;
504
- var _a;
505
- var pGrid = (_a = this.parentGridItem) === null || _a === void 0 ? void 0 : _a.grid;
506
- if (!pGrid)
507
- return;
508
- pGrid.batchUpdate();
509
- pGrid.removeWidget(this.parentGridItem.el, true, true);
510
- this.engine.nodes.forEach(function (n) {
511
- // migrate any children over and offsetting by our location
512
- n.x += _this.parentGridItem.x;
513
- n.y += _this.parentGridItem.y;
514
- pGrid.addWidget(n.el, n);
515
- });
516
- pGrid.batchUpdate(false);
517
- delete this.parentGridItem;
518
- // create an artificial event for the original grid now that this one is gone (got a leave, but won't get enter)
519
- if (nodeThatRemoved) {
520
- window.setTimeout(function () { return utils_1.Utils.simulateMouseEvent(nodeThatRemoved._event, 'mouseenter', pGrid.el); }, 0);
521
- }
522
- };
523
- /**
524
- /**
525
- * saves the current layout returning a list of widgets for serialization which might include any nested grids.
526
- * @param saveContent if true (default) the latest html inside .grid-stack-content will be saved to GridStackWidget.content field, else it will
527
- * be removed.
528
- * @param saveGridOpt if true (default false), save the grid options itself, so you can call the new GridStack.addGrid()
529
- * to recreate everything from scratch. GridStackOptions.children would then contain the widget list instead.
530
- * @returns list of widgets or full grid option, including .children list of widgets
531
- */
532
- GridStack.prototype.save = function (saveContent, saveGridOpt) {
533
- if (saveContent === void 0) { saveContent = true; }
534
- if (saveGridOpt === void 0) { saveGridOpt = false; }
535
- // return copied nodes we can modify at will...
536
- var list = this.engine.save(saveContent);
537
- // check for HTML content and nested grids
538
- list.forEach(function (n) {
539
- var _a;
540
- if (saveContent && n.el && !n.subGrid) { // sub-grid are saved differently, not plain content
541
- var sub = n.el.querySelector('.grid-stack-item-content');
542
- n.content = sub ? sub.innerHTML : undefined;
543
- if (!n.content)
544
- delete n.content;
545
- }
546
- else {
547
- if (!saveContent) {
548
- delete n.content;
549
- }
550
- // check for nested grid
551
- if ((_a = n.subGrid) === null || _a === void 0 ? void 0 : _a.el) {
552
- var listOrOpt = n.subGrid.save(saveContent, saveGridOpt);
553
- n.subGrid = (saveGridOpt ? listOrOpt : { children: listOrOpt });
554
- }
555
- }
556
- delete n.el;
557
- });
558
- // check if save entire grid options (needed for recursive) + children...
559
- if (saveGridOpt) {
560
- var o = utils_1.Utils.cloneDeep(this.opts);
561
- // delete default values that will be recreated on launch
562
- if (o.marginBottom === o.marginTop && o.marginRight === o.marginLeft && o.marginTop === o.marginRight) {
563
- o.margin = o.marginTop;
564
- delete o.marginTop;
565
- delete o.marginRight;
566
- delete o.marginBottom;
567
- delete o.marginLeft;
568
- }
569
- if (o.rtl === (this.el.style.direction === 'rtl')) {
570
- o.rtl = 'auto';
571
- }
572
- if (this._isAutoCellHeight) {
573
- o.cellHeight = 'auto';
574
- }
575
- if (this._autoColumn) {
576
- o.column = 'auto';
577
- delete o.disableOneColumnMode;
578
- }
579
- var origShow = o._alwaysShowResizeHandle;
580
- delete o._alwaysShowResizeHandle;
581
- if (origShow !== undefined) {
582
- o.alwaysShowResizeHandle = origShow;
583
- }
584
- else {
585
- delete o.alwaysShowResizeHandle;
586
- }
587
- utils_1.Utils.removeInternalAndSame(o, types_1.gridDefaults);
588
- o.children = list;
589
- return o;
590
- }
591
- return list;
592
- };
593
- /**
594
- * load the widgets from a list. This will call update() on each (matching by id) or add/remove widgets that are not there.
595
- *
596
- * @param layout list of widgets definition to update/create
597
- * @param addAndRemove boolean (default true) or callback method can be passed to control if and how missing widgets can be added/removed, giving
598
- * the user control of insertion.
599
- *
600
- * @example
601
- * see http://gridstackjs.com/demo/serialization.html
602
- **/
603
- GridStack.prototype.load = function (layout, addRemove) {
604
- var _this = this;
605
- if (addRemove === void 0) { addRemove = this.opts.addRemoveCB || true; }
606
- var items = GridStack.Utils.sort(__spreadArrays(layout), -1, this._prevColumn || this.getColumn()); // make copy before we mod/sort
607
- this._insertNotAppend = true; // since create in reverse order...
608
- // if we're loading a layout into for example 1 column (_prevColumn is set only when going to 1) and items don't fit, make sure to save
609
- // the original wanted layout so we can scale back up correctly #1471
610
- if (this._prevColumn && this._prevColumn !== this.opts.column && items.some(function (n) { return (n.x + n.w) > _this.opts.column; })) {
611
- this._ignoreLayoutsNodeChange = true; // skip layout update
612
- this.engine.cacheLayout(items, this._prevColumn, true);
613
- }
614
- // if given a different callback, temporally set it as global option to creating will use it
615
- var prevCB = this.opts.addRemoveCB;
616
- if (typeof (addRemove) === 'function')
617
- this.opts.addRemoveCB = addRemove;
618
- var removed = [];
619
- this.batchUpdate();
620
- // see if any items are missing from new layout and need to be removed first
621
- if (addRemove) {
622
- var copyNodes = __spreadArrays(this.engine.nodes); // don't loop through array you modify
623
- copyNodes.forEach(function (n) {
624
- var item = items.find(function (w) { return n.id === w.id; });
625
- if (!item) {
626
- if (_this.opts.addRemoveCB)
627
- _this.opts.addRemoveCB(_this, n, false);
628
- removed.push(n); // batch keep track
629
- _this.removeWidget(n.el, true, false);
630
- }
631
- });
632
- }
633
- // now add/update the widgets
634
- items.forEach(function (w) {
635
- var item = (w.id || w.id === 0) ? _this.engine.nodes.find(function (n) { return n.id === w.id; }) : undefined;
636
- if (item) {
637
- _this.update(item.el, w);
638
- if (w.subGrid && w.subGrid.children) { // update any sub grid as well
639
- var sub = item.el.querySelector('.grid-stack');
640
- if (sub && sub.gridstack) {
641
- sub.gridstack.load(w.subGrid.children); // TODO: support updating grid options ?
642
- _this._insertNotAppend = true; // got reset by above call
643
- }
644
- }
645
- }
646
- else if (addRemove) {
647
- _this.addWidget(w);
648
- }
649
- });
650
- this.engine.removedNodes = removed;
651
- this.batchUpdate(false);
652
- // after commit, clear that flag
653
- delete this._ignoreLayoutsNodeChange;
654
- delete this._insertNotAppend;
655
- prevCB ? this.opts.addRemoveCB = prevCB : delete this.opts.addRemoveCB;
656
- return this;
657
- };
658
- /**
659
- * use before calling a bunch of `addWidget()` to prevent un-necessary relayouts in between (more efficient)
660
- * and get a single event callback. You will see no changes until `batchUpdate(false)` is called.
661
- */
662
- GridStack.prototype.batchUpdate = function (flag) {
663
- if (flag === void 0) { flag = true; }
664
- this.engine.batchUpdate(flag);
665
- if (!flag) {
666
- this._triggerRemoveEvent();
667
- this._triggerAddEvent();
668
- this._triggerChangeEvent();
669
- }
670
- return this;
671
- };
672
- /**
673
- * Gets current cell height.
674
- */
675
- GridStack.prototype.getCellHeight = function (forcePixel) {
676
- if (forcePixel === void 0) { forcePixel = false; }
677
- if (this.opts.cellHeight && this.opts.cellHeight !== 'auto' &&
678
- (!forcePixel || !this.opts.cellHeightUnit || this.opts.cellHeightUnit === 'px')) {
679
- return this.opts.cellHeight;
680
- }
681
- // else get first cell height
682
- var el = this.el.querySelector('.' + this.opts.itemClass);
683
- if (el) {
684
- var height = utils_1.Utils.toNumber(el.getAttribute('gs-h'));
685
- return Math.round(el.offsetHeight / height);
686
- }
687
- // else do entire grid and # of rows (but doesn't work if min-height is the actual constrain)
688
- var rows = parseInt(this.el.getAttribute('gs-current-row'));
689
- return rows ? Math.round(this.el.getBoundingClientRect().height / rows) : this.opts.cellHeight;
690
- };
691
- /**
692
- * Update current cell height - see `GridStackOptions.cellHeight` for format.
693
- * This method rebuilds an internal CSS style sheet.
694
- * Note: You can expect performance issues if call this method too often.
695
- *
696
- * @param val the cell height. If not passed (undefined), cells content will be made square (match width minus margin),
697
- * if pass 0 the CSS will be generated by the application instead.
698
- * @param update (Optional) if false, styles will not be updated
699
- *
700
- * @example
701
- * grid.cellHeight(100); // same as 100px
702
- * grid.cellHeight('70px');
703
- * grid.cellHeight(grid.cellWidth() * 1.2);
704
- */
705
- GridStack.prototype.cellHeight = function (val, update) {
706
- if (update === void 0) { update = true; }
707
- // if not called internally, check if we're changing mode
708
- if (update && val !== undefined) {
709
- if (this._isAutoCellHeight !== (val === 'auto')) {
710
- this._isAutoCellHeight = (val === 'auto');
711
- this._updateWindowResizeEvent();
712
- }
713
- }
714
- if (val === 'initial' || val === 'auto') {
715
- val = undefined;
716
- }
717
- // make item content be square
718
- if (val === undefined) {
719
- var marginDiff = -this.opts.marginRight - this.opts.marginLeft
720
- + this.opts.marginTop + this.opts.marginBottom;
721
- val = this.cellWidth() + marginDiff;
722
- }
723
- var data = utils_1.Utils.parseHeight(val);
724
- if (this.opts.cellHeightUnit === data.unit && this.opts.cellHeight === data.h) {
725
- return this;
726
- }
727
- this.opts.cellHeightUnit = data.unit;
728
- this.opts.cellHeight = data.h;
729
- if (update) {
730
- this._updateStyles(true); // true = force re-create for current # of rows
731
- }
732
- return this;
733
- };
734
- /** Gets current cell width. */
735
- GridStack.prototype.cellWidth = function () {
736
- return this._widthOrContainer() / this.getColumn();
737
- };
738
- /** return our expected width (or parent) for 1 column check */
739
- GridStack.prototype._widthOrContainer = function () {
740
- // use `offsetWidth` or `clientWidth` (no scrollbar) ?
741
- // https://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively
742
- return (this.el.clientWidth || this.el.parentElement.clientWidth || window.innerWidth);
743
- };
744
- /** re-layout grid items to reclaim any empty space */
745
- GridStack.prototype.compact = function () {
746
- this.engine.compact();
747
- this._triggerChangeEvent();
748
- return this;
749
- };
750
- /**
751
- * set the number of columns in the grid. Will update existing widgets to conform to new number of columns,
752
- * as well as cache the original layout so you can revert back to previous positions without loss.
753
- * Requires `gridstack-extra.css` or `gridstack-extra.min.css` for [2-11],
754
- * else you will need to generate correct CSS (see https://github.com/gridstack/gridstack.js#change-grid-columns)
755
- * @param column - Integer > 0 (default 12).
756
- * @param layout specify the type of re-layout that will happen (position, size, etc...).
757
- * Note: items will never be outside of the current column boundaries. default (moveScale). Ignored for 1 column
758
- */
759
- GridStack.prototype.column = function (column, layout) {
760
- if (layout === void 0) { layout = 'moveScale'; }
761
- if (column < 1 || this.opts.column === column)
762
- return this;
763
- var oldColumn = this.getColumn();
764
- // if we go into 1 column mode (which happens if we're sized less than minW unless disableOneColumnMode is on)
765
- // then remember the original columns so we can restore.
766
- if (column === 1) {
767
- this._prevColumn = oldColumn;
768
- }
769
- else {
770
- delete this._prevColumn;
771
- }
772
- this.el.classList.remove('grid-stack-' + oldColumn);
773
- this.el.classList.add('grid-stack-' + column);
774
- this.opts.column = this.engine.column = column;
775
- // update the items now - see if the dom order nodes should be passed instead (else default to current list)
776
- var domNodes;
777
- if (column === 1 && this.opts.oneColumnModeDomSort) {
778
- domNodes = [];
779
- this.getGridItems().forEach(function (el) {
780
- if (el.gridstackNode) {
781
- domNodes.push(el.gridstackNode);
782
- }
783
- });
784
- if (!domNodes.length) {
785
- domNodes = undefined;
786
- }
787
- }
788
- this.engine.updateNodeWidths(oldColumn, column, domNodes, layout);
789
- if (this._isAutoCellHeight)
790
- this.cellHeight();
791
- // and trigger our event last...
792
- this._ignoreLayoutsNodeChange = true; // skip layout update
793
- this._triggerChangeEvent();
794
- delete this._ignoreLayoutsNodeChange;
795
- return this;
796
- };
797
- /**
798
- * get the number of columns in the grid (default 12)
799
- */
800
- GridStack.prototype.getColumn = function () {
801
- return this.opts.column;
802
- };
803
- /** returns an array of grid HTML elements (no placeholder) - used to iterate through our children in DOM order */
804
- GridStack.prototype.getGridItems = function () {
805
- var _this = this;
806
- return Array.from(this.el.children)
807
- .filter(function (el) { return el.matches('.' + _this.opts.itemClass) && !el.matches('.' + _this.opts.placeholderClass); });
808
- };
809
- /**
810
- * Destroys a grid instance. DO NOT CALL any methods or access any vars after this as it will free up members.
811
- * @param removeDOM if `false` grid and items HTML elements will not be removed from the DOM (Optional. Default `true`).
812
- */
813
- GridStack.prototype.destroy = function (removeDOM) {
814
- if (removeDOM === void 0) { removeDOM = true; }
815
- if (!this.el)
816
- return; // prevent multiple calls
817
- this._updateWindowResizeEvent(true);
818
- this.setStatic(true, false); // permanently removes DD but don't set CSS class (we're going away)
819
- this.setAnimation(false);
820
- if (!removeDOM) {
821
- this.removeAll(removeDOM);
822
- this.el.classList.remove(this._styleSheetClass);
823
- }
824
- else {
825
- this.el.parentNode.removeChild(this.el);
826
- }
827
- this._removeStylesheet();
828
- this.el.removeAttribute('gs-current-row');
829
- delete this.parentGridItem;
830
- delete this.opts;
831
- delete this._placeholder;
832
- delete this.engine;
833
- delete this.el.gridstack; // remove circular dependency that would prevent a freeing
834
- delete this.el;
835
- return this;
836
- };
837
- /**
838
- * enable/disable floating widgets (default: `false`) See [example](http://gridstackjs.com/demo/float.html)
839
- */
840
- GridStack.prototype.float = function (val) {
841
- if (this.opts.float !== val) {
842
- this.opts.float = this.engine.float = val;
843
- this._triggerChangeEvent();
844
- }
845
- return this;
846
- };
847
- /**
848
- * get the current float mode
849
- */
850
- GridStack.prototype.getFloat = function () {
851
- return this.engine.float;
852
- };
853
- /**
854
- * Get the position of the cell under a pixel on screen.
855
- * @param position the position of the pixel to resolve in
856
- * absolute coordinates, as an object with top and left properties
857
- * @param useDocRelative if true, value will be based on document position vs parent position (Optional. Default false).
858
- * Useful when grid is within `position: relative` element
859
- *
860
- * Returns an object with properties `x` and `y` i.e. the column and row in the grid.
861
- */
862
- GridStack.prototype.getCellFromPixel = function (position, useDocRelative) {
863
- if (useDocRelative === void 0) { useDocRelative = false; }
864
- var box = this.el.getBoundingClientRect();
865
- // console.log(`getBoundingClientRect left: ${box.left} top: ${box.top} w: ${box.w} h: ${box.h}`)
866
- var containerPos;
867
- if (useDocRelative) {
868
- containerPos = { top: box.top + document.documentElement.scrollTop, left: box.left };
869
- // console.log(`getCellFromPixel scrollTop: ${document.documentElement.scrollTop}`)
870
- }
871
- else {
872
- containerPos = { top: this.el.offsetTop, left: this.el.offsetLeft };
873
- // console.log(`getCellFromPixel offsetTop: ${containerPos.left} offsetLeft: ${containerPos.top}`)
874
- }
875
- var relativeLeft = position.left - containerPos.left;
876
- var relativeTop = position.top - containerPos.top;
877
- var columnWidth = (box.width / this.getColumn());
878
- var rowHeight = (box.height / parseInt(this.el.getAttribute('gs-current-row')));
879
- return { x: Math.floor(relativeLeft / columnWidth), y: Math.floor(relativeTop / rowHeight) };
880
- };
881
- /** returns the current number of rows, which will be at least `minRow` if set */
882
- GridStack.prototype.getRow = function () {
883
- return Math.max(this.engine.getRow(), this.opts.minRow);
884
- };
885
- /**
886
- * Checks if specified area is empty.
887
- * @param x the position x.
888
- * @param y the position y.
889
- * @param w the width of to check
890
- * @param h the height of to check
891
- */
892
- GridStack.prototype.isAreaEmpty = function (x, y, w, h) {
893
- return this.engine.isAreaEmpty(x, y, w, h);
894
- };
895
- /**
896
- * If you add elements to your grid by hand, you have to tell gridstack afterwards to make them widgets.
897
- * If you want gridstack to add the elements for you, use `addWidget()` instead.
898
- * Makes the given element a widget and returns it.
899
- * @param els widget or single selector to convert.
900
- *
901
- * @example
902
- * let grid = GridStack.init();
903
- * grid.el.appendChild('<div id="gsi-1" gs-w="3"></div>');
904
- * grid.makeWidget('#gsi-1');
905
- */
906
- GridStack.prototype.makeWidget = function (els) {
907
- var el = GridStack.getElement(els);
908
- this._prepareElement(el, true);
909
- this._updateContainerHeight();
910
- this._triggerAddEvent();
911
- this._triggerChangeEvent();
912
- return el;
913
- };
914
- /**
915
- * Event handler that extracts our CustomEvent data out automatically for receiving custom
916
- * notifications (see doc for supported events)
917
- * @param name of the event (see possible values) or list of names space separated
918
- * @param callback function called with event and optional second/third param
919
- * (see README documentation for each signature).
920
- *
921
- * @example
922
- * grid.on('added', function(e, items) { log('added ', items)} );
923
- * or
924
- * grid.on('added removed change', function(e, items) { log(e.type, items)} );
925
- *
926
- * Note: in some cases it is the same as calling native handler and parsing the event.
927
- * grid.el.addEventListener('added', function(event) { log('added ', event.detail)} );
928
- *
929
- */
930
- GridStack.prototype.on = function (name, callback) {
931
- var _this = this;
932
- // check for array of names being passed instead
933
- if (name.indexOf(' ') !== -1) {
934
- var names = name.split(' ');
935
- names.forEach(function (name) { return _this.on(name, callback); });
936
- return this;
937
- }
938
- if (name === 'change' || name === 'added' || name === 'removed' || name === 'enable' || name === 'disable') {
939
- // native CustomEvent handlers - cash the generic handlers so we can easily remove
940
- var noData = (name === 'enable' || name === 'disable');
941
- if (noData) {
942
- this._gsEventHandler[name] = function (event) { return callback(event); };
943
- }
944
- else {
945
- this._gsEventHandler[name] = function (event) { return callback(event, event.detail); };
946
- }
947
- this.el.addEventListener(name, this._gsEventHandler[name]);
948
- }
949
- else if (name === 'drag' || name === 'dragstart' || name === 'dragstop' || name === 'resizestart' || name === 'resize' || name === 'resizestop' || name === 'dropped') {
950
- // drag&drop stop events NEED to be call them AFTER we update node attributes so handle them ourself.
951
- // do same for start event to make it easier...
952
- this._gsEventHandler[name] = callback;
953
- }
954
- else {
955
- console.log('GridStack.on(' + name + ') event not supported, but you can still use $(".grid-stack").on(...) while jquery-ui is still used internally.');
956
- }
957
- return this;
958
- };
959
- /**
960
- * unsubscribe from the 'on' event below
961
- * @param name of the event (see possible values)
962
- */
963
- GridStack.prototype.off = function (name) {
964
- var _this = this;
965
- // check for array of names being passed instead
966
- if (name.indexOf(' ') !== -1) {
967
- var names = name.split(' ');
968
- names.forEach(function (name) { return _this.off(name); });
969
- return this;
970
- }
971
- if (name === 'change' || name === 'added' || name === 'removed' || name === 'enable' || name === 'disable') {
972
- // remove native CustomEvent handlers
973
- if (this._gsEventHandler[name]) {
974
- this.el.removeEventListener(name, this._gsEventHandler[name]);
975
- }
976
- }
977
- delete this._gsEventHandler[name];
978
- return this;
979
- };
980
- /**
981
- * Removes widget from the grid.
982
- * @param el widget or selector to modify
983
- * @param removeDOM if `false` DOM element won't be removed from the tree (Default? true).
984
- * @param triggerEvent if `false` (quiet mode) element will not be added to removed list and no 'removed' callbacks will be called (Default? true).
985
- */
986
- GridStack.prototype.removeWidget = function (els, removeDOM, triggerEvent) {
987
- var _this = this;
988
- if (removeDOM === void 0) { removeDOM = true; }
989
- if (triggerEvent === void 0) { triggerEvent = true; }
990
- GridStack.getElements(els).forEach(function (el) {
991
- if (el.parentElement && el.parentElement !== _this.el)
992
- return; // not our child!
993
- var node = el.gridstackNode;
994
- // For Meteor support: https://github.com/gridstack/gridstack.js/pull/272
995
- if (!node) {
996
- node = _this.engine.nodes.find(function (n) { return el === n.el; });
997
- }
998
- if (!node)
999
- return;
1000
- // remove our DOM data (circular link) and drag&drop permanently
1001
- delete el.gridstackNode;
1002
- _this._removeDD(el);
1003
- _this.engine.removeNode(node, removeDOM, triggerEvent);
1004
- if (removeDOM && el.parentElement) {
1005
- el.remove(); // in batch mode engine.removeNode doesn't call back to remove DOM
1006
- }
1007
- });
1008
- if (triggerEvent) {
1009
- this._triggerRemoveEvent();
1010
- this._triggerChangeEvent();
1011
- }
1012
- return this;
1013
- };
1014
- /**
1015
- * Removes all widgets from the grid.
1016
- * @param removeDOM if `false` DOM elements won't be removed from the tree (Default? `true`).
1017
- */
1018
- GridStack.prototype.removeAll = function (removeDOM) {
1019
- var _this = this;
1020
- if (removeDOM === void 0) { removeDOM = true; }
1021
- // always remove our DOM data (circular link) before list gets emptied and drag&drop permanently
1022
- this.engine.nodes.forEach(function (n) {
1023
- delete n.el.gridstackNode;
1024
- _this._removeDD(n.el);
1025
- });
1026
- this.engine.removeAll(removeDOM);
1027
- this._triggerRemoveEvent();
1028
- return this;
1029
- };
1030
- /**
1031
- * Toggle the grid animation state. Toggles the `grid-stack-animate` class.
1032
- * @param doAnimate if true the grid will animate.
1033
- */
1034
- GridStack.prototype.setAnimation = function (doAnimate) {
1035
- if (doAnimate) {
1036
- this.el.classList.add('grid-stack-animate');
1037
- }
1038
- else {
1039
- this.el.classList.remove('grid-stack-animate');
1040
- }
1041
- return this;
1042
- };
1043
- /**
1044
- * Toggle the grid static state, which permanently removes/add Drag&Drop support, unlike disable()/enable() that just turns it off/on.
1045
- * Also toggle the grid-stack-static class.
1046
- * @param val if true the grid become static.
1047
- * @param updateClass true (default) if css class gets updated
1048
- * @param recurse true (default) if sub-grids also get updated
1049
- */
1050
- GridStack.prototype.setStatic = function (val, updateClass, recurse) {
1051
- var _this = this;
1052
- if (updateClass === void 0) { updateClass = true; }
1053
- if (recurse === void 0) { recurse = true; }
1054
- if (this.opts.staticGrid === val)
1055
- return this;
1056
- this.opts.staticGrid = val;
1057
- this._setupRemoveDrop();
1058
- this._setupAcceptWidget();
1059
- this.engine.nodes.forEach(function (n) {
1060
- _this._prepareDragDropByNode(n); // either delete or init Drag&drop
1061
- if (n.subGrid && recurse)
1062
- n.subGrid.setStatic(val, updateClass, recurse);
1063
- });
1064
- if (updateClass) {
1065
- this._setStaticClass();
1066
- }
1067
- return this;
1068
- };
1069
- /**
1070
- * Updates widget position/size and other info. Note: if you need to call this on all nodes, use load() instead which will update what changed.
1071
- * @param els widget or selector of objects to modify (note: setting the same x,y for multiple items will be indeterministic and likely unwanted)
1072
- * @param opt new widget options (x,y,w,h, etc..). Only those set will be updated.
1073
- */
1074
- GridStack.prototype.update = function (els, opt) {
1075
- var _this = this;
1076
- // support legacy call for now ?
1077
- if (arguments.length > 2) {
1078
- console.warn('gridstack.ts: `update(el, x, y, w, h)` is deprecated. Use `update(el, {x, w, content, ...})`. It will be removed soon');
1079
- // eslint-disable-next-line prefer-rest-params
1080
- var a = arguments, i = 1;
1081
- opt = { x: a[i++], y: a[i++], w: a[i++], h: a[i++] };
1082
- return this.update(els, opt);
1083
- }
1084
- GridStack.getElements(els).forEach(function (el) {
1085
- if (!el || !el.gridstackNode)
1086
- return;
1087
- var n = el.gridstackNode;
1088
- var w = utils_1.Utils.cloneDeep(opt); // make a copy we can modify in case they re-use it or multiple items
1089
- delete w.autoPosition;
1090
- // move/resize widget if anything changed
1091
- var keys = ['x', 'y', 'w', 'h'];
1092
- var m;
1093
- if (keys.some(function (k) { return w[k] !== undefined && w[k] !== n[k]; })) {
1094
- m = {};
1095
- keys.forEach(function (k) {
1096
- m[k] = (w[k] !== undefined) ? w[k] : n[k];
1097
- delete w[k];
1098
- });
1099
- }
1100
- // for a move as well IFF there is any min/max fields set
1101
- if (!m && (w.minW || w.minH || w.maxW || w.maxH)) {
1102
- m = {}; // will use node position but validate values
1103
- }
1104
- // check for content changing
1105
- if (w.content) {
1106
- var sub = el.querySelector('.grid-stack-item-content');
1107
- if (sub && sub.innerHTML !== w.content) {
1108
- sub.innerHTML = w.content;
1109
- }
1110
- delete w.content;
1111
- }
1112
- // any remaining fields are assigned, but check for dragging changes, resize constrain
1113
- var changed = false;
1114
- var ddChanged = false;
1115
- for (var key in w) {
1116
- if (key[0] !== '_' && n[key] !== w[key]) {
1117
- n[key] = w[key];
1118
- changed = true;
1119
- ddChanged = ddChanged || (!_this.opts.staticGrid && (key === 'noResize' || key === 'noMove' || key === 'locked'));
1120
- }
1121
- }
1122
- // finally move the widget
1123
- if (m) {
1124
- _this.engine.cleanNodes()
1125
- .beginUpdate(n)
1126
- .moveNode(n, m);
1127
- _this._updateContainerHeight();
1128
- _this._triggerChangeEvent();
1129
- _this.engine.endUpdate();
1130
- }
1131
- if (changed) { // move will only update x,y,w,h so update the rest too
1132
- _this._writeAttr(el, n);
1133
- }
1134
- if (ddChanged) {
1135
- _this._prepareDragDropByNode(n);
1136
- }
1137
- });
1138
- return this;
1139
- };
1140
- /**
1141
- * Updates the margins which will set all 4 sides at once - see `GridStackOptions.margin` for format options (CSS string format of 1,2,4 values or single number).
1142
- * @param value margin value
1143
- */
1144
- GridStack.prototype.margin = function (value) {
1145
- var isMultiValue = (typeof value === 'string' && value.split(' ').length > 1);
1146
- // check if we can skip re-creating our CSS file... won't check if multi values (too much hassle)
1147
- if (!isMultiValue) {
1148
- var data = utils_1.Utils.parseHeight(value);
1149
- if (this.opts.marginUnit === data.unit && this.opts.margin === data.h)
1150
- return;
1151
- }
1152
- // re-use existing margin handling
1153
- this.opts.margin = value;
1154
- this.opts.marginTop = this.opts.marginBottom = this.opts.marginLeft = this.opts.marginRight = undefined;
1155
- this._initMargin();
1156
- this._updateStyles(true); // true = force re-create
1157
- return this;
1158
- };
1159
- /** returns current margin number value (undefined if 4 sides don't match) */
1160
- GridStack.prototype.getMargin = function () { return this.opts.margin; };
1161
- /**
1162
- * Returns true if the height of the grid will be less than the vertical
1163
- * constraint. Always returns true if grid doesn't have height constraint.
1164
- * @param node contains x,y,w,h,auto-position options
1165
- *
1166
- * @example
1167
- * if (grid.willItFit(newWidget)) {
1168
- * grid.addWidget(newWidget);
1169
- * } else {
1170
- * alert('Not enough free space to place the widget');
1171
- * }
1172
- */
1173
- GridStack.prototype.willItFit = function (node) {
1174
- // support legacy call for now
1175
- if (arguments.length > 1) {
1176
- console.warn('gridstack.ts: `willItFit(x,y,w,h,autoPosition)` is deprecated. Use `willItFit({x, y,...})`. It will be removed soon');
1177
- // eslint-disable-next-line prefer-rest-params
1178
- var a = arguments, i = 0, w = { x: a[i++], y: a[i++], w: a[i++], h: a[i++], autoPosition: a[i++] };
1179
- return this.willItFit(w);
1180
- }
1181
- return this.engine.willItFit(node);
1182
- };
1183
- /** @internal */
1184
- GridStack.prototype._triggerChangeEvent = function () {
1185
- if (this.engine.batchMode)
1186
- return this;
1187
- var elements = this.engine.getDirtyNodes(true); // verify they really changed
1188
- if (elements && elements.length) {
1189
- if (!this._ignoreLayoutsNodeChange) {
1190
- this.engine.layoutsNodesChange(elements);
1191
- }
1192
- this._triggerEvent('change', elements);
1193
- }
1194
- this.engine.saveInitial(); // we called, now reset initial values & dirty flags
1195
- return this;
1196
- };
1197
- /** @internal */
1198
- GridStack.prototype._triggerAddEvent = function () {
1199
- if (this.engine.batchMode)
1200
- return this;
1201
- if (this.engine.addedNodes && this.engine.addedNodes.length > 0) {
1202
- if (!this._ignoreLayoutsNodeChange) {
1203
- this.engine.layoutsNodesChange(this.engine.addedNodes);
1204
- }
1205
- // prevent added nodes from also triggering 'change' event (which is called next)
1206
- this.engine.addedNodes.forEach(function (n) { delete n._dirty; });
1207
- this._triggerEvent('added', this.engine.addedNodes);
1208
- this.engine.addedNodes = [];
1209
- }
1210
- return this;
1211
- };
1212
- /** @internal */
1213
- GridStack.prototype._triggerRemoveEvent = function () {
1214
- if (this.engine.batchMode)
1215
- return this;
1216
- if (this.engine.removedNodes && this.engine.removedNodes.length > 0) {
1217
- this._triggerEvent('removed', this.engine.removedNodes);
1218
- this.engine.removedNodes = [];
1219
- }
1220
- return this;
1221
- };
1222
- /** @internal */
1223
- GridStack.prototype._triggerEvent = function (type, data) {
1224
- var event = data ? new CustomEvent(type, { bubbles: false, detail: data }) : new Event(type);
1225
- this.el.dispatchEvent(event);
1226
- return this;
1227
- };
1228
- /** @internal called to delete the current dynamic style sheet used for our layout */
1229
- GridStack.prototype._removeStylesheet = function () {
1230
- if (this._styles) {
1231
- utils_1.Utils.removeStylesheet(this._styleSheetClass);
1232
- delete this._styles;
1233
- }
1234
- return this;
1235
- };
1236
- /** @internal updated/create the CSS styles for row based layout and initial margin setting */
1237
- GridStack.prototype._updateStyles = function (forceUpdate, maxH) {
1238
- if (forceUpdate === void 0) { forceUpdate = false; }
1239
- // call to delete existing one if we change cellHeight / margin
1240
- if (forceUpdate) {
1241
- this._removeStylesheet();
1242
- }
1243
- if (!maxH)
1244
- maxH = this.getRow();
1245
- this._updateContainerHeight();
1246
- // if user is telling us they will handle the CSS themselves by setting heights to 0. Do we need this opts really ??
1247
- if (this.opts.cellHeight === 0) {
1248
- return this;
1249
- }
1250
- var cellHeight = this.opts.cellHeight;
1251
- var cellHeightUnit = this.opts.cellHeightUnit;
1252
- var prefix = "." + this._styleSheetClass + " > ." + this.opts.itemClass;
1253
- // create one as needed
1254
- if (!this._styles) {
1255
- // insert style to parent (instead of 'head' by default) to support WebComponent
1256
- var styleLocation = this.opts.styleInHead ? undefined : this.el.parentNode;
1257
- this._styles = utils_1.Utils.createStylesheet(this._styleSheetClass, styleLocation);
1258
- if (!this._styles)
1259
- return this;
1260
- this._styles._max = 0;
1261
- // these are done once only
1262
- utils_1.Utils.addCSSRule(this._styles, prefix, "min-height: " + cellHeight + cellHeightUnit);
1263
- // content margins
1264
- var top_1 = this.opts.marginTop + this.opts.marginUnit;
1265
- var bottom = this.opts.marginBottom + this.opts.marginUnit;
1266
- var right = this.opts.marginRight + this.opts.marginUnit;
1267
- var left = this.opts.marginLeft + this.opts.marginUnit;
1268
- var content = prefix + " > .grid-stack-item-content";
1269
- var placeholder = "." + this._styleSheetClass + " > .grid-stack-placeholder > .placeholder-content";
1270
- utils_1.Utils.addCSSRule(this._styles, content, "top: " + top_1 + "; right: " + right + "; bottom: " + bottom + "; left: " + left + ";");
1271
- utils_1.Utils.addCSSRule(this._styles, placeholder, "top: " + top_1 + "; right: " + right + "; bottom: " + bottom + "; left: " + left + ";");
1272
- // resize handles offset (to match margin)
1273
- utils_1.Utils.addCSSRule(this._styles, prefix + " > .ui-resizable-ne", "right: " + right);
1274
- utils_1.Utils.addCSSRule(this._styles, prefix + " > .ui-resizable-e", "right: " + right);
1275
- utils_1.Utils.addCSSRule(this._styles, prefix + " > .ui-resizable-se", "right: " + right + "; bottom: " + bottom);
1276
- utils_1.Utils.addCSSRule(this._styles, prefix + " > .ui-resizable-nw", "left: " + left);
1277
- utils_1.Utils.addCSSRule(this._styles, prefix + " > .ui-resizable-w", "left: " + left);
1278
- utils_1.Utils.addCSSRule(this._styles, prefix + " > .ui-resizable-sw", "left: " + left + "; bottom: " + bottom);
1279
- }
1280
- // now update the height specific fields
1281
- maxH = maxH || this._styles._max;
1282
- if (maxH > this._styles._max) {
1283
- var getHeight = function (rows) { return (cellHeight * rows) + cellHeightUnit; };
1284
- for (var i = this._styles._max + 1; i <= maxH; i++) { // start at 1
1285
- var h = getHeight(i);
1286
- utils_1.Utils.addCSSRule(this._styles, prefix + "[gs-y=\"" + (i - 1) + "\"]", "top: " + getHeight(i - 1)); // start at 0
1287
- utils_1.Utils.addCSSRule(this._styles, prefix + "[gs-h=\"" + i + "\"]", "height: " + h);
1288
- utils_1.Utils.addCSSRule(this._styles, prefix + "[gs-min-h=\"" + i + "\"]", "min-height: " + h);
1289
- utils_1.Utils.addCSSRule(this._styles, prefix + "[gs-max-h=\"" + i + "\"]", "max-height: " + h);
1290
- }
1291
- this._styles._max = maxH;
1292
- }
1293
- return this;
1294
- };
1295
- /** @internal */
1296
- GridStack.prototype._updateContainerHeight = function () {
1297
- if (!this.engine || this.engine.batchMode)
1298
- return this;
1299
- var row = this.getRow() + this._extraDragRow; // checks for minRow already
1300
- // check for css min height
1301
- // Note: we don't handle %,rem correctly so comment out, beside we don't need need to create un-necessary
1302
- // rows as the CSS will make us bigger than our set height if needed... not sure why we had this.
1303
- // let cssMinHeight = parseInt(getComputedStyle(this.el)['min-height']);
1304
- // if (cssMinHeight > 0) {
1305
- // let minRow = Math.round(cssMinHeight / this.getCellHeight(true));
1306
- // if (row < minRow) {
1307
- // row = minRow;
1308
- // }
1309
- // }
1310
- this.el.setAttribute('gs-current-row', String(row));
1311
- if (row === 0) {
1312
- this.el.style.removeProperty('min-height');
1313
- return this;
1314
- }
1315
- var cellHeight = this.opts.cellHeight;
1316
- var unit = this.opts.cellHeightUnit;
1317
- if (!cellHeight)
1318
- return this;
1319
- this.el.style.minHeight = row * cellHeight + unit;
1320
- return this;
1321
- };
1322
- /** @internal */
1323
- GridStack.prototype._prepareElement = function (el, triggerAddEvent, node) {
1324
- if (triggerAddEvent === void 0) { triggerAddEvent = false; }
1325
- el.classList.add(this.opts.itemClass);
1326
- node = node || this._readAttr(el);
1327
- el.gridstackNode = node;
1328
- node.el = el;
1329
- node.grid = this;
1330
- var copy = __assign({}, node);
1331
- node = this.engine.addNode(node, triggerAddEvent);
1332
- // write node attr back in case there was collision or we have to fix bad values during addNode()
1333
- if (!utils_1.Utils.same(node, copy)) {
1334
- this._writeAttr(el, node);
1335
- }
1336
- this._prepareDragDropByNode(node);
1337
- return this;
1338
- };
1339
- /** @internal call to write position x,y,w,h attributes back to element */
1340
- GridStack.prototype._writePosAttr = function (el, n) {
1341
- if (n.x !== undefined && n.x !== null) {
1342
- el.setAttribute('gs-x', String(n.x));
1343
- }
1344
- if (n.y !== undefined && n.y !== null) {
1345
- el.setAttribute('gs-y', String(n.y));
1346
- }
1347
- if (n.w) {
1348
- el.setAttribute('gs-w', String(n.w));
1349
- }
1350
- if (n.h) {
1351
- el.setAttribute('gs-h', String(n.h));
1352
- }
1353
- return this;
1354
- };
1355
- /** @internal call to write any default attributes back to element */
1356
- GridStack.prototype._writeAttr = function (el, node) {
1357
- if (!node)
1358
- return this;
1359
- this._writePosAttr(el, node);
1360
- var attrs /*: GridStackWidget but strings */ = {
1361
- autoPosition: 'gs-auto-position',
1362
- minW: 'gs-min-w',
1363
- minH: 'gs-min-h',
1364
- maxW: 'gs-max-w',
1365
- maxH: 'gs-max-h',
1366
- noResize: 'gs-no-resize',
1367
- noMove: 'gs-no-move',
1368
- locked: 'gs-locked',
1369
- id: 'gs-id',
1370
- };
1371
- for (var key in attrs) {
1372
- if (node[key]) { // 0 is valid for x,y only but done above already and not in list anyway
1373
- el.setAttribute(attrs[key], String(node[key]));
1374
- }
1375
- else {
1376
- el.removeAttribute(attrs[key]);
1377
- }
1378
- }
1379
- return this;
1380
- };
1381
- /** @internal call to read any default attributes from element */
1382
- GridStack.prototype._readAttr = function (el) {
1383
- var node = {};
1384
- node.x = utils_1.Utils.toNumber(el.getAttribute('gs-x'));
1385
- node.y = utils_1.Utils.toNumber(el.getAttribute('gs-y'));
1386
- node.w = utils_1.Utils.toNumber(el.getAttribute('gs-w'));
1387
- node.h = utils_1.Utils.toNumber(el.getAttribute('gs-h'));
1388
- node.maxW = utils_1.Utils.toNumber(el.getAttribute('gs-max-w'));
1389
- node.minW = utils_1.Utils.toNumber(el.getAttribute('gs-min-w'));
1390
- node.maxH = utils_1.Utils.toNumber(el.getAttribute('gs-max-h'));
1391
- node.minH = utils_1.Utils.toNumber(el.getAttribute('gs-min-h'));
1392
- node.autoPosition = utils_1.Utils.toBool(el.getAttribute('gs-auto-position'));
1393
- node.noResize = utils_1.Utils.toBool(el.getAttribute('gs-no-resize'));
1394
- node.noMove = utils_1.Utils.toBool(el.getAttribute('gs-no-move'));
1395
- node.locked = utils_1.Utils.toBool(el.getAttribute('gs-locked'));
1396
- node.id = el.getAttribute('gs-id');
1397
- // remove any key not found (null or false which is default)
1398
- for (var key in node) {
1399
- if (!node.hasOwnProperty(key))
1400
- return;
1401
- if (!node[key] && node[key] !== 0) { // 0 can be valid value (x,y only really)
1402
- delete node[key];
1403
- }
1404
- }
1405
- return node;
1406
- };
1407
- /** @internal */
1408
- GridStack.prototype._setStaticClass = function () {
1409
- var _a, _b;
1410
- var classes = ['grid-stack-static'];
1411
- if (this.opts.staticGrid) {
1412
- (_a = this.el.classList).add.apply(_a, classes);
1413
- this.el.setAttribute('gs-static', 'true');
1414
- }
1415
- else {
1416
- (_b = this.el.classList).remove.apply(_b, classes);
1417
- this.el.removeAttribute('gs-static');
1418
- }
1419
- return this;
1420
- };
1421
- /**
1422
- * called when we are being resized by the window - check if the one Column Mode needs to be turned on/off
1423
- * and remember the prev columns we used, or get our count from parent, as well as check for auto cell height (square)
1424
- */
1425
- GridStack.prototype.onParentResize = function () {
1426
- var _this = this;
1427
- if (!this.el || !this.el.clientWidth)
1428
- return; // return if we're gone or no size yet (will get called again)
1429
- var changedColumn = false;
1430
- // see if we're nested and take our column count from our parent....
1431
- if (this._autoColumn && this.parentGridItem) {
1432
- if (this.opts.column !== this.parentGridItem.w) {
1433
- changedColumn = true;
1434
- this.column(this.parentGridItem.w, 'none');
1435
- }
1436
- }
1437
- else {
1438
- // else check for 1 column in/out behavior
1439
- var oneColumn = !this.opts.disableOneColumnMode && this.el.clientWidth <= this.opts.oneColumnSize;
1440
- if ((this.opts.column === 1) !== oneColumn) {
1441
- changedColumn = true;
1442
- if (this.opts.animate) {
1443
- this.setAnimation(false);
1444
- } // 1 <-> 12 is too radical, turn off animation
1445
- this.column(oneColumn ? 1 : this._prevColumn);
1446
- if (this.opts.animate) {
1447
- this.setAnimation(true);
1448
- }
1449
- }
1450
- }
1451
- // make the cells content square again
1452
- if (this._isAutoCellHeight) {
1453
- if (!changedColumn && this.opts.cellHeightThrottle) {
1454
- if (!this._cellHeightThrottle) {
1455
- this._cellHeightThrottle = utils_1.Utils.throttle(function () { return _this.cellHeight(); }, this.opts.cellHeightThrottle);
1456
- }
1457
- this._cellHeightThrottle();
1458
- }
1459
- else {
1460
- // immediate update if we've changed column count or have no threshold
1461
- this.cellHeight();
1462
- }
1463
- }
1464
- // finally update any nested grids
1465
- this.engine.nodes.forEach(function (n) {
1466
- if (n.subGrid) {
1467
- n.subGrid.onParentResize();
1468
- }
1469
- });
1470
- return this;
1471
- };
1472
- /** add or remove the window size event handler */
1473
- GridStack.prototype._updateWindowResizeEvent = function (forceRemove) {
1474
- if (forceRemove === void 0) { forceRemove = false; }
1475
- // only add event if we're not nested (parent will call us) and we're auto sizing cells or supporting oneColumn (i.e. doing work)
1476
- var workTodo = (this._isAutoCellHeight || !this.opts.disableOneColumnMode) && !this.parentGridItem;
1477
- if (!forceRemove && workTodo && !this._windowResizeBind) {
1478
- this._windowResizeBind = this.onParentResize.bind(this); // so we can properly remove later
1479
- window.addEventListener('resize', this._windowResizeBind);
1480
- }
1481
- else if ((forceRemove || !workTodo) && this._windowResizeBind) {
1482
- window.removeEventListener('resize', this._windowResizeBind);
1483
- delete this._windowResizeBind; // remove link to us so we can free
1484
- }
1485
- return this;
1486
- };
1487
- /** @internal convert a potential selector into actual element */
1488
- GridStack.getElement = function (els) {
1489
- if (els === void 0) { els = '.grid-stack-item'; }
1490
- return utils_1.Utils.getElement(els);
1491
- };
1492
- /** @internal */
1493
- GridStack.getElements = function (els) {
1494
- if (els === void 0) { els = '.grid-stack-item'; }
1495
- return utils_1.Utils.getElements(els);
1496
- };
1497
- /** @internal */
1498
- GridStack.getGridElement = function (els) { return GridStack.getElement(els); };
1499
- /** @internal */
1500
- GridStack.getGridElements = function (els) { return utils_1.Utils.getElements(els); };
1501
- /** @internal initialize margin top/bottom/left/right and units */
1502
- GridStack.prototype._initMargin = function () {
1503
- var data;
1504
- var margin = 0;
1505
- // support passing multiple values like CSS (ex: '5px 10px 0 20px')
1506
- var margins = [];
1507
- if (typeof this.opts.margin === 'string') {
1508
- margins = this.opts.margin.split(' ');
1509
- }
1510
- if (margins.length === 2) { // top/bot, left/right like CSS
1511
- this.opts.marginTop = this.opts.marginBottom = margins[0];
1512
- this.opts.marginLeft = this.opts.marginRight = margins[1];
1513
- }
1514
- else if (margins.length === 4) { // Clockwise like CSS
1515
- this.opts.marginTop = margins[0];
1516
- this.opts.marginRight = margins[1];
1517
- this.opts.marginBottom = margins[2];
1518
- this.opts.marginLeft = margins[3];
1519
- }
1520
- else {
1521
- data = utils_1.Utils.parseHeight(this.opts.margin);
1522
- this.opts.marginUnit = data.unit;
1523
- margin = this.opts.margin = data.h;
1524
- }
1525
- // see if top/bottom/left/right need to be set as well
1526
- if (this.opts.marginTop === undefined) {
1527
- this.opts.marginTop = margin;
1528
- }
1529
- else {
1530
- data = utils_1.Utils.parseHeight(this.opts.marginTop);
1531
- this.opts.marginTop = data.h;
1532
- delete this.opts.margin;
1533
- }
1534
- if (this.opts.marginBottom === undefined) {
1535
- this.opts.marginBottom = margin;
1536
- }
1537
- else {
1538
- data = utils_1.Utils.parseHeight(this.opts.marginBottom);
1539
- this.opts.marginBottom = data.h;
1540
- delete this.opts.margin;
1541
- }
1542
- if (this.opts.marginRight === undefined) {
1543
- this.opts.marginRight = margin;
1544
- }
1545
- else {
1546
- data = utils_1.Utils.parseHeight(this.opts.marginRight);
1547
- this.opts.marginRight = data.h;
1548
- delete this.opts.margin;
1549
- }
1550
- if (this.opts.marginLeft === undefined) {
1551
- this.opts.marginLeft = margin;
1552
- }
1553
- else {
1554
- data = utils_1.Utils.parseHeight(this.opts.marginLeft);
1555
- this.opts.marginLeft = data.h;
1556
- delete this.opts.margin;
1557
- }
1558
- this.opts.marginUnit = data.unit; // in case side were spelled out, use those units instead...
1559
- if (this.opts.marginTop === this.opts.marginBottom && this.opts.marginLeft === this.opts.marginRight && this.opts.marginTop === this.opts.marginRight) {
1560
- this.opts.margin = this.opts.marginTop; // makes it easier to check for no-ops in setMargin()
1561
- }
1562
- return this;
1563
- };
1564
- /* ===========================================================================================
1565
- * drag&drop methods that used to be stubbed out and implemented in dd-gridstack.ts
1566
- * but caused loading issues in prod - see https://github.com/gridstack/gridstack.js/issues/2039
1567
- * ===========================================================================================
1568
- */
1569
- /** get the global (but static to this code) DD implementation */
1570
- GridStack.getDD = function () {
1571
- return dd;
1572
- };
1573
- /**
1574
- * call to setup dragging in from the outside (say toolbar), by specifying the class selection and options.
1575
- * Called during GridStack.init() as options, but can also be called directly (last param are used) in case the toolbar
1576
- * is dynamically create and needs to be set later.
1577
- * @param dragIn string selector (ex: '.sidebar .grid-stack-item')
1578
- * @param dragInOptions options - see DDDragInOpt. (default: {handle: '.grid-stack-item-content', appendTo: 'body'}
1579
- **/
1580
- GridStack.setupDragIn = function (dragIn, dragInOptions) {
1581
- if ((dragInOptions === null || dragInOptions === void 0 ? void 0 : dragInOptions.pause) !== undefined) {
1582
- dd_manager_1.DDManager.pauseDrag = dragInOptions.pause;
1583
- }
1584
- if (typeof dragIn === 'string') {
1585
- dragInOptions = __assign(__assign({}, types_1.dragInDefaultOptions), (dragInOptions || {}));
1586
- utils_1.Utils.getElements(dragIn).forEach(function (el) {
1587
- if (!dd.isDraggable(el))
1588
- dd.dragIn(el, dragInOptions);
1589
- });
1590
- }
1591
- };
1592
- /**
1593
- * Enables/Disables dragging by the user of specific grid element. If you want all items, and have it affect future items, use enableMove() instead. No-op for static grids.
1594
- * IF you are looking to prevent an item from moving (due to being pushed around by another during collision) use locked property instead.
1595
- * @param els widget or selector to modify.
1596
- * @param val if true widget will be draggable.
1597
- */
1598
- GridStack.prototype.movable = function (els, val) {
1599
- var _this = this;
1600
- if (this.opts.staticGrid)
1601
- return this; // can't move a static grid!
1602
- GridStack.getElements(els).forEach(function (el) {
1603
- var node = el.gridstackNode;
1604
- if (!node)
1605
- return;
1606
- if (val)
1607
- delete node.noMove;
1608
- else
1609
- node.noMove = true;
1610
- _this._prepareDragDropByNode(node); // init DD if need be, and adjust
1611
- });
1612
- return this;
1613
- };
1614
- /**
1615
- * Enables/Disables user resizing of specific grid element. If you want all items, and have it affect future items, use enableResize() instead. No-op for static grids.
1616
- * @param els widget or selector to modify
1617
- * @param val if true widget will be resizable.
1618
- */
1619
- GridStack.prototype.resizable = function (els, val) {
1620
- var _this = this;
1621
- if (this.opts.staticGrid)
1622
- return this; // can't resize a static grid!
1623
- GridStack.getElements(els).forEach(function (el) {
1624
- var node = el.gridstackNode;
1625
- if (!node)
1626
- return;
1627
- if (val)
1628
- delete node.noResize;
1629
- else
1630
- node.noResize = true;
1631
- _this._prepareDragDropByNode(node); // init DD if need be, and adjust
1632
- });
1633
- return this;
1634
- };
1635
- /**
1636
- * Temporarily disables widgets moving/resizing.
1637
- * If you want a more permanent way (which freezes up resources) use `setStatic(true)` instead.
1638
- * Note: no-op for static grid
1639
- * This is a shortcut for:
1640
- * @example
1641
- * grid.enableMove(false);
1642
- * grid.enableResize(false);
1643
- * @param recurse true (default) if sub-grids also get updated
1644
- */
1645
- GridStack.prototype.disable = function (recurse) {
1646
- if (recurse === void 0) { recurse = true; }
1647
- if (this.opts.staticGrid)
1648
- return;
1649
- this.enableMove(false, recurse);
1650
- this.enableResize(false, recurse); // @ts-ignore
1651
- this._triggerEvent('disable');
1652
- return this;
1653
- };
1654
- /**
1655
- * Re-enables widgets moving/resizing - see disable().
1656
- * Note: no-op for static grid.
1657
- * This is a shortcut for:
1658
- * @example
1659
- * grid.enableMove(true);
1660
- * grid.enableResize(true);
1661
- * @param recurse true (default) if sub-grids also get updated
1662
- */
1663
- GridStack.prototype.enable = function (recurse) {
1664
- if (recurse === void 0) { recurse = true; }
1665
- if (this.opts.staticGrid)
1666
- return;
1667
- this.enableMove(true, recurse);
1668
- this.enableResize(true, recurse); // @ts-ignore
1669
- this._triggerEvent('enable');
1670
- return this;
1671
- };
1672
- /**
1673
- * Enables/disables widget moving. No-op for static grids.
1674
- * @param recurse true (default) if sub-grids also get updated
1675
- */
1676
- GridStack.prototype.enableMove = function (doEnable, recurse) {
1677
- var _this = this;
1678
- if (recurse === void 0) { recurse = true; }
1679
- if (this.opts.staticGrid)
1680
- return this; // can't move a static grid!
1681
- this.opts.disableDrag = !doEnable; // FIRST before we update children as grid overrides #1658
1682
- this.engine.nodes.forEach(function (n) {
1683
- _this.movable(n.el, doEnable);
1684
- if (n.subGrid && recurse)
1685
- n.subGrid.enableMove(doEnable, recurse);
1686
- });
1687
- return this;
1688
- };
1689
- /**
1690
- * Enables/disables widget resizing. No-op for static grids.
1691
- * @param recurse true (default) if sub-grids also get updated
1692
- */
1693
- GridStack.prototype.enableResize = function (doEnable, recurse) {
1694
- var _this = this;
1695
- if (recurse === void 0) { recurse = true; }
1696
- if (this.opts.staticGrid)
1697
- return this; // can't size a static grid!
1698
- this.opts.disableResize = !doEnable; // FIRST before we update children as grid overrides #1658
1699
- this.engine.nodes.forEach(function (n) {
1700
- _this.resizable(n.el, doEnable);
1701
- if (n.subGrid && recurse)
1702
- n.subGrid.enableResize(doEnable, recurse);
1703
- });
1704
- return this;
1705
- };
1706
- /** @internal removes any drag&drop present (called during destroy) */
1707
- GridStack.prototype._removeDD = function (el) {
1708
- dd.draggable(el, 'destroy').resizable(el, 'destroy');
1709
- if (el.gridstackNode) {
1710
- delete el.gridstackNode._initDD; // reset our DD init flag
1711
- }
1712
- delete el.ddElement;
1713
- return this;
1714
- };
1715
- /** @internal called to add drag over to support widgets being added externally */
1716
- GridStack.prototype._setupAcceptWidget = function () {
1717
- var _this = this;
1718
- // check if we need to disable things
1719
- if (this.opts.staticGrid || (!this.opts.acceptWidgets && !this.opts.removable)) {
1720
- dd.droppable(this.el, 'destroy');
1721
- return this;
1722
- }
1723
- // vars shared across all methods
1724
- var cellHeight, cellWidth;
1725
- var onDrag = function (event, el, helper) {
1726
- var node = el.gridstackNode;
1727
- if (!node)
1728
- return;
1729
- helper = helper || el;
1730
- var parent = _this.el.getBoundingClientRect();
1731
- var _a = helper.getBoundingClientRect(), top = _a.top, left = _a.left;
1732
- left -= parent.left;
1733
- top -= parent.top;
1734
- var ui = { position: { top: top, left: left } };
1735
- if (node._temporaryRemoved) {
1736
- node.x = Math.max(0, Math.round(left / cellWidth));
1737
- node.y = Math.max(0, Math.round(top / cellHeight));
1738
- delete node.autoPosition;
1739
- _this.engine.nodeBoundFix(node);
1740
- // don't accept *initial* location if doesn't fit #1419 (locked drop region, or can't grow), but maybe try if it will go somewhere
1741
- if (!_this.engine.willItFit(node)) {
1742
- node.autoPosition = true; // ignore x,y and try for any slot...
1743
- if (!_this.engine.willItFit(node)) {
1744
- dd.off(el, 'drag'); // stop calling us
1745
- return; // full grid or can't grow
1746
- }
1747
- if (node._willFitPos) {
1748
- // use the auto position instead #1687
1749
- utils_1.Utils.copyPos(node, node._willFitPos);
1750
- delete node._willFitPos;
1751
- }
1752
- }
1753
- // re-use the existing node dragging method
1754
- _this._onStartMoving(helper, event, ui, node, cellWidth, cellHeight);
1755
- }
1756
- else {
1757
- // re-use the existing node dragging that does so much of the collision detection
1758
- _this._dragOrResize(helper, event, ui, node, cellWidth, cellHeight);
1759
- }
1760
- };
1761
- dd.droppable(this.el, {
1762
- accept: function (el) {
1763
- var node = el.gridstackNode;
1764
- // set accept drop to true on ourself (which we ignore) so we don't get "can't drop" icon in HTML5 mode while moving
1765
- if ((node === null || node === void 0 ? void 0 : node.grid) === _this)
1766
- return true;
1767
- if (!_this.opts.acceptWidgets)
1768
- return false;
1769
- // check for accept method or class matching
1770
- var canAccept = true;
1771
- if (typeof _this.opts.acceptWidgets === 'function') {
1772
- canAccept = _this.opts.acceptWidgets(el);
1773
- }
1774
- else {
1775
- var selector = (_this.opts.acceptWidgets === true ? '.grid-stack-item' : _this.opts.acceptWidgets);
1776
- canAccept = el.matches(selector);
1777
- }
1778
- // finally check to make sure we actually have space left #1571
1779
- if (canAccept && node && _this.opts.maxRow) {
1780
- var n = { w: node.w, h: node.h, minW: node.minW, minH: node.minH }; // only width/height matters and autoPosition
1781
- canAccept = _this.engine.willItFit(n);
1782
- }
1783
- return canAccept;
1784
- }
1785
- })
1786
- /**
1787
- * entering our grid area
1788
- */
1789
- .on(this.el, 'dropover', function (event, el, helper) {
1790
- // console.log(`over ${this.el.gridstack.opts.id} ${count++}`); // TEST
1791
- var node = el.gridstackNode;
1792
- // ignore drop enter on ourself (unless we temporarily removed) which happens on a simple drag of our item
1793
- if ((node === null || node === void 0 ? void 0 : node.grid) === _this && !node._temporaryRemoved) {
1794
- // delete node._added; // reset this to track placeholder again in case we were over other grid #1484 (dropout doesn't always clear)
1795
- return false; // prevent parent from receiving msg (which may be a grid as well)
1796
- }
1797
- // fix #1578 when dragging fast, we may not get a leave on the previous grid so force one now
1798
- if ((node === null || node === void 0 ? void 0 : node.grid) && node.grid !== _this && !node._temporaryRemoved) {
1799
- // console.log('dropover without leave'); // TEST
1800
- var otherGrid = node.grid;
1801
- otherGrid._leave(el, helper);
1802
- }
1803
- // cache cell dimensions (which don't change), position can animate if we removed an item in otherGrid that affects us...
1804
- cellWidth = _this.cellWidth();
1805
- cellHeight = _this.getCellHeight(true);
1806
- // load any element attributes if we don't have a node
1807
- if (!node) { // @ts-ignore private read only on ourself
1808
- node = _this._readAttr(el);
1809
- }
1810
- if (!node.grid) {
1811
- node._isExternal = true;
1812
- el.gridstackNode = node;
1813
- }
1814
- // calculate the grid size based on element outer size
1815
- helper = helper || el;
1816
- var w = node.w || Math.round(helper.offsetWidth / cellWidth) || 1;
1817
- var h = node.h || Math.round(helper.offsetHeight / cellHeight) || 1;
1818
- // if the item came from another grid, make a copy and save the original info in case we go back there
1819
- if (node.grid && node.grid !== _this) {
1820
- // copy the node original values (min/max/id/etc...) but override width/height/other flags which are this grid specific
1821
- // console.log('dropover cloning node'); // TEST
1822
- if (!el._gridstackNodeOrig)
1823
- el._gridstackNodeOrig = node; // shouldn't have multiple nested!
1824
- el.gridstackNode = node = __assign(__assign({}, node), { w: w, h: h, grid: _this });
1825
- _this.engine.cleanupNode(node)
1826
- .nodeBoundFix(node);
1827
- // restore some internal fields we need after clearing them all
1828
- node._initDD =
1829
- node._isExternal = // DOM needs to be re-parented on a drop
1830
- node._temporaryRemoved = true; // so it can be inserted onDrag below
1831
- }
1832
- else {
1833
- node.w = w;
1834
- node.h = h;
1835
- node._temporaryRemoved = true; // so we can insert it
1836
- }
1837
- // clear any marked for complete removal (Note: don't check _isAboutToRemove as that is cleared above - just do it)
1838
- _this._itemRemoving(node.el, false);
1839
- dd.on(el, 'drag', onDrag);
1840
- // make sure this is called at least once when going fast #1578
1841
- onDrag(event, el, helper);
1842
- return false; // prevent parent from receiving msg (which may be a grid as well)
1843
- })
1844
- /**
1845
- * Leaving our grid area...
1846
- */
1847
- .on(this.el, 'dropout', function (event, el, helper) {
1848
- // console.log(`out ${this.el.gridstack.opts.id} ${count++}`); // TEST
1849
- var node = el.gridstackNode;
1850
- if (!node)
1851
- return false;
1852
- // fix #1578 when dragging fast, we might get leave after other grid gets enter (which calls us to clean)
1853
- // so skip this one if we're not the active grid really..
1854
- if (!node.grid || node.grid === _this) {
1855
- _this._leave(el, helper);
1856
- // if we were created as temporary nested grid, go back to before state
1857
- if (_this._isTemp) {
1858
- _this.removeAsSubGrid(node);
1859
- }
1860
- }
1861
- return false; // prevent parent from receiving msg (which may be grid as well)
1862
- })
1863
- /**
1864
- * end - releasing the mouse
1865
- */
1866
- .on(this.el, 'drop', function (event, el, helper) {
1867
- var _a, _b;
1868
- var node = el.gridstackNode;
1869
- // ignore drop on ourself from ourself that didn't come from the outside - dragend will handle the simple move instead
1870
- if ((node === null || node === void 0 ? void 0 : node.grid) === _this && !node._isExternal)
1871
- return false;
1872
- var wasAdded = !!_this.placeholder.parentElement; // skip items not actually added to us because of constrains, but do cleanup #1419
1873
- _this.placeholder.remove();
1874
- // notify previous grid of removal
1875
- // console.log('drop delete _gridstackNodeOrig') // TEST
1876
- var origNode = el._gridstackNodeOrig;
1877
- delete el._gridstackNodeOrig;
1878
- if (wasAdded && (origNode === null || origNode === void 0 ? void 0 : origNode.grid) && origNode.grid !== _this) {
1879
- var oGrid = origNode.grid;
1880
- oGrid.engine.removedNodes.push(origNode);
1881
- oGrid._triggerRemoveEvent()._triggerChangeEvent();
1882
- // if it's an empty sub-grid that got auto-created, nuke it
1883
- if (oGrid.parentGridItem && !oGrid.engine.nodes.length && oGrid.opts.subGridDynamic) {
1884
- oGrid.removeAsSubGrid();
1885
- }
1886
- }
1887
- if (!node)
1888
- return false;
1889
- // use existing placeholder node as it's already in our list with drop location
1890
- if (wasAdded) {
1891
- _this.engine.cleanupNode(node); // removes all internal _xyz values
1892
- node.grid = _this;
1893
- }
1894
- dd.off(el, 'drag');
1895
- // if we made a copy ('helper' which is temp) of the original node then insert a copy, else we move the original node (#1102)
1896
- // as the helper will be nuked by jquery-ui otherwise. TODO: update old code path
1897
- if (helper !== el) {
1898
- helper.remove();
1899
- el.gridstackNode = origNode; // original item (left behind) is re-stored to pre dragging as the node now has drop info
1900
- if (wasAdded) {
1901
- el = el.cloneNode(true);
1902
- }
1903
- }
1904
- else {
1905
- el.remove(); // reduce flicker as we change depth here, and size further down
1906
- _this._removeDD(el);
1907
- }
1908
- if (!wasAdded)
1909
- return false;
1910
- el.gridstackNode = node;
1911
- node.el = el;
1912
- var subGrid = (_b = (_a = node.subGrid) === null || _a === void 0 ? void 0 : _a.el) === null || _b === void 0 ? void 0 : _b.gridstack; // set when actual sub-grid present
1913
- // @ts-ignore
1914
- utils_1.Utils.copyPos(node, _this._readAttr(_this.placeholder)); // placeholder values as moving VERY fast can throw things off #1578
1915
- utils_1.Utils.removePositioningStyles(el); // @ts-ignore
1916
- _this._writeAttr(el, node);
1917
- el.classList.add(types_1.gridDefaults.itemClass, _this.opts.itemClass);
1918
- _this.el.appendChild(el); // @ts-ignore // TODO: now would be ideal time to _removeHelperStyle() overriding floating styles (native only)
1919
- if (subGrid) {
1920
- subGrid.parentGridItem = node;
1921
- if (!subGrid.opts.styleInHead)
1922
- subGrid._updateStyles(true); // re-create sub-grid styles now that we've moved
1923
- }
1924
- _this._updateContainerHeight();
1925
- _this.engine.addedNodes.push(node); // @ts-ignore
1926
- _this._triggerAddEvent(); // @ts-ignore
1927
- _this._triggerChangeEvent();
1928
- _this.engine.endUpdate();
1929
- if (_this._gsEventHandler['dropped']) {
1930
- _this._gsEventHandler['dropped'](__assign(__assign({}, event), { type: 'dropped' }), origNode && origNode.grid ? origNode : undefined, node);
1931
- }
1932
- // wait till we return out of the drag callback to set the new drag&resize handler or they may get messed up
1933
- window.setTimeout(function () {
1934
- // IFF we are still there (some application will use as placeholder and insert their real widget instead and better call makeWidget())
1935
- if (node.el && node.el.parentElement) {
1936
- _this._prepareDragDropByNode(node);
1937
- }
1938
- else {
1939
- _this.engine.removeNode(node);
1940
- }
1941
- delete node.grid._isTemp;
1942
- });
1943
- return false; // prevent parent from receiving msg (which may be grid as well)
1944
- });
1945
- return this;
1946
- };
1947
- /** @internal mark item for removal */
1948
- GridStack.prototype._itemRemoving = function (el, remove) {
1949
- var node = el ? el.gridstackNode : undefined;
1950
- if (!node || !node.grid)
1951
- return;
1952
- remove ? node._isAboutToRemove = true : delete node._isAboutToRemove;
1953
- remove ? el.classList.add('grid-stack-item-removing') : el.classList.remove('grid-stack-item-removing');
1954
- };
1955
- /** @internal called to setup a trash drop zone if the user specifies it */
1956
- GridStack.prototype._setupRemoveDrop = function () {
1957
- var _this = this;
1958
- if (!this.opts.staticGrid && typeof this.opts.removable === 'string') {
1959
- var trashEl = document.querySelector(this.opts.removable);
1960
- if (!trashEl)
1961
- return this;
1962
- // only register ONE drop-over/dropout callback for the 'trash', and it will
1963
- // update the passed in item and parent grid because the 'trash' is a shared resource anyway,
1964
- // and Native DD only has 1 event CB (having a list and technically a per grid removableOptions complicates things greatly)
1965
- if (!dd.isDroppable(trashEl)) {
1966
- dd.droppable(trashEl, this.opts.removableOptions)
1967
- .on(trashEl, 'dropover', function (event, el) { return _this._itemRemoving(el, true); })
1968
- .on(trashEl, 'dropout', function (event, el) { return _this._itemRemoving(el, false); });
1969
- }
1970
- }
1971
- return this;
1972
- };
1973
- /** @internal prepares the element for drag&drop **/
1974
- GridStack.prototype._prepareDragDropByNode = function (node) {
1975
- var _this = this;
1976
- var el = node.el;
1977
- var noMove = node.noMove || this.opts.disableDrag;
1978
- var noResize = node.noResize || this.opts.disableResize;
1979
- // check for disabled grid first
1980
- if (this.opts.staticGrid || (noMove && noResize)) {
1981
- if (node._initDD) {
1982
- this._removeDD(el); // nukes everything instead of just disable, will add some styles back next
1983
- delete node._initDD;
1984
- }
1985
- el.classList.add('ui-draggable-disabled', 'ui-resizable-disabled'); // add styles one might depend on #1435
1986
- return this;
1987
- }
1988
- if (!node._initDD) {
1989
- // variables used/cashed between the 3 start/move/end methods, in addition to node passed above
1990
- var cellWidth_1;
1991
- var cellHeight_1;
1992
- /** called when item starts moving/resizing */
1993
- var onStartMoving = function (event, ui) {
1994
- // trigger any 'dragstart' / 'resizestart' manually
1995
- if (_this._gsEventHandler[event.type]) {
1996
- _this._gsEventHandler[event.type](event, event.target);
1997
- }
1998
- cellWidth_1 = _this.cellWidth();
1999
- cellHeight_1 = _this.getCellHeight(true); // force pixels for calculations
2000
- _this._onStartMoving(el, event, ui, node, cellWidth_1, cellHeight_1);
2001
- };
2002
- /** called when item is being dragged/resized */
2003
- var dragOrResize = function (event, ui) {
2004
- _this._dragOrResize(el, event, ui, node, cellWidth_1, cellHeight_1);
2005
- };
2006
- /** called when the item stops moving/resizing */
2007
- var onEndMoving = function (event) {
2008
- _this.placeholder.remove();
2009
- delete node._moving;
2010
- delete node._event;
2011
- delete node._lastTried;
2012
- // if the item has moved to another grid, we're done here
2013
- var target = event.target;
2014
- if (!target.gridstackNode || target.gridstackNode.grid !== _this)
2015
- return;
2016
- node.el = target;
2017
- if (node._isAboutToRemove) {
2018
- var gridToNotify = el.gridstackNode.grid;
2019
- if (gridToNotify._gsEventHandler[event.type]) {
2020
- gridToNotify._gsEventHandler[event.type](event, target);
2021
- }
2022
- _this._removeDD(el);
2023
- gridToNotify.engine.removedNodes.push(node);
2024
- gridToNotify._triggerRemoveEvent();
2025
- // break circular links and remove DOM
2026
- delete el.gridstackNode;
2027
- delete node.el;
2028
- el.remove();
2029
- }
2030
- else {
2031
- utils_1.Utils.removePositioningStyles(target);
2032
- if (node._temporaryRemoved) {
2033
- // got removed - restore item back to before dragging position
2034
- utils_1.Utils.copyPos(node, node._orig); // @ts-ignore
2035
- _this._writePosAttr(target, node);
2036
- _this.engine.addNode(node);
2037
- }
2038
- else {
2039
- // move to new placeholder location
2040
- _this._writePosAttr(target, node);
2041
- }
2042
- if (_this._gsEventHandler[event.type]) {
2043
- _this._gsEventHandler[event.type](event, target);
2044
- }
2045
- }
2046
- // @ts-ignore
2047
- _this._extraDragRow = 0; // @ts-ignore
2048
- _this._updateContainerHeight(); // @ts-ignore
2049
- _this._triggerChangeEvent();
2050
- _this.engine.endUpdate();
2051
- };
2052
- dd.draggable(el, {
2053
- start: onStartMoving,
2054
- stop: onEndMoving,
2055
- drag: dragOrResize
2056
- }).resizable(el, {
2057
- start: onStartMoving,
2058
- stop: onEndMoving,
2059
- resize: dragOrResize
2060
- });
2061
- node._initDD = true; // we've set DD support now
2062
- }
2063
- // finally fine tune move vs resize by disabling any part...
2064
- dd.draggable(el, noMove ? 'disable' : 'enable')
2065
- .resizable(el, noResize ? 'disable' : 'enable');
2066
- return this;
2067
- };
2068
- /** @internal handles actual drag/resize start **/
2069
- GridStack.prototype._onStartMoving = function (el, event, ui, node, cellWidth, cellHeight) {
2070
- this.engine.cleanNodes()
2071
- .beginUpdate(node);
2072
- // @ts-ignore
2073
- this._writePosAttr(this.placeholder, node);
2074
- this.el.appendChild(this.placeholder);
2075
- // console.log('_onStartMoving placeholder') // TEST
2076
- node.el = this.placeholder;
2077
- node._lastUiPosition = ui.position;
2078
- node._prevYPix = ui.position.top;
2079
- node._moving = (event.type === 'dragstart'); // 'dropover' are not initially moving so they can go exactly where they enter (will push stuff out of the way)
2080
- delete node._lastTried;
2081
- if (event.type === 'dropover' && node._temporaryRemoved) {
2082
- // console.log('engine.addNode x=' + node.x); // TEST
2083
- this.engine.addNode(node); // will add, fix collisions, update attr and clear _temporaryRemoved
2084
- node._moving = true; // AFTER, mark as moving object (wanted fix location before)
2085
- }
2086
- // set the min/max resize info
2087
- this.engine.cacheRects(cellWidth, cellHeight, this.opts.marginTop, this.opts.marginRight, this.opts.marginBottom, this.opts.marginLeft);
2088
- if (event.type === 'resizestart') {
2089
- dd.resizable(el, 'option', 'minWidth', cellWidth * (node.minW || 1))
2090
- .resizable(el, 'option', 'minHeight', cellHeight * (node.minH || 1));
2091
- if (node.maxW) {
2092
- dd.resizable(el, 'option', 'maxWidth', cellWidth * node.maxW);
2093
- }
2094
- if (node.maxH) {
2095
- dd.resizable(el, 'option', 'maxHeight', cellHeight * node.maxH);
2096
- }
2097
- }
2098
- };
2099
- /** @internal handles actual drag/resize **/
2100
- GridStack.prototype._dragOrResize = function (el, event, ui, node, cellWidth, cellHeight) {
2101
- var p = __assign({}, node._orig); // could be undefined (_isExternal) which is ok (drag only set x,y and w,h will default to node value)
2102
- var resizing;
2103
- var mLeft = this.opts.marginLeft, mRight = this.opts.marginRight, mTop = this.opts.marginTop, mBottom = this.opts.marginBottom;
2104
- // if margins (which are used to pass mid point by) are large relative to cell height/width, reduce them down #1855
2105
- var mHeight = Math.round(cellHeight * 0.1), mWidth = Math.round(cellWidth * 0.1);
2106
- mLeft = Math.min(mLeft, mWidth);
2107
- mRight = Math.min(mRight, mWidth);
2108
- mTop = Math.min(mTop, mHeight);
2109
- mBottom = Math.min(mBottom, mHeight);
2110
- if (event.type === 'drag') {
2111
- if (node._temporaryRemoved)
2112
- return; // handled by dropover
2113
- var distance = ui.position.top - node._prevYPix;
2114
- node._prevYPix = ui.position.top;
2115
- if (this.opts.draggable.scroll !== false) {
2116
- utils_1.Utils.updateScrollPosition(el, ui.position, distance);
2117
- }
2118
- // get new position taking into account the margin in the direction we are moving! (need to pass mid point by margin)
2119
- var left = ui.position.left + (ui.position.left > node._lastUiPosition.left ? -mRight : mLeft);
2120
- var top_2 = ui.position.top + (ui.position.top > node._lastUiPosition.top ? -mBottom : mTop);
2121
- p.x = Math.round(left / cellWidth);
2122
- p.y = Math.round(top_2 / cellHeight);
2123
- // @ts-ignore// if we're at the bottom hitting something else, grow the grid so cursor doesn't leave when trying to place below others
2124
- var prev = this._extraDragRow;
2125
- if (this.engine.collide(node, p)) {
2126
- var row = this.getRow();
2127
- var extra = Math.max(0, (p.y + node.h) - row);
2128
- if (this.opts.maxRow && row + extra > this.opts.maxRow) {
2129
- extra = Math.max(0, this.opts.maxRow - row);
2130
- } // @ts-ignore
2131
- this._extraDragRow = extra; // @ts-ignore
2132
- }
2133
- else
2134
- this._extraDragRow = 0; // @ts-ignore
2135
- if (this._extraDragRow !== prev)
2136
- this._updateContainerHeight();
2137
- if (node.x === p.x && node.y === p.y)
2138
- return; // skip same
2139
- // DON'T skip one we tried as we might have failed because of coverage <50% before
2140
- // if (node._lastTried && node._lastTried.x === x && node._lastTried.y === y) return;
2141
- }
2142
- else if (event.type === 'resize') {
2143
- if (p.x < 0)
2144
- return;
2145
- // Scrolling page if needed
2146
- utils_1.Utils.updateScrollResize(event, el, cellHeight);
2147
- // get new size
2148
- p.w = Math.round((ui.size.width - mLeft) / cellWidth);
2149
- p.h = Math.round((ui.size.height - mTop) / cellHeight);
2150
- if (node.w === p.w && node.h === p.h)
2151
- return;
2152
- if (node._lastTried && node._lastTried.w === p.w && node._lastTried.h === p.h)
2153
- return; // skip one we tried (but failed)
2154
- // if we size on left/top side this might move us, so get possible new position as well
2155
- var left = ui.position.left + mLeft;
2156
- var top_3 = ui.position.top + mTop;
2157
- p.x = Math.round(left / cellWidth);
2158
- p.y = Math.round(top_3 / cellHeight);
2159
- resizing = true;
2160
- }
2161
- node._event = event;
2162
- node._lastTried = p; // set as last tried (will nuke if we go there)
2163
- var rect = {
2164
- x: ui.position.left + mLeft,
2165
- y: ui.position.top + mTop,
2166
- w: (ui.size ? ui.size.width : node.w * cellWidth) - mLeft - mRight,
2167
- h: (ui.size ? ui.size.height : node.h * cellHeight) - mTop - mBottom
2168
- };
2169
- if (this.engine.moveNodeCheck(node, __assign(__assign({}, p), { cellWidth: cellWidth, cellHeight: cellHeight, rect: rect, resizing: resizing }))) {
2170
- node._lastUiPosition = ui.position;
2171
- this.engine.cacheRects(cellWidth, cellHeight, mTop, mRight, mBottom, mLeft);
2172
- delete node._skipDown;
2173
- if (resizing && node.subGrid) {
2174
- node.subGrid.onParentResize();
2175
- } // @ts-ignore
2176
- this._extraDragRow = 0; // @ts-ignore
2177
- this._updateContainerHeight();
2178
- var target = event.target; // @ts-ignore
2179
- this._writePosAttr(target, node);
2180
- if (this._gsEventHandler[event.type]) {
2181
- this._gsEventHandler[event.type](event, target);
2182
- }
2183
- }
2184
- };
2185
- /** @internal called when item leaving our area by either cursor dropout event
2186
- * or shape is outside our boundaries. remove it from us, and mark temporary if this was
2187
- * our item to start with else restore prev node values from prev grid it came from.
2188
- **/
2189
- GridStack.prototype._leave = function (el, helper) {
2190
- var node = el.gridstackNode;
2191
- if (!node)
2192
- return;
2193
- dd.off(el, 'drag'); // no need to track while being outside
2194
- // this gets called when cursor leaves and shape is outside, so only do this once
2195
- if (node._temporaryRemoved)
2196
- return;
2197
- node._temporaryRemoved = true;
2198
- this.engine.removeNode(node); // remove placeholder as well, otherwise it's a sign node is not in our list, which is a bigger issue
2199
- node.el = node._isExternal && helper ? helper : el; // point back to real item being dragged
2200
- if (this.opts.removable === true) { // boolean vs a class string
2201
- // item leaving us and we are supposed to remove on leave (no need to drag onto trash) mark it so
2202
- this._itemRemoving(el, true);
2203
- }
2204
- // finally if item originally came from another grid, but left us, restore things back to prev info
2205
- if (el._gridstackNodeOrig) {
2206
- // console.log('leave delete _gridstackNodeOrig') // TEST
2207
- el.gridstackNode = el._gridstackNodeOrig;
2208
- delete el._gridstackNodeOrig;
2209
- }
2210
- else if (node._isExternal) {
2211
- // item came from outside (like a toolbar) so nuke any node info
2212
- delete node.el;
2213
- delete el.gridstackNode;
2214
- // and restore all nodes back to original
2215
- this.engine.restoreInitial();
2216
- }
2217
- };
2218
- // legacy method removed
2219
- GridStack.prototype.commit = function () { utils_1.obsolete(this, this.batchUpdate(false), 'commit', 'batchUpdate', '5.2'); return this; };
2220
- /** scoping so users can call GridStack.Utils.sort() for example */
2221
- GridStack.Utils = utils_1.Utils;
2222
- /** scoping so users can call new GridStack.Engine(12) for example */
2223
- GridStack.Engine = gridstack_engine_1.GridStackEngine;
2224
- GridStack.GDRev = '7.2.3';
2225
- return GridStack;
2226
- }());
2227
- exports.GridStack = GridStack;
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
25
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
26
+ };
27
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
28
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
29
+ if (ar || !(i in from)) {
30
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
31
+ ar[i] = from[i];
32
+ }
33
+ }
34
+ return to.concat(ar || Array.prototype.slice.call(from));
35
+ };
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.GridStack = void 0;
38
+ /*!
39
+ * GridStack 8.0.0
40
+ * https://gridstackjs.com/
41
+ *
42
+ * Copyright (c) 2021-2022 Alain Dumesny
43
+ * see root license https://github.com/gridstack/gridstack.js/tree/master/LICENSE
44
+ */
45
+ var gridstack_engine_1 = require("./gridstack-engine");
46
+ var utils_1 = require("./utils");
47
+ var types_1 = require("./types");
48
+ /*
49
+ * and include D&D by default
50
+ * TODO: while we could generate a gridstack-static.js at smaller size - saves about 31k (41k -> 72k)
51
+ * I don't know how to generate the DD only code at the remaining 31k to delay load as code depends on Gridstack.ts
52
+ * also it caused loading issues in prod - see https://github.com/gridstack/gridstack.js/issues/2039
53
+ */
54
+ var dd_gridstack_1 = require("./dd-gridstack");
55
+ var dd_touch_1 = require("./dd-touch");
56
+ var dd_manager_1 = require("./dd-manager");
57
+ /** global instance */
58
+ var dd = new dd_gridstack_1.DDGridStack;
59
+ // export all dependent file as well to make it easier for users to just import the main file
60
+ __exportStar(require("./types"), exports);
61
+ __exportStar(require("./utils"), exports);
62
+ __exportStar(require("./gridstack-engine"), exports);
63
+ __exportStar(require("./dd-gridstack"), exports);
64
+ /**
65
+ * Main gridstack class - you will need to call `GridStack.init()` first to initialize your grid.
66
+ * Note: your grid elements MUST have the following classes for the CSS layout to work:
67
+ * @example
68
+ * <div class="grid-stack">
69
+ * <div class="grid-stack-item">
70
+ * <div class="grid-stack-item-content">Item 1</div>
71
+ * </div>
72
+ * </div>
73
+ */
74
+ var GridStack = exports.GridStack = /** @class */ (function () {
75
+ /**
76
+ * Construct a grid item from the given element and options
77
+ * @param el
78
+ * @param opts
79
+ */
80
+ function GridStack(el, opts) {
81
+ if (opts === void 0) { opts = {}; }
82
+ var _this = this;
83
+ var _a, _b;
84
+ /** @internal */
85
+ this._gsEventHandler = {};
86
+ /** @internal extra row added when dragging at the bottom of the grid */
87
+ this._extraDragRow = 0;
88
+ this.el = el; // exposed HTML element to the user
89
+ opts = opts || {}; // handles null/undefined/0
90
+ if (!el.classList.contains('grid-stack')) {
91
+ this.el.classList.add('grid-stack');
92
+ }
93
+ // if row property exists, replace minRow and maxRow instead
94
+ if (opts.row) {
95
+ opts.minRow = opts.maxRow = opts.row;
96
+ delete opts.row;
97
+ }
98
+ var rowAttr = utils_1.Utils.toNumber(el.getAttribute('gs-row'));
99
+ // flag only valid in sub-grids (handled by parent, not here)
100
+ if (opts.column === 'auto') {
101
+ delete opts.column;
102
+ }
103
+ // 'minWidth' legacy support in 5.1
104
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
105
+ var anyOpts = opts;
106
+ if (anyOpts.minWidth !== undefined) {
107
+ opts.oneColumnSize = opts.oneColumnSize || anyOpts.minWidth;
108
+ delete anyOpts.minWidth;
109
+ }
110
+ // save original setting so we can restore on save
111
+ if (opts.alwaysShowResizeHandle !== undefined) {
112
+ opts._alwaysShowResizeHandle = opts.alwaysShowResizeHandle;
113
+ }
114
+ // elements DOM attributes override any passed options (like CSS style) - merge the two together
115
+ var defaults = __assign(__assign({}, utils_1.Utils.cloneDeep(types_1.gridDefaults)), { column: utils_1.Utils.toNumber(el.getAttribute('gs-column')) || types_1.gridDefaults.column, minRow: rowAttr ? rowAttr : utils_1.Utils.toNumber(el.getAttribute('gs-min-row')) || types_1.gridDefaults.minRow, maxRow: rowAttr ? rowAttr : utils_1.Utils.toNumber(el.getAttribute('gs-max-row')) || types_1.gridDefaults.maxRow, staticGrid: utils_1.Utils.toBool(el.getAttribute('gs-static')) || types_1.gridDefaults.staticGrid, draggable: {
116
+ handle: (opts.handleClass ? '.' + opts.handleClass : (opts.handle ? opts.handle : '')) || types_1.gridDefaults.draggable.handle,
117
+ }, removableOptions: {
118
+ accept: opts.itemClass ? '.' + opts.itemClass : types_1.gridDefaults.removableOptions.accept,
119
+ } });
120
+ if (el.getAttribute('gs-animate')) { // default to true, but if set to false use that instead
121
+ defaults.animate = utils_1.Utils.toBool(el.getAttribute('gs-animate'));
122
+ }
123
+ this.opts = utils_1.Utils.defaults(opts, defaults);
124
+ opts = null; // make sure we use this.opts instead
125
+ this._initMargin(); // part of settings defaults...
126
+ // Now check if we're loading into 1 column mode FIRST so we don't do un-necessary work (like cellHeight = width / 12 then go 1 column)
127
+ if (this.opts.column !== 1 && !this.opts.disableOneColumnMode && this._widthOrContainer() <= this.opts.oneColumnSize) {
128
+ this._prevColumn = this.getColumn();
129
+ this.opts.column = 1;
130
+ }
131
+ if (this.opts.rtl === 'auto') {
132
+ this.opts.rtl = (el.style.direction === 'rtl');
133
+ }
134
+ if (this.opts.rtl) {
135
+ this.el.classList.add('grid-stack-rtl');
136
+ }
137
+ // check if we're been nested, and if so update our style and keep pointer around (used during save)
138
+ var parentGridItem = (_a = utils_1.Utils.closestUpByClass(this.el, types_1.gridDefaults.itemClass)) === null || _a === void 0 ? void 0 : _a.gridstackNode;
139
+ if (parentGridItem) {
140
+ parentGridItem.subGrid = this;
141
+ this.parentGridItem = parentGridItem;
142
+ this.el.classList.add('grid-stack-nested');
143
+ parentGridItem.el.classList.add('grid-stack-sub-grid');
144
+ }
145
+ this._isAutoCellHeight = (this.opts.cellHeight === 'auto');
146
+ if (this._isAutoCellHeight || this.opts.cellHeight === 'initial') {
147
+ // make the cell content square initially (will use resize/column event to keep it square)
148
+ this.cellHeight(undefined, false);
149
+ }
150
+ else {
151
+ // append unit if any are set
152
+ if (typeof this.opts.cellHeight == 'number' && this.opts.cellHeightUnit && this.opts.cellHeightUnit !== types_1.gridDefaults.cellHeightUnit) {
153
+ this.opts.cellHeight = this.opts.cellHeight + this.opts.cellHeightUnit;
154
+ delete this.opts.cellHeightUnit;
155
+ }
156
+ this.cellHeight(this.opts.cellHeight, false);
157
+ }
158
+ // see if we need to adjust auto-hide
159
+ if (this.opts.alwaysShowResizeHandle === 'mobile') {
160
+ this.opts.alwaysShowResizeHandle = dd_touch_1.isTouch;
161
+ }
162
+ this._styleSheetClass = 'grid-stack-instance-' + gridstack_engine_1.GridStackEngine._idSeq++;
163
+ this.el.classList.add(this._styleSheetClass);
164
+ this._setStaticClass();
165
+ var engineClass = this.opts.engineClass || GridStack.engineClass || gridstack_engine_1.GridStackEngine;
166
+ this.engine = new engineClass({
167
+ column: this.getColumn(),
168
+ float: this.opts.float,
169
+ maxRow: this.opts.maxRow,
170
+ onChange: function (cbNodes) {
171
+ var maxH = 0;
172
+ _this.engine.nodes.forEach(function (n) { maxH = Math.max(maxH, n.y + n.h); });
173
+ cbNodes.forEach(function (n) {
174
+ var el = n.el;
175
+ if (!el)
176
+ return;
177
+ if (n._removeDOM) {
178
+ if (el)
179
+ el.remove();
180
+ delete n._removeDOM;
181
+ }
182
+ else {
183
+ _this._writePosAttr(el, n);
184
+ }
185
+ });
186
+ _this._updateStyles(false, maxH); // false = don't recreate, just append if need be
187
+ }
188
+ });
189
+ if (this.opts.auto) {
190
+ this.batchUpdate(); // prevent in between re-layout #1535 TODO: this only set float=true, need to prevent collision check...
191
+ this.getGridItems().forEach(function (el) { return _this._prepareElement(el); });
192
+ this.batchUpdate(false);
193
+ }
194
+ // load any passed in children as well, which overrides any DOM layout done above
195
+ if (this.opts.children) {
196
+ var children = this.opts.children;
197
+ delete this.opts.children;
198
+ if (children.length)
199
+ this.load(children); // don't load empty
200
+ }
201
+ this.setAnimation(this.opts.animate);
202
+ this._updateStyles();
203
+ if (this.opts.column != 12) {
204
+ this.el.classList.add('grid-stack-' + this.opts.column);
205
+ }
206
+ // legacy support to appear 'per grid` options when really global.
207
+ if (this.opts.dragIn)
208
+ GridStack.setupDragIn(this.opts.dragIn, this.opts.dragInOptions);
209
+ delete this.opts.dragIn;
210
+ delete this.opts.dragInOptions;
211
+ // dynamic grids require pausing during drag to detect over to nest vs push
212
+ if (this.opts.subGridDynamic && !dd_manager_1.DDManager.pauseDrag)
213
+ dd_manager_1.DDManager.pauseDrag = true;
214
+ if (((_b = this.opts.draggable) === null || _b === void 0 ? void 0 : _b.pause) !== undefined)
215
+ dd_manager_1.DDManager.pauseDrag = this.opts.draggable.pause;
216
+ this._setupRemoveDrop();
217
+ this._setupAcceptWidget();
218
+ this._updateWindowResizeEvent();
219
+ }
220
+ /**
221
+ * initializing the HTML element, or selector string, into a grid will return the grid. Calling it again will
222
+ * simply return the existing instance (ignore any passed options). There is also an initAll() version that support
223
+ * multiple grids initialization at once. Or you can use addGrid() to create the entire grid from JSON.
224
+ * @param options grid options (optional)
225
+ * @param elOrString element or CSS selector (first one used) to convert to a grid (default to '.grid-stack' class selector)
226
+ *
227
+ * @example
228
+ * let grid = GridStack.init();
229
+ *
230
+ * Note: the HTMLElement (of type GridHTMLElement) will store a `gridstack: GridStack` value that can be retrieve later
231
+ * let grid = document.querySelector('.grid-stack').gridstack;
232
+ */
233
+ GridStack.init = function (options, elOrString) {
234
+ if (options === void 0) { options = {}; }
235
+ if (elOrString === void 0) { elOrString = '.grid-stack'; }
236
+ var el = GridStack.getGridElement(elOrString);
237
+ if (!el) {
238
+ if (typeof elOrString === 'string') {
239
+ console.error('GridStack.initAll() no grid was found with selector "' + elOrString + '" - element missing or wrong selector ?' +
240
+ '\nNote: ".grid-stack" is required for proper CSS styling and drag/drop, and is the default selector.');
241
+ }
242
+ else {
243
+ console.error('GridStack.init() no grid element was passed.');
244
+ }
245
+ return null;
246
+ }
247
+ if (!el.gridstack) {
248
+ el.gridstack = new GridStack(el, utils_1.Utils.cloneDeep(options));
249
+ }
250
+ return el.gridstack;
251
+ };
252
+ /**
253
+ * Will initialize a list of elements (given a selector) and return an array of grids.
254
+ * @param options grid options (optional)
255
+ * @param selector elements selector to convert to grids (default to '.grid-stack' class selector)
256
+ *
257
+ * @example
258
+ * let grids = GridStack.initAll();
259
+ * grids.forEach(...)
260
+ */
261
+ GridStack.initAll = function (options, selector) {
262
+ if (options === void 0) { options = {}; }
263
+ if (selector === void 0) { selector = '.grid-stack'; }
264
+ var grids = [];
265
+ GridStack.getGridElements(selector).forEach(function (el) {
266
+ if (!el.gridstack) {
267
+ el.gridstack = new GridStack(el, utils_1.Utils.cloneDeep(options));
268
+ delete options.dragIn;
269
+ delete options.dragInOptions; // only need to be done once (really a static global thing, not per grid)
270
+ }
271
+ grids.push(el.gridstack);
272
+ });
273
+ if (grids.length === 0) {
274
+ console.error('GridStack.initAll() no grid was found with selector "' + selector + '" - element missing or wrong selector ?' +
275
+ '\nNote: ".grid-stack" is required for proper CSS styling and drag/drop, and is the default selector.');
276
+ }
277
+ return grids;
278
+ };
279
+ /**
280
+ * call to create a grid with the given options, including loading any children from JSON structure. This will call GridStack.init(), then
281
+ * grid.load() on any passed children (recursively). Great alternative to calling init() if you want entire grid to come from
282
+ * JSON serialized data, including options.
283
+ * @param parent HTML element parent to the grid
284
+ * @param opt grids options used to initialize the grid, and list of children
285
+ */
286
+ GridStack.addGrid = function (parent, opt) {
287
+ if (opt === void 0) { opt = {}; }
288
+ if (!parent)
289
+ return null;
290
+ var el = parent;
291
+ if (el.gridstack) {
292
+ // already a grid - set option and load data
293
+ var grid_1 = el.gridstack;
294
+ if (opt)
295
+ grid_1.opts = __assign(__assign({}, grid_1.opts), opt);
296
+ if (opt.children !== undefined)
297
+ grid_1.load(opt.children);
298
+ return grid_1;
299
+ }
300
+ // create the grid element, but check if the passed 'parent' already has grid styling and should be used instead
301
+ var parentIsGrid = parent.classList.contains('grid-stack');
302
+ if (!parentIsGrid || GridStack.addRemoveCB) {
303
+ if (GridStack.addRemoveCB) {
304
+ el = GridStack.addRemoveCB(parent, opt, true, true);
305
+ }
306
+ else {
307
+ var doc = document.implementation.createHTMLDocument(''); // IE needs a param
308
+ doc.body.innerHTML = "<div class=\"grid-stack ".concat(opt.class || '', "\"></div>");
309
+ el = doc.body.children[0];
310
+ parent.appendChild(el);
311
+ }
312
+ }
313
+ // create grid class and load any children
314
+ var grid = GridStack.init(opt, el);
315
+ return grid;
316
+ };
317
+ /** call this method to register your engine instead of the default one.
318
+ * See instead `GridStackOptions.engineClass` if you only need to
319
+ * replace just one instance.
320
+ */
321
+ GridStack.registerEngine = function (engineClass) {
322
+ GridStack.engineClass = engineClass;
323
+ };
324
+ Object.defineProperty(GridStack.prototype, "placeholder", {
325
+ /** @internal create placeholder DIV as needed */
326
+ get: function () {
327
+ if (!this._placeholder) {
328
+ var placeholderChild = document.createElement('div'); // child so padding match item-content
329
+ placeholderChild.className = 'placeholder-content';
330
+ if (this.opts.placeholderText) {
331
+ placeholderChild.innerHTML = this.opts.placeholderText;
332
+ }
333
+ this._placeholder = document.createElement('div');
334
+ this._placeholder.classList.add(this.opts.placeholderClass, types_1.gridDefaults.itemClass, this.opts.itemClass);
335
+ this.placeholder.appendChild(placeholderChild);
336
+ }
337
+ return this._placeholder;
338
+ },
339
+ enumerable: false,
340
+ configurable: true
341
+ });
342
+ /**
343
+ * add a new widget and returns it.
344
+ *
345
+ * Widget will be always placed even if result height is more than actual grid height.
346
+ * You need to use `willItFit()` before calling addWidget for additional check.
347
+ * See also `makeWidget()`.
348
+ *
349
+ * @example
350
+ * let grid = GridStack.init();
351
+ * grid.addWidget({w: 3, content: 'hello'});
352
+ * grid.addWidget('<div class="grid-stack-item"><div class="grid-stack-item-content">hello</div></div>', {w: 3});
353
+ *
354
+ * @param el GridStackWidget (which can have content string as well), html element, or string definition to add
355
+ * @param options widget position/size options (optional, and ignore if first param is already option) - see GridStackWidget
356
+ */
357
+ GridStack.prototype.addWidget = function (els, options) {
358
+ function isGridStackWidget(w) {
359
+ return w.el !== undefined || w.x !== undefined || w.y !== undefined || w.w !== undefined || w.h !== undefined || w.content !== undefined ? true : false;
360
+ }
361
+ var el;
362
+ var node;
363
+ if (typeof els === 'string') {
364
+ var doc = document.implementation.createHTMLDocument(''); // IE needs a param
365
+ doc.body.innerHTML = els;
366
+ el = doc.body.children[0];
367
+ }
368
+ else if (arguments.length === 0 || arguments.length === 1 && isGridStackWidget(els)) {
369
+ node = options = els;
370
+ if (node === null || node === void 0 ? void 0 : node.el) {
371
+ el = node.el; // re-use element stored in the node
372
+ }
373
+ else if (GridStack.addRemoveCB) {
374
+ el = GridStack.addRemoveCB(this.el, options, true, false);
375
+ }
376
+ else {
377
+ var content = (options === null || options === void 0 ? void 0 : options.content) || '';
378
+ var doc = document.implementation.createHTMLDocument(''); // IE needs a param
379
+ doc.body.innerHTML = "<div class=\"grid-stack-item ".concat(this.opts.itemClass || '', "\"><div class=\"grid-stack-item-content\">").concat(content, "</div></div>");
380
+ el = doc.body.children[0];
381
+ }
382
+ }
383
+ else {
384
+ el = els;
385
+ }
386
+ if (!el)
387
+ return;
388
+ // Tempting to initialize the passed in opt with default and valid values, but this break knockout demos
389
+ // as the actual value are filled in when _prepareElement() calls el.getAttribute('gs-xyz') before adding the node.
390
+ // So make sure we load any DOM attributes that are not specified in passed in options (which override)
391
+ var domAttr = this._readAttr(el);
392
+ options = utils_1.Utils.cloneDeep(options) || {}; // make a copy before we modify in case caller re-uses it
393
+ utils_1.Utils.defaults(options, domAttr);
394
+ node = this.engine.prepareNode(options);
395
+ this._writeAttr(el, options);
396
+ if (this._insertNotAppend) {
397
+ this.el.prepend(el);
398
+ }
399
+ else {
400
+ this.el.appendChild(el);
401
+ }
402
+ // similar to makeWidget() that doesn't read attr again and worse re-create a new node and loose any _id
403
+ this._prepareElement(el, true, options);
404
+ this._updateContainerHeight();
405
+ // see if there is a sub-grid to create
406
+ if (node.subGridOpts) {
407
+ this.makeSubGrid(node.el, node.subGridOpts, undefined, false); // node.subGrid will be used as option in method, no need to pass
408
+ }
409
+ // if we're adding an item into 1 column (_prevColumn is set only when going to 1) make sure
410
+ // we don't override the larger 12 column layout that was already saved. #1985
411
+ if (this._prevColumn && this.opts.column === 1) {
412
+ this._ignoreLayoutsNodeChange = true;
413
+ }
414
+ this._triggerAddEvent();
415
+ this._triggerChangeEvent();
416
+ delete this._ignoreLayoutsNodeChange;
417
+ return el;
418
+ };
419
+ /**
420
+ * Convert an existing gridItem element into a sub-grid with the given (optional) options, else inherit them
421
+ * from the parent's subGrid options.
422
+ * @param el gridItem element to convert
423
+ * @param ops (optional) sub-grid options, else default to node, then parent settings, else defaults
424
+ * @param nodeToAdd (optional) node to add to the newly created sub grid (used when dragging over existing regular item)
425
+ * @returns newly created grid
426
+ */
427
+ GridStack.prototype.makeSubGrid = function (el, ops, nodeToAdd, saveContent) {
428
+ var _a, _b, _c;
429
+ if (saveContent === void 0) { saveContent = true; }
430
+ var node = el.gridstackNode;
431
+ if (!node) {
432
+ node = this.makeWidget(el).gridstackNode;
433
+ }
434
+ if ((_a = node.subGrid) === null || _a === void 0 ? void 0 : _a.el)
435
+ return node.subGrid; // already done
436
+ // find the template subGrid stored on a parent as fallback...
437
+ var subGridTemplate; // eslint-disable-next-line @typescript-eslint/no-this-alias
438
+ var grid = this;
439
+ while (grid && !subGridTemplate) {
440
+ subGridTemplate = (_b = grid.opts) === null || _b === void 0 ? void 0 : _b.subGridOpts;
441
+ grid = (_c = grid.parentGridItem) === null || _c === void 0 ? void 0 : _c.grid;
442
+ }
443
+ //... and set the create options
444
+ ops = utils_1.Utils.cloneDeep(__assign(__assign(__assign({}, (subGridTemplate || {})), { children: undefined }), (ops || node.subGridOpts)));
445
+ node.subGridOpts = ops;
446
+ // if column special case it set, remember that flag and set default
447
+ var autoColumn;
448
+ if (ops.column === 'auto') {
449
+ autoColumn = true;
450
+ ops.column = Math.max(node.w || 1, (nodeToAdd === null || nodeToAdd === void 0 ? void 0 : nodeToAdd.w) || 1);
451
+ ops.disableOneColumnMode = true; // driven by parent
452
+ }
453
+ // if we're converting an existing full item, move over the content to be the first sub item in the new grid
454
+ var content = node.el.querySelector('.grid-stack-item-content');
455
+ var newItem;
456
+ var newItemOpt;
457
+ if (saveContent) {
458
+ this._removeDD(node.el); // remove D&D since it's set on content div
459
+ newItemOpt = __assign(__assign({}, node), { x: 0, y: 0 });
460
+ utils_1.Utils.removeInternalForSave(newItemOpt);
461
+ delete newItemOpt.subGridOpts;
462
+ if (node.content) {
463
+ newItemOpt.content = node.content;
464
+ delete node.content;
465
+ }
466
+ if (GridStack.addRemoveCB) {
467
+ newItem = GridStack.addRemoveCB(this.el, newItemOpt, true, false);
468
+ }
469
+ else {
470
+ var doc = document.implementation.createHTMLDocument(''); // IE needs a param
471
+ doc.body.innerHTML = "<div class=\"grid-stack-item\"></div>";
472
+ newItem = doc.body.children[0];
473
+ newItem.appendChild(content);
474
+ doc.body.innerHTML = "<div class=\"grid-stack-item-content\"></div>";
475
+ content = doc.body.children[0];
476
+ node.el.appendChild(content);
477
+ }
478
+ this._prepareDragDropByNode(node); // ... and restore original D&D
479
+ }
480
+ // if we're adding an additional item, make the container large enough to have them both
481
+ if (nodeToAdd) {
482
+ var w = autoColumn ? ops.column : node.w;
483
+ var h = node.h + nodeToAdd.h;
484
+ var style_1 = node.el.style;
485
+ style_1.transition = 'none'; // show up instantly so we don't see scrollbar with nodeToAdd
486
+ this.update(node.el, { w: w, h: h });
487
+ setTimeout(function () { return style_1.transition = null; }); // recover animation
488
+ }
489
+ var subGrid = node.subGrid = GridStack.addGrid(content, ops);
490
+ if (nodeToAdd === null || nodeToAdd === void 0 ? void 0 : nodeToAdd._moving)
491
+ subGrid._isTemp = true; // prevent re-nesting as we add over
492
+ if (autoColumn)
493
+ subGrid._autoColumn = true;
494
+ // add the original content back as a child of hte newly created grid
495
+ if (saveContent) {
496
+ subGrid.addWidget(newItem, newItemOpt);
497
+ }
498
+ // now add any additional node
499
+ if (nodeToAdd) {
500
+ if (nodeToAdd._moving) {
501
+ // create an artificial event even for the just created grid to receive this item
502
+ window.setTimeout(function () { return utils_1.Utils.simulateMouseEvent(nodeToAdd._event, 'mouseenter', subGrid.el); }, 0);
503
+ }
504
+ else {
505
+ subGrid.addWidget(node.el, node);
506
+ }
507
+ }
508
+ return subGrid;
509
+ };
510
+ /**
511
+ * called when an item was converted into a nested grid to accommodate a dragged over item, but then item leaves - return back
512
+ * to the original grid-item. Also called to remove empty sub-grids when last item is dragged out (since re-creating is simple)
513
+ */
514
+ GridStack.prototype.removeAsSubGrid = function (nodeThatRemoved) {
515
+ var _this = this;
516
+ var _a;
517
+ var pGrid = (_a = this.parentGridItem) === null || _a === void 0 ? void 0 : _a.grid;
518
+ if (!pGrid)
519
+ return;
520
+ pGrid.batchUpdate();
521
+ pGrid.removeWidget(this.parentGridItem.el, true, true);
522
+ this.engine.nodes.forEach(function (n) {
523
+ // migrate any children over and offsetting by our location
524
+ n.x += _this.parentGridItem.x;
525
+ n.y += _this.parentGridItem.y;
526
+ pGrid.addWidget(n.el, n);
527
+ });
528
+ pGrid.batchUpdate(false);
529
+ if (this.parentGridItem)
530
+ delete this.parentGridItem.subGrid;
531
+ delete this.parentGridItem;
532
+ // create an artificial event for the original grid now that this one is gone (got a leave, but won't get enter)
533
+ if (nodeThatRemoved) {
534
+ window.setTimeout(function () { return utils_1.Utils.simulateMouseEvent(nodeThatRemoved._event, 'mouseenter', pGrid.el); }, 0);
535
+ }
536
+ };
537
+ /**
538
+ * saves the current layout returning a list of widgets for serialization which might include any nested grids.
539
+ * @param saveContent if true (default) the latest html inside .grid-stack-content will be saved to GridStackWidget.content field, else it will
540
+ * be removed.
541
+ * @param saveGridOpt if true (default false), save the grid options itself, so you can call the new GridStack.addGrid()
542
+ * to recreate everything from scratch. GridStackOptions.children would then contain the widget list instead.
543
+ * @param saveCB callback for each node -> widget, so application can insert additional data to be saved into the widget data structure.
544
+ * @returns list of widgets or full grid option, including .children list of widgets
545
+ */
546
+ GridStack.prototype.save = function (saveContent, saveGridOpt, saveCB) {
547
+ if (saveContent === void 0) { saveContent = true; }
548
+ if (saveGridOpt === void 0) { saveGridOpt = false; }
549
+ if (saveCB === void 0) { saveCB = GridStack.saveCB; }
550
+ // return copied GridStackWidget (with optionally .el) we can modify at will...
551
+ var list = this.engine.save(saveContent, saveCB);
552
+ // check for HTML content and nested grids
553
+ list.forEach(function (n) {
554
+ var _a;
555
+ if (saveContent && n.el && !n.subGrid && !saveCB) { // sub-grid are saved differently, not plain content
556
+ var sub = n.el.querySelector('.grid-stack-item-content');
557
+ n.content = sub ? sub.innerHTML : undefined;
558
+ if (!n.content)
559
+ delete n.content;
560
+ }
561
+ else {
562
+ if (!saveContent && !saveCB) {
563
+ delete n.content;
564
+ }
565
+ // check for nested grid
566
+ if ((_a = n.subGrid) === null || _a === void 0 ? void 0 : _a.el) {
567
+ var listOrOpt = n.subGrid.save(saveContent, saveGridOpt, saveCB);
568
+ n.subGridOpts = (saveGridOpt ? listOrOpt : { children: listOrOpt });
569
+ delete n.subGrid;
570
+ }
571
+ }
572
+ delete n.el;
573
+ });
574
+ // check if save entire grid options (needed for recursive) + children...
575
+ if (saveGridOpt) {
576
+ var o = utils_1.Utils.cloneDeep(this.opts);
577
+ // delete default values that will be recreated on launch
578
+ if (o.marginBottom === o.marginTop && o.marginRight === o.marginLeft && o.marginTop === o.marginRight) {
579
+ o.margin = o.marginTop;
580
+ delete o.marginTop;
581
+ delete o.marginRight;
582
+ delete o.marginBottom;
583
+ delete o.marginLeft;
584
+ }
585
+ if (o.rtl === (this.el.style.direction === 'rtl')) {
586
+ o.rtl = 'auto';
587
+ }
588
+ if (this._isAutoCellHeight) {
589
+ o.cellHeight = 'auto';
590
+ }
591
+ if (this._autoColumn) {
592
+ o.column = 'auto';
593
+ delete o.disableOneColumnMode;
594
+ }
595
+ var origShow = o._alwaysShowResizeHandle;
596
+ delete o._alwaysShowResizeHandle;
597
+ if (origShow !== undefined) {
598
+ o.alwaysShowResizeHandle = origShow;
599
+ }
600
+ else {
601
+ delete o.alwaysShowResizeHandle;
602
+ }
603
+ utils_1.Utils.removeInternalAndSame(o, types_1.gridDefaults);
604
+ o.children = list;
605
+ return o;
606
+ }
607
+ return list;
608
+ };
609
+ /**
610
+ * load the widgets from a list. This will call update() on each (matching by id) or add/remove widgets that are not there.
611
+ *
612
+ * @param layout list of widgets definition to update/create
613
+ * @param addAndRemove boolean (default true) or callback method can be passed to control if and how missing widgets can be added/removed, giving
614
+ * the user control of insertion.
615
+ *
616
+ * @example
617
+ * see http://gridstackjs.com/demo/serialization.html
618
+ **/
619
+ GridStack.prototype.load = function (layout, addRemove) {
620
+ var _this = this;
621
+ if (addRemove === void 0) { addRemove = GridStack.addRemoveCB || true; }
622
+ var items = GridStack.Utils.sort(__spreadArray([], layout, true), -1, this._prevColumn || this.getColumn()); // make copy before we mod/sort
623
+ this._insertNotAppend = true; // since create in reverse order...
624
+ // if we're loading a layout into for example 1 column (_prevColumn is set only when going to 1) and items don't fit, make sure to save
625
+ // the original wanted layout so we can scale back up correctly #1471
626
+ if (this._prevColumn && this._prevColumn !== this.opts.column && items.some(function (n) { return (n.x + n.w) > _this.opts.column; })) {
627
+ this._ignoreLayoutsNodeChange = true; // skip layout update
628
+ this.engine.cacheLayout(items, this._prevColumn, true);
629
+ }
630
+ // if given a different callback, temporally set it as global option so creating will use it
631
+ var prevCB = GridStack.addRemoveCB;
632
+ if (typeof (addRemove) === 'function')
633
+ GridStack.addRemoveCB = addRemove;
634
+ var removed = [];
635
+ this.batchUpdate();
636
+ // see if any items are missing from new layout and need to be removed first
637
+ if (addRemove) {
638
+ var copyNodes = __spreadArray([], this.engine.nodes, true); // don't loop through array you modify
639
+ copyNodes.forEach(function (n) {
640
+ var item = items.find(function (w) { return n.id === w.id; });
641
+ if (!item) {
642
+ if (GridStack.addRemoveCB)
643
+ GridStack.addRemoveCB(_this.el, n, false, false);
644
+ removed.push(n); // batch keep track
645
+ _this.removeWidget(n.el, true, false);
646
+ }
647
+ });
648
+ }
649
+ // now add/update the widgets
650
+ items.forEach(function (w) {
651
+ var _a;
652
+ var item = (w.id || w.id === 0) ? _this.engine.nodes.find(function (n) { return n.id === w.id; }) : undefined;
653
+ if (item) {
654
+ _this.update(item.el, w);
655
+ if ((_a = w.subGridOpts) === null || _a === void 0 ? void 0 : _a.children) { // update any sub grid as well
656
+ var sub = item.el.querySelector('.grid-stack');
657
+ if (sub && sub.gridstack) {
658
+ sub.gridstack.load(w.subGridOpts.children); // TODO: support updating grid options ?
659
+ _this._insertNotAppend = true; // got reset by above call
660
+ }
661
+ }
662
+ }
663
+ else if (addRemove) {
664
+ _this.addWidget(w);
665
+ }
666
+ });
667
+ this.engine.removedNodes = removed;
668
+ this.batchUpdate(false);
669
+ // after commit, clear that flag
670
+ delete this._ignoreLayoutsNodeChange;
671
+ delete this._insertNotAppend;
672
+ prevCB ? GridStack.addRemoveCB = prevCB : delete GridStack.addRemoveCB;
673
+ return this;
674
+ };
675
+ /**
676
+ * use before calling a bunch of `addWidget()` to prevent un-necessary relayouts in between (more efficient)
677
+ * and get a single event callback. You will see no changes until `batchUpdate(false)` is called.
678
+ */
679
+ GridStack.prototype.batchUpdate = function (flag) {
680
+ if (flag === void 0) { flag = true; }
681
+ this.engine.batchUpdate(flag);
682
+ if (!flag) {
683
+ this._triggerRemoveEvent();
684
+ this._triggerAddEvent();
685
+ this._triggerChangeEvent();
686
+ }
687
+ return this;
688
+ };
689
+ /**
690
+ * Gets current cell height.
691
+ */
692
+ GridStack.prototype.getCellHeight = function (forcePixel) {
693
+ if (forcePixel === void 0) { forcePixel = false; }
694
+ if (this.opts.cellHeight && this.opts.cellHeight !== 'auto' &&
695
+ (!forcePixel || !this.opts.cellHeightUnit || this.opts.cellHeightUnit === 'px')) {
696
+ return this.opts.cellHeight;
697
+ }
698
+ // else get first cell height
699
+ var el = this.el.querySelector('.' + this.opts.itemClass);
700
+ if (el) {
701
+ var height = utils_1.Utils.toNumber(el.getAttribute('gs-h'));
702
+ return Math.round(el.offsetHeight / height);
703
+ }
704
+ // else do entire grid and # of rows (but doesn't work if min-height is the actual constrain)
705
+ var rows = parseInt(this.el.getAttribute('gs-current-row'));
706
+ return rows ? Math.round(this.el.getBoundingClientRect().height / rows) : this.opts.cellHeight;
707
+ };
708
+ /**
709
+ * Update current cell height - see `GridStackOptions.cellHeight` for format.
710
+ * This method rebuilds an internal CSS style sheet.
711
+ * Note: You can expect performance issues if call this method too often.
712
+ *
713
+ * @param val the cell height. If not passed (undefined), cells content will be made square (match width minus margin),
714
+ * if pass 0 the CSS will be generated by the application instead.
715
+ * @param update (Optional) if false, styles will not be updated
716
+ *
717
+ * @example
718
+ * grid.cellHeight(100); // same as 100px
719
+ * grid.cellHeight('70px');
720
+ * grid.cellHeight(grid.cellWidth() * 1.2);
721
+ */
722
+ GridStack.prototype.cellHeight = function (val, update) {
723
+ if (update === void 0) { update = true; }
724
+ // if not called internally, check if we're changing mode
725
+ if (update && val !== undefined) {
726
+ if (this._isAutoCellHeight !== (val === 'auto')) {
727
+ this._isAutoCellHeight = (val === 'auto');
728
+ this._updateWindowResizeEvent();
729
+ }
730
+ }
731
+ if (val === 'initial' || val === 'auto') {
732
+ val = undefined;
733
+ }
734
+ // make item content be square
735
+ if (val === undefined) {
736
+ var marginDiff = -this.opts.marginRight - this.opts.marginLeft
737
+ + this.opts.marginTop + this.opts.marginBottom;
738
+ val = this.cellWidth() + marginDiff;
739
+ }
740
+ var data = utils_1.Utils.parseHeight(val);
741
+ if (this.opts.cellHeightUnit === data.unit && this.opts.cellHeight === data.h) {
742
+ return this;
743
+ }
744
+ this.opts.cellHeightUnit = data.unit;
745
+ this.opts.cellHeight = data.h;
746
+ if (update) {
747
+ this._updateStyles(true); // true = force re-create for current # of rows
748
+ }
749
+ return this;
750
+ };
751
+ /** Gets current cell width. */
752
+ GridStack.prototype.cellWidth = function () {
753
+ return this._widthOrContainer() / this.getColumn();
754
+ };
755
+ /** return our expected width (or parent) for 1 column check */
756
+ GridStack.prototype._widthOrContainer = function () {
757
+ // use `offsetWidth` or `clientWidth` (no scrollbar) ?
758
+ // https://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively
759
+ return (this.el.clientWidth || this.el.parentElement.clientWidth || window.innerWidth);
760
+ };
761
+ /** re-layout grid items to reclaim any empty space */
762
+ GridStack.prototype.compact = function () {
763
+ this.engine.compact();
764
+ this._triggerChangeEvent();
765
+ return this;
766
+ };
767
+ /**
768
+ * set the number of columns in the grid. Will update existing widgets to conform to new number of columns,
769
+ * as well as cache the original layout so you can revert back to previous positions without loss.
770
+ * Requires `gridstack-extra.css` or `gridstack-extra.min.css` for [2-11],
771
+ * else you will need to generate correct CSS (see https://github.com/gridstack/gridstack.js#change-grid-columns)
772
+ * @param column - Integer > 0 (default 12).
773
+ * @param layout specify the type of re-layout that will happen (position, size, etc...).
774
+ * Note: items will never be outside of the current column boundaries. default (moveScale). Ignored for 1 column
775
+ */
776
+ GridStack.prototype.column = function (column, layout) {
777
+ if (layout === void 0) { layout = 'moveScale'; }
778
+ if (column < 1 || this.opts.column === column)
779
+ return this;
780
+ var oldColumn = this.getColumn();
781
+ // if we go into 1 column mode (which happens if we're sized less than minW unless disableOneColumnMode is on)
782
+ // then remember the original columns so we can restore.
783
+ if (column === 1) {
784
+ this._prevColumn = oldColumn;
785
+ }
786
+ else {
787
+ delete this._prevColumn;
788
+ }
789
+ this.el.classList.remove('grid-stack-' + oldColumn);
790
+ this.el.classList.add('grid-stack-' + column);
791
+ this.opts.column = this.engine.column = column;
792
+ // update the items now - see if the dom order nodes should be passed instead (else default to current list)
793
+ var domNodes;
794
+ if (column === 1 && this.opts.oneColumnModeDomSort) {
795
+ domNodes = [];
796
+ this.getGridItems().forEach(function (el) {
797
+ if (el.gridstackNode) {
798
+ domNodes.push(el.gridstackNode);
799
+ }
800
+ });
801
+ if (!domNodes.length) {
802
+ domNodes = undefined;
803
+ }
804
+ }
805
+ this.engine.updateNodeWidths(oldColumn, column, domNodes, layout);
806
+ if (this._isAutoCellHeight)
807
+ this.cellHeight();
808
+ // and trigger our event last...
809
+ this._ignoreLayoutsNodeChange = true; // skip layout update
810
+ this._triggerChangeEvent();
811
+ delete this._ignoreLayoutsNodeChange;
812
+ return this;
813
+ };
814
+ /**
815
+ * get the number of columns in the grid (default 12)
816
+ */
817
+ GridStack.prototype.getColumn = function () {
818
+ return this.opts.column;
819
+ };
820
+ /** returns an array of grid HTML elements (no placeholder) - used to iterate through our children in DOM order */
821
+ GridStack.prototype.getGridItems = function () {
822
+ var _this = this;
823
+ return Array.from(this.el.children)
824
+ .filter(function (el) { return el.matches('.' + _this.opts.itemClass) && !el.matches('.' + _this.opts.placeholderClass); });
825
+ };
826
+ /**
827
+ * Destroys a grid instance. DO NOT CALL any methods or access any vars after this as it will free up members.
828
+ * @param removeDOM if `false` grid and items HTML elements will not be removed from the DOM (Optional. Default `true`).
829
+ */
830
+ GridStack.prototype.destroy = function (removeDOM) {
831
+ if (removeDOM === void 0) { removeDOM = true; }
832
+ if (!this.el)
833
+ return; // prevent multiple calls
834
+ this._updateWindowResizeEvent(true);
835
+ this.setStatic(true, false); // permanently removes DD but don't set CSS class (we're going away)
836
+ this.setAnimation(false);
837
+ if (!removeDOM) {
838
+ this.removeAll(removeDOM);
839
+ this.el.classList.remove(this._styleSheetClass);
840
+ this.el.removeAttribute('gs-current-row');
841
+ }
842
+ else {
843
+ this.el.parentNode.removeChild(this.el);
844
+ }
845
+ this._removeStylesheet();
846
+ if (this.parentGridItem)
847
+ delete this.parentGridItem.subGrid;
848
+ delete this.parentGridItem;
849
+ delete this.opts;
850
+ delete this._placeholder;
851
+ delete this.engine;
852
+ delete this.el.gridstack; // remove circular dependency that would prevent a freeing
853
+ delete this.el;
854
+ return this;
855
+ };
856
+ /**
857
+ * enable/disable floating widgets (default: `false`) See [example](http://gridstackjs.com/demo/float.html)
858
+ */
859
+ GridStack.prototype.float = function (val) {
860
+ if (this.opts.float !== val) {
861
+ this.opts.float = this.engine.float = val;
862
+ this._triggerChangeEvent();
863
+ }
864
+ return this;
865
+ };
866
+ /**
867
+ * get the current float mode
868
+ */
869
+ GridStack.prototype.getFloat = function () {
870
+ return this.engine.float;
871
+ };
872
+ /**
873
+ * Get the position of the cell under a pixel on screen.
874
+ * @param position the position of the pixel to resolve in
875
+ * absolute coordinates, as an object with top and left properties
876
+ * @param useDocRelative if true, value will be based on document position vs parent position (Optional. Default false).
877
+ * Useful when grid is within `position: relative` element
878
+ *
879
+ * Returns an object with properties `x` and `y` i.e. the column and row in the grid.
880
+ */
881
+ GridStack.prototype.getCellFromPixel = function (position, useDocRelative) {
882
+ if (useDocRelative === void 0) { useDocRelative = false; }
883
+ var box = this.el.getBoundingClientRect();
884
+ // console.log(`getBoundingClientRect left: ${box.left} top: ${box.top} w: ${box.w} h: ${box.h}`)
885
+ var containerPos;
886
+ if (useDocRelative) {
887
+ containerPos = { top: box.top + document.documentElement.scrollTop, left: box.left };
888
+ // console.log(`getCellFromPixel scrollTop: ${document.documentElement.scrollTop}`)
889
+ }
890
+ else {
891
+ containerPos = { top: this.el.offsetTop, left: this.el.offsetLeft };
892
+ // console.log(`getCellFromPixel offsetTop: ${containerPos.left} offsetLeft: ${containerPos.top}`)
893
+ }
894
+ var relativeLeft = position.left - containerPos.left;
895
+ var relativeTop = position.top - containerPos.top;
896
+ var columnWidth = (box.width / this.getColumn());
897
+ var rowHeight = (box.height / parseInt(this.el.getAttribute('gs-current-row')));
898
+ return { x: Math.floor(relativeLeft / columnWidth), y: Math.floor(relativeTop / rowHeight) };
899
+ };
900
+ /** returns the current number of rows, which will be at least `minRow` if set */
901
+ GridStack.prototype.getRow = function () {
902
+ return Math.max(this.engine.getRow(), this.opts.minRow);
903
+ };
904
+ /**
905
+ * Checks if specified area is empty.
906
+ * @param x the position x.
907
+ * @param y the position y.
908
+ * @param w the width of to check
909
+ * @param h the height of to check
910
+ */
911
+ GridStack.prototype.isAreaEmpty = function (x, y, w, h) {
912
+ return this.engine.isAreaEmpty(x, y, w, h);
913
+ };
914
+ /**
915
+ * If you add elements to your grid by hand, you have to tell gridstack afterwards to make them widgets.
916
+ * If you want gridstack to add the elements for you, use `addWidget()` instead.
917
+ * Makes the given element a widget and returns it.
918
+ * @param els widget or single selector to convert.
919
+ *
920
+ * @example
921
+ * let grid = GridStack.init();
922
+ * grid.el.appendChild('<div id="gsi-1" gs-w="3"></div>');
923
+ * grid.makeWidget('#gsi-1');
924
+ */
925
+ GridStack.prototype.makeWidget = function (els) {
926
+ var el = GridStack.getElement(els);
927
+ this._prepareElement(el, true);
928
+ this._updateContainerHeight();
929
+ this._triggerAddEvent();
930
+ this._triggerChangeEvent();
931
+ return el;
932
+ };
933
+ /**
934
+ * Event handler that extracts our CustomEvent data out automatically for receiving custom
935
+ * notifications (see doc for supported events)
936
+ * @param name of the event (see possible values) or list of names space separated
937
+ * @param callback function called with event and optional second/third param
938
+ * (see README documentation for each signature).
939
+ *
940
+ * @example
941
+ * grid.on('added', function(e, items) { log('added ', items)} );
942
+ * or
943
+ * grid.on('added removed change', function(e, items) { log(e.type, items)} );
944
+ *
945
+ * Note: in some cases it is the same as calling native handler and parsing the event.
946
+ * grid.el.addEventListener('added', function(event) { log('added ', event.detail)} );
947
+ *
948
+ */
949
+ GridStack.prototype.on = function (name, callback) {
950
+ var _this = this;
951
+ // check for array of names being passed instead
952
+ if (name.indexOf(' ') !== -1) {
953
+ var names = name.split(' ');
954
+ names.forEach(function (name) { return _this.on(name, callback); });
955
+ return this;
956
+ }
957
+ if (name === 'change' || name === 'added' || name === 'removed' || name === 'enable' || name === 'disable') {
958
+ // native CustomEvent handlers - cash the generic handlers so we can easily remove
959
+ var noData = (name === 'enable' || name === 'disable');
960
+ if (noData) {
961
+ this._gsEventHandler[name] = function (event) { return callback(event); };
962
+ }
963
+ else {
964
+ this._gsEventHandler[name] = function (event) { return callback(event, event.detail); };
965
+ }
966
+ this.el.addEventListener(name, this._gsEventHandler[name]);
967
+ }
968
+ else if (name === 'drag' || name === 'dragstart' || name === 'dragstop' || name === 'resizestart' || name === 'resize' || name === 'resizestop' || name === 'dropped') {
969
+ // drag&drop stop events NEED to be call them AFTER we update node attributes so handle them ourself.
970
+ // do same for start event to make it easier...
971
+ this._gsEventHandler[name] = callback;
972
+ }
973
+ else {
974
+ console.log('GridStack.on(' + name + ') event not supported, but you can still use $(".grid-stack").on(...) while jquery-ui is still used internally.');
975
+ }
976
+ return this;
977
+ };
978
+ /**
979
+ * unsubscribe from the 'on' event below
980
+ * @param name of the event (see possible values)
981
+ */
982
+ GridStack.prototype.off = function (name) {
983
+ var _this = this;
984
+ // check for array of names being passed instead
985
+ if (name.indexOf(' ') !== -1) {
986
+ var names = name.split(' ');
987
+ names.forEach(function (name) { return _this.off(name); });
988
+ return this;
989
+ }
990
+ if (name === 'change' || name === 'added' || name === 'removed' || name === 'enable' || name === 'disable') {
991
+ // remove native CustomEvent handlers
992
+ if (this._gsEventHandler[name]) {
993
+ this.el.removeEventListener(name, this._gsEventHandler[name]);
994
+ }
995
+ }
996
+ delete this._gsEventHandler[name];
997
+ return this;
998
+ };
999
+ /**
1000
+ * Removes widget from the grid.
1001
+ * @param el widget or selector to modify
1002
+ * @param removeDOM if `false` DOM element won't be removed from the tree (Default? true).
1003
+ * @param triggerEvent if `false` (quiet mode) element will not be added to removed list and no 'removed' callbacks will be called (Default? true).
1004
+ */
1005
+ GridStack.prototype.removeWidget = function (els, removeDOM, triggerEvent) {
1006
+ var _this = this;
1007
+ if (removeDOM === void 0) { removeDOM = true; }
1008
+ if (triggerEvent === void 0) { triggerEvent = true; }
1009
+ GridStack.getElements(els).forEach(function (el) {
1010
+ if (el.parentElement && el.parentElement !== _this.el)
1011
+ return; // not our child!
1012
+ var node = el.gridstackNode;
1013
+ // For Meteor support: https://github.com/gridstack/gridstack.js/pull/272
1014
+ if (!node) {
1015
+ node = _this.engine.nodes.find(function (n) { return el === n.el; });
1016
+ }
1017
+ if (!node)
1018
+ return;
1019
+ // remove our DOM data (circular link) and drag&drop permanently
1020
+ delete el.gridstackNode;
1021
+ _this._removeDD(el);
1022
+ _this.engine.removeNode(node, removeDOM, triggerEvent);
1023
+ if (removeDOM && el.parentElement) {
1024
+ el.remove(); // in batch mode engine.removeNode doesn't call back to remove DOM
1025
+ }
1026
+ });
1027
+ if (triggerEvent) {
1028
+ this._triggerRemoveEvent();
1029
+ this._triggerChangeEvent();
1030
+ }
1031
+ return this;
1032
+ };
1033
+ /**
1034
+ * Removes all widgets from the grid.
1035
+ * @param removeDOM if `false` DOM elements won't be removed from the tree (Default? `true`).
1036
+ */
1037
+ GridStack.prototype.removeAll = function (removeDOM) {
1038
+ var _this = this;
1039
+ if (removeDOM === void 0) { removeDOM = true; }
1040
+ // always remove our DOM data (circular link) before list gets emptied and drag&drop permanently
1041
+ this.engine.nodes.forEach(function (n) {
1042
+ delete n.el.gridstackNode;
1043
+ _this._removeDD(n.el);
1044
+ });
1045
+ this.engine.removeAll(removeDOM);
1046
+ this._triggerRemoveEvent();
1047
+ return this;
1048
+ };
1049
+ /**
1050
+ * Toggle the grid animation state. Toggles the `grid-stack-animate` class.
1051
+ * @param doAnimate if true the grid will animate.
1052
+ */
1053
+ GridStack.prototype.setAnimation = function (doAnimate) {
1054
+ if (doAnimate) {
1055
+ this.el.classList.add('grid-stack-animate');
1056
+ }
1057
+ else {
1058
+ this.el.classList.remove('grid-stack-animate');
1059
+ }
1060
+ return this;
1061
+ };
1062
+ /**
1063
+ * Toggle the grid static state, which permanently removes/add Drag&Drop support, unlike disable()/enable() that just turns it off/on.
1064
+ * Also toggle the grid-stack-static class.
1065
+ * @param val if true the grid become static.
1066
+ * @param updateClass true (default) if css class gets updated
1067
+ * @param recurse true (default) if sub-grids also get updated
1068
+ */
1069
+ GridStack.prototype.setStatic = function (val, updateClass, recurse) {
1070
+ var _this = this;
1071
+ if (updateClass === void 0) { updateClass = true; }
1072
+ if (recurse === void 0) { recurse = true; }
1073
+ if (this.opts.staticGrid === val)
1074
+ return this;
1075
+ this.opts.staticGrid = val;
1076
+ this._setupRemoveDrop();
1077
+ this._setupAcceptWidget();
1078
+ this.engine.nodes.forEach(function (n) {
1079
+ _this._prepareDragDropByNode(n); // either delete or init Drag&drop
1080
+ if (n.subGrid && recurse)
1081
+ n.subGrid.setStatic(val, updateClass, recurse);
1082
+ });
1083
+ if (updateClass) {
1084
+ this._setStaticClass();
1085
+ }
1086
+ return this;
1087
+ };
1088
+ /**
1089
+ * Updates widget position/size and other info. Note: if you need to call this on all nodes, use load() instead which will update what changed.
1090
+ * @param els widget or selector of objects to modify (note: setting the same x,y for multiple items will be indeterministic and likely unwanted)
1091
+ * @param opt new widget options (x,y,w,h, etc..). Only those set will be updated.
1092
+ */
1093
+ GridStack.prototype.update = function (els, opt) {
1094
+ var _this = this;
1095
+ // support legacy call for now ?
1096
+ if (arguments.length > 2) {
1097
+ console.warn('gridstack.ts: `update(el, x, y, w, h)` is deprecated. Use `update(el, {x, w, content, ...})`. It will be removed soon');
1098
+ // eslint-disable-next-line prefer-rest-params
1099
+ var a = arguments, i = 1;
1100
+ opt = { x: a[i++], y: a[i++], w: a[i++], h: a[i++] };
1101
+ return this.update(els, opt);
1102
+ }
1103
+ GridStack.getElements(els).forEach(function (el) {
1104
+ if (!el || !el.gridstackNode)
1105
+ return;
1106
+ var n = el.gridstackNode;
1107
+ var w = utils_1.Utils.cloneDeep(opt); // make a copy we can modify in case they re-use it or multiple items
1108
+ delete w.autoPosition;
1109
+ // move/resize widget if anything changed
1110
+ var keys = ['x', 'y', 'w', 'h'];
1111
+ var m;
1112
+ if (keys.some(function (k) { return w[k] !== undefined && w[k] !== n[k]; })) {
1113
+ m = {};
1114
+ keys.forEach(function (k) {
1115
+ m[k] = (w[k] !== undefined) ? w[k] : n[k];
1116
+ delete w[k];
1117
+ });
1118
+ }
1119
+ // for a move as well IFF there is any min/max fields set
1120
+ if (!m && (w.minW || w.minH || w.maxW || w.maxH)) {
1121
+ m = {}; // will use node position but validate values
1122
+ }
1123
+ // check for content changing
1124
+ if (w.content) {
1125
+ var sub = el.querySelector('.grid-stack-item-content');
1126
+ if (sub && sub.innerHTML !== w.content) {
1127
+ sub.innerHTML = w.content;
1128
+ }
1129
+ delete w.content;
1130
+ }
1131
+ // any remaining fields are assigned, but check for dragging changes, resize constrain
1132
+ var changed = false;
1133
+ var ddChanged = false;
1134
+ for (var key in w) {
1135
+ if (key[0] !== '_' && n[key] !== w[key]) {
1136
+ n[key] = w[key];
1137
+ changed = true;
1138
+ ddChanged = ddChanged || (!_this.opts.staticGrid && (key === 'noResize' || key === 'noMove' || key === 'locked'));
1139
+ }
1140
+ }
1141
+ utils_1.Utils.sanitizeMinMax(n);
1142
+ // finally move the widget
1143
+ if (m) {
1144
+ _this.engine.cleanNodes()
1145
+ .beginUpdate(n)
1146
+ .moveNode(n, m);
1147
+ _this._updateContainerHeight();
1148
+ _this._triggerChangeEvent();
1149
+ _this.engine.endUpdate();
1150
+ }
1151
+ if (changed) { // move will only update x,y,w,h so update the rest too
1152
+ _this._writeAttr(el, n);
1153
+ }
1154
+ if (ddChanged) {
1155
+ _this._prepareDragDropByNode(n);
1156
+ }
1157
+ });
1158
+ return this;
1159
+ };
1160
+ /**
1161
+ * Updates the margins which will set all 4 sides at once - see `GridStackOptions.margin` for format options (CSS string format of 1,2,4 values or single number).
1162
+ * @param value margin value
1163
+ */
1164
+ GridStack.prototype.margin = function (value) {
1165
+ var isMultiValue = (typeof value === 'string' && value.split(' ').length > 1);
1166
+ // check if we can skip re-creating our CSS file... won't check if multi values (too much hassle)
1167
+ if (!isMultiValue) {
1168
+ var data = utils_1.Utils.parseHeight(value);
1169
+ if (this.opts.marginUnit === data.unit && this.opts.margin === data.h)
1170
+ return;
1171
+ }
1172
+ // re-use existing margin handling
1173
+ this.opts.margin = value;
1174
+ this.opts.marginTop = this.opts.marginBottom = this.opts.marginLeft = this.opts.marginRight = undefined;
1175
+ this._initMargin();
1176
+ this._updateStyles(true); // true = force re-create
1177
+ return this;
1178
+ };
1179
+ /** returns current margin number value (undefined if 4 sides don't match) */
1180
+ GridStack.prototype.getMargin = function () { return this.opts.margin; };
1181
+ /**
1182
+ * Returns true if the height of the grid will be less than the vertical
1183
+ * constraint. Always returns true if grid doesn't have height constraint.
1184
+ * @param node contains x,y,w,h,auto-position options
1185
+ *
1186
+ * @example
1187
+ * if (grid.willItFit(newWidget)) {
1188
+ * grid.addWidget(newWidget);
1189
+ * } else {
1190
+ * alert('Not enough free space to place the widget');
1191
+ * }
1192
+ */
1193
+ GridStack.prototype.willItFit = function (node) {
1194
+ // support legacy call for now
1195
+ if (arguments.length > 1) {
1196
+ console.warn('gridstack.ts: `willItFit(x,y,w,h,autoPosition)` is deprecated. Use `willItFit({x, y,...})`. It will be removed soon');
1197
+ // eslint-disable-next-line prefer-rest-params
1198
+ var a = arguments, i = 0, w = { x: a[i++], y: a[i++], w: a[i++], h: a[i++], autoPosition: a[i++] };
1199
+ return this.willItFit(w);
1200
+ }
1201
+ return this.engine.willItFit(node);
1202
+ };
1203
+ /** @internal */
1204
+ GridStack.prototype._triggerChangeEvent = function () {
1205
+ if (this.engine.batchMode)
1206
+ return this;
1207
+ var elements = this.engine.getDirtyNodes(true); // verify they really changed
1208
+ if (elements && elements.length) {
1209
+ if (!this._ignoreLayoutsNodeChange) {
1210
+ this.engine.layoutsNodesChange(elements);
1211
+ }
1212
+ this._triggerEvent('change', elements);
1213
+ }
1214
+ this.engine.saveInitial(); // we called, now reset initial values & dirty flags
1215
+ return this;
1216
+ };
1217
+ /** @internal */
1218
+ GridStack.prototype._triggerAddEvent = function () {
1219
+ var _a;
1220
+ if (this.engine.batchMode)
1221
+ return this;
1222
+ if ((_a = this.engine.addedNodes) === null || _a === void 0 ? void 0 : _a.length) {
1223
+ if (!this._ignoreLayoutsNodeChange) {
1224
+ this.engine.layoutsNodesChange(this.engine.addedNodes);
1225
+ }
1226
+ // prevent added nodes from also triggering 'change' event (which is called next)
1227
+ this.engine.addedNodes.forEach(function (n) { delete n._dirty; });
1228
+ this._triggerEvent('added', this.engine.addedNodes);
1229
+ this.engine.addedNodes = [];
1230
+ }
1231
+ return this;
1232
+ };
1233
+ /** @internal */
1234
+ GridStack.prototype._triggerRemoveEvent = function () {
1235
+ var _a;
1236
+ if (this.engine.batchMode)
1237
+ return this;
1238
+ if ((_a = this.engine.removedNodes) === null || _a === void 0 ? void 0 : _a.length) {
1239
+ this._triggerEvent('removed', this.engine.removedNodes);
1240
+ this.engine.removedNodes = [];
1241
+ }
1242
+ return this;
1243
+ };
1244
+ /** @internal */
1245
+ GridStack.prototype._triggerEvent = function (type, data) {
1246
+ var event = data ? new CustomEvent(type, { bubbles: false, detail: data }) : new Event(type);
1247
+ this.el.dispatchEvent(event);
1248
+ return this;
1249
+ };
1250
+ /** @internal called to delete the current dynamic style sheet used for our layout */
1251
+ GridStack.prototype._removeStylesheet = function () {
1252
+ if (this._styles) {
1253
+ utils_1.Utils.removeStylesheet(this._styleSheetClass);
1254
+ delete this._styles;
1255
+ }
1256
+ return this;
1257
+ };
1258
+ /** @internal updated/create the CSS styles for row based layout and initial margin setting */
1259
+ GridStack.prototype._updateStyles = function (forceUpdate, maxH) {
1260
+ if (forceUpdate === void 0) { forceUpdate = false; }
1261
+ // call to delete existing one if we change cellHeight / margin
1262
+ if (forceUpdate) {
1263
+ this._removeStylesheet();
1264
+ }
1265
+ if (!maxH)
1266
+ maxH = this.getRow();
1267
+ this._updateContainerHeight();
1268
+ // if user is telling us they will handle the CSS themselves by setting heights to 0. Do we need this opts really ??
1269
+ if (this.opts.cellHeight === 0) {
1270
+ return this;
1271
+ }
1272
+ var cellHeight = this.opts.cellHeight;
1273
+ var cellHeightUnit = this.opts.cellHeightUnit;
1274
+ var prefix = ".".concat(this._styleSheetClass, " > .").concat(this.opts.itemClass);
1275
+ // create one as needed
1276
+ if (!this._styles) {
1277
+ // insert style to parent (instead of 'head' by default) to support WebComponent
1278
+ var styleLocation = this.opts.styleInHead ? undefined : this.el.parentNode;
1279
+ this._styles = utils_1.Utils.createStylesheet(this._styleSheetClass, styleLocation, {
1280
+ nonce: this.opts.nonce,
1281
+ });
1282
+ if (!this._styles)
1283
+ return this;
1284
+ this._styles._max = 0;
1285
+ // these are done once only
1286
+ utils_1.Utils.addCSSRule(this._styles, prefix, "min-height: ".concat(cellHeight).concat(cellHeightUnit));
1287
+ // content margins
1288
+ var top_1 = this.opts.marginTop + this.opts.marginUnit;
1289
+ var bottom = this.opts.marginBottom + this.opts.marginUnit;
1290
+ var right = this.opts.marginRight + this.opts.marginUnit;
1291
+ var left = this.opts.marginLeft + this.opts.marginUnit;
1292
+ var content = "".concat(prefix, " > .grid-stack-item-content");
1293
+ var placeholder = ".".concat(this._styleSheetClass, " > .grid-stack-placeholder > .placeholder-content");
1294
+ utils_1.Utils.addCSSRule(this._styles, content, "top: ".concat(top_1, "; right: ").concat(right, "; bottom: ").concat(bottom, "; left: ").concat(left, ";"));
1295
+ utils_1.Utils.addCSSRule(this._styles, placeholder, "top: ".concat(top_1, "; right: ").concat(right, "; bottom: ").concat(bottom, "; left: ").concat(left, ";"));
1296
+ // resize handles offset (to match margin)
1297
+ utils_1.Utils.addCSSRule(this._styles, "".concat(prefix, " > .ui-resizable-ne"), "right: ".concat(right));
1298
+ utils_1.Utils.addCSSRule(this._styles, "".concat(prefix, " > .ui-resizable-e"), "right: ".concat(right));
1299
+ utils_1.Utils.addCSSRule(this._styles, "".concat(prefix, " > .ui-resizable-se"), "right: ".concat(right, "; bottom: ").concat(bottom));
1300
+ utils_1.Utils.addCSSRule(this._styles, "".concat(prefix, " > .ui-resizable-nw"), "left: ".concat(left));
1301
+ utils_1.Utils.addCSSRule(this._styles, "".concat(prefix, " > .ui-resizable-w"), "left: ".concat(left));
1302
+ utils_1.Utils.addCSSRule(this._styles, "".concat(prefix, " > .ui-resizable-sw"), "left: ".concat(left, "; bottom: ").concat(bottom));
1303
+ }
1304
+ // now update the height specific fields
1305
+ maxH = maxH || this._styles._max;
1306
+ if (maxH > this._styles._max) {
1307
+ var getHeight = function (rows) { return (cellHeight * rows) + cellHeightUnit; };
1308
+ for (var i = this._styles._max + 1; i <= maxH; i++) { // start at 1
1309
+ var h = getHeight(i);
1310
+ utils_1.Utils.addCSSRule(this._styles, "".concat(prefix, "[gs-y=\"").concat(i - 1, "\"]"), "top: ".concat(getHeight(i - 1))); // start at 0
1311
+ utils_1.Utils.addCSSRule(this._styles, "".concat(prefix, "[gs-h=\"").concat(i, "\"]"), "height: ".concat(h));
1312
+ }
1313
+ this._styles._max = maxH;
1314
+ }
1315
+ return this;
1316
+ };
1317
+ /** @internal */
1318
+ GridStack.prototype._updateContainerHeight = function () {
1319
+ if (!this.engine || this.engine.batchMode)
1320
+ return this;
1321
+ var row = this.getRow() + this._extraDragRow; // checks for minRow already
1322
+ // check for css min height
1323
+ // Note: we don't handle %,rem correctly so comment out, beside we don't need need to create un-necessary
1324
+ // rows as the CSS will make us bigger than our set height if needed... not sure why we had this.
1325
+ // let cssMinHeight = parseInt(getComputedStyle(this.el)['min-height']);
1326
+ // if (cssMinHeight > 0) {
1327
+ // let minRow = Math.round(cssMinHeight / this.getCellHeight(true));
1328
+ // if (row < minRow) {
1329
+ // row = minRow;
1330
+ // }
1331
+ // }
1332
+ this.el.setAttribute('gs-current-row', String(row));
1333
+ if (row === 0) {
1334
+ this.el.style.removeProperty('min-height');
1335
+ return this;
1336
+ }
1337
+ var cellHeight = this.opts.cellHeight;
1338
+ var unit = this.opts.cellHeightUnit;
1339
+ if (!cellHeight)
1340
+ return this;
1341
+ this.el.style.minHeight = row * cellHeight + unit;
1342
+ return this;
1343
+ };
1344
+ /** @internal */
1345
+ GridStack.prototype._prepareElement = function (el, triggerAddEvent, node) {
1346
+ if (triggerAddEvent === void 0) { triggerAddEvent = false; }
1347
+ el.classList.add(this.opts.itemClass);
1348
+ node = node || this._readAttr(el);
1349
+ el.gridstackNode = node;
1350
+ node.el = el;
1351
+ node.grid = this;
1352
+ var copy = __assign({}, node);
1353
+ node = this.engine.addNode(node, triggerAddEvent);
1354
+ // write node attr back in case there was collision or we have to fix bad values during addNode()
1355
+ if (!utils_1.Utils.same(node, copy)) {
1356
+ this._writeAttr(el, node);
1357
+ }
1358
+ this._prepareDragDropByNode(node);
1359
+ return this;
1360
+ };
1361
+ /** @internal call to write position x,y,w,h attributes back to element */
1362
+ GridStack.prototype._writePosAttr = function (el, n) {
1363
+ if (n.x !== undefined && n.x !== null) {
1364
+ el.setAttribute('gs-x', String(n.x));
1365
+ }
1366
+ if (n.y !== undefined && n.y !== null) {
1367
+ el.setAttribute('gs-y', String(n.y));
1368
+ }
1369
+ n.w > 1 ? el.setAttribute('gs-w', String(n.w)) : el.removeAttribute('gs-w');
1370
+ n.h > 1 ? el.setAttribute('gs-h', String(n.h)) : el.removeAttribute('gs-h');
1371
+ return this;
1372
+ };
1373
+ /** @internal call to write any default attributes back to element */
1374
+ GridStack.prototype._writeAttr = function (el, node) {
1375
+ if (!node)
1376
+ return this;
1377
+ this._writePosAttr(el, node);
1378
+ var attrs /*: GridStackWidget but strings */ = {
1379
+ autoPosition: 'gs-auto-position',
1380
+ noResize: 'gs-no-resize',
1381
+ noMove: 'gs-no-move',
1382
+ locked: 'gs-locked',
1383
+ id: 'gs-id',
1384
+ };
1385
+ for (var key in attrs) {
1386
+ if (node[key]) { // 0 is valid for x,y only but done above already and not in list anyway
1387
+ el.setAttribute(attrs[key], String(node[key]));
1388
+ }
1389
+ else {
1390
+ el.removeAttribute(attrs[key]);
1391
+ }
1392
+ }
1393
+ return this;
1394
+ };
1395
+ /** @internal call to read any default attributes from element */
1396
+ GridStack.prototype._readAttr = function (el) {
1397
+ var n = {};
1398
+ n.x = utils_1.Utils.toNumber(el.getAttribute('gs-x'));
1399
+ n.y = utils_1.Utils.toNumber(el.getAttribute('gs-y'));
1400
+ n.w = utils_1.Utils.toNumber(el.getAttribute('gs-w'));
1401
+ n.h = utils_1.Utils.toNumber(el.getAttribute('gs-h'));
1402
+ if (!(n.w > 1))
1403
+ el.removeAttribute('gs-w');
1404
+ if (!(n.h > 1))
1405
+ el.removeAttribute('gs-h');
1406
+ n.autoPosition = utils_1.Utils.toBool(el.getAttribute('gs-auto-position'));
1407
+ n.noResize = utils_1.Utils.toBool(el.getAttribute('gs-no-resize'));
1408
+ n.noMove = utils_1.Utils.toBool(el.getAttribute('gs-no-move'));
1409
+ n.locked = utils_1.Utils.toBool(el.getAttribute('gs-locked'));
1410
+ n.id = el.getAttribute('gs-id');
1411
+ // read but never written out
1412
+ n.maxW = utils_1.Utils.toNumber(el.getAttribute('gs-max-w'));
1413
+ if (n.maxW)
1414
+ el.removeAttribute('gs-max-w');
1415
+ n.minW = utils_1.Utils.toNumber(el.getAttribute('gs-min-w'));
1416
+ if (n.minW)
1417
+ el.removeAttribute('gs-min-w');
1418
+ n.maxH = utils_1.Utils.toNumber(el.getAttribute('gs-max-h'));
1419
+ if (n.maxH)
1420
+ el.removeAttribute('gs-max-h');
1421
+ n.minH = utils_1.Utils.toNumber(el.getAttribute('gs-min-h'));
1422
+ if (n.minH)
1423
+ el.removeAttribute('gs-min-h');
1424
+ // remove any key not found (null or false which is default)
1425
+ for (var key in n) {
1426
+ if (!n.hasOwnProperty(key))
1427
+ return;
1428
+ if (!n[key] && n[key] !== 0) { // 0 can be valid value (x,y only really)
1429
+ delete n[key];
1430
+ }
1431
+ }
1432
+ return n;
1433
+ };
1434
+ /** @internal */
1435
+ GridStack.prototype._setStaticClass = function () {
1436
+ var _a, _b;
1437
+ var classes = ['grid-stack-static'];
1438
+ if (this.opts.staticGrid) {
1439
+ (_a = this.el.classList).add.apply(_a, classes);
1440
+ this.el.setAttribute('gs-static', 'true');
1441
+ }
1442
+ else {
1443
+ (_b = this.el.classList).remove.apply(_b, classes);
1444
+ this.el.removeAttribute('gs-static');
1445
+ }
1446
+ return this;
1447
+ };
1448
+ /**
1449
+ * called when we are being resized by the window - check if the one Column Mode needs to be turned on/off
1450
+ * and remember the prev columns we used, or get our count from parent, as well as check for auto cell height (square)
1451
+ */
1452
+ GridStack.prototype.onParentResize = function () {
1453
+ var _this = this;
1454
+ if (!this.el || !this.el.clientWidth)
1455
+ return; // return if we're gone or no size yet (will get called again)
1456
+ var changedColumn = false;
1457
+ // see if we're nested and take our column count from our parent....
1458
+ if (this._autoColumn && this.parentGridItem) {
1459
+ if (this.opts.column !== this.parentGridItem.w) {
1460
+ changedColumn = true;
1461
+ this.column(this.parentGridItem.w, 'none');
1462
+ }
1463
+ }
1464
+ else {
1465
+ // else check for 1 column in/out behavior
1466
+ var oneColumn = !this.opts.disableOneColumnMode && this.el.clientWidth <= this.opts.oneColumnSize;
1467
+ if ((this.opts.column === 1) !== oneColumn) {
1468
+ changedColumn = true;
1469
+ if (this.opts.animate) {
1470
+ this.setAnimation(false);
1471
+ } // 1 <-> 12 is too radical, turn off animation
1472
+ this.column(oneColumn ? 1 : this._prevColumn);
1473
+ if (this.opts.animate) {
1474
+ this.setAnimation(true);
1475
+ }
1476
+ }
1477
+ }
1478
+ // make the cells content square again
1479
+ if (this._isAutoCellHeight) {
1480
+ if (!changedColumn && this.opts.cellHeightThrottle) {
1481
+ if (!this._cellHeightThrottle) {
1482
+ this._cellHeightThrottle = utils_1.Utils.throttle(function () { return _this.cellHeight(); }, this.opts.cellHeightThrottle);
1483
+ }
1484
+ this._cellHeightThrottle();
1485
+ }
1486
+ else {
1487
+ // immediate update if we've changed column count or have no threshold
1488
+ this.cellHeight();
1489
+ }
1490
+ }
1491
+ // finally update any nested grids
1492
+ this.engine.nodes.forEach(function (n) {
1493
+ if (n.subGrid)
1494
+ n.subGrid.onParentResize();
1495
+ });
1496
+ return this;
1497
+ };
1498
+ /** add or remove the window size event handler */
1499
+ GridStack.prototype._updateWindowResizeEvent = function (forceRemove) {
1500
+ if (forceRemove === void 0) { forceRemove = false; }
1501
+ // only add event if we're not nested (parent will call us) and we're auto sizing cells or supporting oneColumn (i.e. doing work)
1502
+ var workTodo = (this._isAutoCellHeight || !this.opts.disableOneColumnMode) && !this.parentGridItem;
1503
+ if (!forceRemove && workTodo && !this._windowResizeBind) {
1504
+ this._windowResizeBind = this.onParentResize.bind(this); // so we can properly remove later
1505
+ window.addEventListener('resize', this._windowResizeBind);
1506
+ }
1507
+ else if ((forceRemove || !workTodo) && this._windowResizeBind) {
1508
+ window.removeEventListener('resize', this._windowResizeBind);
1509
+ delete this._windowResizeBind; // remove link to us so we can free
1510
+ }
1511
+ return this;
1512
+ };
1513
+ /** @internal convert a potential selector into actual element */
1514
+ GridStack.getElement = function (els) {
1515
+ if (els === void 0) { els = '.grid-stack-item'; }
1516
+ return utils_1.Utils.getElement(els);
1517
+ };
1518
+ /** @internal */
1519
+ GridStack.getElements = function (els) {
1520
+ if (els === void 0) { els = '.grid-stack-item'; }
1521
+ return utils_1.Utils.getElements(els);
1522
+ };
1523
+ /** @internal */
1524
+ GridStack.getGridElement = function (els) { return GridStack.getElement(els); };
1525
+ /** @internal */
1526
+ GridStack.getGridElements = function (els) { return utils_1.Utils.getElements(els); };
1527
+ /** @internal initialize margin top/bottom/left/right and units */
1528
+ GridStack.prototype._initMargin = function () {
1529
+ var data;
1530
+ var margin = 0;
1531
+ // support passing multiple values like CSS (ex: '5px 10px 0 20px')
1532
+ var margins = [];
1533
+ if (typeof this.opts.margin === 'string') {
1534
+ margins = this.opts.margin.split(' ');
1535
+ }
1536
+ if (margins.length === 2) { // top/bot, left/right like CSS
1537
+ this.opts.marginTop = this.opts.marginBottom = margins[0];
1538
+ this.opts.marginLeft = this.opts.marginRight = margins[1];
1539
+ }
1540
+ else if (margins.length === 4) { // Clockwise like CSS
1541
+ this.opts.marginTop = margins[0];
1542
+ this.opts.marginRight = margins[1];
1543
+ this.opts.marginBottom = margins[2];
1544
+ this.opts.marginLeft = margins[3];
1545
+ }
1546
+ else {
1547
+ data = utils_1.Utils.parseHeight(this.opts.margin);
1548
+ this.opts.marginUnit = data.unit;
1549
+ margin = this.opts.margin = data.h;
1550
+ }
1551
+ // see if top/bottom/left/right need to be set as well
1552
+ if (this.opts.marginTop === undefined) {
1553
+ this.opts.marginTop = margin;
1554
+ }
1555
+ else {
1556
+ data = utils_1.Utils.parseHeight(this.opts.marginTop);
1557
+ this.opts.marginTop = data.h;
1558
+ delete this.opts.margin;
1559
+ }
1560
+ if (this.opts.marginBottom === undefined) {
1561
+ this.opts.marginBottom = margin;
1562
+ }
1563
+ else {
1564
+ data = utils_1.Utils.parseHeight(this.opts.marginBottom);
1565
+ this.opts.marginBottom = data.h;
1566
+ delete this.opts.margin;
1567
+ }
1568
+ if (this.opts.marginRight === undefined) {
1569
+ this.opts.marginRight = margin;
1570
+ }
1571
+ else {
1572
+ data = utils_1.Utils.parseHeight(this.opts.marginRight);
1573
+ this.opts.marginRight = data.h;
1574
+ delete this.opts.margin;
1575
+ }
1576
+ if (this.opts.marginLeft === undefined) {
1577
+ this.opts.marginLeft = margin;
1578
+ }
1579
+ else {
1580
+ data = utils_1.Utils.parseHeight(this.opts.marginLeft);
1581
+ this.opts.marginLeft = data.h;
1582
+ delete this.opts.margin;
1583
+ }
1584
+ this.opts.marginUnit = data.unit; // in case side were spelled out, use those units instead...
1585
+ if (this.opts.marginTop === this.opts.marginBottom && this.opts.marginLeft === this.opts.marginRight && this.opts.marginTop === this.opts.marginRight) {
1586
+ this.opts.margin = this.opts.marginTop; // makes it easier to check for no-ops in setMargin()
1587
+ }
1588
+ return this;
1589
+ };
1590
+ /* ===========================================================================================
1591
+ * drag&drop methods that used to be stubbed out and implemented in dd-gridstack.ts
1592
+ * but caused loading issues in prod - see https://github.com/gridstack/gridstack.js/issues/2039
1593
+ * ===========================================================================================
1594
+ */
1595
+ /** get the global (but static to this code) DD implementation */
1596
+ GridStack.getDD = function () {
1597
+ return dd;
1598
+ };
1599
+ /**
1600
+ * call to setup dragging in from the outside (say toolbar), by specifying the class selection and options.
1601
+ * Called during GridStack.init() as options, but can also be called directly (last param are used) in case the toolbar
1602
+ * is dynamically create and needs to be set later.
1603
+ * @param dragIn string selector (ex: '.sidebar .grid-stack-item')
1604
+ * @param dragInOptions options - see DDDragInOpt. (default: {handle: '.grid-stack-item-content', appendTo: 'body'}
1605
+ **/
1606
+ GridStack.setupDragIn = function (dragIn, dragInOptions) {
1607
+ if ((dragInOptions === null || dragInOptions === void 0 ? void 0 : dragInOptions.pause) !== undefined) {
1608
+ dd_manager_1.DDManager.pauseDrag = dragInOptions.pause;
1609
+ }
1610
+ if (typeof dragIn === 'string') {
1611
+ dragInOptions = __assign(__assign({}, types_1.dragInDefaultOptions), (dragInOptions || {}));
1612
+ utils_1.Utils.getElements(dragIn).forEach(function (el) {
1613
+ if (!dd.isDraggable(el))
1614
+ dd.dragIn(el, dragInOptions);
1615
+ });
1616
+ }
1617
+ };
1618
+ /**
1619
+ * Enables/Disables dragging by the user of specific grid element. If you want all items, and have it affect future items, use enableMove() instead. No-op for static grids.
1620
+ * IF you are looking to prevent an item from moving (due to being pushed around by another during collision) use locked property instead.
1621
+ * @param els widget or selector to modify.
1622
+ * @param val if true widget will be draggable.
1623
+ */
1624
+ GridStack.prototype.movable = function (els, val) {
1625
+ var _this = this;
1626
+ if (this.opts.staticGrid)
1627
+ return this; // can't move a static grid!
1628
+ GridStack.getElements(els).forEach(function (el) {
1629
+ var node = el.gridstackNode;
1630
+ if (!node)
1631
+ return;
1632
+ if (val)
1633
+ delete node.noMove;
1634
+ else
1635
+ node.noMove = true;
1636
+ _this._prepareDragDropByNode(node); // init DD if need be, and adjust
1637
+ });
1638
+ return this;
1639
+ };
1640
+ /**
1641
+ * Enables/Disables user resizing of specific grid element. If you want all items, and have it affect future items, use enableResize() instead. No-op for static grids.
1642
+ * @param els widget or selector to modify
1643
+ * @param val if true widget will be resizable.
1644
+ */
1645
+ GridStack.prototype.resizable = function (els, val) {
1646
+ var _this = this;
1647
+ if (this.opts.staticGrid)
1648
+ return this; // can't resize a static grid!
1649
+ GridStack.getElements(els).forEach(function (el) {
1650
+ var node = el.gridstackNode;
1651
+ if (!node)
1652
+ return;
1653
+ if (val)
1654
+ delete node.noResize;
1655
+ else
1656
+ node.noResize = true;
1657
+ _this._prepareDragDropByNode(node); // init DD if need be, and adjust
1658
+ });
1659
+ return this;
1660
+ };
1661
+ /**
1662
+ * Temporarily disables widgets moving/resizing.
1663
+ * If you want a more permanent way (which freezes up resources) use `setStatic(true)` instead.
1664
+ * Note: no-op for static grid
1665
+ * This is a shortcut for:
1666
+ * @example
1667
+ * grid.enableMove(false);
1668
+ * grid.enableResize(false);
1669
+ * @param recurse true (default) if sub-grids also get updated
1670
+ */
1671
+ GridStack.prototype.disable = function (recurse) {
1672
+ if (recurse === void 0) { recurse = true; }
1673
+ if (this.opts.staticGrid)
1674
+ return;
1675
+ this.enableMove(false, recurse);
1676
+ this.enableResize(false, recurse); // @ts-ignore
1677
+ this._triggerEvent('disable');
1678
+ return this;
1679
+ };
1680
+ /**
1681
+ * Re-enables widgets moving/resizing - see disable().
1682
+ * Note: no-op for static grid.
1683
+ * This is a shortcut for:
1684
+ * @example
1685
+ * grid.enableMove(true);
1686
+ * grid.enableResize(true);
1687
+ * @param recurse true (default) if sub-grids also get updated
1688
+ */
1689
+ GridStack.prototype.enable = function (recurse) {
1690
+ if (recurse === void 0) { recurse = true; }
1691
+ if (this.opts.staticGrid)
1692
+ return;
1693
+ this.enableMove(true, recurse);
1694
+ this.enableResize(true, recurse); // @ts-ignore
1695
+ this._triggerEvent('enable');
1696
+ return this;
1697
+ };
1698
+ /**
1699
+ * Enables/disables widget moving. No-op for static grids.
1700
+ * @param recurse true (default) if sub-grids also get updated
1701
+ */
1702
+ GridStack.prototype.enableMove = function (doEnable, recurse) {
1703
+ var _this = this;
1704
+ if (recurse === void 0) { recurse = true; }
1705
+ if (this.opts.staticGrid)
1706
+ return this; // can't move a static grid!
1707
+ this.opts.disableDrag = !doEnable; // FIRST before we update children as grid overrides #1658
1708
+ this.engine.nodes.forEach(function (n) {
1709
+ _this.movable(n.el, doEnable);
1710
+ if (n.subGrid && recurse)
1711
+ n.subGrid.enableMove(doEnable, recurse);
1712
+ });
1713
+ return this;
1714
+ };
1715
+ /**
1716
+ * Enables/disables widget resizing. No-op for static grids.
1717
+ * @param recurse true (default) if sub-grids also get updated
1718
+ */
1719
+ GridStack.prototype.enableResize = function (doEnable, recurse) {
1720
+ var _this = this;
1721
+ if (recurse === void 0) { recurse = true; }
1722
+ if (this.opts.staticGrid)
1723
+ return this; // can't size a static grid!
1724
+ this.opts.disableResize = !doEnable; // FIRST before we update children as grid overrides #1658
1725
+ this.engine.nodes.forEach(function (n) {
1726
+ _this.resizable(n.el, doEnable);
1727
+ if (n.subGrid && recurse)
1728
+ n.subGrid.enableResize(doEnable, recurse);
1729
+ });
1730
+ return this;
1731
+ };
1732
+ /** @internal removes any drag&drop present (called during destroy) */
1733
+ GridStack.prototype._removeDD = function (el) {
1734
+ dd.draggable(el, 'destroy').resizable(el, 'destroy');
1735
+ if (el.gridstackNode) {
1736
+ delete el.gridstackNode._initDD; // reset our DD init flag
1737
+ }
1738
+ delete el.ddElement;
1739
+ return this;
1740
+ };
1741
+ /** @internal called to add drag over to support widgets being added externally */
1742
+ GridStack.prototype._setupAcceptWidget = function () {
1743
+ var _this = this;
1744
+ // check if we need to disable things
1745
+ if (this.opts.staticGrid || (!this.opts.acceptWidgets && !this.opts.removable)) {
1746
+ dd.droppable(this.el, 'destroy');
1747
+ return this;
1748
+ }
1749
+ // vars shared across all methods
1750
+ var cellHeight, cellWidth;
1751
+ var onDrag = function (event, el, helper) {
1752
+ var _a;
1753
+ var node = el.gridstackNode;
1754
+ if (!node)
1755
+ return;
1756
+ helper = helper || el;
1757
+ var parent = _this.el.getBoundingClientRect();
1758
+ var top = (_a = helper.getBoundingClientRect(), _a.top), left = _a.left;
1759
+ left -= parent.left;
1760
+ top -= parent.top;
1761
+ var ui = { position: { top: top, left: left } };
1762
+ if (node._temporaryRemoved) {
1763
+ node.x = Math.max(0, Math.round(left / cellWidth));
1764
+ node.y = Math.max(0, Math.round(top / cellHeight));
1765
+ delete node.autoPosition;
1766
+ _this.engine.nodeBoundFix(node);
1767
+ // don't accept *initial* location if doesn't fit #1419 (locked drop region, or can't grow), but maybe try if it will go somewhere
1768
+ if (!_this.engine.willItFit(node)) {
1769
+ node.autoPosition = true; // ignore x,y and try for any slot...
1770
+ if (!_this.engine.willItFit(node)) {
1771
+ dd.off(el, 'drag'); // stop calling us
1772
+ return; // full grid or can't grow
1773
+ }
1774
+ if (node._willFitPos) {
1775
+ // use the auto position instead #1687
1776
+ utils_1.Utils.copyPos(node, node._willFitPos);
1777
+ delete node._willFitPos;
1778
+ }
1779
+ }
1780
+ // re-use the existing node dragging method
1781
+ _this._onStartMoving(helper, event, ui, node, cellWidth, cellHeight);
1782
+ }
1783
+ else {
1784
+ // re-use the existing node dragging that does so much of the collision detection
1785
+ _this._dragOrResize(helper, event, ui, node, cellWidth, cellHeight);
1786
+ }
1787
+ };
1788
+ dd.droppable(this.el, {
1789
+ accept: function (el) {
1790
+ var node = el.gridstackNode;
1791
+ // set accept drop to true on ourself (which we ignore) so we don't get "can't drop" icon in HTML5 mode while moving
1792
+ if ((node === null || node === void 0 ? void 0 : node.grid) === _this)
1793
+ return true;
1794
+ if (!_this.opts.acceptWidgets)
1795
+ return false;
1796
+ // check for accept method or class matching
1797
+ var canAccept = true;
1798
+ if (typeof _this.opts.acceptWidgets === 'function') {
1799
+ canAccept = _this.opts.acceptWidgets(el);
1800
+ }
1801
+ else {
1802
+ var selector = (_this.opts.acceptWidgets === true ? '.grid-stack-item' : _this.opts.acceptWidgets);
1803
+ canAccept = el.matches(selector);
1804
+ }
1805
+ // finally check to make sure we actually have space left #1571
1806
+ if (canAccept && node && _this.opts.maxRow) {
1807
+ var n = { w: node.w, h: node.h, minW: node.minW, minH: node.minH }; // only width/height matters and autoPosition
1808
+ canAccept = _this.engine.willItFit(n);
1809
+ }
1810
+ return canAccept;
1811
+ }
1812
+ })
1813
+ /**
1814
+ * entering our grid area
1815
+ */
1816
+ .on(this.el, 'dropover', function (event, el, helper) {
1817
+ // console.log(`over ${this.el.gridstack.opts.id} ${count++}`); // TEST
1818
+ var node = el.gridstackNode;
1819
+ // ignore drop enter on ourself (unless we temporarily removed) which happens on a simple drag of our item
1820
+ if ((node === null || node === void 0 ? void 0 : node.grid) === _this && !node._temporaryRemoved) {
1821
+ // delete node._added; // reset this to track placeholder again in case we were over other grid #1484 (dropout doesn't always clear)
1822
+ return false; // prevent parent from receiving msg (which may be a grid as well)
1823
+ }
1824
+ // fix #1578 when dragging fast, we may not get a leave on the previous grid so force one now
1825
+ if ((node === null || node === void 0 ? void 0 : node.grid) && node.grid !== _this && !node._temporaryRemoved) {
1826
+ // console.log('dropover without leave'); // TEST
1827
+ var otherGrid = node.grid;
1828
+ otherGrid._leave(el, helper);
1829
+ }
1830
+ // cache cell dimensions (which don't change), position can animate if we removed an item in otherGrid that affects us...
1831
+ cellWidth = _this.cellWidth();
1832
+ cellHeight = _this.getCellHeight(true);
1833
+ // load any element attributes if we don't have a node
1834
+ if (!node) { // @ts-ignore private read only on ourself
1835
+ node = _this._readAttr(el);
1836
+ }
1837
+ if (!node.grid) {
1838
+ node._isExternal = true;
1839
+ el.gridstackNode = node;
1840
+ }
1841
+ // calculate the grid size based on element outer size
1842
+ helper = helper || el;
1843
+ var w = node.w || Math.round(helper.offsetWidth / cellWidth) || 1;
1844
+ var h = node.h || Math.round(helper.offsetHeight / cellHeight) || 1;
1845
+ // if the item came from another grid, make a copy and save the original info in case we go back there
1846
+ if (node.grid && node.grid !== _this) {
1847
+ // copy the node original values (min/max/id/etc...) but override width/height/other flags which are this grid specific
1848
+ // console.log('dropover cloning node'); // TEST
1849
+ if (!el._gridstackNodeOrig)
1850
+ el._gridstackNodeOrig = node; // shouldn't have multiple nested!
1851
+ el.gridstackNode = node = __assign(__assign({}, node), { w: w, h: h, grid: _this });
1852
+ _this.engine.cleanupNode(node)
1853
+ .nodeBoundFix(node);
1854
+ // restore some internal fields we need after clearing them all
1855
+ node._initDD =
1856
+ node._isExternal = // DOM needs to be re-parented on a drop
1857
+ node._temporaryRemoved = true; // so it can be inserted onDrag below
1858
+ }
1859
+ else {
1860
+ node.w = w;
1861
+ node.h = h;
1862
+ node._temporaryRemoved = true; // so we can insert it
1863
+ }
1864
+ // clear any marked for complete removal (Note: don't check _isAboutToRemove as that is cleared above - just do it)
1865
+ _this._itemRemoving(node.el, false);
1866
+ dd.on(el, 'drag', onDrag);
1867
+ // make sure this is called at least once when going fast #1578
1868
+ onDrag(event, el, helper);
1869
+ return false; // prevent parent from receiving msg (which may be a grid as well)
1870
+ })
1871
+ /**
1872
+ * Leaving our grid area...
1873
+ */
1874
+ .on(this.el, 'dropout', function (event, el, helper) {
1875
+ // console.log(`out ${this.el.gridstack.opts.id} ${count++}`); // TEST
1876
+ var node = el.gridstackNode;
1877
+ if (!node)
1878
+ return false;
1879
+ // fix #1578 when dragging fast, we might get leave after other grid gets enter (which calls us to clean)
1880
+ // so skip this one if we're not the active grid really..
1881
+ if (!node.grid || node.grid === _this) {
1882
+ _this._leave(el, helper);
1883
+ // if we were created as temporary nested grid, go back to before state
1884
+ if (_this._isTemp) {
1885
+ _this.removeAsSubGrid(node);
1886
+ }
1887
+ }
1888
+ return false; // prevent parent from receiving msg (which may be grid as well)
1889
+ })
1890
+ /**
1891
+ * end - releasing the mouse
1892
+ */
1893
+ .on(this.el, 'drop', function (event, el, helper) {
1894
+ var _a, _b;
1895
+ var node = el.gridstackNode;
1896
+ // ignore drop on ourself from ourself that didn't come from the outside - dragend will handle the simple move instead
1897
+ if ((node === null || node === void 0 ? void 0 : node.grid) === _this && !node._isExternal)
1898
+ return false;
1899
+ var wasAdded = !!_this.placeholder.parentElement; // skip items not actually added to us because of constrains, but do cleanup #1419
1900
+ _this.placeholder.remove();
1901
+ // notify previous grid of removal
1902
+ // console.log('drop delete _gridstackNodeOrig') // TEST
1903
+ var origNode = el._gridstackNodeOrig;
1904
+ delete el._gridstackNodeOrig;
1905
+ if (wasAdded && (origNode === null || origNode === void 0 ? void 0 : origNode.grid) && origNode.grid !== _this) {
1906
+ var oGrid = origNode.grid;
1907
+ oGrid.engine.removedNodes.push(origNode);
1908
+ oGrid._triggerRemoveEvent()._triggerChangeEvent();
1909
+ // if it's an empty sub-grid that got auto-created, nuke it
1910
+ if (oGrid.parentGridItem && !oGrid.engine.nodes.length && oGrid.opts.subGridDynamic) {
1911
+ oGrid.removeAsSubGrid();
1912
+ }
1913
+ }
1914
+ if (!node)
1915
+ return false;
1916
+ // use existing placeholder node as it's already in our list with drop location
1917
+ if (wasAdded) {
1918
+ _this.engine.cleanupNode(node); // removes all internal _xyz values
1919
+ node.grid = _this;
1920
+ }
1921
+ dd.off(el, 'drag');
1922
+ // if we made a copy ('helper' which is temp) of the original node then insert a copy, else we move the original node (#1102)
1923
+ // as the helper will be nuked by jquery-ui otherwise. TODO: update old code path
1924
+ if (helper !== el) {
1925
+ helper.remove();
1926
+ el.gridstackNode = origNode; // original item (left behind) is re-stored to pre dragging as the node now has drop info
1927
+ if (wasAdded) {
1928
+ el = el.cloneNode(true);
1929
+ }
1930
+ }
1931
+ else {
1932
+ el.remove(); // reduce flicker as we change depth here, and size further down
1933
+ _this._removeDD(el);
1934
+ }
1935
+ if (!wasAdded)
1936
+ return false;
1937
+ el.gridstackNode = node;
1938
+ node.el = el;
1939
+ var subGrid = (_b = (_a = node.subGrid) === null || _a === void 0 ? void 0 : _a.el) === null || _b === void 0 ? void 0 : _b.gridstack; // set when actual sub-grid present
1940
+ // @ts-ignore
1941
+ utils_1.Utils.copyPos(node, _this._readAttr(_this.placeholder)); // placeholder values as moving VERY fast can throw things off #1578
1942
+ utils_1.Utils.removePositioningStyles(el); // @ts-ignore
1943
+ _this._writeAttr(el, node);
1944
+ el.classList.add(types_1.gridDefaults.itemClass, _this.opts.itemClass);
1945
+ _this.el.appendChild(el); // @ts-ignore // TODO: now would be ideal time to _removeHelperStyle() overriding floating styles (native only)
1946
+ if (subGrid) {
1947
+ subGrid.parentGridItem = node;
1948
+ if (!subGrid.opts.styleInHead)
1949
+ subGrid._updateStyles(true); // re-create sub-grid styles now that we've moved
1950
+ }
1951
+ _this._updateContainerHeight();
1952
+ _this.engine.addedNodes.push(node); // @ts-ignore
1953
+ _this._triggerAddEvent(); // @ts-ignore
1954
+ _this._triggerChangeEvent();
1955
+ _this.engine.endUpdate();
1956
+ if (_this._gsEventHandler['dropped']) {
1957
+ _this._gsEventHandler['dropped'](__assign(__assign({}, event), { type: 'dropped' }), origNode && origNode.grid ? origNode : undefined, node);
1958
+ }
1959
+ // wait till we return out of the drag callback to set the new drag&resize handler or they may get messed up
1960
+ window.setTimeout(function () {
1961
+ // IFF we are still there (some application will use as placeholder and insert their real widget instead and better call makeWidget())
1962
+ if (node.el && node.el.parentElement) {
1963
+ _this._prepareDragDropByNode(node);
1964
+ }
1965
+ else {
1966
+ _this.engine.removeNode(node);
1967
+ }
1968
+ delete node.grid._isTemp;
1969
+ });
1970
+ return false; // prevent parent from receiving msg (which may be grid as well)
1971
+ });
1972
+ return this;
1973
+ };
1974
+ /** @internal mark item for removal */
1975
+ GridStack.prototype._itemRemoving = function (el, remove) {
1976
+ var node = el ? el.gridstackNode : undefined;
1977
+ if (!node || !node.grid)
1978
+ return;
1979
+ remove ? node._isAboutToRemove = true : delete node._isAboutToRemove;
1980
+ remove ? el.classList.add('grid-stack-item-removing') : el.classList.remove('grid-stack-item-removing');
1981
+ };
1982
+ /** @internal called to setup a trash drop zone if the user specifies it */
1983
+ GridStack.prototype._setupRemoveDrop = function () {
1984
+ var _this = this;
1985
+ if (!this.opts.staticGrid && typeof this.opts.removable === 'string') {
1986
+ var trashEl = document.querySelector(this.opts.removable);
1987
+ if (!trashEl)
1988
+ return this;
1989
+ // only register ONE drop-over/dropout callback for the 'trash', and it will
1990
+ // update the passed in item and parent grid because the 'trash' is a shared resource anyway,
1991
+ // and Native DD only has 1 event CB (having a list and technically a per grid removableOptions complicates things greatly)
1992
+ if (!dd.isDroppable(trashEl)) {
1993
+ dd.droppable(trashEl, this.opts.removableOptions)
1994
+ .on(trashEl, 'dropover', function (event, el) { return _this._itemRemoving(el, true); })
1995
+ .on(trashEl, 'dropout', function (event, el) { return _this._itemRemoving(el, false); });
1996
+ }
1997
+ }
1998
+ return this;
1999
+ };
2000
+ /** @internal prepares the element for drag&drop **/
2001
+ GridStack.prototype._prepareDragDropByNode = function (node) {
2002
+ var _this = this;
2003
+ var el = node.el;
2004
+ var noMove = node.noMove || this.opts.disableDrag;
2005
+ var noResize = node.noResize || this.opts.disableResize;
2006
+ // check for disabled grid first
2007
+ if (this.opts.staticGrid || (noMove && noResize)) {
2008
+ if (node._initDD) {
2009
+ this._removeDD(el); // nukes everything instead of just disable, will add some styles back next
2010
+ delete node._initDD;
2011
+ }
2012
+ el.classList.add('ui-draggable-disabled', 'ui-resizable-disabled'); // add styles one might depend on #1435
2013
+ return this;
2014
+ }
2015
+ if (!node._initDD) {
2016
+ // variables used/cashed between the 3 start/move/end methods, in addition to node passed above
2017
+ var cellWidth_1;
2018
+ var cellHeight_1;
2019
+ /** called when item starts moving/resizing */
2020
+ var onStartMoving = function (event, ui) {
2021
+ // trigger any 'dragstart' / 'resizestart' manually
2022
+ if (_this._gsEventHandler[event.type]) {
2023
+ _this._gsEventHandler[event.type](event, event.target);
2024
+ }
2025
+ cellWidth_1 = _this.cellWidth();
2026
+ cellHeight_1 = _this.getCellHeight(true); // force pixels for calculations
2027
+ _this._onStartMoving(el, event, ui, node, cellWidth_1, cellHeight_1);
2028
+ };
2029
+ /** called when item is being dragged/resized */
2030
+ var dragOrResize = function (event, ui) {
2031
+ _this._dragOrResize(el, event, ui, node, cellWidth_1, cellHeight_1);
2032
+ };
2033
+ /** called when the item stops moving/resizing */
2034
+ var onEndMoving = function (event) {
2035
+ _this.placeholder.remove();
2036
+ delete node._moving;
2037
+ delete node._event;
2038
+ delete node._lastTried;
2039
+ // if the item has moved to another grid, we're done here
2040
+ var target = event.target;
2041
+ if (!target.gridstackNode || target.gridstackNode.grid !== _this)
2042
+ return;
2043
+ node.el = target;
2044
+ if (node._isAboutToRemove) {
2045
+ var gridToNotify = el.gridstackNode.grid;
2046
+ if (gridToNotify._gsEventHandler[event.type]) {
2047
+ gridToNotify._gsEventHandler[event.type](event, target);
2048
+ }
2049
+ _this._removeDD(el);
2050
+ gridToNotify.engine.removedNodes.push(node);
2051
+ gridToNotify._triggerRemoveEvent();
2052
+ // break circular links and remove DOM
2053
+ delete el.gridstackNode;
2054
+ delete node.el;
2055
+ el.remove();
2056
+ }
2057
+ else {
2058
+ utils_1.Utils.removePositioningStyles(target);
2059
+ if (node._temporaryRemoved) {
2060
+ // got removed - restore item back to before dragging position
2061
+ utils_1.Utils.copyPos(node, node._orig); // @ts-ignore
2062
+ _this._writePosAttr(target, node);
2063
+ _this.engine.addNode(node);
2064
+ }
2065
+ else {
2066
+ // move to new placeholder location
2067
+ _this._writePosAttr(target, node);
2068
+ }
2069
+ if (_this._gsEventHandler[event.type]) {
2070
+ _this._gsEventHandler[event.type](event, target);
2071
+ }
2072
+ }
2073
+ // @ts-ignore
2074
+ _this._extraDragRow = 0; // @ts-ignore
2075
+ _this._updateContainerHeight(); // @ts-ignore
2076
+ _this._triggerChangeEvent();
2077
+ _this.engine.endUpdate();
2078
+ };
2079
+ dd.draggable(el, {
2080
+ start: onStartMoving,
2081
+ stop: onEndMoving,
2082
+ drag: dragOrResize
2083
+ }).resizable(el, {
2084
+ start: onStartMoving,
2085
+ stop: onEndMoving,
2086
+ resize: dragOrResize
2087
+ });
2088
+ node._initDD = true; // we've set DD support now
2089
+ }
2090
+ // finally fine tune move vs resize by disabling any part...
2091
+ dd.draggable(el, noMove ? 'disable' : 'enable')
2092
+ .resizable(el, noResize ? 'disable' : 'enable');
2093
+ return this;
2094
+ };
2095
+ /** @internal handles actual drag/resize start **/
2096
+ GridStack.prototype._onStartMoving = function (el, event, ui, node, cellWidth, cellHeight) {
2097
+ this.engine.cleanNodes()
2098
+ .beginUpdate(node);
2099
+ // @ts-ignore
2100
+ this._writePosAttr(this.placeholder, node);
2101
+ this.el.appendChild(this.placeholder);
2102
+ // console.log('_onStartMoving placeholder') // TEST
2103
+ node.el = this.placeholder;
2104
+ node._lastUiPosition = ui.position;
2105
+ node._prevYPix = ui.position.top;
2106
+ node._moving = (event.type === 'dragstart'); // 'dropover' are not initially moving so they can go exactly where they enter (will push stuff out of the way)
2107
+ delete node._lastTried;
2108
+ if (event.type === 'dropover' && node._temporaryRemoved) {
2109
+ // console.log('engine.addNode x=' + node.x); // TEST
2110
+ this.engine.addNode(node); // will add, fix collisions, update attr and clear _temporaryRemoved
2111
+ node._moving = true; // AFTER, mark as moving object (wanted fix location before)
2112
+ }
2113
+ // set the min/max resize info
2114
+ this.engine.cacheRects(cellWidth, cellHeight, this.opts.marginTop, this.opts.marginRight, this.opts.marginBottom, this.opts.marginLeft);
2115
+ if (event.type === 'resizestart') {
2116
+ dd.resizable(el, 'option', 'minWidth', cellWidth * (node.minW || 1))
2117
+ .resizable(el, 'option', 'minHeight', cellHeight * (node.minH || 1));
2118
+ if (node.maxW) {
2119
+ dd.resizable(el, 'option', 'maxWidth', cellWidth * node.maxW);
2120
+ }
2121
+ if (node.maxH) {
2122
+ dd.resizable(el, 'option', 'maxHeight', cellHeight * node.maxH);
2123
+ }
2124
+ }
2125
+ };
2126
+ /** @internal handles actual drag/resize **/
2127
+ GridStack.prototype._dragOrResize = function (el, event, ui, node, cellWidth, cellHeight) {
2128
+ var p = __assign({}, node._orig); // could be undefined (_isExternal) which is ok (drag only set x,y and w,h will default to node value)
2129
+ var resizing;
2130
+ var mLeft = this.opts.marginLeft, mRight = this.opts.marginRight, mTop = this.opts.marginTop, mBottom = this.opts.marginBottom;
2131
+ // if margins (which are used to pass mid point by) are large relative to cell height/width, reduce them down #1855
2132
+ var mHeight = Math.round(cellHeight * 0.1), mWidth = Math.round(cellWidth * 0.1);
2133
+ mLeft = Math.min(mLeft, mWidth);
2134
+ mRight = Math.min(mRight, mWidth);
2135
+ mTop = Math.min(mTop, mHeight);
2136
+ mBottom = Math.min(mBottom, mHeight);
2137
+ if (event.type === 'drag') {
2138
+ if (node._temporaryRemoved)
2139
+ return; // handled by dropover
2140
+ var distance = ui.position.top - node._prevYPix;
2141
+ node._prevYPix = ui.position.top;
2142
+ if (this.opts.draggable.scroll !== false) {
2143
+ utils_1.Utils.updateScrollPosition(el, ui.position, distance);
2144
+ }
2145
+ // get new position taking into account the margin in the direction we are moving! (need to pass mid point by margin)
2146
+ var left = ui.position.left + (ui.position.left > node._lastUiPosition.left ? -mRight : mLeft);
2147
+ var top_2 = ui.position.top + (ui.position.top > node._lastUiPosition.top ? -mBottom : mTop);
2148
+ p.x = Math.round(left / cellWidth);
2149
+ p.y = Math.round(top_2 / cellHeight);
2150
+ // @ts-ignore// if we're at the bottom hitting something else, grow the grid so cursor doesn't leave when trying to place below others
2151
+ var prev = this._extraDragRow;
2152
+ if (this.engine.collide(node, p)) {
2153
+ var row = this.getRow();
2154
+ var extra = Math.max(0, (p.y + node.h) - row);
2155
+ if (this.opts.maxRow && row + extra > this.opts.maxRow) {
2156
+ extra = Math.max(0, this.opts.maxRow - row);
2157
+ } // @ts-ignore
2158
+ this._extraDragRow = extra; // @ts-ignore
2159
+ }
2160
+ else
2161
+ this._extraDragRow = 0; // @ts-ignore
2162
+ if (this._extraDragRow !== prev)
2163
+ this._updateContainerHeight();
2164
+ if (node.x === p.x && node.y === p.y)
2165
+ return; // skip same
2166
+ // DON'T skip one we tried as we might have failed because of coverage <50% before
2167
+ // if (node._lastTried && node._lastTried.x === x && node._lastTried.y === y) return;
2168
+ }
2169
+ else if (event.type === 'resize') {
2170
+ if (p.x < 0)
2171
+ return;
2172
+ // Scrolling page if needed
2173
+ utils_1.Utils.updateScrollResize(event, el, cellHeight);
2174
+ // get new size
2175
+ p.w = Math.round((ui.size.width - mLeft) / cellWidth);
2176
+ p.h = Math.round((ui.size.height - mTop) / cellHeight);
2177
+ if (node.w === p.w && node.h === p.h)
2178
+ return;
2179
+ if (node._lastTried && node._lastTried.w === p.w && node._lastTried.h === p.h)
2180
+ return; // skip one we tried (but failed)
2181
+ // if we size on left/top side this might move us, so get possible new position as well
2182
+ var left = ui.position.left + mLeft;
2183
+ var top_3 = ui.position.top + mTop;
2184
+ p.x = Math.round(left / cellWidth);
2185
+ p.y = Math.round(top_3 / cellHeight);
2186
+ resizing = true;
2187
+ }
2188
+ node._event = event;
2189
+ node._lastTried = p; // set as last tried (will nuke if we go there)
2190
+ var rect = {
2191
+ x: ui.position.left + mLeft,
2192
+ y: ui.position.top + mTop,
2193
+ w: (ui.size ? ui.size.width : node.w * cellWidth) - mLeft - mRight,
2194
+ h: (ui.size ? ui.size.height : node.h * cellHeight) - mTop - mBottom
2195
+ };
2196
+ if (this.engine.moveNodeCheck(node, __assign(__assign({}, p), { cellWidth: cellWidth, cellHeight: cellHeight, rect: rect, resizing: resizing }))) {
2197
+ node._lastUiPosition = ui.position;
2198
+ this.engine.cacheRects(cellWidth, cellHeight, mTop, mRight, mBottom, mLeft);
2199
+ delete node._skipDown;
2200
+ if (resizing && node.subGrid)
2201
+ node.subGrid.onParentResize();
2202
+ this._extraDragRow = 0; // @ts-ignore
2203
+ this._updateContainerHeight();
2204
+ var target = event.target; // @ts-ignore
2205
+ this._writePosAttr(target, node);
2206
+ if (this._gsEventHandler[event.type]) {
2207
+ this._gsEventHandler[event.type](event, target);
2208
+ }
2209
+ }
2210
+ };
2211
+ /** @internal called when item leaving our area by either cursor dropout event
2212
+ * or shape is outside our boundaries. remove it from us, and mark temporary if this was
2213
+ * our item to start with else restore prev node values from prev grid it came from.
2214
+ **/
2215
+ GridStack.prototype._leave = function (el, helper) {
2216
+ var node = el.gridstackNode;
2217
+ if (!node)
2218
+ return;
2219
+ dd.off(el, 'drag'); // no need to track while being outside
2220
+ // this gets called when cursor leaves and shape is outside, so only do this once
2221
+ if (node._temporaryRemoved)
2222
+ return;
2223
+ node._temporaryRemoved = true;
2224
+ this.engine.removeNode(node); // remove placeholder as well, otherwise it's a sign node is not in our list, which is a bigger issue
2225
+ node.el = node._isExternal && helper ? helper : el; // point back to real item being dragged
2226
+ if (this.opts.removable === true) { // boolean vs a class string
2227
+ // item leaving us and we are supposed to remove on leave (no need to drag onto trash) mark it so
2228
+ this._itemRemoving(el, true);
2229
+ }
2230
+ // finally if item originally came from another grid, but left us, restore things back to prev info
2231
+ if (el._gridstackNodeOrig) {
2232
+ // console.log('leave delete _gridstackNodeOrig') // TEST
2233
+ el.gridstackNode = el._gridstackNodeOrig;
2234
+ delete el._gridstackNodeOrig;
2235
+ }
2236
+ else if (node._isExternal) {
2237
+ // item came from outside (like a toolbar) so nuke any node info
2238
+ delete node.el;
2239
+ delete el.gridstackNode;
2240
+ // and restore all nodes back to original
2241
+ this.engine.restoreInitial();
2242
+ }
2243
+ };
2244
+ // legacy method removed
2245
+ GridStack.prototype.commit = function () { (0, utils_1.obsolete)(this, this.batchUpdate(false), 'commit', 'batchUpdate', '5.2'); return this; };
2246
+ /** scoping so users can call GridStack.Utils.sort() for example */
2247
+ GridStack.Utils = utils_1.Utils;
2248
+ /** scoping so users can call new GridStack.Engine(12) for example */
2249
+ GridStack.Engine = gridstack_engine_1.GridStackEngine;
2250
+ GridStack.GDRev = '8.0.0';
2251
+ return GridStack;
2252
+ }());
2228
2253
  //# sourceMappingURL=gridstack.js.map