/
gridstack.ts
2279 lines (2042 loc) · 95.5 KB
/
gridstack.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* GridStack 7.1.1-dev
* https://gridstackjs.com/
*
* Copyright (c) 2021-2022 Alain Dumesny
* see root license https://github.com/gridstack/gridstack.js/tree/master/LICENSE
*/
import { GridStackEngine } from './gridstack-engine';
import { Utils, HeightData, obsolete } from './utils';
import { gridDefaults, ColumnOptions, GridItemHTMLElement, GridStackElement, GridStackEventHandlerCallback,
GridStackNode, GridStackWidget, numberOrString, DDUIData, DDDragInOpt, GridStackPosition, GridStackOptions,
dragInDefaultOptions, GridStackEventHandler, GridStackNodesHandler } from './types';
/*
* and include D&D by default
* TODO: while we could generate a gridstack-static.js at smaller size - saves about 31k (41k -> 72k)
* I don't know how to generate the DD only code at the remaining 31k to delay load as code depends on Gridstack.ts
* also it caused loading issues in prod - see https://github.com/gridstack/gridstack.js/issues/2039
*/
import { DDGridStack } from './dd-gridstack';
import { isTouch } from './dd-touch';
import { DDManager } from './dd-manager';
import { DDElementHost } from './dd-element';
/** global instance */
const dd = new DDGridStack;
// export all dependent file as well to make it easier for users to just import the main file
export * from './types';
export * from './utils';
export * from './gridstack-engine';
export * from './dd-gridstack';
export interface GridHTMLElement extends HTMLElement {
gridstack?: GridStack; // grid's parent DOM element points back to grid class
}
/** list of possible events, or space separated list of them */
export type GridStackEvent = 'added' | 'change' | 'disable' | 'drag' | 'dragstart' | 'dragstop' | 'dropped' |
'enable' | 'removed' | 'resize' | 'resizestart' | 'resizestop' | string;
/** Defines the coordinates of an object */
export interface MousePosition {
top: number;
left: number;
}
/** Defines the position of a cell inside the grid*/
export interface CellPosition {
x: number;
y: number;
}
/** optional function called during load() to callback the user on new added/remove items */
export type AddRemoveFcn = (g: GridStack, w: GridStackWidget, add: boolean) => GridItemHTMLElement;
interface GridCSSStyleSheet extends CSSStyleSheet {
_max?: number; // internal tracker of the max # of rows we created
}
// extend with internal fields we need - TODO: move other items in here
interface InternalGridStackOptions extends GridStackOptions {
_alwaysShowResizeHandle?: true | false | 'mobile'; // so we can restore for save
}
/**
* Main gridstack class - you will need to call `GridStack.init()` first to initialize your grid.
* Note: your grid elements MUST have the following classes for the CSS layout to work:
* @example
* <div class="grid-stack">
* <div class="grid-stack-item">
* <div class="grid-stack-item-content">Item 1</div>
* </div>
* </div>
*/
export class GridStack {
/**
* initializing the HTML element, or selector string, into a grid will return the grid. Calling it again will
* simply return the existing instance (ignore any passed options). There is also an initAll() version that support
* multiple grids initialization at once. Or you can use addGrid() to create the entire grid from JSON.
* @param options grid options (optional)
* @param elOrString element or CSS selector (first one used) to convert to a grid (default to '.grid-stack' class selector)
*
* @example
* let grid = GridStack.init();
*
* Note: the HTMLElement (of type GridHTMLElement) will store a `gridstack: GridStack` value that can be retrieve later
* let grid = document.querySelector('.grid-stack').gridstack;
*/
public static init(options: GridStackOptions = {}, elOrString: GridStackElement = '.grid-stack'): GridStack {
let el = GridStack.getGridElement(elOrString);
if (!el) {
if (typeof elOrString === 'string') {
console.error('GridStack.initAll() no grid was found with selector "' + elOrString + '" - element missing or wrong selector ?' +
'\nNote: ".grid-stack" is required for proper CSS styling and drag/drop, and is the default selector.');
} else {
console.error('GridStack.init() no grid element was passed.');
}
return null;
}
if (!el.gridstack) {
el.gridstack = new GridStack(el, Utils.cloneDeep(options));
}
return el.gridstack
}
/**
* Will initialize a list of elements (given a selector) and return an array of grids.
* @param options grid options (optional)
* @param selector elements selector to convert to grids (default to '.grid-stack' class selector)
*
* @example
* let grids = GridStack.initAll();
* grids.forEach(...)
*/
public static initAll(options: GridStackOptions = {}, selector = '.grid-stack'): GridStack[] {
let grids: GridStack[] = [];
GridStack.getGridElements(selector).forEach(el => {
if (!el.gridstack) {
el.gridstack = new GridStack(el, Utils.cloneDeep(options));
delete options.dragIn; delete options.dragInOptions; // only need to be done once (really a static global thing, not per grid)
}
grids.push(el.gridstack);
});
if (grids.length === 0) {
console.error('GridStack.initAll() no grid was found with selector "' + selector + '" - element missing or wrong selector ?' +
'\nNote: ".grid-stack" is required for proper CSS styling and drag/drop, and is the default selector.');
}
return grids;
}
/**
* call to create a grid with the given options, including loading any children from JSON structure. This will call GridStack.init(), then
* grid.load() on any passed children (recursively). Great alternative to calling init() if you want entire grid to come from
* JSON serialized data, including options.
* @param parent HTML element parent to the grid
* @param opt grids options used to initialize the grid, and list of children
*/
public static addGrid(parent: HTMLElement, opt: GridStackOptions = {}): GridStack {
if (!parent) return null;
// create the grid element, but check if the passed 'parent' already has grid styling and should be used instead
let el = parent;
if (!parent.classList.contains('grid-stack')) {
let doc = document.implementation.createHTMLDocument(''); // IE needs a param
doc.body.innerHTML = `<div class="grid-stack ${opt.class || ''}"></div>`;
el = doc.body.children[0] as HTMLElement;
parent.appendChild(el);
}
// create grid class and load any children
let grid = GridStack.init(opt, el);
if (grid.opts.children) {
let children = grid.opts.children;
delete grid.opts.children;
grid.load(children);
}
return grid;
}
/** call this method to register your engine instead of the default one.
* See instead `GridStackOptions.engineClass` if you only need to
* replace just one instance.
*/
static registerEngine(engineClass: typeof GridStackEngine): void {
GridStack.engineClass = engineClass;
}
/** scoping so users can call GridStack.Utils.sort() for example */
public static Utils = Utils;
/** scoping so users can call new GridStack.Engine(12) for example */
public static Engine = GridStackEngine;
/** the HTML element tied to this grid after it's been initialized */
public el: GridHTMLElement;
/** engine used to implement non DOM grid functionality */
public engine: GridStackEngine;
/** grid options - public for classes to access, but use methods to modify! */
public opts: GridStackOptions;
/** point to a parent grid item if we're nested (inside a grid-item in between 2 Grids) */
public parentGridItem?: GridStackNode;
protected static engineClass: typeof GridStackEngine;
/** @internal unique class name for our generated CSS style sheet */
protected _styleSheetClass?: string;
/** @internal true if we got created by drag over gesture, so we can removed on drag out (temporary) */
public _isTemp?: boolean;
/** @internal create placeholder DIV as needed */
public get placeholder(): HTMLElement {
if (!this._placeholder) {
let placeholderChild = document.createElement('div'); // child so padding match item-content
placeholderChild.className = 'placeholder-content';
if (this.opts.placeholderText) {
placeholderChild.innerHTML = this.opts.placeholderText;
}
this._placeholder = document.createElement('div');
this._placeholder.classList.add(this.opts.placeholderClass, gridDefaults.itemClass, this.opts.itemClass);
this.placeholder.appendChild(placeholderChild);
}
return this._placeholder;
}
/** @internal */
protected _placeholder: HTMLElement;
/** @internal */
protected _prevColumn: number;
/** @internal prevent cached layouts from being updated when loading into small column layouts */
protected _ignoreLayoutsNodeChange: boolean;
/** @internal */
public _gsEventHandler = {};
/** @internal */
protected _styles: GridCSSStyleSheet;
/** @internal flag to keep cells square during resize */
protected _isAutoCellHeight: boolean;
/** @internal track event binding to window resize so we can remove */
protected _windowResizeBind: () => void;
/** @internal limit auto cell resizing method */
protected _cellHeightThrottle: () => void;
/** @internal true when loading items to insert first rather than append */
protected _insertNotAppend: boolean;
/** @internal extra row added when dragging at the bottom of the grid */
protected _extraDragRow = 0;
/** @internal true if nested grid should get column count from our width */
protected _autoColumn?: boolean;
/**
* Construct a grid item from the given element and options
* @param el
* @param opts
*/
public constructor(el: GridHTMLElement, opts: GridStackOptions = {}) {
this.el = el; // exposed HTML element to the user
opts = opts || {}; // handles null/undefined/0
if (!el.classList.contains('grid-stack')) {
this.el.classList.add('grid-stack');
}
// if row property exists, replace minRow and maxRow instead
if (opts.row) {
opts.minRow = opts.maxRow = opts.row;
delete opts.row;
}
let rowAttr = Utils.toNumber(el.getAttribute('gs-row'));
// flag only valid in sub-grids (handled by parent, not here)
if (opts.column === 'auto') {
delete opts.column;
}
// 'minWidth' legacy support in 5.1
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
let anyOpts = opts as any;
if (anyOpts.minWidth !== undefined) {
opts.oneColumnSize = opts.oneColumnSize || anyOpts.minWidth;
delete anyOpts.minWidth;
}
// save original setting so we can restore on save
if (opts.alwaysShowResizeHandle !== undefined) {
(opts as InternalGridStackOptions)._alwaysShowResizeHandle = opts.alwaysShowResizeHandle;
}
// elements DOM attributes override any passed options (like CSS style) - merge the two together
let defaults: GridStackOptions = {...Utils.cloneDeep(gridDefaults),
column: Utils.toNumber(el.getAttribute('gs-column')) || gridDefaults.column,
minRow: rowAttr ? rowAttr : Utils.toNumber(el.getAttribute('gs-min-row')) || gridDefaults.minRow,
maxRow: rowAttr ? rowAttr : Utils.toNumber(el.getAttribute('gs-max-row')) || gridDefaults.maxRow,
staticGrid: Utils.toBool(el.getAttribute('gs-static')) || gridDefaults.staticGrid,
draggable: {
handle: (opts.handleClass ? '.' + opts.handleClass : (opts.handle ? opts.handle : '')) || gridDefaults.draggable.handle,
},
removableOptions: {
accept: opts.itemClass ? '.' + opts.itemClass : gridDefaults.removableOptions.accept,
},
};
if (el.getAttribute('gs-animate')) { // default to true, but if set to false use that instead
defaults.animate = Utils.toBool(el.getAttribute('gs-animate'))
}
this.opts = Utils.defaults(opts, defaults);
opts = null; // make sure we use this.opts instead
this._initMargin(); // part of settings defaults...
// 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)
if (this.opts.column !== 1 && !this.opts.disableOneColumnMode && this._widthOrContainer() <= this.opts.oneColumnSize) {
this._prevColumn = this.getColumn();
this.opts.column = 1;
}
if (this.opts.rtl === 'auto') {
this.opts.rtl = (el.style.direction === 'rtl');
}
if (this.opts.rtl) {
this.el.classList.add('grid-stack-rtl');
}
// check if we're been nested, and if so update our style and keep pointer around (used during save)
let parentGridItem = (Utils.closestUpByClass(this.el, gridDefaults.itemClass) as GridItemHTMLElement)?.gridstackNode;
if (parentGridItem) {
parentGridItem.subGrid = this;
this.parentGridItem = parentGridItem;
this.el.classList.add('grid-stack-nested');
parentGridItem.el.classList.add('grid-stack-sub-grid');
}
this._isAutoCellHeight = (this.opts.cellHeight === 'auto');
if (this._isAutoCellHeight || this.opts.cellHeight === 'initial') {
// make the cell content square initially (will use resize/column event to keep it square)
this.cellHeight(undefined, false);
} else {
// append unit if any are set
if (typeof this.opts.cellHeight == 'number' && this.opts.cellHeightUnit && this.opts.cellHeightUnit !== gridDefaults.cellHeightUnit) {
this.opts.cellHeight = this.opts.cellHeight + this.opts.cellHeightUnit;
delete this.opts.cellHeightUnit;
}
this.cellHeight(this.opts.cellHeight, false);
}
// see if we need to adjust auto-hide
if (this.opts.alwaysShowResizeHandle === 'mobile') {
this.opts.alwaysShowResizeHandle = isTouch;
}
this._styleSheetClass = 'grid-stack-instance-' + GridStackEngine._idSeq++;
this.el.classList.add(this._styleSheetClass);
this._setStaticClass();
let engineClass = this.opts.engineClass || GridStack.engineClass || GridStackEngine;
this.engine = new engineClass({
column: this.getColumn(),
float: this.opts.float,
maxRow: this.opts.maxRow,
onChange: (cbNodes) => {
let maxH = 0;
this.engine.nodes.forEach(n => { maxH = Math.max(maxH, n.y + n.h) });
cbNodes.forEach(n => {
let el = n.el;
if (!el) return;
if (n._removeDOM) {
if (el) el.remove();
delete n._removeDOM;
} else {
this._writePosAttr(el, n);
}
});
this._updateStyles(false, maxH); // false = don't recreate, just append if need be
}
});
if (this.opts.auto) {
this.batchUpdate(); // prevent in between re-layout #1535 TODO: this only set float=true, need to prevent collision check...
let elements: {el: HTMLElement; i: number}[] = [];
let column = this.getColumn();
if (column === 1 && this._prevColumn) column = this._prevColumn; // do 12 column when reading into 1 column mode
this.getGridItems().forEach(el => { // get dom elements (not nodes yet)
let x = parseInt(el.getAttribute('gs-x'));
let y = parseInt(el.getAttribute('gs-y'));
elements.push({
el,
// if x,y are missing (autoPosition) add them to end of list - but keep their respective DOM order
i: (Number.isNaN(x) ? 1000 : x) + (Number.isNaN(y) ? 1000 : y) * column
});
});
elements.sort((a, b) => b.i - a.i).forEach(e => this._prepareElement(e.el)); // revert sort so lowest item wins
this.batchUpdate(false);
}
this.setAnimation(this.opts.animate);
this._updateStyles();
if (this.opts.column != 12) {
this.el.classList.add('grid-stack-' + this.opts.column);
}
// legacy support to appear 'per grid` options when really global.
if (this.opts.dragIn) GridStack.setupDragIn(this.opts.dragIn, this.opts.dragInOptions);
delete this.opts.dragIn;
delete this.opts.dragInOptions;
// dynamic grids require pausing during drag to detect over to nest vs push
if (this.opts.subGridDynamic && !DDManager.pauseDrag) DDManager.pauseDrag = true;
if (this.opts.draggable?.pause !== undefined) DDManager.pauseDrag = this.opts.draggable.pause;
this._setupRemoveDrop();
this._setupAcceptWidget();
this._updateWindowResizeEvent();
}
/**
* add a new widget and returns it.
*
* Widget will be always placed even if result height is more than actual grid height.
* You need to use `willItFit()` before calling addWidget for additional check.
* See also `makeWidget()`.
*
* @example
* let grid = GridStack.init();
* grid.addWidget({w: 3, content: 'hello'});
* grid.addWidget('<div class="grid-stack-item"><div class="grid-stack-item-content">hello</div></div>', {w: 3});
*
* @param el GridStackWidget (which can have content string as well), html element, or string definition to add
* @param options widget position/size options (optional, and ignore if first param is already option) - see GridStackWidget
*/
public addWidget(els?: GridStackWidget | GridStackElement, options?: GridStackWidget): GridItemHTMLElement {
function isGridStackWidget(w: GridStackWidget): w is GridStackWidget { // https://medium.com/ovrsea/checking-the-type-of-an-object-in-typescript-the-type-guards-24d98d9119b0
return w.x !== undefined || w.y !== undefined || w.w !== undefined || w.h !== undefined || w.content !== undefined ? true : false;
}
let el: HTMLElement;
let node: GridStackNode;
if (typeof els === 'string') {
let doc = document.implementation.createHTMLDocument(''); // IE needs a param
doc.body.innerHTML = els;
el = doc.body.children[0] as HTMLElement;
} else if (arguments.length === 0 || arguments.length === 1 && isGridStackWidget(els)) {
node = options = els;
if (node?.el) {
el = node.el; // re-use element stored in the node
} else {
let content = options?.content || '';
let doc = document.implementation.createHTMLDocument(''); // IE needs a param
doc.body.innerHTML = `<div class="grid-stack-item ${this.opts.itemClass || ''}"><div class="grid-stack-item-content">${content}</div></div>`;
el = doc.body.children[0] as HTMLElement;
}
} else {
el = els as HTMLElement;
}
// Tempting to initialize the passed in opt with default and valid values, but this break knockout demos
// as the actual value are filled in when _prepareElement() calls el.getAttribute('gs-xyz') before adding the node.
// So make sure we load any DOM attributes that are not specified in passed in options (which override)
let domAttr = this._readAttr(el);
options = Utils.cloneDeep(options) || {}; // make a copy before we modify in case caller re-uses it
Utils.defaults(options, domAttr);
node = this.engine.prepareNode(options);
this._writeAttr(el, options);
if (this._insertNotAppend) {
this.el.prepend(el);
} else {
this.el.appendChild(el);
}
// similar to makeWidget() that doesn't read attr again and worse re-create a new node and loose any _id
this._prepareElement(el, true, options);
this._updateContainerHeight();
// see if there is a sub-grid to create too
if (node.subGrid) {
this.makeSubGrid(node.el, undefined, undefined, false);
}
// if we're adding an item into 1 column (_prevColumn is set only when going to 1) make sure
// we don't override the larger 12 column layout that was already saved. #1985
if (this._prevColumn && this.opts.column === 1) {
this._ignoreLayoutsNodeChange = true;
}
this._triggerAddEvent();
this._triggerChangeEvent();
delete this._ignoreLayoutsNodeChange;
return el;
}
/**
* Convert an existing gridItem element into a sub-grid with the given (optional) options, else inherit them
* from the parent subGrid options.
* @param el gridItem element to convert
* @param ops (optional) sub-grid options, else default to node, then parent settings, else defaults
* @param nodeToAdd (optional) node to add to the newly created sub grid (used when dragging over existing regular item)
* @returns newly created grid
*/
public makeSubGrid(el: GridItemHTMLElement, ops?: GridStackOptions, nodeToAdd?: GridStackNode, saveContent = true): GridStack {
let node = el.gridstackNode;
if (!node) {
node = this.makeWidget(el).gridstackNode;
}
if ((node.subGrid as GridStack)?.el) return node.subGrid as GridStack; // already done
ops = Utils.cloneDeep(ops || node.subGrid as GridStackOptions || {...this.opts.subGrid, children: undefined});
ops.subGrid = Utils.cloneDeep(ops); // carry nesting settings to next one down
node.subGrid = ops;
// if column special case it set, remember that flag and set default
let autoColumn: boolean;
if (ops.column === 'auto') {
autoColumn = true;
ops.column = Math.max(node.w || 1, nodeToAdd?.w || 1);
ops.disableOneColumnMode = true; // driven by parent
}
// if we're converting an existing full item, move over the content to be the first sub item in the new grid
let content = node.el.querySelector('.grid-stack-item-content') as HTMLElement;
let newItem: HTMLElement;
let newItemOpt: GridStackNode;
if (saveContent) {
this._removeDD(node.el); // remove D&D since it's set on content div
let doc = document.implementation.createHTMLDocument(''); // IE needs a param
doc.body.innerHTML = `<div class="grid-stack-item"></div>`;
newItem = doc.body.children[0] as HTMLElement;
newItem.appendChild(content);
newItemOpt = {...node, x:0, y:0};
Utils.removeInternalForSave(newItemOpt);
delete newItemOpt.subGrid;
if (node.content) {
newItemOpt.content = node.content;
delete node.content;
}
doc.body.innerHTML = `<div class="grid-stack-item-content"></div>`;
content = doc.body.children[0] as HTMLElement;
node.el.appendChild(content);
this._prepareDragDropByNode(node); // ... and restore original D&D
}
// if we're adding an additional item, make the container large enough to have them both
if (nodeToAdd) {
let w = autoColumn ? ops.column : node.w;
let h = node.h + nodeToAdd.h;
let style = node.el.style;
style.transition = 'none'; // show up instantly so we don't see scrollbar with nodeToAdd
this.update(node.el, {w, h});
setTimeout(() => style.transition = null); // recover animation
}
let subGrid = node.subGrid = GridStack.addGrid(content, ops);
if (nodeToAdd?._moving) subGrid._isTemp = true; // prevent re-nesting as we add over
if (autoColumn) subGrid._autoColumn = true;
// add the original content back as a child of hte newly created grid
if (saveContent) {
subGrid.addWidget(newItem, newItemOpt);
}
// now add any additional node
if (nodeToAdd) {
if (nodeToAdd._moving) {
// create an artificial event even for the just created grid to receive this item
window.setTimeout(() => Utils.simulateMouseEvent(nodeToAdd._event, 'mouseenter', subGrid.el), 0);
} else {
subGrid.addWidget(node.el, node);
}
}
return subGrid;
}
/**
* called when an item was converted into a nested grid to accommodate a dragged over item, but then item leaves - return back
* to the original grid-item. Also called to remove empty sub-grids when last item is dragged out (since re-creating is simple)
*/
public removeAsSubGrid(nodeThatRemoved?: GridStackNode): void {
let pGrid = this.parentGridItem?.grid;
if (!pGrid) return;
pGrid.batchUpdate();
pGrid.removeWidget(this.parentGridItem.el, true, true);
this.engine.nodes.forEach(n => {
// migrate any children over and offsetting by our location
n.x += this.parentGridItem.x;
n.y += this.parentGridItem.y;
pGrid.addWidget(n.el, n);
});
pGrid.batchUpdate(false);
delete this.parentGridItem;
// create an artificial event for the original grid now that this one is gone (got a leave, but won't get enter)
if (nodeThatRemoved) {
window.setTimeout(() => Utils.simulateMouseEvent(nodeThatRemoved._event, 'mouseenter', pGrid.el), 0);
}
}
/**
/**
* saves the current layout returning a list of widgets for serialization which might include any nested grids.
* @param saveContent if true (default) the latest html inside .grid-stack-content will be saved to GridStackWidget.content field, else it will
* be removed.
* @param saveGridOpt if true (default false), save the grid options itself, so you can call the new GridStack.addGrid()
* to recreate everything from scratch. GridStackOptions.children would then contain the widget list instead.
* @returns list of widgets or full grid option, including .children list of widgets
*/
public save(saveContent = true, saveGridOpt = false): GridStackWidget[] | GridStackOptions {
// return copied nodes we can modify at will...
let list = this.engine.save(saveContent);
// check for HTML content and nested grids
list.forEach(n => {
if (saveContent && n.el && !n.subGrid) { // sub-grid are saved differently, not plain content
let sub = n.el.querySelector('.grid-stack-item-content');
n.content = sub ? sub.innerHTML : undefined;
if (!n.content) delete n.content;
} else {
if (!saveContent) { delete n.content; }
// check for nested grid
if (n.subGrid) {
n.subGrid = (n.subGrid as GridStack).save(saveContent, true) as GridStackOptions;
}
}
delete n.el;
});
// check if save entire grid options (needed for recursive) + children...
if (saveGridOpt) {
let o: InternalGridStackOptions = Utils.cloneDeep(this.opts);
// delete default values that will be recreated on launch
if (o.marginBottom === o.marginTop && o.marginRight === o.marginLeft && o.marginTop === o.marginRight) {
o.margin = o.marginTop;
delete o.marginTop; delete o.marginRight; delete o.marginBottom; delete o.marginLeft;
}
if (o.rtl === (this.el.style.direction === 'rtl')) { o.rtl = 'auto' }
if (this._isAutoCellHeight) {
o.cellHeight = 'auto'
}
if (this._autoColumn) {
o.column = 'auto';
delete o.disableOneColumnMode;
}
const origShow = o._alwaysShowResizeHandle;
delete o._alwaysShowResizeHandle;
if (origShow !== undefined) {
o.alwaysShowResizeHandle = origShow;
} else {
delete o.alwaysShowResizeHandle;
}
Utils.removeInternalAndSame(o, gridDefaults);
o.children = list;
return o;
}
return list;
}
/**
* load the widgets from a list. This will call update() on each (matching by id) or add/remove widgets that are not there.
*
* @param layout list of widgets definition to update/create
* @param addAndRemove boolean (default true) or callback method can be passed to control if and how missing widgets can be added/removed, giving
* the user control of insertion.
*
* @example
* see http://gridstackjs.com/demo/serialization.html
**/
public load(layout: GridStackWidget[], addAndRemove: boolean | AddRemoveFcn = true): GridStack {
let items = GridStack.Utils.sort([...layout], -1, this._prevColumn || this.getColumn()); // make copy before we mod/sort
this._insertNotAppend = true; // since create in reverse order...
// if we're loading a layout into for example 1 column (_prevColumn is set only when going to 1) and items don't fit, make sure to save
// the original wanted layout so we can scale back up correctly #1471
if (this._prevColumn && this._prevColumn !== this.opts.column && items.some(n => (n.x + n.w) > this.opts.column)) {
this._ignoreLayoutsNodeChange = true; // skip layout update
this.engine.cacheLayout(items, this._prevColumn, true);
}
let removed: GridStackNode[] = [];
this.batchUpdate();
// see if any items are missing from new layout and need to be removed first
if (addAndRemove) {
let copyNodes = [...this.engine.nodes]; // don't loop through array you modify
copyNodes.forEach(n => {
let item = items.find(w => n.id === w.id);
if (!item) {
if (typeof(addAndRemove) === 'function') {
addAndRemove(this, n, false);
} else {
removed.push(n); // batch keep track
this.removeWidget(n.el, true, false);
}
}
});
}
// now add/update the widgets
items.forEach(w => {
let item = (w.id || w.id === 0) ? this.engine.nodes.find(n => n.id === w.id) : undefined;
if (item) {
this.update(item.el, w);
if (w.subGrid && (w.subGrid as GridStackOptions).children) { // update any sub grid as well
let sub = item.el.querySelector('.grid-stack') as GridHTMLElement;
if (sub && sub.gridstack) {
sub.gridstack.load((w.subGrid as GridStackOptions).children); // TODO: support updating grid options ?
this._insertNotAppend = true; // got reset by above call
}
}
} else if (addAndRemove) {
if (typeof(addAndRemove) === 'function') {
w = addAndRemove(this, w, true).gridstackNode;
} else {
w = (w.el ? this.addWidget(w.el, w) : this.addWidget(w)).gridstackNode;
}
}
});
this.engine.removedNodes = removed;
this.batchUpdate(false);
// after commit, clear that flag
delete this._ignoreLayoutsNodeChange;
delete this._insertNotAppend;
return this;
}
/**
* use before calling a bunch of `addWidget()` to prevent un-necessary relayouts in between (more efficient)
* and get a single event callback. You will see no changes until `batchUpdate(false)` is called.
*/
public batchUpdate(flag = true): GridStack {
this.engine.batchUpdate(flag);
if (!flag) {
this._triggerRemoveEvent();
this._triggerAddEvent();
this._triggerChangeEvent();
}
return this;
}
/**
* Gets current cell height.
*/
public getCellHeight(forcePixel = false): number {
if (this.opts.cellHeight && this.opts.cellHeight !== 'auto' &&
(!forcePixel || !this.opts.cellHeightUnit || this.opts.cellHeightUnit === 'px')) {
return this.opts.cellHeight as number;
}
// else get first cell height
let el = this.el.querySelector('.' + this.opts.itemClass) as HTMLElement;
if (el) {
let height = Utils.toNumber(el.getAttribute('gs-h'));
return Math.round(el.offsetHeight / height);
}
// else do entire grid and # of rows (but doesn't work if min-height is the actual constrain)
let rows = parseInt(this.el.getAttribute('gs-current-row'));
return rows ? Math.round(this.el.getBoundingClientRect().height / rows) : this.opts.cellHeight as number;
}
/**
* Update current cell height - see `GridStackOptions.cellHeight` for format.
* This method rebuilds an internal CSS style sheet.
* Note: You can expect performance issues if call this method too often.
*
* @param val the cell height. If not passed (undefined), cells content will be made square (match width minus margin),
* if pass 0 the CSS will be generated by the application instead.
* @param update (Optional) if false, styles will not be updated
*
* @example
* grid.cellHeight(100); // same as 100px
* grid.cellHeight('70px');
* grid.cellHeight(grid.cellWidth() * 1.2);
*/
public cellHeight(val?: numberOrString, update = true): GridStack {
// if not called internally, check if we're changing mode
if (update && val !== undefined) {
if (this._isAutoCellHeight !== (val === 'auto')) {
this._isAutoCellHeight = (val === 'auto');
this._updateWindowResizeEvent();
}
}
if (val === 'initial' || val === 'auto') { val = undefined; }
// make item content be square
if (val === undefined) {
let marginDiff = - (this.opts.marginRight as number) - (this.opts.marginLeft as number)
+ (this.opts.marginTop as number) + (this.opts.marginBottom as number);
val = this.cellWidth() + marginDiff;
}
let data = Utils.parseHeight(val);
if (this.opts.cellHeightUnit === data.unit && this.opts.cellHeight === data.h) {
return this;
}
this.opts.cellHeightUnit = data.unit;
this.opts.cellHeight = data.h;
if (update) {
this._updateStyles(true); // true = force re-create for current # of rows
}
return this;
}
/** Gets current cell width. */
public cellWidth(): number {
return this._widthOrContainer() / this.getColumn();
}
/** return our expected width (or parent) for 1 column check */
protected _widthOrContainer(): number {
// use `offsetWidth` or `clientWidth` (no scrollbar) ?
// https://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively
return (this.el.clientWidth || this.el.parentElement.clientWidth || window.innerWidth);
}
/** re-layout grid items to reclaim any empty space */
public compact(): GridStack {
this.engine.compact();
this._triggerChangeEvent();
return this;
}
/**
* set the number of columns in the grid. Will update existing widgets to conform to new number of columns,
* as well as cache the original layout so you can revert back to previous positions without loss.
* Requires `gridstack-extra.css` or `gridstack-extra.min.css` for [2-11],
* else you will need to generate correct CSS (see https://github.com/gridstack/gridstack.js#change-grid-columns)
* @param column - Integer > 0 (default 12).
* @param layout specify the type of re-layout that will happen (position, size, etc...).
* Note: items will never be outside of the current column boundaries. default (moveScale). Ignored for 1 column
*/
public column(column: number, layout: ColumnOptions = 'moveScale'): GridStack {
if (column < 1 || this.opts.column === column) return this;
let oldColumn = this.getColumn();
// if we go into 1 column mode (which happens if we're sized less than minW unless disableOneColumnMode is on)
// then remember the original columns so we can restore.
if (column === 1) {
this._prevColumn = oldColumn;
} else {
delete this._prevColumn;
}
this.el.classList.remove('grid-stack-' + oldColumn);
this.el.classList.add('grid-stack-' + column);
this.opts.column = this.engine.column = column;
// update the items now - see if the dom order nodes should be passed instead (else default to current list)
let domNodes: GridStackNode[];
if (column === 1 && this.opts.oneColumnModeDomSort) {
domNodes = [];
this.getGridItems().forEach(el => { // get dom elements in order
if (el.gridstackNode) { domNodes.push(el.gridstackNode); }
});
if (!domNodes.length) { domNodes = undefined; }
}
this.engine.updateNodeWidths(oldColumn, column, domNodes, layout);
if (this._isAutoCellHeight) this.cellHeight();
// and trigger our event last...
this._ignoreLayoutsNodeChange = true; // skip layout update
this._triggerChangeEvent();
delete this._ignoreLayoutsNodeChange;
return this;
}
/**
* get the number of columns in the grid (default 12)
*/
public getColumn(): number {
return this.opts.column as number;
}
/** returns an array of grid HTML elements (no placeholder) - used to iterate through our children in DOM order */
public getGridItems(): GridItemHTMLElement[] {
return Array.from(this.el.children)
.filter((el: HTMLElement) => el.matches('.' + this.opts.itemClass) && !el.matches('.' + this.opts.placeholderClass)) as GridItemHTMLElement[];
}
/**
* Destroys a grid instance. DO NOT CALL any methods or access any vars after this as it will free up members.
* @param removeDOM if `false` grid and items HTML elements will not be removed from the DOM (Optional. Default `true`).
*/
public destroy(removeDOM = true): GridStack {
if (!this.el) return; // prevent multiple calls
this._updateWindowResizeEvent(true);
this.setStatic(true, false); // permanently removes DD but don't set CSS class (we're going away)
this.setAnimation(false);
if (!removeDOM) {
this.removeAll(removeDOM);
this.el.classList.remove(this._styleSheetClass);
} else {
this.el.parentNode.removeChild(this.el);
}
this._removeStylesheet();
this.el.removeAttribute('gs-current-row');
delete this.parentGridItem;
delete this.opts;
delete this._placeholder;
delete this.engine;
delete this.el.gridstack; // remove circular dependency that would prevent a freeing
delete this.el;
return this;
}
/**
* enable/disable floating widgets (default: `false`) See [example](http://gridstackjs.com/demo/float.html)
*/
public float(val: boolean): GridStack {
if (this.opts.float !== val) {
this.opts.float = this.engine.float = val;
this._triggerChangeEvent();
}
return this;
}
/**
* get the current float mode
*/
public getFloat(): boolean {
return this.engine.float;
}
/**
* Get the position of the cell under a pixel on screen.
* @param position the position of the pixel to resolve in
* absolute coordinates, as an object with top and left properties
* @param useDocRelative if true, value will be based on document position vs parent position (Optional. Default false).
* Useful when grid is within `position: relative` element
*
* Returns an object with properties `x` and `y` i.e. the column and row in the grid.
*/
public getCellFromPixel(position: MousePosition, useDocRelative = false): CellPosition {
let box = this.el.getBoundingClientRect();
// console.log(`getBoundingClientRect left: ${box.left} top: ${box.top} w: ${box.w} h: ${box.h}`)
let containerPos: {top: number, left: number};
if (useDocRelative) {
containerPos = {top: box.top + document.documentElement.scrollTop, left: box.left};
// console.log(`getCellFromPixel scrollTop: ${document.documentElement.scrollTop}`)
} else {
containerPos = {top: this.el.offsetTop, left: this.el.offsetLeft}
// console.log(`getCellFromPixel offsetTop: ${containerPos.left} offsetLeft: ${containerPos.top}`)
}
let relativeLeft = position.left - containerPos.left;
let relativeTop = position.top - containerPos.top;
let columnWidth = (box.width / this.getColumn());
let rowHeight = (box.height / parseInt(this.el.getAttribute('gs-current-row')));
return {x: Math.floor(relativeLeft / columnWidth), y: Math.floor(relativeTop / rowHeight)};
}
/** returns the current number of rows, which will be at least `minRow` if set */
public getRow(): number {
return Math.max(this.engine.getRow(), this.opts.minRow);
}
/**
* Checks if specified area is empty.
* @param x the position x.
* @param y the position y.
* @param w the width of to check
* @param h the height of to check
*/
public isAreaEmpty(x: number, y: number, w: number, h: number): boolean {
return this.engine.isAreaEmpty(x, y, w, h);
}
/**
* If you add elements to your grid by hand, you have to tell gridstack afterwards to make them widgets.
* If you want gridstack to add the elements for you, use `addWidget()` instead.
* Makes the given element a widget and returns it.
* @param els widget or single selector to convert.
*
* @example
* let grid = GridStack.init();
* grid.el.appendChild('<div id="gsi-1" gs-w="3"></div>');
* grid.makeWidget('#gsi-1');
*/
public makeWidget(els: GridStackElement): GridItemHTMLElement {
let el = GridStack.getElement(els);
this._prepareElement(el, true);
this._updateContainerHeight();
this._triggerAddEvent();
this._triggerChangeEvent();
return el;
}
/**
* Event handler that extracts our CustomEvent data out automatically for receiving custom
* notifications (see doc for supported events)
* @param name of the event (see possible values) or list of names space separated
* @param callback function called with event and optional second/third param
* (see README documentation for each signature).
*
* @example
* grid.on('added', function(e, items) { log('added ', items)} );
* or
* grid.on('added removed change', function(e, items) { log(e.type, items)} );
*
* Note: in some cases it is the same as calling native handler and parsing the event.
* grid.el.addEventListener('added', function(event) { log('added ', event.detail)} );
*
*/
public on(name: GridStackEvent, callback: GridStackEventHandlerCallback): GridStack {
// check for array of names being passed instead
if (name.indexOf(' ') !== -1) {
let names = name.split(' ') as GridStackEvent[];
names.forEach(name => this.on(name, callback));
return this;
}
if (name === 'change' || name === 'added' || name === 'removed' || name === 'enable' || name === 'disable') {
// native CustomEvent handlers - cash the generic handlers so we can easily remove
let noData = (name === 'enable' || name === 'disable');
if (noData) {
this._gsEventHandler[name] = (event: Event) => (callback as GridStackEventHandler)(event);
} else {
this._gsEventHandler[name] = (event: CustomEvent) => (callback as GridStackNodesHandler)(event, event.detail);
}