ExpressionInput.tsx 17 KB

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