|
| 1 | +import { useState, useCallback, useMemo } from 'react' |
| 2 | +import CodeMirror from '@uiw/react-codemirror' |
| 3 | +import { autocompletion, type CompletionContext, type CompletionResult } from '@codemirror/autocomplete' |
| 4 | +import { EditorView } from '@codemirror/view' |
| 5 | + |
| 6 | +export interface TemplateItem { |
| 7 | + key: string |
| 8 | + valueType: string |
| 9 | +} |
| 10 | + |
| 11 | +interface ExpressionEditorProps { |
| 12 | + value: string |
| 13 | + onChange: (value: string) => void |
| 14 | + placeholder?: string |
| 15 | + templateItems: TemplateItem[] |
| 16 | + onValidate?: (expression: string) => Promise<{ valid: boolean; error?: string }> |
| 17 | +} |
| 18 | + |
| 19 | +const BUILTIN_VARS = [ |
| 20 | + { label: '{user.tenant}', detail: 'string', apply: '{user.tenant}' }, |
| 21 | + { label: '{user.username}', detail: 'string', apply: '{user.username}' }, |
| 22 | + { label: '{user.id}', detail: 'string', apply: '{user.id}' }, |
| 23 | +] |
| 24 | + |
| 25 | +function templateCompletionSource(items: TemplateItem[]) { |
| 26 | + return (context: CompletionContext): CompletionResult | null => { |
| 27 | + // Match {user. followed by optional word chars and optional closing brace |
| 28 | + const match = context.matchBefore(/\{user\.[\w]*\}?/) |
| 29 | + if (!match) return null |
| 30 | + |
| 31 | + const custom = items.map((a) => ({ |
| 32 | + label: `{user.${a.key}}`, |
| 33 | + detail: a.valueType === 'list' ? 'list (use with IN)' : a.valueType, |
| 34 | + apply: `{user.${a.key}}`, |
| 35 | + })) |
| 36 | + |
| 37 | + return { |
| 38 | + from: match.from, |
| 39 | + options: [...BUILTIN_VARS, ...custom], |
| 40 | + filter: true, |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +const compactTheme = EditorView.theme({ |
| 46 | + '&': { fontSize: '14px' }, |
| 47 | + '.cm-editor': { maxHeight: '120px', overflow: 'auto' }, |
| 48 | + '.cm-content': { padding: '6px 10px', fontFamily: 'ui-monospace, monospace' }, |
| 49 | + '.cm-line': { lineHeight: '1.5' }, |
| 50 | + '.cm-placeholder': { color: '#9ca3af' }, |
| 51 | + '.cm-focused': { outline: 'none' }, |
| 52 | +}) |
| 53 | + |
| 54 | +export function ExpressionEditor({ |
| 55 | + value, |
| 56 | + onChange, |
| 57 | + placeholder, |
| 58 | + templateItems, |
| 59 | + onValidate, |
| 60 | +}: ExpressionEditorProps) { |
| 61 | + const [validationState, setValidationState] = useState< |
| 62 | + 'idle' | 'loading' | 'valid' | 'invalid' |
| 63 | + >('idle') |
| 64 | + const [validationError, setValidationError] = useState<string>('') |
| 65 | + |
| 66 | + const handleChange = useCallback( |
| 67 | + (val: string) => { |
| 68 | + onChange(val) |
| 69 | + // Reset validation state when expression changes |
| 70 | + if (validationState !== 'idle') { |
| 71 | + setValidationState('idle') |
| 72 | + setValidationError('') |
| 73 | + } |
| 74 | + }, |
| 75 | + [onChange, validationState], |
| 76 | + ) |
| 77 | + |
| 78 | + const handleValidate = useCallback(async () => { |
| 79 | + if (!onValidate || !value.trim()) return |
| 80 | + setValidationState('loading') |
| 81 | + try { |
| 82 | + const result = await onValidate(value) |
| 83 | + if (result.valid) { |
| 84 | + setValidationState('valid') |
| 85 | + setValidationError('') |
| 86 | + } else { |
| 87 | + setValidationState('invalid') |
| 88 | + setValidationError(result.error ?? 'Invalid expression') |
| 89 | + } |
| 90 | + } catch { |
| 91 | + setValidationState('invalid') |
| 92 | + setValidationError('Validation request failed') |
| 93 | + } |
| 94 | + }, [onValidate, value]) |
| 95 | + |
| 96 | + const extensions = useMemo( |
| 97 | + () => [ |
| 98 | + autocompletion({ override: [templateCompletionSource(templateItems)] }), |
| 99 | + compactTheme, |
| 100 | + ], |
| 101 | + [templateItems], |
| 102 | + ) |
| 103 | + |
| 104 | + return ( |
| 105 | + <div> |
| 106 | + <div className="flex items-center gap-2"> |
| 107 | + <div |
| 108 | + className={`flex-1 border rounded-lg overflow-hidden ${ |
| 109 | + validationState === 'invalid' |
| 110 | + ? 'border-red-400' |
| 111 | + : validationState === 'valid' |
| 112 | + ? 'border-green-400' |
| 113 | + : 'border-gray-300 focus-within:ring-2 focus-within:ring-blue-500 focus-within:border-blue-500' |
| 114 | + }`} |
| 115 | + > |
| 116 | + <CodeMirror |
| 117 | + value={value} |
| 118 | + onChange={handleChange} |
| 119 | + placeholder={placeholder} |
| 120 | + basicSetup={{ |
| 121 | + lineNumbers: false, |
| 122 | + foldGutter: false, |
| 123 | + highlightActiveLine: false, |
| 124 | + autocompletion: false, |
| 125 | + }} |
| 126 | + extensions={extensions} |
| 127 | + /> |
| 128 | + </div> |
| 129 | + {onValidate && ( |
| 130 | + <button |
| 131 | + type="button" |
| 132 | + onClick={handleValidate} |
| 133 | + disabled={validationState === 'loading' || !value.trim()} |
| 134 | + className="shrink-0 px-2 py-1.5 text-xs font-medium rounded-md border border-gray-300 bg-white text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed" |
| 135 | + title="Validate expression syntax" |
| 136 | + > |
| 137 | + {validationState === 'loading' ? ( |
| 138 | + <span className="inline-block w-4 h-4 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin" /> |
| 139 | + ) : validationState === 'valid' ? ( |
| 140 | + <span className="text-green-600">✓</span> |
| 141 | + ) : validationState === 'invalid' ? ( |
| 142 | + <span className="text-red-600">✗</span> |
| 143 | + ) : ( |
| 144 | + 'Check' |
| 145 | + )} |
| 146 | + </button> |
| 147 | + )} |
| 148 | + </div> |
| 149 | + {validationState === 'invalid' && validationError && ( |
| 150 | + <p className="text-xs text-red-500 mt-1">{validationError}</p> |
| 151 | + )} |
| 152 | + </div> |
| 153 | + ) |
| 154 | +} |
0 commit comments