Skip to content

Commit ea35082

Browse files
authored
Merge pull request #3463 from adumesny/master
drop target goes by the grabbed handle
2 parents 400eb8c + 14f9b3e commit ea35082

7 files changed

Lines changed: 321 additions & 121 deletions

File tree

‎doc/API.md‎

Lines changed: 110 additions & 110 deletions
Large diffs are not rendered by default.

‎doc/CHANGES.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,9 @@ Change log
151151

152152
## 14.1.1 (TBD)
153153
* fix: [#3459](https://github.com/gridstack/gridstack.js/issues/3459) React/Vue wrappers: a `change` event fired mid drag/resize no longer unmounts the item's content (state lost)
154+
* feat: [#3463](https://github.com/gridstack/gridstack.js/pull/3463) drop target goes by the grabbed handle (min 10%) rather than the whole widget, so widgets dragged by a header follow the mouse more closely
155+
* feat: a hidden (collapsed) sub-grid works like a folder: the widget goes in (as its first widget) from its middle, and beside it near its edges, so you can insert between collapsed ones
156+
* fix: `ui-droppable-over` class is now removed when the widget leaves or drops
154157

155158
## 14.1.0 (2026-11-04)
156159
* feat: [#3451](https://github.com/gridstack/gridstack.js/pull/3451), [#3452](https://github.com/gridstack/gridstack.js/pull/3452) dragging between grids now goes by how much of the item is over a grid (like jquery-ui's `intersect` before v6) rather than where the cursor is. Also make it possible to insert above a nested grid even when parent grid overlapps exactly.

‎spec/dd-droppable-spec.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,7 @@ describe('DDDroppable', () => {
208208

209209
expect(DDManager.dropElement).toBeUndefined();
210210
expect(droppable.option.out).toHaveBeenCalled();
211+
expect(element.classList.contains('ui-droppable-over')).toBe(false);
211212
});
212213

213214
it('should not handle mouse leave when not the current drop element', () => {

‎spec/regression-spec.ts‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1438,6 +1438,129 @@ describe('regression >', () => {
14381438
expect(DDManager.dropElement).toBe(subDrop());
14391439
});
14401440

1441+
it('drops into a hidden (collapsed) sub-grid as its first widget, which its parent does not push out of the way', () => {
1442+
main.addWidget({x: 6, y: 0, w: 6, h: 4, id: 'g2', subGridOpts: {acceptWidgets: true, children: [{x: 0, y: 0, id: 'j'}]}});
1443+
const g2 = main.engine.nodes.find(n => n.id === 'g2')!, sub2 = g2.subGrid!, sub2Drop = sub2.el.ddElement!.ddDroppable!;
1444+
const cell2Box = box(500, 100, 400, 400);
1445+
vi.spyOn(g2.el!, 'getBoundingClientRect').mockImplementation(() => cell2Box);
1446+
// a hidden grid isn't hit itself, only its cell (eg: the section header)
1447+
(document as unknown as {elementFromPoint: (x: number, y: number) => Element}).elementFromPoint = (x, y) =>
1448+
inside(cellBox, x, y) ? sub.el : inside(cell2Box, x, y) ? g2.el! : inside(mainBox, x, y) ? main.el : document.body;
1449+
(sub2.el as unknown as {checkVisibility: () => boolean}).checkVisibility = () => false; // jsdom has no layout
1450+
delete g2.subGrid; // as an app may do while it's collapsed
1451+
1452+
moveTo(150, 40); // out to the parent
1453+
const accepting = (main as unknown as { _acceptingSubGrid(n: GridStackNode, p: object): GridStackNode | undefined })._acceptingSubGrid;
1454+
expect(accepting.call(main, main.engine.nodes.find(n => n.id === 'i')!, {x: 6, y: 0})).toBe(g2);
1455+
moveTo(650, 200); // on its middle
1456+
expect(DDManager.dropElement).toBe(sub2Drop);
1457+
expect(sub2.el.classList.contains('ui-droppable-over')).toBe(true);
1458+
const yOf = (id: string) => sub2.engine.nodes.find(n => n.id === id)?.y;
1459+
expect([yOf('i'), yOf('j')]).toEqual([0, 1]);
1460+
moveTo(150, 40); // out again
1461+
expect(sub2.el.classList.contains('ui-droppable-over')).toBe(false);
1462+
moveTo(650, 200);
1463+
sub2Drop.drop(new MouseEvent('mouseup'));
1464+
expect(item.parentElement).toBe(sub2.el);
1465+
expect([yOf('i'), yOf('j')]).toEqual([0, 1]);
1466+
});
1467+
1468+
it('goes into a hidden (collapsed) sub-grid from its middle only, so near its edges it goes in between instead', () => {
1469+
// two collapsed ones stacked, as tall as the widget: some of it is always over one or the other
1470+
const hidden = (y: number, b: DOMRect) => {
1471+
const n = main.addWidget({x: 6, y, w: 6, h: 1, subGridOpts: {acceptWidgets: true}}).gridstackNode!;
1472+
vi.spyOn(n.el!, 'getBoundingClientRect').mockImplementation(() => b);
1473+
(n.subGrid!.el as unknown as {checkVisibility: () => boolean}).checkVisibility = () => false; // jsdom has no layout
1474+
return n;
1475+
};
1476+
const pBox = box(500, 100, 400, 100), sBox = box(500, 200, 400, 100); // middles at y 125-175 and 225-275
1477+
const p = hidden(0, pBox), s = hidden(1, sBox);
1478+
const pDrop = p.subGrid!.el.ddElement!.ddDroppable!, sDrop = s.subGrid!.el.ddElement!.ddDroppable!;
1479+
(document as unknown as {elementFromPoint: (x: number, y: number) => Element}).elementFromPoint = (x, y) =>
1480+
inside(cellBox, x, y) ? sub.el : inside(pBox, x, y) ? p.el! : inside(sBox, x, y) ? s.el! : inside(mainBox, x, y) ? main.el : document.body;
1481+
1482+
moveTo(150, 40); // out to the parent
1483+
moveTo(650, 200); // centered on the lower one
1484+
expect(DDManager.dropElement).toBe(sDrop);
1485+
moveTo(650, 160); // center on its top edge (60% of the widget still over it): in between, in the parent
1486+
expect(DDManager.dropElement).toBe(mainDrop());
1487+
moveTo(650, 200);
1488+
moveTo(650, 125); // its top edge to the upper one's bottom edge: in between too, rather than straight in the upper one
1489+
expect(DDManager.dropElement).toBe(mainDrop());
1490+
moveTo(650, 100); // centered on the upper one
1491+
expect(DDManager.dropElement).toBe(pDrop);
1492+
});
1493+
1494+
it('moves past a collapsed sub-grid in its parent like any widget, but into it from its middle', () => {
1495+
vi.spyOn(main, 'cellWidth').mockReturnValue(800 / 12);
1496+
vi.spyOn(main, 'getCellHeight').mockReturnValue(100);
1497+
main.update(cell, {h: 1}); // collapsed: 1 row, its middle at y 125-175 while at the top
1498+
cellBox = box(100, 100, 400, 100);
1499+
(sub.el as unknown as {checkVisibility: () => boolean}).checkVisibility = () => false;
1500+
(sub as unknown as { _onStartMoving(...a: unknown[]): void })._onStartMoving(item, new Event('dragstart'), {position: {top: 0, left: 0}}, sub.engine.nodes[0], 66, 100);
1501+
moveTo(150, 40); // into the parent above it
1502+
const g = main.engine.nodes.find(n => n.id === 'g')!, i = main.engine.nodes.find(n => n.id === 'i')!;
1503+
expect([i.y, g.y]).toEqual([0, 1]);
1504+
// the parent's drag handling, the widget drawn there (top relative to the grid)
1505+
const dragTo = (top: number) => {
1506+
vi.spyOn(self().helper!, 'getBoundingClientRect').mockReturnValue(box(150, 100 + top, 100, 100));
1507+
(main as unknown as { _dragOrResize(...a: unknown[]): void })
1508+
._dragOrResize(item, {type: 'drag', target: item}, {position: {left: 0, top}}, i, 800 / 12, 100);
1509+
};
1510+
dragTo(80); // down onto it: past it
1511+
expect([g.y, i.y]).toEqual([0, 1]);
1512+
dragTo(30); // back up, center on its middle: stay below it (going in)
1513+
expect([g.y, i.y]).toEqual([0, 1]);
1514+
dragTo(-30); // center on its top edge: above it
1515+
expect(g.y).toBe(1);
1516+
expect(i.y).toBeLessThan(1);
1517+
});
1518+
1519+
it('goes by the grabbed handle, so a tall widget leaves by its header', () => {
1520+
mainBox = box(100, 0, 800, 500); // room above the sub-grid
1521+
moveTo(150, 80); // 80% of the widget still over the sub-grid
1522+
expect(DDManager.dropElement).toBe(subDrop());
1523+
const content = item.querySelector<HTMLElement>('.grid-stack-item-content')!; // the handle
1524+
vi.spyOn(item, 'getBoundingClientRect').mockReturnValue(box(150, 150, 100, 100));
1525+
vi.spyOn(content, 'getBoundingClientRect').mockReturnValue(box(150, 150, 100, 20));
1526+
const d = dd as unknown as { mouseDownEvent: object, _handleBox?: object, _getHandleBox(): object };
1527+
d.mouseDownEvent = {target: content};
1528+
d._handleBox = d._getHandleBox();
1529+
expect(d._handleBox).toEqual({left: 0, top: 0, width: 100, height: 20});
1530+
moveTo(150, 81); // the handle is out
1531+
expect(DDManager.dropElement).toBe(mainDrop());
1532+
});
1533+
1534+
it('grows a small handle to 10% of the widget each way, kept inside it', () => {
1535+
const content = item.querySelector<HTMLElement>('.grid-stack-item-content')!;
1536+
const d = dd as unknown as { mouseDownEvent: object, _getHandleBox(): object | undefined };
1537+
d.mouseDownEvent = {target: content};
1538+
vi.spyOn(item, 'getBoundingClientRect').mockReturnValue(box(0, 0, 200, 400));
1539+
const handleAt = (b: DOMRect) => { vi.spyOn(content, 'getBoundingClientRect').mockReturnValue(b); return d._getHandleBox(); };
1540+
expect(handleAt(box(0, 0, 200, 20))).toEqual({left: 0, top: 0, width: 200, height: 40}); // header: taller, down from the top
1541+
expect(handleAt(box(90, 190, 4, 4))).toEqual({left: 82, top: 172, width: 20, height: 40}); // grip: around its center
1542+
expect(handleAt(box(196, 396, 4, 4))).toEqual({left: 180, top: 360, width: 20, height: 40}); // in the corner: slid back inside
1543+
expect(handleAt(box(0, 0, 0, 0))).toBeUndefined(); // nothing to measure: the whole widget
1544+
});
1545+
1546+
it('comes out of a sub-grid on the side its grabbed handle is, not the widget center', () => {
1547+
vi.spyOn(main, 'cellWidth').mockReturnValue(800 / 12);
1548+
vi.spyOn(main, 'getCellHeight').mockReturnValue(100);
1549+
vi.spyOn(sub, 'getCellHeight').mockReturnValue(100);
1550+
main.mode('float');
1551+
main.update(cell, {y: 1, h: 2}); // rows 1-2, center at 2
1552+
cellBox = box(100, 100, 400, 200);
1553+
mainBox = box(100, 0, 800, 500);
1554+
sub.update(item, {w: 6, h: 3});
1555+
(sub as unknown as { _onStartMoving(...a: unknown[]): void })._onStartMoving(item, new Event('dragstart'), {position: {top: 0, left: 0}}, sub.engine.nodes[0], 66, 100);
1556+
dd._handleBox = {left: 0, top: 0, width: 400, height: 60}; // its top 60px
1557+
vi.spyOn(self().helper!, 'getBoundingClientRect').mockReturnValue(box(100, 60, 400, 300)); // center below the sub-grid's, handle above
1558+
self()._checkDropTarget(new MouseEvent('mousemove'));
1559+
const g = main.engine.nodes.find(n => n.id === 'g')!, i = main.engine.nodes.find(n => n.id === 'i')!;
1560+
expect(DDManager.dropElement).toBe(mainDrop());
1561+
expect(i.y).toBeLessThan(g.y!); // above it (by the widget center, it'd be below)
1562+
});
1563+
14411564
it('coming out of a sub-grid below or beside it lands there in the parent, not above it (pushed out of the way)', () => {
14421565
vi.spyOn(main, 'cellWidth').mockReturnValue(800 / 12);
14431566
vi.spyOn(main, 'getCellHeight').mockReturnValue(100);

‎src/dd-draggable.ts‎

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { DDManager } from './dd-manager';
77
import { Box, DDDroppable } from './dd-droppable';
88
import { DragTransform, Utils } from './utils';
99
import { DDBaseImplement, HTMLElementExtendOpt } from './dd-base-impl';
10-
import { GridItemHTMLElement, DDUIData, GridStackNode, GridStackPosition, DDDragOpt } from './types';
10+
import { GridItemHTMLElement, DDUIData, GridStackNode, GridStackPosition, DDDragOpt, Rect } from './types';
1111
import { DDElementHost } from './dd-element';
1212
import { isTouch, touchend, touchmove, touchstart, cancelPendingTouchDrag, DDTouch } from './dd-touch';
1313
import { GridHTMLElement } from './gridstack';
@@ -65,6 +65,10 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
6565
};
6666
/** @internal element we bound the touch handlers to in _mouseDown(), so _mouseUp() can un-bind the same one */
6767
protected _touchTarget?: HTMLElement;
68+
/** @internal the grabbed handle's spot in the widget (px), set at drag start, see _getHandleBox() */
69+
public _handleBox?: Rect;
70+
/** @internal smallest the handle drop targets are measured by can be, as a fraction of the widget each way */
71+
public static minDropShape = 0.1;
6872
/** @internal how far the helper's containing block has slid since dragstart.
6973
* A transform on an ancestor makes IT - not the viewport - the containing block for our
7074
* position:fixed helper, so the left/top we write are relative to that element, and it scrolls
@@ -293,7 +297,40 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
293297
*/
294298
public _overlap(drop: DDDroppable, rect: Box): number | undefined {
295299
if (drop.eventEl !== drop.el && drop.eventEl.getAnimations?.().some(a => 'transitionProperty' in a)) return undefined;
296-
return DDDroppable.overlap(rect, drop.eventEl.getBoundingClientRect());
300+
const b = drop.eventEl.getBoundingClientRect();
301+
// a hidden one (eg: collapsed sub-grid) is a single slot, like a folder: all in from its middle, out at its edges
302+
if (drop.el.checkVisibility?.() === false) return DDDroppable.inMiddle(rect, b) ? 1 : 0;
303+
return DDDroppable.overlap(rect, b);
304+
}
305+
306+
/** @internal what's measured against drop targets (screen px): the grabbed handle (see _getHandleBox), the widget, else the cursor */
307+
public _dropShape(e: MouseEvent): Box {
308+
const s = this.helper?.getBoundingClientRect();
309+
if (!s?.width || !s.height) return { left: e.clientX, top: e.clientY, right: e.clientX + 1, bottom: e.clientY + 1, width: 1, height: 1 };
310+
const b = this._handleBox;
311+
if (!b) return s;
312+
const left = s.left + b.left, top = s.top + b.top;
313+
return { left, top, width: b.width, height: b.height, right: left + b.width, bottom: top + b.height };
314+
}
315+
316+
/**
317+
* @internal the grabbed handle's spot in the widget (px), so a widget dragged by a header goes where that is rather than mostly
318+
* past an edge. Grown to at least minDropShape of the widget each way (a tiny handle isn't much to hit), kept inside it.
319+
*/
320+
protected _getHandleBox(): Rect | undefined {
321+
const target = this.mouseDownEvent?.target as Node | undefined;
322+
const handle = target && this.dragEls.find(h => h !== this.el && h.contains(target));
323+
if (!handle) return undefined;
324+
const i = this.el.getBoundingClientRect(), h = handle.getBoundingClientRect();
325+
if (!h.width || !h.height) return undefined;
326+
// grow around its center, then slide back inside the widget
327+
const fit = (start: number, size: number, max: number): [number, number] => {
328+
const s = Math.min(max, Math.max(size, max * DDDraggable.minDropShape));
329+
return [Math.max(0, Math.min(max - s, start - (s - size) / 2)), s];
330+
};
331+
const [left, width] = fit(h.left - i.left, h.width, i.width);
332+
const [top, height] = fit(h.top - i.top, h.height, i.height);
333+
return { left, top, width, height };
297334
}
298335

299336
/**
@@ -305,9 +342,7 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
305342
* more of it over that one than ours (switchBy).
306343
*/
307344
protected _checkDropTarget(e: MouseEvent): void {
308-
const shape = this.helper?.getBoundingClientRect();
309-
const rect: Box = shape?.width && shape.height ? shape // else nothing to measure (an unsized helper): go by the cursor
310-
: { left: e.clientX, top: e.clientY, right: e.clientX + 1, bottom: e.clientY + 1, width: 1, height: 1 };
345+
const rect = this._dropShape(e);
311346
const cur = DDManager.dropElement;
312347

313348
// drop targets under the item's center, innermost first - looking inside web components, as elementFromPoint() stops at their host
@@ -377,6 +412,7 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
377412
Utils.pauseIframePointerEvents(true);
378413
this.el.classList.remove('ui-draggable-armed');
379414
DDManager.dragElement = this;
415+
this._handleBox = this._getHandleBox(); // before the helper moves
380416
// if we're dragging an actual grid item, set the current drop as the grid (to detect enter/leave)
381417
const grid = this.el.gridstackNode?.grid;
382418
if (grid) {
@@ -429,6 +465,8 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
429465
document.removeEventListener('scroll', this._updateCBDrift, true);
430466
this._cbDrift = { dx: 0, dy: 0 };
431467

468+
delete this._handleBox;
469+
DDManager.dropElement?.el.classList.remove('ui-droppable-over');
432470
// reset the drop target if dragging over ourself (already parented, just moving during stop callback below)
433471
if (DDManager.dropElement?.el === this.el.parentElement) {
434472
delete DDManager.dropElement;
@@ -483,6 +521,7 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
483521
.setAnimation();
484522
n._moving = true;
485523
this.dragOffset = this._getDragOffset(this.lastDrag, n.el!, this.helperContainment);
524+
this._handleBox = this._getHandleBox();
486525
this.helper!.style.width = this.dragOffset.width + 'px';
487526
this.helper!.style.height = this.dragOffset.height + 'px';
488527
Utils.swap(n._orig, 'w', 'h');

‎src/dd-droppable.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ export class DDDroppable extends DDBaseImplement implements HTMLElementExtendOpt
4141
public static stayOver = { grid: 0.25, sub: 0.5, trash: 0.4 };
4242
/** @internal how much more of the dragged item must be over a neighbor grid than the one it's in to switch to it */
4343
public static switchBy = 0.2;
44+
/** @internal edge of a hidden target (eg: collapsed sub-grid), as part of its smaller side, that puts us beside it */
45+
public static hiddenEdge = 0.25;
4446

4547
constructor(public el: HTMLElement, public option: DDDroppableOpt = {}) {
4648
super();
@@ -126,6 +128,7 @@ export class DDDroppable extends DDBaseImplement implements HTMLElementExtendOpt
126128
this.option.out(ev, this._ui(DDManager.dragElement))
127129
}
128130
this.triggerEvent('dropout', ev);
131+
this.el.classList.remove('ui-droppable-over');
129132

130133
if (DDManager.dropElement === this) {
131134
delete DDManager.dropElement;
@@ -141,6 +144,12 @@ export class DDDroppable extends DDBaseImplement implements HTMLElementExtendOpt
141144
return w > 0 && h > 0 && area > 0 ? (w * h) / area : 0;
142145
}
143146

147+
/** @internal if a's center is inside b, away from its edges (see hiddenEdge) */
148+
public static inMiddle(a: Box, b: Box): boolean {
149+
const x = a.left + a.width / 2, y = a.top + a.height / 2, m = Math.min(b.width, b.height) * DDDroppable.hiddenEdge;
150+
return x > b.left + m && x < b.right - m && y > b.top + m && y < b.bottom - m;
151+
}
152+
144153
/** @internal the closest droppable above us (the parent grid when we're a sub-grid) */
145154
public parentDroppable(): DDDroppable | undefined {
146155
for (let el = DDDroppable.parentOf(this.el); el; el = DDDroppable.parentOf(el)) {

0 commit comments

Comments
 (0)