• 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 {MathUtils} from 'three/src/Three';
18import {Segment} from '../timeline/utils';
19import {CanvasDrawer} from './canvas_drawer';
20
21export interface DrawConfig {
22  fillStyle: string;
23  fill: boolean;
24}
25
26export class DraggableCanvasObject {
27  private draggingPosition: number | undefined;
28
29  constructor(
30    private drawer: CanvasDrawer,
31    private positionGetter: () => number,
32    private definePathFunc: (ctx: CanvasRenderingContext2D, position: number) => void,
33    private drawConfig: DrawConfig,
34    private onDrag: (x: number) => void,
35    private onDrop: (x: number) => void,
36    private rangeGetter: () => Segment
37  ) {
38    this.drawer.handler.registerDraggableObject(
39      this,
40      (x: number) => {
41        this.draggingPosition = this.clampPositionToRange(x);
42        this.onDrag(this.draggingPosition);
43        this.drawer.draw();
44      },
45      (x: number) => {
46        this.draggingPosition = undefined;
47        this.onDrop(this.clampPositionToRange(x));
48        this.drawer.draw();
49      }
50    );
51  }
52
53  get range(): Segment {
54    return this.rangeGetter();
55  }
56
57  get position(): number {
58    return this.draggingPosition !== undefined ? this.draggingPosition : this.positionGetter();
59  }
60
61  definePath(ctx: CanvasRenderingContext2D) {
62    this.definePathFunc(ctx, this.position);
63  }
64
65  draw(ctx: CanvasRenderingContext2D) {
66    this.doDraw(ctx);
67    this.drawer.handler.notifyDrawnOnTop(this);
68  }
69
70  private doDraw(ctx: CanvasRenderingContext2D) {
71    this.definePath(ctx);
72    ctx.fillStyle = this.drawConfig.fillStyle;
73    if (this.drawConfig.fill) {
74      ctx.fill();
75    }
76  }
77
78  private clampPositionToRange(x: number): number {
79    return MathUtils.clamp(x, this.range.from, this.range.to);
80  }
81}
82