A local-first personal finance app
Typescript: GenericInput (#5976)
Matiss Janis Aboltins88313c029b7b
diff --git a/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx b/packages/desktop-client/src/components/autocomplete/Autocomplete.tsxindex 584ff59823..d6f8de109d 100644--- a/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx+++ b/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx@@ -86,7 +86,7 @@ function getItemName<T extends AutocompleteItem>(return item.name || '';}-function getItemId<T extends AutocompleteItem>(item: T | T['id']) {+function getItemId<T extends AutocompleteItem>(item: T | NonNullable<T['id']>) {if (typeof item === 'string') {return item;}@@ -680,8 +680,8 @@ const defaultMultiAutocompleteInputClassName = css({type MultiAutocompleteProps<T extends AutocompleteItem> =CommonAutocompleteProps<T> & {type: 'multi';- onSelect: (ids: T['id'][], id?: T['id']) => void;- value: null | T[] | T['id'][];+ onSelect: (ids: NonNullable<T['id']>[], id?: NonNullable<T['id']>) => void;+ value: null | T[] | NonNullable<T['id']>[];};function MultiAutocomplete<T extends AutocompleteItem>({diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsxindex be189f4e5d..615a2359d6 100644--- a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx@@ -46,14 +46,13 @@ export const HistoricalAutomation = ({title={t('Number of months back')}htmlFor="look-back-field"/>- {/* @ts-expect-error should be auto-patched once GenericInput is converted to TS */}<GenericInputkey="look-back-input"type="number"value={template.type === 'average' ? template.numMonths : template.lookBack}- onChange={(value: number) =>+ onChange={value =>dispatch(updateTemplate(template.type === 'average'diff --git a/packages/desktop-client/src/components/filters/FiltersMenu.jsx b/packages/desktop-client/src/components/filters/FiltersMenu.jsxindex 1e17a1be90..8cacdac1a8 100644--- a/packages/desktop-client/src/components/filters/FiltersMenu.jsx+++ b/packages/desktop-client/src/components/filters/FiltersMenu.jsx@@ -240,8 +240,7 @@ function ConfigureField({{type !== 'boolean' && field !== 'payee' && (<GenericInputref={inputRef}- field={field}- subfield={subfield}+ field={field === 'date' ? subfield : field}type={type === 'id' &&(op === 'contains' ||@@ -252,7 +251,9 @@ function ConfigureField({: type}numberFormatType="currency"- value={formattedValue}+ value={+ formattedValue ?? (op === 'oneOf' || op === 'notOneOf' ? [] : '')+ }multi={op === 'oneOf' || op === 'notOneOf'}op={op}options={subfieldToOptions(field, subfield)}diff --git a/packages/desktop-client/src/components/reports/SaveReportChoose.tsx b/packages/desktop-client/src/components/reports/SaveReportChoose.tsxindex cc349d12d8..4b7a2a8752 100644--- a/packages/desktop-client/src/components/reports/SaveReportChoose.tsx+++ b/packages/desktop-client/src/components/reports/SaveReportChoose.tsx@@ -47,12 +47,10 @@ export function SaveReportChoose({ onApply }: SaveReportChooseProps) {<GenericInputref={inputRef}field="report"- subfield={null}type="saved"value={value}- multi={false}style={{ marginTop: 10 }}- onChange={(v: string) => setValue(v)}+ onChange={setValue}/><Viewdiff --git a/packages/desktop-client/src/components/rules/RuleEditor.tsx b/packages/desktop-client/src/components/rules/RuleEditor.tsxindex fe55fa05d0..daad645e6b 100644--- a/packages/desktop-client/src/components/rules/RuleEditor.tsx+++ b/packages/desktop-client/src/components/rules/RuleEditor.tsx@@ -321,12 +321,11 @@ function ConditionEditor({);} else {valueEditor = (- // @ts-expect-error fix this<GenericInputkey={inputKey}field={field}type={type}- value={value}+ value={value ?? ''}op={op}multi={op === 'oneOf' || op === 'notOneOf'}onChange={v => onChange('value', v)}@@ -535,12 +534,15 @@ function ActionEditor({onChange={v => onChange('formula', v, { formula: true })}/>) : (- // @ts-expect-error fix this<GenericInputkey={inputKey}+ // @ts-expect-error fix thisfield={field}+ // @ts-expect-error fix thistype={templated ? 'string' : type}+ // @ts-expect-error fix thisop={op}+ // @ts-expect-error fix thisvalue={options?.template ?? value}onChange={v => onChange('value', v)}numberFormatType="currency"@@ -644,9 +646,9 @@ function ActionEditor({}}>{options.method !== 'remainder' && (- // @ts-expect-error fix this<GenericInputkey={inputKey}+ // @ts-expect-error fix thisfield={field}op={op}type="number"@@ -680,9 +682,9 @@ function ActionEditor({/><View style={{ flex: 1 }}>- {/* @ts-expect-error fix this */}<GenericInputkey={inputKey}+ // @ts-expect-error fix thisfield={field}type="string"op={op}diff --git a/packages/desktop-client/src/components/schedules/ScheduleEditModal.tsx b/packages/desktop-client/src/components/schedules/ScheduleEditModal.tsxindex bd371204f7..affd3da711 100644--- a/packages/desktop-client/src/components/schedules/ScheduleEditModal.tsx+++ b/packages/desktop-client/src/components/schedules/ScheduleEditModal.tsx@@ -620,12 +620,9 @@ export function ScheduleEditModal({ id, transaction }: ScheduleEditModalProps) {<FormField style={{ flex: 1 }}><FormLabel title={t('Schedule Name')} htmlFor="name-field" /><InitialFocus>- {/* @ts-expect-error should be auto-patched once GenericInput is converted to TS */}<GenericInput- field="string"type="string"value={state.fields.name}- multi={false}onChange={e => {dispatch({ type: 'set-field', field: 'name', value: e });}}diff --git a/packages/desktop-client/src/components/util/GenericInput.jsx b/packages/desktop-client/src/components/util/GenericInput.jsxdeleted file mode 100644index 4f1c3e7835..0000000000--- a/packages/desktop-client/src/components/util/GenericInput.jsx+++ /dev/null@@ -1,320 +0,0 @@-import React from 'react';-import { useTranslation } from 'react-i18next';--import { useResponsive } from '@actual-app/components/hooks/useResponsive';-import { Input } from '@actual-app/components/input';-import { View } from '@actual-app/components/view';--import { getMonthYearFormat } from 'loot-core/shared/months';--import { AmountInput } from './AmountInput';-import { PercentInput } from './PercentInput';--import { AccountAutocomplete } from '@desktop-client/components/autocomplete/AccountAutocomplete';-import { Autocomplete } from '@desktop-client/components/autocomplete/Autocomplete';-import { CategoryAutocomplete } from '@desktop-client/components/autocomplete/CategoryAutocomplete';-import { FilterAutocomplete } from '@desktop-client/components/autocomplete/FilterAutocomplete';-import { PayeeAutocomplete } from '@desktop-client/components/autocomplete/PayeeAutocomplete';-import { ReportAutocomplete } from '@desktop-client/components/autocomplete/ReportAutocomplete';-import { Checkbox } from '@desktop-client/components/forms';-import { DateSelect } from '@desktop-client/components/select/DateSelect';-import { RecurringSchedulePicker } from '@desktop-client/components/select/RecurringSchedulePicker';-import { useCategories } from '@desktop-client/hooks/useCategories';-import { useDateFormat } from '@desktop-client/hooks/useDateFormat';-import { useReports } from '@desktop-client/hooks/useReports';-import { pushModal } from '@desktop-client/modals/modalsSlice';-import { useDispatch } from '@desktop-client/redux';--export function GenericInput({- field,- subfield,- type,- numberFormatType = undefined,- multi,- value,- ref,- style,- onChange,- op = undefined,- options = undefined,- inputStyle = undefined,-}) {- const dispatch = useDispatch();- const { isNarrowWidth } = useResponsive();- const { t } = useTranslation();- const { grouped: categoryGroups } = useCategories();- const { data: savedReports } = useReports();- const dateFormat = useDateFormat() || 'MM/dd/yyyy';-- // Helper function to open autocomplete modal with safe event handling- const openAutocompleteModal = modalName => {- dispatch(- pushModal({- modal: {- name: modalName,- options: {- onSelect: newValue => {- onChange(multi ? [...value, newValue] : newValue);- },- },- },- }),- );- };-- const getNumberInputByFormatType = numberFormatType => {- switch (numberFormatType) {- case 'currency':- return (- <AmountInput- ref={ref}- value={value}- onUpdate={v => onChange(v)}- sign={options?.inflow || options?.outflow ? '+' : undefined}- inputStyle={inputStyle}- />- );- case 'percentage':- return (- <PercentInput- inputRef={ref}- value={value}- onUpdatePercent={onChange}- inputStyle={inputStyle}- />- );- default:- return (- <Input- ref={ref}- value={value || ''}- placeholder={t('nothing')}- onChangeValue={onChange}- style={inputStyle}- />- );- }- };-- // This makes the UI more resilient in case of faulty data- if (multi && !Array.isArray(value)) {- value = [];- } else if (!multi && Array.isArray(value)) {- return null;- }-- const showPlaceholder = multi ? value.length === 0 : true;- const autocompleteType = multi ? 'multi' : 'single';-- let content;- switch (type) {- case 'id':- switch (field) {- case 'payee':- content = (- <PayeeAutocomplete- type={autocompleteType}- showMakeTransfer={false}- openOnFocus={!isNarrowWidth}- updateOnValueChange={isNarrowWidth}- value={value}- onSelect={onChange}- inputProps={{- ref,- ...(showPlaceholder ? { placeholder: t('nothing') } : null),- onClick: () => {- if (!isNarrowWidth) {- return;- }-- openAutocompleteModal('payee-autocomplete');- },- }}- />- );- break;-- case 'account':- switch (op) {- case 'onBudget':- case 'offBudget':- content = null;- break;- default:- content = (- <AccountAutocomplete- type={autocompleteType}- value={value}- openOnFocus={!isNarrowWidth}- updateOnValueChange={isNarrowWidth}- onSelect={onChange}- inputProps={{- ref,- ...(showPlaceholder ? { placeholder: t('nothing') } : null),- onClick: () => {- if (!isNarrowWidth) {- return;- }-- openAutocompleteModal('account-autocomplete');- },- }}- />- );- break;- }- break;-- case 'category':- content = (- <CategoryAutocomplete- type={autocompleteType}- categoryGroups={categoryGroups}- value={value}- openOnFocus={!isNarrowWidth}- updateOnValueChange={isNarrowWidth}- onSelect={onChange}- showHiddenCategories={true}- inputProps={{- ref,- ...(showPlaceholder ? { placeholder: t('nothing') } : null),- onClick: () => {- if (!isNarrowWidth) {- return;- }-- openAutocompleteModal('category-autocomplete');- },- }}- />- );- break;-- default:- }- break;-- case 'saved':- switch (field) {- case 'saved':- content = (- <FilterAutocomplete- type={autocompleteType}- value={value}- openOnFocus={true}- onSelect={onChange}- inputProps={{- ref,- ...(showPlaceholder ? { placeholder: t('nothing') } : null),- }}- />- );- break;- case 'report':- content = (- <ReportAutocomplete- type={autocompleteType}- saved={savedReports}- value={value}- openOnFocus={true}- onSelect={onChange}- inputProps={{- ref,- ...(showPlaceholder ? { placeholder: t('nothing') } : null),- }}- />- );- break;-- default:- }- break;-- case 'date':- switch (subfield) {- case 'month':- content = (- <Input- ref={ref}- value={value || ''}- placeholder={getMonthYearFormat(dateFormat).toLowerCase()}- onChangeValue={onChange}- />- );- break;-- case 'year':- content = (- <Input- ref={ref}- value={value || ''}- placeholder="yyyy"- onChangeValue={onChange}- />- );- break;-- default:- if (value && value.frequency) {- content = (- <RecurringSchedulePicker- value={value}- buttonStyle={{ justifyContent: 'flex-start' }}- onChange={onChange}- />- );- } else {- content = (- <DateSelect- value={value}- dateFormat={dateFormat}- openOnFocus={false}- ref={ref}- inputProps={{ placeholder: dateFormat.toLowerCase() }}- onSelect={onChange}- />- );- }- break;- }- break;-- case 'boolean':- content = (- <Checkbox- checked={value}- value={value}- onChange={() => onChange(!value)}- />- );- break;-- default:- if (multi) {- content = (- <Autocomplete- type={autocompleteType}- suggestions={[]}- value={value}- inputProps={{ ref }}- onSelect={onChange}- />- );- } else if (type === 'number') {- content = getNumberInputByFormatType(numberFormatType);- } else {- content = (- <Input- ref={ref}- value={value || ''}- placeholder={t('nothing')}- onChangeValue={onChange}- style={inputStyle}- />- );- }- break;- }-- return <View style={{ flex: 1, ...style }}>{content}</View>;-}diff --git a/packages/desktop-client/src/components/util/GenericInput.tsx b/packages/desktop-client/src/components/util/GenericInput.tsxnew file mode 100644index 0000000000..09b6f25718--- /dev/null+++ b/packages/desktop-client/src/components/util/GenericInput.tsx@@ -0,0 +1,450 @@+import { type JSX, type Ref } from 'react';+import { useTranslation } from 'react-i18next';++import { useResponsive } from '@actual-app/components/hooks/useResponsive';+import { Input } from '@actual-app/components/input';+import { type CSSProperties } from '@actual-app/components/styles';+import { View } from '@actual-app/components/view';++import { getMonthYearFormat } from 'loot-core/shared/months';+import { type RecurConfig, type RuleConditionOp } from 'loot-core/types/models';++import { AmountInput } from './AmountInput';+import { PercentInput } from './PercentInput';++import { AccountAutocomplete } from '@desktop-client/components/autocomplete/AccountAutocomplete';+import { Autocomplete } from '@desktop-client/components/autocomplete/Autocomplete';+import { CategoryAutocomplete } from '@desktop-client/components/autocomplete/CategoryAutocomplete';+import { FilterAutocomplete } from '@desktop-client/components/autocomplete/FilterAutocomplete';+import { PayeeAutocomplete } from '@desktop-client/components/autocomplete/PayeeAutocomplete';+import { ReportAutocomplete } from '@desktop-client/components/autocomplete/ReportAutocomplete';+import { Checkbox } from '@desktop-client/components/forms';+import { DateSelect } from '@desktop-client/components/select/DateSelect';+import { RecurringSchedulePicker } from '@desktop-client/components/select/RecurringSchedulePicker';+import { useCategories } from '@desktop-client/hooks/useCategories';+import { useDateFormat } from '@desktop-client/hooks/useDateFormat';+import { pushModal } from '@desktop-client/modals/modalsSlice';+import { useDispatch } from '@desktop-client/redux';++type GenericInputProps = {+ ref?: Ref<HTMLInputElement>;+ style?: CSSProperties;+ inputStyle?: CSSProperties;+} & (+ | ((+ | {+ type: 'id';+ field: 'payee' | 'category';+ }+ | {+ type: 'id';+ field: 'account';+ op?: RuleConditionOp;+ }+ ) &+ (+ | {+ multi: true;+ value: string[];+ onChange: (value: string[]) => void;+ }+ | {+ multi?: false;+ value: string;+ onChange: (value: string) => void;+ }+ ))+ | ({+ type: 'saved';+ field: 'saved' | 'report';+ } & (+ | {+ multi: true;+ value: string[];+ onChange: (value: string[]) => void;+ }+ | {+ multi?: false;+ value: string;+ onChange: (value: string) => void;+ }+ ))+ | ({+ type: 'date';+ } & (+ | {+ field: 'date' | 'month' | 'year';+ value: string;+ onChange: (value: string) => void;+ }+ | {+ field: 'date';+ value: RecurConfig;+ onChange: (value: RecurConfig) => void;+ }+ ))+ | {+ type: 'boolean';+ value: boolean;+ onChange: (value: boolean) => void;+ }+ | {+ type: 'number';+ value: number;+ onChange: (value: number) => void;+ numberFormatType?: 'currency' | 'percentage';+ options?: {+ inflow?: boolean;+ outflow?: boolean;+ };+ }+ | ({+ type: 'string';+ } & (+ | {+ multi: true;+ value: string[];+ onChange: (value: string[]) => void;+ }+ | {+ multi?: false;+ value: string;+ onChange: (value: string) => void;+ }+ ))+);++export const GenericInput = ({+ ref,+ style,+ inputStyle,+ ...props+}: GenericInputProps) => {+ const dispatch = useDispatch();+ const { isNarrowWidth } = useResponsive();+ const { t } = useTranslation();+ const { grouped: categoryGroups } = useCategories();+ const dateFormat = useDateFormat() || 'MM/dd/yyyy';++ let content: JSX.Element | null = null;+ switch (props.type) {+ case 'id': {+ const showPlaceholder = props.multi ? props.value.length === 0 : true;+ const multiProps =+ props.multi === true+ ? {+ type: 'multi' as const,+ value: props.value,+ onSelect: props.onChange,+ }+ : {+ type: 'single' as const,+ value: props.value,+ onSelect: props.onChange,+ };++ switch (props.field) {+ case 'payee':+ content = (+ <PayeeAutocomplete+ {...multiProps}+ showMakeTransfer={false}+ openOnFocus={!isNarrowWidth}+ updateOnValueChange={isNarrowWidth}+ inputProps={{+ ref,+ ...(showPlaceholder ? { placeholder: t('nothing') } : null),+ onClick: () => {+ if (!isNarrowWidth) {+ return;+ }++ dispatch(+ pushModal({+ modal: {+ name: 'payee-autocomplete',+ options: {+ onSelect: newValue => {+ if (props.multi === true) {+ props.onChange([...props.value, newValue]);+ return;+ }+ props.onChange(newValue);+ },+ },+ },+ }),+ );+ },+ }}+ />+ );+ break;++ case 'account':+ switch (props.op) {+ case 'onBudget':+ case 'offBudget':+ content = null;+ break;+ default:+ content = (+ <AccountAutocomplete+ {...multiProps}+ openOnFocus={!isNarrowWidth}+ updateOnValueChange={isNarrowWidth}+ inputProps={{+ ref,+ ...(showPlaceholder ? { placeholder: t('nothing') } : null),+ onClick: () => {+ if (!isNarrowWidth) {+ return;+ }++ dispatch(+ pushModal({+ modal: {+ name: 'account-autocomplete',+ options: {+ onSelect: newValue => {+ if (props.multi === true) {+ props.onChange([...props.value, newValue]);+ return;+ }+ props.onChange(newValue);+ },+ },+ },+ }),+ );+ },+ }}+ />+ );+ break;+ }+ break;++ case 'category':+ content = (+ <CategoryAutocomplete+ {...multiProps}+ categoryGroups={categoryGroups}+ openOnFocus={!isNarrowWidth}+ updateOnValueChange={isNarrowWidth}+ showHiddenCategories={true}+ inputProps={{+ ref,+ ...(showPlaceholder ? { placeholder: t('nothing') } : null),+ onClick: () => {+ if (!isNarrowWidth) {+ return;+ }++ dispatch(+ pushModal({+ modal: {+ name: 'category-autocomplete',+ options: {+ onSelect: newValue => {+ if (props.multi === true) {+ props.onChange([...props.value, newValue]);+ return;+ }+ props.onChange(newValue);+ },+ },+ },+ }),+ );+ },+ }}+ />+ );+ break;++ default:+ }+ break;+ }++ case 'saved': {+ const showSavedPlaceholder = props.multi+ ? props.value.length === 0+ : true;+ const savedMultiProps =+ props.multi === true+ ? {+ type: 'multi' as const,+ value: props.value,+ onSelect: props.onChange,+ }+ : {+ type: 'single' as const,+ value: props.value,+ onSelect: props.onChange,+ };++ switch (props.field) {+ case 'saved':+ content = (+ <FilterAutocomplete+ {...savedMultiProps}+ openOnFocus={true}+ inputProps={{+ ref,+ ...(showSavedPlaceholder+ ? { placeholder: t('nothing') }+ : null),+ }}+ />+ );+ break;+ case 'report':+ content = (+ <ReportAutocomplete+ {...savedMultiProps}+ openOnFocus={true}+ inputProps={{+ ref,+ ...(showSavedPlaceholder+ ? { placeholder: t('nothing') }+ : null),+ }}+ />+ );+ break;++ default:+ }+ break;+ }++ case 'date':+ switch (props.field) {+ case 'month':+ content = (+ <Input+ ref={ref}+ value={props.value || ''}+ placeholder={getMonthYearFormat(dateFormat).toLowerCase()}+ onChangeValue={props.onChange}+ />+ );+ break;++ case 'year':+ content = (+ <Input+ ref={ref}+ value={props.value || ''}+ placeholder={t('yyyy')}+ onChangeValue={props.onChange}+ />+ );+ break;++ default:+ if (typeof props.value !== 'string') {+ content = (+ <RecurringSchedulePicker+ value={props.value}+ buttonStyle={{ justifyContent: 'flex-start' }}+ onChange={props.onChange}+ />+ );+ } else {+ content = (+ <DateSelect+ ref={ref}+ value={props.value}+ dateFormat={dateFormat}+ openOnFocus={false}+ inputProps={{ placeholder: dateFormat.toLowerCase() }}+ onSelect={props.onChange}+ />+ );+ }+ break;+ }+ break;++ case 'boolean':+ content = (+ <Checkbox+ checked={props.value}+ value={String(props.value)}+ onChange={() => props.onChange(!props.value)}+ />+ );+ break;++ case 'number':+ switch (props.numberFormatType) {+ case 'currency':+ content = (+ <AmountInput+ ref={ref}+ value={props.value}+ onUpdate={props.onChange}+ sign={+ props.options?.inflow || props.options?.outflow+ ? '+'+ : undefined+ }+ inputStyle={inputStyle}+ />+ );+ break;++ case 'percentage':+ content = (+ <PercentInput+ inputRef={ref}+ value={props.value}+ onUpdatePercent={props.onChange}+ style={inputStyle}+ />+ );+ break;++ default:+ content = (+ <Input+ ref={ref}+ value={props.value || ''}+ placeholder={t('nothing')}+ onChangeValue={newValue => props.onChange(Number(newValue))}+ style={inputStyle}+ />+ );+ }+ break;++ default:+ if (props.multi === true) {+ content = (+ <Autocomplete+ type="multi"+ suggestions={[]}+ value={props.value}+ inputProps={{ ref }}+ onSelect={props.onChange}+ />+ );+ } else {+ content = (+ <Input+ ref={ref}+ value={props.value || ''}+ placeholder={t('nothing')}+ onChangeValue={props.onChange}+ style={inputStyle}+ />+ );+ }+ break;+ }++ return <View style={{ flex: 1, ...style }}>{content}</View>;+};diff --git a/upcoming-release-notes/5976.md b/upcoming-release-notes/5976.mdnew file mode 100644index 0000000000..878c9b6053--- /dev/null+++ b/upcoming-release-notes/5976.md@@ -0,0 +1,7 @@+---+category: Maintenance+authors: [MatissJanis]+---++Convert GenericInput component to TypeScript with generic types+