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.

feat(channels/core):refactor channels context (#998)

teoa7794ba8e6db
diff --git a/js/app/bun.lock b/js/app/bun.lock
index 24a03998b6..d4bdc26ed5 100644
--- a/js/app/bun.lock
+++ b/js/app/bun.lock
@@ -39,6 +39,7 @@
"@panzoom/panzoom": "^4.6.0",
"@phosphor-icons/core": "^2.1.1",
"@solid-primitives/audio": "^1.4.2",
+ "@solid-primitives/context": "^0.3.2",
"@solid-primitives/deep": "^0.3.3",
"@solid-primitives/event-bus": "^1.1.2",
"@solid-primitives/event-listener": "^2.4.3",
@@ -1024,6 +1025,8 @@
"@solid-primitives/bounds": ["@solid-primitives/[email protected]", "", { "dependencies": { "@solid-primitives/event-listener": "^2.4.1", "@solid-primitives/resize-observer": "^2.1.1", "@solid-primitives/static-store": "^0.1.1", "@solid-primitives/utils": "^6.3.1" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-b4s8JClkRq2RQlU3K4qeCVASdtct5gfg3HNfWGeD7oPjWlSkp2RyDHJwt9ZtPaXOEOIHhNBbLgjtLax/4B6VUQ=="],
+ "@solid-primitives/context": ["@solid-primitives/[email protected]", "", { "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-6fvTtpK17PFHnUf/UOc1TzBjd+kLFjtA62aRFEm1kDP9ufTo7FYW2kUzQAWbfbRHi30yjBJtopbR8qd6nShwyg=="],
+
"@solid-primitives/deep": ["@solid-primitives/[email protected]", "", { "dependencies": { "@solid-primitives/memo": "^1.4.3" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-YnCV2OFbBlNYlww0lSD7oDpk9zN20KQWr699s6euwd6+oRE1nbI+vqrfYuqC7E0WPDfk0DIG+ylY1xvY31ZlTg=="],
"@solid-primitives/event-bus": ["@solid-primitives/[email protected]", "", { "dependencies": { "@solid-primitives/utils": "^6.3.2" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-l+n10/51neGcMaP3ypYt21bXfoeWh8IaC8k7fYuY3ww2a8S1Zv2N2a7FF5Qn+waTu86l0V8/nRHjkyqVIZBYwA=="],
diff --git a/js/app/package.json b/js/app/package.json
index c46a749144..6bf8c6b310 100644
--- a/js/app/package.json
+++ b/js/app/package.json
@@ -54,6 +54,7 @@
"@panzoom/panzoom": "^4.6.0",
"@phosphor-icons/core": "^2.1.1",
"@solid-primitives/audio": "^1.4.2",
+ "@solid-primitives/context": "^0.3.2",
"@solid-primitives/deep": "^0.3.3",
"@solid-primitives/event-bus": "^1.1.2",
"@solid-primitives/event-listener": "^2.4.3",
diff --git a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
index cbc0434e17..42ba8311d0 100644
--- a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
+++ b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
@@ -1,4 +1,4 @@
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import {
type CombinedEntity,
ENTITY_SEARCH_CONFIG,
@@ -87,7 +87,7 @@ export const FilterValueEntity: Component<FilterValueEntityProps> = (props) => {
// Data sources (same pattern as PropertyEntitySelector)
const contacts = useContacts();
const channelsContext = useChannelsContext();
- const channels = () => channelsContext.channels();
+ const channels = channelsContext.channels;
const history = useHistory();
// Email queries for THREAD type or generic ENTITY (no specific type)
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index 2738a32498..266993681e 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -3,7 +3,7 @@ import { setHotkeyRoot, useSubscribeToKeypress } from '@app/signal/hotkeyRoot';
import { globalSplitManager } from '@app/signal/splitLayout';
import { withAnalytics } from '@coparse/analytics';
import { useIsAuthenticated } from '@core/auth';
-import { ChannelsContextProvider } from '@core/component/ChannelsProvider';
+import { ChannelsContextProvider } from '@core/context/channels';
import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
import { toast } from '@core/component/Toast/Toast';
import { ToastRegion } from '@core/component/Toast/ToastRegion';
diff --git a/js/app/packages/app/component/SoupContext.tsx b/js/app/packages/app/component/SoupContext.tsx
index da76af19fb..4582ae4cde 100644
--- a/js/app/packages/app/component/SoupContext.tsx
+++ b/js/app/packages/app/component/SoupContext.tsx
@@ -1,5 +1,5 @@
import { globalSplitManager } from '@app/signal/splitLayout';
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import { toast } from '@core/component/Toast/Toast';
import { HotkeyTags } from '@core/hotkey/constants';
import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';
diff --git a/js/app/packages/app/component/command/Konsole.tsx b/js/app/packages/app/component/command/Konsole.tsx
index c1976cc464..484389b941 100644
--- a/js/app/packages/app/component/command/Konsole.tsx
+++ b/js/app/packages/app/component/command/Konsole.tsx
@@ -1,4 +1,4 @@
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import { ClippedPanel } from '@core/component/ClippedPanel';
import { DialogWrapper } from '@core/component/DialogWrapper';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
@@ -22,11 +22,11 @@ import { VList } from 'virtua/solid';
import { beveledCorners } from '../../../block-theme/signals/themeSignals';
import { KonsoleFilter } from './KonsoleFilter';
import {
+ type ChannelLookup,
COMMAND_ITEM_HEIGHT,
COMMAND_ITEM_MARGIN,
COMMAND_ITEM_PADDING,
CommandItemCard,
- createChannelLookup,
filterItemByCategory,
hydrateChannel,
setCommandCategoryIndex,
@@ -161,7 +161,7 @@ export function KommandMenuInner(props: {
});
const paginatedSearch = usePaginatedSearchItems(fullTextQueryOrBlank);
- const channelLookup = createChannelLookup(channelsContext);
+ const channelLookup = () => channelsContext!.channelsById() as ChannelLookup;
const handleLoadMore = async () => {
const loadMoreIndex = filteredItems().length - 1; // Position of "Load More" button
diff --git a/js/app/packages/app/component/command/KonsoleItem.tsx b/js/app/packages/app/component/command/KonsoleItem.tsx
index 6cab21c028..0ff8722595 100644
--- a/js/app/packages/app/component/command/KonsoleItem.tsx
+++ b/js/app/packages/app/component/command/KonsoleItem.tsx
@@ -3,7 +3,6 @@ import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';
import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';
import type { BlockAlias, BlockName } from '@core/block';
import { BozzyBracket } from '@core/component/BozzyBracket';
-import type { ChannelsContext } from '@core/component/ChannelsProvider';
import { Hotkey } from '@core/component/Hotkey';
import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { Message } from '@core/component/Message';
@@ -70,18 +69,6 @@ export const [commandCategoryIndex, setCommandCategoryIndex] = createSignal(0);
export type ChannelLookup = Record<string, Channel>;
-export function createChannelLookup(channelsContext: ChannelsContext) {
- return createMemo(() => {
- const lookup: ChannelLookup = {};
- const channels = channelsContext.channels();
-
- for (const channel of channels) {
- lookup[channel.id] = channel;
- }
- return lookup;
- });
-}
-
// Context information for actions and stuff
export const [konsoleContextInformation, setKonsoleContextInformation] =
createSignal<Record<string, unknown>>({});
diff --git a/js/app/packages/app/component/command/useCommandItems.ts b/js/app/packages/app/component/command/useCommandItems.ts
index 8562ce81cf..9cc013d683 100644
--- a/js/app/packages/app/component/command/useCommandItems.ts
+++ b/js/app/packages/app/component/command/useCommandItems.ts
@@ -1,4 +1,4 @@
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import { getActiveCommandsFromScope } from '@core/hotkey/getCommands';
import { activeScope } from '@core/hotkey/state';
import { mapFromListsByKey } from '@core/util/compareUtils';
@@ -30,7 +30,7 @@ function channelsIntoCategories(channels: Channel[]) {
export function useCommandItems() {
const historyQuery = useHistoryQuery();
const channelsContext = useChannelsContext();
- const channels = () => channelsContext.channels();
+ const channels = channelsContext.channels;
const activeCommands = getActiveCommandsFromScope(activeScope(), {
sortByScopeLevel: false,
hideShadowedCommands: false,
diff --git a/js/app/packages/app/component/dock/QuickAccess.tsx b/js/app/packages/app/component/dock/QuickAccess.tsx
index 4ae0ae2ffc..e3f57f40b8 100644
--- a/js/app/packages/app/component/dock/QuickAccess.tsx
+++ b/js/app/packages/app/component/dock/QuickAccess.tsx
@@ -4,7 +4,7 @@ import {
} from '@app/component/GlobalAppState';
import { useSplitLayout } from '@app/component/split-layout/layout';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import { Tooltip } from '@core/component/Tooltip';
import { UserIcon } from '@core/component/UserIcon';
import {
@@ -187,11 +187,10 @@ function QuickAccessItem(props: QuickAccessItemProps) {
export function QuickAccess() {
const channelsContext = useChannelsContext();
- const channels = channelsContext.channels;
const notificationSource = useGlobalNotificationSource();
const allNotifications = notificationSource.notifications;
const channelsWithNotifications = createMemo(() => {
- const channels_ = channels();
+ const channels_ = channelsContext.channels();
const notifications = allNotifications();
return channels_
diff --git a/js/app/packages/block-channel/component/Block.tsx b/js/app/packages/block-channel/component/Block.tsx
index 6afe24129e..51ac453aae 100644
--- a/js/app/packages/block-channel/component/Block.tsx
+++ b/js/app/packages/block-channel/component/Block.tsx
@@ -4,7 +4,7 @@ import {
isValidChannelData,
} from '@block-channel/signal/channel';
import { useBlockId } from '@core/block';
-import { useChannelName } from '@core/component/ChannelsProvider';
+import { useChannelName } from '@core/context/channels';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { useChannelQuery } from '@queries/channel/channel';
import { commsServiceClient } from '@service-comms/client';
diff --git a/js/app/packages/block-channel/component/Top.tsx b/js/app/packages/block-channel/component/Top.tsx
index da50136c6c..07b7eb335c 100644
--- a/js/app/packages/block-channel/component/Top.tsx
+++ b/js/app/packages/block-channel/component/Top.tsx
@@ -6,7 +6,7 @@ import {
import { SplitLabel } from '@app/component/split-layout/components/SplitLabel';
import { SplitToolbarRight } from '@app/component/split-layout/components/SplitToolbar';
import { useBlockId } from '@core/block';
-import { useChannelName } from '@core/component/ChannelsProvider';
+import { useChannelName } from '@core/context/channels';
import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import { BlockLiveIndicators } from '@core/component/LiveIndicators';
import { NotificationsModal } from '@core/component/NotificationsModal';
diff --git a/js/app/packages/block-channel/signal/activity.ts b/js/app/packages/block-channel/signal/activity.ts
index db3e75e38a..5ced77a8eb 100644
--- a/js/app/packages/block-channel/signal/activity.ts
+++ b/js/app/packages/block-channel/signal/activity.ts
@@ -1,8 +1,6 @@
import { createBlockSignal } from '@core/block';
-import {
- useChannelsContext,
- useLatestActivityForChannel,
-} from '@core/component/ChannelsProvider';
+import { useChannelActivity } from '@core/context/channels';
+import { invalidateChannelsActivity } from '@queries/channel/activity';
import { commsServiceClient } from '@service-comms/client';
import type { Activity as ChannelActivity } from '@service-comms/generated/models/activity';
@@ -16,9 +14,7 @@ export async function updateActivityOnChannelOpen() {
const channelId = channel?.channel?.id;
if (!channelId) return;
- const channelsContext = useChannelsContext();
-
- const latestActivity = useLatestActivityForChannel(channelId);
+ const latestActivity = useChannelActivity(channelId);
const setLatestActivity = latestActivitySignal.set;
const setOpenedChannel = openedChannelSignal.set;
@@ -36,7 +32,7 @@ export async function updateActivityOnChannelOpen() {
channel_id: channelId,
});
- channelsContext.refetchActivity();
+ invalidateChannelsActivity();
}
export async function updateActivityOnChannelClose() {
@@ -53,14 +49,12 @@ export async function updateActivityOnChannelClose() {
export async function updateActivityOnMessageReceived(
incomingChannelId: string
) {
- const channelsContext = useChannelsContext();
const channel = channelStore.get;
const channelId = channel?.channel?.id;
if (!channelId || channelId === incomingChannelId) return;
- channelsContext.refetchActivity();
+ invalidateChannelsActivity();
}
export async function updateActivityOnMessageSend() {
- const channelsContext = useChannelsContext();
- channelsContext.refetchActivity();
+ invalidateChannelsActivity();
}
diff --git a/js/app/packages/block-channel/signal/channel.ts b/js/app/packages/block-channel/signal/channel.ts
index d8048b6864..3b3e3d284a 100644
--- a/js/app/packages/block-channel/signal/channel.ts
+++ b/js/app/packages/block-channel/signal/channel.ts
@@ -2,7 +2,7 @@ import type { ChannelData } from '@block-channel/definition';
import { withAnalytics } from '@coparse/analytics';
import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
import { createBlockMemo, createBlockStore } from '@core/block';
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { invalidateListChannels } from '@queries/channel/channels';
import {
type InputAttachment,
isStaticAttachmentType,
@@ -210,12 +210,11 @@ export type SendMessageArgs = {
export function useSendChannelMessageAction(channelID: Accessor<string>) {
const optimisticSend = createCallback(optimisticChannelMessage);
- const channelsContext = useChannelsContext();
const userId = useUserId();
const mutation = useSendMessageMutation({
onSettled() {
- channelsContext.refetchChannels();
+ invalidateListChannels();
},
onSuccess(_, variables) {
const message = variables.message;
diff --git a/js/app/packages/core/component/AI/signal/attachment.ts b/js/app/packages/core/component/AI/signal/attachment.ts
index 3220b16c8c..813d955f71 100644
--- a/js/app/packages/core/component/AI/signal/attachment.ts
+++ b/js/app/packages/core/component/AI/signal/attachment.ts
@@ -4,11 +4,10 @@ import {
} from '@core/component/AI/constant';
import type { Attachment, Attachments } from '@core/component/AI/types';
import { asFileType } from '@core/component/AI/util';
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import type { ItemMention } from '@core/component/LexicalMarkdown/plugins/mentions';
import { ENABLE_CHAT_CHANNEL_ATTACHMENT } from '@core/constant/featureFlags';
import { getItemBlockName } from '@core/util/getItemBlockName';
-import { useEmails } from '@macro-entity';
import { useHistory } from '@service-storage/history';
import { createMemo, createSignal } from 'solid-js';
@@ -56,7 +55,6 @@ export const useChatAttachableHistory = () => {
export const useGetChatAttachmentInfo = () => {
const history = useChatAttachableHistory();
const { channels } = useChannelsContext();
- const _emails = useEmails();
const getDocumentAttachment = (id: string): Attachment | undefined => {
const item = history().find((item) => item.id === id);
diff --git a/js/app/packages/core/component/AI/signal/tabAttachments.ts b/js/app/packages/core/component/AI/signal/tabAttachments.ts
index a77f7b3de2..5cd2873b8e 100644
--- a/js/app/packages/core/component/AI/signal/tabAttachments.ts
+++ b/js/app/packages/core/component/AI/signal/tabAttachments.ts
@@ -1,6 +1,6 @@
import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';
import type { Attachment } from '@core/component/AI/types';
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import type { ChannelWithParticipants } from '@core/user';
import { isOk } from '@core/util/maybeResult';
import { type EmailEntity, useEmails } from '@macro-entity';
@@ -94,7 +94,7 @@ function convertSplitToAttachment(
export function useTabAttachments(): Accessor<ChatAttachmentWithName[]> {
const history = useHistory();
const channelsContext = useChannelsContext();
- const channels = () => channelsContext.channels();
+ const channels = channelsContext.channels;
const emails = useEmails();
// Get valid active tabs using createMemo
diff --git a/js/app/packages/core/component/ChannelsProvider.tsx b/js/app/packages/core/component/ChannelsProvider.tsx
deleted file mode 100644
index a686dfb8f7..0000000000
--- a/js/app/packages/core/component/ChannelsProvider.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-import { isErr } from '@core/util/maybeResult';
-import { queryKeys } from '@macro-entity';
-import { commsServiceClient } from '@service-comms/client';
-import type {
- ActivityType,
- ApiChannelWithLatest as ChannelWithLatest,
-} from '@service-comms/generated/models';
-import type { Activity as ChannelActivity } from '@service-comms/generated/models/activity';
-import { type UseQueryResult, useQuery } from '@tanstack/solid-query';
-import {
- type Accessor,
- createContext,
- createEffect,
- createMemo,
- createSignal,
- type ParentProps,
- useContext,
-} from 'solid-js';
-
-const ACTIVITY_QUERY_KEY = ['channelActivity'];
-
-export function createChannelActivityQuery() {
- return useQuery(() => ({
- queryKey: ACTIVITY_QUERY_KEY,
- queryFn: async () => {
- const result = await commsServiceClient.getActivity();
-
- if (isErr(result)) {
- throw new Error('Failed to fetch activity', { cause: result[0] });
- }
-
- return result[1] ?? [];
- },
- }));
-}
-
-export function createChannelsQuery() {
- return useQuery(() => ({
- queryKey: queryKeys.all.channel,
- queryFn: async () => {
- const result = await commsServiceClient.getChannels();
-
- if (isErr(result)) {
- throw new Error('Failed to fetch channels', { cause: result[0] });
- }
-
- return result[1] ?? [];
- },
- }));
-}
-
-export type ChannelsContext = {
- readonly channels: Accessor<ChannelWithLatest[]>;
- readonly activity: Accessor<ChannelActivity[]>;
- readonly isLoading: Accessor<boolean>;
-
- readonly _channelsQuery: UseQueryResult<ChannelWithLatest[], Error>;
- readonly _activityQuery: UseQueryResult<ChannelActivity[], Error>;
-
- /** Post a new activity for a channel */
- updateActivityForChannel(
- channelId: string,
- activityType: ActivityType
- ): Promise<void>;
-
- // NOTE: Ideally nothing should require a manual refetch
- // Once we hook all the tanstack queries togehter, we can remove these refetch calls
-
- refetchChannels(): Promise<void>;
- refetchActivity(): Promise<void>;
-};
-
-function createChannelsContext(
- channelsQuery: UseQueryResult<ChannelWithLatest[], Error>,
- activityQuery: UseQueryResult<ChannelActivity[], Error>
-): ChannelsContext {
- const [channels, setChannels] = createSignal<ChannelWithLatest[]>([]);
- const [activity, setActivity] = createSignal<ChannelActivity[]>([]);
-
- createEffect(() => {
- if (!channelsQuery.isSuccess) return;
- setChannels(channelsQuery.data ?? []);
- });
-
- createEffect(() => {
- if (!activityQuery.isSuccess) return;
- setActivity(activityQuery.data ?? []);
- });
-
- const updateActivityForChannel = async (
- channelId: string,
- activityType: ActivityType
- ) => {
- await commsServiceClient.postActivity({
- activity_type: activityType,
- channel_id: channelId,
- });
- activityQuery.refetch();
- };
-
- const refetchChannels = async () => {
- await channelsQuery.refetch();
- };
-
- const refetchActivity = async () => {
- await activityQuery.refetch();
- };
-
- return {
- channels,
- activity,
- isLoading: () => channelsQuery.isLoading || activityQuery.isLoading,
- _channelsQuery: channelsQuery,
- _activityQuery: activityQuery,
- updateActivityForChannel,
- refetchChannels,
- refetchActivity,
- };
-}
-
-const ChannelsContext = createContext<ChannelsContext>();
-
-export function ChannelsContextProvider(
- props: ParentProps & {
- channelsQuery?: ReturnType<typeof createChannelsQuery>;
- activityQuery?: ReturnType<typeof createChannelActivityQuery>;
- }
-) {
- const channelsContext = createChannelsContext(
- props.channelsQuery ?? createChannelsQuery(),
- props.activityQuery ?? createChannelActivityQuery()
- );
-
- return (
- <ChannelsContext.Provider value={channelsContext}>
- {props.children}
- </ChannelsContext.Provider>
- );
-}
-
-const CHANNEL_CONTEXT_ERROR = `ChannelsContext not found. Make sure you are calling it under <ChannelsContextProvider />`;
-
-export function useChannelsContext() {
- const context = useContext(ChannelsContext);
- if (!context) {
- throw new Error(CHANNEL_CONTEXT_ERROR);
- }
- return context;
-}
-
-export function useLatestActivityForChannel(channelId: string) {
- const context = useChannelsContext();
- return createMemo(() =>
- context.activity().find((a) => a.channel_id === channelId)
- );
-}
-
-export function useChannelName(channelId: string, fallback?: string) {
- const context = useChannelsContext();
- return createMemo(() => {
- const channel = context.channels().find((c) => c.id === channelId);
- return channel?.name ?? fallback;
- });
-}
diff --git a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
index ec622932ff..a8fdd9443d 100644
--- a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
@@ -1,6 +1,6 @@
import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';
import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/signal/location';
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import { itemToBlockName } from '@core/constant/allBlocks';
import { isOk } from '@core/util/maybeResult';
import { cognitionApiServiceClient } from '@service-cognition/client';
@@ -57,8 +57,7 @@ const createChatMentionXML = (chatId: string) => {
const createChannelMentionXML = (channelId: string) => {
const channelsContext = useChannelsContext();
- const channels = () => channelsContext.channels();
- const channel = channels().find((c) => c.id === channelId);
+ const channel = channelsContext.channels().find((c) => c.id === channelId);
if (!channel) {
if (import.meta.env.DEV) {
console.error('Could not find channel', channelId);
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 f37dac3ab4..c3752d931b 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
@@ -5,7 +5,7 @@ import {
} from '@core/block';
import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';
import { BozzyBracketInnerSibling } from '@core/component/BozzyBracket';
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import { EntityIcon } from '@core/component/EntityIcon';
import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';
import { UserIcon } from '@core/component/UserIcon';
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 f0b243daca..a7d135ab0b 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,5 +1,5 @@
import { useMaybeBlockId } from '@core/block';
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import { EntityIcon } from '@core/component/EntityIcon';
import { UserIcon } from '@core/component/UserIcon';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
@@ -155,7 +155,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
const history = useHistory();
const contacts = useContacts();
const channelsContext = useChannelsContext();
- const channels = () => channelsContext.channels();
+ const channels = channelsContext.channels;
// Get current user info for injection into contacts
const currentUserId = useUserId();
diff --git a/js/app/packages/core/component/Properties/hooks/usePropertyEntityDisplay.tsx b/js/app/packages/core/component/Properties/hooks/usePropertyEntityDisplay.tsx
index 88896145a7..18dd8d486e 100644
--- a/js/app/packages/core/component/Properties/hooks/usePropertyEntityDisplay.tsx
+++ b/js/app/packages/core/component/Properties/hooks/usePropertyEntityDisplay.tsx
@@ -1,4 +1,4 @@
-import { useChannelName } from '@core/component/ChannelsProvider';
+import { useChannelName } from '@core/context/channels';
import { EntityIcon as CoreEntityIcon } from '@core/component/EntityIcon';
import { UserIcon } from '@core/component/UserIcon';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
diff --git a/js/app/packages/core/context/channels.ts b/js/app/packages/core/context/channels.ts
new file mode 100644
index 0000000000..0105bb11a6
--- /dev/null
+++ b/js/app/packages/core/context/channels.ts
@@ -0,0 +1,70 @@
+import { createMemo, type Accessor } from 'solid-js';
+import type {
+ ApiActivity as ChannelsActivity,
+ ApiChannelWithLatest,
+} from '@service-comms/generated/models';
+import { useListChannelsQuery } from '@queries/channel/channels';
+import { useChannelsActivityQuery } from '@queries/channel/activity';
+import { queryReadyGate } from '@queries/gate';
+import { createAssertedContextProvider } from './createContext';
+
+type ChannelsContextValue = {
+ channels: Accessor<ApiChannelWithLatest[]>;
+ activity: Accessor<ChannelsActivity[]>;
+ channelsById: Accessor<Record<string, ApiChannelWithLatest>>;
+ activityByChannelId: Accessor<Record<string, ChannelsActivity>>;
+ isLoading: Accessor<boolean>;
+ error: Accessor<Error | null>;
+};
+
+export const [ChannelsContextProvider, useChannelsContext] =
+ createAssertedContextProvider('ChannelsContext', (): ChannelsContextValue => {
+ const channelsQuery = useListChannelsQuery();
+ const activityQuery = useChannelsActivityQuery();
+
+ const channels = () =>
+ queryReadyGate(channelsQuery) ? channelsQuery.data : [];
+ const activity = () =>
+ queryReadyGate(activityQuery) ? activityQuery.data : [];
+
+ const channelsById = createMemo(() => {
+ if (!queryReadyGate(channelsQuery)) return {};
+ return channelsQuery.data.reduce<Record<string, ApiChannelWithLatest>>(
+ (acc, ch) => {
+ acc[ch.id] = ch;
+ return acc;
+ },
+ {}
+ );
+ });
+
+ const activityByChannelId = createMemo(() => {
+ if (!queryReadyGate(activityQuery)) return {};
+ return activityQuery.data.reduce<Record<string, ChannelsActivity>>(
+ (acc, a) => {
+ acc[a.channel_id] = a;
+ return acc;
+ },
+ {}
+ );
+ });
+
+ return {
+ channels,
+ activity,
+ channelsById,
+ activityByChannelId,
+ isLoading: () => channelsQuery.isLoading || activityQuery.isLoading,
+ error: () => channelsQuery.error ?? activityQuery.error ?? null,
+ };
+ });
+
+export function useChannelName(channelId: string, fallback?: string) {
+ const ctx = useChannelsContext();
+ return createMemo(() => ctx.channelsById()[channelId]?.name ?? fallback);
+}
+
+export function useChannelActivity(channelId: string) {
+ const ctx = useChannelsContext();
+ return createMemo(() => ctx.activityByChannelId()[channelId]);
+}
diff --git a/js/app/packages/core/context/createContext.ts b/js/app/packages/core/context/createContext.ts
new file mode 100644
index 0000000000..74e4eac4db
--- /dev/null
+++ b/js/app/packages/core/context/createContext.ts
@@ -0,0 +1,30 @@
+import {
+ createContextProvider,
+ type ContextProvider,
+ type ContextProviderProps,
+} from '@solid-primitives/context';
+
+/**
+ * Creates a context provider that throws if used outside of provider tree.
+ * Thin wrapper around solid-primitives createContextProvider.
+ *
+ * @param name - Name of the context (used in error messages)
+ * @param factory - Factory function that creates the context value
+ * @returns Tuple of [Provider, useContext] where useContext throws if undefined
+ */
+export function createAssertedContextProvider<T>(
+ name: string,
+ factory: () => T
+): [provider: ContextProvider<ContextProviderProps>, useContext: () => T] {
+ const [Provider, useContext] = createContextProvider(factory);
+
+ const useAssertedContext = (): T => {
+ const ctx = useContext();
+ if (ctx === undefined) {
+ throw new Error(`${name} must be used within <${name}Provider />`);
+ }
+ return ctx;
+ };
+
+ return [Provider, useAssertedContext];
+}
diff --git a/js/app/packages/core/signal/useCombinedRecipient.ts b/js/app/packages/core/signal/useCombinedRecipient.ts
index c9dbf0b4c7..f061f80c85 100644
--- a/js/app/packages/core/signal/useCombinedRecipient.ts
+++ b/js/app/packages/core/signal/useCombinedRecipient.ts
@@ -1,4 +1,4 @@
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import {
type CombinedRecipientItem,
recipientEntityMapper,
diff --git a/js/app/packages/core/util/channels.ts b/js/app/packages/core/util/channels.ts
index 6341cff145..462378f039 100644
--- a/js/app/packages/core/util/channels.ts
+++ b/js/app/packages/core/util/channels.ts
@@ -2,7 +2,7 @@ import { useGlobalBlockOrchestrator } from '@app/component/GlobalAppState';
import { useSplitLayout } from '@app/component/split-layout/layout';
import { withAnalytics } from '@coparse/analytics';
import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { invalidateListChannels } from '@queries/channel/channels';
import { toast } from '@core/component/Toast/Toast';
import { refetchContacts } from '@core/user/contactService';
import { isErr } from '@core/util/maybeResult';
@@ -36,7 +36,6 @@ export type SendToChannelArgs = SendContent & {
export function useSendMessageToPeople() {
const { track } = withAnalytics();
- const channelsContext = useChannelsContext();
const { replaceSplit } = useSplitLayout();
const orchestrator = useGlobalBlockOrchestrator();
@@ -64,7 +63,7 @@ export function useSendMessageToPeople() {
const messageResponse = message.at(1) as IdResponse;
- channelsContext.refetchChannels();
+ invalidateListChannels();
refetchContacts();
const navigateToChannel = async () => {
diff --git a/js/app/packages/macro-entity/src/queries/search.ts b/js/app/packages/macro-entity/src/queries/search.ts
index eb6f7113b4..384b9b371e 100644
--- a/js/app/packages/macro-entity/src/queries/search.ts
+++ b/js/app/packages/macro-entity/src/queries/search.ts
@@ -1,4 +1,4 @@
-import { useChannelsContext } from '@core/component/ChannelsProvider';
+import { useChannelsContext } from '@core/context/channels';
import { blockNameToDefaultFile } from '@core/constant/allBlocks';
import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';
import { emailToId } from '@core/user';
@@ -162,7 +162,7 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {
const useMapSearchResponseItem = () => {
const channelsContext = useChannelsContext();
- const channels = () => channelsContext.channels();
+ const channels = channelsContext.channels;
const history = useHistory();
diff --git a/js/app/packages/queries/channel/activity.ts b/js/app/packages/queries/channel/activity.ts
new file mode 100644
index 0000000000..c65e383edc
--- /dev/null
+++ b/js/app/packages/queries/channel/activity.ts
@@ -0,0 +1,57 @@
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import { channelKeys } from './keys';
+import { throwOnErr } from '@core/util/maybeResult';
+import { commsServiceClient } from '@service-comms/client';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import type {
+ ActivityType,
+ ApiActivity as ChannelsActivity,
+} from '@service-comms/generated/models';
+import { queryClient } from '@queries/client';
+
+export function useChannelsActivityQuery() {
+ return useQuery(() => ({
+ queryKey: channelKeys.activity.queryKey,
+ queryFn: async () => await throwOnErr(commsServiceClient.getActivity),
+ }));
+}
+
+type UpdateChannelActivityMutationVars = {
+ channelId: string;
+ activityType: ActivityType;
+};
+
+export function useUpdateChannelsActivityMutation(
+ callbacks?: MutationCallbacks<
+ ChannelsActivity,
+ Error,
+ UpdateChannelActivityMutationVars
+ >
+) {
+ return useMutation(() => ({
+ mutationFn: async (vars: UpdateChannelActivityMutationVars) =>
+ await throwOnErr(
+ async () =>
+ await commsServiceClient.postActivity({
+ channel_id: vars.channelId,
+ activity_type: vars.activityType,
+ })
+ ),
+ ...withCallbacks<
+ ChannelsActivity,
+ Error,
+ UpdateChannelActivityMutationVars
+ >(
+ {
+ onError(error) {
+ console.error('failed to update activity for channel', error);
+ },
+ },
+ callbacks
+ ),
+ }));
+}
+
+export function invalidateChannelsActivity() {
+ queryClient.invalidateQueries({ queryKey: channelKeys.activity.queryKey });
+}
diff --git a/js/app/packages/queries/channel/channels.ts b/js/app/packages/queries/channel/channels.ts
new file mode 100644
index 0000000000..cd780cd681
--- /dev/null
+++ b/js/app/packages/queries/channel/channels.ts
@@ -0,0 +1,18 @@
+import { useQuery } from '@tanstack/solid-query';
+import { channelKeys } from './keys';
+import { throwOnErr } from '@core/util/maybeResult';
+import { commsServiceClient } from '@service-comms/client';
+import { queryClient } from '@queries/client';
+
+export function useListChannelsQuery() {
+ return useQuery(() => ({
+ queryKey: channelKeys.listChannels.queryKey,
+ queryFn: async () => await throwOnErr(commsServiceClient.getChannels),
+ }));
+}
+
+export function invalidateListChannels() {
+ return queryClient.invalidateQueries({
+ queryKey: channelKeys.listChannels.queryKey,
+ });
+}
diff --git a/js/app/packages/queries/channel/keys.ts b/js/app/packages/queries/channel/keys.ts
index 01569ce1d8..99bc63fcc5 100644
--- a/js/app/packages/queries/channel/keys.ts
+++ b/js/app/packages/queries/channel/keys.ts
@@ -4,4 +4,6 @@ export const channelKeys = createQueryKeys('channel', {
withID: (channelID: string) => ({
queryKey: [channelID],
}),
+ activity: null,
+ listChannels: null,
});
diff --git a/js/app/packages/queries/gate.ts b/js/app/packages/queries/gate.ts
new file mode 100644
index 0000000000..9b00625ded
--- /dev/null
+++ b/js/app/packages/queries/gate.ts
@@ -0,0 +1,12 @@
+import type {
+ UseQueryResult,
+ UseInfiniteQueryResult,
+} from '@tanstack/solid-query';
+
+export function queryReadyGate<T>(
+ query: UseQueryResult<T> | UseInfiniteQueryResult<T>
+): query is
+ | (UseQueryResult<T, never> & { data: T })
+ | (UseInfiniteQueryResult<T, never> & { data: T }) {
+ return !query.isLoading && query.data !== undefined;
+}
diff --git a/js/app/packages/service-clients/service-comms/client.ts b/js/app/packages/service-clients/service-comms/client.ts
index 4e38bb39bd..d94f77b359 100644
--- a/js/app/packages/service-clients/service-comms/client.ts
+++ b/js/app/packages/service-clients/service-comms/client.ts
@@ -152,7 +152,7 @@ export const commsServiceClient = {
(result) => result
);
},
- async postActivity(args: PostActivityRequest & WithChannelId) {
+ async postActivity(args: PostActivityRequest) {
const { activity_type, channel_id } = args;
return mapOk(
await commsFetch<Activity>(`/activity`, {