Skip to content

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

Go
11.7 KB
Raw Blame
"use client";

import { memo, type Ref } from "react";
import { useSortable, defaultAnimateLayoutChanges } from "@dnd-kit/sortable";
import type { AnimateLayoutChanges } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { AppLink } from "../../navigation";
import type { Issue, Project,
  IssueProperty,
} from "@multica/core/types";
import { formatDateOnly } from "@multica/core/issues/date";
import { ActorAvatar } from "../../common/actor-avatar";
import { PropertyIcon } from "../../common/property-icon";
import { useWorkspacePaths, issueRouteRef } from "@multica/core/paths";
import { useQuery } from "@tanstack/react-query";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
import { useWorkspaceId } from "@multica/core/hooks";
import { propertyListOptions } from "@multica/core/properties";
import { CustomPropertyValueDisplay } from "./pickers/custom-property-picker";
import { ProjectIcon } from "../../projects/components/project-icon";
import { PriorityIcon } from "./priority-icon";
import { ProgressRing } from "./progress-ring";
import { IssueActionsContextMenu } from "../actions";
import { LabelChip } from "../../labels/label-chip";
import { CustomStatusChip } from "./custom-status-chip";
import { IssueBlockedMarker } from "./issue-blockers";
import { IssueDuplicateOfMarker } from "./issue-duplicates";
import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
import { IssuePullRequestChips, useIssuePullRequestSummaries } from "./pull-request-chips";
import { useIssueSurfaceSelection } from "../surface/selection-context";
import { CURSOR_ROW_CLASS, useIsIssueCursor } from "../surface/issue-cursor";
import {
  PEEKED_ROW_CLASS,
  PEEK_TARGET_ATTR,
  useIsIssuePeeked,
  useIssuePeekLinkProps,
} from "../surface/peek-context";
import { useLocale } from "../../i18n";

export interface ChildProgress {
  done: number;
  total: number;
}

function formatDate(date: string, locale: string): string {
  return formatDateOnly(date, { month: "short", day: "numeric" }, locale);
}

/** A row's position within its status group, for themes that stripe rows. */
export type RowParity = "even" | "odd";

export function rowParity(index: number): RowParity {
  return index % 2 === 0 ? "even" : "odd";
}

function ListRowContent({
  issue,
  parity,
  childProgress,
  project,
  isDragging,
  containerRef,
  containerStyle,
  containerProps,
  checkboxProps,
}: {
  issue: Issue;
  parity: RowParity;
  childProgress?: ChildProgress;
  project?: Project;
  isDragging?: boolean;
  containerRef?: Ref<HTMLDivElement>;
  containerStyle?: React.CSSProperties;
  containerProps?: Record<string, unknown>;
  checkboxProps?: Pick<React.HTMLAttributes<HTMLDivElement>, "onClick" | "onMouseDown" | "onPointerDown">;
}) {
  const locale = useLocale();
  const selection = useIssueSurfaceSelection();
  const peeked = useIsIssuePeeked(issue.id);
  const cursor = useIsIssueCursor(issue.id);
  const peekLinkProps = useIssuePeekLinkProps(issue);
  const selected = selection.selectedIds.has(issue.id);
  const toggle = selection.toggle;
  const p = useWorkspacePaths();
  const storeProperties = useViewStore((s) => s.cardProperties);
  const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);
  const rowWsId = useWorkspaceId();
  const { data: workspaceProperties = [] } = useQuery(propertyListOptions(rowWsId));
  const cardCustomProperties = cardPropertyIds
    .map((id) => workspaceProperties.find((p) => p.id === id))
    .filter((p): p is IssueProperty => !!p && issue.properties?.[p.id] !== undefined);
  const labels = issue.labels ?? [];

  const showProject = storeProperties.project && project;
  const showChildProgress = storeProperties.childProgress && childProgress;
  const showAssignee = storeProperties.assignee && issue.assignee_type && issue.assignee_id;
  const showStartDate = storeProperties.startDate && issue.start_date;
  const showDueDate = storeProperties.dueDate && issue.due_date;
  const showLabels = storeProperties.labels && labels.length > 0;
  const pullRequests = useIssuePullRequestSummaries(issue.id, storeProperties.pullRequests);
  const showPullRequests = storeProperties.pullRequests && pullRequests.length > 0;

  return (
    <IssueActionsContextMenu issue={issue}>
      <div
        ref={containerRef}
        data-slot="issue-list-row"
        data-mc="issue-row"
        data-status={issue.status}
        data-priority={issue.priority}
        data-assignee-type={issue.assignee_type ?? "none"}
        data-parity={parity}
        data-selected={selected ? "true" : "false"}
        {...{ [PEEK_TARGET_ATTR]: issue.id }}
        data-peeked={peeked ? "" : undefined}
        data-cursor={cursor ? "" : undefined}
        style={containerStyle}
        {...containerProps}
        className={`group/row flex h-[var(--issue-row-height)] items-center gap-2 px-[var(--issue-row-padding-x,1rem)] text-body transition-[background-color,color,opacity] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none ${
          selected
            ? "bg-issue-row-selected hover:not-data-[popup-open]:bg-issue-row-selected data-[popup-open]:bg-issue-row-selected"
            : "hover:not-data-[popup-open]:bg-issue-row-hover data-[popup-open]:bg-issue-row-hover data-[cursor]:bg-issue-row-hover"
        } ${PEEKED_ROW_CLASS} ${CURSOR_ROW_CLASS} ${isDragging ? "opacity-30" : ""}`}
      >
        <div
          className="relative flex shrink-0 items-center justify-center w-4 h-4"
          {...checkboxProps}
        >
          {storeProperties.priority && issue.priority !== "none" && (
            <PriorityIcon
              priority={issue.priority}
              className={`transition-opacity duration-100 motion-reduce:transition-none ${
                selected
                  ? "opacity-0"
                  : "group-hover/row:opacity-0 group-focus-within/row:opacity-0"
              }`}
            />
          )}
          <input
            type="checkbox"
            checked={selected}
            onChange={() => toggle(issue.id)}
            className={`absolute inset-0 cursor-pointer accent-primary transition-opacity duration-100 motion-reduce:transition-none ${
              selected
                ? "opacity-100"
                : "opacity-0 group-hover/row:opacity-100 focus-visible:opacity-100"
            }`}
          />
        </div>
        <AppLink
          href={p.issueDetail(issueRouteRef(issue))}
          newTabTitle={issue.identifier}
          className={`flex flex-1 items-center gap-2 min-w-0 ${isDragging ? "pointer-events-none" : ""}`}
          {...peekLinkProps}
        >
          <span className="min-w-16 shrink-0 text-caption text-issue-row-identifier">
            {issue.identifier}
          </span>
          <IssueAgentActivityIndicator issueId={issue.id} />

          <span className="flex min-w-0 flex-1 items-center gap-1.5">
            <span className="truncate">{issue.title}</span>
            {/* Keep custom names visible when this row appears outside a status section. */}
            <CustomStatusChip status={issue.status} className="shrink-0" />
            <IssueBlockedMarker issue={issue} />
            <IssueDuplicateOfMarker issue={issue} insideLink />
            {showChildProgress && (
              <span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5">
                <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>
              </span>
            )}
            {showPullRequests && (
              // Capped so a long PR set never squeezes the title away.
              <IssuePullRequestChips
                pullRequests={pullRequests}
                max={2}
                insideLink
                className="max-w-[40%]"
              />
            )}
            {showLabels && (
              <span className="ml-1.5 hidden md:inline-flex shrink-0 items-center gap-1 max-w-[260px] overflow-hidden">
                {labels.slice(0, 3).map((label) => (
                  <LabelChip key={label.id} label={label} />
                ))}
                {labels.length > 3 && (
                  <span className="text-micro text-muted-foreground">
                    +{labels.length - 3}
                  </span>
                )}
              </span>
            )}
            {cardCustomProperties.length > 0 && (
              <span className="ml-1.5 hidden md:inline-flex shrink-0 items-center gap-1 max-w-[260px] overflow-hidden">
                {cardCustomProperties.slice(0, 3).map((property) => (
                  <span
                    key={property.id}
                    className="inline-flex max-w-[120px] 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>
                ))}
              </span>
            )}
          </span>
          {showProject && (
            <span className="inline-flex shrink-0 items-center gap-1 text-caption text-muted-foreground max-w-[140px]">
              <ProjectIcon project={project} size="sm" />
              <span className="truncate">{project!.title}</span>
            </span>
          )}
          {showStartDate && (
            <span className="shrink-0 text-caption text-muted-foreground">
              {formatDate(issue.start_date!, locale)}
            </span>
          )}
          {showDueDate && (
            <span className="shrink-0 text-caption text-muted-foreground">
              {formatDate(issue.due_date!, locale)}
            </span>
          )}
          {showAssignee && (
            <ActorAvatar
              actorType={issue.assignee_type!}
              actorId={issue.assignee_id!}
              size="sm"
              enableHoverCard
            />
          )}
        </AppLink>
      </div>
    </IssueActionsContextMenu>
  );
}

export const ListRow = memo(function ListRow({
  issue,
  parity,
  childProgress,
  project,
}: {
  issue: Issue;
  parity: RowParity;
  childProgress?: ChildProgress;
  project?: Project;
}) {
  return (
    <ListRowContent
      issue={issue}
      parity={parity}
      childProgress={childProgress}
      project={project}
    />
  );
});

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

const stopDrag = (e: React.SyntheticEvent) => {
  e.stopPropagation();
};

export const DraggableListRow = memo(function DraggableListRow({
  issue,
  parity,
  childProgress,
  project,
  disableSorting,
}: {
  issue: Issue;
  parity: RowParity;
  childProgress?: ChildProgress;
  project?: Project;
  disableSorting?: boolean;
}) {
  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 (
    <ListRowContent
      issue={issue}
      parity={parity}
      childProgress={childProgress}
      project={project}
      isDragging={isDragging}
      containerRef={setNodeRef}
      containerStyle={style}
      containerProps={{ ...attributes, ...listeners }}
      checkboxProps={{ onClick: stopDrag, onMouseDown: stopDrag, onPointerDown: stopDrag }}
    />
  );
});