Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
220 changes: 110 additions & 110 deletions doc/API.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions doc/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ Change log

## 14.1.1 (TBD)
* 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)
* 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
* 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
* fix: `ui-droppable-over` class is now removed when the widget leaves or drops

## 14.1.0 (2026-11-04)
* 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.
Expand Down
1 change: 1 addition & 0 deletions spec/dd-droppable-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ describe('DDDroppable', () => {

expect(DDManager.dropElement).toBeUndefined();
expect(droppable.option.out).toHaveBeenCalled();
expect(element.classList.contains('ui-droppable-over')).toBe(false);
});

it('should not handle mouse leave when not the current drop element', () => {
Expand Down
123 changes: 123 additions & 0 deletions spec/regression-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1438,6 +1438,129 @@ describe('regression >', () => {
expect(DDManager.dropElement).toBe(subDrop());
});

it('drops into a hidden (collapsed) sub-grid as its first widget, which its parent does not push out of the way', () => {
main.addWidget({x: 6, y: 0, w: 6, h: 4, id: 'g2', subGridOpts: {acceptWidgets: true, children: [{x: 0, y: 0, id: 'j'}]}});
const g2 = main.engine.nodes.find(n => n.id === 'g2')!, sub2 = g2.subGrid!, sub2Drop = sub2.el.ddElement!.ddDroppable!;
const cell2Box = box(500, 100, 400, 400);
vi.spyOn(g2.el!, 'getBoundingClientRect').mockImplementation(() => cell2Box);
// a hidden grid isn't hit itself, only its cell (eg: the section header)
(document as unknown as {elementFromPoint: (x: number, y: number) => Element}).elementFromPoint = (x, y) =>
inside(cellBox, x, y) ? sub.el : inside(cell2Box, x, y) ? g2.el! : inside(mainBox, x, y) ? main.el : document.body;
(sub2.el as unknown as {checkVisibility: () => boolean}).checkVisibility = () => false; // jsdom has no layout
delete g2.subGrid; // as an app may do while it's collapsed

moveTo(150, 40); // out to the parent
const accepting = (main as unknown as { _acceptingSubGrid(n: GridStackNode, p: object): GridStackNode | undefined })._acceptingSubGrid;
expect(accepting.call(main, main.engine.nodes.find(n => n.id === 'i')!, {x: 6, y: 0})).toBe(g2);
moveTo(650, 200); // on its middle
expect(DDManager.dropElement).toBe(sub2Drop);
expect(sub2.el.classList.contains('ui-droppable-over')).toBe(true);
const yOf = (id: string) => sub2.engine.nodes.find(n => n.id === id)?.y;
expect([yOf('i'), yOf('j')]).toEqual([0, 1]);
moveTo(150, 40); // out again
expect(sub2.el.classList.contains('ui-droppable-over')).toBe(false);
moveTo(650, 200);
sub2Drop.drop(new MouseEvent('mouseup'));
expect(item.parentElement).toBe(sub2.el);
expect([yOf('i'), yOf('j')]).toEqual([0, 1]);
});

it('goes into a hidden (collapsed) sub-grid from its middle only, so near its edges it goes in between instead', () => {
// two collapsed ones stacked, as tall as the widget: some of it is always over one or the other
const hidden = (y: number, b: DOMRect) => {
const n = main.addWidget({x: 6, y, w: 6, h: 1, subGridOpts: {acceptWidgets: true}}).gridstackNode!;
vi.spyOn(n.el!, 'getBoundingClientRect').mockImplementation(() => b);
(n.subGrid!.el as unknown as {checkVisibility: () => boolean}).checkVisibility = () => false; // jsdom has no layout
return n;
};
const pBox = box(500, 100, 400, 100), sBox = box(500, 200, 400, 100); // middles at y 125-175 and 225-275
const p = hidden(0, pBox), s = hidden(1, sBox);
const pDrop = p.subGrid!.el.ddElement!.ddDroppable!, sDrop = s.subGrid!.el.ddElement!.ddDroppable!;
(document as unknown as {elementFromPoint: (x: number, y: number) => Element}).elementFromPoint = (x, y) =>
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;

moveTo(150, 40); // out to the parent
moveTo(650, 200); // centered on the lower one
expect(DDManager.dropElement).toBe(sDrop);
moveTo(650, 160); // center on its top edge (60% of the widget still over it): in between, in the parent
expect(DDManager.dropElement).toBe(mainDrop());
moveTo(650, 200);
moveTo(650, 125); // its top edge to the upper one's bottom edge: in between too, rather than straight in the upper one
expect(DDManager.dropElement).toBe(mainDrop());
moveTo(650, 100); // centered on the upper one
expect(DDManager.dropElement).toBe(pDrop);
});

it('moves past a collapsed sub-grid in its parent like any widget, but into it from its middle', () => {
vi.spyOn(main, 'cellWidth').mockReturnValue(800 / 12);
vi.spyOn(main, 'getCellHeight').mockReturnValue(100);
main.update(cell, {h: 1}); // collapsed: 1 row, its middle at y 125-175 while at the top
cellBox = box(100, 100, 400, 100);
(sub.el as unknown as {checkVisibility: () => boolean}).checkVisibility = () => false;
(sub as unknown as { _onStartMoving(...a: unknown[]): void })._onStartMoving(item, new Event('dragstart'), {position: {top: 0, left: 0}}, sub.engine.nodes[0], 66, 100);
moveTo(150, 40); // into the parent above it
const g = main.engine.nodes.find(n => n.id === 'g')!, i = main.engine.nodes.find(n => n.id === 'i')!;
expect([i.y, g.y]).toEqual([0, 1]);
// the parent's drag handling, the widget drawn there (top relative to the grid)
const dragTo = (top: number) => {
vi.spyOn(self().helper!, 'getBoundingClientRect').mockReturnValue(box(150, 100 + top, 100, 100));
(main as unknown as { _dragOrResize(...a: unknown[]): void })
._dragOrResize(item, {type: 'drag', target: item}, {position: {left: 0, top}}, i, 800 / 12, 100);
};
dragTo(80); // down onto it: past it
expect([g.y, i.y]).toEqual([0, 1]);
dragTo(30); // back up, center on its middle: stay below it (going in)
expect([g.y, i.y]).toEqual([0, 1]);
dragTo(-30); // center on its top edge: above it
expect(g.y).toBe(1);
expect(i.y).toBeLessThan(1);
});

it('goes by the grabbed handle, so a tall widget leaves by its header', () => {
mainBox = box(100, 0, 800, 500); // room above the sub-grid
moveTo(150, 80); // 80% of the widget still over the sub-grid
expect(DDManager.dropElement).toBe(subDrop());
const content = item.querySelector<HTMLElement>('.grid-stack-item-content')!; // the handle
vi.spyOn(item, 'getBoundingClientRect').mockReturnValue(box(150, 150, 100, 100));
vi.spyOn(content, 'getBoundingClientRect').mockReturnValue(box(150, 150, 100, 20));
const d = dd as unknown as { mouseDownEvent: object, _handleBox?: object, _getHandleBox(): object };
d.mouseDownEvent = {target: content};
d._handleBox = d._getHandleBox();
expect(d._handleBox).toEqual({left: 0, top: 0, width: 100, height: 20});
moveTo(150, 81); // the handle is out
expect(DDManager.dropElement).toBe(mainDrop());
});

it('grows a small handle to 10% of the widget each way, kept inside it', () => {
const content = item.querySelector<HTMLElement>('.grid-stack-item-content')!;
const d = dd as unknown as { mouseDownEvent: object, _getHandleBox(): object | undefined };
d.mouseDownEvent = {target: content};
vi.spyOn(item, 'getBoundingClientRect').mockReturnValue(box(0, 0, 200, 400));
const handleAt = (b: DOMRect) => { vi.spyOn(content, 'getBoundingClientRect').mockReturnValue(b); return d._getHandleBox(); };
expect(handleAt(box(0, 0, 200, 20))).toEqual({left: 0, top: 0, width: 200, height: 40}); // header: taller, down from the top
expect(handleAt(box(90, 190, 4, 4))).toEqual({left: 82, top: 172, width: 20, height: 40}); // grip: around its center
expect(handleAt(box(196, 396, 4, 4))).toEqual({left: 180, top: 360, width: 20, height: 40}); // in the corner: slid back inside
expect(handleAt(box(0, 0, 0, 0))).toBeUndefined(); // nothing to measure: the whole widget
});

it('comes out of a sub-grid on the side its grabbed handle is, not the widget center', () => {
vi.spyOn(main, 'cellWidth').mockReturnValue(800 / 12);
vi.spyOn(main, 'getCellHeight').mockReturnValue(100);
vi.spyOn(sub, 'getCellHeight').mockReturnValue(100);
main.mode('float');
main.update(cell, {y: 1, h: 2}); // rows 1-2, center at 2
cellBox = box(100, 100, 400, 200);
mainBox = box(100, 0, 800, 500);
sub.update(item, {w: 6, h: 3});
(sub as unknown as { _onStartMoving(...a: unknown[]): void })._onStartMoving(item, new Event('dragstart'), {position: {top: 0, left: 0}}, sub.engine.nodes[0], 66, 100);
dd._handleBox = {left: 0, top: 0, width: 400, height: 60}; // its top 60px
vi.spyOn(self().helper!, 'getBoundingClientRect').mockReturnValue(box(100, 60, 400, 300)); // center below the sub-grid's, handle above
self()._checkDropTarget(new MouseEvent('mousemove'));
const g = main.engine.nodes.find(n => n.id === 'g')!, i = main.engine.nodes.find(n => n.id === 'i')!;
expect(DDManager.dropElement).toBe(mainDrop());
expect(i.y).toBeLessThan(g.y!); // above it (by the widget center, it'd be below)
});

it('coming out of a sub-grid below or beside it lands there in the parent, not above it (pushed out of the way)', () => {
vi.spyOn(main, 'cellWidth').mockReturnValue(800 / 12);
vi.spyOn(main, 'getCellHeight').mockReturnValue(100);
Expand Down
49 changes: 44 additions & 5 deletions src/dd-draggable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { DDManager } from './dd-manager';
import { Box, DDDroppable } from './dd-droppable';
import { DragTransform, Utils } from './utils';
import { DDBaseImplement, HTMLElementExtendOpt } from './dd-base-impl';
import { GridItemHTMLElement, DDUIData, GridStackNode, GridStackPosition, DDDragOpt } from './types';
import { GridItemHTMLElement, DDUIData, GridStackNode, GridStackPosition, DDDragOpt, Rect } from './types';
import { DDElementHost } from './dd-element';
import { isTouch, touchend, touchmove, touchstart, cancelPendingTouchDrag, DDTouch } from './dd-touch';
import { GridHTMLElement } from './gridstack';
Expand Down Expand Up @@ -65,6 +65,10 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
};
/** @internal element we bound the touch handlers to in _mouseDown(), so _mouseUp() can un-bind the same one */
protected _touchTarget?: HTMLElement;
/** @internal the grabbed handle's spot in the widget (px), set at drag start, see _getHandleBox() */
public _handleBox?: Rect;
/** @internal smallest the handle drop targets are measured by can be, as a fraction of the widget each way */
public static minDropShape = 0.1;
/** @internal how far the helper's containing block has slid since dragstart.
* A transform on an ancestor makes IT - not the viewport - the containing block for our
* position:fixed helper, so the left/top we write are relative to that element, and it scrolls
Expand Down Expand Up @@ -293,7 +297,40 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
*/
public _overlap(drop: DDDroppable, rect: Box): number | undefined {
if (drop.eventEl !== drop.el && drop.eventEl.getAnimations?.().some(a => 'transitionProperty' in a)) return undefined;
return DDDroppable.overlap(rect, drop.eventEl.getBoundingClientRect());
const b = drop.eventEl.getBoundingClientRect();
// a hidden one (eg: collapsed sub-grid) is a single slot, like a folder: all in from its middle, out at its edges
if (drop.el.checkVisibility?.() === false) return DDDroppable.inMiddle(rect, b) ? 1 : 0;
return DDDroppable.overlap(rect, b);
}

/** @internal what's measured against drop targets (screen px): the grabbed handle (see _getHandleBox), the widget, else the cursor */
public _dropShape(e: MouseEvent): Box {
const s = this.helper?.getBoundingClientRect();
if (!s?.width || !s.height) return { left: e.clientX, top: e.clientY, right: e.clientX + 1, bottom: e.clientY + 1, width: 1, height: 1 };
const b = this._handleBox;
if (!b) return s;
const left = s.left + b.left, top = s.top + b.top;
return { left, top, width: b.width, height: b.height, right: left + b.width, bottom: top + b.height };
}

/**
* @internal the grabbed handle's spot in the widget (px), so a widget dragged by a header goes where that is rather than mostly
* past an edge. Grown to at least minDropShape of the widget each way (a tiny handle isn't much to hit), kept inside it.
*/
protected _getHandleBox(): Rect | undefined {
const target = this.mouseDownEvent?.target as Node | undefined;
const handle = target && this.dragEls.find(h => h !== this.el && h.contains(target));
if (!handle) return undefined;
const i = this.el.getBoundingClientRect(), h = handle.getBoundingClientRect();
if (!h.width || !h.height) return undefined;
// grow around its center, then slide back inside the widget
const fit = (start: number, size: number, max: number): [number, number] => {
const s = Math.min(max, Math.max(size, max * DDDraggable.minDropShape));
return [Math.max(0, Math.min(max - s, start - (s - size) / 2)), s];
};
const [left, width] = fit(h.left - i.left, h.width, i.width);
const [top, height] = fit(h.top - i.top, h.height, i.height);
return { left, top, width, height };
}

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

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

delete this._handleBox;
DDManager.dropElement?.el.classList.remove('ui-droppable-over');
// reset the drop target if dragging over ourself (already parented, just moving during stop callback below)
if (DDManager.dropElement?.el === this.el.parentElement) {
delete DDManager.dropElement;
Expand Down Expand Up @@ -483,6 +521,7 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
.setAnimation();
n._moving = true;
this.dragOffset = this._getDragOffset(this.lastDrag, n.el!, this.helperContainment);
this._handleBox = this._getHandleBox();
this.helper!.style.width = this.dragOffset.width + 'px';
this.helper!.style.height = this.dragOffset.height + 'px';
Utils.swap(n._orig, 'w', 'h');
Expand Down
9 changes: 9 additions & 0 deletions src/dd-droppable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ export class DDDroppable extends DDBaseImplement implements HTMLElementExtendOpt
public static stayOver = { grid: 0.25, sub: 0.5, trash: 0.4 };
/** @internal how much more of the dragged item must be over a neighbor grid than the one it's in to switch to it */
public static switchBy = 0.2;
/** @internal edge of a hidden target (eg: collapsed sub-grid), as part of its smaller side, that puts us beside it */
public static hiddenEdge = 0.25;

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

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

/** @internal if a's center is inside b, away from its edges (see hiddenEdge) */
public static inMiddle(a: Box, b: Box): boolean {
const x = a.left + a.width / 2, y = a.top + a.height / 2, m = Math.min(b.width, b.height) * DDDroppable.hiddenEdge;
return x > b.left + m && x < b.right - m && y > b.top + m && y < b.bottom - m;
}

/** @internal the closest droppable above us (the parent grid when we're a sub-grid) */
public parentDroppable(): DDDroppable | undefined {
for (let el = DDDroppable.parentOf(this.el); el; el = DDDroppable.parentOf(el)) {
Expand Down
Loading