feat(designer): structural refactor scaffold (PanelsContainer, DesignerRoot, ActionLibraryPanel, InspectorPanel, FlowListView, BottomStatusBar)

This commit is contained in:
2025-08-11 16:43:58 -04:00
parent 779c639465
commit 245150e9ef
8 changed files with 2259 additions and 3 deletions

View File

@@ -0,0 +1,339 @@
"use client";
import React, { useCallback, useMemo } from "react";
import {
Save,
RefreshCw,
Download,
Hash,
AlertTriangle,
CheckCircle2,
UploadCloud,
Wand2,
Sparkles,
GitBranch,
Keyboard,
} from "lucide-react";
import { Button } from "~/components/ui/button";
import { Badge } from "~/components/ui/badge";
import { Separator } from "~/components/ui/separator";
import { cn } from "~/lib/utils";
import { useDesignerStore } from "../state/store";
/**
* BottomStatusBar
*
* Compact, persistent status + quick-action bar for the Experiment Designer.
* Shows:
* - Validation / drift / unsaved state
* - Short design hash & version
* - Aggregate counts (steps / actions)
* - Last persisted hash (if available)
* - Quick actions (Save, Validate, Export, Command Palette)
*
* The bar is intentionally UI-only: callback props are used so that higher-level
* orchestration (e.g. DesignerRoot / Shell) controls actual side effects.
*/
export interface BottomStatusBarProps {
onSave?: () => void;
onValidate?: () => void;
onExport?: () => void;
onOpenCommandPalette?: () => void;
onToggleVersionStrategy?: () => void;
className?: string;
saving?: boolean;
validating?: boolean;
exporting?: boolean;
/**
* Optional externally supplied last saved Date for relative display.
*/
lastSavedAt?: Date;
}
export function BottomStatusBar({
onSave,
onValidate,
onExport,
onOpenCommandPalette,
onToggleVersionStrategy,
className,
saving,
validating,
exporting,
lastSavedAt,
}: BottomStatusBarProps) {
/* ------------------------------------------------------------------------ */
/* Store Selectors */
/* ------------------------------------------------------------------------ */
const steps = useDesignerStore((s) => s.steps);
const lastPersistedHash = useDesignerStore((s) => s.lastPersistedHash);
const currentDesignHash = useDesignerStore((s) => s.currentDesignHash);
const lastValidatedHash = useDesignerStore((s) => s.lastValidatedHash);
const pendingSave = useDesignerStore((s) => s.pendingSave);
const versionStrategy = useDesignerStore((s) => s.versionStrategy);
const autoSaveEnabled = useDesignerStore((s) => s.autoSaveEnabled);
const actionCount = useMemo(
() => steps.reduce((sum, st) => sum + st.actions.length, 0),
[steps],
);
const hasUnsaved = useMemo(
() =>
Boolean(currentDesignHash) &&
currentDesignHash !== lastPersistedHash &&
!pendingSave,
[currentDesignHash, lastPersistedHash, pendingSave],
);
const validationStatus = useMemo<"unvalidated" | "valid" | "drift">(() => {
if (!currentDesignHash || !lastValidatedHash) return "unvalidated";
if (currentDesignHash !== lastValidatedHash) return "drift";
return "valid";
}, [currentDesignHash, lastValidatedHash]);
const shortHash = useMemo(
() => (currentDesignHash ? currentDesignHash.slice(0, 8) : "—"),
[currentDesignHash],
);
const lastPersistedShort = useMemo(
() => (lastPersistedHash ? lastPersistedHash.slice(0, 8) : null),
[lastPersistedHash],
);
/* ------------------------------------------------------------------------ */
/* Derived Display Helpers */
/* ------------------------------------------------------------------------ */
function formatRelative(date?: Date): string {
if (!date) return "—";
const now = Date.now();
const diffMs = now - date.getTime();
if (diffMs < 30_000) return "just now";
const mins = Math.floor(diffMs / 60_000);
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.floor(hrs / 24);
return `${days}d ago`;
}
const relSaved = formatRelative(lastSavedAt);
const validationBadge = (() => {
switch (validationStatus) {
case "valid":
return (
<Badge
variant="outline"
className="border-green-400 text-green-600 dark:text-green-400"
title="Validated (hash stable)"
>
<CheckCircle2 className="mr-1 h-3 w-3" />
Validated
</Badge>
);
case "drift":
return (
<Badge
variant="destructive"
className="border-amber-400 bg-amber-50 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400"
title="Drift since last validation"
>
<AlertTriangle className="mr-1 h-3 w-3" />
Drift
</Badge>
);
default:
return (
<Badge variant="outline" title="Not validated yet">
<Hash className="mr-1 h-3 w-3" />
Unvalidated
</Badge>
);
}
})();
const unsavedBadge =
hasUnsaved && !pendingSave ? (
<Badge
variant="outline"
className="border-orange-300 text-orange-600 dark:text-orange-400"
title="Unsaved changes"
>
Unsaved
</Badge>
) : null;
const savingIndicator =
pendingSave || saving ? (
<Badge
variant="secondary"
className="animate-pulse"
title="Saving changes"
>
<RefreshCw className="mr-1 h-3 w-3 animate-spin" />
Saving
</Badge>
) : null;
/* ------------------------------------------------------------------------ */
/* Handlers */
/* ------------------------------------------------------------------------ */
const handleSave = useCallback(() => {
if (onSave) onSave();
}, [onSave]);
const handleValidate = useCallback(() => {
if (onValidate) onValidate();
}, [onValidate]);
const handleExport = useCallback(() => {
if (onExport) onExport();
}, [onExport]);
const handlePalette = useCallback(() => {
if (onOpenCommandPalette) onOpenCommandPalette();
}, [onOpenCommandPalette]);
const handleToggleVersionStrategy = useCallback(() => {
if (onToggleVersionStrategy) onToggleVersionStrategy();
}, [onToggleVersionStrategy]);
/* ------------------------------------------------------------------------ */
/* Render */
/* ------------------------------------------------------------------------ */
return (
<div
className={cn(
"border-border/60 bg-muted/40 backdrop-blur supports-[backdrop-filter]:bg-muted/30",
"flex h-10 w-full flex-shrink-0 items-center gap-3 border-t px-3 text-xs",
"font-medium",
className,
)}
aria-label="Designer status bar"
>
{/* Left Cluster: Validation & Hash */}
<div className="flex items-center gap-2">
{validationBadge}
{unsavedBadge}
{savingIndicator}
<Separator orientation="vertical" className="h-4" />
<div
className="flex items-center gap-1 font-mono text-[11px]"
title="Current design hash"
>
<Hash className="h-3 w-3 text-muted-foreground" />
{shortHash}
{lastPersistedShort && lastPersistedShort !== shortHash && (
<span
className="text-muted-foreground/70"
title="Last persisted hash"
>
/ {lastPersistedShort}
</span>
)}
</div>
</div>
{/* Middle Cluster: Aggregate Counts */}
<div className="flex items-center gap-3 text-muted-foreground">
<div
className="flex items-center gap-1"
title="Steps in current design"
>
<GitBranch className="h-3 w-3" />
{steps.length} steps
</div>
<div
className="flex items-center gap-1"
title="Total actions across all steps"
>
<Sparkles className="h-3 w-3" />
{actionCount} actions
</div>
<div
className="hidden items-center gap-1 sm:flex"
title="Auto-save setting"
>
<UploadCloud className="h-3 w-3" />
{autoSaveEnabled ? "auto-save on" : "auto-save off"}
</div>
<div
className="hidden cursor-pointer items-center gap-1 sm:flex"
title={`Version strategy: ${versionStrategy}`}
onClick={handleToggleVersionStrategy}
>
<Wand2 className="h-3 w-3" />
{versionStrategy.replace(/_/g, " ")}
</div>
<div
className="hidden items-center gap-1 text-[10px] font-normal tracking-wide text-muted-foreground/80 md:flex"
title="Relative time since last save"
>
Saved {relSaved}
</div>
</div>
{/* Flexible Spacer */}
<div className="flex-1" />
{/* Right Cluster: Quick Actions */}
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-7 px-2"
disabled={!hasUnsaved && !pendingSave}
onClick={handleSave}
aria-label="Save (s)"
>
<Save className="mr-1 h-3 w-3" />
Save
</Button>
<Button
variant="ghost"
size="sm"
className="h-7 px-2"
onClick={handleValidate}
disabled={validating}
aria-label="Validate (v)"
>
<RefreshCw
className={cn(
"mr-1 h-3 w-3",
validating && "animate-spin",
)}
/>
Validate
</Button>
<Button
variant="ghost"
size="sm"
className="h-7 px-2"
onClick={handleExport}
disabled={exporting}
aria-label="Export (e)"
>
<Download className="mr-1 h-3 w-3" />
Export
</Button>
<Separator orientation="vertical" className="mx-1 h-4" />
<Button
variant="outline"
size="sm"
className="h-7 px-2"
onClick={handlePalette}
aria-label="Command Palette (⌘K)"
>
<Keyboard className="mr-1 h-3 w-3" />
Commands
</Button>
</div>
</div>
);
}
export default BottomStatusBar;

View File

@@ -0,0 +1,389 @@
"use client";
import React, {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type ReactNode,
} from "react";
import { cn } from "~/lib/utils";
/**
* PanelsContainer
*
* Structural layout component for the Experiment Designer refactor.
* Provides:
* - Optional left + right side panels (resizable + collapsible)
* - Central workspace (always present)
* - Persistent panel widths (localStorage)
* - Keyboard-accessible resize handles
* - Minimal DOM repaint during drag (inline styles)
*
* NOT responsible for:
* - Business logic or data fetching
* - Panel content semantics (passed via props)
*
* Accessibility:
* - Resize handles are <button> elements with aria-label
* - Keyboard: ArrowLeft / ArrowRight adjusts width by step
*/
const STORAGE_KEY = "hristudio-designer-panels-v1";
interface PersistedLayout {
left: number;
right: number;
leftCollapsed: boolean;
rightCollapsed: boolean;
}
export interface PanelsContainerProps {
left?: ReactNode;
center: ReactNode;
right?: ReactNode;
/**
* Initial (non-collapsed) widths in pixels.
* If panels are omitted, their widths are ignored.
*/
initialLeftWidth?: number;
initialRightWidth?: number;
/**
* Minimum / maximum constraints to avoid unusable panels.
*/
minLeftWidth?: number;
minRightWidth?: number;
maxLeftWidth?: number;
maxRightWidth?: number;
/**
* Whether persistence to localStorage should be skipped (e.g. SSR preview)
*/
disablePersistence?: boolean;
/**
* ClassName pass-through for root container
*/
className?: string;
}
interface DragState {
edge: "left" | "right";
startX: number;
startWidth: number;
}
export function PanelsContainer({
left,
center,
right,
initialLeftWidth = 280,
initialRightWidth = 340,
minLeftWidth = 200,
minRightWidth = 260,
maxLeftWidth = 520,
maxRightWidth = 560,
disablePersistence = false,
className,
}: PanelsContainerProps) {
const hasLeft = Boolean(left);
const hasRight = Boolean(right);
/* ------------------------------------------------------------------------ */
/* State */
/* ------------------------------------------------------------------------ */
const [leftWidth, setLeftWidth] = useState(initialLeftWidth);
const [rightWidth, setRightWidth] = useState(initialRightWidth);
const [leftCollapsed, setLeftCollapsed] = useState(false);
const [rightCollapsed, setRightCollapsed] = useState(false);
const dragRef = useRef<DragState | null>(null);
const frameReq = useRef<number | null>(null);
/* ------------------------------------------------------------------------ */
/* Persistence */
/* ------------------------------------------------------------------------ */
useLayoutEffect(() => {
if (disablePersistence) return;
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return;
const parsed = JSON.parse(raw) as PersistedLayout;
if (typeof parsed.left === "number") setLeftWidth(parsed.left);
if (typeof parsed.right === "number") setRightWidth(parsed.right);
if (typeof parsed.leftCollapsed === "boolean") {
setLeftCollapsed(parsed.leftCollapsed);
}
if (typeof parsed.rightCollapsed === "boolean") {
setRightCollapsed(parsed.rightCollapsed);
}
} catch {
/* noop */
}
}, [disablePersistence]);
const persist = useCallback(
(next?: Partial<PersistedLayout>) => {
if (disablePersistence) return;
const snapshot: PersistedLayout = {
left: leftWidth,
right: rightWidth,
leftCollapsed,
rightCollapsed,
...next,
};
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(snapshot));
} catch {
/* noop */
}
},
[disablePersistence, leftWidth, rightWidth, leftCollapsed, rightCollapsed],
);
useEffect(() => {
persist();
}, [leftWidth, rightWidth, leftCollapsed, rightCollapsed, persist]);
/* ------------------------------------------------------------------------ */
/* Drag Handlers */
/* ------------------------------------------------------------------------ */
const onPointerMove = useCallback(
(e: PointerEvent) => {
if (!dragRef.current) return;
const { edge, startX, startWidth } = dragRef.current;
const delta = e.clientX - startX;
if (edge === "left") {
let next = startWidth + delta;
next = Math.max(minLeftWidth, Math.min(maxLeftWidth, next));
if (next !== leftWidth) {
if (frameReq.current) cancelAnimationFrame(frameReq.current);
frameReq.current = requestAnimationFrame(() => setLeftWidth(next));
}
} else if (edge === "right") {
let next = startWidth - delta;
next = Math.max(minRightWidth, Math.min(maxRightWidth, next));
if (next !== rightWidth) {
if (frameReq.current) cancelAnimationFrame(frameReq.current);
frameReq.current = requestAnimationFrame(() => setRightWidth(next));
}
}
},
[
leftWidth,
rightWidth,
minLeftWidth,
maxLeftWidth,
minRightWidth,
maxRightWidth,
],
);
const endDrag = useCallback(() => {
dragRef.current = null;
window.removeEventListener("pointermove", onPointerMove);
window.removeEventListener("pointerup", endDrag);
}, [onPointerMove]);
const startDrag = useCallback(
(edge: "left" | "right", e: React.PointerEvent<HTMLButtonElement>) => {
e.preventDefault();
if (edge === "left" && leftCollapsed) return;
if (edge === "right" && rightCollapsed) return;
dragRef.current = {
edge,
startX: e.clientX,
startWidth: edge === "left" ? leftWidth : rightWidth,
};
window.addEventListener("pointermove", onPointerMove);
window.addEventListener("pointerup", endDrag);
},
[leftWidth, rightWidth, leftCollapsed, rightCollapsed, onPointerMove, endDrag],
);
/* ------------------------------------------------------------------------ */
/* Collapse / Expand */
/* ------------------------------------------------------------------------ */
const toggleLeft = useCallback(() => {
if (!hasLeft) return;
setLeftCollapsed((c) => {
const next = !c;
if (next === false && leftWidth < minLeftWidth) {
setLeftWidth(initialLeftWidth);
}
return next;
});
}, [hasLeft, leftWidth, minLeftWidth, initialLeftWidth]);
const toggleRight = useCallback(() => {
if (!hasRight) return;
setRightCollapsed((c) => {
const next = !c;
if (next === false && rightWidth < minRightWidth) {
setRightWidth(initialRightWidth);
}
return next;
});
}, [hasRight, rightWidth, minRightWidth, initialRightWidth]);
/* Keyboard resizing (focused handle) */
const handleKeyResize = useCallback(
(edge: "left" | "right", e: React.KeyboardEvent<HTMLButtonElement>) => {
const step = e.shiftKey ? 24 : 12;
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
e.preventDefault();
if (edge === "left" && !leftCollapsed) {
setLeftWidth((w) => {
const delta = e.key === "ArrowLeft" ? -step : step;
return Math.max(minLeftWidth, Math.min(maxLeftWidth, w + delta));
});
} else if (edge === "right" && !rightCollapsed) {
setRightWidth((w) => {
const delta = e.key === "ArrowLeft" ? -step : step;
return Math.max(minRightWidth, Math.min(maxRightWidth, w + delta));
});
}
} else if (e.key === "Enter" || e.key === " ") {
if (edge === "left") toggleLeft();
else toggleRight();
}
},
[
leftCollapsed,
rightCollapsed,
minLeftWidth,
maxLeftWidth,
minRightWidth,
maxRightWidth,
toggleLeft,
toggleRight,
],
);
/* ------------------------------------------------------------------------ */
/* Render */
/* ------------------------------------------------------------------------ */
return (
<div
className={cn(
"flex h-full w-full select-none overflow-hidden",
className,
)}
aria-label="Designer panel layout"
>
{/* Left Panel */}
{hasLeft && (
<div
className={cn(
"relative flex h-full flex-shrink-0 flex-col border-r bg-background/50 transition-[width] duration-150",
leftCollapsed ? "w-0 border-r-0" : "w-[--panel-left-width]",
)}
style={
leftCollapsed
? undefined
: ({ ["--panel-left-width" as string]: `${leftWidth}px` } as React.CSSProperties)
}
>
{!leftCollapsed && (
<div className="flex-1 overflow-hidden">{left}</div>
)}
</div>
)}
{/* Left Resize Handle */}
{hasLeft && !leftCollapsed && (
<button
type="button"
aria-label="Resize left panel (Enter to toggle collapse)"
onPointerDown={(e) => startDrag("left", e)}
onKeyDown={(e) => handleKeyResize("left", e)}
className="hover:bg-accent/40 focus-visible:ring-ring group relative z-10 h-full w-1 cursor-col-resize outline-none focus-visible:ring-2"
>
<span className="bg-border absolute inset-y-0 left-0 w-px" />
<span className="bg-border/0 group-hover:bg-border absolute inset-y-0 right-0 w-px transition-colors" />
</button>
)}
{/* Collapse / Expand Toggle (Left) */}
{hasLeft && (
<button
type="button"
aria-label={leftCollapsed ? "Expand left panel" : "Collapse left panel"}
onClick={toggleLeft}
className={cn(
"text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute top-2 z-20 rounded border bg-background/95 px-1.5 py-0.5 text-[10px] font-medium shadow-sm outline-none focus-visible:ring-2",
leftCollapsed ? "left-1" : "left-2",
)}
>
{leftCollapsed ? "»" : "«"}
</button>
)}
{/* Center (Workspace) */}
<div className="relative flex min-w-0 flex-1 flex-col overflow-hidden">
<div className="flex-1 overflow-hidden">{center}</div>
</div>
{/* Right Resize Handle */}
{hasRight && !rightCollapsed && (
<button
type="button"
aria-label="Resize right panel (Enter to toggle collapse)"
onPointerDown={(e) => startDrag("right", e)}
onKeyDown={(e) => handleKeyResize("right", e)}
className="hover:bg-accent/40 focus-visible:ring-ring group relative z-10 h-full w-1 cursor-col-resize outline-none focus-visible:ring-2"
>
<span className="bg-border absolute inset-y-0 right-0 w-px" />
<span className="bg-border/0 group-hover:bg-border absolute inset-y-0 left-0 w-px transition-colors" />
</button>
)}
{/* Right Panel */}
{hasRight && (
<div
className={cn(
"relative flex h-full flex-shrink-0 flex-col border-l bg-background/50 transition-[width] duration-150",
rightCollapsed ? "w-0 border-l-0" : "w-[--panel-right-width]",
)}
style={
rightCollapsed
? undefined
: ({ ["--panel-right-width" as string]: `${rightWidth}px` } as React.CSSProperties)
}
>
{!rightCollapsed && (
<div className="flex-1 overflow-hidden">{right}</div>
)}
</div>
)}
{/* Collapse / Expand Toggle (Right) */}
{hasRight && (
<button
type="button"
aria-label={
rightCollapsed ? "Expand right panel" : "Collapse right panel"
}
onClick={toggleRight}
className={cn(
"text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute top-2 z-20 rounded border bg-background/95 px-1.5 py-0.5 text-[10px] font-medium shadow-sm outline-none focus-visible:ring-2",
rightCollapsed ? "right-1" : "right-2",
)}
>
{rightCollapsed ? "«" : "»"}
</button>
)}
</div>
);
}
export default PanelsContainer;