A local-first personal finance app
Fix InitialFocus not working on some fields (#5987)
Joel Jeremy Marquezcf8a4b6e6a68
diff --git a/packages/component-library/src/InitialFocus.ts b/packages/component-library/src/InitialFocus.tsindex d87c48ea5a..ff8f182419 100644--- a/packages/component-library/src/InitialFocus.ts+++ b/packages/component-library/src/InitialFocus.ts@@ -4,6 +4,7 @@ import {isValidElement,type ReactElement,Ref,+ RefObject,useEffect,useRef,} from 'react';@@ -11,15 +12,20 @@ import {type InitialFocusProps<T extends HTMLElement> = {/*** The child element to focus when the component mounts. This can be either a single React element or a function that returns a React element.+ * The child element should have a `ref` prop for this to work. For child components which receives a ref via another prop+ * e.g. `inputRef`, use a function as child and pass the ref to the appropriate prop.*/- children: ReactElement<{ ref: Ref<T> }> | ((ref: Ref<T>) => ReactElement);+ children:+ | ReactElement<{ ref: Ref<T> }>+ | ((ref: RefObject<T | null>) => ReactElement);};/*** InitialFocus sets focus on its child element* when it mounts.- * @param {Object} props - The component props.- * @param {ReactElement | function} props.children - A single React element or a function that returns a React element.+ * @param {ReactElement | function} children - A single React element or a function that returns a React element.+ * The child element should have a `ref` prop for this to work. For child components which receives a ref via another prop+ * e.g. `inputRef`, use a function as child and pass the ref to the appropriate prop.*/export function InitialFocus<T extends HTMLElement = HTMLElement>({children,diff --git a/packages/desktop-client/e2e/transactions.mobile.test.ts-snapshots/Mobile-Transactions-creates-a-transaction-via-footer-button-6-chromium-linux.png b/packages/desktop-client/e2e/transactions.mobile.test.ts-snapshots/Mobile-Transactions-creates-a-transaction-via-footer-button-6-chromium-linux.pngindex 8a21fdf5d3..06b8046d30 100644Binary files a/packages/desktop-client/e2e/transactions.mobile.test.ts-snapshots/Mobile-Transactions-creates-a-transaction-via-footer-button-6-chromium-linux.png and b/packages/desktop-client/e2e/transactions.mobile.test.ts-snapshots/Mobile-Transactions-creates-a-transaction-via-footer-button-6-chromium-linux.png differdiff --git a/packages/desktop-client/src/components/accounts/Header.tsx b/packages/desktop-client/src/components/accounts/Header.tsxindex 41eadac911..6f28d73a16 100644--- a/packages/desktop-client/src/components/accounts/Header.tsx+++ b/packages/desktop-client/src/components/accounts/Header.tsx@@ -387,7 +387,7 @@ export function AccountHeader({placeholder={t('Search')}value={search}onChange={onSearch}- inputRef={searchInput}+ ref={searchInput}// Remove marginRight magically being added by Stack...// We need to refactor the Stack componentstyle={{ marginRight: 0 }}diff --git a/packages/desktop-client/src/components/common/Search.tsx b/packages/desktop-client/src/components/common/Search.tsxindex 9373c79361..eca1b1b974 100644--- a/packages/desktop-client/src/components/common/Search.tsx+++ b/packages/desktop-client/src/components/common/Search.tsx@@ -10,7 +10,7 @@ import { View } from '@actual-app/components/view';import { css } from '@emotion/css';type SearchProps = {- inputRef?: Ref<HTMLInputElement>;+ ref?: Ref<HTMLInputElement>;value: string;onChange: (value: string) => void;placeholder: string;@@ -21,7 +21,7 @@ type SearchProps = {};export function Search({- inputRef,+ ref,value,onChange,placeholder,@@ -70,7 +70,7 @@ export function Search({/><Input- ref={inputRef}+ ref={ref}value={value}placeholder={placeholder}onEscape={() => onChange('')}diff --git a/packages/desktop-client/src/components/mobile/MobileForms.tsx b/packages/desktop-client/src/components/mobile/MobileForms.tsxindex 756c462017..3a5328be48 100644--- a/packages/desktop-client/src/components/mobile/MobileForms.tsx+++ b/packages/desktop-client/src/components/mobile/MobileForms.tsx@@ -1,7 +1,6 @@import React, {type ComponentPropsWithoutRef,type ComponentPropsWithRef,- forwardRef,type ReactNode,type CSSProperties,} from 'react';@@ -12,7 +11,7 @@ import { styles } from '@actual-app/components/styles';import { Text } from '@actual-app/components/text';import { theme } from '@actual-app/components/theme';import { Toggle } from '@actual-app/components/toggle';-import { css } from '@emotion/css';+import { css, cx } from '@emotion/css';type FieldLabelProps = {title: string;@@ -48,28 +47,32 @@ const valueStyle = {type InputFieldProps = ComponentPropsWithRef<typeof Input>;-export const InputField = forwardRef<HTMLInputElement, InputFieldProps>(- ({ disabled, style, onUpdate, ...props }, ref) => {- return (- <Input- ref={ref}- autoCorrect="false"- autoCapitalize="none"- disabled={disabled}- onUpdate={onUpdate}- style={{- ...valueStyle,- ...style,- color: disabled ? theme.tableTextInactive : theme.tableText,- backgroundColor: disabled- ? theme.formInputTextReadOnlySelection- : theme.tableBackground,- }}- {...props}- />- );- },-);+export function InputField({+ disabled,+ style,+ onUpdate,+ ref,+ ...props+}: InputFieldProps) {+ return (+ <Input+ ref={ref}+ autoCorrect="false"+ autoCapitalize="none"+ disabled={disabled}+ onUpdate={onUpdate}+ style={{+ ...valueStyle,+ ...style,+ color: disabled ? theme.tableTextInactive : theme.tableText,+ backgroundColor: disabled+ ? theme.formInputTextReadOnlySelection+ : theme.tableBackground,+ }}+ {...props}+ />+ );+}InputField.displayName = 'InputField';@@ -78,60 +81,63 @@ type TapFieldProps = ComponentPropsWithRef<typeof Button> & {textStyle?: CSSProperties;};-const defaultTapFieldStyle: ComponentPropsWithoutRef<- typeof Button->['style'] = ({ isDisabled, isPressed, isHovered }) => ({- ...valueStyle,- flexDirection: 'row',- alignItems: 'center',- backgroundColor: theme.tableBackground,- ...(isDisabled && {- backgroundColor: theme.formInputTextReadOnlySelection,- }),- ...(isPressed- ? {- opacity: 0.5,- boxShadow: 'none',- }- : {}),- ...(isHovered- ? {- boxShadow: 'none',- }- : {}),-});+const defaultTapFieldClassName = () =>+ css({+ ...valueStyle,+ flexDirection: 'row',+ alignItems: 'center',+ backgroundColor: theme.tableBackground,+ '&[data-disabled]': {+ backgroundColor: theme.formInputTextReadOnlySelection,+ },+ '&[data-pressed]': {+ opacity: 0.5,+ boxShadow: 'none',+ },+ '&[data-hovered]': {+ boxShadow: 'none',+ },+ });-export const TapField = forwardRef<HTMLButtonElement, TapFieldProps>(- ({ value, children, rightContent, style, textStyle, ...props }, ref) => {- return (- <Button- ref={ref}- bounce={false}- style={renderProps => ({- ...defaultTapFieldStyle(renderProps),- ...(typeof style === 'function' ? style(renderProps) : style),- })}- {...props}- >- {children ? (- children- ) : (- <Text- style={{- flex: 1,- userSelect: 'none',- textAlign: 'left',- ...textStyle,- }}- >- {value}- </Text>- )}- {!props.isDisabled && rightContent}- </Button>- );- },-);+export function TapField({+ value,+ children,+ className,+ rightContent,+ textStyle,+ ref,+ ...props+}: TapFieldProps) {+ return (+ <Button+ ref={ref}+ bounce={false}+ className={renderProps =>+ cx(+ defaultTapFieldClassName(),+ typeof className === 'function' ? className(renderProps) : className,+ )+ }+ {...props}+ >+ {children ? (+ children+ ) : (+ <Text+ style={{+ flex: 1,+ userSelect: 'none',+ textAlign: 'left',+ ...textStyle,+ }}+ >+ {value}+ </Text>+ )}+ {!props.isDisabled && rightContent}+ </Button>+ );+}TapField.displayName = 'TapField';diff --git a/packages/desktop-client/src/components/modals/CoverModal.tsx b/packages/desktop-client/src/components/modals/CoverModal.tsxindex d6751c0b17..77d6c79b19 100644--- a/packages/desktop-client/src/components/modals/CoverModal.tsx+++ b/packages/desktop-client/src/components/modals/CoverModal.tsx@@ -1,7 +1,8 @@-import React, { useCallback, useMemo, useState } from 'react';+import React, { useCallback, useEffect, useMemo, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';+import { InitialFocus } from '@actual-app/components/initial-focus';import { styles } from '@actual-app/components/styles';import { View } from '@actual-app/components/view';@@ -19,6 +20,7 @@ import {TapField,} from '@desktop-client/components/mobile/MobileForms';import { useCategories } from '@desktop-client/hooks/useCategories';+import { useInitialMount } from '@desktop-client/hooks/useInitialMount';import {type Modal as ModalType,pushModal,@@ -54,7 +56,7 @@ export function CoverModal({const [fromCategoryId, setFromCategoryId] = useState<string | null>(null);const dispatch = useDispatch();- const onCategoryClick = useCallback(() => {+ const openCategoryModal = useCallback(() => {dispatch(pushModal({modal: {@@ -79,6 +81,13 @@ export function CoverModal({const fromCategory = categories.find(c => c.id === fromCategoryId);+ const isInitialMount = useInitialMount();+ useEffect(() => {+ if (isInitialMount) {+ openCategoryModal();+ }+ }, [isInitialMount, openCategoryModal]);+return (<Modal name="cover">{({ state: { close } }) => (@@ -89,7 +98,13 @@ export function CoverModal({/><View><FieldLabel title={t('Cover from a category:')} />- <TapField value={fromCategory?.name} onPress={onCategoryClick} />+ <InitialFocus>+ <TapField+ autoFocus+ value={fromCategory?.name}+ onPress={openCategoryModal}+ />+ </InitialFocus></View><Viewdiff --git a/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx b/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsxindex c1ae6d4c23..b93c079778 100644--- a/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx+++ b/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx@@ -446,28 +446,25 @@ export function KeyboardShortcutModal() {padding: '0 16px 16px 16px',}}>- <InitialFocus<HTMLInputElement>>- {ref => (- <Search- inputRef={ref}- value={searchText}- isInModal- onChange={text => {- setSearchText(text);- // Clear category selection when searching to search all shortcuts- if (text && selectedCategoryId) {- setSelectedCategoryId(null);- }- }}- placeholder={t('Search shortcuts')}- width="100%"- style={{- backgroundColor: theme.tableBackground,- borderColor: theme.formInputBorder,- marginBottom: 10,- }}- />- )}+ <InitialFocus>+ <Search+ value={searchText}+ isInModal+ onChange={text => {+ setSearchText(text);+ // Clear category selection when searching to search all shortcuts+ if (text && selectedCategoryId) {+ setSelectedCategoryId(null);+ }+ }}+ placeholder={t('Search shortcuts')}+ width="100%"+ style={{+ backgroundColor: theme.tableBackground,+ borderColor: theme.formInputBorder,+ marginBottom: 10,+ }}+ /></InitialFocus><Viewstyle={{diff --git a/packages/desktop-client/src/components/schedules/ScheduleLink.tsx b/packages/desktop-client/src/components/schedules/ScheduleLink.tsxindex 197af9c53b..2919c09347 100644--- a/packages/desktop-client/src/components/schedules/ScheduleLink.tsx+++ b/packages/desktop-client/src/components/schedules/ScheduleLink.tsx@@ -51,7 +51,7 @@ export function ScheduleLink({statuses,} = useSchedules({ query: schedulesQuery });- const searchInput = useRef(null);+ const searchInput = useRef<HTMLInputElement | null>(null);async function onSelect(scheduleId: string) {if (ids?.length > 0) {@@ -105,15 +105,20 @@ export function ScheduleLink({{ count: ids?.length ?? 0 },)}</Text>- <InitialFocus>- <Search- inputRef={searchInput}- isInModal- width={300}- placeholder={t('Filter schedules…')}- value={filter}- onChange={setFilter}- />+ <InitialFocus<HTMLInputElement>>+ {node => (+ <Search+ ref={r => {+ node.current = r;+ searchInput.current = r;+ }}+ isInModal+ width={300}+ placeholder={t('Filter schedules…')}+ value={filter}+ onChange={setFilter}+ />+ )}</InitialFocus>{ids.length === 1 && (<Buttondiff --git a/packages/desktop-client/src/components/select/DateSelect.tsx b/packages/desktop-client/src/components/select/DateSelect.tsxindex dc2b520750..6dc72716cb 100644--- a/packages/desktop-client/src/components/select/DateSelect.tsx+++ b/packages/desktop-client/src/components/select/DateSelect.tsx@@ -1,6 +1,7 @@// @ts-strict-ignoreimport React, {forwardRef,+ type Ref,useEffect,useImperativeHandle,useLayoutEffect,@@ -9,7 +10,6 @@ import React, {useState,type ComponentProps,type KeyboardEvent,- type RefObject,} from 'react';import { useResponsive } from '@actual-app/components/hooks/useResponsive';@@ -45,6 +45,7 @@ import DateSelectRight from './DateSelect.right.png';import { InputField } from '@desktop-client/components/mobile/MobileForms';import { useLocale } from '@desktop-client/hooks/useLocale';+import { useMergedRefs } from '@desktop-client/hooks/useMergedRefs';import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';const pickerStyles: CSSProperties = {@@ -234,7 +235,7 @@ type DateSelectProps = {embedded?: boolean;dateFormat: string;openOnFocus?: boolean;- inputRef?: RefObject<HTMLInputElement>;+ ref?: Ref<HTMLInputElement>;shouldSaveFromKey?: (e: KeyboardEvent<HTMLInputElement>) => boolean;clearOnBlur?: boolean;onUpdate?: (selectedDate: string) => void;@@ -250,7 +251,7 @@ function DateSelectDesktop({embedded,dateFormat = 'yyyy-MM-dd',openOnFocus = true,- inputRef: originalInputRef,+ ref,shouldSaveFromKey = defaultShouldSaveFromKey,clearOnBlur = true,onUpdate,@@ -269,13 +270,8 @@ function DateSelectDesktop({const picker = useRef(null);const [value, setValue] = useState(parsedDefaultValue);const [open, setOpen] = useState(embedded || isOpen || false);- const inputRef = useRef(null);-- useLayoutEffect(() => {- if (originalInputRef) {- originalInputRef.current = inputRef.current;- }- }, []);+ const innerRef = useRef<HTMLInputElement | null>(null);+ const mergedRef = useMergedRefs<HTMLInputElement>(innerRef, ref);// This is confusing, so let me explain: `selectedValue` should be// renamed to `currentValue`. It represents the current highlighted@@ -366,8 +362,8 @@ function DateSelectDesktop({onKeyDown?.(e);} else if (!open) {setOpen(true);- if (inputRef.current) {- inputRef.current.setSelectionRange(0, 10000);+ if (innerRef.current) {+ innerRef.current.setSelectionRange(0, 10000);}}}@@ -383,7 +379,7 @@ function DateSelectDesktop({return (<Popover- triggerRef={inputRef}+ triggerRef={innerRef}placement="bottom start"offset={2}isOpen={open}@@ -402,7 +398,7 @@ function DateSelectDesktop({<Inputid={id}{...inputProps}- ref={inputRef}+ ref={mergedRef}value={value}onPointerUp={() => {if (!embedded) {diff --git a/packages/desktop-client/src/components/util/AmountInput.tsx b/packages/desktop-client/src/components/util/AmountInput.tsxindex 77816f9b79..0df36a379d 100644--- a/packages/desktop-client/src/components/util/AmountInput.tsx+++ b/packages/desktop-client/src/components/util/AmountInput.tsx@@ -23,7 +23,7 @@ import { useMergedRefs } from '@desktop-client/hooks/useMergedRefs';type AmountInputProps = {id?: string;- inputRef?: Ref<HTMLInputElement>;+ ref?: Ref<HTMLInputElement>;value: number;zeroSign?: '-' | '+';sign?: '-' | '+';@@ -42,7 +42,7 @@ type AmountInputProps = {export function AmountInput({id,- inputRef,+ ref,value: initialValue,zeroSign = '-', // + or -sign,@@ -83,13 +83,13 @@ export function AmountInput({[initialValue, isFocused, getDisplayValue],);- const buttonRef = useRef(null);- const ref = useRef<HTMLInputElement>(null);- const mergedRef = useMergedRefs<HTMLInputElement>(inputRef, ref);+ const buttonRef = useRef<HTMLButtonElement | null>(null);+ const innerRef = useRef<HTMLInputElement | null>(null);+ const mergedRef = useMergedRefs<HTMLInputElement>(ref, innerRef);useEffect(() => {if (focused) {- ref.current?.focus();+ innerRef.current?.focus();}}, [focused]);@@ -105,9 +105,11 @@ export function AmountInput({}, [symbol, value, format]);useEffect(() => {- if (ref.current) {+ if (innerRef.current) {(- ref.current as HTMLInputElement & { getCurrentAmount?: () => number }+ innerRef.current as HTMLInputElement & {+ getCurrentAmount?: () => number;+ }).getCurrentAmount = () => getAmount();}}, [getAmount]);@@ -156,7 +158,7 @@ export function AmountInput({}function onInputAmountBlur(e) {- if (!ref.current?.contains(e.relatedTarget)) {+ if (!innerRef.current?.contains(e.relatedTarget)) {const amount = getAmount();fireUpdate(amount);}diff --git a/packages/desktop-client/src/components/util/GenericInput.jsx b/packages/desktop-client/src/components/util/GenericInput.jsxindex cf8e13719e..4f1c3e7835 100644--- a/packages/desktop-client/src/components/util/GenericInput.jsx+++ b/packages/desktop-client/src/components/util/GenericInput.jsx@@ -67,7 +67,7 @@ export function GenericInput({case 'currency':return (<AmountInput- inputRef={ref}+ ref={ref}value={value}onUpdate={v => onChange(v)}sign={options?.inflow || options?.outflow ? '+' : undefined}@@ -269,7 +269,7 @@ export function GenericInput({value={value}dateFormat={dateFormat}openOnFocus={false}- inputRef={ref}+ ref={ref}inputProps={{ placeholder: dateFormat.toLowerCase() }}onSelect={onChange}/>diff --git a/packages/desktop-client/src/hooks/useMergedRefs.ts b/packages/desktop-client/src/hooks/useMergedRefs.tsindex 3c39084d82..1c9a54428a 100644--- a/packages/desktop-client/src/hooks/useMergedRefs.ts+++ b/packages/desktop-client/src/hooks/useMergedRefs.ts@@ -14,8 +14,8 @@ export function useMergedRefs<T>([...refs].forEach(ref => {if (typeof ref === 'function') {ref(value);- } else if (ref != null && 'current' in ref) {- (ref as RefObject<T>).current = value;+ } else if (ref != null) {+ ref.current = value;}});},diff --git a/upcoming-release-notes/5987.md b/upcoming-release-notes/5987.mdnew file mode 100644index 0000000000..0b0be67a6c--- /dev/null+++ b/upcoming-release-notes/5987.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [joel-jeremy]+---++Fix InitialFocus not working on some fields