collection-tree-node.component.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { CdkDragDrop } from '@angular/cdk/drag-drop';
  2. import { ChangeDetectionStrategy, Component, Input, OnInit, Optional, SkipSelf } from '@angular/core';
  3. import { Collection } from 'shared/generated-types';
  4. import { RootNode, TreeNode } from './array-to-tree';
  5. import { CollectionTreeComponent } from './collection-tree.component';
  6. @Component({
  7. selector: 'vdr-collection-tree-node',
  8. templateUrl: './collection-tree-node.component.html',
  9. styleUrls: ['./collection-tree-node.component.scss'],
  10. changeDetection: ChangeDetectionStrategy.OnPush,
  11. })
  12. export class CollectionTreeNodeComponent implements OnInit {
  13. depth = 0;
  14. parentName: string;
  15. @Input() collectionTree: TreeNode<Collection.Fragment>;
  16. constructor(
  17. @SkipSelf() @Optional() private parent: CollectionTreeNodeComponent,
  18. private root: CollectionTreeComponent,
  19. ) {
  20. if (parent) {
  21. this.depth = parent.depth + 1;
  22. }
  23. }
  24. ngOnInit() {
  25. this.parentName = this.collectionTree.name || '<root>';
  26. }
  27. getMoveListItems(category: Collection.Fragment): Array<{ path: string; id: string }> {
  28. const visit = (
  29. node: TreeNode<any>,
  30. parentPath: string[],
  31. output: Array<{ path: string; id: string }>,
  32. ) => {
  33. if (node.id !== category.id) {
  34. const path = parentPath.concat(node.name);
  35. if (node.id !== category.parent.id) {
  36. output.push({ path: path.slice(1).join(' / ') || 'root', id: node.id });
  37. }
  38. node.children.forEach(child => visit(child, path, output));
  39. }
  40. return output;
  41. };
  42. return visit(this.root.categoryTree, [], []);
  43. }
  44. move(category: Collection.Fragment, parentId: string) {
  45. this.root.onMove({
  46. index: 0,
  47. parentId,
  48. collectionId: category.id,
  49. });
  50. }
  51. moveUp(category: Collection.Fragment, currentIndex: number) {
  52. this.root.onMove({
  53. index: currentIndex - 1,
  54. parentId: category.parent.id,
  55. collectionId: category.id,
  56. });
  57. }
  58. moveDown(category: Collection.Fragment, currentIndex: number) {
  59. this.root.onMove({
  60. index: currentIndex + 1,
  61. parentId: category.parent.id,
  62. collectionId: category.id,
  63. });
  64. }
  65. drop(event: CdkDragDrop<Collection.Fragment | RootNode<Collection.Fragment>>) {
  66. this.root.onDrop(event);
  67. }
  68. }