Skip to content

Commit

Permalink
feat(camera): add config change and move to range abilities
Browse files Browse the repository at this point in the history
refs: #4
  • Loading branch information
christoph-fricke committed Aug 17, 2022
1 parent 43fbbd3 commit 139df40
Showing 1 changed file with 45 additions and 10 deletions.
55 changes: 45 additions & 10 deletions src/core/camera.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,40 @@ export interface CameraConfig {
initialZoom: number;
minZoom: number;
maxZoom: number;
viewportPadding: number;
}

const defaultConfig: CameraConfig = {
initialDayWidth: 4,
initialDayOffset: 0,
initialZoom: 1,
minZoom: 0.1,
maxZoom: 2,
viewportPadding: 100,
};

export class Camera {
private readonly config: CameraConfig;
private config: CameraConfig = {} as CameraConfig;

private _offset: number;
private _zoom: number;
private _viewport: ViewPort;

constructor(config?: Partial<CameraConfig>) {
this.config = {
initialDayWidth: config?.initialDayWidth ?? 4,
initialDayOffset: config?.initialDayOffset ?? 0,
initialZoom: config?.initialZoom ?? 1,
minZoom: config?.minZoom ?? 0.1,
maxZoom: config?.maxZoom ?? 2,
};
this.updateConfig(config);

this._offset = this.config.initialDayWidth * this.config.initialDayOffset;
this._offset = this.initialOffset;
this._zoom = this.config.initialZoom;
this._viewport = { width: 0, height: 0 };
}

private get initialOffset() {
return (
this.config.initialDayWidth * this.config.initialDayOffset +
this.config.viewportPadding
);
}

get offset() {
return this._offset;
}
Expand All @@ -48,10 +59,34 @@ export class Camera {
return this._viewport;
}

public updateConfig(config?: Partial<CameraConfig>): CameraConfig {
this.config = {
...defaultConfig,
...this.config,
...config,
};
return this.config;
}

public changeOffset(by: number) {
this._offset += by;
}

/** Changes the offset to display the given range in the viewport. */
public moveRangeIntoViewport(start: number, end: number) {
const leftPadded = this.config.viewportPadding;
const rightPadded = this.viewport.width - this.config.viewportPadding;

switch (true) {
case start >= leftPadded && end <= rightPadded:
return;
case start < leftPadded:
return this.changeOffset(leftPadded - start);
case true:
return this.changeOffset(rightPadded - end);
}
}

public changeZoom(by: number) {
this._zoom = this.clamp(
this.config.minZoom,
Expand All @@ -66,7 +101,7 @@ export class Camera {

public reset() {
this._zoom = this.config.initialZoom;
this._offset = this.config.initialDayWidth * this.config.initialDayOffset;
this._offset = this.initialOffset;
}

private clamp(min: number, actual: number, max: number): number {
Expand Down

0 comments on commit 139df40

Please sign in to comment.