@@ -658,6 +658,7 @@ export class GridStack {
658658 * see http://gridstackjs.com/demo/serialization.html
659659 */
660660 public load ( items : GridStackWidget [ ] , addRemove : boolean | AddRemoveFcn = GridStack . addRemoveCB || true ) : GridStack {
661+ items = Utils . cloneDeep ( items ) ; // so we can mod
661662 // if passed list has coordinates, use them (insert from end to beginning for conflict resolution) else force widget same order
662663 const haveCoord = items . some ( w => w . x !== undefined || w . y !== undefined ) ;
663664 if ( haveCoord ) items = Utils . sort ( items , - 1 , this . _prevColumn || this . getColumn ( ) ) ;
@@ -692,18 +693,34 @@ export class GridStack {
692693 } ) ;
693694 }
694695
695- // now add/update the widgets
696+ // now add/update the widgets - starting with removing items in the new layout we will reposition
697+ // to reduce collision and add no-coord ones at next available spot
698+ let updateNodes : GridStackWidget [ ] = [ ] ;
699+ this . engine . nodes = this . engine . nodes . filter ( n => {
700+ if ( Utils . find ( items , n . id ) ) { updateNodes . push ( n ) ; return false ; } // remove if found from list
701+ return true ;
702+ } ) ;
696703 let widthChanged = false ;
697704 items . forEach ( w => {
698- let item = Utils . find ( this . engine . nodes , w . id ) ;
705+ let item = Utils . find ( updateNodes , w . id ) ;
699706 if ( item ) {
707+ // if item sizes to content, re-use the exiting height so it's a better guess at the final size 9same if width doesn't change)
708+ if ( Utils . shouldSizeToContent ( item ) ) w . h = item . h ;
700709 // check if missing coord, in which case find next empty slot with new (or old if missing) sizes
701710 if ( w . autoPosition || w . x === undefined || w . y === undefined ) {
702711 w . w = w . w || item . w ;
703712 w . h = w . h || item . h ;
704713 this . engine . findEmptyPosition ( w ) ;
705714 }
706715 widthChanged = widthChanged || ( w . w !== undefined && w . w !== item . w ) ;
716+
717+ // 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
718+ this . engine . nodes . push ( item ) ;
719+ if ( Utils . samePos ( item , w ) ) {
720+ this . moveNode ( item , { ...w , forceCollide : true } ) ;
721+ Utils . copyPos ( w , item , true ) ;
722+ }
723+
707724 this . update ( item . el , w ) ;
708725 if ( w . subGridOpts ?. children ) { // update any sub grid as well
709726 let sub = item . el . querySelector ( '.grid-stack' ) as GridHTMLElement ;
0 commit comments