Files
esengine/packages/behavior-tree-editor/src/domain/models/Connection.ts

141 lines
3.4 KiB
TypeScript
Raw Normal View History

import { ValidationError } from '../errors';
/**
*
*/
export type ConnectionType = 'node' | 'property';
/**
*
*
*/
export class Connection {
private readonly _from: string;
private readonly _to: string;
private readonly _fromProperty?: string;
private readonly _toProperty?: string;
private readonly _connectionType: ConnectionType;
constructor(
from: string,
to: string,
connectionType: ConnectionType = 'node',
fromProperty?: string,
toProperty?: string
) {
if (from === to) {
throw ValidationError.circularReference(from);
}
if (connectionType === 'property' && (!fromProperty || !toProperty)) {
throw new ValidationError('属性连接必须指定源属性和目标属性');
}
this._from = from;
this._to = to;
this._connectionType = connectionType;
this._fromProperty = fromProperty;
this._toProperty = toProperty;
}
get from(): string {
return this._from;
}
get to(): string {
return this._to;
}
get fromProperty(): string | undefined {
return this._fromProperty;
}
get toProperty(): string | undefined {
return this._toProperty;
}
get connectionType(): ConnectionType {
return this._connectionType;
}
/**
*
*/
isNodeConnection(): boolean {
return this._connectionType === 'node';
}
/**
*
*/
isPropertyConnection(): boolean {
return this._connectionType === 'property';
}
/**
*
*/
matches(from: string, to: string, fromProperty?: string, toProperty?: string): boolean {
if (this._from !== from || this._to !== to) {
return false;
}
if (this._connectionType === 'property') {
return this._fromProperty === fromProperty && this._toProperty === toProperty;
}
return true;
}
/**
*
*/
equals(other: Connection): boolean {
return (
this._from === other._from &&
this._to === other._to &&
this._connectionType === other._connectionType &&
this._fromProperty === other._fromProperty &&
this._toProperty === other._toProperty
);
}
/**
*
*/
toObject(): {
from: string;
to: string;
fromProperty?: string;
toProperty?: string;
connectionType: ConnectionType;
} {
return {
from: this._from,
to: this._to,
connectionType: this._connectionType,
...(this._fromProperty && { fromProperty: this._fromProperty }),
...(this._toProperty && { toProperty: this._toProperty })
};
}
/**
*
*/
static fromObject(obj: {
from: string;
to: string;
fromProperty?: string;
toProperty?: string;
connectionType: ConnectionType;
}): Connection {
return new Connection(
obj.from,
obj.to,
obj.connectionType,
obj.fromProperty,
obj.toProperty
);
}
}