Skip to content

A local-first personal finance app

Add ability to create tags on the fly in tag autocomplete (#7882)

Alec Bakholdin277cca051d89
diff --git a/packages/desktop-client/src/components/autocomplete/TagAutocomplete.tsx b/packages/desktop-client/src/components/autocomplete/TagAutocomplete.tsx
index af75d6db56..5a17de8874 100644
--- a/packages/desktop-client/src/components/autocomplete/TagAutocomplete.tsx
+++ b/packages/desktop-client/src/components/autocomplete/TagAutocomplete.tsx
@@ -1,11 +1,4 @@
-import {
- useCallback,
- useEffect,
- useId,
- useMemo,
- useRef,
- useState,
-} from 'react';
+import { useCallback, useId, useMemo, useRef, useState } from 'react';
import type {
CSSProperties,
FocusEventHandler,
@@ -13,11 +6,13 @@ import type {
KeyboardEventHandler,
} from 'react';
import { ListBox, ListBoxItem, Popover } from 'react-aria-components';
-import { useTranslation } from 'react-i18next';
+import { Trans, useTranslation } from 'react-i18next';
+import { SvgAdd } from '@actual-app/components/icons/v0';
import { Input } from '@actual-app/components/input';
import { styles } from '@actual-app/components/styles';
import { theme } from '@actual-app/components/theme';
+import { send } from '@actual-app/core/platform/client/connection';
import { css } from '@emotion/css';
import { useCurrentWordRange } from '#hooks/useCurrentWordRange';
@@ -44,7 +39,7 @@ export function TagAutocomplete({
onUpdate,
}: TagAutocompleteProps) {
const { t } = useTranslation();
- const getTagCSS = useTagCSS();
+ const getTagCSS = useTagCSS({ ellipsis: true });
const autocompleteId = useId();
const id = useCallback(
(itemId: string) => autocompleteId + '|' + itemId,
@@ -56,31 +51,57 @@ export function TagAutocomplete({
const [startIdx, endIdx] = useCurrentWordRange(inputValue, cursorPosition);
const currentWord = inputValue.slice(startIdx, endIdx);
- const filteredTags = useFilteredTags(currentWord, true);
- const filteredItems = useMemo(
- () => filteredTags?.map(tag => ({ ...tag, name: '#' + tag.tag })) ?? [],
- [filteredTags],
- );
+ const { data: filteredTags, refetch } = useFilteredTags(currentWord, true);
+ const filteredItems = useMemo(() => {
+ const tagArr =
+ filteredTags?.map(tag => ({ ...tag, name: '#' + tag.tag })) ?? [];
+
+ const isValidTag = currentWord.startsWith('#') && currentWord.length > 1;
+ const exactMatchExists =
+ tagArr.length && '#' + tagArr[0].tag === currentWord;
+ if (isValidTag && !exactMatchExists) {
+ const currentWordSingleHash = currentWord.replace(/^#+/, '#');
+ tagArr.push({
+ id: 'create_tag',
+ name: `${currentWordSingleHash}`,
+ tag: currentWordSingleHash.slice(1),
+ });
+ }
+ return tagArr;
+ }, [filteredTags, currentWord]);
const [isOpen, setIsOpen] = useState(false);
const showPopup = isOpen && filteredItems.length > 0;
const [highlightedIdx, setHighlightedIdx] = useState(0);
const highlightedId =
- showPopup && highlightedIdx < filteredItems.length
+ showPopup && highlightedIdx >= 0 && highlightedIdx < filteredItems.length
? filteredItems[highlightedIdx].id
: null;
- useEffect(() => {
- if (highlightedId) {
- const el = document.querySelector(`[data-key="${id(highlightedId)}"]`);
- el?.scrollIntoView?.({ block: 'nearest' });
- }
- }, [highlightedId, id]);
+ const scrollItemIntoView = useCallback(
+ (idx: number) => {
+ const targetId =
+ showPopup &&
+ idx >= 0 &&
+ idx < filteredItems?.length &&
+ filteredItems[idx].id;
+ if (targetId) {
+ const el = document.querySelector(`[data-key="${id(targetId)}"]`);
+ el?.scrollIntoView?.({ block: 'nearest' });
+ }
+ },
+ [id, filteredItems, showPopup],
+ );
- function handleSelect(id: string | null) {
+ async function handleSelect(id: string | null) {
const tagObj = filteredItems.find(tag => tag.id === id);
if (!tagObj) return;
+ if (id === 'create_tag') {
+ await send('tags-create', { tag: tagObj.tag });
+ void refetch({ cancelRefetch: true });
+ }
+
const nextChar = inputValue.charAt(endIdx);
const space = nextChar === ' ' ? '' : ' ';
const newValue =
@@ -102,21 +123,23 @@ export function TagAutocomplete({
}
if (e.key === 'ArrowUp') {
- setHighlightedIdx(highlightedIdx - 1);
e.preventDefault();
+ setHighlightedIdx(highlightedIdx - 1);
+ scrollItemIntoView(highlightedIdx - 1);
} else if (e.key === 'ArrowDown') {
- setHighlightedIdx(highlightedIdx + 1);
e.preventDefault();
+ setHighlightedIdx(highlightedIdx + 1);
+ scrollItemIntoView(highlightedIdx + 1);
} else if (e.key === 'Home' && filteredItems.length > 1) {
- setHighlightedIdx(0);
e.preventDefault();
+ setHighlightedIdx(0);
} else if (e.key === 'End' && filteredItems.length > 1) {
setHighlightedIdx(filteredItems.length - 1);
e.preventDefault();
} else if (highlightedId && (e.key === 'Enter' || e.key === 'Tab')) {
- handleSelect(highlightedId);
e.preventDefault();
e.stopPropagation();
+ void handleSelect(highlightedId);
} else if (e.key === 'Escape') {
setIsOpen(false);
}
@@ -141,23 +164,23 @@ export function TagAutocomplete({
setIsOpen(true);
setInputValue(e.currentTarget.value);
}}
+ tabIndex={-1}
onKeyDown={handleKeyDown}
onFocus={() => setIsOpen(true)}
onBlur={onBlur}
onUpdate={onUpdate}
- autoComplete={showPopup ? 'off' : undefined}
+ autoComplete="off"
/>
<Popover
isNonModal
placement="bottom start"
- className={css(styles.darkScrollbar)}
- style={{
+ className={css(styles.darkScrollbar, {
background: theme.menuAutoCompleteBackground,
borderRadius: 6,
boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
width: inputRef.current?.offsetWidth ?? 100,
- }}
+ })}
offset={1}
triggerRef={inputRef}
isOpen={showPopup}
@@ -170,7 +193,11 @@ export function TagAutocomplete({
selectionMode="single"
dependencies={[highlightedId]}
onPointerDown={e => e.preventDefault()}
- style={{ borderRadius: 4, maxHeight: '150px', overflowY: 'auto' }}
+ style={{
+ borderRadius: 4,
+ maxHeight: '150px',
+ overflowY: 'auto',
+ }}
>
{(item: (typeof filteredItems)[number]) => (
<ListBoxItem
@@ -183,26 +210,49 @@ export function TagAutocomplete({
? theme.menuAutoCompleteBackgroundHover
: 'transparent',
alignItems: 'center',
- padding: 4,
fontWeight: 500,
cursor: 'pointer',
color:
highlightedId === item.id
? theme.menuAutoCompleteItemTextHover
: theme.menuAutoCompleteItemText,
+ padding: '4px 6px 1px 6px',
})}
- onMouseOver={() =>
- setHighlightedIdx(
- Math.max(
- 0,
- filteredItems.findIndex(_item => _item.id === item.id),
- ),
- )
- }
+ onMouseMove={() => {
+ const idx = filteredItems.findIndex(
+ _item => _item.id === item.id,
+ );
+ if (idx >= 0 && highlightedIdx !== idx) {
+ setHighlightedIdx(idx);
+ }
+ }}
onPointerDown={e => e.preventDefault()}
onClick={() => handleSelect(item.id)}
>
- <div className={getTagCSS(item.tag)}>{item.name}</div>
+ {item.id === 'create_tag' ? (
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 5,
+ color: theme.noticeTextMenu,
+ paddingBottom: 3,
+ }}
+ >
+ <SvgAdd height={8} width={8} />
+ <span
+ style={{
+ textWrap: 'nowrap',
+ fontSize: 11,
+ }}
+ >
+ <Trans>Create tag</Trans>
+ </span>
+ <span className={getTagCSS('')}>{item.name}</span>
+ </div>
+ ) : (
+ <div className={getTagCSS(item.tag)}>{item.name}</div>
+ )}
</ListBoxItem>
)}
</ListBox>
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
index 442a8dda33..0bf216bbbc 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
@@ -1471,6 +1471,7 @@ function NoteTagAutocomplete({
}: {
inputRef: RefObject<HTMLInputElement | null>;
}) {
+ const dispatch = useDispatch();
// Yes, there is a lot of ref usages in this component. Here's the motivation
// 1. This component purely modifies HTML Input state, app state is handled elsewhere
// 2. This component deals with cursor state, which is not easily accessible through regular React code
@@ -1482,9 +1483,14 @@ function NoteTagAutocomplete({
const [cursorPosition] = useCursorPosition(inputRef);
const [startIdx, endIdx] = useCurrentWordRange(note, cursorPosition);
const currentWord = note.slice(startIdx, endIdx);
- const filteredTags = useFilteredTags(currentWord, true);
+ const currentWordNoHash = currentWord.replace(/^#+/, '');
+ const { data: filteredTags, refetch } = useFilteredTags(currentWord, true);
+ const showNewTag =
+ currentWord.startsWith('#') &&
+ currentWordNoHash &&
+ !filteredTags.some(tag => tag.tag === currentWordNoHash);
- const getTagCSS = useTagCSS();
+ const getTagCSS = useTagCSS({ ellipsis: true });
function handleSelect(tag: string) {
if (!inputRef.current) return;
@@ -1497,6 +1503,25 @@ function NoteTagAutocomplete({
document.dispatchEvent(new Event('selectionchange'));
}
+ async function handleCreate(tag: string) {
+ if (!inputRef.current) return;
+ try {
+ await send('tags-create', { tag });
+ void refetch();
+ handleSelect(tag);
+ } catch (e) {
+ dispatch(
+ addNotification({
+ notification: {
+ type: 'error',
+ message: 'Failed to add tag, check logs',
+ },
+ }),
+ );
+ console.trace(e);
+ }
+ }
+
const hideScrollbar = css({
'scrollbar-width': 'none',
'-ms-overflow-style': 'none',
@@ -1512,7 +1537,7 @@ function NoteTagAutocomplete({
padding: '4px 8px 4px 8px',
borderRadius: 30,
overflowX: 'auto',
- height: filteredTags.length ? 30 : 0,
+ height: filteredTags.length || showNewTag ? 30 : 0,
transitionProperty: 'height',
transitionDuration: '100ms',
}}
@@ -1532,7 +1557,11 @@ function NoteTagAutocomplete({
<div key={tag.id}>
<button
type="button"
- style={{ border: 'none', height: 22 }}
+ style={{
+ border: 'none',
+ height: 22,
+ maxWidth: '50dvw',
+ }}
className={getTagCSS(tag.tag)}
onMouseDown={e => e.preventDefault()} // stops input from losing focus
onClick={() => handleSelect(tag.tag)}
@@ -1541,6 +1570,42 @@ function NoteTagAutocomplete({
</button>
</div>
))}
+ {showNewTag && (
+ <button
+ type="button"
+ style={{
+ padding: '1px 1px 1px 9px',
+ borderRadius: 12,
+ borderWidth: 0,
+ backgroundColor: theme.noticeBackground,
+ color: theme.noticeTextDark,
+ display: 'flex',
+ alignItems: 'center',
+ flexWrap: 'nowrap',
+ gap: 4,
+ }}
+ onMouseDown={e => e.preventDefault()} // stops input from losing focus
+ onClick={() => handleCreate(currentWordNoHash)}
+ >
+ <SvgAdd height={8} width={8} />
+ <span style={{ whiteSpace: 'nowrap' }}>
+ <Trans>Create tag</Trans>
+ </span>
+ <div
+ style={{
+ borderWidth: 0,
+ height: 20,
+ maxWidth: '50dvw',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ display: 'inline-block',
+ }}
+ className={getTagCSS('')}
+ >
+ #{currentWordNoHash}
+ </div>
+ </button>
+ )}
</View>
</View>
);
diff --git a/packages/desktop-client/src/components/tags/TagCreationRow.tsx b/packages/desktop-client/src/components/tags/TagCreationRow.tsx
index 820b6a6322..5f95c13fad 100644
--- a/packages/desktop-client/src/components/tags/TagCreationRow.tsx
+++ b/packages/desktop-client/src/components/tags/TagCreationRow.tsx
@@ -70,6 +70,18 @@ export const TagCreationRow = ({ onClose, tags }: TagCreationRowProps) => {
createTag({ tag: { tag, color, description } });
resetInputs();
};
+ function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
+ if (e.nativeEvent.isComposing) {
+ return;
+ }
+ if (e.key === 'Escape') {
+ onClose();
+ }
+ if (e.key === 'Enter' && tag) {
+ e.preventDefault();
+ onAddTag();
+ }
+ }
const isInitialMount = useInitialMount();
@@ -87,14 +99,7 @@ export const TagCreationRow = ({ onClose, tags }: TagCreationRowProps) => {
}}
data-testid="new-tag"
{...tableNavigator.getNavigatorProps({
- onKeyUp: (e: KeyboardEvent<HTMLDivElement>) => {
- if (e.key === 'Escape') {
- onClose();
- }
- if (e.key === 'Enter' && tag) {
- onAddTag();
- }
- },
+ onKeyUp: onKeyDown,
})}
>
<Row
@@ -120,6 +125,7 @@ export const TagCreationRow = ({ onClose, tags }: TagCreationRowProps) => {
inputProps={{
value: tag || '',
onChange: e => setTag(e.target.value.replace(/\s/g, '')),
+ onKeyDownCapture: onKeyDown,
placeholder: t('New tag'),
ref: tagInput,
}}
@@ -140,6 +146,7 @@ export const TagCreationRow = ({ onClose, tags }: TagCreationRowProps) => {
inputProps={{
value: description || '',
onUpdate: setDescription,
+ onKeyDownCapture: onKeyDown,
placeholder: t('Tag description'),
}}
/>
diff --git a/packages/desktop-client/src/components/tags/TagEditor.tsx b/packages/desktop-client/src/components/tags/TagEditor.tsx
index d0567aa32e..92c32a18d1 100644
--- a/packages/desktop-client/src/components/tags/TagEditor.tsx
+++ b/packages/desktop-client/src/components/tags/TagEditor.tsx
@@ -13,7 +13,7 @@ type TagEditorProps = {
};
export const TagEditor = ({ tag, ref }: TagEditorProps) => {
- const getTagCSS = useTagCSS();
+ const getTagCSS = useTagCSS({ ellipsis: true });
const { mutate: updateTag } = useUpdateTagMutation();
const formattedTag = <>#{tag.tag}</>;
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
index 1b0d41c4e8..381e599e61 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
@@ -252,6 +252,10 @@ function initBasicServer() {
list: categories,
}),
'tags-get': async () => tags,
+ 'tags-create': async (tag: Omit<TagEntity, 'id'>) => ({
+ id: 'new-tag',
+ ...tag,
+ }),
});
}
@@ -402,14 +406,22 @@ expect.extend({
) {
return {
message: () =>
- `Expected ${validPayeeListWithFavorite.join(', ')} to have favorite stars.` +
- `Received ${foundStarList.length} items with favorite stars. Incorrect: ${incorrectStarList.join(', ')}`,
+ `Expected ${validPayeeListWithFavorite.join(
+ ', ',
+ )} to have favorite stars.` +
+ `Received ${
+ foundStarList.length
+ } items with favorite stars. Incorrect: ${incorrectStarList.join(
+ ', ',
+ )}`,
pass: false,
};
} else {
return {
message: () =>
- `Expected ${String(validPayeeListWithFavorite)} to have favorite stars`,
+ `Expected ${String(
+ validPayeeListWithFavorite,
+ )} to have favorite stars`,
pass: true,
};
}
@@ -1331,5 +1343,23 @@ describe('Transactions', () => {
expect(getTransactions()[3].notes).toBe('#taxes');
});
+
+ test('creating a new tag via the autocomplete', async () => {
+ const { container, getTransactions } = renderTransactions();
+ const input = await editField(container, 'notes', 2);
+ await userEvent.clear(input);
+ await userEvent.type(input, 'spending on #coffee');
+
+ // The "Create tag #coffee" option should appear
+ const createOption = await screen.findByText('Create tag');
+ expect(createOption).toBeTruthy();
+
+ await userEvent.click(createOption);
+ await waitForAutocomplete();
+ fireEvent.blur(input);
+
+ // Verify the tag was added to the note correctly
+ expect(getTransactions()[2].notes).toBe('spending on #coffee');
+ });
});
});
diff --git a/packages/desktop-client/src/hooks/useCursorPosition.ts b/packages/desktop-client/src/hooks/useCursorPosition.ts
index 747c1298ec..b3e160d45d 100644
--- a/packages/desktop-client/src/hooks/useCursorPosition.ts
+++ b/packages/desktop-client/src/hooks/useCursorPosition.ts
@@ -6,32 +6,35 @@ import { useRefEventListener } from './useRefEventListener';
export function useCursorPosition(
ref: RefObject<HTMLInputElement | null>,
): [number | null, (n: number | null) => void] {
+ const doc = useRef(document);
const [cursorPosition, setCursorPosition] = useState<number | null>(null);
- function _setCursorPosition(n: number | null) {
- setTimeout(() => {
- ref.current?.setSelectionRange(n, n);
- document.dispatchEvent(new Event('selectionchange'));
- });
- }
+
const update = () => {
- const input = ref.current;
- if (!input) return;
+ if (!ref.current || !document.hasFocus()) return;
setCursorPosition(
- document.activeElement === input ? input.selectionStart : null,
+ document.activeElement === ref.current
+ ? ref.current.selectionStart
+ : null,
);
};
- const clear = () => setCursorPosition(null);
-
useRefEventListener(ref, 'focusin', update, [ref, setCursorPosition]);
useRefEventListener(ref, 'keyup', update, [ref, setCursorPosition]);
- useRefEventListener(ref, 'focusout', clear, [setCursorPosition]);
-
- // sync on mount
- useEffect(update, [ref, setCursorPosition]);
-
- // listen for selectionchange which only gets fired on document
- const doc = useRef(document);
useRefEventListener(doc, 'selectionchange', update, [ref, setCursorPosition]);
+ useEffect(update, [ref, setCursorPosition]); // sync on mount
+
+ const clear = () => {
+ if (document.hasFocus()) {
+ setCursorPosition(null);
+ }
+ };
+ useRefEventListener(ref, 'focusout', clear, [setCursorPosition]);
- return [cursorPosition, _setCursorPosition];
+ return [
+ cursorPosition,
+ (n: number | null) =>
+ setTimeout(() => {
+ ref.current?.setSelectionRange(n, n);
+ document.dispatchEvent(new Event('selectionchange'));
+ }),
+ ];
}
diff --git a/packages/desktop-client/src/hooks/useTagCSS.ts b/packages/desktop-client/src/hooks/useTagCSS.ts
index d98f55afe8..919968e2ab 100644
--- a/packages/desktop-client/src/hooks/useTagCSS.ts
+++ b/packages/desktop-client/src/hooks/useTagCSS.ts
@@ -8,7 +8,7 @@ import { useTheme } from '#style';
import { useTags } from './useTags';
-export function useTagCSS() {
+export function useTagCSS(opts?: { ellipsis?: boolean }) {
const { data: tags = [] } = useTags();
const [theme] = useTheme();
@@ -24,7 +24,14 @@ export function useTagCSS() {
);
return css({
- display: 'inline-flex',
+ ...(opts?.ellipsis
+ ? {
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ maxWidth: '100%',
+ display: 'inline-block',
+ }
+ : { display: 'inline-flex' }),
padding: options.compact ? '0px 7px' : '3px 7px',
borderRadius: 16,
userSelect: 'none',
@@ -39,7 +46,7 @@ export function useTagCSS() {
},
});
},
- [theme, tags],
+ [theme, tags, opts],
);
}
diff --git a/packages/desktop-client/src/hooks/useTags.ts b/packages/desktop-client/src/hooks/useTags.ts
index 6fc121e258..e9faa7b78f 100644
--- a/packages/desktop-client/src/hooks/useTags.ts
+++ b/packages/desktop-client/src/hooks/useTags.ts
@@ -1,7 +1,7 @@
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
-import { Fzf } from 'fzf';
+import { byLengthAsc, byStartAsc, Fzf } from 'fzf';
import { tagQueries } from '#tags/queries';
@@ -13,16 +13,20 @@ export function useFilteredTags(
filterStr: string,
requireHashInFilter?: boolean,
) {
- const { data: tags } = useTags();
- return useMemo(() => {
+ const { data: tags, ...rest } = useTags();
+ const filteredTags = useMemo(() => {
if (!filterStr || !tags) return [];
if (requireHashInFilter && !filterStr.startsWith('#')) return [];
-
return new Fzf(tags, {
selector: tag => tag.tag,
limit: 100,
+ tiebreakers: [byLengthAsc, byStartAsc],
})
.find(filterStr.replace(/^#/, ''))
.map(item => item.item);
}, [tags, filterStr, requireHashInFilter]);
+ return {
+ data: filteredTags,
+ ...rest,
+ };
}
diff --git a/packages/loot-core/src/server/db/index.ts b/packages/loot-core/src/server/db/index.ts
index 6b2a6bde49..b1ff1eec2b 100644
--- a/packages/loot-core/src/server/db/index.ts
+++ b/packages/loot-core/src/server/db/index.ts
@@ -964,7 +964,6 @@ export function getTags() {
SELECT id, tag, color, description
FROM tags
WHERE tombstone = 0
- ORDER BY tag COLLATE NOCASE
`);
}
@@ -972,7 +971,6 @@ export function getAllTags() {
return all<DbTag>(`
SELECT id, tag, color, description
FROM tags
- ORDER BY tag COLLATE NOCASE
`);
}
diff --git a/packages/loot-core/src/server/tags/app.ts b/packages/loot-core/src/server/tags/app.ts
index 051d71d99b..5dfa33ce36 100644
--- a/packages/loot-core/src/server/tags/app.ts
+++ b/packages/loot-core/src/server/tags/app.ts
@@ -22,8 +22,14 @@ app.method('tags-delete-all', mutator(deleteAllTags));
app.method('tags-update', mutator(undoable(updateTag)));
app.method('tags-discover', mutator(discoverTags));
+const collator = new Intl.Collator(undefined, {
+ numeric: true,
+ sensitivity: 'base',
+});
async function getTags(): Promise<TagEntity[]> {
- return await db.getTags();
+ const tags = await db.getTags();
+ tags.sort((a, b) => collator.compare(a.tag, b.tag));
+ return tags;
}
async function createTag({
diff --git a/upcoming-release-notes/7882.md b/upcoming-release-notes/7882.md
new file mode 100644
index 0000000000..160e67813f
--- /dev/null
+++ b/upcoming-release-notes/7882.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [alecbakholdin, PuddleOfFat]
+---
+
+Added ability to create tags using the new tag autocomplete on mobile and desktop