Smooth share-link drawer opening; number fields can be cleared
- Share links: opening the assistant focused its composer while the drawer was still sliding in from off-screen, so the browser scrolled the whole page 680px sideways and back. The composer now focuses without scrolling, and both page rows clip sideways overflow so a sliding drawer can never widen or scroll the page. - Number fields clamped on every keystroke, so clearing one snapped it to its minimum (1, or 256 for max output tokens). A shared NumberInput keeps the text as typed while focused, passes on in-range values as they are typed, and fits the value into its limits when the field is left or Enter is pressed (an empty field returns to its last value). Used for question and card counts, med math count, timers, review limits, template counts and model settings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f738fbe7be
commit
0ad6290250
10 changed files with 101 additions and 21 deletions
|
|
@ -577,7 +577,7 @@ export function Shell() {
|
||||||
const showDrawer = assistantOpen && isDesktop && !onAssistantPage;
|
const showDrawer = assistantOpen && isDesktop && !onAssistantPage;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-dvh">
|
<div className="flex min-h-dvh overflow-x-clip">
|
||||||
<a href="#main" className="sr-only focus:not-sr-only focus:fixed focus:top-3 focus:left-3 focus:z-[90] focus:rounded-lg focus:bg-ink focus:px-3 focus:py-2 focus:text-paper">
|
<a href="#main" className="sr-only focus:not-sr-only focus:fixed focus:top-3 focus:left-3 focus:z-[90] focus:rounded-lg focus:bg-ink focus:px-3 focus:py-2 focus:text-paper">
|
||||||
Skip to content
|
Skip to content
|
||||||
</a>
|
</a>
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import { McpSettings } from './McpSettings';
|
||||||
import { SemanticSettings } from './SemanticSettings';
|
import { SemanticSettings } from './SemanticSettings';
|
||||||
import { REASONING_EFFORTS, type AdapterMeta, type AiModel, type AiStatus, type Provider, type ProviderKind, type TaskConfig, type TaskName, type TaskSettings } from '@/lib/types';
|
import { REASONING_EFFORTS, type AdapterMeta, type AiModel, type AiStatus, type Provider, type ProviderKind, type TaskConfig, type TaskName, type TaskSettings } from '@/lib/types';
|
||||||
import { cx, formatCost, formatTokens, plural, timeAgo } from '@/lib/util';
|
import { cx, formatCost, formatTokens, plural, timeAgo } from '@/lib/util';
|
||||||
import { Badge, Button, Callout, Dialog, EmptyState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Section, Select, Skeleton, Switch, Textarea, Tooltip, useConfirm } from '@/ui';
|
import { Badge, Button, Callout, Dialog, EmptyState, Field, IconButton, Input, NumberInput, Menu, MenuItem, MenuSeparator, Section, Select, Skeleton, Switch, Textarea, Tooltip, useConfirm } from '@/ui';
|
||||||
|
|
||||||
interface Meta {
|
interface Meta {
|
||||||
adapters: AdapterMeta[];
|
adapters: AdapterMeta[];
|
||||||
|
|
@ -558,10 +558,10 @@ function TaskRow({
|
||||||
</Select>
|
</Select>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Temperature" hint={model && !model.capabilities.temperature ? 'Ignored by this model' : '0 to 2'}>
|
<Field label="Temperature" hint={model && !model.capabilities.temperature ? 'Ignored by this model' : '0 to 2'}>
|
||||||
<Input type="number" min={0} max={2} step={0.1} value={config.temperature ?? ''} placeholder={same ?? 'Model default'} onChange={(e) => onChange({ ...config, temperature: e.target.value === '' ? null : Math.max(0, Math.min(2, Number(e.target.value))) })} />
|
<NumberInput min={0} max={2} step={0.1} integer={false} allowEmpty value={config.temperature ?? null} placeholder={same ?? 'Model default'} onValueChange={(n) => onChange({ ...config, temperature: n })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Output limit" hint="Tokens per response">
|
<Field label="Output limit" hint="Tokens per response">
|
||||||
<Input type="number" min={256} step={256} value={config.maxOutputTokens ?? ''} placeholder={same ?? 'Automatic'} onChange={(e) => onChange({ ...config, maxOutputTokens: e.target.value === '' ? null : Math.max(256, Math.round(Number(e.target.value))) })} />
|
<NumberInput min={256} step={256} allowEmpty value={config.maxOutputTokens ?? null} placeholder={same ?? 'Automatic'} onValueChange={(n) => onChange({ ...config, maxOutputTokens: n })} />
|
||||||
</Field>
|
</Field>
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import { api, errorMessage } from '@/lib/api';
|
||||||
import { qk, useAiModels, useAiStatus, useClass } from '@/lib/queries';
|
import { qk, useAiModels, useAiStatus, useClass } from '@/lib/queries';
|
||||||
import type { DocumentItem, Template } from '@/lib/types';
|
import type { DocumentItem, Template } from '@/lib/types';
|
||||||
import { cx, formatTokens, useLocalStorage } from '@/lib/util';
|
import { cx, formatTokens, useLocalStorage } from '@/lib/util';
|
||||||
import { Button, Callout, Dialog, Field, Input, Segmented, Select, Switch, Textarea } from '@/ui';
|
import { Button, Callout, Dialog, Field, Input, NumberInput, Segmented, Select, Switch, Textarea } from '@/ui';
|
||||||
|
|
||||||
export interface GeneratePreset {
|
export interface GeneratePreset {
|
||||||
kind?: 'quiz' | 'deck' | 'note';
|
kind?: 'quiz' | 'deck' | 'note';
|
||||||
|
|
@ -273,7 +273,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
{!fixedSource && (
|
{!fixedSource && (
|
||||||
<Field label="Questions">
|
<Field label="Questions">
|
||||||
<Input type="number" min={1} max={100} value={count} onChange={(e) => setCount(Math.max(1, Math.min(100, Number(e.target.value) || 1)))} />
|
<NumberInput min={1} max={100} value={count} onValueChange={(n) => n !== null && setCount(n)} />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
<Field label="Difficulty">
|
<Field label="Difficulty">
|
||||||
|
|
@ -293,7 +293,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
||||||
</div>
|
</div>
|
||||||
{mathOn && (
|
{mathOn && (
|
||||||
<Field label="How many" className="w-24 shrink-0">
|
<Field label="How many" className="w-24 shrink-0">
|
||||||
<Input type="number" min={1} max={Math.min(25, count)} value={mathCount} onChange={(e) => setMathCount(Math.max(1, Math.min(25, Number(e.target.value) || 1)))} aria-label="Med math questions" />
|
<NumberInput min={1} max={25} value={mathCount} onValueChange={(n) => n !== null && setMathCount(n)} aria-label="Med math questions" />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -306,7 +306,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
{!fixedSource && (
|
{!fixedSource && (
|
||||||
<Field label="Cards">
|
<Field label="Cards">
|
||||||
<Input type="number" min={1} max={200} value={count} onChange={(e) => setCount(Math.max(1, Math.min(200, Number(e.target.value) || 1)))} />
|
<NumberInput min={1} max={200} value={count} onValueChange={(n) => n !== null && setCount(n)} />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
<Field label="Card style">
|
<Field label="Card style">
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ export function SharedAssistant({ token, title, item, hidden }: { token: string;
|
||||||
if (el && stick.current) el.scrollTop = el.scrollHeight;
|
if (el && stick.current) el.scrollTop = el.scrollHeight;
|
||||||
}, [turns, open]);
|
}, [turns, open]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open && !hidden) inputRef.current?.focus();
|
if (open && !hidden) inputRef.current?.focus({ preventScroll: true }); // the drawer is still sliding in from off-screen
|
||||||
}, [open, hidden]);
|
}, [open, hidden]);
|
||||||
|
|
||||||
const send = useCallback(
|
const send = useCallback(
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import { useEffect, useState } from 'react';
|
||||||
import { api, errorMessage } from '@/lib/api';
|
import { api, errorMessage } from '@/lib/api';
|
||||||
import type { PublicCollection, SharedGenerated } from '@/lib/types';
|
import type { PublicCollection, SharedGenerated } from '@/lib/types';
|
||||||
import { cx } from '@/lib/util';
|
import { cx } from '@/lib/util';
|
||||||
import { Button, Callout, Dialog, Field, IconButton, Input, ProgressBar, Segmented, Select, Switch } from '@/ui';
|
import { Button, Callout, Dialog, Field, IconButton, Input, NumberInput, ProgressBar, Segmented, Select, Switch } from '@/ui';
|
||||||
|
|
||||||
type Kind = 'quiz' | 'deck';
|
type Kind = 'quiz' | 'deck';
|
||||||
|
|
||||||
|
|
@ -212,7 +212,7 @@ function GenerateDialog({
|
||||||
)}
|
)}
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
<Field label={kind === 'quiz' ? `Questions (max ${max})` : `Cards (max ${max})`}>
|
<Field label={kind === 'quiz' ? `Questions (max ${max})` : `Cards (max ${max})`}>
|
||||||
<Input type="number" min={1} max={max} value={count} onChange={(e) => setCount(Math.max(1, Math.min(max, Number(e.target.value) || 1)))} />
|
<NumberInput min={1} max={max} value={count} onValueChange={(n) => n !== null && setCount(n)} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Difficulty">
|
<Field label="Difficulty">
|
||||||
<Select value={difficulty} onChange={(e) => setDifficulty(e.target.value as typeof difficulty)}>
|
<Select value={difficulty} onChange={(e) => setDifficulty(e.target.value as typeof difficulty)}>
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import { api, errorMessage } from '@/lib/api';
|
||||||
import { qk, useRefresh } from '@/lib/queries';
|
import { qk, useRefresh } from '@/lib/queries';
|
||||||
import type { Template } from '@/lib/types';
|
import type { Template } from '@/lib/types';
|
||||||
import { cx, plural } from '@/lib/util';
|
import { cx, plural } from '@/lib/util';
|
||||||
import { Badge, Button, Dialog, Field, IconButton, Input, Section, Segmented, Select, Skeleton, Textarea, useConfirm } from '@/ui';
|
import { Badge, Button, Dialog, Field, IconButton, Input, NumberInput, Section, Segmented, Select, Skeleton, Textarea, useConfirm } from '@/ui';
|
||||||
|
|
||||||
/* ------------------------------ shared text editor ------------------------------ */
|
/* ------------------------------ shared text editor ------------------------------ */
|
||||||
|
|
||||||
|
|
@ -198,7 +198,7 @@ function PresetDialog({ template, onClose }: { template: Template | null; onClos
|
||||||
/>
|
/>
|
||||||
{kind !== 'note' && (
|
{kind !== 'note' && (
|
||||||
<Field label={kind === 'quiz' ? 'Questions' : 'Cards'}>
|
<Field label={kind === 'quiz' ? 'Questions' : 'Cards'}>
|
||||||
<Input type="number" min={1} max={200} value={payload.count ?? (kind === 'quiz' ? 15 : 30)} onChange={(e) => set({ count: Math.max(1, Math.min(200, Number(e.target.value) || 1)) })} className="w-28" />
|
<NumberInput min={1} max={200} value={payload.count ?? (kind === 'quiz' ? 15 : 30)} onValueChange={(n) => n !== null && set({ count: n })} className="w-28" />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
{kind === 'quiz' && (
|
{kind === 'quiz' && (
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ import { cx, downloadFile, formatDateTime, formatMinutes, gradeTone, pct, plural
|
||||||
import { Markdown } from '@/ui/Markdown';
|
import { Markdown } from '@/ui/Markdown';
|
||||||
import { formatRationale } from '@shared/rationale';
|
import { formatRationale } from '@shared/rationale';
|
||||||
import { SortableList } from '@/ui/Sortable';
|
import { SortableList } from '@/ui/Sortable';
|
||||||
import { Badge, Button, Callout, ClassDot, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, Switch, Textarea, useConfirm } from '@/ui';
|
import { Badge, Button, Callout, ClassDot, Dialog, EmptyState, ErrorState, Field, IconButton, Input, NumberInput, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, Switch, Textarea, useConfirm } from '@/ui';
|
||||||
|
|
||||||
interface StartPrefs {
|
interface StartPrefs {
|
||||||
mode: 'practice' | 'exam';
|
mode: 'practice' | 'exam';
|
||||||
|
|
@ -79,7 +79,7 @@ function StartOptionsFields({ o }: { o: ReturnType<typeof useStartOptions> }) {
|
||||||
{timed && (
|
{timed && (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Timer className="size-4 text-ink-3" />
|
<Timer className="size-4 text-ink-3" />
|
||||||
<Input type="number" min={1} max={600} value={minutes} onChange={(e) => setMinutes(Math.max(1, Math.min(600, Number(e.target.value) || 1)))} className="w-24" aria-label="Minutes" />
|
<NumberInput min={1} max={600} value={minutes} onValueChange={(n) => n !== null && setMinutes(n)} className="w-24" aria-label="Minutes" />
|
||||||
<span className="text-sm text-ink-2">minutes</span>
|
<span className="text-sm text-ink-2">minutes</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import { api, ApiError, errorMessage, uploadWithProgress } from '@/lib/api';
|
||||||
import { qk, useRefresh } from '@/lib/queries';
|
import { qk, useRefresh } from '@/lib/queries';
|
||||||
import type { AppSettings, ShareAiSettings, ShareListItem, Template } from '@/lib/types';
|
import type { AppSettings, ShareAiSettings, ShareListItem, Template } from '@/lib/types';
|
||||||
import { copyText, cx, downloadFile, formatBytes, formatDateTime, plural, timeAgo, useDocumentTitle, useTheme } from '@/lib/util';
|
import { copyText, cx, downloadFile, formatBytes, formatDateTime, plural, timeAgo, useDocumentTitle, useTheme } from '@/lib/util';
|
||||||
import { Badge, Button, Callout, ClassDot, EmptyState, Field, IconButton, Input, PageHeader, PageLoading, ProgressBar, Section, Segmented, Select, Skeleton, Switch, useConfirm } from '@/ui';
|
import { Badge, Button, Callout, ClassDot, EmptyState, Field, IconButton, Input, NumberInput, PageHeader, PageLoading, ProgressBar, Section, Segmented, Select, Skeleton, Switch, useConfirm } from '@/ui';
|
||||||
|
|
||||||
const AiSettings = lazy(() => import('@/features/AiSettings'));
|
const AiSettings = lazy(() => import('@/features/AiSettings'));
|
||||||
|
|
||||||
|
|
@ -88,7 +88,7 @@ function StudySettings() {
|
||||||
<div className="text-sm font-medium">New cards per day</div>
|
<div className="text-sm font-medium">New cards per day</div>
|
||||||
<div className="text-[13px] text-ink-3">How many never-seen cards are introduced each day, across all decks. Reviews of cards you already know are never limited.</div>
|
<div className="text-[13px] text-ink-3">How many never-seen cards are introduced each day, across all decks. Reviews of cards you already know are never limited.</div>
|
||||||
</div>
|
</div>
|
||||||
<Input type="number" min={0} max={500} value={form.newCardsPerDay} onChange={(e) => setForm({ ...form, newCardsPerDay: Number(e.target.value) })} onBlur={() => save({ newCardsPerDay: Math.max(0, Math.min(500, Math.round(form.newCardsPerDay) || 0)) })} aria-label="New cards per day" />
|
<NumberInput min={0} max={500} value={form.newCardsPerDay} onValueChange={(n) => n !== null && setForm({ ...form, newCardsPerDay: n })} onCommit={(n) => n !== null && save({ newCardsPerDay: n })} aria-label="New cards per day" />
|
||||||
</div>
|
</div>
|
||||||
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_160px]">
|
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_160px]">
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -113,7 +113,7 @@ function StudySettings() {
|
||||||
<div className="text-sm font-medium">Daily goal</div>
|
<div className="text-sm font-medium">Daily goal</div>
|
||||||
<div className="text-[13px] text-ink-3">Cards reviewed plus questions answered that make a day count toward your streak.</div>
|
<div className="text-[13px] text-ink-3">Cards reviewed plus questions answered that make a day count toward your streak.</div>
|
||||||
</div>
|
</div>
|
||||||
<Input type="number" min={1} max={1000} value={form.dailyGoal} onChange={(e) => setForm({ ...form, dailyGoal: Number(e.target.value) })} onBlur={() => save({ dailyGoal: Math.max(1, Math.min(1000, Math.round(form.dailyGoal) || 1)) })} aria-label="Daily goal" />
|
<NumberInput min={1} max={1000} value={form.dailyGoal} onValueChange={(n) => n !== null && setForm({ ...form, dailyGoal: n })} onCommit={(n) => n !== null && save({ dailyGoal: n })} aria-label="Daily goal" />
|
||||||
</div>
|
</div>
|
||||||
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_260px]">
|
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_260px]">
|
||||||
<div>
|
<div>
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ import { api, ApiError } from '@/lib/api';
|
||||||
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, ShareAi, SnapshotQuestion } from '@/lib/types';
|
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, ShareAi, SnapshotQuestion } from '@/lib/types';
|
||||||
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useMediaQuery, useTheme } from '@/lib/util';
|
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useMediaQuery, useTheme } from '@/lib/util';
|
||||||
import { Markdown } from '@/ui/Markdown';
|
import { Markdown } from '@/ui/Markdown';
|
||||||
import { Badge, Button, EmptyState, IconButton, Input, PageLoading, Segmented, Switch } from '@/ui';
|
import { Badge, Button, EmptyState, IconButton, Input, NumberInput, PageLoading, Segmented, Switch } from '@/ui';
|
||||||
|
|
||||||
/* ------------------------------ frame ------------------------------ */
|
/* ------------------------------ frame ------------------------------ */
|
||||||
|
|
||||||
|
|
@ -275,7 +275,7 @@ function SharedQuiz({ quiz, storageKey, back, explainUrl, onImmersive }: { quiz:
|
||||||
{prefs.timed && (
|
{prefs.timed && (
|
||||||
<label className="flex items-center gap-2 text-sm text-ink-2">
|
<label className="flex items-center gap-2 text-sm text-ink-2">
|
||||||
<Timer className="size-4 text-ink-3" />
|
<Timer className="size-4 text-ink-3" />
|
||||||
<Input type="number" min={1} max={600} value={minutes} onChange={(e) => setPrefs((p) => ({ ...p, minutes: Math.max(1, Math.min(600, Math.round(Number(e.target.value)) || 1)) }))} className="w-24" aria-label="Minutes" />
|
<NumberInput min={1} max={600} value={minutes} onValueChange={(n) => n !== null && setPrefs((p) => ({ ...p, minutes: n }))} className="w-24" aria-label="Minutes" />
|
||||||
minutes
|
minutes
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
|
@ -593,8 +593,9 @@ export default function SharedPage() {
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
// A row, so the assistant drawer can sit beside the page on wide screens (it floats over it below 1360px).
|
// A row, so the assistant drawer can sit beside the page on wide screens (it floats over it below 1360px).
|
||||||
|
// Clipped sideways so the drawer sliding in from off-screen never widens or scrolls the page.
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-dvh">
|
<div className="flex min-h-dvh overflow-x-clip">
|
||||||
<div className="min-w-0 flex-1">{page}</div>
|
<div className="min-w-0 flex-1">{page}</div>
|
||||||
{assistant}
|
{assistant}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -123,6 +123,85 @@ export const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputE
|
||||||
return <input ref={ref} className={cx(CONTROL, 'h-10', className)} {...rest} />;
|
return <input ref={ref} className={cx(CONTROL, 'h-10', className)} {...rest} />;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** Fits a typed number into a field's limits; null when the text is not a number. */
|
||||||
|
export function settleNumber(text: string, opts: { min?: number; max?: number; integer?: boolean }): number | null {
|
||||||
|
if (text.trim() === '') return null;
|
||||||
|
const n = Number(text);
|
||||||
|
if (!Number.isFinite(n)) return null;
|
||||||
|
const whole = opts.integer === false ? n : Math.round(n);
|
||||||
|
return Math.min(opts.max ?? Infinity, Math.max(opts.min ?? -Infinity, whole));
|
||||||
|
}
|
||||||
|
|
||||||
|
type NumberInputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange' | 'type' | 'min' | 'max'> & {
|
||||||
|
value: number | null;
|
||||||
|
min?: number;
|
||||||
|
max?: number;
|
||||||
|
/** Whole numbers only (the default). */
|
||||||
|
integer?: boolean;
|
||||||
|
/** An empty field means "no value" (null) instead of going back to the last number. */
|
||||||
|
allowEmpty?: boolean;
|
||||||
|
/** Every value within the limits as it is typed, and the settled value when the field is left. */
|
||||||
|
onValueChange: (value: number | null) => void;
|
||||||
|
/** The settled value when the field is left or Enter is pressed (for fields that save on blur). */
|
||||||
|
onCommit?: (value: number | null) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A number field that can be cleared and retyped freely. While it has focus the text is kept as
|
||||||
|
* typed (empty, or out of range part-way through "150"); values within the limits are passed on
|
||||||
|
* as they are typed. On leaving the field (or Enter) the value is fitted into the limits, and an
|
||||||
|
* empty field goes back to the last value unless `allowEmpty`.
|
||||||
|
*/
|
||||||
|
export const NumberInput = forwardRef<HTMLInputElement, NumberInputProps>(function NumberInput(
|
||||||
|
{ value, min, max, integer = true, allowEmpty = false, onValueChange, onCommit, onBlur, onKeyDown, onFocus, ...rest },
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
const [draft, setDraft] = useState<string | null>(null);
|
||||||
|
const shown = draft ?? (value === null ? '' : String(value));
|
||||||
|
const settle = () => {
|
||||||
|
if (draft === null) return;
|
||||||
|
const fitted = settleNumber(draft, { min, max, integer });
|
||||||
|
const next = fitted ?? (allowEmpty ? null : value);
|
||||||
|
setDraft(null);
|
||||||
|
if (next !== value) onValueChange(next);
|
||||||
|
onCommit?.(next);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Input
|
||||||
|
ref={ref}
|
||||||
|
type="number"
|
||||||
|
inputMode={integer ? 'numeric' : 'decimal'}
|
||||||
|
min={min}
|
||||||
|
max={max}
|
||||||
|
value={shown}
|
||||||
|
onFocus={(e) => {
|
||||||
|
setDraft(shown);
|
||||||
|
onFocus?.(e);
|
||||||
|
}}
|
||||||
|
onChange={(e) => {
|
||||||
|
const text = e.target.value;
|
||||||
|
setDraft(text);
|
||||||
|
if (text.trim() === '') {
|
||||||
|
if (allowEmpty && value !== null) onValueChange(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const n = Number(text);
|
||||||
|
const whole = integer ? Math.round(n) : n;
|
||||||
|
if (Number.isFinite(n) && whole >= (min ?? -Infinity) && whole <= (max ?? Infinity) && whole !== value) onValueChange(whole);
|
||||||
|
}}
|
||||||
|
onBlur={(e) => {
|
||||||
|
settle();
|
||||||
|
onBlur?.(e);
|
||||||
|
}}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') settle();
|
||||||
|
onKeyDown?.(e);
|
||||||
|
}}
|
||||||
|
{...rest}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement> & { autoGrow?: boolean; maxRows?: number }>(function Textarea(
|
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement> & { autoGrow?: boolean; maxRows?: number }>(function Textarea(
|
||||||
{ className, autoGrow, maxRows = 16, onChange, value, rows = 3, ...rest },
|
{ className, autoGrow, maxRows = 16, onChange, value, rows = 3, ...rest },
|
||||||
ref,
|
ref,
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue