mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-01 20:55:16 +09:00
Keep the 2FA setup modal open until cancelled
Overlay click and Escape closed the setup modal and dropped the user onto the Change password form. Add a Modal closeOnDismiss prop (default unchanged) and use it for the setup modal; Cancel and the header X still close it. Guard Enable with a ref-based single-flight lock in both the settings tab and the setup wizard so a double-click cannot fire two requests, and show a hint after a failed confirm that the code may belong to an older QR. Add the string to every locale.
This commit is contained in:
1 parent
9bb3672551
commit
b156e2dce1
23 files changed
+134
-32
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { dismissGuards } from '@/components/ui/dismissGuards';
|
||||
|
||||
// Generic modal built on the Radix Dialog primitive. SCSS owns all geometry
|
||||
// (styles/components/_ui.scss → .sk-modal*). `size` picks a max-width on
|
||||
@@ -12,6 +13,9 @@ import { cn } from '@/lib/utils';
|
||||
// to the bottom of the scrolling body, and a nested .modal-body adds no extra
|
||||
// padding or scroller. Two-column .form-row stacks in narrow modals.
|
||||
//
|
||||
// closeOnDismiss={false}: overlay click and Escape no longer close the modal
|
||||
// (for flows that would lose in-progress state); explicit buttons still do.
|
||||
//
|
||||
// Form mode: pass `onSubmit` and the body AND footer
|
||||
// are wrapped in one <form>. This exists because a submit button must live
|
||||
// inside the form it submits — without it, every modal with a form had to
|
||||
@@ -27,6 +31,7 @@ export default function Modal({
|
||||
onSubmit,
|
||||
className = '',
|
||||
size = 'md',
|
||||
closeOnDismiss = true,
|
||||
}) {
|
||||
const body = (
|
||||
<>
|
||||
@@ -42,7 +47,7 @@ export default function Modal({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
||||
<DialogContent className={cn('sk-modal', `sk-modal--${size}`, className)}>
|
||||
<DialogContent className={cn('sk-modal', `sk-modal--${size}`, className)} {...dismissGuards(closeOnDismiss)}>
|
||||
{title && (
|
||||
<div className="sk-modal__header">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useState, useEffect, useId } from 'react';
|
||||
import { useState, useEffect, useId, useRef } from 'react';
|
||||
import { useAuth } from '../../contexts/useAuth.js';
|
||||
import api from '../../services/api';
|
||||
import useSettingFocus from '../../hooks/useSettingFocus';
|
||||
import TwoFactorPolicyCard from './TwoFactorPolicyCard';
|
||||
import SSOProviderIcon from '../SSOProviderIcon';
|
||||
import Modal from '../Modal';
|
||||
import { createSingleFlight } from '@/utils/singleFlight';
|
||||
import ErrorState from '../ErrorState';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -155,6 +156,8 @@ const SecuritySettingsTab = () => {
|
||||
const [backupCodes, setBackupCodes] = useState([]);
|
||||
const [twoFAError, setTwoFAError] = useState('');
|
||||
const [twoFALoadError, setTwoFALoadError] = useState(null);
|
||||
const [confirmFailed, setConfirmFailed] = useState(false);
|
||||
const initiateFlight = useRef(createSingleFlight()).current;
|
||||
|
||||
useEffect(() => {
|
||||
load2FAStatus();
|
||||
@@ -204,21 +207,25 @@ const SecuritySettingsTab = () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleInitiate2FA() {
|
||||
setTwoFAError('');
|
||||
setTwoFALoading(true);
|
||||
try {
|
||||
const data = await api.initiate2FASetup();
|
||||
setSetupData(data);
|
||||
setShowSetupModal(true);
|
||||
window.dispatchEvent(new CustomEvent('serverkit:walkthrough-signal', {
|
||||
detail: { type: 'two-factor-setup-started' },
|
||||
}));
|
||||
} catch (err) {
|
||||
setTwoFAError(err.message);
|
||||
} finally {
|
||||
setTwoFALoading(false);
|
||||
}
|
||||
// The ref lock refuses a double-click before `twoFALoading` flushes.
|
||||
function handleInitiate2FA() {
|
||||
return initiateFlight(async () => {
|
||||
setTwoFAError('');
|
||||
setConfirmFailed(false);
|
||||
setTwoFALoading(true);
|
||||
try {
|
||||
const data = await api.initiate2FASetup();
|
||||
setSetupData(data);
|
||||
setShowSetupModal(true);
|
||||
window.dispatchEvent(new CustomEvent('serverkit:walkthrough-signal', {
|
||||
detail: { type: 'two-factor-setup-started' },
|
||||
}));
|
||||
} catch (err) {
|
||||
setTwoFAError(err.message);
|
||||
} finally {
|
||||
setTwoFALoading(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function handleConfirm2FA() {
|
||||
@@ -229,6 +236,7 @@ const SecuritySettingsTab = () => {
|
||||
|
||||
setTwoFALoading(true);
|
||||
setTwoFAError('');
|
||||
setConfirmFailed(false);
|
||||
try {
|
||||
const result = await api.confirm2FASetup(verificationCode);
|
||||
setBackupCodes(result.backup_codes);
|
||||
@@ -240,6 +248,7 @@ const SecuritySettingsTab = () => {
|
||||
detail: { type: 'two-factor-enabled' },
|
||||
}));
|
||||
} catch (err) {
|
||||
setConfirmFailed(true);
|
||||
setTwoFAError(err.message || t('auth.codeMismatch', "That code didn't match. Enter the current 6-digit code from your authenticator app."));
|
||||
} finally {
|
||||
setTwoFALoading(false);
|
||||
@@ -455,7 +464,7 @@ Keep these codes in a safe place.`;
|
||||
|
||||
{/* 2FA Setup Modal */}
|
||||
{showSetupModal && setupData && (
|
||||
<Modal open={true} onClose={() => setShowSetupModal(false)} title={t('app.securitySettingsTab.setUpTwoFactorAuthentication', 'Set up two-factor authentication')} size="md">
|
||||
<Modal open={true} onClose={() => setShowSetupModal(false)} closeOnDismiss={false} title={t('app.securitySettingsTab.setUpTwoFactorAuthentication', 'Set up two-factor authentication')} size="md">
|
||||
<div className="setup-steps" data-walkthrough="two-factor-verify">
|
||||
<div className="setup-step">
|
||||
<span className="step-number">1</span>
|
||||
@@ -494,6 +503,7 @@ Keep these codes in a safe place.`;
|
||||
autoFocus
|
||||
/>
|
||||
{twoFAError && <p className="error-text">{twoFAError}</p>}
|
||||
{confirmFailed && <p className="form-hint">{t('app.securitySettingsTab.codeMayBeFromOlderQr', 'The code may be from an older QR. Use the code for the QR currently on screen.')}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { ShieldCheck, Download, AlertTriangle, Check, Loader } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -7,6 +7,7 @@ import CopyField from '../CopyField';
|
||||
import { downloadBlob } from '@/utils/downloadBlob';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import InfoTip from '@/components/InfoTip';
|
||||
import { createSingleFlight } from '@/utils/singleFlight';
|
||||
|
||||
// Enrolment is a three-beat flow. Offer is the default so someone who just
|
||||
// wants a dashboard is one click from moving on — 2FA is offered here because
|
||||
@@ -28,6 +29,8 @@ const SetupStepSecurity = ({ onComplete }) => {
|
||||
const [savedCodes, setSavedCodes] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [confirmFailed, setConfirmFailed] = useState(false);
|
||||
const enableFlight = useRef(createSingleFlight()).current;
|
||||
|
||||
// Stepping back to Capacity and forward again re-mounts this step, but the
|
||||
// enrolment already landed server-side — re-offering it would just 400.
|
||||
@@ -45,18 +48,22 @@ const SetupStepSecurity = ({ onComplete }) => {
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function handleEnable() {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const data = await api.initiate2FASetup();
|
||||
setSetupData(data);
|
||||
setStage(STAGE_ENROLL);
|
||||
} catch (err) {
|
||||
setError(err.message || 'Could not start two-factor setup.');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
// The ref lock refuses a double-click before `busy` flushes.
|
||||
function handleEnable() {
|
||||
return enableFlight(async () => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setConfirmFailed(false);
|
||||
try {
|
||||
const data = await api.initiate2FASetup();
|
||||
setSetupData(data);
|
||||
setStage(STAGE_ENROLL);
|
||||
} catch (err) {
|
||||
setError(err.message || 'Could not start two-factor setup.');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function handleConfirm() {
|
||||
@@ -66,11 +73,13 @@ const SetupStepSecurity = ({ onComplete }) => {
|
||||
}
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setConfirmFailed(false);
|
||||
try {
|
||||
const result = await api.confirm2FASetup(code);
|
||||
setBackupCodes(result.backup_codes || []);
|
||||
setStage(STAGE_CODES);
|
||||
} catch (err) {
|
||||
setConfirmFailed(true);
|
||||
setError(err.message || 'That code did not match. Try the next one.');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
@@ -151,7 +160,10 @@ const SetupStepSecurity = ({ onComplete }) => {
|
||||
{error && (
|
||||
<div className="tier-warning">
|
||||
<AlertTriangle size={20} className="tier-warning-icon" />
|
||||
<div className="tier-warning-text">{error}</div>
|
||||
<div className="tier-warning-text">
|
||||
{error}
|
||||
{confirmFailed && <> {t('app.securitySettingsTab.codeMayBeFromOlderQr', 'The code may be from an older QR. Use the code for the QR currently on screen.')}</>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
// Radix Dialog props that stop overlay click / Escape from closing a dialog.
|
||||
// Explicit close buttons (Cancel, the header X) still work.
|
||||
const block = (event) => event.preventDefault();
|
||||
|
||||
export function dismissGuards(closeOnDismiss = true) {
|
||||
return closeOnDismiss
|
||||
? {}
|
||||
: { onPointerDownOutside: block, onInteractOutside: block, onEscapeKeyDown: block };
|
||||
}
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "تغيير كلمة المرور",
|
||||
"changing": "جارٍ التغيير…",
|
||||
"codeFromAuthenticatorOrBackupCode": "رمز من المصادقة أو رمز النسخ الاحتياطي",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "تأكيد كلمة المرور الجديدة",
|
||||
"confirmNewPassword2": "تأكيد كلمة المرور الجديدة",
|
||||
"connectExternalIdentityProvidersToYour": "قم بتوصيل موفري الهوية الخارجيين بحسابك",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "পাসওয়ার্ড পরিবর্তন করুন",
|
||||
"changing": "পরিবর্তন করা হচ্ছে…",
|
||||
"codeFromAuthenticatorOrBackupCode": "প্রমাণীকরণকারী বা ব্যাকআপ কোড থেকে কোড",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "নতুন পাসওয়ার্ড নিশ্চিত করুন",
|
||||
"confirmNewPassword2": "নতুন পাসওয়ার্ড নিশ্চিত করুন",
|
||||
"connectExternalIdentityProvidersToYour": "আপনার অ্যাকাউন্টে বহিরাগত পরিচয় প্রদানকারীকে সংযুক্ত করুন",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "Passwort ändern",
|
||||
"changing": "Wird geändert…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Code vom Authentifikator oder Backup-Code",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Bestätigen Sie das neue Passwort",
|
||||
"confirmNewPassword2": "Neues Passwort bestätigen",
|
||||
"connectExternalIdentityProvidersToYour": "Verbinden Sie externe Identitätsanbieter mit Ihrem Konto",
|
||||
|
||||
@@ -5500,6 +5500,7 @@
|
||||
"changePassword": "Change password",
|
||||
"changing": "Changing…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Code from authenticator or backup code",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Confirm new password",
|
||||
"confirmNewPassword2": "Confirm new password",
|
||||
"connectExternalIdentityProvidersToYour": "Connect external identity providers to your account",
|
||||
|
||||
@@ -5266,6 +5266,7 @@
|
||||
"changePassword": "Cambiar contraseña",
|
||||
"changing": "Cambiando…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Código de la app de autenticación o código de recuperación",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Confirmar nueva contraseña",
|
||||
"confirmNewPassword2": "Confirma la nueva contraseña",
|
||||
"connectExternalIdentityProvidersToYour": "Conecta proveedores de identidad externos a tu cuenta",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "Changer le mot de passe",
|
||||
"changing": "Modification…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Code de l'authentificateur ou code de sauvegarde",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Confirmer le nouveau mot de passe",
|
||||
"confirmNewPassword2": "Confirmer le nouveau mot de passe",
|
||||
"connectExternalIdentityProvidersToYour": "Connectez des fournisseurs d'identité externes à votre compte",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "Ubah Kata Sandi",
|
||||
"changing": "Mengubah…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Kode dari pengautentikasi atau kode cadangan",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Konfirmasi Kata Sandi Baru",
|
||||
"confirmNewPassword2": "Konfirmasikan kata sandi baru",
|
||||
"connectExternalIdentityProvidersToYour": "Hubungkan penyedia identitas eksternal ke akun Anda",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "Cambiare la password",
|
||||
"changing": "Modifica…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Codice dall'autenticatore o codice di backup",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Conferma nuova password",
|
||||
"confirmNewPassword2": "Conferma la nuova password",
|
||||
"connectExternalIdentityProvidersToYour": "Connetti i provider di identità esterni al tuo account",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "비밀번호 변경",
|
||||
"changing": "변경 중…",
|
||||
"codeFromAuthenticatorOrBackupCode": "인증자의 코드 또는 백업 코드",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "새 비밀번호 확인",
|
||||
"confirmNewPassword2": "새 비밀번호 확인",
|
||||
"connectExternalIdentityProvidersToYour": "외부 ID 공급자를 계정에 연결",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "Zmień hasło",
|
||||
"changing": "Zmienianie…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Kod z uwierzytelniacza lub kod zapasowy",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Potwierdź nowe hasło",
|
||||
"confirmNewPassword2": "Potwierdź nowe hasło",
|
||||
"connectExternalIdentityProvidersToYour": "Połącz zewnętrznych dostawców tożsamości ze swoim kontem",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "Alterar senha",
|
||||
"changing": "Alterando…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Código do autenticador ou código de backup",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Confirme a nova senha",
|
||||
"confirmNewPassword2": "Confirme a nova senha",
|
||||
"connectExternalIdentityProvidersToYour": "Conecte provedores de identidade externos à sua conta",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "Изменить пароль",
|
||||
"changing": "Изменение…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Код из аутентификатора или резервный код",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Подтвердите новый пароль",
|
||||
"confirmNewPassword2": "Подтвердите новый пароль",
|
||||
"connectExternalIdentityProvidersToYour": "Подключите внешних поставщиков удостоверений к своей учетной записи",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "เปลี่ยนรหัสผ่าน",
|
||||
"changing": "กำลังเปลี่ยน…",
|
||||
"codeFromAuthenticatorOrBackupCode": "รหัสจากตัวตรวจสอบสิทธิ์หรือรหัสสำรอง",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "ยืนยันรหัสผ่านใหม่",
|
||||
"confirmNewPassword2": "ยืนยันรหัสผ่านใหม่",
|
||||
"connectExternalIdentityProvidersToYour": "เชื่อมต่อผู้ให้บริการข้อมูลประจำตัวภายนอกกับบัญชีของคุณ",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "Şifre değiştir",
|
||||
"changing": "Değiştiriliyor…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Kimlik doğrulayıcıdan veya yedek koddan gelen kod",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Yeni Şifreyi Onayla",
|
||||
"confirmNewPassword2": "Yeni şifreyi onayla",
|
||||
"connectExternalIdentityProvidersToYour": "Harici kimlik sağlayıcılarını hesabınıza bağlayın",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "Thay đổi mật khẩu",
|
||||
"changing": "Đang thay đổi…",
|
||||
"codeFromAuthenticatorOrBackupCode": "Mã từ trình xác thực hoặc mã dự phòng",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "Xác nhận mật khẩu mới",
|
||||
"confirmNewPassword2": "Xác nhận mật khẩu mới",
|
||||
"connectExternalIdentityProvidersToYour": "Kết nối nhà cung cấp danh tính bên ngoài với tài khoản của bạn",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "更改密码",
|
||||
"changing": "正在更改…",
|
||||
"codeFromAuthenticatorOrBackupCode": "来自验证器或备份代码的代码",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "确认新密码",
|
||||
"confirmNewPassword2": "确认新密码",
|
||||
"connectExternalIdentityProvidersToYour": "将外部身份提供商连接到您的帐户",
|
||||
|
||||
@@ -5265,6 +5265,7 @@
|
||||
"changePassword": "更改密碼",
|
||||
"changing": "正在變更…",
|
||||
"codeFromAuthenticatorOrBackupCode": "驗證器或備用驗證碼",
|
||||
"codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.",
|
||||
"confirmNewPassword": "確認新密碼",
|
||||
"confirmNewPassword2": "確認新密碼",
|
||||
"connectExternalIdentityProvidersToYour": "將外部身分提供者連線到您的帳戶",
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { createSingleFlight } from '../singleFlight.js';
|
||||
import { dismissGuards } from '../../components/ui/dismissGuards.js';
|
||||
|
||||
test('single flight refuses a second call before the first settles', async () => {
|
||||
const run = createSingleFlight();
|
||||
let calls = 0;
|
||||
let release;
|
||||
const first = run(() => { calls += 1; return new Promise((r) => { release = r; }); });
|
||||
assert.equal(await run(() => { calls += 1; }), undefined);
|
||||
release('done');
|
||||
assert.equal(await first, 'done');
|
||||
assert.equal(calls, 1);
|
||||
await run(() => { calls += 1; });
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('single flight unlocks after a failure', async () => {
|
||||
const run = createSingleFlight();
|
||||
await assert.rejects(run(() => { throw new Error('x'); }));
|
||||
assert.equal(await run(() => 'ok'), 'ok');
|
||||
});
|
||||
|
||||
test('dismiss guards only block overlay and Escape when asked', () => {
|
||||
assert.deepEqual(dismissGuards(), {});
|
||||
const g = dismissGuards(false);
|
||||
for (const key of ['onPointerDownOutside', 'onInteractOutside', 'onEscapeKeyDown']) {
|
||||
let prevented = false;
|
||||
g[key]({ preventDefault: () => { prevented = true; } });
|
||||
assert.ok(prevented, key);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
// Drops a call while a previous one is still running. Backed by a plain
|
||||
// object (hold it in a useRef) so a double-click is refused synchronously,
|
||||
// before React has flushed any `disabled` state.
|
||||
export function createSingleFlight() {
|
||||
let busy = false;
|
||||
return async function run(fn) {
|
||||
if (busy) return undefined;
|
||||
busy = true;
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user