All files / src/pages/flowsheet-page/flowsheet/revisions FlowsheetRevisionList.tsx

62.06% Statements 36/58
40.5% Branches 32/79
21.42% Functions 3/14
65% Lines 26/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247                                                          103x     52x     52x       10x 10x                   10x                             10x                   52x 62x   10x           10x 52x     62x 72x 72x         26x                               26x 52x 52x 52x                                                                                                   52x               52x                             5x                                                                                                 390x   26x           78x    
import { Check, Loader2, Pencil, RotateCcw, Trash2, X } from "lucide-react";
import { badgeVariants } from "@/ahuora-design-system/ui/badge";
import { Button } from "@/ahuora-design-system/ui/button";
import { Input } from "@/ahuora-design-system/ui/input";
import { ScrollArea } from "@/ahuora-design-system/ui/scroll-area";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import { FlowsheetRevisionRead } from "@/api/apiStore.gen.ts";
import {
  getFlowsheetVersionLabel,
  hasDefaultFlowsheetVersionLabel,
} from "./versionLabels";
 
type FlowsheetRevisionListProps = {
  revisions: FlowsheetRevisionRead[];
  previewedRevisionStateId: number | null;
  canEdit: boolean;
  editingRevisionId: number | null;
  revisionName: string;
  renamePending: boolean;
  onPreview: (revision: FlowsheetRevisionRead) => void;
  onStopPreview: () => void;
  onRestore: (revision: FlowsheetRevisionRead) => void;
  onDelete: (revision: FlowsheetRevisionRead) => void;
  onStartRename: (revision: FlowsheetRevisionRead) => void;
  onCancelRename: () => void;
  onRevisionNameChange: (name: string) => void;
  onSaveRevisionName: () => void;
};
 
const RELATIVE_DATE_LIMIT_MS = 7 * 24 * 60 * 60 * 1000;
 
function revisionCreator(revision: FlowsheetRevisionRead): string {
  const fullName = [revision.creator?.first_name, revision.creator?.last_name]
    .filter(Boolean)
    .join(" ");
  return fullName || revision.creator?.email || "Unknown creator";
}
 
function relativeRevisionDate(value: string, now = new Date()): string {
  const createdAt = new Date(value);
  const elapsedMs = Math.max(0, now.getTime() - createdAt.getTime());
  if (elapsedMs >= RELATIVE_DATE_LIMIT_MS) {
    return createdAt.toLocaleDateString("en-GB", {
      day: "numeric",
      month: "short",
      year:
        createdAt.getFullYear() === now.getFullYear() ? undefined : "numeric",
    });
  }
 
  if (elapsedMs < 60 * 1000) return "Just now";
  const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [
    ["day", 24 * 60 * 60 * 1000],
    ["hour", 60 * 60 * 1000],
    ["minute", 60 * 1000],
  ];
  const [unit, unitMs] =
    units.find(([, size]) => elapsedMs >= size) ?? units[2];
  return new Intl.RelativeTimeFormat("en", { numeric: "always" }).format(
    -Math.floor(elapsedMs / unitMs),
    unit,
  );
}
 
function preciseRevisionDate(value: string): string {
  return new Date(value).toLocaleString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
}
 
/** One revision timestamp with concise copy and exact hover/focus detail. */
function RevisionTimestamp({ value }: { value: string }) {
  const preciseDate = preciseRevisionDate(value);
  return (
    <ToolTipCover
      asChild
      delay={0}
      content={preciseDate}
      contentClassName="px-2 py-1"
    >
      <span
        aria-label={`Created ${preciseDate}`}
        className="text-xs font-normal leading-4"
      >
        {relativeRevisionDate(value)}
      </span>
    </ToolTipCover>
  );
}
 
/** Paginated revision rows with restore, inline rename, and delete actions. */
export function FlowsheetRevisionList({
  revisions,
  previewedRevisionStateId,
  canEdit,
  editingRevisionId,
  revisionName,
  renamePending,
  onPreview,
  onStopPreview,
  onRestore,
  onDelete,
  onStartRename,
  onCancelRename,
  onRevisionNameChange,
  onSaveRevisionName,
}: FlowsheetRevisionListProps) {
  const rows = revisions.map((revision) => {
    const label = getFlowsheetVersionLabel(revision);
    const usesDefaultName = hasDefaultFlowsheetVersionLabel(revision);
    const isPreviewed = previewedRevisionStateId === revision.state_id;
    if (canEdit && editingRevisionId === revision.state_id) {
      return (
        <div
          key={revision.state_id}
          className="flex min-w-0 items-center gap-1 rounded-md bg-secondary/20 p-1"
        >
          <Input
            autoFocus
            value={revisionName}
            maxLength={64}
            aria-label={`Name for Version ${revision.revision_number}`}
            className="h-7 min-w-0 flex-1 px-2 text-sm"
            onChange={(event) => onRevisionNameChange(event.target.value)}
            onKeyDown={(event) => {
              Iif (event.key === "Enter") onSaveRevisionName();
              Iif (event.key === "Escape") onCancelRename();
            }}
          />
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="h-7 w-7 shrink-0"
            aria-label="Save version name"
            disabled={!revisionName.trim() || renamePending}
            onClick={onSaveRevisionName}
          >
            {renamePending ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Check className="h-4 w-4" />
            )}
          </Button>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="h-7 w-7 shrink-0"
            aria-label="Cancel version rename"
            disabled={renamePending}
            onClick={onCancelRename}
          >
            <X className="h-4 w-4" />
          </Button>
        </div>
      );
    }
 
    const content = (
      <>
        <span className="min-w-0 flex-1 truncate font-medium">{label}</span>
        <span className="truncate text-xs font-normal leading-4 text-muted-foreground">
          {!usesDefaultName && <>Version {revision.revision_number} · </>}
          <RevisionTimestamp value={revision.created_at} /> ·{" "}
          {revisionCreator(revision)}
        </span>
      </>
    );
    return (
      <div
        key={revision.state_id}
        className={`group flex min-w-0 items-stretch gap-0.5 rounded-md border transition-colors hover:bg-accent/40 focus-within:bg-accent/40 ${
          isPreviewed
            ? "border-primary/60 bg-primary/10"
            : "border-transparent bg-secondary/20"
        }`}
      >
        <button
          type="button"
          aria-label={`Preview ${label}`}
          aria-current={isPreviewed ? "true" : undefined}
          className="flex min-w-0 flex-1 flex-col items-start gap-0.5 rounded-md px-2.5 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
          onClick={() => onPreview(revision)}
        >
          {content}
        </button>
        {isPreviewed && (
          <button
            type="button"
            aria-label={`Stop previewing ${label}`}
            className={`${badgeVariants({
              variant: "secondary",
              size: "xs",
              borderRadius: "round",
            })} my-auto mr-1 gap-1 px-2 py-0.5`}
            onClick={onStopPreview}
          >
            Previewing
            <X className="h-3 w-3" aria-hidden="true" />
          </button>
        )}
        {canEdit && (
          <>
            <button
              type="button"
              aria-label={`Restore ${label}`}
              className="w-8 shrink-0 rounded-md text-muted-foreground opacity-60 outline-none hover:text-foreground hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring group-hover:opacity-100"
              onClick={() => onRestore(revision)}
            >
              <RotateCcw className="mx-auto h-3.5 w-3.5" />
            </button>
            <button
              type="button"
              aria-label={`Rename ${label}`}
              className="w-8 shrink-0 rounded-md text-muted-foreground opacity-60 outline-none hover:text-foreground hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring group-hover:opacity-100"
              onClick={() => onStartRename(revision)}
            >
              <Pencil className="mx-auto h-3.5 w-3.5" />
            </button>
            <button
              type="button"
              aria-label={`Delete ${label}`}
              className="w-8 shrink-0 rounded-md text-muted-foreground opacity-60 outline-none hover:text-destructive hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring group-hover:opacity-100"
              onClick={() => onDelete(revision)}
            >
              <Trash2 className="mx-auto h-4 w-4" />
            </button>
          </>
        )}
      </div>
    );
  });
 
  return revisions.length > 6 ? (
    <ScrollArea className="h-80 pr-2">
      <div className="space-y-1.5">{rows}</div>
    </ScrollArea>
  ) : (
    <div className="space-y-1.5">{rows}</div>
  );
}