| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469 |
- import { useState, useRef, useEffect, useCallback } from 'react'
- import { ChevronDown, Code, X } from 'lucide-react'
- export interface AvailableField {
- path: string
- type: string
- nodeName: string
- nodeId: string
- displayName?: string
- isDirectUpstream?: boolean // true if this is an immediate predecessor node
- }
- interface ExpressionInputProps {
- value: string
- onChange: (value: string) => void
- placeholder?: string
- availableFields?: AvailableField[]
- multiline?: boolean
- className?: string
- // 'path' when the setting wants a bare path - data.result.items - rather than
- // an expression. The available-data panel always hands over the {{ }} form,
- // because that is what most settings take; dropping one into a path field
- // would otherwise leave braces the node has to be lenient about.
- valueKind?: 'path' | 'expression'
- }
- type ContentKind = 'plain' | 'json' | 'templated-json' | 'broken-json' | 'markdown'
- // What someone typed into a field says what it is. A prompt, a JSON body and a
- // note are all "string" to the schema, so the shape of the text is the only
- // signal available - and it is a reliable one.
- function detectContentKind(value: string): ContentKind {
- const text = value.trim()
- if (!text) return 'plain'
- const looksStructured = /^[[{]/.test(text) && /[\]}]$/.test(text)
- if (looksStructured) {
- try {
- JSON.parse(text)
- return 'json'
- } catch {
- // A graph or request body written for this system holds placeholders
- // where values will go, and a placeholder standing in for a number is not
- // JSON until it is filled in. That is the field working as intended, not
- // a mistake, so it is only called broken if it still fails once the
- // placeholders are given a value.
- const filled = text
- .replace(/<<[^>]*>>/g, '0')
- .replace(/\{\{[^}]*\}\}/g, '0')
- try {
- JSON.parse(filled)
- return 'templated-json'
- } catch {
- return 'broken-json'
- }
- }
- }
- // Two or more markdown constructs, so a lone hyphen or a URL in prose does
- // not get called markdown.
- const markers = [
- /^#{1,6}\s+\S/m, // heading
- /^\s*[-*+]\s+\S/m, // bullet list
- /^\s*\d+\.\s+\S/m, // numbered list
- /\*\*[^*\n]+\*\*/, // bold
- /\[[^\]\n]+\]\([^)\n]+\)/, // link
- /^>\s+\S/m, // quote
- /```/, // fenced code
- ].filter((pattern) => pattern.test(text)).length
- return markers >= 2 ? 'markdown' : 'plain'
- }
- const KIND_LABELS: Record<ContentKind, { label: string; className: string } | null> = {
- plain: null,
- json: {
- label: 'JSON',
- className: 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300',
- },
- 'templated-json': {
- label: 'JSON with placeholders',
- className: 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300',
- },
- 'broken-json': {
- label: 'JSON with a syntax error',
- className: 'bg-amber-100 dark:bg-amber-900/30 text-amber-800 dark:text-amber-300',
- },
- markdown: {
- label: 'Markdown',
- className: 'bg-violet-100 dark:bg-violet-900/30 text-violet-700 dark:text-violet-300',
- },
- }
- const TYPE_COLORS: Record<string, string> = {
- string: 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300',
- number: 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300',
- boolean: 'bg-purple-100 dark:bg-purple-900/30 text-purple-800 dark:text-purple-300',
- object: 'bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300',
- array: 'bg-pink-100 dark:bg-pink-900/30 text-pink-800 dark:text-pink-300',
- any: 'bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-300',
- }
- export function ExpressionInput({
- value,
- onChange,
- placeholder,
- availableFields = [],
- multiline = false,
- className = '',
- valueKind = 'expression',
- }: ExpressionInputProps) {
- // A setting that wants a path gets the path, not the {{ }} wrapping it. Only
- // the plain form is unwrapped: {{$node["X"].y}} names a different node, which
- // a path cannot express, so that is left alone rather than silently turned
- // into something that would read the wrong node.
- const handleDrop = (event: React.DragEvent<HTMLInputElement | HTMLTextAreaElement>) => {
- const dropped = event.dataTransfer.getData('text/plain')
- if (!dropped) return
- if (valueKind !== 'path') return
- const plain = /^\{\{\s*([^${}][^{}]*?)\s*\}\}$/.exec(dropped)
- if (!plain) return
- event.preventDefault()
- onChange(plain[1])
- }
- const [showAutocomplete, setShowAutocomplete] = useState(false)
- const [autocompletePosition, setAutocompletePosition] = useState({ top: 0, left: 0 })
- const [filterText, setFilterText] = useState('')
- const [selectedIndex, setSelectedIndex] = useState(0)
- const [cursorPosition, setCursorPosition] = useState(0)
- const inputRef = useRef<HTMLTextAreaElement | HTMLInputElement>(null)
- const autocompleteRef = useRef<HTMLDivElement>(null)
- // Check if cursor is inside an expression {{ }}
- const isInsideExpression = useCallback((text: string, position: number): { inside: boolean; start: number; filter: string } => {
- const beforeCursor = text.slice(0, position)
- const lastOpenBrace = beforeCursor.lastIndexOf('{{')
- const lastCloseBrace = beforeCursor.lastIndexOf('}}')
- if (lastOpenBrace > lastCloseBrace) {
- const filter = beforeCursor.slice(lastOpenBrace + 2).trim()
- return { inside: true, start: lastOpenBrace + 2, filter }
- }
- return { inside: false, start: 0, filter: '' }
- }, [])
- // Filter fields based on input
- const filteredFields = availableFields.filter((field) => {
- const searchText = filterText.toLowerCase()
- return (
- field.path.toLowerCase().includes(searchText) ||
- field.nodeName.toLowerCase().includes(searchText) ||
- (field.displayName?.toLowerCase().includes(searchText) ?? false)
- )
- })
- // Handle input change
- const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
- const newValue = e.target.value
- const newPosition = e.target.selectionStart || 0
- onChange(newValue)
- setCursorPosition(newPosition)
- const { inside, filter } = isInsideExpression(newValue, newPosition)
- if (inside) {
- setFilterText(filter)
- setShowAutocomplete(true)
- setSelectedIndex(0)
- // Calculate autocomplete position
- if (inputRef.current) {
- const rect = inputRef.current.getBoundingClientRect()
- setAutocompletePosition({
- top: rect.height + 4,
- left: 0,
- })
- }
- } else {
- setShowAutocomplete(false)
- }
- }
- // Handle cursor position changes
- const handleSelect = (e: React.SyntheticEvent<HTMLTextAreaElement | HTMLInputElement>) => {
- const target = e.target as HTMLTextAreaElement | HTMLInputElement
- const newPosition = target.selectionStart || 0
- setCursorPosition(newPosition)
- const { inside, filter } = isInsideExpression(value, newPosition)
- if (inside && availableFields.length > 0) {
- setFilterText(filter)
- setShowAutocomplete(true)
- } else {
- setShowAutocomplete(false)
- }
- }
- // Insert selected field
- const insertField = useCallback((field: AvailableField) => {
- const { inside, start } = isInsideExpression(value, cursorPosition)
- if (!inside) return
- // Build the expression based on whether this is a direct upstream node
- // Direct upstream: raw path (no $node accessor)
- // Non-direct upstream: full expression with node accessor
- const expression = field.isDirectUpstream
- ? field.path
- : `$node["${field.nodeName}"].${field.path}`
- // Find the end of current filter text
- const beforeFilter = value.slice(0, start)
- const afterCursor = value.slice(cursorPosition)
- // Check if there's a closing }}
- const closingBrace = afterCursor.indexOf('}}')
- const afterExpression = closingBrace >= 0 ? afterCursor.slice(closingBrace) : '}}'
- const newValue = beforeFilter + expression + afterExpression
- onChange(newValue)
- setShowAutocomplete(false)
- // Focus back on input
- setTimeout(() => {
- if (inputRef.current) {
- inputRef.current.focus()
- const newPosition = beforeFilter.length + expression.length
- inputRef.current.setSelectionRange(newPosition, newPosition)
- }
- }, 0)
- }, [value, cursorPosition, isInsideExpression, onChange])
- // Keyboard navigation
- const handleKeyDown = (e: React.KeyboardEvent) => {
- if (!showAutocomplete) return
- switch (e.key) {
- case 'ArrowDown':
- e.preventDefault()
- setSelectedIndex((prev) => Math.min(prev + 1, filteredFields.length - 1))
- break
- case 'ArrowUp':
- e.preventDefault()
- setSelectedIndex((prev) => Math.max(prev - 1, 0))
- break
- case 'Enter':
- if (filteredFields[selectedIndex]) {
- e.preventDefault()
- insertField(filteredFields[selectedIndex])
- }
- break
- case 'Escape':
- e.preventDefault()
- setShowAutocomplete(false)
- break
- case 'Tab':
- if (filteredFields[selectedIndex]) {
- e.preventDefault()
- insertField(filteredFields[selectedIndex])
- }
- break
- }
- }
- // Close autocomplete when clicking outside
- useEffect(() => {
- const handleClickOutside = (e: MouseEvent) => {
- if (
- autocompleteRef.current &&
- !autocompleteRef.current.contains(e.target as Node) &&
- inputRef.current &&
- !inputRef.current.contains(e.target as Node)
- ) {
- setShowAutocomplete(false)
- }
- }
- document.addEventListener('mousedown', handleClickOutside)
- return () => document.removeEventListener('mousedown', handleClickOutside)
- }, [])
- // Insert expression template
- const insertExpressionTemplate = () => {
- const template = '{{ }}'
- const newValue = value + template
- onChange(newValue)
- setTimeout(() => {
- if (inputRef.current) {
- inputRef.current.focus()
- const position = value.length + 3 // Position cursor between {{ and }}
- inputRef.current.setSelectionRange(position, position)
- setCursorPosition(position)
- setShowAutocomplete(true)
- setFilterText('')
- }
- }, 0)
- }
- const kind = detectContentKind(value || '')
- const kindLabel = KIND_LABELS[kind]
- const isCode = kind === 'json' || kind === 'templated-json' || kind === 'broken-json'
- // The field is always a textarea so it can grow with what is typed into it
- // without swapping the element under the cursor, which would lose focus and
- // the caret mid-sentence.
- useEffect(() => {
- const el = inputRef.current as HTMLTextAreaElement | null
- if (!el) return
- el.style.height = 'auto'
- const minHeight = multiline ? 80 : 38
- el.style.height = Math.min(Math.max(el.scrollHeight, minHeight), 420) + 'px'
- }, [value, multiline])
- const formatJson = () => {
- try {
- onChange(JSON.stringify(JSON.parse(value), null, 2))
- } catch {
- // Only offered when the value parses, so there is nothing to report here.
- }
- }
- return (
- <div className={`relative ${className}`}>
- <div className="flex items-stretch">
- <div className="relative flex-1">
- <textarea
- ref={inputRef as any}
- value={value}
- onChange={handleChange}
- onSelect={handleSelect}
- onKeyDown={handleKeyDown}
- onDrop={handleDrop}
- placeholder={
- placeholder ||
- (valueKind === 'path'
- ? 'A path such as data.result.items'
- : 'Enter value or use {{ }} for expressions')
- }
- 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 ${
- isCode ? 'font-mono text-xs' : ''
- }`}
- rows={1}
- />
- {/* Clear button */}
- {value && (
- <button
- onClick={() => onChange('')}
- className="absolute right-2 top-2 p-1 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400"
- title="Clear"
- >
- <X className="w-4 h-4" />
- </button>
- )}
- </div>
- {/* Expression helper button */}
- <button
- onClick={insertExpressionTemplate}
- 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"
- title="Insert expression {{ }}"
- >
- <Code className="w-4 h-4" />
- <ChevronDown className="w-3 h-3" />
- </button>
- </div>
- {/* Autocomplete dropdown */}
- {showAutocomplete && filteredFields.length > 0 && (
- <div
- ref={autocompleteRef}
- 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"
- style={{
- top: autocompletePosition.top,
- left: autocompletePosition.left,
- }}
- >
- <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">
- Available Fields {filterText && `(filtered: "${filterText}")`}
- </div>
- {filteredFields.map((field, index) => (
- <button
- key={`${field.nodeId}-${field.path}`}
- onClick={() => insertField(field)}
- className={`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-gray-50 dark:hover:bg-slate-700 ${
- index === selectedIndex ? 'bg-primary-50 dark:bg-primary-900/20' : ''
- }`}
- >
- <span
- className={`px-1.5 py-0.5 rounded text-[10px] font-medium ${
- TYPE_COLORS[field.type] || TYPE_COLORS.any
- }`}
- >
- {field.type}
- </span>
- <div className="flex-1 min-w-0">
- <div className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
- {field.displayName || field.path}
- </div>
- <div className="text-xs text-gray-500 dark:text-gray-400 truncate">
- {field.nodeName} → {field.path}
- </div>
- </div>
- </button>
- ))}
- </div>
- )}
- {/* What the field currently holds, and the one action that content wants */}
- {kindLabel && (
- <div className="flex items-center gap-2 mt-1 text-xs">
- <span className={`px-1.5 py-0.5 rounded font-medium ${kindLabel.className}`}>
- {kindLabel.label}
- </span>
- {kind === 'json' && (
- <button
- onClick={formatJson}
- className="text-primary-600 dark:text-primary-400 hover:underline"
- title="Re-indent this JSON"
- >
- Format
- </button>
- )}
- {kind === 'templated-json' && (
- <span className="text-gray-500 dark:text-gray-400">
- Valid once the placeholders are filled in
- </span>
- )}
- {kind === 'broken-json' && (
- <span className="text-gray-500 dark:text-gray-400">
- Starts and ends like JSON but does not parse - check quotes and commas
- </span>
- )}
- {kind === 'markdown' && (
- <span className="text-gray-500 dark:text-gray-400">
- <code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">**bold**</code>{' '}
- <code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">- list</code>{' '}
- <code className="bg-gray-100 dark:bg-slate-700 px-1 rounded"># heading</code>{' '}
- <code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">[text](url)</code>
- </span>
- )}
- </div>
- )}
- {/* Expression syntax help */}
- {showAutocomplete && filteredFields.length === 0 && (
- <div
- ref={autocompleteRef}
- 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"
- style={{
- top: autocompletePosition.top,
- left: autocompletePosition.left,
- }}
- >
- <div className="text-xs text-gray-600 dark:text-gray-400">
- <div className="font-medium mb-2">Expression Syntax:</div>
- <ul className="space-y-1 text-gray-500 dark:text-gray-400">
- <li><code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">data.field</code> - Access input data</li>
- <li><code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">$node["Name"].field</code> - Access node output</li>
- <li><code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">$trigger.timestamp</code> - Trigger data</li>
- </ul>
- </div>
- </div>
- )}
- </div>
- )
- }
|