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