# All files / src/components/panels GitHubAccountsPanel.tsx

0% Statements 0/195
0% Branches 0/1
0% Functions 0/1
0% Lines 0/195

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

     import { useState, type JSX, type FormEvent } from "react";
    import { X, Star } from "lucide-react";
    import type { ToastVariant } from "../../context/ToastContext.js";
    import type { GitHubAccountData } from "../../hooks/types.js";
    import { ICON_MD } from "../../utils/iconSize.js";
    import { ConfirmDialog } from "../display/index.js";
    import styles from "./SettingsPanel.module.scss";

    /** Props for the GitHubAccountsPanel component. */
    export interface GitHubAccountsPanelProps {
      /** All registered GitHub accounts. */
      githubAccounts: GitHubAccountData[];
      /** Whether the account list is loading. */
      githubAccountsLoading: boolean;
      /** Register a new GitHub account. Username will be resolved server-side if empty. */
      onAddGitHubAccount: (
        label: string,
        token: string,
        username: string,
        isDefault: boolean,
      ) => Promise<void>;
      /** Update an existing GitHub account. */
      onUpdateGitHubAccount: (
        id: string,
        fields: { label?: string; token?: string; isDefault?: boolean },
      ) => Promise<void>;
      /** Remove a GitHub account by ID. */
      onRemoveGitHubAccount: (id: string) => Promise<void>;
      /** Import accounts from the local gh CLI authentication state. */
      onImportGitHubAccounts: () => Promise<{ imported: number; usernames: string[] }>;
      /** Display a toast notification. */
      onShowToast?: (message: string, variant?: ToastVariant) => void;
    }

    /** Settings panel for managing registered GitHub accounts. */
    export function GitHubAccountsPanel({
      githubAccounts,
      githubAccountsLoading,
      onAddGitHubAccount,
      onUpdateGitHubAccount,
      onRemoveGitHubAccount,
      onImportGitHubAccounts,
      onShowToast,
    }: GitHubAccountsPanelProps): JSX.Element {
      const [label, setLabel] = useState("");
      const [token, setToken] = useState("");
      const [isDefault, setIsDefault] = useState(false);
      const [adding, setAdding] = useState(false);
      const [importing, setImporting] = useState(false);
      const [confirmRemoveId, setConfirmRemoveId] = useState<string | null>(null);

      const confirmRemoveAccount = githubAccounts.find((a) => a.id === confirmRemoveId);

      const handleSubmit = async (e: FormEvent): Promise<void> => {
        e.preventDefault();
        if (!label.trim() || !token.trim()) {
          return;
        }
        setAdding(true);
        try {
          await onAddGitHubAccount(label.trim(), token.trim(), "", isDefault);
          onShowToast?.("GitHub account added", "success");
          setLabel("");
          setToken("");
          setIsDefault(false);
        } catch (err) {
          const msg = err instanceof Error ? err.message : "Failed to add account";
          onShowToast?.(msg, "error");
        } finally {
          setAdding(false);
        }
      };

      const handleSetDefault = async (id: string): Promise<void> => {
        try {
          await onUpdateGitHubAccount(id, { isDefault: true });
          onShowToast?.("Default account updated", "success");
        } catch (err) {
          const msg = err instanceof Error ? err.message : "Failed to update account";
          onShowToast?.(msg, "error");
        }
      };

      const handleConfirmRemove = async (): Promise<void> => {
        if (!confirmRemoveId) {
          return;
        }
        try {
          await onRemoveGitHubAccount(confirmRemoveId);
          onShowToast?.("GitHub account removed", "info");
        } catch (err) {
          const msg = err instanceof Error ? err.message : "Failed to remove account";
          onShowToast?.(msg, "error");
        } finally {
          setConfirmRemoveId(null);
        }
      };

      const handleImport = async (): Promise<void> => {
        setImporting(true);
        try {
          const result = await onImportGitHubAccounts();
          if (result.imported > 0) {
            onShowToast?.(
              `Imported ${result.imported} account(s): ${result.usernames.join(", ")}`,
              "success",
            );
          } else {
            onShowToast?.("No new accounts to import", "info");
          }
        } catch (err) {
          const msg = err instanceof Error ? err.message : "Import failed";
          onShowToast?.(msg, "error");
        } finally {
          setImporting(false);
        }
      };

      return (
        <>
          <ConfirmDialog
            isOpen={confirmRemoveId !== null}
            title="Remove GitHub Account?"
            description={
              confirmRemoveAccount
                ? `"${confirmRemoveAccount.label}"${confirmRemoveAccount.username ? ` (@${confirmRemoveAccount.username})` : ""} will be permanently removed.`
                : undefined
            }
            onConfirm={() => {
              handleConfirmRemove().catch(() => {});
            }}
            onCancel={() => setConfirmRemoveId(null)}
          />

          <section className={styles.section} data-testid="github-accounts-panel">
            <h3 className={styles.sectionTitle}>GitHub Accounts</h3>
            <p className={styles.sectionDescription}>
              Register multiple GitHub accounts to use different identities per environment. The default
              account is used when no specific account is assigned.
            </p>

            {githubAccountsLoading && githubAccounts.length === 0 ? (
              <div className={styles.emptyState}>Loading...</div>
            ) : githubAccounts.length === 0 ? (
              <div className={styles.emptyStateInfo}>
                No GitHub accounts registered. Add one below or import from the gh CLI.
              </div>
            ) : (
              <div className={styles.tokenList}>
                {githubAccounts.map((account) => (
                  <div
                    key={account.id}
                    className={styles.tokenRow}
                    data-testid={`github-account-row-${account.id}`}
                  >
                    {account.isDefault && (
                      <span className={styles.tokenBadge} title="Default account">
                        default
                      </span>
                    )}
                    <span className={styles.tokenName}>{account.label}</span>
                    {account.username && (
                      <span className={styles.tokenTarget}>@{account.username}</span>
                    )}
                    {!account.isDefault && (
                      <button
                        className={styles.deleteButton}
                        onClick={() => {
                          handleSetDefault(account.id).catch(() => {});
                        }}
                        title="Set as default"
                        aria-label={`Set ${account.label} as default`}
                        data-testid={`github-account-set-default-${account.id}`}
                      >
                        <Star size={ICON_MD} aria-hidden="true" />
                      </button>
                    )}
                    <button
                      className={styles.deleteButton}
                      onClick={() => setConfirmRemoveId(account.id)}
                      title={`Remove ${account.label}`}
                      aria-label={`Remove ${account.label}`}
                      data-testid={`github-account-remove-${account.id}`}
                    >
                      <X size={ICON_MD} aria-hidden="true" />
                    </button>
                  </div>
                ))}
              </div>
            )}

            <form
              className={styles.addForm}
              onSubmit={(e) => {
                handleSubmit(e).catch(() => {});
              }}
            >
              <div className={styles.formRow}>
                <input
                  className={styles.input}
                  type="text"
                  placeholder="Label (e.g. personal, work)"
                  value={label}
                  onChange={(e) => setLabel(e.target.value)}
                  data-testid="github-account-label-input"
                />
                <input
                  className={styles.input}
                  type="password"
                  placeholder="Personal access token"
                  value={token}
                  onChange={(e) => setToken(e.target.value)}
                  data-testid="github-account-token-input"
                />
              </div>
              <div className={styles.formRow}>
                <label
                  className={styles.tokenTarget}
                  style={{ display: "flex", alignItems: "center", gap: "6px", cursor: "pointer" }}
                >
                  <input
                    type="checkbox"
                    checked={isDefault}
                    onChange={(e) => setIsDefault(e.target.checked)}
                    data-testid="github-account-default-checkbox"
                  />
                  Set as default
                </label>
                <button
                  className={styles.addButton}
                  type="submit"
                  disabled={!label.trim() || !token.trim() || adding}
                  data-testid="github-account-add-button"
                >
                  {adding ? "Adding..." : "Add Account"}
                </button>
                <button
                  className={styles.addButton}
                  type="button"
                  onClick={() => {
                    handleImport().catch(() => {});
                  }}
                  disabled={importing}
                  data-testid="github-account-import-button"
                >
                  {importing ? "Importing..." : "Import from gh CLI"}
                </button>
              </div>
            </form>
          </section>
        </>
      );
    }