Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 22c84c59f6 polish(app): smart-fill Direct connection form on paste (#12099)
* feat(app): smart-fill Direct connection form when pasting host:port or URI

Pasting a host:port, bracketed IPv6 address, or direct connection URI into the Direct connection form now splits and populates Host, Port, Use SSL, and Password instead of leaving the raw string in Host or kicking tcp:// URIs out of Form mode.

Unifies address parsing in direct-connection-host.ts so form normalization, URI-to-Form conversion, and smart paste share one parser. Handles web paste events directly when replacing the field (avoiding mid-string paste interference) and detects multi-character paste in onChangeText for native platforms without fighting manual typing or bare IPv6 entry.

* fix(app): preserve typed URI settings, clear password on tcp paste, and track native selection

Addresses review feedback on Direct connection smart-paste:
- Clears any previous host password when pasting a tcp:// URI without ?password=, while still preserving user-entered password on plain host:port or http(s)/ws(s) pastes.
- Resolves explicit scheme, port, ssl, and password from a manually typed URI in Host on Connect and Form-to-URI mode switching instead of dropping query settings.
- Requires decimal digits for ports in buildDirectConnectionUri so non-decimal IPv6 ports like [::1]:0x10 are rejected instead of parsed as hex.
- Tracks onSelectionChange on Host and Port so native platforms accurately distinguish full-field replacements from partial pastes.

* fix(app): commit typed Host URI into form fields on blur, edit, and connect

Eliminates conflicting sources of truth when a user manually types a URI into Host: leaving Host, editing Port/SSL/Password, switching modes, or clicking Connect now commits the parsed URI into the visible form fields so password retries and subsequent edits always control the next connection attempt.

* fix(app): sync Direct connection inputs when SSL toggle or Password commits Host

Routes handleToggleUseTls and handlePasswordChange through syncFormInputs so committing a manually typed URI in Host while Host still has focus (such as tapping Use SSL on native) updates the displayed Host, Port, and Password inputs immediately.

* fix(app): defer Host blur commit when clicking Use SSL checkbox

When clicking Use SSL while Host still holds a typed URI on web, Host blurs before the checkbox press fires. Deferring the blur commit when relatedTarget is the Use SSL toggle lets handleToggleUseTls own the single commit and toggle so clicking an unchecked Use SSL after typing an https:// URL leaves SSL enabled.
2026-12-05 13:13:54 +07:00
Mohamed Boudra d6512537f4 polish(app): unify SegmentedControl with recessed pill track and Direct connection icons (#12089)
* polish(app): unify SegmentedControl with recessed pill track and Direct connection icons

Switch SegmentedControl from a transparent ghost layout to a single recessed surface2 pill track with 2px inset padding and an elevated active thumb across all surfaces. Add surfaceSegmentThumb and borderSegmentThumb semantic theme tokens so Light themes use an elevated surface0 thumb with shadow instead of colliding with surface3/border, while Dark themes (including Pure Black) use surface3 with a subtle highlight border. Replace the two wrap call sites with horizontal scroll containers so pill tracks stay single-row, align column-hosted controls so they hug content, and add Form and Link icons to the Direct connection Form/URI switcher.

* test(app): verify horizontal overflow pills selection in agent controls sheet

* test(app): force vertical overflow and use real wheel input in pills scroll test

* Update plugin directory E2E tab container lookup for horizontal scroll wrapper

* Render Command Center filter tabs as ghost tab pills with bottom breathing room

* Use shared Button and horizontal ScrollView for Command Center tab pills

* Reveal keyboard-selected Command Center filter pills on horizontal overflow
2026-12-05 13:04:13 +07:00
Mohamed Boudra 59afa917b2 polish(app): derive borderFocus token for focused inputs (#12094)
* polish(app): derive borderFocus token for focused inputs

Composer focus previously borrowed surface4 (too bright in Default Dark, compressed in Pure Black), while SearchField and MenuTextField focused to borderAccent (fading lighter than border in Light mode). Deriving borderFocus at 1.30x contrast from borderAccent toward foreground keeps focus borders consistent across built-in and plugin themes while leaving surface4 to UsageMeter.

* fix(app): composite translucent plugin borders before deriving borderFocus

* fix(app): preserve translucency when deriving borderFocus from translucent borders

* fix(app): start opaque borderFocus step from closest surface to foreground
2026-12-05 12:58:03 +07:00
29 changed files with 1931 additions and 184 deletions
+2 -2
View File
@@ -78,7 +78,7 @@ In the composer, the first glyph's ink starts on the text column's edge, and the
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or touch is the primary input. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The primary input comes from `(pointer: coarse)` (`hasTouchPrimaryPointer` in `hooks/pointer-capabilities.ts`), not from whether a touch screen exists: WebKit keeps touch primary on an iPad with a trackpad attached, and Chromium reports a fine primary pointer for a laptop with a touch screen that its trackpad drives. The fact is read once at startup: attaching a pointer to a tablet does not shrink its controls, and a 2-in-1 launched with a pointer keeps pointer sizes after it switches to tablet mode until the app reloads. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it takes presses over its size's control height without adding that height to its row. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it takes presses over its size's control height without adding that height to its row. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. `<SegmentedControl>` sits in a recessed `surface2` pill track with an elevated active thumb (`surface3` on dark themes, `surface0` with a subtle shadow on light themes) and `foreground` text, never an inverted fill inside thin chrome. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
A `<Pressable>` wrapping a `<Text>` is a sixth variant. It is wrong. `<Button>` accepts `style`, `textStyle`, `leftIcon`, `disabled`, `size`, and `variant`.
@@ -96,7 +96,7 @@ A list that is itself the page content — sidebar items in `sidebar-workspace-l
Pane chrome — the workspace pane header, the file-explorer header, the diff pane header — uses a single bottom border to separate the header from the content (`packages/app/src/components/git-diff-pane.tsx:2328-2331`). One border, no shadow.
`borderAccent` is reserved for the outline button. Inputs use `border`. Single-thing borders are wrong; a single bordered element is either a card with one row (use the card) or it does not need a border.
`borderAccent` is reserved for the outline button and resting frames like the composer. Inputs rest at `border` and step to `borderFocus` on focus. Single-thing borders are wrong; a single bordered element is either a card with one row (use the card) or it does not need a border.
---
@@ -173,6 +173,29 @@ test("command center tabs rotate with Tab and never move the header", async ({ p
await expectCommandCenterTabs(panel, ["All", "Workspaces", "Files", "Actions"]);
});
await test.step("overflowing filter tabs scroll into view on narrow viewports", async () => {
const originalViewport = page.viewportSize() ?? { width: 1280, height: 720 };
await page.setViewportSize({ width: 280, height: 640 });
try {
const tabsBar = panel.getByTestId("command-center-tabs");
const metrics = await tabsBar.evaluate((el) => ({
scrollWidth: el.scrollWidth,
clientWidth: el.clientWidth,
}));
expect(metrics.scrollWidth).toBeGreaterThan(metrics.clientWidth);
await page.keyboard.press("Shift+Tab");
await expectCommandCenterTab(panel, "Actions");
const actionsTab = panel.getByTestId("command-center-tab-actions");
await expect(actionsTab).toBeInViewport({ ratio: 1 });
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "All");
const scrollLeft = await tabsBar.evaluate((el) => el.scrollLeft);
expect(scrollLeft).toBe(0);
} finally {
await page.setViewportSize(originalViewport);
}
});
await test.step("outside a workspace there is no Files tab, and Tab skips it", async () => {
const outside = { workspaceOpen: false };
await closeCommandCenter(page);
@@ -248,10 +248,10 @@ async function readSettledFrameBorder(page: Page): Promise<string> {
});
}
// `borderAccent` at rest, `surface4` while focused: greys in both themes, never the accent.
// `borderAccent` at rest, `borderFocus` while focused: greys in both themes, never the accent.
const FRAME_BORDERS = {
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(89, 91, 91)" },
light: { rest: "rgb(236, 236, 241)", focus: "rgb(212, 212, 216)" },
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(66, 70, 69)" },
light: { rest: "rgb(236, 236, 241)", focus: "rgb(208, 208, 213)" },
} as const;
for (const colorScheme of ["dark", "light"] as const) {
@@ -41,6 +41,9 @@ import {
connectDirectHost,
connectDirectHostExpectingPassword,
pasteIntoDirectHost,
pasteClipboardIntoDirectField,
pasteIntoMiddleOfDirectHost,
typeDirectHostCharacters,
fillDirectHostPromptPassword,
openCompactSettings,
expectCompactSettingsList,
@@ -56,6 +59,7 @@ import {
fillDirectHostUri,
expectDirectHostFormValues,
expectDirectHostSslEnabled,
expectDirectHostSslDisabled,
fillDirectHostAddress,
toggleDirectHostSsl,
expectDirectHostUriValue,
@@ -373,6 +377,110 @@ test.describe("Settings sidebar navigation", () => {
});
});
test("direct connection form smart-fills on paste without disrupting manual typing", async ({
page,
}) => {
await gotoAppShell(page);
await openSettings(page);
await openAddHostFlow(page);
await selectHostConnectionType(page, "direct");
await expectDirectConnectionMode(page, "Form");
await test.step("pasting localhost:port splits Host and Port", async () => {
await pasteClipboardIntoDirectField(page, "Host", "localhost:6768");
await expectDirectHostFormValues(page, { host: "localhost", port: "6768", password: "" });
await expectDirectHostSslDisabled(page);
});
await test.step("pasting an https URI populates Host, Port, and Use SSL", async () => {
await pasteClipboardIntoDirectField(page, "Host", "https://myhost.ts.net:7443/");
await expectDirectHostFormValues(page, { host: "myhost.ts.net", port: "7443", password: "" });
await expectDirectHostSslEnabled(page);
});
await test.step("pasting a full Paseo URI populates Host, Port, Use SSL, and Password", async () => {
await pasteClipboardIntoDirectField(
page,
"Host",
"tcp://100.91.42.18:6769?ssl=false&password=my%20secret",
);
await expectDirectHostFormValues(page, {
host: "100.91.42.18",
port: "6769",
password: "my secret",
});
await expectDirectHostSslDisabled(page);
});
await test.step("pasting https without a port defaults Port to 443", async () => {
await pasteClipboardIntoDirectField(page, "Host", "https://tunnel.example.test");
await expectDirectHostFormValues(page, {
host: "tunnel.example.test",
port: "443",
password: "my secret",
});
await expectDirectHostSslEnabled(page);
});
await test.step("typing bare IPv6 and pasting into the middle of Host stay literal", async () => {
await typeDirectHostCharacters(page, "2001:1234::1");
await expectDirectHostFormValues(page, {
host: "2001:1234::1",
port: "443",
password: "my secret",
});
await pasteIntoMiddleOfDirectHost(page, "example.com", 2, "sub:9000");
await expectDirectHostFormValues(page, {
host: "exsub:9000ample.com",
port: "443",
password: "my secret",
});
});
await test.step("pasting a tcp URI without password clears a previous host password", async () => {
await pasteClipboardIntoDirectField(page, "Host", "tcp://second.example.test:7443");
await expectDirectHostFormValues(page, {
host: "second.example.test",
port: "7443",
password: "",
});
await expectDirectHostSslDisabled(page);
});
await test.step("clicking Use SSL after typing an https URL keeps SSL enabled", async () => {
await expectDirectHostSslDisabled(page);
await typeDirectHostCharacters(page, "https://typed.example.test:7443");
await toggleDirectHostSsl(page);
await expectDirectHostFormValues(page, {
host: "typed.example.test",
port: "7443",
password: "",
});
await expectDirectHostSslEnabled(page);
});
await test.step("pasting a host:port into Port fills Host and Port", async () => {
await pasteClipboardIntoDirectField(page, "Port", "hetzner.tail8a2f.ts.net:6768");
await expectDirectHostFormValues(page, {
host: "hetzner.tail8a2f.ts.net",
port: "6768",
password: "",
});
});
await test.step("pasting a live daemon address connects cleanly", async () => {
await pasteClipboardIntoDirectField(page, "Host", `http://127.0.0.1:${getE2EDaemonPort()}/`);
await expectDirectHostFormValues(page, {
host: "127.0.0.1",
port: String(getE2EDaemonPort()),
password: "",
});
await expectDirectHostSslDisabled(page);
await connectDirectHost(page);
});
});
test("direct connection connects to a URI with Host blank", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
@@ -500,12 +500,11 @@ async function sampleFramesDuring(
}
return match;
};
const findOverviewCard = (tabsEl: Element | null, stacked: boolean): Element | null => {
const findOverviewCard = (tabsEl: Element | null): Element | null => {
if (!tabsEl) return null;
const container = stacked
? (tabsEl.closest('[style*="overflow"]')?.parentElement ??
tabsEl.parentElement?.parentElement?.parentElement)
: tabsEl.parentElement?.parentElement;
const container =
tabsEl.closest('[style*="overflow"]')?.parentElement ??
tabsEl.parentElement?.parentElement?.parentElement;
if (!container) return null;
const visibleChildren = Array.from(container.children).filter(isVisible);
return visibleChildren[visibleChildren.length - 1] ?? null;
@@ -519,7 +518,7 @@ async function sampleFramesDuring(
const skeletonEl = queryVisible('[data-testid="plugin-overview-skeleton"]');
const licenseRect = roundRect(findVisibleText("License"));
const relatedRect = roundRect(findVisibleText("Related plugins"));
const overviewCard = findOverviewCard(tabsEl, stacked);
const overviewCard = findOverviewCard(tabsEl);
const overviewRect = roundRect(overviewCard);
samples.push({
@@ -455,6 +455,46 @@ export async function pasteIntoDirectHost(page: Page, text: string): Promise<voi
await page.getByRole("textbox", { name: "Host", exact: true }).fill(text);
}
export async function pasteClipboardIntoDirectField(
page: Page,
field: "Host" | "Port",
text: string,
options?: { replace?: boolean },
): Promise<void> {
const input = page.getByRole("textbox", { name: field, exact: true });
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.evaluate((value) => navigator.clipboard.writeText(value), text);
await input.click();
if (options?.replace ?? true) {
await page.keyboard.press("ControlOrMeta+a");
}
await page.keyboard.press("ControlOrMeta+v");
}
export async function typeDirectHostCharacters(page: Page, text: string): Promise<void> {
const input = page.getByRole("textbox", { name: "Host", exact: true });
await input.click();
await page.keyboard.press("ControlOrMeta+a");
await page.keyboard.press("Backspace");
await input.pressSequentially(text);
}
export async function pasteIntoMiddleOfDirectHost(
page: Page,
initialHost: string,
offset: number,
pastedText: string,
): Promise<void> {
await typeDirectHostCharacters(page, initialHost);
await page.keyboard.press("Home");
for (let index = 0; index < offset; index += 1) {
await page.keyboard.press("ArrowRight");
}
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.evaluate((value) => navigator.clipboard.writeText(value), pastedText);
await page.keyboard.press("ControlOrMeta+v");
}
export async function toggleDirectHostSsl(page: Page): Promise<void> {
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
}
@@ -111,6 +111,7 @@ function ThinkingField({
value={state.thinkingOptionId || null}
onValueChange={onSegmentChange}
size={controlSize}
style={styles.thinkingControl}
testID="agent-profile-thinking-trigger"
/>
</Field>
@@ -574,6 +575,9 @@ const styles = StyleSheet.create((theme) => ({
padding: theme.spacing[4],
gap: theme.spacing[4],
},
thinkingControl: {
alignSelf: "flex-start",
},
featureCardPending: {
opacity: theme.opacity[50],
},
@@ -12,6 +12,7 @@ import {
type NativeScrollEvent,
type NativeSyntheticEvent,
type PressableStateCallbackType,
type ScrollView as NativeScrollView,
} from "react-native";
import {
memo,
@@ -33,7 +34,7 @@ import { ArchivedBadge } from "@/components/archived-badge";
import { StatusIcon } from "@/components/status-icon";
import { useWorkspaceStatus } from "@/workspace-status";
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import type { Theme } from "@/styles/theme";
import { SPACING, type Theme } from "@/styles/theme";
import { HighlightedText, type HighlightedTextProps } from "@/components/ui/highlighted-text";
import { findHighlightRanges } from "@/components/ui/highlighted-text-segments";
import { MaterialFileIcon } from "@/components/material-file-icon";
@@ -44,7 +45,9 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { Button } from "@/components/ui/button";
import { getScrollOffsetToRevealItem } from "@/components/ui/scroll-reveal";
import { ScrollView } from "@/components/ui/scroll-view";
import { Shortcut } from "@/components/ui/shortcut";
import {
IsolatedBottomSheetModal,
@@ -1025,7 +1028,7 @@ export function CommandCenter() {
onKeyDown: handleOverlayKeyDown,
});
const tabOptions = useMemo<SegmentedControlOption<CommandCenterTab>[]>(
const tabOptions = useMemo<CommandCenterTabOption[]>(
() =>
state.tabs.map((tab) => ({
value: tab,
@@ -1035,13 +1038,7 @@ export function CommandCenter() {
[state.tabs, t],
);
const tabs = (
<SegmentedControl
options={tabOptions}
value={state.tab}
onValueChange={state.selectTab}
size="sm"
testID="command-center-tabs"
/>
<CommandCenterTabPills options={tabOptions} value={state.tab} onValueChange={state.selectTab} />
);
const placeholder = t(placeholderKey(state.tab, state.tabs));
@@ -1128,6 +1125,136 @@ export function CommandCenter() {
);
}
interface CommandCenterTabOption {
value: CommandCenterTab;
label: string;
testID: string;
}
function CommandCenterTabPill({
option,
selected,
onSelect,
onLayoutPill,
}: {
option: CommandCenterTabOption;
selected: boolean;
onSelect(tab: CommandCenterTab): void;
onLayoutPill(tab: CommandCenterTab, event: LayoutChangeEvent): void;
}) {
const handlePress = useCallback(() => {
if (!selected) onSelect(option.value);
}, [onSelect, option.value, selected]);
const handleLayout = useCallback(
(event: LayoutChangeEvent) => onLayoutPill(option.value, event),
[onLayoutPill, option.value],
);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
return (
<Button
variant={selected ? "secondary" : "ghost"}
size="sm"
numberOfLines={1}
accessibilityState={accessibilityState}
aria-selected={selected}
testID={option.testID}
onPress={handlePress}
onLayout={handleLayout}
style={styles.tabPill}
>
{option.label}
</Button>
);
}
function CommandCenterTabPills({
options,
value,
onValueChange,
}: {
options: readonly CommandCenterTabOption[];
value: CommandCenterTab;
onValueChange(tab: CommandCenterTab): void;
}) {
const scrollRef = useRef<NativeScrollView>(null);
const viewportWidthRef = useRef(0);
const scrollOffsetRef = useRef(0);
const pillLayoutsRef = useRef<Partial<Record<CommandCenterTab, { x: number; width: number }>>>(
{},
);
const revealTab = useCallback((tab: CommandCenterTab) => {
const layout = pillLayoutsRef.current[tab];
const scroll = scrollRef.current;
const viewportWidth = viewportWidthRef.current;
if (!layout || !scroll || viewportWidth <= 0) return;
const edgeMargin = SPACING[4];
const nextOffset = getScrollOffsetToRevealItem({
currentOffset: scrollOffsetRef.current,
viewportHeight: Math.floor(viewportWidth),
itemTop: Math.max(0, Math.floor(layout.x) - edgeMargin),
itemHeight: Math.ceil(layout.width) + edgeMargin * 2,
});
const clampedOffset = Math.ceil(nextOffset);
if (Math.abs(clampedOffset - scrollOffsetRef.current) < 1) return;
scrollOffsetRef.current = clampedOffset;
scroll.scrollTo({ x: clampedOffset, animated: false });
}, []);
useEffect(() => {
revealTab(value);
}, [revealTab, value]);
const handleViewportLayout = useCallback(
(event: LayoutChangeEvent) => {
viewportWidthRef.current = event.nativeEvent.layout.width;
revealTab(value);
},
[revealTab, value],
);
const handlePillLayout = useCallback(
(tab: CommandCenterTab, event: LayoutChangeEvent) => {
const { x, width } = event.nativeEvent.layout;
pillLayoutsRef.current[tab] = { x, width };
if (tab === value) {
revealTab(tab);
}
},
[revealTab, value],
);
const handleScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
scrollOffsetRef.current = event.nativeEvent.contentOffset.x;
}, []);
return (
<ScrollView
ref={scrollRef}
horizontal
showsHorizontalScrollIndicator={false}
keyboardShouldPersistTaps={KEYBOARD_SHOULD_PERSIST_TAPS}
scrollEventThrottle={16}
onLayout={handleViewportLayout}
onScroll={handleScroll}
style={styles.tabScroll}
testID="command-center-tabs"
>
<View style={styles.tabList}>
{options.map((option) => (
<CommandCenterTabPill
key={option.value}
option={option}
selected={option.value === value}
onSelect={onValueChange}
onLayoutPill={handlePillLayout}
/>
))}
</View>
</ScrollView>
);
}
function FileSearchLoadingIndicator({ loading, label }: { loading: boolean; label: string }) {
return (
<View style={styles.fileSearchStatus} testID="command-center-file-search-status">
@@ -1170,12 +1297,25 @@ const styles = StyleSheet.create((theme) => ({
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
// Below the divider, above the list. The first section label brings its own top gap, so the
// pills sit with equal space above and below. A fixed bar, so switching tabs never moves the
// field or the list.
// Below the divider, above the list. Adds subtle bottom room so pills never sit glued onto
// the first row or section header while keeping the bar fixed across tab switches.
tabBar: {
paddingHorizontal: theme.spacing[4],
paddingTop: COMMAND_CENTER_SECTION_GAP,
paddingBottom: theme.spacing[3],
},
tabScroll: {
flexGrow: 0,
flexShrink: 0,
},
tabList: {
flexDirection: "row",
alignItems: "center",
flexShrink: 0,
gap: theme.spacing[1],
paddingHorizontal: theme.spacing[4],
},
tabPill: {
flexShrink: 0,
},
input: {
fontSize: theme.fontSize.base,
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
import { buildDirectConnectionUri, normalizeDirectConnectionHost } from "./direct-connection-host";
import {
buildDirectConnectionUri,
normalizeDirectConnectionHost,
parseDirectConnectionPaste,
} from "./direct-connection-host";
const labels = {
hostRequired: "host required",
@@ -57,6 +61,26 @@ describe("buildDirectConnectionUri", () => {
).toBe("tcp://example.test:443?ssl=true&password=secret");
});
it("honors scheme, ssl, and password from a typed URI in Host", () => {
expect(
buildDirectConnectionUri(
{
host: "tcp://secure.example.test:7443?ssl=true&password=example",
port: "6767",
useTls: false,
password: "",
},
labels,
),
).toBe("tcp://secure.example.test:7443?ssl=true&password=example");
expect(
buildDirectConnectionUri(
{ host: "https://myhost.ts.net", port: "6767", useTls: false, password: "" },
labels,
),
).toBe("tcp://myhost.ts.net:443?ssl=true");
});
it.each(["", " ", "tcp://", "http:///path"])("requires a host for %j", (host) => {
expect(() => buildUri(host)).toThrow("host required");
});
@@ -64,5 +88,102 @@ describe("buildDirectConnectionUri", () => {
it("rejects an invalid port", () => {
expect(() => buildUri("100.66.69.36", "70000")).toThrow("invalid port");
expect(() => buildUri("100.66.69.36:0")).toThrow("invalid port");
expect(() => buildUri("[::1]:0x10")).toThrow("invalid port");
expect(() => buildUri("100.66.69.36", "0x10")).toThrow("invalid port");
});
});
describe("parseDirectConnectionPaste", () => {
it.each([
["localhost:6768", { host: "localhost", port: "6768" }],
[" localhost:6768\n", { host: "localhost", port: "6768" }],
["100.91.42.18:6767", { host: "100.91.42.18", port: "6767" }],
["hetzner.tail8a2f.ts.net:6768", { host: "hetzner.tail8a2f.ts.net", port: "6768" }],
["localhost:6768/", { host: "localhost", port: "6768" }],
["localhost:6768/ws", { host: "localhost", port: "6768" }],
["[::1]:6768", { host: "::1", port: "6768" }],
["[fe80::1]:7000/", { host: "fe80::1", port: "7000" }],
["[::1]", { host: "::1" }],
["localhost/", { host: "localhost" }],
["http://localhost:6768", { host: "localhost", port: "6768", useTls: false }],
["http://localhost:6768/", { host: "localhost", port: "6768", useTls: false }],
["http://myhost.ts.net", { host: "myhost.ts.net", port: "80", useTls: false }],
["https://myhost.ts.net:6767", { host: "myhost.ts.net", port: "6767", useTls: true }],
["https://myhost.ts.net:6767/", { host: "myhost.ts.net", port: "6767", useTls: true }],
["HTTPS://MyHost.ts.net", { host: "MyHost.ts.net", port: "443", useTls: true }],
["https://myhost.ts.net/", { host: "myhost.ts.net", port: "443", useTls: true }],
["ws://localhost:6768/ws", { host: "localhost", port: "6768", useTls: false }],
["ws://myhost.ts.net/ws", { host: "myhost.ts.net", port: "80", useTls: false }],
["wss://myhost.ts.net:6767/ws", { host: "myhost.ts.net", port: "6767", useTls: true }],
["wss://myhost.ts.net/ws", { host: "myhost.ts.net", port: "443", useTls: true }],
["wss://[2001:db8::1]:7443/ws", { host: "2001:db8::1", port: "7443", useTls: true }],
["tcp://localhost:6768", { host: "localhost", port: "6768", useTls: false, password: "" }],
[
"tcp://myhost.ts.net:6767?ssl=true",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "" },
],
[
"tcp://myhost.ts.net:6767?ssl=true&password=a%26b%3Dc+d",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "a&b=c d" },
],
[
"tcp://[::1]:7000?ssl=true&password=secret",
{ host: "::1", port: "7000", useTls: true, password: "secret" },
],
["tcp://myhost.ts.net", { host: "myhost.ts.net", useTls: false, password: "" }],
["tcp://myhost.ts.net?ssl=true", { host: "myhost.ts.net", useTls: true, password: "" }],
[
"https://myhost.ts.net:6767?password=pw",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "pw" },
],
[
"https://:my%20pass@myhost.ts.net:6767",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "my pass" },
],
[
"localhost:6768?ssl=true&password=pw",
{ host: "localhost", port: "6768", useTls: true, password: "pw" },
],
])("extracts fields from %j", (input, expected) => {
expect(parseDirectConnectionPaste(input)).toEqual(expected);
});
it.each([
"",
" ",
"localhost",
"100.91.42.18",
"::1",
"fe80::1",
"2001:db8::1",
"localhost:0",
"localhost:65536",
"localhost:70000",
"localhost:abc",
"localhost:",
"http://localhost:0",
"http://localhost:70000",
"http://localhost:abc",
"http://localhost:",
"tcp://localhost:abc",
"http://",
"https://",
"tcp://",
"http:///path",
":6768",
"[]:6768",
"ftp://example.com:21",
"ssh://user@host:22",
"fe80:abcd",
"my host:6768",
"line1\nlocalhost:6768",
"getpaseo/paseo",
"alice@example.com",
"alice@example.com/",
"relay://relay.paseo.test:443/srv_abc?key=k",
"https://app.paseo.sh/#connect=abc",
"https://app.paseo.sh/#offer=abc",
])("returns null for %j", (input) => {
expect(parseDirectConnectionPaste(input)).toBeNull();
});
});
@@ -19,52 +19,297 @@ export interface NormalizedDirectConnectionHost {
isIpv6: boolean;
}
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(\d*))?$/;
const HOST_WITH_PORT_PATTERN = /^([^:]+):(\d+)$/;
export interface ParsedDirectConnectionAddress {
/** Lowercased scheme without `://`, if present (e.g. "tcp", "http", "https", "ws", "wss"). */
scheme: string | null;
host: string;
/** Explicit port text after `:`, if present (`""` when a trailing `:` had no port). */
port: string | null;
isIpv6: boolean;
/** Path suffix starting with `/`, or empty string when omitted. */
path: string;
/** Password from `?password=` (or URL userinfo when query password is absent), if present. */
password: string | null;
/** Explicit `ssl` query flag (`"true"` / `"false"`), or null when omitted. */
sslParam: boolean | null;
}
export interface DirectConnectionPasteFields {
host: string;
port?: string;
useTls?: boolean;
password?: string;
}
const SCHEME_PATTERN = /^([a-z][a-z0-9+.-]*):\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(.*))?$/;
const DIGITS_ONLY_PATTERN = /^\d+$/;
const DIRECT_CONNECTION_SCHEMES = new Set(["tcp", "http", "https", "ws", "wss"]);
export function defaultPortForDirectScheme(scheme: string | null): string | null {
if (scheme === "https" || scheme === "wss") return "443";
if (scheme === "http" || scheme === "ws") return "80";
return null;
}
export function resolveDirectSchemeTls(
scheme: string | null,
sslParam: boolean | null,
): boolean | undefined {
if (scheme === "https" || scheme === "wss") return true;
if (scheme === "http" || scheme === "ws") return false;
if (scheme === "tcp") return sslParam === true;
return sslParam ?? undefined;
}
function decodeUserinfoComponent(value: string): string {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function parseSslParam(value: string | null): boolean | null {
if (value === "true") return true;
if (value === "false") return false;
return null;
}
function parseValidPortNumber(raw: string): number | null {
if (!DIGITS_ONLY_PATTERN.test(raw)) return null;
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
return port;
}
function parseValidPort(raw: string): string | null {
const port = parseValidPortNumber(raw);
return port === null ? null : String(port);
}
function stripUserinfo(
authority: string,
hasScheme: boolean,
): { authority: string; password: string | null } {
const atIndex = hasScheme ? authority.lastIndexOf("@") : -1;
if (atIndex === -1) return { authority, password: null };
const userinfo = authority.slice(0, atIndex);
const hostPort = authority.slice(atIndex + 1);
const colonIndex = userinfo.indexOf(":");
if (colonIndex === -1) return { authority: hostPort, password: null };
const decoded = decodeUserinfoComponent(userinfo.slice(colonIndex + 1));
return { authority: hostPort, password: decoded || null };
}
function splitAuthorityHostPort(authority: string): {
host: string;
port: string | null;
isIpv6: boolean;
} {
const bracketed = BRACKETED_IPV6_PATTERN.exec(authority);
if (bracketed) {
return {
host: bracketed[1] ?? "",
port: bracketed[2] ?? null,
isIpv6: true,
};
}
const parts = authority.split(":");
if (parts.length === 2) {
return { host: parts[0] ?? "", port: parts[1] ?? "", isIpv6: false };
}
return { host: authority, port: null, isIpv6: parts.length > 2 };
}
function hasInvalidPasteHost(host: string): boolean {
return !host || /[\s[\]@]/.test(host);
}
function resolvePastePort(address: ParsedDirectConnectionAddress): string | null | undefined {
if (address.port !== null) return parseValidPort(address.port);
return defaultPortForDirectScheme(address.scheme) ?? undefined;
}
/**
* Lenient split of a direct-connection address or URI into host, port, scheme, and credentials.
* Keeps invalid port text intact so callers can decide whether to carry it as text or reject it.
*/
export function parseDirectConnectionAddress(input: string): ParsedDirectConnectionAddress {
const trimmed = input.trim();
if (!trimmed) {
return {
scheme: null,
host: "",
port: null,
isIpv6: false,
path: "",
password: null,
sslParam: null,
};
}
const schemeMatch = SCHEME_PATTERN.exec(trimmed);
const scheme = schemeMatch ? (schemeMatch[1] ?? "").toLowerCase() : null;
const rest = schemeMatch ? trimmed.slice(schemeMatch[0].length) : trimmed;
const hashIndex = rest.indexOf("#");
const beforeHash = hashIndex === -1 ? rest : rest.slice(0, hashIndex);
const queryIndex = beforeHash.indexOf("?");
const beforeQuery = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
const query = new URLSearchParams(queryIndex === -1 ? "" : beforeHash.slice(queryIndex + 1));
const slashIndex = beforeQuery.indexOf("/");
const rawAuthority = slashIndex === -1 ? beforeQuery : beforeQuery.slice(0, slashIndex);
const path = slashIndex === -1 ? "" : beforeQuery.slice(slashIndex);
const { authority, password: userinfoPassword } = stripUserinfo(rawAuthority, scheme !== null);
const { host, port, isIpv6 } = splitAuthorityHostPort(authority);
return {
scheme,
host,
port,
isIpv6,
path,
password: query.get("password") || userinfoPassword || null,
sslParam: parseSslParam(query.get("ssl")),
};
}
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
export function isPairingLink(input: string): boolean {
const trimmed = input.trim();
return (
trimmed.toLowerCase().startsWith("relay://") ||
trimmed.includes("#connect=") ||
trimmed.includes("#offer=")
);
}
function shouldNormalizeBareHostPaste(
trimmed: string,
address: ParsedDirectConnectionAddress,
): boolean {
const hasOnlyTrailingSlashes = address.path.length > 0 && /^\/+$/.test(address.path);
if (address.path.length > 0 && !hasOnlyTrailingSlashes) return false;
return hasOnlyTrailingSlashes || (address.isIpv6 && trimmed.startsWith("["));
}
/**
* Extracts structured Direct connection form fields from a pasted `host:port`, bracketed IPv6,
* or supported URI (`http`, `https`, `ws`, `wss`, `tcp`). Returns `null` when the text is a plain
* host, bare IPv6, pairing link, unsupported scheme, or contains an invalid explicit port.
*/
export function parseDirectConnectionPaste(input: string): DirectConnectionPasteFields | null {
const trimmed = input.trim();
if (!trimmed || /[\r\n]/.test(trimmed) || isPairingLink(trimmed)) return null;
const address = parseDirectConnectionAddress(trimmed);
if (address.scheme !== null && !DIRECT_CONNECTION_SCHEMES.has(address.scheme)) return null;
if (hasInvalidPasteHost(address.host)) return null;
const port = resolvePastePort(address);
if (port === null) return null;
const useTls = resolveDirectSchemeTls(address.scheme, address.sslParam);
// A pasted `tcp://` URI is a complete Paseo connection string: omitting `?password=` means no
// password and clears any credential left over from a previous host.
const password =
address.scheme === "tcp" ? (address.password ?? "") : (address.password ?? undefined);
if (
port === undefined &&
useTls === undefined &&
password === undefined &&
!shouldNormalizeBareHostPaste(trimmed, address)
) {
return null;
}
return {
host: address.host,
...(port !== undefined ? { port } : {}),
...(useTls !== undefined ? { useTls } : {}),
...(password !== undefined ? { password } : {}),
};
}
export interface ResolvedDirectHostDraft {
host: string;
port: string;
isIpv6: boolean;
useTls: boolean;
password: string;
}
/**
* Resolves a Form draft where Host may still contain a manually typed `host:port` or URI.
* Honors explicit scheme, port, `ssl`, and `password` settings from Host while preserving
* separate form fields for anything Host did not specify.
*/
export function resolveDirectHostDraft(draft: DirectConnectionHostInput): ResolvedDirectHostDraft {
const address = parseDirectConnectionAddress(draft.host);
const explicitPort = address.port !== null && address.port.length > 0 ? address.port : null;
const port = (explicitPort ?? defaultPortForDirectScheme(address.scheme) ?? draft.port).trim();
let useTls = draft.useTls;
if (address.scheme === "https" || address.scheme === "wss") {
useTls = true;
} else if (address.scheme === "http" || address.scheme === "ws") {
useTls = false;
} else if (address.sslParam !== null) {
useTls = address.sslParam;
}
return {
host: address.host,
port,
isIpv6: address.isIpv6,
useTls,
password: address.password ?? draft.password,
};
}
/**
* Users often paste `host:port` or a full URL into the host field.
* Reduce it to a bare host (plus an optional port) before building the URI.
*/
export function normalizeDirectConnectionHost(input: string): NormalizedDirectConnectionHost {
let host = input.trim().replace(SCHEME_PATTERN, "");
const suffixIndex = host.search(/[/?#]/);
if (suffixIndex !== -1) {
host = host.slice(0, suffixIndex);
const address = parseDirectConnectionAddress(input);
if (address.port !== null && !DIGITS_ONLY_PATTERN.test(address.port)) {
if (address.isIpv6 && address.port === "") {
return { host: address.host, port: null, isIpv6: true };
}
if (!address.isIpv6) {
return { host: `${address.host}:${address.port}`, port: null, isIpv6: false };
}
}
const bracketed = BRACKETED_IPV6_PATTERN.exec(host);
if (bracketed) {
return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true };
}
const hostWithPort = HOST_WITH_PORT_PATTERN.exec(host);
if (hostWithPort) {
return { host: hostWithPort[1] ?? "", port: hostWithPort[2] ?? null, isIpv6: false };
}
return { host, port: null, isIpv6: host.split(":").length > 2 };
return {
host: address.host,
port: address.port || null,
isIpv6: address.isIpv6,
};
}
export function buildDirectConnectionUri(
draft: DirectConnectionHostInput,
labels: DirectConnectionHostLabels,
): string {
const normalized = normalizeDirectConnectionHost(draft.host);
const port = Number((normalized.port ?? draft.port).trim());
if (!normalized.host) {
const resolved = resolveDirectHostDraft(draft);
if (!resolved.host) {
throw new Error(labels.hostRequired);
}
if (!Number.isInteger(port) || port < 1 || port > 65535) {
const port = parseValidPortNumber(resolved.port);
if (port === null) {
throw new Error(labels.invalidPort);
}
return serializeConnectionUriForStorage({
host: normalized.host,
host: resolved.host,
port,
isIpv6: normalized.isIpv6,
useTls: draft.useTls,
...(draft.password ? { password: draft.password } : {}),
isIpv6: resolved.isIpv6,
useTls: resolved.useTls,
...(resolved.password ? { password: resolved.password } : {}),
});
}
@@ -251,11 +251,15 @@ describe("control geometry", () => {
}
});
it("keeps segmented controls ghost with button-radius segments in a button-sized track", () => {
it("keeps segmented controls in an inset pill track sized to match buttons", () => {
const geometry = createControlGeometry(theme);
expect(geometry.segmentedContainerSm.padding).toBe(0);
expect(geometry.segmentedContainerMd.padding).toBe(0);
expect(geometry.segmentedContainerSm.padding).toBe(2);
expect(geometry.segmentedContainerMd.padding).toBe(2);
expect(geometry.segmentedContainerSm.gap).toBe(2);
expect(geometry.segmentedContainerMd.gap).toBe(2);
expect(geometry.segmentedContainerSm.borderRadius).toBe(geometry.buttonSm.borderRadius);
expect(geometry.segmentedContainerMd.borderRadius).toBe(geometry.buttonMd.borderRadius);
expect(geometry.segmentedSegmentSm.borderRadius).toBe(geometry.buttonSm.borderRadius);
expect(geometry.segmentedSegmentMd.borderRadius).toBe(geometry.buttonMd.borderRadius);
expect(geometry.segmentedContainerSm.minHeight).toEqual(geometry.buttonSm.minHeight);
@@ -462,11 +462,15 @@ export function createControlGeometry(theme: Theme) {
},
segmentedContainerSm: {
minHeight: CONTROL_HEIGHTS.sm,
padding: 0,
padding: SEGMENTED_INSET,
gap: SEGMENTED_INSET,
borderRadius: theme.borderRadius.full,
},
segmentedContainerMd: {
minHeight: CONTROL_HEIGHTS.md,
padding: 0,
padding: SEGMENTED_INSET,
gap: SEGMENTED_INSET,
borderRadius: theme.borderRadius.full,
},
segmentedSegmentSm: {
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height - SEGMENTED_INSET * 2),
@@ -574,7 +574,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface2,
},
fieldFocused: {
borderColor: theme.colors.borderAccent,
borderColor: theme.colors.borderFocus,
},
fieldInput: {
flex: 1,
@@ -176,7 +176,7 @@ const styles = StyleSheet.create((theme) => ({
maxWidth: "100%",
},
fieldFocused: {
borderColor: theme.colors.borderAccent,
borderColor: theme.colors.borderFocus,
backgroundColor: theme.colors.surface2,
},
input: {
@@ -0,0 +1,63 @@
import React from "react";
import { cleanup, fireEvent, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { SegmentedControl } from "./segmented-control";
afterEach(cleanup);
describe("SegmentedControl", () => {
it("renders a recessed surface2 pill track with an elevated surface0 selected thumb in light theme", () => {
const { getByTestId } = render(
<SegmentedControl
testID="mode-picker"
value="form"
onValueChange={vi.fn()}
options={[
{ value: "form", label: "Form", testID: "mode-form" },
{ value: "uri", label: "URI", testID: "mode-uri" },
]}
/>,
);
const track = getByTestId("mode-picker");
const selected = getByTestId("mode-form");
const unselected = getByTestId("mode-uri");
const trackStyle = getComputedStyle(track);
const selectedStyle = getComputedStyle(selected);
const unselectedStyle = getComputedStyle(unselected);
expect(trackStyle.backgroundColor).toBe("rgb(244, 244, 245)");
expect(trackStyle.paddingTop).toBe("2px");
expect(selectedStyle.backgroundColor).toBe("rgb(255, 255, 255)");
expect(unselectedStyle.backgroundColor).toBe("rgba(0, 0, 0, 0)");
expect(selected.getAttribute("aria-selected")).toBe("true");
expect(unselected.getAttribute("aria-selected")).toBe("false");
});
it("calls onValueChange only when clicking an enabled unselected segment", () => {
const onValueChange = vi.fn();
const { getByTestId } = render(
<SegmentedControl
testID="mode-picker"
value="form"
onValueChange={onValueChange}
options={[
{ value: "form", label: "Form", testID: "mode-form" },
{ value: "uri", label: "URI", testID: "mode-uri" },
{ value: "ssh", label: "SSH", testID: "mode-ssh", disabled: true },
]}
/>,
);
fireEvent.click(getByTestId("mode-form"));
expect(onValueChange).not.toHaveBeenCalled();
fireEvent.click(getByTestId("mode-ssh"));
expect(onValueChange).not.toHaveBeenCalled();
fireEvent.click(getByTestId("mode-uri"));
expect(onValueChange).toHaveBeenCalledTimes(1);
expect(onValueChange).toHaveBeenCalledWith("uri");
});
});
@@ -31,8 +31,6 @@ interface SegmentedControlProps<T extends string> {
hideLabels?: boolean;
/** Share the container's width equally between the segments, for a control that heads a surface. */
fill?: boolean;
/** Let the segments run onto more lines when they do not fit on one. */
wrap?: boolean;
style?: StyleProp<ViewStyle>;
testID?: string;
}
@@ -59,7 +57,6 @@ export function SegmentedControl<T extends string>({
size: sizeProp,
hideLabels = false,
fill = false,
wrap = false,
style,
testID,
}: SegmentedControlProps<T>) {
@@ -75,8 +72,8 @@ export function SegmentedControl<T extends string>({
const iconSize = controlIconSize[size];
const containerStyle = useMemo(
() => [styles.container, containerSizeStyle, wrap && styles.containerWrap, style],
[containerSizeStyle, style, wrap],
() => [styles.container, containerSizeStyle, style],
[containerSizeStyle, style],
);
return (
@@ -191,11 +188,7 @@ const styles = StyleSheet.create((theme) => {
container: {
flexDirection: "row",
alignItems: "center",
backgroundColor: "transparent",
gap: theme.spacing[1],
},
containerWrap: {
flexWrap: "wrap",
backgroundColor: theme.colors.surface2,
},
containerSm: {
...geometry.segmentedContainerSm,
@@ -209,6 +202,8 @@ const styles = StyleSheet.create((theme) => {
justifyContent: "center",
flexShrink: 0,
gap: theme.spacing[1],
borderWidth: theme.borderWidth[1],
borderColor: "transparent",
},
segmentSm: {
...geometry.segmentedSegmentSm,
@@ -223,10 +218,16 @@ const styles = StyleSheet.create((theme) => {
minWidth: 0,
},
segmentSelected: {
backgroundColor: theme.colors.surface3,
backgroundColor: theme.colors.surfaceSegmentThumb,
borderColor: theme.colors.borderSegmentThumb,
shadowColor: theme.shadow.sm.shadowColor,
shadowOffset: { width: 0, height: 1 },
shadowRadius: 2,
shadowOpacity: 1,
elevation: 1,
},
segmentHover: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.interactionHighlight,
},
segmentPressed: {
backgroundColor: theme.colors.surface3,
@@ -25,7 +25,8 @@ import { AgentSheetHome, type AgentSheetControls } from "./sheet-home";
const SERVER_ID = "srv-live-settings";
const AGENT_ID = "agent-1";
const SHEET_FRAME_STYLE = { width: 390, height: 640, display: "flex" } as const;
const SHEET_FRAME_WIDTH = 390;
const SHEET_FRAME_HEIGHT = 640;
const GESTURE_ROOT_STYLE = { flex: 1 } as const;
const PRESENTATION = resolveComposerControlPresentation("compact");
const ignoreOpenSelect = () => undefined;
@@ -147,7 +148,7 @@ function setupSession() {
}
// Reads strictly from session-store — zero overlay merging in the view.
function LiveSheet({ toast }: { toast: ToastApi }) {
function LiveSheet({ toast, height = SHEET_FRAME_HEIGHT }: { toast: ToastApi; height?: number }) {
const agent = useSessionStore((state) => state.sessions[SERVER_ID]?.agents.get(AGENT_ID) ?? null);
const modeControl = useLiveAgentModeControl(SERVER_ID, AGENT_ID);
@@ -206,8 +207,13 @@ function LiveSheet({ toast }: { toast: ToastApi }) {
[items.features, items.thinking, modeControl],
);
const frameStyle = useMemo(
() => ({ width: SHEET_FRAME_WIDTH, height, display: "flex" as const }),
[height],
);
return (
<div style={SHEET_FRAME_STYLE}>
<div style={frameStyle}>
<AgentSheetHome
controls={controls}
disabled={false}
@@ -224,14 +230,14 @@ function createToast() {
};
}
function renderSheet() {
function renderSheet(height = SHEET_FRAME_HEIGHT) {
const toast = createToast();
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<GestureHandlerRootView style={GESTURE_ROOT_STYLE}>
<QueryClientProvider client={queryClient}>
<ToastApiProvider api={toast}>
<LiveSheet toast={toast} />
<LiveSheet toast={toast} height={height} />
</ToastApiProvider>
</QueryClientProvider>
</GestureHandlerRootView>,
@@ -239,6 +245,16 @@ function renderSheet() {
return toast;
}
function toViewportPoint(x: number, y: number): { x: number; y: number } {
const frameRect = window.frameElement?.getBoundingClientRect();
const scaleX = frameRect ? frameRect.width / window.innerWidth : 1;
const scaleY = frameRect ? frameRect.height / window.innerHeight : 1;
return {
x: Math.round((frameRect?.left ?? 0) + x * scaleX),
y: Math.round((frameRect?.top ?? 0) + y * scaleY),
};
}
beforeEach(() => vi.stubGlobal("React", React));
afterEach(() => {
cleanup();
@@ -377,17 +393,16 @@ describe("live agent settings sheet (browser geometry & races)", () => {
const lowStop = screen.getByTestId("agent-controls-thinking-low");
const highStop = screen.getByTestId("agent-controls-thinking-high");
const mediumStop = screen.getByTestId("agent-controls-thinking-medium");
const frameRect = window.frameElement?.getBoundingClientRect();
const scaleX = frameRect ? frameRect.width / window.innerWidth : 1;
const scaleY = frameRect ? frameRect.height / window.innerHeight : 1;
const toViewport = (x: number, y: number) => ({
x: Math.round((frameRect?.left ?? 0) + x * scaleX),
y: Math.round((frameRect?.top ?? 0) + y * scaleY),
});
const lowRect = lowStop.getBoundingClientRect();
const highRect = highStop.getBoundingClientRect();
const start = toViewport(lowRect.left + lowRect.width / 2, lowRect.top + lowRect.height / 2);
const end = toViewport(highRect.left + highRect.width / 2, highRect.top + highRect.height / 2);
const start = toViewportPoint(
lowRect.left + lowRect.width / 2,
lowRect.top + lowRect.height / 2,
);
const end = toViewportPoint(
highRect.left + highRect.width / 2,
highRect.top + highRect.height / 2,
);
const initialLeft = Math.round(thumb.getBoundingClientRect().left);
const browserCdp = cdp();
@@ -466,7 +481,7 @@ describe("live agent settings sheet (browser geometry & races)", () => {
// A plain tap after the drag still selects immediately.
const medRect = mediumStop.getBoundingClientRect();
const med = toViewport(medRect.left + medRect.width / 2, medRect.top + medRect.height / 2);
const med = toViewportPoint(medRect.left + medRect.width / 2, medRect.top + medRect.height / 2);
await browserCdp.send("Input.dispatchMouseEvent", {
type: "mousePressed",
x: med.x,
@@ -488,4 +503,93 @@ describe("live agent settings sheet (browser geometry & races)", () => {
expect(mediumLeft).toBeGreaterThan(initialLeft);
expect(mediumLeft).toBeLessThan(draggedLeft);
});
it("scrolls an overflowing pills row horizontally inside the sheet and selects a clipped option while keeping vertical sheet scroll", async () => {
const calls = setupSession();
const sevenChoices = [
{ value: "default", label: "Option One" },
{ value: "opt-2", label: "Option Two" },
{ value: "opt-3", label: "Option Three" },
{ value: "opt-4", label: "Option Four" },
{ value: "opt-5", label: "Option Five" },
{ value: "opt-6", label: "Option Six" },
{ value: "opt-7", label: "Option Seven" },
];
pushServerUpdate({
controls: [
CONTROLS[0],
{
type: "select",
key: "service_tier",
label: "Speed",
defaultValue: "default",
choices: sevenChoices,
},
],
});
renderSheet(240);
const track = await screen.findByTestId("agent-feature-service_tier");
const firstPill = screen.getByTestId("agent-feature-service_tier-default");
const lastPill = screen.getByTestId("agent-feature-service_tier-opt-7");
await nextPaint();
// All seven pills sit on one horizontal line inside the recessed track.
expect(Math.round(firstPill.getBoundingClientRect().top)).toBe(
Math.round(lastPill.getBoundingClientRect().top),
);
const horizontalScroller = track.parentElement?.parentElement;
expect(horizontalScroller).toBeTruthy();
if (!horizontalScroller) throw new Error("Missing horizontal scroller around pills control");
expect(horizontalScroller.scrollWidth).toBeGreaterThan(horizontalScroller.clientWidth);
expect(lastPill.getBoundingClientRect().right).toBeGreaterThan(
horizontalScroller.getBoundingClientRect().right,
);
const scrollerRect = horizontalScroller.getBoundingClientRect();
const pillsCenter = toViewportPoint(
scrollerRect.left + scrollerRect.width / 2,
scrollerRect.top + scrollerRect.height / 2,
);
const browserCdp = cdp();
// Wheel horizontally over the pills row to reveal the clipped trailing option and select it.
await browserCdp.send("Input.dispatchMouseEvent", {
type: "mouseWheel",
x: pillsCenter.x,
y: pillsCenter.y,
deltaX: horizontalScroller.scrollWidth,
deltaY: 0,
});
await nextPaint();
await nextPaint();
expect(horizontalScroller.scrollLeft).toBeGreaterThan(0);
expect(lastPill.getBoundingClientRect().right).toBeLessThanOrEqual(
horizontalScroller.getBoundingClientRect().right + 2,
);
fireEvent.click(lastPill);
expect(calls.map((call) => [call.kind, call.value])).toEqual([
["options", { service_tier: "opt-7" }],
]);
// Vertical wheel input over the pills row scrolls the outer sheet to reveal controls below it.
const sheetScroller = screen.getByTestId("agent-controls-settings-list");
expect(sheetScroller.scrollHeight).toBeGreaterThan(sheetScroller.clientHeight);
const modeCard = screen.getByTestId("mode-control");
const modeTopBefore = modeCard.getBoundingClientRect().top;
await browserCdp.send("Input.dispatchMouseEvent", {
type: "mouseWheel",
x: pillsCenter.x,
y: pillsCenter.y,
deltaX: 0,
deltaY: 160,
});
await nextPaint();
await nextPaint();
expect(sheetScroller.scrollTop).toBeGreaterThan(0);
expect(modeCard.getBoundingClientRect().top).toBeLessThan(modeTopBefore);
});
});
@@ -279,13 +279,14 @@ function PillsControl({ item, disabled }: { item: SelectItem; disabled: boolean
const handleChange = useCallback((value: string) => run(() => item.onChange(value)), [item, run]);
return (
<View style={styles.pills}>
<SegmentedControl
options={options}
value={item.value}
onValueChange={handleChange}
wrap
testID={item.testID}
/>
<SheetScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.pillsScroll}>
<SegmentedControl
options={options}
value={item.value}
onValueChange={handleChange}
testID={item.testID}
/>
</SheetScrollView>
</View>
);
}
@@ -640,6 +641,9 @@ const styles = StyleSheet.create((theme) => ({
pills: {
padding: theme.spacing[2],
},
pillsScroll: {
flexGrow: 0,
},
sliderCard: {
paddingHorizontal: theme.spacing[4],
paddingTop: theme.spacing[3],
+1 -1
View File
@@ -2492,7 +2492,7 @@ const styles = StyleSheet.create((theme: Theme) => ({
// A neutral step up from the resting `borderAccent`, never the accent. There is no hover
// step: `surface3` is fainter than the resting border in the pure black theme.
inputWrapperFocused: {
borderColor: theme.colors.surface4,
borderColor: theme.colors.borderFocus,
},
// The band the fullscreen glyph sits in is the input's own padding, so a tap
// anywhere in it (under the glyph, or where the glyph would be) is a tap on the
@@ -1,11 +1,19 @@
import { useCheckboxSpaceKey } from "@/components/ui/checkbox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useCallback, useMemo, useRef, useState } from "react";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Alert, Text, View, type LayoutChangeEvent } from "react-native";
import {
Alert,
Text,
View,
type LayoutChangeEvent,
type NativeSyntheticEvent,
type TextInputSelectionChangeEventData,
} from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { Check, Eye, EyeOff, Link2 } from "lucide-react-native";
import { Check, Eye, EyeOff, Form, Link, Link2 } from "lucide-react-native";
import type { HostProfile } from "@/types/host-connection";
import { useHosts, useHostMutations } from "@/runtime/host-runtime";
import { buildConnectionFailureCopy } from "@/components/connection-failure-copy";
@@ -27,11 +35,14 @@ import { useHardwareKeyboardPresent } from "@/keyboard/availability";
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
import {
canSwitchToForm,
commitHost,
editForm,
editHost,
editPort,
editPromptPassword,
editUri,
openDirectConnection,
pasteDirectConnection,
promptForPassword,
resolveConnection,
switchMode,
@@ -41,6 +52,7 @@ import {
type DirectConnectionMode,
type DirectConnectionUri,
type ResolvedDirectConnection,
type TextSelection,
} from "./direct-connection";
const FLEX_ONE_STYLE = { flex: 1 } as const;
@@ -212,11 +224,17 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
{
value: "form",
label: t("pairing.direct.modes.form"),
icon: ({ color, size }) => <Form color={color} size={size} />,
testID: "direct-mode-form",
disabled: !formAvailable,
...(formAvailable ? {} : { tooltip: t("pairing.direct.modes.uriOnlyLink") }),
},
{ value: "uri", label: t("pairing.direct.modes.uri"), testID: "direct-mode-uri" },
{
value: "uri",
label: t("pairing.direct.modes.uri"),
icon: ({ color, size }) => <Link color={color} size={size} />,
testID: "direct-mode-uri",
},
],
[formAvailable, t],
);
@@ -462,6 +480,22 @@ interface FieldEvents {
onSubmit: () => void;
}
function syncTextField(
inputRef: React.RefObject<EditingTextInputHandle | null>,
selectionRef: React.RefObject<TextSelection | null> | null,
currentValue: string,
nextValue: string,
options: { collapseSelectionToEnd: boolean; forceReplace: boolean },
) {
if (!options.forceReplace && nextValue === currentValue) return;
const endSelection = { start: nextValue.length, end: nextValue.length };
inputRef.current?.replaceText(
nextValue,
options.collapseSelectionToEnd ? endSelection : undefined,
);
if (selectionRef) selectionRef.current = endSelection;
}
function DirectFormFields({
input,
isSaving,
@@ -475,6 +509,13 @@ function DirectFormFields({
}) {
const { t } = useTranslation();
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const hostInputRef = useRef<EditingTextInputHandle | null>(null);
const portInputRef = useRef<EditingTextInputHandle | null>(null);
const passwordInputRef = useRef<EditingTextInputHandle | null>(null);
const sslToggleRef = useRef<View | null>(null);
const hostSelectionRef = useRef<TextSelection | null>(null);
const portSelectionRef = useRef<TextSelection | null>(null);
const suppressedPasteRef = useRef<{ field: "host" | "port"; text: string } | null>(null);
const hostFieldStyle = useMemo(() => [styles.field, styles.hostField], []);
const portFieldStyle = useMemo(() => [styles.field, styles.portField], []);
const passwordInputStyle = useMemo(() => [styles.input, styles.passwordInput], []);
@@ -487,22 +528,188 @@ function DirectFormFields({
[isSaving, input.useTls],
);
const syncFormInputs = useCallback(
(
previous: DirectConnectionForm,
next: DirectConnectionForm,
source:
| { kind: "paste"; field: "host" | "port" }
| { kind: "change"; field: "host" | "port" | "password"; rawText: string }
| { kind: "sync" },
) => {
syncTextField(
hostInputRef,
hostSelectionRef,
source.kind === "change" && source.field === "host" ? source.rawText : previous.host,
next.host,
{
collapseSelectionToEnd: source.kind !== "sync" && source.field === "host",
forceReplace: source.kind === "paste" && source.field === "host",
},
);
syncTextField(
portInputRef,
portSelectionRef,
source.kind === "change" && source.field === "port" ? source.rawText : previous.port,
next.port,
{
collapseSelectionToEnd: source.kind !== "sync" && source.field === "port",
forceReplace: source.kind === "paste" && source.field === "port",
},
);
syncTextField(
passwordInputRef,
null,
source.kind === "change" && source.field === "password"
? source.rawText
: previous.password,
next.password,
{ collapseSelectionToEnd: false, forceReplace: false },
);
},
[],
);
const handleNativePaste = useEffectEvent(
(field: "host" | "port", inputEl: HTMLInputElement, event: ClipboardEvent) => {
if (isSaving) return;
const pastedText = event.clipboardData?.getData("text/plain");
if (!pastedText) return;
const value = inputEl.value;
const selectionStart = inputEl.selectionStart ?? value.length;
const selectionEnd = inputEl.selectionEnd ?? value.length;
const replacesWholeField = selectionStart === 0 && selectionEnd === value.length;
if (!replacesWholeField) {
// Record the resulting single-line input value so the immediately following onChangeText
// treats a partial/mid-field paste as a literal edit rather than smart-filling the form.
const singleLinePaste = pastedText.replace(/[\r\n]/g, "");
suppressedPasteRef.current = {
field,
text: value.slice(0, selectionStart) + singleLinePaste + value.slice(selectionEnd),
};
return;
}
const next = pasteDirectConnection(input, pastedText);
if (!next) return;
event.preventDefault();
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "paste", field });
}
onChange(next);
},
);
useEffect(() => {
if (!isWeb) return;
const entries: Array<{ field: "host" | "port"; handle: EditingTextInputHandle | null }> = [
{ field: "host", handle: hostInputRef.current },
{ field: "port", handle: portInputRef.current },
];
const cleanups: Array<() => void> = [];
for (const { field, handle } of entries) {
const nativeEl = handle?.getNativeRef();
if (!(nativeEl instanceof HTMLInputElement)) continue;
const listener = (event: ClipboardEvent) => handleNativePaste(field, nativeEl, event);
nativeEl.addEventListener("paste", listener);
cleanups.push(() => nativeEl.removeEventListener("paste", listener));
}
return () => {
for (const cleanup of cleanups) cleanup();
};
}, []);
const handleHostSelectionChange = useCallback(
(event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
hostSelectionRef.current = event.nativeEvent.selection;
},
[],
);
const handlePortSelectionChange = useCallback(
(event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
portSelectionRef.current = event.nativeEvent.selection;
},
[],
);
const handleHostBlur = useCallback(
(event: unknown) => {
fieldEvents.onBlur();
// Clicking Use SSL on web blurs Host before onPress fires. Defer committing to the checkbox
// handler so blur's scheme inference cannot flip Use SSL right before the click toggles it.
if (isWeb && sslToggleRef.current instanceof Node) {
const relatedTarget =
(event as { relatedTarget?: unknown; nativeEvent?: { relatedTarget?: unknown } } | null)
?.relatedTarget ??
(event as { nativeEvent?: { relatedTarget?: unknown } } | null)?.nativeEvent
?.relatedTarget;
if (relatedTarget instanceof Node && sslToggleRef.current.contains(relatedTarget)) {
return;
}
}
const next = commitHost(input);
if (next === input) return;
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "sync" });
}
onChange(next);
},
[fieldEvents, input, onChange, syncFormInputs],
);
const handleHostChange = useCallback(
(host: string) => onChange(editHost(input, host)),
[input, onChange],
(host: string) => {
const suppressed = suppressedPasteRef.current;
suppressedPasteRef.current = null;
const allowSmartPaste = !(suppressed?.field === "host" && suppressed.text === host);
const next = editHost(input, host, {
allowSmartPaste,
selection: hostSelectionRef.current,
});
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "change", field: "host", rawText: host });
}
onChange(next);
},
[input, onChange, syncFormInputs],
);
const handlePortChange = useCallback(
(port: string) => onChange(editForm(input, { port })),
[input, onChange],
(port: string) => {
const suppressed = suppressedPasteRef.current;
suppressedPasteRef.current = null;
const allowSmartPaste = !(suppressed?.field === "port" && suppressed.text === port);
const next = editPort(input, port, {
allowSmartPaste,
selection: portSelectionRef.current,
});
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "change", field: "port", rawText: port });
}
onChange(next);
},
[input, onChange, syncFormInputs],
);
const handlePasswordChange = useCallback(
(password: string) => onChange(editForm(input, { password })),
[input, onChange],
(password: string) => {
const next = editForm(input, { password });
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "change", field: "password", rawText: password });
}
onChange(next);
},
[input, onChange, syncFormInputs],
);
const handleToggleUseTls = useCallback(() => {
if (isSaving) return;
onChange(editForm(input, { useTls: !input.useTls }));
}, [input, isSaving, onChange]);
const next = editForm(input, { useTls: !input.useTls });
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "sync" });
}
onChange(next);
}, [input, isSaving, onChange, syncFormInputs]);
const tlsCheckboxKeyProps = useCheckboxSpaceKey(handleToggleUseTls, isSaving);
const handleTogglePasswordVisibility = useCallback(() => {
setIsPasswordVisible((current) => !current);
@@ -516,13 +723,15 @@ function DirectFormFields({
<View style={hostFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
<AdaptiveTextInput
ref={hostInputRef}
testID="direct-host-input"
nativeID="direct-host-input"
accessibilityLabel={t("pairing.direct.fields.host")}
initialValue={input.host}
onChangeText={handleHostChange}
onSelectionChange={handleHostSelectionChange}
onFocus={fieldEvents.onFocus}
onBlur={fieldEvents.onBlur}
onBlur={handleHostBlur}
autoFocus={fieldEvents.autoFocus}
placeholder="localhost"
style={styles.input}
@@ -536,11 +745,13 @@ function DirectFormFields({
<View style={portFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.port")}</Text>
<AdaptiveTextInput
ref={portInputRef}
testID="direct-port-input"
nativeID="direct-port-input"
accessibilityLabel={t("pairing.direct.fields.port")}
initialValue={input.port}
onChangeText={handlePortChange}
onSelectionChange={handlePortSelectionChange}
onFocus={fieldEvents.onFocus}
onBlur={fieldEvents.onBlur}
placeholder="6767"
@@ -556,6 +767,7 @@ function DirectFormFields({
</View>
<PressHighlight
ref={sslToggleRef}
style={styles.checkboxRow}
onPress={handleToggleUseTls}
disabled={isSaving}
@@ -580,6 +792,7 @@ function DirectFormFields({
<Text style={styles.label}>{t("pairing.direct.fields.password")}</Text>
<View style={styles.passwordRow}>
<AdaptiveTextInput
ref={passwordInputRef}
testID="direct-password-input"
nativeID="direct-password-input"
accessibilityLabel={t("pairing.direct.fields.password")}
@@ -1,11 +1,14 @@
import { describe, expect, it } from "vitest";
import {
canSwitchToForm,
commitHost,
editForm,
editHost,
editPort,
editPromptPassword,
editUri,
openDirectConnection,
pasteDirectConnection,
promptForPassword,
resolveConnection,
switchMode,
@@ -28,7 +31,17 @@ const OFFER_LINK = `https://app.paseo.sh/#offer=${Buffer.from(
function form(fields: Partial<Omit<DirectConnectionForm, "mode">>): DirectConnectionInput {
const { host = "", ...rest } = fields;
return editForm(editHost(openDirectConnection(), host), rest);
return editForm(typeHost(openDirectConnection(), host), rest);
}
function typeHost(input: DirectConnectionInput, text: string): DirectConnectionInput {
let current = input;
let value = current.mode === "form" ? current.host : "";
for (const ch of text) {
value += ch;
current = editHost(current, value);
}
return current;
}
function uri(text: string): DirectConnectionInput {
@@ -129,6 +142,20 @@ describe("switching from URI to Form", () => {
port: "7000",
useTls: true,
});
expect(switchMode(uri("https://myhost.ts.net"), "form")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "443",
useTls: true,
password: "",
});
expect(switchMode(uri("wss://myhost.ts.net:7443/ws"), "form")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "7443",
useTls: true,
password: "",
});
});
it("round-trips any form with a host", () => {
@@ -153,18 +180,348 @@ describe("switching from URI to Form", () => {
});
describe("typing in Host", () => {
it("keeps host:port and URL shapes in Host", () => {
for (const text of ["host:7000", "http://host:7000/", "[::1]:7000"]) {
expect(editHost(openDirectConnection(), text)).toMatchObject({ mode: "form", host: text });
it("never hijacks manual character-by-character typing for host:port, URLs, or bare IPv6", () => {
for (const text of [
"host:7000",
"http://host:7000/",
"[::1]:7000",
"::1",
"2001:1234::1",
"fe80::1",
"tcp://h:7000?password=x",
]) {
expect(typeHost(openDirectConnection(), text)).toEqual({
mode: "form",
host: text,
port: "6767",
useTls: false,
password: "",
});
}
});
it("moves a typed or pasted URI to URI mode", () => {
expect(editHost(openDirectConnection(), "tcp://h:7000?password=x")).toEqual({
mode: "uri",
uri: "tcp://h:7000?password=x",
prompt: null,
it("does not trigger smart-fill on backspace or mid-string paste", () => {
const typedIpv6 = typeHost(openDirectConnection(), "2001:1234:");
expect(editHost(typedIpv6, "2001:1234")).toEqual({
mode: "form",
host: "2001:1234",
port: "6767",
useTls: false,
password: "",
});
const typedUrl = typeHost(openDirectConnection(), "http://example.com");
expect(editHost(typedUrl, "http://sub.example.com")).toEqual({
mode: "form",
host: "http://sub.example.com",
port: "6767",
useTls: false,
password: "",
});
const typedHostPort = typeHost(openDirectConnection(), "example.com:6768");
expect(editHost(typedHostPort, "my-example.com:6768")).toEqual({
mode: "form",
host: "my-example.com:6768",
port: "6767",
useTls: false,
password: "",
});
});
it("smart-fills Host, Port, Use SSL, and Password on paste into Host", () => {
expect(editHost(openDirectConnection(), "localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "100.91.42.18:6767")).toEqual({
mode: "form",
host: "100.91.42.18",
port: "6767",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "hetzner.tail8a2f.ts.net:6768")).toEqual({
mode: "form",
host: "hetzner.tail8a2f.ts.net",
port: "6768",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "[::1]:6768")).toEqual({
mode: "form",
host: "::1",
port: "6768",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "https://myhost.ts.net:6767/")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "6767",
useTls: true,
password: "",
});
expect(editHost(openDirectConnection(), "https://myhost.ts.net")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "443",
useTls: true,
password: "",
});
expect(editHost(openDirectConnection(), "http://myhost.ts.net")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "80",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "wss://myhost.ts.net/ws")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "443",
useTls: true,
password: "",
});
expect(editHost(openDirectConnection(), "tcp://h:7000?ssl=true&password=x")).toEqual({
mode: "form",
host: "h",
port: "7000",
useTls: true,
password: "x",
});
});
it("preserves unspecified fields and updates specified fields on paste", () => {
const existing = form({
host: "oldhost",
port: "7000",
useTls: true,
password: "saved-password",
});
// host:port without scheme or password preserves SSL and password
expect(pasteDirectConnection(existing, "localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: true,
password: "saved-password",
});
// http:// explicitly disables SSL while keeping password
expect(pasteDirectConnection(existing, "http://localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: false,
password: "saved-password",
});
// tcp:// without port or password keeps current port, clears stale password, and sets SSL from ?ssl=
expect(pasteDirectConnection(existing, "tcp://newhost")).toEqual({
mode: "form",
host: "newhost",
port: "7000",
useTls: false,
password: "",
});
// tcp:// with port and no password clears the previous host's password
expect(pasteDirectConnection(existing, "tcp://second.example.test:7443")).toEqual({
mode: "form",
host: "second.example.test",
port: "7443",
useTls: false,
password: "",
});
// tcp:// with password overwrites password
expect(pasteDirectConnection(existing, "tcp://newhost:8080?ssl=true&password=next")).toEqual({
mode: "form",
host: "newhost",
port: "8080",
useTls: true,
password: "next",
});
});
it("uses native selection range to distinguish full replacements from partial pastes", () => {
const existingDomain = form({ host: "home.example.test", port: "6767" });
expect(
editHost(existingDomain, "https://new.example.test", {
selection: { start: 0, end: "home.example.test".length },
}),
).toEqual({
mode: "form",
host: "new.example.test",
port: "443",
useTls: true,
password: "",
});
// Replacing only a leading word slice is a partial edit, not a full paste
expect(
editHost(existingDomain, "https://new.example.test", {
selection: { start: 0, end: 4 },
}),
).toEqual({
mode: "form",
host: "https://new.example.test",
port: "6767",
useTls: false,
password: "",
});
const existingIp = form({ host: "192.168.1.10", port: "6767" });
expect(
editHost(existingIp, "192.168.1.11:6710", {
selection: { start: 0, end: "192.168.1.10".length },
}),
).toEqual({
mode: "form",
host: "192.168.1.11",
port: "6710",
useTls: false,
password: "",
});
// Pasting `:6710` at the end of an existing host stays a literal edit
expect(
editHost(existingIp, "192.168.1.10:6710", {
selection: { start: "192.168.1.10".length, end: "192.168.1.10".length },
}),
).toEqual({
mode: "form",
host: "192.168.1.10:6710",
port: "6767",
useTls: false,
password: "",
});
});
it("preserves SSL, port, and password when submitting or switching a manually typed URI", () => {
const typedTcp = typeHost(
openDirectConnection(),
"tcp://secure.example.test:7443?ssl=true&password=example",
);
expect(resolveConnection(typedTcp, LABELS)).toEqual({
kind: "direct",
uri: "tcp://secure.example.test:7443?ssl=true",
endpoint: "secure.example.test:7443",
useTls: true,
password: "example",
});
expect(switchMode(typedTcp, "uri")).toMatchObject({
mode: "uri",
uri: "tcp://secure.example.test:7443?ssl=true&password=example",
});
const typedHttps = typeHost(openDirectConnection(), "https://myhost.ts.net");
expect(resolveConnection(typedHttps, LABELS)).toEqual({
kind: "direct",
uri: "tcp://myhost.ts.net:443?ssl=true",
endpoint: "myhost.ts.net:443",
useTls: true,
});
expect(switchMode(typedHttps, "uri")).toMatchObject({
mode: "uri",
uri: "tcp://myhost.ts.net:443?ssl=true",
});
// Typing a tcp:// URI without SSL or password clears a previous host's SSL and password
const previousHost = form({
host: "first.example.test",
port: "6767",
useTls: true,
password: "first-password",
});
const replacedByTyping = typeHost(editHost(previousHost, ""), "tcp://second.example.test:7443");
expect(commitHost(replacedByTyping)).toEqual({
mode: "form",
host: "second.example.test",
port: "7443",
useTls: false,
password: "",
});
expect(resolveConnection(replacedByTyping, LABELS)).toEqual({
kind: "direct",
uri: "tcp://second.example.test:7443",
endpoint: "second.example.test:7443",
useTls: false,
});
// Editing Password after typing a URI with a wrong password overrides the URI password
const typedWrongPassword = typeHost(
openDirectConnection(),
"tcp://host.example.test:7000?password=wrong",
);
const corrected = editForm(typedWrongPassword, { password: "right" });
expect(corrected).toEqual({
mode: "form",
host: "host.example.test",
port: "7000",
useTls: false,
password: "right",
});
expect(resolveConnection(corrected, LABELS)).toEqual({
kind: "direct",
uri: "tcp://host.example.test:7000",
endpoint: "host.example.test:7000",
useTls: false,
password: "right",
});
});
it("smart-fills when replacing an existing host or pasting into Port", () => {
const withHost = form({ host: "localhost", port: "6767" });
expect(editHost(withHost, "localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: false,
password: "",
});
expect(editPort(openDirectConnection(), "100.91.42.18:6767")).toEqual({
mode: "form",
host: "100.91.42.18",
port: "6767",
useTls: false,
password: "",
});
expect(editPort(openDirectConnection(), "https://myhost.ts.net:7443")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "7443",
useTls: true,
password: "",
});
expect(editPort(openDirectConnection(), "7000")).toEqual({
mode: "form",
host: "",
port: "7000",
useTls: false,
password: "",
});
});
it("leaves invalid ports and bare IPv6 untouched on paste", () => {
expect(pasteDirectConnection(openDirectConnection(), "localhost:70000")).toBeNull();
expect(pasteDirectConnection(openDirectConnection(), "localhost:0")).toBeNull();
expect(pasteDirectConnection(openDirectConnection(), "localhost:abc")).toBeNull();
expect(pasteDirectConnection(openDirectConnection(), "::1")).toBeNull();
expect(editHost(openDirectConnection(), "localhost:70000")).toMatchObject({
mode: "form",
host: "localhost:70000",
port: "6767",
});
});
it("moves a pasted pairing link to URI mode", () => {
expect(editHost(openDirectConnection(), RELAY_LINK)).toMatchObject({
mode: "uri",
uri: RELAY_LINK,
@@ -177,6 +534,11 @@ describe("typing in Host", () => {
uri: OFFER_LINK,
prompt: null,
});
expect(pasteDirectConnection(openDirectConnection(), OFFER_LINK)).toEqual({
mode: "uri",
uri: OFFER_LINK,
prompt: null,
});
});
});
@@ -1,6 +1,11 @@
import {
buildDirectConnectionUri,
normalizeDirectConnectionHost,
defaultPortForDirectScheme,
isPairingLink,
parseDirectConnectionAddress,
parseDirectConnectionPaste,
resolveDirectHostDraft,
resolveDirectSchemeTls,
type DirectConnectionHostLabels,
} from "@/components/direct-connection-host";
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
@@ -38,7 +43,6 @@ export type ResolvedDirectConnection =
| { kind: "relay"; link: string; password?: string };
const DEFAULT_PORT = "6767";
const TCP_URI_PATTERN = /^tcp:\/\//i;
export function openDirectConnection(): DirectConnectionForm {
return { mode: "form", host: "", port: DEFAULT_PORT, useTls: false, password: "" };
@@ -59,21 +63,97 @@ export function canSwitchToForm(input: DirectConnectionInput): boolean {
return input.mode === "form" || !isPairingLink(input.uri);
}
/**
* Commits a manually typed `host:port`, URI, or pairing link sitting in Host into the form's
* structured fields (or URI mode for pairing links) once the user leaves Host or submits.
*/
export function commitHost(input: DirectConnectionInput): DirectConnectionInput {
if (input.mode !== "form") return input;
return pasteDirectConnection(input, input.host) ?? input;
}
function commitDirectFormHost(input: DirectConnectionForm): DirectConnectionForm {
const committed = pasteDirectConnection(input, input.host);
return committed && committed.mode === "form" ? committed : input;
}
export function editForm(
input: DirectConnectionInput,
fields: Partial<Omit<DirectConnectionForm, "mode" | "host">>,
): DirectConnectionInput {
if (input.mode !== "form") return input;
return { ...input, ...fields };
return { ...commitDirectFormHost(input), ...fields };
}
/** A URI typed or pasted into Host moves to URI mode, where its query and pairing data count. */
export function editHost(input: DirectConnectionInput, text: string): DirectConnectionInput {
/**
* Parses a pasted host:port, URI, or pairing link into the next Direct connection state.
* Returns `null` when the text should stay a literal edit in the active field.
*/
export function pasteDirectConnection(
input: DirectConnectionInput,
text: string,
): DirectConnectionInput | null {
if (input.mode !== "form") return null;
if (isPairingLink(text)) return { mode: "uri", uri: text.trim(), prompt: null };
const parsed = parseDirectConnectionPaste(text);
if (!parsed) return null;
return {
...input,
host: parsed.host,
...(parsed.port !== undefined ? { port: parsed.port } : {}),
...(parsed.useTls !== undefined ? { useTls: parsed.useTls } : {}),
...(parsed.password !== undefined ? { password: parsed.password } : {}),
};
}
export interface TextSelection {
start: number;
end: number;
}
export interface DirectFieldEditOptions {
allowSmartPaste?: boolean;
/** The input's selection range immediately before this text change, when known. */
selection?: TextSelection | null;
}
/**
* Updates Host in Form mode. Multi-character pastes that look like a host:port, URI, or pairing
* link populate the form (or switch to URI mode for pairing links) without fighting normal typing.
*/
export function editHost(
input: DirectConnectionInput,
text: string,
options?: DirectFieldEditOptions,
): DirectConnectionInput {
if (input.mode !== "form") return input;
if (looksLikeUri(text)) return { mode: "uri", uri: text.trim(), prompt: null };
if (
options?.allowSmartPaste !== false &&
isWholeFieldPasteChange(input.host, text, options?.selection)
) {
const pasted = pasteDirectConnection(input, text);
if (pasted) return pasted;
}
return { ...input, host: text };
}
/** Updates Port in Form mode, smart-filling when a full host:port or URI is pasted into Port. */
export function editPort(
input: DirectConnectionInput,
text: string,
options?: DirectFieldEditOptions,
): DirectConnectionInput {
if (input.mode !== "form") return input;
if (
options?.allowSmartPaste !== false &&
isWholeFieldPasteChange(input.port, text, options?.selection)
) {
const pasted = pasteDirectConnection(input, text);
if (pasted) return pasted;
}
return { ...commitDirectFormHost(input), port: text };
}
/** Editing the URI to point at another host drops the password typed for the previous one. */
export function editUri(input: DirectConnectionInput, text: string): DirectConnectionInput {
if (input.mode !== "uri") return input;
@@ -100,11 +180,12 @@ export function resolveConnection(
input: DirectConnectionInput,
labels: DirectConnectionHostLabels,
): ResolvedDirectConnection {
if (input.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(input, labels));
const effective = commitHost(input);
if (effective.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(effective, labels));
}
const uri = input.uri.trim();
const promptPassword = input.prompt?.password || undefined;
const uri = effective.uri.trim();
const promptPassword = effective.prompt?.password || undefined;
if (isPairingLink(uri)) {
return { kind: "relay", link: uri, ...(promptPassword ? { password: promptPassword } : {}) };
}
@@ -123,43 +204,85 @@ function resolveTcpUri(uri: string, passwordOverride?: string): ResolvedDirectCo
};
}
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
function isPairingLink(uri: string): boolean {
const trimmed = uri.trim();
function hasAddressDelimiter(text: string): boolean {
return isPairingLink(text) || /[:[\]/]/.test(text);
}
function matchesSelectionEdit(previous: string, next: string, selection: TextSelection): boolean {
const start = Math.min(selection.start, selection.end);
const end = Math.max(selection.start, selection.end);
const prefix = previous.slice(0, start);
const suffix = previous.slice(end);
return (
trimmed.toLowerCase().startsWith("relay://") ||
trimmed.includes("#connect=") ||
trimmed.includes("#offer=")
next.length >= prefix.length + suffix.length && next.startsWith(prefix) && next.endsWith(suffix)
);
}
function looksLikeUri(text: string): boolean {
return TCP_URI_PATTERN.test(text.trim()) || isPairingLink(text);
function isWholeFieldPasteChange(
previous: string,
next: string,
selection?: TextSelection | null,
): boolean {
if (next === previous) return false;
if (previous.length === 0) return next.length >= 2 && hasAddressDelimiter(next);
if (selection) {
const start = Math.min(selection.start, selection.end);
const end = Math.max(selection.start, selection.end);
if (start === 0 && end === previous.length) {
return next.length >= 2 && hasAddressDelimiter(next);
}
if (matchesSelectionEdit(previous, next, selection)) {
return false;
}
}
let prefix = 0;
const minLength = Math.min(previous.length, next.length);
while (prefix < minLength && previous[prefix] === next[prefix]) {
prefix += 1;
}
let suffix = 0;
while (
suffix < minLength - prefix &&
previous[previous.length - 1 - suffix] === next[next.length - 1 - suffix]
) {
suffix += 1;
}
const inserted = next.slice(prefix, next.length - suffix);
if (inserted.length < 2) return false;
if (prefix > 0 && suffix > 0) return false;
return isPairingLink(next) || /[:[\]/]/.test(inserted);
}
// Built as text, not through the strict serializer, so an invalid port carries over and Connect
// reports it instead of the switch failing.
function formToUri(input: DirectConnectionForm): string {
const normalized = normalizeDirectConnectionHost(input.host);
if (!normalized.host) return "";
const host = normalized.isIpv6 ? `[${normalized.host}]` : normalized.host;
const port = normalized.port ?? input.port.trim();
const committed = commitHost(input);
if (committed.mode === "uri") return committed.uri;
const resolved = resolveDirectHostDraft(committed);
if (!resolved.host) return "";
const host = resolved.isIpv6 ? `[${resolved.host}]` : resolved.host;
const query = new URLSearchParams();
if (input.useTls) query.set("ssl", "true");
if (input.password) query.set("password", input.password);
if (resolved.useTls) query.set("ssl", "true");
if (resolved.password) query.set("password", resolved.password);
const search = query.toString();
return `tcp://${host}:${port}${search ? `?${search}` : ""}`;
return `tcp://${host}:${resolved.port}${search ? `?${search}` : ""}`;
}
function uriToForm(uri: string): DirectConnectionForm {
const address = splitUri(uri);
const address = parseDirectConnectionAddress(uri);
if (!address.host) return openDirectConnection();
const port =
(address.port && address.port.length > 0 ? address.port : null) ??
defaultPortForDirectScheme(address.scheme) ??
DEFAULT_PORT;
return {
mode: "form",
host: address.host,
port: address.port ?? DEFAULT_PORT,
useTls: address.query.get("ssl") === "true",
password: address.query.get("password") ?? "",
port,
useTls: resolveDirectSchemeTls(address.scheme, address.sslParam) ?? false,
password: address.password ?? "",
};
}
@@ -174,35 +297,7 @@ export function uriHostLabel(uri: string): string | null {
return null;
}
}
const address = splitUri(trimmed);
const address = parseDirectConnectionAddress(trimmed);
if (!address.host || !address.port) return null;
return address.isIpv6 ? `[${address.host}]:${address.port}` : `${address.host}:${address.port}`;
}
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(.*))?$/;
/** Lenient split of a typed URI. Keeps an invalid port as text instead of rejecting it. */
function splitUri(uri: string): {
host: string;
port: string | null;
isIpv6: boolean;
query: URLSearchParams;
} {
const rest = uri.trim().replace(SCHEME_PATTERN, "");
const queryIndex = rest.indexOf("?");
const query = new URLSearchParams(
queryIndex === -1 ? "" : rest.slice(queryIndex + 1).split("#")[0],
);
const authority = rest.split(/[/?#]/)[0] ?? "";
const bracketed = BRACKETED_IPV6_PATTERN.exec(authority);
if (bracketed) {
return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true, query };
}
const parts = authority.split(":");
if (parts.length === 2) {
return { host: parts[0] ?? "", port: parts[1] || null, isIpv6: false, query };
}
return { host: authority, port: null, isIpv6: parts.length > 2, query };
}
@@ -796,15 +796,14 @@ function ListedPluginLayout({
{hero}
<View style={styles.twoCol}>
<View style={styles.main}>
<View style={styles.tabBar}>
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.tabBar}>
<SegmentedControl
options={tabs}
value={activeTab}
onValueChange={onTabChange}
wrap
testID="plugin-page-tabs"
/>
</View>
</ScrollView>
{panel}
</View>
@@ -1086,7 +1085,12 @@ const styles = StyleSheet.create((theme) => ({
},
controls: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
installRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
tabBar: { marginBottom: theme.spacing[4], alignSelf: "flex-start", maxWidth: "100%" },
tabBar: {
flexGrow: 0,
marginBottom: theme.spacing[4],
alignSelf: "flex-start",
maxWidth: "100%",
},
compactTabScroll: { flexGrow: 0 },
description: {
color: theme.colors.foreground,
+42 -1
View File
@@ -10,7 +10,14 @@
* A ratio keeps the step equally visible on every base; a lightness delta disappears near black.
* The numbers come from the default themes: Paseo dark and Light.
*/
import { contrastRatio, mixHexColors, stepContrast, translucentStep } from "@/utils/color";
import {
contrastRatio,
isTranslucentHexColor,
mixHexColors,
paintHexOver,
stepContrast,
translucentStep,
} from "@/utils/color";
export type ColorScheme = "light" | "dark";
@@ -53,6 +60,10 @@ const NEUTRAL_FILL_MIN_STEP = 1.25;
const TERTIARY_TEXT_FADE = 0.35;
const TERTIARY_TEXT_FLOOR = 2.55;
// Focused input borders step from the resting accent border toward the foreground so focus
// stays equally legible across dark and light palettes without borrowing `surface4`.
const BORDER_FOCUS_STEP = 1.3;
function deriveStates({
surface,
foreground,
@@ -133,3 +144,33 @@ export function deriveSidebarStateText(
if (contrastRatio(tertiary, surface) >= TERTIARY_TEXT_FLOOR) return tertiary;
return stepContrast(surface, foreground, TERTIARY_TEXT_FLOOR);
}
function closestToForeground(candidates: readonly string[], foreground: string): string {
return candidates.reduce((best, candidate) =>
contrastRatio(candidate, foreground) < contrastRatio(best, foreground) ? candidate : best,
);
}
/**
* Neutral focus border stepped from `borderAccent` toward `foreground`.
*
* When `borderAccent` is translucent, the focus border stays translucent (calibrated against
* `surface1`) so it scales cleanly over both `surface1` (composer) and `surface2` (`SearchField`,
* `MenuTextField`). When `borderAccent` is opaque, stepping starts from whichever of
* `[borderAccent, surface1, surface2]` already sits closest to `foreground` so focus never lands
* on `surface2`.
*/
export function deriveBorderFocus(
borderAccent: string,
foreground: string,
surface1: string,
surface2: string,
): string {
if (isTranslucentHexColor(borderAccent)) {
const painted = paintHexOver(surface1, borderAccent);
const target = stepContrast(painted, foreground, BORDER_FOCUS_STEP);
return translucentStep(surface1, foreground, contrastRatio(surface1, target));
}
const base = closestToForeground([borderAccent, surface1, surface2], foreground);
return stepContrast(base, foreground, BORDER_FOCUS_STEP);
}
+116 -3
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { PluginThemeContribution } from "@getpaseo/plugin";
import { buildPluginTheme } from "@/plugins/themes";
import { contrastRatio, mixHexColors } from "@/utils/color";
import { contrastRatio, mixHexColors, paintHexOver } from "@/utils/color";
import { darkPureBlackTheme, THEME_OPTIONS, type Theme } from "./theme";
// Palettes of the plugin themes users run into: Catppuccin (the e2e fixture) and
@@ -70,11 +70,80 @@ const SOLARIZED_DARK: PluginThemeContribution = {
},
};
const TRANSLUCENT_DARK: PluginThemeContribution = {
id: "translucent-dark",
name: "Translucent Dark",
appearance: "dark",
colors: {
background: "#101010",
foreground: "#fafafa",
raised: "#161616",
control: "#222222",
border: "#ffffff20",
mutedForeground: "#a1a1aa",
ring: "#52525b",
},
};
const TRANSLUCENT_LIGHT: PluginThemeContribution = {
id: "translucent-light",
name: "Translucent Light",
appearance: "light",
colors: {
background: "#ffffff",
foreground: "#1a1a1e",
raised: "#fafafa",
control: "#f4f4f5",
border: "#00000018",
mutedForeground: "#71717a",
ring: "#a1a1aa",
},
};
const TRANSLUCENT_HIGH_CONTRAST_CONTROL: PluginThemeContribution = {
id: "translucent-high-contrast-control",
name: "Translucent High-Contrast Control",
appearance: "dark",
colors: {
background: "#101010",
foreground: "#fafafa",
raised: "#161616",
control: "#444444",
border: "#ffffff20",
mutedForeground: "#a1a1aa",
ring: "#52525b",
},
};
const OPAQUE_HIGH_CONTRAST_CONTROL: PluginThemeContribution = {
id: "opaque-high-contrast-control",
name: "Opaque High-Contrast Control",
appearance: "dark",
colors: {
background: "#101010",
foreground: "#fafafa",
raised: "#161616",
control: "#444444",
border: "#333333",
mutedForeground: "#a1a1aa",
ring: "#52525b",
},
};
const themes: Array<{ name: string; theme: Theme }> = [
...THEME_OPTIONS.flatMap((option) =>
"theme" in option ? [{ name: option.name, theme: option.theme as Theme }] : [],
),
...[LATTE, MOCHA, SOLARIZED_LIGHT, SOLARIZED_DARK].map((contribution) => ({
...[
LATTE,
MOCHA,
SOLARIZED_LIGHT,
SOLARIZED_DARK,
TRANSLUCENT_DARK,
TRANSLUCENT_LIGHT,
TRANSLUCENT_HIGH_CONTRAST_CONTROL,
OPAQUE_HIGH_CONTRAST_CONTROL,
].map((contribution) => ({
name: `plugin ${contribution.name}`,
theme: buildPluginTheme(contribution),
})),
@@ -99,9 +168,14 @@ const TREE_GUIDE_FLOOR = 1.18;
// The bright hues are dim on a cream or white background by design; the floor only has to catch a
// color that disappears.
const TERMINAL_COLOR_FLOOR = 1.5;
// Focus borders step 1.30x from `borderAccent` toward `foreground`; 8-bit rounding lands around 1.29x.
const BORDER_FOCUS_STEP_FLOOR = 1.28;
const BORDER_FOCUS_BAND_MIN = 1.5;
const BORDER_FOCUS_BAND_MAX = 1.95;
/** The color a translucent `rgba()` token shows once painted over `surface`. */
/** The color a translucent `rgba()` or hex token shows once painted over `surface`. */
function paintedOver(surface: string, token: string): string {
if (token.startsWith("#")) return paintHexOver(surface, token);
const [r, g, b, alpha] = (token.match(/[\d.]+/g) ?? []).map(Number);
const ink = `#${[r, g, b].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
return mixHexColors(surface, ink, alpha);
@@ -184,6 +258,33 @@ describe.each(themes)("$name", ({ theme }) => {
expect(contrastRatio(colors.surface3, colors.surface4)).toBeGreaterThanOrEqual(1.15);
});
it("steps focus borders cleanly above resting borders and field surfaces", () => {
const fieldSurface = paintedOver(colors.surface0, colors.surface1);
const controlSurface = paintedOver(colors.surface0, colors.surface2);
const paintedBorderAccent = paintedOver(fieldSurface, colors.borderAccent);
const paintedBorderOnControl = paintedOver(controlSurface, colors.border);
const paintedFocusOnField = paintedOver(fieldSurface, colors.borderFocus);
const paintedFocusOnControl = paintedOver(controlSurface, colors.borderFocus);
const paintedFocusOnPage = paintedOver(colors.surface0, colors.borderFocus);
expect(contrastRatio(paintedBorderAccent, paintedFocusOnField)).toBeGreaterThanOrEqual(
BORDER_FOCUS_STEP_FLOOR,
);
expect(contrastRatio(colors.surface0, paintedFocusOnPage)).toBeGreaterThan(
contrastRatio(colors.surface0, paintedOver(colors.surface0, colors.borderAccent)),
);
expect(contrastRatio(colors.surface0, paintedFocusOnPage)).toBeGreaterThan(
contrastRatio(colors.surface0, paintedOver(colors.surface0, colors.border)),
);
expect(contrastRatio(controlSurface, paintedFocusOnControl)).toBeGreaterThanOrEqual(
BORDER_FOCUS_STEP_FLOOR,
);
expect(contrastRatio(controlSurface, paintedFocusOnControl)).toBeGreaterThan(
contrastRatio(controlSurface, paintedBorderOnControl),
);
expect(contrastRatio(fieldSurface, paintedFocusOnField)).toBeLessThanOrEqual(2.5);
});
it("keeps terminal text readable on the terminal background", () => {
const terminal = colors.terminal;
const { background, ...palette } = terminal;
@@ -275,4 +376,16 @@ describe("built-in themes", () => {
expect(contrastRatio(pureBlack.borderAccent, pureBlack.surface3)).toBeGreaterThanOrEqual(1.15);
expect(contrastRatio(pureBlack.surface3, pureBlack.surface4)).toBeGreaterThanOrEqual(1.35);
});
it.each(themes.filter(({ name }) => !name.startsWith("plugin ")))(
"$name holds borderFocus inside the calm contrast band",
({ theme }) => {
const vsPage = contrastRatio(theme.colors.surface0, theme.colors.borderFocus);
expect(vsPage).toBeGreaterThanOrEqual(BORDER_FOCUS_BAND_MIN);
expect(vsPage).toBeLessThanOrEqual(BORDER_FOCUS_BAND_MAX);
expect(contrastRatio(theme.colors.surface1, theme.colors.borderFocus)).toBeGreaterThanOrEqual(
1.45,
);
},
);
});
+23 -1
View File
@@ -1,7 +1,13 @@
import { Platform, type ViewStyle } from "react-native";
import { isWeb } from "@/constants/platform";
import { paintHexOver } from "@/utils/color";
import { darkHighlightColors, lightHighlightColors } from "@getpaseo/highlight";
import { derivePageSurfaceStates, deriveSurfaceStates, deriveTreeGuide } from "./derive-colors";
import {
deriveBorderFocus,
derivePageSurfaceStates,
deriveSurfaceStates,
deriveTreeGuide,
} from "./derive-colors";
export const baseColors = {
// Base colors
@@ -287,6 +293,8 @@ export function buildLightSemanticColors(tint: LightThemeConfig) {
foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted,
treeGuide: deriveTreeGuide(tint.surfaceSidebar, tint.foreground, "light"),
surfaceWorkspace: tint.surface0,
surfaceSegmentThumb: tint.surface0,
borderSegmentThumb: "transparent",
interactionHighlight: "rgba(0, 0, 0, 0.06)",
foreground: tint.foreground,
@@ -295,6 +303,12 @@ export function buildLightSemanticColors(tint: LightThemeConfig) {
border: tint.border,
borderAccent: tint.borderAccent,
borderFocus: deriveBorderFocus(
tint.borderAccent,
tint.foreground,
paintHexOver(tint.surface0, tint.surface1),
paintHexOver(tint.surface0, tint.surface2),
),
accent: tint.accent,
accentBright: tint.accentBright,
@@ -425,6 +439,8 @@ export function buildDarkSemanticColors(tint: DarkThemeConfig) {
foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted,
treeGuide: deriveTreeGuide(tint.surfaceSidebar, foreground, "dark"),
surfaceWorkspace: tint.surface1,
surfaceSegmentThumb: tint.surface3,
borderSegmentThumb: "rgba(255, 255, 255, 0.08)",
interactionHighlight: "rgba(255, 255, 255, 0.08)",
foreground,
@@ -433,6 +449,12 @@ export function buildDarkSemanticColors(tint: DarkThemeConfig) {
border: tint.border,
borderAccent: tint.borderAccent,
borderFocus: deriveBorderFocus(
tint.borderAccent,
foreground,
paintHexOver(tint.surface0, tint.surface1),
paintHexOver(tint.surface0, tint.surface2),
),
accent: tint.accent,
accentBright: tint.accentBright,
+14
View File
@@ -3,7 +3,9 @@ import {
contrastRatio,
desaturateHexColor,
hexColorWithAlpha,
isTranslucentHexColor,
mixHexColors,
paintHexOver,
parseHexColor,
stepContrast,
} from "./color";
@@ -118,3 +120,15 @@ describe("mixHexColors", () => {
expect(mixHexColors("#000000", "#ffffff", 0.5)).toBe("#808080");
});
});
describe("paintHexOver", () => {
it("leaves opaque hexes unchanged and composites translucent hexes over the surface", () => {
expect(isTranslucentHexColor("#2f3534")).toBe(false);
expect(isTranslucentHexColor("#45475aff")).toBe(false);
expect(isTranslucentHexColor("#ffffff20")).toBe(true);
expect(paintHexOver("#161616", "#2f3534")).toBe("#2f3534");
expect(paintHexOver("#161616", "#45475aff")).toBe("#45475aff");
expect(paintHexOver("#161616", "#ffffff20")).toBe("#333333");
expect(paintHexOver("#000000", "#fff8")).toBe("#888888");
});
});
+22
View File
@@ -184,3 +184,25 @@ export function mixHexColors(hex: string, toward: string, amount: number): strin
);
return `#${channels.join("")}`;
}
function hexAlpha(hex: string): number {
if (/^#[0-9a-fA-F]{4}$/.test(hex)) {
return Number.parseInt(`${hex[4]}${hex[4]}`, 16) / 255;
}
if (/^#[0-9a-fA-F]{8}$/.test(hex)) {
return Number.parseInt(hex.slice(7, 9), 16) / 255;
}
return 1;
}
/** Whether a hex colour carries a non-opaque alpha channel (`< 1`). */
export function isTranslucentHexColor(hex: string): boolean {
return hexAlpha(hex) < 1;
}
/** Paints a hex colour with optional alpha over an opaque `surface`. */
export function paintHexOver(surface: string, hex: string): string {
const alpha = hexAlpha(hex);
if (alpha >= 1) return hex;
return mixHexColors(surface, hex, alpha);
}
@@ -49,6 +49,7 @@ export const Folder = StubIcon;
export const FolderOpen = StubIcon;
export const FolderPlus = StubIcon;
export const FolderTree = StubIcon;
export const Form = StubIcon;
export const Gift = StubIcon;
export const GitBranch = StubIcon;
export const GitCommitHorizontal = StubIcon;