From f358417127bc693b6c71c1e1c6e957b49837f195 Mon Sep 17 00:00:00 2001 From: Andreas Schultz Date: Fri, 20 Nov 2026 14:47:31 +0100 Subject: [PATCH] Stabilize CodeAutocompleteField validation feedback --- CHANGELOG.md | 1 + .../AutoSuggestion/AutoSuggestion.tsx | 221 ++++++++------ .../tests/AutoSuggestion.test.tsx | 288 +++++++++++++++++- 3 files changed, 420 insertions(+), 90 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93be23c7..1ddc4c9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p ### Fixed +- `` keeps validation errors in sync during editing and autocomplete, and avoids spurious `onChange` calls for equivalent line endings during multiline reinitialization - Fix misused menu roles in selection popups and overlays - `` - improve keyboard navigation, tag removal and focus handling diff --git a/src/components/AutoSuggestion/AutoSuggestion.tsx b/src/components/AutoSuggestion/AutoSuggestion.tsx index 23f61095..b60edf80 100644 --- a/src/components/AutoSuggestion/AutoSuggestion.tsx +++ b/src/components/AutoSuggestion/AutoSuggestion.tsx @@ -1,7 +1,8 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import React, { useEffect, useMemo, useState } from "react"; import { Classes as BlueprintClassNames, PopupKind } from "@blueprintjs/core"; -import { EditorView, Rect } from "@codemirror/view"; +import { StateEffect, StateField } from "@codemirror/state"; +import { Decoration, DecorationSet, EditorView, Rect } from "@codemirror/view"; import { debounce } from "lodash"; import { IntentTypes } from "../../common/Intent"; @@ -85,6 +86,37 @@ export interface CodeAutocompleteFieldValidationResult { }; } +type ParseError = NonNullable; + +const setValidationUnderline = StateEffect.define(); + +const validationUnderline = StateField.define({ + create: () => Decoration.none, + update(marks, transaction) { + const effect = transaction.effects.find((effect) => effect.is(setValidationUnderline)); + if (!effect) { + return transaction.docChanged ? Decoration.none : marks; + } + + const error = effect.value; + if (!error || !Number.isInteger(error.start) || !Number.isInteger(error.end)) { + return Decoration.none; + } + const end = Math.min(error.end, transaction.newDoc.length); + if (error.start < 0 || error.start >= end) { + return Decoration.none; + } + + return Decoration.set( + Decoration.mark({ + class: `${eccgui}-autosuggestion__text--highlighted-error`, + attributes: { title: error.message }, + }).range(error.start, end), + ); + }, + provide: (field) => EditorView.decorations.from(field), +}); + export interface CodeAutocompleteFieldProps { /** Additional class name. */ @@ -169,6 +201,15 @@ interface RequestMetaData { requestId: string | undefined; } +interface ValidationRequest { + input: string; +} + +interface ValidationResponse { + request: ValidationRequest; + result: CodeAutocompleteFieldValidationResult | undefined; +} + /** * Input component that allows partial, fine-grained auto-completion, i.e. of sub-strings of the input string. * This is comparable to a one line code editor. @@ -209,12 +250,12 @@ export const CodeAutocompleteField = ({ const [suggestions, setSuggestions] = React.useState([]); const [suggestionsPending, setSuggestionsPending] = React.useState(false); const suggestionRequestData = React.useRef({ requestId: undefined }); - const [pathValidationPending, setPathValidationPending] = React.useState(false); - const validationRequestData = React.useRef({ requestId: undefined }); - const errorMarkers = React.useRef([]); - const [validationResponse, setValidationResponse] = useState( - undefined, - ); + const [validationStatus, setValidationStatus] = useState<"idle" | "queued" | "checking">("idle"); + const currentValidationRequest = React.useRef(); + const [validationResponse, setValidationResponse] = useState(); + const currentCheckInput = React.useRef(checkInput); + currentCheckInput.current = checkInput; + const validationEnabled = !!checkInput; const [suggestionResponse, setSuggestionResponse] = useState< CodeAutocompleteFieldPartialAutoCompleteResult | undefined >(undefined); @@ -279,24 +320,69 @@ export const CodeAutocompleteField = ({ }, [cm, shouldShowDropdown, suggestionsPending, suggestions.length, focusedIndex, suggestionListId]); const selectedTextRanges = React.useRef([]); - const pathIsValid = validationResponse?.valid ?? true; + const validationResult = validationEnabled ? validationResponse?.result : undefined; + const pathIsValid = validationResult?.valid ?? true; - React.useEffect(() => { - if (reInitOnInitialValueChange && initialValue != null && currentCm.current) { - dispatch({ - changes: { from: 0, to: currentCm.current.state?.doc.length, insert: initialValue }, - }); - // Validate initial value change - checkValuePathValidity(initialValue); + const validateInput = useMemo( + () => + debounce(async (request: ValidationRequest) => { + const validate = currentCheckInput.current; + if (!validate || currentValidationRequest.current !== request) return; + + setValidationStatus("checking"); + let result: CodeAutocompleteFieldValidationResult | undefined; + try { + result = await validate(request.input); + } catch { + result = undefined; + } + + if (currentValidationRequest.current !== request) return; + setValidationResponse({ request, result }); + setValidationStatus("idle"); + }, validationRequestDelay), + [validationRequestDelay], + ); + + const queueValidation = React.useCallback( + (input: string) => { + if (!validationEnabled) return; + + // Give each edit its own identity, including edits that restore previously validated text. + const request = { input }; + currentValidationRequest.current = request; + setValidationStatus("queued"); + validateInput(request); + }, + [validateInput, validationEnabled], + ); + + useEffect(() => { + if (!validationEnabled) setValidationStatus("idle"); + return () => { + currentValidationRequest.current = undefined; + validateInput.cancel(); + }; + }, [validateInput, validationEnabled]); + + useEffect(() => { + if (!reInitOnInitialValueChange || !cm || initialValue == null) return; + + const nextDoc = cm.state.toText(initialValue); + if (!cm.state.doc.eq(nextDoc)) { + cm.dispatch({ changes: { from: 0, to: cm.state.doc.length, insert: nextDoc } }); } - }, [initialValue, reInitOnInitialValueChange]); + }, [cm, initialValue, reInitOnInitialValueChange]); - React.useEffect(() => { - if (currentCm.current) { - // Validate initial value - checkValuePathValidity(initialValue); + useEffect(() => { + if (!cm) return; + + const input = cm.state.doc.toString(); + value.current = input; + if (currentValidationRequest.current?.input !== input) { + queueValidation(input); } - }, [!!currentCm.current]); + }, [cm, queueValidation]); const setCurrentIndex = (newIndex: number) => { editorState.index = newIndex; @@ -308,10 +394,6 @@ export const CodeAutocompleteField = ({ editorState.cm = cm; }, [cm, editorState]); - const dispatch = ( - typeof editorState?.cm?.dispatch === "function" ? editorState?.cm?.dispatch : () => {} - ) as EditorView["dispatch"]; - // Handle replacement highlighting useEffect(() => { if (highlightedElement && cm) { @@ -335,36 +417,26 @@ export const CodeAutocompleteField = ({ return; }, [highlightedElement, selectedTextRanges, cm]); - //handle linting - React.useEffect(() => { - const parseError = validationResponse?.parseError; - if (cm) { - const clearCurrentErrorMarker = () => { - if (errorMarkers.current.length) { - const [from, to] = errorMarkers.current; - removeMarkFromText({ view: cm, from, to }); - errorMarkers.current = []; - } - }; - if (parseError) { - const { message, start, end } = parseError; - clearCurrentErrorMarker(); - const { from, to } = markText({ - view: cm, - from: start, - to: end, - className: `${eccgui}-autosuggestion__text--highlighted-error`, - title: message, - }); - errorMarkers.current = [from, to]; - } else { - clearCurrentErrorMarker(); - } - } + useEffect(() => { + if (!cm) return; + + const hasUnderlineField = cm.state.field(validationUnderline, false) !== undefined; + if (!validationEnabled && !hasUnderlineField) return; + + const request = validationResponse?.request; + const parseError = + request && request === currentValidationRequest.current && request.input === cm.state.doc.toString() + ? validationResult?.parseError + : undefined; + const underline = setValidationUnderline.of(parseError); + cm.dispatch({ + effects: hasUnderlineField ? underline : [StateEffect.appendConfig.of(validationUnderline), underline], + }); + }, [cm, validationEnabled, validationResponse, validationResult]); - const isValid = validationResponse?.valid === undefined || validationResponse.valid; - onInputChecked?.(isValid); - }, [validationResponse?.valid, validationResponse?.parseError, cm, onInputChecked]); + useEffect(() => { + onInputChecked?.(pathIsValid); + }, [onInputChecked, pathIsValid, validationResult]); /** generate suggestions and also populate the replacement indexes dict */ React.useEffect(() => { @@ -416,36 +488,6 @@ export const CodeAutocompleteField = ({ } }, []); - const asyncCheckInput = useMemo( - () => async (inputString: string) => { - if ( - !checkInput || - inputString !== value.current || - validationRequestData.current.requestId === inputString - ) { - return; - } - validationRequestData.current.requestId = inputString; - setPathValidationPending(true); - try { - const result: CodeAutocompleteFieldValidationResult | undefined = await checkInput(inputString); - setValidationResponse(result); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - } catch (e) { - setValidationResponse(undefined); - // TODO: Error handling - } finally { - setPathValidationPending(false); - } - }, - [checkInput], - ); - - const checkValuePathValidity = useMemo( - () => debounce((inputString: string) => asyncCheckInput(inputString), validationRequestDelay), - [asyncCheckInput, validationRequestDelay], - ); - const asyncHandleEditorInputChange = useMemo( () => async (inputString: string, cursorPosition: number) => { const requestId = `${inputString} ${cursorPosition}`; @@ -490,11 +532,10 @@ export const CodeAutocompleteField = ({ const handleChange = React.useMemo(() => { return (val: string) => { value.current = val; - checkValuePathValidity.cancel(); - checkValuePathValidity(value.current); + queueValidation(val); onChange(val); }; - }, [onChange, checkValuePathValidity]); + }, [onChange, queueValidation]); const handleCursorChange = (cursor: number, coords: Rect, scrollinfo: HTMLElement, view: EditorView) => { //cursor here is offset from line 1, autosuggestion works with cursor per-line. @@ -692,7 +733,7 @@ export const CodeAutocompleteField = ({ [], ); - const hasError = !!value.current && !pathIsValid && !pathValidationPending; + const hasError = !!value.current && !pathIsValid && validationStatus === "idle"; const effectiveIntent = hasError ? "danger" : intent; const blueprintIntent = effectiveIntent && !["info", "accent", "neutral"].includes(effectiveIntent) ? effectiveIntent : undefined; @@ -804,7 +845,9 @@ export const CodeAutocompleteField = ({ <> {label}   - {(pathValidationPending || suggestionsPending) && } + {(validationStatus === "checking" || suggestionsPending) && ( + + )} ), }} diff --git a/src/components/AutoSuggestion/tests/AutoSuggestion.test.tsx b/src/components/AutoSuggestion/tests/AutoSuggestion.test.tsx index 8577079e..b72e6852 100644 --- a/src/components/AutoSuggestion/tests/AutoSuggestion.test.tsx +++ b/src/components/AutoSuggestion/tests/AutoSuggestion.test.tsx @@ -4,7 +4,40 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react" import "@testing-library/jest-dom"; -import CodeAutocompleteField, { CodeAutocompleteFieldProps } from "../AutoSuggestion"; +import { Modal } from "../../Dialog/Modal"; +import CodeAutocompleteField, { + CodeAutocompleteFieldProps, + CodeAutocompleteFieldValidationResult, +} from "../AutoSuggestion"; + +const validTemplate = "{{project.test}}\n\n{{project.test}}"; +const invalidTemplate = "{{project.testx}}\n\n{{project.test}}"; +const validationError = { + valid: false, + parseError: { start: 2, end: 15, message: "Unknown variable" }, +}; +const underlineSelector = ".eccgui-autosuggestion__text--highlighted-error"; +const underlinedText = () => + Array.from(document.querySelectorAll(underlineSelector), (span) => span.textContent).join(""); +const suggestVariable: CodeAutocompleteFieldProps["fetchSuggestions"] = (inputString, cursorPosition) => ({ + inputString, + cursorPosition, + replacementResults: [ + { + replacementInterval: { from: 2, length: 12 }, + extractedQuery: "project", + replacements: [{ value: "project.test" }], + }, + ], +}); + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((complete) => { + resolve = complete; + }); + return { promise, resolve }; +} describe("CodeAutocompleteField", () => { let props: CodeAutocompleteFieldProps; @@ -51,6 +84,259 @@ describe("CodeAutocompleteField", () => { expect(getByText(props.label!)).toBeTruthy(); }); + it("normalizes line endings before reinitializing a multiline document", () => { + const field = (initialValue: string) => ( + + ); + const { rerender } = render(field("first\r\nsecond")); + const view = EditorView.findFromDOM(screen.getByRole("combobox"))!; + expect(view.state.doc.toString()).toBe("first\nsecond"); + expect(props.onChange).not.toHaveBeenCalled(); + + rerender(field("first\nsecond")); + expect(props.onChange).not.toHaveBeenCalled(); + + rerender(field("first\r\nupdated")); + expect(view.state.doc.toString()).toBe("first\nupdated"); + expect(props.onChange).toHaveBeenCalledTimes(1); + expect(props.onChange).toHaveBeenCalledWith("first\nupdated"); + }); + + describe("validation underlines", () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + afterEach(() => { + jest.useRealTimers(); + }); + + const advance = async (ms: number) => { + await act(async () => { + jest.advanceTimersByTime(ms); + }); + }; + + it.each(["Escape", "blur"])("keeps the underline when %s closes highlighted suggestions", async (action) => { + const checkInput = jest.fn(() => validationError); + render( + , + ); + const editor = screen.getByRole("combobox"); + act(() => editor.focus()); + await advance(500); + expect(editor.querySelector(".eccgui-autosuggestion__text--highlighted")).toBeInTheDocument(); + expect(underlinedText()).toBe("project.testx"); + expect(document.querySelector(underlineSelector)).toHaveAttribute( + "title", + validationError.parseError.message, + ); + + if (action === "Escape") { + fireEvent.keyDown(editor, { key: "Escape", code: "Escape", keyCode: 40 }); + } else { + act(() => editor.blur()); + } + + expect(editor).toHaveAttribute("aria-expanded", "false"); + expect(underlinedText()).toBe("project.testx"); + expect(checkInput).toHaveBeenCalledTimes(1); + }); + + it("keeps a new underline while the next autocomplete request is pending", async () => { + const autocomplete = deferred(); + const fetchSuggestions = jest.fn((text: string, cursor: number) => + text.includes("testx") ? autocomplete.promise : suggestVariable(text, cursor), + ); + render( + (text === invalidTemplate ? validationError : { valid: true })} + fetchSuggestions={fetchSuggestions} + />, + ); + const editor = screen.getByRole("combobox"); + const view = EditorView.findFromDOM(editor)!; + jest.spyOn(view, "coordsAtPos").mockReturnValue({ left: 0, right: 1, top: 0, bottom: 1 }); + act(() => editor.focus()); + await advance(500); + expect(editor.querySelector(".eccgui-autosuggestion__text--highlighted")).toBeInTheDocument(); + + act(() => view.dispatch({ changes: { from: 14, insert: "x" }, selection: { anchor: 15 } })); + await advance(250); + expect(underlinedText()).toBe("project.testx"); + expect(fetchSuggestions).toHaveBeenCalledTimes(1); + + await advance(250); + expect(fetchSuggestions).toHaveBeenLastCalledWith("{{project.testx}}", 15); + expect(editor).toHaveAttribute("aria-expanded", "false"); + expect(underlinedText()).toBe("project.testx"); + await act(async () => autocomplete.resolve(undefined)); + }); + + it("ignores an older response when the latest edit has already been validated", async () => { + const oldValidation = deferred(); + const checkInput = jest.fn((text: string) => + text === validTemplate ? oldValidation.promise : validationError, + ); + render( + , + ); + await advance(250); + expect(checkInput).toHaveBeenCalledWith(validTemplate); + + const view = EditorView.findFromDOM(screen.getByRole("combobox"))!; + act(() => view.dispatch({ changes: { from: 14, insert: "x" } })); + await advance(250); + expect(underlinedText()).toBe("project.testx"); + expect(props.onInputChecked).toHaveBeenLastCalledWith(false); + + await act(async () => oldValidation.resolve({ valid: true })); + expect(underlinedText()).toBe("project.testx"); + expect(props.onInputChecked).toHaveBeenLastCalledWith(false); + }); + + it("keeps the old field error hidden when another edit queues validation", async () => { + const firstEditValidation = deferred(); + const checkInput = jest.fn((text: string) => + text === validTemplate ? firstEditValidation.promise : validationError, + ); + const errorText = "Template validation failed"; + render( + , + ); + const editor = screen.getByRole("combobox"); + const view = EditorView.findFromDOM(editor)!; + const input = editor.closest(".eccgui-autosuggestion__inputfield"); + await advance(250); + expect(screen.getByText(errorText)).toBeVisible(); + expect(input).toHaveClass("eccgui-intent--danger"); + + act(() => view.dispatch({ changes: { from: 14, to: 15 } })); + expect(screen.queryByText(errorText)).not.toBeInTheDocument(); + await advance(250); + expect(checkInput).toHaveBeenLastCalledWith(validTemplate); + expect(screen.queryByText(errorText)).not.toBeInTheDocument(); + + act(() => view.dispatch({ changes: { from: 14, insert: "x" } })); + expect(checkInput).toHaveBeenCalledTimes(2); + expect(screen.queryByText(errorText)).not.toBeInTheDocument(); + expect(input).not.toHaveClass("eccgui-intent--danger"); + + await act(async () => firstEditValidation.resolve({ valid: true })); + expect(props.onInputChecked).toHaveBeenLastCalledWith(false); + await advance(250); + expect(checkInput).toHaveBeenLastCalledWith(invalidTemplate); + expect(screen.getByText(errorText)).toBeVisible(); + expect(input).toHaveClass("eccgui-intent--danger"); + }); + + it("clears a previous underline on edit and validates returning to the same text", async () => { + const checkInput = jest.fn((text: string) => + text === invalidTemplate ? validationError : { valid: true }, + ); + render( + , + ); + const view = EditorView.findFromDOM(screen.getByRole("combobox"))!; + await advance(250); + expect(underlinedText()).toBe("project.testx"); + + act(() => view.dispatch({ changes: { from: 14, to: 15 } })); + expect(underlinedText()).toBe(""); + expect(props.onInputChecked).toHaveBeenLastCalledWith(false); + act(() => view.dispatch({ changes: { from: 14, insert: "x" } })); + await advance(250); + expect(checkInput.mock.calls).toEqual([[invalidTemplate], [invalidTemplate]]); + expect(underlinedText()).toBe("project.testx"); + + act(() => view.dispatch({ changes: { from: 14, to: 15 } })); + await advance(250); + expect(underlinedText()).toBe(""); + expect(props.onInputChecked).toHaveBeenLastCalledWith(true); + }); + + it("restores the accepted underline when the editor view is replaced", async () => { + const checkInput = jest.fn(() => validationError); + const editorProps = { ...props, initialValue: invalidTemplate, multiline: true, checkInput }; + const { rerender } = render(); + const originalView = EditorView.findFromDOM(screen.getByRole("combobox")); + await advance(200); + expect(underlinedText()).toBe("project.testx"); + + rerender(); + expect(EditorView.findFromDOM(screen.getByRole("combobox"))).not.toBe(originalView); + expect(underlinedText()).toBe("project.testx"); + await advance(200); + expect(checkInput).toHaveBeenCalledTimes(1); + }); + + it("validates the displayed template each time the modal opens", async () => { + const checkInput = jest.fn(() => validationError); + const modal = (isOpen: boolean) => ( + +
+ {isOpen && ( + + )} +
+
+ ); + const { rerender } = render(modal(true)); + await advance(250); + expect(underlinedText()).toBe("project.testx"); + + rerender(modal(false)); + await waitFor(() => expect(underlinedText()).toBe("")); + rerender(modal(true)); + await advance(250); + expect(underlinedText()).toBe("project.testx"); + expect(checkInput.mock.calls).toEqual([[invalidTemplate], [invalidTemplate]]); + }); + }); + it("connects the focused editor to the active suggestion", async () => { const { container } = render(