# All files / src/button AsyncButton.tsx

100% Statements 320/320
89.74% Branches 35/39
100% Functions 2/2
100% Lines 320/320

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    3211x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    26x
    26x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    2x
    2x
    27x
    2x
    2x
    27x
    27x
    27x
    23x
    23x
    1x
    23x
    1x
    22x
    21x
    21x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    23x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    27x
    1x
    26x
    27x
    27x
    27x
    27x
    27x
    1x
     "use client";
    import { cnb } from "cnbuilder";
    import { forwardRef, type MouseEvent, type ReactNode } from "react";
    import { type BoxAlignItems } from "../box/styles.js";
    import { overlay } from "../overlay/overlayStyles.js";
    import {
      CircularProgress,
      type CircularProgressProps,
    } from "../progress/CircularProgress.js";
    import {
      LinearProgress,
      type LinearProgressProps,
    } from "../progress/LinearProgress.js";
    import { type ProgressTheme } from "../progress/types.js";
    import { type PropsWithRef } from "../types.js";
    import { useAsyncAction } from "../useAsyncAction.js";
    import { useEnsuredId } from "../useEnsuredId.js";
    import { Button, type ButtonProps } from "./Button.js";

    const noop = (): void => {
      // do nothing
    };

    /**
     * @remarks \@since 6.0.0
     */
    export type AsyncButtonLoadingType =
      | "circular-before"
      | "circular-after"
      | "circular-overlay"
      | "linear-above"
      | "linear-below";

    /**
     * @remarks \@since 6.0.0
     */
    export interface AsyncButtonProps extends ButtonProps {
      /**
       * @see {@link progressAriaLabelledBy}
       * @defaultValue `"async-button" + useId()`
       */
      id?: string;

      /**
       * When this is defined and returns a `Promise`, the loading indicator will
       * display until the promise has resolved.
       *
       * @defaultValue `() => {}`
       */
      onClick?(event: MouseEvent<HTMLButtonElement>): Promise<void> | void;

      /**
       * Set this to `true` to manually display a loading spinner.
       *
       * @defaultValue `false`
       */
      loading?: boolean;

      /**
       * - `"circular-overlay"` - Covers and hides the button content with a
       *   centered circular progress
       * - `"circular-before"` - Renders a circular progress bar before the button
       *   content which is useful when rendering an icon before the button text.
       *   See {@link beforeAddon} as well.
       * - `"circular-after"` - Renders a circular progress bar before the button
       *   content which is useful when rendering an icon after the button text.
       *   See {@link afterAddon} as well.
       * - `"linear-above"` - Renders a linear progress bar at the top of the button
       *   while still displaying the button contents. Usually looks good for
       *   outlined buttons.
       * - `"linear-below"` - Renders a linear progress bar at the bottom of the
       *   button while still displaying the button contents. Usually looks good for
       *   outlined buttons.
       *
       * @defaultValue `"circular-overlay"`
       */
      loadingType?: AsyncButtonLoadingType;

      /**
       * Optional content to display instead of the default `children` while
       * loading.
       */
      loadingChildren?: ReactNode;

      /**
       * Set this to `true` to use the `disabled` theme while loading.
       *
       * @defaultValue `false`
       */
      loadingDisabledTheme?: boolean;

      /**
       * This should be used when the {@link loadingType} is set to
       * `"circular-before"`, an icon should appear before the other content in
       * the button, and the loading indicator should replace the icon.
       */
      beforeAddon?: ReactNode;

      /**
       * This should be used when the {@link loadingType} is set to
       * `"circular-after"`, an icon should appear before the other content in
       * the button, and the loading indicator should replace the icon.
       */
      afterAddon?: ReactNode;

      /**
       * An optional label to provide to the progressbar.
       *
       * @see {@link progressAriaLabelledBy}
       */
      progressAriaLabel?: string;

      /**
       * @see {@link id}
       * @defaultValue `id`
       */
      progressAriaLabelledBy?: string;

      /**
       * Any additional props to pass to the `CircularProgress` bar when the
       * {@link loadingType} is one of the circular types.
       */
      linearProgressProps?: PropsWithRef<LinearProgressProps, HTMLDivElement>;

      /**
       * Any additional props to pass to the `LinearProgress` bar when the
       * {@link loadingType} is one of the linear types.
       */
      circularProgressProps?: PropsWithRef<CircularProgressProps, HTMLSpanElement>;
    }

    /**
     * **Client Component**
     *
     * The async button can be used to render a loading indicator within a button
     * during an async task. The loading spinner can be shown either by enabling the
     * `loading` prop or returning a promise from the `onClick` event which will
     * continue to show the loading indicator until the promise has been resolved.
     *
     * @example
     * Async onClick
     * ```tsx
     * import { AsyncButton } from "@react-md/core";
     * import { useState, type ReactElement } from "react";
     *
     * function Example(): ReactElement {
     *   const [data, setData] = useState(null);
     *   return (
     *     <AsyncButton
     *       type="submit"
     *       onClick={async () => {
     *         const response = await fetch("/my-api");
     *         const json = await response.json();
     *         setData(json);
     *       }}
     *     >
     *       Submit
     *     </AsyncButton>
     *   );
     * }
     * ```
     *
     * @example
     * Manual Loading State
     * ```tsx
     * import { AsyncButton } from "@react-md/core";
     * import { useMutation } from "@tanstack/query";
     * import { useState, type ReactElement } from "react";
     *
     * function Example(): ReactElement {
     *   const { isLoading, mutate } = useMutation({
     *     mutationFn: (newTodo) => fetch('/todos', {
     *       method: "POST",
     *       body: JSON.stringify(newTodo),
     *     }),
     *   });
     *
     *   return (
     *     <AsyncButton
     *       type="submit"
     *       loading={isLoading}
     *       onClick={() => {
     *         mutate({ id: Date.now(), title: "Create example" });
     *       }}
     *     >
     *       Create Todo
     *     </AsyncButton>
     *   );
     * }
     * ```
     *
     * @remarks \@since 6.0.0
     */
    export const AsyncButton = forwardRef<HTMLButtonElement, AsyncButtonProps>(
      function AsyncButton(props, ref) {
        const {
          id: propId,
          onClick = noop,
          children,
          floating = null,
          theme = floating ? "secondary" : "clear",
          themeType = floating ? "contained" : "flat",
          buttonType = floating ? "icon" : "text",
          className,
          disabled,
          loading: propLoading = false,
          loadingType = "circular-overlay",
          loadingChildren,
          loadingDisabledTheme = false,
          afterAddon: propAfterAddon,
          beforeAddon: propBeforeAddon,
          linearProgressProps,
          circularProgressProps,
          progressAriaLabel,
          progressAriaLabelledBy: propProgressAriaLabelledBy,
          ...remaining
        } = props;
        const id = useEnsuredId(propId, "async-button");
        const { handleAsync, pending } = useAsyncAction({ disabled });
        const loading = pending || propLoading;

        let progressTheme: ProgressTheme = "current-color";
        if (theme === "clear" || theme === "disabled") {
          progressTheme = "primary";
        }

        let progressAriaLabelledBy = propProgressAriaLabelledBy;
        if (
          !progressAriaLabel &&
          !linearProgressProps?.["aria-label"] &&
          !linearProgressProps?.["aria-labelledby"] &&
          !circularProgressProps?.["aria-label"] &&
          !circularProgressProps?.["aria-labelledby"]
        ) {
          progressAriaLabelledBy = id;
        }

        const progress = loadingType.includes("linear") ? (
          <LinearProgress
            aria-label={progressAriaLabel}
            aria-labelledby={progressAriaLabelledBy as string}
            {...linearProgressProps}
            theme={progressTheme}
          />
        ) : (
          <CircularProgress
            aria-label={progressAriaLabel}
            aria-labelledby={progressAriaLabelledBy as string}
            {...circularProgressProps}
            theme={progressTheme}
          />
        );

        let afterAddon = propAfterAddon;
        let beforeAddon = propBeforeAddon;
        let overlayElement: ReactNode;
        let isOverlayCover = false;
        switch (loadingType) {
          case "circular-before":
            beforeAddon = loading ? progress : propBeforeAddon;
            break;
          case "circular-after":
            afterAddon = loading ? progress : propAfterAddon;
            break;
          case "circular-overlay":
          case "linear-above":
          case "linear-below": {
            let alignItems: BoxAlignItems = "center";
            if (loadingType === "linear-above") {
              alignItems = "start";
            } else if (loadingType === "linear-below") {
              alignItems = "end";
            } else {
              isOverlayCover = true;
            }

            overlayElement = loading && (
              <span
                className={overlay({
                  active: true,
                  visible: true,
                  absolute: true,
                  align: alignItems,
                })}
              >
                {progress}
              </span>
            );
            break;
          }
        }

        return (
          <Button
            {...remaining}
            aria-disabled={loading || undefined}
            id={id}
            ref={ref}
            disabled={disabled}
            floating={floating}
            className={cnb(
              "rmd-button--async",
              loading && isOverlayCover && "rmd-button--async-overlay",
              className
            )}
            theme={loading && loadingDisabledTheme ? "disabled" : theme}
            themeType={themeType}
            buttonType={buttonType}
            onClick={handleAsync((event) => Promise.resolve(onClick(event)))}
          >
            {beforeAddon}
            {loading && typeof loadingChildren !== "undefined"
              ? loadingChildren
              : children}
            {afterAddon}
            {overlayElement}
          </Button>
        );
      }
    );