1/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import {Segment} from 'app/components/timeline/segment';
18import {MathUtils} from 'three/src/Three';
19import {DraggableCanvasObject} from './draggable_canvas_object';
20import {MiniTimelineDrawer} from './mini_timeline_drawer';
21
22export interface DrawConfig {
23  fillStyle: string;
24  fill: boolean;
25}
26
27export class DraggableCanvasObjectImpl implements DraggableCanvasObject {
28  private draggingPosition: number | undefined;
29
30  constructor(
31    private drawer: MiniTimelineDrawer,
32    private positionGetter: () => number,
33    private definePathFunc: (
34      ctx: CanvasRenderingContext2D,
35      position: number,
36    ) => void,
37    private drawConfig: DrawConfig,
38    private onDrag: (x: number) => void,
39    private onDrop: (x: number) => void,
40    private rangeGetter: () => Segment,
41  ) {
42    this.drawer.handler.registerDraggableObject(
43      this,
44      (x: number) => {
45        this.draggingPosition = this.clampPositionToRange(x);
46        this.onDrag(this.draggingPosition);
47        this.drawer.draw();
48      },
49      (x: number) => {
50        this.draggingPosition = undefined;
51        this.onDrop(this.clampPositionToRange(x));
52        this.drawer.draw();
53      },
54    );
55  }
56
57  get range(): Segment {
58    return this.rangeGetter();
59  }
60
61  get position(): number {
62    return this.draggingPosition !== undefined
63      ? this.draggingPosition
64      : this.positionGetter();
65  }
66
67  definePath(ctx: CanvasRenderingContext2D) {
68    this.definePathFunc(ctx, this.position);
69  }
70
71  draw(ctx: CanvasRenderingContext2D) {
72    this.doDraw(ctx);
73    this.drawer.handler.notifyDrawnOnTop(this);
74  }
75
76  private doDraw(ctx: CanvasRenderingContext2D) {
77    this.definePath(ctx);
78    ctx.fillStyle = this.drawConfig.fillStyle;
79    if (this.drawConfig.fill) {
80      ctx.fill();
81    }
82  }
83
84  private clampPositionToRange(x: number): number {
85    return MathUtils.clamp(x, this.range.from, this.range.to);
86  }
87}
88