ExpressionInput.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import { useState, useRef, useEffect, useCallback } from 'react'
  2. import { ChevronDown, Code, X } from 'lucide-react'
  3. export interface AvailableField {
  4. path: string
  5. type: string
  6. nodeName: string
  7. nodeId: string
  8. displayName?: string
  9. isDirectUpstream?: boolean // true if this is an immediate predecessor node
  10. }
  11. interface ExpressionInputProps {
  12. value: string
  13. onChange: (value: string) => void
  14. placeholder?: string
  15. availableFields?: AvailableField[]
  16. multiline?: boolean
  17. // Set for fields that hold source code, which want a monospace face and room
  18. // to work in whatever their current contents happen to look like.
  19. codeMode?: boolean
  20. className?: string
  21. }
  22. type ContentKind = 'plain' | 'json' | 'broken-json' | 'markdown'
  23. // What someone typed into a field says what it is. A prompt, a JSON body and a
  24. // note are all "string" to the schema, so the shape of the text is the only
  25. // signal available - and it is a reliable one.
  26. function detectContentKind(value: string): ContentKind {
  27. const text = value.trim()
  28. if (!text) return 'plain'
  29. const looksStructured = /^[[{]/.test(text) && /[\]}]$/.test(text)
  30. if (looksStructured) {
  31. try {
  32. JSON.parse(text)
  33. return 'json'
  34. } catch {
  35. return 'broken-json'
  36. }
  37. }
  38. // Two or more markdown constructs, so a lone hyphen or a URL in prose does
  39. // not get called markdown.
  40. const markers = [
  41. /^#{1,6}\s+\S/m, // heading
  42. /^\s*[-*+]\s+\S/m, // bullet list
  43. /^\s*\d+\.\s+\S/m, // numbered list
  44. /\*\*[^*\n]+\*\*/, // bold
  45. /\[[^\]\n]+\]\([^)\n]+\)/, // link
  46. /^>\s+\S/m, // quote
  47. /```/, // fenced code
  48. ].filter((pattern) => pattern.test(text)).length
  49. return markers >= 2 ? 'markdown' : 'plain'
  50. }
  51. const KIND_LABELS: Record<ContentKind, { label: string; className: string } | null> = {
  52. plain: null,
  53. json: {
  54. label: 'JSON',
  55. className: 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300',
  56. },
  57. 'broken-json': {
  58. label: 'JSON with a syntax error',
  59. className: 'bg-amber-100 dark:bg-amber-900/30 text-amber-800 dark:text-amber-300',
  60. },
  61. markdown: {
  62. label: 'Markdown',
  63. className: 'bg-violet-100 dark:bg-violet-900/30 text-violet-700 dark:text-violet-300',
  64. },
  65. }
  66. const TYPE_COLORS: Record<string, string> = {
  67. string: 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300',
  68. number: 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300',
  69. boolean: 'bg-purple-100 dark:bg-purple-900/30 text-purple-800 dark:text-purple-300',
  70. object: 'bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300',
  71. array: 'bg-pink-100 dark:bg-pink-900/30 text-pink-800 dark:text-pink-300',
  72. any: 'bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-300',
  73. }
  74. export function ExpressionInput({
  75. value,
  76. onChange,
  77. placeholder,
  78. availableFields = [],
  79. multiline = false,
  80. codeMode = false,
  81. className = '',
  82. }: ExpressionInputProps) {
  83. const [showAutocomplete, setShowAutocomplete] = useState(false)
  84. const [autocompletePosition, setAutocompletePosition] = useState({ top: 0, left: 0 })
  85. const [filterText, setFilterText] = useState('')
  86. const [selectedIndex, setSelectedIndex] = useState(0)
  87. const [cursorPosition, setCursorPosition] = useState(0)
  88. const inputRef = useRef<HTMLTextAreaElement | HTMLInputElement>(null)
  89. const autocompleteRef = useRef<HTMLDivElement>(null)
  90. // Check if cursor is inside an expression {{ }}
  91. const isInsideExpression = useCallback((text: string, position: number): { inside: boolean; start: number; filter: string } => {
  92. const beforeCursor = text.slice(0, position)
  93. const lastOpenBrace = beforeCursor.lastIndexOf('{{')
  94. const lastCloseBrace = beforeCursor.lastIndexOf('}}')
  95. if (lastOpenBrace > lastCloseBrace) {
  96. const filter = beforeCursor.slice(lastOpenBrace + 2).trim()
  97. return { inside: true, start: lastOpenBrace + 2, filter }
  98. }
  99. return { inside: false, start: 0, filter: '' }
  100. }, [])
  101. // Filter fields based on input
  102. const filteredFields = availableFields.filter((field) => {
  103. const searchText = filterText.toLowerCase()
  104. return (
  105. field.path.toLowerCase().includes(searchText) ||
  106. field.nodeName.toLowerCase().includes(searchText) ||
  107. (field.displayName?.toLowerCase().includes(searchText) ?? false)
  108. )
  109. })
  110. // Handle input change
  111. const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
  112. const newValue = e.target.value
  113. const newPosition = e.target.selectionStart || 0
  114. onChange(newValue)
  115. setCursorPosition(newPosition)
  116. const { inside, filter } = isInsideExpression(newValue, newPosition)
  117. if (inside) {
  118. setFilterText(filter)
  119. setShowAutocomplete(true)
  120. setSelectedIndex(0)
  121. // Calculate autocomplete position
  122. if (inputRef.current) {
  123. const rect = inputRef.current.getBoundingClientRect()
  124. setAutocompletePosition({
  125. top: rect.height + 4,
  126. left: 0,
  127. })
  128. }
  129. } else {
  130. setShowAutocomplete(false)
  131. }
  132. }
  133. // Handle cursor position changes
  134. const handleSelect = (e: React.SyntheticEvent<HTMLTextAreaElement | HTMLInputElement>) => {
  135. const target = e.target as HTMLTextAreaElement | HTMLInputElement
  136. const newPosition = target.selectionStart || 0
  137. setCursorPosition(newPosition)
  138. const { inside, filter } = isInsideExpression(value, newPosition)
  139. if (inside && availableFields.length > 0) {
  140. setFilterText(filter)
  141. setShowAutocomplete(true)
  142. } else {
  143. setShowAutocomplete(false)
  144. }
  145. }
  146. // Insert selected field
  147. const insertField = useCallback((field: AvailableField) => {
  148. const { inside, start } = isInsideExpression(value, cursorPosition)
  149. if (!inside) return
  150. // Build the expression based on whether this is a direct upstream node
  151. // Direct upstream: raw path (no $node accessor)
  152. // Non-direct upstream: full expression with node accessor
  153. const expression = field.isDirectUpstream
  154. ? field.path
  155. : `$node["${field.nodeName}"].${field.path}`
  156. // Find the end of current filter text
  157. const beforeFilter = value.slice(0, start)
  158. const afterCursor = value.slice(cursorPosition)
  159. // Check if there's a closing }}
  160. const closingBrace = afterCursor.indexOf('}}')
  161. const afterExpression = closingBrace >= 0 ? afterCursor.slice(closingBrace) : '}}'
  162. const newValue = beforeFilter + expression + afterExpression
  163. onChange(newValue)
  164. setShowAutocomplete(false)
  165. // Focus back on input
  166. setTimeout(() => {
  167. if (inputRef.current) {
  168. inputRef.current.focus()
  169. const newPosition = beforeFilter.length + expression.length
  170. inputRef.current.setSelectionRange(newPosition, newPosition)
  171. }
  172. }, 0)
  173. }, [value, cursorPosition, isInsideExpression, onChange])
  174. // Keyboard navigation
  175. const handleKeyDown = (e: React.KeyboardEvent) => {
  176. if (!showAutocomplete) return
  177. switch (e.key) {
  178. case 'ArrowDown':
  179. e.preventDefault()
  180. setSelectedIndex((prev) => Math.min(prev + 1, filteredFields.length - 1))
  181. break
  182. case 'ArrowUp':
  183. e.preventDefault()
  184. setSelectedIndex((prev) => Math.max(prev - 1, 0))
  185. break
  186. case 'Enter':
  187. if (filteredFields[selectedIndex]) {
  188. e.preventDefault()
  189. insertField(filteredFields[selectedIndex])
  190. }
  191. break
  192. case 'Escape':
  193. e.preventDefault()
  194. setShowAutocomplete(false)
  195. break
  196. case 'Tab':
  197. if (filteredFields[selectedIndex]) {
  198. e.preventDefault()
  199. insertField(filteredFields[selectedIndex])
  200. }
  201. break
  202. }
  203. }
  204. // Close autocomplete when clicking outside
  205. useEffect(() => {
  206. const handleClickOutside = (e: MouseEvent) => {
  207. if (
  208. autocompleteRef.current &&
  209. !autocompleteRef.current.contains(e.target as Node) &&
  210. inputRef.current &&
  211. !inputRef.current.contains(e.target as Node)
  212. ) {
  213. setShowAutocomplete(false)
  214. }
  215. }
  216. document.addEventListener('mousedown', handleClickOutside)
  217. return () => document.removeEventListener('mousedown', handleClickOutside)
  218. }, [])
  219. // Insert expression template
  220. const insertExpressionTemplate = () => {
  221. const template = '{{ }}'
  222. const newValue = value + template
  223. onChange(newValue)
  224. setTimeout(() => {
  225. if (inputRef.current) {
  226. inputRef.current.focus()
  227. const position = value.length + 3 // Position cursor between {{ and }}
  228. inputRef.current.setSelectionRange(position, position)
  229. setCursorPosition(position)
  230. setShowAutocomplete(true)
  231. setFilterText('')
  232. }
  233. }, 0)
  234. }
  235. const kind = detectContentKind(value || '')
  236. const kindLabel = KIND_LABELS[kind]
  237. const isCode = codeMode || kind === 'json' || kind === 'broken-json'
  238. // The field is always a textarea so it can grow with what is typed into it
  239. // without swapping the element under the cursor, which would lose focus and
  240. // the caret mid-sentence.
  241. useEffect(() => {
  242. const el = inputRef.current as HTMLTextAreaElement | null
  243. if (!el) return
  244. el.style.height = 'auto'
  245. const minHeight = codeMode ? 200 : multiline ? 80 : 38
  246. el.style.height = Math.min(Math.max(el.scrollHeight, minHeight), 420) + 'px'
  247. }, [value, multiline, codeMode])
  248. const formatJson = () => {
  249. try {
  250. onChange(JSON.stringify(JSON.parse(value), null, 2))
  251. } catch {
  252. // Only offered when the value parses, so there is nothing to report here.
  253. }
  254. }
  255. return (
  256. <div className={`relative ${className}`}>
  257. <div className="flex items-stretch">
  258. <div className="relative flex-1">
  259. <textarea
  260. ref={inputRef as any}
  261. value={value}
  262. onChange={handleChange}
  263. onSelect={handleSelect}
  264. onKeyDown={handleKeyDown}
  265. placeholder={placeholder || 'Enter value or use {{ }} for expressions'}
  266. className={`w-full px-3 py-2 pr-10 border border-gray-200 dark:border-slate-600 rounded-l-lg text-sm bg-white dark:bg-slate-900 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 resize-y overflow-hidden ${
  267. isCode ? 'font-mono text-xs' : ''
  268. }`}
  269. rows={1}
  270. />
  271. {/* Clear button */}
  272. {value && (
  273. <button
  274. onClick={() => onChange('')}
  275. className="absolute right-2 top-2 p-1 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
  276. title="Clear"
  277. >
  278. <X className="w-4 h-4" />
  279. </button>
  280. )}
  281. </div>
  282. {/* Expression helper button */}
  283. <button
  284. onClick={insertExpressionTemplate}
  285. className="px-3 border border-l-0 border-gray-200 dark:border-slate-600 rounded-r-lg bg-gray-50 dark:bg-slate-800 hover:bg-gray-100 dark:hover:bg-slate-700 text-gray-600 dark:text-gray-400 flex items-center gap-1"
  286. title="Insert expression {{ }}"
  287. >
  288. <Code className="w-4 h-4" />
  289. <ChevronDown className="w-3 h-3" />
  290. </button>
  291. </div>
  292. {/* Autocomplete dropdown */}
  293. {showAutocomplete && filteredFields.length > 0 && (
  294. <div
  295. ref={autocompleteRef}
  296. className="absolute z-50 w-full bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-lg shadow-lg mt-1 max-h-60 overflow-auto"
  297. style={{
  298. top: autocompletePosition.top,
  299. left: autocompletePosition.left,
  300. }}
  301. >
  302. <div className="p-2 text-xs text-gray-500 dark:text-gray-400 border-b border-gray-200 dark:border-slate-700 bg-gray-50 dark:bg-slate-900">
  303. Available Fields {filterText && `(filtered: "${filterText}")`}
  304. </div>
  305. {filteredFields.map((field, index) => (
  306. <button
  307. key={`${field.nodeId}-${field.path}`}
  308. onClick={() => insertField(field)}
  309. className={`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-gray-50 dark:hover:bg-slate-700 ${
  310. index === selectedIndex ? 'bg-primary-50 dark:bg-primary-900/20' : ''
  311. }`}
  312. >
  313. <span
  314. className={`px-1.5 py-0.5 rounded text-[10px] font-medium ${
  315. TYPE_COLORS[field.type] || TYPE_COLORS.any
  316. }`}
  317. >
  318. {field.type}
  319. </span>
  320. <div className="flex-1 min-w-0">
  321. <div className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
  322. {field.displayName || field.path}
  323. </div>
  324. <div className="text-xs text-gray-500 dark:text-gray-400 truncate">
  325. {field.nodeName} &rarr; {field.path}
  326. </div>
  327. </div>
  328. </button>
  329. ))}
  330. </div>
  331. )}
  332. {/* What the field currently holds, and the one action that content wants */}
  333. {kindLabel && (
  334. <div className="flex items-center gap-2 mt-1 text-xs">
  335. <span className={`px-1.5 py-0.5 rounded font-medium ${kindLabel.className}`}>
  336. {kindLabel.label}
  337. </span>
  338. {kind === 'json' && (
  339. <button
  340. onClick={formatJson}
  341. className="text-primary-600 dark:text-primary-400 hover:underline"
  342. title="Re-indent this JSON"
  343. >
  344. Format
  345. </button>
  346. )}
  347. {kind === 'broken-json' && (
  348. <span className="text-gray-500 dark:text-gray-400">
  349. Starts and ends like JSON but does not parse - check quotes and commas
  350. </span>
  351. )}
  352. {kind === 'markdown' && (
  353. <span className="text-gray-500 dark:text-gray-400">
  354. <code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">**bold**</code>{' '}
  355. <code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">- list</code>{' '}
  356. <code className="bg-gray-100 dark:bg-slate-700 px-1 rounded"># heading</code>{' '}
  357. <code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">[text](url)</code>
  358. </span>
  359. )}
  360. </div>
  361. )}
  362. {/* Expression syntax help */}
  363. {showAutocomplete && filteredFields.length === 0 && (
  364. <div
  365. ref={autocompleteRef}
  366. className="absolute z-50 w-full bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-lg shadow-lg mt-1 p-3"
  367. style={{
  368. top: autocompletePosition.top,
  369. left: autocompletePosition.left,
  370. }}
  371. >
  372. <div className="text-xs text-gray-600 dark:text-gray-400">
  373. <div className="font-medium mb-2">Expression Syntax:</div>
  374. <ul className="space-y-1 text-gray-500 dark:text-gray-400">
  375. <li><code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">data.field</code> - Access input data</li>
  376. <li><code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">$node["Name"].field</code> - Access node output</li>
  377. <li><code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">$trigger.timestamp</code> - Trigger data</li>
  378. </ul>
  379. </div>
  380. </div>
  381. )}
  382. </div>
  383. )
  384. }