Skip to content
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

feat(lib): use inject to pass container reference to selectableItem #112

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,27 @@ Here we listen for `scroll` on the `div` and call `container.update()` in case t

In order not to kill the performance, because the `scroll` event is called many many times, you may want to **throttle** it to only call `update` every 16ms or so.

### Does the `dtsSelectItem` directive need to be a direct child of the `dts-select-container`?

As of version `4.1.0`, an injection token is used to pass the `SelectContainerComponent` parent to the directive. You can use this in any component nested within the `dts-select-container`.

```ts
import { DTS_SELECT_CONTAINER } from 'ngx-drag-to-select';

@Component({...})
export class TaskListComponent {
constructor(
@Inject(DTS_SELECT_CONTAINER) @Optional()
d3lm marked this conversation as resolved.
Show resolved Hide resolved
public container: SelectContainerComponent
) {}
d3lm marked this conversation as resolved.
Show resolved Hide resolved
```

You can find an example of this in the [drag and drop example](https://github.com/d3lm/ngx-drag-to-select/blob/master/src/app/dragndrop).

### Why is my `dtsSelectItem` directive not selecting when I click on it?

If you are using the `dtsSelectItem` within a nested component then your mousedown/up events might being captured by another directive or component in your code. For example if you are using this libary with Angular CDK's DragDropModule, the mouse events are captured by the `cdkDrag` directive, [see here](https://github.com/angular/components/pull/19674).

## Want to contribute?

If you want to file a bug, contribute some code, or improve our documentation, read up on our [contributing guidelines](CONTRIBUTING.md) and [code of conduct](CODE_OF_CONDUCT.md), and check out [open issues](/issues).
Expand Down
80 changes: 80 additions & 0 deletions cypress/integration/drag-and-drop.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { DEFAULT_CONFIG } from '../../projects/ngx-drag-to-select/src/lib/config';

import {
disableSelection,
disableSelectOnDrag,
enableSelectMode,
getDesktopExample,
getDoingList,
getDragAndDropExample,
getTodoList,
shouldBeInvisible,
shouldBeVisible,
toggleItem,
} from '../support/utils';

const SELECTED_CLASS = DEFAULT_CONFIG.selectedClass;

describe('Drag And Drop', () => {
beforeEach(() => {
cy.visit('/');
});

describe('Select on Drag', () => {
it('should start new selection', () => {
getDragAndDropExample().within(() => {
getTodoList()
.dispatch('mousedown', 'topLeft', { button: 0 })
.getSelectItem(2)
.dispatch('mousemove')
.dispatch('mouseup');

cy.get('.selected').should('have.length', 3);
});
});

it('should drag to new list', () => {
getDragAndDropExample().within(() => {
getTodoList()
// Select First 3 items in list
Copy link
Owner

Choose a reason for hiding this comment

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

Single line comments always all lower case

Copy link
Owner

Choose a reason for hiding this comment

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

Did you forget this?

.dispatch('mousedown', 'topLeft', { button: 0 })
.getSelectItem(2)
.dispatch('mousemove')
.dispatch('mouseup')
// Click on second item
Copy link
Owner

Choose a reason for hiding this comment

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

same

Copy link
Owner

Choose a reason for hiding this comment

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

And here too.

.getSelectItem(1)
.dispatch('mousedown', { button: 0 })
// Drag to Select Item in other list
Copy link
Owner

Choose a reason for hiding this comment

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

same

Copy link
Owner

Choose a reason for hiding this comment

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

Same again.

.getSelectItem(5)
.wait(16)
.dispatch('mousemove')
.dispatch('mousemove')
.dispatch('mouseup');

getDoingList().within(() => {
cy.get('app-task').should('have.length', 5);
});
});
});

it('should reorder within list', () => {
getDragAndDropExample().within(() => {
getTodoList()
.dispatch('mousedown', 'bottomRight', { button: 0 })
.getSelectItem(2)
.dispatch('mousemove')
.dispatch('mouseup')
.getSelectItem(3)
.dispatch('mousedown', { button: 0 })
.getSelectItem(0)
.wait(16)
.dispatch('mousemove')
.dispatch('mousemove')
.dispatch('mouseup');

cy.get('app-task').eq(0).should('contain', 'Open Ticket #1');
cy.get('app-task').eq(1).should('contain', 'Open Ticket #2');
});
});
});
});
16 changes: 16 additions & 0 deletions cypress/support/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ export const getMobileExample = () => {
return cy.get('[data-cy="mobile"]');
};

export const getDragAndDropExample = () => {
return cy.get('[data-cy="drag-and-drop"]');
};

export const getSelectCount = () => {
return cy.get('[data-cy="select-count"]');
};
Expand All @@ -48,6 +52,18 @@ export const getClearButton = () => {
return cy.get('[data-cy="clearSelection"]');
};

export const getTodoList = () => {
return cy.get('[data-cy="todo-list"]');
};

export const getDoingList = () => {
return cy.get('[data-cy="doing-list"]');
};

export const getDoneList = () => {
return cy.get('[data-cy="done-list"]');
};

export const disableSelectOnDrag = () => {
return cy.get('[data-cy="selectOnDrag"]').click();
};
Expand Down
8 changes: 8 additions & 0 deletions projects/ngx-drag-to-select/src/lib/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,11 @@ export enum Action {
Delete,
None,
}

export interface SelectContainer<T = any> {
selectedItems: T[];
register(item: T): void;
unregister(item: T): void;
}

export type ComponentType<T> = new (...args: any[]) => T;
56 changes: 25 additions & 31 deletions projects/ngx-drag-to-select/src/lib/select-container.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,10 @@ import {
Renderer2,
ViewChild,
NgZone,
ContentChildren,
QueryList,
HostBinding,
AfterViewInit,
PLATFORM_ID,
Inject,
AfterContentInit,
} from '@angular/core';

import { isPlatformBrowser } from '@angular/common';
Expand All @@ -32,7 +29,6 @@ import {
share,
withLatestFrom,
distinctUntilChanged,
observeOn,
startWith,
concatMapTo,
first,
Expand All @@ -41,7 +37,7 @@ import {
import { SelectItemDirective, SELECT_ITEM_INSTANCE } from './select-item.directive';
import { ShortcutService } from './shortcut.service';

import { createSelectBox, whenSelectBoxVisible, distinctKeyEvents } from './operators';
import { createSelectBox, whenSelectBoxVisible } from './operators';

import {
Action,
Expand All @@ -52,6 +48,7 @@ import {
UpdateActions,
PredicateFn,
BoundingBox,
SelectContainer,
} from './models';

import { AUDIT_TIME, NO_SELECT_CLASS } from './constants';
Expand All @@ -67,6 +64,7 @@ import {
hasMinimumSize,
} from './utils';
import { KeyboardEventsService } from './keyboard-events.service';
import { DTS_SELECT_CONTAINER } from './tokens';

@Component({
selector: 'dts-select-container',
Expand All @@ -84,18 +82,16 @@ import { KeyboardEventsService } from './keyboard-events.service';
></div>
`,
styleUrls: ['./select-container.component.scss'],
providers: [{ provide: DTS_SELECT_CONTAINER, useExisting: SelectContainerComponent }],
})
export class SelectContainerComponent implements AfterViewInit, OnDestroy, AfterContentInit {
export class SelectContainerComponent implements AfterViewInit, OnDestroy, SelectContainer<SelectItemDirective> {
host: SelectContainerHost;
selectBoxStyles$: Observable<SelectBox<string>>;
selectBoxClasses$: Observable<{ [key: string]: boolean }>;

@ViewChild('selectBox', { static: true })
private $selectBox: ElementRef;

@ContentChildren(SelectItemDirective, { descendants: true })
private $selectableItems: QueryList<SelectItemDirective>;

@Input() selectedItems: any;
@Input() selectOnDrag = true;
@Input() disabled = false;
Expand Down Expand Up @@ -127,6 +123,8 @@ export class SelectContainerComponent implements AfterViewInit, OnDestroy, After
private _newRangeStart = false;
private _lastRangeSelection: Map<SelectItemDirective, boolean> = new Map();

private _registry: Set<SelectItemDirective> = new Set();

constructor(
@Inject(PLATFORM_ID) private platformId: Object,
private shortcuts: ShortcutService,
Expand Down Expand Up @@ -258,12 +256,12 @@ export class SelectContainerComponent implements AfterViewInit, OnDestroy, After
}
}

ngAfterContentInit() {
this._selectableItems = this.$selectableItems.toArray();
updateSelectableItems() {
this._selectableItems = Array.from(this._registry);
}

selectAll() {
this.$selectableItems.forEach((item) => {
this._selectableItems.forEach((item) => {
this._selectItem(item);
});
}
Expand All @@ -281,14 +279,24 @@ export class SelectContainerComponent implements AfterViewInit, OnDestroy, After
}

clearSelection() {
this.$selectableItems.forEach((item) => {
this._selectableItems.forEach((item) => {
this._deselectItem(item);
});
}

register(item: SelectItemDirective) {
this._registry.add(item);
this.updateSelectableItems();
}
d3lm marked this conversation as resolved.
Show resolved Hide resolved
unregister(item: SelectItemDirective) {
this._registry.delete(item);
this.updateSelectableItems();
this._removeItem(item, this.selectedItems);
}

update() {
this._calculateBoundingClientRect();
this.$selectableItems.forEach((item) => item.calculateBoundingClientRect());
this._selectableItems.forEach((item) => item.calculateBoundingClientRect());
}

ngOnDestroy() {
Expand Down Expand Up @@ -335,21 +343,6 @@ export class SelectContainerComponent implements AfterViewInit, OnDestroy, After
break;
}
});

// Update the container as well as all selectable items if the list has changed
this.$selectableItems.changes
.pipe(withLatestFrom(this._selectedItems$), observeOn(asyncScheduler), takeUntil(this.destroy$))
.subscribe(([items, selectedItems]: [QueryList<SelectItemDirective>, any[]]) => {
const newList = items.toArray();
this._selectableItems = newList;
const removedItems = selectedItems.filter((item) => !newList.includes(item.value));

if (removedItems.length) {
removedItems.forEach((item) => this._removeItem(item, selectedItems));
}

this.update();
});
}

private _observeBoundingRectChanges() {
Expand Down Expand Up @@ -395,6 +388,7 @@ export class SelectContainerComponent implements AfterViewInit, OnDestroy, After
}

private _onMouseDown(event: MouseEvent) {
console.log('Mouse Down');
if (this.shortcuts.disableSelection(event) || this.disabled) {
return;
}
Expand Down Expand Up @@ -446,7 +440,7 @@ export class SelectContainerComponent implements AfterViewInit, OnDestroy, After
return;
}

this.$selectableItems.forEach((item, index) => {
this._selectableItems.forEach((item, index) => {
const itemRect = item.getBoundingClientRect();
const withinBoundingBox = inBoundingBox(mousePoint, itemRect);

Expand Down Expand Up @@ -509,7 +503,7 @@ export class SelectContainerComponent implements AfterViewInit, OnDestroy, After
private _selectItems(event: Event) {
const selectionBox = calculateBoundingClientRect(this.$selectBox.nativeElement);

this.$selectableItems.forEach((item, index) => {
this._selectableItems.forEach((item, index) => {
if (this._isExtendedSelection(event)) {
this._extendedSelectionMode(selectionBox, item, event);
} else {
Expand Down
15 changes: 12 additions & 3 deletions projects/ngx-drag-to-select/src/lib/select-item.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@ import {
Renderer2,
OnInit,
HostBinding,
Optional,
SkipSelf,
OnDestroy,
} from '@angular/core';

import { DragToSelectConfig, BoundingBox } from './models';
import { CONFIG } from './tokens';
import { DragToSelectConfig, BoundingBox, SelectContainer } from './models';
import { CONFIG, DTS_SELECT_CONTAINER } from './tokens';
import { calculateBoundingClientRect } from './utils';

export const SELECT_ITEM_INSTANCE = Symbol();
Expand All @@ -25,7 +28,7 @@ export const SELECT_ITEM_INSTANCE = Symbol();
class: 'dts-select-item',
},
})
export class SelectItemDirective implements OnInit, DoCheck {
export class SelectItemDirective implements OnInit, DoCheck, OnDestroy {
private _boundingClientRect: BoundingBox | undefined;

selected = false;
Expand All @@ -41,18 +44,24 @@ export class SelectItemDirective implements OnInit, DoCheck {
constructor(
@Inject(CONFIG) private config: DragToSelectConfig,
@Inject(PLATFORM_ID) private platformId: Object,
@Inject(DTS_SELECT_CONTAINER) @Optional() @SkipSelf() public container: SelectContainer,
private host: ElementRef,
private renderer: Renderer2
) {}

ngOnInit() {
this.nativeElememnt[SELECT_ITEM_INSTANCE] = this;
this.container.register(this);
}

ngDoCheck() {
this.applySelectedClass();
}

ngOnDestroy() {
this.container.unregister(this);
}

toggleRangeStart() {
this.rangeStart = !this.rangeStart;
}
Expand Down
3 changes: 2 additions & 1 deletion projects/ngx-drag-to-select/src/lib/tokens.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { InjectionToken } from '@angular/core';
import { DragToSelectConfig } from './models';
import { DragToSelectConfig, SelectContainer, ComponentType } from './models';

export const CONFIG = new InjectionToken<DragToSelectConfig>('DRAG_TO_SELECT_CONFIG');
export const USER_CONFIG = new InjectionToken<DragToSelectConfig>('USER_CONFIG');
export const DTS_SELECT_CONTAINER = new InjectionToken<ComponentType<SelectContainer>>('SelectContainerComponent');
1 change: 1 addition & 0 deletions projects/ngx-drag-to-select/src/public_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
export * from './lib/drag-to-select.module';
export * from './lib/select-container.component';
export * from './lib/select-item.directive';
export { DTS_SELECT_CONTAINER } from './lib/tokens';
Loading