aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/core/confirm/confirm.service.ts
blob: 89a25f0a50e52ba23bd176020c3ddfe2eeea3cde (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
import { firstValueFrom, map, Observable, Subject } from 'rxjs'
import { Injectable } from '@angular/core'

type ConfirmOptions = {
  title: string
  message: string
} & (
  {
    type: 'confirm'
    confirmButtonText?: string
  } |
  {
    type: 'confirm-password'
    confirmButtonText?: string
  } |
  {
    type: 'confirm-expected-input'
    inputLabel?: string
    expectedInputValue?: string
    confirmButtonText?: string
  }
)

@Injectable()
export class ConfirmService {
  showConfirm = new Subject<ConfirmOptions>()
  confirmResponse = new Subject<{ confirmed: boolean, value?: string }>()

  confirm (message: string, title = '', confirmButtonText?: string) {
    this.showConfirm.next({ type: 'confirm', title, message, confirmButtonText })

    return firstValueFrom(this.extractConfirmed(this.confirmResponse.asObservable()))
  }

  confirmWithPassword (message: string, title = '', confirmButtonText?: string) {
    this.showConfirm.next({ type: 'confirm-password', title, message, confirmButtonText })

    const obs = this.confirmResponse.asObservable()
      .pipe(map(({ confirmed, value }) => ({ confirmed, password: value })))

    return firstValueFrom(obs)
  }

  confirmWithExpectedInput (message: string, inputLabel: string, expectedInputValue: string, title = '', confirmButtonText?: string) {
    this.showConfirm.next({ type: 'confirm-expected-input', title, message, inputLabel, expectedInputValue, confirmButtonText })

    return firstValueFrom(this.extractConfirmed(this.confirmResponse.asObservable()))
  }

  private extractConfirmed (obs: Observable<{ confirmed: boolean }>) {
    return obs.pipe(map(({ confirmed }) => confirmed))
  }
}