fix(settings): fall back to visible parent when search target is gated

This commit is contained in:
陈大猫 committed 2026-11-13 18:26:11 +08:00
1 parent d52d3914fc
commit e8fef8eebc
7 files changed
+182 -18

No files matched your search

+1
View File
@@ -409,6 +409,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
const nestedDelayMs = (request.aiSubTab || request.syncSubTab) ? 80 : 40;
const focusHandle = window.setTimeout(() => {
void focusSettingsAnchor(request.anchorId, {
fallbackAnchorId: request.fallbackAnchorId,
attempts: 48,
delayMs: 50,
}).finally(() => {
@@ -93,6 +93,7 @@ export function SettingsSearchControl({
aiSubTab: hit.entry.aiSubTab,
syncSubTab: hit.entry.syncSubTab,
anchorId: hit.entry.id,
fallbackAnchorId: hit.entry.fallbackAnchorId,
});
collapseSearch(false);
};
+97 -1
View File
@@ -1,6 +1,102 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import test, { type TestContext } from "node:test";
import { settingsAnchorDomId } from "../../domain/settingsSearchCatalog.ts";
import { focusSettingsAnchor } from "./settingsFocus.ts";
function setupFocusDom(t: TestContext) {
t.mock.timers.enable({ apis: ["setTimeout"] });
const anchors = new Map<string, HTMLElement>();
const focused: string[] = [];
const scrolled: string[] = [];
const globals = {
document: {
getElementById: (id: string) => anchors.get(id) ?? null,
querySelectorAll: () => [],
documentElement: {},
body: {},
},
window: { setTimeout, clearTimeout },
CSS: { escape: (value: string) => value },
requestAnimationFrame: (callback: FrameRequestCallback) => { callback(0); return 0; },
};
for (const [key, value] of Object.entries(globals)) {
const previous = Object.getOwnPropertyDescriptor(globalThis, key);
Object.defineProperty(globalThis, key, { configurable: true, value });
t.after(() => {
if (previous) Object.defineProperty(globalThis, key, previous);
else Reflect.deleteProperty(globalThis, key);
});
}
const mount = (id: string, visible = true) => {
const classes = new Set<string>();
const el = {
closest: () => null,
checkVisibility: () => visible,
classList: { add: (name: string) => classes.add(name), remove: (name: string) => classes.delete(name) },
matches: () => true,
hasAttribute: () => true,
focus: () => focused.push(id),
scrollIntoView: () => scrolled.push(id),
} as unknown as HTMLElement;
anchors.set(settingsAnchorDomId(id), el);
return classes;
};
return { mount, focused, scrolled };
}
test("missing search target focuses and highlights its visible parent after a short mount window", async (t) => {
const { mount, focused, scrolled } = setupFocusDom(t);
const parentClasses = mount("parent");
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent", attempts: 48, delayMs: 50 });
for (let retry = 0; retry < 3; retry += 1) t.mock.timers.tick(50);
t.mock.timers.tick(49);
assert.deepEqual(focused, []);
t.mock.timers.tick(1);
assert.equal(await result, true);
assert.deepEqual(focused, ["parent"]);
assert.deepEqual(scrolled, ["parent"]);
assert.ok(parentClasses.has("settings-search-highlight"));
});
test("search focus prefers a visible primary over its fallback", async (t) => {
const { mount, focused } = setupFocusDom(t);
const childClasses = mount("child");
const parentClasses = mount("parent");
assert.equal(await focusSettingsAnchor("child", { fallbackAnchorId: "parent" }), true);
assert.deepEqual(focused, ["child"]);
assert.ok(childClasses.has("settings-search-highlight"));
assert.equal(parentClasses.has("settings-search-highlight"), false);
});
test("search focus waits for a lazy primary before using a visible fallback", async (t) => {
const { mount, focused } = setupFocusDom(t);
mount("parent");
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent" });
t.mock.timers.tick(50);
t.mock.timers.tick(50);
mount("child");
t.mock.timers.tick(50);
assert.equal(await result, true);
assert.deepEqual(focused, ["child"]);
});
test("search focus skips a hidden primary and waits for a visible fallback", async (t) => {
const { mount, focused } = setupFocusDom(t);
mount("child", false);
mount("parent", false);
const result = focusSettingsAnchor("child", { fallbackAnchorId: "parent" });
for (let retry = 0; retry < 4; retry += 1) t.mock.timers.tick(50);
assert.deepEqual(focused, []);
mount("parent");
t.mock.timers.tick(50);
assert.equal(await result, true);
assert.deepEqual(focused, ["parent"]);
});
test("system setting hints sit below their cards with a shared top gap", () => {
const uiSource = readFileSync(new URL("./settings-ui.tsx", import.meta.url), "utf8");
+24 -15
View File
@@ -4,12 +4,15 @@ const HIGHLIGHT_CLASS = "settings-search-highlight";
const HIGHLIGHT_MS = 1600;
/** Keep focused anchors slightly below the top of the settings content pane. */
const SCROLL_TOP_PADDING_PX = 24;
/** Allow 200ms at the default retry delay for lazy tab / sub-tab mounts. */
const FALLBACK_AFTER_ATTEMPTS = 5;
export type SettingsFocusTarget = {
tab: string;
aiSubTab?: string;
syncSubTab?: string;
anchorId: string;
fallbackAnchorId?: string;
};
let focusGeneration = 0;
@@ -30,6 +33,18 @@ function isAnchorVisible(el: HTMLElement): boolean {
return el.getClientRects().length > 0;
}
function findVisibleAnchor(anchorId: string): HTMLElement | undefined {
const candidates = [
document.getElementById(settingsAnchorDomId(anchorId)),
...Array.from(
document.querySelectorAll<HTMLElement>(
`[data-settings-anchor="${CSS.escape(anchorId)}"]`,
),
),
].filter((node): node is HTMLElement => Boolean(node));
return candidates.find((node) => isAnchorVisible(node));
}
function focusAnchorElement(el: HTMLElement): void {
const focusable = el.matches("button, a, input, select, textarea, [tabindex]")
? el
@@ -103,15 +118,16 @@ export function scrollSettingsAnchorIntoView(
/**
* Scroll the settings content pane to a catalog anchor and briefly highlight it.
* Retries to cover lazy tab mounts / nested sub-tab switches.
* After a short mount window, use a visible parent fallback for gated rows.
*/
export function focusSettingsAnchor(
anchorId: string,
options?: { attempts?: number; delayMs?: number },
options?: { attempts?: number; delayMs?: number; fallbackAnchorId?: string },
): Promise<boolean> {
const attempts = options?.attempts ?? 40;
const delayMs = options?.delayMs ?? 50;
const generation = ++focusGeneration;
let remaining = attempts;
let attempt = 0;
return new Promise((resolve) => {
const finish = (ok: boolean) => {
@@ -125,20 +141,13 @@ export function focusSettingsAnchor(
return;
}
const domId = settingsAnchorDomId(anchorId);
const candidates = [
document.getElementById(domId),
...Array.from(
document.querySelectorAll<HTMLElement>(
`[data-settings-anchor="${CSS.escape(anchorId)}"]`,
),
),
].filter((node): node is HTMLElement => Boolean(node));
const el = candidates.find((node) => isAnchorVisible(node));
attempt += 1;
let el = findVisibleAnchor(anchorId);
if (!el && options?.fallbackAnchorId && attempt >= Math.min(FALLBACK_AFTER_ATTEMPTS, attempts)) {
el = findVisibleAnchor(options.fallbackAnchorId);
}
if (!el) {
remaining -= 1;
if (remaining > 0) {
if (attempt < attempts) {
window.setTimeout(tryFocus, delayMs);
return;
}
+35
View File
@@ -64,6 +64,41 @@ test("settings search catalog has unique ids", () => {
assert.equal(new Set(ids).size, ids.length);
});
test("newly indexed gated settings retain visible parent destinations in search", () => {
const fallbacks = {
"terminal-hibernate-hidden-tabs-delay": "terminal-hibernate-hidden-tabs",
"terminal-hibernate-skip-alt-screen": "terminal-hibernate-hidden-tabs",
"terminal-hibernate-keep-renderer-count": "terminal-hibernate-hidden-tabs",
"terminal-hibernate-replay-chunk-bytes": "terminal-hibernate-hidden-tabs",
"terminal-hibernate-prefer-wasm-serialize": "terminal-hibernate-hidden-tabs",
"terminal-inline-images-kitty": "terminal-inline-images-enabled",
"terminal-inline-images-sixel": "terminal-inline-images-enabled",
"terminal-inline-images-iip": "terminal-inline-images-enabled",
"terminal-inline-images-storage-limit": "terminal-inline-images-enabled",
"terminal-inline-images-max-megapixels": "terminal-inline-images-enabled",
"terminal-inline-images-sequence-limit": "terminal-inline-images-enabled",
"terminal-host-info-bar-title-mode": "terminal-host-info-bar-show",
"terminal-server-stats-refresh-interval": "terminal-server-stats-show",
"ai-web-search-api-key": "ai-web-search-provider",
"system-network-proxy-url": "system-network-proxy-mode",
"system-network-proxy-bypass": "system-network-proxy-mode",
"system-app-lock-timeout": "system-app-lock",
};
const hits = filterSettingsSearchCatalog("", (key) => en[key] ?? key, { limit: 500 });
for (const [id, fallbackId] of Object.entries(fallbacks)) {
const entry = hits.find((hit) => hit.entry.id === id)?.entry;
assert.ok(entry, id);
assert.equal(entry.fallbackAnchorId, fallbackId, id);
const parent = SETTINGS_SEARCH_CATALOG.find((candidate) => candidate.id === fallbackId);
assert.ok(parent, fallbackId);
assert.equal(parent.tab, entry.tab, id);
assert.equal(parent.aiSubTab, entry.aiSubTab, id);
assert.equal(parent.fallbackAnchorId, undefined, fallbackId);
}
// The local start-directory row is always mounted in this UI.
assert.equal(hits.find((hit) => hit.entry.id === "terminal-local-shell-start-dir")?.entry.fallbackAnchorId, undefined);
});
test("filterSettingsSearchCatalog matches English labels", () => {
const hits = filterSettingsSearchCatalog("copy on select", tEn);
assert.ok(hits.some((hit) => hit.entry.id === "terminal-copy-on-select"));
+2 -2
View File
@@ -24,7 +24,7 @@ function collectSourceFiles(root: string): string[] {
return out;
}
test("every settings search catalog id is wired as an anchor in components", () => {
test("every settings search catalog id and fallback is wired as an anchor in components", () => {
const roots = [
join(process.cwd(), "components"),
];
@@ -32,7 +32,7 @@ test("every settings search catalog id is wired as an anchor in components", ()
const haystack = sources.map((file) => readFileSync(file, "utf8")).join("\n");
const missing = SETTINGS_SEARCH_CATALOG
.map((entry) => entry.id)
.flatMap((entry) => [entry.id, ...(entry.fallbackAnchorId ? [entry.fallbackAnchorId] : [])])
.filter((id) => {
const asProp = `anchorId="${id}"`;
const asPropSingle = `anchorId='${id}'`;
+22
View File
@@ -36,6 +36,11 @@ export type SettingsPlatform = "mac" | "win" | "linux";
export type SettingsSearchEntry = {
/** Stable id; also used as `data-settings-anchor` on the target element. */
id: string;
/**
* Already-mounted parent to highlight when a prerequisite setting is off and
* this entry's own anchor is not in the DOM.
*/
fallbackAnchorId?: string;
tab: SettingsTabId;
/** Nested AI settings tab when `tab === "ai"`. */
aiSubTab?: AISettingsSubTabId;
@@ -723,6 +728,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-host-info-bar-title-mode",
fallbackAnchorId: "terminal-host-info-bar-show",
tab: "terminal",
labelKey: "settings.terminal.hostInfoBar.titleMode",
descriptionKey: "settings.terminal.hostInfoBar.titleMode.desc",
@@ -737,6 +743,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-server-stats-refresh-interval",
fallbackAnchorId: "terminal-server-stats-show",
tab: "terminal",
labelKey: "settings.terminal.serverStats.refreshInterval",
descriptionKey: "settings.terminal.serverStats.refreshInterval.desc",
@@ -787,6 +794,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-hibernate-hidden-tabs-delay",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernateHiddenTabsDelay",
descriptionKey: "settings.terminal.rendering.hibernateHiddenTabsDelay.desc",
@@ -794,6 +802,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-hibernate-skip-alt-screen",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernateSkipAltScreen",
descriptionKey: "settings.terminal.rendering.hibernateSkipAltScreen.desc",
@@ -801,6 +810,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-hibernate-keep-renderer-count",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernateKeepRendererCount",
descriptionKey: "settings.terminal.rendering.hibernateKeepRendererCount.desc",
@@ -808,6 +818,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-hibernate-replay-chunk-bytes",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernateReplayChunkBytes",
descriptionKey: "settings.terminal.rendering.hibernateReplayChunkBytes.desc",
@@ -815,6 +826,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-hibernate-prefer-wasm-serialize",
fallbackAnchorId: "terminal-hibernate-hidden-tabs",
tab: "terminal",
labelKey: "settings.terminal.rendering.hibernatePreferWasmSerialize",
descriptionKey: "settings.terminal.rendering.hibernatePreferWasmSerialize.desc",
@@ -830,6 +842,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-inline-images-kitty",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.kitty",
descriptionKey: "settings.terminal.inlineImages.kitty.desc",
@@ -837,6 +850,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-inline-images-sixel",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.sixel",
descriptionKey: "settings.terminal.inlineImages.sixel.desc",
@@ -844,6 +858,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-inline-images-iip",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.iip",
descriptionKey: "settings.terminal.inlineImages.iip.desc",
@@ -851,6 +866,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-inline-images-storage-limit",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.storageLimit",
descriptionKey: "settings.terminal.inlineImages.storageLimit.desc",
@@ -858,6 +874,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-inline-images-max-megapixels",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.maxMegapixels",
descriptionKey: "settings.terminal.inlineImages.maxMegapixels.desc",
@@ -865,6 +882,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "terminal-inline-images-sequence-limit",
fallbackAnchorId: "terminal-inline-images-enabled",
tab: "terminal",
labelKey: "settings.terminal.inlineImages.sequenceLimit",
descriptionKey: "settings.terminal.inlineImages.sequenceLimit.desc",
@@ -1190,6 +1208,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "ai-web-search-api-key",
fallbackAnchorId: "ai-web-search-provider",
tab: "ai",
aiSubTab: "search",
labelKey: "ai.webSearch.apiKey",
@@ -1341,6 +1360,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "system-network-proxy-url",
fallbackAnchorId: "system-network-proxy-mode",
tab: "system",
labelKey: "settings.system.networkProxy.url",
descriptionKey: "settings.system.networkProxy.url.desc",
@@ -1348,6 +1368,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "system-network-proxy-bypass",
fallbackAnchorId: "system-network-proxy-mode",
tab: "system",
labelKey: "settings.system.networkProxy.bypass",
descriptionKey: "settings.system.networkProxy.bypass.desc",
@@ -1362,6 +1383,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
},
{
id: "system-app-lock-timeout",
fallbackAnchorId: "system-app-lock",
tab: "system",
labelKey: "settings.appLock.timeout",
descriptionKey: "settings.appLock.timeoutDesc",