import React, { useState, useEffect, useRef } from "react"; /** * FormulaBar – Excel-like formula bar. * Props: * cellAddress – "B3", "A1", etc. (empty string if nothing selected) * formulaDisplay – raw string to show (formula text like "=SUM(Revenue)" or a plain value) * onFormulaApply – (newValue: string) => void called on Enter / ✔ * readOnly – true for Summary sheet (no editing) * dark – boolean */ function FormulaBar({ cellAddress, formulaDisplay, onFormulaApply, readOnly = false, dark }) { const [localVal, setLocalVal] = useState(""); const [editing, setEditing] = useState(false); const inputRef = useRef(); // Sync incoming value whenever the selected cell changes useEffect(() => { setLocalVal(formulaDisplay ?? ""); setEditing(false); }, [formulaDisplay, cellAddress]); const isFormula = localVal.trim().startsWith("="); const hasCell = !!cellAddress; const apply = () => { if (!readOnly && hasCell) { onFormulaApply?.(localVal); } setEditing(false); inputRef.current?.blur(); }; const cancel = () => { setLocalVal(formulaDisplay ?? ""); setEditing(false); inputRef.current?.blur(); }; const onKeyDown = (e) => { if (e.key === "Enter") { e.preventDefault(); apply(); } if (e.key === "Escape") { e.preventDefault(); cancel(); } }; // ── Token colours ────────────────────────────────────────────── const surface = dark ? "#141d2e" : "#ffffff"; const border = dark ? "#1e2843" : "#d1d5db"; const textCol = dark ? "#cbd5e1" : "#1e293b"; const muted = dark ? "#4a5a7a" : "#94a3b8"; const accent = "#3b82f6"; return (
{/* Cell address box */}
{cellAddress || ""}
{/* Thin separator */}
{/* Cancel / Accept – only while editing */} {editing && !readOnly && ( <> )} {/* fx badge */}
f x
{/* Main input */}
{ setLocalVal(e.target.value); setEditing(true); }} onFocus={() => { if (!readOnly && hasCell) setEditing(true); }} onBlur={() => setTimeout(() => setEditing(false), 180)} onKeyDown={onKeyDown} style={{ width:"100%", height:"21px", padding:"0 8px", border: editing ? `1px solid ${accent}` : "1px solid transparent", borderRadius:"3px", background: editing ? (dark ? "#0f1828" : "#fefce8") : "transparent", outline:"none", fontSize:"12.5px", fontFamily: isFormula ? "'Courier New', monospace" : "inherit", fontWeight: isFormula ? "500" : "400", color: isFormula ? (dark ? "#60a5fa" : "#1d4ed8") : textCol, cursor: (!readOnly && hasCell) ? "text" : "default", transition:"border 0.15s, background 0.15s", boxSizing:"border-box", }} />
{/* Formula badge on the right */} {isFormula && (
FORMULA
)} {readOnly && hasCell && (
read-only
)}
); } export default FormulaBar;