• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 getRange: () => 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  definePath(ctx: CanvasRenderingContext2D) {
58    this.definePathFunc(ctx, this.getPosition());
59  }
60
61  draw(ctx: CanvasRenderingContext2D) {
62    this.doDraw(ctx);
63    this.drawer.handler.notifyDrawnOnTop(this);
64  }
65
66  private getPosition(): number {
67    return this.draggingPosition !== undefined
68      ? this.draggingPosition
69      : this.positionGetter();
70  }
71
72  private doDraw(ctx: CanvasRenderingContext2D) {
73    this.definePath(ctx);
74    ctx.fillStyle = this.drawConfig.fillStyle;
75    if (this.drawConfig.fill) {
76      ctx.fill();
77    }
78  }
79
80  private clampPositionToRange(x: number): number {
81    const range = this.getRange();
82    return MathUtils.clamp(x, range.from, range.to);
83  }
84}
85