aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/shared-forms/timestamp-input.component.ts
blob: 3fc705905e267b5b48f3de21b89310595f72dd90 (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
62
63
64
65
import { ChangeDetectorRef, Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
import { secondsToTime, timeToInt } from '@shared/core-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

  @Output() inputBlur = new EventEmitter()

  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)
    }

    this.inputBlur.emit()
  }
}