// @ts-check
// The prompt waiting on you, above the composer: a permission to grant or a question to answer.
//
// Like the TUI's card, it holds back every answer but the refusal for a moment after it appears,
// since it can slide in under a thumb aimed at Send; a tap that lands then can't grant anything.
import { useEffect, useState } from "preact/hooks";
import { fieldOf, html } from "./html.js";
import { permissionReply, questionReply } from "./pending.js";
/** @import { Frame } from "./connection.js" */
/** @import { PermissionPrompt, Prompt, QuestionOption, QuestionPrompt } from "./pending.js" */
/** @typedef {(frame: Frame) => boolean} Send */
/** How long a new prompt ignores everything but a refusal, as the TUI's `GRACE`. */
export const GRACE_MS = 400;
/** @param {{ prompts: Prompt[], send: Send }} props */
export function PromptCard({ prompts, send }) {
const prompt = prompts[0];
const settled = useSettled(prompt?.id);
if (!prompt) return null;
const count = prompts.length > 1 ? html` 1 of ${prompts.length}` : null;
const card = prompt.kind === "permission"
? html`<${Permission} prompt=${prompt} send=${send} settled=${settled} />`
: html`<${Question} key=${prompt.id} prompt=${prompt} send=${send} settled=${settled} />`;
return html`${count}${card}`;
}
/**
* False for [`GRACE_MS`] after the prompt `id` appears. Keyed by id rather than a flag reset in an
* effect, which would leave the next prompt one render with the last one's grace already spent.
* @param {string | undefined} id
*/
function useSettled(id) {
const [settledId, setSettledId] = useState(/** @type {string | undefined} */ (undefined));
useEffect(() => {
const timer = setTimeout(() => setSettledId(id), GRACE_MS);
return () => clearTimeout(timer);
}, [id]);
return id != null && settledId === id;
}
/**
* The TUI's answers, in its order; the two that remember only when the call has a pattern to.
* @param {PermissionPrompt} prompt
*/
export function permissionChoices(prompt) {
const patterns = prompt.always_patterns ?? [];
const remembered = patterns.join(", ");
return [
{ reply: "once", label: "Allow once", hint: "run just this call" },
...(patterns.length
? [
{ reply: "always", label: "Allow for this session", hint: `remember ${remembered}` },
{ reply: "always_persist", label: "Allow always", hint: `save ${remembered} to your permissions` },
]
: []),
{ reply: "reject", label: "Reject", hint: "deny this call" },
];
}
/** @param {{ prompt: PermissionPrompt, send: Send, settled: boolean }} props */
function Permission({ prompt, send, settled }) {
return html`