From 9e2df37e21fce9af0b2a6424165325283ac46f34 Mon Sep 17 00:00:00 2001 From: Baptiste Grob <60621355+baptiste-grob@users.noreply.github.com> Date: Mon, 29 Jun 2020 12:57:07 +0200 Subject: [PATCH] refactor: begin splitting alertService into standalone functions --- .../javascripts/services/alertService.ts | 83 ++++++++++++------- 1 file changed, 55 insertions(+), 28 deletions(-) diff --git a/app/assets/javascripts/services/alertService.ts b/app/assets/javascripts/services/alertService.ts index e73626d07..9e2801a0d 100644 --- a/app/assets/javascripts/services/alertService.ts +++ b/app/assets/javascripts/services/alertService.ts @@ -2,6 +2,45 @@ import { SNAlertService } from 'snjs'; import { SKAlert } from 'sn-stylekit'; +/** @returns a promise resolving to true if the user confirmed, false if they canceled */ +export function confirmDialog({ + text, + title, + confirmButtonText = 'Confirm', + cancelButtonText = 'Cancel', + confirmButtonStyle = 'info' +}: { + text: string, + title?: string, + confirmButtonText?: string, + cancelButtonText?: string, + confirmButtonStyle?: 'danger' | 'info' +}) { + return new Promise((resolve) => { + const alert = new SKAlert({ + title, + text, + buttons: [ + { + text: cancelButtonText, + style: 'neutral', + action() { + resolve(false); + }, + }, + { + text: confirmButtonText, + style: confirmButtonStyle, + action() { + resolve(true); + }, + }, + ], + }); + alert.present(); + }); +} + export class AlertService extends SNAlertService { async alert( text: string, @@ -13,20 +52,21 @@ export class AlertService extends SNAlertService { const buttons = [ { text: closeButtonText, - style: "neutral", + style: 'neutral', action: async () => { if (onClose) { this.deviceInterface!.timeout(onClose); } resolve(true); - } - } + }, + }, ]; const alert = new SKAlert({ title, text, buttons }); alert.present(); }); } + /** @deprecated use confirmDialog instead */ async confirm( text: string, title: string, @@ -36,31 +76,18 @@ export class AlertService extends SNAlertService { onCancel: () => void, destructive = false ) { - return new Promise((resolve, reject) => { - const buttons = [ - { - text: cancelButtonText, - style: "neutral", - action: async () => { - if (onCancel) { - this.deviceInterface!.timeout(onCancel); - } - reject(false); - } - }, - { - text: confirmButtonText, - style: destructive ? "danger" : "info", - action: async () => { - if (onConfirm) { - this.deviceInterface!.timeout(onConfirm); - } - resolve(true); - } - }, - ]; - const alert = new SKAlert({ title, text, buttons }); - alert.present(); + const confirmed = await confirmDialog({ + text, + title, + confirmButtonText, + cancelButtonText, + confirmButtonStyle: destructive ? 'danger' : 'info' }); + if (confirmed) { + onConfirm(); + } else { + onCancel(); + } + return confirmed; } }