Skip to content

A local-first personal finance app

:recycle: extract rules components to individual files + TS (#1517)

Matiss Janis Aboltinsf8ce38f11e48
diff --git a/packages/desktop-client/src/components/ManageRules.js b/packages/desktop-client/src/components/ManageRules.js
index 9b1f229908..98b433d4fe 100644
--- a/packages/desktop-client/src/components/ManageRules.js
+++ b/packages/desktop-client/src/components/ManageRules.js
@@ -1,6 +1,4 @@
import React, {
- forwardRef,
- memo,
useState,
useEffect,
useRef,
@@ -9,491 +7,26 @@ import React, {
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
-import { format as formatDate, parseISO } from 'date-fns';
-
import { pushModal } from 'loot-core/src/client/actions/modals';
import { initiallyLoadPayees } from 'loot-core/src/client/actions/queries';
-import q from 'loot-core/src/client/query-helpers';
-import { liveQueryContext } from 'loot-core/src/client/query-hooks';
-import { getPayeesById } from 'loot-core/src/client/reducers/queries';
import { send } from 'loot-core/src/platform/client/fetch';
import * as undo from 'loot-core/src/platform/client/undo';
-import { getMonthYearFormat } from 'loot-core/src/shared/months';
import { mapField, friendlyOp } from 'loot-core/src/shared/rules';
-import { getRecurringDescription } from 'loot-core/src/shared/schedules';
-import { integerToCurrency } from 'loot-core/src/shared/util';
-
-import useSelected, {
- useSelectedDispatch,
- useSelectedItems,
- SelectedProvider,
-} from '../hooks/useSelected';
-import ArrowRight from '../icons/v0/RightArrow2';
+import { describeSchedule } from 'loot-core/src/shared/schedules';
+
+import useSelected, { SelectedProvider } from '../hooks/useSelected';
import { theme } from '../style';
import Button from './common/Button';
import ExternalLink from './common/ExternalLink';
-import LinkButton from './common/LinkButton';
import Search from './common/Search';
import Stack from './common/Stack';
import Text from './common/Text';
import View from './common/View';
-import { SelectCell, Row, Field, Cell, CellButton, TableHeader } from './table';
-
-let valueStyle = {
- color: theme.pageTextPositive,
-};
-let SchedulesQuery = liveQueryContext(q('schedules').select('*'));
-
-export function Value({
- value,
- field,
- valueIsRaw,
- inline = false,
- data: dataProp,
- describe = x => x.name,
-}) {
- let { data, dateFormat } = useSelector(state => {
- let data;
- if (dataProp) {
- data = dataProp;
- } else {
- switch (field) {
- case 'payee':
- data = state.queries.payees;
- break;
- case 'category':
- data = state.queries.categories.list;
- break;
- case 'account':
- data = state.queries.accounts;
- break;
- default:
- data = [];
- }
- }
-
- return {
- data,
- dateFormat: state.prefs.local.dateFormat || 'MM/dd/yyyy',
- };
- });
- let [expanded, setExpanded] = useState(false);
-
- function onExpand(e) {
- e.preventDefault();
- setExpanded(true);
- }
-
- function formatValue(value) {
- if (value == null || value === '') {
- return '(nothing)';
- } else if (typeof value === 'boolean') {
- return value ? 'true' : 'false';
- } else {
- switch (field) {
- case 'amount':
- return integerToCurrency(value);
- case 'date':
- if (value) {
- if (value.frequency) {
- return getRecurringDescription(value);
- }
- return formatDate(parseISO(value), dateFormat);
- }
- return null;
- case 'month':
- return value
- ? formatDate(parseISO(value), getMonthYearFormat(dateFormat))
- : null;
- case 'year':
- return value ? formatDate(parseISO(value), 'yyyy') : null;
- case 'notes':
- case 'imported_payee':
- return value;
- case 'payee':
- case 'category':
- case 'account':
- case 'rule':
- if (valueIsRaw) {
- return value;
- }
- if (data && data.length) {
- let item = data.find(item => item.id === value);
- if (item) {
- return describe(item);
- } else {
- return '(deleted)';
- }
- }
-
- return '…';
- default:
- throw new Error(`Unknown field ${field}`);
- }
- }
- }
-
- if (Array.isArray(value)) {
- if (value.length === 0) {
- return <Text style={valueStyle}>(empty)</Text>;
- } else if (value.length === 1) {
- return (
- <Text>
- [<Text style={valueStyle}>{formatValue(value[0])}</Text>]
- </Text>
- );
- }
-
- let displayed = value;
- if (!expanded && value.length > 4) {
- displayed = value.slice(0, 3);
- }
- let numHidden = value.length - displayed.length;
- return (
- <Text style={{ color: theme.tableText }}>
- [
- {displayed.map((v, i) => {
- let text = <Text style={valueStyle}>{formatValue(v)}</Text>;
- let spacing;
- if (inline) {
- spacing = i !== 0 ? ' ' : '';
- } else {
- spacing = (
- <>
- {i === 0 && <br />}
- &nbsp;&nbsp;
- </>
- );
- }
-
- return (
- <Text key={i}>
- {spacing}
- {text}
- {i === value.length - 1 ? '' : ','}
- {!inline && <br />}
- </Text>
- );
- })}
- {numHidden > 0 && (
- <Text style={valueStyle}>
- &nbsp;&nbsp;
- <LinkButton onClick={onExpand} style={valueStyle}>
- {numHidden} more items...
- </LinkButton>
- {!inline && <br />}
- </Text>
- )}
- ]
- </Text>
- );
- } else if (value && value.num1 != null && value.num2 != null) {
- // An "in between" type
- return (
- <Text>
- <Text style={valueStyle}>{formatValue(value.num1)}</Text> and{' '}
- <Text style={valueStyle}>{formatValue(value.num2)}</Text>
- </Text>
- );
- } else {
- return <Text style={valueStyle}>{formatValue(value)}</Text>;
- }
-}
-
-function ConditionExpression({
- field,
- op,
- value,
- options,
- prefix,
- style,
- inline,
-}) {
- return (
- <View
- style={[
- {
- display: 'block',
- maxWidth: '100%',
- color: theme.altPillText,
- backgroundColor: theme.altPillBackground,
- borderRadius: 4,
- padding: '3px 5px',
- whiteSpace: 'nowrap',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- },
- style,
- ]}
- >
- {prefix && <Text>{prefix} </Text>}
- <Text style={valueStyle}>{mapField(field, options)}</Text>{' '}
- <Text>{friendlyOp(op)}</Text>{' '}
- <Value value={value} field={field} inline={inline} />
- </View>
- );
-}
-
-function describeSchedule(schedule, payee) {
- if (payee) {
- return `${payee.name} (${schedule.next_date})`;
- } else {
- return `Next: ${schedule.next_date}`;
- }
-}
-
-function ScheduleValue({ value }) {
- let payees = useSelector(state => state.queries.payees);
- let byId = getPayeesById(payees);
- let { data: schedules } = SchedulesQuery.useQuery();
-
- return (
- <Value
- value={value}
- field="rule"
- data={schedules}
- describe={schedule => describeSchedule(schedule, byId[schedule._payee])}
- />
- );
-}
-
-function ActionExpression({ field, op, value, options, style }) {
- return (
- <View
- style={[
- {
- display: 'block',
- maxWidth: '100%',
- color: theme.altPillText,
- backgroundColor: theme.altPillBackground,
- borderRadius: 4,
- padding: '3px 5px',
- whiteSpace: 'nowrap',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- },
- style,
- ]}
- >
- {op === 'set' ? (
- <>
- <Text>{friendlyOp(op)}</Text>{' '}
- <Text style={valueStyle}>{mapField(field, options)}</Text>{' '}
- <Text>to </Text>
- <Value value={value} field={field} />
- </>
- ) : op === 'link-schedule' ? (
- <>
- <Text>{friendlyOp(op)}</Text> <ScheduleValue value={value} />
- </>
- ) : null}
- </View>
- );
-}
-
-let Rule = memo(({ rule, hovered, selected, onHover, onEditRule }) => {
- let dispatchSelected = useSelectedDispatch();
- let borderColor = selected ? theme.tableBorderSelected : 'none';
- let backgroundFocus = hovered;
-
- return (
- <Row
- height="auto"
- style={{
- fontSize: 13,
- zIndex: selected ? 101 : 'auto',
- borderColor,
- backgroundColor: selected
- ? theme.tableRowBackgroundHighlight
- : backgroundFocus
- ? theme.tableRowBackgroundHover
- : theme.tableBackground,
- }}
- collapsed="true"
- onMouseEnter={() => onHover && onHover(rule.id)}
- onMouseLeave={() => onHover && onHover(null)}
- >
- <SelectCell
- exposed={hovered || selected}
- focused={true}
- onSelect={e => {
- dispatchSelected({ type: 'select', id: rule.id, event: e });
- }}
- selected={selected}
- />
-
- <Cell name="stage" width={50} plain style={{ color: theme.tableText }}>
- {rule.stage && (
- <View
- style={{
- alignSelf: 'flex-start',
- margin: 5,
- backgroundColor: theme.pillBackgroundSelected,
- color: theme.pillTextSelected,
- borderRadius: 4,
- padding: '3px 5px',
- }}
- >
- {rule.stage}
- </View>
- )}
- </Cell>
-
- <Field width="flex" style={{ padding: '15px 0' }} truncate={false}>
- <Stack direction="row" align="center">
- <View
- style={{ flex: 1, alignItems: 'flex-start' }}
- data-testid="conditions"
- >
- {rule.conditions.map((cond, i) => (
- <ConditionExpression
- key={i}
- field={cond.field}
- op={cond.op}
- inline={true}
- value={cond.value}
- options={cond.options}
- prefix={i > 0 ? friendlyOp(rule.conditionsOp) : null}
- style={i !== 0 && { marginTop: 3 }}
- />
- ))}
- </View>
-
- <Text>
- <ArrowRight
- style={{ width: 12, height: 12, color: theme.tableText }}
- />
- </Text>
-
- <View
- style={{ flex: 1, alignItems: 'flex-start' }}
- data-testid="actions"
- >
- {rule.actions.map((action, i) => (
- <ActionExpression
- key={i}
- field={action.field}
- op={action.op}
- value={action.value}
- options={action.options}
- style={i !== 0 && { marginTop: 3 }}
- />
- ))}
- </View>
- </Stack>
- </Field>
-
- <Cell name="edit" plain style={{ padding: '0 15px', paddingLeft: 5 }}>
- <Button as={CellButton} onSelect={() => onEditRule(rule)}>
- Edit
- </Button>
- </Cell>
- </Row>
- );
-});
-
-let SimpleTable = forwardRef(
- ({ data, loadMore, style, onHoverLeave, children, ...props }, ref) => {
- let contentRef = useRef();
- let contentHeight = useRef();
- let scrollRef = useRef();
-
- function onScroll(e) {
- if (contentHeight.current != null) {
- if (loadMore && e.target.scrollTop > contentHeight.current - 750) {
- loadMore();
- }
- }
- }
-
- useEffect(() => {
- if (contentRef.current) {
- contentHeight.current =
- contentRef.current.getBoundingClientRect().height;
- } else {
- contentHeight.current = null;
- }
- }, [contentRef.current, data]);
-
- return (
- <View
- style={[
- {
- flex: 1,
- outline: 'none',
- '& .animated .animated-row': { transition: '.25s transform' },
- },
- style,
- ]}
- tabIndex="1"
- data-testid="table"
- >
- <View
- innerRef={scrollRef}
- style={{ maxWidth: '100%', overflow: 'auto' }}
- onScroll={onScroll}
- >
- <div ref={contentRef} onMouseLeave={onHoverLeave}>
- {children}
- </div>
- </View>
- </View>
- );
- },
-);
-
-function RulesHeader() {
- let selectedItems = useSelectedItems();
- let dispatchSelected = useSelectedDispatch();
-
- return (
- <TableHeader version="v2" style={{}}>
- <SelectCell
- exposed={true}
- focused={false}
- selected={selectedItems.size > 0}
- onSelect={e => dispatchSelected({ type: 'select-all', event: e })}
- />
- <Cell value="Stage" width={50} />
- <Cell value="Rule" width="flex" />
- </TableHeader>
- );
-}
-
-function RulesList({
- rules,
- selectedItems,
- hoveredRule,
- collapsed: borderCollapsed,
- onHover,
- onCollapse,
- onEditRule,
-}) {
- if (rules.length === 0) {
- return null;
- }
-
- return (
- <View>
- {rules.map(rule => {
- let hovered = hoveredRule === rule.id;
- let selected = selectedItems.has(rule.id);
-
- return (
- <Rule
- key={rule.id}
- rule={rule}
- hovered={hovered}
- selected={selected}
- onHover={onHover}
- onEditRule={onEditRule}
- />
- );
- })}
- </View>
- );
-}
+import RulesHeader from './rules/RulesHeader';
+import RulesList from './rules/RulesList';
+import { SchedulesQuery } from './rules/SchedulesQuery';
+import SimpleTable from './rules/SimpleTable';
function mapValue(field, value, { payees, categories, accounts }) {
if (!value) return '';
diff --git a/packages/desktop-client/src/components/common/Button.tsx b/packages/desktop-client/src/components/common/Button.tsx
index 02d2917ec5..f630ba82d3 100644
--- a/packages/desktop-client/src/components/common/Button.tsx
+++ b/packages/desktop-client/src/components/common/Button.tsx
@@ -1,4 +1,4 @@
-import React, { forwardRef } from 'react';
+import React, { forwardRef, type ElementType } from 'react';
import { css, type CSSProperties } from 'glamor';
@@ -19,7 +19,7 @@ type ButtonProps = HTMLPropsWithStyle<HTMLButtonElement> & {
activeStyle?: CSSProperties;
textStyle?: CSSProperties;
bounce?: boolean;
- as?: 'button';
+ as?: ElementType;
};
type ButtonType = 'normal' | 'primary' | 'bare';
diff --git a/packages/desktop-client/src/components/filters/FiltersMenu.js b/packages/desktop-client/src/components/filters/FiltersMenu.js
index a628b0cec1..3e73d8c0ce 100644
--- a/packages/desktop-client/src/components/filters/FiltersMenu.js
+++ b/packages/desktop-client/src/components/filters/FiltersMenu.js
@@ -32,7 +32,7 @@ import Select from '../common/Select';
import Stack from '../common/Stack';
import Text from '../common/Text';
import View from '../common/View';
-import { Value } from '../ManageRules';
+import Value from '../rules/Value';
import { Tooltip } from '../tooltips';
import GenericInput from '../util/GenericInput';
diff --git a/packages/desktop-client/src/components/rules/ActionExpression.tsx b/packages/desktop-client/src/components/rules/ActionExpression.tsx
new file mode 100644
index 0000000000..fe93b300e5
--- /dev/null
+++ b/packages/desktop-client/src/components/rules/ActionExpression.tsx
@@ -0,0 +1,64 @@
+import React, { type CSSProperties } from 'react';
+
+import { mapField, friendlyOp } from 'loot-core/src/shared/rules';
+import { type ScheduleEntity } from 'loot-core/src/types/models';
+
+import { theme } from '../../style';
+import Text from '../common/Text';
+import View from '../common/View';
+
+import ScheduleValue from './ScheduleValue';
+import Value from './Value';
+
+let valueStyle = {
+ color: theme.pageTextPositive,
+};
+
+type ActionExpressionProps = {
+ field: unknown;
+ op: unknown;
+ value: unknown;
+ options: unknown;
+ style?: CSSProperties;
+};
+
+export default function ActionExpression({
+ field,
+ op,
+ value,
+ options,
+ style,
+}: ActionExpressionProps) {
+ return (
+ <View
+ style={[
+ {
+ display: 'block',
+ maxWidth: '100%',
+ color: theme.altPillText,
+ backgroundColor: theme.altPillBackground,
+ borderRadius: 4,
+ padding: '3px 5px',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ },
+ style,
+ ]}
+ >
+ {op === 'set' ? (
+ <>
+ <Text>{friendlyOp(op)}</Text>{' '}
+ <Text style={valueStyle}>{mapField(field, options)}</Text>{' '}
+ <Text>to </Text>
+ <Value value={value} field={field} />
+ </>
+ ) : op === 'link-schedule' ? (
+ <>
+ <Text>{friendlyOp(op)}</Text>{' '}
+ <ScheduleValue value={value as ScheduleEntity} />
+ </>
+ ) : null}
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/rules/ConditionExpression.tsx b/packages/desktop-client/src/components/rules/ConditionExpression.tsx
new file mode 100644
index 0000000000..fd0f80b3e4
--- /dev/null
+++ b/packages/desktop-client/src/components/rules/ConditionExpression.tsx
@@ -0,0 +1,57 @@
+import React, { type CSSProperties } from 'react';
+
+import { mapField, friendlyOp } from 'loot-core/src/shared/rules';
+
+import { theme } from '../../style';
+import Text from '../common/Text';
+import View from '../common/View';
+
+import Value from './Value';
+
+let valueStyle = {
+ color: theme.pageTextPositive,
+};
+
+type ConditionExpressionProps = {
+ field: unknown;
+ op: unknown;
+ value: unknown;
+ options: unknown;
+ prefix?: string;
+ style?: CSSProperties;
+ inline?: boolean;
+};
+
+export default function ConditionExpression({
+ field,
+ op,
+ value,
+ options,
+ prefix,
+ style,
+ inline,
+}: ConditionExpressionProps) {
+ return (
+ <View
+ style={[
+ {
+ display: 'block',
+ maxWidth: '100%',
+ color: theme.altPillText,
+ backgroundColor: theme.altPillBackground,
+ borderRadius: 4,
+ padding: '3px 5px',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ },
+ style,
+ ]}
+ >
+ {prefix && <Text>{prefix} </Text>}
+ <Text style={valueStyle}>{mapField(field, options)}</Text>{' '}
+ <Text>{friendlyOp(op)}</Text>{' '}
+ <Value value={value} field={field} inline={inline} />
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/rules/RuleRow.tsx b/packages/desktop-client/src/components/rules/RuleRow.tsx
new file mode 100644
index 0000000000..9199a68ed3
--- /dev/null
+++ b/packages/desktop-client/src/components/rules/RuleRow.tsx
@@ -0,0 +1,130 @@
+import React, { memo } from 'react';
+
+import { friendlyOp } from 'loot-core/src/shared/rules';
+import { type RuleEntity } from 'loot-core/src/types/models';
+
+import { useSelectedDispatch } from '../../hooks/useSelected';
+import ArrowRight from '../../icons/v0/RightArrow2';
+import { theme } from '../../style';
+import Button from '../common/Button';
+import Stack from '../common/Stack';
+import Text from '../common/Text';
+import View from '../common/View';
+import { SelectCell, Row, Field, Cell, CellButton } from '../table';
+
+import ActionExpression from './ActionExpression';
+import ConditionExpression from './ConditionExpression';
+
+type RuleRowProps = {
+ rule: RuleEntity;
+ hovered?: boolean;
+ selected?: boolean;
+ onHover?: (id: string | null) => void;
+ onEditRule?: (rule: RuleEntity) => void;
+};
+
+const RuleRow = memo(
+ ({ rule, hovered, selected, onHover, onEditRule }: RuleRowProps) => {
+ let dispatchSelected = useSelectedDispatch();
+ let borderColor = selected ? theme.tableBorderSelected : 'none';
+ let backgroundFocus = hovered;
+
+ return (
+ <Row
+ height="auto"
+ style={{
+ fontSize: 13,
+ zIndex: selected ? 101 : 'auto',
+ borderColor,
+ backgroundColor: selected
+ ? theme.tableRowBackgroundHighlight
+ : backgroundFocus
+ ? theme.tableRowBackgroundHover
+ : theme.tableBackground,
+ }}
+ collapsed={true}
+ onMouseEnter={() => onHover && onHover(rule.id)}
+ onMouseLeave={() => onHover && onHover(null)}
+ >
+ <SelectCell
+ exposed={hovered || selected}
+ focused={true}
+ onSelect={e => {
+ dispatchSelected({ type: 'select', id: rule.id, event: e });
+ }}
+ selected={selected}
+ />
+
+ <Cell name="stage" width={50} plain style={{ color: theme.tableText }}>
+ {rule.stage && (
+ <View
+ style={{
+ alignSelf: 'flex-start',
+ margin: 5,
+ backgroundColor: theme.pillBackgroundSelected,
+ color: theme.pillTextSelected,
+ borderRadius: 4,
+ padding: '3px 5px',
+ }}
+ >
+ {rule.stage}
+ </View>
+ )}
+ </Cell>
+
+ <Field width="flex" style={{ padding: '15px 0' }} truncate={false}>
+ <Stack direction="row" align="center">
+ <View
+ style={{ flex: 1, alignItems: 'flex-start' }}
+ data-testid="conditions"
+ >
+ {rule.conditions.map((cond, i) => (
+ <ConditionExpression
+ key={i}
+ field={cond.field}
+ op={cond.op}
+ inline={true}
+ value={cond.value}
+ options={cond.options}
+ prefix={i > 0 ? friendlyOp(rule.conditionsOp) : null}
+ style={i !== 0 && { marginTop: 3 }}
+ />
+ ))}
+ </View>
+
+ <Text>
+ <ArrowRight
+ style={{ width: 12, height: 12, color: theme.tableText }}
+ />
+ </Text>
+
+ <View
+ style={{ flex: 1, alignItems: 'flex-start' }}
+ data-testid="actions"
+ >
+ {rule.actions.map((action, i) => (
+ <ActionExpression
+ key={i}
+ field={action.field}
+ op={action.op}
+ value={action.value}
+ options={action.options}
+ style={i !== 0 && { marginTop: 3 }}
+ />
+ ))}
+ </View>
+ </Stack>
+ </Field>
+
+ <Cell name="edit" plain style={{ padding: '0 15px', paddingLeft: 5 }}>
+ {/* @ts-expect-error fix this later */}
+ <Button as={CellButton} onSelect={() => onEditRule(rule)}>
+ Edit
+ </Button>
+ </Cell>
+ </Row>
+ );
+ },
+);
+
+export default RuleRow;
diff --git a/packages/desktop-client/src/components/rules/RulesHeader.tsx b/packages/desktop-client/src/components/rules/RulesHeader.tsx
new file mode 100644
index 0000000000..f41c53f9c0
--- /dev/null
+++ b/packages/desktop-client/src/components/rules/RulesHeader.tsx
@@ -0,0 +1,22 @@
+import React from 'react';
+
+import { useSelectedItems, useSelectedDispatch } from '../../hooks/useSelected';
+import { SelectCell, Cell, TableHeader } from '../table';
+
+export default function RulesHeader() {
+ let selectedItems = useSelectedItems();
+ let dispatchSelected = useSelectedDispatch();
+
+ return (
+ <TableHeader version="v2" style={{}}>
+ <SelectCell
+ exposed={true}
+ focused={false}
+ selected={selectedItems.size > 0}
+ onSelect={e => dispatchSelected({ type: 'select-all', event: e })}
+ />
+ <Cell value="Stage" width={50} />
+ <Cell value="Rule" width="flex" />
+ </TableHeader>
+ );
+}
diff --git a/packages/desktop-client/src/components/rules/RulesList.tsx b/packages/desktop-client/src/components/rules/RulesList.tsx
new file mode 100644
index 0000000000..1f5a45437a
--- /dev/null
+++ b/packages/desktop-client/src/components/rules/RulesList.tsx
@@ -0,0 +1,47 @@
+import React from 'react';
+
+import { type RuleEntity } from 'loot-core/src/types/models';
+
+import View from '../common/View';
+
+import RuleRow from './RuleRow';
+
+type RulesListProps = {
+ rules: RuleEntity[];
+ selectedItems: Set<string>;
+ hoveredRule?: string;
+ onHover?: (id: string | null) => void;
+ onEditRule?: (rule: RuleEntity) => void;
+};
+
+export default function RulesList({
+ rules,
+ selectedItems,
+ hoveredRule,
+ onHover,
+ onEditRule,
+}: RulesListProps) {
+ if (rules.length === 0) {
+ return null;
+ }
+
+ return (
+ <View>
+ {rules.map(rule => {
+ let hovered = hoveredRule === rule.id;
+ let selected = selectedItems.has(rule.id);
+
+ return (
+ <RuleRow
+ key={rule.id}
+ rule={rule}
+ hovered={hovered}
+ selected={selected}
+ onHover={onHover}
+ onEditRule={onEditRule}
+ />
+ );
+ })}
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/rules/ScheduleValue.tsx b/packages/desktop-client/src/components/rules/ScheduleValue.tsx
new file mode 100644
index 0000000000..9031a19410
--- /dev/null
+++ b/packages/desktop-client/src/components/rules/ScheduleValue.tsx
@@ -0,0 +1,32 @@
+import React from 'react';
+import { useSelector } from 'react-redux';
+
+import { getPayeesById } from 'loot-core/src/client/reducers/queries';
+import { describeSchedule } from 'loot-core/src/shared/schedules';
+import { type ScheduleEntity } from 'loot-core/src/types/models';
+
+import { SchedulesQuery } from './SchedulesQuery';
+import Value from './Value';
+
+type ScheduleValueProps = {
+ value: ScheduleEntity;
+};
+
+export default function ScheduleValue({ value }: ScheduleValueProps) {
+ let payees = useSelector(state => state.queries.payees);
+ let byId = getPayeesById(payees);
+ let { data: schedules } = SchedulesQuery.useQuery();
+
+ return (
+ <Value
+ value={value}
+ field="rule"
+ data={schedules}
+ // TODO: this manual type coercion does not make much sense -
+ // should we instead do `schedule._payee.id`?
+ describe={schedule =>
+ describeSchedule(schedule, byId[schedule._payee as unknown as string])
+ }
+ />
+ );
+}
diff --git a/packages/desktop-client/src/components/rules/SchedulesQuery.tsx b/packages/desktop-client/src/components/rules/SchedulesQuery.tsx
new file mode 100644
index 0000000000..ff3b196b0c
--- /dev/null
+++ b/packages/desktop-client/src/components/rules/SchedulesQuery.tsx
@@ -0,0 +1,4 @@
+import q from 'loot-core/src/client/query-helpers';
+import { liveQueryContext } from 'loot-core/src/client/query-hooks';
+
+export const SchedulesQuery = liveQueryContext(q('schedules').select('*'));
diff --git a/packages/desktop-client/src/components/rules/SimpleTable.tsx b/packages/desktop-client/src/components/rules/SimpleTable.tsx
new file mode 100644
index 0000000000..628955e1fb
--- /dev/null
+++ b/packages/desktop-client/src/components/rules/SimpleTable.tsx
@@ -0,0 +1,69 @@
+import React, {
+ useEffect,
+ useRef,
+ type CSSProperties,
+ type ReactChild,
+} from 'react';
+
+import View from '../common/View';
+
+type SimpleTableProps = {
+ data: unknown;
+ loadMore?: () => void;
+ style?: CSSProperties;
+ onHoverLeave?: () => void;
+ children: ReactChild;
+};
+
+export default function SimpleTable({
+ data,
+ loadMore,
+ style,
+ onHoverLeave,
+ children,
+}: SimpleTableProps) {
+ let contentRef = useRef<HTMLDivElement>();
+ let contentHeight = useRef<number>();
+ let scrollRef = useRef<HTMLDivElement>();
+
+ function onScroll(e) {
+ if (contentHeight.current != null) {
+ if (loadMore && e.target.scrollTop > contentHeight.current - 750) {
+ loadMore();
+ }
+ }
+ }
+
+ useEffect(() => {
+ if (contentRef.current) {
+ contentHeight.current = contentRef.current.getBoundingClientRect().height;
+ } else {
+ contentHeight.current = null;
+ }
+ }, [contentRef.current, data]);
+
+ return (
+ <View
+ style={[
+ {
+ flex: 1,
+ outline: 'none',
+ '& .animated .animated-row': { transition: '.25s transform' },
+ },
+ style,
+ ]}
+ tabIndex={1}
+ data-testid="table"
+ >
+ <View
+ innerRef={scrollRef}
+ style={{ maxWidth: '100%', overflow: 'auto' }}
+ onScroll={onScroll}
+ >
+ <div ref={contentRef} onMouseLeave={onHoverLeave}>
+ {children}
+ </div>
+ </View>
+ </View>
+ );
+}
diff --git a/packages/desktop-client/src/components/rules/Value.tsx b/packages/desktop-client/src/components/rules/Value.tsx
new file mode 100644
index 0000000000..e7d24448ca
--- /dev/null
+++ b/packages/desktop-client/src/components/rules/Value.tsx
@@ -0,0 +1,185 @@
+import React, { useState } from 'react';
+import { useSelector } from 'react-redux';
+
+import { format as formatDate, parseISO } from 'date-fns';
+
+import { getMonthYearFormat } from 'loot-core/src/shared/months';
+import { getRecurringDescription } from 'loot-core/src/shared/schedules';
+import { integerToCurrency } from 'loot-core/src/shared/util';
+
+import { theme } from '../../style';
+import LinkButton from '../common/LinkButton';
+import Text from '../common/Text';
+
+let valueStyle = {
+ color: theme.pageTextPositive,
+};
+
+type ValueProps<T> = {
+ value: T;
+ field: unknown;
+ valueIsRaw?: boolean;
+ inline?: boolean;
+ data?: unknown;
+ describe?: (item: T) => string;
+};
+
+export default function Value<T>({
+ value,
+ field,
+ valueIsRaw,
+ inline = false,
+ data: dataProp,
+ // @ts-expect-error fix this later
+ describe = x => x.name,
+}: ValueProps<T>) {
+ let { data, dateFormat } = useSelector(state => {
+ let data;
+ if (dataProp) {
+ data = dataProp;
+ } else {
+ switch (field) {
+ case 'payee':
+ data = state.queries.payees;
+ break;
+ case 'category':
+ data = state.queries.categories.list;
+ break;
+ case 'account':
+ data = state.queries.accounts;
+ break;
+ default:
+ data = [];
+ }
+ }
+
+ return {
+ data,
+ dateFormat: state.prefs.local.dateFormat || 'MM/dd/yyyy',
+ };
+ });
+ let [expanded, setExpanded] = useState(false);
+
+ function onExpand(e) {
+ e.preventDefault();
+ setExpanded(true);
+ }
+
+ function formatValue(value) {
+ if (value == null || value === '') {
+ return '(nothing)';
+ } else if (typeof value === 'boolean') {
+ return value ? 'true' : 'false';
+ } else {
+ switch (field) {
+ case 'amount':
+ return integerToCurrency(value);
+ case 'date':
+ if (value) {
+ if (value.frequency) {
+ return getRecurringDescription(value);
+ }
+ return formatDate(parseISO(value), dateFormat);
+ }
+ return null;
+ case 'month':
+ return value
+ ? formatDate(parseISO(value), getMonthYearFormat(dateFormat))
+ : null;
+ case 'year':
+ return value ? formatDate(parseISO(value), 'yyyy') : null;
+ case 'notes':
+ case 'imported_payee':
+ return value;
+ case 'payee':
+ case 'category':
+ case 'account':
+ case 'rule':
+ if (valueIsRaw) {
+ return value;
+ }
+ if (data && data.length) {
+ let item = data.find(item => item.id === value);
+ if (item) {
+ return describe(item);
+ } else {
+ return '(deleted)';
+ }
+ }
+
+ return '…';
+ default:
+ throw new Error(`Unknown field ${field}`);
+ }
+ }
+ }
+
+ if (Array.isArray(value)) {
+ if (value.length === 0) {
+ return <Text style={valueStyle}>(empty)</Text>;
+ } else if (value.length === 1) {
+ return (
+ <Text>
+ [<Text style={valueStyle}>{formatValue(value[0])}</Text>]
+ </Text>
+ );
+ }
+
+ let displayed: unknown[] = value;
+ if (!expanded && value.length > 4) {
+ displayed = value.slice(0, 3);
+ }
+ let numHidden = value.length - displayed.length;
+ return (
+ <Text style={{ color: theme.tableText }}>
+ [
+ {displayed.map((v, i) => {
+ let text = <Text style={valueStyle}>{formatValue(v)}</Text>;
+ let spacing;
+ if (inline) {
+ spacing = i !== 0 ? ' ' : '';
+ } else {
+ spacing = (
+ <>
+ {i === 0 && <br />}
+ &nbsp;&nbsp;
+ </>
+ );
+ }
+
+ return (
+ <Text key={i}>
+ {spacing}
+ {text}
+ {i === value.length - 1 ? '' : ','}
+ {!inline && <br />}
+ </Text>
+ );
+ })}
+ {numHidden > 0 && (
+ <Text style={valueStyle}>
+ &nbsp;&nbsp;
+ <LinkButton onClick={onExpand} style={valueStyle}>
+ {numHidden} more items...
+ </LinkButton>
+ {!inline && <br />}
+ </Text>
+ )}
+ ]
+ </Text>
+ );
+ // @ts-expect-error Fix typechecker here
+ } else if (value && value.num1 != null && value.num2 != null) {
+ // An "in between" type
+ // @ts-expect-error Fix typechecker here
+ const { num1, num2 } = value;
+ return (
+ <Text>
+ <Text style={valueStyle}>{formatValue(num1)}</Text> and{' '}
+ <Text style={valueStyle}>{formatValue(num2)}</Text>
+ </Text>
+ );
+ } else {
+ return <Text style={valueStyle}>{formatValue(value)}</Text>;
+ }
+}
diff --git a/packages/desktop-client/src/components/table.tsx b/packages/desktop-client/src/components/table.tsx
index 55f83f0b4f..e5d712e7b2 100644
--- a/packages/desktop-client/src/components/table.tsx
+++ b/packages/desktop-client/src/components/table.tsx
@@ -604,7 +604,7 @@ export const CellButton = forwardRef<HTMLDivElement, CellButtonProps>(
);
type SelectCellProps = Omit<ComponentProps<typeof Cell>, 'children'> & {
- partial: boolean;
+ partial?: boolean;
onEdit?: () => void;
onSelect?: (e) => void;
};
diff --git a/packages/loot-core/src/client/query-hooks.tsx b/packages/loot-core/src/client/query-hooks.tsx
index d516f01163..671ebf6d69 100644
--- a/packages/loot-core/src/client/query-hooks.tsx
+++ b/packages/loot-core/src/client/query-hooks.tsx
@@ -65,7 +65,7 @@ function makeContext(queryState, opts, QueryClass) {
};
}
-export function liveQueryContext(query, opts) {
+export function liveQueryContext(query, opts?) {
return makeContext(query, opts, LiveQuery);
}
diff --git a/packages/loot-core/src/shared/rules.ts b/packages/loot-core/src/shared/rules.ts
index aa6fb843cd..53b143d61a 100644
--- a/packages/loot-core/src/shared/rules.ts
+++ b/packages/loot-core/src/shared/rules.ts
@@ -67,7 +67,7 @@ export function mapField(field, opts) {
}
}
-export function friendlyOp(op, type) {
+export function friendlyOp(op, type?) {
switch (op) {
case 'oneOf':
return 'one of';
diff --git a/packages/loot-core/src/shared/schedules.ts b/packages/loot-core/src/shared/schedules.ts
index 3844c098a5..fd0dea9885 100644
--- a/packages/loot-core/src/shared/schedules.ts
+++ b/packages/loot-core/src/shared/schedules.ts
@@ -235,3 +235,11 @@ export function getScheduledAmount(amount) {
}
return amount;
}
+
+export function describeSchedule(schedule, payee) {
+ if (payee) {
+ return `${payee.name} (${schedule.next_date})`;
+ } else {
+ return `Next: ${schedule.next_date}`;
+ }
+}
diff --git a/packages/loot-core/src/types/models/index.d.ts b/packages/loot-core/src/types/models/index.d.ts
index 4c2ba44960..1ae5a25bfa 100644
--- a/packages/loot-core/src/types/models/index.d.ts
+++ b/packages/loot-core/src/types/models/index.d.ts
@@ -2,5 +2,6 @@ export type * from './account';
export type * from './category';
export type * from './category-group';
export type * from './payee';
+export type * from './rule';
export type * from './schedule';
export type * from './transaction';
diff --git a/packages/loot-core/src/types/models/rule.d.ts b/packages/loot-core/src/types/models/rule.d.ts
index e2991e0cc0..e7e79faf83 100644
--- a/packages/loot-core/src/types/models/rule.d.ts
+++ b/packages/loot-core/src/types/models/rule.d.ts
@@ -2,7 +2,23 @@ export interface RuleEntity {
id: string;
stage: string;
conditions_op: string;
- conditions: unknown;
- actions: unknown;
+ conditionsOp?: string; // TODO: this should not be here.. figure out howto remove it
+ conditions: RuleConditionEntity[];
+ actions: RuleActionEntity[];
tombstone: boolean;
}
+
+interface RuleConditionEntity {
+ field: unknown;
+ op: unknown;
+ value: unknown;
+ options: unknown;
+ conditionsOp: unknown;
+}
+
+interface RuleActionEntity {
+ field: unknown;
+ op: unknown;
+ value: unknown;
+ options: unknown;
+}
diff --git a/upcoming-release-notes/1517.md b/upcoming-release-notes/1517.md
new file mode 100644
index 0000000000..536fbedf8e
--- /dev/null
+++ b/upcoming-release-notes/1517.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [MatissJanis]
+---
+
+Extract rules components into individual files