aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/forms/timestamp-input.component.ts
blob: 8d67a96ac3ca68744a4f94e389967816a92d1f17 (plain) (blame)
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
import { ChangeDetectorRef, Component, forwardRef, Input, OnInit } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
import { secondsToTime, timeToInt } from '../../../assets/player/utils'

@Component({
  selector: 'my-timestamp-input',
  styleUrls: [ './timestamp-input.component.scss' ],
  templateUrl: './timestamp-input.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => TimestampInputComponent),
      multi: true
    }
  ]
})
export class TimestampInputComponent implements ControlValueAccessor, OnInit {
  @Input() maxTimestamp: number
  @Input() timestamp: number
  @Input() disabled = false

  timestampString: string

  constructor (private changeDetector: ChangeDetectorRef) {}

  ngOnInit () {
    this.writeValue(this.timestamp || 0)
  }

  propagateChange = (_: any) => { /* empty */ }

  writeValue (timestamp: number) {
    this.timestamp = timestamp

    this.timestampString = secondsToTime(this.timestamp, true, ':')
  }

  registerOnChange (fn: (_: any) => void) {
    this.propagateChange = fn
  }

  registerOnTouched () {
    // Unused
  }

  onModelChange () {
    this.timestamp = timeToInt(this.timestampString)

    this.propagateChange(this.timestamp)
  }

  onBlur () {
    if (this.maxTimestamp && this.timestamp > this.maxTimestamp) {
      this.writeValue(this.maxTimestamp)

      this.changeDetector.detectChanges()

      this.propagateChange(this.timestamp)
    }
  }
}