A local-first personal finance app
Convert client to TS part 2 (#1037)
Alberto Gasparina6b6295426ea
diff --git a/.gitignore b/.gitignoreindex 849d42c0e0..e5defbf5ea 100644--- a/.gitignore+++ b/.gitignore@@ -19,6 +19,7 @@ bundle.mobile.jsbundle.mobile.js.mapexport-2020-01-10.csv.idea+.vscode**/*.logdiff --git a/packages/desktop-client/src/components/KeyHandlers.js b/packages/desktop-client/src/components/KeyHandlers.tsxsimilarity index 65%rename from packages/desktop-client/src/components/KeyHandlers.jsrename to packages/desktop-client/src/components/KeyHandlers.tsxindex 156b8c0199..fc58fc5315 100644--- a/packages/desktop-client/src/components/KeyHandlers.js+++ b/packages/desktop-client/src/components/KeyHandlers.tsx@@ -1,12 +1,12 @@import React, { createContext, useEffect, useContext } from 'react';-import hotkeys from 'hotkeys-js';+import hotkeys, { type KeyHandler as HotKeyHandler } from 'hotkeys-js';let KeyScopeContext = createContext('app');hotkeys.filter = event => {- var target = event.target || event.srcElement;- var tagName = target.tagName;+ let target = (event.target || event.srcElement) as HTMLElement;+ let tagName = target.tagName;// This is the default behavior of hotkeys, except we only suppress// key presses if the meta key is not pressed@@ -16,7 +16,7 @@ hotkeys.filter = event => {((tagName === 'INPUT' ||tagName === 'TEXTAREA' ||tagName === 'SELECT') &&- !target.readOnly))+ !target['readOnly']))) {return false;}@@ -24,7 +24,16 @@ hotkeys.filter = event => {return true;};-export function KeyHandler({ keyName, eventType = 'keydown', handler }) {+type KeyHandlerProps = {+ keyName: string;+ eventType?: string;+ handler: HotKeyHandler;+};+export function KeyHandler({+ keyName,+ eventType = 'keydown',+ handler,+}: KeyHandlerProps) {let scope = useContext(KeyScopeContext);if (eventType !== 'keyup' && eventType !== 'keydown') {@@ -44,6 +53,7 @@ export function KeyHandler({ keyName, eventType = 'keydown', handler }) {hotkeys(keyName, { scope, keyup: true }, _handler);return () => {+ // @ts-expect-error unbind args typedef does not expect an objecthotkeys.unbind({key: keyName,scope,@@ -55,7 +65,11 @@ export function KeyHandler({ keyName, eventType = 'keydown', handler }) {return null;}-export function KeyHandlers({ eventType, keys = {} }) {+type KeyHandlersProps = {+ eventType?: string;+ keys: Record<string, HotKeyHandler>;+};+export function KeyHandlers({ eventType, keys = {} }: KeyHandlersProps) {let handlers = Object.keys(keys).map(key => {return (<KeyHandler@@ -67,5 +81,6 @@ export function KeyHandlers({ eventType, keys = {} }) {);});- return handlers;+ // eslint-disable-next-line react/jsx-no-useless-fragment+ return <>{handlers}</>;}diff --git a/packages/desktop-client/src/components/NotesButton.js b/packages/desktop-client/src/components/NotesButton.tsxsimilarity index 85%rename from packages/desktop-client/src/components/NotesButton.jsrename to packages/desktop-client/src/components/NotesButton.tsxindex b6dcc1b000..b1956532b9 100644--- a/packages/desktop-client/src/components/NotesButton.js+++ b/packages/desktop-client/src/components/NotesButton.tsx@@ -1,6 +1,6 @@import React, { createRef, useState, useEffect, useMemo } from 'react';-import { css } from 'glamor';+import { type CSSProperties, css } from 'glamor';import q from 'loot-core/src/client/query-helpers';import { useLiveQuery } from 'loot-core/src/client/query-hooks';@@ -11,14 +11,20 @@ import { colors } from '../style';import { View, Button, Tooltip, useTooltip, Text } from './common';+type NotesTooltipProps = {+ editable?: boolean;+ defaultNotes?: string;+ position?: string;+ onClose?: (notes: string) => void;+};export function NotesTooltip({editable,defaultNotes,position = 'bottom-left',onClose,-}) {- let [notes, setNotes] = useState(defaultNotes);- let inputRef = createRef();+}: NotesTooltipProps) {+ let [notes, setNotes] = useState<string>(defaultNotes);+ let inputRef = createRef<HTMLTextAreaElement>();useEffect(() => {if (editable) {@@ -58,6 +64,14 @@ export function NotesTooltip({);}+type NotesButtonProps = {+ id: string;+ width?: number;+ height?: number;+ defaultColor?: string;+ tooltipPosition?: string;+ style?: CSSProperties;+};export default function NotesButton({id,width = 12,@@ -65,7 +79,7 @@ export default function NotesButton({defaultColor = colors.n8,tooltipPosition,style,-}) {+}: NotesButtonProps) {let [hover, setHover] = useState(false);let tooltip = useTooltip();let { data } = useLiveQuery(diff --git a/packages/desktop-client/src/components/Stack.js b/packages/desktop-client/src/components/Stack.tsxsimilarity index 75%rename from packages/desktop-client/src/components/Stack.jsrename to packages/desktop-client/src/components/Stack.tsxindex a15576734f..4c54eafcee 100644--- a/packages/desktop-client/src/components/Stack.js+++ b/packages/desktop-client/src/components/Stack.tsx@@ -1,4 +1,11 @@-import React, { Children, Fragment, cloneElement, forwardRef } from 'react';+import React, {+ Children,+ type ComponentProps,+ Fragment,+ cloneElement,+ forwardRef,+ type ReactNode,+} from 'react';import Text from './common/Text';import View from './common/View';@@ -6,17 +13,28 @@ import View from './common/View';function getChildren(key, children) {return Children.toArray(children).reduce((list, child) => {if (child) {- if (child.type === Fragment) {+ if (+ typeof child === 'object' &&+ 'type' in child &&+ child.type === Fragment+ ) {return list.concat(getChildren(child.key, child.props.children));}- list.push({ key: key + child.key, child });+ list.push({ key: key + child['key'], child });return list;}return list;- }, []);+ }, [] as Array<{ key: string; child: ReactNode }>);}-const Stack = forwardRef(+type StackProps = ComponentProps<typeof View> & {+ direction?: string;+ align?: string;+ justify?: string;+ spacing?: number;+ debug?: boolean;+};+const Stack = forwardRef<HTMLDivElement, StackProps>(({direction = 'column',diff --git a/packages/desktop-client/src/components/autocomplete/Autocomplete.js b/packages/desktop-client/src/components/autocomplete/Autocomplete.tsxsimilarity index 87%rename from packages/desktop-client/src/components/autocomplete/Autocomplete.jsrename to packages/desktop-client/src/components/autocomplete/Autocomplete.tsxindex a1b88a5e5a..a56ac15d72 100644--- a/packages/desktop-client/src/components/autocomplete/Autocomplete.js+++ b/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx@@ -1,13 +1,23 @@-import React, { useState, useRef, useEffect, useMemo } from 'react';+import React, {+ useState,+ useRef,+ useEffect,+ useMemo,+ type ComponentProps,+ type HTMLProps,+ type ReactNode,+ type KeyboardEvent,+ type ChangeEvent,+} from 'react';import Downshift from 'downshift';-import { css } from 'glamor';+import { type CSSProperties, css } from 'glamor';import Remove from '../../icons/v2/Remove';import { colors } from '../../style';import { View, Input, Tooltip, Button } from '../common';-const inst = {};+const inst: { lastChangeType? } = {};function findItem(strict, suggestions, value) {if (strict) {@@ -104,6 +114,35 @@ function defaultItemToString(item) {return item ? getItemName(item) : '';}+type SingleAutocompleteProps = {+ focused?: boolean;+ embedded?: boolean;+ containerProps?: HTMLProps<HTMLDivElement>;+ labelProps?: { id?: string };+ inputProps?: ComponentProps<typeof Input>;+ suggestions?: unknown[];+ tooltipStyle?: CSSProperties;+ tooltipProps?: ComponentProps<typeof Tooltip>;+ renderInput?: (props: ComponentProps<typeof Input>) => ReactNode;+ renderItems?: (+ items,+ getItemProps: (arg: { item: unknown }) => HTMLProps<HTMLDivElement>,+ idx: number,+ value?: unknown,+ ) => ReactNode;+ itemToString?: (item: unknown) => string;+ shouldSaveFromKey?: (e: KeyboardEvent) => boolean;+ filterSuggestions?: (suggestions, value: string) => unknown[];+ openOnFocus?: boolean;+ getHighlightedIndex?: (suggestions) => number | null;+ highlightFirst?: boolean;+ onUpdate: (id: unknown, value: string) => void;+ strict?: boolean;+ onSelect: (id: unknown, value: string) => void;+ tableBehavior?: boolean;+ value: unknown[];+ isMulti?: boolean;+};function SingleAutocomplete({focused,embedded = false,@@ -127,7 +166,7 @@ function SingleAutocomplete({tableBehavior,value: initialValue,isMulti = false,-}) {+}: SingleAutocompleteProps) {const [selectedItem, setSelectedItem] = useState(() =>findItem(strict, suggestions, initialValue),);@@ -220,6 +259,7 @@ function SingleAutocomplete({Downshift.stateChangeTypes.controlledPropUpdatedSelectedItem,// Do nothing if it is a "touch" selection eventDownshift.stateChangeTypes.touchEnd,+ // @ts-expect-error Types say there is no type].includes(changes.type)) {return;@@ -232,7 +272,7 @@ function SingleAutocomplete({if (value === '') {// A blank value shouldn't highlight any item so that the field// can be left blank if desired-+ // @ts-expect-error Types say there is no typeif (changes.type !== Downshift.stateChangeTypes.clickItem) {fireUpdate(onUpdate, strict, filteredSuggestions, null, null);}@@ -245,7 +285,7 @@ function SingleAutocomplete({let highlightedIndex = (getHighlightedIndex || defaultGetHighlightedIndex)(filteredSuggestions);-+ // @ts-expect-error Types say there is no typeif (changes.type !== Downshift.stateChangeTypes.clickItem) {fireUpdate(onUpdate,@@ -330,6 +370,7 @@ function SingleAutocomplete({}},onBlur: e => {+ // @ts-expect-error Should this be e.nativeEvente.preventDownshiftDefault = true;inputProps.onBlur && inputProps.onBlur(e);@@ -350,7 +391,7 @@ function SingleAutocomplete({setIsOpen(false);}},- onKeyDown: e => {+ onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => {let { onKeyDown } = inputProps || {};// If the dropdown is open, an item is highlighted, and the user@@ -374,7 +415,7 @@ function SingleAutocomplete({} else if (!strict) {// Handle it ourselvese.stopPropagation();- onSelect(value, e.target.value);+ onSelect(value, (e.target as HTMLInputElement).value);return onSelectAfter();} else {// No highlighted item, still allow the table to save the item@@ -390,7 +431,7 @@ function SingleAutocomplete({// Handle escape ourselvesif (e.key === 'Escape') {- e.nativeEvent.preventDownshiftDefault = true;+ e.nativeEvent['preventDownshiftDefault'] = true;if (!embedded) {e.stopPropagation();@@ -410,8 +451,9 @@ function SingleAutocomplete({setIsOpen(embedded ? true : false);}},- onChange: e => {+ onChange: (e: ChangeEvent<HTMLInputElement>) => {const { onChange } = inputProps || {};+ // @ts-expect-error unsure if onChange needs an event or a stringonChange && onChange(e.target.value);},}),@@ -475,15 +517,22 @@ function MultiItem({ name, onRemove }) {);}+type MultiAutocompleteProps = Omit<+ SingleAutocompleteProps,+ 'value' | 'onSelect'+> & {+ value: unknown[];+ onSelect: (ids: unknown[], id?: string) => void;+};export function MultiAutocomplete({value: selectedItems,onSelect,suggestions,strict,...props-}) {+}: MultiAutocompleteProps) {let [focused, setFocused] = useState(false);- let lastSelectedItems = useRef();+ let lastSelectedItems = useRef<unknown[]>();useEffect(() => {lastSelectedItems.current = selectedItems;@@ -608,7 +657,16 @@ export function AutocompleteFooterButton({);}-export function AutocompleteFooter({ show = true, embedded, children }) {+type AutocompleteFooterProps = {+ show?: boolean;+ embedded: boolean;+ children: ReactNode;+};+export function AutocompleteFooter({+ show = true,+ embedded,+ children,+}: AutocompleteFooterProps) {return (show && (<View@@ -624,7 +682,10 @@ export function AutocompleteFooter({ show = true, embedded, children }) {);}-export default function Autocomplete({ multi, ...props }) {+type AutocompleteProps = ComponentProps<typeof SingleAutocomplete> & {+ multi?: boolean;+};+export default function Autocomplete({ multi, ...props }: AutocompleteProps) {if (multi) {return <MultiAutocomplete {...props} />;} else {diff --git a/packages/desktop-client/src/components/autocomplete/CategorySelect.js b/packages/desktop-client/src/components/autocomplete/CategorySelect.tsxsimilarity index 73%rename from packages/desktop-client/src/components/autocomplete/CategorySelect.jsrename to packages/desktop-client/src/components/autocomplete/CategorySelect.tsxindex 7579baf9a2..6a1824dfb8 100644--- a/packages/desktop-client/src/components/autocomplete/CategorySelect.js+++ b/packages/desktop-client/src/components/autocomplete/CategorySelect.tsx@@ -1,37 +1,67 @@-import React, { Fragment, forwardRef, useMemo } from 'react';+import React, {+ type ComponentProps,+ Fragment,+ forwardRef,+ useMemo,+ type ReactNode,+} from 'react';import Split from '../../icons/v0/Split';import { colors } from '../../style';+import { type HTMLPropsWithStyle } from '../../types/utils';import { View, Text, Select } from '../common';import Autocomplete, { defaultFilterSuggestion } from './Autocomplete';-export const NativeCategorySelect = forwardRef(- ({ categoryGroups, emptyLabel, ...nativeProps }, ref) => {- return (- <Select {...nativeProps} ref={ref}>- <option value="">{emptyLabel || 'Select category...'}</option>- {categoryGroups.map(group => (- <optgroup key={group.id} label={group.name}>- {group.categories.map(category => (- <option key={category.id} value={category.id}>- {category.name}- </option>- ))}- </optgroup>- ))}- </Select>- );- },-);+type CategoryGroup = {+ id: string;+ name: string;+ categories: Array<{ id: string; name: string }>;+};+type NativeCategorySelectProps = HTMLPropsWithStyle<HTMLSelectElement> & {+ categoryGroups: CategoryGroup[];+ emptyLabel: string;+};+export const NativeCategorySelect = forwardRef<+ HTMLSelectElement,+ NativeCategorySelectProps+>(({ categoryGroups, emptyLabel, ...nativeProps }, ref) => {+ return (+ <Select {...nativeProps} ref={ref}>+ <option value="">{emptyLabel || 'Select category...'}</option>+ {categoryGroups.map(group => (+ <optgroup key={group.id} label={group.name}>+ {group.categories.map(category => (+ <option key={category.id} value={category.id}>+ {category.name}+ </option>+ ))}+ </optgroup>+ ))}+ </Select>+ );+});++type CategoryListProps = {+ items: Array<{+ id: string;+ cat_group: unknown;+ groupName: string;+ name: string;+ }>;+ getItemProps?: (arg: { item }) => Partial<ComponentProps<typeof View>>;+ highlightedIndex: number;+ embedded: boolean;+ footer?: ReactNode;+};export function CategoryList({items,getItemProps,highlightedIndex,embedded,footer,-}) {+}: CategoryListProps) {let lastGroup = null;return (@@ -117,13 +147,16 @@ export function CategoryList({);}+type CategoryAutocompleteProps = ComponentProps<typeof Autocomplete> & {+ categoryGroups: CategoryGroup[];+ showSplitOption?: boolean;+};export default function CategoryAutocomplete({categoryGroups,showSplitOption,embedded,- onSplit,...props-}) {+}: CategoryAutocompleteProps) {let categorySuggestions = useMemo(() =>categoryGroups.reduce(diff --git a/packages/desktop-client/src/components/budget/BalanceWithCarryover.js b/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsxsimilarity index 82%rename from packages/desktop-client/src/components/budget/BalanceWithCarryover.jsrename to packages/desktop-client/src/components/budget/BalanceWithCarryover.tsxindex 1512596cf7..324fb30ada 100644--- a/packages/desktop-client/src/components/budget/BalanceWithCarryover.js+++ b/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx@@ -1,4 +1,4 @@-import React from 'react';+import React, { type ComponentProps } from 'react';import ArrowThinRight from '../../icons/v1/ArrowThinRight';import { View } from '../common';@@ -7,12 +7,16 @@ import useSheetValue from '../spreadsheet/useSheetValue';import { makeAmountStyle } from './util';+type BalanceWithCarryoverProps = {+ carryover: ComponentProps<typeof CellValue>['binding'];+ balance: ComponentProps<typeof CellValue>['binding'];+ disabled?: boolean;+};export default function BalanceWithCarryover({carryover,balance,- category,disabled,-}) {+}: BalanceWithCarryoverProps) {let carryoverValue = useSheetValue(carryover);let balanceValue = useSheetValue(balance);diff --git a/packages/desktop-client/src/components/budget/report/BudgetSummary.js b/packages/desktop-client/src/components/budget/report/BudgetSummary.tsxsimilarity index 85%rename from packages/desktop-client/src/components/budget/report/BudgetSummary.jsrename to packages/desktop-client/src/components/budget/report/BudgetSummary.tsxindex 7dcc057857..b7542b8922 100644--- a/packages/desktop-client/src/components/budget/report/BudgetSummary.js+++ b/packages/desktop-client/src/components/budget/report/BudgetSummary.tsx@@ -1,6 +1,13 @@-import React, { memo, useState } from 'react';+import React, {+ type ComponentProps,+ type ComponentType,+ memo,+ type ReactNode,+ useState,+ type SVGProps,+} from 'react';-import { css } from 'glamor';+import { css, type CSSProperties } from 'glamor';import { reportBudget } from 'loot-core/src/client/queries';import * as monthUtils from 'loot-core/src/shared/months';@@ -29,7 +36,18 @@ import { makeAmountFullStyle } from '../util';import { useReport } from './ReportContext';-function PieProgress({ style, progress, color, backgroundColor }) {+type PieProgressProps = {+ style?: SVGProps<SVGSVGElement>['style'];+ progress: number;+ color: string;+ backgroundColor: string;+};+function PieProgress({+ style,+ progress,+ color,+ backgroundColor,+}: PieProgressProps) {let radius = 4;let circum = 2 * Math.PI * radius;let dash = progress * circum;@@ -63,7 +81,11 @@ function fraction(num, denom) {return num / denom;}-function IncomeProgress({ current, target }) {+type IncomeProgressProps = {+ current: ComponentProps<typeof CellValue>['binding'];+ target: ComponentProps<typeof CellValue>['binding'];+};+function IncomeProgress({ current, target }: IncomeProgressProps) {let totalIncome = useSheetValue(current) || 0;let totalBudgeted = useSheetValue(target) || 0;@@ -86,7 +108,11 @@ function IncomeProgress({ current, target }) {);}-function ExpenseProgress({ current, target }) {+type ExpenseProgressProps = {+ current: ComponentProps<typeof CellValue>['binding'];+ target: ComponentProps<typeof CellValue>['binding'];+};+function ExpenseProgress({ current, target }: ExpenseProgressProps) {let totalSpent = useSheetValue(current) || 0;let totalBudgeted = useSheetValue(target) || 0;@@ -115,7 +141,20 @@ function ExpenseProgress({ current, target }) {);}-function BudgetTotal({ title, current, target, ProgressComponent, style }) {+type BudgetTotalProps = {+ title: ReactNode;+ current: ComponentProps<typeof CellValue>['binding'];+ target: ComponentProps<typeof CellValue>['binding'];+ ProgressComponent: ComponentType<{ current; target }>;+ style?: CSSProperties;+};+function BudgetTotal({+ title,+ current,+ target,+ ProgressComponent,+ style,+}: BudgetTotalProps) {return (<Viewstyle={[@@ -151,7 +190,10 @@ function BudgetTotal({ title, current, target, ProgressComponent, style }) {);}-function IncomeTotal({ projected, style }) {+type IncomeTotalProps = {+ style?: CSSProperties;+};+function IncomeTotal({ style }: IncomeTotalProps) {return (<BudgetTotaltitle="Income"@@ -163,7 +205,10 @@ function IncomeTotal({ projected, style }) {);}-function ExpenseTotal({ style }) {+type ExpenseTotalProps = {+ style?: CSSProperties;+};+function ExpenseTotal({ style }: ExpenseTotalProps) {return (<BudgetTotaltitle="Expenses"@@ -175,7 +220,11 @@ function ExpenseTotal({ style }) {);}-function Saved({ projected, style }) {+type SavedProps = {+ projected: boolean;+ style?: CSSProperties;+};+function Saved({ projected, style }: SavedProps) {let budgetedSaved = useSheetValue(reportBudget.totalBudgetedSaved) || 0;let totalSaved = useSheetValue(reportBudget.totalSaved) || 0;let saved = projected ? budgetedSaved : totalSaved;@@ -239,7 +288,12 @@ function Saved({ projected, style }) {);}-export const BudgetSummary = memo(function BudgetSummary({ month }) {+type BudgetSummaryProps = {+ month?: string;+};+export const BudgetSummary = memo(function BudgetSummary({+ month,+}: BudgetSummaryProps) {let {currentMonth,summaryCollapsed: collapsed,@@ -248,11 +302,11 @@ export const BudgetSummary = memo(function BudgetSummary({ month }) {} = useReport();let [menuOpen, setMenuOpen] = useState(false);- function onMenuOpen(e) {+ function onMenuOpen() {setMenuOpen(true);}- function onMenuClose(bag) {+ function onMenuClose() {setMenuOpen(false);}@@ -280,9 +334,7 @@ export const BudgetSummary = memo(function BudgetSummary({ month }) {},}}>- <NamespaceContext.Provider- value={monthUtils.sheetForMonth(month, 'report')}- >+ <NamespaceContext.Provider value={monthUtils.sheetForMonth(month)}><Viewstyle={[{ padding: '0 13px' },diff --git a/packages/desktop-client/src/components/budget/report/ReportContext.js b/packages/desktop-client/src/components/budget/report/ReportContext.tsxsimilarity index 63%rename from packages/desktop-client/src/components/budget/report/ReportContext.jsrename to packages/desktop-client/src/components/budget/report/ReportContext.tsxindex 09dd444be7..fc9927882e 100644--- a/packages/desktop-client/src/components/budget/report/ReportContext.js+++ b/packages/desktop-client/src/components/budget/report/ReportContext.tsx@@ -1,15 +1,21 @@-import React, { createContext, useContext } from 'react';+import React, { type ReactNode, createContext, useContext } from 'react';import * as monthUtils from 'loot-core/src/shared/months';let Context = createContext(null);+type ReportProviderProps = {+ summaryCollapsed: boolean;+ onBudgetAction: (idx: number, action: string, arg: unknown) => void;+ onToggleSummaryCollapse: () => void;+ children: ReactNode;+};export function ReportProvider({summaryCollapsed,onBudgetAction,onToggleSummaryCollapse,children,-}) {+}: ReportProviderProps) {let currentMonth = monthUtils.currentMonth();return (diff --git a/packages/desktop-client/src/components/budget/report/components.js b/packages/desktop-client/src/components/budget/report/components.tsxsimilarity index 90%rename from packages/desktop-client/src/components/budget/report/components.jsrename to packages/desktop-client/src/components/budget/report/components.tsxindex b68192611e..dd663c6c19 100644--- a/packages/desktop-client/src/components/budget/report/components.js+++ b/packages/desktop-client/src/components/budget/report/components.tsx@@ -79,7 +79,10 @@ export function IncomeHeaderMonth() {);}-export const GroupMonth = memo(function ExpenseGroupMonth({ group }) {+type GroupMonthProps = {+ group: { id: string; is_income: boolean };+};+export const GroupMonth = memo(function GroupMonth({ group }: GroupMonthProps) {let borderColor = colors.border;let { id } = group;@@ -127,7 +130,18 @@ export const GroupMonth = memo(function ExpenseGroupMonth({ group }) {);});-function BalanceTooltip({ categoryId, tooltip, monthIndex, onBudgetAction }) {+type BalanceTooltipProps = {+ categoryId: string;+ tooltip: { close: () => void };+ monthIndex: number;+ onBudgetAction: (idx: number, action: string, arg: unknown) => void;+};+function BalanceTooltip({+ categoryId,+ tooltip,+ monthIndex,+ onBudgetAction,+}: BalanceTooltipProps) {let carryover = useSheetValue(reportBudget.catCarryover(categoryId));return (@@ -158,17 +172,22 @@ function BalanceTooltip({ categoryId, tooltip, monthIndex, onBudgetAction }) {);}+type CategoryMonthProps = {+ monthIndex: number;+ category: { id: string; name: string; is_income: boolean };+ editing: boolean;+ onEdit: (id: string | null, idx?: number) => void;+ onBudgetAction: (idx: number, action: string, arg: unknown) => void;+ onShowActivity: (name: string, id: string, idx: number) => void;+};export const CategoryMonth = memo(function CategoryMonth({monthIndex,category,- budgeted,- currentSum,- balance,editing,onEdit,onBudgetAction,onShowActivity,-}) {+}: CategoryMonthProps) {let borderColor = colors.border;let balanceTooltip = useTooltip();@@ -176,7 +195,6 @@ export const CategoryMonth = memo(function CategoryMonth({<View style={{ flex: 1, flexDirection: 'row' }}><SheetCellname="budget"- sync={true}exposed={editing}width="flex"borderColor={borderColor}@@ -253,7 +271,6 @@ export const CategoryMonth = memo(function CategoryMonth({><span {...(category.is_income ? {} : balanceTooltip.getOpenEvents())}><BalanceWithCarryover- category={category}disabled={category.is_income}carryover={reportBudget.catCarryover(category.id)}balance={reportBudget.catBalance(category.id)}diff --git a/packages/desktop-client/src/components/budget/rollover/BudgetSummary.js b/packages/desktop-client/src/components/budget/rollover/BudgetSummary.tsxsimilarity index 95%rename from packages/desktop-client/src/components/budget/rollover/BudgetSummary.jsrename to packages/desktop-client/src/components/budget/rollover/BudgetSummary.tsxindex d9f919fe4d..c6a2d3d720 100644--- a/packages/desktop-client/src/components/budget/rollover/BudgetSummary.js+++ b/packages/desktop-client/src/components/budget/rollover/BudgetSummary.tsx@@ -29,7 +29,11 @@ import HoldTooltip from './HoldTooltip';import { useRollover } from './RolloverContext';import TransferTooltip from './TransferTooltip';-function TotalsList({ prevMonthName, collapsed }) {+type TotalsListProps = {+ prevMonthName: string;+ collapsed?: boolean;+};+function TotalsList({ prevMonthName, collapsed }: TotalsListProps) {return (<Viewstyle={[@@ -133,7 +137,18 @@ function TotalsList({ prevMonthName, collapsed }) {);}-function ToBudget({ month, prevMonthName, collapsed, onBudgetAction }) {+type ToBudgetProps = {+ month: string | number;+ prevMonthName?: string;+ collapsed?: boolean;+ onBudgetAction: (idx: string | number, action: string, arg?: unknown) => void;+};+function ToBudget({+ month,+ prevMonthName,+ collapsed,+ onBudgetAction,+}: ToBudgetProps) {let [menuOpen, setMenuOpen] = useState(null);return (@@ -240,7 +255,14 @@ function ToBudget({ month, prevMonthName, collapsed, onBudgetAction }) {);}-export function BudgetSummary({ month, isGoalTemplatesEnabled }) {+type BudgetSummaryProps = {+ month: string | number;+ isGoalTemplatesEnabled: boolean;+};+export function BudgetSummary({+ month,+ isGoalTemplatesEnabled,+}: BudgetSummaryProps) {let {currentMonth,summaryCollapsed: collapsed,@@ -253,7 +275,7 @@ export function BudgetSummary({ month, isGoalTemplatesEnabled }) {setMenuOpen(true);}- function onMenuClose(bag) {+ function onMenuClose() {setMenuOpen(false);}diff --git a/packages/desktop-client/src/components/budget/rollover/HoldTooltip.js b/packages/desktop-client/src/components/budget/rollover/HoldTooltip.tsxsimilarity index 81%rename from packages/desktop-client/src/components/budget/rollover/HoldTooltip.jsrename to packages/desktop-client/src/components/budget/rollover/HoldTooltip.tsxindex 64b2901116..fe0bf61dfe 100644--- a/packages/desktop-client/src/components/budget/rollover/HoldTooltip.js+++ b/packages/desktop-client/src/components/budget/rollover/HoldTooltip.tsx@@ -1,4 +1,9 @@-import React, { useState, useContext, useEffect } from 'react';+import React, {+ useState,+ useContext,+ useEffect,+ type ChangeEvent,+} from 'react';import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';import evalArithmetic from 'loot-core/src/shared/arithmetic';@@ -7,7 +12,11 @@ import { integerToCurrency, amountToInteger } from 'loot-core/src/shared/util';import { View, Button, Tooltip, InitialFocus, Input } from '../../common';import NamespaceContext from '../../spreadsheet/NamespaceContext';-export default function HoldTooltip({ onSubmit, onClose }) {+type HoldTooltipProps = {+ onSubmit: (amount: number) => void;+ onClose: () => void;+};+export default function HoldTooltip({ onSubmit, onClose }: HoldTooltipProps) {const spreadsheet = useSpreadsheet();const sheetName = useContext(NamespaceContext);@@ -45,7 +54,9 @@ export default function HoldTooltip({ onSubmit, onClose }) {<InitialFocus><Inputvalue={amount}- onChange={e => setAmount(e.target.value)}+ onChange={(e: ChangeEvent<HTMLInputElement>) =>+ setAmount(e.target.value)+ }onEnter={submit}/></InitialFocus>diff --git a/packages/desktop-client/src/components/budget/rollover/RolloverContext.js b/packages/desktop-client/src/components/budget/rollover/RolloverContext.tsxsimilarity index 63%rename from packages/desktop-client/src/components/budget/rollover/RolloverContext.jsrename to packages/desktop-client/src/components/budget/rollover/RolloverContext.tsxindex c3a00bec39..706999c7cb 100644--- a/packages/desktop-client/src/components/budget/rollover/RolloverContext.js+++ b/packages/desktop-client/src/components/budget/rollover/RolloverContext.tsx@@ -1,16 +1,23 @@-import React, { createContext, useContext } from 'react';+import React, { type ReactNode, createContext, useContext } from 'react';import * as monthUtils from 'loot-core/src/shared/months';let Context = createContext(null);+type RolloverContextProps = {+ categoryGroups: unknown[];+ summaryCollapsed: boolean;+ onBudgetAction: (idx: number, action: string, arg?: unknown) => void;+ onToggleSummaryCollapse: () => void;+ children: ReactNode;+};export function RolloverContext({categoryGroups,summaryCollapsed,onBudgetAction,onToggleSummaryCollapse,children,-}) {+}: RolloverContextProps) {let currentMonth = monthUtils.currentMonth();return (diff --git a/packages/desktop-client/src/components/budget/rollover/TransferTooltip.js b/packages/desktop-client/src/components/budget/rollover/TransferTooltip.tsxsimilarity index 87%rename from packages/desktop-client/src/components/budget/rollover/TransferTooltip.jsrename to packages/desktop-client/src/components/budget/rollover/TransferTooltip.tsxindex 92bac19623..e4829c9e8b 100644--- a/packages/desktop-client/src/components/budget/rollover/TransferTooltip.js+++ b/packages/desktop-client/src/components/budget/rollover/TransferTooltip.tsx@@ -1,4 +1,9 @@-import React, { useState, useContext, useEffect } from 'react';+import React, {+ useState,+ useContext,+ useEffect,+ type ComponentProps,+} from 'react';import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';import evalArithmetic from 'loot-core/src/shared/arithmetic';@@ -9,6 +14,14 @@ import { View, Button, Tooltip, InitialFocus, Input } from '../../common';import NamespaceContext from '../../spreadsheet/NamespaceContext';import { addToBeBudgetedGroup, CategoryGroupsContext } from '../util';+type TransferTooltipProps = {+ initialAmount?: number;+ initialAmountName?: string;+ showToBeBudgeted?: boolean;+ tooltipProps?: ComponentProps<typeof Tooltip>;+ onSubmit: (amount: number, category: unknown) => void;+ onClose: () => void;+};export default function TransferTooltip({initialAmount,initialAmountName,@@ -16,7 +29,7 @@ export default function TransferTooltip({tooltipProps,onSubmit,onClose,-}) {+}: TransferTooltipProps) {let spreadsheet = useSpreadsheet();let sheetName = useContext(NamespaceContext);let categoryGroups = useContext(CategoryGroupsContext);@@ -69,7 +82,7 @@ export default function TransferTooltip({<InitialFocus><Inputvalue={amount}- onChange={e => setAmount(e.target.value)}+ onChange={e => setAmount(e.target['value'])}onEnter={submit}/></InitialFocus>diff --git a/packages/desktop-client/src/components/budget/rollover/rollover-components.js b/packages/desktop-client/src/components/budget/rollover/rollover-components.tsxsimilarity index 89%rename from packages/desktop-client/src/components/budget/rollover/rollover-components.jsrename to packages/desktop-client/src/components/budget/rollover/rollover-components.tsxindex a604d22cea..b9ec4d0f78 100644--- a/packages/desktop-client/src/components/budget/rollover/rollover-components.js+++ b/packages/desktop-client/src/components/budget/rollover/rollover-components.tsx@@ -1,4 +1,4 @@-import React, { memo, useContext, useState } from 'react';+import React, { type ComponentProps, memo, useContext, useState } from 'react';import { rolloverBudget } from 'loot-core/src/client/queries';import evalArithmetic from 'loot-core/src/shared/arithmetic';@@ -31,13 +31,12 @@ import TransferTooltip from './TransferTooltip';export { BudgetSummary } from './BudgetSummary';-function CoverTooltip({- showToBeBudgeted,- inline,- tooltipProps,- onSubmit,- onClose,-}) {+type CoverTooltipProps = {+ tooltipProps?: ComponentProps<typeof Tooltip>;+ onSubmit: (category: unknown) => void;+ onClose: () => void;+};+function CoverTooltip({ tooltipProps, onSubmit, onClose }: CoverTooltipProps) {let categoryGroups = useContext(CategoryGroupsContext);categoryGroups = addToBeBudgetedGroup(categoryGroups.filter(g => !g.is_income),@@ -102,7 +101,18 @@ function CoverTooltip({);}-function BalanceTooltip({ categoryId, tooltip, monthIndex, onBudgetAction }) {+type BalanceTooltipProps = {+ categoryId: string;+ tooltip: { close: () => void };+ monthIndex: number;+ onBudgetAction: (idx: number, action: string, arg?: unknown) => void;+};+function BalanceTooltip({+ categoryId,+ tooltip,+ monthIndex,+ onBudgetAction,+}: BalanceTooltipProps) {let carryover = useSheetValue(rolloverBudget.catCarryover(categoryId));let balance = useSheetValue(rolloverBudget.catBalance(categoryId));let [menu, setMenu] = useState('menu');@@ -165,7 +175,6 @@ function BalanceTooltip({ categoryId, tooltip, monthIndex, onBudgetAction }) {{menu === 'cover' && (<CoverTooltip- showToBeBudgeted={true}onClose={tooltip.close}onSubmit={fromCategory => {onBudgetAction(monthIndex, 'cover', {@@ -237,7 +246,12 @@ export function IncomeHeaderMonth() {);}-export const ExpenseGroupMonth = memo(function ExpenseGroupMonth({ group }) {+type ExpenseGroupMonthProps = {+ group: { id: string };+};+export const ExpenseGroupMonth = memo(function ExpenseGroupMonth({+ group,+}: ExpenseGroupMonthProps) {let borderColor = colors.border;let { id } = group;@@ -283,6 +297,14 @@ export const ExpenseGroupMonth = memo(function ExpenseGroupMonth({ group }) {);});+type ExpenseCategoryMonthProps = {+ monthIndex: number;+ category: { id: string; name: string; is_income: boolean };+ editing: boolean;+ onEdit: (id: string | null, idx?: number) => void;+ onBudgetAction: (idx: number, action: string, arg?: unknown) => void;+ onShowActivity: (name: string, id: string, idx: number) => void;+};export const ExpenseCategoryMonth = memo(function ExpenseCategoryMonth({monthIndex,category,@@ -290,7 +312,7 @@ export const ExpenseCategoryMonth = memo(function ExpenseCategoryMonth({onEdit,onBudgetAction,onShowActivity,-}) {+}: ExpenseCategoryMonthProps) {let borderColor = colors.border;let balanceTooltip = useTooltip();@@ -298,7 +320,6 @@ export const ExpenseCategoryMonth = memo(function ExpenseCategoryMonth({<View style={{ flex: 1, flexDirection: 'row' }}><SheetCellname="budget"- sync={true}exposed={editing}width="flex"borderColor={borderColor}@@ -372,7 +393,6 @@ export const ExpenseCategoryMonth = memo(function ExpenseCategoryMonth({><span {...balanceTooltip.getOpenEvents()}><BalanceWithCarryover- category={category}carryover={rolloverBudget.catCarryover(category.id)}balance={rolloverBudget.catBalance(category.id)}/>@@ -390,9 +410,7 @@ export const ExpenseCategoryMonth = memo(function ExpenseCategoryMonth({);});-export function IncomeGroupMonth({ group }) {- // let { id } = group;-+export function IncomeGroupMonth() {return (<View style={{ flex: 1 }}><SheetCell@@ -413,12 +431,18 @@ export function IncomeGroupMonth({ group }) {);}+type IncomeCategoryMonthProps = {+ category: { id: string; name: string };+ isLast: boolean;+ monthIndex: number;+ onShowActivity: (name: string, id: string, idx: number) => void;+};export function IncomeCategoryMonth({category,isLast,monthIndex,onShowActivity,-}) {+}: IncomeCategoryMonthProps) {return (<View style={{ flex: 1 }}><Fielddiff --git a/packages/desktop-client/src/components/common.tsx b/packages/desktop-client/src/components/common.tsxindex e2fa996f3c..d36b3b5a74 100644--- a/packages/desktop-client/src/components/common.tsx+++ b/packages/desktop-client/src/components/common.tsx@@ -472,18 +472,18 @@ export function Keybinding({ keyName }: KeybindingProps) {}type MenuItem = {- type: string | symbol;+ type?: string | symbol;name: string;disabled?: boolean;icon?;iconSize?: number;text: string;- key: string;+ key?: string;};type MenuProps = {- header: ReactNode;- footer: ReactNode;+ header?: ReactNode;+ footer?: ReactNode;items: Array<MenuItem | typeof Menu.line>;onMenuSelect;};@@ -637,7 +637,7 @@ type AlignedTextProps = ComponentProps<typeof View> & {style?: CSSProperties;leftStyle?: CSSProperties;rightStyle?: CSSProperties;- truncate: 'left' | 'right';+ truncate?: 'left' | 'right';};export function AlignedText({left,@@ -759,7 +759,7 @@ export function FormError({ style, children }: FormErrorProps) {}type InitialFocusProps = {- children?: ReactElement | ((node: unknown) => ReactNode);+ children?: ReactElement | ((node: Ref<HTMLInputElement>) => ReactElement);};export function InitialFocus({ children }: InitialFocusProps) {diff --git a/packages/desktop-client/src/components/common/View.tsx b/packages/desktop-client/src/components/common/View.tsxindex 68849ab909..9229205afc 100644--- a/packages/desktop-client/src/components/common/View.tsx+++ b/packages/desktop-client/src/components/common/View.tsx@@ -1,18 +1,14 @@-import React, {- type HTMLProps,- type Ref,- type StyleHTMLAttributes,-} from 'react';+import React, { type Ref, type StyleHTMLAttributes } from 'react';import { css } from 'glamor';-import type { CSSProperties } from 'glamor';-type ViewProps = {+import { type HTMLPropsWithStyle } from '../../types/utils';++type ViewProps = HTMLPropsWithStyle<HTMLDivElement> & {className?: string;- style?: CSSProperties;nativeStyle?: StyleHTMLAttributes<HTMLDivElement>;innerRef?: Ref<HTMLDivElement>;-} & Omit<HTMLProps<HTMLDivElement>, 'style'>;+};const View = (props: ViewProps) => {// The default styles are special-cased and pulled out into staticdiff --git a/packages/desktop-client/src/components/manager/subscribe/Bootstrap.js b/packages/desktop-client/src/components/manager/subscribe/Bootstrap.tsxsimilarity index 100%rename from packages/desktop-client/src/components/manager/subscribe/Bootstrap.jsrename to packages/desktop-client/src/components/manager/subscribe/Bootstrap.tsxdiff --git a/packages/desktop-client/src/components/manager/subscribe/ChangePassword.js b/packages/desktop-client/src/components/manager/subscribe/ChangePassword.tsxsimilarity index 100%rename from packages/desktop-client/src/components/manager/subscribe/ChangePassword.jsrename to packages/desktop-client/src/components/manager/subscribe/ChangePassword.tsxdiff --git a/packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.js b/packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.tsxsimilarity index 86%rename from packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.jsrename to packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.tsxindex d2540eadc9..c049150eb6 100644--- a/packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.js+++ b/packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.tsx@@ -1,4 +1,4 @@-import React, { useState } from 'react';+import React, { type ChangeEvent, useState } from 'react';import { View, ButtonWithLoading } from '../../common';@@ -44,14 +44,18 @@ export function ConfirmPasswordForm({ buttons, onSetPassword, onError }) {placeholder="Password"type={showPassword ? 'text' : 'password'}value={password1}- onChange={e => setPassword1(e.target.value)}+ onChange={(e: ChangeEvent<HTMLInputElement>) =>+ setPassword1(e.target.value)+ }onEnter={onSubmit}/><Inputplaceholder="Confirm password"type={showPassword ? 'text' : 'password'}value={password2}- onChange={e => setPassword2(e.target.value)}+ onChange={(e: ChangeEvent<HTMLInputElement>) =>+ setPassword2(e.target.value)+ }style={{ marginTop: 10 }}onEnter={onSubmit}/>diff --git a/packages/desktop-client/src/components/manager/subscribe/Error.js b/packages/desktop-client/src/components/manager/subscribe/Error.tsxsimilarity index 94%rename from packages/desktop-client/src/components/manager/subscribe/Error.jsrename to packages/desktop-client/src/components/manager/subscribe/Error.tsxindex d182b272bd..b83a3f5e09 100644--- a/packages/desktop-client/src/components/manager/subscribe/Error.js+++ b/packages/desktop-client/src/components/manager/subscribe/Error.tsx@@ -16,7 +16,7 @@ function getErrorMessage(reason) {export default function Error() {let history = useHistory();let location = useLocation();- let { error } = location.state || {};+ let { error } = (location.state || {}) as { error? };function onTryAgain() {history.push('/');diff --git a/packages/desktop-client/src/components/manager/subscribe/Login.js b/packages/desktop-client/src/components/manager/subscribe/Login.tsxsimilarity index 94%rename from packages/desktop-client/src/components/manager/subscribe/Login.jsrename to packages/desktop-client/src/components/manager/subscribe/Login.tsxindex 3305b9f400..3347246b58 100644--- a/packages/desktop-client/src/components/manager/subscribe/Login.js+++ b/packages/desktop-client/src/components/manager/subscribe/Login.tsx@@ -1,4 +1,4 @@-import React, { useState } from 'react';+import React, { type ChangeEvent, useState } from 'react';import { useDispatch } from 'react-redux';import { createBudget } from 'loot-core/src/client/actions/budgets';@@ -90,7 +90,9 @@ export default function Login() {autoFocus={true}placeholder="Password"type="password"- onChange={e => setPassword(e.target.value)}+ onChange={(e: ChangeEvent<HTMLInputElement>) =>+ setPassword(e.target.value)+ }style={{ flex: 1, marginRight: 10 }}/><ButtonWithLoading primary loading={loading} style={{ fontSize: 15 }}>diff --git a/packages/desktop-client/src/components/manager/subscribe/common.js b/packages/desktop-client/src/components/manager/subscribe/common.tsxsimilarity index 51%rename from packages/desktop-client/src/components/manager/subscribe/common.jsrename to packages/desktop-client/src/components/manager/subscribe/common.tsxindex 6b132de55d..ed96e65706 100644--- a/packages/desktop-client/src/components/manager/subscribe/common.js+++ b/packages/desktop-client/src/components/manager/subscribe/common.tsx@@ -1,6 +1,14 @@-import React, { forwardRef, useEffect, useState } from 'react';+import React, {+ type ComponentProps,+ forwardRef,+ useEffect,+ useState,+ type ReactNode,+} from 'react';import { useHistory, useLocation } from 'react-router-dom';+import { type CSSProperties } from 'glamor';+import { send } from 'loot-core/src/platform/client/fetch';import { colors, styles } from '../../../style';@@ -36,28 +44,27 @@ export function useBootstrapped() {if (url == null) {// A server hasn't been specified yetlet serverURL = window.location.origin;- let { error, hasServer, bootstrapped } = await send(- 'subscribe-needs-bootstrap',- { url: serverURL },- );- if (error || !hasServer) {- console.log(error);+ let result = await send('subscribe-needs-bootstrap', {+ url: serverURL,+ });+ if ('error' in result || !result.hasServer) {+ console.log('error' in result && result.error);history.push('/config-server');return;}await setServerURL(serverURL, { validate: false });- if (bootstrapped) {+ if (result.bootstrapped) {ensure('/login');} else {ensure('/bootstrap');}} else {- let { error, bootstrapped } = await send('subscribe-needs-bootstrap');- if (error) {- history.push('/error', { error });- } else if (bootstrapped) {+ let result = await send('subscribe-needs-bootstrap');+ if ('error' in result) {+ history.push('/error', { error: result.error });+ } else if (result.bootstrapped) {ensure('/login');} else {ensure('/bootstrap');@@ -78,7 +85,10 @@ export function getEmail(location) {return decodeURIComponent(m[1]);}-export function Title({ text }) {+type TitleProps = {+ text: string;+};+export function Title({ text }: TitleProps) {return (<h1style={{@@ -93,7 +103,8 @@ export function Title({ text }) {);}-export const Input = forwardRef((props, ref) => {+type InputProps = ComponentProps<typeof BaseInput>;+export const Input = forwardRef<HTMLInputElement, InputProps>((props, ref) => {return (<BaseInput{...props}@@ -111,62 +122,79 @@ export const Input = forwardRef((props, ref) => {);});-export const BareButton = forwardRef((props, ref) => {- return (- <Button- ref={ref}- bare- {...props}- style={[- {- color: colors.p4,- fontSize: 15,- textDecoration: 'none',- padding: '5px 7px',- borderRadius: 4,- ':hover': {- backgroundColor: colors.n9,+type BareButtonProps = ComponentProps<typeof Button>;+export const BareButton = forwardRef<HTMLButtonElement, BareButtonProps>(+ (props, ref) => {+ return (+ <Button+ ref={ref}+ bare+ {...props}+ style={[+ {+ color: colors.p4,+ fontSize: 15,+ textDecoration: 'none',+ padding: '5px 7px',+ borderRadius: 4,+ ':hover': {+ backgroundColor: colors.n9,+ },+ ':active': {+ backgroundColor: colors.n9,+ },},- ':active': {- backgroundColor: colors.n9,- },- },- props.style,- ]}- />- );-});+ props.style,+ ]}+ />+ );+ },+);-export const ExternalLink = forwardRef((props, ref) => {- let { href, ...linkProps } = props;- return (- <BareButton- to="/"- {...linkProps}- onClick={e => {- e.preventDefault();- window.Actual.openURLInBrowser(href);- }}- />- );-});+type ExternalLinkProps = ComponentProps<typeof BareButton>;+export const ExternalLink = forwardRef<HTMLButtonElement, ExternalLinkProps>(+ (props, ref) => {+ let { href, ...linkProps } = props;+ return (+ <BareButton+ // @ts-expect-error prop does not exist on Button+ to="/"+ {...linkProps}+ onClick={e => {+ e.preventDefault();+ window.Actual.openURLInBrowser(href);+ }}+ />+ );+ },+);-export const BackLink = forwardRef((props, ref) => {- return (- <BareButton- ref={ref}- to="/"- onClick={e => {- e.preventDefault();- props.history.goBack();- }}- >- Back- </BareButton>- );-});+type BackLinkProps = ComponentProps<typeof BareButton> & {+ history;+};+export const BackLink = forwardRef<HTMLButtonElement, BackLinkProps>(+ (props, ref) => {+ return (+ <BareButton+ ref={ref}+ // @ts-expect-error prop does not exist on Button+ to="/"+ onClick={e => {+ e.preventDefault();+ props.history.goBack();+ }}+ >+ Back+ </BareButton>+ );+ },+);-export function Paragraph({ style, children }) {+type ParagraphProps = {+ style?: CSSProperties;+ children: ReactNode;+};+export function Paragraph({ style, children }: ParagraphProps) {return (<Textstyle={[diff --git a/packages/desktop-client/src/components/reports/Container.js b/packages/desktop-client/src/components/reports/Container.tsxsimilarity index 54%rename from packages/desktop-client/src/components/reports/Container.jsrename to packages/desktop-client/src/components/reports/Container.tsxindex e3850268bf..d8d54c9ad1 100644--- a/packages/desktop-client/src/components/reports/Container.js+++ b/packages/desktop-client/src/components/reports/Container.tsx@@ -1,10 +1,16 @@-import React, { useRef } from 'react';+import React, { type ReactNode, useRef } from 'react';import AutoSizer from 'react-virtualized-auto-sizer';+import { type CSSProperties } from 'glamor';+import { View } from '../common';-export default function Container({ style, children }) {- const portalHost = useRef(null);+type ContainerProps = {+ style?: CSSProperties;+ children: (width: number, height: number, host: HTMLDivElement) => ReactNode;+};+export default function Container({ style, children }: ContainerProps) {+ const portalHost = useRef<HTMLDivElement>(null);return (<View style={[{ height: 300, position: 'relative', flexShrink: 0 }, style]}>diff --git a/packages/desktop-client/src/components/reports/graphs/CashFlowGraph.js b/packages/desktop-client/src/components/reports/graphs/CashFlowGraph.tsxsimilarity index 91%rename from packages/desktop-client/src/components/reports/graphs/CashFlowGraph.jsrename to packages/desktop-client/src/components/reports/graphs/CashFlowGraph.tsxindex f00b0b9f5f..a83abe5252 100644--- a/packages/desktop-client/src/components/reports/graphs/CashFlowGraph.js+++ b/packages/desktop-client/src/components/reports/graphs/CashFlowGraph.tsx@@ -15,7 +15,11 @@ import theme from '../chart-theme';import Container from '../Container';import Tooltip from '../Tooltip';-function CashFlowGraph({ style, start, end, graphData, isConcise, compact }) {+type CashFlowGraphProps = {+ graphData: { expenses; income; balances };+ isConcise: boolean;+};+function CashFlowGraph({ graphData, isConcise }: CashFlowGraphProps) {return (<Container>{(width, height, portalHost) =>diff --git a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.js b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsxsimilarity index 90%rename from packages/desktop-client/src/components/reports/graphs/NetWorthGraph.jsrename to packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsxindex dbaeb4248f..3eebc6c9d8 100644--- a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.js+++ b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx@@ -1,6 +1,7 @@import React, { createElement } from 'react';import * as d from 'date-fns';+import { type CSSProperties } from 'glamor';import {VictoryChart,VictoryBar,@@ -14,7 +15,13 @@ import theme from '../chart-theme';import Container from '../Container';import Tooltip from '../Tooltip';-function Area({ start, end, data, style, scale, range }) {+type AreaProps = {+ start: string;+ end: string;+ scale?;+ range?;+};+function Area({ start, end, scale, range }: AreaProps) {const zero = scale.y(0);const startX = scale.x(d.parseISO(start + '-01'));@@ -72,7 +79,12 @@ function Area({ start, end, data, style, scale, range }) {);}-function NetWorthGraph({ style, start, end, graphData, compact }) {+type NetWorthGraphProps = {+ style?: CSSProperties;+ graphData;+ compact: boolean;+};+function NetWorthGraph({ style, graphData, compact }: NetWorthGraphProps) {const Chart = compact ? VictoryGroup : VictoryChart;return (@@ -97,12 +109,9 @@ function NetWorthGraph({ style, start, end, graphData, compact }) {}}>- <Area- start={graphData.start}- end={graphData.end}- data={graphData.data}- />+ <Area start={graphData.start} end={graphData.end} />{createElement(+ // @ts-expect-error defaultProps mismatch causing issuegraphData.data.length === 1 ? VictoryBar : VictoryArea,{data: graphData.data,diff --git a/packages/desktop-client/src/components/reports/graphs/cash-flow-spreadsheet.js b/packages/desktop-client/src/components/reports/graphs/cash-flow-spreadsheet.tsxsimilarity index 100%rename from packages/desktop-client/src/components/reports/graphs/cash-flow-spreadsheet.jsrename to packages/desktop-client/src/components/reports/graphs/cash-flow-spreadsheet.tsxdiff --git a/packages/desktop-client/src/components/reports/graphs/net-worth-spreadsheet.js b/packages/desktop-client/src/components/reports/graphs/net-worth-spreadsheet.tsxsimilarity index 100%rename from packages/desktop-client/src/components/reports/graphs/net-worth-spreadsheet.jsrename to packages/desktop-client/src/components/reports/graphs/net-worth-spreadsheet.tsxdiff --git a/packages/desktop-client/src/components/spreadsheet/CellValue.js b/packages/desktop-client/src/components/spreadsheet/CellValue.tsxsimilarity index 57%rename from packages/desktop-client/src/components/spreadsheet/CellValue.jsrename to packages/desktop-client/src/components/spreadsheet/CellValue.tsxindex cefcbf8829..215720ca82 100644--- a/packages/desktop-client/src/components/spreadsheet/CellValue.js+++ b/packages/desktop-client/src/components/spreadsheet/CellValue.tsx@@ -1,4 +1,6 @@-import React from 'react';+import React, { type ComponentProps, type ReactNode } from 'react';++import { type CSSProperties } from 'glamor';import { styles } from '../../style';import Text from '../common/Text';@@ -6,9 +8,23 @@ import Text from '../common/Text';import format from './format';import SheetValue from './SheetValue';-function CellValue({ binding, type, formatter, style, getStyle, debug }) {+type CellValueProps = {+ binding: ComponentProps<typeof SheetValue>['binding'];+ type?: string;+ formatter?: (value) => ReactNode;+ style?: CSSProperties;+ getStyle?: (value) => CSSProperties;+};++function CellValue({+ binding,+ type,+ formatter,+ style,+ getStyle,+}: CellValueProps) {return (- <SheetValue binding={binding} debug={debug}>+ <SheetValue binding={binding}>{({ name, value }) => {return (<Textdiff --git a/packages/desktop-client/src/components/spreadsheet/SheetValue.js b/packages/desktop-client/src/components/spreadsheet/SheetValue.tsxsimilarity index 64%rename from packages/desktop-client/src/components/spreadsheet/SheetValue.jsrename to packages/desktop-client/src/components/spreadsheet/SheetValue.tsxindex a0141db5a8..b1810c0085 100644--- a/packages/desktop-client/src/components/spreadsheet/SheetValue.js+++ b/packages/desktop-client/src/components/spreadsheet/SheetValue.tsx@@ -1,9 +1,23 @@-import { useContext, useState, useRef, useLayoutEffect } from 'react';+import {+ useContext,+ useState,+ useRef,+ useLayoutEffect,+ type ReactNode,+} from 'react';import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';import NamespaceContext from './NamespaceContext.js';+type Binding = { name: string; value; query?: unknown };++type SheetValueProps = {+ binding: string | Binding;+ initialValue?;+ children?: (result: Binding, setCell: () => void) => ReactNode;+ onChange?;+};// !! Do not use this!! This is deprecated. Use the `useSheetValue`// hook instead. The reason this hasn't been refactored on top of it// is because the hook only exposes the value, not the node. It also@@ -14,7 +28,7 @@ export default function SheetValue({initialValue,children,onChange,-}) {+}: SheetValueProps) {if (!binding) {throw new Error('SheetValue binding is required');}@@ -23,23 +37,24 @@ export default function SheetValue({binding = { ...binding, name: binding.value.toString() };}- binding =+ const bindingObj =typeof binding === 'string' ? { name: binding, value: null } : binding;- if (binding.name == null) {+ if (bindingObj.name == null) {throw new Error('Binding name is now required');}let spreadsheet = useSpreadsheet();let sheetName = useContext(NamespaceContext) || '__global';let [result, setResult] = useState({- name: sheetName + '!' + binding.name,- value: initialValue != null ? initialValue : binding.value,- query: binding.query,+ name: sheetName + '!' + bindingObj.name,+ value: initialValue != null ? initialValue : bindingObj.value,+ query: bindingObj.query,});let latestOnChange = useRef(onChange);let latestValue = useRef(result.value);+ /** @deprecated */function setCell() {throw new Error('setCell is not implemented anymore');}@@ -50,11 +65,11 @@ export default function SheetValue({});useLayoutEffect(() => {- if (binding.query) {- spreadsheet.createQuery(sheetName, binding.name, binding.query);+ if (bindingObj.query) {+ spreadsheet.createQuery(sheetName, bindingObj.name, bindingObj.query);}- return spreadsheet.bind(sheetName, binding, null, newResult => {+ return spreadsheet.bind(sheetName, bindingObj, null, newResult => {if (latestOnChange.current) {latestOnChange.current(newResult);}@@ -63,7 +78,7 @@ export default function SheetValue({setResult(newResult);}});- }, [sheetName, binding.name]);+ }, [sheetName, bindingObj.name]);- return result.value != null ? children(result, setCell) : null;+ return result.value != null ? <>{children(result, setCell)}</> : null;}diff --git a/packages/desktop-client/src/components/table.js b/packages/desktop-client/src/components/table.tsxsimilarity index 85%rename from packages/desktop-client/src/components/table.jsrename to packages/desktop-client/src/components/table.tsxindex 585d57eb12..7d50ed73eb 100644--- a/packages/desktop-client/src/components/table.js+++ b/packages/desktop-client/src/components/table.tsx@@ -9,10 +9,16 @@ import React, {useImperativeHandle,useContext,useMemo,+ type ComponentProps,+ type ReactNode,+ type KeyboardEvent,+ type UIEvent,} from 'react';import { useStore } from 'react-redux';import AutoSizer from 'react-virtualized-auto-sizer';+import { type CSSProperties } from 'glamor';+import {AvoidRefocusScrollProvider,useProperFocus,@@ -58,7 +64,16 @@ const CellContext = createContext({borderColor: colors.n9,});-function CellProvider({ backgroundColor, borderColor, children }) {+type CellProviderProps = {+ backgroundColor: string;+ borderColor: string;+ children: ReactNode;+};+function CellProvider({+ backgroundColor,+ borderColor,+ children,+}: CellProviderProps) {let value = useMemo(() => ({backgroundColor,@@ -70,7 +85,14 @@ function CellProvider({ backgroundColor, borderColor, children }) {return <CellContext.Provider value={value}>{children}</CellContext.Provider>;}-export const Field = forwardRef(function Field(+type FieldProps = ComponentProps<typeof View> & {+ width: number | 'flex';+ name?: string;+ borderColor?: string;+ truncate?: boolean;+ contentStyle?: CSSProperties;+};+export const Field = forwardRef<HTMLDivElement, FieldProps>(function Field({width,name,@@ -140,6 +162,18 @@ export const Field = forwardRef(function Field();});+type CellProps = Omit<ComponentProps<typeof View>, 'children' | 'value'> & {+ formatter?: (value: string, type?: unknown) => string;+ focused?: boolean;+ textAlign?: string;+ borderColor?: string;+ plain?: boolean;+ exposed?: boolean;+ children?: ReactNode | (() => ReactNode);+ value?: string;+ valueStyle?: CSSProperties;+ onExpose?: (name: string) => void;+};export function Cell({width,name,@@ -155,7 +189,7 @@ export function Cell({style,valueStyle,...viewProps-}) {+}: CellProps) {let mouseCoords = useRef(null);let viewRef = useRef(null);@@ -191,6 +225,7 @@ export function Cell({{plain ? (children) : exposed ? (+ // @ts-expect-error Missing props refinementchildren()) : (<View@@ -234,6 +269,14 @@ export function Cell({);}+type RowProps = ComponentProps<typeof View> & {+ backgroundColor?: string;+ borderColor?: string;+ inset?: number;+ collapsed?: boolean;+ focused?: boolean;+ highlighted?: boolean;+};export function Row({backgroundColor = 'white',borderColor = colors.border,@@ -245,7 +288,7 @@ export function Row({height,style,...nativeProps-}) {+}: RowProps) {let [shouldHighlight, setShouldHighlight] = useState(false);let prevHighlighted = useRef(false);let rowRef = useRef(null);@@ -315,7 +358,15 @@ const readonlyInputStyle = {'::selection': { backgroundColor: '#d9d9d9' },};-function InputValue({ value: defaultValue, onUpdate, onBlur, ...props }) {+type InputValueProps = ComponentProps<typeof Input> & {+ value: string;+};+function InputValue({+ value: defaultValue,+ onUpdate,+ onBlur,+ ...props+}: InputValueProps) {let [value, setValue] = useState(defaultValue);function onBlur_(e) {@@ -355,6 +406,13 @@ function InputValue({ value: defaultValue, onUpdate, onBlur, ...props }) {);}+type InputCellProps = ComponentProps<typeof Cell> & {+ inputProps: ComponentProps<typeof InputValue>;+ onUpdate: ComponentProps<typeof InputValue>['onUpdate'];+ onBlur: ComponentProps<typeof InputValue>['onBlur'];+ textAlign?: string;+ error?: ReactNode;+};export function InputCell({inputProps,onUpdate,@@ -362,7 +420,7 @@ export function InputCell({textAlign,error,...props-}) {+}: InputCellProps) {return (<Cell textAlign={textAlign} {...props}>{() => (@@ -400,13 +458,26 @@ export function shouldSaveFromKey(e) {}}+type CustomCellRenderProps = {+ onBlur: (ev: UIEvent<unknown>) => void;+ onKeyDown: (ev: KeyboardEvent<unknown>) => void;+ onUpdate: (value: string) => void;+ onSave: (value: string) => void;+ shouldSaveFromKey: (ev: KeyboardEvent<unknown>) => boolean;+ inputStyle: CSSProperties;+};+type CustomCellProps = Omit<ComponentProps<typeof Cell>, 'children'> & {+ children: (props: CustomCellRenderProps) => ReactNode;+ onUpdate: (value: string) => void;+ onBlur: (ev: UIEvent<unknown>) => void;+};export function CustomCell({value: defaultValue,children,onUpdate,onBlur,...props-}) {+}: CustomCellProps) {let [value, setValue] = useState(defaultValue);let [prevDefaultValue, setPrevDefaultValue] = useState(defaultValue);@@ -450,7 +521,10 @@ export function CustomCell({);}-export function DeleteCell({ onDelete, style, ...props }) {+type DeleteCellProps = Omit<ComponentProps<typeof Cell>, 'children'> & {+ onDelete?: () => void;+};+export function DeleteCell({ onDelete, style, ...props }: DeleteCellProps) {return (<Cell{...props}@@ -467,7 +541,15 @@ export function DeleteCell({ onDelete, style, ...props }) {);}-export const CellButton = forwardRef(+type CellButtonProps = {+ style?: CSSProperties;+ disabled?: boolean;+ clickBehavior?: string;+ onSelect?: (e) => void;+ onEdit?: () => void;+ children: ReactNode;+};+export const CellButton = forwardRef<HTMLDivElement, CellButtonProps>(({ style, disabled, clickBehavior, onSelect, onEdit, children }, ref) => {// This represents a cell that acts like a button: it's clickable,// focusable, etc. The reason we don't use a button is because the@@ -486,7 +568,7 @@ export const CellButton = forwardRef(<ViewinnerRef={ref}className="cell-button"- tabIndex="0"+ tabIndex={0}onKeyDown={e => {if (e.key === 'x' || e.key === ' ') {e.preventDefault();@@ -527,6 +609,11 @@ export const CellButton = forwardRef(},);+type SelectCellProps = Omit<ComponentProps<typeof Cell>, 'children'> & {+ partial: boolean;+ onEdit?: () => void;+ onSelect?: (e) => void;+};export function SelectCell({focused,selected,@@ -535,7 +622,7 @@ export function SelectCell({onSelect,onEdit,...props-}) {+}: SelectCellProps) {return (<Cell{...props}@@ -583,24 +670,36 @@ export function SelectCell({);}+type SheetCellValueProps = {+ binding: ComponentProps<typeof SheetValue>['binding'];+ type: string;+ getValueStyle?: (value: unknown) => CSSProperties;+ formatExpr?: (value) => string;+ unformatExpr?: (value: string) => unknown;+};++type SheetCellProps = ComponentProps<typeof Cell> & {+ valueProps: SheetCellValueProps;+ inputProps?: Omit<ComponentProps<typeof InputValue>, 'value' | 'onUpdate'>;+ onSave?: (value) => void;+};export function SheetCell({valueProps,valueStyle,inputProps,- sync,textAlign,onSave,...props-}) {+}: SheetCellProps) {const { binding, type, getValueStyle, formatExpr, unformatExpr } = valueProps;return (<SheetValuebinding={binding}- onChange={() => {+ onChange={e => {// "close" the cell if it's editingif (props.exposed && inputProps && inputProps.onBlur) {- inputProps.onBlur();+ inputProps.onBlur(e);}}}>@@ -641,7 +740,16 @@ export function SheetCell({);}-export function TableHeader({ headers, children, version, ...rowProps }) {+type TableHeaderProps = ComponentProps<typeof Row> & {+ headers?: Array<ComponentProps<typeof Cell>>;+ version?: string;+};+export function TableHeader({+ headers,+ children,+ version,+ ...rowProps+}: TableHeaderProps) {return (<Viewstyle={@@ -726,12 +834,59 @@ export function SelectedItemsButton({ name, keyHandlers, items, onSelect }) {let rowStyle = { position: 'absolute', willChange: 'transform', width: '100%' };-export const TableWithNavigator = forwardRef(({ fields, ...props }, ref) => {+type TableHandleRef = {+ scrollTo: (id: number, alignment?: string) => void;+ scrollToTop: () => void;+ getScrolledItem: () => number;+ setRowAnimation: (flag) => void;+ edit(id: number, field, shouldScroll): void;+ anchor(): void;+ unanchor(): void;+ isAnchored(): boolean;+};++type TableWithNavigatorProps = TableProps & {+ fields;+};+export const TableWithNavigator = forwardRef<+ TableHandleRef,+ TableWithNavigatorProps+>(({ fields, ...props }, ref) => {let navigator = useTableNavigator(props.items, fields);return <Table {...props} navigator={navigator} />;});-export const Table = forwardRef(+type TableItem = { id: number };++type TableProps = {+ items: TableItem[];+ count?: number;+ headers?: ReactNode | TableHeaderProps['headers'];+ contentHeader: ReactNode;+ loading: boolean;+ rowHeight?: number;+ backgroundColor?: string;+ renderItem: (arg: {+ item: TableItem;+ editing: boolean;+ focusedField: unknown;+ onEdit: (id, field) => void;+ index: number;+ position: number;+ }) => ReactNode;+ renderEmpty?: ReactNode | (() => ReactNode);+ getItemKey: (index: number) => TableItem['id'];+ loadMore?: () => void;+ style?: CSSProperties;+ navigator: ReturnType<typeof useTableNavigator>;+ listRef;+ onScroll: () => void;+ version?: string;+ animated?: boolean;+ allowPopupsEscape?: boolean;+ isSelected?: (id: TableItem['id']) => boolean;+};+export const Table = forwardRef<TableHandleRef, TableProps>(({items,@@ -808,6 +963,7 @@ export const Table = forwardRef(onEdit(id, field);if (id && shouldScroll) {+ // @ts-expect-error this should not be possibleref.scrollTo(id);}},@@ -863,6 +1019,7 @@ export const Table = forwardRef(transform: 'translateY(var(--pos))',},]}+ // @ts-expect-error not a recognised style attributenativeStyle={{ '--pos': `${style.top - 1}px` }}data-focus-key={item.id}>@@ -1006,14 +1163,14 @@ export function useTableNavigator(data, fields) {let getFields = typeof fields !== 'function' ? () => fields : fields;let [editingId, setEditingId] = useState(null);let [focusedField, setFocusedField] = useState(null);- let containerRef = useRef();+ let containerRef = useRef<HTMLDivElement>();// See `onBlur` for why we need thislet store = useStore();let modalStackLength = useRef(0);// onEdit is passed to children, so make sure it maintains identity- let onEdit = useCallback((id, field) => {+ let onEdit = useCallback((id, field?) => {setEditingId(id);setFocusedField(id ? field : null);}, []);diff --git a/packages/loot-core/src/client/query-hooks.tsx b/packages/loot-core/src/client/query-hooks.tsxindex da9b988c95..2525140874 100644--- a/packages/loot-core/src/client/query-hooks.tsx+++ b/packages/loot-core/src/client/query-hooks.tsx@@ -70,7 +70,7 @@ export function pagedQueryContext(query, opts) {return makeContext(query, opts, PagedQuery);}-export function useLiveQuery(query, opts) {+export function useLiveQuery(query, opts?) {let [data, setData] = useState(null);useEffect(() => {diff --git a/packages/loot-core/src/server/notes/types/handlers.d.ts b/packages/loot-core/src/server/notes/types/handlers.d.tsindex 873a7fb12b..2c4f576a54 100644--- a/packages/loot-core/src/server/notes/types/handlers.d.ts+++ b/packages/loot-core/src/server/notes/types/handlers.d.ts@@ -1,3 +1,3 @@-export interface NoteHandlers {+export interface NotesHandlers {'notes-save': (arg: { id; note }) => Promise<unknown>;}diff --git a/packages/loot-core/src/types/main.handlers.d.ts b/packages/loot-core/src/types/main.handlers.d.tsindex 90cb6cc8b8..66f41d141c 100644--- a/packages/loot-core/src/types/main.handlers.d.ts+++ b/packages/loot-core/src/types/main.handlers.d.ts@@ -101,7 +101,9 @@ export interface MainHandlers {'rules-run': (arg: { transaction }) => Promise<unknown>;- 'make-filters-from-conditions': (arg: { conditions }) => Promise<unknown>;+ 'make-filters-from-conditions': (arg: {+ conditions;+ }) => Promise<{ filters: unknown[] }>;getCell: (arg: { sheetName; name }) => Promise<unknown>;diff --git a/upcoming-release-notes/1037.md b/upcoming-release-notes/1037.mdnew file mode 100644index 0000000000..9169905c6d--- /dev/null+++ b/upcoming-release-notes/1037.md@@ -0,0 +1,6 @@+---+category: Maintenance+authors: [albertogasparin]+---++Convert few other components in `desktop-client` to Typescript