Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d34d1d3

Browse files
authored
Fixed algorithm for fixing width of item
1 parent 57c6511 commit d34d1d3

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

src/gridstack.js

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1672,10 +1672,41 @@
16721672
this.grid._sortNodes();
16731673
this.grid.batchUpdate();
16741674
var node = {};
1675-
for (var i = 0; i < this.grid.nodes.length; i++) {
1676-
node = this.grid.nodes[i];
1677-
this.update(node.el, Math.round(node.x * newWidth / oldWidth), undefined,
1678-
Math.round(node.width * newWidth / oldWidth), undefined);
1675+
1676+
// We need an array of the elements to update so that we make sure that
1677+
// each item in the grid gets processed. We need to get a fixed list of
1678+
// array items, because the this.update() can shift items in the this.grid.nodes
1679+
// array which can lead to elements not being processed.
1680+
var nodes = _.map(this.grid.nodes, 'el')
1681+
, columnPos, columnWidth;
1682+
1683+
for (var i = 0; i < nodes.length; i++) {
1684+
// get the current live node data, in case a previous update has changed anything
1685+
node = this.grid.getNodeDataByDOMEl(nodes[i]);
1686+
/*
1687+
* Calculate the new column position for the item, but make sure it fits inside the
1688+
* grid range. If the calculated position is outside the range, then it will move
1689+
* it to the last column (newWidth-1).
1690+
*/
1691+
columnPos = Math.min(Math.round(node.x * newWidth / oldWidth), newWidth-1);
1692+
// calculate the new width of the item
1693+
columnWidth = Math.round(node.width * newWidth / oldWidth);
1694+
1695+
// if the item is too wide, we need to adjust our calculations
1696+
if( columnPos + columnWidth > newWidth ){
1697+
/*
1698+
* To keep the original calculated width, we could just move the item to the left to
1699+
* fit within the width of the grid, but this would cause other items to shift:
1700+
*
1701+
* columnPos = newWidth - columnWidth;
1702+
*
1703+
* Instead of shifting other items around, we will just make sure the item's
1704+
* width is resized to fit inside the width of the grid.
1705+
*/
1706+
columnWidth = columnWidth - ((columnPos + columnWidth) - newWidth);
1707+
}
1708+
1709+
this.update(node.el, columnPos, undefined, columnWidth, undefined);
16791710
}
16801711
this.grid.commit();
16811712
};

0 commit comments

Comments
 (0)