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