-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment.ts
64 lines (52 loc) · 1.79 KB
/
segment.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { Particle } from './particle';
import { RangeValue, AnyFunction } from './background-interfaces';
import { chooseOption, getRndInteger, randomString } from './utils';
import deepMerge from 'deepmerge';
import defaultSegmentOptions from './default-segment-options';
export interface SegmentOptions {
stroke?: string[] | string;
width?: RangeValue;
}
export class Segment {
options: SegmentOptions;
startParticle: Particle;
endParticle: Particle;
stroke: string;
width: number;
id: string;
positionX1: number;
positionX2: number;
positionY1: number;
positionY2: number;
private callOnUpdate: AnyFunction[] = [];
private callOnDestroy: AnyFunction[] = [];
constructor(startParticle: Particle, endParticle: Particle, options?: SegmentOptions) {
const errBase = `The first param to 'Segment' `;
if (!(startParticle instanceof Particle && endParticle instanceof Particle))
throw new Error(errBase + `must be of type '[Particle, Particle]'`);
this.options = deepMerge(defaultSegmentOptions, options || {});
this.startParticle = startParticle;
this.endParticle = endParticle;
this.stroke = chooseOption(this.options.stroke);
this.width = getRndInteger(this.options.width.min, this.options.width.max);
this.id = randomString(20);
this.startParticle.onDestroy(() => this.destroy());
this.endParticle.onDestroy(() => this.destroy());
}
triggerUpdate() {
this.positionX1 = this.startParticle.positionX;
this.positionX2 = this.endParticle.positionX;
this.positionY1 = this.startParticle.positionY;
this.positionY2 = this.endParticle.positionY;
this.callOnUpdate.forEach(fn => fn());
}
destroy() {
this.callOnDestroy.forEach(fn => fn());
}
onUpdate(fn: AnyFunction) {
this.callOnUpdate.push(fn);
}
onDestroy(fn: AnyFunction) {
this.callOnDestroy.push(fn);
}
}