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.

20.7 KB
Raw Blame
import { DebugSuspense } from '@channel/DebugSuspense';
import { useUserId } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { getDisplayName, tryMacroId } from '@core/user';
import { thrownResultErrorHasCode } from '@core/util/result';
import { MarkMessageNotifications } from '@notifications/components/MarkMessageNotifications';
import { MessageReadVisibilityProvider } from '@notifications/components/MessageReadVisibility';
import { queryReadyGate } from '@queries/gate';
import { useThreadRepliesQuery } from '@queries/messages/thread-replies';
import type { Message as EntityMessage } from '@service-storage/messages';
import {
  createEffect,
  createSignal,
  Match,
  on,
  onCleanup,
  type ParentProps,
  Show,
  Switch,
  untrack,
} from 'solid-js';
import { DetachedCallRootLine } from '../Call/discussion/PastCallLine';
import { createMessageSelection } from '../Channel/create-message-selection';
import { ChannelMessage } from '../Message';
import { createTargetReplyNavigationController } from './create-target-reply-navigation-controller';
import { createTargetReplyScroller } from './create-target-reply-scroller';
import { createThreadHotkeys } from './create-thread-hotkeys';
import { createThreadRepliesFetchGate } from './create-thread-replies-fetch-gate';
import { createThreadReplyView } from './create-thread-reply-view';
import { notifyElementOnMount } from './message-element-lifecycle';
import { Thread } from './Thread';
import type { ThreadReplyListHandle } from './ThreadReplyList';
import { ThreadTypingIndicator } from './ThreadTypingIndicator';
import type { ThreadProps } from './types';
import { channelReplyInputOffsetX } from './utils/thread-rail-geometry';
import {
  getCollapsedRepliesCount,
  getThreadLatestReplyAt,
  getUniqueReplyUserIds,
} from './utils/thread-reply-indicator-helpers';

export function ChannelThread(props: ThreadProps) {
  const [messageElement, setMessageElement] = createSignal<HTMLDivElement>();
  const userId = useUserId();
  const replyUserId = () => userId() ?? props.data().sender_id;
  const macroId = () => tryMacroId(replyUserId());
  const displayName = () => getDisplayName(macroId());
  const thread = () => props.data().thread;
  const hasReplies = () => thread().reply_count > 0;
  const fetchRepliesEnabled = createThreadRepliesFetchGate({
    threadId: () => props.data().id,
    replyCount: () => thread().reply_count,
    isExpanded: props.isExpanded,
    isFindBarOpen: props.isFindBarOpen,
    targetThreadId: () => props.targetNavigation?.targetThreadId(),
    targetReplyId: () => props.targetNavigation?.targetReplyId(),
  });

  const isSelected = () => props.selectedMessageId?.() === props.data().id;

  // The unified input's reply binding, resolved against this thread.
  // `undefined` unless the binding points into this thread; otherwise it is
  // bound either to the root or to one of this thread's replies.
  const unifiedReplyBinding = () => {
    const target = props.unifiedReplyTarget;
    if (props.inputMode !== 'unified' || target?.threadId !== props.data().id) {
      return undefined;
    }
    return { boundToRoot: !target.replyId, boundReplyId: target.replyId };
  };

  const repliesQuery = useThreadRepliesQuery(
    props.parent,
    () => props.data().id,
    fetchRepliesEnabled
  );
  // A project's cached root must not outlive an explicit denial from its
  // thread read while the surrounding project is revalidating access.
  const projectUnavailable = () =>
    props.parent().type === 'initiative' &&
    ['UNAUTHORIZED', 'FORBIDDEN', 'NOT_FOUND'].some((code) =>
      thrownResultErrorHasCode(repliesQuery.error, code)
    );

  const queryReplies = (): Array<EntityMessage> | undefined => {
    if (projectUnavailable()) return [];
    return queryReadyGate(repliesQuery) ? repliesQuery.data : undefined;
  };

  const loadedReplies = () => queryReplies() ?? [];
  const canScrollToTargetReply = () => queryReplies() !== undefined;

  const { activeReplies, visibleReplyCount, displayReplies } =
    createThreadReplyView({
      preview: () => thread().preview,
      loaded: queryReplies,
      isExpanded: props.isExpanded,
      hideCollapsedPreview: props.hideCollapsedPreview,
    });

  // Thread-local reply selection
  const replySelection = createMessageSelection({
    keys: () => activeReplies().map((r) => r.id),
  });

  // Clears the local reply selection when the channel-level selection moves away
  createEffect(
    on(
      () => props.selectedMessageId?.(),
      (selectedId) => {
        if (selectedId === props.data().id) return;
        if (replySelection.selectedId()) replySelection.clear();
      },
      { defer: true }
    )
  );

  const isThreadFocused = () => !!replySelection.selectedId();

  // Channel navigation landed on this root message (and not on one of its
  // replies).
  const isRootNavTargeted = () =>
    !!props.targetNavigation?.targetThreadId() &&
    props.targetNavigation.targetThreadId() === props.data().id &&
    !props.targetNavigation.activeTargetReplyId();

  const selectThreadMessage = () => {
    // Clicking the navigation-targeted message releases the target instead
    // of toggling selection.
    if (isRootNavTargeted()) {
      props.targetNavigation?.onClearTarget(props.data().id);
      return;
    }
    // On touch devices, we want to block "click to select"
    if (isTouchDevice()) return;
    if (isSelected() && !isThreadFocused()) {
      props.onClearSelection?.();
      return;
    }

    props.onSelectMessage?.(props.data().id);
    replySelection.clear();
  };

  const selectReply = (replyId: string) => {
    // Clicking the navigation-targeted reply releases the target instead of
    // toggling selection.
    if (props.targetNavigation?.activeTargetReplyId() === replyId) {
      props.targetNavigation.onClearTarget(props.data().id);
      return;
    }
    // On touch devices, we want to block "click to select"
    if (isTouchDevice()) return;
    if (isSelected() && replySelection.selectedId() === replyId) {
      replySelection.clear();
      props.onClearSelection?.();
      return;
    }

    props.onSelectMessage?.(props.data().id);
    replySelection.select(replyId);
  };

  let replyInputContainerRef: HTMLDivElement | undefined;

  const { attachReplyInputRef } = createThreadHotkeys({
    messageListScopeId: props.messageListScopeId!,
    replySelection,
    isThreadFocused,
    isEditing: () => !!props.messageEditor?.state(),
    activeReplies,
    threadId: () => props.data().id,
    getMessageActions: (msg) => props.getMessageActions?.(msg),
    userId,
    parentMessage: props.data,
    collapseThread: () => props.setIsExpanded(false),
    isSelected,
    hasReplies,
    expandThread: () => props.setIsExpanded(true),
    isThreadExpanded: props.isExpanded,
    setIsReplying: (v) => props.setIsReplying(v),
  });

  const collapsedRepliesCount = () =>
    getCollapsedRepliesCount(thread().reply_count, visibleReplyCount());
  const collapsedRepliesContainsNewMessages = () =>
    activeReplies()
      .slice(visibleReplyCount())
      .some((reply: EntityMessage) => props.isNewMessage?.(reply));
  const collapsedRepliesHaveUnreadNotifications = () =>
    props.unreadMessageIds?.some(
      (id) =>
        id !== props.data().id &&
        !displayReplies().some((reply) => reply.id === id)
    ) ?? false;
  const collapsedReplyUsers = () =>
    getUniqueReplyUserIds(activeReplies().slice(visibleReplyCount()));
  const collapsedLatestReplyAt = () =>
    getThreadLatestReplyAt(thread().latest_reply_at, activeReplies());
  // Replying to this thread — inline input open, or the unified input bound.
  const isReplyingToThread = () =>
    props.isReplying() || unifiedReplyBinding() !== undefined;
  const hasRootSlot = () => !!props.rootSlot;
  const hasInlineReplyInput = () =>
    props.isReplying() && props.inputMode !== 'unified';
  const rootRailVisible = () =>
    !props.hideRail && (hasReplies() || hasInlineReplyInput());
  const shouldShowCollapsedIndicator = () =>
    !isReplyingToThread() && !props.isExpanded() && collapsedRepliesCount() > 0;
  const replyAction = () => props.getMessageActions?.(props.data())?.onReply;
  const shouldShowReplyButton = () =>
    (hasReplies() || hasRootSlot()) &&
    !!replyAction() &&
    !isReplyingToThread() &&
    !shouldShowCollapsedIndicator();
  const [replyListHandle, setReplyListHandle] =
    createSignal<ThreadReplyListHandle>();
  const [threadRowElement, setThreadRowElement] = createSignal<HTMLElement>();
  const targetMessageScroller = createTargetReplyScroller({
    getTarget: () =>
      threadRowElement()?.querySelector<HTMLElement>(
        `[data-message-id="${props.data().id}"]`
      ) ?? undefined,
    positionTarget: props.targetNavigation?.positionTarget,
  });

  createEffect(
    on(
      [
        () => props.targetNavigation?.targetMessageId(),
        threadRowElement,
        () => props.targetNavigation?.requestKey?.(),
      ],
      ([targetMessageId]) => {
        if (!targetMessageId || targetMessageId !== props.data().id) {
          targetMessageScroller.cancel();
          return;
        }
        targetMessageScroller.scrollToIndex(0, () => {
          props.targetNavigation?.onTargetMessageScrolled(targetMessageId);
        });
      }
    )
  );

  onCleanup(targetMessageScroller.dispose);

  createEffect(
    on(
      [
        () => props.targetNavigation?.activeTargetReplyId(),
        () => props.targetNavigation?.targetReplyId(),
        loadedReplies,
      ],
      ([activeTargetReplyId, _targetReplyId, replies]) => {
        if (!activeTargetReplyId) {
          return;
        }
        const found = replies.some((r) => r.id === activeTargetReplyId);
        if (!found) {
          if (replySelection.selectedId()) replySelection.clear();
          return;
        }
        props.onSelectMessage?.(props.data().id);
        replySelection.select(activeTargetReplyId);
      }
    )
  );

  const targetReplyNavigation = createTargetReplyNavigationController();
  createEffect(
    on(
      [
        () => props.targetNavigation?.targetReplyId(),
        replyListHandle,
        canScrollToTargetReply,
        props.isExpanded,
        () => props.targetNavigation?.requestKey?.(),
      ],
      ([targetReplyId, handle, canScroll, isExpanded, requestKey]) => {
        // Untracked: channel-message reconciles must not re-fire scroll.
        const replies =
          targetReplyId && canScroll && handle
            ? isExpanded
              ? untrack(loadedReplies)
              : untrack(displayReplies)
            : [];
        targetReplyNavigation.update({
          requestKey,
          targetReplyId,
          handle,
          canScroll,
          replies,
          getCurrentTargetReplyId: () =>
            props.targetNavigation?.targetReplyId(),
          onScrolled: props.targetNavigation?.onTargetReplyScrolled,
        });
      }
    )
  );

  onCleanup(targetReplyNavigation.dispose);

  const actionsFooter = () => (
    <Show when={shouldShowCollapsedIndicator() || shouldShowReplyButton()}>
      <Thread.ActionsFooter>
        <Show when={shouldShowCollapsedIndicator()}>
          <Thread.CollapsedIndicator
            ref={(element) =>
              notifyElementOnMount(
                props.onDisclosureMount,
                props.data().id,
                element
              )
            }
            withoutPreview={props.hideCollapsedPreview}
            hasUnreadNotifications={collapsedRepliesHaveUnreadNotifications()}
            collapsedRepliesCount={collapsedRepliesCount()}
            participants={collapsedReplyUsers()}
            latestReplyAt={collapsedLatestReplyAt()}
            onClick={() => props.setIsExpanded(true)}
            hasNewMessages={collapsedRepliesContainsNewMessages()}
          />
        </Show>
        <Show when={shouldShowReplyButton()}>
          <Thread.ReplyButton
            getFocusTarget={() =>
              props.inputMode !== 'unified'
                ? (replyInputContainerRef?.querySelector<HTMLElement>(
                    '[contenteditable]'
                  ) ?? null)
                : document.querySelector<HTMLElement>(
                    `[data-input-id="thread-reply-input-${props.data().id}"] [contenteditable]`
                  )
            }
            onClick={(event) =>
              replyAction()?.({ message: props.data(), event })
            }
            aria-label="Reply"
          />
        </Show>
      </Thread.ActionsFooter>
    </Show>
  );

  return (
    <ThreadReadBoundary available={!projectUnavailable()}>
      <Thread.Row
        ref={setThreadRowElement}
        channelId={
          props.parent().type === 'channel' ? props.parent().id : undefined
        }
        message={props.data()}
        listMeta={props.listMeta}
        onDismissNewMessages={props.threadActions?.onDismissNewMessages}
      >
        <div class="flex flex-col w-full">
          {props.beforeMessage}
          {/* Rail segment along the root message: from the avatar's center
              (masked by the avatar's fill until its lower edge) to the
              message's bottom, where the reply-branch elbow takes over. A
              grouped root has no avatar — its segment enters from the row
              top (fed by the run's pass-through rails) and a fork node on
              the spine marks which message the thread replies to. Plain
              messages carry no rail. */}
          <div
            class="relative"
            ref={(element) => {
              setMessageElement(element);
              notifyElementOnMount(
                props.onMessageMount,
                props.data().id,
                element
              );
            }}
          >
            <Thread.RootRail
              visible={rootRailVisible()}
              grouped={props.listMeta?.isGroupedWithPrevious}
            />
            <MarkMessageNotifications
              element={messageElement()}
              messageId={props.data().id}
              parent={props.parent()}
            >
              <DebugSuspense name="ChannelThread.message">
                <Switch
                  fallback={
                    <ChannelMessage
                      renderContent={props.renderMessageContent}
                      hideTriggeredBy={props.hideTriggeredBy}
                      parent={props.parent()}
                      message={props.data()}
                      actions={props.getMessageActions?.(props.data())}
                      listMeta={props.listMeta}
                      inputMode={props.inputMode}
                      messageEditor={props.messageEditor}
                      onClick={selectThreadMessage}
                      selected={isSelected() && !isThreadFocused()}
                      targeted={
                        // The unified input's reply is bound to this root, or
                        // channel navigation landed on it.
                        unifiedReplyBinding()?.boundToRoot ||
                        isRootNavTargeted()
                      }
                    />
                  }
                >
                  <Match when={hasRootSlot()}>{props.rootSlot?.()}</Match>
                  <Match when={props.data().kind === 'call_root'}>
                    <DetachedCallRootLine message={props.data()} />
                  </Match>
                </Switch>
              </DebugSuspense>
            </MarkMessageNotifications>
          </div>
          {props.afterMessage}
          <Show when={hasReplies() || hasInlineReplyInput() || hasRootSlot()}>
            <div class="relative w-full">
              <Show when={!props.hideRail}>
                <Thread.RepliesBridgeRail />
              </Show>
              {/* Terminal branch: the spine's final curve into the footer
                  button's left edge. Its vertical part starts exactly at the
                  last reply row's bottom (button h-8 + mb-2 + container pb). */}
              <Show
                when={
                  !props.hideRail &&
                  !props.monorail &&
                  (shouldShowCollapsedIndicator() || shouldShowReplyButton())
                }
              >
                <Thread.TerminalRail />
              </Show>
              <DebugSuspense name="ChannelThread.replies">
                <Thread.RepliesContainer flat={props.monorail}>
                  <DebugSuspense name="ChannelThread.ReplyList">
                    <Thread.ReplyList
                      parent={props.parent()}
                      threadId={props.data().id}
                      replies={displayReplies()}
                      onMessageMount={props.onMessageMount}
                      getMessageActions={props.getMessageActions}
                      inputMode={props.inputMode}
                      messageEditor={props.messageEditor}
                      isNewMessage={props.isNewMessage}
                      onReady={setReplyListHandle}
                      positionTarget={props.targetNavigation?.positionTarget}
                      selectedReplyId={replySelection.selectedId}
                      targetedReplyId={() =>
                        props.targetNavigation?.activeTargetReplyId() ??
                        unifiedReplyBinding()?.boundReplyId
                      }
                      isThreadFocused={isThreadFocused}
                      onSelectReply={selectReply}
                      monorail={props.monorail}
                      hideRail={props.hideRail}
                      railContinues={
                        hasInlineReplyInput() ||
                        shouldShowCollapsedIndicator() ||
                        shouldShowReplyButton()
                      }
                    />
                  </DebugSuspense>

                  <Show when={hasInlineReplyInput()}>
                    <div
                      ref={(el) => {
                        attachReplyInputRef(el);
                        replyInputContainerRef = el;
                      }}
                      class="ph-no-capture relative"
                    >
                      {/* The first reply has an author avatar before its
                          composer, so this branch turns at the avatar's
                          center. Once replies exist, it instead joins the
                          composer at its vertical center. */}
                      <Show when={!props.hideRail && !props.monorail}>
                        <div
                          class="pointer-events-none absolute top-0 -z-1 channel-rail-left channel-rail-bottom border-thread-rail rounded-bl-[14px]"
                          style={{
                            left: 'calc(var(--user-icon-width) / 2 + var(--message-padding-x) - var(--thread-shift) - var(--channel-rail-width) / 2)',
                            width:
                              'calc(var(--thread-shift) - var(--user-icon-width) / 2 - var(--channel-rail-clearance))',
                            ...(hasReplies()
                              ? { bottom: '50%' }
                              : {
                                  height:
                                    'calc(var(--message-padding-x) + var(--user-icon-width) / 2)',
                                }),
                          }}
                        />
                      </Show>
                      <Show when={!hasReplies()}>
                        <Thread.ReplyAuthor
                          userId={replyUserId()}
                          displayName={displayName()}
                        />
                      </Show>
                      <Thread.ReplyInput
                        connector={false}
                        offsetX={channelReplyInputOffsetX}
                        parent={props.parent()}
                        messageId={props.data().id}
                        replyInputState={props.replyInputState}
                        setReplyInputState={props.setReplyInputState}
                        setIsReplying={props.setIsReplying}
                        replyInputHandle={props.replyInputHandle}
                        setReplyInputEl={props.setReplyInputEl}
                        setReplyInputHandle={props.setReplyInputHandle}
                        focusRequest={props.replyInputFocusRequest}
                      />
                    </div>
                  </Show>

                  {actionsFooter()}
                </Thread.RepliesContainer>
              </DebugSuspense>
            </div>
          </Show>
          <Show when={props.isNewestThread}>
            <ThreadTypingIndicator parent={props.parent()} threadId={null} />
          </Show>
        </div>
      </Thread.Row>
    </ThreadReadBoundary>
  );
}

function ThreadReadBoundary(props: ParentProps<{ available: boolean }>) {
  return (
    <MessageReadVisibilityProvider>
      <DebugSuspense name="ChannelThread.root">
        <Show when={props.available}>{props.children}</Show>
      </DebugSuspense>
    </MessageReadVisibilityProvider>
  );
}