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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | 119x 119x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 175x 132x 9x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 132x 2x 175x 175x 175x 175x 10x 5x 5x 4x 168x 168x 168x 29x 168x 168x 197x 10x 336x 168x 5x 5x 285x 168x 282x 168x 504x 168x 504x 168x 168x 34x 1x 270x 168x 272x 672x 504x 5x 5x 5x 5x 5x 15x 5x 25x | import {
Copy,
EllipsisVertical,
Pencil,
Plus,
Search,
Trash2,
X,
} from "lucide-react";
import { Dispatch, SetStateAction, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { Button } from "@/ahuora-design-system/ui/button";
import DebouncedInput from "@/ahuora-design-system/ui/debounced-input";
import DeleteDialog from "@/ahuora-design-system/ui/delete-dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/ahuora-design-system/ui/dropdown-menu";
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 {
FlowsheetTemplateTypeEnum,
ProjectConfigSummaryRead,
type ScenarioResultCopySummary,
useCoreFlowsheetsDestroyMutation,
useCoreFlowsheetsPartialUpdateMutation,
useFlowsheetCopyCreateMutation,
useLazyFlowsheetCopyPreviewRetrieveQuery,
} from "@/api/apiStore.gen";
import {
type CloneValidationProblem,
parseCloneValidationProblem,
} from "@/flowsheet-cloning/cloneValidation";
import { DuplicateWithResultsDialog } from "@/flowsheet-cloning/DuplicateWithResultsDialog";
import { FlowsheetCloneProblemDialog } from "@/flowsheet-cloning/FlowsheetCloneProblemDialog";
import { useFlowsheetAccess } from "@/hooks/flowsheetAccess";
import { useFlowsheetRevisionPreview } from "@/hooks/flowsheetRevisionPreview";
import {
useCreateFlowsheetInCurrentProject,
useCurrentProject,
useFlowsheetId,
} from "@/hooks/project";
import { FlowsheetRevisionsMenu } from "./Revisions/FlowsheetRevisionsMenu";
function formatDate(value?: string | null) {
Iif (!value) return "Never saved";
return new Date(value).toLocaleDateString("en-GB", {
year: "numeric",
month: "short",
day: "numeric",
});
}
const ProjectContent = () => {
const nav = useNavigate();
const activeFlowsheetId = useFlowsheetId();
const { data: project, isLoading, error } = useCurrentProject();
const { createInCurrentProject } = useCreateFlowsheetInCurrentProject();
const flowsheetAccess = useFlowsheetAccess();
const { isPreview } = useFlowsheetRevisionPreview();
const [searchedObj, setSearchedObj] = useState<string>("");
const [deleteTarget, setDeleteTarget] = useState<{
id: number;
name: string;
} | null>(null);
const [deleteFlowsheet] = useCoreFlowsheetsDestroyMutation();
const [copyFlowsheet, copyFlowsheetResult] = useFlowsheetCopyCreateMutation();
const [loadCopyPreview] = useLazyFlowsheetCopyPreviewRetrieveQuery();
const [duplicateConfirmation, setDuplicateConfirmation] = useState<{
config: ProjectConfigSummaryRead;
summary: ScenarioResultCopySummary;
} | null>(null);
const [duplicateFailure, setDuplicateFailure] = useState<{
config: ProjectConfigSummaryRead;
problem: CloneValidationProblem;
includeScenarioResults: boolean;
} | null>(null);
const [renameTarget, setRenameTarget] =
useState<ProjectConfigSummaryRead | null>(null);
const [renameValue, setRenameValue] = useState("");
const [renameFlowsheet] = useCoreFlowsheetsPartialUpdateMutation();
const searchTerm = searchedObj.trim().toLowerCase();
const filteredConfigurations =
project?.configurations?.filter((config) =>
(config.name ?? "").toLowerCase().includes(searchTerm),
) ?? [];
const canEditProject = flowsheetAccess?.can_edit ?? false;
const openConfiguration = (configId: number) => {
nav(`/project/${configId}/flowsheet?content=project`);
};
const handleCreateInCurrentProject = async () => {
try {
const flowsheet = await createInCurrentProject();
openConfiguration(flowsheet.id);
} catch (error) {
console.error("Failed to create a new flowsheet.");
}
};
const handleDeleteFlowsheet = async () => {
Iif (!deleteTarget) return;
try {
const response = await deleteFlowsheet({
id: String(deleteTarget.id),
}).unwrap();
setDeleteTarget(null);
if (response?.active_flowsheet_id) {
openConfiguration(response.active_flowsheet_id);
}
} catch (error) {
console.error("Failed to delete flowsheet:", error);
}
};
const handleDuplicateFlowsheet = async (
config: ProjectConfigSummaryRead,
repairLegacyFormulaUnits = false,
includeScenarioResults = false,
) => {
setDuplicateConfirmation(null);
try {
const newFlowsheetId = await copyFlowsheet({
flowsheet: config.id,
...(repairLegacyFormulaUnits ? { repairLegacyFormulaUnits: true } : {}),
...(includeScenarioResults ? { includeScenarioResults: true } : {}),
}).unwrap();
if (!newFlowsheetId) {
throw new Error("No flowsheet id returned from duplication");
}
toast.success("Flowsheet Duplicated Successfully");
setDuplicateFailure(null);
openConfiguration(newFlowsheetId);
} catch (error) {
const problem = parseCloneValidationProblem(error);
if (problem) {
setDuplicateFailure({ config, problem, includeScenarioResults });
return;
}
console.error("Failed to duplicate flowsheet:", error);
toast.error("Something went wrong when duplicating the flowsheet");
}
};
const requestDuplicateFlowsheet = async (
config: ProjectConfigSummaryRead,
) => {
try {
const summary = await loadCopyPreview({ flowsheet: config.id }).unwrap();
if (summary.has_results) {
setDuplicateConfirmation({ config, summary });
return;
}
await handleDuplicateFlowsheet(config);
} catch {
toast.error("Scenario result counts could not be loaded");
}
};
return (
<div className="h-full w-full">
<div className="flex flex-col h-full w-full pt-2">
{/* Imported Data is temporarily hidden until project import support is complete. */}
{/* Search Bar Section */}
<div className="px-4 items-center flex justify-between gap-4">
<div className="relative flex-1 my-2">
<Input
name="search"
placeholder="Search flowsheets"
type="text"
startIcon={Search}
onChange={(e) => setSearchedObj(e.target.value)}
value={searchedObj}
className="pr-10"
aria-label="search-projectPanel"
/>
{searchedObj && (
<Button
variant="ghost"
size="icon"
className="absolute right-1 top-1/2 transform -translate-y-1/2 hover:bg-transparent hover:text-neutral-500"
onClick={() => setSearchedObj("")}
aria-label="Clear search"
>
<X size={18} />
</Button>
)}
</div>
</div>
<ScrollArea className="flex-1 min-w-0">
<div className="min-w-0 w-full overflow-hidden">
{/* This Project Section */}
<div className="mt-0 h-full">
<div className="px-4 pb-4">
<div className="mb-3 flex items-center justify-between">
<p className="text-xs text-muted-foreground">
{filteredConfigurations.length} flowsheet
{filteredConfigurations.length === 1 ? "" : "s"}
</p>
{project?.savedDate && (
<span className="text-xs text-muted-foreground">
Updated {formatDate(project.savedDate)}
</span>
)}
</div>
{/* Configurations List */}
{isLoading ? (
<p className="italic text-muted-foreground">
Loading project...
</p>
) : error ? (
<p className="italic text-destructive">
Failed to load project flowsheets.
</p>
) : filteredConfigurations.length === 0 ? (
<p className="italic text-muted-foreground">
{searchTerm
? "No matching flowsheets."
: "No flowsheets yet."}
</p>
) : (
<div
className="flex flex-col gap-1.5"
aria-label="flowsheets-list"
>
{filteredConfigurations.map((config) => {
const isActive = config.id === activeFlowsheetId;
const isEditing =
canEditProject && renameTarget?.id === config.id;
const name = config.name || `Flowsheet ${config.id}`;
return (
<div
key={config.id}
aria-label={`flowsheet-${config.id}`}
className={`rounded-md border border-transparent transition-colors ${
isActive
? "border-l-2 border-l-primary bg-secondary/25"
: "hover:bg-secondary/40"
}`}
>
<div className="flex min-w-0 items-center gap-2 px-2.5 py-2">
{isEditing ? (
<div className="min-w-0 flex-1">
<EditableFlowsheetName
id={config.id}
value={renameValue}
isEditing
onCancel={() => setRenameTarget(null)}
onSave={async (nextName) => {
Iif (!canEditProject) return;
await renameFlowsheet({
id: String(config.id),
patchedFlowsheet: { name: nextName },
}).unwrap();
}}
/>
</div>
) : (
<button
type="button"
className="min-w-0 flex-1 rounded-sm text-left text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={`Open ${name}`}
onClick={() => openConfiguration(config.id)}
>
<span className="block truncate">{name}</span>
</button>
)}
{isActive && (
<Badge
variant="success"
size="xs"
borderRadius="round"
className="shrink-0"
aria-label="active-flowsheet-badge"
>
Active
</Badge>
)}
<FlowsheetOverflowMenu
config={config}
canEditProject={canEditProject}
canDuplicate={!isPreview}
setDeleteTarget={setDeleteTarget}
setRenameTarget={setRenameTarget}
setRenameValue={setRenameValue}
onDuplicate={requestDuplicateFlowsheet}
/>
</div>
{isActive &&
config.flowsheet_template_type ===
FlowsheetTemplateTypeEnum.NotTemplate && (
<div className="px-1.5 pb-1.5 pt-0">
<FlowsheetRevisionsMenu
flowsheetId={config.id}
canEdit={canEditProject}
/>
</div>
)}
</div>
);
})}
</div>
)}
</div>
<div className="px-4 pb-4">
<Button
className="w-full"
size="sm"
onClick={handleCreateInCurrentProject}
disabled={!canEditProject}
aria-label="Create New Flowsheet"
>
<Plus /> New Flowsheet
</Button>
</div>
</div>
</div>
</ScrollArea>
<DeleteDialog
projectName={deleteTarget?.name ?? ""}
isOpen={deleteTarget !== null}
onOpenChange={(open) => {
Iif (!open) setDeleteTarget(null);
}}
onCancel={() => setDeleteTarget(null)}
onDelete={handleDeleteFlowsheet}
/>
<FlowsheetCloneProblemDialog
problem={duplicateFailure?.problem ?? null}
scope="flowsheet"
isRepairingAutomatically={copyFlowsheetResult.isLoading}
onDismiss={() => setDuplicateFailure(null)}
onRepairManually={(affectedFlowsheetId) => {
setDuplicateFailure(null);
openConfiguration(affectedFlowsheetId);
}}
onRepairAutomatically={async () => {
if (duplicateFailure) {
await handleDuplicateFlowsheet(
duplicateFailure.config,
true,
duplicateFailure.includeScenarioResults,
);
}
}}
/>
{duplicateConfirmation && (
<DuplicateWithResultsDialog
key={duplicateConfirmation.config.id}
name={
duplicateConfirmation.config.name ??
`Flowsheet ${duplicateConfirmation.config.id}`
}
scope="flowsheet"
summary={duplicateConfirmation.summary}
isDuplicating={copyFlowsheetResult.isLoading}
onCancel={() => setDuplicateConfirmation(null)}
onConfirm={(includeScenarioResults) =>
handleDuplicateFlowsheet(
duplicateConfirmation.config,
false,
includeScenarioResults,
)
}
/>
)}
</div>
</div>
);
};
type DeleteTarget = {
id: number;
name: string;
} | null;
type FlowsheetOverflowMenuProps = {
config: ProjectConfigSummaryRead;
canEditProject: boolean;
canDuplicate: boolean;
setDeleteTarget: Dispatch<SetStateAction<DeleteTarget>>;
setRenameTarget: Dispatch<SetStateAction<ProjectConfigSummaryRead | null>>;
setRenameValue: Dispatch<SetStateAction<string>>;
onDuplicate: (config: ProjectConfigSummaryRead) => void;
};
/** Secondary flowsheet management actions kept out of the primary row content. */
function FlowsheetOverflowMenu({
config,
canEditProject,
canDuplicate,
setDeleteTarget,
setRenameTarget,
setRenameValue,
onDuplicate,
}: FlowsheetOverflowMenuProps) {
const dismissedWithPointerRef = useRef(false);
return (
<DropdownMenu>
<ToolTipCover asChild content="Flowsheet actions">
<DropdownMenuTrigger asChild>
<Button
size="icon"
variant="ghost"
aria-label={`Flowsheet ${config.id} actions`}
className="h-8 w-8 shrink-0"
>
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
</ToolTipCover>
<DropdownMenuContent
align="end"
onPointerDownOutside={() => {
dismissedWithPointerRef.current = true;
}}
onCloseAutoFocus={(event) => {
// Pointer dismissal should preserve the user's clicked target instead
// of refocusing the trigger and opening its tooltip. Keyboard dismissal
// retains Radix's default focus restoration for accessibility.
Iif (dismissedWithPointerRef.current) event.preventDefault();
dismissedWithPointerRef.current = false;
}}
>
<DropdownMenuItem
className="gap-2"
disabled={!canEditProject}
onSelect={() => {
setRenameTarget(config);
setRenameValue(config.name ?? "");
}}
>
<Pencil className="h-4 w-4" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
className="gap-2"
disabled={!canDuplicate}
onSelect={() => onDuplicate(config)}
>
<Copy className="h-4 w-4" />
Duplicate
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="gap-2 text-destructive focus:text-destructive"
disabled={!canEditProject}
onSelect={() =>
setDeleteTarget({
id: config.id,
name: config.name || `Flowsheet ${config.id}`,
})
}
>
<Trash2 className="h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
type EditableFlowsheetNameProps = {
id: number;
value: string;
isEditing: boolean;
onCancel: () => void;
onSave: (nextName: string) => Promise<void>;
};
export function EditableFlowsheetName({
id,
value,
isEditing,
onCancel,
onSave,
}: EditableFlowsheetNameProps) {
if (!isEditing) {
return <span className="block min-w-0 w-full truncate">{value}</span>;
}
return (
<DebouncedInput
autoSelect
value={value}
onUpdate={async (next) => {
const name = String(next).trim();
Iif (!name) return;
await onSave(name);
onCancel();
}}
onBlur={onCancel}
ariaLabel={`rename-Flowsheet-${id}-field`}
className="w-full"
/>
);
}
export default ProjectContent;
|