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(channel): Fix reactive updates to channel query data when renaming (#618)

dev-rb25dcc4c54b72
diff --git a/js/app/packages/app/component/EntityModal/RenameView.tsx b/js/app/packages/app/component/EntityModal/RenameView.tsx
index b2a6682f70..0fe3fce47c 100644
--- a/js/app/packages/app/component/EntityModal/RenameView.tsx
+++ b/js/app/packages/app/component/EntityModal/RenameView.tsx
@@ -2,6 +2,10 @@ import { useUpsertSavedViewMutation } from '@app/component/Soup';
import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
import type { ViewConfigBase } from '@app/component/ViewConfig';
import { unwrapSignals } from '@core/util/unwrapSignals';
+import { optimisticUpdateChannelName } from '@queries/channel/channel';
+import { channelKeys } from '@queries/channel/keys';
+import { queryClient } from '@queries/client';
+import type { GetChannelResponse } from '@service-comms/generated/models';
import { createMemo, createSignal, onMount } from 'solid-js';
import { createRenameDssEntityMutation } from '../../../macro-entity/src/queries/dss';
import type { EntityData } from '../../../macro-entity/src/types/entity';
@@ -13,7 +17,35 @@ export const RenameView = (props: {
onFinish: () => void;
onCancel: () => void;
}) => {
- const renameMutation = createRenameDssEntityMutation();
+ const renameMutation = createRenameDssEntityMutation({
+ onMutate(variables) {
+ if (variables.entity.type !== 'channel') return;
+
+ const queryKey = channelKeys.withID(variables.entity.id).queryKey;
+
+ const previousData: GetChannelResponse | undefined =
+ queryClient.getQueryData(queryKey);
+
+ optimisticUpdateChannelName(variables.entity.id, variables.newName);
+ return { previousData };
+ },
+ onError(
+ _,
+ variables,
+ onMutateResult: { previousData: GetChannelResponse | undefined }
+ ) {
+ const queryKey = channelKeys.withID(variables.entity.id).queryKey;
+ queryClient.setQueriesData(
+ { queryKey },
+ () => onMutateResult.previousData
+ );
+ },
+ onSettled(_, __, variables) {
+ queryClient.invalidateQueries({
+ queryKey: channelKeys.withID(variables.entity.id).queryKey,
+ });
+ },
+ });
let inputRef: HTMLInputElement | undefined;
const saveViewMutation = useUpsertSavedViewMutation();
const {
diff --git a/js/app/packages/block-channel/component/Block.tsx b/js/app/packages/block-channel/component/Block.tsx
index 23b22c0f48..c30e0d95fb 100644
--- a/js/app/packages/block-channel/component/Block.tsx
+++ b/js/app/packages/block-channel/component/Block.tsx
@@ -1,21 +1,15 @@
-import type { ChannelData } from '@block-channel/definition';
import {
doesChannelRequireJoin,
+ initializeChannelData,
isValidChannelData,
} from '@block-channel/signal/channel';
-import { channelBlockDataSignal } from '@block-channel/signal/channelBlockData';
+import { useBlockId } from '@core/block';
import { useChannelName } from '@core/component/ChannelsProvider';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
+import { useChannelQuery } from '@queries/channel/channel';
import { commsServiceClient } from '@service-comms/client';
import { useUserId } from '@service-gql/client';
-import {
- createEffect,
- createMemo,
- createSignal,
- type JSXElement,
- Match,
- Switch,
-} from 'solid-js';
+import { createSignal, type JSXElement, Match, Switch } from 'solid-js';
import { Channel } from './Channel';
import { JoinChannelDialog } from './JoinChannelDialog';
@@ -26,27 +20,28 @@ export function WithTopBar(props: { children: JSXElement }) {
export type JoinState = 'REQUIRED' | 'NOT_REQUIRED';
export default function BlockChannel() {
- const blockData = channelBlockDataSignal.get;
+ const channelId = useBlockId();
+
+ const channel = useChannelQuery(() => channelId);
const userId = useUserId();
const [error] = createSignal<string>();
const [joinState, setJoinState] = createSignal<JoinState>();
- const [validChannelData, setValidChannelData] =
- createSignal<Required<ChannelData>>();
- createEffect(() => {
- const blockData_ = blockData();
+ const validChannelData = () => {
+ const blockData_ = channel.data;
const userId_ = userId();
if (!userId_) return;
if (!blockData_) return;
if (!isValidChannelData(blockData_)) return;
+ initializeChannelData(blockData_);
setJoinState(
doesChannelRequireJoin(blockData_, userId_) ? 'REQUIRED' : 'NOT_REQUIRED'
);
- setValidChannelData(blockData_);
- });
+ return blockData_;
+ };
function handleJoinChannel(
channelId: string,
@@ -74,14 +69,14 @@ export default function BlockChannel() {
return undefined;
};
- const channelName = createMemo(() => {
- const data = blockData();
+ const channelName = () => {
+ const data = channel.data;
if (!data) return undefined;
const id = data.channel.id;
const name = data.channel.name;
const maybeChannelName = useChannelName(id, name as string);
return maybeChannelName();
- });
+ };
return (
<DocumentBlockContainer title={channelName() ?? 'Channel'}>
diff --git a/js/app/packages/block-channel/component/Channel.tsx b/js/app/packages/block-channel/component/Channel.tsx
index b511aabc0d..d22126b2a8 100644
--- a/js/app/packages/block-channel/component/Channel.tsx
+++ b/js/app/packages/block-channel/component/Channel.tsx
@@ -11,11 +11,7 @@ import {
isDraggingOverChannelSignal,
isValidChannelDragSignal,
} from '@block-channel/signal/attachment';
-import {
- channelStore,
- initializeChannelData,
- refetchChannelData,
-} from '@block-channel/signal/channel';
+import { refetchChannelData } from '@block-channel/signal/channel';
import { activeThreadIdSignal } from '@block-channel/signal/threads';
import { handleFileUpload } from '@block-channel/utils/inputAttachments';
import { withAnalytics } from '@coparse/analytics';
@@ -35,6 +31,7 @@ import { createTabFocusEffect } from '@core/signal/tabFocus';
import type { InputAttachment } from '@core/store/cacheChannelInput';
import { handleFileFolderDrop } from '@core/util/upload';
import { ChannelDebouncedNotificationReadMarker } from '@notifications';
+import { useChannelQuery } from '@queries/channel/channel';
import type { Message } from '@service-comms/generated/models';
import { connectionGatewayClient } from '@service-connection/client';
import { createCallback } from '@solid-primitives/rootless';
@@ -50,6 +47,7 @@ import {
on,
onCleanup,
onMount,
+ Suspense,
} from 'solid-js';
import { createStore } from 'solid-js/store';
import { type FocusableElement, tabbable } from 'tabbable';
@@ -81,7 +79,8 @@ export function createChannelRefetchEffect(channelId: string) {
}
export function Channel(props: { data: Required<ChannelData> }) {
- const channel = channelStore.get; // this is our source of truth because data can be updated outside
+ const channel = useChannelQuery(() => props.data.channel.id);
+
const [_activeThreadId, setActiveThreadId] = activeThreadIdSignal;
const latestActivity = latestActivitySignal.get;
const updateActivityOnOpen = createCallback(updateActivityOnChannelOpen);
@@ -143,7 +142,6 @@ export function Channel(props: { data: Required<ChannelData> }) {
>(undefined);
onMount(() => {
- initializeChannelData(props.data);
updateActivityOnOpen();
track(TrackingEvents.BLOCKCHANNEL.CHANNEL.OPEN);
@@ -322,7 +320,9 @@ export function Channel(props: { data: Required<ChannelData> }) {
channelId={channelId}
/>
<StaticMarkdownContext>
- <Top />
+ <Suspense>
+ <Top channelID={channelId} />
+ </Suspense>
<div
class="h-full flex flex-col min-h-0 flex-1 relative w-full"
use:fileFolderDrop={{
@@ -351,7 +351,7 @@ export function Channel(props: { data: Required<ChannelData> }) {
/>
<MessageList
channelId={channelId}
- messages={channel.messages}
+ messages={channel.data?.messages ?? []}
focusedMessageId={focusedMessageId}
setFocusedMessageId={setFocusedMessageId}
targetMessage={targetMessage}
@@ -364,7 +364,7 @@ export function Channel(props: { data: Required<ChannelData> }) {
{/* seamus: note this element is below the scroll so we translate it back to account for the scroll above */}
<div class="mx-auto -translate-x-1 w-full macro-message-width">
<ChannelInput
- channelName={channel?.channel?.name ?? ''}
+ channelName={channel.data?.channel?.name ?? ''}
inputAttachmentsStore={channelInputAttachmentsStore}
setInputAttachmentsStore={setChannelInputAttachmentsStore}
inputAttachmentsKey={channelId}
diff --git a/js/app/packages/block-channel/component/Top.tsx b/js/app/packages/block-channel/component/Top.tsx
index ec5a69a3a9..6a138fe88f 100644
--- a/js/app/packages/block-channel/component/Top.tsx
+++ b/js/app/packages/block-channel/component/Top.tsx
@@ -5,7 +5,6 @@ import {
} from '@app/component/split-layout/components/SplitHeader';
import { SplitLabel } from '@app/component/split-layout/components/SplitLabel';
import { SplitToolbarRight } from '@app/component/split-layout/components/SplitToolbar';
-import { channelStore } from '@block-channel/signal/channel';
import { useBlockId } from '@core/block';
import { useChannelName } from '@core/component/ChannelsProvider';
import { IconButton } from '@core/component/IconButton';
@@ -16,6 +15,7 @@ import { UserIcon } from '@core/component/UserIcon';
import { buildSimpleEntityUrl } from '@core/util/url';
import HashIcon from '@icon/regular/hash.svg';
import LinkIcon from '@icon/regular/link.svg';
+import { useChannelQuery } from '@queries/channel/channel';
import type { ChannelParticipant } from '@service-comms/generated/models/channelParticipant';
import type { ChannelType } from '@service-comms/generated/models/channelType';
import { useUserId } from '@service-gql/client';
@@ -48,11 +48,12 @@ function TopIcon(props: TopIconProps) {
);
}
-export function Top() {
- const channel = channelStore.get;
- const channelType = () => channel?.channel?.channel_type ?? 'private';
- const participantCount = () => channel?.participants.length ?? 0;
- const participants = () => channel?.participants ?? [];
+export function Top(props: { channelID: string }) {
+ const channel = useChannelQuery(() => props.channelID);
+
+ const channelType = () => channel.data?.channel?.channel_type ?? 'private';
+ const participantCount = () => channel.data?.participants.length ?? 0;
+ const participants = () => channel.data?.participants ?? [];
const blockId = useBlockId();
const notificationSource = useGlobalNotificationSource();
@@ -68,11 +69,15 @@ export function Top() {
);
toast.success('Link copied to clipboard');
}
- const channelName = useChannelName(
+ const _channelName = useChannelName(
blockId,
- channel?.channel?.name ?? 'New Channel'
+ channel.data?.channel?.name ?? 'New Channel'
);
+ const channelName = () => {
+ return channel.data?.channel?.name ?? _channelName() ?? 'New Channel';
+ };
+
return (
<>
<SplitHeaderLeft>
@@ -83,8 +88,8 @@ export function Top() {
participants={participants()}
/>
<SplitLabel
- label={channelName() ?? 'New Channel'}
- id={channel.id}
+ label={channelName()}
+ id={channel.data?.channel.id}
itemType="channel"
/>
</div>
diff --git a/js/app/packages/block-channel/definition.ts b/js/app/packages/block-channel/definition.ts
index 93e42210c0..31259637ce 100644
--- a/js/app/packages/block-channel/definition.ts
+++ b/js/app/packages/block-channel/definition.ts
@@ -1,6 +1,6 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
import { isErr, ok } from '@core/util/maybeResult';
-import { commsServiceClient } from '@service-comms/client';
+import { fetchAndCacheChannel } from '@queries/channel/channel';
import ChannelBlock from './component/Block';
export const definition = defineBlock({
@@ -10,9 +10,7 @@ export const definition = defineBlock({
liveTrackingEnabled: true,
async load(source, _intent) {
if (source.type === 'dss') {
- let channel = await commsServiceClient.getChannel({
- channel_id: source.id,
- });
+ const channel = await fetchAndCacheChannel(source.id);
if (isErr(channel)) {
if (isErr(channel, 'MISSING')) {
@@ -29,7 +27,7 @@ export const definition = defineBlock({
const [, channelData] = channel;
return ok({
- ...channelData,
+ ...channelData.channel,
});
}
diff --git a/js/app/packages/macro-entity/src/queries/client.ts b/js/app/packages/macro-entity/src/queries/client.ts
index b2cb70da7b..b8dea596b5 100644
--- a/js/app/packages/macro-entity/src/queries/client.ts
+++ b/js/app/packages/macro-entity/src/queries/client.ts
@@ -1,12 +1,6 @@
-import { QueryClient } from '@tanstack/solid-query';
+import { queryClient as _queryClient } from '@queries/client';
-export const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- experimental_prefetchInRender: true,
- },
- },
-});
+export const queryClient = _queryClient;
export function useQueryClient() {
return queryClient;
diff --git a/js/app/packages/queries/channel/channel.ts b/js/app/packages/queries/channel/channel.ts
new file mode 100644
index 0000000000..d135d71998
--- /dev/null
+++ b/js/app/packages/queries/channel/channel.ts
@@ -0,0 +1,107 @@
+import {
+ catchToResult,
+ isErr,
+ type MaybeResult,
+ ok,
+ throwOnErr,
+} from '@core/util/maybeResult';
+import { commsServiceClient } from '@service-comms/client';
+import type { getChannelResponseError } from '@service-comms/generated/client';
+import type { GetChannelResponse } from '@service-comms/generated/models';
+import {
+ type QueryClient,
+ type UseBaseQueryOptions,
+ useQuery,
+} from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { queryClient } from '../client';
+import { channelKeys } from './keys';
+
+type ChannelQueryOptions = UseBaseQueryOptions<
+ GetChannelResponse,
+ getChannelResponseError
+>;
+
+/**
+ * Shared query options for getting a channel with an ID
+ */
+function channelQueryOptions(channelId: string): ChannelQueryOptions {
+ return {
+ queryKey: channelKeys.withID(channelId).queryKey,
+ queryFn: async () => {
+ const result = await throwOnErr(
+ async () =>
+ await commsServiceClient.getChannel({
+ channel_id: channelId,
+ })
+ );
+ console.log('fetch', result);
+
+ return result;
+ },
+ };
+}
+
+/**
+ * Imperatively fetch a channel (for use outside of components).
+ * Returns cached data if fresh, otherwise fetches from server.
+ * Ensures the query data will be available for the next time the query is
+ * accessed if it's before the stale time period.
+ */
+export async function fetchAndCacheChannel(
+ channelId: string
+): Promise<MaybeResult<string, { channel: GetChannelResponse }>> {
+ const result = await catchToResult(
+ async () =>
+ await queryClient.ensureQueryData(channelQueryOptions(channelId))
+ );
+
+ if (isErr(result)) {
+ return result;
+ }
+
+ return ok({ channel: result[1] });
+}
+
+/**
+ * Query hook for fetching a channel
+ */
+export function useChannelQuery(
+ channelId: Accessor<string>,
+ options?: Accessor<Omit<ChannelQueryOptions, 'queryKey' | 'queryFn'>>,
+ queryClient?: Accessor<QueryClient>
+) {
+ return useQuery(() => {
+ return {
+ initialData: undefined,
+ ...options?.(),
+ ...channelQueryOptions(channelId()),
+ };
+ }, queryClient);
+}
+
+export function optimisticUpdateChannelName(
+ channelID: string,
+ newName: string
+) {
+ const queryKey = channelKeys.withID(channelID).queryKey;
+ queryClient.cancelQueries({ queryKey });
+
+ queryClient.setQueriesData(
+ { queryKey },
+ (prev: GetChannelResponse | undefined) => {
+ if (!prev) return;
+
+ const next = {
+ ...prev,
+ channel: {
+ ...prev.channel,
+ name: newName,
+ updatedAt: new Date().toISOString(),
+ },
+ };
+
+ return { ...next };
+ }
+ );
+}
diff --git a/js/app/packages/queries/channel/keys.ts b/js/app/packages/queries/channel/keys.ts
new file mode 100644
index 0000000000..01569ce1d8
--- /dev/null
+++ b/js/app/packages/queries/channel/keys.ts
@@ -0,0 +1,7 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const channelKeys = createQueryKeys('channel', {
+ withID: (channelID: string) => ({
+ queryKey: [channelID],
+ }),
+});
diff --git a/js/app/packages/queries/utils.ts b/js/app/packages/queries/utils.ts
index e29acc3ecc..f9815a0071 100644
--- a/js/app/packages/queries/utils.ts
+++ b/js/app/packages/queries/utils.ts
@@ -1,3 +1,5 @@
+import type { MutationOptions } from '@tanstack/solid-query';
+
/**
* Standard mutation callback types matching TanStack Query's mutation options.
* Use this to ensure consistent callback signatures across mutations.
@@ -7,25 +9,10 @@ export type MutationCallbacks<
TError = Error,
TVariables = void,
TContext = unknown,
-> = {
- onMutate?: (variables: TVariables) => Promise<TContext> | TContext;
- onSuccess?: (
- data: TData,
- variables: TVariables,
- context: TContext
- ) => void | Promise<unknown>;
- onError?: (
- error: TError,
- variables: TVariables,
- context: TContext | undefined
- ) => void | Promise<unknown>;
- onSettled?: (
- data: TData | undefined,
- error: TError | null,
- variables: TVariables,
- context: TContext | undefined
- ) => void | Promise<unknown>;
-};
+> = Pick<
+ MutationOptions<TData, TError, TVariables, TContext>,
+ 'onMutate' | 'onError' | 'onSuccess' | 'onSettled'
+>;
/**
* Helper to merge user-provided callbacks with default mutation behavior.
@@ -46,22 +33,22 @@ export function withCallbacks<
if (!overrides) return defaults;
return {
- onMutate: async (variables) => {
- const defaultContext = await defaults.onMutate?.(variables);
- const overrideContext = await overrides.onMutate?.(variables);
+ onMutate: async (...args) => {
+ const defaultContext = await defaults.onMutate?.(...args);
+ const overrideContext = await overrides.onMutate?.(...args);
return (overrideContext ?? defaultContext) as TContext;
},
- onSuccess: async (data, variables, context) => {
- await defaults.onSuccess?.(data, variables, context);
- await overrides.onSuccess?.(data, variables, context);
+ onSuccess: async (...args) => {
+ await defaults.onSuccess?.(...args);
+ await overrides.onSuccess?.(...args);
},
- onError: async (error, variables, context) => {
- await defaults.onError?.(error, variables, context);
- await overrides.onError?.(error, variables, context);
+ onError: async (...args) => {
+ await defaults.onError?.(...args);
+ await overrides.onError?.(...args);
},
- onSettled: async (data, error, variables, context) => {
- await defaults.onSettled?.(data, error, variables, context);
- await overrides.onSettled?.(data, error, variables, context);
+ onSettled: async (...args) => {
+ await defaults.onSettled?.(...args);
+ await overrides.onSettled?.(...args);
},
};
}