loopable / web /src /home /ItemTileMenu.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
382942c verified
Raw History Blame Contribute Delete
16.3 kB
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";
import { createPortal } from "react-dom";
import { Pause } from "@phosphor-icons/react/dist/csr/Pause";
import { Play } from "@phosphor-icons/react/dist/csr/Play";
import { TOAST_EVENT, signal } from "../apiContract";
import type { Automation } from "../automation/automationApi";
import { AutomationError, deleteAutomation, patchAutomation } from "../automation/automationApi";
import { AnchoredOverlay, useOverlayLayer } from "../customer-grid/OverlaySurface";
import { MenuLabel } from "../customer-grid/icons";
import { ConfirmDialog } from "../ui/ConfirmDialog";
/** Mutation ports shared by the rail and the Automation home menu. */
export interface AutomationMutationContext {
writing: { current: boolean };
setBusy(id: string): void;
mergeSaved(fresh: Automation): boolean;
load(): Promise<unknown>;
}
export const toggleEnabled = async (a: Automation, context: AutomationMutationContext) => {
const { writing, setBusy, mergeSaved, load } = context;
if (writing.current || a.system) return false;
writing.current = true;
const flipped: Automation = {
...a,
schedule: { ...a.schedule, enabled: !a.schedule.enabled },
};
setBusy(a.id);
const painted = mergeSaved(flipped);
try {
const { automation: fresh } = await patchAutomation(a.id, {
schedule: { cron: a.schedule.cron, enabled: !a.schedule.enabled },
});
if (!fresh || !mergeSaved(fresh)) await load();
return true;
} catch (e) {
if (painted) mergeSaved(a);
signal(TOAST_EVENT, {
text: e instanceof AutomationError ? e.message : "That change was not saved.",
tone: "error",
});
return false;
} finally {
writing.current = false;
setBusy("");
}
};
export const renameAutomation = async (a: Automation, value: string, context: AutomationMutationContext) => {
const name = value.trim();
const { writing, setBusy, mergeSaved, load } = context;
if (!name || name === a.name || writing.current || a.system) return false;
writing.current = true;
setBusy(a.id);
try {
const { automation: fresh } = await patchAutomation(a.id, { name });
if (!fresh || !mergeSaved(fresh)) await load();
return true;
} catch (e) {
signal(TOAST_EVENT, {
text: e instanceof AutomationError ? e.message : "The name was not saved.",
tone: "error",
});
return false;
} finally {
writing.current = false;
setBusy("");
}
};
/** The caller owns confirmation and keeps a refused delete beside its Retry action. */
export const removeAutomation = async (
a: Automation,
context: Pick<AutomationMutationContext, "writing" | "setBusy"> & { onDeleted(id: string): void },
) => {
const { writing, setBusy, onDeleted } = context;
if (writing.current || a.system) return false;
const id = a.id;
writing.current = true;
setBusy(id);
try {
const { itemDeleted } = await import("../starred/starredApi");
await deleteAutomation(id);
onDeleted(id);
itemDeleted({ kind: "automation", id });
return true;
} finally {
writing.current = false;
setBusy("");
}
};
function onRowMenuKey(event: ReactKeyboardEvent<HTMLElement>) {
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
const buttons = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>(
'button[role="menuitem"]:not(:disabled)'
));
if (!buttons.length) return;
event.preventDefault();
const at = buttons.indexOf(document.activeElement as HTMLButtonElement);
const next = event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1
: event.key === "ArrowDown" ? (at + 1) % buttons.length
: (at - 1 + buttons.length) % buttons.length;
buttons[next]?.focus();
}
export interface ItemTileMenuProps {
id: string;
database?: string;
kind: string;
name: string;
canRename?: boolean;
canDelete?: boolean;
busy?: boolean;
onRename?: (name: string) => Promise<void>;
onDelete?: () => Promise<void>;
deleteBody?: ReactNode;
prepareDelete?: () => Promise<ReactNode>;
deleteConfirmation?: (onCancel: () => void) => ReactNode;
/** A template App leaves the workspace by Remove, never Delete: its data stays. */
remove?: boolean;
children: ReactNode;
}
/** A fresh item permission refusal has no retry action. */
export class ItemPermissionError extends Error {}
/** Keep the editor beside the link, at its title's position, including wrapped DatabaseTile titles. */
function TileNameEditor({ tile, name, busy, onSave, onCancel }: {
tile: HTMLDivElement | null;
name: string;
busy: boolean;
onSave(name: string): Promise<void>;
onCancel(): void;
}) {
const panel = useRef<HTMLFormElement>(null);
const input = useRef<HTMLInputElement>(null);
const [draft, setDraft] = useState(name);
const [bounds, setBounds] = useState<{ left: number; top: number }>();
useOverlayLayer({ panelRef: panel, onDismiss: onCancel, initialFocus: "input", restoreFocus: true });
useLayoutEffect(() => {
const title = tile?.querySelector<HTMLElement>(".home-tile-name");
if (!tile || !title) return;
const measure = () => {
const base = tile.getBoundingClientRect();
const text = title.getBoundingClientRect();
setBounds({ left: text.left - base.left, top: text.top - base.top });
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(tile);
return () => observer.disconnect();
}, [tile]);
useEffect(() => { if (!busy) input.current?.select(); }, [busy]);
return <form ref={panel} className="home-item-rename" style={bounds}
aria-label={`Rename ${name}`} onClick={(event) => event.stopPropagation()}
onSubmit={(event) => { event.preventDefault(); if (!busy && draft.trim()) void onSave(draft.trim()); }}>
<input ref={input} className="cg-input" aria-label={`Name for ${name}`} value={draft}
disabled={busy} onChange={(event) => setDraft(event.currentTarget.value)} />
<button type="submit" className="cg-btn" disabled={busy || !draft.trim()}>{busy ? "Saving…" : "Save"}</button>
</form>;
}
/** File rights come from the item's server response, independently of folder administration. */
export default function ItemTileMenu({
id, database, kind, name, canRename = false, canDelete = false, busy = false,
onRename, onDelete, deleteBody, prepareDelete, deleteConfirmation, remove = false, children,
}: ItemTileMenuProps) {
const tile = useRef<HTMLDivElement>(null);
const trigger = useRef<HTMLButtonElement>(null);
const writing = useRef(false);
const refusalReported = useRef(false);
const [surface, setSurface] = useState<"menu" | "rename" | "delete" | null>(null);
const [saving, setSaving] = useState(false);
const [deleteError, setDeleteError] = useState("");
const [preparedDeleteBody, setPreparedDeleteBody] = useState<ReactNode>();
const renameAllowed = canRename === true && !!onRename;
const deleteAllowed = canDelete === true && (!!onDelete || !!deleteConfirmation);
const pending = busy || saving;
const reportRefusal = useCallback((text: string) => {
if (refusalReported.current) return;
refusalReported.current = true;
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
}, []);
useEffect(() => {
if ((!renameAllowed && surface === "rename") || (!deleteAllowed && surface === "delete")
|| (surface === "menu" && !renameAllowed && !deleteAllowed)) {
setSurface(null);
reportRefusal(`You no longer have permission to edit this ${kind}.`);
}
}, [renameAllowed, deleteAllowed, surface, kind, reportRefusal]);
const dismiss = () => {
if (writing.current) return;
setSurface(null);
trigger.current?.focus({ preventScroll: true });
};
const open = async (next: "rename" | "delete") => {
if (pending || writing.current || (next === "rename" ? !renameAllowed : !deleteAllowed)) return;
refusalReported.current = false;
trigger.current?.focus({ preventScroll: true });
setDeleteError("");
if (next === "delete" && prepareDelete) {
writing.current = true;
setSaving(true);
setSurface(null);
try {
setPreparedDeleteBody(await prepareDelete());
} catch (error) {
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: {
text: error instanceof Error ? error.message : "The item could not be checked.", tone: "error",
} }));
return;
} finally {
writing.current = false;
setSaving(false);
}
}
setSurface(next);
};
const save = async (nextName?: string) => {
if (pending || writing.current || (nextName === undefined ? !deleteAllowed : !renameAllowed)) return;
if (nextName === name) { dismiss(); return; }
refusalReported.current = false;
writing.current = true;
setSaving(true);
setDeleteError("");
try {
if (nextName === undefined) await onDelete?.();
else await onRename?.(nextName);
setSurface(null);
trigger.current?.focus({ preventScroll: true });
} catch (error) {
const text = error instanceof Error ? error.message : "The change was not saved.";
if (error instanceof ItemPermissionError) {
setSurface(null);
reportRefusal(text);
} else if (nextName === undefined) setDeleteError(text);
else reportRefusal(text);
} finally {
writing.current = false;
setSaving(false);
}
};
return <div ref={tile} className={"st-tilewrap home-item-tile"
+ (renameAllowed || deleteAllowed ? " can-manage" : "") + (surface === "rename" && renameAllowed ? " is-renaming" : "")}
data-item-id={id} data-item-database={database} data-item-kind={kind} aria-busy={pending || undefined}>
{children}
{renameAllowed || deleteAllowed ? <button ref={trigger} type="button" className="home-item-menu-trigger"
aria-label={`Actions for ${name}`} title="Item actions" aria-haspopup="menu" aria-expanded={surface === "menu"}
disabled={pending} onClick={() => {
refusalReported.current = false;
setSurface(surface === "menu" ? null : "menu");
}}>
<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false">
<circle cx="3" cy="8" r="1" fill="currentColor" />
<circle cx="8" cy="8" r="1" fill="currentColor" />
<circle cx="13" cy="8" r="1" fill="currentColor" />
</svg>
</button> : null}
{surface === "menu" ? <AnchoredOverlay anchor={trigger.current} className="cg-view-menu home-item-menu"
placement="bottom-end" role="menu" ariaLabel={`Actions for ${name}`} dataKind="home-item-menu"
onDismiss={dismiss} onKeyDown={onRowMenuKey}>
{renameAllowed ? <button type="button" role="menuitem" onClick={() => open("rename")}>
<MenuLabel icon="rename" text="Rename" />
</button> : null}
{deleteAllowed ? <button type="button" role="menuitem" className="is-danger" onClick={() => open("delete")}>
<MenuLabel icon="trash" text={remove ? "Remove" : "Delete"} />
</button> : null}
</AnchoredOverlay> : null}
{surface === "rename" && renameAllowed ? <TileNameEditor tile={tile.current} name={name} busy={pending}
onSave={save} onCancel={dismiss} /> : null}
{surface === "delete" && deleteAllowed && remove ? <ConfirmDialog
open title={`Remove ${name}?`} body={<><p>Its data stays. Add it again from Templates.</p>
{deleteError ? <p className="home-item-delete-error" role="alert">{deleteError}</p> : null}</>}
confirmLabel={pending ? "Removing…" : deleteError ? "Retry remove" : "Remove"}
tone="destructive" busy={pending} onCancel={dismiss} onConfirm={() => void save()} />
: surface === "delete" && deleteAllowed ? deleteConfirmation ? deleteConfirmation(dismiss) : <ConfirmDialog
open title={`Delete ${kind}`} body={<><p>Delete “{name}”?</p>{preparedDeleteBody ?? deleteBody}
{deleteError ? <p className="home-item-delete-error" role="alert">{deleteError}</p> : null}</>}
confirmLabel={pending ? "Deleting…" : deleteError ? "Retry delete" : "Delete"}
tone="destructive" busy={pending} onCancel={dismiss} onConfirm={() => void save()} /> : null}
</div>;
}
export interface AutomationRowMenuProps extends Omit<AutomationMutationContext, "setBusy"> {
automation: Automation;
anchor: HTMLButtonElement;
onClose(): void;
onMenuClose(): void;
onDeleted(id: string): void;
}
/** Loaded only on a row action, with inline editing portalled into the immediate rail. */
export function AutomationRowMenu({
automation: a, anchor, writing, mergeSaved, load, onClose, onMenuClose, onDeleted,
}: AutomationRowMenuProps) {
const [mode, setMode] = useState<"menu" | "rename" | "delete">("menu");
const [busy, setBusy] = useState("");
const [deleteError, setDeleteError] = useState("");
const input = useRef<HTMLInputElement>(null);
const renameFinished = useRef(false);
const mutations = { writing, setBusy, mergeSaved, load };
const unavailable = !!busy || writing.current || !!a.system;
const explanation = a.system ? "Edit this automation at its source." : undefined;
const dismiss = () => { if (!writing.current) onClose(); };
const open = (next: "rename" | "delete") => {
if (unavailable) return;
onMenuClose();
setMode(next);
};
useEffect(() => {
if (mode === "rename") {
input.current?.focus();
input.current?.select();
}
}, [mode]);
const commitRename = (value: string) => {
if (renameFinished.current || writing.current) return;
renameFinished.current = true;
onClose();
void renameAutomation(a, value, mutations);
};
const confirmDelete = async () => {
if (writing.current || a.system) return;
setDeleteError("");
try {
if (await removeAutomation(a, { ...mutations, onDeleted })) onClose();
} catch (e) {
setDeleteError(e instanceof AutomationError ? e.message : "The automation was not deleted.");
}
};
if (mode === "rename") return anchor.parentElement ? createPortal(
<input
ref={input}
className="cg-view-rename cg-input auto-row-rename"
aria-label={`Rename ${a.name}`}
defaultValue={a.name}
onBlur={(event) => commitRename(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
if (event.key === "Escape") event.currentTarget.value = a.name;
event.currentTarget.blur();
anchor.focus({ preventScroll: true });
}
}}
/>, anchor.parentElement,
) : null;
if (mode === "delete") return <ConfirmDialog
open
title="Delete automation"
body={<>
<p>Delete “{a.name}”? This cannot be undone.</p>
{deleteError ? <p className="auto-row-delete-error" role="alert">{deleteError}</p> : null}
</>}
confirmLabel={busy ? "Deleting…" : deleteError ? "Retry delete" : "Delete"}
tone="destructive"
busy={!!busy}
onConfirm={() => void confirmDelete()}
onCancel={dismiss}
/>;
return <AnchoredOverlay
anchor={anchor}
className="cg-view-menu auto-row-menu"
placement="bottom-end"
role="menu"
ariaLabel={`Actions for ${a.name}`}
dataKind="automation-row-menu"
onDismiss={dismiss}
onKeyDown={onRowMenuKey}
>
<button type="button" role="menuitem" disabled={unavailable} title={explanation}
onClick={() => open("rename")}>
<MenuLabel icon="rename" text="Rename" />
</button>
<button type="button" role="menuitem" data-role="toggle-automation"
disabled={unavailable} title={explanation}
onClick={() => { if (!unavailable) { onClose(); void toggleEnabled(a, mutations); } }}>
<MenuLabel icon={a.schedule?.enabled ? <Pause size={16} /> : <Play size={16} />}
text={a.schedule?.enabled ? "Pause" : "Resume"} />
</button>
<button type="button" role="menuitem" className="is-danger"
disabled={unavailable} title={explanation} onClick={() => open("delete")}>
<MenuLabel icon="trash" text="Delete" />
</button>
</AnchoredOverlay>;
}