All files / src spel-editor.ts

95.91% Statements 94/98
94.54% Branches 52/55
91.3% Functions 21/23
97.84% Lines 91/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355                                  4x                                                                                           4x 4x 71x   4x 67x   4x 67x   4x 67x   4x 67x   4x 67x   4x 67x   4x     67x 67x 67x     91x                           55x       91x     55x     91x 1x       91x 90x     91x 59x         57x   57x 2x 2x 2x             57x 57x 53x 53x   57x 57x             19x             34x 34x 30x               30x               6x 5x 5x                   7x             9x 8x 8x 8x 4x                             21x                               90x 90x   90x 90x   5x       5x               252x 193x   252x 5x 5x                 5x 5x 5x 2x 2x   3x 5x                                     113x             113x                     46x 45x 45x 45x         113x 8x     113x           113x       55x 55x 55x                 45x 45x 45x       45x      
import { LitElement, html, css, type PropertyValues } from 'lit';
import { customElement, property, query } from 'lit/decorators.js';
import { EditorView, keymap, placeholder as cmPlaceholder } from '@codemirror/view';
import { EditorState, type Extension } from '@codemirror/state';
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands';
import { closeBrackets, autocompletion } from '@codemirror/autocomplete';
import { linter } from '@codemirror/lint';
 
import { spelLanguage } from './cm6/spel-language.js';
import { spelCompletion } from './cm6/completion-source.js';
import { spelLint } from './cm6/lint-source.js';
import { spelHover } from './cm6/hover-tooltip.js';
import { SpelFormatter, SpelDiagnosticEngine } from '@agentix-e/spel-ts';
 
import type { SpelEditorDetail } from './types.js';
import type { ContextSchema, SpelDiagnostic } from '@agentix-e/spel-ts';
 
const EDITOR_STYLES = css`
  :host {
    display: block;
  }
  .cm-container {
    overflow: hidden;
  }
  .cm-editor {
    height: 100%;
    font-family: var(--spel-font-family, 'JetBrains Mono', monospace);
    font-size: var(--spel-font-size, 14px);
    line-height: var(--spel-line-height, 1.6);
  }
  .cm-editor.cm-focused {
    outline: none;
  }
  .cm-editor .cm-scroller {
    overflow: auto;
  }
  .cm-editor .cm-content {
    caret-color: var(--spel-cursor, #111827);
  }
  .cm-editor .cm-cursor,
  .cm-editor .cm-dropCursor {
    border-left-color: var(--spel-cursor, #111827);
  }
  .cm-editor .cm-activeLine {
    background-color: var(--spel-line-highlight, #f3f4f6);
  }
  .cm-editor .cm-selectionBackground,
  .cm-editor.cm-focused .cm-selectionBackground {
    background: var(--spel-selection-bg, #bfdbfe) !important;
  }
  .cm-editor .cm-gutters {
    background: var(--spel-gutter-bg, #f9fafb);
    /* 5.72:1 on the gutter background. The previous #9ca3af measured 2.43:1, under
       the 4.5:1 WCAG AA requires for text, which made line numbers and lint markers
       unreadable at reduced contrast sensitivity. */
    color: var(--spel-gutter-fg, #5b6472);
    border: none;
  }
`;
 
/**
 * `<spel-editor>` — Web-embeddable SpEL expression editor.
 */
@customElement('spel-editor')
export class SpelEditor extends LitElement {
  static override styles = EDITOR_STYLES;
 
  @property({ type: String })
  value = '';
 
  @property({ type: Object, attribute: false })
  contextSchema: ContextSchema | null = null;
 
  @property({ type: String })
  placeholder = 'Enter SpEL expression...';
 
  @property({ type: Boolean, reflect: true })
  readonly = false;
 
  @property({ type: Boolean, reflect: true })
  disabled = false;
 
  @property({ type: String, attribute: 'min-height' })
  minHeight = '80px';
 
  @query('.cm-container')
  private containerEl!: HTMLElement;
 
  #editorView: EditorView | null = null;
  #diagnosticCache: SpelDiagnostic[] = [];
  #diagnosticDebounceTimer: ReturnType<typeof setTimeout> | null = null;
 
  override render() {
    return html`
      <div
        class="cm-container"
        style="
          min-height: ${this.minHeight};
          border: var(--spel-border-width, 1px) solid var(--spel-border-color, #d0d5dd);
          border-radius: var(--spel-border-radius, 6px);
          background: var(--spel-bg, #ffffff);
        "
      ></div>
    `;
  }
 
  override firstUpdated() {
    this.#createEditor();
  }
 
  override updated(changed: PropertyValues) {
    if (changed.has('disabled') || changed.has('readonly') || changed.has('placeholder')) {
      // All three are baked into the extension list, so a change has to rebuild the
      // editor rather than mutate it.
      this.#updateEditorState();
    }
    // Re-create editor if it was destroyed (e.g. after re-attach to DOM)
    if (!this.#editorView && this.containerEl) {
      this.#createEditor();
    }
    // Reflect a value that was assigned rather than typed, so a declarative binding
    // (`el.value = …`, or the `value` attribute) reaches the visible document.
    if (changed.has('value')) {
      this.#reflectValue();
    }
    // Re-run diagnostics when context schema changes
    if (changed.has('contextSchema')) {
      this.#scheduleDiagnostics();
    }
  }
 
  override connectedCallback() {
    super.connectedCallback();
    // Re-create editor when re-attached to DOM after removal
    if (this.hasUpdated && !this.#editorView) {
      void this.updateComplete.then(() => {
        Eif (!this.#editorView) {
          this.#createEditor();
        }
      });
    }
  }
 
  override disconnectedCallback() {
    super.disconnectedCallback();
    if (this.#diagnosticDebounceTimer) {
      clearTimeout(this.#diagnosticDebounceTimer);
      this.#diagnosticDebounceTimer = null;
    }
    this.#editorView?.destroy();
    this.#editorView = null;
  }
 
  /**
   * Get the current expression text from the editor.
   */
  getValue(): string {
    return this.#editorView?.state.sliceDoc() ?? this.value;
  }
 
  /**
   * Set the expression text programmatically.
   */
  setValue(value: string): void {
    this.value = value;
    if (this.#editorView) {
      this.#editorView.dispatch({
        changes: {
          from: 0,
          to: this.#editorView.state.doc.length,
          insert: value,
        },
        selection: { anchor: value.length },
      });
      this.#scheduleDiagnostics();
    }
  }
 
  /**
   * Insert a text snippet at the current cursor position.
   */
  insertSnippet(snippet: string): void {
    if (!this.#editorView) return;
    const { from, to } = this.#editorView.state.selection.main;
    this.#editorView.dispatch({
      changes: { from, to, insert: snippet },
      selection: { anchor: from + snippet.length },
    });
  }
 
  /**
   * Get the current diagnostics from the debounced validation cache.
   */
  validate(): SpelDiagnostic[] {
    return this.#diagnosticCache;
  }
 
  /**
   * Format the current expression using SpelFormatter.
   */
  format(): void {
    if (!this.#editorView) return;
    const current = this.#editorView.state.sliceDoc();
    const formatted = SpelFormatter.format(current);
    if (formatted && formatted !== current) {
      this.#editorView.dispatch({
        changes: {
          from: 0,
          to: this.#editorView.state.doc.length,
          insert: formatted,
        },
        selection: { anchor: formatted.length },
      });
    }
  }
 
  /**
   * Get the underlying CodeMirror 6 EditorView instance.
   */
  getEditorView(): EditorView | null {
    return this.#editorView;
  }
 
  /**
   * Push the current `value` into the editor, if the two have diverged.
   *
   * Typing sets `value` from the document, so this is a no-op for the common case and
   * only acts on a value assigned from outside — which is how every declarative
   * consumer sets it. Without this, `el.value = 'a > 1'` updated the element's state
   * while the visible document kept showing the previous expression.
   *
   * The guard is what keeps it from looping: the change listener writes the document
   * text back into `value`, and a dispatch here is skipped whenever they already
   * agree, so the cursor is never reset mid-edit.
   */
  #reflectValue(): void {
    const view = this.#editorView;
    Iif (!view) return;
 
    const current = view.state.sliceDoc();
    if (current === this.value) return;
 
    view.dispatch({
      changes: { from: 0, to: view.state.doc.length, insert: this.value },
      selection: { anchor: this.value.length },
    });
    this.#scheduleDiagnostics();
  }
 
  /**
   * Schedule a debounced diagnostic run (300ms).
   * Avoids redundant computation on rapid typing.
   */
  #scheduleDiagnostics() {
    if (this.#diagnosticDebounceTimer) {
      clearTimeout(this.#diagnosticDebounceTimer);
    }
    this.#diagnosticDebounceTimer = setTimeout(() => {
      this.#runDiagnostics();
      this.#diagnosticDebounceTimer = null;
    }, 300);
  }
 
  /**
   * Populate diagnosticCache by running validation.
   * Dispatches a `validate` event after diagnostics complete.
   */
  #runDiagnostics() {
    Iif (!this.#editorView) return;
    const expr = this.#editorView.state.sliceDoc();
    if (expr.trim().length === 0) {
      this.#diagnosticCache = [];
      return;
    }
    this.#diagnosticCache = SpelDiagnosticEngine.validate(expr, this.contextSchema ?? undefined);
    this.dispatchEvent(
      new CustomEvent('validate', {
        detail: { diagnostics: this.#diagnosticCache },
        bubbles: true,
        composed: true,
      }),
    );
  }
 
  /**
   * Attributes for the editable region.
   *
   * CodeMirror already renders `.cm-content` with `role="textbox"`,
   * `aria-multiline="true"` and — when the state is read-only — `aria-readonly`, so
   * that element is the component's one textbox. The label and the disabled state
   * belong on it as well: declaring them on the wrapper as well produced two nested
   * textboxes and two tab stops for a single editable region.
   */
  #contentAttributes(): Record<string, string> {
    return {
      'aria-label': this.placeholder,
      ...(this.disabled ? { 'aria-disabled': 'true' } : {}),
    };
  }
 
  #createEditor() {
    const extensions: Extension[] = [
      spelLanguage(),
      autocompletion({ override: [spelCompletion(() => this.contextSchema)] }),
      linter(spelLint(() => this.contextSchema)),
      spelHover(),
      history(),
      closeBrackets(),
      keymap.of([...defaultKeymap, ...historyKeymap]),
      cmPlaceholder(this.placeholder),
      EditorView.contentAttributes.of(this.#contentAttributes()),
      EditorView.updateListener.of((update) => {
        if (update.docChanged) {
          this.value = update.state.sliceDoc();
          this.#fireChange();
          this.#scheduleDiagnostics();
        }
      }),
    ];
 
    if (this.readonly || this.disabled) {
      extensions.push(EditorState.readOnly.of(true));
    }
 
    this.#editorView = new EditorView({
      state: EditorState.create({ doc: this.value, extensions }),
      parent: this.containerEl,
    });
 
    // Run initial diagnostics
    this.#scheduleDiagnostics();
  }
 
  #updateEditorState() {
    this.#editorView?.destroy();
    this.#editorView = null;
    this.#createEditor();
  }
 
  #fireChange() {
    // Run a synchronous syntax check to determine validity immediately.
    // The debounced full validation (semantic + context + type) is handled
    // by #scheduleDiagnostics, but the change event fires now so consumers
    // get an accurate isValid reading without a 300ms delay.
    // Empty expressions are considered valid (no expression = no error).
    const expr = this.value.trim();
    const syntaxDiags = expr.length === 0 ? [] : SpelDiagnosticEngine.checkSyntax(this.value);
    const detail: SpelEditorDetail = {
      value: this.value,
      isValid: syntaxDiags.length === 0,
    };
    this.dispatchEvent(new CustomEvent('change', { detail, bubbles: true, composed: true }));
  }
}