Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Dev cards: focus moves after the render that shows its target (#897)

Oleksandr Ivanchenkoe0fca3b68d1b
diff --git a/frontend/src/components/dev/ProdFloorCard.tsx b/frontend/src/components/dev/ProdFloorCard.tsx
index 6090b229..82383743 100644
--- a/frontend/src/components/dev/ProdFloorCard.tsx
+++ b/frontend/src/components/dev/ProdFloorCard.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useEffect, useReducer, useRef, useState } from 'react';
+import React, { useCallback, useEffect, useLayoutEffect, useReducer, useRef, useState } from 'react';
import { Database, Folder, Target, X, Check, Terminal } from 'lucide-react';
import type { BackupResult, FloorBackup, FloorResolveOpts, ProdFloor } from '../../dev/types';
import { parseBackupResult, parseBackupState } from '../../dev/types';
@@ -125,6 +125,18 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({
// The server's backup state, re-read on focus and after a backup or a new command, so a backup taken (or a
// command set) elsewhere counts without a reload. The server checks freshness again at answer time.
const spaceId = floor.space_id;
+ // Focus moves after the render that shows its target, never on a timer: a setTimeout(0) can run before React
+ // commits when the scheduler yields (a slow machine), find the target not rendered yet and drop focus to <body>.
+ const focusNext = useRef<(() => HTMLElement | null) | null>(null);
+ const focusAfterRender = (target: () => HTMLElement | null) => {
+ focusNext.current = target;
+ };
+ useLayoutEffect(() => {
+ const target = focusNext.current;
+ if (!target) return;
+ focusNext.current = null;
+ target()?.focus();
+ });
const busyRef = useRef(false);
busyRef.current = view.busy || cmd.saving;
const refresh = useCallback(async () => {
@@ -186,11 +198,11 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({
if (off) return;
setSkip({ open: false, sure: false });
setCmd((c) => ({ ...c, open: true, error: null }));
- window.setTimeout(() => cmdRef.current?.focus(), 0);
+ focusAfterRender(() => cmdRef.current);
};
const closeCommand = () => {
setCmd((c) => ({ ...c, open: false, error: null }));
- window.setTimeout(() => mainRef.current?.focus(), 0);
+ focusAfterRender(() => mainRef.current);
};
const saveCommand = async (e?: React.FormEvent) => {
e?.preventDefault();
@@ -206,7 +218,7 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({
await onSetCommand(spaceId, value);
} catch (err) {
setCmd((c) => ({ ...c, saving: false, error: err instanceof Error ? err.message : 'Couldn’t save the command.' }));
- window.setTimeout(() => cmdRef.current?.focus(), 0);
+ focusAfterRender(() => cmdRef.current);
return;
}
const b = await refresh();
@@ -215,18 +227,18 @@ export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({
setCmd({ open: false, value: '', saving: false, error: null });
setJustSaved(true);
// The main button is Back up first now, in the same place: focus goes there.
- window.setTimeout(() => mainRef.current?.focus(), 0);
+ focusAfterRender(() => mainRef.current);
};
const openSkip = () => {
if (off) return;
setCmd((c) => ({ ...c, open: false, error: null }));
setSkip({ open: true, sure: false });
- window.setTimeout(() => skipRef.current?.focus(), 0);
+ focusAfterRender(() => skipRef.current);
};
const closeSkip = () => {
setSkip({ open: false, sure: false });
- window.setTimeout(() => (skipOpenerRef.current ?? mainRef.current)?.focus(), 0);
+ focusAfterRender(() => skipOpenerRef.current ?? mainRef.current);
};
const allowWithoutBackup = () => {
if (off || !skip.sure || !view.skip) return;
diff --git a/frontend/tests/devCards.test.mjs b/frontend/tests/devCards.test.mjs
index 53a5c2a2..f810e49e 100644
--- a/frontend/tests/devCards.test.mjs
+++ b/frontend/tests/devCards.test.mjs
@@ -896,6 +896,48 @@ test('22f (b): set a command inline, back up and allow, without leaving the card
}
});
+test('22f: focus lands on its target even when React yields before rendering it (the #895 flake)', async () => {
+ // React's scheduler gives up the thread after 5 ms of work. Advancing performance.now 10 ms per call makes it
+ // yield every time, as on a starved CI runner: a focus on a setTimeout(0) then runs before the render that
+ // mounts its target, and focus drops to <body> for good.
+ const perf = window.performance === globalThis.performance ? [globalThis.performance] : [globalThis.performance, window.performance];
+ const realNows = perf.map((p) => p.now);
+ let skew = 0;
+ const slow = (on) => perf.forEach((p, i) => (p.now = on ? () => (skew += 10) + realNows[i].call(p) : realNows[i]));
+ // Name the focused element instead of handing two jsdom nodes to assert (printing them runs out of memory).
+ const focused = () => {
+ const a = document.activeElement;
+ return a ? `${a.tagName.toLowerCase()}${a.dataset?.floorMain ? `[data-floor-main=${a.dataset.floorMain}]` : ''}` : 'nothing';
+ };
+ const waitFor = async (cond, ms = 2000) => {
+ const end = Date.now() + ms;
+ while (!cond() && Date.now() < end) await new Promise((r) => setTimeout(r, 10));
+ };
+ try {
+ let server = { state: 'no_command', age_s: null, bytes: null, path: null, error: null };
+ const host = await mount(m.ModernApprovalCard, {
+ approval: fx.FLOOR_GUESS_NO_COMMAND,
+ onResolve() {},
+ onSetCommand: async () => {
+ server = NONE;
+ },
+ onLoadBackup: async () => server,
+ });
+ slow(true);
+ await click(host.querySelector('[data-floor-main]'));
+ await waitFor(() => document.activeElement === host.querySelector('[data-floor-command] input'));
+ assert.ok(document.activeElement === host.querySelector('[data-floor-command] input'), `focus goes to the field, not ${focused()}`);
+ await typeInto(host.querySelector('[data-floor-command] input'), 'pg_dump app');
+ await click(host.querySelector('[data-floor-command-save]'));
+ await waitFor(() => document.activeElement === host.querySelector('[data-floor-main]'));
+ slow(false);
+ assert.equal(host.querySelector('[data-floor-main]')?.dataset.floorMain, 'backup');
+ assert.ok(document.activeElement === host.querySelector('[data-floor-main]'), `focus is on Back up first, not ${focused()}`);
+ } finally {
+ slow(false);
+ }
+});
+
test('22f: a refused save keeps the field open with the server’s reason; an older server still moves on', async () => {
const host = await mount(m.ModernApprovalCard, {
approval: fx.FLOOR_NO_COMMAND,