Skip to content

A local-first personal finance app

[AI] Add Tags to bulk edit notes (#8866)

dreptschara7b797007ee7
diff --git a/packages/desktop-client/src/components/autocomplete/NoteInsertHashButton.tsx b/packages/desktop-client/src/components/autocomplete/NoteInsertHashButton.tsx
new file mode 100644
index 0000000000..306df0ed04
--- /dev/null
+++ b/packages/desktop-client/src/components/autocomplete/NoteInsertHashButton.tsx
@@ -0,0 +1,52 @@
+import type { RefObject } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@actual-app/components/button';
+import { SvgHash } from '@actual-app/components/icons/v0';
+
+import { useCursorPosition } from '#hooks/useCursorPosition';
+import { useInputRefValue } from '#hooks/useInputRefValue';
+
+type NoteInsertHashButtonProps = {
+ inputRef: RefObject<HTMLInputElement | null>;
+};
+
+export function NoteInsertHashButton({ inputRef }: NoteInsertHashButtonProps) {
+ const { t } = useTranslation();
+ const [inputValue, setInputValue] = useInputRefValue(inputRef);
+ const [_, setCursorPosition] = useCursorPosition(inputRef);
+
+ return (
+ <Button
+ variant="bare"
+ aria-label={t('Add tag')}
+ style={{ color: 'inherit', padding: 1 }}
+ onPointerDown={e => e.preventDefault()}
+ onClick={() => {
+ if (!inputRef.current) return;
+ const isFocused = document.activeElement === inputRef.current;
+ const start = isFocused
+ ? (inputRef.current.selectionStart ?? 0)
+ : inputValue.length;
+ const end = isFocused
+ ? (inputRef.current.selectionEnd ?? 0)
+ : inputValue.length;
+
+ const before = inputValue.substring(0, start);
+ const after = inputValue.substring(end);
+
+ const space = start === 0 || before.match(/\s$/) ? '' : ' ';
+
+ setInputValue(before + space + '#' + after);
+ inputRef.current.focus();
+ setCursorPosition(start + 1 + space.length);
+ // so Safari requires that I do inputRef.current.focus() synchronously,
+ // but Chrome doesn't work unless I do it after. We do both this way.
+ // If the element is already focused, these invocations have no effect
+ setTimeout(() => inputRef.current?.focus(), 1);
+ }}
+ >
+ <SvgHash width={17} height={17} />
+ </Button>
+ );
+}
diff --git a/packages/desktop-client/src/components/autocomplete/NoteTagAutocomplete.tsx b/packages/desktop-client/src/components/autocomplete/NoteTagAutocomplete.tsx
new file mode 100644
index 0000000000..d89091fc76
--- /dev/null
+++ b/packages/desktop-client/src/components/autocomplete/NoteTagAutocomplete.tsx
@@ -0,0 +1,185 @@
+import type { RefObject } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+
+import { SvgAdd } from '@actual-app/components/icons/v1';
+import { theme } from '@actual-app/components/theme';
+import { View } from '@actual-app/components/view';
+import { send } from '@actual-app/core/platform/client/connection';
+import { css } from '@emotion/css';
+
+import { useCurrentWordRange } from '#hooks/useCurrentWordRange';
+import { useCursorPosition } from '#hooks/useCursorPosition';
+import { useInputRefValue } from '#hooks/useInputRefValue';
+import { useRefEventListener } from '#hooks/useRefEventListener';
+import { useTagCSS } from '#hooks/useTagCSS';
+import { useFilteredTags } from '#hooks/useTags';
+import { addNotification } from '#notifications/notificationsSlice';
+import { useDispatch } from '#redux';
+
+type NoteTagAutocompleteProps = {
+ inputRef: RefObject<HTMLInputElement | null>;
+};
+
+export function NoteTagAutocomplete({ inputRef }: NoteTagAutocompleteProps) {
+ const { t } = useTranslation();
+ 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
+ // 3. Child transaction notes (transaction.notes) does not update until blur, so we have to use input state
+ // 4. Given we are already using inputRef in multiple locations, I elected to simplify the props to just the ref and use HTML/JS events
+
+ const [note, setNote] = useInputRefValue(inputRef);
+
+ const [cursorPosition] = useCursorPosition(inputRef);
+ const [startIdx, endIdx] = useCurrentWordRange(note, cursorPosition);
+ const currentWord = note.slice(startIdx, endIdx);
+ // `##name` is the escape sequence for a literal `#name` (see docs), so only
+ // a word with exactly one leading `#` is eligible for tag completion.
+ const leadingHashCount = currentWord.match(/^#+/)?.[0].length ?? 0;
+ const hasSingleLeadingHash = leadingHashCount === 1;
+ const currentWordNoHash = hasSingleLeadingHash ? currentWord.slice(1) : '';
+ const { data: filteredTags, refetch } = useFilteredTags(
+ hasSingleLeadingHash ? currentWord : '',
+ true,
+ );
+ const showNewTag =
+ hasSingleLeadingHash &&
+ currentWordNoHash &&
+ !filteredTags.some(tag => tag.tag === currentWordNoHash);
+
+ const getTagCSS = useTagCSS({ ellipsis: true });
+
+ function handleSelect(tag: string) {
+ if (!inputRef.current) return;
+ const newValue =
+ note.slice(0, startIdx) + '#' + tag + ' ' + note.slice(endIdx);
+ setNote(newValue);
+ const newPos = startIdx + tag.length + 2;
+
+ inputRef.current.setSelectionRange(newPos, newPos);
+ document.dispatchEvent(new Event('selectionchange'));
+ }
+
+ async function handleCreate(tag: string) {
+ if (!inputRef.current) return;
+ try {
+ await send('tags-create', { tag });
+ void refetch();
+ if (inputRef.current && inputRef.current.value === note) {
+ handleSelect(tag);
+ }
+ } catch (e) {
+ dispatch(
+ addNotification({
+ notification: {
+ type: 'error',
+ message: t('Failed to add tag, check logs'),
+ },
+ }),
+ );
+ console.trace(e);
+ }
+ }
+
+ useRefEventListener(inputRef, 'keydown', e => {
+ if (e.key !== 'Tab') return;
+ if (filteredTags.length) {
+ e.preventDefault();
+ e.stopPropagation();
+ handleSelect(filteredTags[0].tag);
+ } else if (showNewTag) {
+ e.preventDefault();
+ e.stopPropagation();
+ void handleCreate(currentWordNoHash);
+ }
+ });
+
+ const hideScrollbar = css({
+ 'scrollbar-width': 'none',
+ '-ms-overflow-style': 'none',
+ '&::-webkit-scrollbar': {
+ display: 'none',
+ },
+ });
+
+ return (
+ <View
+ style={{
+ width: '100%',
+ padding: '4px 8px 4px 8px',
+ borderRadius: 30,
+ overflowX: 'auto',
+ height: filteredTags.length || showNewTag ? 30 : 0,
+ transitionProperty: 'height',
+ transitionDuration: '100ms',
+ }}
+ className={hideScrollbar}
+ >
+ <View
+ style={{
+ display: 'flex',
+ flexDirection: 'row',
+ alignItems: 'end',
+ flexWrap: 'nowrap',
+ gap: 4,
+ paddingRight: 8,
+ }}
+ >
+ {filteredTags.map(tag => (
+ <div key={tag.id}>
+ <button
+ type="button"
+ style={{
+ border: 'none',
+ height: 22,
+ maxWidth: '50dvw',
+ }}
+ className={getTagCSS(tag.tag)}
+ onMouseDown={e => e.preventDefault()} // stops input from losing focus
+ onClick={() => handleSelect(tag.tag)}
+ >
+ #{tag.tag}
+ </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/mobile/transactions/TransactionEdit.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
index 30f340032e..3c6b9c39ec 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
@@ -7,12 +7,12 @@ import {
useRef,
useState,
} from 'react';
-import type { ReactNode, RefObject } from 'react';
+import type { ReactNode } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { useLocation, useParams, useSearchParams } from 'react-router';
import { Button } from '@actual-app/components/button';
-import { SvgHash, SvgSplit } from '@actual-app/components/icons/v0';
+import { SvgSplit } from '@actual-app/components/icons/v0';
import {
SvgAdd,
SvgCalendar,
@@ -64,7 +64,6 @@ import type {
PayeeEntity,
TransactionEntity,
} from '@actual-app/core/types/models';
-import { css } from '@emotion/css';
import {
format as formatDate,
isValid as isValidDate,
@@ -72,6 +71,8 @@ import {
parseISO,
} from 'date-fns';
+import { NoteInsertHashButton } from '#components/autocomplete/NoteInsertHashButton';
+import { NoteTagAutocomplete } from '#components/autocomplete/NoteTagAutocomplete';
import { MobileBackButton } from '#components/mobile/MobileBackButton';
import {
FieldLabel,
@@ -84,10 +85,7 @@ import { MobilePageHeader, Page } from '#components/Page';
import { shouldApplyRuleChange } from '#components/transactions/table/utils';
import { useAccounts } from '#hooks/useAccounts';
import { useCategories } from '#hooks/useCategories';
-import { useCurrentWordRange } from '#hooks/useCurrentWordRange';
-import { useCursorPosition } from '#hooks/useCursorPosition';
import { useDateFormat } from '#hooks/useDateFormat';
-import { useInputRefValue } from '#hooks/useInputRefValue';
import { useLocalPref } from '#hooks/useLocalPref';
import { useLocationPermission } from '#hooks/useLocationPermission';
import { useNavigate } from '#hooks/useNavigate';
@@ -98,8 +96,6 @@ import {
useSingleActiveEditForm,
} from '#hooks/useSingleActiveEditForm';
import { useSyncedPref } from '#hooks/useSyncedPref';
-import { useTagCSS } from '#hooks/useTagCSS';
-import { useFilteredTags } from '#hooks/useTags';
import { pushModal } from '#modals/modalsSlice';
import { addNotification } from '#notifications/notificationsSlice';
import { useSavePayeeLocationMutation } from '#payees';
@@ -553,7 +549,7 @@ const ChildTransactionEdit = forwardRef<
<InputField
ref={noteRef}
iconStart={<SvgNotesPaper width={17} height={17} />}
- iconEnd={<NoteInsertHashButton noteRef={noteRef} />}
+ iconEnd={<NoteInsertHashButton inputRef={noteRef} />}
placeholder={t('Add a note (optional)')}
disabled={
!!editingField &&
@@ -1494,7 +1490,7 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
<InputField
ref={noteRef}
iconStart={<SvgNotesPaper width={17} height={17} />}
- iconEnd={<NoteInsertHashButton noteRef={noteRef} />}
+ iconEnd={<NoteInsertHashButton inputRef={noteRef} />}
placeholder={t('Add a note (optional)')}
disabled={
!!editingField &&
@@ -1549,195 +1545,6 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
},
);
-function NoteInsertHashButton({
- noteRef,
-}: {
- noteRef: RefObject<HTMLInputElement | null>;
-}) {
- const { t } = useTranslation();
- const [inputValue, setInputValue] = useInputRefValue(noteRef);
- const [_, setCursorPosition] = useCursorPosition(noteRef);
-
- return (
- <Button
- variant="bare"
- aria-label={t('Add tag')}
- style={{ color: 'inherit', padding: 1 }}
- onPointerDown={e => e.preventDefault()}
- onClick={() => {
- if (!noteRef.current) return;
- const isFocused = document.activeElement === noteRef.current;
- const start = isFocused
- ? (noteRef.current.selectionStart ?? 0)
- : inputValue.length;
- const end = isFocused
- ? (noteRef.current.selectionEnd ?? 0)
- : inputValue.length;
-
- const before = inputValue.substring(0, start);
- const after = inputValue.substring(end);
-
- const space = start === 0 || before.match(/\s$/) ? '' : ' ';
-
- setInputValue(before + space + '#' + after);
- noteRef.current.focus();
- setCursorPosition(start + 1 + space.length);
- // so Safari requires that I do noteRef.current.focus() synchronously,
- // but Chrome doesn't work unless I do it after. We do both this way.
- // If the element is already focused, these invocations have no effect
- setTimeout(() => noteRef.current?.focus(), 1);
- }}
- >
- <SvgHash width={17} height={17} />
- </Button>
- );
-}
-
-function NoteTagAutocomplete({
- inputRef,
-}: {
- 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
- // 3. Child transaction notes (transaction.notes) does not update until blur, so we have to use input state
- // 4. Given we are already using inputRef in multiple locations, I elected to simplify the props to just the ref and use HTML/JS events
-
- const [note, setNote] = useInputRefValue(inputRef);
-
- const [cursorPosition] = useCursorPosition(inputRef);
- const [startIdx, endIdx] = useCurrentWordRange(note, cursorPosition);
- const currentWord = note.slice(startIdx, endIdx);
- 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({ ellipsis: true });
-
- function handleSelect(tag: string) {
- if (!inputRef.current) return;
- const newValue =
- note.slice(0, startIdx) + '#' + tag + ' ' + note.slice(endIdx);
- setNote(newValue);
- const newPos = startIdx + tag.length + 2;
-
- inputRef.current.setSelectionRange(newPos, newPos);
- 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',
- '&::-webkit-scrollbar': {
- display: 'none',
- },
- });
-
- return (
- <View
- style={{
- width: '100%',
- padding: '4px 8px 4px 8px',
- borderRadius: 30,
- overflowX: 'auto',
- height: filteredTags.length || showNewTag ? 30 : 0,
- transitionProperty: 'height',
- transitionDuration: '100ms',
- }}
- className={hideScrollbar}
- >
- <View
- style={{
- display: 'flex',
- flexDirection: 'row',
- alignItems: 'end',
- flexWrap: 'nowrap',
- gap: 4,
- paddingRight: 8,
- }}
- >
- {filteredTags.map(tag => (
- <div key={tag.id}>
- <button
- type="button"
- style={{
- border: 'none',
- height: 22,
- maxWidth: '50dvw',
- }}
- className={getTagCSS(tag.tag)}
- onMouseDown={e => e.preventDefault()} // stops input from losing focus
- onClick={() => handleSelect(tag.tag)}
- >
- #{tag.tag}
- </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>
- );
-}
-
function isTemporary(transaction: TransactionEntity) {
return transaction.id.indexOf('temp') === 0;
}
diff --git a/packages/desktop-client/src/components/modals/EditFieldModal.tsx b/packages/desktop-client/src/components/modals/EditFieldModal.tsx
index 0c4e11de8f..da3551e162 100644
--- a/packages/desktop-client/src/components/modals/EditFieldModal.tsx
+++ b/packages/desktop-client/src/components/modals/EditFieldModal.tsx
@@ -15,9 +15,12 @@ import {
} from '@actual-app/core/shared/util';
import { format as formatDate, parse as parseDate, parseISO } from 'date-fns';
+import { NoteInsertHashButton } from '#components/autocomplete/NoteInsertHashButton';
+import { NoteTagAutocomplete } from '#components/autocomplete/NoteTagAutocomplete';
import { Modal, ModalCloseButton, ModalHeader } from '#components/common/Modal';
import { SectionLabel } from '#components/forms';
import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';
+import { InputField } from '#components/mobile/MobileForms';
import { DateSelect } from '#components/select/DateSelect';
import { useDateFormat } from '#hooks/useDateFormat';
import type { Modal as ModalType } from '#modals/modalsSlice';
@@ -124,6 +127,7 @@ export function EditFieldModal({
case 'notes':
label = t('Notes');
+ width = tokens.breakpoint_small;
editor = ({ close }) => (
<>
<View
@@ -231,15 +235,31 @@ export function EditFieldModal({
/>
</View>
) : (
- <Input
- ref={noteInputRef}
- autoFocus
- onEnter={value => {
- onSelectNote(value, noteAmend);
- close();
- }}
- style={inputStyle}
- />
+ <>
+ {isNarrowWidth ? (
+ <InputField
+ ref={noteInputRef}
+ autoFocus
+ iconEnd={<NoteInsertHashButton inputRef={noteInputRef} />}
+ onEnter={value => {
+ onSelectNote(value, noteAmend);
+ close();
+ }}
+ style={inputStyle}
+ />
+ ) : (
+ <Input
+ ref={noteInputRef}
+ autoFocus
+ onEnter={value => {
+ onSelectNote(value, noteAmend);
+ close();
+ }}
+ style={inputStyle}
+ />
+ )}
+ <NoteTagAutocomplete inputRef={noteInputRef} />
+ </>
)}
</>
);
diff --git a/upcoming-release-notes/add-tags-to-bulk-edit-notes.md b/upcoming-release-notes/add-tags-to-bulk-edit-notes.md
new file mode 100644
index 0000000000..42179372ad
--- /dev/null
+++ b/upcoming-release-notes/add-tags-to-bulk-edit-notes.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [Dreptschar]
+---
+
+Suggest matching tags as you type # in the notes field when bulk editing transaction notes