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
1 change: 1 addition & 0 deletions doc/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ Change log
<!-- END doctoc generated TOC please keep comment here to allow auto update -->

## 14.0.1 (TBD)
* feat: [#3443](https://github.com/gridstack/gridstack.js/pull/3443) 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.
* feat: [#3356](https://github.com/gridstack/gridstack.js/issues/3356) auto-scroll triggers off the cursor nearing an edge (not just widget being clipped)
* fix: [#3355](https://github.com/gridstack/gridstack.js/issues/3355) auto-scroll hands off to the outer container when a nested scroll container is pinned
* fix: [#2729](https://github.com/gridstack/gridstack.js/issues/2729) `cancel` selector now matches elements inside a shadow root
Expand Down
254 changes: 254 additions & 0 deletions spec/regression-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1231,4 +1231,258 @@ describe('regression >', () => {
}
});
});
describe('drop target by item shape, not the cursor >', () => {
let main: GridStack, sub: GridStack, item: GridItemHTMLElement, dd: DDDraggable;
let cell: HTMLElement & { getAnimations?: () => object[] }; // the sub-grid's .grid-stack-item
let cellBox: DOMRect, mainBox: DOMRect, otherBox: DOMRect | undefined, other: GridStack | undefined;
const box = (left: number, top: number, w: number, h: number) =>
({left, top, right: left + w, bottom: top + h, width: w, height: h, x: left, y: top} as DOMRect);
const inside = (b: DOMRect | undefined, x: number, y: number) => !!b && x >= b.left && x <= b.right && y >= b.top && y <= b.bottom;
type Drop = { _domEnter(e: MouseEvent): void; _domLeave(e: MouseEvent): void };
const self = () => dd as unknown as { helper?: HTMLElement; _checkDropTarget(e: MouseEvent): void };
const subDrop = () => sub.el.ddElement!.ddDroppable!;
const mainDrop = () => main.el.ddElement!.ddDroppable!;

/** the item (100x100) at the given spot, as a mouse move would report (the cursor doesn't matter) */
const moveTo = (left: number, top: number) => {
vi.spyOn(self().helper!, 'getBoundingClientRect').mockReturnValue(box(left, top, 100, 100));
self()._checkDropTarget(new MouseEvent('mousemove', {clientX: left + 50, clientY: top + 5}));
};
const leaveAll = () => {
moveTo(150, 40); // into the parent
moveTo(150, -10); // and out of it all
expect(DDManager.dropElement).toBeUndefined();
};

beforeEach(() => {
document.body.insertAdjacentHTML('afterbegin', '<div id="gs-cont" style="width: 800px"><div class="grid-stack main"></div></div>');
main = GridStack.init({column: 12, acceptWidgets: true, children: [
{x: 0, y: 0, w: 6, h: 4, id: 'g', subGridOpts: {acceptWidgets: true, children: [{x: 0, y: 0, id: 'i'}]}},
]}, '.grid-stack.main');
sub = main.engine.nodes[0].subGrid!;
item = sub.engine.nodes[0].el!;
cell = main.engine.nodes[0].el!;
// the sub-grid fills the top left of the main one, flush with its top/left/bottom edges like in nested.html
cellBox = box(100, 100, 400, 400);
mainBox = box(100, 100, 800, 400);
otherBox = other = undefined;
vi.spyOn(cell, 'getBoundingClientRect').mockImplementation(() => cellBox);
vi.spyOn(main.el, 'getBoundingClientRect').mockImplementation(() => mainBox);
// what's under a point (jsdom has no layout)
(document as unknown as {elementFromPoint: (x: number, y: number) => Element}).elementFromPoint = (x, y) =>
inside(cellBox, x, y) ? sub.el : inside(otherBox, x, y) ? other!.el : inside(mainBox, x, y) ? main.el : document.body;
dd = item.ddElement!.ddDraggable!;
self().helper = item;
vi.spyOn(item, 'getBoundingClientRect').mockReturnValue(box(150, 150, 100, 100)); // being dragged in the sub-grid
DDManager.dragElement = dd;
DDManager.dropElement = subDrop();
});
afterEach(() => {
vi.restoreAllMocks();
delete (document as unknown as {elementFromPoint?: unknown}).elementFromPoint;
delete DDManager.dragElement;
delete DDManager.dropElement;
document.getElementById('gs-cont')?.remove();
});

it('stays in the sub-grid while at least half of the item is over it', () => {
moveTo(150, 50); // exactly half above
expect(DDManager.dropElement).toBe(subDrop());
});

for (const [dir, left, top] of [['above', 150, 40], ['below', 150, 460], ['left', 40, 200], ['right', 460, 200]] as const) {
it(`hands the item to the parent grid once more than half is ${dir} the sub-grid`, () => {
moveTo(left, top);
expect(DDManager.dropElement).toBe(mainDrop());
expect(sub.engine.nodes.find(n => n.id === 'i')).toBeUndefined(); // left the sub-grid
});
}

it('ignores the cursor coming in or going out of grids', () => {
(subDrop() as unknown as Drop)._domLeave(new MouseEvent('mouseleave'));
expect(DDManager.dropElement).toBe(subDrop());
moveTo(150, 40); // into the parent
(subDrop() as unknown as Drop)._domEnter(new MouseEvent('mouseenter'));
(mainDrop() as unknown as Drop)._domLeave(new MouseEvent('mouseleave'));
expect(DDManager.dropElement).toBe(mainDrop());
});

it('goes into a sub-grid once mostly over it, so it does not flip right back out', () => {
moveTo(150, 40); // into the parent
moveTo(150, 60); // 60% over the sub-grid
expect(DDManager.dropElement).toBe(mainDrop());
moveTo(150, 80); // 80%
expect(DDManager.dropElement).toBe(subDrop());
});

it('goes by where the sub-grid is drawn, once it has settled', () => {
moveTo(150, 40); // into the parent, which pushes the sub-grid down to make room...
cell.getAnimations = () => [{transitionProperty: 'top'}]; // ...sliding down
moveTo(150, 90); // over where it was, but it's on its way
expect(DDManager.dropElement).toBe(mainDrop());

cell.getAnimations = () => [];
cellBox = box(100, 210, 400, 400); // settled below our placeholder
moveTo(150, 120); // over where it used to be (now our own placeholder) isn't going back in
expect(DDManager.dropElement).toBe(mainDrop());
moveTo(150, 190); // mostly over where it is now
expect(DDManager.dropElement).toBe(subDrop());

cell.getAnimations = () => [{transitionProperty: 'top'}]; // the parent no longer has us, so it slides back up
cellBox = box(100, 300, 400, 400); // whatever mid way says...
moveTo(150, 195);
expect(DDManager.dropElement).toBe(subDrop()); // ...is ignored
cell.getAnimations = () => [];
cellBox = box(100, 100, 400, 400); // back home, we're well inside
moveTo(150, 200);
expect(DDManager.dropElement).toBe(subDrop());
});

it('measures the whole sub-grid cell, not just its rows', () => {
vi.spyOn(sub.el, 'getBoundingClientRect').mockReturnValue(box(100, 100, 400, 100)); // the nested .grid-stack is 1 row
moveTo(150, 300); // well inside the cell, below its rows
expect(DDManager.dropElement).toBe(subDrop());
});

it('leaves the outermost grid only once the item is mostly out of it', () => {
moveTo(150, 40); // into the parent
moveTo(150, 30); // 30% still over it
expect(DDManager.dropElement).toBe(mainDrop());
moveTo(150, 20); // 20%
expect(DDManager.dropElement).toBeUndefined();
});

it('enters the outermost grid once half of the item is over it', () => {
leaveAll();
moveTo(150, 30); // 30%
expect(DDManager.dropElement).toBeUndefined();
moveTo(150, 60); // 60%
expect(DDManager.dropElement).toBe(mainDrop());
});

it('coming in at the edge of a nest it goes into the outermost grid first, as it went out', () => {
leaveAll();
moveTo(150, 55); // 55% over both: enough for the outer grid, not the sub-grid
expect(DDManager.dropElement).toBe(mainDrop());
});

it('coming in fast right over a sub-grid goes straight in (not pushing it out of the way first)', () => {
leaveAll();
const enter = vi.spyOn(mainDrop(), '_mouseEnter');
moveTo(150, 150);
expect(DDManager.dropElement).toBe(subDrop());
expect(enter).not.toHaveBeenCalled();
});

it('flying out fast leaves it all at once (not dropping it in the parent grid for a moment)', () => {
const enter = vi.spyOn(mainDrop(), '_mouseEnter');
moveTo(150, -200);
expect(DDManager.dropElement).toBeUndefined();
expect(enter).not.toHaveBeenCalled();
});

it('moves between plain grids once half of the item is over the other one', () => {
document.getElementById('gs-cont')!.insertAdjacentHTML('beforeend', '<div class="grid-stack other"></div>');
other = GridStack.init({acceptWidgets: true}, '.grid-stack.other');
mainBox = box(100, 100, 400, 400);
otherBox = box(500, 100, 400, 400);
vi.spyOn(other.el, 'getBoundingClientRect').mockImplementation(() => otherBox!);
const otherDrop = other.el.ddElement!.ddDroppable!;

moveTo(440, 200); // 40% over the other grid
expect(DDManager.dropElement).toBe(subDrop());
moveTo(470, 200); // 70%: straight there
expect(DDManager.dropElement).toBe(otherDrop);
(otherDrop as unknown as Drop)._domLeave(new MouseEvent('mouseleave')); // the cursor doesn't matter
expect(DDManager.dropElement).toBe(otherDrop);
moveTo(445, 200); // 45/55, not clearly more over the nest yet
expect(DDManager.dropElement).toBe(otherDrop);
moveTo(430, 200); // back: 70% over the nest, enough for its outer grid but not the sub-grid
expect(DDManager.dropElement).toBe(mainDrop());
moveTo(420, 200); // 80%
expect(DDManager.dropElement).toBe(subDrop());
});

it('does not push a sub-grid that would take it out of the way (so we can get over it, and in)', () => {
// as a real drag start does (the node then points to the placeholder, not the item)
(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 the sub-grid, which makes room
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]); // pushed down below us
// the parent's drag handling, well down onto the sub-grid (the engine alone would push it by now)
const dragTo = (top: number) => (main as unknown as { _dragOrResize(...a: unknown[]): void })
._dragOrResize(item, {type: 'drag', target: item}, {position: {left: 0, top}}, i, 800 / 12, 100);
dragTo(320);
expect([i.y, g.y]).toEqual([0, 1]); // not pushed any further

sub.opts.acceptWidgets = false; // one that won't take us is moved around as before (we get past it)
dragTo(330);
expect(i.y).toBeGreaterThan(g.y!);
});

it('moves between side by side sub-grids once clearly more over the other one, not on the line between them', () => {
// a second sub-grid right of the first one, both flush in the parent
main.addWidget({x: 6, y: 0, w: 6, h: 4, id: 'g2', subGridOpts: {acceptWidgets: true}});
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);
(document as unknown as {elementFromPoint: (x: number, y: number) => Element}).elementFromPoint = (x, y) =>
inside(cellBox, x, y) ? sub.el : inside(cell2Box, x, y) ? sub2.el : inside(mainBox, x, y) ? main.el : document.body;

moveTo(445, 200); // 45/55 over the other one: stays, rather than dropping it in the parent in between
expect(DDManager.dropElement).toBe(subDrop());
moveTo(465, 200); // 35/65
expect(DDManager.dropElement).toBe(sub2Drop);
moveTo(445, 200); // back on the line: no flip
expect(DDManager.dropElement).toBe(sub2Drop);
moveTo(430, 200); // 70/30
expect(DDManager.dropElement).toBe(subDrop());
});

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);
vi.spyOn(sub, 'getCellHeight').mockReturnValue(100);
sub.update(item, {h: 2}); // 2 rows, like item 6 in nested.html
(sub as unknown as { _onStartMoving(...a: unknown[]): void })._onStartMoving(item, new Event('dragstart'), {position: {top: 0, left: 0}}, sub.engine.nodes[0], 66, 100);
vi.spyOn(self().helper!, 'getBoundingClientRect').mockReturnValue(box(150, 410, 100, 200)); // more than half below it...
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([g.y, i.y]).toEqual([0, 4]); // ...yet its top is in its last row: it didn't get pushed (and us float up above it)
});

it('leaves non-grid targets (a trash) to the cursor', () => {
const trashEl = document.createElement('div');
document.getElementById('gs-cont')!.appendChild(trashEl);
const trash = DDElement.init(trashEl as GridItemHTMLElement).setupDroppable({}).ddDroppable! as unknown as Drop;
trash._domEnter(new MouseEvent('mouseenter'));
expect(DDManager.dropElement).toBe(trash);
moveTo(150, 150); // all over the sub-grid
expect(DDManager.dropElement).toBe(trash);
trash._domLeave(new MouseEvent('mouseleave'));
moveTo(150, 150); // back
expect(DDManager.dropElement).toBe(subDrop());
});

it('leaves a temporary sub-grid (subGridDynamic) to the cursor', () => {
sub._isTemp = true;
moveTo(600, 200); // all out of it, over the parent
expect(DDManager.dropElement).toBe(subDrop());
(subDrop() as unknown as Drop)._domLeave(new MouseEvent('mouseleave')); // the cursor leaves: it goes away
expect(DDManager.dropElement).not.toBe(subDrop());
moveTo(600, 200);
expect(DDManager.dropElement).toBe(mainDrop());
});

it('leaves to nowhere if the parent grid will not take it, and back once mostly over the sub-grid', () => {
main.opts.acceptWidgets = false;
moveTo(150, 40);
expect(DDManager.dropElement).toBeUndefined();
moveTo(150, 60); // 60% back
expect(DDManager.dropElement).toBeUndefined();
moveTo(150, 80); // 80%
expect(DDManager.dropElement).toBe(subDrop());
});
});
});
58 changes: 58 additions & 0 deletions src/dd-draggable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,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';
Expand Down Expand Up @@ -288,6 +289,62 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
this.triggerEvent('drag', ev);
}

/**
* @internal fraction of the dragged item over the given drop target (a sub-grid's whole cell, as its nested .grid-stack
* is only as tall as its rows), or undefined while a sub-grid is still sliding into place: its parent grid pushes it
* out of our way as we go in or out, and deciding on that mid-way position would flip us right back.
*/
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());
}

/**
* Which grid we're over goes by how much of the item is over it rather than where the cursor is, which depends on where
* the item was grabbed (and can't get it above/below a sub-grid flush with its parent's edge, as both share that edge).
* Go into the innermost grid under the item's center once enough of it is over it (DDDroppable.enterOver - more for a
* sub-grid, so coming in at the edge of a nest we go into its outer grid first, as we come out of it), and out once not
* enough is (stayOver) to the closest outer grid still having enough of it. Going to a neighbor grid instead takes clearly
* more of it over that one than ours (switchBy).
*/
protected _checkDropTarget(e: MouseEvent): void {
const rect = this.helper?.getBoundingClientRect();
if (!rect?.width || !rect.height) return;
const cur = DDManager.dropElement;
if (cur && !cur._byShape()) return; // a trash (or temporary sub-grid) the cursor went in, it decides when we're out
// what we pass on (not the passive mousemove we're in)
const ev = { ...Utils.initEvent<MouseEvent>(e, { type: e.type }), preventDefault: () => undefined, stopPropagation: () => undefined } as MouseEvent;

// grids under the item's center, innermost first
const under: DDDroppable[] = [];
for (let el = document.elementFromPoint?.(rect.left + rect.width / 2, rect.top + rect.height / 2); el; el = el.parentElement) {
const d = DDDroppable.byEventEl.get(el as HTMLElement);
if (d && !d.disabled && d._byShape() && d._canDrop(this.el)) under.push(d);
}
const kind = (d: DDDroppable) => d.parentDroppable() ? 'sub' : 'grid';
const over = cur ? this._overlap(cur, rect) : 0;
if (over === undefined) return; // the one we're in is still sliding into place

// going in (not to one we're already in, or around): an inner grid once enough of us is over it, a neighbor (other grid,
// or a sibling sub-grid at just half) once clearly more of us is over it than ours, so we don't flip on the line between them
for (const d of under) {
if (cur && d.el.contains(cur.el)) break;
const o = this._overlap(d, rect) ?? 0;
const neighbor = cur && !cur.el.contains(d.el);
const sibling = neighbor && d.parentDroppable()?.el.contains(cur.el);
if (o >= (sibling ? 0.5 : DDDroppable.enterOver[kind(d)]) && (!neighbor || o >= over + DDDroppable.switchBy)) return d._mouseEnter(ev);
}

// going out: once not enough of us is over it (unless a neighbor has most of us, see above) to the closest outer grid
// that still has enough of us, if any (so flying out fast doesn't drop it in the parent grid for a moment)
if (!cur || over >= DDDroppable.stayOver[kind(cur)]) return;
if (under.some(d => !d.el.contains(cur.el) && (this._overlap(d, rect) ?? 0) >= 0.5)) return;
let to = cur.parentDroppable();
while (to && !(to._canDrop(this.el) && (this._overlap(to, rect) ?? 1) >= DDDroppable.stayOver[kind(to)])) to = to.parentDroppable();
if (to) to._mouseEnter(ev);
else cur._mouseLeave(ev, false, false);
}

/** @internal called when the main page (after successful mousedown) receives a move event to drag the item around the screen */
protected _mouseMove(e: MouseEvent): boolean {
// console.log(`${count++} move ${e.x},${e.y}`)
Expand All @@ -304,6 +361,7 @@ export class DDDraggable extends DDBaseImplement implements HTMLElementExtendOpt
} else {
this._callDrag(e);
}
this._checkDropTarget(e);
// once the cursor leaves the grid (pushed past its edge, the natural way to scroll) the grid stops
// listening to 'drag' and never calls updateScrollPosition() again, so check ourself while over empty
// space, else a quick push past the edge never starts the scroll #3356
Expand Down
Loading