Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/automation/automationUi.tsx
T

250 lines
10 KiB
TypeScript

import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import {
FeatherBell,
FeatherCalendarClock,
FeatherCheckSquare,
FeatherChevronRight,
FeatherClock,
FeatherFileText,
FeatherGitBranch,
FeatherGlobe,
FeatherInbox,
FeatherMail,
FeatherRepeat,
FeatherSend,
FeatherTarget,
FeatherUserCog,
FeatherUserPlus,
FeatherZap,
} from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import type { LocaleFormatters } from "~/locale/format";
/** Shared UI helpers for the WF-P12 automation screens (S01-S04 + dialogs). */
export function AutomationStatusBadge({ status }: { status: string }): React.JSX.Element {
const { t } = useTranslation();
return (
<BadgeFeedback farbe={statusBadgeTone(status)} size="small">
{automationStatusLabel(t, status)}
</BadgeFeedback>
);
}
export function automationStatusLabel(t: TFunction, status: string): string {
return localizedValue(t, `automation.status.${status}`, "automation.values.unknownStatus");
}
export function statusBadgeTone(status: string): React.ComponentProps<typeof BadgeFeedback>["farbe"] {
if (status === "success" || status === "completed" || status === "active" || status === "enabled") return "subtle-positive";
if (status === "failed" || status === "error") return "subtle-negative";
if (status === "paused" || status === "skipped" || status === "waiting" || status === "retrying") return "subtle-warning";
if (status === "running" || status === "queued") return "subtle-information";
return "subtle-neutral";
}
/** The page header now lives in the shared screen chrome and is used app-wide. */
export { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
export function FilterPill({
label,
count,
active = false,
dotClassName,
onClick,
}: {
label: React.ReactNode;
count?: number | string;
active?: boolean;
dotClassName?: string;
onClick?: () => void;
}): React.JSX.Element {
return (
<button
type="button"
onClick={onClick}
className={
active
? "flex items-center gap-1.5 rounded-round border border-solid border-brand-brand-border-solid-default bg-brand-brand-secondary-surface-subtle px-3 py-1"
: "flex items-center gap-1.5 rounded-round border border-solid border-border-default bg-surface-neutral-secondary px-3 py-1 hover:bg-surface-neutral-tertiary"
}
>
{dotClassName ? <span className={`flex h-1.5 w-1.5 flex-none rounded-round ${dotClassName}`} /> : null}
<span
className={
active
? "text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary"
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary"
}
>
{label}
</span>
{count !== undefined ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{count}</span> : null}
</button>
);
}
/** Translates a node key (e.g. "forms.submitted") via the automation.nodes catalog keys. */
export function nodeTitle(t: TFunction, nodeKey: string | null | undefined): string {
if (!nodeKey) return t("automation.values.noTrigger");
return localizedValue(t, `automation.nodes.${nodeKey.replaceAll(".", "_")}.title`, "automation.values.unknownNode");
}
/**
* `errorText` is what the executor threw: usually a catalog key with a
* technical detail appended ("automation.execution.unsupportedNode:
* portal.invite_user"). Rendering it verbatim puts an i18n key in front of the
* user, so translate the key part and name the offending block in plain
* language. Anything that is not key-shaped is a real sentence and stays.
*/
const ERROR_CATALOG_KEY = /^([a-z][A-Za-z0-9]*(?:\.[A-Za-z0-9_]+)+)(?::\s*(.+))?$/s;
const I18N_KEY = /^[a-z][A-Za-z0-9]*(?:\.[A-Za-z0-9_]+)+$/;
/** Translate stored catalog keys without ever exposing a missing key in the UI. */
export function localizedValue(t: TFunction, value: string, fallbackKey: string): string {
const translated = t(value, { defaultValue: "" });
if (translated) return translated;
return I18N_KEY.test(value) ? t(fallbackKey) : value;
}
export function errorMessage(t: TFunction, errorText: string | null | undefined): string | null {
if (!errorText?.trim()) return null;
const match = ERROR_CATALOG_KEY.exec(errorText.trim());
if (!match) return t("automation.values.unknownError");
const [, key, detail] = match;
const translated = t(key, { defaultValue: "" });
if (!translated) return t("automation.values.unknownError");
if (!detail) return translated;
return `${translated} (${nodeTitle(t, detail)})`;
}
/**
* Renders the guard that auto-paused a rule (M02). `anomalyText` holds the i18n
* key the guard stored; the meter numbers travel separately so the sentence
* stays translatable instead of being assembled on the server.
*/
export function anomalyMessage(
t: TFunction,
rule: {
readonly anomalyText: string | null;
readonly anomalyCount: number | null;
readonly anomalyWindowMinutes: number | null;
readonly triggerKey: string | null;
}
): string | null {
if (!rule.anomalyText) return null;
const translated = t(rule.anomalyText, {
defaultValue: "",
// Not `count`: that name switches i18next into plural resolution.
triggerCount: rule.anomalyCount ?? 0,
minutes: rule.anomalyWindowMinutes ?? 0,
trigger: nodeTitle(t, rule.triggerKey),
});
return translated || t("automation.values.unknownWarning");
}
const NODE_GROUP_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
crm: FeatherUserCog,
lead: FeatherUserPlus,
sales: FeatherTarget,
projects: FeatherGitBranch,
email: FeatherMail,
forms: FeatherFileText,
booking: FeatherCalendarClock,
calendar: FeatherCalendarClock,
time: FeatherClock,
webhook: FeatherGlobe,
notification: FeatherBell,
http: FeatherGlobe,
task: FeatherCheckSquare,
condition: FeatherGitBranch,
delay: FeatherClock,
loop: FeatherRepeat,
inbox: FeatherInbox,
kwp: FeatherSend,
};
export function nodeIcon(nodeKey: string | null | undefined): React.ComponentType<{ className?: string }> {
if (!nodeKey) return FeatherZap;
const group = nodeKey.split(".")[0];
return NODE_GROUP_ICONS[group] ?? FeatherZap;
}
/** Formats a millisecond duration in the compact style of the Subframe designs. */
export function formatDurationMs(t: TFunction, formatters: LocaleFormatters, durationMs: number | null | undefined): string {
if (durationMs == null) return t("automation.values.notAvailable");
if (durationMs < 1000) return t("automation.values.durationMs", { value: formatters.number(durationMs) });
if (durationMs < 60_000) {
return t("automation.values.durationSeconds", { value: formatters.number(durationMs / 1000, { maximumFractionDigits: 1 }) });
}
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1000);
return t("automation.values.durationMinutes", { minutes: formatters.number(minutes), seconds: formatters.number(seconds) });
}
/** Renders a plain (non-array, non-null) record as an uppercase-labelled key/value block. */
export function KeyValueBlock({ label, value }: { label: React.ReactNode; value: unknown }): React.JSX.Element | null {
const entries = recordEntries(value);
if (entries.length === 0) return null;
return (
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-2 rounded-md bg-surface-neutral-tertiary px-4 py-3 mobile:w-full">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 uppercase tracking-wide text-text-neutral-tertiary">{label}</span>
{entries.map(([key, entryValue]) => (
<div key={key} className="flex w-full items-start gap-3">
<span className="w-32 flex-none break-words text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{key}</span>
<span className="grow shrink-0 basis-0 break-words text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary">
{stringifyValue(entryValue)}
</span>
</div>
))}
</div>
);
}
export function recordEntries(value: unknown): [string, unknown][] {
if (!value || typeof value !== "object" || Array.isArray(value)) return [];
return Object.entries(value as Record<string, unknown>);
}
function stringifyValue(value: unknown): string {
if (value == null) return "—";
if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean") return String(value);
return JSON.stringify(value);
}
/** Trigger -> action chain chips used on the S04 cards and the M03 mini catalog. */
export function ChainChips({
chain,
}: {
chain: readonly { readonly kind: string; readonly summaryKey: string; readonly nodeType: string }[];
}): React.JSX.Element | null {
const { t } = useTranslation();
if (chain.length === 0) return null;
return (
<div className="flex w-full flex-wrap items-center gap-1.5">
{chain.map((step, index) => {
const StepIcon = nodeIcon(step.nodeType);
return (
<span key={`${step.nodeType}-${index}`} className="contents">
{index > 0 ? <FeatherChevronRight className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-subtle" /> : null}
<span className="flex items-center gap-1.5 rounded-md bg-surface-neutral-tertiary px-2 py-1">
<StepIcon
className={
step.kind === "trigger"
? "text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-icon-feedback-information"
: "text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-icon-neutral-tertiary"
}
/>
<span className="whitespace-nowrap text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-secondary">
{t(step.summaryKey, { defaultValue: nodeTitle(t, step.nodeType) })}
</span>
</span>
</span>
);
})}
</div>
);
}