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.

4.4 KB
Raw Blame
import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { toast } from '@core/component/Toast/Toast';
import { useUserId } from '@core/context/user';
import { invalidateContacts } from '@core/user/contactService';
import { fireAndForget } from '@core/util/fireAndForget';
import { invalidateListChannels } from '@queries/channel/channels';
import {
  useGetOrCreateDirectMessageMutation,
  useGetOrCreatePrivateChannelMutation,
} from '@queries/channel/get-or-create-dm';
import {
  newMessageId,
  useSendMessageMutation,
} from '@queries/messages/mutations';
import type { NewAttachment } from '@service-storage/generated/schemas/newAttachment';
import type { SimpleMention } from '@service-storage/generated/schemas/simpleMention';
import { createCallback } from '@solid-primitives/rootless';

type SendContent = {
  content: string;
  mentions: SimpleMention[];
  attachments?: NewAttachment[];
  /** An entity owner may need to authorize the resolved DM/channel before sending. */
  beforeSend?: (channelId: string) => Promise<void>;
};

type NavigationOptions = {
  navigate: boolean;
  mergeHistory?: boolean;
};

type SendToUsersArgs = SendContent & {
  users: string[];
  navigate?: NavigationOptions;
};

type SendToChannelArgs = SendContent & {
  channelId: string;
  navigate?: NavigationOptions;
};

export function useSendMessageToPeople() {
  const { replaceSplit } = useSplitLayout();
  const orchestrator = useGlobalBlockOrchestrator();
  const getOrCreateDmMutation = useGetOrCreateDirectMessageMutation();
  const getOrCreatePrivateChannelMutation =
    useGetOrCreatePrivateChannelMutation();
  const userId = useUserId();
  const sendMessage = useSendMessageMutation();

  async function sendAndNavigateToChannel(
    channelId: string,
    content: string,
    mentions: SimpleMention[],
    attachments: NewAttachment[],
    navigate?: NavigationOptions,
    beforeSend?: (channelId: string) => Promise<void>
  ) {
    const senderId = userId();
    if (!senderId) return;
    await beforeSend?.(channelId);
    const messageResponse = await sendMessage
      .mutateAsync({
        parent: { type: 'channel', id: channelId },
        message: { content, attachments, mentions },
        senderId,
        optimisticId: newMessageId(),
      })
      .catch(() => null);
    if (!messageResponse) return;

    fireAndForget(invalidateListChannels(), 'messages');
    fireAndForget(invalidateContacts(), 'messages');

    const navigateToChannel = async () => {
      replaceSplit({
        content: {
          type: 'channel',
          id: channelId,
        },
        mergeHistory: navigate?.mergeHistory,
      });
      const handle = await orchestrator.getBlockHandle(channelId);
      await handle?.goToLocationFromParams({
        [CHANNEL_PARAMS.message]: messageResponse.id,
      });
    };

    if (navigate?.navigate) {
      await navigateToChannel();
    }

    return { channelId, messageResponse, navigateToChannel };
  }

  async function sendToUsers(args: SendToUsersArgs) {
    let channelId: string;
    try {
      const result =
        args.users.length === 1
          ? await getOrCreateDmMutation.mutateAsync({
              recipient_id: args.users[0],
            })
          : await getOrCreatePrivateChannelMutation.mutateAsync({
              recipients: args.users,
            });
      channelId = result.channel_id;
    } catch (err) {
      toast.failure('Failed to send message to people');
      console.error('failed to create new channel to forward', err);
      return;
    }

    return sendAndNavigateToChannel(
      channelId,
      args.content,
      args.mentions,
      args.attachments ?? [],
      args.navigate,
      args.beforeSend
    );
  }

  async function sendToChannel(args: SendToChannelArgs) {
    return sendAndNavigateToChannel(
      args.channelId,
      args.content,
      args.mentions,
      args.attachments ?? [],
      args.navigate,
      args.beforeSend
    );
  }

  return {
    /** Sends a message to a list of users,
     * if the users already have an existing channel,
     * it will send the message to that channel
     * otherwise, it will create a new channel and send the message to that channel */
    sendToUsers: createCallback(sendToUsers),
    /** sends a message to an existing channel */
    sendToChannel: createCallback(sendToChannel),
  };
}