Skip to content

A local-first personal finance app

Improve Tag Filter UX (#7848)

Alec Bakholdinf96f8e4b618e
diff --git a/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx b/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx
index 6f36fa7ab6..6b5ebc80ba 100644
--- a/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx
+++ b/packages/desktop-client/src/components/autocomplete/Autocomplete.tsx
@@ -681,13 +681,24 @@ function MultiItem({ name, onRemove }: MultiItemProps) {
style={{
alignItems: 'center',
flexDirection: 'row',
+ flexWrap: 'nowrap',
backgroundColor: theme.pillBackgroundSelected,
padding: '2px 4px',
margin: '2px',
borderRadius: 4,
}}
>
- {name}
+ <span
+ style={{
+ overflow: 'hidden',
+ maxWidth: '100%',
+ textOverflow: 'ellipsis',
+ textWrap: 'nowrap',
+ display: 'inline-block',
+ }}
+ >
+ {name}
+ </span>
<Button variant="bare" style={{ marginLeft: 1 }} onPress={onRemove}>
<SvgRemove style={{ width: 8, height: 8 }} />
</Button>
@@ -707,6 +718,7 @@ type MultiAutocompleteProps<T extends AutocompleteItem> =
type: 'multi';
onSelect: (ids: NonNullable<T['id']>[], id?: NonNullable<T['id']>) => void;
value: null | T[] | NonNullable<T['id']>[];
+ renderMultiItem?: (props: MultiItemProps) => ReactNode;
};
function MultiAutocomplete<T extends AutocompleteItem>({
@@ -715,6 +727,7 @@ function MultiAutocomplete<T extends AutocompleteItem>({
suggestions,
strict,
clearOnBlur = true,
+ renderMultiItem = MultiItem,
...props
}: MultiAutocompleteProps<T>) {
const [focused, setFocused] = useState(false);
@@ -745,6 +758,8 @@ function MultiAutocomplete<T extends AutocompleteItem>({
prevOnKeyDown?.(e);
}
+ const RenderMultiItem = renderMultiItem;
+
return (
<Autocomplete
{...props}
@@ -778,7 +793,7 @@ function MultiAutocomplete<T extends AutocompleteItem>({
item = findItem(strict, suggestions, item);
return (
item && (
- <MultiItem
+ <RenderMultiItem
key={getItemId(item) || idx}
name={getItemName(item)}
onRemove={() => onRemoveItem(getItemId(item))}
diff --git a/packages/desktop-client/src/components/autocomplete/TagMultiAutocomplete.tsx b/packages/desktop-client/src/components/autocomplete/TagMultiAutocomplete.tsx
new file mode 100644
index 0000000000..0d5b210b96
--- /dev/null
+++ b/packages/desktop-client/src/components/autocomplete/TagMultiAutocomplete.tsx
@@ -0,0 +1,122 @@
+import { useMemo } from 'react';
+import type { ComponentProps } from 'react';
+
+import { Button } from '@actual-app/components/button';
+import { SvgRemove } from '@actual-app/components/icons/v2';
+import { SpaceBetween } from '@actual-app/components/space-between';
+import { theme } from '@actual-app/components/theme';
+import type { View } from '@actual-app/components/view';
+import { extractTagsForFilter } from '@actual-app/core/shared/tags';
+import { css } from '@emotion/css';
+
+import { useTagCSS } from '#hooks/useTagCSS';
+import { filterTags, useTags } from '#hooks/useTags';
+
+import { Autocomplete } from './Autocomplete';
+import type { AutocompleteItem } from './Autocomplete';
+
+export function TagMultiAutocomplete({
+ value,
+ setValue,
+}: {
+ value: string;
+ setValue: (value: string) => void;
+}) {
+ const tags = useMemo(() => {
+ return extractTagsForFilter(value);
+ }, [value]);
+ const { data: allTags } = useTags();
+ const allTagItems = useMemo(
+ () =>
+ allTags?.map(tag => ({
+ ...tag,
+ id: '#' + tag.tag,
+ name: '#' + tag.tag,
+ })) ?? [],
+ [allTags],
+ );
+
+ function handleSelect(ids: string[]) {
+ setValue(ids.join(' '));
+ }
+
+ return (
+ <Autocomplete<(typeof allTagItems)[number]>
+ value={tags}
+ strict
+ type="multi"
+ onSelect={handleSelect}
+ suggestions={allTagItems}
+ filterSuggestions={filterTags}
+ renderItems={(items, getItemProps, highlightedIndex) => (
+ <TagList
+ items={items}
+ getItemProps={getItemProps}
+ highlightedIndex={highlightedIndex}
+ />
+ )}
+ renderMultiItem={TagMultiItem}
+ inputProps={{ placeholder: 'Choose tags' }}
+ />
+ );
+}
+
+function TagList<T extends AutocompleteItem>({
+ items,
+ getItemProps,
+ highlightedIndex,
+}: {
+ items: T[];
+ getItemProps: (arg: { item: T }) => ComponentProps<typeof View>;
+ highlightedIndex: number;
+}) {
+ const getTagCSS = useTagCSS({ ellipsis: true });
+ return (
+ <div>
+ {items.map((item, index) => {
+ return (
+ <div
+ key={item.name}
+ {...getItemProps({ item })}
+ // oxlint-disable-next-line jsx_a11y/prefer-tag-over-role
+ role="button"
+ className={css({
+ unset: 'all',
+ cursor: 'pointer',
+ padding: '4px 6px 1px 6px',
+ backgroundColor:
+ highlightedIndex === index
+ ? theme.menuAutoCompleteBackgroundHover
+ : undefined,
+ })}
+ >
+ <div className={getTagCSS(item.name.slice(1))}>{item.name}</div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+function TagMultiItem({
+ name,
+ onRemove,
+}: {
+ name: string;
+ onRemove: () => unknown;
+}) {
+ const getTagCSS = useTagCSS({ ellipsis: true });
+ return (
+ <Button
+ variant="bare"
+ onClick={onRemove}
+ className={getTagCSS(name.replace(/^#/, ''))}
+ style={{ margin: 1, maxWidth: 'calc(100% - 2px)' }}
+ >
+ <SpaceBetween direction="horizontal" gap={3} wrap={false} align="center">
+ <span>{name}</span>
+ <SvgRemove height={8} width={8} color={theme.buttonPrimaryText} />
+ </SpaceBetween>
+ </Button>
+ );
+}
diff --git a/packages/desktop-client/src/components/filters/FilterExpression.tsx b/packages/desktop-client/src/components/filters/FilterExpression.tsx
index 9dfd0d410f..c1abffbe87 100644
--- a/packages/desktop-client/src/components/filters/FilterExpression.tsx
+++ b/packages/desktop-client/src/components/filters/FilterExpression.tsx
@@ -94,7 +94,8 @@ export function FilterExpression<T extends RuleConditionEntity>({
op === 'contains' ||
op === 'matches' ||
op === 'doesNotContain' ||
- op === 'hasTags'
+ op === 'hasTags' ||
+ op === 'hasAnyTag'
}
/>
)}
diff --git a/packages/desktop-client/src/components/filters/FiltersMenu.tsx b/packages/desktop-client/src/components/filters/FiltersMenu.tsx
index 18a6939a42..949cb47c7c 100644
--- a/packages/desktop-client/src/components/filters/FiltersMenu.tsx
+++ b/packages/desktop-client/src/components/filters/FiltersMenu.tsx
@@ -34,6 +34,7 @@ import {
parse as parseDate,
} from 'date-fns';
+import { TagMultiAutocomplete } from '#components/autocomplete/TagMultiAutocomplete';
import { GenericInput } from '#components/util/GenericInput';
import { useAccounts } from '#hooks/useAccounts';
import { useCategories } from '#hooks/useCategories';
@@ -155,6 +156,7 @@ function ConfigureField<T extends RuleConditionEntity>({
// For account ops that do not use an input value but should preserve the current value in state
const isNoValueAccountOp = (op: T['op']) =>
['onBudget', 'offBudget'].includes(op);
+ const isTagOp = (op: T['op']) => ['hasAnyTag', 'hasTags'].includes(op);
// Convert stored ID value into text
const resolveIdToText = (field: string, subfield: string, value: unknown) => {
@@ -477,6 +479,7 @@ function ConfigureField<T extends RuleConditionEntity>({
}}
>
{type !== 'boolean' &&
+ (field !== 'notes' || !isTagOp(op)) &&
(field !== 'payee' || !isIdOp(op)) &&
(field !== 'account' || !isNoValueAccountOp(op)) && (
<GenericInput
@@ -490,8 +493,7 @@ function ConfigureField<T extends RuleConditionEntity>({
type === 'id' &&
(op === 'contains' ||
op === 'matches' ||
- op === 'doesNotContain' ||
- op === 'hasTags')
+ op === 'doesNotContain')
? 'string'
: type
}
@@ -512,7 +514,6 @@ function ConfigureField<T extends RuleConditionEntity>({
}}
/>
)}
-
{field === 'payee' && isIdOp(op) && (
<PayeeFilter
// @ts-expect-error - fix me
@@ -522,7 +523,13 @@ function ConfigureField<T extends RuleConditionEntity>({
onChange={v => dispatch({ type: 'set-value', value: v })}
/>
)}
-
+ {field === 'notes' && isTagOp(op) && (
+ <TagMultiAutocomplete
+ // @ts-expect-error - fix me
+ value={formattedValue}
+ setValue={(v: string) => dispatch({ type: 'set-value', value: v })}
+ />
+ )}
<SpaceBetween
style={{
marginTop: 15,
diff --git a/packages/desktop-client/src/components/filters/updateFilterReducer.ts b/packages/desktop-client/src/components/filters/updateFilterReducer.ts
index 9a6a3a9c6b..82c4023960 100644
--- a/packages/desktop-client/src/components/filters/updateFilterReducer.ts
+++ b/packages/desktop-client/src/components/filters/updateFilterReducer.ts
@@ -20,6 +20,7 @@ export function updateFilterReducer<T extends RuleConditionEntity>(
action.op === 'doesNotContain' ||
action.op === 'isNot' ||
action.op === 'hasTags' ||
+ action.op === 'hasAnyTag' ||
action.op === 'onBudget' ||
action.op === 'offBudget')
) {
diff --git a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx b/packages/desktop-client/src/components/reports/reports/CustomReport.tsx
index 35a0dd5752..4209bc5dc7 100644
--- a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx
+++ b/packages/desktop-client/src/components/reports/reports/CustomReport.tsx
@@ -203,7 +203,13 @@ function CustomReportInner({
!!conditions.find(
({ field, op }) =>
field === 'category' &&
- ['contains', 'doesNotContain', 'matches', 'hasTags'].includes(op),
+ [
+ 'contains',
+ 'doesNotContain',
+ 'matches',
+ 'hasTags',
+ 'hasAnyTag',
+ ].includes(op),
) ||
conditions.filter(({ field }) => field === 'category').length >= 2 ||
conditions.filter(({ field }) => field === 'category_group').length >= 1;
diff --git a/packages/desktop-client/src/components/rules/RuleEditor.tsx b/packages/desktop-client/src/components/rules/RuleEditor.tsx
index 8cca32ff43..aa1c369ad9 100644
--- a/packages/desktop-client/src/components/rules/RuleEditor.tsx
+++ b/packages/desktop-client/src/components/rules/RuleEditor.tsx
@@ -46,6 +46,7 @@ import type {
import { css } from '@emotion/css';
import { v4 as uuidv4 } from 'uuid';
+import { TagMultiAutocomplete } from '#components/autocomplete/TagMultiAutocomplete';
import { FinancialText } from '#components/FinancialText';
import { StatusBadge } from '#components/schedules/StatusBadge';
import { SimpleTransactionsTable } from '#components/transactions/SimpleTransactionsTable';
@@ -150,7 +151,13 @@ export function OpSelect<T extends string>({
// TODO: Add matches op support for payees, accounts, categories.
.filter(op =>
type === 'id'
- ? !['contains', 'matches', 'doesNotContain', 'hasTags'].includes(op)
+ ? ![
+ 'contains',
+ 'matches',
+ 'doesNotContain',
+ 'hasTags',
+ 'hasAnyTag',
+ ].includes(op)
: true,
)
.map(op => [op, formatOp(op, type)]);
@@ -307,6 +314,14 @@ function ConditionEditor({
onChange={v => onChange('value', v)}
/>
);
+ } else if (type === 'string' && (op === 'hasTags' || op === 'hasAnyTag')) {
+ valueEditor = (
+ <TagMultiAutocomplete
+ key={inputKey}
+ value={value ?? ''}
+ setValue={(value: string) => onChange('value', value)}
+ />
+ );
} else {
valueEditor = (
<GenericInput
diff --git a/packages/desktop-client/src/hooks/useTags.ts b/packages/desktop-client/src/hooks/useTags.ts
index e9faa7b78f..41bfdd016a 100644
--- a/packages/desktop-client/src/hooks/useTags.ts
+++ b/packages/desktop-client/src/hooks/useTags.ts
@@ -1,5 +1,6 @@
import { useMemo } from 'react';
+import type { TagEntity } from '@actual-app/core/types/models';
import { useQuery } from '@tanstack/react-query';
import { byLengthAsc, byStartAsc, Fzf } from 'fzf';
@@ -9,6 +10,19 @@ export function useTags() {
return useQuery(tagQueries.list());
}
+export function filterTags<T extends TagEntity>(
+ tags: T[],
+ filterStr: string,
+): T[] {
+ return new Fzf(tags as TagEntity[], {
+ selector: tag => tag.tag,
+ limit: 100,
+ tiebreakers: [byLengthAsc, byStartAsc],
+ })
+ .find(filterStr.replace(/^#/, ''))
+ .map(item => item.item as T);
+}
+
export function useFilteredTags(
filterStr: string,
requireHashInFilter?: boolean,
diff --git a/packages/loot-core/src/server/rules/condition.ts b/packages/loot-core/src/server/rules/condition.ts
index 532d07dd05..efeb67c3a4 100644
--- a/packages/loot-core/src/server/rules/condition.ts
+++ b/packages/loot-core/src/server/rules/condition.ts
@@ -17,6 +17,7 @@ import {
isValidOp,
sortNumbers,
} from '#shared/rules';
+import { extractTagsForFilter } from '#shared/tags';
import {
assert,
@@ -98,6 +99,7 @@ export const CONDITION_TYPES = {
'doesNotContain',
'notOneOf',
'hasTags',
+ 'hasAnyTag',
],
nullable: true,
parse(op, value, fieldName) {
@@ -122,7 +124,8 @@ export const CONDITION_TYPES = {
op === 'contains' ||
op === 'matches' ||
op === 'doesNotContain' ||
- op === 'hasTags'
+ op === 'hasTags' ||
+ op === 'hasAnyTag'
) {
assert(
value.length > 0,
@@ -131,7 +134,7 @@ export const CONDITION_TYPES = {
);
}
- if (op === 'hasTags') {
+ if (op === 'hasTags' || op === 'hasAnyTag') {
return value;
}
@@ -346,7 +349,30 @@ export class Condition {
if (fieldValue === null) {
return false;
}
- return String(fieldValue).indexOf(this.value) !== -1;
+ const normalizedFieldValue = String(fieldValue);
+ const tags = extractTagsForFilter(this.value);
+ return !tags.some(tag => {
+ const escapedTag = tag
+ .toLowerCase()
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const pattern = new RegExp(`(?<!#)${escapedTag}([\\s#]|$)`);
+ return !pattern.test(normalizedFieldValue);
+ });
+
+ case 'hasAnyTag': {
+ if (fieldValue === null) {
+ return false;
+ }
+ const normalizedFieldValue = String(fieldValue);
+ const tags = extractTagsForFilter(this.value);
+ return tags.some(tag => {
+ const escapedTag = tag
+ .toLowerCase()
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const pattern = new RegExp(`(?<!#)${escapedTag}([\\s#]|$)`);
+ return pattern.test(normalizedFieldValue);
+ });
+ }
case 'notOneOf':
if (fieldValue === null) {
diff --git a/packages/loot-core/src/server/rules/rule-utils.ts b/packages/loot-core/src/server/rules/rule-utils.ts
index 7c4193f1b1..3d2e0b1d2b 100644
--- a/packages/loot-core/src/server/rules/rule-utils.ts
+++ b/packages/loot-core/src/server/rules/rule-utils.ts
@@ -30,6 +30,7 @@ const OP_SCORES: Record<RuleConditionEntity['op'], number> = {
doesNotContain: 0,
matches: 0,
hasTags: 0,
+ hasAnyTag: 0,
onBudget: 0,
offBudget: 0,
};
diff --git a/packages/loot-core/src/server/transactions/transaction-rules.test.ts b/packages/loot-core/src/server/transactions/transaction-rules.test.ts
index d283cf25f2..65c965665f 100644
--- a/packages/loot-core/src/server/transactions/transaction-rules.test.ts
+++ b/packages/loot-core/src/server/transactions/transaction-rules.test.ts
@@ -510,6 +510,96 @@ describe('Transaction rules', () => {
// todo: isapprox
});
+ test('transactions can be queried by hasTags', async () => {
+ await loadRules();
+ const account = await db.insertAccount({ name: 'bank' });
+ const payeeId = await db.insertPayee({ name: 'payee' });
+
+ await db.insertTransaction({
+ id: '1',
+ date: '2020-10-01',
+ account,
+ payee: payeeId,
+ notes: 'Follow up #tagContent',
+ amount: 123,
+ });
+
+ await db.insertTransaction({
+ id: '2',
+ date: '2020-10-01',
+ account,
+ payee: payeeId,
+ notes: 'Follow up #Tag_1 issue',
+ amount: 123,
+ });
+
+ const transactions = await getMatchingTransactions([
+ { field: 'notes', op: 'hasTags', value: '#Tag_1' },
+ ]);
+
+ expect(transactions.map(t => t.id)).toEqual(['2']);
+ });
+
+ test('transactions can be queried by hasTags if no "#" is included', async () => {
+ await loadRules();
+ const account = await db.insertAccount({ name: 'bank' });
+ const payeeId = await db.insertPayee({ name: 'payee' });
+
+ await db.insertTransaction({
+ id: '1',
+ date: '2020-10-01',
+ account,
+ payee: payeeId,
+ notes: 'Follow up #tagContent',
+ amount: 123,
+ });
+
+ await db.insertTransaction({
+ id: '2',
+ date: '2020-10-01',
+ account,
+ payee: payeeId,
+ notes: 'Follow up #Tag_1 issue',
+ amount: 123,
+ });
+
+ const transactions = await getMatchingTransactions([
+ { field: 'notes', op: 'hasTags', value: 'Tag_1' },
+ ]);
+
+ expect(transactions.map(t => t.id)).toEqual(['2']);
+ });
+
+ test('transactions can be queried by hasTags with multiple tags present', async () => {
+ await loadRules();
+ const account = await db.insertAccount({ name: 'bank' });
+ const payeeId = await db.insertPayee({ name: 'payee' });
+
+ await db.insertTransaction({
+ id: '1',
+ date: '2020-10-01',
+ account,
+ payee: payeeId,
+ notes: 'Follow up #Tag_1',
+ amount: 123,
+ });
+
+ await db.insertTransaction({
+ id: '2',
+ date: '2020-10-01',
+ account,
+ payee: payeeId,
+ notes: 'Follow up #Tag_1 #Tag_2 issue',
+ amount: 123,
+ });
+
+ const transactions = await getMatchingTransactions([
+ { field: 'notes', op: 'hasTags', value: '#Tag_1 #Tag_2' },
+ ]);
+
+ expect(transactions.map(t => t.id)).toEqual(['2']);
+ });
+
test('transactions can be queried by hasTags when tag starts with dollar', async () => {
await loadRules();
const account = await db.insertAccount({ name: 'bank' });
@@ -540,7 +630,46 @@ describe('Transaction rules', () => {
expect(transactions.map(t => t.id)).toEqual(['1']);
});
- test('hasTags matches nothing when input contains no `#` tag pattern', async () => {
+ test('transactions can be queried by hasAnyTag with two tags returns everything', async () => {
+ await loadRules();
+ const account = await db.insertAccount({ name: 'bank' });
+ const payeeId = await db.insertPayee({ name: 'payee' });
+
+ await db.insertTransaction({
+ id: '1',
+ date: '2020-10-01',
+ account,
+ payee: payeeId,
+ notes: 'Follow up #Tag_2 issue',
+ amount: 123,
+ });
+
+ await db.insertTransaction({
+ id: '2',
+ date: '2020-10-01',
+ account,
+ payee: payeeId,
+ notes: 'Follow up #Tag_1 issue',
+ amount: 123,
+ });
+
+ await db.insertTransaction({
+ id: '3',
+ date: '2020-10-01',
+ account,
+ payee: payeeId,
+ notes: 'Follow up #Tag_3 issue',
+ amount: 123,
+ });
+
+ const transactions = await getMatchingTransactions([
+ { field: 'notes', op: 'hasAnyTag', value: '#Tag_1 Tag_2' },
+ ]);
+
+ expect(transactions.map(t => t.id)).toEqual(['1', '2']);
+ });
+
+ test('transactions can be queried by hasAnyTag with one tag', async () => {
await loadRules();
const account = await db.insertAccount({ name: 'bank' });
const payeeId = await db.insertPayee({ name: 'payee' });
@@ -550,7 +679,7 @@ describe('Transaction rules', () => {
date: '2020-10-01',
account,
payee: payeeId,
- notes: 'Follow up #foo issue',
+ notes: 'Follow up #Tag_2 issue',
amount: 123,
});
@@ -559,17 +688,15 @@ describe('Transaction rules', () => {
date: '2020-10-01',
account,
payee: payeeId,
- notes: 'unrelated note',
+ notes: 'Follow up #Tag_1 issue',
amount: 123,
});
- // Input is missing the leading `#` — previously this returned every
- // transaction; now it should match nothing.
const transactions = await getMatchingTransactions([
- { field: 'notes', op: 'hasTags', value: 'foo' },
+ { field: 'notes', op: 'hasAnyTag', value: '##Tag_1' },
]);
- expect(transactions).toEqual([]);
+ expect(transactions.map(t => t.id)).toEqual(['2']);
});
test('and sub expression builds $and condition', async () => {
diff --git a/packages/loot-core/src/server/transactions/transaction-rules.ts b/packages/loot-core/src/server/transactions/transaction-rules.ts
index 498850270b..ac7e64b125 100644
--- a/packages/loot-core/src/server/transactions/transaction-rules.ts
+++ b/packages/loot-core/src/server/transactions/transaction-rules.ts
@@ -38,6 +38,7 @@ import {
} from '#shared/months';
import { q } from '#shared/query';
import { getApproxNumberThreshold, sortNumbers } from '#shared/rules';
+import { extractTagsForFilter } from '#shared/tags';
import { ungroupTransaction } from '#shared/transactions';
import { fastSetMerge, partitionByField } from '#shared/util';
import type {
@@ -490,7 +491,9 @@ export function conditionsToAQL(
} else if (type === 'string') {
return {
[field]: {
- $transform: op !== 'hasTags' ? '$lower' : undefined,
+ $transform: !['hasTags', 'hasAnyTag'].includes(op)
+ ? '$lower'
+ : undefined,
[aqlOp]: value,
},
};
@@ -614,14 +617,7 @@ export function conditionsToAQL(
return { $or: values.map(v => apply(field, '$eq', v)) };
case 'hasTags': {
- const tagValues = [];
- const seenTags = new Set();
- for (const [_, tag] of value.matchAll(/(?<!#)(#[^#\s]+)/g)) {
- if (!seenTags.has(tag)) {
- seenTags.add(tag);
- tagValues.push(tag);
- }
- }
+ const tagValues = extractTagsForFilter(value);
if (tagValues.length === 0) {
// No `#tag` patterns in the input — match nothing rather than
@@ -640,6 +636,20 @@ export function conditionsToAQL(
};
}
+ case 'hasAnyTag': {
+ const tagValues = extractTagsForFilter(value);
+
+ return {
+ $or: tagValues.map(v => {
+ const escapedTag = v
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ .replace(/\\\$/g, '[$]'); // Use '[$]' instead of '\$' so AQL string unescaping doesn't turn it into a bare '$' end-of-string anchor
+ const pattern = `(?<!#)${escapedTag}([\\s#]|$)`;
+ return apply(field, '$regexp', pattern);
+ }),
+ };
+ }
+
case 'notOneOf':
const notValues = value;
if (notValues.length === 0) {
@@ -788,7 +798,6 @@ function* getIsSetterRules(
return null;
}
-
function* getOneOfSetterRules(
stage,
condField,
diff --git a/packages/loot-core/src/shared/rules.test.ts b/packages/loot-core/src/shared/rules.test.ts
index 1c16749caf..693726ab7c 100644
--- a/packages/loot-core/src/shared/rules.test.ts
+++ b/packages/loot-core/src/shared/rules.test.ts
@@ -19,6 +19,7 @@ describe('rules', () => {
expect(isValidOp('notes', 'doesNotContain')).toBe(true);
expect(isValidOp('notes', 'matches')).toBe(true);
expect(isValidOp('notes', 'hasTags')).toBe(true);
+ expect(isValidOp('notes', 'hasAnyTag')).toBe(true);
});
it('should return true for oneOf operation on payee field', () => {
@@ -45,6 +46,7 @@ describe('rules', () => {
expect(validOps).toContain('doesNotContain');
expect(validOps).toContain('matches');
expect(validOps).toContain('hasTags');
+ expect(validOps).toContain('hasAnyTag');
});
it('should include oneOf and notOneOf for payee field', () => {
diff --git a/packages/loot-core/src/shared/rules.ts b/packages/loot-core/src/shared/rules.ts
index aa1b3c40bb..5f8b3f5d3b 100644
--- a/packages/loot-core/src/shared/rules.ts
+++ b/packages/loot-core/src/shared/rules.ts
@@ -38,6 +38,7 @@ const TYPE_INFO = {
'doesNotContain',
'notOneOf',
'hasTags',
+ 'hasAnyTag',
],
nullable: true,
},
@@ -63,7 +64,7 @@ type FieldInfoConstraint = Record<
const FIELD_INFO = {
imported_payee: {
type: 'string',
- disallowedOps: new Set(['hasTags']),
+ disallowedOps: new Set(['hasTags', 'hasAnyTag']),
},
payee: { type: 'id', disallowedOps: new Set(['onBudget', 'offBudget']) },
payee_name: { type: 'string' },
@@ -188,7 +189,9 @@ export function friendlyOp(op, type?) {
case 'contains':
return t('contains');
case 'hasTags':
- return t('has tags');
+ return t('has all tags');
+ case 'hasAnyTag':
+ return t('has any tag');
case 'matches':
return t('matches');
case 'doesNotContain':
diff --git a/packages/loot-core/src/shared/tags.ts b/packages/loot-core/src/shared/tags.ts
new file mode 100644
index 0000000000..224622c19b
--- /dev/null
+++ b/packages/loot-core/src/shared/tags.ts
@@ -0,0 +1,17 @@
+// for a given string, returns an array of unique words
+// (whitespace-separated) with only a single # prepended,
+// so "one #one ##one ##two three" becomes
+// ["#one", "#two", "#three"]
+export function extractTagsForFilter(value: string) {
+ if (!value) return [];
+ const tagValues = [];
+ const seenTags = new Set();
+ for (const [_, tag] of value.matchAll(/#*([^#\s]+)/g)) {
+ const tagWithHash = '#' + tag;
+ if (!seenTags.has(tagWithHash)) {
+ seenTags.add(tagWithHash);
+ tagValues.push(tagWithHash);
+ }
+ }
+ return tagValues;
+}
diff --git a/packages/loot-core/src/types/models/rule.ts b/packages/loot-core/src/types/models/rule.ts
index 1cfb2aa6b1..425ed54402 100644
--- a/packages/loot-core/src/types/models/rule.ts
+++ b/packages/loot-core/src/types/models/rule.ts
@@ -97,7 +97,13 @@ export type RuleConditionEntity =
>
| BaseConditionEntity<
'notes',
- 'is' | 'isNot' | 'contains' | 'doesNotContain' | 'matches' | 'hasTags'
+ | 'is'
+ | 'isNot'
+ | 'contains'
+ | 'doesNotContain'
+ | 'matches'
+ | 'hasTags'
+ | 'hasAnyTag'
>
| BaseConditionEntity<
'payee',
diff --git a/upcoming-release-notes/7848.md b/upcoming-release-notes/7848.md
new file mode 100644
index 0000000000..a4f49bb85c
--- /dev/null
+++ b/upcoming-release-notes/7848.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [alecbakholdin]
+---
+
+Introduced selector to "has tag" filter. Introduced new "has any tag" filter and renamed "has tag" to "has all tags"