Skip to content

feat(material/datepicker): Support drag and drop to adjust date ranges #25548

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 16, 2022
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
71 changes: 69 additions & 2 deletions src/material/datepicker/calendar-body.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {waitForAsync, ComponentFixture, TestBed} from '@angular/core/testing';
import {Component} from '@angular/core';
import {MatCalendarBody, MatCalendarCell, MatCalendarUserEvent} from './calendar-body';
import {By} from '@angular/platform-browser';
import {dispatchMouseEvent, dispatchFakeEvent} from '../../cdk/testing/private';
import {dispatchMouseEvent, dispatchFakeEvent, dispatchTouchEvent} from '../../cdk/testing/private';

describe('MatCalendarBody', () => {
beforeEach(waitForAsync(() => {
Expand Down Expand Up @@ -630,6 +630,53 @@ describe('MatCalendarBody', () => {
}),
).toBe(false);
});

describe('drag and drop ranges', () => {
beforeEach(() => {
// Pre-select a range to drag.
fixture.componentInstance.startValue = 4;
fixture.componentInstance.endValue = 6;
fixture.detectChanges();
});

it('triggers and previews a drag (mouse)', () => {
dispatchMouseEvent(cells[3], 'mousedown');
fixture.detectChanges();
expect(fixture.componentInstance.drag).not.toBe(null);

// Expand to earlier.
dispatchMouseEvent(cells[2], 'mouseenter');
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(inPreviewClass);
expect(cells[5].classList).toContain(previewEndClass);

// End drag.
dispatchMouseEvent(cells[2], 'mouseup');
expect(fixture.componentInstance.drag).toBe(null);
});

it('triggers and previews a drag (touch)', () => {
dispatchTouchEvent(cells[3], 'touchstart');
fixture.detectChanges();
expect(fixture.componentInstance.drag).not.toBe(null);

// Expand to earlier.
const rect = cells[2].getBoundingClientRect();

dispatchTouchEvent(cells[2], 'touchmove', rect.left, rect.top, rect.left, rect.top);
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(inPreviewClass);
expect(cells[5].classList).toContain(previewEndClass);

// End drag.
dispatchTouchEvent(cells[2], 'touchend', rect.left, rect.top, rect.left, rect.top);
expect(fixture.componentInstance.drag).toBe(null);
});
});
});
});

Expand Down Expand Up @@ -672,7 +719,10 @@ class StandardCalendarBody {
[previewStart]="previewStart"
[previewEnd]="previewEnd"
(selectedValueChange)="onSelect($event)"
(previewChange)="previewChanged($event)">
(previewChange)="previewChanged($event)"
(dragStarted)="dragStarted($event)"
(dragEnded)="dragEnded($event)"
>
</table>`,
})
class RangeCalendarBody {
Expand All @@ -683,6 +733,7 @@ class RangeCalendarBody {
comparisonEnd: number | null;
previewStart: number | null;
previewEnd: number | null;
drag: MatCalendarUserEvent<unknown> | null = null;

onSelect(event: MatCalendarUserEvent<number>) {
const value = event.value;
Expand All @@ -699,6 +750,20 @@ class RangeCalendarBody {
previewChanged(event: MatCalendarUserEvent<MatCalendarCell<Date> | null>) {
this.previewStart = this.startValue;
this.previewEnd = event.value?.compareValue || null;

if (this.drag) {
// For sake of testing, hardcode a preview for drags.
this.previewStart = this.startValue! - 1;
this.previewEnd = this.endValue;
}
}

dragStarted(event: MatCalendarUserEvent<unknown>) {
this.drag = event;
}

dragEnded(event: MatCalendarUserEvent<unknown>) {
this.drag = null;
}
}

Expand Down Expand Up @@ -728,6 +793,8 @@ function createCalendarCells(weeks: number): MatCalendarCell[][] {
`${cell}-label`,
true,
cell % 2 === 0 ? 'even' : undefined,
cell,
cell,
);
}),
);
Expand Down
152 changes: 141 additions & 11 deletions src/material/datepicker/calendar-body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ let calendarBodyId = 1;
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatCalendarBody implements OnChanges, OnDestroy, AfterViewChecked {
export class MatCalendarBody<D = any> implements OnChanges, OnDestroy, AfterViewChecked {
/**
* Used to skip the next focus event when rendering the preview range.
* We need a flag like this, because some browsers fire focus events asynchronously.
Expand Down Expand Up @@ -150,6 +150,12 @@ export class MatCalendarBody implements OnChanges, OnDestroy, AfterViewChecked {

@Output() readonly activeDateChange = new EventEmitter<MatCalendarUserEvent<number>>();

/** Emits the date at the possible start of a drag event. */
@Output() readonly dragStarted = new EventEmitter<MatCalendarUserEvent<D>>();

/** Emits the date at the conclusion of a drag, or null if mouse was not released on a date. */
@Output() readonly dragEnded = new EventEmitter<MatCalendarUserEvent<D | null>>();

/** The number of blank cells to put at the beginning for the first row. */
_firstRowOffset: number;

Expand All @@ -159,18 +165,31 @@ export class MatCalendarBody implements OnChanges, OnDestroy, AfterViewChecked {
/** Width of an individual cell. */
_cellWidth: string;

private _didDragSinceMouseDown = false;

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated to this line, but I noticed that sometimes the highlight was being cleared when I stop dragging. See the cell for 19 below.
image

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure what you mean - the 19 appears to be in the currently hovered state. Is the mouse not currently over 19?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wasn't hovering the 19, I started dragging from it but my mouse was completely outside of the calendar.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't really track this one down. One thing I noticed is that the hover effect does not show up in chrome's simulated touch mode. It seems to work as expected in mouse mode the vast majority of the time. Are we willing to live with this for now?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, we can fix it in a follow-up.

constructor(private _elementRef: ElementRef<HTMLElement>, private _ngZone: NgZone) {
_ngZone.runOutsideAngular(() => {
const element = _elementRef.nativeElement;
element.addEventListener('mouseenter', this._enterHandler, true);
element.addEventListener('touchmove', this._touchmoveHandler, true);
element.addEventListener('focus', this._enterHandler, true);
element.addEventListener('mouseleave', this._leaveHandler, true);
element.addEventListener('blur', this._leaveHandler, true);
element.addEventListener('mousedown', this._mousedownHandler);
element.addEventListener('touchstart', this._mousedownHandler);
window.addEventListener('mouseup', this._mouseupHandler);
window.addEventListener('touchend', this._touchendHandler);
});
}

/** Called when a cell is clicked. */
_cellClicked(cell: MatCalendarCell, event: MouseEvent): void {
// Ignore "clicks" that are actually canceled drags (eg the user dragged
// off and then went back to this cell to undo).
if (this._didDragSinceMouseDown) {
return;
}

if (cell.enabled) {
this.selectedValueChange.emit({value: cell.value, event});
}
Expand Down Expand Up @@ -207,9 +226,14 @@ export class MatCalendarBody implements OnChanges, OnDestroy, AfterViewChecked {
ngOnDestroy() {
const element = this._elementRef.nativeElement;
element.removeEventListener('mouseenter', this._enterHandler, true);
element.removeEventListener('touchmove', this._touchmoveHandler, true);
element.removeEventListener('focus', this._enterHandler, true);
element.removeEventListener('mouseleave', this._leaveHandler, true);
element.removeEventListener('blur', this._leaveHandler, true);
element.removeEventListener('mousedown', this._mousedownHandler);
element.removeEventListener('touchstart', this._mousedownHandler);
window.removeEventListener('mouseup', this._mouseupHandler);
window.removeEventListener('touchend', this._touchendHandler);
}

/** Returns whether a cell is active. */
Expand Down Expand Up @@ -400,32 +424,112 @@ export class MatCalendarBody implements OnChanges, OnDestroy, AfterViewChecked {
}
};

private _touchmoveHandler = (event: TouchEvent) => {
if (!this.isRange) return;

const target = getActualTouchTarget(event);
const cell = target ? this._getCellFromElement(target as HTMLElement) : null;

if (target !== event.target) {
this._didDragSinceMouseDown = true;
}

// If the initial target of the touch is a date cell, prevent default so
// that the move is not handled as a scroll.
if (getCellElement(event.target as HTMLElement)) {
event.preventDefault();
}

this._ngZone.run(() => this.previewChange.emit({value: cell?.enabled ? cell : null, event}));
};

/**
* Event handler for when the user's pointer leaves an element
* inside the calendar body (e.g. by hovering out or blurring).
*/
private _leaveHandler = (event: Event) => {
// We only need to hit the zone when we're selecting a range.
if (this.previewEnd !== null && this.isRange) {
if (event.type !== 'blur') {
this._didDragSinceMouseDown = true;
}

// Only reset the preview end value when leaving cells. This looks better, because
// we have a gap between the cells and the rows and we don't want to remove the
// range just for it to show up again when the user moves a few pixels to the side.
if (event.target && this._getCellFromElement(event.target as HTMLElement)) {
if (
event.target &&
this._getCellFromElement(event.target as HTMLElement) &&
!(
(event as MouseEvent).relatedTarget &&
this._getCellFromElement((event as MouseEvent).relatedTarget as HTMLElement)
)
) {
this._ngZone.run(() => this.previewChange.emit({value: null, event}));
}
}
};

/** Finds the MatCalendarCell that corresponds to a DOM node. */
private _getCellFromElement(element: HTMLElement): MatCalendarCell | null {
let cell: HTMLElement | undefined;
/**
* Triggered on mousedown or touchstart on a date cell.
* Respsonsible for starting a drag sequence.
*/
private _mousedownHandler = (event: Event) => {
if (!this.isRange) return;

if (isTableCell(element)) {
cell = element;
} else if (isTableCell(element.parentNode!)) {
cell = element.parentNode as HTMLElement;
this._didDragSinceMouseDown = false;
// Begin a drag if a cell within the current range was targeted.
const cell = event.target && this._getCellFromElement(event.target as HTMLElement);
if (!cell || !this._isInRange(cell.rawValue)) {
return;
}

this._ngZone.run(() => {
this.dragStarted.emit({
value: cell.rawValue,
event,
});
});
};

/** Triggered on mouseup anywhere. Respsonsible for ending a drag sequence. */
private _mouseupHandler = (event: Event) => {
if (!this.isRange) return;

const cellElement = getCellElement(event.target as HTMLElement);
if (!cellElement) {
// Mouseup happened outside of datepicker. Cancel drag.
this._ngZone.run(() => {
this.dragEnded.emit({value: null, event});
});
return;
}

if (cellElement.closest('.mat-calendar-body') !== this._elementRef.nativeElement) {
// Mouseup happened inside a different month instance.
// Allow it to handle the event.
return;
}

this._ngZone.run(() => {
const cell = this._getCellFromElement(cellElement);
this.dragEnded.emit({value: cell?.rawValue ?? null, event});
});
};

/** Triggered on touchend anywhere. Respsonsible for ending a drag sequence. */
private _touchendHandler = (event: TouchEvent) => {
const target = getActualTouchTarget(event);

if (target) {
this._mouseupHandler({target} as unknown as Event);
}
};

/** Finds the MatCalendarCell that corresponds to a DOM node. */
private _getCellFromElement(element: HTMLElement): MatCalendarCell | null {
const cell = getCellElement(element);

if (cell) {
const row = cell.getAttribute('data-mat-row');
const col = cell.getAttribute('data-mat-col');
Expand All @@ -446,8 +550,25 @@ export class MatCalendarBody implements OnChanges, OnDestroy, AfterViewChecked {
}

/** Checks whether a node is a table cell element. */
function isTableCell(node: Node): node is HTMLTableCellElement {
return node.nodeName === 'TD';
function isTableCell(node: Node | undefined | null): node is HTMLTableCellElement {
return node?.nodeName === 'TD';
}

/**
* Gets the date table cell element that is or contains the specified element.
* Or returns null if element is not part of a date cell.
*/
function getCellElement(element: HTMLElement): HTMLElement | null {
let cell: HTMLElement | undefined;
if (isTableCell(element)) {
cell = element;
} else if (isTableCell(element.parentNode)) {
cell = element.parentNode as HTMLElement;
} else if (isTableCell(element.parentNode?.parentNode)) {
cell = element.parentNode!.parentNode as HTMLElement;
}

return cell?.getAttribute('data-mat-row') != null ? cell : null;
}

/** Checks whether a value is the start of a range. */
Expand Down Expand Up @@ -476,3 +597,12 @@ function isInRange(
value <= end
);
}

/**
* Extracts the element that actually corresponds to a touch event's location
* (rather than the element that initiated the sequence of touch events).
*/
function getActualTouchTarget(event: TouchEvent): Element | null {
const touchLocation = event.changedTouches[0];
return document.elementFromPoint(touchLocation.clientX, touchLocation.clientY);
}
6 changes: 5 additions & 1 deletion src/material/datepicker/calendar.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
[comparisonEnd]="comparisonEnd"
[startDateAccessibleName]="startDateAccessibleName"
[endDateAccessibleName]="endDateAccessibleName"
(_userSelection)="_dateSelected($event)">
(_userSelection)="_dateSelected($event)"
(dragStarted)="_dragStarted($event)"
(dragEnded)="_dragEnded($event)"
[activeDrag]="_activeDrag"
>
</mat-month-view>

<mat-year-view
Expand Down
Loading