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.

10.3 KB
Raw Blame
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
import { EmojiSelector } from '@core/component/Emoji/EmojiSelector';
import { recordEmojiUsage } from '@core/component/Emoji/emojiUsage';
import { focusInput } from '@core/directive/focusInput';
import type {
  MessageActionEvent,
  MessageActionHandler,
  MessageActions,
} from '@core/messages/types';
import { fireAndForget } from '@core/util/fireAndForget';
import ReplyIcon from '@icon/system/regular/arrow-bend-up-left.svg';
import CheckSquareIcon from '@icon/system/regular/check-square.svg';
import CopyIcon from '@icon/system/regular/copy.svg';
import LinkIcon from '@icon/system/regular/link.svg';
import PencilIcon from '@icon/system/regular/pencil.svg';
import SmileyIcon from '@icon/system/regular/smiley.svg';
import SparkleIcon from '@icon/system/regular/sparkle.svg';
import TrashIcon from '@icon/system/regular/trash.svg';
import {
  type Component,
  createSignal,
  For,
  type JSX,
  onMount,
  Show,
} from 'solid-js';
import { renderIcon } from '../Message/render-icon';
import { useMessageActionDrawer } from './message-action-drawer-context';

const QUICK_REACTION_EMOJIS = ['❤️', '👍', '👎', '😂', '😡'] as const;

type ActionId =
  | 'reply'
  | 'copy-link'
  | 'copy-message-text'
  | 'edit'
  | 'delete'
  | 'create-task'
  | 'ask-macro';

type ActionItem = {
  id: ActionId;
  label: string;
  icon: Component<JSX.SvgSVGAttributes<SVGSVGElement>> | string;
  onClick?: MessageActionHandler;
  destructive?: boolean;
  getFocusTarget?: () => HTMLElement | null | undefined;
};

function buildActionItems(
  actions: MessageActions | undefined,
  message: { id: string; thread_id?: string | null } | undefined
): ActionItem[] {
  const messageId = message?.id;
  // Reply inputs are keyed by the thread root, not the long-pressed message.
  const replyThreadId = message ? (message.thread_id ?? message.id) : undefined;
  return [
    {
      id: 'reply',
      label: 'Reply',
      icon: ReplyIcon,
      onClick: actions?.onReply,
      getFocusTarget: replyThreadId
        ? () =>
            document.querySelector<HTMLElement>(
              `[data-input-id="thread-reply-input-${replyThreadId}"] [contenteditable]`
            )
        : undefined,
    },
    {
      id: 'copy-message-text',
      label: 'Copy message text',
      icon: CopyIcon,
      onClick: actions?.onCopyMessageText,
    },
    {
      id: 'copy-link',
      label: 'Copy link',
      icon: LinkIcon,
      onClick: actions?.onCopyLink,
    },
    {
      id: 'create-task',
      label: 'Create task',
      icon: CheckSquareIcon,
      onClick: actions?.onCreateTask,
    },
    {
      id: 'ask-macro',
      label: 'Ask Macro',
      icon: SparkleIcon,
      onClick: actions?.onChat,
    },
    {
      id: 'edit',
      label: 'Edit',
      icon: PencilIcon,
      onClick: actions?.onEdit,
      getFocusTarget: messageId
        ? () =>
            document.querySelector<HTMLElement>(
              `[data-input-id="edit-message-input-${messageId}"] [contenteditable]`
            )
        : undefined,
    },
    {
      id: 'delete',
      label: 'Delete',
      icon: TrashIcon,
      onClick: actions?.onDelete,
      destructive: true,
    },
  ];
}

function EmojiSearchView(props: {
  onSelect: (emoji: string) => void;
  onBack: () => void;
}) {
  let inputRef: HTMLInputElement | undefined;
  const [query, setQuery] = createSignal('');

  onMount(() => {
    setTimeout(() => {
      inputRef?.focus();
    }, 0);
  });

  return (
    <div class="flex flex-col flex-1 min-h-0 pb-2">
      {/* Search input */}
      <div class="flex items-center gap-2 px-3 pb-2 shrink-0">
        <div class="flex flex-1 items-center bg-surface border border-edge-muted rounded-sm px-2 py-1.5 text-sm gap-1">
          <input
            ref={inputRef}
            value={query()}
            onInput={(e) => setQuery(e.currentTarget.value)}
            placeholder="Search emojis"
            aria-label="Search emojis"
            class="flex-1 bg-transparent outline-none placeholder:text-ink-placeholder"
          />
        </div>
      </div>

      {/* Emoji grid — onPointerDown preventDefault prevents the input from
          blurring before the click fires on an emoji button */}
      <div
        class="overflow-y-auto flex-1 px-1"
        onPointerDown={(e) => e.preventDefault()}
      >
        <EmojiSelector
          nameFilter={query()}
          onEmojiClick={(emoji) => props.onSelect(emoji.emoji)}
          columns={7}
        />
      </div>
    </div>
  );
}

export function ActionDrawer() {
  const drawerState = useMessageActionDrawer();
  const [showEmojiSearch, setShowEmojiSearch] = createSignal(false);

  if (!drawerState) {
    console.warn('No drawer state.');
    return null;
  }

  const message = () => drawerState.message();
  const actions = () => drawerState.actions();

  const handleReaction = (emoji: string, event?: MessageActionEvent) => {
    const msg = message();
    if (!msg) return;
    fireAndForget(
      actions()?.onReact?.({ message: msg, event, emoji }),
      'channel-message-actions'
    );
    drawerState.close();
    setShowEmojiSearch(false);
  };

  const handleAction = (
    handler: MessageActionHandler | undefined,
    event: MouseEvent
  ) => {
    const msg = message();
    if (!msg) return;
    fireAndForget(
      handler?.({ message: msg, event }),
      'channel-message-actions'
    );
    drawerState.close();
  };

  const actionItems = () => buildActionItems(actions(), message());
  const nonDestructiveActions = () =>
    actionItems().filter((item) => item.onClick && !item.destructive);
  const destructiveActions = () =>
    actionItems().filter((item) => item.onClick && item.destructive);
  const hasReactAction = () => actions()?.onReact !== undefined;

  return (
    <MobileDrawer
      side="bottom"
      open={drawerState.isOpen()}
      closeOnOutsidePointerStrategy="pointerdown"
      onOpenChange={(v) => {
        if (!v) {
          drawerState.close();
          setShowEmojiSearch(false);
        }
      }}
      preventScroll={false}
      preventScrollbarShift={false}
      restoreFocus={false}
    >
      <MobileDrawer.Portal>
        <MobileDrawer.Overlay />
        <MobileDrawer.Content
          aria-label="Message actions"
          class={showEmojiSearch() ? 'h-[80vh]' : undefined}
        >
          {/* Drag handle */}
          <MobileDrawer.Handle />

          <Show
            when={!showEmojiSearch()}
            fallback={
              <EmojiSearchView
                onSelect={(emoji) => handleReaction(emoji)}
                onBack={() => setShowEmojiSearch(false)}
              />
            }
          >
            {/* Emoji reaction row */}
            <Show when={hasReactAction()}>
              <div class="flex flex-row items-center justify-between px-3 pb-4 gap-1 shrink-0">
                <For each={QUICK_REACTION_EMOJIS}>
                  {(emoji) => (
                    <button
                      type="button"
                      title={`React ${emoji}`}
                      aria-label={`React ${emoji}`}
                      class="size-12 flex items-center justify-center bg-edge rounded-full text-[28px]"
                      onClick={(event) => {
                        recordEmojiUsage(emoji);
                        handleReaction(emoji, event);
                      }}
                    >
                      {emoji}
                    </button>
                  )}
                </For>
                <button
                  type="button"
                  title="More reactions"
                  aria-label="More reactions"
                  class="size-12 bg-edge rounded-full flex items-center justify-center text-ink-muted"
                  onClick={() => setShowEmojiSearch(true)}
                >
                  {renderIcon(SmileyIcon, 'size-[28px]')}
                </button>
              </div>
            </Show>

            {/* Action sections scroll; the handle and reaction row stay pinned */}
            <MobileDrawer.ScrollBody>
              {/* Non-destructive actions */}
              <Show when={nonDestructiveActions().length > 0}>
                <MobileDrawer.Section class="flex flex-col shrink-0">
                  <For each={nonDestructiveActions()}>
                    {(action) => (
                      <MobileDrawer.Item
                        type="button"
                        data-message-action={action.id}
                        ref={(el) => {
                          const getTarget = action.getFocusTarget;
                          if (getTarget) focusInput(el, () => ({ getTarget }));
                        }}
                        onClick={(event) => handleAction(action.onClick, event)}
                      >
                        <span class="size-5 flex items-center justify-center shrink-0">
                          {renderIcon(action.icon)}
                        </span>
                        {action.label}
                      </MobileDrawer.Item>
                    )}
                  </For>
                </MobileDrawer.Section>
              </Show>

              {/* Destructive actions */}
              <Show when={destructiveActions().length > 0}>
                <MobileDrawer.Section class="flex flex-col shrink-0 mt-3">
                  <For each={destructiveActions()}>
                    {(action) => (
                      <MobileDrawer.Item
                        type="button"
                        data-message-action={action.id}
                        class="text-failure-ink"
                        ref={(el) => {
                          const getTarget = action.getFocusTarget;
                          if (getTarget) focusInput(el, () => ({ getTarget }));
                        }}
                        onClick={(event) => handleAction(action.onClick, event)}
                      >
                        <span class="size-5 flex items-center justify-center shrink-0">
                          {renderIcon(action.icon)}
                        </span>
                        {action.label}
                      </MobileDrawer.Item>
                    )}
                  </For>
                </MobileDrawer.Section>
              </Show>
            </MobileDrawer.ScrollBody>
          </Show>
        </MobileDrawer.Content>
      </MobileDrawer.Portal>
    </MobileDrawer>
  );
}