aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/angular/timestamp-route-transformer.directive.ts
blob: f4d9aeb1fef3ac004f8bdc88b8d9dee3d5e72cf8 (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
import { Directive, EventEmitter, HostListener, Output } from '@angular/core'

@Directive({
  selector: '[timestampRouteTransformer]'
})
export class TimestampRouteTransformerDirective {
  @Output() timestampClicked = new EventEmitter<number>()

  @HostListener('click', ['$event'])
  public onClick ($event: Event) {
    const target = $event.target as HTMLLinkElement

    if (target.hasAttribute('href')) {
      const ngxLink = document.createElement('a')
      ngxLink.href = target.getAttribute('href')

      // we only care about reflective links
      if (ngxLink.host !== window.location.host) return

      const ngxLinkParams = new URLSearchParams(ngxLink.search)
      if (ngxLinkParams.has('start')) {
        const separators = ['h', 'm', 's']
        const start = ngxLinkParams
          .get('start')
          .match(new RegExp('(\\d{1,9}[' + separators.join('') + '])','g')) // match digits before any given separator
          .map(t => {
            if (t.includes('h')) return parseInt(t, 10) * 3600
            if (t.includes('m')) return parseInt(t, 10) * 60
            return parseInt(t, 10)
          })
          .reduce((acc, t) => acc + t)
        this.timestampClicked.emit(start)
      }

      $event.preventDefault()
    }

    return
  }
}