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: add plugin support to ngu-flow #8

Merged
merged 4 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"start": "ng serve --port 52666",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"gh": "ng deploy --dir=dist/angular-flow/browser --base-href=/ngu-flow/",
"test": "jest"
},
"private": true,
Expand Down
8 changes: 4 additions & 4 deletions projects/flow/src/lib/flow-child.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ export class FlowChildComponent implements OnInit, OnChanges, OnDestroy {
});

this.positionChange.subscribe((x) => {
const { left, top } = this.flow.zRect;
// const { left, top } = this.flow.zRect;
// if (!this.position) console.log(this.position);
sheikalthaf marked this conversation as resolved.
Show resolved Hide resolved
this.updatePosition(this.position.x + left, this.position.y + top);
this.updatePosition(this.position.x, this.position.y);
});
}

Expand Down Expand Up @@ -135,8 +135,8 @@ export class FlowChildComponent implements OnInit, OnChanges, OnDestroy {
(this.flow.gridSize * this.flow.scale)
) * this.flow.gridSize;

this.position.x = x - zRect.left;
this.position.y = y - zRect.top;
this.position.x = x;
this.position.y = y;
this.positionChange.next(this.position);
this.flow.arrowsChange.next(this.position);
}
Expand Down
10 changes: 10 additions & 0 deletions projects/flow/src/lib/flow-interface.ts
sheikalthaf marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { FlowComponent } from './flow.component';

export interface ChildInfo {
position: FlowOptions;
dots?: DOMRect[];
Expand Down Expand Up @@ -26,6 +28,7 @@ export interface DotOptions extends FlowOptions {
export class FlowConfig {
Arrows = true;
ArrowSize = 20;
Plugins: { [x: string]: FlowPlugin } = {};
}

export type FlowDirection = 'horizontal' | 'vertical';
Expand All @@ -36,3 +39,10 @@ export type ArrowPathFn = (
arrowSize: number,
strokeWidth: number
) => string;

export interface FlowPlugin {
onInit?(data: FlowComponent): void;
afterInit?(data: FlowComponent): void;
beforeUpdate?(data: FlowComponent): void;
afterUpdate?(data: FlowComponent): void;
}
148 changes: 30 additions & 118 deletions projects/flow/src/lib/flow.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import {
ElementRef,
NgZone,
ChangeDetectionStrategy,
Input,
OnInit,
} from '@angular/core';
import { startWith } from 'rxjs';
import { Arrangements2 as Arrangements } from './arrangements';
import { Connections } from './connections';
import { FlowChildComponent } from './flow-child.component';
import { FlowService } from './flow.service';
import {
Expand All @@ -22,9 +22,10 @@ import {
FlowDirection,
DotOptions,
ArrowPathFn,
FlowConfig,
FlowPlugin,
} from './flow-interface';
import { blendCorners, flowPath, bezierPath, blendCorners1 } from './svg';
import { FitToWindow } from './fit-to-window';

const BASE_SCALE_AMOUNT = 0.05;
sheikalthaf marked this conversation as resolved.
Show resolved Hide resolved

Expand Down Expand Up @@ -125,10 +126,11 @@ const BASE_SCALE_AMOUNT = 0.05;
],
})
export class FlowComponent
implements AfterContentInit, AfterViewInit, OnDestroy
implements OnInit, AfterContentInit, AfterViewInit, OnDestroy
{
@ContentChildren(FlowChildComponent) children: QueryList<FlowChildComponent> =
new QueryList();
@Input() config: FlowConfig = new FlowConfig();
@ContentChildren(FlowChildComponent) children =
new QueryList<FlowChildComponent>();

// @ViewChildren('arrowPaths') arrowPaths: QueryList<ElementRef<SVGPathElement>>;
@ViewChild('zoomContainer') zoomContainer: ElementRef<HTMLDivElement>;
Expand All @@ -143,7 +145,9 @@ export class FlowComponent
public el: ElementRef<HTMLElement>,
public flow: FlowService,
private ngZone: NgZone
) {
) {}

ngOnInit(): void {
this.flow.zoomContainer = this.el.nativeElement;
this.flow.arrowsChange.subscribe((e) => this.updateArrows(e));
this.ngZone.runOutsideAngular(() => {
Expand All @@ -166,14 +170,24 @@ export class FlowComponent

ngAfterViewInit(): void {
this.createArrows();
this.runPlugin((e) => e.afterInit?.(this));
}

private runPlugin(callback: (e: FlowPlugin) => void) {
for (const key in this.config.Plugins) {
if (Object.prototype.hasOwnProperty.call(this.config.Plugins, key)) {
const element = this.config.Plugins[key];
callback(element);
}
}
}

ngAfterContentInit() {
this.children.changes
.pipe(startWith(this.children))
.subscribe((children) => {
this.flow.update(this.children.map((x) => x.position));
this.arrangeChildren();
this.runPlugin((e) => e.beforeUpdate?.(this));
this.createArrows();
});
requestAnimationFrame(() => this.updateArrows()); // this required for angular to render the dot
Expand All @@ -189,7 +203,7 @@ export class FlowComponent

updateDirection(direction: FlowDirection) {
this.flow.direction = direction;
this.arrangeChildren();
this.runPlugin((e) => e.beforeUpdate?.(this));
this.createArrows();
}

Expand Down Expand Up @@ -281,38 +295,10 @@ export class FlowComponent
return { scale: newScale, panX: newPanX, panY: newPanY };
}

fitToWindow() {
const ftw = new FitToWindow(
this.list,
this.zoomContainer.nativeElement.getBoundingClientRect(),
this.flow.scale,
this.flow.panX,
this.flow.panY
);
const { scale, panX, panY } = ftw.fitToWindow();
this.flow.scale = scale;
this.flow.panX = panX;
this.flow.panY = panY;
this.updateZoomContainer();
}

private updateZoomContainer() {
updateZoomContainer() {
this.zoomContainer.nativeElement.style.transform = `translate3d(${this.flow.panX}px, ${this.flow.panY}px, 0) scale(${this.flow.scale})`;
}

arrangeChildren() {
const arrangements = new Arrangements(
this.list,
this.flow.direction,
this.flow.horizontalPadding,
this.flow.verticalPadding,
this.flow.groupPadding
);
const newList = arrangements.autoArrange();
this.flow.update([...newList.values()]);
this.flow.layoutUpdated.next();
}

get list() {
return this.children.toArray().map((x) => {
// calculate the width and height with scale
Expand Down Expand Up @@ -397,101 +383,27 @@ export class FlowComponent
}

updateArrows(e?: FlowOptions) {
const gElement: SVGGElement = this.g.nativeElement;
const childObj = this.getChildInfo();
this.runPlugin((e) => e.afterUpdate?.(this));
// const gElement: SVGGElement = this.g.nativeElement;
// const childObj = this.getChildInfo();
// Handle reverse dependencies
this.flow.connections = new Connections(this.list, this.flow.direction);

// Calculate new arrows
this.flow.arrows.forEach((arrow) => {
const [from, to] = arrow.deps;
const fromItem = childObj[from];
const toItem = childObj[to];
if (fromItem && toItem) {
const [endDotIndex, startDotIndex] = this.getClosestDots(toItem, from);

const startDot = this.getDotByIndex(
childObj,
fromItem.position,
startDotIndex,
this.flow.scale,
this.flow.panX,
this.flow.panY
);
const endDot = this.getDotByIndex(
childObj,
toItem.position,
endDotIndex,
this.flow.scale,
this.flow.panX,
this.flow.panY
);

// we need to reverse the path because the arrow head is at the end
arrow.d = this.flow.arrowFn(
endDot,
startDot,
this.flow.config.ArrowSize,
2
);
}

// Update the SVG paths
this.flow.arrows.forEach((arrow) => {
const pathElement = gElement.querySelector(
`#${arrow.id}`
) as SVGPathElement;
if (pathElement) {
pathElement.setAttribute('d', arrow.d);
}
});
});

this.flow.connections.updateDotVisibility(this.oldChildObj());
// this.flow.connections = new Connections(this.list, this.flow.direction);
sheikalthaf marked this conversation as resolved.
Show resolved Hide resolved
}

private oldChildObj() {
oldChildObj() {
return this.children.toArray().reduce((acc, curr) => {
acc[curr.position.id] = curr;
return acc;
}, {} as Record<string, FlowChildComponent>);
}

private getChildInfo() {
getChildInfo() {
return this.list.reduce((acc, curr) => {
acc[curr.position.id] = curr;
return acc;
}, {} as Record<string, ChildInfo>);
}

private getDotByIndex(
childObj: Record<string, ChildInfo>,
item: FlowOptions,
dotIndex: number,
scale: number,
panX: number,
panY: number
): DotOptions {
const child = childObj[item.id];
const childDots = child.dots as DOMRect[];
// Make sure the dot index is within bounds
if (dotIndex < 0 || dotIndex >= childDots.length) {
throw new Error(`Invalid dot index: ${dotIndex}`);
}

const rect = childDots[dotIndex];
const { left, top } = this.flow.zRect;
// const rect = dotEl.nativeElement.getBoundingClientRect();
const x = (rect.x + rect.width / 2 - panX - left) / scale;
const y = (rect.y + rect.height / 2 - panY - top) / scale;

return { ...item, x, y, dotIndex };
}

public getClosestDots(item: ChildInfo, dep?: string): number[] {
return this.flow.connections.getClosestDotsSimplified(item, dep as string);
}

ngOnDestroy(): void {
this.el.nativeElement.removeEventListener('wheel', this.zoomHandle);
}
Expand Down
18 changes: 0 additions & 18 deletions projects/flow/src/lib/flow.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Injectable, NgZone } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { Connections } from './connections';
import {
ArrowPathFn,
FlowConfig,
Expand Down Expand Up @@ -29,7 +28,6 @@ export class FlowService {
gridSize = 1;
arrows: Arrow[] = [];
zoomContainer: HTMLElement;
connections: Connections;
layoutUpdated = new Subject<void>();
onMouse = new Subject<MouseEvent>();

Expand All @@ -47,7 +45,6 @@ export class FlowService {
};

update(children: FlowOptions[]) {
// console.log('update', children);
this.items.clear();
children.forEach((child) => {
this.items.set(child.id, child);
Expand All @@ -62,21 +59,6 @@ export class FlowService {
});
}

// delete(option: FlowOptions) {
// this.items.delete(option.id);
// this.deps.delete(option.id);
// this.deps.forEach((v, k) => {
// const index = v.indexOf(option.id);
// if (index > -1) {
// v.splice(index, 1);
// }
// });
// }

get list() {
return Array.from(this.items.values());
}

get zRect() {
return this.zoomContainer.getBoundingClientRect();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Arrangements, Arrangements2 } from './arrangements';
import { ChildInfo } from './flow-interface';
import { ArrangementsOld, Arrangements } from './arrangements';
import { ChildInfo } from '../flow-interface';
import { FlowComponent } from '../flow.component';

export const FLOW_LIST = [
{ x: 40, y: 40, id: '1', deps: [] },
Expand All @@ -13,15 +14,15 @@ export const FLOW_LIST = [
];

describe('Arrangements', () => {
let arrangements: Arrangements;
let arrangements: ArrangementsOld;

it('should be created', () => {
const childObj: ChildInfo[] = FLOW_LIST.map((x) => ({
position: x,
elRect: { width: 200, height: 200 } as any,
}));

arrangements = new Arrangements(childObj);
arrangements = new ArrangementsOld(childObj);
arrangements.verticalPadding = 20;
arrangements.groupPadding = 100;
const expected = {
Expand All @@ -40,17 +41,23 @@ describe('Arrangements', () => {
});

describe('Arrangements2', () => {
let arrangements: Arrangements2;
let arrangements: Arrangements;

it('should be created', () => {
const childObj: ChildInfo[] = FLOW_LIST.map((x) => ({
position: x,
elRect: { width: 200, height: 200 } as any,
}));

arrangements = new Arrangements2(childObj);
arrangements.verticalPadding = 20;
arrangements.groupPadding = 100;
arrangements = new Arrangements();
arrangements.onInit({
list: childObj,
flow: {
direction: 'vertical',
verticalPadding: 20,
groupPadding: 100,
},
} as Partial<FlowComponent> as any);
const expected = {
'1': { x: 330, y: 0, id: '1', deps: [] },
'2': { x: 110, y: 300, id: '2', deps: ['1'] },
Expand All @@ -61,7 +68,7 @@ describe('Arrangements2', () => {
'7': { x: 660, y: 600, id: '7', deps: ['5'] },
'8': { x: 660, y: 900, id: '8', deps: ['6', '7'] },
};
const actual = Object.fromEntries(arrangements.autoArrange());
const actual = Object.fromEntries(arrangements._autoArrange());
expect(actual).toEqual(expected);
Copy link
Member

Choose a reason for hiding this comment

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

same her lets remove _ from functions

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Just for testing purpose made it public and added _

Copy link
Member

Choose a reason for hiding this comment

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

yes it should be testes with public methods, call the public methods and check

});
});
Loading
Loading