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.

13.5 KB
Raw Blame
import { fireAndForget } from '@core/util/fireAndForget';
import type { Accessor } from 'solid-js';
import { createEffect, createMemo, createSignal, on } from 'solid-js';
import { createStore } from 'solid-js/store';
import type { EmailRecipient } from '../../email-compose/core/email-recipient';
import type { ReplyType } from '../../email-compose/core/reply-type';
import type { EmailMessage } from '../../email-message/core/email-message';
import type {
  ArchiveThreadOptions,
  EmailThreadContext,
  EmailThreadHost,
} from '../context/email-thread-context';
import type { EmailThread } from '../core/email-thread';
import { selectThreadMessages } from '../core/thread-messages';
import type { HoveredThreadStop } from '../core/thread-stops';
import { hiddenMessagesControl } from './scroll-to-message';
import { createThreadDrafts } from './thread-drafts';
import { createThreadRecipients } from './thread-recipients';
import { createThreadSnapshot } from './thread-snapshot';

type NavigationTarget = {
  threadId: string;
  messageId: string | undefined;
  request?: string;
};

export type EmailThreadState = {
  isScrollingToMessage: Accessor<boolean>;
  setIsScrollingToMessage: (value: boolean) => void;
  registerMessagesList: (list: HTMLElement) => void;
  messagesListRef: Accessor<HTMLElement | undefined>;
  registerMessagesContainer: (container: HTMLElement) => void;
  messagesContainerRef: Accessor<HTMLElement | undefined>;

  recipientOptions: Accessor<EmailRecipient[]>;
  onRecipientsChange: (items: EmailRecipient[]) => void;

  drafts: {
    getDraftForMessage: (messageDbId: string) => EmailMessage | undefined;
    deleteDraftForMessage: (messageDbId: string) => void;
    restoreDraftForMessage: (draft: EmailMessage) => void;
    initialDraftsSettled: Accessor<boolean>;
  };

  messages: {
    unfiltered: Accessor<EmailMessage[]>;
    list: Accessor<EmailMessage[]>;
    targetMessageId: Accessor<string | undefined>;
    clearTargetMessage: () => void;
    focusedId: Accessor<string | undefined>;
    setFocused: (messageId: string | undefined) => void;
    hiddenChipFocused: Accessor<boolean>;
    setHiddenChipFocused: (focused: boolean) => void;
    hovered: Accessor<HoveredThreadStop | undefined>;
    setHovered: (stop: HoveredThreadStop | undefined) => void;
    expandedBodyIds: Record<string, boolean>;
    setExpandedBodyId: (id: string, expanded: boolean) => void;
    isBodyExpanded: (id: string) => boolean;
    replyingToMessageId: Accessor<string | undefined>;
    setReplyingToMessageId: (id: string | undefined) => void;
    bottomReplyOpen: Accessor<boolean>;
    setBottomReplyOpen: (open: boolean) => void;
    // Sender emails (lowercased) with a CATEGORY_PERSONAL message in the thread
    personalSenders: Accessor<Set<string>>;
  };
  mobileReplyComposer: {
    open: Accessor<boolean>;
    messageId: Accessor<string | undefined>;
    setOpen: (open: boolean) => void;
    openForMessage: (id: string) => void;
    close: () => void;
  };
  replyRequest: {
    messageId: Accessor<string | undefined>;
    replyType: Accessor<ReplyType | undefined>;
    set: (messageId: string, replyType: ReplyType) => void;
    clear: () => void;
  };
  thread: Accessor<EmailThread | undefined>;
  permissions: Accessor<{
    isOwner: boolean;
    /** Owners, and recipients the thread was shared with at edit access,
     *  who reply from their own inbox. */
    canReply: boolean;
  }>;

  query: {
    hasMore: Accessor<boolean>;
    isFetching: Accessor<boolean>;
    fetchNextPage: () => Promise<void>;
    refetch: () => Promise<void>;
  };

  archiveThread: (opts?: ArchiveThreadOptions) => boolean;
  /** Closes an embedded thread back to its list, when the host has one. */
  returnToList?: () => void;
  /** Marks the thread done and opens the next one in the host's list. */
  archiveThreadAndAdvance: (opts?: ArchiveThreadOptions) => boolean;
  /** True when the thread is archived, i.e. currently marked done. */
  isThreadDone: Accessor<boolean>;
  /** True when the done state can actually be reversed — see
   *  `markThreadNotDone`. */
  canMarkThreadNotDone: Accessor<boolean>;
  /** Unarchives a done thread and restores its notifications. */
  markThreadNotDone: () => boolean;
  /** True when the user marked the open thread unread. Resets to false per
   *  thread — viewing marks it read, so the toggle starts at Mark Unread. */
  isThreadMarkedUnread: Accessor<boolean>;
  /** True when the user re-marked the open thread read, as opposed to the
   *  mark-as-read that viewing it queues. Resets to false per thread. */
  isThreadMarkedRead: Accessor<boolean>;
  /** Marks the open thread unread; the toggle then offers Mark Read. */
  markThreadUnread: () => boolean;
  /** Re-marks the thread read after a mark-unread. */
  markThreadRead: () => boolean;
  /** True when a sender other than the viewer exists for the sender actions
   *  to target. False on a thread the viewer sent alone. */
  canActOnSender: Accessor<boolean>;
  blockSender: () => boolean;
  markSenderSignal: () => boolean;
  markSenderNoise: () => boolean;
  initialLoadComplete: Accessor<boolean>;
  onInitialDataLoad: (
    callback: () => void,
    onTargetChange: (target: NavigationTarget) => void
  ) => void;
};

export function createEmailThreadState(
  threadContext: EmailThreadContext,
  host: EmailThreadHost = {}
): EmailThreadState {
  const threadSnapshot = createThreadSnapshot(threadContext.source);
  const selected = createMemo(() => {
    const thread = threadSnapshot();
    return thread ? selectThreadMessages(thread) : undefined;
  });
  const [isScrollingToMessage, setIsScrollingToMessage] = createSignal(false);
  const [focusedMessageId, setFocusedMessageId] = createSignal<string>();
  const [hiddenChipFocused, setHiddenChipFocused] = createSignal(false);
  const [hoveredStop, setHoveredStop] = createSignal<HoveredThreadStop>();
  const [replyingToMessageId, setReplyingToMessageId] = createSignal<string>();
  const [bottomReplyTarget, setBottomReplyTarget] = createSignal<{
    threadId: string;
    messageId: string;
  }>();
  // An open reply belongs to the selected message, even when sending adds
  // a new last message to the thread.
  const bottomReplyOpen = () => {
    const target = bottomReplyTarget();
    const thread = selected();
    return (
      !!target &&
      target.threadId === thread?.db_id &&
      target.messageId === thread.filtered.at(-1)?.db_id
    );
  };
  const setBottomReplyOpen = (open: boolean) => {
    const thread = selected();
    const messageId = thread?.filtered.at(-1)?.db_id;
    setBottomReplyTarget(
      open && thread && messageId
        ? { threadId: thread.db_id, messageId }
        : undefined
    );
  };
  const [mobileReplyComposerOpen, setMobileReplyComposerOpen] =
    createSignal(false);
  const [mobileReplyComposerMessageId, setMobileReplyComposerMessageId] =
    createSignal<string>();
  const [replyRequest, setReplyRequest] = createSignal<{
    messageId: string;
    replyType: ReplyType;
  }>();
  const [expandedMessageBodyIds, setExpandedMessageBodyIds] = createStore<
    Record<string, boolean>
  >({});
  // Identity distinguishes returning to a previously cleared deep link from
  // continuing to display it after its highlight has expired.
  const navigationTarget = createMemo(
    () => ({
      threadId: threadContext.source.id(),
      messageId: host.targetMessageId?.(),
      request: host.targetRequest?.(),
    }),
    undefined,
    {
      equals: (a, b) =>
        a.threadId === b.threadId &&
        a.messageId === b.messageId &&
        a.request === b.request,
    }
  );
  const [clearedTarget, setClearedTarget] = createSignal<NavigationTarget>();
  const [handledTarget, setHandledTarget] = createSignal<NavigationTarget>();
  const targetMessageId = () =>
    clearedTarget() === navigationTarget()
      ? undefined
      : navigationTarget().messageId;
  const hasHandledTarget = () => handledTarget() === navigationTarget();

  const drafts = createThreadDrafts(selected);

  const recipients = createThreadRecipients(
    threadContext.recipients,
    () => selected()?.messages
  );

  const [messagesListRef, setMessagesListRef] = createSignal<
    HTMLDivElement | undefined
  >(undefined);
  const [messagesContainerRef, setMessagesContainerRef] = createSignal<
    HTMLDivElement | undefined
  >(undefined);

  /** Selecting a message clears the hidden-chip stop explicitly (no createEffect). */
  const setFocused = (messageId: string | undefined) => {
    if (messageId) {
      setHiddenChipFocused(false);
      const list = messagesListRef();
      const button = list ? hiddenMessagesControl(list) : undefined;
      if (button && document.activeElement === button) {
        button.blur();
        host.focusContainer?.();
      }
    }
    setFocusedMessageId(messageId);
  };

  const onInitialDataLoad: EmailThreadState['onInitialDataLoad'] = (
    callback,
    onTargetChange
  ) => {
    let previousTarget: NavigationTarget | undefined;
    const ready = () =>
      !threadContext.source.isFetching() &&
      (!threadContext.isTouch() || host.isActive?.() !== false) &&
      !!messagesListRef() &&
      ((!!messagesContainerRef() && !!selected()?.db_id) ||
        !threadContext.source.hasMore());
    // One boundary from reactive route/query/DOM readiness into navigation.
    // Cancel the previous target even while fetching or hidden on mobile.
    createEffect(
      on(
        [navigationTarget, hasHandledTarget, ready],
        ([target, handled, ready]) => {
          if (target !== previousTarget) {
            previousTarget = target;
            onTargetChange(target);
          }
          if (handled || !ready) return;
          callback();
          setHandledTarget(target);
        }
      )
    );
  };

  const commands = threadContext.createCommands(threadSnapshot);
  const archiveUnlessCancelled = (opts?: ArchiveThreadOptions) =>
    !opts?.cancelled?.() && commands.archiveThread(opts);
  // A send resolves after a round trip; by then the user may have moved on.
  // The host advances only from this thread; otherwise it is marked done
  // where it is.
  const advanceFrom = async (
    navigation: NonNullable<typeof host.listNavigation>,
    threadId: string,
    opts?: ArchiveThreadOptions
  ) => {
    const archived = await navigation.markDone(
      (step) => archiveUnlessCancelled({ ...opts, ...step }),
      threadId
    );
    if (!archived) archiveUnlessCancelled({ ...opts, navigate: false });
  };
  const archiveThreadAndAdvance = (opts?: ArchiveThreadOptions) => {
    const navigation = host.listNavigation;
    const threadId = threadContext.source.id();
    if (!navigation || !threadId) return archiveUnlessCancelled(opts);
    fireAndForget(advanceFrom(navigation, threadId, opts), 'email-thread');
    return true;
  };

  return {
    registerMessagesList: setMessagesListRef,
    registerMessagesContainer: setMessagesContainerRef,
    thread: selected,
    recipientOptions: recipients.options,
    onRecipientsChange: recipients.add,
    ...commands,
    returnToList: host.returnToList,
    archiveThreadAndAdvance,
    messagesContainerRef,
    messagesListRef,
    query: {
      hasMore: threadContext.source.hasMore,
      fetchNextPage: threadContext.source.fetchOlder,
      isFetching: () =>
        threadContext.source.isLoading() ||
        threadContext.source.isFetchingOlder(),
      refetch: threadContext.source.refresh,
    },
    drafts,
    messages: {
      focusedId: focusedMessageId,
      setFocused,
      hiddenChipFocused,
      setHiddenChipFocused,
      hovered: hoveredStop,
      setHovered: setHoveredStop,
      targetMessageId,
      clearTargetMessage: () => setClearedTarget(navigationTarget()),
      list: createMemo(() => selected()?.filtered ?? []),
      unfiltered: createMemo(() => selected()?.messages ?? []),
      // Google's CATEGORY_PERSONAL classification is inconsistent across
      // identical messages, so promote it per-sender across the thread
      personalSenders: createMemo(() => {
        const senders = new Set<string>();
        for (const message of selected()?.messages ?? []) {
          const email = message.from?.email?.toLowerCase();
          if (!email) continue;
          if (message.labels.some((l) => l.name === 'CATEGORY_PERSONAL')) {
            senders.add(email);
          }
        }
        return senders;
      }),
      expandedBodyIds: expandedMessageBodyIds,
      setExpandedBodyId: setExpandedMessageBodyIds,
      isBodyExpanded: (id: string) => expandedMessageBodyIds[id] ?? false,
      replyingToMessageId,
      setReplyingToMessageId,
      bottomReplyOpen,
      setBottomReplyOpen,
    },
    mobileReplyComposer: {
      open: mobileReplyComposerOpen,
      messageId: mobileReplyComposerMessageId,
      setOpen: setMobileReplyComposerOpen,
      openForMessage: (id: string) => {
        setMobileReplyComposerMessageId(id);
        setMobileReplyComposerOpen(true);
      },
      close: () => {
        setMobileReplyComposerOpen(false);
        setMobileReplyComposerMessageId(undefined);
      },
    },
    replyRequest: {
      messageId: () => replyRequest()?.messageId,
      replyType: () => replyRequest()?.replyType,
      set: (messageId: string, replyType: ReplyType) => {
        setReplyRequest({ messageId, replyType });
      },
      clear: () => {
        setReplyRequest(undefined);
      },
    },
    permissions: () => {
      const accessLevel = selected()?.access_level;
      return {
        isOwner: accessLevel === 'owner',
        canReply: accessLevel === 'owner' || accessLevel === 'edit',
      };
    },
    initialLoadComplete: hasHandledTarget,
    onInitialDataLoad,
    isScrollingToMessage,
    setIsScrollingToMessage,
  };
}