import { Icon, copyText, useToast } from "@getpaseo/plugin/client/react-native"; import { InlineMarkdown } from "../markdown"; import React, { useMemo, useState } from "react"; import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native"; import { calendarLayout, calendarStats, dayLabel, readDays } from "../../shared/logic/calendarMath"; import { percentages, pieSlices } from "../../shared/logic/chartMath"; import { buildTree, defaultExpanded, timelineEntries, visibleRows } from "../../shared/logic/content-model"; import { addMonths, dayKey, initialMonth, localToday, monthKey, monthWeeks, parseEvents, parseMonth, } from "../../shared/logic/explain-logic"; import { asRecord, finiteNumber, formatNumber, isNode, isObject, list, optionalText, text, tone, type Props, type Tone, } from "../../shared/logic/values"; import { ErrorLine, RenderNode } from "../node-renderer"; import { InTableContext, propsKey, toneColor, usePersistedState, useUiRuntime } from "../runtime"; import { hasOwnNumber } from "../../shared/logic/reply"; import { useItemFeedback } from "./feedback"; export function Table({ props }: { props: Props }) { const { theme, compact } = useUiRuntime(); const columns = list(props.columns).map((col) => { const rec = asRecord(col); return rec ? text(rec.label ?? rec.key) : text(col); }); const rows = list(props.rows); const feedback = useItemFeedback(`table:${propsKey(props.rows)}`, { comments: props.comments === true, editable: false }); return ( {columns.map((col, idx) => ( {col} ))} {rows.map((row, rIdx) => { const rec = asRecord(row); const cells = Array.isArray(row) ? row : rec ? columns.map((c) => rec[c] ?? null) : [row]; const first = isNode(cells[0]) ? "" : text(cells[0]); const controls = feedback.controls(rIdx, `row ${rIdx + 1}${first ? ` (${first})` : ""}`, {}); return ( {columns.map((_, cIdx) => { const cell = cells[cIdx]; return ( {isNode(cell) ? ( ) : ( {text(cell)} )} ); })} {controls ? {controls} : null} ); })} ); } interface ParsedSeries { name: string; values: (number | null)[]; tone: Tone; } function parseChartSeries(raw: unknown): ParsedSeries[] { if (Array.isArray(raw)) { return [ { name: "Value", values: raw.map((v) => finiteNumber(v)), tone: "info", }, ]; } if (isObject(raw)) { const tones: Tone[] = ["info", "good", "warn", "bad", "neutral"]; return Object.entries(raw).map(([name, entry], idx) => { if (Array.isArray(entry)) { return { name, values: entry.map((v) => finiteNumber(v)), tone: tones[idx % tones.length]!, }; } if (isObject(entry) && Array.isArray(entry.values)) { return { name, values: entry.values.map((v) => finiteNumber(v)), tone: tone(entry.tone as never), }; } return { name, values: [], tone: tones[idx % tones.length]! }; }); } return []; } export function Chart({ props }: { props: Props }) { const { theme } = useUiRuntime(); const chartType = text(props.type) || "bar"; const labels = list(props.labels).map((l) => text(l)); const series = useMemo(() => parseChartSeries(props.series), [props.series]); const unit = optionalText(props.unit) ?? ""; const fmtVal = (v: number) => (unit ? `${formatNumber(v)} ${unit}`.trim() : formatNumber(v)); if (series.length === 0) return ; if (chartType === "pie" || chartType === "funnel") { const first = series[0]!; const slices = pieSlices(labels, first.values, 8); const shares = percentages(slices.map((s) => s.value)); const maxVal = Math.max(1, ...slices.map((s) => s.value)); return ( {slices.map((slice, idx) => { const pct = chartType === "funnel" ? Math.round((slice.value / maxVal) * 100) : shares[idx] ?? 0; return ( {slice.label} {fmtVal(slice.value)} ({pct}%) ); })} ); } if (chartType === "heatmap") { const allNums = series.flatMap((s) => s.values.filter((v): v is number => v !== null)); const maxVal = Math.max(1, ...allNums); return ( {labels.map((l, idx) => ( {l} ))} {series.map((row, rIdx) => ( {row.name} {labels.map((_, cIdx) => { const v = row.values[cIdx] ?? 0; const intensity = Math.max(0.12, Math.min(1, v / maxVal)); return ( 0 ? intensity : 0.4, }} > {formatNumber(v)} ); })} ))} ); } const allValues = series.flatMap((s) => s.values.filter((v): v is number => v !== null)); const maxAbs = Math.max(1, ...allValues.map((v) => Math.abs(v))); return ( {series.length > 1 ? ( {series.map((s, idx) => ( {s.name} ))} ) : null} {labels.map((label, lIdx) => ( {label} {series .map((s) => { const v = s.values[lIdx]; return v === null || v === undefined ? "—" : fmtVal(v); }) .join(" / ")} {series.map((s, sIdx) => { const v = s.values[lIdx] ?? 0; const pct = Math.min(100, Math.max(2, Math.round((Math.abs(v) / maxAbs) * 100))); return ( 1 ? 7 : 9, borderRadius: 4, backgroundColor: theme.colors.surface2, overflow: "hidden", }} > ); })} ))} ); } export function Sparkline({ props }: { props: Props }) { const { theme } = useUiRuntime(); const values = list(props.values) .map((v) => finiteNumber(v)) .filter((v): v is number => v !== null); const t = tone(props.tone); const color = toneColor(theme, t === "neutral" ? "info" : t); if (values.length === 0) return null; const min = Math.min(...values); const max = Math.max(...values); const span = Math.max(1, max - min); return ( {values.map((v, idx) => { const h = Math.max(3, Math.round(((v - min) / span) * 22)); return ( ); })} {formatNumber(values[values.length - 1]!)} ); } export function Progress({ props }: { props: Props }) { const { theme } = useUiRuntime(); const value = finiteNumber(props.value) ?? 0; const max = finiteNumber(props.max) ?? 100; const label = optionalText(props.label); const t = tone(props.tone); const pct = max > 0 ? Math.min(100, Math.max(0, Math.round((value / max) * 100))) : 0; const color = toneColor(theme, t === "neutral" ? "info" : t); return ( {label ? {label} : } {pct}% ); } export function Gauge({ props }: { props: Props }) { const { theme } = useUiRuntime(); const value = finiteNumber(props.value) ?? 0; const min = finiteNumber(props.min) ?? 0; const max = finiteNumber(props.max) ?? 100; const label = optionalText(props.label); const t = tone(props.tone); const span = Math.max(1, max - min); const pct = Math.min(100, Math.max(0, Math.round(((value - min) / span) * 100))); const color = toneColor(theme, t === "neutral" ? "info" : t); return ( {label ?? "Gauge"} {formatNumber(value)} / {formatNumber(max)} ); } export function SegmentedBar({ props }: { props: Props }) { const { theme } = useUiRuntime(); const unit = optionalText(props.unit) ?? ""; const parts = list(props.parts).flatMap((p) => { const rec = asRecord(p); if (!rec) return []; const val = finiteNumber(rec.value); if (val === null || val <= 0) return []; return [{ label: text(rec.label), value: val, tone: tone(rec.tone) }]; }); const shares = percentages(parts.map((p) => p.value)); const tones: Tone[] = ["info", "good", "warn", "bad", "neutral"]; return ( {parts.map((part, idx) => { const t = part.tone === "neutral" ? tones[idx % tones.length]! : part.tone; return ( ); })} {parts.map((part, idx) => { const t = part.tone === "neutral" ? tones[idx % tones.length]! : part.tone; return ( {part.label}:{" "} {formatNumber(part.value)} {unit ? ` ${unit}` : ""} ({shares[idx] ?? 0}%) ); })} ); } export function Steps({ props }: { props: Props }) { const { theme } = useUiRuntime(); const items = list(props.items); const feedback = useItemFeedback(`steps:${propsKey(props.items)}`, { comments: props.comments === true, editable: props.editable === true, }); return ( {items.map((item, idx) => { const obj = asRecord(item) ?? { title: text(item) }; const original = { title: text(obj.title ?? obj.label), detail: optionalText(obj.detail) ?? "" }; const { title, detail } = feedback.fields(idx, original); const status = text(obj.status); const color = status === "done" ? theme.colors.statusSuccess : status === "blocked" ? theme.colors.statusDanger : status === "current" ? theme.colors.accent : theme.colors.foregroundMuted; return ( {idx + 1} {title} {detail ? ( ) : null} {feedback.controls(idx, hasOwnNumber(original.title) ? `step "${original.title}"` : `step ${idx + 1} (${original.title})`, original)} ); })} ); } export function Timeline({ props }: { props: Props }) { const { theme } = useUiRuntime(); const entries = timelineEntries(list(props.items)); return ( {entries.map((entry, idx) => ( {entry.title} {entry.time ? ( {entry.time} ) : null} {entry.detail ? ( ) : null} ))} ); } export function Calendar({ props }: { props: Props }) { const { theme } = useUiRuntime(); const { events } = parseEvents(props.events); const requested = parseMonth(props.month); const today = useMemo(() => localToday(new Date()), []); const startMonth = useMemo(() => initialMonth(events, requested, today), [events, requested, today]); const [month, setMonth] = useState(startMonth); const weeks = useMemo(() => monthWeeks(month, 1), [month]); const byDay = useMemo(() => { const map = new Map(); for (const ev of events) { map.set(ev.key, [...(map.get(ev.key) ?? []), ev]); } return map; }, [events]); return ( {monthKey(month)} setMonth((m) => addMonths(m, -1))} style={{ padding: 4, borderRadius: 4, backgroundColor: theme.colors.surface1 }} > setMonth((m) => addMonths(m, 1))} style={{ padding: 4, borderRadius: 4, backgroundColor: theme.colors.surface1 }} > {weeks.map((week, wIdx) => ( {week.map((day, dIdx) => { const key = day === null ? "" : dayKey({ ...month, day }); const dayEvents = key ? byDay.get(key) ?? [] : []; return ( {day !== null ? ( {day} ) : null} {dayEvents.slice(0, 2).map((ev, eIdx) => ( {ev.title} ))} ); })} ))} ); } export function CalendarHeatmap({ props }: { props: Props }) { const { theme } = useUiRuntime(); const { values } = useMemo(() => readDays(props.days), [props.days]); const label = optionalText(props.label); const stats = useMemo(() => calendarStats(values), [values]); const days = [...values.keys()].sort((a, b) => a - b); if (days.length === 0) return ; const first = days[0]!; const last = Math.max(first + 28, days[days.length - 1]!); const layout = calendarLayout(first, last); const peakVal = stats.peak?.value ?? 1; return ( {label ?? "Activity"} {formatNumber(stats.total)} total · {stats.active} active days {stats.peak ? ` · peak ${formatNumber(stats.peak.value)} (${dayLabel(stats.peak.day)})` : ""} {Array.from({ length: Math.min(53, layout.weeks) }, (_, w) => ( {Array.from({ length: 7 }, (__, d) => { const day = layout.start + w * 7 + d; const val = values.get(day) ?? 0; const active = val > 0; return ( ); })} ))} ); } export function Tree({ props }: { props: Props }) { const { theme } = useUiRuntime(); const roots = useMemo(() => buildTree(list(props.items)), [props.items]); const initialOpen = useMemo(() => [...defaultExpanded(roots)], [roots]); const [openIds, setOpenIds] = usePersistedState( `tree:${propsKey(props.items)}`, initialOpen, (v) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : null), ); const openSet = useMemo(() => new Set(openIds), [openIds]); const rows = useMemo(() => visibleRows(roots, (id) => openSet.has(id)), [roots, openSet]); return ( {rows.map(({ item, depth }) => { const isOpen = openSet.has(item.id); return ( { if (!item.folder) return; setOpenIds((prev) => prev.includes(item.id) ? prev.filter((x) => x !== item.id) : [...prev, item.id], ); }} style={{ flexDirection: "row", alignItems: "center", justifyContent: "space-between", paddingLeft: 10 + depth * 16, paddingRight: 10, paddingVertical: 5, gap: 8, }} > {item.label} {item.note !== null ? ( isNode(item.note) ? ( ) : ( {text(item.note)} ) ) : null} ); })} ); } const PROSE_LANGUAGES = new Set(["markdown", "md", "text", "txt"]); export function Code({ props }: { props: Props }) { const { theme } = useUiRuntime(); const toast = useToast(); const code = text(props.code); const language = optionalText(props.language); const wrap = language !== null && PROSE_LANGUAGES.has(language.toLowerCase()); const codeText = ( {code} ); return ( {language ?? "code"} { void copyText(code).then( () => toast.show("Copied", { variant: "success" }), () => toast.error("Could not copy"), ); }} > {wrap ? ( {codeText} ) : ( {codeText} )} ); } export function Snippet({ props }: { props: Props }) { const { theme, openFile } = useUiRuntime(); const filePath = text(props.path); const from = finiteNumber(props.from) ?? 1; const code = text(props.code); const lines = code.split("\n"); return ( { if (openFile) void openFile(filePath, Math.round(from)); }} style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingHorizontal: 10, paddingVertical: 6, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: theme.colors.border, }} > {filePath}:{Math.round(from)} {lines.map((line, idx) => ( {Math.round(from) + idx} {line} ))} ); } export function Diff({ props }: { props: Props }) { const { theme } = useUiRuntime(); const patch = text(props.patch); const lines = patch.split("\n"); return ( {lines.map((line, idx) => { const added = line.startsWith("+") && !line.startsWith("+++"); const removed = line.startsWith("-") && !line.startsWith("---"); const hunk = line.startsWith("@@"); const color = added ? theme.colors.statusSuccess : removed ? theme.colors.statusDanger : hunk ? theme.colors.accent : theme.colors.foreground; return ( {line} ); })} ); }