Skip to content

A local-first personal finance app

Tag autocomplete v2 (#7654)

Alec Bakholdin390ed57c46cf
diff --git a/packages/desktop-client/e2e/page-models/account-page.ts b/packages/desktop-client/e2e/page-models/account-page.ts
index e8337341ea..0386b022a0 100644
--- a/packages/desktop-client/e2e/page-models/account-page.ts
+++ b/packages/desktop-client/e2e/page-models/account-page.ts
@@ -245,7 +245,7 @@ export class AccountPage {
if (transaction.notes) {
const notesCell = transactionRow.getByTestId('notes');
await notesCell.click();
- const notesInput = notesCell.getByRole('textbox');
+ const notesInput = notesCell.getByRole('combobox');
await this.selectInputText(notesInput);
await notesInput.pressSequentially(transaction.notes);
await this.page.keyboard.press('Tab');
diff --git a/packages/desktop-client/src/components/autocomplete/TagAutocomplete.tsx b/packages/desktop-client/src/components/autocomplete/TagAutocomplete.tsx
new file mode 100644
index 0000000000..af75d6db56
--- /dev/null
+++ b/packages/desktop-client/src/components/autocomplete/TagAutocomplete.tsx
@@ -0,0 +1,212 @@
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import type {
+ CSSProperties,
+ FocusEventHandler,
+ KeyboardEvent,
+ KeyboardEventHandler,
+} from 'react';
+import { ListBox, ListBoxItem, Popover } from 'react-aria-components';
+import { useTranslation } from 'react-i18next';
+
+import { Input } from '@actual-app/components/input';
+import { styles } from '@actual-app/components/styles';
+import { theme } from '@actual-app/components/theme';
+import { css } from '@emotion/css';
+
+import { useCurrentWordRange } from '#hooks/useCurrentWordRange';
+import { useCursorPosition } from '#hooks/useCursorPosition';
+import { useTagCSS } from '#hooks/useTagCSS';
+import { useFilteredTags } from '#hooks/useTags';
+
+export type TagAutocompleteProps = {
+ inputValue: string;
+ setInputValue: (v: string) => void;
+ inputStyle?: CSSProperties;
+ onBlur?: FocusEventHandler;
+ onKeyDown?: KeyboardEventHandler;
+ onUpdate?: (value: string) => void;
+};
+
+export function TagAutocomplete({
+ inputValue,
+
+ setInputValue,
+ onBlur,
+ inputStyle,
+ onKeyDown,
+ onUpdate,
+}: TagAutocompleteProps) {
+ const { t } = useTranslation();
+ const getTagCSS = useTagCSS();
+ const autocompleteId = useId();
+ const id = useCallback(
+ (itemId: string) => autocompleteId + '|' + itemId,
+ [autocompleteId],
+ );
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ const [cursorPosition, setCursorPosition] = useCursorPosition(inputRef);
+ 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 [isOpen, setIsOpen] = useState(false);
+ const showPopup = isOpen && filteredItems.length > 0;
+
+ const [highlightedIdx, setHighlightedIdx] = useState(0);
+ const highlightedId =
+ showPopup && highlightedIdx < filteredItems.length
+ ? filteredItems[highlightedIdx].id
+ : null;
+ useEffect(() => {
+ if (highlightedId) {
+ const el = document.querySelector(`[data-key="${id(highlightedId)}"]`);
+ el?.scrollIntoView?.({ block: 'nearest' });
+ }
+ }, [highlightedId, id]);
+
+ function handleSelect(id: string | null) {
+ const tagObj = filteredItems.find(tag => tag.id === id);
+ if (!tagObj) return;
+
+ const nextChar = inputValue.charAt(endIdx);
+ const space = nextChar === ' ' ? '' : ' ';
+ const newValue =
+ inputValue.slice(0, startIdx) +
+ '#' +
+ tagObj.tag +
+ space +
+ inputValue.slice(endIdx);
+ setInputValue(newValue);
+ setHighlightedIdx(0);
+ setIsOpen(false);
+ setCursorPosition(startIdx + tagObj.tag.length + 1 + space.length);
+ }
+
+ function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
+ if (!showPopup) {
+ onKeyDown?.(e);
+ return;
+ }
+
+ if (e.key === 'ArrowUp') {
+ setHighlightedIdx(highlightedIdx - 1);
+ e.preventDefault();
+ } else if (e.key === 'ArrowDown') {
+ setHighlightedIdx(highlightedIdx + 1);
+ e.preventDefault();
+ } else if (e.key === 'Home' && filteredItems.length > 1) {
+ setHighlightedIdx(0);
+ e.preventDefault();
+ } 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();
+ } else if (e.key === 'Escape') {
+ setIsOpen(false);
+ }
+
+ setHighlightedIdx(idx =>
+ Math.max(0, Math.min(idx, filteredItems.length - 1)),
+ );
+ }
+
+ return (
+ <>
+ <Input
+ ref={inputRef}
+ name="notes"
+ aria-label={t('Notes')}
+ aria-expanded={showPopup}
+ aria-controls={id('popover')}
+ role="combobox"
+ style={inputStyle}
+ value={inputValue}
+ onChange={e => {
+ setIsOpen(true);
+ setInputValue(e.currentTarget.value);
+ }}
+ onKeyDown={handleKeyDown}
+ onFocus={() => setIsOpen(true)}
+ onBlur={onBlur}
+ onUpdate={onUpdate}
+ autoComplete={showPopup ? 'off' : undefined}
+ />
+
+ <Popover
+ isNonModal
+ placement="bottom start"
+ className={css(styles.darkScrollbar)}
+ style={{
+ 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}
+ onOpenChange={setIsOpen}
+ >
+ <ListBox
+ aria-label={t('Tag List')}
+ id={id('popover')}
+ items={filteredItems}
+ selectionMode="single"
+ dependencies={[highlightedId]}
+ onPointerDown={e => e.preventDefault()}
+ style={{ borderRadius: 4, maxHeight: '150px', overflowY: 'auto' }}
+ >
+ {(item: (typeof filteredItems)[number]) => (
+ <ListBoxItem
+ key={item.id}
+ id={id(item.id)}
+ textValue={item.name}
+ style={() => ({
+ backgroundColor:
+ highlightedId === item.id
+ ? theme.menuAutoCompleteBackgroundHover
+ : 'transparent',
+ alignItems: 'center',
+ padding: 4,
+ fontWeight: 500,
+ cursor: 'pointer',
+ color:
+ highlightedId === item.id
+ ? theme.menuAutoCompleteItemTextHover
+ : theme.menuAutoCompleteItemText,
+ })}
+ onMouseOver={() =>
+ setHighlightedIdx(
+ Math.max(
+ 0,
+ filteredItems.findIndex(_item => _item.id === item.id),
+ ),
+ )
+ }
+ onPointerDown={e => e.preventDefault()}
+ onClick={() => handleSelect(item.id)}
+ >
+ <div className={getTagCSS(item.tag)}>{item.name}</div>
+ </ListBoxItem>
+ )}
+ </ListBox>
+ </Popover>
+ </>
+ );
+}
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
index 6ccd948b41..442a8dda33 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
@@ -7,6 +7,7 @@ import {
useRef,
useState,
} from 'react';
+import type { RefObject } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { useLocation, useParams, useSearchParams } from 'react-router';
@@ -67,6 +68,7 @@ import type {
PayeeEntity,
TransactionEntity,
} from '@actual-app/core/types/models';
+import { css } from '@emotion/css';
import {
format as formatDate,
isValid as isValidDate,
@@ -87,8 +89,11 @@ import { createSingleTimeScheduleFromTransaction } from '#components/transaction
import { AmountInput } from '#components/util/AmountInput';
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 { useInitialMount } from '#hooks/useInitialMount';
+import { useInputRefValue } from '#hooks/useInputRefValue';
import { useLocalPref } from '#hooks/useLocalPref';
import { useLocationPermission } from '#hooks/useLocationPermission';
import { useNavigate } from '#hooks/useNavigate';
@@ -99,6 +104,8 @@ 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';
@@ -419,6 +426,7 @@ const ChildTransactionEdit = forwardRef<
const { editingField, onRequestActiveEdit, onClearActiveEdit } =
useSingleActiveEditForm()!;
const [hideFraction, _] = useSyncedPref('hideFraction');
+ const noteRef = useRef<HTMLInputElement | null>(null);
const prettyPayee = getPrettyPayee({
t,
@@ -521,6 +529,7 @@ const ChildTransactionEdit = forwardRef<
<View>
<FieldLabel title={t('Notes')} />
<InputField
+ ref={noteRef}
icon={<SvgNotesPaper width={17} height={17} />}
placeholder={t('Add a note (optional)')}
disabled={
@@ -533,6 +542,7 @@ const ChildTransactionEdit = forwardRef<
}
onUpdate={value => onUpdate(transaction, 'notes', value)}
/>
+ <NoteTagAutocomplete inputRef={noteRef} />
</View>
<View style={{ alignItems: 'center' }}>
@@ -627,6 +637,7 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
);
const { data: { grouped: categoryGroups } = { grouped: [] } } =
useCategories();
+ const noteRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
if (window.history.length === 1) {
@@ -1399,6 +1410,7 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
<View>
<FieldLabel title={t('Notes')} />
<InputField
+ ref={noteRef}
icon={<SvgNotesPaper width={17} height={17} />}
placeholder={t('Add a note (optional)')}
disabled={
@@ -1414,6 +1426,7 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
onUpdateInner(transaction, 'notes', event.target.value)
}
/>
+ <NoteTagAutocomplete inputRef={noteRef} />
</View>
{!isAdding && (
@@ -1453,6 +1466,86 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
},
);
+function NoteTagAutocomplete({
+ inputRef,
+}: {
+ inputRef: RefObject<HTMLInputElement | null>;
+}) {
+ // 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 filteredTags = useFilteredTags(currentWord, true);
+
+ const getTagCSS = useTagCSS();
+
+ 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'));
+ }
+
+ 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 ? 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 }}
+ className={getTagCSS(tag.tag)}
+ onMouseDown={e => e.preventDefault()} // stops input from losing focus
+ onClick={() => handleSelect(tag.tag)}
+ >
+ #{tag.tag}
+ </button>
+ </div>
+ ))}
+ </View>
+ </View>
+ );
+}
+
function isTemporary(transaction: TransactionEntity) {
return transaction.id.indexOf('temp') === 0;
}
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
index 2cc763ffa4..1b0d41c4e8 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
@@ -18,6 +18,7 @@ import type {
CategoryEntity,
CategoryGroupEntity,
PayeeEntity,
+ TagEntity,
TransactionEntity,
} from '@actual-app/core/types/models';
import { fireEvent, render, screen } from '@testing-library/react';
@@ -32,6 +33,7 @@ import { SplitsExpandedProvider } from '#hooks/useSplitsExpanded';
import { SpreadsheetProvider } from '#hooks/useSpreadsheet';
import { createTestQueryClient, TestProviders } from '#mocks';
import { payeeQueries } from '#payees';
+import { tagQueries } from '#tags/queries';
import { TransactionTable } from './TransactionsTable';
@@ -72,6 +74,13 @@ const payees: PayeeEntity[] = [
];
queryClient.setQueryData(payeeQueries.list().queryKey, payees);
+const tags: TagEntity[] = [
+ { id: 'tag1', tag: 'vacation' },
+ { id: 'tag2', tag: 'taxes' },
+ { id: 'tag3', tag: 'groceries' },
+];
+queryClient.setQueryData(tagQueries.list().queryKey, tags);
+
const categoryGroups = generateCategoryGroups([
{
name: 'Investments and Savings',
@@ -242,6 +251,7 @@ function initBasicServer() {
grouped: categoryGroups,
list: categories,
}),
+ 'tags-get': async () => tags,
});
}
@@ -1252,4 +1262,74 @@ describe('Transactions', () => {
expect(queryField(container, 'debit', '', 2).textContent).toBe('');
expect(queryField(container, 'credit', '', 2).textContent).toBe('0.00');
});
+
+ describe('Tag Autocomplete', () => {
+ test('adding a tag at the end of the note', async () => {
+ const { container, getTransactions } = renderTransactions();
+ const input = await editField(container, 'notes', 2);
+ await userEvent.clear(input);
+ await userEvent.type(input, 'going on #vac');
+ await screen.findByText('#vacation');
+ await userEvent.keyboard('[Enter]');
+ fireEvent.blur(input);
+
+ expect(getTransactions()[2].notes).toBe('going on #vacation');
+ });
+
+ test('adding a tag at the start of the note', async () => {
+ const { container, getTransactions } = renderTransactions();
+ const input = await editField(container, 'notes', 2);
+ await userEvent.clear(input);
+ await userEvent.type(input, ' is fun');
+ await userEvent.type(input, '#vac', {
+ initialSelectionStart: 0,
+ initialSelectionEnd: 0,
+ });
+ await screen.findByText('#vacation');
+ await userEvent.keyboard('[Enter]');
+ fireEvent.blur(input);
+
+ expect(getTransactions()[2].notes).toBe('#vacation is fun');
+ });
+
+ test('adding a tag in the middle of the note', async () => {
+ const { container, getTransactions } = renderTransactions();
+ const input = await editField(container, 'notes', 2);
+ await userEvent.clear(input);
+ await userEvent.type(input, 'going on is fun');
+ await userEvent.type(input, '#vac', {
+ initialSelectionStart: 9,
+ initialSelectionEnd: 9,
+ });
+ await screen.findByText('#vacation');
+ await userEvent.keyboard('[Enter]');
+ fireEvent.blur(input);
+
+ expect(getTransactions()[2].notes).toBe('going on #vacation is fun');
+ });
+
+ test('select a tag with both Tab and Enter', async () => {
+ const { container, getTransactions } = renderTransactions();
+
+ // Test Tab
+ let input = await editField(container, 'notes', 2);
+ await userEvent.clear(input);
+ await userEvent.type(input, '#vac');
+ await screen.findByText('#vacation');
+ await userEvent.keyboard('[Tab]');
+ fireEvent.blur(input);
+
+ expect(getTransactions()[2].notes).toBe('#vacation');
+
+ // Test Enter
+ input = await editField(container, 'notes', 3);
+ await userEvent.clear(input);
+ await userEvent.type(input, '#tax');
+ await screen.findByText('#taxes');
+ await userEvent.keyboard('[Enter]');
+ fireEvent.blur(input);
+
+ expect(getTransactions()[3].notes).toBe('#taxes');
+ });
+ });
});
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
index edbe75b27e..c2048ea5ff 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
@@ -81,6 +81,7 @@ import { getAccountsById } from '#accounts/accountsSlice';
import { AccountAutocomplete } from '#components/autocomplete/AccountAutocomplete';
import { CategoryAutocomplete } from '#components/autocomplete/CategoryAutocomplete';
import { PayeeAutocomplete } from '#components/autocomplete/PayeeAutocomplete';
+import { TagAutocomplete } from '#components/autocomplete/TagAutocomplete';
import { getStatusProps } from '#components/schedules/StatusBadge';
import type { StatusTypes } from '#components/schedules/StatusBadge';
import { DateSelect } from '#components/select/DateSelect';
@@ -623,7 +624,10 @@ function PayeeCell({
</Text>
</View>
}
- style={{ ...styles.tooltip, borderRadius: '0px 5px 5px 0px' }}
+ style={{
+ ...styles.tooltip,
+ borderRadius: '0px 5px 5px 0px',
+ }}
placement="bottom"
triggerProps={{ delay: 750 }}
>
@@ -701,7 +705,10 @@ function PayeeCell({
</Text>
</View>
}
- style={{ ...styles.tooltip, borderRadius: '0px 5px 5px 0px' }}
+ style={{
+ ...styles.tooltip,
+ borderRadius: '0px 5px 5px 0px',
+ }}
placement="bottom"
triggerProps={{ delay: 750 }}
>
@@ -1427,7 +1434,10 @@ const Transaction = memo(function Transaction({
<DeleteCell
onDelete={() => onDelete && onDelete(transaction.id)}
exposed={editing}
- style={{ ...(isChild && { borderLeftWidth: 1 }), lineHeight: 0 }}
+ style={{
+ ...(isChild && { borderLeftWidth: 1 }),
+ lineHeight: 0,
+ }}
/>
) : (
<Cell width={20} />
@@ -1573,22 +1583,15 @@ const Transaction = memo(function Transaction({
/>
))()}
- <InputCell
- width="flex"
- name="notes"
- textAlign="flex"
- exposed={focusedField === 'notes'}
+ <NotesCell
+ note={notes ?? ''}
+ scheduleNote={isPreview ? schedule?.name : null}
focused={focusedField === 'notes'}
- value={notes ?? (isPreview ? schedule?.name : null) ?? ''}
- valueStyle={valueStyle}
- formatter={value =>
- NotesTagFormatter({ notes: value, onNotesTagClick })
- }
- onExpose={name => !isPreview && onEdit(id, name)}
- inputProps={{
- value: notes || '',
- onUpdate: onUpdate.bind(null, 'notes'),
+ onClickTag={onNotesTagClick}
+ onUpdate={value => {
+ onUpdate('notes', value?.trim());
}}
+ onExpose={name => !isPreview && onEdit(id, name)}
/>
{(isPreview && !isChild) || isParent ? (
@@ -1689,7 +1692,7 @@ const Transaction = memo(function Transaction({
) : isBudgetTransfer || isOffBudget ? (
<InputCell
/* Category field for transfer and off budget transactions
- (NOT preview, it is covered first) */
+ (NOT preview, it is covered first) */
name="category"
width="flex"
exposed={focusedField === 'category'}
@@ -1957,6 +1960,65 @@ const Transaction = memo(function Transaction({
);
});
+type NotesCellProps = {
+ note: string;
+ scheduleNote: string | null | undefined;
+ focused: boolean;
+ onUpdate: (value: string) => void;
+ onClickTag: (tag: string) => void;
+ onExpose: (name: string) => void;
+};
+
+function NotesCell({
+ note,
+ scheduleNote,
+ focused,
+ onUpdate,
+ onClickTag,
+ onExpose,
+}: NotesCellProps) {
+ const [inputValue, setInputValue] = useState(note);
+ useEffect(() => {
+ setInputValue(note);
+ }, [note, setInputValue]);
+
+ function onKeyDown(e: KeyboardEvent) {
+ if (e.key === 'Enter' || e.key === 'Tab') {
+ onUpdate(inputValue);
+ } else if (e.key === 'Escape') {
+ setInputValue(note);
+ }
+ }
+
+ return (
+ <CustomCell
+ width="flex"
+ name="notes"
+ value={note ?? scheduleNote ?? ''}
+ formatter={value =>
+ NotesTagFormatter({ notes: value, onNotesTagClick: onClickTag })
+ }
+ focused={focused}
+ exposed={focused}
+ onExpose={onExpose}
+ onUpdate={onUpdate}
+ onKeyDown={onKeyDown}
+ onBlur={() => onUpdate(inputValue)}
+ >
+ {({ inputStyle, onKeyDown, onBlur }) => (
+ <TagAutocomplete
+ inputValue={inputValue}
+ setInputValue={setInputValue}
+ inputStyle={inputStyle}
+ onBlur={onBlur}
+ onKeyDown={onKeyDown}
+ onUpdate={onUpdate}
+ />
+ )}
+ </CustomCell>
+ );
+}
+
type TransactionErrorProps = {
error: NonNullable<TransactionEntity['error']>;
isDeposit: boolean;
diff --git a/packages/desktop-client/src/hooks/useCurrentWordRange.ts b/packages/desktop-client/src/hooks/useCurrentWordRange.ts
new file mode 100644
index 0000000000..df86dd574d
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useCurrentWordRange.ts
@@ -0,0 +1,31 @@
+import { useMemo } from 'react';
+
+export function useCurrentWordRange(
+ inputValue: string,
+ cursorPosition: number | null,
+) {
+ return useMemo(
+ () => getCurrentWordRange(inputValue, cursorPosition),
+ [inputValue, cursorPosition],
+ );
+}
+
+function getCurrentWordRange(
+ inputValue: string,
+ cursorPosition: number | null,
+): [number, number] {
+ if (!cursorPosition || cursorPosition < 0) return [0, 0];
+ if (cursorPosition > inputValue.length) {
+ return [inputValue.length, inputValue.length];
+ }
+ let startIdx = cursorPosition;
+ const endIdx = cursorPosition;
+
+ while (startIdx > 0 && inputValue.charAt(startIdx - 1).trim() !== '') {
+ startIdx--;
+ }
+ if (startIdx < 0 || endIdx < 0 || startIdx === endIdx) {
+ return [0, 0];
+ }
+ return [startIdx, endIdx];
+}
diff --git a/packages/desktop-client/src/hooks/useCursorPosition.ts b/packages/desktop-client/src/hooks/useCursorPosition.ts
new file mode 100644
index 0000000000..747c1298ec
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useCursorPosition.ts
@@ -0,0 +1,37 @@
+import { useEffect, useRef, useState } from 'react';
+import type { RefObject } from 'react';
+
+import { useRefEventListener } from './useRefEventListener';
+
+export function useCursorPosition(
+ ref: RefObject<HTMLInputElement | null>,
+): [number | null, (n: number | null) => void] {
+ 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;
+ setCursorPosition(
+ document.activeElement === input ? input.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]);
+
+ return [cursorPosition, _setCursorPosition];
+}
diff --git a/packages/desktop-client/src/hooks/useInputRefValue.ts b/packages/desktop-client/src/hooks/useInputRefValue.ts
new file mode 100644
index 0000000000..c13e3109de
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useInputRefValue.ts
@@ -0,0 +1,40 @@
+import { useEffect, useState } from 'react';
+import type { RefObject } from 'react';
+
+import { useRefEventListener } from './useRefEventListener';
+
+export function useInputRefValue(
+ inputRef: RefObject<HTMLInputElement | null>,
+): [string, (newValue: string) => void] {
+ const [value, setValue] = useState('');
+ useRefEventListener(
+ inputRef,
+ 'input',
+ e => setValue((e.target as HTMLInputElement).value),
+ [setValue],
+ );
+ useEffect(
+ () => setValue(inputRef.current?.value ?? ''),
+ [inputRef, setValue],
+ );
+
+ function _setValue(newValue: string) {
+ if (!inputRef.current) return;
+ // If we want to honor the input's onChange prop, we have
+ // to use native value setter, then fire the 'input' event.
+ // Doing normal inputRef.current.value = 'newval' and then
+ // following that up with firing an event doesn't work, because
+ // React will intercept that and change the value internally,
+ // and when you go to fire an event, it will see that nothing has
+ // changed since it last saw a value (it just updated it itself)
+ // meaning no event will get fired. Or Something.
+ // eslint-disable-next-line typescript-eslint(unbound-method)
+ const nativeSetter = Object.getOwnPropertyDescriptor(
+ window.HTMLInputElement.prototype,
+ 'value',
+ )?.set;
+ nativeSetter?.call(inputRef.current, newValue);
+ inputRef.current.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+ return [value, _setValue];
+}
diff --git a/packages/desktop-client/src/hooks/useRefEventListener.ts b/packages/desktop-client/src/hooks/useRefEventListener.ts
new file mode 100644
index 0000000000..7900f1d1be
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useRefEventListener.ts
@@ -0,0 +1,27 @@
+import { useCallback, useEffect } from 'react';
+import type { RefObject } from 'react';
+
+export function useRefEventListener<
+ ElementType extends EventTarget,
+ EventType extends keyof HTMLElementEventMap,
+>(
+ ref: RefObject<ElementType | null>,
+ event: EventType,
+ // oxlint-disable-next-line typescript/no-explicit-any
+ callback: (this: ElementType, ev: HTMLElementEventMap[EventType]) => any,
+ // oxlint-disable-next-line typescript/no-explicit-any
+ deps: any[],
+) {
+ // oxlint-disable-next-line eslint-plugin-react-hooks/exhaustive-deps
+ const _callback = useCallback(callback, deps);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+
+ const callbackRef = _callback as EventListener; // closure?
+ el.addEventListener(event, callbackRef);
+ return () => {
+ el.removeEventListener(event, callbackRef);
+ };
+ }, [ref, event, _callback]);
+}
diff --git a/packages/desktop-client/src/hooks/useTags.ts b/packages/desktop-client/src/hooks/useTags.ts
index e6a9fcb183..6fc121e258 100644
--- a/packages/desktop-client/src/hooks/useTags.ts
+++ b/packages/desktop-client/src/hooks/useTags.ts
@@ -1,7 +1,28 @@
+import { useMemo } from 'react';
+
import { useQuery } from '@tanstack/react-query';
+import { Fzf } from 'fzf';
import { tagQueries } from '#tags/queries';
export function useTags() {
return useQuery(tagQueries.list());
}
+
+export function useFilteredTags(
+ filterStr: string,
+ requireHashInFilter?: boolean,
+) {
+ const { data: tags } = useTags();
+ return useMemo(() => {
+ if (!filterStr || !tags) return [];
+ if (requireHashInFilter && !filterStr.startsWith('#')) return [];
+
+ return new Fzf(tags, {
+ selector: tag => tag.tag,
+ limit: 100,
+ })
+ .find(filterStr.replace(/^#/, ''))
+ .map(item => item.item);
+ }, [tags, filterStr, requireHashInFilter]);
+}
diff --git a/packages/desktop-client/src/style/styles.ts b/packages/desktop-client/src/style/styles.ts
index 680546561c..bb72cd830c 100644
--- a/packages/desktop-client/src/style/styles.ts
+++ b/packages/desktop-client/src/style/styles.ts
@@ -49,6 +49,7 @@ function onScrollbarChange() {
borderRadius: 30,
backgroundClip: 'padding-box',
backgroundColor: 'rgba(200, 200, 200, .5)',
+ border: '2px solid rgba(0, 0, 0, 0)',
},
};
diff --git a/packages/loot-core/src/server/db/index.ts b/packages/loot-core/src/server/db/index.ts
index 4a27730a64..6b2a6bde49 100644
--- a/packages/loot-core/src/server/db/index.ts
+++ b/packages/loot-core/src/server/db/index.ts
@@ -56,7 +56,7 @@ import type {
export * from './types';
-export { toDateRepr, fromDateRepr } from '#server/models';
+export { fromDateRepr, toDateRepr } from '#server/models';
let dbPath: string | null = null;
let db: Database | null = null;
@@ -366,7 +366,9 @@ export async function insertCategoryGroup(
);
if (existingGroup) {
throw new Error(
- `A ${existingGroup.hidden ? 'hidden ' : ''}'${existingGroup.name}' category group already exists.`,
+ `A ${
+ existingGroup.hidden ? 'hidden ' : ''
+ }'${existingGroup.name}' category group already exists.`,
);
}
@@ -397,7 +399,9 @@ export async function updateCategoryGroup(
);
if (existingGroup) {
throw new Error(
- `A ${existingGroup.hidden ? 'hidden ' : ''}'${existingGroup.name}' category group already exists.`,
+ `A ${
+ existingGroup.hidden ? 'hidden ' : ''
+ }'${existingGroup.name}' category group already exists.`,
);
}
group = categoryGroupModel.validate(group, { update: true });
@@ -960,7 +964,7 @@ export function getTags() {
SELECT id, tag, color, description
FROM tags
WHERE tombstone = 0
- ORDER BY tag
+ ORDER BY tag COLLATE NOCASE
`);
}
@@ -968,7 +972,7 @@ export function getAllTags() {
return all<DbTag>(`
SELECT id, tag, color, description
FROM tags
- ORDER BY tag
+ ORDER BY tag COLLATE NOCASE
`);
}
diff --git a/upcoming-release-notes/7654.md b/upcoming-release-notes/7654.md
new file mode 100644
index 0000000000..04ba3c55bd
--- /dev/null
+++ b/upcoming-release-notes/7654.md
@@ -0,0 +1,6 @@
+---
+category: Features
+authors: [alecbakholdin]
+---
+
+Added dropdown for tags when entering '#' on desktop and mobile