diff --git a/.changeset/diagnostics-open-code-at-line.md b/.changeset/diagnostics-open-code-at-line.md new file mode 100644 index 00000000000..128d00ed22e --- /dev/null +++ b/.changeset/diagnostics-open-code-at-line.md @@ -0,0 +1,5 @@ +--- +"@hashintel/petrinaut": patch +--- + +Open a diagnostic's code at its line when it is clicked in the Diagnostics tab. diff --git a/libs/@hashintel/petrinaut/docs/code-editor.md b/libs/@hashintel/petrinaut/docs/code-editor.md index 7e2661944e8..2abe33162b4 100644 --- a/libs/@hashintel/petrinaut/docs/code-editor.md +++ b/libs/@hashintel/petrinaut/docs/code-editor.md @@ -13,7 +13,7 @@ Select a place, transition, or differential equation in the canvas or left sideb The item’s menu in the left sidebar opens its code directly. A Canvas visualizer’s **Edit visualizer code** button opens and focuses its expanded code section. For a place with dynamics, the arrow on each row of its **Dynamics** section opens that equation’s properties and code. -Every code section, the Visualizer included, is checked as you type: type errors are underlined and listed in the Diagnostics tab, completion suggests the names in scope, and pointing at a name shows its type. +Every code section, the Visualizer included, is checked as you type: type errors are underlined and listed in the Diagnostics tab, completion suggests the names in scope, and pointing at a name shows its type. Click a problem in the Diagnostics tab to open its code: the section fills the panel, the editor takes focus, and the cursor is where the problem starts, with that line in view. ## Fill the panel diff --git a/libs/@hashintel/petrinaut/docs/petri-net-extensions.md b/libs/@hashintel/petrinaut/docs/petri-net-extensions.md index a3070185eea..fe7b79c4221 100644 --- a/libs/@hashintel/petrinaut/docs/petri-net-extensions.md +++ b/libs/@hashintel/petrinaut/docs/petri-net-extensions.md @@ -342,7 +342,7 @@ Use read arcs when a transition needs to inspect shared state, permission tokens ## Diagnostics -The **Diagnostics** tab in the bottom panel shows problems in your code (dynamics, firing rate, kernels, visualizers), grouped by entity. Click a diagnostic to select the relevant entity and see the problem in context. +The **Diagnostics** tab in the bottom panel shows problems in your code (dynamics, firing rate, kernels, visualizers), grouped by entity. Click a diagnostic to open the code it is in: the entity is selected, its [code section fills the Properties Panel](code-editor.md#fill-the-panel), and the cursor is where the problem starts, with that line in view. Above the problems, the tab reads [the class of the net](simulation.md#the-class-of-a-net): whether it is timed, how it is coloured and whether it is stochastic. diff --git a/libs/@hashintel/petrinaut/src/ui/monaco/code-editor.tsx b/libs/@hashintel/petrinaut/src/ui/monaco/code-editor.tsx index f6ed1de9b16..a71d05d863f 100644 --- a/libs/@hashintel/petrinaut/src/ui/monaco/code-editor.tsx +++ b/libs/@hashintel/petrinaut/src/ui/monaco/code-editor.tsx @@ -4,6 +4,7 @@ import { Tooltip } from "@hashintel/ds-components"; import { css, cva } from "@hashintel/ds-helpers/css"; import { CODE_FONT_FAMILY } from "../shared/ui-constants"; +import { FocusOnRequest } from "./code-editor/focus-on-request"; import { MonacoContext } from "./context"; import { releaseReplacedModels } from "./release-replaced-models"; @@ -211,6 +212,7 @@ const CodeEditorInner: React.FC< value, onChange, mountSelection, + path, ...props }) => { const { Editor } = environment; @@ -221,9 +223,11 @@ const CodeEditorInner: React.FC< // Withholding `value` makes @monaco-editor/react skip its sync; the prop // resumes syncing external changes once focus leaves. const [editorFocused, setEditorFocused] = useState(false); - // Until Monaco mounts, its `loading` label sits where the placeholder - // would, so the placeholder waits for the mount rather than overlapping it. - const [editorMounted, setEditorMounted] = useState(false); + // The editor Monaco last mounted: a new one each time an `Activity` shows + // this again. Until the first, Monaco's `loading` label sits where the + // placeholder would, so the placeholder waits for it. + const [mountedEditor, setMountedEditor] = + useState(null); useEffect(() => { if (!onEscape) { @@ -265,7 +269,7 @@ const CodeEditorInner: React.FC< editorRef.current = editorInstance; releaseReplacedModels(editorInstance); setEditorFocused(false); - setEditorMounted(true); + setMountedEditor(editorInstance); // With a `path`, @monaco-editor/react reuses the existing model and // ignores `value` — a reopened editor would show the model's stale text @@ -396,12 +400,16 @@ const CodeEditorInner: React.FC< return ( <> - {placeholder && !value && editorMounted && ( + {placeholder && !value && mountedEditor && (
{placeholder}
)} + {path !== undefined && ( + + )} diff --git a/libs/@hashintel/petrinaut/src/ui/monaco/code-editor/focus-on-request.test.tsx b/libs/@hashintel/petrinaut/src/ui/monaco/code-editor/focus-on-request.test.tsx new file mode 100644 index 00000000000..3693058f1a9 --- /dev/null +++ b/libs/@hashintel/petrinaut/src/ui/monaco/code-editor/focus-on-request.test.tsx @@ -0,0 +1,111 @@ +/** @vitest-environment jsdom */ +import { cleanup, render, waitFor } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; + +import { CodeNavigationContext } from "../code-navigation-context"; +import { FocusOnRequest } from "./focus-on-request"; + +import type { CodeNavigation } from "../code-navigation-context"; +import type { editor } from "monaco-editor"; + +afterEach(cleanup); + +const fakeEditor = (model: object | null = {}) => { + const calls: string[] = []; + const instance = { + getModel: () => model, + layout: vi.fn(() => calls.push("layout")), + setPosition: vi.fn(() => calls.push("setPosition")), + revealPositionInCenterIfOutsideViewport: vi.fn(() => calls.push("reveal")), + focus: vi.fn(() => calls.push("focus")), + }; + return { + calls, + instance, + editorInstance: instance as unknown as editor.IStandaloneCodeEditor, + }; +}; + +const renderWithRequest = ( + focusRequest: CodeNavigation["focusRequest"], + editorInstance: editor.IStandaloneCodeEditor | null, +) => { + const acknowledgeFocus = vi.fn(); + render( + true, + focusRequest, + acknowledgeFocus, + }} + > + + , + ); + return acknowledgeFocus; +}; + +/** Long enough for the frame the component waits for to have run. */ +const nextFrames = () => + new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + }); + +it("puts the caret on the requested position, brings it into view and takes focus", async () => { + const { calls, instance, editorInstance } = fakeEditor(); + const acknowledgeFocus = renderWithRequest( + { path: "kernel.ts", position: { line: 4, character: 2 } }, + editorInstance, + ); + + await waitFor(() => + expect(acknowledgeFocus).toHaveBeenCalledWith("kernel.ts"), + ); + // Monaco counts lines and columns from one. + const position = { lineNumber: 5, column: 3 }; + expect(instance.setPosition).toHaveBeenCalledWith(position); + expect(instance.revealPositionInCenterIfOutsideViewport).toHaveBeenCalledWith( + position, + ); + // Measured first: the reveal centres the line in the size the editor has. + expect(calls).toEqual(["layout", "setPosition", "reveal", "focus"]); +}); + +it("takes focus without moving the caret when the request names no position", async () => { + const { calls, editorInstance } = fakeEditor(); + const acknowledgeFocus = renderWithRequest( + { path: "kernel.ts" }, + editorInstance, + ); + + await waitFor(() => + expect(acknowledgeFocus).toHaveBeenCalledWith("kernel.ts"), + ); + expect(calls).toEqual(["focus"]); +}); + +it("leaves a request for another path alone", async () => { + const { calls, editorInstance } = fakeEditor(); + const acknowledgeFocus = renderWithRequest( + { path: "lambda.ts", position: { line: 0, character: 0 } }, + editorInstance, + ); + + await nextFrames(); + expect(calls).toEqual([]); + expect(acknowledgeFocus).not.toHaveBeenCalled(); +}); + +it("leaves the request for the next editor when this one is disposed", async () => { + const { calls, editorInstance } = fakeEditor(null); + const acknowledgeFocus = renderWithRequest( + { path: "kernel.ts", position: { line: 0, character: 0 } }, + editorInstance, + ); + + await nextFrames(); + expect(calls).toEqual([]); + expect(acknowledgeFocus).not.toHaveBeenCalled(); +}); diff --git a/libs/@hashintel/petrinaut/src/ui/monaco/code-editor/focus-on-request.tsx b/libs/@hashintel/petrinaut/src/ui/monaco/code-editor/focus-on-request.tsx new file mode 100644 index 00000000000..ecc5550b82f --- /dev/null +++ b/libs/@hashintel/petrinaut/src/ui/monaco/code-editor/focus-on-request.tsx @@ -0,0 +1,51 @@ +import { useEffect } from "react"; + +import { useStableCallback } from "../../../react/shared/use-stable-callback"; +import { useCodeNavigation } from "../code-navigation-context"; + +import type { editor } from "monaco-editor"; + +/** + * Gives the editor of `path` focus when code navigation asks for that path. + * A request that names a position puts the caret there and brings its line + * into view. + * + * A component of its own, so that a change to the navigation's entries + * renders this and not the editor. + */ +export const FocusOnRequest = ({ + path, + editorInstance, +}: { + path: string; + editorInstance: editor.IStandaloneCodeEditor | null; +}) => { + const { focusRequest, acknowledgeFocus } = useCodeNavigation(); + const acknowledge = useStableCallback(acknowledgeFocus); + const request = focusRequest?.path === path ? focusRequest : null; + + useEffect(() => { + if (!editorInstance || !request) return; + const frame = requestAnimationFrame(() => { + // A disposed editor has no model. The one that replaces it answers. + if (!editorInstance.getModel()) return; + if (request.position) { + const position = { + lineNumber: request.position.line + 1, + column: request.position.character + 1, + }; + // Monaco learns the size of its container from a resize observer, + // which reports after this frame. An editor that has just mounted + // would centre the line in the few pixels it started with. + editorInstance.layout(); + editorInstance.setPosition(position); + editorInstance.revealPositionInCenterIfOutsideViewport(position); + } + editorInstance.focus(); + acknowledge(request.path); + }); + return () => cancelAnimationFrame(frame); + }, [editorInstance, request, acknowledge]); + + return null; +}; diff --git a/libs/@hashintel/petrinaut/src/ui/monaco/code-navigation-context.ts b/libs/@hashintel/petrinaut/src/ui/monaco/code-navigation-context.ts index 90cd4d92c53..67952a51bc4 100644 --- a/libs/@hashintel/petrinaut/src/ui/monaco/code-navigation-context.ts +++ b/libs/@hashintel/petrinaut/src/ui/monaco/code-navigation-context.ts @@ -10,18 +10,32 @@ export type CodeEntry = { section: string; }; +/** A place in a piece of code, counted from zero as the language server does. */ +export type CodePosition = { line: number; character: number }; + export type CodeNavigation = { enabled: boolean; entries: CodeEntry[]; - open: (path: string, options?: { maximize?: boolean }) => void; - focusRequest: { path: string } | null; + /** + * Opens the section that holds the code at `path`. With `maximize` the + * section fills its panel and the editor takes focus. With a `position` the + * editor takes focus too, with its caret there and that line in view. + * + * False when there is no such code to open. + */ + open: ( + path: string, + options?: { maximize?: boolean; position?: CodePosition }, + ) => boolean; + /** The code whose editor is to take focus, until that editor acknowledges it. */ + focusRequest: { path: string; position?: CodePosition } | null; acknowledgeFocus: (path: string) => void; }; export const CodeNavigationContext = createContext({ enabled: false, entries: [], - open: () => {}, + open: () => false, focusRequest: null, acknowledgeFocus: () => {}, }); diff --git a/libs/@hashintel/petrinaut/src/ui/monaco/monaco.mdx b/libs/@hashintel/petrinaut/src/ui/monaco/monaco.mdx index 4c30755168d..f154e617e3c 100644 --- a/libs/@hashintel/petrinaut/src/ui/monaco/monaco.mdx +++ b/libs/@hashintel/petrinaut/src/ui/monaco/monaco.mdx @@ -16,13 +16,13 @@ The Monaco layer wires the Monaco editor to the language server for authoring us ## Interface -| Name | Use it to | -| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `CodeEditor` | Edit one document. `path` names its URI, `value` and `onChange` carry the text. | -| `singleLine`, `onSubmit`, `onEscape` | Use the editor as a one-line expression input. | -| `mountSelection` | Say where the caret lands when the editor mounts. | -| `getDocumentUri` | Build the URI of a piece of user code, the same one the language server uses. | -| `useCodeNavigation` | Open the section that holds a piece of code and focus its editor. `EditorView` mounts its provider, which is a file of the editor shell. Outside it, as in the preview, the hook returns a default that opens nothing. | +| Name | Use it to | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `CodeEditor` | Edit one document. `path` names its URI, `value` and `onChange` carry the text. | +| `singleLine`, `onSubmit`, `onEscape` | Use the editor as a one-line expression input. | +| `mountSelection` | Say where the caret lands when the editor mounts. | +| `getDocumentUri` | Build the URI of a piece of user code, the same one the language server uses. | +| `useCodeNavigation` | Open the section that holds a piece of code and focus its editor, with the caret on a `position` when one is given. `EditorView` mounts its provider, which is a file of the editor shell. Outside it, as in the preview, the hook returns a default that opens nothing. | ## Data flow @@ -39,6 +39,8 @@ A user types one character in a place's visualizer code: **The model is the source of truth while the editor has focus.** Writing a controlled value into a focused editor moves the caret to the end. The tests in `code-editor-activity.test.tsx` cover typing in one view while another is hidden, and coming back to it. +**The editor of a `path` answers the focus request for that path.** `open` from `useCodeNavigation` leaves a request, and the `CodeEditor` whose `path` it names takes focus, puts the caret on the request's position and brings that line into view. No section that holds code handles the request itself. Before it reveals the line the editor measures its container, because Monaco learns its size from a resize observer a frame after it mounts, and would centre the line in the height it started with. `focus-on-request.test.tsx` holds this. + **An editor inside a hidden `Activity` is disposed.** React removes the effects of a hidden `Activity`, and the editor instance lives in one. A collapsed section keeps its editor through `retainOnCollapse`, which [Sub-views](doc:ui.sub-view/sub-views) describes. **The warm-up creates one editor and never competes with a real one.** `warmEditor` waits for the code font and an idle callback, creates a hidden editor, and disposes it on the next frame. It does nothing when an editor is already open, or in a browser without `document.fonts` or `requestIdleCallback`. `warm-editor.test.ts` holds this. diff --git a/libs/@hashintel/petrinaut/src/ui/sub-view/sub-views.mdx b/libs/@hashintel/petrinaut/src/ui/sub-view/sub-views.mdx index 7174c8a9c79..0e8a7d5d44f 100644 --- a/libs/@hashintel/petrinaut/src/ui/sub-view/sub-views.mdx +++ b/libs/@hashintel/petrinaut/src/ui/sub-view/sub-views.mdx @@ -59,6 +59,8 @@ A plugin's `bottomPanelViews` entry never becomes a `SubView`. `usePluginBottomP **The maximize animation changes no layout property.** The section is laid out once at the size of the container, then moved with `transform` and clipped with `clip-path`, while its title and the other sections change `opacity`. Its content is not laid out again on each frame. The test "animates how the section is drawn in both directions and can reverse an unfinished expansion" in `vertical-sub-views-container.test.tsx` holds this. +**A section that fills the container or returns leaves focus in its content.** The control of its header takes focus, so that a keyboard user is not left on a button that has gone. Focus that is already in the section's content stays there: code navigation opens a section for its editor, and the editor takes focus first. The test "leaves focus in the section's content when it is there as the section fills the container" in `vertical-sub-views-container.test.tsx` holds this. + **A collapsible section that holds a code editor sets `retainOnCollapse`.** Creating a Monaco editor costs more than keeping one, so a visited section keeps its editor while collapsed. The test "retains visited code while collapsed and releases it when selecting another item" in the same file holds this. See [Monaco](doc:ui.monaco/monaco). ## Pitfalls diff --git a/libs/@hashintel/petrinaut/src/ui/sub-view/vertical-sub-views-container.test.tsx b/libs/@hashintel/petrinaut/src/ui/sub-view/vertical-sub-views-container.test.tsx index b2e8384d7cd..5391f2a2272 100644 --- a/libs/@hashintel/petrinaut/src/ui/sub-view/vertical-sub-views-container.test.tsx +++ b/libs/@hashintel/petrinaut/src/ui/sub-view/vertical-sub-views-container.test.tsx @@ -309,6 +309,25 @@ describe("maximizing a subview", () => { expect(updateSubViewSection).not.toHaveBeenCalled(); }); + it("leaves focus in the section's content when it is there as the section fills the container", async () => { + render(); + const code = screen.getByRole("textbox", { name: "Code" }); + code.focus(); + fireEvent.click(screen.getByRole("button", { name: "Expand Firing Time" })); + + expect( + screen.getByRole("button", { name: "Back to Transition Collision" }), + ).toBeTruthy(); + // Two frames: the header takes focus, when it does, in the first. + await act( + () => + new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + }), + ); + expect(document.activeElement).toBe(code); + }); + it("returns with Escape and clears maximization when changing items or removing a section", async () => { const view = render(); fireEvent.click(screen.getByRole("button", { name: "Expand Firing Time" })); diff --git a/libs/@hashintel/petrinaut/src/ui/sub-view/vertical-sub-views-container/use-sub-view-maximization.ts b/libs/@hashintel/petrinaut/src/ui/sub-view/vertical-sub-views-container/use-sub-view-maximization.ts index 42668a664cf..f5c71e3fbd0 100644 --- a/libs/@hashintel/petrinaut/src/ui/sub-view/vertical-sub-views-container/use-sub-view-maximization.ts +++ b/libs/@hashintel/petrinaut/src/ui/sub-view/vertical-sub-views-container/use-sub-view-maximization.ts @@ -58,12 +58,31 @@ const drawnAs = (bounds: Bounds, fullHeight: number): Keyframe => ({ clipPath: `inset(0px 0px ${Math.max(0, fullHeight - bounds.height)}px 0px)`, }); +/** Whether focus is in what the section shows, below its header. */ +const hasFocusInContent = (section: HTMLElement): boolean => { + const active = document.activeElement; + return ( + active !== null && + section.contains(active) && + active.closest("[data-subview-header]") === null + ); +}; + +/** + * Moves focus to a control of the section's header, for a section that + * changed size under a keyboard user. Focus that is already in the section's + * content stays there: whoever opened the section for its content, as a link + * to a line of its code does, has put it there. + */ const focusHeader = ( section: HTMLElement, selector: string, fallbackSelector?: string, ) => { requestAnimationFrame(() => { + if (hasFocusInContent(section)) { + return; + } const target = section.querySelector(selector) ?? (fallbackSelector diff --git a/libs/@hashintel/petrinaut/src/ui/views/Editor/editor-view/code-navigation-provider.test.tsx b/libs/@hashintel/petrinaut/src/ui/views/Editor/editor-view/code-navigation-provider.test.tsx index 758fc26ba69..d9e982ebdcd 100644 --- a/libs/@hashintel/petrinaut/src/ui/views/Editor/editor-view/code-navigation-provider.test.tsx +++ b/libs/@hashintel/petrinaut/src/ui/views/Editor/editor-view/code-navigation-provider.test.tsx @@ -83,7 +83,9 @@ it("opens the matching property section and preserves its saved size", () => { (entry) => entry.label === "Transition kernel", ); expect(kernel).toBeDefined(); - if (kernel) act(() => result.current.open(kernel.path)); + act(() => { + if (kernel) result.current.open(kernel.path); + }); expect(selectItem).toHaveBeenCalledWith(kernel?.selection); expect(updateSubViewSection).toHaveBeenCalledWith( "transition-properties", @@ -98,8 +100,12 @@ it("does not navigate to unavailable functions or reveal code in a preview", () }); const entry = result.current.entries.at(0); expect(entry).toBeDefined(); - if (entry) act(() => result.current.open(entry.path)); - act(() => result.current.open("missing")); + const opened: boolean[] = []; + act(() => { + if (entry) opened.push(result.current.open(entry.path)); + opened.push(result.current.open("missing")); + }); + expect(opened).toEqual([false, false]); expect(selectItem).not.toHaveBeenCalled(); expect(updateSubViewSection).not.toHaveBeenCalled(); }); @@ -116,7 +122,9 @@ it("opens a maximized editor without leaving simulate mode and consumes its focu }, ); const entry = result.current.code.entries[0]!; - act(() => result.current.code.open(entry.path, { maximize: true })); + act(() => { + result.current.code.open(entry.path, { maximize: true }); + }); expect(result.current.navigation.state).toMatchObject({ mode: "simulate", selection: [entry.selection], @@ -128,3 +136,46 @@ it("opens a maximized editor without leaving simulate mode and consumes its focu act(() => result.current.code.acknowledgeFocus(entry.path)); expect(result.current.code.focusRequest).toBeNull(); }); + +it("asks the editor for a position, and again when the same code is asked for twice", () => { + const { result } = renderHook(useCodeNavigation, { + wrapper: ({ children }) => ( + + {children} + + ), + }); + const entry = result.current.entries[0]!; + const position = { line: 6, character: 2 }; + + let opened = false; + act(() => { + opened = result.current.open(entry.path, { maximize: true, position }); + }); + expect(opened).toBe(true); + const first = result.current.focusRequest; + expect(first).toEqual({ path: entry.path, position }); + + act(() => { + result.current.open(entry.path, { maximize: true, position }); + }); + expect(result.current.focusRequest).toEqual(first); + expect(result.current.focusRequest).not.toBe(first); +}); + +it("asks the editor for a position without maximizing its section", () => { + const { result } = renderHook(useCodeNavigation, { wrapper: Harness }); + const entry = result.current.entries[0]!; + const position = { line: 1, character: 0 }; + + act(() => { + result.current.open(entry.path, { position }); + }); + expect(result.current.focusRequest).toEqual({ path: entry.path, position }); + + act(() => result.current.acknowledgeFocus(entry.path)); + act(() => { + result.current.open(entry.path); + }); + expect(result.current.focusRequest).toBeNull(); +}); diff --git a/libs/@hashintel/petrinaut/src/ui/views/Editor/editor-view/code-navigation-provider.tsx b/libs/@hashintel/petrinaut/src/ui/views/Editor/editor-view/code-navigation-provider.tsx index 8f85785cadd..0dad2a3e5b7 100644 --- a/libs/@hashintel/petrinaut/src/ui/views/Editor/editor-view/code-navigation-provider.tsx +++ b/libs/@hashintel/petrinaut/src/ui/views/Editor/editor-view/code-navigation-provider.tsx @@ -23,9 +23,8 @@ import type { PropsWithChildren } from "react"; export const CodeNavigationProvider = ({ children }: PropsWithChildren) => { const navigate = usePetrinautNavigate(); - const [focusRequest, setFocusRequest] = useState<{ path: string } | null>( - null, - ); + const [focusRequest, setFocusRequest] = + useState(null); const { activeNet } = use(ActiveNetContext); const petriNetDefinition = useSDCPNState( (document) => document.petriNetDefinition, @@ -113,7 +112,7 @@ export const CodeNavigationProvider = ({ children }: PropsWithChildren) => { setFocusRequest((request) => (request?.path === path ? null : request)), open: (path, options) => { const entry = entries.find((candidate) => candidate.path === path); - if (!enabled || !entry) return; + if (!enabled || !entry) return false; const expandSection = () => updateSubViewSection(entry.panel, entry.section, { ...subViewPanels[entry.panel]?.[entry.section], @@ -127,7 +126,6 @@ export const CodeNavigationProvider = ({ children }: PropsWithChildren) => { }, { cause: "user", action: "subview" }, ); - setFocusRequest({ path }); // The section fills its container whether or not it is collapsed. // Expanding it only matters once the user goes back, so it waits: // the container then knows of the request first, and keeps the @@ -137,6 +135,12 @@ export const CodeNavigationProvider = ({ children }: PropsWithChildren) => { expandSection(); selectItem(entry.selection); } + if (options?.maximize || options?.position) { + // A new object each time, so asking again for the code that is + // already open moves its caret again. + setFocusRequest({ path, position: options.position }); + } + return true; }, }; return ( diff --git a/libs/@hashintel/petrinaut/src/ui/views/Editor/panels/BottomPanel/subviews/diagnostics.test.tsx b/libs/@hashintel/petrinaut/src/ui/views/Editor/panels/BottomPanel/subviews/diagnostics.test.tsx new file mode 100644 index 00000000000..9c631c1cde2 --- /dev/null +++ b/libs/@hashintel/petrinaut/src/ui/views/Editor/panels/BottomPanel/subviews/diagnostics.test.tsx @@ -0,0 +1,97 @@ +/** @vitest-environment jsdom */ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { use } from "react"; +import { afterEach, expect, it, vi } from "vitest"; + +import { DiagnosticSeverity, getDocumentUri } from "@hashintel/petrinaut-core"; + +import { + DEFAULT_LANGUAGE_CLIENT_CONTEXT, + LanguageClientContext, +} from "../../../../../../react/lsp/context"; +import { EditorContext } from "../../../../../../react/state/editor-context"; +import { CodeNavigationContext } from "../../../../../monaco/code-navigation-context"; +import { DiagnosticsPanel } from "./diagnostics"; + +import type { CodeNavigation } from "../../../../../monaco/code-navigation-context"; +import type { PropsWithChildren } from "react"; + +afterEach(cleanup); + +const kernelUri = getDocumentUri("transition-kernel", "transition__launch"); +const start = { line: 6, character: 4 }; +const selectItem = vi.fn(); + +const Harness = ({ + children, + open, +}: PropsWithChildren<{ open: CodeNavigation["open"] }>) => { + const editor = use(EditorContext); + return ( + + + {}, + }} + > + {children} + + + + ); +}; + +const clickDiagnostic = () => + fireEvent.click(screen.getByRole("button", { name: /is never used/ })); + +it("opens a diagnostic's code full-size, at the position the diagnostic starts", () => { + const open = vi.fn(() => true); + render( + + + , + ); + + clickDiagnostic(); + expect(open).toHaveBeenCalledWith(kernelUri, { + maximize: true, + position: start, + }); + expect(selectItem).not.toHaveBeenCalled(); +}); + +it("selects the entity when its code cannot be opened", () => { + render( + false}> + + , + ); + + clickDiagnostic(); + expect(selectItem).toHaveBeenCalledWith({ + type: "transition", + id: "transition__launch", + }); +}); diff --git a/libs/@hashintel/petrinaut/src/ui/views/Editor/panels/BottomPanel/subviews/diagnostics.tsx b/libs/@hashintel/petrinaut/src/ui/views/Editor/panels/BottomPanel/subviews/diagnostics.tsx index 89e7738be48..b7c9be8aee0 100644 --- a/libs/@hashintel/petrinaut/src/ui/views/Editor/panels/BottomPanel/subviews/diagnostics.tsx +++ b/libs/@hashintel/petrinaut/src/ui/views/Editor/panels/BottomPanel/subviews/diagnostics.tsx @@ -7,7 +7,10 @@ import { useSDCPNState } from "../../../../../../react/document/sdcpn-context"; import { LanguageClientContext } from "../../../../../../react/lsp/context"; import { SimulationContext } from "../../../../../../react/simulation/context"; import { useEditorActions } from "../../../../../../react/state/editor-context"; -import { useCodeNavigation } from "../../../../../monaco/code-navigation-context"; +import { + useCodeNavigation, + type CodePosition, +} from "../../../../../monaco/code-navigation-context"; import { problemTextStyle } from "../../../../../shared/problem-severity"; import { useKeptState } from "../../../../../shared/use-kept-state"; import { severityOfDiagnostic } from "../../../shared/diagnostic-severity"; @@ -91,12 +94,16 @@ const DiagnosticsContent: React.FC = () => { ); const hasSimulationError = simulationState === "Error" && !!simulationError; - // Clicking a diagnostic selects its entity. A visualizer's section is - // collapsed by default, so its diagnostics also open that section. - const revealDiagnostic = (entity: EntityDiagnostics, uri: string) => { - selectItem({ type: entity.entityType, id: entity.entityId }); - if (entity.entityType === "place") { - codeNavigation.open(uri); + // Clicking a diagnostic opens its code over the properties panel, with the + // caret where the diagnostic starts. Where the code cannot be opened, as in + // a profile that hides source code, it selects the entity. + const revealDiagnostic = ( + entity: EntityDiagnostics, + uri: string, + position: CodePosition, + ) => { + if (!codeNavigation.open(uri, { maximize: true, position })) { + selectItem({ type: entity.entityType, id: entity.entityId }); } }; @@ -188,7 +195,11 @@ const DiagnosticsContent: React.FC = () => {