Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
17.9 KB
Raw Blame
"use client";

import { useCallback, memo } from "react";
import { AppLink } from "../../navigation";
import { useSortable, defaultAnimateLayoutChanges } from "@dnd-kit/sortable";
import type { AnimateLayoutChanges } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { Issue, IssueProperty, Project, UpdateIssueRequest } from "@multica/core/types";
import { useQuery } from "@tanstack/react-query";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useModalStore } from "@multica/core/modals";
import { propertyListOptions } from "@multica/core/properties";
import { CustomPropertyValueDisplay } from "./pickers/custom-property-picker";
import { descriptionPreview } from "./description-preview";
import { formatDateOnly, isPastDateOnly } from "@multica/core/issues/date";
import { CalendarClock, CalendarDays } from "@multica/ui/icons";
import { ActorAvatar } from "../../common/actor-avatar";
import { CardControl } from "../../common/card-control";
import { PropertyIcon } from "../../common/property-icon";
import { useWorkspacePaths, issueRouteRef } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import { useLocale, useT, useTimeAgo } from "../../i18n";
import { ProjectIcon } from "../../projects/components/project-icon";
import { PriorityIcon } from "./priority-icon";
import { PriorityPicker, AssigneePicker, StartDatePicker, DueDatePicker } from "./pickers";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
import { ProgressRing } from "./progress-ring";
import type { ChildProgress } from "./list-row";
import { IssueActionsContextMenu } from "../actions";
import { runConfirmIntent } from "../actions/run-confirm-gate";
import { LabelChip } from "../../labels/label-chip";
import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
import { CustomStatusChip, useIsCustomStatus } from "./custom-status-chip";
import { IssueBlockedMarker } from "./issue-blockers";
import { IssueDuplicateOfMarker } from "./issue-duplicates";
import { IssuePullRequestChips, useIssuePullRequestSummaries } from "./pull-request-chips";
import { useIssueSurfaceActionsOptional } from "../surface/actions-context";
import {
  PEEK_TARGET_ATTR,
  useIsIssuePeeked,
  useIssuePeekActions,
  useIssuePeekLinkProps,
} from "../surface/peek-context";
import { useIsIssueCursor } from "../surface/issue-cursor";
function formatDate(date: string, locale: string): string {
  return formatDateOnly(date, { month: "short", day: "numeric" }, locale);
}

export const BoardCardContent = memo(function BoardCardContent({
  issue,
  editable = false,
  childProgress,
  project,
}: {
  issue: Issue;
  editable?: boolean;
  childProgress?: ChildProgress;
  project?: Project;
}) {
  const { t } = useT("issues");
  const locale = useLocale();
  const timeAgo = useTimeAgo();
  const storeProperties = useViewStore((s) => s.cardProperties);
  const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);
  const viewMode = useViewStore((s) => s.viewMode);
  const grouping = useViewStore((s) => s.grouping);
  const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);
  const cardGrouping =
    viewMode === "board"
      ? grouping
      : viewMode === "swimlane"
        ? swimlaneGrouping
        : null;
  const groupedPropertyId = cardGrouping
    ? propertyIdFromViewKey(cardGrouping)
    : null;
  const cardWsId = useWorkspaceId();
  const { data: workspaceProperties = [] } = useQuery(propertyListOptions(cardWsId));
  // Custom properties toggled on in Display options, in toggle order, only
  // when this issue actually carries a value.
  const cardCustomProperties = cardPropertyIds
    .filter((id) => id !== groupedPropertyId)
    .map((id) => workspaceProperties.find((p) => p.id === id))
    .filter((p): p is IssueProperty => !!p && issue.properties?.[p.id] !== undefined);
  const labels = issue.labels ?? [];

  const surfaceActions = useIssueSurfaceActionsOptional();
  const { entryOf } = useIssueStatuses(cardWsId);
  const openModal = useModalStore((s) => s.open);
  // Card pickers are single-issue writes like the right-click menu on this same
  // card, so handing the issue to an agent confirms first (MUL-6463).
  const handleUpdate = useCallback(
    (updates: Partial<UpdateIssueRequest>) => {
      const intent = runConfirmIntent(issue, updates, { entryOf });
      if (intent) {
        openModal("issue-run-confirm", intent);
        return;
      }
      surfaceActions?.updateIssue(issue.id, updates, {
        errorMessage: t(($) => $.card.update_failed),
      });
    },
    [issue, entryOf, openModal, surfaceActions, t],
  );
  const canEdit = editable && !!surfaceActions;

  const hasAssignee = !!issue.assignee_type && !!issue.assignee_id;
  const showPriority = storeProperties.priority && issue.priority !== "none";
  const showDescription = storeProperties.description && issue.description;
  const showAssigneeSection =
    storeProperties.assignee && cardGrouping !== "assignee" && hasAssignee;
  const showStartDate = storeProperties.startDate && issue.start_date;
  const showDueDate = storeProperties.dueDate && issue.due_date;
  const showProject =
    storeProperties.project && cardGrouping !== "project" && project;
  const showChildProgress = storeProperties.childProgress && childProgress;
  const showLabels = storeProperties.labels && labels.length > 0;
  const pullRequests = useIssuePullRequestSummaries(issue.id, storeProperties.pullRequests);
  const showPullRequests = storeProperties.pullRequests && pullRequests.length > 0;
  // Keeps the chip row from rendering an empty flex container when the status
  // chip is the only thing in it and it decides to render nothing.
  const showCustomStatus = useIsCustomStatus(issue.status);

  const showAssigneeName = showAssigneeSection && hasAssignee && !showStartDate && !showDueDate;
  const showUpdatedHint = showAssigneeName && !showChildProgress;
  const { getActorName } = useActorName();
  const assigneeName =
    showAssigneeName && issue.assignee_type && issue.assignee_id
      ? getActorName(issue.assignee_type, issue.assignee_id)
      : null;

  const priorityLabel = t(($) => $.priority[issue.priority]);
  const priorityIconNode = showPriority ? (
    canEdit ? (
      <CardControl className="flex">
        <PriorityPicker
          priority={issue.priority}
          onUpdate={handleUpdate}
          tooltip={priorityLabel}
          triggerRender={
            <button
              type="button"
              aria-label={priorityLabel}
              className="inline-flex size-5 shrink-0 items-center justify-center rounded-xs hover:bg-muted/60"
            >
              <PriorityIcon priority={issue.priority} />
            </button>
          }
        />
      </CardControl>
    ) : (
      <span
        aria-label={priorityLabel}
        className="inline-flex size-5 shrink-0 items-center justify-center"
      >
        <PriorityIcon priority={issue.priority} />
      </span>
    )
  ) : null;

  // The parent row gives this container the leftover space; min-w-0 and
  // max-w-full make the nested picker trigger respect that limit.
  const assigneeContainerClass = assigneeName
    ? "flex min-w-0 max-w-full items-center"
    : "inline-flex items-center";

  const assigneeInner = hasAssignee ? (
    <span className="flex min-w-0 max-w-full items-center gap-1.5">
      <ActorAvatar
        actorType={issue.assignee_type!}
        actorId={issue.assignee_id!}
        size="sm"
        enableHoverCard
        profileLink={false}
        className="shrink-0"
      />
      {assigneeName && (
        <span className="min-w-0 truncate text-caption text-foreground">{assigneeName}</span>
      )}
    </span>
  ) : (
    <span className="text-caption text-muted-foreground">{t(($) => $.pickers.assignee.trigger_unassigned)}</span>
  );

  const assigneeNode = showAssigneeSection ? (
    canEdit ? (
      <CardControl className={assigneeContainerClass}>
        <AssigneePicker
          assigneeType={issue.assignee_type}
          assigneeId={issue.assignee_id}
          onUpdate={handleUpdate}
          trigger={assigneeInner}
        />
      </CardControl>
    ) : (
      <span className={assigneeContainerClass}>{assigneeInner}</span>
    )
  ) : null;

  const showMetaRow = showAssigneeSection || showStartDate || showDueDate || showChildProgress;
  const showRightMeta = !!showStartDate || !!showDueDate || !!showChildProgress || showUpdatedHint;

  return (
    <div
      data-mc="board-card"
      data-status={issue.status}
      data-priority={issue.priority}
      data-assignee-type={issue.assignee_type ?? "none"}
      className="rounded-board-card border-[0.5px] border-board-card-border bg-board-card py-[var(--board-card-padding-y,var(--space-sm,0.75rem))] px-[var(--board-card-padding-x,0.625rem)] shadow-[var(--board-card-shadow,var(--surface-shadow))] transition-colors group-hover/card:border-foreground/15 group-hover/card:bg-board-card-hover group-data-[popup-open]/card:border-foreground/15 group-data-[popup-open]/card:bg-board-card-hover group-data-[peeked]/card:ring-2 group-data-[peeked]/card:ring-brand/50 group-data-[cursor]/card:border-foreground/15 group-data-[cursor]/card:bg-board-card-hover group-data-[cursor]/card:ring-1 group-data-[cursor]/card:ring-ring/60">
      {/* Row 1: priority + identifier (left), agent activity + assignee (right) */}
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-1.5 min-w-0">
          {priorityIconNode}
          <p className="text-caption text-muted-foreground truncate">{issue.identifier}</p>
          <IssueBlockedMarker issue={issue} />
            <IssueDuplicateOfMarker issue={issue} insideLink />
        </div>
        <IssueAgentActivityIndicator issueId={issue.id} />
      </div>

      {/* Row 2: Title */}
      <p className="mt-1 text-body font-medium leading-snug cjk:leading-normal line-clamp-2">
        {issue.title}
      </p>

      {showDescription && (() => {
        const preview = descriptionPreview(issue.description!);
        if (!preview) return null;
        return (
          <p className="mt-1 text-caption text-muted-foreground line-clamp-1">
            {preview}
          </p>
        );
      })()}

      {/* Chip row: status + project + labels + PRs + custom property values.
          The status chip renders only for a CUSTOM status — the column header
          already names the category. (MUL-6243) */}
      {(showCustomStatus || showProject || showLabels || showPullRequests || cardCustomProperties.length > 0) && (
        <div className="mt-1.5 flex items-center gap-1.5 flex-wrap">
          <CustomStatusChip status={issue.status} />
          {showProject && (
            <span className="inline-flex items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5 text-micro text-muted-foreground max-w-[160px]">
              <ProjectIcon project={project} size="sm" />
              <span className="truncate">{project!.title}</span>
            </span>
          )}
          {showLabels && labels.slice(0, 2).map((label) => (
            <LabelChip key={label.id} label={label} />
          ))}
          {showLabels && labels.length > 2 && (
            <span className="text-micro text-muted-foreground">
              +{labels.length - 2}
            </span>
          )}
          {showPullRequests && (
            <IssuePullRequestChips pullRequests={pullRequests} max={2} insideLink />
          )}
          {cardCustomProperties.map((property) => (
            <span
              key={property.id}
              className="inline-flex max-w-[160px] items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5 text-micro text-muted-foreground"
            >
              <PropertyIcon property={property} className="size-3 text-micro" />
              <CustomPropertyValueDisplay property={property} value={issue.properties?.[property.id]} />
            </span>
          ))}
        </div>
      )}

      {/* Meta row: assignee (left), start date, due date, child progress (right) */}
      {showMetaRow && (
        <div className="mt-2 flex items-center justify-between gap-2">
          {showAssigneeSection && (
            <div className="min-w-0 flex-1">
              {assigneeNode}
            </div>
          )}
          {showRightMeta && (
            <div className="ml-auto flex shrink-0 items-center gap-2">
              {showStartDate && (
                canEdit ? (
                  <CardControl className="flex shrink-0">
                    <StartDatePicker
                      startDate={issue.start_date}
                      onUpdate={handleUpdate}
                      tooltip={t(($) => $.detail.prop_start_date)}
                      trigger={
                        <span className="flex items-center gap-1 text-caption text-muted-foreground">
                          <CalendarClock className="size-3" />
                          {formatDate(issue.start_date!, locale)}
                        </span>
                      }
                    />
                  </CardControl>
                ) : (
                  <span className="flex shrink-0 items-center gap-1 text-caption text-muted-foreground">
                    <CalendarClock className="size-3" />
                    {formatDate(issue.start_date!, locale)}
                  </span>
                )
              )}
              {showDueDate && (
                canEdit ? (
                  <CardControl className="flex shrink-0">
                    <DueDatePicker
                      dueDate={issue.due_date}
                      onUpdate={handleUpdate}
                      tooltip={t(($) => $.detail.prop_due_date)}
                      trigger={
                        <span
                          className={`flex items-center gap-1 text-caption ${
                            isPastDateOnly(issue.due_date)
                              ? "text-destructive"
                              : "text-muted-foreground"
                          }`}
                        >
                          <CalendarDays className="size-3" />
                          {formatDate(issue.due_date!, locale)}
                        </span>
                      }
                    />
                  </CardControl>
                ) : (
                  <span
                    className={`flex shrink-0 items-center gap-1 text-caption ${
                      isPastDateOnly(issue.due_date)
                        ? "text-destructive"
                        : "text-muted-foreground"
                    }`}
                  >
                    <CalendarDays className="size-3" />
                    {formatDate(issue.due_date!, locale)}
                  </span>
                )
              )}
              {showChildProgress && (
                <div className="inline-flex shrink-0 items-center gap-1">
                  <ProgressRing done={childProgress!.done} total={childProgress!.total} size={14} />
                  <span className="text-micro text-muted-foreground tabular-nums font-medium">
                    {childProgress!.done}/{childProgress!.total}
                  </span>
                </div>
              )}
              {showUpdatedHint && (
                <span className="shrink-0 text-caption text-muted-foreground">
                  {t(($) => $.card.updated_ago, { time: timeAgo(issue.updated_at) })}
                </span>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
});

const animateLayoutChanges: AnimateLayoutChanges = (args) => {
  const { isSorting, wasDragging } = args;
  if (isSorting || wasDragging) return false;
  return defaultAnimateLayoutChanges(args);
};

export const DraggableBoardCard = memo(function DraggableBoardCard({
  issue,
  childProgress,
  project,
  disableSorting,
}: {
  issue: Issue;
  childProgress?: ChildProgress;
  project?: Project;
  disableSorting?: boolean;
}) {
  const p = useWorkspacePaths();
  const peek = useIssuePeekActions();
  const peeked = useIsIssuePeeked(issue.id);
  const cursor = useIsIssueCursor(issue.id);
  const peekLinkProps = useIssuePeekLinkProps(issue);
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: issue.id,
    data: { status: issue.status },
    animateLayoutChanges,
    disabled: disableSorting ? { droppable: true } : undefined,
  });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };

  return (
    <IssueActionsContextMenu issue={issue}>
      <div
        ref={setNodeRef}
        style={style}
        data-board-card=""
        {...{ [PEEK_TARGET_ATTR]: issue.id }}
        data-peeked={peeked ? "" : undefined}
        data-cursor={cursor ? "" : undefined}
        {...attributes}
        {...listeners}
        className={`group/card transition-opacity duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none ${isDragging ? "opacity-30" : ""}`}
        onKeyDown={
          peek
            ? (e) => {
                // Space peeks the focused card (the card itself or its link,
                // never a picker button inside it). The board registers no
                // keyboard drag sensor, so Space is free here.
                if (e.key !== " " || e.repeat) return;
                if (e.target !== e.currentTarget && (e.target as HTMLElement).tagName !== "A") return;
                e.preventDefault();
                peek.toggle(issue.id);
              }
            : undefined
        }
      >
        <AppLink
          href={p.issueDetail(issueRouteRef(issue))}
          newTabTitle={issue.identifier}
          className={`group block transition-colors ${isDragging ? "pointer-events-none" : ""}`}
          {...peekLinkProps}
        >
          <BoardCardContent
            issue={issue}
            editable
            childProgress={childProgress}
            project={project}
          />
        </AppLink>
      </div>
    </IssueActionsContextMenu>
  );
});