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.

26.6 KB
Raw Blame
import { CollapsibleSection } from '@app/components/view-shell/CollapsibleSection';
import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';
import { usePreference } from '@app/preferences/use-preference';
import { useMaybeBlockAliasedName } from '@core/block';
import { Resize, ResizeZoneContext } from '@core/component/Resize/Resize';
import { registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { isMobile } from '@core/mobile/isMobile';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import ArrowLeft from '@icon/system/regular/arrow-left.svg';
import CircleDashedEmpty from '@icon/system/regular/circle-dashed.svg';
import InfoIcon from '@icon/system/regular/info.svg';
import SidePanelIcon from '@icon/system/regular/sidebar-simple.svg';
import { Accordion } from '@kobalte/core/accordion';
import { Button, ButtonGroup, Panel, Scroll } from '@ui';
import { cn } from '@ui/utils/classname';
import {
  type Accessor,
  children,
  createEffect,
  createMemo,
  createSignal,
  For,
  type JSX,
  onCleanup,
  onMount,
  type ParentProps,
  type Setter,
  Show,
  Suspense,
  useContext,
} from 'solid-js';
import { Portal } from 'solid-js/web';
import { Transition } from 'solid-transition-group';
import { HeaderActionGroup } from '../HeaderActionGroup';
import { MobileDrawer } from '../mobile/MobileDrawer';
import { HeaderIsland } from '../split-layout/components/HeaderIsland';
import { SplitHeaderRight } from '../split-layout/components/SplitHeader';
import { useSplitPanel } from '../split-layout/layoutUtils';
import {
  SidePanelContext,
  type SidePanelContextType,
  type SidePanelSectionEntry,
} from './context';
import { registerSidePanelInstance } from './registry';

const NARROW_THRESHOLD_PX = 1224;
const SIDE_MIN_PX = 320;
const SIDE_MAX_PX = 380;
const MAIN_MIN_PX = 320;
// The floating card's width, and its inset from the pane's top and right.
const FLOATING_WIDTH_PX = 320;
const FLOATING_INSET_PX = 12;
/**
 * Room to leave on the right so an open floating card covers nothing, for
 * content that makes room for it where the pane is wide enough.
 */
const FLOATING_CLEARANCE_PX = FLOATING_WIDTH_PX + 2 * FLOATING_INSET_PX;

/**
 * Wide-mode open state for a side panel.
 *
 * With a `persistKey`, the user's show/hide choice is remembered across
 * visits under a per-block localStorage key; without one the panel falls back
 * to a plain signal that resets to `defaultOpen` on every mount.
 *
 * Only wide mode is persisted. Narrow mode renders the panel as a full-screen
 * overlay on top of the content, so restoring it open would hide the content
 * the user came back to.
 */
function createWideOpenState(
  persistKey: string | undefined,
  defaultOpen: boolean
): [Accessor<boolean>, Setter<boolean>] {
  if (persistKey === undefined) return createSignal(defaultOpen);
  return usePreference(`macro:pref:side-panel:open:${persistKey}`, {
    default: defaultOpen,
  });
}

/**
 * Owns side-panel state so controls and chrome can sit outside the horizontal
 * Layout row while still operating on the same panel.
 */
function Root(
  props: ParentProps<{
    defaultOpen?: boolean;
    persistKey?: string;
    floating?: boolean;
  }>
) {
  const splitPanel = useSplitPanel();
  const content = splitPanel?.handle.content();
  const persistKey =
    props.persistKey ??
    useMaybeBlockAliasedName() ??
    (content?.type === 'component' ? content.id : content?.type);
  const [sections, setSections] = createSignal<SidePanelSectionEntry[]>([]);
  const [openIds, setOpenIds] = createSignal<string[]>([]);
  const [headerActionsMount, setHeaderActionsMount] =
    createSignal<HTMLDivElement>();
  // Independent open state per mode so wide and narrow can have different
  // defaults (and the user's preference in one mode doesn't bleed into the
  // other after a resize).
  const [isWideOpen, setIsWideOpen] = createWideOpenState(
    persistKey,
    props.defaultOpen ?? true
  );
  const [isOverlayOpen, setIsOverlayOpen] = createSignal(false);
  // Stay closed until the layout has measured its actual split width.
  const [isOverlayMode, setIsOverlayMode] = createSignal(true);
  const updateLayoutMode: Setter<boolean> = (next) => {
    const overlay = typeof next === 'function' ? next(isOverlayMode()) : next;
    if (overlay !== isOverlayMode()) setIsOverlayOpen(false);
    return setIsOverlayMode(() => overlay);
  };

  const isOpen = () => (isOverlayMode() ? isOverlayOpen() : isWideOpen());
  const setIsOpen = (next: boolean | ((prev: boolean) => boolean)) => {
    const setter = isOverlayMode() ? setIsOverlayOpen : setIsWideOpen;
    setter(typeof next === 'function' ? next : () => next);
  };
  const toggle = () => setIsOpen((prev) => !prev);

  // Let global chrome shortcuts (cmd+.) hide/show this panel alongside the
  // app sidebar.
  onCleanup(registerSidePanelInstance({ setIsOpen, isOverlayMode }));

  const register = (entry: SidePanelSectionEntry) => {
    setSections((prev) => {
      const next = prev.filter((s) => s.id !== entry.id);
      next.push(entry);
      return next;
    });
    if (entry.defaultOpen) {
      setOpenIds((prev) =>
        prev.includes(entry.id) ? prev : [...prev, entry.id]
      );
    }
  };

  const unregister = (id: string) => {
    setSections((prev) => prev.filter((s) => s.id !== id));
    setOpenIds((prev) => prev.filter((v) => v !== id));
  };

  const hasSections = createMemo(() => sections().length > 0);
  if (splitPanel?.splitHotkeyScope) {
    registerHotkey({
      hotkey: ']',
      scopeId: splitPanel.splitHotkeyScope,
      hotkeyToken: TOKENS.block.toggleSidePanel,
      description: 'Toggle Side Panel',
      keyDownHandler: () => {
        if (!hasSections()) return false;
        toggle();
        return true;
      },
    });
  }

  const ctx: SidePanelContextType = {
    headerActionsMount,
    setHeaderActionsMount,
    register,
    unregister,
    sections,
    hasSections,
    isOpen,
    setIsOpen,
    toggle,
    isOverlayMode,
    setIsOverlayMode: updateLayoutMode,
    setOpenSectionIds: setOpenIds,
    openSectionIds: openIds,
    isFloating: () => props.floating ?? false,
  };

  return (
    <SidePanelContext.Provider value={ctx}>
      {props.children}
    </SidePanelContext.Provider>
  );
}

/**
 * Horizontal content row for a block that opts in to a right-side panel.
 *
 * The side panel renders beside the main content in wide layouts and as an
 * overlay in narrow layouts. Sections declared as descendants register with
 * the nearest `<SidePanel.Root>`. For backwards compatibility, Layout creates
 * its own Root when one is not already present.
 */
function Layout(
  props: ParentProps<{
    defaultOpen?: boolean;
    persistKey?: string;
    headerToggle?: boolean;
    /** Render the panel over the block instead of reserving horizontal space. */
    floating?: boolean;
  }>
) {
  const parentContext = useContext(SidePanelContext);

  const Panels = () => {
    const ctx = useContext(SidePanelContext);
    if (!ctx) {
      throw new Error('<SidePanel.Layout> must be inside <SidePanel.Root>');
    }

    return (
      <>
        <Show when={props.headerToggle ?? true}>
          <SidePanelHeaderToggle />
        </Show>
        <Resize.Zone direction="horizontal" gutter={0} resizable={false}>
          <SidePanelLayoutInner
            sections={ctx.sections}
            openIds={ctx.openSectionIds}
            setOpenIds={ctx.setOpenSectionIds}
            isOpen={ctx.isOpen}
            setIsOpen={ctx.setIsOpen}
            setIsOverlayMode={ctx.setIsOverlayMode}
            floating={props.floating ?? ctx.isFloating()}
          >
            {props.children}
          </SidePanelLayoutInner>
        </Resize.Zone>
      </>
    );
  };

  return (
    <Show
      when={parentContext}
      fallback={
        <Root
          defaultOpen={props.defaultOpen}
          persistKey={props.persistKey}
          floating={props.floating}
        >
          <Panels />
        </Root>
      }
    >
      <Panels />
    </Show>
  );
}

function SidePanelLayoutInner(
  props: ParentProps<{
    sections: Accessor<SidePanelSectionEntry[]>;
    openIds: Accessor<string[]>;
    setOpenIds: (ids: string[]) => void;
    isOpen: Accessor<boolean>;
    setIsOpen: (next: boolean | ((prev: boolean) => boolean)) => void;
    setIsOverlayMode: Setter<boolean>;
    floating: boolean;
  }>
) {
  const resolved = children(() => props.children);
  const zoneCtx = useContext(ResizeZoneContext);

  if (!zoneCtx) {
    throw new Error('SidePanelLayoutInner must be rendered inside Resize.Zone');
  }

  const isNarrow = createMemo(
    () => isMobile() || zoneCtx.size() < NARROW_THRESHOLD_PX
  );
  const hasSections = createMemo(() => props.sections().length > 0);

  createEffect(() =>
    props.setIsOverlayMode(props.floating || isTouchDevice() || isNarrow())
  );

  const showSplit = createMemo(
    () =>
      !isTouchDevice() &&
      !props.floating &&
      !isNarrow() &&
      hasSections() &&
      props.isOpen()
  );
  const showOverlay = createMemo(
    () =>
      !isTouchDevice() &&
      !props.floating &&
      isNarrow() &&
      hasSections() &&
      props.isOpen()
  );
  const showFloating = createMemo(
    () => !isTouchDevice() && props.floating && hasSections() && props.isOpen()
  );

  return (
    <>
      <Resize.Panel id="side-panel-main" minSize={MAIN_MIN_PX} index={0}>
        {resolved()}
      </Resize.Panel>
      <Show when={showSplit()}>
        <Resize.Panel
          id="side-panel-side"
          minSize={SIDE_MIN_PX}
          maxSize={SIDE_MAX_PX}
          index={1}
        >
          <div class="relative flex size-full min-h-0 flex-col z-split-panel-chrome">
            <SidePanelOutlet
              sections={props.sections}
              openIds={props.openIds}
              setOpenIds={props.setOpenIds}
            />
          </div>
        </Resize.Panel>
      </Show>
      <Show when={showOverlay()}>
        <div
          class={cn(
            'absolute inset-0 flex flex-col bg-surface z-split-panel-chrome'
          )}
        >
          <Scroll>
            {/* Full-frame mobile: the overlay spans the whole panel, so the
                content must clear the floating header islands + status bar. */}
            <div class="w-full max-w-2xl mx-auto min-w-0 touch:pt-(--mobile-content-inset-top)">
              <div class="px-2 pt-2">
                <Button
                  variant="ghost"
                  size="sm"
                  class="gap-2 px-2 text-ink-muted"
                  onClick={() => props.setIsOpen(false)}
                >
                  <ArrowLeft class="size-4" />
                  Back to content
                </Button>
              </div>
              <SidePanelOutlet
                sections={props.sections}
                openIds={props.openIds}
                setOpenIds={props.setOpenIds}
              />
            </div>
          </Scroll>
        </div>
      </Show>
      <Show when={isTouchDevice()}>
        <MobileDrawer
          side="bottom"
          open={hasSections() && props.isOpen()}
          onOpenChange={props.setIsOpen}
          preventScroll={false}
          preventScrollbarShift={false}
        >
          <MobileDrawer.Portal>
            <MobileDrawer.Overlay />
            <MobileDrawer.Content aria-label="Item details">
              <MobileDrawer.Handle />
              <MobileDrawer.ScrollBody>
                <SidePanelOutlet
                  floating
                  scrollable={false}
                  sections={props.sections}
                  openIds={props.openIds}
                  setOpenIds={props.setOpenIds}
                />
              </MobileDrawer.ScrollBody>
            </MobileDrawer.Content>
          </MobileDrawer.Portal>
        </MobileDrawer>
      </Show>
      <Show when={props.floating && !isTouchDevice()}>
        <div class="absolute inset-0 z-split-panel-chrome pointer-events-none">
          <Show when={showFloating()}>
            <div
              class="absolute inset-0 pointer-events-auto bg-transparent"
              onClick={() => props.setIsOpen(false)}
            />
          </Show>
          <Transition
            appear
            enterActiveClass="transition-[opacity,translate] duration-120 ease-out motion-reduce:duration-0"
            enterClass="opacity-0 translate-x-1"
            enterToClass="opacity-100 translate-x-0"
            exitActiveClass="transition-opacity duration-70 ease-out motion-reduce:duration-0"
            exitClass="opacity-100"
            exitToClass="opacity-0"
          >
            <Show when={showFloating()}>
              <aside
                aria-label="Block details"
                inert={!showFloating()}
                class="absolute flex max-w-full flex-col overflow-hidden rounded-xl border border-edge-frame bg-surface shadow-xl pointer-events-auto"
                style={{
                  top: `${FLOATING_INSET_PX}px`,
                  right: `${FLOATING_INSET_PX}px`,
                  width: `min(${FLOATING_WIDTH_PX}px, calc(100% - ${2 * FLOATING_INSET_PX}px))`,
                  'max-height': `calc(100% - ${2 * FLOATING_INSET_PX}px)`,
                }}
                onClick={(event) => event.stopPropagation()}
              >
                <SidePanelOutlet
                  floating
                  sections={props.sections}
                  openIds={props.openIds}
                  setOpenIds={props.setOpenIds}
                />
              </aside>
            </Show>
          </Transition>
        </div>
      </Show>
    </>
  );
}

function Toggle(props: { size?: 'sm' | 'md' } = {}) {
  const ctx = useContext(SidePanelContext);
  if (!ctx) {
    throw new Error('<SidePanel.Toggle> must be inside <SidePanel.Root>');
  }
  const iconSize = () =>
    isTouchDevice() || props.size === 'md' ? 'icon-md' : 'icon-sm';

  return (
    <Show when={ctx.hasSections()}>
      <HeaderActionGroup label="Details" size={props.size}>
        <ButtonGroup.Button
          variant="ghost"
          size={iconSize()}
          aria-label={ctx.isOpen() ? 'Hide details' : 'Show details'}
          class={cn(
            isTouchDevice() &&
              'border-0 hover:bg-transparent! active:bg-transparent! focus-visible:bg-transparent! active:text-accent',
            isTouchDevice() && ctx.isOpen() && 'text-accent'
          )}
          tooltip={{
            content: isTouchDevice()
              ? ctx.isOpen()
                ? 'Hide details'
                : 'Show details'
              : ctx.isOpen()
                ? 'Hide Side Panel'
                : 'Show Side Panel',
            hotkey: TOKENS.block.toggleSidePanel,
          }}
          aria-haspopup={isTouchDevice() ? 'dialog' : undefined}
          aria-expanded={ctx.isOpen()}
          onClick={() => ctx.toggle()}
        >
          <Show
            when={isTouchDevice()}
            fallback={
              <SidePanelIcon
                class={cn(
                  'size-4 shrink-0 rotate-180',
                  ctx.isOpen() && 'text-accent'
                )}
              />
            }
          >
            <InfoIcon
              class={cn('size-6 shrink-0', ctx.isOpen() && 'text-accent')}
            />
          </Show>
        </ButtonGroup.Button>
      </HeaderActionGroup>
    </Show>
  );
}

/**
 * Keeps action state in the owning block while rendering it before Share.
 * Wrap the actions in `HeaderActionGroup` islands; a split button keeps its own frame.
 */
function HeaderActions(props: ParentProps) {
  const ctx = useContext(SidePanelContext);
  return (
    <Show when={ctx?.headerActionsMount()}>
      {(mount) => <Portal mount={mount()}>{props.children}</Portal>}
    </Show>
  );
}

function HeaderActionsOutlet() {
  const ctx = useContext(SidePanelContext);
  onCleanup(() => ctx?.setHeaderActionsMount(undefined));
  return (
    <Show when={ctx}>
      <div
        ref={ctx?.setHeaderActionsMount}
        data-side-panel-header-actions
        class="flex shrink-0 items-center gap-2 touch:gap-1 empty:hidden [&>div]:contents"
      />
    </Show>
  );
}

function SidePanelHeaderToggle() {
  const panel = useSplitPanel();
  const ctx = useContext(SidePanelContext);
  if (!ctx) {
    throw new Error('<SidePanelHeaderToggle> must be inside <SidePanel.Root>');
  }

  return (
    <Show when={ctx.hasSections()}>
      <Show when={!isTouchDevice() && !panel?.isInlinePreview}>
        <SplitHeaderRight>
          <div class="order-[1001] flex shrink-0 items-center">
            <Toggle />
          </div>
        </SplitHeaderRight>
      </Show>
      <Show when={isTouchDevice() || panel?.isInlinePreview}>
        <SplitHeaderRight>
          <div class="order-last flex items-center">
            <HeaderIsland
              class={cn(
                'size-10 justify-center !px-0',
                ctx.isOpen() && 'text-accent'
              )}
            >
              <Toggle />
            </HeaderIsland>
          </div>
        </SplitHeaderRight>
      </Show>
    </Show>
  );
}

function SidePanelOutlet(props: {
  floating?: boolean;
  scrollable?: boolean;
  sections: Accessor<SidePanelSectionEntry[]>;
  openIds: Accessor<string[]>;
  setOpenIds: (ids: string[]) => void;
}) {
  // Sort by `order` ascending; sections without an explicit order go after
  // ordered ones, preserving registration order via the stable sort.
  const sortedSections = createMemo(() =>
    [...props.sections()].sort((a, b) => {
      const ao = a.order ?? Number.MAX_SAFE_INTEGER;
      const bo = b.order ?? Number.MAX_SAFE_INTEGER;
      return ao - bo;
    })
  );

  const Sections = () => (
    <Accordion
      multiple
      collapsible
      value={props.openIds()}
      onChange={(value) => props.setOpenIds(value as string[])}
      class={cn(
        'flex flex-col min-h-0',
        props.floating ? 'p-0 gap-0' : 'p-2 gap-2'
      )}
    >
      <For each={sortedSections().filter((section) => !section.footer)}>
        {(section) => section.component(props.floating ?? false)}
      </For>
    </Accordion>
  );

  return (
    <Show
      when={props.floating}
      fallback={
        <Scroll class="flex flex-col min-h-0">
          <Metadata />
          <Sections />
        </Scroll>
      }
    >
      <div
        class={cn(
          'min-h-0',
          props.scrollable !== false && 'overflow-y-auto overscroll-contain'
        )}
      >
        <Metadata />
        <Sections />
      </div>
    </Show>
  );

  function Metadata() {
    return (
      <For each={sortedSections().filter((section) => section.footer)}>
        {(section) => section.component(props.floating ?? false)}
      </For>
    );
  }
}

/** Unheaded metadata appears before the panel's interactive sections. */
function Footer(props: ParentProps) {
  const ctx = useContext(SidePanelContext);
  if (!ctx)
    throw new Error('<SidePanel.Footer> must be inside <SidePanel.Root>');
  onMount(() => {
    ctx.register({
      id: 'metadata-footer',
      title: 'Metadata',
      defaultOpen: false,
      footer: true,
      component: () => (
        <section
          aria-label="Details"
          class="border-b border-edge-muted p-3 text-xs leading-relaxed text-ink-muted"
        >
          <Suspense fallback={<Loading />}>{props.children}</Suspense>
        </section>
      ),
    });
    onCleanup(() => ctx.unregister('metadata-footer'));
  });
  return null;
}

/** Native section composition; defer body content until the accordion opens. */
export type SidePanelSectionLayout = (
  content: () => JSX.Element,
  actions?: JSX.Element
) => JSX.Element;
/**
 * A collapsible section that registers itself with the nearest SidePanel.Root.
 *
 * The section component returns null in place; its children are rendered
 * inside the side panel's Accordion. Children evaluate lazily when the
 * panel renders the section, so they only mount when the panel is visible.
 *
 * Use `render` when a provider must own both header actions and body content.
 * Must be a descendant of `<SidePanel.Root>`. A standalone Layout creates one.
 */
function Section(
  props: ParentProps<{
    id: string;
    title: JSX.Element;
    defaultOpen?: boolean;
    /** Render order — lower numbers appear first. */
    order?: number;
    /**
     * Optional controls rendered at the right edge while the section is open,
     * outside the collapse trigger. Keep them visible without hover.
     */
    actions?: JSX.Element;
    /** Compose header and body beneath a shared provider without a portal. */
    render?: (layout: SidePanelSectionLayout) => JSX.Element;
  }>
) {
  const ctx = useContext(SidePanelContext);
  if (!ctx) {
    throw new Error('<SidePanel.Section> must be inside <SidePanel.Root>');
  }

  onMount(() => {
    ctx.register({
      id: props.id,
      title: props.title,
      defaultOpen: props.defaultOpen ?? false,
      order: props.order,
      component: (floating) => (
        <Accordion.Item
          value={props.id}
          class={cn(
            'group/sidebar-section',
            floating && 'border-b border-edge-muted last:border-b-0'
          )}
        >
          <Show
            when={floating}
            fallback={
              <Panel
                depth={2}
                style={{ height: 'auto' }}
                class="rounded-xl bg-surface"
              >
                <SectionContent />
              </Panel>
            }
          >
            <SectionContent />
          </Show>
        </Accordion.Item>
      ),
    });
    onCleanup(() => ctx.unregister(props.id));
  });
  return null;

  function SectionContent() {
    const renderSection: SidePanelSectionLayout = (content, actions) => {
      const resolvedActions = children(() =>
        actions === undefined ? props.actions : actions
      );
      return (
        <>
          <Accordion.Header class="flex min-w-0 items-center gap-1">
            <Accordion.Trigger class="flex min-w-0 flex-1 items-center gap-1 rounded-lg p-3 text-left text-xs font-medium leading-5 text-ink-muted outline-none transition-colors group-hover/sidebar-section:text-ink focus-visible:outline-2 focus-visible:outline-accent">
              <span class="min-w-0 truncate">{props.title}</span>
              <CollapsibleSection.Indicator class="touch:opacity-100 group-focus-within/sidebar-section:opacity-100" />
            </Accordion.Trigger>
            <Show when={resolvedActions.toArray().length > 0}>
              <div class="hidden shrink-0 items-center pr-3 group-data-expanded/sidebar-section:flex">
                {resolvedActions()}
              </div>
            </Show>
          </Accordion.Header>
          <Accordion.Content class="group/content overflow-hidden data-expanded:animate-accordion-down data-closed:animate-accordion-up">
            <Suspense fallback={<Loading />}>
              <div class="px-3 pb-3 text-sm opacity-0 group-data-expanded/content:opacity-100 transition-opacity duration-150 ease-out">
                {content()}
              </div>
            </Suspense>
          </Accordion.Content>
        </>
      );
    };

    if (props.render) return props.render(renderSection);
    return renderSection(() => props.children);
  }
}

/** Hook to access the SidePanel context for toggling visibility */
function useSidePanel() {
  const ctx = useContext(SidePanelContext);
  if (!ctx) {
    return null;
  }
  return {
    isOpen: ctx.isOpen,
    setIsOpen: ctx.setIsOpen,
    toggle: ctx.toggle,
    isOverlayMode: ctx.isOverlayMode,
    hasSections: ctx.hasSections,
    setOpenSectionIds: ctx.setOpenSectionIds,
    openSectionIds: ctx.openSectionIds,
  };
}

/** Indicates whether the current subtree has a SidePanel.Layout ancestor. */
function _useHasSidePanel(): boolean {
  return useContext(SidePanelContext) !== undefined;
}

/**
 * Two-column label/value grid. The left column width is driven by the
 * `--sidepanel-label-width` CSS variable so multiple grids in the same panel
 * align their labels; rows have a fixed 2rem height for vertical rhythm.
 *
 * Use with `<SidePanel.Row>` children.
 */
function Grid(props: ParentProps<{ class?: string }>) {
  return (
    <div
      class={cn(
        'grid grid-cols-[var(--sidepanel-label-width,auto)_1fr] gap-x-3 items-center text-xs auto-rows-[1.75rem]',
        props.class
      )}
    >
      {props.children}
    </div>
  );
}

/**
 * A label/value row inside a `<SidePanel.Grid>`. Renders two siblings into the
 * parent grid: a muted, truncating label on the left and the value on the
 * right.
 */
function Row(props: ParentProps<{ label: JSX.Element }>) {
  return (
    <>
      <span
        class="text-ink-muted truncate self-center"
        title={typeof props.label === 'string' ? props.label : undefined}
      >
        {props.label}
      </span>
      <div class="flex items-center gap-2 min-w-0 self-center">
        {props.children}
      </div>
    </>
  );
}

/**
 * Shared pill className used for value cells in the side panel. Exported as a
 * string so callers can compose it onto their own trigger (e.g. a Property
 * EditTrigger, an anchor, a button) without nesting elements.
 */
const pillClass = cn(
  'inline-flex items-center gap-1.5 min-w-0 max-w-[30ch]',
  'px-2 py-1 leading-tight text-left rounded-full'
);

/** Static pill wrapper. For interactive triggers, use `pillClass` directly. */
function Pill(props: ParentProps<{ class?: string }>) {
  return (
    <div class={cn(pillClass, 'w-fit', props.class)}>{props.children}</div>
  );
}

/** Empty-state indicator used inside value pills. */
function EmptyPill(props: { label?: JSX.Element } = {}) {
  return (
    <span class="inline-flex min-w-0 items-center gap-1.5 opacity-50">
      <Show when={!props.label}>
        <CircleDashedEmpty class="size-3 shrink-0" />
      </Show>
      <Show when={props.label}>
        <span class="truncate">{props.label}</span>
      </Show>
    </span>
  );
}

/**
 * Canonical loading fallback for side panel sections. Sized to roughly match
 * a one-row section so its appearance doesn't shift the panel layout.
 */
function Loading() {
  return (
    <div class="flex items-center justify-center p-2">
      <ListSkeleton.Bar class="h-2 w-full" />
    </div>
  );
}

/**
 * Section title with a muted count suffix. Renders `Label (n)` when `count > 0`,
 * otherwise just the label.
 */
function CountTitle(props: { label: JSX.Element; count: number }) {
  return (
    <>
      {props.label}
      <Show when={props.count > 0}>
        {' '}
        <span class="text-ink-extra-muted">({props.count})</span>
      </Show>
    </>
  );
}

function Card(props: ParentProps) {
  return (
    <div class="rounded-lg border border-edge-muted bg-inset overflow-hidden">
      <div class="divide-y divide-edge-muted">{props.children}</div>
    </div>
  );
}

export const SidePanel = {
  Root,
  Layout,
  Toggle,
  HeaderActions,
  HeaderActionsOutlet,
  Section,
  Footer,
  Grid,
  Row,
  Pill,
  pillClass,
  EmptyPill,
  Loading,
  CountTitle,
  Card,
  FLOATING_CLEARANCE_PX,
};
export { useSidePanel };