/** * Copyright (c) OpenLens Authors. All rights reserved. * Licensed under MIT License. See LICENSE in root directory for more information. */ import "./confirm-dialog.scss"; import type { ReactNode } from "react"; import React from "react"; import type { IObservableValue } from "mobx"; import { observable, makeObservable, computed } from "mobx"; import { observer } from "mobx-react"; import { cssNames, noop, prevDefault } from "../../utils"; import type { ButtonProps } from "../button"; import { Button } from "../button"; import type { DialogProps } from "../dialog"; import { Dialog } from "../dialog"; import { Icon } from "../icon"; import { Notifications } from "../notifications"; import { withInjectables } from "@ogre-tools/injectable-react"; import confirmDialogStateInjectable from "./state.injectable"; export interface ConfirmDialogProps extends Partial { } export interface ConfirmDialogParams extends ConfirmDialogBooleanParams { ok?: () => any | Promise; cancel?: () => any | Promise; } export interface ConfirmDialogBooleanParams { labelOk?: ReactNode; labelCancel?: ReactNode; message: ReactNode; icon?: ReactNode; okButtonProps?: Partial; cancelButtonProps?: Partial; } interface Dependencies { state: IObservableValue; } const defaultParams = { ok: noop, cancel: noop, labelOk: "Ok", labelCancel: "Cancel", icon: , }; @observer class NonInjectedConfirmDialog extends React.Component { @observable isSaving = false; constructor(props: ConfirmDialogProps & Dependencies) { super(props); makeObservable(this); } @computed get params() { return Object.assign({}, defaultParams, this.props.state.get() ?? {} as ConfirmDialogParams); } ok = async () => { try { this.isSaving = true; await (async () => this.params.ok())(); } catch (error) { Notifications.error( <>

Confirmation action failed:

{( error instanceof Error ? error.message : typeof error === "string" ? error : "Unknown error occured while ok-ing" )}

, ); } finally { this.isSaving = false; this.props.state.set(undefined); } }; onClose = () => { this.isSaving = false; }; close = async () => { try { await Promise.resolve(this.params.cancel()); } catch (error) { Notifications.error( <>

Cancelling action failed:

{( error instanceof Error ? error.message : typeof error === "string" ? error : "Unknown error occured while cancelling" )}

, ); } finally { this.isSaving = false; this.props.state.set(undefined); } }; render() { const { state, className, ...dialogProps } = this.props; const isOpen = Boolean(state.get()); const { icon, labelOk, labelCancel, message, okButtonProps = {}, cancelButtonProps = {}, } = this.params; return (
{icon} {" "} {message}
); } } export const ConfirmDialog = withInjectables(NonInjectedConfirmDialog, { getProps: (di, props) => ({ ...props, state: di.inject(confirmDialogStateInjectable), }), });