Skip to content

Commit

Permalink
♻️ (synced-prefs) refactor some SyncedPrefs to string type (#3395)
Browse files Browse the repository at this point in the history
  • Loading branch information
MatissJanis authored Sep 8, 2024
1 parent 21dc573 commit 95ed7aa
Show file tree
Hide file tree
Showing 21 changed files with 125 additions and 97 deletions.
7 changes: 4 additions & 3 deletions packages/desktop-client/src/components/Titlebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,16 @@ type PrivacyButtonProps = {
};

function PrivacyButton({ style }: PrivacyButtonProps) {
const [isPrivacyEnabled, setPrivacyEnabledPref] =
const [isPrivacyEnabledPref, setPrivacyEnabledPref] =
useSyncedPref('isPrivacyEnabled');
const isPrivacyEnabled = String(isPrivacyEnabledPref) === 'true';

const privacyIconStyle = { width: 15, height: 15 };

useHotkeys(
'shift+ctrl+p, shift+cmd+p, shift+meta+p',
() => {
setPrivacyEnabledPref(!isPrivacyEnabled);
setPrivacyEnabledPref(String(!isPrivacyEnabled));
},
{
preventDefault: true,
Expand All @@ -81,7 +82,7 @@ function PrivacyButton({ style }: PrivacyButtonProps) {
<Button
variant="bare"
aria-label={`${isPrivacyEnabled ? 'Disable' : 'Enable'} privacy mode`}
onPress={() => setPrivacyEnabledPref(!isPrivacyEnabled)}
onPress={() => setPrivacyEnabledPref(String(!isPrivacyEnabled))}
style={style}
>
{isPrivacyEnabled ? (
Expand Down
24 changes: 14 additions & 10 deletions packages/desktop-client/src/components/accounts/Account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1836,7 +1836,7 @@ export function Account() {
const payees = usePayees();
const failedAccounts = useFailedAccounts();
const dateFormat = useDateFormat() || 'MM/dd/yyyy';
const [hideFraction = false] = useSyncedPref('hideFraction');
const [hideFraction] = useSyncedPref('hideFraction');
const [expandSplits] = useLocalPref('expand-splits');
const [showBalances, setShowBalances] = useSyncedPref(
`show-balances-${params.id}`,
Expand Down Expand Up @@ -1871,16 +1871,20 @@ export function Account() {
accounts={accounts}
failedAccounts={failedAccounts}
dateFormat={dateFormat}
hideFraction={hideFraction}
hideFraction={String(hideFraction) === 'true'}
expandSplits={expandSplits}
showBalances={showBalances}
setShowBalances={setShowBalances}
showCleared={!hideCleared}
setShowCleared={val => setHideCleared(!val)}
showReconciled={!hideReconciled}
setShowReconciled={val => setHideReconciled(!val)}
showExtraBalances={showExtraBalances}
setShowExtraBalances={setShowExtraBalances}
showBalances={String(showBalances) === 'true'}
setShowBalances={showBalances =>
setShowBalances(String(showBalances))
}
showCleared={String(hideCleared) !== 'true'}
setShowCleared={val => setHideCleared(String(!val))}
showReconciled={String(hideReconciled) !== 'true'}
setShowReconciled={val => setHideReconciled(String(!val))}
showExtraBalances={String(showExtraBalances) === 'true'}
setShowExtraBalances={extraBalances =>
setShowExtraBalances(String(extraBalances))
}
payees={payees}
modalShowing={modalShowing}
accountsSyncing={accountsSyncing}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function Account() {

const [_numberFormat] = useSyncedPref('numberFormat');
const numberFormat = _numberFormat || 'comma-dot';
const [hideFraction = false] = useSyncedPref('hideFraction');
const [hideFraction] = useSyncedPref('hideFraction');

const { id: accountId } = useParams();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import { isPreviewId } from 'loot-core/shared/transactions';
import { useDateFormat } from '../../../hooks/useDateFormat';
import { useNavigate } from '../../../hooks/useNavigate';
import { usePreviewTransactions } from '../../../hooks/usePreviewTransactions';
import { useSyncedPref } from '../../../hooks/useSyncedPref';
import { styles, theme } from '../../../style';
import { Text } from '../../common/Text';
import { View } from '../../common/View';
Expand Down Expand Up @@ -153,7 +152,6 @@ function TransactionListWithPreviews({ account }) {
);

const dateFormat = useDateFormat() || 'MM/dd/yyyy';
const [_numberFormat] = useSyncedPref('numberFormat');
const dispatch = useDispatch();
const navigate = useNavigate();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ export function Accounts() {
const updatedAccounts = useSelector(state => state.queries.updatedAccounts);
const [_numberFormat] = useSyncedPref('numberFormat');
const numberFormat = _numberFormat || 'comma-dot';
const [hideFraction = false] = useSyncedPref('hideFraction');
const [hideFraction] = useSyncedPref('hideFraction');

const navigate = useNavigate();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function Category() {
useSetThemeColor(theme.mobileViewTheme);
const [_numberFormat] = useSyncedPref('numberFormat');
const numberFormat = _numberFormat || 'comma-dot';
const [hideFraction = false] = useSyncedPref('hideFraction');
const [hideFraction] = useSyncedPref('hideFraction');

const { id: categoryId } = useParams();
const [searchParams] = useSearchParams();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { isPreviewId } from 'loot-core/shared/transactions';

import { useDateFormat } from '../../../hooks/useDateFormat';
import { useNavigate } from '../../../hooks/useNavigate';
import { useSyncedPref } from '../../../hooks/useSyncedPref';
import { TextOneLine } from '../../common/TextOneLine';
import { View } from '../../common/View';
import { MobilePageHeader, Page } from '../../Page';
Expand All @@ -29,7 +28,6 @@ export function CategoryTransactions({ category, month }) {
const [transactions, setTransactions] = useState([]);

const dateFormat = useDateFormat() || 'MM/dd/yyyy';
const [_numberFormat] = useSyncedPref('numberFormat');

const makeRootQuery = useCallback(
() =>
Expand Down
10 changes: 7 additions & 3 deletions packages/desktop-client/src/components/mobile/budget/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ import { SyncRefresh } from '../../SyncRefresh';

import { BudgetTable } from './BudgetTable';

function isBudgetType(input?: string): input is 'rollover' | 'report' {
return ['rollover', 'report'].includes(input);
}

type BudgetInnerProps = {
categories: CategoryEntity[];
categoryGroups: CategoryGroupEntity[];
Expand All @@ -60,7 +64,7 @@ function BudgetInner(props: BudgetInnerProps) {

const [_numberFormat] = useSyncedPref('numberFormat');
const numberFormat = _numberFormat || 'comma-dot';
const [hideFraction = false] = useSyncedPref('hideFraction');
const [hideFraction] = useSyncedPref('hideFraction');
const dispatch = useDispatch();

useEffect(() => {
Expand Down Expand Up @@ -462,14 +466,14 @@ function BudgetInner(props: BudgetInnerProps) {

export function Budget() {
const { list: categories, grouped: categoryGroups } = useCategories();
const [budgetType = 'rollover'] = useSyncedPref('budgetType');
const [budgetType] = useSyncedPref('budgetType');
const spreadsheet = useSpreadsheet();
useSetThemeColor(theme.mobileViewTheme);
return (
<BudgetInner
categoryGroups={categoryGroups}
categories={categories}
budgetType={budgetType}
budgetType={isBudgetType(budgetType) ? budgetType : 'rollover'}
spreadsheet={spreadsheet}
/>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const AmountInput = memo(function AmountInput({
const [text, setText] = useState('');
const [value, setValue] = useState(0);
const inputRef = useRef<HTMLInputElement>();
const [hideFraction = false] = useSyncedPref('hideFraction');
const [hideFraction] = useSyncedPref('hideFraction');

const mergedInputRef = useMergedRefs<HTMLInputElement>(
props.inputRef,
Expand Down Expand Up @@ -107,7 +107,7 @@ const AmountInput = memo(function AmountInput({
};

const onChangeText = (text: string) => {
text = appendDecimals(text, hideFraction);
text = appendDecimals(text, String(hideFraction) === 'true');
setEditing(true);
setText(text);
props.onChangeValue?.(text);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -875,13 +875,13 @@ export function ImportTransactions({ options }) {
(filename.endsWith('.tsv') ? '\t' : ','),
);
const [skipLines, setSkipLines] = useState(
prefs[`csv-skip-lines-${accountId}`] ?? 0,
parseInt(prefs[`csv-skip-lines-${accountId}`], 10) || 0,
);
const [hasHeaderRow, setHasHeaderRow] = useState(
prefs[`csv-has-header-${accountId}`] ?? true,
String(prefs[`csv-has-header-${accountId}`]) !== 'false',
);
const [fallbackMissingPayeeToMemo, setFallbackMissingPayeeToMemo] = useState(
prefs[`ofx-fallback-missing-payee-${accountId}`] ?? true,
String(prefs[`ofx-fallback-missing-payee-${accountId}`]) !== 'false',
);

const [parseDateFormat, setParseDateFormat] = useState(null);
Expand Down Expand Up @@ -923,7 +923,8 @@ export function ImportTransactions({ options }) {
let parseDateFormat = null;

if (filetype === 'csv' || filetype === 'qif') {
flipAmount = prefs[`flip-amount-${accountId}-${filetype}`] || false;
flipAmount =
String(prefs[`flip-amount-${accountId}-${filetype}`]) === 'true';
setFlipAmount(flipAmount);
}

Expand Down Expand Up @@ -1186,7 +1187,9 @@ export function ImportTransactions({ options }) {

if (isOfxFile(filetype)) {
savePrefs({
[`ofx-fallback-missing-payee-${accountId}`]: fallbackMissingPayeeToMemo,
[`ofx-fallback-missing-payee-${accountId}`]: String(
fallbackMissingPayeeToMemo,
),
});
}

Expand All @@ -1195,12 +1198,14 @@ export function ImportTransactions({ options }) {
[`csv-mappings-${accountId}`]: JSON.stringify(fieldMappings),
});
savePrefs({ [`csv-delimiter-${accountId}`]: delimiter });
savePrefs({ [`csv-has-header-${accountId}`]: hasHeaderRow });
savePrefs({ [`csv-skip-lines-${accountId}`]: skipLines });
savePrefs({ [`csv-has-header-${accountId}`]: String(hasHeaderRow) });
savePrefs({ [`csv-skip-lines-${accountId}`]: String(skipLines) });
}

if (filetype === 'csv' || filetype === 'qif') {
savePrefs({ [`flip-amount-${accountId}-${filetype}`]: flipAmount });
savePrefs({
[`flip-amount-${accountId}-${filetype}`]: String(flipAmount),
});
}

const didChange = await importTransactions(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function FeatureToggle({
<Checkbox
checked={enabled}
onChange={() => {
setFlagPref(!enabled);
setFlagPref(String(!enabled));
}}
disabled={disableToggle}
/>
Expand Down
11 changes: 6 additions & 5 deletions packages/desktop-client/src/components/settings/Format.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ export function FormatSettings() {
const [, setDateFormatPref] = useSyncedPref('dateFormat');
const [_numberFormat, setNumberFormatPref] = useSyncedPref('numberFormat');
const numberFormat = _numberFormat || 'comma-dot';
const [hideFraction = false, setHideFractionPref] =
useSyncedPref('hideFraction');
const [hideFraction, setHideFractionPref] = useSyncedPref('hideFraction');

const selectButtonStyle: CSSProperties = {
':hover': {
Expand Down Expand Up @@ -95,16 +94,18 @@ export function FormatSettings() {
onChange={format => setNumberFormatPref(format)}
options={numberFormats.map(f => [
f.value,
hideFraction ? f.labelNoFraction : f.label,
String(hideFraction) === 'true' ? f.labelNoFraction : f.label,
])}
buttonStyle={selectButtonStyle}
/>

<Text style={{ display: 'flex' }}>
<Checkbox
id="settings-textDecimal"
checked={!!hideFraction}
onChange={e => setHideFractionPref(e.currentTarget.checked)}
checked={String(hideFraction) === 'true'}
onChange={e =>
setHideFractionPref(String(e.currentTarget.checked))
}
/>
<label htmlFor="settings-textDecimal">Hide decimal places</label>
</Text>
Expand Down
6 changes: 4 additions & 2 deletions packages/desktop-client/src/components/util/AmountInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function AmountInput({
const buttonRef = useRef();
const ref = useRef<HTMLInputElement>(null);
const mergedRef = useMergedRefs<HTMLInputElement>(inputRef, ref);
const [hideFraction = false] = useSyncedPref('hideFraction');
const [hideFraction] = useSyncedPref('hideFraction');

useEffect(() => {
if (focused) {
Expand All @@ -81,7 +81,9 @@ export function AmountInput({
}

function onInputTextChange(val) {
val = autoDecimals ? appendDecimals(val, hideFraction) : val;
val = autoDecimals
? appendDecimals(val, String(hideFraction) === 'true')
: val;
setValue(val ? val : '');
onChangeValue?.(val);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop-client/src/hooks/useFeatureFlag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ export function useFeatureFlag(name: FeatureFlag): boolean {

return value === undefined
? DEFAULT_FEATURE_FLAG_STATE[name] || false
: value;
: String(value) === 'true';
});
}
9 changes: 3 additions & 6 deletions packages/desktop-client/src/hooks/usePrivacyMode.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { useSelector } from 'react-redux';

import { type State } from 'loot-core/src/client/state-types';
import { useSyncedPref } from './useSyncedPref';

export function usePrivacyMode() {
return useSelector(
(state: State) => state.prefs.local?.isPrivacyEnabled ?? false,
);
const [isPrivacyEnabled] = useSyncedPref('isPrivacyEnabled');
return String(isPrivacyEnabled) === 'true';
}
22 changes: 15 additions & 7 deletions packages/loot-core/src/client/reducers/prefs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @ts-strict-ignore
import { setNumberFormat } from '../../shared/util';
import { isNumberFormat, setNumberFormat } from '../../shared/util';
import * as constants from '../constants';
import type { Action } from '../state-types';
import type { PrefsState } from '../state-types/prefs';
Expand All @@ -14,19 +14,27 @@ export function update(state = initialState, action: Action): PrefsState {
case constants.SET_PREFS:
if (action.prefs) {
setNumberFormat({
format: action.prefs.numberFormat || 'comma-dot',
hideFraction: action.prefs.hideFraction,
format: isNumberFormat(action.prefs.numberFormat)
? action.prefs.numberFormat
: 'comma-dot',
hideFraction: String(action.prefs.hideFraction) === 'true',
});
}
return { local: action.prefs, global: action.globalPrefs };
case constants.MERGE_LOCAL_PREFS:
if (action.prefs.numberFormat || action.prefs.hideFraction != null) {
setNumberFormat({
format: action.prefs.numberFormat || state.local.numberFormat,
format: isNumberFormat(action.prefs.numberFormat)
? action.prefs.numberFormat
: isNumberFormat(state.local.numberFormat)
? state.local.numberFormat
: 'comma-dot',
hideFraction:
action.prefs.hideFraction != null
? action.prefs.hideFraction
: state.local.hideFraction,
String(
action.prefs.hideFraction != null
? action.prefs.hideFraction
: state.local.hideFraction,
) === 'true',
});
}

Expand Down
6 changes: 3 additions & 3 deletions packages/loot-core/src/client/selectors.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @ts-strict-ignore
import { createSelector } from 'reselect';

import { getNumberFormat } from '../shared/util';
import { getNumberFormat, isNumberFormat } from '../shared/util';

import type { State } from './state-types';

Expand All @@ -12,7 +12,7 @@ const getLocalPrefsState = createSelector(getPrefsState, prefs => prefs.local);

export const selectNumberFormat = createSelector(getLocalPrefsState, prefs =>
getNumberFormat({
format: prefs.numberFormat,
hideFraction: prefs.hideFraction,
format: isNumberFormat(prefs.numberFormat) ? prefs.numberFormat : undefined,
hideFraction: String(prefs.hideFraction) === 'true',
}),
);
Loading

0 comments on commit 95ed7aa

Please sign in to comment.