|
| 1 | +import { Stack, TextField, IconButton, Chip, Typography } from "@mui/material"; |
| 2 | +import AddIcon from "@mui/icons-material/Add"; |
| 3 | +import { useState } from "react"; |
| 4 | + |
| 5 | +// Simple CEL validation function (stub, replace with real parser) |
| 6 | +const validateCel = (expr: string): boolean => { |
| 7 | + try { |
| 8 | + if (!expr) return true; // empty allowed |
| 9 | + // TODO: Replace with actual CEL parser/validation |
| 10 | + // For now: basic check for balanced parentheses |
| 11 | + let count = 0; |
| 12 | + for (const c of expr) { |
| 13 | + if (c === "(") count++; |
| 14 | + if (c === ")") count--; |
| 15 | + if (count < 0) return false; |
| 16 | + } |
| 17 | + return count === 0; |
| 18 | + } catch { |
| 19 | + return false; |
| 20 | + } |
| 21 | +}; |
| 22 | + |
| 23 | +interface CelExprBuilderProps { |
| 24 | + value: string[]; |
| 25 | + onChange: (value: string[]) => void; |
| 26 | + label?: string; |
| 27 | + placeholder?: string; |
| 28 | +} |
| 29 | + |
| 30 | +export default function CelExprBuilder({ |
| 31 | + value, |
| 32 | + onChange, |
| 33 | + label = "CEL Expressions", |
| 34 | + placeholder = "Enter CEL expression", |
| 35 | +}: CelExprBuilderProps) { |
| 36 | + const [input, setInput] = useState(""); |
| 37 | + |
| 38 | + const addExpr = () => { |
| 39 | + const expr = input.trim(); |
| 40 | + if (!expr) return; |
| 41 | + |
| 42 | + const newValue = [...value, expr]; |
| 43 | + onChange(newValue); |
| 44 | + setInput(""); |
| 45 | + }; |
| 46 | + |
| 47 | + const removeExpr = (index: number) => { |
| 48 | + onChange(value.filter((_, i) => i !== index)); |
| 49 | + }; |
| 50 | + |
| 51 | + return ( |
| 52 | + <Stack spacing={1}> |
| 53 | + <Typography variant="subtitle2">{label}</Typography> |
| 54 | + |
| 55 | + {/* Existing expressions as Chips */} |
| 56 | + <Stack direction="row" spacing={1} flexWrap="wrap"> |
| 57 | + {value.map((expr, idx) => { |
| 58 | + const valid = validateCel(expr); |
| 59 | + return ( |
| 60 | + <Chip |
| 61 | + key={idx} |
| 62 | + label={expr} |
| 63 | + color={valid ? "primary" : "error"} |
| 64 | + onDelete={() => removeExpr(idx)} |
| 65 | + /> |
| 66 | + ); |
| 67 | + })} |
| 68 | + </Stack> |
| 69 | + |
| 70 | + {/* Input field for new expression */} |
| 71 | + <Stack direction="row" spacing={1}> |
| 72 | + <TextField |
| 73 | + fullWidth |
| 74 | + size="small" |
| 75 | + placeholder={placeholder} |
| 76 | + value={input} |
| 77 | + onChange={(e) => setInput(e.target.value)} |
| 78 | + error={(input && !validateCel(input)) || false} |
| 79 | + helperText={input && !validateCel(input) ? "Invalid CEL syntax" : ""} |
| 80 | + /> |
| 81 | + <IconButton |
| 82 | + color="primary" |
| 83 | + onClick={addExpr} |
| 84 | + disabled={!input || !validateCel(input)} |
| 85 | + > |
| 86 | + <AddIcon /> |
| 87 | + </IconButton> |
| 88 | + </Stack> |
| 89 | + </Stack> |
| 90 | + ); |
| 91 | +} |
0 commit comments