Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: ensure fresh search gets timestamps (#1310)

gbirman1bf813a31ff4
diff --git a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
index 434f353bc3..ba9129cc77 100644
--- a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
+++ b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
@@ -1,18 +1,17 @@
-import {
- useChannelsContext,
- useDmActivityByUserId,
-} from '@core/context/channels';
+import { useChannelsContext } from '@core/context/channels';
import {
type CombinedEntity,
createEntitySearchConfig,
entityMapper,
getEntityName,
getEntitySearchText,
+ getEntityTimestampedItem,
getEntityType,
+ isChannelEntity,
threadMapper,
} from '@core/component/Properties/component/modal/shared/entityUtils';
import { usePropertyEntityDisplay } from '@core/component/Properties/hooks/usePropertyEntityDisplay';
-import { useContacts } from '@core/user';
+import { useAugmentUserWithDmActivity, useContacts } from '@core/user';
import { useEmail } from '@core/context/user';
import { createFreshSearch } from '@core/util/freshSort';
import {
@@ -92,7 +91,6 @@ export const FilterValueEntity: Component<FilterValueEntityProps> = (props) => {
const contacts = useContacts();
const channelsContext = useChannelsContext();
const channels = channelsContext.channels;
- const dmActivityByUserId = useDmActivityByUserId();
const historyQuery = useHistoryQuery();
// Email queries for THREAD type or generic ENTITY (no specific type)
@@ -131,20 +129,11 @@ export const FilterValueEntity: Component<FilterValueEntityProps> = (props) => {
});
// Helper to augment user entities with DM activity timestamps (same as MentionsMenu)
- const augmentUsersWithDmActivity = () => {
- const dmActivity = dmActivityByUserId();
- return contacts()
- .map(entityMapper('user'))
- .map((entity) => {
- const dmTimestamp = dmActivity.get(entity.id);
- if (dmTimestamp) {
- return {
- ...entity,
- lastInteraction: dmTimestamp,
- };
- }
- return entity;
- });
+ const augmentUserWithDmActivity = useAugmentUserWithDmActivity();
+ const augmentUsersWithDmActivity = (): CombinedEntity[] => {
+ return contacts().map((user) =>
+ entityMapper('user')(augmentUserWithDmActivity(user))
+ );
};
// Get entities based on specific entity type (same logic as PropertyEntitySelector)
@@ -203,7 +192,9 @@ export const FilterValueEntity: Component<FilterValueEntityProps> = (props) => {
// Search function for fuzzy matching (same config as PropertyEntitySelector)
const entitySearch = createFreshSearch<CombinedEntity>(
createEntitySearchConfig(currentUserDomain),
- getEntitySearchText
+ getEntitySearchText,
+ isChannelEntity,
+ getEntityTimestampedItem
);
// Get selected entity IDs for filtering
diff --git a/js/app/packages/app/component/command/Konsole.tsx b/js/app/packages/app/component/command/Konsole.tsx
index b809b651a4..52edfd6bf8 100644
--- a/js/app/packages/app/component/command/Konsole.tsx
+++ b/js/app/packages/app/component/command/Konsole.tsx
@@ -142,7 +142,9 @@ export function KommandMenuInner(props: {
const searchItems = createMemo(() => {
const freshSearch = createFreshSearch<CommandItemCard>(
freshSearchConfig(),
- (item) => item.data.name
+ (item) => item.data.name,
+ (item) => item.type === 'channel',
+ (_item) => ({})
);
return freshSearch(allItems(), debouncedLocalQuery()).map(
(result) => result.item
diff --git a/js/app/packages/app/component/property-edit-modal/hooks/useEntitiesForProperty.ts b/js/app/packages/app/component/property-edit-modal/hooks/useEntitiesForProperty.ts
index 98cf66683a..7c1186524c 100644
--- a/js/app/packages/app/component/property-edit-modal/hooks/useEntitiesForProperty.ts
+++ b/js/app/packages/app/component/property-edit-modal/hooks/useEntitiesForProperty.ts
@@ -1,15 +1,14 @@
-import {
- useChannelsContext,
- useDmActivityByUserId,
-} from '@core/context/channels';
+import { useChannelsContext } from '@core/context/channels';
import {
type CombinedEntity,
createEntitySearchConfig,
entityMapper,
getEntitySearchText,
+ getEntityTimestampedItem,
+ isChannelEntity,
threadMapper,
} from '@core/component/Properties/component/modal/shared/entityUtils';
-import { useContacts } from '@core/user';
+import { useAugmentUserWithDmActivity, useContacts } from '@core/user';
import { createFreshSearch } from '@core/util/freshSort';
import { useEmail } from '@core/context/user';
import {
@@ -48,7 +47,6 @@ export function useEntitiesForProperty(
const contacts = useContacts();
const channelsContext = useChannelsContext();
const channels = channelsContext.channels;
- const dmActivityByUserId = useDmActivityByUserId();
const historyQuery = useHistoryQuery();
const history = () => historyQuery.data ?? [];
@@ -90,20 +88,11 @@ export function useEntitiesForProperty(
});
// Helper to augment user entities with DM activity timestamps (same as MentionsMenu)
- const augmentUsersWithDmActivity = () => {
- const dmActivity = dmActivityByUserId();
- return contacts()
- .map(entityMapper('user'))
- .map((entity) => {
- const dmTimestamp = dmActivity.get(entity.id);
- if (dmTimestamp) {
- return {
- ...entity,
- lastInteraction: dmTimestamp,
- };
- }
- return entity;
- });
+ const augmentUserWithDmActivity = useAugmentUserWithDmActivity();
+ const augmentUsersWithDmActivity = (): CombinedEntity[] => {
+ return contacts().map((user) =>
+ entityMapper('user')(augmentUserWithDmActivity(user))
+ );
};
// Get entities based on specific entity type
@@ -161,7 +150,9 @@ export function useEntitiesForProperty(
// search function for fuzzy matching
const entitySearch = createFreshSearch<CombinedEntity>(
createEntitySearchConfig(currentUserDomain),
- getEntitySearchText
+ getEntitySearchText,
+ isChannelEntity,
+ getEntityTimestampedItem
);
// get filtered entities based on search query
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
index ef15abc403..82d18fae1a 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
@@ -9,19 +9,21 @@ import { EntityIcon } from '@core/component/EntityIcon';
import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';
import { UserIcon } from '@core/component/UserIcon';
import { ENABLE_CHAT_CHANNEL_ATTACHMENT } from '@core/constant/featureFlags';
-import {
- useChannelsContext,
- useDmActivityByUserId,
-} from '@core/context/channels';
+import { useChannelsContext } from '@core/context/channels';
import { useEmail } from '@core/context/user';
import clickOutside from '@core/directive/clickOutside';
import {
type ChannelWithParticipants,
type IUser,
+ useAugmentUserWithDmActivity,
useContacts,
} from '@core/user';
import { getDateSuggestions } from '@core/util/dateParser';
-import { createFreshSearch, FreshSearchPresets } from '@core/util/freshSort';
+import {
+ createFreshSearch,
+ FreshSearchPresets,
+ type TimestampedItem,
+} from '@core/util/freshSort';
import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
import ClockIcon from '@icon/regular/clock.svg';
import EmailIcon from '@icon/regular/envelope.svg';
@@ -114,6 +116,30 @@ const getItemSearchText = (item: CombinedEntity): string => {
}
};
+const getItemTimestamp = (item: CombinedEntity): TimestampedItem => {
+ switch (item.kind) {
+ case 'item':
+ return {
+ updatedAt: item.data.updatedAt,
+ };
+ case 'channel':
+ return {
+ updatedAt: item.data.updated_at,
+ };
+ case 'email':
+ return {
+ updatedAt: item.data.updatedAt,
+ viewedAt: item.data.viewedAt,
+ };
+ case 'user':
+ return {
+ lastInteraction: item.data.lastInteraction,
+ };
+ default:
+ return {};
+ }
+};
+
/**
* All incoming items will be run through this filter function. PLEASE use this function
* to ignore certain items before they make it to search.
@@ -438,6 +464,7 @@ function MentionsMenuInner(props: {
props.menu.searchTerm()
);
const historyQuery = useHistoryQuery();
+ // TODO: support viewed at in history
const history = createMemo(() => {
if (props.history) {
return props.history().map(entityMapper('item'));
@@ -461,25 +488,13 @@ function MentionsMenuInner(props: {
}
const contacts = useContacts();
+ const augmentUserWithDmActivity = useAugmentUserWithDmActivity();
- const dmActivityByUserId = useDmActivityByUserId();
-
- const users = createMemo(() => {
+ const users = createMemo((): Entity<'user'>[] => {
const list = props.users?.() ?? contacts();
- const dmActivity = dmActivityByUserId();
return list
- .map(entityMapper('user'))
- .map((entity) => {
- const dmTimestamp = dmActivity.get(entity.id);
- if (dmTimestamp) {
- return {
- ...entity,
- lastInteraction: dmTimestamp,
- };
- }
- return entity;
- })
+ .map((user) => entityMapper('user')(augmentUserWithDmActivity(user)))
.filter(allItemFilter);
});
@@ -645,7 +660,9 @@ function MentionsMenuInner(props: {
const itemSearch = createFreshSearch<CombinedEntity<'item' | 'channel'>>(
{},
- getItemSearchText
+ getItemSearchText,
+ (item) => item.kind === 'channel',
+ getItemTimestamp
);
const filteredItems = createMemo(() => {
const allResults = itemSearch(historyAndChannels(), searchTerm()).map(
@@ -678,11 +695,13 @@ function MentionsMenuInner(props: {
});
const userSearch = createFreshSearch<Entity<'user'>>(
- FreshSearchPresets.baseUserSearch(
+ FreshSearchPresets.baseUserSearch<Entity<'user'>>(
currentUserDomain,
(item) => item.data.email
),
- getItemSearchText
+ getItemSearchText,
+ (_item) => false,
+ getItemTimestamp
);
// Group aliases available in channel context
@@ -712,7 +731,9 @@ function MentionsMenuInner(props: {
const emailSearch = createFreshSearch<Entity<'email'>>(
{ timeWeight: 0, brevityWeight: 0.3 },
- getItemSearchText
+ getItemSearchText,
+ (_item) => false,
+ getItemTimestamp
);
const filteredEmails = createMemo(() => {
diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
index 6f946fcccf..f63f0dec2c 100644
--- a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
@@ -1,13 +1,16 @@
import { useMaybeBlockId } from '@core/block';
-import {
- useChannelsContext,
- useDmActivityByUserId,
-} from '@core/context/channels';
+import { useChannelsContext } from '@core/context/channels';
import { EntityIcon } from '@core/component/EntityIcon';
import { UserIcon } from '@core/component/UserIcon';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import type { IUser } from '@core/user';
-import { idToEmail, tryMacroId, useContacts, useDisplayName } from '@core/user';
+import {
+ idToEmail,
+ tryMacroId,
+ useAugmentUserWithDmActivity,
+ useContacts,
+ useDisplayName,
+} from '@core/user';
import { createFreshSearch } from '@core/util/freshSort';
import CompanyIcon from '@icon/duotone/building-duotone.svg';
import ChannelBuildingIcon from '@icon/duotone/building-office-duotone.svg';
@@ -45,7 +48,9 @@ import {
entityMapper,
getEntityName,
getEntitySearchText,
+ getEntityTimestampedItem,
getEntityType,
+ isChannelEntity,
threadMapper,
} from './entityUtils';
import { OptionCheckBox } from './OptionCheckBox';
@@ -159,7 +164,6 @@ export function PropertyEntitySelector(props: EntityInputProps) {
const contacts = useContacts();
const channelsContext = useChannelsContext();
const channels = channelsContext.channels;
- const dmActivityByUserId = useDmActivityByUserId();
// Get current user info for injection into contacts
const currentUserId = useUserId();
@@ -239,18 +243,11 @@ export function PropertyEntitySelector(props: EntityInputProps) {
});
// Helper to augment user entities with DM activity timestamps (same as MentionsMenu)
- const augmentUsersWithDmActivity = (users: IUser[]) => {
- const dmActivity = dmActivityByUserId();
- return users.map(entityMapper('user')).map((entity) => {
- const dmTimestamp = dmActivity.get(entity.id);
- if (dmTimestamp) {
- return {
- ...entity,
- lastInteraction: dmTimestamp,
- };
- }
- return entity;
- });
+ const augmentUserWithDmActivity = useAugmentUserWithDmActivity();
+ const augmentUsersWithDmActivity = (users: IUser[]): CombinedEntity[] => {
+ return users.map((user) =>
+ entityMapper('user')(augmentUserWithDmActivity(user))
+ );
};
// Local entities (always available, used for instant results)
@@ -323,7 +320,9 @@ export function PropertyEntitySelector(props: EntityInputProps) {
const entitySearch = createFreshSearch<CombinedEntity>(
createEntitySearchConfig(currentUserDomain),
- getEntitySearchText
+ getEntitySearchText,
+ isChannelEntity,
+ getEntityTimestampedItem
);
const filteredEntities = createMemo(() => {
diff --git a/js/app/packages/core/component/Properties/component/modal/shared/entityUtils.ts b/js/app/packages/core/component/Properties/component/modal/shared/entityUtils.ts
index 762dcc2f56..c788be8b07 100644
--- a/js/app/packages/core/component/Properties/component/modal/shared/entityUtils.ts
+++ b/js/app/packages/core/component/Properties/component/modal/shared/entityUtils.ts
@@ -16,7 +16,7 @@ export type CombinedEntity =
/** Creates a mapper function for a specific entity kind */
export function entityMapper(kind: 'item' | 'user' | 'channel') {
return (data: Item | IUser | ChannelWithParticipants): CombinedEntity => {
- return { kind, data, id: (data as { id: string }).id } as CombinedEntity;
+ return { kind, data, id: data.id } as CombinedEntity;
};
}
@@ -85,20 +85,47 @@ export function getEntityType(entity: CombinedEntity): EntityType {
}
}
+/** Check if entity is a channel */
+export function isChannelEntity(item: CombinedEntity): boolean {
+ return item.kind === 'channel';
+}
+
+/** Get timestamped item from combined entity */
+export function getEntityTimestampedItem<T extends CombinedEntity>(
+ item: T
+): TimestampedItem {
+ switch (item.kind) {
+ case 'item':
+ return {
+ updatedAt: item.data.updatedAt,
+ };
+ case 'channel':
+ return {
+ updatedAt: item.data.updated_at,
+ };
+ case 'user':
+ return {
+ lastInteraction: item.data.lastInteraction,
+ };
+ default:
+ return {};
+ }
+}
+
/**
* Creates search config for entity searches with same-domain boost.
* Uses the same preset as MentionsMenu and RecipientSelector for consistency.
*/
-export function createEntitySearchConfig(
+export function createEntitySearchConfig<T extends CombinedEntity>(
currentUserDomain: Accessor<string | undefined>
-): FreshSortConfig {
- const boostFn = <T extends TimestampedItem>(item: T): number => {
+): FreshSortConfig<T> {
+ const boostFn = (item: T): number => {
const userDomain = currentUserDomain();
if (!userDomain) return 0;
// Check if this looks like a CombinedEntity with user data
- if (item?.kind === 'user' && item?.data?.email) {
- const email = item.data.email as string;
+ if (item.kind === 'user' && item.data.email) {
+ const email = item.data.email;
const itemDomain = email.split('@')[1];
return itemDomain === userDomain ? 0.5 : 0;
}
diff --git a/js/app/packages/core/component/RecipientSelector.tsx b/js/app/packages/core/component/RecipientSelector.tsx
index 1d9ebf71bf..4a2543897c 100644
--- a/js/app/packages/core/component/RecipientSelector.tsx
+++ b/js/app/packages/core/component/RecipientSelector.tsx
@@ -26,7 +26,6 @@ import {
} from '@kobalte/core/combobox';
import type { Channel } from '@service-comms/generated/models/channel';
import { useEmail, useUserId } from '@core/context/user';
-import { useDmActivityByUserId } from '@core/context/channels';
import { debounce } from '@solid-primitives/scheduled';
import { createFreshSearch, FreshSearchPresets } from '@core/util/freshSort';
import * as EmailValidator from 'email-validator';
@@ -42,6 +41,7 @@ import {
Switch,
} from 'solid-js';
import { type VirtualizerHandle, VList } from 'virtua/solid';
+import { useAugmentUserWithDmActivity } from '@core/user/dmActivity';
function getRecipientOptionEmail(
option: CombinedRecipientItem
@@ -331,22 +331,25 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
return email ? email.split('@')[1] : undefined;
});
- const dmActivityByUserId = useDmActivityByUserId();
-
// Create search function for recipients - only used for initial sorting with no query
- const recipientSearch = createFreshSearch<CombinedRecipientItem<K>>(
- FreshSearchPresets.baseUserSearch(currentUserDomain, (item) =>
- item.kind === 'user' ? item.data.email : undefined
+ const recipientSearch = createFreshSearch<CombinedRecipientItem>(
+ FreshSearchPresets.baseUserSearch<CombinedRecipientItem>(
+ currentUserDomain,
+ getRecipientOptionEmail
),
- getRecipientOptionTextValue as (item: CombinedRecipientItem<K>) => string
+ getRecipientOptionTextValue,
+ (item) => item.kind === 'channel',
+ (item) => ({
+ lastInteraction:
+ item.kind === 'user' ? item.data.lastInteraction : undefined,
+ })
);
+ const augmentUserWithDmActivity = useAugmentUserWithDmActivity();
const recipients = createMemo(() => {
- const options: CombinedRecipientItem<K>[] = [];
+ const options: CombinedRecipientItem[] = [];
const emails = new Set<string>();
- const dmActivity = dmActivityByUserId();
-
for (const option of props.options()) {
const item = option as CombinedRecipientItem;
const email = getRecipientOptionEmail(item);
@@ -364,19 +367,11 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
emails.add(email.toLowerCase());
}
- // Augment user items with DM activity timestamp
if (item.kind === 'user') {
- const dmTimestamp = dmActivity.get(item.id);
- if (dmTimestamp) {
- options.push({
- ...option,
- lastInteraction: dmTimestamp,
- } as CombinedRecipientItem<K>);
- continue;
- }
+ item.data = augmentUserWithDmActivity(item.data);
}
- options.push(option);
+ options.push(item);
}
const sorted = recipientSearch(options, '').map((item) => {
diff --git a/js/app/packages/core/user/dmActivity.ts b/js/app/packages/core/user/dmActivity.ts
new file mode 100644
index 0000000000..98acf2fd47
--- /dev/null
+++ b/js/app/packages/core/user/dmActivity.ts
@@ -0,0 +1,14 @@
+import { useDmActivityByUserId } from '@core/context/channels';
+import type { IUser } from './types';
+
+export function useAugmentUserWithDmActivity() {
+ const getDmActivity = useDmActivityByUserId();
+
+ return (user: IUser): IUser => {
+ const dmTimestamp = getDmActivity().get(user.id);
+ return {
+ ...user,
+ lastInteraction: dmTimestamp,
+ };
+ };
+}
diff --git a/js/app/packages/core/user/index.ts b/js/app/packages/core/user/index.ts
index 0f7ba959d8..21da99a7e7 100644
--- a/js/app/packages/core/user/index.ts
+++ b/js/app/packages/core/user/index.ts
@@ -7,6 +7,7 @@ export {
type WithCustomUserInput,
} from './combinedRecipient';
export { useContacts } from './contactService';
+export { useAugmentUserWithDmActivity } from './dmActivity';
export {
type DisplayNameParts,
useDisplayName,
diff --git a/js/app/packages/core/user/types.ts b/js/app/packages/core/user/types.ts
index a674ec95ce..b12b50e4da 100644
--- a/js/app/packages/core/user/types.ts
+++ b/js/app/packages/core/user/types.ts
@@ -13,6 +13,7 @@ export type IUser = {
id: string;
email: string;
name: string;
+ lastInteraction?: number;
};
type BaseUserName = {
diff --git a/js/app/packages/core/util/freshSort.test.ts b/js/app/packages/core/util/freshSort.test.ts
index 156cdc2df0..cac8e9bc74 100644
--- a/js/app/packages/core/util/freshSort.test.ts
+++ b/js/app/packages/core/util/freshSort.test.ts
@@ -17,7 +17,9 @@ function createSearch(opts: { useViewedAt?: boolean; channelBoost?: number }) {
timeWeight: 0.9,
fuzzyWeight: 0.1,
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ viewedAt: item.viewedAt, updatedAt: item.updatedAt })
);
}
@@ -77,7 +79,9 @@ describe('createFreshSearch with comma-separated channel matching', () => {
fuzzyWeight: 0.9,
timeWeight: 0.1,
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ viewedAt: item.viewedAt, updatedAt: item.updatedAt })
);
}
@@ -217,7 +221,9 @@ describe('freshSort with all exact matches', () => {
fuzzyWeight: 0.5,
timeWeight: 0.5,
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ viewedAt: item.viewedAt, updatedAt: item.updatedAt })
);
const results = search(items, 'Design');
@@ -248,7 +254,9 @@ describe('freshSort with all exact matches', () => {
timeWeight: 0.2,
channelBoost: 2.0,
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ viewedAt: item.viewedAt, updatedAt: item.updatedAt })
);
const results = search(items, 'Design');
@@ -299,7 +307,9 @@ describe('boostFn functionality', () => {
return itemDomain === currentUserDomain ? 1.0 : 0; // 100% boost for same domain
},
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ viewedAt: item.viewedAt, updatedAt: item.updatedAt })
);
const results = search(items, 'o'); // All three match with 'o' in their names
@@ -337,7 +347,9 @@ describe('boostFn functionality', () => {
return itemDomain === currentUserDomain ? 0.5 : 0;
},
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ viewedAt: item.viewedAt, updatedAt: item.updatedAt })
);
const results = search(items, 'Ali');
@@ -360,7 +372,9 @@ describe('boostFn functionality', () => {
timeWeight: 0.5,
boostFn: () => 0, // No boost
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ viewedAt: item.viewedAt, updatedAt: item.updatedAt })
);
const results = search(items, '');
@@ -398,7 +412,9 @@ describe('boostFn functionality', () => {
return itemDomain === 'macro.com' ? 0.3 : 0;
},
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ viewedAt: item.viewedAt, updatedAt: item.updatedAt })
);
const results = search(items, 'Design');
@@ -420,7 +436,9 @@ describe('boostFn functionality', () => {
timeWeight: 0.5,
// boostFn is undefined
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ viewedAt: item.viewedAt, updatedAt: item.updatedAt })
);
const results = search(items, '');
@@ -468,7 +486,9 @@ describe('DM activity timestamps for user ranking', () => {
timeWeight: 0.3,
brevityWeight: 0.1,
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ lastInteraction: item.lastInteraction })
);
const results = search(users, '');
@@ -513,7 +533,9 @@ describe('DM activity timestamps for user ranking', () => {
timeWeight: 0.3,
brevityWeight: 0.1,
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ lastInteraction: item.lastInteraction })
);
const results = search(users, 'Ali');
@@ -548,7 +570,9 @@ describe('DM activity timestamps for user ranking', () => {
timeWeight: 0.3,
brevityWeight: 0.1,
},
- (item) => item.name
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => ({ lastInteraction: item.lastInteraction })
);
const results = search(users, '');
diff --git a/js/app/packages/core/util/freshSort.ts b/js/app/packages/core/util/freshSort.ts
index 729ec2dd35..644f250684 100644
--- a/js/app/packages/core/util/freshSort.ts
+++ b/js/app/packages/core/util/freshSort.ts
@@ -7,7 +7,17 @@ import type { FilterResult } from 'fuzzy';
import fuzzy from 'fuzzy';
import { fuzzyScoreCommaSpaceSeparated } from './fuzzy';
-export interface FreshSortConfig {
+type BoostFn<T> = (item: T) => number;
+
+type NameFn<T> = (item: T) => string;
+
+type TimestampFn<T> = (item: T) => TimestampedItem;
+
+type IsChannelFn<T> = (item: T) => boolean;
+
+type EmailFn<T> = (item: T) => string | undefined;
+
+export interface FreshSortConfig<T> {
/** Weight for fuzzy match (0-1). Higher values prioritize search relevance. Default: 0.7 */
fuzzyWeight?: number;
/** Weight for time recency (0-1). Higher values prioritize recent items. Default: 0.3 */
@@ -27,21 +37,15 @@ export interface FreshSortConfig {
/** Enable comma-separated matching for channel names. When enabled, query "a,b" matches channel name "a,c,b". Default: false */
commaSeparatedChannelMatch?: boolean;
/** Function to calculate per-item boost. Returns a boost multiplier (e.g., 0.2 for +20% boost). Default: undefined */
- boostFn?: <T extends TimestampedItem>(item: T) => number;
+ boostFn?: BoostFn<T>;
}
-// TODO: fix this type since [key: string]: any is too loose
-// for example, CombinedEntity in mentions menu only includes timestamp info under the data field
-// but this assumed a flattened object so fresh search isn't working
+type FreshSortConfigWithDefaults = Required<FreshSortConfig<unknown>>;
+
export interface TimestampedItem {
updatedAt?: number | string;
- updated_at?: number | string;
viewedAt?: number | string;
- viewed_at?: number | string;
lastInteraction?: number | string;
- last_interaction?: number | string;
- type?: string;
- [key: string]: any;
}
export interface FreshSortResult<T> {
@@ -66,12 +70,6 @@ const DEFAULT_CONFIG = {
boostFn: undefined,
} as const;
-type FreshSortConfigWithDefaults = Required<
- Omit<FreshSortConfig, 'boostFn'>
-> & {
- boostFn: FreshSortConfig['boostFn'];
-};
-
function extractTimestamp(
item: TimestampedItem,
useViewedAt: boolean = false
@@ -79,19 +77,9 @@ function extractTimestamp(
let timestamp: number | string | undefined;
if (useViewedAt) {
- timestamp =
- item.viewedAt ??
- item.viewed_at ??
- item.updatedAt ??
- item.updated_at ??
- item.lastInteraction ??
- item.last_interaction;
+ timestamp = item.viewedAt ?? item.updatedAt ?? item.lastInteraction;
} else {
- timestamp =
- item.updatedAt ??
- item.updated_at ??
- item.lastInteraction ??
- item.last_interaction;
+ timestamp = item.updatedAt ?? item.lastInteraction;
}
if (timestamp === undefined || timestamp === null) return 0;
@@ -115,10 +103,6 @@ function extractTimestamp(
return 0;
}
-function isChannelItem(item: TimestampedItem): boolean {
- return item.type === 'channel';
-}
-
function calculateTimeScore(
timestamp: number,
config: FreshSortConfigWithDefaults
@@ -158,9 +142,11 @@ function calculateBrevityScore(text: string): number {
return Math.exp(-2 * normalizedLength);
}
-export function freshSort<T extends TimestampedItem>(
+function freshSort<T>(
filterResults: FilterResult<T>[],
- config: FreshSortConfig = {}
+ config: FreshSortConfig<T> = {},
+ isChannelItem: IsChannelFn<T>,
+ getTimestamp: TimestampFn<T>
): FreshSortResult<T>[] {
const finalConfig = {
...DEFAULT_CONFIG,
@@ -181,11 +167,12 @@ export function freshSort<T extends TimestampedItem>(
: 1;
const scoredResults: FreshSortResult<T>[] = filterResults.map((result) => {
+ const timestampInfo = getTimestamp(result.original);
const rawScore = result.score === Infinity ? maxFuzzyScore : result.score;
const fuzzyScore =
maxFuzzyScore === 0 ? 0 : normalizeFuzzyScore(rawScore, maxFuzzyScore);
const timeScore = calculateTimeScore(
- extractTimestamp(result.original, finalConfig.useViewedAt),
+ extractTimestamp(timestampInfo, finalConfig.useViewedAt),
finalConfig
);
@@ -226,9 +213,11 @@ export function freshSort<T extends TimestampedItem>(
return scoredResults;
}
-export function createFreshSearch<T extends TimestampedItem>(
- config: FreshSortConfig = {},
- extractor: (item: T) => string
+export function createFreshSearch<T>(
+ config: FreshSortConfig<T> = {},
+ getName: NameFn<T>,
+ isChannelItem: IsChannelFn<T>,
+ getTimestamp: TimestampFn<T>
) {
return (items: T[], query: string): FreshSortResult<T>[] => {
const finalConfig = { ...DEFAULT_CONFIG, ...config };
@@ -245,7 +234,7 @@ export function createFreshSearch<T extends TimestampedItem>(
for (const item of items) {
if (isChannelItem(item)) {
- const name = extractor(item);
+ const name = getName(item);
const score = fuzzyScoreCommaSpaceSeparated(query, name);
if (score >= 0) {
channelResults.push({
@@ -262,18 +251,18 @@ export function createFreshSearch<T extends TimestampedItem>(
// Get fuzzy results for non-channel items using regular matching
const nonChannelResults = fuzzy.filter(query, nonChannelItems, {
- extract: extractor,
+ extract: getName,
});
// Combine results
const allResults = [...channelResults, ...nonChannelResults];
- return freshSort(allResults, config);
+ return freshSort(allResults, config, isChannelItem, getTimestamp);
}
const fuzzyResults = fuzzy.filter(query, items, {
- extract: extractor,
+ extract: getName,
});
- return freshSort(fuzzyResults, config);
+ return freshSort(fuzzyResults, config, isChannelItem, getTimestamp);
};
}
@@ -283,12 +272,11 @@ export function createFreshSearch<T extends TimestampedItem>(
* @param boost - The boost multiplier to apply (default: 0.5 for +50% boost)
* @param getEmail - Function to extract email from item (default: assumes item.data.email)
*/
-export function createSameDomainBoostFn<T extends TimestampedItem>(
+export function createSameDomainBoostFn<T>(
currentUserDomain: Accessor<string | undefined>,
boost: number = 0.5,
- getEmail: (item: T) => string | undefined = (item) =>
- (item as { data?: { email?: string } }).data?.email
-): (item: T) => number {
+ getEmail: EmailFn<T>
+): BoostFn<T> {
return (item: T) => {
const userDomain = currentUserDomain();
if (!userDomain) return 0;
@@ -306,14 +294,13 @@ export const FreshSearchPresets = {
* Base user search - balances fuzzy matching with recency, includes same-domain boost.
* Good for recipient selectors, user pickers, and @mention menus.
*/
- baseUserSearch: <T extends TimestampedItem>(
+ baseUserSearch: <T>(
currentUserDomain: Accessor<string | undefined>,
- getEmail: (item: T) => string | undefined = (item) =>
- (item as { data?: { email?: string } }).data?.email
- ): Omit<FreshSortConfig, 'boostFn'> & { boostFn: (item: T) => number } => ({
+ getEmail: EmailFn<T>
+ ): FreshSortConfig<T> => ({
fuzzyWeight: 0.5,
timeWeight: 0.4,
brevityWeight: 0.1,
- boostFn: createSameDomainBoostFn(currentUserDomain, 0.5, getEmail),
+ boostFn: createSameDomainBoostFn<T>(currentUserDomain, 0.5, getEmail),
}),
} as const;