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; } 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 & { 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) { if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return; const buttons = Array.from(event.currentTarget.querySelectorAll( '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; onDelete?: () => Promise; deleteBody?: ReactNode; prepareDelete?: () => Promise; 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; onCancel(): void; }) { const panel = useRef(null); const input = useRef(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(".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
event.stopPropagation()} onSubmit={(event) => { event.preventDefault(); if (!busy && draft.trim()) void onSave(draft.trim()); }}> setDraft(event.currentTarget.value)} />
; } /** 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(null); const trigger = useRef(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(); 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
{children} {renameAllowed || deleteAllowed ? : null} {surface === "menu" ? {renameAllowed ? : null} {deleteAllowed ? : null} : null} {surface === "rename" && renameAllowed ? : null} {surface === "delete" && deleteAllowed && remove ?

Its data stays. Add it again from Templates.

{deleteError ?

{deleteError}

: null}} confirmLabel={pending ? "Removing…" : deleteError ? "Retry remove" : "Remove"} tone="destructive" busy={pending} onCancel={dismiss} onConfirm={() => void save()} /> : surface === "delete" && deleteAllowed ? deleteConfirmation ? deleteConfirmation(dismiss) :

Delete “{name}”?

{preparedDeleteBody ?? deleteBody} {deleteError ?

{deleteError}

: null}} confirmLabel={pending ? "Deleting…" : deleteError ? "Retry delete" : "Delete"} tone="destructive" busy={pending} onCancel={dismiss} onConfirm={() => void save()} /> : null}
; } export interface AutomationRowMenuProps extends Omit { 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(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( 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

Delete “{a.name}”? This cannot be undone.

{deleteError ?

{deleteError}

: null} } confirmLabel={busy ? "Deleting…" : deleteError ? "Retry delete" : "Delete"} tone="destructive" busy={!!busy} onConfirm={() => void confirmDelete()} onCancel={dismiss} />; return ; }