Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/diagnostics-open-code-at-line.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@hashintel/petrinaut": patch
---

Open a diagnostic's code at its line when it is clicked in the Diagnostics tab.
2 changes: 1 addition & 1 deletion libs/@hashintel/petrinaut/docs/code-editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion libs/@hashintel/petrinaut/docs/petri-net-extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
18 changes: 13 additions & 5 deletions libs/@hashintel/petrinaut/src/ui/monaco/code-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -211,6 +212,7 @@ const CodeEditorInner: React.FC<
value,
onChange,
mountSelection,
path,
...props
}) => {
const { Editor } = environment;
Expand All @@ -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<editor.IStandaloneCodeEditor | null>(null);

useEffect(() => {
if (!onEscape) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -396,12 +400,16 @@ const CodeEditorInner: React.FC<

return (
<>
{placeholder && !value && editorMounted && (
{placeholder && !value && mountedEditor && (
<div className={placeholderStyle}>{placeholder}</div>
)}
{path !== undefined && (
<FocusOnRequest path={path} editorInstance={mountedEditor} />
)}
<Editor
theme="petrinaut-light"
saveViewState={false}
path={path}
height={singleLine ? SINGLE_LINE_TOTAL_HEIGHT : "100%"}
options={editorOptions}
onMount={(editorInstance, monacoInstance) =>
Expand Down
Original file line number Diff line number Diff line change
@@ -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(
<CodeNavigationContext
value={{
enabled: true,
entries: [],
open: () => true,
focusRequest,
acknowledgeFocus,
}}
>
<FocusOnRequest path="kernel.ts" editorInstance={editorInstance} />
</CodeNavigationContext>,
);
return acknowledgeFocus;
};

/** Long enough for the frame the component waits for to have run. */
const nextFrames = () =>
new Promise<void>((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();
});
Original file line number Diff line number Diff line change
@@ -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;
};
Original file line number Diff line number Diff line change
Expand Up @@ -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<CodeNavigation>({
enabled: false,
entries: [],
open: () => {},
open: () => false,
focusRequest: null,
acknowledgeFocus: () => {},
});
Expand Down
16 changes: 9 additions & 7 deletions libs/@hashintel/petrinaut/src/ui/monaco/monaco.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions libs/@hashintel/petrinaut/src/ui/sub-view/sub-views.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(<Harness />);
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<void>((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(<Harness />);
fireEvent.click(screen.getByRole("button", { name: "Expand Firing Time" }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>(selector) ??
(fallbackSelector
Expand Down
Loading
Loading