summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSebastian <sebasjm@gmail.com>2024-03-04 16:37:34 -0300
committerSebastian <sebasjm@gmail.com>2024-03-04 16:37:34 -0300
commitc9dd92b08dc65c131903c288dafc613456c206e8 (patch)
tree151bb46f95e00c5ed1d7a176a95ae6cf7b2262db
parent6c124075b9a8540d848cd02cc3ba170eae052915 (diff)
downloadwallet-core-c9dd92b08dc65c131903c288dafc613456c206e8.tar.gz
wallet-core-c9dd92b08dc65c131903c288dafc613456c206e8.tar.bz2
wallet-core-c9dd92b08dc65c131903c288dafc613456c206e8.zip
async button
-rw-r--r--packages/web-util/src/components/Button.tsx114
-rw-r--r--packages/web-util/src/components/index.ts1
-rw-r--r--packages/web-util/src/hooks/useNotifications.ts57
3 files changed, 165 insertions, 7 deletions
diff --git a/packages/web-util/src/components/Button.tsx b/packages/web-util/src/components/Button.tsx
new file mode 100644
index 000000000..758efafcf
--- /dev/null
+++ b/packages/web-util/src/components/Button.tsx
@@ -0,0 +1,114 @@
+import { OperationFail, OperationOk, OperationResult, TalerError, TranslatedString } from "@gnu-taler/taler-util";
+// import { NotificationMessage, notifyInfo } from "@gnu-taler/web-util/browser";
+import { Fragment, VNode, h } from "preact";
+import { HTMLAttributes, useEffect, useState, useTransition } from "preact/compat";
+import { NotificationMessage, buildRequestErrorMessage, notifyInfo, useTranslationContext } from "../index.browser.js";
+// import { useBankCoreApiContext } from "../context/config.js";
+
+// function errorMap<T extends OperationFail<unknown>>(resp: T, map: (d: T["case"]) => TranslatedString): void {
+
+export interface ButtonHandler<T extends OperationResult<A, B>, A, B> {
+ onClick: () => Promise<T | undefined>,
+ onNotification: (n: NotificationMessage) => void;
+ onOperationSuccess: ((result:T extends OperationOk<any> ? T :never) => void) | ((result:T extends OperationOk<any> ? T :never) => TranslatedString | undefined),
+ onOperationFail: (d: T extends OperationFail<any> ? T : never) => TranslatedString;
+ onOperationComplete?: () => void;
+}
+
+interface Props<T extends OperationResult<A, B>, A, B> extends HTMLAttributes<HTMLButtonElement> {
+ handler: ButtonHandler<T, A, B> | undefined,
+}
+
+/**
+ * This button accept an async function and report a notification
+ * on error or success.
+ *
+ * When the async function is running the inner text will change into
+ * a "loading" animation.
+ *
+ * @param param0
+ * @returns
+ */
+export function Button<T extends OperationResult<A, B>, A, B>({
+ handler,
+ children,
+ disabled,
+ onClick:clickEvent,
+ ...rest
+}: Props<T, A, B>): VNode {
+ const {i18n} = useTranslationContext();
+ const [running, setRunning] = useState(false)
+ return <button {...rest} disabled={disabled || running} onClick={(e) => {
+ e.preventDefault();
+ if (!handler) { return; }
+ setRunning(true)
+ handler.onClick().then((resp) => {
+ if (resp) {
+ if (resp.type === "ok") {
+ // @ts-expect-error this is an operationOk
+ const result: OperationOk<any> = resp.body
+ // @ts-expect-error this is an operationOk
+ const msg = handler.onOperationSuccess(result)
+ if (msg) {
+ notifyInfo(msg)
+ }
+ }
+ if (resp.type === "fail") {
+ // @ts-expect-error this is an operationFail
+ const error: OperationFail<any> = resp;
+ // @ts-expect-error this is an operationFail
+ const title = handler.onOperationFail(error)
+ handler.onNotification({
+ title,
+ type: "error",
+ description: error.detail.hint as TranslatedString,
+ debug: error.detail,
+ })
+ }
+ }
+ if (handler.onOperationComplete) {
+ handler.onOperationComplete()
+ }
+ setRunning(false)
+ }).catch(error => {
+ console.error(error)
+
+ if (error instanceof TalerError) {
+ handler.onNotification(buildRequestErrorMessage(i18n, error))
+ } else {
+ const description = (error instanceof Error ?
+ error.message : String(error)) as TranslatedString
+
+ handler.onNotification({
+ title: i18n.str`Operation failed`,
+ type: "error",
+ description,
+ })
+ }
+
+ if (handler.onOperationComplete) {
+ handler.onOperationComplete()
+ }
+ setRunning(false)
+ })
+ }} >
+ {running ? <Wait /> : children}
+ </button>
+}
+
+function Wait():VNode {
+ return <Fragment>
+ <style>{`
+ #l1 { width: 120px;
+ height: 20px;
+ -webkit-mask: radial-gradient(circle closest-side, currentColor 90%, #0000) left/20% 100%;
+ background: linear-gradient(currentColor 0 0) left/0% 100% no-repeat #ddd;
+ animation: l17 2s infinite steps(6);
+ }
+ @keyframes l17 {
+ 100% {background-size:120% 100%}
+`}
+ </style>
+ <div id="l1" />
+ </Fragment>
+}
diff --git a/packages/web-util/src/components/index.ts b/packages/web-util/src/components/index.ts
index d94502b48..4ef840c7d 100644
--- a/packages/web-util/src/components/index.ts
+++ b/packages/web-util/src/components/index.ts
@@ -6,6 +6,7 @@ export * from "./LangSelector.js";
export * from "./Loading.js";
export * from "./Header.js";
export * from "./Footer.js";
+export * from "./Button.js";
export * from "./ShowInputErrorLabel.js";
export * from "./LocalNotificationBanner.js";
export * from "./GlobalNotificationBanner.js";
diff --git a/packages/web-util/src/hooks/useNotifications.ts b/packages/web-util/src/hooks/useNotifications.ts
index ca67c5b9b..33e0cdf53 100644
--- a/packages/web-util/src/hooks/useNotifications.ts
+++ b/packages/web-util/src/hooks/useNotifications.ts
@@ -1,6 +1,7 @@
-import { TalerError, TalerErrorCode, TranslatedString } from "@gnu-taler/taler-util";
+import { OperationFail, OperationOk, OperationResult, TalerError, TalerErrorCode, TranslatedString } from "@gnu-taler/taler-util";
import { useEffect, useState } from "preact/hooks";
-import { memoryMap, useTranslationContext } from "../index.browser.js";
+import { ButtonHandler } from "../components/Button.js";
+import { InternationalizationAPI, memoryMap, useTranslationContext } from "../index.browser.js";
export type NotificationMessage = ErrorNotification | InfoNotification;
@@ -106,7 +107,23 @@ function hash(msg: NotificationMessage): string {
return hashCode(str);
}
-export function useLocalNotification(): [Notification | undefined, (n: NotificationMessage) => void, (cb: () => Promise<void>) => Promise<void>] {
+function errorMap<T extends OperationFail<unknown>>(resp: T, map: (d: T["case"]) => TranslatedString): void {
+ notify({
+ type: "error",
+ title: map(resp.case),
+ description: resp.detail.hint as TranslatedString,
+ debug: resp.detail,
+ })
+}
+
+export type ErrorNotificationHandler = (cb: (notify: typeof errorMap) => Promise<void>) => Promise<void>;
+
+/**
+ * @deprecated use useLocalNotificationHandler
+ *
+ * @returns
+ */
+export function useLocalNotification(): [Notification | undefined, (n: NotificationMessage) => void, ErrorNotificationHandler] {
const {i18n} = useTranslationContext();
const [value, setter] = useState<NotificationMessage>();
@@ -117,9 +134,9 @@ export function useLocalNotification(): [Notification | undefined, (n: Notificat
},
}
- async function errorHandling(cb: () => Promise<void>) {
+ async function errorHandling(cb: (notify: typeof errorMap) => Promise<void>) {
try {
- return await cb()
+ return await cb(errorMap)
} catch (error: unknown) {
if (error instanceof TalerError) {
notify(buildRequestErrorMessage(i18n, error))
@@ -137,9 +154,35 @@ export function useLocalNotification(): [Notification | undefined, (n: Notificat
return [notif, setter, errorHandling]
}
-type Translator = ReturnType<typeof useTranslationContext>["i18n"]
+type HandlerMaker = <T extends OperationResult<A, B>,A,B>(
+ onClick: () => Promise<T | undefined>,
+ onOperationSuccess: ((result:T extends OperationOk<any> ? T :never) => void) | ((result:T extends OperationOk<any> ? T :never) => TranslatedString | undefined),
+ onOperationFail: (d: T extends OperationFail<any> ? T : never) => TranslatedString,
+ onOperationComplete?: () => void,
+) => ButtonHandler<T,A,B>;
+
+export function useLocalNotificationHandler(): [Notification | undefined, HandlerMaker, (n: NotificationMessage) => void] {
+ const [value, setter] = useState<NotificationMessage>();
+ const notif = !value ? undefined : {
+ message: value,
+ remove: () => {
+ setter(undefined);
+ },
+ }
+
+ function makeHandler<T extends OperationResult<A, B>,A,B>(
+ onClick: () => Promise<T | undefined>,
+ onOperationSuccess: ((result:T extends OperationOk<any> ? T :never) => void) | ((result:T extends OperationOk<any> ? T :never) => TranslatedString | undefined),
+ onOperationFail: (d: T extends OperationFail<any> ? T : never) => TranslatedString,
+ onOperationComplete?: () => void,
+ ): ButtonHandler<T,A,B> {
+ return { onClick, onNotification: setter, onOperationFail, onOperationSuccess, onOperationComplete }
+ }
+
+ return [notif, makeHandler, setter]
+}
-function buildRequestErrorMessage( i18n: Translator, cause: TalerError): ErrorNotification {
+export function buildRequestErrorMessage( i18n: InternationalizationAPI, cause: TalerError): ErrorNotification {
let result: ErrorNotification;
switch (cause.errorDetail.code) {
case TalerErrorCode.WALLET_HTTP_REQUEST_GENERIC_TIMEOUT: {