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.

11.8 KB
Raw Blame
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useSplitLayout } from '@components/app/split-layout/layout';
import type { BlockAlias, BlockName } from '@core/block';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { matches } from '@core/util/match';
import { openInNewSplitForMention } from '@core/util/openInNewSplit';
import { truncateString } from '@core/util/string';
import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
import type { NamedSubType } from '@entity';
import EyeSlash from '@icon/system/regular/eye-slash.svg';
import LoadingSpinner from '@icon/system/regular/spinner.svg';
import TrashSimple from '@icon/system/regular/trash-simple.svg';
import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
import {
  BULK_DOCUMENT_WAKEUP_FEATURE_FLAG,
  enqueuePreviewWakeup,
  type ItemEntity,
  isAccessiblePreviewItem,
  useItemPreview,
} from '@queries/preview';
import type { ItemType } from '@service-storage/client';
import type { FileType } from '@service-storage/generated/schemas/fileType';
import { cn } from '@ui';
import {
  type Accessor,
  type ComponentProps,
  createEffect,
  Match,
  Show,
  Suspense,
  Switch,
} from 'solid-js';
import { PopupPreview } from './DocumentPreview';
import {
  EntityIcon,
  type EntityIconProps,
  getPreviewItemIconType,
} from './EntityIcon';
import { HoverCard } from './HoverCard';
import { TaskStatusIcon } from './TaskStatusIcon';

export function useItemPreviewData(entity: Accessor<ItemEntity>) {
  const [item, { documentProperties }] = useItemPreview(entity);
  const bulkWakeupEnabled = useFeatureFlag(BULK_DOCUMENT_WAKEUP_FEATURE_FLAG);

  createEffect(() => {
    if (!bulkWakeupEnabled().enabled) return;

    enqueuePreviewWakeup(item());
  });

  const { replaceOrInsertSplit, insertSplit } = useSplitLayout();

  function openItem(blockOrFileType: string, id: string, inNewSplit?: boolean) {
    const targetBlock: BlockName | BlockAlias =
      fileTypeToBlockName(blockOrFileType);

    if (!targetBlock) {
      return;
    }

    if (inNewSplit) {
      const handle = insertSplit({
        type: targetBlock,
        id,
      });
      handle?.activate();
    } else {
      const handle = replaceOrInsertSplit({
        type: targetBlock,
        id,
      });
      handle?.activate();
    }
  }

  function onPreviewClick(
    type: ItemType | undefined,
    id: string,
    fileType?: FileType,
    subType?: NamedSubType,
    shiftKey?: boolean
  ) {
    const _type = subType ?? fileType ?? type;
    if (!_type) return;
    openItem(_type, id, openInNewSplitForMention(shiftKey, true));
  }

  const name = () => {
    const preview = item();

    if (preview.loading || preview.access !== 'access') {
      return 'Untitled';
    }

    const baseName = preview.name ?? 'Untitled';

    return baseName;
  };

  const targetType = () => {
    return getPreviewItemIconType(item());
  };

  const ItemEntityIcon = (
    localProps?: Partial<Omit<ComponentProps<typeof EntityIcon>, 'targetType'>>
  ) => {
    const statusId = () => {
      const preview = item();
      if (!isAccessiblePreviewItem(preview) || preview.type !== 'document')
        return;
      const property = preview.documentMetadata?.properties.find(
        (property) =>
          property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.STATUS
      );
      return property?.valueType === 'SELECT_STRING'
        ? property.value?.[0]
        : undefined;
    };
    const completed = () => {
      const preview = item();
      return isAccessiblePreviewItem(preview) &&
        preview.subType?.type === 'task'
        ? preview.subType.is_completed
        : undefined;
    };
    return (
      <Show
        when={targetType() === 'task'}
        fallback={<EntityIcon targetType={targetType()} {...localProps} />}
      >
        <TaskStatusIcon
          {...localProps}
          statusId={statusId()}
          completed={completed()}
        />
      </Show>
    );
  };

  return {
    item,
    documentProperties,
    name,
    onPreviewClick,
    targetType,
    ItemEntityIcon,
  };
}

const DEFAULT_BUTTON_CLASS =
  'text-ink text-sm border border-edge-muted/50 rounded-md hover:bg-hover flex flex-row h-6 px-2 justify-center items-center';
const DEFAULT_ICON_CLASS = 'flex justify-start items-center w-3.5 h-3.5 mr-2';
const DEFAULT_TEXT_CLASS = 'flex-1 text-left leading-5 min-w-0 truncate';

interface StatusDisplayProps {
  class?: string;
  iconClass?: string;
  textClass?: string;
}

function ButtonNoAccess(props: StatusDisplayProps) {
  return (
    <div
      class={cn(
        DEFAULT_BUTTON_CLASS,
        'opacity-50 cursor-not-allowed',
        props.class
      )}
    >
      <div class={cn(DEFAULT_ICON_CLASS, props.iconClass)}>
        <EyeSlash class="text-ink-muted size-3.5" />
      </div>
      <div class={cn(DEFAULT_TEXT_CLASS, props.textClass)}>No Access</div>
    </div>
  );
}

function InlineNoAccess() {
  return (
    <span class="inline-flex items-baseline gap-1 align-baseline">
      <span class="relative top-[0.125em] inline-flex size-[1em] shrink-0">
        <EyeSlash class="size-[1em] text-ink-muted" />
      </span>
      <span class="text-ink-muted">No Access</span>
    </span>
  );
}

function ButtonDeleted(props: StatusDisplayProps) {
  return (
    <div
      class={cn(
        DEFAULT_BUTTON_CLASS,
        'opacity-50 cursor-not-allowed',
        props.class
      )}
    >
      <div class={cn(DEFAULT_ICON_CLASS, props.iconClass)}>
        <TrashSimple class="text-ink-muted size-3.5" />
      </div>
      <div class={cn(DEFAULT_TEXT_CLASS, props.textClass)}>Deleted</div>
    </div>
  );
}

function InlineDeleted() {
  return (
    <span class="inline-flex items-baseline gap-1 align-baseline">
      <span class="relative top-[0.125em] inline-flex size-[1em] shrink-0">
        <TrashSimple class="size-[1em] text-ink-muted" />
      </span>
      <span class="text-ink-muted">Deleted</span>
    </span>
  );
}

function ButtonLoading(props: StatusDisplayProps) {
  return (
    <div
      class={cn(
        DEFAULT_BUTTON_CLASS,
        'opacity-50 cursor-not-allowed',
        props.class
      )}
    >
      <div class={cn(DEFAULT_ICON_CLASS, props.iconClass)}>
        <div class="size-3.5 animate-spin">
          <LoadingSpinner />
        </div>
      </div>
      <div class={cn(DEFAULT_TEXT_CLASS, props.textClass)}>Loading...</div>
    </div>
  );
}

function InlineLoading() {
  return (
    <span class="inline-flex items-baseline gap-1 align-baseline">
      <span class="relative top-[0.125em] inline-flex size-[1em] shrink-0 animate-spin">
        <LoadingSpinner />
      </span>
      <span class="text-ink-muted">Loading...</span>
    </span>
  );
}

type ItemPreviewProps = ItemEntity & {
  /** Custom class for the button wrapper */
  class?: string;
  /** Custom class for the icon container */
  iconClass?: string;
  /** Custom class for the text/name */
  textClass?: string;
  /** Disable hover card popup */
  disableHoverCard?: boolean;
  /** Max length for text truncation */
  maxLength?: number;
  /** Icon size (defaults to 'fill') */
  iconSize?: EntityIconProps['size'];
};

export function ItemPreview(props: ItemPreviewProps) {
  return (
    <Suspense>
      <ItemPreviewInner {...props} />
    </Suspense>
  );
}

function ItemPreviewInner(props: ItemPreviewProps) {
  const { item, name, onPreviewClick, targetType, ItemEntityIcon } =
    useItemPreviewData(() => props);

  const maxLength = () => props.maxLength ?? 80;
  const iconSize = () => props.iconSize ?? 'fill';
  const buttonClass = () => cn(DEFAULT_BUTTON_CLASS, props.class);
  const iconClass = () => cn(DEFAULT_ICON_CLASS, props.iconClass);
  const textClass = () => cn(DEFAULT_TEXT_CLASS, props.textClass);

  return (
    <Switch>
      <Match when={item().loading}>
        <ButtonLoading
          class={props.class}
          iconClass={props.iconClass}
          textClass={props.textClass}
        />
      </Match>
      <Match when={matches(item(), (i) => !i.loading)}>
        {(loadedItem) => (
          <Switch>
            <Match when={matches(loadedItem(), isAccessiblePreviewItem)}>
              {(accessibleItem) => {
                const blockName = () => {
                  const type = targetType();
                  const itemType = accessibleItem().type;
                  return fileTypeToBlockName(type ?? itemType);
                };

                const navHandlers =
                  useSplitNavigationHandler<HTMLButtonElement>((e) => {
                    const item = accessibleItem();
                    onPreviewClick(
                      item.type,
                      item.id,
                      item.fileType,
                      item.subType?.type as NamedSubType | undefined,
                      e.shiftKey
                    );
                  });

                return (
                  <HoverCard
                    disabled={
                      props.disableHoverCard || isTouchDevice() || !blockName()
                    }
                    trigger={
                      <button
                        type="button"
                        class={buttonClass()}
                        {...navHandlers}
                      >
                        <div class={iconClass()}>
                          <ItemEntityIcon size={iconSize()} />
                        </div>
                        <div class={textClass()}>
                          {truncateString(name(), maxLength())}
                        </div>
                      </button>
                    }
                    content={
                      <PopupPreview
                        mouseEnter={() => {}}
                        mouseLeave={() => {}}
                        documentInfo={{
                          id: accessibleItem().id,
                          type: blockName() as BlockName,
                          params: {},
                          isOpenable: true,
                        }}
                      />
                    }
                  />
                );
              }}
            </Match>
            <Match when={loadedItem().access === 'no_access'}>
              <ButtonNoAccess
                class={props.class}
                iconClass={props.iconClass}
                textClass={props.textClass}
              />
            </Match>
            <Match when={loadedItem().access === 'does_not_exist'}>
              <ButtonDeleted
                class={props.class}
                iconClass={props.iconClass}
                textClass={props.textClass}
              />
            </Match>
          </Switch>
        )}
      </Match>
    </Switch>
  );
}

export function InlineItemPreview(props: ItemEntity) {
  const { item, name, ItemEntityIcon } = useItemPreviewData(() => props);

  return (
    <Switch>
      <Match when={item().loading}>
        <InlineLoading />
      </Match>
      <Match when={matches(item(), (i) => !i.loading)}>
        {(loadedItem) => (
          <Switch>
            <Match when={matches(loadedItem(), isAccessiblePreviewItem)}>
              <span class="inline-flex min-w-0 max-w-full items-baseline gap-1 align-baseline">
                <span class="relative top-[0.125em] inline-flex size-[1em] shrink-0">
                  <ItemEntityIcon size="fill" />
                </span>
                <span class="min-w-0 truncate text-ink underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">
                  {truncateString(name(), 80)}
                </span>
              </span>
            </Match>
            <Match when={loadedItem().access === 'no_access'}>
              <InlineNoAccess />
            </Match>
            <Match when={loadedItem().access === 'does_not_exist'}>
              <InlineDeleted />
            </Match>
          </Switch>
        )}
      </Match>
    </Switch>
  );
}