Add autofocus to text boxes

This commit is contained in:
Jack Kingsman
2026-04-06 21:59:46 -07:00
parent eeaa11b8b0
commit ca7349a1a8
6 changed files with 178 additions and 108 deletions
+17 -1
View File
@@ -25,7 +25,8 @@ import { DistanceUnitProvider } from './contexts/DistanceUnitContext';
import { messageContainsMention } from './utils/messageParser'; import { messageContainsMention } from './utils/messageParser';
import { getStateKey } from './utils/conversationState'; import { getStateKey } from './utils/conversationState';
import type { BulkCreateHashtagChannelsResult, Conversation, Message, RawPacket } from './types'; import type { BulkCreateHashtagChannelsResult, Conversation, Message, RawPacket } from './types';
import { CONTACT_TYPE_ROOM } from './types'; import { CONTACT_TYPE_REPEATER, CONTACT_TYPE_ROOM } from './types';
import { shouldAutoFocusInput } from './utils/autoFocusInput';
interface ChannelUnreadMarker { interface ChannelUnreadMarker {
channelId: string; channelId: string;
@@ -296,6 +297,21 @@ export function App() {
} = useConversationMessages(activeConversation, targetMessageId); } = useConversationMessages(activeConversation, targetMessageId);
removeConversationMessagesRef.current = removeConversationMessages; removeConversationMessagesRef.current = removeConversationMessages;
// Auto-focus the message input on conversation change (desktop only by default)
useEffect(() => {
if (!activeConversation) return;
if (activeConversation.type !== 'channel' && activeConversation.type !== 'contact') return;
// Repeaters show a login form, not a message input
if (activeConversation.type === 'contact') {
const contact = contacts.find((c) => c.public_key === activeConversation.id);
if (contact?.type === CONTACT_TYPE_REPEATER) return;
}
if (!shouldAutoFocusInput()) return;
// Defer to let the input mount/render first
const raf = requestAnimationFrame(() => messageInputRef.current?.focus?.());
return () => cancelAnimationFrame(raf);
}, [activeConversation?.id]); // eslint-disable-line react-hooks/exhaustive-deps
// Room servers replay stored history as a burst of DMs, all arriving with similar received_at // Room servers replay stored history as a burst of DMs, all arriving with similar received_at
// but spanning a wide range of sender_timestamps. Sort by sender_timestamp for room contacts // but spanning a wide range of sender_timestamps. Sort by sender_timestamp for room contacts
// so the display reflects the original send order rather than our radio's receipt order. // so the display reflects the original send order rather than our radio's receipt order.
+4
View File
@@ -44,6 +44,7 @@ type LimitState = 'normal' | 'warning' | 'danger' | 'error';
export interface MessageInputHandle { export interface MessageInputHandle {
appendText: (text: string) => void; appendText: (text: string) => void;
focus: () => void;
} }
export const MessageInput = forwardRef<MessageInputHandle, MessageInputProps>(function MessageInput( export const MessageInput = forwardRef<MessageInputHandle, MessageInputProps>(function MessageInput(
@@ -60,6 +61,9 @@ export const MessageInput = forwardRef<MessageInputHandle, MessageInputProps>(fu
// Focus the input after appending // Focus the input after appending
inputRef.current?.focus(); inputRef.current?.focus();
}, },
focus: () => {
inputRef.current?.focus();
},
})); }));
// Calculate character limits based on conversation type // Calculate character limits based on conversation type
+2 -1
View File
@@ -2,6 +2,7 @@ import { useCallback, type FormEvent } from 'react';
import { Input } from './ui/input'; import { Input } from './ui/input';
import { Button } from './ui/button'; import { Button } from './ui/button';
import { Checkbox } from './ui/checkbox'; import { Checkbox } from './ui/checkbox';
import { shouldAutoFocusInput } from '../utils/autoFocusInput';
interface RepeaterLoginProps { interface RepeaterLoginProps {
repeaterName: string; repeaterName: string;
@@ -64,7 +65,7 @@ export function RepeaterLogin({
placeholder={passwordPlaceholder} placeholder={passwordPlaceholder}
aria-label="Repeater password" aria-label="Repeater password"
disabled={loading} disabled={loading}
autoFocus autoFocus={shouldAutoFocusInput()}
/> />
<label <label
@@ -27,6 +27,7 @@ import {
getSavedFontScale, getSavedFontScale,
setSavedFontScale, setSavedFontScale,
} from '../../utils/fontScale'; } from '../../utils/fontScale';
import { getAutoFocusInputEnabled, setAutoFocusInputEnabled } from '../../utils/autoFocusInput';
export function SettingsLocalSection({ export function SettingsLocalSection({
onLocalLabelChange, onLocalLabelChange,
@@ -48,6 +49,7 @@ export function SettingsLocalSection({
}); });
const [localLabelText, setLocalLabelText] = useState(() => getLocalLabel().text); const [localLabelText, setLocalLabelText] = useState(() => getLocalLabel().text);
const [localLabelColor, setLocalLabelColor] = useState(() => getLocalLabel().color); const [localLabelColor, setLocalLabelColor] = useState(() => getLocalLabel().color);
const [autoFocusInput, setAutoFocusInput] = useState(getAutoFocusInputEnabled);
const [fontScale, setFontScale] = useState(getSavedFontScale); const [fontScale, setFontScale] = useState(getSavedFontScale);
const [fontScaleSlider, setFontScaleSlider] = useState(getSavedFontScale); const [fontScaleSlider, setFontScaleSlider] = useState(getSavedFontScale);
const [fontScaleInput, setFontScaleInput] = useState(() => String(getSavedFontScale())); const [fontScaleInput, setFontScaleInput] = useState(() => String(getSavedFontScale()));
@@ -129,6 +131,76 @@ export function SettingsLocalSection({
<Separator /> <Separator />
<div className="space-y-3">
<Label htmlFor="distance-units">Distance Units</Label>
<select
id="distance-units"
value={distanceUnit}
onChange={(event) => {
const nextUnit = event.target.value as (typeof DISTANCE_UNITS)[number];
setSavedDistanceUnit(nextUnit);
setDistanceUnit(nextUnit);
}}
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
>
{DISTANCE_UNITS.map((unit) => (
<option key={unit} value={unit}>
{DISTANCE_UNIT_LABELS[unit]}
</option>
))}
</select>
<p className="text-xs text-muted-foreground">
Controls how distances are shown throughout the app.
</p>
</div>
<Separator />
<div className="space-y-3">
<Label>UI Tweaks</Label>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={reopenLastConversation}
onChange={(e) => handleToggleReopenLastConversation(e.target.checked)}
className="w-4 h-4 rounded border-input accent-primary"
/>
<span className="text-sm">Reopen to last viewed channel/conversation</span>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={darkMap}
onChange={(e) => {
const v = e.target.checked;
setDarkMap(v);
try {
localStorage.setItem('remoteterm-dark-map', String(v));
} catch {
// localStorage may be disabled
}
}}
className="w-4 h-4 rounded border-input accent-primary"
/>
<span className="text-sm">Dark mode map tiles</span>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={autoFocusInput}
onChange={(e) => {
const v = e.target.checked;
setAutoFocusInput(v);
setAutoFocusInputEnabled(v);
}}
className="w-4 h-4 rounded border-input accent-primary"
/>
<span className="text-sm">Auto-focus input on conversation load (desktop only)</span>
</label>
<div className="space-y-3"> <div className="space-y-3">
<Label htmlFor="font-scale-input">Relative Font Size</Label> <Label htmlFor="font-scale-input">Relative Font Size</Label>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center"> <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
@@ -201,65 +273,11 @@ export function SettingsLocalSection({
</button> </button>
</div> </div>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Scales the app&apos;s typography for this browser only. The slider moves in 5% steps; the Scales the app&apos;s typography for this browser only. The slider moves in 5% steps;
number field accepts any value from 25% to 400%. the number field accepts any value from 25% to 400%.
</p> </p>
</div> </div>
<Separator />
<div className="space-y-3">
<Label htmlFor="distance-units">Distance Units</Label>
<select
id="distance-units"
value={distanceUnit}
onChange={(event) => {
const nextUnit = event.target.value as (typeof DISTANCE_UNITS)[number];
setSavedDistanceUnit(nextUnit);
setDistanceUnit(nextUnit);
}}
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
>
{DISTANCE_UNITS.map((unit) => (
<option key={unit} value={unit}>
{DISTANCE_UNIT_LABELS[unit]}
</option>
))}
</select>
<p className="text-xs text-muted-foreground">
Controls how distances are shown throughout the app.
</p>
</div> </div>
<Separator />
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={reopenLastConversation}
onChange={(e) => handleToggleReopenLastConversation(e.target.checked)}
className="w-4 h-4 rounded border-input accent-primary"
/>
<span className="text-sm">Reopen to last viewed channel/conversation</span>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={darkMap}
onChange={(e) => {
const v = e.target.checked;
setDarkMap(v);
try {
localStorage.setItem('remoteterm-dark-map', String(v));
} catch {
// localStorage may be disabled
}
}}
className="w-4 h-4 rounded border-input accent-primary"
/>
<span className="text-sm">Dark mode map tiles</span>
</label>
</div> </div>
); );
} }
@@ -65,7 +65,7 @@ function createArgs(overrides: Partial<Parameters<typeof useConversationActions>
setContacts: vi.fn(), setContacts: vi.fn(),
setChannels: vi.fn(), setChannels: vi.fn(),
observeMessage: vi.fn(() => ({ added: true, activeConversation: true })), observeMessage: vi.fn(() => ({ added: true, activeConversation: true })),
messageInputRef: { current: { appendText: vi.fn() } }, messageInputRef: { current: { appendText: vi.fn(), focus: vi.fn() } },
...overrides, ...overrides,
}; };
} }
+31
View File
@@ -0,0 +1,31 @@
const KEY = 'remoteterm-auto-focus-input';
export function getAutoFocusInputEnabled(): boolean {
try {
const raw = localStorage.getItem(KEY);
return raw === null || raw !== 'false';
} catch {
return true;
}
}
export function setAutoFocusInputEnabled(enabled: boolean): void {
try {
if (enabled) {
localStorage.removeItem(KEY);
} else {
localStorage.setItem(KEY, 'false');
}
} catch {
// localStorage may be unavailable
}
}
/**
* Returns true when auto-focus should fire: the setting is enabled
* AND the viewport is wide enough that focusing won't summon a
* mobile keyboard (matches the md: Tailwind breakpoint).
*/
export function shouldAutoFocusInput(): boolean {
return getAutoFocusInputEnabled() && window.innerWidth >= 768;
}