import { ExternalLink } from "@getpaseo/plugin/client/ui"; import React, { useEffect, useMemo, useState } from "react"; import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native"; import { hasOwnNumber } from "../../shared/logic/reply"; import { useItemFeedback } from "./feedback"; import { CheckBox } from "./inputs"; import { decisionMessage, estimateTask, estimateTotals, estimateUnit, formatQuantity, formatWithUnit, initialChecks, nudgeWeight, planMessage, planTotal, rankOptions, readDecision, readEstimate, readPlan, round, weightMax, weightStep, } from "../../shared/core/decisions"; import { axisShare, formatDay, formatRange, HEALTH_LABEL, localDay, readBoard, readRoadmap, readStatus, ROADMAP_STATUS_LABEL, } from "../../shared/core/tracking"; import { parseSteps } from "../../shared/logic/explain-logic"; import { finiteNumber, optionalText, text, type Props } from "../../shared/logic/values"; import { countdownSeconds, elapsedMs, formatClock, parseCards, parseQuestions, pauseClock, quizScore, remainingMs, startClock, STOPPED, type Clock, } from "../../shared/logic/widget-logic"; import { InlineMarkdown, MarkdownText } from "../markdown"; import { ErrorLine } from "../node-renderer"; import { propsKey, usePersistedState, useUiRuntime } from "../runtime"; export function Timer({ props }: { props: Props }) { const { theme } = useUiRuntime(); const totalSeconds = finiteNumber(props.seconds); const label = optionalText(props.label) ?? (totalSeconds !== null ? "Timer" : "Stopwatch"); const [clock, setClock] = useState(STOPPED); const [now, setNow] = useState(() => Date.now()); useEffect(() => { if (clock.startedAt === null) return; const id = setInterval(() => setNow(Date.now()), 200); return () => clearInterval(id); }, [clock.startedAt]); const running = clock.startedAt !== null; const shownSeconds = totalSeconds !== null ? countdownSeconds(remainingMs(clock, totalSeconds * 1000, now)) : Math.floor(elapsedMs(clock, now) / 1000); return ( {label} {formatClock(shownSeconds)} { const t = Date.now(); setNow(t); setClock((c) => (c.startedAt === null ? startClock(c, t) : pauseClock(c, t))); }} style={{ paddingHorizontal: 12, paddingVertical: 6, borderRadius: 6, backgroundColor: theme.colors.accent, }} > {running ? "Pause" : "Start"} setClock(STOPPED)} style={{ paddingHorizontal: 10, paddingVertical: 6, borderRadius: 6, backgroundColor: theme.colors.surface1, }} > Reset ); } export function Quiz({ props }: { props: Props }) { const { theme } = useUiRuntime(); const { questions } = parseQuestions(props.questions); const [picks, setPicks] = usePersistedState<(number | null)[]>( `quiz:${propsKey(props.questions)}`, questions.map(() => null), (v) => (Array.isArray(v) ? v.map((x) => (typeof x === "number" ? x : null)) : null), ); if (questions.length === 0) return ; const answered = picks.filter((p) => p !== null).length; const score = quizScore(questions, picks); return ( {questions.map((q, qIdx) => { const picked = picks[qIdx] ?? null; return ( {qIdx + 1}. {q.q} {q.options.map((opt, oIdx) => { const isPicked = picked === oIdx; const isCorrect = q.answer === oIdx; const borderColor = picked === null ? theme.colors.border : isCorrect ? theme.colors.statusSuccess : isPicked ? theme.colors.statusDanger : theme.colors.border; return ( setPicks((prev) => { const copy = [...prev]; copy[qIdx] = oIdx; return copy; }) } style={{ paddingHorizontal: 10, paddingVertical: 7, borderRadius: 6, borderWidth: isPicked || (picked !== null && isCorrect) ? 1.5 : StyleSheet.hairlineWidth, borderColor, backgroundColor: theme.colors.surface1, }} > {opt} ); })} {picked !== null && q.why ? ( {q.why} ) : null} ); })} {answered > 0 ? ( Score: {score} / {questions.length} ) : null} ); } export function Flashcards({ props }: { props: Props }) { const { theme } = useUiRuntime(); const cards = parseCards(props.cards); const [index, setIndex] = useState(0); const [flipped, setFlipped] = useState(false); if (cards.length === 0) return ; const card = cards[Math.min(index, cards.length - 1)]!; return ( setFlipped((f) => !f)} style={{ minHeight: 110, borderRadius: 10, borderWidth: StyleSheet.hairlineWidth, borderColor: theme.colors.border, backgroundColor: theme.colors.surface2, padding: 16, justifyContent: "center", alignItems: "center", gap: 6, }} > {flipped ? "Back" : "Front"} · Card {index + 1} of {cards.length} (tap to flip) {flipped ? card.back : card.front} { setFlipped(false); setIndex((i) => (i > 0 ? i - 1 : cards.length - 1)); }} style={{ paddingHorizontal: 10, paddingVertical: 5, borderRadius: 6, backgroundColor: theme.colors.surface2 }} > Previous { setFlipped(false); setIndex((i) => (i + 1) % cards.length); }} style={{ paddingHorizontal: 10, paddingVertical: 5, borderRadius: 6, backgroundColor: theme.colors.surface2 }} > Next ); } export function Walkthrough({ props }: { props: Props }) { const { theme, compact } = useUiRuntime(); const { steps } = parseSteps(props.steps); const [stepIdx, setStepIdx] = useState(0); if (steps.length === 0) return ; const current = steps[Math.min(stepIdx, steps.length - 1)]!; return ( {current.title || `Step ${stepIdx + 1}`} {stepIdx + 1} / {steps.length} {current.body ? : null} {current.code ? ( {current.code} ) : null} setStepIdx((i) => Math.max(0, i - 1))} style={{ paddingHorizontal: 10, paddingVertical: 5, borderRadius: 6, backgroundColor: theme.colors.surface1, opacity: stepIdx === 0 ? 0.4 : 1, }} > Back = steps.length - 1} onPress={() => setStepIdx((i) => Math.min(steps.length - 1, i + 1))} style={{ paddingHorizontal: 10, paddingVertical: 5, borderRadius: 6, backgroundColor: theme.colors.accent, opacity: stepIdx >= steps.length - 1 ? 0.4 : 1, }} > Next ); } export function Plan({ props }: { props: Props }) { const { theme, run, answer } = useUiRuntime(); const { steps, error } = readPlan(props.steps); const submitLabel = optionalText(props.submit) ?? "Approve plan"; const [checked, setChecked] = usePersistedState( `plan:${propsKey(props.steps)}`, initialChecks(steps), (v) => (Array.isArray(v) ? v.map(Boolean) : null), ); const feedback = useItemFeedback(`plan:${propsKey(props.steps)}`, { comments: props.comments === true, editable: props.editable === true, }); if (error) return ; const total = planTotal(steps, checked); return ( {steps.map((step, idx) => { const isOn = checked[idx] !== false; const original = { title: step.title, detail: step.detail ?? "" }; const shown = feedback.fields(idx, original); const toggle = () => setChecked((prev) => { const next = [...prev]; next[idx] = !isOn; return next; }); return ( {hasOwnNumber(shown.title) ? shown.title : `${idx + 1}. ${shown.title}`} {step.estimate ? ( {step.estimate} ) : null} {shown.detail ? ( ) : null} {step.files.length > 0 ? ( {step.files.map((f, fIdx) => ( {f.line === null ? f.path : `${f.path}:${f.line}`} ))} ) : null} {feedback.controls(idx, hasOwnNumber(step.title) ? `step "${step.title}"` : `step ${idx + 1} (${step.title})`, original)} ); })} {total.total ? `Estimated total: ${formatQuantity(total.total)}` : `${checked.filter(Boolean).length} steps selected`} {answer ? ( Approved ) : ( { const msg = planMessage(steps, checked, ""); if (msg) void run([{ kind: "action", type: "send", text: msg }]); }} style={{ paddingHorizontal: 12, paddingVertical: 7, borderRadius: 8, backgroundColor: theme.colors.accent, }} > {submitLabel} )} ); } export function Decision({ props }: { props: Props }) { const { theme, run } = useUiRuntime(); const feedback = useItemFeedback(`decision:${propsKey(props.options)}`, { comments: props.comments === true, editable: false }); const parsed = readDecision(props.options, props.criteria); if (!parsed.ok) return ; const { model } = parsed; const [weights, setWeights] = usePersistedState( `decision:${propsKey(props)}`, model.criteria.map((c) => c.weight), (v) => (Array.isArray(v) && v.length === model.criteria.length ? v.map((n) => Number(n) || 0) : null), ); const ranked = rankOptions(model, weights); const step = weightStep(weights); const maxW = weightMax(weights); return ( Criteria weights {model.criteria.map((c, cIdx) => { const w = weights[cIdx] ?? c.weight; return ( {c.name} setWeights((prev) => prev.map((val, i) => (i === cIdx ? nudgeWeight(val, -1, step, maxW) : val)), ) } > − {round(w, 2)} setWeights((prev) => prev.map((val, i) => (i === cIdx ? nudgeWeight(val, 1, step, maxW) : val)), ) } > + ); })} {ranked.map((entry, rIdx) => { const opt = model.options[entry.index]!; const isLeader = rIdx === 0; return ( {opt.name} {round(entry.total, 2)} / {model.scale} {opt.pros.length > 0 ? ( + {opt.pros.join(" · ")} ) : null} {opt.cons.length > 0 ? ( − {opt.cons.join(" · ")} ) : null} { const msg = decisionMessage(model, entry.index, weights); void run([{ kind: "action", type: "send", text: msg }]); }} style={{ alignSelf: "flex-start", paddingHorizontal: 10, paddingVertical: 5, borderRadius: 6, backgroundColor: isLeader ? theme.colors.accent : theme.colors.surface1, }} > Go with {opt.name} {feedback.controls(entry.index, `option "${opt.name}"`, {})} ); })} ); } export function Estimate({ props }: { props: Props }) { const { theme } = useUiRuntime(); const { tasks, error } = readEstimate(props.tasks); if (error) return ; const unit = estimateUnit(props.unit); const estimates = tasks.map(estimateTask); const totals = estimateTotals(estimates); return ( P50 (Expected) {formatWithUnit(totals.p50, unit)} P80 {formatWithUnit(totals.p80, unit)} P90 (Safe) {formatWithUnit(totals.p90, unit)} {estimates.map((est, idx) => ( {est.task.title} {est.error ? est.error : `${est.task.low} / ${round(est.likely, 1)} / ${est.task.high} ${unit}`} ))} ); } export function Board({ props }: { props: Props }) { const { theme, compact } = useUiRuntime(); const parsed = readBoard(props.items, props.columns); if (!parsed.ok) return ; const board = parsed.value; return ( {board.columns.map((col) => ( {col.label} {col.cards.length} {col.cards.map((card) => ( {card.key ? ( {card.key} ) : null} {card.priority ? ( {card.priority} ) : null} {card.url ? ( {card.title} ) : ( {card.title} )} {card.owners.length > 0 ? ( {card.owners.join(", ")} ) : null} ))} ))} ); } export function Roadmap({ props }: { props: Props }) { const { theme } = useUiRuntime(); const today = useMemo(() => localDay(new Date()), []); const parsed = readRoadmap(props.items, today); if (!parsed.ok) return ; const roadmap = parsed.value; return ( {roadmap.lanes.map((lane, lIdx) => ( {lane.name ? ( {lane.name} ) : null} {lane.items.map((item) => { const leftPct = Math.max(0, Math.min(95, axisShare(item.start, roadmap) * 100)); const rightPct = Math.max(leftPct + 3, Math.min(100, axisShare(item.end + 1, roadmap) * 100)); const widthPct = Math.max(3, rightPct - leftPct); const barColor = item.status === "done" ? theme.colors.statusSuccess : item.status === "blocked" || item.status === "at-risk" ? theme.colors.statusWarning : theme.colors.accent; return ( {item.title} {formatRange(item.start, item.end, today)} · {ROADMAP_STATUS_LABEL[item.status]} ); })} ))} ); } export function Status({ props }: { props: Props }) { const { theme } = useUiRuntime(); const today = useMemo(() => localDay(new Date()), []); const parsed = readStatus(props.items, today); if (!parsed.ok) return ; const report = parsed.value; return ( {report.items.map((item, idx) => { const color = item.status === "on-track" || item.status === "done" ? theme.colors.statusSuccess : item.status === "at-risk" ? theme.colors.statusWarning : item.status === "off-track" || item.status === "blocked" ? theme.colors.statusDanger : theme.colors.foregroundMuted; return ( {item.name} {item.status ? HEALTH_LABEL[item.status] : item.given ?? "Unknown"} {item.progress !== null ? ` (${Math.round(item.progress)}%)` : ""} {item.note || item.owner || item.due !== null ? ( {[ item.owner, item.due !== null ? `Due ${formatDay(item.due, today)}` : null, item.note, ] .filter(Boolean) .join(" · ")} ) : null} ); })} ); }