Skip to content
TypeScript

fix(mobile): branch naming text saves when you leave the screen (#18381)

Aditya Vardhan Sharma1a9572a4d899
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
new file mode 100644
index 00000000000..df758e3e78a
--- /dev/null
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
@@ -0,0 +1,102 @@
+// @vitest-environment jsdom
+import { DEFAULT_SERVER_SETTINGS, type ServerSettingsPatch } from "@t3tools/contracts";
+import type { ReactNode } from "react";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const { Children, mocks } = vi.hoisted(() => ({
+ Children: ({ children }: { children?: ReactNode }) => children,
+ mocks: {
+ branchNaming: { onChange: (_patch: ServerSettingsPatch) => {} },
+ updateSettings: vi.fn(),
+ },
+}));
+
+vi.mock("react-native", () => ({ View: Children }));
+vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
+vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) }));
+vi.mock("../../state/session", () => ({
+ readEnvironmentScope: () => true,
+ useEnvironmentsWithScope: () => new Set(["local"]),
+}));
+vi.mock("../../state/server", () => ({ serverEnvironment: { updateSettings: {} } }));
+vi.mock("../../state/use-atom-command", () => ({
+ useAtomCommand: () => mocks.updateSettings,
+}));
+vi.mock("../threads/thread-settings-options", () => ({ RUNTIME_MODE_CHOICES: [] }));
+vi.mock("../../components/ScreenScrollView", () => ({ ScreenScrollView: Children }));
+vi.mock("../../components/AppText", () => ({ AppText: Children }));
+vi.mock("./components/SettingsScreen", () => ({ SettingsScreen: Children }));
+vi.mock("./components/SettingsEnvironmentFilterHeader", () => ({
+ AndroidSettingsEnvironmentFilter: () => null,
+ SettingsEnvironmentFilterHeader: () => null,
+}));
+vi.mock("./components/SettingsSection", () => ({ SettingsSection: Children }));
+vi.mock("./components/SettingsChoiceRow", () => ({ SettingsChoiceRow: () => null }));
+vi.mock("./components/SettingsSwitchRow", () => ({ SettingsSwitchRow: () => null }));
+vi.mock("./components/SettingsRow", () => ({ SettingsRow: () => null }));
+vi.mock("./components/SettingsProjectOverridesSection", () => ({
+ SettingsProjectOverridesSection: () => null,
+}));
+vi.mock("./components/BranchNamingSettings", () => ({
+ BranchNamingSettings: (props: { onChange: (patch: ServerSettingsPatch) => void }) => {
+ mocks.branchNaming.onChange = props.onChange;
+ return null;
+ },
+}));
+vi.mock("./settings-environment-filter", () => ({
+ useSettingsEnvironmentFilter: () => ({
+ selectedTargets: [
+ {
+ environmentId: "local",
+ serverConfig: {
+ settings: DEFAULT_SERVER_SETTINGS,
+ environment: { capabilities: { projectSettingsOverrides: true } },
+ },
+ },
+ ],
+ projectGroups: [],
+ selectedProjectKey: null,
+ }),
+}));
+
+import { SettingsEnvironmentSourceControlRouteScreen } from "./SettingsServerControlsRouteScreen";
+
+let root: Root;
+
+beforeEach(() => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ root = createRoot(document.createElement("div"));
+ mocks.updateSettings.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+});
+
+describe("SettingsServerControlsRouteScreen", () => {
+ it("sends a draft saved during a pending write once that write settles", async () => {
+ let settle = () => {};
+ mocks.updateSettings.mockImplementationOnce(
+ () => new Promise<void>((resolve) => (settle = resolve)),
+ );
+ mocks.updateSettings.mockResolvedValue(undefined);
+ act(() => root.render(<SettingsEnvironmentSourceControlRouteScreen />));
+
+ act(() => mocks.branchNaming.onChange({ branchNamingMode: "custom" }));
+ // The branch naming view closes with a draft while the mode write is pending.
+ act(() => mocks.branchNaming.onChange({ branchNameInstructions: "Use issue IDs." }));
+ expect(mocks.updateSettings).toHaveBeenCalledOnce();
+
+ await act(async () => settle());
+
+ expect(mocks.updateSettings).toHaveBeenCalledTimes(2);
+ expect(mocks.updateSettings).toHaveBeenLastCalledWith({
+ environmentId: "local",
+ input: {
+ patch: { branchNamingMode: "custom", branchNameInstructions: "Use issue IDs." },
+ },
+ });
+ });
+});
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
index b444f70054d..8ca4bb410e3 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
@@ -151,6 +151,12 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
);
const [pendingWrites, setPendingWrites] = useState(0);
const writeInFlight = useRef(false);
+ // A closing view can still save its drafts while a write is pending, after
+ // the controls disabled. Those patches run once the current write settles.
+ const queuedPatch = useRef<{ key: string; patch: ServerSettingsPatch } | null>(null);
+ const targetsKey = targets
+ .map((target) => `${target.environment.environmentId}:${target.projectId}`)
+ .join(",");
const [pendingTargets, setPendingTargets] = useState<
readonly ScopedMobileSettingsTarget[] | null
>(null);
@@ -171,8 +177,15 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
reportFailure: true,
});
const write = (patch: ServerSettingsPatch) => {
+ if (writeInFlight.current) {
+ const queued = queuedPatch.current;
+ queuedPatch.current = {
+ key: targetsKey,
+ patch: queued?.key === targetsKey ? { ...queued.patch, ...patch } : patch,
+ };
+ return;
+ }
if (
- writeInFlight.current ||
!hasConnectedSelection ||
!targets.every((target) =>
readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope),
@@ -192,6 +205,11 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
writeInFlight.current = false;
setPendingTargets(null);
setPendingWrites((count) => count - 1);
+ const queued = queuedPatch.current;
+ queuedPatch.current = null;
+ // These targets may not show this write yet, so send it again with the
+ // queued patch; project overrides are replaced whole.
+ if (queued?.key === targetsKey) write({ ...patch, ...queued.patch });
});
};
const clearProjectOverrides = () => {
@@ -213,6 +231,8 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
),
).finally(() => {
writeInFlight.current = false;
+ // Resending a draft over these pre-clear targets would undo the clear.
+ queuedPatch.current = null;
setPendingTargets(null);
setPendingWrites((count) => count - 1);
});
@@ -349,9 +369,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
{props.page === "source-control" ? (
<>
<BranchNamingSettings
- key={targets
- .map((target) => `${target.environment.environmentId}:${target.projectId}`)
- .join(",")}
+ key={targetsKey}
mode={uniform("branchNamingMode")}
prefix={uniform("branchNamePrefix")}
instructions={uniform("branchNameInstructions")}
diff --git a/apps/mobile/src/features/settings/components/BranchNamingSettings.test.tsx b/apps/mobile/src/features/settings/components/BranchNamingSettings.test.tsx
new file mode 100644
index 00000000000..9e158fb58b2
--- /dev/null
+++ b/apps/mobile/src/features/settings/components/BranchNamingSettings.test.tsx
@@ -0,0 +1,167 @@
+// @vitest-environment jsdom
+import type { BranchNamingMode } from "@t3tools/contracts";
+import type { ReactNode } from "react";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+type InputProps = {
+ accessibilityLabel: string;
+ defaultValue: string;
+ onChangeText: (text: string) => void;
+ onEndEditing: (event: { nativeEvent: { text: string } }) => void;
+};
+
+const inputs = vi.hoisted(() => new Map<string, InputProps>());
+
+vi.mock("react-native", () => ({
+ View: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.mock("../../../components/AppText", () => ({
+ AppText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+ AppTextInput: (props: InputProps) => {
+ inputs.set(props.accessibilityLabel, props);
+ return null;
+ },
+}));
+vi.mock("./SettingsChoiceRow", () => ({ SettingsChoiceRow: () => null }));
+vi.mock("./SettingsSection", () => ({
+ SettingsSection: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+import { BranchNamingSettings } from "./BranchNamingSettings";
+
+const PREFIX = "Branch prefix";
+const INSTRUCTIONS = "Branch naming instructions";
+
+let root: Root;
+const onChange = vi.fn();
+
+function render(
+ mode: BranchNamingMode,
+ saved: { prefix?: string; instructions?: string } = {},
+ disabled = false,
+) {
+ act(() =>
+ root.render(
+ <BranchNamingSettings
+ mode={mode}
+ prefix={saved.prefix ?? "t3"}
+ instructions={saved.instructions ?? "Use issue IDs."}
+ disabled={disabled}
+ onChange={onChange}
+ />,
+ ),
+ );
+}
+
+// Android Back hides the keyboard but never ends editing, so leaving the
+// screen is just an unmount with the text still in the field.
+function leaveScreen() {
+ act(() => root.unmount());
+ root = createRoot(document.createElement("div"));
+}
+
+const typed = (text: string) => ({ nativeEvent: { text } });
+
+function input(label: string) {
+ const props = inputs.get(label);
+ if (!props) throw new Error(`${label} input not rendered`);
+ return props;
+}
+
+beforeEach(() => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ root = createRoot(document.createElement("div"));
+ inputs.clear();
+ onChange.mockClear();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+});
+
+describe("BranchNamingSettings", () => {
+ it("saves typed instructions when the screen closes before editing ends", () => {
+ render("custom");
+ act(() => input(INSTRUCTIONS).onChangeText(" Use julius/ prefixes. "));
+ leaveScreen();
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith({
+ branchNameInstructions: "Use julius/ prefixes.",
+ });
+ });
+
+ it("saves typed prefix when the screen closes before editing ends", () => {
+ render("static");
+ act(() => input(PREFIX).onChangeText("feat/"));
+ leaveScreen();
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith({ branchNamePrefix: "feat/" });
+ });
+
+ it.each([
+ { mode: "static", label: PREFIX, key: "prefix", text: "feat/" },
+ { mode: "custom", label: INSTRUCTIONS, key: "instructions", text: "Use julius/ prefixes." },
+ ] as const)("shows the $key typed before Back when the screen reopens", (field) => {
+ render(field.mode);
+ act(() => input(field.label).onChangeText(field.text));
+ leaveScreen();
+
+ const [patch] = onChange.mock.lastCall ?? [];
+ inputs.clear();
+ render(field.mode, {
+ prefix: patch?.branchNamePrefix,
+ instructions: patch?.branchNameInstructions,
+ });
+ expect(input(field.label).defaultValue).toBe(field.text);
+ });
+
+ it("saves both drafts in one patch when the screen closes", () => {
+ render("static");
+ act(() => input(PREFIX).onChangeText("feat/"));
+ render("custom");
+ act(() => input(INSTRUCTIONS).onChangeText("New rules."));
+ leaveScreen();
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith({
+ branchNamePrefix: "feat/",
+ branchNameInstructions: "New rules.",
+ });
+ });
+
+ it("still saves a draft when a pending write disables the field", () => {
+ render("custom");
+ act(() => input(INSTRUCTIONS).onChangeText("New rules."));
+ render("custom", {}, true);
+ leaveScreen();
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith({ branchNameInstructions: "New rules." });
+ });
+
+ it("drops a draft once a newer saved value replaces the field", () => {
+ render("custom");
+ act(() => input(INSTRUCTIONS).onChangeText("Old draft."));
+ render("custom", { instructions: "Saved elsewhere." });
+ leaveScreen();
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("does not save again on close after editing ended", () => {
+ render("custom");
+ act(() => input(INSTRUCTIONS).onChangeText("New rules."));
+ act(() => input(INSTRUCTIONS).onEndEditing(typed("New rules.")));
+ leaveScreen();
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith({ branchNameInstructions: "New rules." });
+ });
+
+ it("does not save unchanged text", () => {
+ render("custom");
+ act(() => input(INSTRUCTIONS).onChangeText("Use issue IDs."));
+ act(() => input(INSTRUCTIONS).onEndEditing(typed("Use issue IDs.")));
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/features/settings/components/BranchNamingSettings.tsx b/apps/mobile/src/features/settings/components/BranchNamingSettings.tsx
index 26f8a3ff16c..f42b499d5f5 100644
--- a/apps/mobile/src/features/settings/components/BranchNamingSettings.tsx
+++ b/apps/mobile/src/features/settings/components/BranchNamingSettings.tsx
@@ -1,5 +1,5 @@
import { BranchNamingMode, type ServerSettingsPatch } from "@t3tools/contracts";
-import { useRef } from "react";
+import { useEffect, useEffectEvent, useRef } from "react";
import { View } from "react-native";
import { AppText as Text, AppTextInput } from "../../../components/ui/AppText";
@@ -25,8 +25,36 @@ export function BranchNamingSettings(props: {
disabled: boolean;
onChange: (patch: ServerSettingsPatch) => void;
}) {
- const prefixEdited = useRef(false);
- const instructionsEdited = useRef(false);
+ // Typed text waits here until it saves. Android's Back closes the keyboard
+ // without ending editing, so leaving the screen saves it too.
+ type Field = "branchNamePrefix" | "branchNameInstructions";
+ const drafts = useRef<Partial<Record<Field, { text: string; over: string | null }>>>({});
+ const savedValue = (field: Field) =>
+ field === "branchNamePrefix" ? props.prefix : props.instructions;
+ const edit = (field: Field, text: string) => {
+ drafts.current[field] = { text, over: savedValue(field) };
+ };
+ // Takes a field's draft as a patch, or {} when there is nothing new to save.
+ // A newer saved value remounts the input, so a draft typed over an older one
+ // is no longer on screen and is dropped.
+ const take = (field: Field): ServerSettingsPatch => {
+ const draft = drafts.current[field];
+ delete drafts.current[field];
+ const saved = savedValue(field);
+ // Not gated on `disabled`: a pending write disables the inputs, and the
+ // route queues this save behind it and checks write access itself.
+ if (draft === undefined || draft.over !== saved) return {};
+ const value = draft.text.trim();
+ return saved === null || value !== saved ? { [field]: value } : {};
+ };
+ const send = (patch: ServerSettingsPatch) => {
+ if (Object.keys(patch).length > 0) props.onChange(patch);
+ };
+ // One patch, because the screen drops writes while another is in flight.
+ const saveDrafts = useEffectEvent(() =>
+ send({ ...take("branchNamePrefix"), ...take("branchNameInstructions") }),
+ );
+ useEffect(() => () => saveDrafts(), []);
return (
<SettingsSection
title="Worktree branch naming"
@@ -53,25 +81,14 @@ export function BranchNamingSettings(props: {
<AppTextInput
key={props.prefix}
accessibilityLabel="Branch prefix"
- onChangeText={() => {
- prefixEdited.current = true;
- }}
+ onChangeText={(text) => edit("branchNamePrefix", text)}
defaultValue={props.prefix ?? ""}
placeholder={props.prefix === null ? "Mixed" : "No prefix"}
editable={!props.disabled}
autoCapitalize="none"
autoCorrect={false}
className="min-h-10 rounded-xl px-3 py-2 text-base text-foreground"
- onEndEditing={(event) => {
- const value = event.nativeEvent.text.trim();
- if (
- !props.disabled &&
- prefixEdited.current &&
- (props.prefix === null || value !== props.prefix)
- )
- props.onChange({ branchNamePrefix: value });
- prefixEdited.current = false;
- }}
+ onEndEditing={() => send(take("branchNamePrefix"))}
/>
</View>
) : null}
@@ -83,9 +100,7 @@ export function BranchNamingSettings(props: {
<AppTextInput
key={props.instructions}
accessibilityLabel="Branch naming instructions"
- onChangeText={() => {
- instructionsEdited.current = true;
- }}
+ onChangeText={(text) => edit("branchNameInstructions", text)}
defaultValue={props.instructions ?? ""}
placeholder={
props.instructions === null
@@ -96,16 +111,7 @@ export function BranchNamingSettings(props: {
multiline
autoCapitalize="sentences"
className="min-h-24 rounded-xl px-3 py-2 text-base text-foreground"
- onEndEditing={(event) => {
- const value = event.nativeEvent.text.trim();
- if (
- !props.disabled &&
- instructionsEdited.current &&
- (props.instructions === null || value !== props.instructions)
- )
- props.onChange({ branchNameInstructions: value });
- instructionsEdited.current = false;
- }}
+ onEndEditing={() => send(take("branchNameInstructions"))}
/>
</View>
) : null}