Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor(explorer): own Ontology Hub URL state in one module (#1440)

Wei Tao0338f90bcafb
diff --git a/explorer/package.json b/explorer/package.json
index 9290271a..48c94e73 100644
--- a/explorer/package.json
+++ b/explorer/package.json
@@ -9,7 +9,7 @@
"lint": "eslint .",
"preview": "vite preview",
"test:graph-store": "node --test tests/graphStore.multi-edge.test.mjs",
- "test:graph-workspace": "node --import tsx --test tests/markdownContentViewer.test.ts tests/markdownEditorInteraction.test.tsx tests/markdownEditorState.test.ts tests/nodeMarkdownSync.test.ts tests/graphSceneState.display.test.ts tests/temporalLifecycle.test.ts tests/temporalScrubberBounds.test.ts tests/deterministicExplorerRendering.test.ts tests/explorerCapabilities.test.tsx tests/smallGraphLayout.test.ts tests/realtimeGraphAttributes.test.ts tests/ontologyEditorModel.test.ts tests/graphColorLegend.test.ts",
+ "test:graph-workspace": "node --import tsx --test tests/markdownContentViewer.test.ts tests/markdownEditorInteraction.test.tsx tests/markdownEditorState.test.ts tests/nodeMarkdownSync.test.ts tests/graphSceneState.display.test.ts tests/temporalLifecycle.test.ts tests/temporalScrubberBounds.test.ts tests/deterministicExplorerRendering.test.ts tests/explorerCapabilities.test.tsx tests/smallGraphLayout.test.ts tests/realtimeGraphAttributes.test.ts tests/ontologyEditorModel.test.ts tests/graphColorLegend.test.ts tests/ontologyUrlState.test.ts",
"test:deterministic-e2e": "node --import tsx --test tests/deterministicExplorerRendering.e2e.ts",
"test:graph-legend-e2e": "node --import tsx --test tests/graphColorLegend.e2e.ts",
"test:plugin-registry": "node --import tsx --test tests/pluginRegistry.temporal.test.mjs"
diff --git a/explorer/src/App.tsx b/explorer/src/App.tsx
index 51bf4c90..450c16c3 100644
--- a/explorer/src/App.tsx
+++ b/explorer/src/App.tsx
@@ -19,6 +19,7 @@ import {
import { ErrorBoundary } from './ErrorBoundary';
import { ExploreWorkspaceTabs, type ExploreView } from './ExploreWorkspaceTabs';
import { fetchAgentMemoryAvailability } from './explorerCapabilities';
+import { hasOntologyUrlState } from './workspaces/OntologyWorkspace/ontologyUrlState';
const DecisionWorkspace = lazy(() => import('./workspaces/DecisionWorkspace/DecisionWorkspace').then((module) => ({ default: module.DecisionWorkspace })));
const DiffMergeWorkspace = lazy(() => import('./workspaces/DiffMergeWorkspace/DiffMergeWorkspace').then((module) => ({ default: module.DiffMergeWorkspace })));
@@ -96,15 +97,7 @@ const navItems: NavItem[] = [
];
function readInitialWorkspace(): WorkspaceId {
- try {
- const params = new URLSearchParams(window.location.search);
- if (params.has("ontologyTab") || params.has("ontologyEntity")) {
- return "ontology-hub";
- }
- } catch {
- // Default to the welcome screen when URL state is unavailable.
- }
- return "welcome";
+ return hasOntologyUrlState() ? 'ontology-hub' : 'welcome';
}
const shellStyles = `
diff --git a/explorer/src/workspaces/OntologyWorkspace/OntologyEditor.tsx b/explorer/src/workspaces/OntologyWorkspace/OntologyEditor.tsx
index c4965748..043d4678 100644
--- a/explorer/src/workspaces/OntologyWorkspace/OntologyEditor.tsx
+++ b/explorer/src/workspaces/OntologyWorkspace/OntologyEditor.tsx
@@ -33,6 +33,7 @@ import {
ONTOLOGY_MINIMAP_THEME,
} from "./ontologyEditorModel";
import type { EditorEntityType, RegistryEntry } from "./ontologyEditorModel";
+import { clearEntitySelection, readOntologyUrlState, writeEntitySelection } from "./ontologyUrlState";
type OntologyNodeData = {
label?: string;
@@ -137,11 +138,7 @@ interface DraftDiff {
}
function requestedEntityUri(): string {
- try {
- return new URLSearchParams(window.location.search).get("ontologyEntity") || "";
- } catch {
- return "";
- }
+ return readOntologyUrlState().entityUri || "";
}
function nodeLabel(node: OntologyGraphNode): string {
@@ -377,14 +374,7 @@ export function OntologyEditor() {
const selectNode = useCallback((node: OntologyNode) => {
setSelectedElement(node);
- try {
- const params = new URLSearchParams(window.location.search);
- params.set("ontologyTab", "editor");
- params.set("ontologyEntity", node.id);
- window.history.replaceState(null, "", `?${params.toString()}`);
- } catch {
- // URL state is optional; the editor selection still works without it.
- }
+ writeEntitySelection(node.id);
}, []);
const saveDraft = useCallback(async () => {
@@ -554,15 +544,7 @@ export function OntologyEditor() {
onChange={(event) => {
setOntologyUri(event.target.value);
setSelectedElement(null);
- try {
- // Drop the previous ontology's entity from the URL, or a reload
- // would resolve the stale ID and jump back to that ontology.
- const params = new URLSearchParams(window.location.search);
- params.delete("ontologyEntity");
- window.history.replaceState(null, "", `?${params.toString()}`);
- } catch {
- // URL state is optional; switching ontologies still works.
- }
+ clearEntitySelection();
}}
style={selectStyle}
>
diff --git a/explorer/src/workspaces/OntologyWorkspace/index.tsx b/explorer/src/workspaces/OntologyWorkspace/index.tsx
index 70d4d719..35fdb707 100644
--- a/explorer/src/workspaces/OntologyWorkspace/index.tsx
+++ b/explorer/src/workspaces/OntologyWorkspace/index.tsx
@@ -13,6 +13,7 @@ import { OntologyManager } from "./OntologyManager";
import { OntologyEditor } from "./OntologyEditor";
import { ShaclStudio } from "./ShaclStudio";
import { VersionsTab } from "./VersionsTab";
+import { readOntologyUrlState, writeEntitySelection, writeTab } from "./ontologyUrlState";
export type OntologyHubTab =
| "registry"
@@ -22,8 +23,6 @@ export type OntologyHubTab =
| "health"
| "shacl";
-const TAB_PARAM = "ontologyTab";
-
const TABS: { id: OntologyHubTab; label: string; icon: typeof GitMerge }[] = [
{ id: "registry", label: "Registry", icon: BookMarked },
{ id: "editor", label: "Editor", icon: Sliders },
@@ -33,37 +32,23 @@ const TABS: { id: OntologyHubTab; label: string; icon: typeof GitMerge }[] = [
{ id: "shacl", label: "SHACL", icon: Shield },
];
-function readTabParam(): OntologyHubTab {
- try {
- const params = new URLSearchParams(window.location.search);
- const raw = params.get(TAB_PARAM);
- if (raw && TABS.some((t) => t.id === raw)) return raw as OntologyHubTab;
- if (params.get("ontologyEntity")) return "editor";
- } catch {
- // ignore
- }
+function readInitialTab(): OntologyHubTab {
+ const { tab, entityUri } = readOntologyUrlState();
+ const requested = TABS.find((candidate) => candidate.id === tab);
+ if (requested) return requested.id;
+ if (entityUri) return "editor";
return "registry";
}
-function writeTabParam(tab: OntologyHubTab) {
- try {
- const params = new URLSearchParams(window.location.search);
- params.set(TAB_PARAM, tab);
- window.history.replaceState(null, "", `?${params.toString()}`);
- } catch {
- // ignore
- }
-}
-
interface OntologyWorkspaceProps {
onJumpToGraphNode?: (nodeId: string) => void;
}
export function OntologyWorkspace({ onJumpToGraphNode }: OntologyWorkspaceProps) {
- const [activeTab, setActiveTab] = useState<OntologyHubTab>(readTabParam);
+ const [activeTab, setActiveTab] = useState<OntologyHubTab>(readInitialTab);
useEffect(() => {
- writeTabParam(activeTab);
+ writeTab(activeTab);
}, [activeTab]);
const handleTabChange = useCallback((tab: OntologyHubTab) => {
@@ -71,10 +56,7 @@ export function OntologyWorkspace({ onJumpToGraphNode }: OntologyWorkspaceProps)
}, []);
const handleFixInEditor = useCallback((entityUri: string) => {
- const params = new URLSearchParams(window.location.search);
- params.set(TAB_PARAM, "editor");
- params.set("ontologyEntity", entityUri);
- window.history.replaceState(null, "", `?${params.toString()}`);
+ writeEntitySelection(entityUri);
setActiveTab("editor");
}, []);
diff --git a/explorer/src/workspaces/OntologyWorkspace/ontologyUrlState.ts b/explorer/src/workspaces/OntologyWorkspace/ontologyUrlState.ts
new file mode 100644
index 00000000..90be0e1d
--- /dev/null
+++ b/explorer/src/workspaces/OntologyWorkspace/ontologyUrlState.ts
@@ -0,0 +1,94 @@
+// Sole owner of the Ontology Hub deep-link query parameters: the names below must not be
+// spelled out anywhere else, so that the protocol can change in one place.
+const TAB_PARAM = "ontologyTab";
+const ENTITY_PARAM = "ontologyEntity";
+const EDITOR_TAB = "editor";
+
+export interface OntologyUrlState {
+ /** Raw parameter value; the set of legal tab ids belongs to the workspace, not this module. */
+ tab?: string;
+ entityUri?: string;
+}
+
+/** `undefined` means the parameter is absent; an empty string means it is present but blank. */
+export function parseOntologyUrlState(search: string): OntologyUrlState {
+ const params = new URLSearchParams(search);
+ return {
+ tab: params.get(TAB_PARAM) ?? undefined,
+ entityUri: params.get(ENTITY_PARAM) ?? undefined,
+ };
+}
+
+export function applyTab(search: string, tab: string): string {
+ const params = new URLSearchParams(search);
+ params.set(TAB_PARAM, tab);
+ return `?${params.toString()}`;
+}
+
+// A selected entity is only addressable from the editor, so the tab moves with it.
+export function applyEntitySelection(search: string, entityUri: string): string {
+ const params = new URLSearchParams(search);
+ params.set(TAB_PARAM, EDITOR_TAB);
+ params.set(ENTITY_PARAM, entityUri);
+ return `?${params.toString()}`;
+}
+
+// Pairs with applyEntitySelection: an entity URI is resolved back to its owning ontology on
+// load, so leaving a stale one behind when the active ontology changes reopens the old ontology.
+export function removeEntitySelection(search: string): string {
+ const params = new URLSearchParams(search);
+ params.delete(ENTITY_PARAM);
+ return `?${params.toString()}`;
+}
+
+/**
+ * Deliberately dual-role, and the argument is what selects the role: given a
+ * `search` string this is pure and total, delegating straight to
+ * `parseOntologyUrlState`; called with no argument it reads live `window`
+ * state and yields empty state if the URL is unreadable. Callers in render or
+ * effect paths use the no-argument form; tests and any caller that already
+ * holds a search string pass it, which is the only form that is testable.
+ */
+export function readOntologyUrlState(search?: string): OntologyUrlState {
+ if (search !== undefined) {
+ return parseOntologyUrlState(search);
+ }
+ try {
+ return parseOntologyUrlState(window.location.search);
+ } catch {
+ return {};
+ }
+}
+
+/** True when the URL addresses the Ontology Hub at all, even with blank parameter values. */
+export function hasOntologyUrlState(search?: string): boolean {
+ const { tab, entityUri } = readOntologyUrlState(search);
+ return tab !== undefined || entityUri !== undefined;
+}
+
+// The transform returns a query string only, so the fragment has to be carried
+// across explicitly: replaceState with a bare "?..." drops it. This is the one
+// place that knows how the URL is written, so it is the only place that can.
+function updateSearch(transform: (search: string) => string): void {
+ try {
+ window.history.replaceState(
+ null,
+ "",
+ `${transform(window.location.search)}${window.location.hash}`,
+ );
+ } catch {
+ // Deep-link state is a convenience; every caller stays correct without it.
+ }
+}
+
+export function writeTab(tab: string): void {
+ updateSearch((search) => applyTab(search, tab));
+}
+
+export function writeEntitySelection(entityUri: string): void {
+ updateSearch((search) => applyEntitySelection(search, entityUri));
+}
+
+export function clearEntitySelection(): void {
+ updateSearch(removeEntitySelection);
+}
diff --git a/explorer/tests/ontologyUrlState.test.ts b/explorer/tests/ontologyUrlState.test.ts
new file mode 100644
index 00000000..b51e0c78
--- /dev/null
+++ b/explorer/tests/ontologyUrlState.test.ts
@@ -0,0 +1,102 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ applyEntitySelection,
+ applyTab,
+ clearEntitySelection,
+ hasOntologyUrlState,
+ parseOntologyUrlState,
+ readOntologyUrlState,
+ removeEntitySelection,
+ writeEntitySelection,
+ writeTab,
+} from "../src/workspaces/OntologyWorkspace/ontologyUrlState";
+
+function withStubbedLocation(search: string, hash: string, body: () => void): string[] {
+ const written: string[] = [];
+ const original = (globalThis as { window?: unknown }).window;
+ (globalThis as { window?: unknown }).window = {
+ location: { search, hash },
+ history: { replaceState: (_s: unknown, _t: string, url: string) => written.push(url) },
+ };
+ try {
+ body();
+ } finally {
+ (globalThis as { window?: unknown }).window = original;
+ }
+ return written;
+}
+
+test("selecting an entity round-trips and pins the editor tab", () => {
+ const search = applyEntitySelection("", "https://example.test/foo#Bar");
+ assert.deepEqual(parseOntologyUrlState(search), {
+ tab: "editor",
+ entityUri: "https://example.test/foo#Bar",
+ });
+});
+
+test("clearing the selection drops only the entity and keeps unrelated params", () => {
+ const search = applyEntitySelection("?view=graph&depth=2", "https://example.test/foo#Bar");
+ const cleared = parseOntologyUrlState(removeEntitySelection(search));
+
+ assert.equal(cleared.entityUri, undefined);
+ assert.equal(cleared.tab, "editor");
+ assert.equal(new URLSearchParams(removeEntitySelection(search)).get("depth"), "2");
+});
+
+test("writing a tab leaves an existing entity selection alone", () => {
+ const search = applyTab(applyEntitySelection("", "urn:x"), "health");
+ assert.deepEqual(parseOntologyUrlState(search), { tab: "health", entityUri: "urn:x" });
+});
+
+test("absent params read as undefined, blank params as empty strings", () => {
+ assert.deepEqual(parseOntologyUrlState(""), { tab: undefined, entityUri: undefined });
+ assert.deepEqual(parseOntologyUrlState("?other=1"), { tab: undefined, entityUri: undefined });
+ assert.deepEqual(parseOntologyUrlState("?ontologyTab=&ontologyEntity="), {
+ tab: "",
+ entityUri: "",
+ });
+});
+
+test("a present but blank param still counts as ontology deep-link state", () => {
+ assert.equal(hasOntologyUrlState("?ontologyEntity="), true);
+ assert.equal(hasOntologyUrlState("?ontologyTab="), true);
+ assert.equal(hasOntologyUrlState("?view=graph"), false);
+ assert.equal(hasOntologyUrlState(""), false);
+});
+
+test("malformed search strings degrade to plain values instead of throwing", () => {
+ assert.deepEqual(parseOntologyUrlState("???"), { tab: undefined, entityUri: undefined });
+ assert.deepEqual(parseOntologyUrlState("ontologyEntity=urn%3Ax&&=&"), {
+ tab: undefined,
+ entityUri: "urn:x",
+ });
+});
+
+test("entity URIs survive characters that need escaping", () => {
+ const entityUri = "https://example.test/vocab#Has Part/&?=";
+ const search = applyEntitySelection("?keep=1", entityUri);
+ assert.equal(parseOntologyUrlState(search).entityUri, entityUri);
+});
+
+test("every writer preserves the URL fragment", () => {
+ const written = withStubbedLocation("?view=graph", "#section-3", () => {
+ writeTab("health");
+ writeEntitySelection("urn:x");
+ clearEntitySelection();
+ });
+
+ assert.deepEqual(written, [
+ "?view=graph&ontologyTab=health#section-3",
+ "?view=graph&ontologyTab=editor&ontologyEntity=urn%3Ax#section-3",
+ "?view=graph#section-3",
+ ]);
+});
+
+test("readOntologyUrlState with no argument reads live URL state", () => {
+ withStubbedLocation("?ontologyTab=editor&ontologyEntity=urn%3Ax", "", () => {
+ assert.deepEqual(readOntologyUrlState(), { tab: "editor", entityUri: "urn:x" });
+ assert.equal(hasOntologyUrlState(), true);
+ });
+});