diff --git a/README.md b/README.md index 8d49d57..8d12f34 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Every education system organises what students should learn into structured docu | | | |---|---| -| **Visual Editor** | Build competency frameworks on an interactive canvas. Drag, connect, and organise items visually — no spreadsheets or hand-edited files required. | +| **Visual Editor** | Build competency frameworks in a tree view, and align their items to other frameworks (including CASE Global ones) by dragging — no spreadsheets or hand-edited files required. | | **Publishing Server** | Publish frameworks through a standards-compliant API so that learning platforms, assessment tools, and credential systems can discover and consume them automatically. | | **Identity and Access** | Multi-tenant security so that different organisations can each manage their own frameworks independently, with role-based access controls for viewers, authors, and administrators. | diff --git a/apps/editor/README.md b/apps/editor/README.md index c9d316d..75d8747 100644 --- a/apps/editor/README.md +++ b/apps/editor/README.md @@ -1,21 +1,19 @@ # OpenCASE — Visual Framework Editor -The Editor is the authoring interface for OpenCASE. It provides an interactive canvas where users build [1EdTech CASE](https://www.1edtech.org/activity/case) competency frameworks visually — organising learning objectives, connecting related standards, and publishing the result directly to the OpenCASE publishing server. +The Editor is the authoring interface for OpenCASE. It provides a tree view where users build [1EdTech CASE](https://www.1edtech.org/activity/case) competency frameworks visually — organising learning objectives, connecting related standards, and publishing the result directly to the OpenCASE publishing server. --- ## What it does -- **Visual canvas editing** — competencies appear as items on a canvas; users drag, reposition, and connect them to define relationships such as "is child of", "is related to", or "precedes" -- **Automatic layout** — when a framework is opened for the first time, the editor analyses its structure and applies an appropriate layout automatically, so items are arranged clearly from the start -- **Publish to the API** — frameworks edited on the canvas can be saved directly to the OpenCASE publishing server, making them immediately available to consuming systems +- **Tree editing** — a framework's items appear as a tree; users add and edit items and see the hierarchy at a glance +- **Crosswalks** — users align items to items in other frameworks on the server, or in CASE Global frameworks, by dragging one onto the other +- **Publish to the API** — edited frameworks can be saved directly to the OpenCASE publishing server, making them immediately available to consuming systems - **Multi-tenant aware** — users sign in through the platform's identity service and work within their organisation's workspace ## How it works -A competency framework is a structured collection of items (individual learning objectives or standards) and associations (the relationships between them). On the canvas, items appear as nodes and associations appear as connections between them. Users can add, edit, reorder, and delete items; create associations between them; and rearrange the layout to suit the framework's structure. - -The editor detects whether a framework is best displayed as a hierarchy, a radial layout, or a tree, and applies the most suitable arrangement before anything appears on screen. +A competency framework is a structured collection of items (individual learning objectives or standards) and associations (the relationships between them). The Tree View shows the items as a hierarchy, with a second panel of associated frameworks to align them to. Users can add and edit items and create, change, and remove associations to other frameworks. Changes are saved as new immutable versions on the server, preserving a full history of every revision. diff --git a/apps/editor/docs/DEVELOPER.md b/apps/editor/docs/DEVELOPER.md index cb58e73..6e62238 100644 --- a/apps/editor/docs/DEVELOPER.md +++ b/apps/editor/docs/DEVELOPER.md @@ -47,35 +47,18 @@ Dependencies flow inward: `domain ← application ← infrastructure ← ui` Editor state uses a **pure reducer** pattern. The reducer and all its helpers have zero React dependencies, which makes them straightforward to test and reason about. - `state/EditorContext.tsx` — Thin React provider that wires the reducer to hooks. Orchestration only, no business logic. -- `state/editorReducer.ts` — Pure reducer handling all state transitions (selection, CRUD, layout, connect, delete, etc.) -- `state/helpers/nodeGeometry.ts` — Geometry utilities, type guards, graph adjacency builders -- `state/editorFactories.ts` — Factory functions for items, documents, edges, and graph structures +- `state/editorReducer.ts` — Pure reducer handling all state transitions (selection, item edits, adding items, inline alignment edits, graph loading) +- `state/graphTypes.ts` — Editor graph node/edge types and type guards +- `state/editorFactories.ts` — Factory functions for items, documents, and graphs --- -## Layout Algorithms +## Editor Graph Mapping -Three auto-layout modes, all pure functions with no side effects: +The CASE domain model (Framework, Item, Association) is the source of truth. The editor graph that the Tree View and save work from is a derived projection, with no layout: -| Layout | When to use | Edge style | -|--------|------------|-----------| -| **Hierarchy** | Flat lists — many items at one level | smoothstep | -| **Star** | Radial — framework at centre, branches fan out | bezier | -| **Tree** | General purpose — recursive horizontal spread | bezier | - -The editor auto-detects which layout suits a framework when no saved positions exist, and applies it *before* the first render (so there's no visible jump). - -- `layout/detectTopology.ts` — Classifies the graph shape -- `layout/applyInitialLayout.ts` — Pre-render layout orchestrator - ---- - -## React Flow Mapping - -The CASE domain model (Framework, Item, Association) is the source of truth. React Flow is a derived projection: - -- `reactflow/mapping/toReactFlow.ts` — Domain → React Flow -- `reactflow/mapping/fromEditorGraph.ts` — React Flow → Domain + layout +- `state/mapping/toEditorGraph.ts` — Domain → editor graph +- `state/mapping/fromEditorGraph.ts` — editor graph → Domain --- @@ -85,7 +68,7 @@ The CASE domain model (Framework, Item, Association) is the source of truth. Rea npm run test ``` -The test suite covers all the pure modules — reducer, layout algorithms, geometry helpers, topology detection, and factories. Tests live alongside the code they cover (`*.test.ts`), with shared fixtures in `src/__tests__/fixtures.ts`. +The test suite covers the pure modules — reducer, graph mapping, CASE package mappers, and factories. Tests live alongside the code they cover (`*.test.ts`), with shared fixtures in `src/__tests__/fixtures.ts`. --- @@ -94,6 +77,5 @@ The test suite covers all the pure modules — reducer, layout algorithms, geome - **React 19** + TypeScript - **Vite** (build + dev server) - **Tailwind CSS v4** + shadcn/ui -- **@xyflow/react** (React Flow) - **Vitest** (testing) - **oidc-client-ts** (authentication) diff --git a/apps/editor/docs/architecture.md b/apps/editor/docs/architecture.md index 62ae180..8551fd5 100644 --- a/apps/editor/docs/architecture.md +++ b/apps/editor/docs/architecture.md @@ -2,16 +2,15 @@ ## What this project is -An **open-source editor for 1EdTech CASE frameworks**. You can create and edit frameworks (CFDocument), items (CFItem), and associations (CFAssociation) through a visual canvas, with a **draft → publish** workflow. It's deliberately focused on core authoring — not trying to replace commercial CASE tools. +An **open-source editor for 1EdTech CASE frameworks**. You can create and edit frameworks (CFDocument), items (CFItem), and associations (CFAssociation) in a Tree View, with a **draft → publish** workflow. It's deliberately focused on core authoring — not trying to replace commercial CASE tools. -Under the hood, the CASE model is treated as a **graph** (items + associations). The canvas you see in the UI is just one way to visualise that graph — the domain model is what matters. +Under the hood, the CASE model is treated as a **graph** (items + associations). The Tree View is one way to show that graph — the domain model is what matters. (An earlier canvas view, built on React Flow, was removed in CGE-165.) ## Tech stack * React 19 + TypeScript (Vite) * Tailwind CSS v4 * shadcn/ui components -* React Flow (`@xyflow/react`) * Vitest (unit testing) * oidc-client-ts (authentication) @@ -23,12 +22,12 @@ These are the principles we don't bend on: 1. **Domain model is the source of truth** — The domain representation of a framework (items + associations) is authoritative. -2. **React Flow is a projection of the domain graph** — React Flow nodes/edges are derived from the domain model. They're not the canonical data. +2. **The editor graph is a projection of the domain model** — the editor's nodes/edges are derived from the domain model. They're not the canonical data. 3. **All user interactions become application commands** — UI events (edit node, add child, connect, delete) must translate to commands handled by the application layer. 4. **Clean architecture dependency direction** — Dependencies always point inward: - * `domain` has no dependencies on React, React Flow, APIs, or storage + * `domain` has no dependencies on React, APIs, or storage * `application` depends on `domain` * `infrastructure` implements interfaces defined by `application` * `ui` depends on `application` (and uses `infrastructure` through composition) @@ -37,12 +36,12 @@ These are the principles we don't bend on: ## Folder structure -Pure logic (reducer, layout algorithms, geometry) is isolated from React so it can be tested and reasoned about independently. +Pure logic (reducer, graph mapping) is isolated from React so it can be tested and reasoned about independently. ``` src ├── app -│ ├── App.tsx # App shell — topology detection + pre-render layout +│ ├── App.tsx # App shell — loading, saving, CASE Global targets │ ├── main.tsx │ └── providers/ @@ -62,26 +61,17 @@ src ├── ui │ ├── editor -│ │ ├── components/ # Canvas, header, dialogs -│ │ ├── reactflow/ -│ │ │ ├── nodeTypes/ # CaseItemNode, CaseFrameworkNode -│ │ │ ├── edgeTypes/ # LabeledEdge -│ │ │ ├── mapping/ -│ │ │ │ ├── toReactFlow.ts # Domain → React Flow nodes/edges -│ │ │ │ └── fromEditorGraph.ts # React Flow → Domain + layout -│ │ │ └── types.ts # CaseEditorNodeType, CaseEditorEdge, CaseEdgeData +│ │ ├── FrameworkEditor.tsx # Header, Tree View, properties panel, save +│ │ ├── components/ # Header, properties panel, dialogs +│ │ ├── treePanel/ # Tree View and crosswalk (associated frameworks) │ │ ├── state/ │ │ │ ├── EditorContext.tsx # React provider (orchestration only) │ │ │ ├── editorReducer.ts # Pure state reducer (no React dependency) -│ │ │ ├── editorFactories.ts # Node/edge factory helpers -│ │ │ └── helpers/ -│ │ │ └── nodeGeometry.ts # Pure geometry, type guards, adjacency -│ │ ├── layout/ -│ │ │ ├── detectTopology.ts # Classify graph as hierarchy/star/tree -│ │ │ ├── applyInitialLayout.ts # Pre-render layout orchestrator -│ │ │ ├── hierarchyLayout.ts # Flat column layout (smoothstep) -│ │ │ ├── starLayout.ts # Elliptical radial layout (bezier) -│ │ │ └── treeLayout.ts # Recursive tree-spread layout (bezier) +│ │ │ ├── editorFactories.ts # Graph factory helpers +│ │ │ ├── graphTypes.ts # CaseEditorNodeType, CaseEditorEdge, CaseEdgeData +│ │ │ └── mapping/ +│ │ │ ├── toEditorGraph.ts # Domain → editor graph +│ │ │ └── fromEditorGraph.ts # Editor graph → Domain │ │ └── terminology/ │ │ ├── lens.ts │ │ └── strings.ts @@ -110,22 +100,22 @@ We treat CASE as a **graph**: * `Association` = edge (`CFAssociation`) * `Framework` = aggregate root owning items + associations (`CFDocument` + supporting structures) -The domain model has no knowledge of React Flow, the UI, or any external system. +The domain model has no knowledge of the UI or any external system. --- -## Domain ↔ React Flow mapping +## Domain ↔ editor graph mapping This is the most important boundary in the codebase. The mapping code is intentionally centralised in two files: -* `src/ui/editor/reactflow/mapping/toReactFlow.ts` — Domain → React Flow -* `src/ui/editor/reactflow/mapping/fromEditorGraph.ts` — React Flow → Domain +* `src/ui/editor/state/mapping/toEditorGraph.ts` — Domain → editor graph +* `src/ui/editor/state/mapping/fromEditorGraph.ts` — editor graph → Domain **How it works:** -1. **Domain → React Flow is derived** — React Flow nodes/edges are built from the domain `Framework` (Item → Node, Association → Edge). -2. **UI changes become commands** — When a user drags, edits, or connects something, the UI translates that into an application command. The command updates the domain model, and the UI re-renders by re-projecting the domain. -3. **Layout is separate** — Positions (x, y) are a UI concern. They're stored in UI state, not in domain entities. +1. **Domain → graph is derived** — the editor's nodes/edges are built from the domain `Framework` (Item → Node, Association → Edge). +2. **UI changes become commands** — When a user edits or adds something, the UI dispatches a reducer action; saving rebuilds the domain `Framework` from the graph. +3. **No layout** — nodes carry no positions. Saves no longer write the canvas-era `ext:opencase` layout, edge style, or remote-link data, and drop it where a loaded framework had it. --- @@ -135,21 +125,12 @@ Editor state uses a **pure reducer** pattern, cleanly separated from React: ### Pure modules (no React dependency) -* **`state/editorReducer.ts`** — A single pure function that handles all state transitions: selection, CRUD, layout, connections, graph loading, etc. -* **`state/helpers/nodeGeometry.ts`** — Geometry utilities (sizing, handles, overlap detection), type guards, and graph adjacency builders. -* **`state/editorFactories.ts`** — Factory functions for items, documents, edges, and graph structures. - -### Layout algorithms (also pure) - -* **`layout/detectTopology.ts`** — Looks at a graph's shape and classifies it as `hierarchy`, `star`, or `tree`. -* **`layout/hierarchyLayout.ts`** — Vertical column: framework at top, items stacked below. Smoothstep edges. -* **`layout/starLayout.ts`** — Radial: framework at centre, branches fan out in angular sectors. Bezier edges. -* **`layout/treeLayout.ts`** — Recursive horizontal tree-spread. Bezier edges. -* **`layout/applyInitialLayout.ts`** — Pre-render orchestrator. Detects topology and applies layout *before* the first React Flow render, so there's no visible jump. +* **`state/editorReducer.ts`** — A single pure function that handles all state transitions: selection, item edits, adding items, inline alignment edits, graph loading. +* **`state/editorFactories.ts`** — Factory functions for items, documents, and graphs. ### React orchestration -* **`state/EditorContext.tsx`** — A thin React provider. It imports the reducer and layout functions, wires them up with hooks, and exposes the `EditorContext` API. Business logic stays out. +* **`state/EditorContext.tsx`** — A thin React provider. It wires the reducer up with hooks and exposes the `EditorContext` API. Business logic stays out. --- @@ -178,7 +159,7 @@ Implements the interfaces defined in `application/ports`: ## UI layer -* Renders the canvas editor (React Flow) +* Renders the framework in the Tree View * Provides panels and dialogs for editing properties * Translates UI events → commands * Shows draft status and the explicit publishing flow @@ -219,7 +200,7 @@ npm run test # Single run npm run test:watch # Watch mode ``` -If you're adding a new reducer action or layout algorithm, please add tests to go with it. +If you're adding a new reducer action, please add tests to go with it. --- @@ -233,8 +214,8 @@ Where to put things: * **External integrations** → `infrastructure/` If you're working on **nodes/edges**: -* Change components in `ui/editor/reactflow/*` -* Keep mapping logic in `mapping/*` +* Change the graph types in `ui/editor/state/graphTypes.ts` +* Keep mapping logic in `ui/editor/state/mapping/*` If you're adding **state logic**: * Add new actions to the `Action` union in `editorReducer.ts` diff --git a/apps/editor/docs/associations.md b/apps/editor/docs/associations.md index 0913e3b..8517b61 100644 --- a/apps/editor/docs/associations.md +++ b/apps/editor/docs/associations.md @@ -1,6 +1,6 @@ # Associations: import, display and authoring -How the editor and server handle a framework's associations: what gets imported, where associations are stored, how the Tree View shows and edits them, and what happens on save. The canvas view is disabled and is not covered here. +How the editor and server handle a framework's associations: what gets imported, where associations are stored, how the Tree View shows and edits them, and what happens on save. --- @@ -103,9 +103,9 @@ Import order matters for hosted vs remote. When imported frameworks link to each ## Loading into the editor -The editor state (`EditorContext`, `editorReducer`) holds a framework as nodes (items and the document) and edges (associations between them). Only associations with **both ends in the framework** become edges. Associations to anything else, including every external association, have no edge. `withOffCanvasAssociations` carries them over from the framework as loaded when the editor saves, so they aren't lost. +The editor state (`EditorContext`, `editorReducer`) holds a framework as nodes (items and the document) and edges (associations between them). Only associations with **both ends in the framework** become edges. Associations to anything else, including every external association, have no edge. `withOffCanvasAssociations` carries them over from the framework as loaded when the editor saves, so they aren't lost. That includes links the former canvas view drew to CASE Global frameworks (`ext:opencase.remoteLink`); a save keeps them but drops the canvas's handle positions from their `ext:opencase`, along with the document's and items' layout, edge style, and `linkedFrameworks`/`remoteItemLinks`. -Edges keep their association's stored node titles (`toReactFlow` → `fromEditorGraph`), so a save writes back the titles that were loaded. +Edges keep their association's stored node titles (`toEditorGraph` → `fromEditorGraph`), so a save writes back the titles that were loaded. --- @@ -208,7 +208,7 @@ Associations interact with forking in four ways: | Alignment framework shape, ownership, merge, fork remap | `src/domain/framework/alignmentFrameworks.ts` | | Inline edits made in the Tree View | `src/domain/framework/inlineAlignmentEdits.ts`, `editorReducer` (`inlineAlignment/*`) | | Moving associations on save | `src/application/framework/services/AlignmentStorage.ts` | -| Saving, plan before fork warning | `src/ui/editor/EditorCanvas.tsx` (`handleSave`, `doSave`), `src/app/App.tsx` (`handleSaveToServer`) | +| Saving, plan before fork warning | `src/ui/editor/FrameworkEditor.tsx` (`handleSave`, `doSave`), `src/app/App.tsx` (`handleSaveToServer`) | | Data-change detection (editor) | `src/domain/framework/hasFrameworkDataChanged.ts` | | Associations without an edge | `src/domain/framework/offCanvasAssociations.ts` | | Association export, node titles | `src/application/framework/mappers/case/toCasePackage.ts` | diff --git a/apps/editor/docs/design.md b/apps/editor/docs/design.md index f650c9d..dab7165 100644 --- a/apps/editor/docs/design.md +++ b/apps/editor/docs/design.md @@ -1,5 +1,7 @@ # Project Context: CASE Framework Editor +> Historical design notes. The React Flow canvas described below was removed in CGE-165; the editor now uses the Tree View only. See [architecture.md](architecture.md) for the current structure. + ## What this project is This project is an **editor for CASE frameworks**, built as an **open-source reference implementation**. diff --git a/apps/editor/package-lock.json b/apps/editor/package-lock.json index 2343ec1..e413342 100644 --- a/apps/editor/package-lock.json +++ b/apps/editor/package-lock.json @@ -15,7 +15,6 @@ "@radix-ui/react-label": "^2.1.8", "@radix-ui/react-radio-group": "^1.3.8", "@radix-ui/react-slot": "^1.2.4", - "@xyflow/react": "^12.10.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "lucide-react": "^0.563.0", @@ -2644,55 +2643,6 @@ "assertion-error": "^2.0.1" } }, - "node_modules/@types/d3-color": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", - "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", - "license": "MIT" - }, - "node_modules/@types/d3-drag": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz", - "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==", - "license": "MIT", - "dependencies": { - "@types/d3-selection": "*" - } - }, - "node_modules/@types/d3-interpolate": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", - "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", - "license": "MIT", - "dependencies": { - "@types/d3-color": "*" - } - }, - "node_modules/@types/d3-selection": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz", - "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==", - "license": "MIT" - }, - "node_modules/@types/d3-transition": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz", - "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==", - "license": "MIT", - "dependencies": { - "@types/d3-selection": "*" - } - }, - "node_modules/@types/d3-zoom": { - "version": "3.0.8", - "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz", - "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==", - "license": "MIT", - "dependencies": { - "@types/d3-interpolate": "*", - "@types/d3-selection": "*" - } - }, "node_modules/@types/deep-eql": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", @@ -3155,38 +3105,6 @@ "url": "https://opencollective.com/vitest" } }, - "node_modules/@xyflow/react": { - "version": "12.10.0", - "resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.10.0.tgz", - "integrity": "sha512-eOtz3whDMWrB4KWVatIBrKuxECHqip6PfA8fTpaS2RUGVpiEAe+nqDKsLqkViVWxDGreq0lWX71Xth/SPAzXiw==", - "license": "MIT", - "dependencies": { - "@xyflow/system": "0.0.74", - "classcat": "^5.0.3", - "zustand": "^4.4.0" - }, - "peerDependencies": { - "react": ">=17", - "react-dom": ">=17" - } - }, - "node_modules/@xyflow/system": { - "version": "0.0.74", - "resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.74.tgz", - "integrity": "sha512-7v7B/PkiVrkdZzSbL+inGAo6tkR/WQHHG0/jhSvLQToCsfa8YubOGmBYd1s08tpKpihdHDZFwzQZeR69QSBb4Q==", - "license": "MIT", - "dependencies": { - "@types/d3-drag": "^3.0.7", - "@types/d3-interpolate": "^3.0.4", - "@types/d3-selection": "^3.0.10", - "@types/d3-transition": "^3.0.8", - "@types/d3-zoom": "^3.0.8", - "d3-drag": "^3.0.0", - "d3-interpolate": "^3.0.1", - "d3-selection": "^3.0.0", - "d3-zoom": "^3.0.0" - } - }, "node_modules/acorn": { "version": "8.15.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", @@ -3467,12 +3385,6 @@ "url": "https://polar.sh/cva" } }, - "node_modules/classcat": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz", - "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==", - "license": "MIT" - }, "node_modules/clsx": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", @@ -3606,111 +3518,6 @@ "devOptional": true, "license": "MIT" }, - "node_modules/d3-color": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", - "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-dispatch": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz", - "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-drag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz", - "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==", - "license": "ISC", - "dependencies": { - "d3-dispatch": "1 - 3", - "d3-selection": "3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-ease": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", - "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", - "license": "BSD-3-Clause", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-interpolate": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", - "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", - "license": "ISC", - "dependencies": { - "d3-color": "1 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-selection": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", - "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-timer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", - "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-transition": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz", - "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==", - "license": "ISC", - "dependencies": { - "d3-color": "1 - 3", - "d3-dispatch": "1 - 3", - "d3-ease": "1 - 3", - "d3-interpolate": "1 - 3", - "d3-timer": "1 - 3" - }, - "engines": { - "node": ">=12" - }, - "peerDependencies": { - "d3-selection": "2 - 3" - } - }, - "node_modules/d3-zoom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz", - "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==", - "license": "ISC", - "dependencies": { - "d3-dispatch": "1 - 3", - "d3-drag": "2 - 3", - "d3-interpolate": "1 - 3", - "d3-selection": "2 - 3", - "d3-transition": "2 - 3" - }, - "engines": { - "node": ">=12" - } - }, "node_modules/data-urls": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz", @@ -5824,15 +5631,6 @@ } } }, - "node_modules/use-sync-external-store": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", - "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==", - "license": "MIT", - "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, "node_modules/vite": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", @@ -6175,34 +5973,6 @@ "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } - }, - "node_modules/zustand": { - "version": "4.5.7", - "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz", - "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==", - "license": "MIT", - "dependencies": { - "use-sync-external-store": "^1.2.2" - }, - "engines": { - "node": ">=12.7.0" - }, - "peerDependencies": { - "@types/react": ">=16.8", - "immer": ">=9.0.6", - "react": ">=16.8" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "immer": { - "optional": true - }, - "react": { - "optional": true - } - } } } } diff --git a/apps/editor/package.json b/apps/editor/package.json index c201476..eb69e3d 100644 --- a/apps/editor/package.json +++ b/apps/editor/package.json @@ -19,7 +19,6 @@ "@radix-ui/react-label": "^2.1.8", "@radix-ui/react-radio-group": "^1.3.8", "@radix-ui/react-slot": "^1.2.4", - "@xyflow/react": "^12.10.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "lucide-react": "^0.563.0", diff --git a/apps/editor/src/__tests__/fixtures.ts b/apps/editor/src/__tests__/fixtures.ts index aab8c29..fed3416 100644 --- a/apps/editor/src/__tests__/fixtures.ts +++ b/apps/editor/src/__tests__/fixtures.ts @@ -1,11 +1,7 @@ /** - * Shared test fixtures for the CASE editor. - * - * Provides factory helpers to build mock nodes, edges, and graphs - * representing common framework structures (flat hierarchy, star, tree). + * Shared test fixtures for the CASE editor: factory helpers for graph nodes and edges. */ -import type { CaseEditorEdge, CaseEditorNodeType, CaseFrameworkNodeType, CaseItemNodeType } from '@/ui/editor/reactflow/types' -import type { EditorGraph } from '@/ui/editor/state/editorFactories' +import type { CaseEditorEdge, CaseFrameworkNodeType, CaseItemNodeType } from '@/ui/editor/state/graphTypes' // ── Node factories ───────────────────────────────────────────────────── @@ -13,25 +9,24 @@ export function makeFrameworkNode(overrides: Partial = {} return { id: 'fw-1', type: 'caseFrameworkNode', - position: { x: 0, y: 0 }, data: { cfDocument: { identifier: 'fw-1', uri: 'urn:case:fw-1', title: 'Test Framework', + creator: 'Test', + CFPackageURI: { uri: 'urn:case:package:fw-1' }, lastChangeDateTime: '2025-01-01T00:00:00Z', }, }, ...overrides, - } as CaseFrameworkNodeType + } } export function makeItemNode(id: string, overrides: Partial = {}): CaseItemNodeType { return { id, type: 'caseItemNode', - position: { x: 100, y: 100 }, - style: { width: 280, height: 140 }, data: { cfItem: { identifier: id, @@ -41,7 +36,7 @@ export function makeItemNode(id: string, overrides: Partial = }, }, ...overrides, - } as CaseItemNodeType + } } // ── Edge factory ─────────────────────────────────────────────────────── @@ -62,94 +57,3 @@ export function makeEdge( ...overrides, } } - -/** Make an edge with a sequence number. */ -export function makeSeqEdge( - source: string, - target: string, - seq: number, - overrides: Partial = {}, -): CaseEditorEdge { - return makeEdge(source, target, { - data: { - isHierarchical: true, - associationType: source.startsWith('fw') ? '__startsFrom' : 'isChildOf', - sequenceNumber: seq, - }, - ...overrides, - }) -} - -// ── Graph factories ──────────────────────────────────────────────────── - -/** - * Flat hierarchy: framework → N items, no item-to-item edges. - * - * fw-1 - * ├─ item-1 - * ├─ item-2 - * └─ item-3 - */ -export function makeFlatHierarchyGraph(itemCount = 3): EditorGraph { - const fw = makeFrameworkNode() - const items = Array.from({ length: itemCount }, (_, i) => makeItemNode(`item-${i + 1}`)) - const edges = items.map((item, i) => makeSeqEdge('fw-1', item.id, i + 1)) - return { nodes: [fw, ...items], edges } -} - -/** - * Star/multi-branch: framework → start nodes, each with children. - * - * fw-1 - * ├─ branch-A - * │ ├─ child-A1 - * │ └─ child-A2 - * └─ branch-B - * └─ child-B1 - */ -export function makeStarGraph(): EditorGraph { - const fw = makeFrameworkNode() - const branchA = makeItemNode('branch-A') - const branchB = makeItemNode('branch-B') - const childA1 = makeItemNode('child-A1') - const childA2 = makeItemNode('child-A2') - const childB1 = makeItemNode('child-B1') - - const edges: CaseEditorEdge[] = [ - makeSeqEdge('fw-1', 'branch-A', 1), - makeSeqEdge('fw-1', 'branch-B', 2), - makeEdge('branch-A', 'child-A1'), - makeEdge('branch-A', 'child-A2'), - makeEdge('branch-B', 'child-B1'), - ] - - return { nodes: [fw, branchA, branchB, childA1, childA2, childB1], edges } -} - -/** - * Deep tree: framework → single chain of depth N. - * - * fw-1 → item-1 → item-2 → item-3 - */ -export function makeDeepTreeGraph(depth = 3): EditorGraph { - const fw = makeFrameworkNode() - const items: CaseItemNodeType[] = [] - const edges: CaseEditorEdge[] = [] - - let parentId = 'fw-1' - for (let i = 1; i <= depth; i++) { - const id = `item-${i}` - items.push(makeItemNode(id)) - edges.push(makeEdge(parentId, id)) - parentId = id - } - - return { nodes: [fw, ...items], edges } -} - -/** - * Empty graph: just a framework node, no items. - */ -export function makeEmptyGraph(): EditorGraph { - return { nodes: [makeFrameworkNode()], edges: [] } -} diff --git a/apps/editor/src/app/App.tsx b/apps/editor/src/app/App.tsx index c50b387..4acdf8e 100644 --- a/apps/editor/src/app/App.tsx +++ b/apps/editor/src/app/App.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { EditorProvider } from '@/ui/editor/state/EditorContext' -import EditorCanvas from '@/ui/editor/EditorCanvas' +import FrameworkEditor from '@/ui/editor/FrameworkEditor' import HomeScreen from '@/ui/home/HomeScreen' import { createNewFrameworkDraft, createHomeFrameworkFromDomain, loadFrameworks, saveFrameworks, type HomeFramework } from '@/ui/home/frameworkStore' import type { CreateFrameworkDraft } from '@/ui/home/CreateFrameworkDialog' @@ -9,19 +9,18 @@ import { alignmentFrameworkSourceId, alignmentFrameworkTargetId } from '@/domain import { AuthProvider, useAuth } from '@/app/providers/AuthProvider' import { getAppConfig } from '@/app/config' import { CaseApiClient, type CfDocumentSummary } from '@/infrastructure/caseApi/CaseApiClient' +import type { CgeFrameworkSummary } from '@/infrastructure/caseApi/cgeTypes' +import type { CgeTargetSupport } from '@/ui/editor/treePanel/TreePanelView' import { createFetchHttpClient } from '@/infrastructure/caseApi/http' import { loadFrameworkFromCfPackage } from '@/application/framework/services/FrameworkLoader' import { planAlignmentStorage, saveWithAlignmentStorage, type AlignmentStoragePlan, type AlignmentStoragePort } from '@/application/framework/services/AlignmentStorage' -import { toReactFlowGraph, extractLayoutFromCfPackage, extractEditorSettingsFromCfPackage, extractRemoteFrameworkDataFromCfPackage, normalizeLinkedFrameworkColors } from '@/ui/editor/reactflow/mapping' +import { toEditorGraph } from '@/ui/editor/state/mapping/toEditorGraph' import { frameworkToCfPackage, toOpenCaseFormat } from '@/application/framework/mappers/case/toCasePackage' -import type { LayoutState } from '@/ui/editor/reactflow/mapping' import type { CaseVersion } from '@/application/framework/mappers/case/CasePackageSnapshot' import type { CFAssociationGrouping, CFItemType, CFLicense, CFSubject, CFConcept, CFDefinition } from '@/domain/case/types' import { extractCfDefinitions, preferFrameworkDefinitions } from '@/application/framework/mappers/case/frameworkDefinitions' import LoginScreen from '@/ui/auth/LoginScreen' import { ensureDefaultMembership } from '@/app/ensureDefaultMembership' -import { detectTopology } from '@/ui/editor/layout/detectTopology' -import { applyInitialLayout } from '@/ui/editor/layout/applyInitialLayout' /** Parse the `` out of a `#/framework/` hash, or null if the hash doesn't match. */ function getFrameworkIdFromHash(): string | null { @@ -49,12 +48,6 @@ function AppInner() { const [frameworks, setFrameworks] = useState(() => loadFrameworks()) const [activeFrameworkId, setActiveFrameworkId] = useState(() => getFrameworkIdFromHash()) - // Store layouts extracted from CASE extensions (keyed by framework ID) - const [frameworkLayouts, setFrameworkLayouts] = useState>({}) - - // Store per-framework edge type from CASE extensions (keyed by framework ID) - const [frameworkEdgeTypes, setFrameworkEdgeTypes] = useState>({}) - // Each framework's own CFDefinitions as returned by its CFPackage (keyed by framework ID). // These take precedence over the tenant catalogue when the framework is saved. const [frameworkCfDefinitions, setFrameworkCfDefinitions] = useState>({}) @@ -366,10 +359,6 @@ function AppInner() { // Extract CFDefinitions (item types, subjects, concepts, groupings) from the package mergeCfDefinitions(pkg) - // Extract layout and editor settings from CASE extensions before converting to domain model - const layout = extractLayoutFromCfPackage(pkg) - const editorSettings = extractEditorSettingsFromCfPackage(pkg) - // Use the FrameworkLoader to map CASE → domain Framework // This handles v1p0/v1p1 differences through the normalization layer const framework = loadFrameworkFromCfPackage(pkg) @@ -402,16 +391,6 @@ function AppInner() { return ownDefinitions ? { ...rest, [fw.id]: ownDefinitions } : rest }) - // Store the extracted layout - if (layout) { - setFrameworkLayouts((prev) => ({ ...prev, [fw.id]: layout })) - } - - // Store the extracted edge type - if (editorSettings?.edgeType) { - setFrameworkEdgeTypes((prev) => ({ ...prev, [fw.id]: editorSettings.edgeType! })) - } - setFrameworks((prev) => { // Update existing framework or add new one const existingIdx = prev.findIndex((f) => f.id === fw.id) @@ -455,20 +434,18 @@ function AppInner() { // Load a framework from the server into the local session without navigating to it. // Used by TreePanelView when the user selects a crosswalk target that isn't loaded locally yet. + // `replace` swaps in the server's copy when the framework is already loaded (after a refresh). const handleLoadTargetFramework = useCallback( - async (docId: string) => { + async (docId: string, options?: { replace?: boolean }) => { const pkg = await api.getCfPackage({ docId, caseVersion: 'v1p1' }) mergeCfDefinitions(pkg) - const layout = extractLayoutFromCfPackage(pkg) - const editorSettings = extractEditorSettingsFromCfPackage(pkg) const framework = loadFrameworkFromCfPackage(pkg) if (!framework) throw new Error('Failed to load framework from CASE package') const fw = createHomeFrameworkFromDomain(framework) - if (layout) setFrameworkLayouts((prev) => ({ ...prev, [fw.id]: layout })) - if (editorSettings?.edgeType) setFrameworkEdgeTypes((prev) => ({ ...prev, [fw.id]: editorSettings.edgeType! })) setFrameworks((prev) => { - if (prev.some((f) => f.id === fw.id)) return prev - const next = [...prev, fw] + const existingIdx = prev.findIndex((f) => f.id === fw.id) + if (existingIdx !== -1 && !options?.replace) return prev + const next = existingIdx === -1 ? [...prev, fw] : prev.map((f, i) => (i === existingIdx ? { ...fw, readOnly: f.readOnly } : f)) saveFrameworks(next) return next }) @@ -476,37 +453,69 @@ function AppInner() { [api, mergeCfDefinitions], ) - // Derive the graph from the active framework - // This converts the domain Framework to React Flow format. - // When no saved layout exists the topology is detected and an appropriate - // auto-layout is applied *before* the first render so there is no visible jump. - const { graph: activeGraph, autoEdgeType } = useMemo(() => { - if (!activeFramework) return { graph: null, autoEdgeType: undefined as string | undefined } - - // Use legacy graph if available (for backward compatibility with stored data) - if (activeFramework.graph) { - return { graph: activeFramework.graph, autoEdgeType: undefined as string | undefined } + // Server frameworks that are read-only copies of CASE Global frameworks: document id -> coalition framework id. + const cgeCacheFrameworkIds = useMemo(() => { + const ids = new Map() + for (const doc of serverCfDocuments) { + const ext = doc.extensions?.['ext:opencase'] + const cgeFrameworkId = doc.cgeFrameworkId ?? ext?.cgeFrameworkId + if ((doc.readOnly ?? ext?.readOnly) === true && cgeFrameworkId) ids.set(doc.identifier, cgeFrameworkId) } - - // Get the stored layout for this framework (from CASE extensions) - const layout = frameworkLayouts[activeFramework.id] - const remoteEditorData = extractRemoteFrameworkDataFromCfPackage({ - CFDocument: activeFramework.cfDocument, - CFItems: [], - CFAssociations: [], + return ids + }, [serverCfDocuments]) + + // Cache a CASE Global framework on this server (read-only) so it can be a crosswalk target. + const handleAddCgeTarget = useCallback(async (fw: CgeFrameworkSummary): Promise => { + if (!tenantId) throw new Error('Sign in required') + for (const [docId, cgeFrameworkId] of cgeCacheFrameworkIds) { + if (cgeFrameworkId === fw.frameworkId) return docId + } + const result = await api.importCgeFramework({ + tenantId, + frameworkId: fw.frameworkId, + sourceUri: fw.sourceUri, + registryId: fw.registryId, + readOnly: true, + subscribe: false, }) - remoteEditorData.linkedFrameworks = normalizeLinkedFrameworkColors(remoteEditorData.linkedFrameworks) - const graph = toReactFlowGraph({ framework: activeFramework.framework, layout, remoteEditorData }) - - // If no saved layout, detect topology and apply appropriate layout - if (!layout) { - const topology = detectTopology(graph) - const result = applyInitialLayout(graph, topology) - return { graph: result.graph, autoEdgeType: result.edgeType } + const summary: CfDocumentSummary = { + identifier: result.docId, + title: result.title ?? fw.title, + readOnly: true, + cgeFrameworkId: fw.frameworkId, } + setServerCfDocuments((prev) => (prev.some((d) => d.identifier === result.docId) ? prev : [...prev, summary])) + return result.docId + }, [api, tenantId, cgeCacheFrameworkIds]) + + // Download a cached CASE Global framework from its publisher again, then reload it. + const handleRefreshCgeTarget = useCallback(async (docId: string) => { + const cgeFrameworkId = cgeCacheFrameworkIds.get(docId) + if (!tenantId || !cgeFrameworkId) return + await api.refreshCgeCache({ tenantId, frameworkId: cgeFrameworkId }) + await handleLoadTargetFramework(docId, { replace: true }) + }, [api, tenantId, cgeCacheFrameworkIds, handleLoadTargetFramework]) + + const cgeTargetSupport = useMemo( + () => (tenantId + ? { + tenantId, + api, + onAddTarget: handleAddCgeTarget, + cachedFrameworkIds: new Set(cgeCacheFrameworkIds.keys()), + onRefreshTarget: handleRefreshCgeTarget, + } + : undefined), + [tenantId, api, handleAddCgeTarget, cgeCacheFrameworkIds, handleRefreshCgeTarget], + ) - return { graph, autoEdgeType: undefined as string | undefined } - }, [activeFramework, frameworkLayouts]) + // Derive the editor graph from the active framework + const activeGraph = useMemo(() => { + if (!activeFramework) return null + // Use legacy graph if available (for backward compatibility with stored data) + if (activeFramework.graph) return activeFramework.graph + return toEditorGraph({ framework: activeFramework.framework }) + }, [activeFramework]) // Determine CASE version from framework metadata or CFDocument // (computed early so useCallback has stable deps - must be before all early returns) @@ -516,25 +525,11 @@ function AppInner() { ?? '1.1') as CaseVersion) : '1.1' - // Always save/archive via v1p1 management endpoints. + // Always save via v1p1 management endpoints. // The backend serves frameworks transparently over both v1p0 and v1p1 public APIs // via on-the-fly downconversion, so a single v1p1 store is sufficient. const caseApiVersion: 'v1p0' | 'v1p1' = 'v1p1' - // Handler to archive the active framework on the server - // Must be defined before early returns (React hooks rules) - const handleArchiveFramework = useCallback(async () => { - if (!tenantId || !activeFrameworkId) { - throw new Error('Not signed in or no active framework') - } - await api.deleteCfPackage({ - tenantId, - docId: activeFrameworkId, - caseVersion: caseApiVersion, - }) - removeFrameworkFromStorage(activeFrameworkId) - }, [api, tenantId, activeFrameworkId, caseApiVersion, removeFrameworkFromStorage]) - // Handler to fetch the published CFPackage from the server (returns CASE JSON with absolute URIs). // This is the user-facing view/export, so omit OpenCASE extensions (ext:opencase). const handleFetchCfPackage = useCallback(async () => { @@ -595,14 +590,6 @@ function AppInner() { saveFrameworks(next) return next }) - setFrameworkLayouts((prev) => { - const { [oldId]: _dropped, ...rest } = prev - return rest - }) - setFrameworkEdgeTypes((prev) => { - const { [oldId]: _dropped, ...rest } = prev - return rest - }) setFrameworkCfDefinitions((prev) => { const { [oldId]: _dropped, ...rest } = prev return rest @@ -785,19 +772,16 @@ function AppInner() { initialGraph={activeGraph} graphKey={activeFramework.id} caseVersion={activeCaseVersion} - skipAutoLayout={Boolean(frameworkLayouts[activeFramework.id]) || Boolean(autoEdgeType)} - initialEdgeType={frameworkEdgeTypes[activeFramework.id] ?? autoEdgeType} initialCfItemTypes={editorDefinitions.cfItemTypes} initialCfSubjects={editorDefinitions.cfSubjects} initialCfConcepts={editorDefinitions.cfConcepts} initialCfLicenses={editorDefinitions.cfLicenses} initialCfAssociationGroupings={editorDefinitions.cfAssociationGroupings} > - navigateHome()} onSaveToServer={tenantId ? handleSaveToServer : undefined} onPlanAlignmentStorage={tenantId ? handlePlanAlignmentStorage : undefined} - onArchiveFramework={tenantId && activeFrameworkId ? handleArchiveFramework : undefined} onFetchCfPackage={activeFrameworkId ? handleFetchCfPackage : undefined} availableFrameworks={frameworks} serverFrameworks={serverFrameworkSummaries} @@ -806,6 +790,7 @@ function AppInner() { onLoadAlignmentsForTarget={tenantId ? handleLoadAlignmentsForTarget : undefined} onDiscoverAlignedTargets={tenantId ? handleDiscoverAlignedTargets : undefined} onLookupItemDocuments={handleLookupItemDocuments} + cge={cgeTargetSupport} mirrorStatus={activeFramework.mirrorStatus} readOnly={activeFramework.readOnly} cfDefinitionsExtensions={activeCfDefinitions?.extensions} diff --git a/apps/editor/src/app/providers/AuthProvider.tsx b/apps/editor/src/app/providers/AuthProvider.tsx index 26eeee6..53aec9c 100644 --- a/apps/editor/src/app/providers/AuthProvider.tsx +++ b/apps/editor/src/app/providers/AuthProvider.tsx @@ -11,8 +11,7 @@ type AuthContextValue = { userName: string | null accessToken: string | null error: string | null - setTenantId: (_tenantId: string) => void - signIn: (_tenantId?: string, _options?: { loginHint?: string }) => Promise + signIn: () => Promise completeSignIn: (_callbackUrl?: string) => Promise signOut: () => Promise getAccessToken: () => Promise @@ -25,22 +24,6 @@ type AuthContextValue = { changePassword: (() => Promise) | null } -const STORAGE_KEY_TENANT = 'case-editor:auth:tenantId' - -function readTenantId(): string { - const raw = globalThis.localStorage?.getItem(STORAGE_KEY_TENANT) ?? '' - const trimmed = raw.trim() - return trimmed || 'demo' -} - -function writeTenantId(tenantId: string) { - try { - globalThis.localStorage?.setItem(STORAGE_KEY_TENANT, tenantId) - } catch { - // ignore (storage may be unavailable) - } -} - function isFederatedUser(user: User | null): boolean { const profile = user?.profile as Record | undefined const idp = profile?.identity_provider @@ -82,7 +65,7 @@ export function createUserManager(params: { authority: string; clientId: string; */ export async function runSilentRenewCallback(): Promise { const cfg = getAppConfig() - const tenantId = readTenantId() + const tenantId = cfg.defaultTenantId const mgr = createUserManager({ authority: cfg.oidcAuthority, clientId: `${cfg.oidcClientIdPrefix}${tenantId}`, @@ -96,7 +79,8 @@ const AuthContext = createContext(null) export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) { const cfg = getAppConfig() - const [tenantId, setTenantIdState] = useState(() => readTenantId()) + // Everyone signs in to the deployment's one tenant (`system` unless configured otherwise). + const tenantId = cfg.defaultTenantId const [status, setStatus] = useState('loading') const [user, setUser] = useState(null) const [error, setError] = useState(null) @@ -161,39 +145,17 @@ export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) { } }, [userManager]) - const setTenantId = useCallback((nextTenantId: string) => { - const trimmed = nextTenantId.trim() - if (!trimmed) return - writeTenantId(trimmed) - setTenantIdState(trimmed) - }, []) - - const signIn = useCallback( - async (maybeTenantId?: string, options?: { loginHint?: string }) => { - const nextTenantId = (maybeTenantId ?? tenantId).trim() - if (!nextTenantId) throw new Error('tenantId is required') - if (nextTenantId !== tenantId) setTenantId(nextTenantId) - - setStatus('loading') - setError(null) - // Important: tenantId changes affect client_id. If the caller supplied a different tenantId, - // we must redirect using a UserManager configured for that tenant immediately (state updates - // are async, and React StrictMode can remount in dev). - const mgr = - nextTenantId === tenantId - ? userManager - : createUserManager({ - authority: cfg.oidcAuthority, - clientId: `${cfg.oidcClientIdPrefix}${nextTenantId}`, - redirectUri, - tenantId: nextTenantId, - }) - await mgr.signinRedirect({ - extraQueryParams: options?.loginHint ? { login_hint: options.loginHint } : undefined, - }) - }, - [tenantId, userManager, setTenantId, cfg.oidcAuthority, cfg.oidcClientIdPrefix, redirectUri], - ) + const signIn = useCallback(async () => { + setStatus('loading') + setError(null) + try { + await userManager.signinRedirect() + } catch (e) { + // The redirect never started (e.g. no Web Crypto outside a secure context): let the user retry. + setStatus('anonymous') + throw e + } + }, [userManager]) const completeSignIn = useCallback(async (callbackUrl?: string) => { setStatus('loading') @@ -268,7 +230,6 @@ export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) { userName, accessToken, error, - setTenantId, signIn, completeSignIn, signOut, @@ -276,7 +237,7 @@ export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) { refreshAccessToken, changePassword, }), - [status, tenantId, user, userName, accessToken, error, setTenantId, signIn, completeSignIn, signOut, getAccessToken, refreshAccessToken, changePassword], + [status, tenantId, user, userName, accessToken, error, signIn, completeSignIn, signOut, getAccessToken, refreshAccessToken, changePassword], ) return {children} diff --git a/apps/editor/src/application/framework/mappers/case/frameworkDefinitions.test.ts b/apps/editor/src/application/framework/mappers/case/frameworkDefinitions.test.ts index 3214e75..6fcc37b 100644 --- a/apps/editor/src/application/framework/mappers/case/frameworkDefinitions.test.ts +++ b/apps/editor/src/application/framework/mappers/case/frameworkDefinitions.test.ts @@ -2,8 +2,8 @@ import { describe, it, expect } from 'vitest' import { frameworkToCfPackage } from './toCasePackage' import { extractCfDefinitions, preferFrameworkDefinitions, type DefinitionLists } from './frameworkDefinitions' import { loadFrameworkFromCfPackage } from '@/application/framework/services/FrameworkLoader' -import { toReactFlowGraph } from '@/ui/editor/reactflow/mapping/toReactFlow' -import { fromEditorGraph } from '@/ui/editor/reactflow/mapping/fromEditorGraph' +import { toEditorGraph } from '@/ui/editor/state/mapping/toEditorGraph' +import { fromEditorGraph } from '@/ui/editor/state/mapping/fromEditorGraph' import type { CFItemType, CFPackage, CFSubject } from '@/domain/case/types' const DOC_ID = 'sc-doc' @@ -101,15 +101,14 @@ function makeScPackage(): CFPackage { } as unknown as CFPackage } -// Open the package in the editor and save it again, the way App + EditorCanvas do. +// Open the package in the editor and save it again, the way App + FrameworkEditor do. function openAndSave(pkg: CFPackage, tenant: DefinitionLists) { const own = extractCfDefinitions(pkg) const loaded = loadFrameworkFromCfPackage(pkg) if (!loaded) throw new Error('failed to load framework') - const { framework, layout } = fromEditorGraph({ graph: toReactFlowGraph({ framework: loaded }) }) + const { framework } = fromEditorGraph({ graph: toEditorGraph({ framework: loaded }) }) return frameworkToCfPackage({ framework, - layout, caseVersion: '1.1', ...preferFrameworkDefinitions(own, tenant), definitionsExtensions: own?.extensions, diff --git a/apps/editor/src/application/framework/mappers/case/toCasePackage.extensionsRoundTrip.test.ts b/apps/editor/src/application/framework/mappers/case/toCasePackage.extensionsRoundTrip.test.ts index 07829e7..9d9c385 100644 --- a/apps/editor/src/application/framework/mappers/case/toCasePackage.extensionsRoundTrip.test.ts +++ b/apps/editor/src/application/framework/mappers/case/toCasePackage.extensionsRoundTrip.test.ts @@ -1,9 +1,10 @@ import { describe, it, expect } from 'vitest' import { frameworkToCfPackage } from './toCasePackage' import { loadFrameworkFromCfPackage } from '@/application/framework/services/FrameworkLoader' -import { toReactFlowGraph } from '@/ui/editor/reactflow/mapping/toReactFlow' -import { fromEditorGraph } from '@/ui/editor/reactflow/mapping/fromEditorGraph' +import { toEditorGraph } from '@/ui/editor/state/mapping/toEditorGraph' +import { fromEditorGraph } from '@/ui/editor/state/mapping/fromEditorGraph' import { hasFrameworkDataChanged } from '@/domain/framework/hasFrameworkDataChanged' +import { withOffCanvasAssociations } from '@/domain/framework/offCanvasAssociations' import type { CFDocument, CFItem, CFPackage } from '@/domain/case/types' import type { Framework, Item } from '@/domain/framework/model/types' import type { ItemId } from '@/domain/shared/types' @@ -52,12 +53,12 @@ function makePackage(): CFPackage { function loadIntoEditor() { const framework = loadFrameworkFromCfPackage(makePackage()) if (!framework) throw new Error('failed to load framework') - return toReactFlowGraph({ framework }) + return toEditorGraph({ framework }) } -function saveFromEditor(graph: ReturnType) { - const { framework, layout } = fromEditorGraph({ graph }) - return frameworkToCfPackage({ framework, caseVersion: '1.1', layout }) +function saveFromEditor(graph: ReturnType) { + const { framework } = fromEditorGraph({ graph }) + return frameworkToCfPackage({ framework, caseVersion: '1.1' }) } function withItemMetadata(framework: Framework, patch: Record): Framework { @@ -68,7 +69,7 @@ function withItemMetadata(framework: Framework, patch: Record): } describe('CASE extensions round-trip through the editor', () => { - it('shows custom item and document extensions on the canvas, without ext:opencase on the document', () => { + it('shows custom item and document extensions in the editor, without ext:opencase on the document', () => { const graph = loadIntoEditor() const itemNode = graph.nodes.find((n) => (n.data as { cfItem?: CFItem }).cfItem?.identifier === 'item-1') const docNode = graph.nodes.find((n) => (n.data as { cfDocument?: CFDocument }).cfDocument?.identifier === DOC_ID) @@ -91,7 +92,52 @@ describe('CASE extensions round-trip through the editor', () => { expect(item?.extensions).toMatchObject({ smartschoolId: 'ss-1', 'ext:opencase': { colorBand: '#ff0000' } }) const assoc = saved.CFAssociations?.find((a) => a.identifier === 'assoc-root') - expect(assoc?.extensions).toMatchObject({ minimumGoal: 'MG-7', 'ext:opencase': { originHandle: 'top' } }) + expect(assoc?.extensions).toEqual({ minimumGoal: 'MG-7' }) + }) + + it('drops the former canvas view\'s ext:opencase data when saving, and keeps the rest', () => { + const pkg = makePackage() + pkg.CFDocument.extensions = { + ...pkg.CFDocument.extensions, + 'ext:opencase': { + publicAccess: true, + layout: { x: 1, y: 2, w: 400, h: 160 }, + edgeType: 'smoothstep', + linkedFrameworks: [{ id: 'ref-1', cgeFrameworkId: 'cge-1' }], + remoteItemLinks: [{ id: 'link-1', localItemId: 'item-1' }], + }, + } + const item = pkg.CFItems![0] + item.extensions = { ...item.extensions, 'ext:opencase': { colorBand: '#ff0000', layout: { x: 10, y: 20 } } } + pkg.CFAssociations!.push({ + identifier: 'assoc-remote', + uri: '/ims/case/v1p1/CFAssociations/assoc-remote', + associationType: 'isRelatedTo', + originNodeURI: { identifier: 'item-1', uri: '/ims/case/v1p1/CFItems/item-1', title: 'Item 1' }, + destinationNodeURI: { identifier: 'remote-item', uri: 'https://publisher.example/CFItems/remote-item', title: 'Remote' }, + lastChangeDateTime: '2026-01-01T00:00:00.000Z', + extensions: { + 'ext:opencase': { remoteLink: true, remoteItemIdentifier: 'remote-item', remoteItemUri: 'https://publisher.example/CFItems/remote-item', originHandle: 'right', destinationHandle: 'left' }, + }, + } as unknown as NonNullable[number]) + + const loaded = loadFrameworkFromCfPackage(pkg)! + const saved = frameworkToCfPackage({ + framework: withOffCanvasAssociations(loaded, fromEditorGraph({ graph: toEditorGraph({ framework: loaded }) }).framework), + caseVersion: '1.1', + }) + + expect(saved.CFDocument.extensions).toEqual({ + sourceSystem: { name: 'smartschool', curriculumId: 'cur-9' }, + 'ext:opencase': { publicAccess: true }, + }) + expect(saved.CFItems?.[0].extensions).toEqual({ smartschoolId: 'ss-1', 'ext:opencase': { colorBand: '#ff0000' } }) + // A link the canvas drew to a CASE Global framework is kept, minus its handles. + const remote = saved.CFAssociations?.find((a) => a.identifier === 'assoc-remote') + expect(remote?.destinationNodeURI).toMatchObject({ identifier: 'remote-item', uri: 'https://publisher.example/CFItems/remote-item' }) + expect(remote?.extensions).toEqual({ + 'ext:opencase': { remoteLink: true, remoteItemIdentifier: 'remote-item', remoteItemUri: 'https://publisher.example/CFItems/remote-item' }, + }) }) it('keeps custom document extensions even when there is no ext:opencase data to write', () => { @@ -128,7 +174,7 @@ describe('CASE extensions round-trip through the editor', () => { if (!framework) throw new Error('failed to load framework') expect(framework.metadata.alignmentStorage).toBe('alignmentFramework') - const saved = saveFromEditor(toReactFlowGraph({ framework })) + const saved = saveFromEditor(toEditorGraph({ framework })) expect(saved.CFDocument.extensions).toEqual({ 'ext:opencase': expect.objectContaining({ alignmentStorage: 'alignmentFramework' }) }) }) }) diff --git a/apps/editor/src/application/framework/mappers/case/toCasePackage.targetTypeRoundTrip.test.ts b/apps/editor/src/application/framework/mappers/case/toCasePackage.targetTypeRoundTrip.test.ts index bdfe05d..288000c 100644 --- a/apps/editor/src/application/framework/mappers/case/toCasePackage.targetTypeRoundTrip.test.ts +++ b/apps/editor/src/application/framework/mappers/case/toCasePackage.targetTypeRoundTrip.test.ts @@ -1,8 +1,8 @@ import { describe, it, expect } from 'vitest' import { frameworkToCfPackage, toOpenCaseFormat } from './toCasePackage' import { loadFrameworkFromCfPackage } from '@/application/framework/services/FrameworkLoader' -import { toReactFlowGraph } from '@/ui/editor/reactflow/mapping/toReactFlow' -import { fromEditorGraph } from '@/ui/editor/reactflow/mapping/fromEditorGraph' +import { toEditorGraph } from '@/ui/editor/state/mapping/toEditorGraph' +import { fromEditorGraph } from '@/ui/editor/state/mapping/fromEditorGraph' import { withOffCanvasAssociations } from '@/domain/framework/offCanvasAssociations' import type { CFPackage } from '@/domain/case/types' @@ -78,10 +78,10 @@ function load(pkg: CFPackage = makePackage()) { return framework } -/** Load → canvas graph → save, the same path EditorCanvas.handleSave takes. */ +/** Load → editor graph → save, the same path FrameworkEditor.handleSave takes. */ function saveFromEditor(pkg?: CFPackage) { const loaded = load(pkg) - const framework = withOffCanvasAssociations(loaded, fromEditorGraph({ graph: toReactFlowGraph({ framework: loaded }) }).framework) + const framework = withOffCanvasAssociations(loaded, fromEditorGraph({ graph: toEditorGraph({ framework: loaded }) }).framework) return { framework, openCase: toOpenCaseFormat(frameworkToCfPackage({ framework, caseVersion: '1.1' })) } } diff --git a/apps/editor/src/application/framework/mappers/case/toCasePackage.ts b/apps/editor/src/application/framework/mappers/case/toCasePackage.ts index 3c3521b..15b890c 100644 --- a/apps/editor/src/application/framework/mappers/case/toCasePackage.ts +++ b/apps/editor/src/application/framework/mappers/case/toCasePackage.ts @@ -1,7 +1,6 @@ import type { CFAssociation, CFAssociationGrouping, CFConcept, CFDefinition, CFDocument, CFItem, CFItemType, CFLicense, CFSubject, CFPackage, CaseExtensions, LinkURI } from '@/domain/case/types' import type { AlignmentStorage, Framework } from '@/domain/framework/model/types' import type { CaseVersion } from './CasePackageSnapshot' -import type { LayoutState, NodeLayout } from '@/ui/editor/reactflow/mapping/types' const nowIso = () => new Date().toISOString() @@ -89,18 +88,30 @@ function makePackageUri(uuid: string): string { } type OpencaseExtension = { - layout?: NodeLayout - notes?: string - originHandle?: string - destinationHandle?: string - edgeType?: string colorBand?: string - linkedFrameworks?: unknown[] - remoteItemLinks?: unknown[] publicAccess?: boolean alignmentStorage?: AlignmentStorage } +/** + * ext:opencase keys the former canvas view wrote. Nothing reads them any more, so a + * save leaves them out: the document's and items' ext:opencase are rebuilt from + * editor state, and these are removed from an association's. + */ +const RETIRED_CANVAS_KEYS = ['layout', 'edgeType', 'linkedFrameworks', 'remoteItemLinks', 'originHandle', 'destinationHandle'] as const + +/** An association's extensions without the retired canvas keys in its ext:opencase. */ +function withoutRetiredCanvasKeys(extensions: CaseExtensions | undefined): CaseExtensions | undefined { + const opencase = extensions?.[OPENCASE_EXT_KEY] + if (!opencase || typeof opencase !== 'object') return extensions + const kept = { ...(opencase as Record) } + if (!RETIRED_CANVAS_KEYS.some((k) => k in kept)) return extensions + for (const k of RETIRED_CANVAS_KEYS) delete kept[k] + const { [OPENCASE_EXT_KEY]: _opencase, ...rest } = extensions! + const result: CaseExtensions = Object.keys(kept).length > 0 ? { ...rest, [OPENCASE_EXT_KEY]: kept } : rest + return Object.keys(result).length > 0 ? result : undefined +} + /** * Merge OpenCASE extension data into existing extensions object. */ @@ -112,7 +123,7 @@ function mergeOpencaseExtension( const extensions = { ...base } // Only add if there's data to store - if (opencaseData.layout || opencaseData.notes || opencaseData.originHandle || opencaseData.destinationHandle || opencaseData.edgeType || opencaseData.colorBand || opencaseData.linkedFrameworks || opencaseData.remoteItemLinks || opencaseData.publicAccess || opencaseData.alignmentStorage) { + if (opencaseData.colorBand || opencaseData.publicAccess || opencaseData.alignmentStorage) { const existing = (extensions[OPENCASE_EXT_KEY] as OpencaseExtension | undefined) ?? {} extensions[OPENCASE_EXT_KEY] = { ...existing, @@ -128,9 +139,7 @@ function mergeOpencaseExtension( */ function frameworkToCfDocument( framework: Framework, - caseVersion: CaseVersion, - layout?: NodeLayout, - options?: { edgeType?: string; linkedFrameworks?: unknown[]; remoteItemLinks?: unknown[] } + caseVersion: CaseVersion ): CFDocument { const meta = framework.metadata const fwId = String(framework.id) @@ -167,12 +176,8 @@ function frameworkToCfDocument( }, // meta.extensions holds the document's non-OpenCASE extensions (never ext:opencase), // so ext:opencase is always regenerated from editor state while the rest round-trip. - extensions: (layout || options?.edgeType || options?.linkedFrameworks || options?.remoteItemLinks || meta.publicAccess === true || meta.alignmentStorage) + extensions: (meta.publicAccess === true || meta.alignmentStorage) ? mergeOpencaseExtension(meta.extensions, { - layout, - edgeType: options?.edgeType, - linkedFrameworks: options?.linkedFrameworks, - remoteItemLinks: options?.remoteItemLinks, ...(meta.publicAccess === true ? { publicAccess: true } : {}), ...(meta.alignmentStorage ? { alignmentStorage: meta.alignmentStorage } : {}), }) @@ -187,8 +192,7 @@ function frameworkToCfDocument( */ function itemToCfItem( framework: Framework, - itemId: string, - layout?: NodeLayout + itemId: string ): CFItem & { sourcedId: string } { // ItemId is a branded type, but we receive string from the caller const item = framework.items.get(itemId as Parameters[0]) @@ -211,8 +215,8 @@ function itemToCfItem( } // Keep every non-OpenCASE extension verbatim. An item's ext:opencase only holds - // layout and colorBand, both regenerated below from current editor state, so the - // loaded copy is dropped rather than letting stale values (e.g. a cleared colorBand) survive. + // colorBand (and, from the former canvas view, layout), so it is rebuilt below from + // current editor state rather than letting stale values (e.g. a cleared colorBand) survive. const { [OPENCASE_EXT_KEY]: _staleOpencaseExt, ...customExtensions } = (md.extensions as CaseExtensions | undefined) ?? {} const existingExtensions = Object.keys(customExtensions).length > 0 ? customExtensions : undefined @@ -243,8 +247,8 @@ function itemToCfItem( identifier: fwId, title: fwTitle, }, - extensions: (layout || s('colorBand')) - ? mergeOpencaseExtension(existingExtensions, { layout, colorBand: s('colorBand') }) + extensions: s('colorBand') + ? mergeOpencaseExtension(existingExtensions, { colorBand: s('colorBand') }) : existingExtensions, } @@ -289,15 +293,10 @@ function associationToCfAssociation( const originTargetType = s('originTargetType') const destinationTargetType = s('destinationTargetType') - const existingExtensions = (md.extensions as CaseExtensions | undefined) ?? undefined + const existingExtensions = withoutRetiredCanvasKeys((md.extensions as CaseExtensions | undefined) ?? undefined) const remoteExt = (existingExtensions?.[OPENCASE_EXT_KEY] as { remoteLink?: boolean; remoteItemUri?: string; remoteItemIdentifier?: string; remoteLabel?: string; localItemUri?: string } | undefined) - // Persist user-defined edge handle positions in ext:opencase - const originHandle = s('originHandle') - const destinationHandle = s('destinationHandle') - const extensions = (originHandle || destinationHandle) - ? mergeOpencaseExtension(existingExtensions, { originHandle, destinationHandle }) - : existingExtensions + const extensions = existingExtensions const isRemoteLink = remoteExt?.remoteLink === true @@ -355,18 +354,13 @@ function associationToCfAssociation( * Convert domain Framework to CASE CFPackage format. * * This is the authoritative conversion from the domain model to CASE format. - * Layout data (positions, dimensions) can be optionally included in extensions. - * + * * @param framework - The domain Framework (source of truth) * @param caseVersion - Target CASE version for serialization ('1.0' or '1.1') - * @param layout - Optional layout state to store in extensions */ export function frameworkToCfPackage(params: { framework: Framework caseVersion: CaseVersion - layout?: LayoutState - /** Edge rendering style to persist with this framework */ - edgeType?: string /** CFItemType definitions to include in CFDefinitions (from editor state) */ cfItemTypes?: CFItemType[] /** CFSubject definitions to include in CFDefinitions (from editor state) */ @@ -379,26 +373,15 @@ export function frameworkToCfPackage(params: { cfLicenses?: CFLicense[] /** Extensions on the framework's own CFDefinitions object, carried through unchanged */ definitionsExtensions?: CaseExtensions - /** Remote framework editor data from canvas */ - remoteEditorData?: { linkedFrameworks: unknown[]; remoteItemLinks: unknown[] } }): CFPackage { - const { framework, caseVersion, layout, edgeType, cfItemTypes, cfSubjects, cfConcepts, cfAssociationGroupings, cfLicenses, definitionsExtensions, remoteEditorData } = params - const fwId = String(framework.id) + const { framework, caseVersion, cfItemTypes, cfSubjects, cfConcepts, cfAssociationGroupings, cfLicenses, definitionsExtensions } = params // Build CFDocument - const documentLayout = layout?.byNodeId?.[fwId] - const document = frameworkToCfDocument(framework, caseVersion, documentLayout, { - edgeType, - linkedFrameworks: remoteEditorData?.linkedFrameworks, - remoteItemLinks: remoteEditorData?.remoteItemLinks, - }) + const document = frameworkToCfDocument(framework, caseVersion) // Build CFItems const itemIds = Array.from(framework.items.keys()).map(String) - const items: CFItem[] = itemIds.map((itemId) => { - const itemLayout = layout?.byNodeId?.[itemId] - return itemToCfItem(framework, itemId, itemLayout) - }) + const items: CFItem[] = itemIds.map((itemId) => itemToCfItem(framework, itemId)) // Build CFAssociations const assocIds = Array.from(framework.associations.keys()).map(String) @@ -847,5 +830,4 @@ export function absolutizeCaseUris(payload: T, baseUrl: string): T { export type FrameworkExportParams = { framework: Framework caseVersion: CaseVersion - layout?: LayoutState } diff --git a/apps/editor/src/domain/framework/hasFrameworkDataChanged.layoutSwitch.test.ts b/apps/editor/src/domain/framework/hasFrameworkDataChanged.layoutSwitch.test.ts deleted file mode 100644 index d4e2dea..0000000 --- a/apps/editor/src/domain/framework/hasFrameworkDataChanged.layoutSwitch.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { hasFrameworkDataChanged } from './hasFrameworkDataChanged' -import { toReactFlowGraph } from '@/ui/editor/reactflow/mapping/toReactFlow' -import { fromEditorGraph } from '@/ui/editor/reactflow/mapping/fromEditorGraph' -import { computeStarLayout } from '@/ui/editor/layout/starLayout' -import { computeHierarchyLayout } from '@/ui/editor/layout/hierarchyLayout' -import type { Framework, Item, Association } from './model/types' -import type { FrameworkId, ItemId, AssociationId } from '@/domain/shared/types' -import type { CaseEditorEdge } from '@/ui/editor/reactflow/types' - -function makeItem(id: string, statement: string): Item { - return { - id: id as unknown as ItemId, - statement, - type: 'Competency', - metadata: { CFItemType: 'Competency', caseUri: `urn:case:item:${id}` }, - } -} - -function makeFramework(): Framework { - const fwId = 'fw-1' - const itemA = makeItem('item-a', 'Item A') - const itemB = makeItem('item-b', 'Item B') - const assocA: Association = { - id: 'assoc-a' as unknown as AssociationId, - fromItemId: itemA.id, - toItemId: fwId as unknown as ItemId, - associationType: 'isChildOf', - metadata: { caseUri: 'urn:case:association:assoc-a' }, - } - const assocB: Association = { - id: 'assoc-b' as unknown as AssociationId, - fromItemId: itemB.id, - toItemId: fwId as unknown as ItemId, - associationType: 'isChildOf', - metadata: { caseUri: 'urn:case:association:assoc-b' }, - } - return { - id: fwId as unknown as FrameworkId, - metadata: { title: 'Test Framework', creator: 'Test', caseUri: `urn:case:document:${fwId}` }, - items: new Map([[itemA.id, itemA], [itemB.id, itemB]]), - associations: new Map([[assocA.id, assocA], [assocB.id, assocB]]), - status: 'Draft', - } -} - -// Mirrors editorReducer.ts's 'layout/applyHierarchy' case exactly. -function applyLayout(nodes: ReturnType['nodes'], edges: CaseEditorEdge[], result: ReturnType) { - const nextNodes = nodes.map((n) => { - const p = result.positions[n.id] - return p ? { ...n, position: { x: p.x, y: p.y } } : n - }) - const nextEdges = edges.map((e) => { - const h = result.edgeHandles[e.id] - if (!h) return e - return { ...e, sourceHandle: h.sourceHandle, targetHandle: h.targetHandle, data: { ...e.data, edgeType: h.edgeType, labelPosition: h.labelPosition } } - }) - return { nodes: nextNodes, edges: nextEdges } -} - -describe('hasFrameworkDataChanged — switching layout algorithms', () => { - it('does not register as a data (forking) change when switching from star to hierarchical layout', () => { - const framework = makeFramework() - const graph = toReactFlowGraph({ framework }) - - // Baseline captured on mount, as EditorCanvas.tsx does. - const baseline = fromEditorGraph({ graph }).framework - - // User clicks "Star layout". - const starResult = computeStarLayout(graph.nodes, graph.edges) - const afterStar = applyLayout(graph.nodes, graph.edges, starResult) - - // User then clicks "Hierarchical layout" — recomputes positions AND edge handles. - const hierarchyResult = computeHierarchyLayout(afterStar.nodes, afterStar.edges) - const afterHierarchy = applyLayout(afterStar.nodes, afterStar.edges, hierarchyResult) - - const current = fromEditorGraph({ graph: { nodes: afterHierarchy.nodes, edges: afterHierarchy.edges } }).framework - - expect(hasFrameworkDataChanged(baseline, current)).toBe(false) - }) -}) diff --git a/apps/editor/src/domain/framework/hasFrameworkDataChanged.test.ts b/apps/editor/src/domain/framework/hasFrameworkDataChanged.test.ts index 174e6db..bd48cc7 100644 --- a/apps/editor/src/domain/framework/hasFrameworkDataChanged.test.ts +++ b/apps/editor/src/domain/framework/hasFrameworkDataChanged.test.ts @@ -80,7 +80,7 @@ describe('hasFrameworkDataChanged', () => { }) it('ignores canvas-only changes stored as TOP-LEVEL metadata keys (the shape fromEditorGraph.ts actually produces)', () => { - // fromEditorGraph.ts (re-derives a Framework from the live canvas on every + // fromEditorGraph.ts (re-derives a Framework from the editor graph on every // save, and to capture the fork-detection baseline) writes colorBand/ // originHandle/destinationHandle directly on metadata, NOT nested under // an 'ext:opencase' key — e.g. switching layout algorithms (star ↔ diff --git a/apps/editor/src/domain/framework/hasFrameworkDataChanged.ts b/apps/editor/src/domain/framework/hasFrameworkDataChanged.ts index bd35ace..95910d1 100644 --- a/apps/editor/src/domain/framework/hasFrameworkDataChanged.ts +++ b/apps/editor/src/domain/framework/hasFrameworkDataChanged.ts @@ -1,22 +1,19 @@ import type { Association, Framework, Item } from '@/domain/framework/model/types' /** - * Canvas-only concerns (node position, per-node color band, edge handle - * anchors, edge render style) show up in TWO different metadata shapes - * depending on where the Framework snapshot came from: + * Editor-only presentation data (per-item color band, and node positions and + * edge handle anchors written by the former canvas view) shows up in TWO + * metadata shapes depending on where the Framework snapshot came from: * - Stored as CASE extensions: under `metadata.extensions['ext:opencase']` * (or a top-level `metadata['ext:opencase']` key from older builds). * Other keys in `metadata.extensions` are real framework data and ARE * compared — editing a custom extension is a data change. - * - Re-derived from the live canvas during an editing session - * (`fromEditorGraph.ts`, called on every save and to capture the - * fork-detection baseline): `colorBand` (items) and `originHandle`/ - * `destinationHandle` (associations) are written directly as TOP-LEVEL - * metadata keys, not nested under `ext:opencase` — e.g. switching layout - * algorithms (star ↔ hierarchical) recomputes every edge's handle - * anchors, which land here. - * Both shapes must be excluded here so neither a pure layout edit nor - * switching layout algorithms ever reads as a "framework data" change. + * - Re-derived from the editor graph (`fromEditorGraph.ts`, called on every + * save and to capture the fork-detection baseline): `colorBand` (items) is + * written as a TOP-LEVEL metadata key, as were `originHandle`/ + * `destinationHandle` (associations) before the canvas view was removed. + * Both shapes are excluded here so presentation data never reads as a + * "framework data" change. */ function stripLayoutMetadata(metadata: Record | undefined): Record { if (!metadata) return {} @@ -50,7 +47,7 @@ function sortedNormalizedEntries(map: Map, normalize: /** * True if two Framework snapshots differ in actual framework data — * metadata, item statements/types/CASE fields, hierarchy, or associations. - * Deliberately blind to canvas-only concerns (position, color band, edge + * Deliberately blind to editor-only presentation data (position, color band, edge * handle anchors), since those don't affect a mirrored framework's CASE-spec * content and shouldn't be treated as a forking change. */ diff --git a/apps/editor/src/domain/framework/inlineAlignmentEdits.ts b/apps/editor/src/domain/framework/inlineAlignmentEdits.ts index 76ae49c..7a82035 100644 --- a/apps/editor/src/domain/framework/inlineAlignmentEdits.ts +++ b/apps/editor/src/domain/framework/inlineAlignmentEdits.ts @@ -2,7 +2,7 @@ import type { Association, AssociationType, Framework } from '@/domain/framework /** * Edits to a framework's inline associations to other frameworks, made in the - * Tree View. These associations aren't canvas edges, so they never enter the + * Tree View. These associations aren't editor graph edges, so they never enter the * editor graph: the edits are kept alongside it and applied to the framework * when it's saved. * diff --git a/apps/editor/src/domain/framework/offCanvasAssociations.test.ts b/apps/editor/src/domain/framework/offCanvasAssociations.test.ts index 6a8870f..5d7fb02 100644 --- a/apps/editor/src/domain/framework/offCanvasAssociations.test.ts +++ b/apps/editor/src/domain/framework/offCanvasAssociations.test.ts @@ -42,10 +42,10 @@ describe('withOffCanvasAssociations', () => { expect(withOffCanvasAssociations(loaded, saved).associations.has(external.id)).toBe(false) }) - it('leaves editor-authored remote links to remoteEditorData', () => { + it('carries over links the former canvas view drew to a CASE Global framework', () => { const remote = assoc('remote-1', 'item-1', 'remote-item', { extensions: { 'ext:opencase': { remoteLink: true } } }) const saved = framework([item('item-1')], []) - expect(withOffCanvasAssociations(framework([item('item-1')], [remote]), saved).associations.has(remote.id)).toBe(false) + expect(withOffCanvasAssociations(framework([item('item-1')], [remote]), saved).associations.has(remote.id)).toBe(true) }) it('returns the saved framework untouched when there is nothing to carry over', () => { diff --git a/apps/editor/src/domain/framework/offCanvasAssociations.ts b/apps/editor/src/domain/framework/offCanvasAssociations.ts index eb34160..65b704c 100644 --- a/apps/editor/src/domain/framework/offCanvasAssociations.ts +++ b/apps/editor/src/domain/framework/offCanvasAssociations.ts @@ -4,14 +4,14 @@ import type { ItemId } from '@/domain/shared/types' /** * The editor graph only has nodes for this framework's own items and its * CFDocument, so an association whose origin or destination is anything else - * — a CASE 1.1 non-CASE target (`targetType: 'ext:…'`, GitHub #49) or an item - * in another framework — has no edge on the canvas and never comes back out of - * `fromEditorGraph`. Saving would silently delete it. + * — a CASE 1.1 non-CASE target (`targetType: 'ext:…'`, GitHub #49), an item + * in another framework, or a link the former canvas view drew to a CASE Global + * framework (`ext:opencase.remoteLink`) — has no edge in the graph and never + * comes back out of `fromEditorGraph`. Saving would silently delete it. * * This carries such associations over from the framework as loaded into the * framework rebuilt from the graph, unless the local item they hang off was - * deleted in this session. Editor-authored remote links are excluded: they - * already round-trip through `remoteEditorData`. + * deleted in this session. */ export function withOffCanvasAssociations(loaded: Framework, saved: Framework): Framework { const isLoadedNode = (id: ItemId) => loaded.items.has(id) || (id as unknown as string) === (loaded.id as unknown as string) @@ -20,7 +20,6 @@ export function withOffCanvasAssociations(loaded: Framework, saved: Framework): let associations: Map | undefined for (const a of loaded.associations.values()) { if (saved.associations.has(a.id)) continue - if (isRemoteLink(a)) continue const endpoints = [a.fromItemId, a.toItemId] // Both ends on the canvas: if it's missing from `saved`, the user deleted it. if (endpoints.every(isLoadedNode)) continue @@ -31,8 +30,3 @@ export function withOffCanvasAssociations(loaded: Framework, saved: Framework): return associations ? { ...saved, associations } : saved } - -function isRemoteLink(a: Association): boolean { - const ext = (a.metadata?.extensions as Record | undefined)?.['ext:opencase'] - return (ext as { remoteLink?: unknown } | undefined)?.remoteLink === true -} diff --git a/apps/editor/src/infrastructure/caseApi/CaseApiClient.ts b/apps/editor/src/infrastructure/caseApi/CaseApiClient.ts index abdefe7..808811c 100644 --- a/apps/editor/src/infrastructure/caseApi/CaseApiClient.ts +++ b/apps/editor/src/infrastructure/caseApi/CaseApiClient.ts @@ -22,6 +22,10 @@ export type OpenCaseListExtensions = { publicAccess?: boolean /** Server-level archive flag — independent of CASE adoptionStatus. */ archived?: boolean + /** A read-only copy cached from a publisher, not editable on this server. */ + readOnly?: boolean + /** For a read-only copy of a CASE Global framework: its coalition framework id. */ + cgeFrameworkId?: string } export type AlignmentFrameworkSummary = { @@ -67,26 +71,6 @@ export type CfDocumentSummary = { export class CaseApiClient { constructor(private readonly _http: HttpClient) {} - async lookupTenantByEmail(params: { email: string }): Promise<{ tenantId?: string } | null> { - const email = params.email.trim() - if (!email) return null - const res = (await this._http.get(`/public/tenant-lookup?email=${encodeURIComponent(email)}`)) as unknown - if (!res || typeof res !== 'object') return null - const any = res as { tenantId?: unknown } - if (typeof any.tenantId === 'string' && any.tenantId.trim()) return { tenantId: any.tenantId.trim() } - return {} - } - - async lookupTenantByOrgId(params: { orgId: string }): Promise<{ tenantId?: string } | null> { - const orgId = params.orgId.trim() - if (!orgId) return null - const res = (await this._http.get(`/public/tenant-lookup?orgId=${encodeURIComponent(orgId)}`)) as unknown - if (!res || typeof res !== 'object') return null - const any = res as { tenantId?: unknown } - if (typeof any.tenantId === 'string' && any.tenantId.trim()) return { tenantId: any.tenantId.trim() } - return {} - } - /** * First login: assign the default author role to a user who has never had a role. * Idempotent. Caller should refresh its access token if status is `assigned`. @@ -703,7 +687,6 @@ export class CaseApiClient { refresh?: boolean linkedFromDocId?: string caseVersion?: '1.0' | '1.1' - skipPublisherAuth?: boolean }): Promise { const url = `/management/tenants/${encodeURIComponent(params.tenantId)}/cge/import` const res = (await this._http.post(url, { @@ -715,7 +698,6 @@ export class CaseApiClient { refresh: params.refresh ?? false, linkedFromDocId: params.linkedFromDocId, caseVersion: params.caseVersion ?? '1.1', - skipPublisherAuth: params.skipPublisherAuth ?? false, })) as unknown if (res && typeof res === 'object') { const obj = res as CgeImportResult @@ -739,12 +721,9 @@ export class CaseApiClient { async refreshCgeCache(params: { tenantId: string frameworkId: string - skipPublisherAuth?: boolean }): Promise { const url = `/management/tenants/${encodeURIComponent(params.tenantId)}/cge/frameworks/${encodeURIComponent(params.frameworkId)}/refresh` - const res = (await this._http.post(url, { - skipPublisherAuth: params.skipPublisherAuth ?? false, - })) as unknown + const res = (await this._http.post(url, {})) as unknown if (res && typeof res === 'object') { const obj = res as CgeImportResult return { diff --git a/apps/editor/src/styles/index.css b/apps/editor/src/styles/index.css index ed107a1..12ab062 100644 --- a/apps/editor/src/styles/index.css +++ b/apps/editor/src/styles/index.css @@ -1,11 +1,6 @@ @import "tailwindcss"; @import "tw-animate-css"; -/* React Flow note for Tailwind v4: import React Flow styles in global CSS (not JS) */ -@layer base { - @import "@xyflow/react/dist/style.css"; -} - :root { /* ── 1EdTech brand palette ─────────────────────────────── */ --brand-navy: #000072; @@ -151,145 +146,3 @@ } } -/* React Flow edge styles for better selection feedback */ -.react-flow__edge { - cursor: pointer; -} - -.react-flow__edge-path { - stroke-width: 2; - transition: stroke 0.15s ease, stroke-width 0.15s ease, filter 0.15s ease; -} - -/* Edge hover state */ -.react-flow__edge:hover .react-flow__edge-path { - stroke: #a78bfa; /* violet-400 */ - stroke-width: 2.5; -} - -/* Edge selected state - prominent purple */ -.react-flow__edge.selected .react-flow__edge-path { - stroke: #7c3aed; /* violet-600 */ - stroke-width: 3; - filter: drop-shadow(0 0 4px rgba(124, 58, 237, 0.5)); -} - -/* Edge label styling */ -.react-flow__edge-textwrapper { - pointer-events: none; -} - -.react-flow__edge-text { - fill: #94a3b8; /* slate-400 */ - font-size: 11px; - font-weight: 500; -} - -/* Selected edge label - purple */ -.react-flow__edge.selected .react-flow__edge-text { - fill: #7c3aed; /* violet-600 */ - font-weight: 600; -} - -/* Hover edge label */ -.react-flow__edge:hover .react-flow__edge-text { - fill: #64748b; /* slate-500 */ -} - -/* Make the edge interaction area larger for easier clicking */ -.react-flow__edge-interaction { - stroke-width: 20; - stroke: transparent; - fill: none; - cursor: pointer; -} - -/* Arrow markers - match edge color when selected */ -.react-flow__edge.selected marker path { - fill: #7c3aed; -} - -/* ============================================ - Edge Reconnection Handles - ============================================ */ - -/* Container for reconnection handles */ -.react-flow__edgeupdater { - cursor: move; - pointer-events: all; -} - -.react-flow__edgeupdater-source, -.react-flow__edgeupdater-target { - pointer-events: all; -} - -/* Default reconnection handle circles - hidden until edge is selected/hovered */ -.react-flow__edgeupdater circle { - fill: #f8fafc; - stroke: #cbd5e1; - stroke-width: 2; - r: 6; - cursor: move; - opacity: 0; - transition: opacity 0.15s ease, r 0.15s ease, fill 0.15s ease; -} - -/* Show handles on edge hover */ -.react-flow__edge:hover .react-flow__edgeupdater circle { - opacity: 1; - fill: #f1f5f9; - stroke: #a78bfa; - r: 8; -} - -/* Prominent handles when edge is SELECTED - always visible with pulse animation */ -.react-flow__edge.selected .react-flow__edgeupdater circle { - opacity: 1; - fill: #7c3aed; /* violet-600 - filled purple */ - stroke: #5b21b6; /* violet-700 */ - stroke-width: 3; - r: 10; - animation: handle-pulse 1.5s ease-in-out infinite; -} - -/* Pulsing animation for draggable handles */ -@keyframes handle-pulse { - 0%, 100% { - r: 10; - stroke-width: 3; - filter: drop-shadow(0 0 0 transparent); - } - 50% { - r: 12; - stroke-width: 4; - filter: drop-shadow(0 0 8px rgba(124, 58, 237, 0.6)); - } -} - -/* Handle hover state */ -.react-flow__edgeupdater circle:hover { - fill: #8b5cf6 !important; /* violet-500 */ - stroke: #6d28d9 !important; /* violet-700 */ - r: 12 !important; - cursor: grab; -} - -/* Handle active/dragging state */ -.react-flow__edgeupdater circle:active { - cursor: grabbing; - fill: #6d28d9 !important; - r: 14 !important; -} - -/* Shift-select mode: crosshair on canvas, pointer on nodes */ -.shift-select-mode .react-flow__pane { - cursor: crosshair !important; -} -.shift-select-mode .react-flow__node { - cursor: pointer !important; -} -.shift-select-mode .react-flow__edge { - cursor: pointer !important; -} - diff --git a/apps/editor/src/ui/auth/LoginScreen.tsx b/apps/editor/src/ui/auth/LoginScreen.tsx index 3166891..6ab7062 100644 --- a/apps/editor/src/ui/auth/LoginScreen.tsx +++ b/apps/editor/src/ui/auth/LoginScreen.tsx @@ -1,167 +1,30 @@ -import { useCallback, useMemo, useState } from 'react' +import { useCallback, useState } from 'react' import { useAuth } from '@/app/providers/AuthProvider' -import { getAppConfig } from '@/app/config' -import { CaseApiClient } from '@/infrastructure/caseApi/CaseApiClient' -import { createFetchHttpClient } from '@/infrastructure/caseApi/http' import { Button } from '@/ui/shared/components/ui/button' export default function LoginScreen() { - const { status, error, setTenantId, signIn } = useAuth() - const cfg = getAppConfig() - const publicApi = useMemo(() => new CaseApiClient(createFetchHttpClient(cfg.opencaseBaseUrl)), [cfg.opencaseBaseUrl]) + const { status, error, signIn } = useAuth() + const [signInError, setSignInError] = useState(null) - const [email, setEmail] = useState('') - const [orgId, setOrgId] = useState('') - const [mode, setMode] = useState<'email' | 'org'>('org') - const [uiState, setUiState] = useState<'idle' | 'loading'>('idle') - const [hint, setHint] = useState(null) - - // Single-tenant mode: skip tenant lookup, show a direct sign-in button - const [autoSignInError, setAutoSignInError] = useState(null) - const singleTenantSignIn = useCallback(() => { - if (!cfg.defaultTenantId) return - setAutoSignInError(null) - setTenantId(cfg.defaultTenantId) - signIn(cfg.defaultTenantId).catch((err: unknown) => { + const handleSignIn = useCallback(() => { + setSignInError(null) + signIn().catch((err: unknown) => { console.error('[LoginScreen] sign-in failed:', err) - setAutoSignInError(err instanceof Error ? err.message : String(err)) + setSignInError(err instanceof Error ? err.message : String(err)) }) - }, [cfg.defaultTenantId, setTenantId, signIn]) - - const continueWithEmail = useCallback(async () => { - const trimmed = email.trim() - if (!trimmed) return - setUiState('loading') - setHint(null) - try { - const res = await publicApi.lookupTenantByEmail({ email: trimmed }) - const resolvedTenantId = res?.tenantId - if (resolvedTenantId) { - setTenantId(resolvedTenantId) - await signIn(resolvedTenantId, { loginHint: trimmed }) - return - } - - // Anti-enumeration UX: don't reveal whether this email exists / is mapped. - setHint("If your account is recognized, you'll be redirected to sign in.") - } catch { - setHint("If your account is recognized, you'll be redirected to sign in.") - } finally { - setUiState('idle') - } - }, [email, publicApi, setTenantId, signIn]) - - const continueWithOrgId = useCallback(async () => { - const trimmed = orgId.trim() - if (!trimmed) return - setUiState('loading') - setHint(null) - try { - const res = await publicApi.lookupTenantByOrgId({ orgId: trimmed }) - const resolvedTenantId = res?.tenantId - if (resolvedTenantId) { - setTenantId(resolvedTenantId) - await signIn(resolvedTenantId) - return - } - setHint("If your organization is recognized, you'll be redirected to sign in.") - } catch { - setHint("If your organization is recognized, you'll be redirected to sign in.") - } finally { - setUiState('idle') - } - }, [orgId, publicApi, setTenantId, signIn]) - - // Single-tenant mode: show a direct sign-in button (no email/tenant lookup) - if (cfg.defaultTenantId) { - return ( -
-
-
-
Welcome to OpenCASE
-
Sign in to continue.
- {autoSignInError ?
{autoSignInError}
: null} - {status === 'error' && error ?
{error}
: null} -
- -
-
-
-
- ) - } + }, [signIn]) return (
-
Sign in
-
- {mode === 'org' - ? 'Enter your organization ID to continue to your organization’s sign-in.' - : 'Enter your email to continue to your organization’s sign-in.'} -
- -
- - -
- - {mode === 'org' ? ( -
- - setOrgId(e.target.value)} - placeholder="your-org-id" - autoComplete="organization" - onKeyDown={(e) => { - if (e.key === 'Enter') void continueWithOrgId() - }} - /> -
- ) : ( -
- - setEmail(e.target.value)} - placeholder="you@example.org" - autoComplete="email" - inputMode="email" - onKeyDown={(e) => { - if (e.key === 'Enter') void continueWithEmail() - }} - /> -
- )} - - {hint ?
{hint}
: null} +
Welcome to OpenCASE
+
Sign in to continue.
+ {signInError ?
{signInError}
: null} {status === 'error' && error ?
{error}
: null} -
-
diff --git a/apps/editor/src/ui/editor/EditorCanvas.tsx b/apps/editor/src/ui/editor/EditorCanvas.tsx deleted file mode 100644 index 3940bc0..0000000 --- a/apps/editor/src/ui/editor/EditorCanvas.tsx +++ /dev/null @@ -1,2082 +0,0 @@ -import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent } from 'react' -import type { ReactFlowInstance, Connection, Edge, NodeChange, EdgeChange } from '@xyflow/react' -import type { OnBeforeDelete } from '@xyflow/react' -import type { OnSelectionChangeFunc } from '@xyflow/react' -import { Background, BackgroundVariant, ConnectionMode, Controls, MiniMap, ReactFlow, SelectionMode, useUpdateNodeInternals } from '@xyflow/react' -import { nodeTypes } from '@/ui/editor/reactflow/nodeTypes' -import { edgeTypes } from '@/ui/editor/reactflow/edgeTypes' -import CanvasHeader from '@/ui/editor/components/CanvasHeader' -import NodePropertiesPanel from '@/ui/editor/components/NodePropertiesPanel' -import EdgePropertiesPanel from '@/ui/editor/components/EdgePropertiesPanel' -import MultiSelectionPanel from '@/ui/editor/components/MultiSelectionPanel' -import AddItemDialog from '@/ui/editor/components/AddItemDialog' -import ConfirmActionDialog from '@/ui/editor/components/ConfirmActionDialog' -import ConfirmLeaveDialog from '@/ui/editor/components/ConfirmLeaveDialog' -import SettingsModal from '@/ui/editor/components/SettingsModal' -import FloatingAddButton from '@/ui/editor/components/FloatingAddButton' -import CgeFrameworkSearchPanel from '@/ui/editor/components/CgeFrameworkSearchPanel' -import RemoteFrameworkItemsPanel from '@/ui/editor/components/RemoteFrameworkItemsPanel' -import AssociationTypePickerDialog from '@/ui/editor/components/AssociationTypePickerDialog' -import ViewCFPackageDialog from '@/ui/editor/components/ViewCFPackageDialog' -import TreePanelView from '@/ui/editor/treePanel/TreePanelView' -import { CANVAS_VIEW_ENABLED } from '@/ui/editor/featureFlags' -import { CaseApiClient } from '@/infrastructure/caseApi/CaseApiClient' -import { createFetchHttpClient, formatApiErrorMessage } from '@/infrastructure/caseApi/http' -import { getAppConfig } from '@/app/config' -import type { CgeFrameworkSummary } from '@/infrastructure/caseApi/cgeTypes' -import { REMOTE_ITEM_MIME, parseRemoteItemDragPayload, type RemoteItemLink } from '@/ui/editor/remoteFramework/remoteFrameworkTypes' -import { - buildRemoteLinkEdges, - remoteLinkIdFromEdgeId, -} from '@/ui/editor/remoteFramework/buildRemoteLinkGraph' -import { useEditor } from '@/ui/editor/state/EditorContext' -import { isFrameworkNode, getNodeSize } from '@/ui/editor/state/helpers/nodeGeometry' -import type { CaseEditorNodeType, CaseEditorEdge } from '@/ui/editor/reactflow/types' -import type { CFAssociationGrouping, CFDocument, CFItem, CFPackage, CaseExtensions } from '@/domain/case/types' -import type { HomeFramework } from '@/ui/home/frameworkStore' -import { useAuth } from '@/app/providers/AuthProvider' -import { fromEditorGraph } from '@/ui/editor/reactflow/mapping/fromEditorGraph' -import { frameworkToCfPackage, toOpenCaseFormat } from '@/application/framework/mappers/case/toCasePackage' -import type { Framework } from '@/domain/framework/model/types' -import { hasFrameworkDataChanged } from '@/domain/framework/hasFrameworkDataChanged' -import { withOffCanvasAssociations } from '@/domain/framework/offCanvasAssociations' -import { alignmentMoveCount, type AlignmentStoragePlan } from '@/application/framework/services/AlignmentStorage' -import type { HostedDocumentRef } from '@/domain/framework/externalAlignments' -import { applyInlineAlignmentEdits } from '@/domain/framework/inlineAlignmentEdits' - -// ── Stable ReactFlow config (module scope — never recreated) ────────────── -// -// A fresh object/array/function literal passed as a prop to on -// every EditorCanvas render defeats any attempt to keep it from doing work -// while hidden behind Tree View: CPU profiling showed React Flow's internal -// store (setState/shallow-equality selectors) re-syncing on every keystroke -// even when node/edge DATA was unchanged, because other props (these) were -// still fresh references each render. -const REACT_FLOW_DEFAULT_EDGE_OPTIONS = { - interactionWidth: 20, - style: { strokeWidth: 1.5, stroke: '#94a3b8' }, - focusable: true, - reconnectable: true, -} -const REACT_FLOW_PRO_OPTIONS = { hideAttribution: true } -const REACT_FLOW_BACKGROUND_STYLE = { backgroundColor: '#f0f0f2' } -const minimapNodeColor = (node: CaseEditorNodeType) => (node.selected ? '#8b5cf6' : '#e2e8f0') // violet-500 if selected, slate-200 otherwise -const NO_EDGES: CaseEditorEdge[] = [] -const NO_GROUPINGS: CFAssociationGrouping[] = [] -const minimapNodeStrokeColor = (node: CaseEditorNodeType) => (node.selected ? '#7c3aed' : '#cbd5e1') // violet-600 if selected, slate-300 otherwise - -type ReactFlowGraphProps = { - wrapRef: React.RefObject - visible: boolean - nodes: CaseEditorNodeType[] - edges: CaseEditorEdge[] - /** Cross-framework links — drive handle-position resyncs via RemoteLinkInternalsSync */ - remoteLinks: RemoteItemLink[] - onNodesChange: (changes: NodeChange[]) => void - onEdgesChange: (changes: EdgeChange[]) => void - onConnect: (connection: Connection) => void - onNodeClick: (event: ReactMouseEvent, node: CaseEditorNodeType) => void - onNodeDoubleClick: (event: ReactMouseEvent, node: CaseEditorNodeType) => void - onNodeDragStart: (event: ReactMouseEvent, node: CaseEditorNodeType) => void - onNodeDragStop: () => void - onEdgeClick: (event: ReactMouseEvent, edge: Edge) => void - onPaneClick: (event: ReactMouseEvent) => void - isValidConnection: (connection: Connection) => boolean - onSelectionChange: OnSelectionChangeFunc - onBeforeDelete: OnBeforeDelete - nodesDraggable: boolean - onReconnectStart: () => void - onReconnect: (oldEdge: Edge, newConnection: Connection) => void - onReconnectEnd: (_: unknown, edge: Edge) => void - onInit: (instance: ReactFlowInstance) => void - onPointerDownCapture: (event: ReactPointerEvent) => void - onDragOver: (event: React.DragEvent) => void - onDrop: (event: React.DragEvent) => void -} - -/** - * Isolated in its own `React.memo`'d component (rather than inline JSX in - * EditorCanvas) so that when every prop here is referentially stable — - * which is the case while Tree View is active, since `nodes`/`edges` are - * frozen and every handler is `useCallback`'d — React skips calling this - * component's render function entirely, instead of merely receiving - * unchanged props. That's what actually stops React Flow's internal effects - * from re-running on every keystroke while the canvas is invisible. - */ -const ReactFlowGraph = memo(function ReactFlowGraph({ - wrapRef, - visible, - nodes, - edges, - remoteLinks, - onNodesChange, - onEdgesChange, - onConnect, - onNodeClick, - onNodeDoubleClick, - onNodeDragStart, - onNodeDragStop, - onEdgeClick, - onPaneClick, - isValidConnection, - onSelectionChange, - onBeforeDelete, - nodesDraggable, - onReconnectStart, - onReconnect, - onReconnectEnd, - onInit, - onPointerDownCapture, - onDragOver, - onDrop, -}: ReactFlowGraphProps) { - return ( -
- - nodes={nodes} - edges={edges} - onNodesChange={onNodesChange} - onEdgesChange={onEdgesChange} - onConnect={onConnect} - onNodeClick={onNodeClick} - onNodeDoubleClick={onNodeDoubleClick} - onNodeDragStart={onNodeDragStart} - onNodeDragStop={onNodeDragStop} - onEdgeClick={onEdgeClick} - onPaneClick={onPaneClick} - isValidConnection={isValidConnection} - onSelectionChange={onSelectionChange} - onBeforeDelete={onBeforeDelete} - selectionMode={SelectionMode.Full} - multiSelectionKeyCode="Meta" - selectionOnDrag={false} - selectionKeyCode="Shift" - panOnDrag - nodesDraggable={nodesDraggable} - nodeTypes={nodeTypes} - edgeTypes={edgeTypes} - edgesFocusable - elevateEdgesOnSelect - edgesReconnectable - onReconnectStart={onReconnectStart} - onReconnect={onReconnect} - onReconnectEnd={onReconnectEnd} - connectOnClick={true} - connectionMode={ConnectionMode.Loose} - onlyRenderVisibleElements - defaultEdgeOptions={REACT_FLOW_DEFAULT_EDGE_OPTIONS} - proOptions={REACT_FLOW_PRO_OPTIONS} - onInit={onInit} - > - - - - - -
- ) -}) - -type MirrorStatus = { isModifiedFromSource?: boolean; sourcePackageURI?: string } - -type EditorCanvasProps = { - onBack?: () => void - onSaveToServer?: (cfPackage: ReturnType, framework: Framework, plan?: AlignmentStoragePlan) => Promise - /** Works out which associations a save will move for the framework's alignment storage setting, without saving */ - onPlanAlignmentStorage?: (cfPackage: ReturnType, framework: Framework) => Promise - /** Archive the current framework on the server and navigate home */ - onArchiveFramework?: () => Promise - /** Fetch the published CFPackage from the server (returns CASE JSON with absolute URIs) */ - onFetchCfPackage?: () => Promise - /** All locally-available frameworks — used to populate the crosswalk target selector in tree view */ - availableFrameworks?: HomeFramework[] - /** Server-side framework summaries not yet loaded locally — shown in crosswalk target selector for auto-load */ - serverFrameworks?: Array<{ id: string; title: string }> - /** Load a framework from the server into the local session (called when a server-only crosswalk target is selected) */ - onLoadTargetFramework?: (id: string) => Promise - /** Save a serialized alignment CFPackage to the server */ - onSaveAlignments?: (cfPackage: unknown) => Promise - /** Load existing alignment associations for a target framework pairing */ - onLoadAlignmentsForTarget?: (targetId: string) => Promise<{ - docId: string - associations: Array<{ id: string; fromItemId: string; toItemId: string; toFrameworkId: string; associationType: string; originUri: string; destinationUri: string }> - }> - /** Discover all frameworks that already have saved alignment docs with the given source framework */ - onDiscoverAlignedTargets?: (sourceId: string) => Promise> - /** Resolve item identifiers to the hosted frameworks that hold them — used by the tree view to place inline external alignments */ - onLookupItemDocuments?: (identifiers: string[]) => Promise> - /** Mirror/fork status of the open framework, if it was ever imported */ - mirrorStatus?: MirrorStatus - /** Read-only cached remote framework (CGE cache) */ - readOnly?: boolean - /** Extensions on the open framework's own CFDefinitions object — the editor can't author them, so they're carried through on save */ - cfDefinitionsExtensions?: CaseExtensions - /** The framework as loaded — its associations to nodes outside this framework have no canvas edge, so they're carried through on save */ - loadedFramework?: Framework - /** Changes whenever a save moved associations between this framework and its alignment frameworks */ - alignmentsRevision?: number -} - -function RemoteLinkInternalsSync({ - remoteLinks, - nodes, -}: { - remoteLinks: RemoteItemLink[] - nodes: CaseEditorNodeType[] -}) { - const updateNodeInternals = useUpdateNodeInternals() - - useLayoutEffect(() => { - const frameworkRefIds = new Set(remoteLinks.map((l) => l.remoteFrameworkRefId)) - const frameworkNodeIds = nodes - .filter((n) => n.type === 'externalFrameworkNode' && frameworkRefIds.has((n.data as { refId?: string }).refId ?? '')) - .map((n) => n.id) - - const raf = requestAnimationFrame(() => { - for (const link of remoteLinks) { - updateNodeInternals(link.localItemId) - } - for (const nodeId of frameworkNodeIds) { - updateNodeInternals(nodeId) - } - }) - return () => cancelAnimationFrame(raf) - }, [remoteLinks, nodes, updateNodeInternals]) - - return null -} - -/** The fork warning's sentence about associations a save will move. */ -function describeAlignmentMove(plan: AlignmentStoragePlan, count: number): string { - const associations = count === 1 ? '1 association' : `${count} associations` - return plan.kind === 'toInline' - ? `${associations} to frameworks on this server will move from alignment frameworks into this framework.` - : `${associations} to frameworks on this server will move from this framework into alignment frameworks.` -} - -export default function EditorCanvas({ onBack, onSaveToServer, onPlanAlignmentStorage, onArchiveFramework, onFetchCfPackage, availableFrameworks, serverFrameworks, onLoadTargetFramework, onSaveAlignments, onLoadAlignmentsForTarget, onDiscoverAlignedTargets, onLookupItemDocuments, mirrorStatus, readOnly, cfDefinitionsExtensions, loadedFramework, alignmentsRevision }: Readonly) { - const { status: authStatus, userName, tenantId, signOut, changePassword } = useAuth() - const { - nodes, - nodesWithCallbacks, - edges: editorEdges, - onNodesChange, - onEdgesChange, - onConnect, - selectedNode, - selectedEdge, - selectedNodeIds, - selectedEdgeIds, - frameworkInfo, - clearSelection, - updateNodeData, - updateEdgeData, - flipEdge, - reconnectEdge: reconnectEdgeAction, - layoutVersion, - cfItemTypes, - ensureCfItemType, - cfSubjects, - ensureCfSubject, - cfConcepts, - ensureCfConcept, - cfLicenses, - cfAssociationGroupings, - ensureCfAssociationGrouping, - activeGroupingFilter, - setActiveGroupingFilter, - addItemDialog, - setAddItemDraft, - cancelAddItem, - confirmAddItem, - deleteElements, - isDirty, - clearDirty, - caseVersion, - settings, - updateSettings, - addDetachedItem, - addExternalFramework, - remoteLinks, - inlineAlignmentEdits, - clearInlineAlignmentEdits, - addRemoteLink, - removeRemoteLink, - updateRemoteLinkType, - removeRemoteFramework, - openCgeSearchPanel, - openRemoteItemsPanel, - closeSidePanel, - openExternalFrameworkSettings, - sidePanelMode, - setSidePanelMode, - activeRemoteFrameworkNodeId, - setActiveRemoteFrameworkNodeId, - applyHierarchyLayout, - applyStarLayout, - } = useEditor() - - const cfg = getAppConfig() - const { getAccessToken } = useAuth() - const api = useMemo( - () => new CaseApiClient(createFetchHttpClient(cfg.opencaseBaseUrl, { getAccessToken })), - [cfg.opencaseBaseUrl, getAccessToken], - ) - - const reactFlowWrapRef = useRef(null) - const reactFlowRef = useRef | null>(null) - const [rfReady, setRfReady] = useState(false) - const didInitialViewportRef = useRef(false) - const prevLayoutVersionRef = useRef(null) - const [leaveOpen, setLeaveOpen] = useState(false) - const [settingsOpen, setSettingsOpen] = useState(false) - const [pendingRemoteDrop, setPendingRemoteDrop] = useState<{ localItemId: string; payload: ReturnType } | null>(null) - const [remoteFrameworkRefreshing, setRemoteFrameworkRefreshing] = useState(false) - const [cfPackageDialogOpen, setCfPackageDialogOpen] = useState(false) - const [generatedCfPackage, setGeneratedCfPackage] = useState(null) - const [viewCaseLoading, setViewCaseLoading] = useState(false) - const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'success' | 'error'>('idle') - const [saveError, setSaveError] = useState(null) - const [selectedRemoteEdgeIds, setSelectedRemoteEdgeIds] = useState([]) - - const [activeView, setActiveView] = useState<'canvas' | 'tree'>('tree') - - // The edge derivations below exist only to feed . Skip them - // entirely while the canvas view is disabled (see featureFlags.ts) so they - // don't add per-keystroke cost to Tree View on large frameworks. - const remoteLinkEdges = useMemo( - () => (CANVAS_VIEW_ENABLED ? buildRemoteLinkEdges(nodesWithCallbacks, remoteLinks, selectedRemoteEdgeIds) : NO_EDGES), - [nodesWithCallbacks, remoteLinks, selectedRemoteEdgeIds], - ) - - const allEditorEdges = useMemo( - () => (CANVAS_VIEW_ENABLED ? [...editorEdges, ...remoteLinkEdges] : NO_EDGES), - [editorEdges, remoteLinkEdges], - ) - const [forkWarningOpen, setForkWarningOpen] = useState(false) - - // Baseline Framework snapshot for fork-detection — captured once when this - // session's graph first loads, and refreshed after every successful save. - // Only ever needs to change mid-session for a fork itself, and once forked - // mirrorStatus.isModifiedFromSource flips true, permanently disabling the - // gate below — so a single per-mount baseline is sufficient. - const baselineFrameworkRef = useRef(null) - if (baselineFrameworkRef.current === null) { - const baseline = fromEditorGraph({ graph: { nodes, edges: editorEdges } }).framework - baselineFrameworkRef.current = loadedFramework ? withOffCanvasAssociations(loadedFramework, baseline) : baseline - } - const pendingSaveRef = useRef<{ openCasePackage: ReturnType; framework: Framework; plan?: AlignmentStoragePlan } | null>(null) - // What the fork warning says about associations the save will move, if any. - const [forkWarningMove, setForkWarningMove] = useState(null) - - // Available licenses from context (loaded via App.tsx definitions pipeline) - const availableLicenses = cfLicenses - - // Track Shift key for selection cursor styling only (DOM class, no React state). - const shiftHeldRef = useRef(false) - const [shiftHeldForInteractions, setShiftHeldForInteractions] = useState(false) - useEffect(() => { - const el = reactFlowWrapRef.current - if (!el) return - const onDown = (e: KeyboardEvent) => { - if (e.key === 'Shift') { - shiftHeldRef.current = true - setShiftHeldForInteractions(true) - el.classList.add('shift-select-mode') - } - } - const onUp = (e: KeyboardEvent) => { - if (e.key === 'Shift') { - shiftHeldRef.current = false - setShiftHeldForInteractions(false) - el.classList.remove('shift-select-mode') - } - } - const onBlur = () => { - shiftHeldRef.current = false - setShiftHeldForInteractions(false) - el.classList.remove('shift-select-mode') - } - globalThis.addEventListener('keydown', onDown) - globalThis.addEventListener('keyup', onUp) - globalThis.addEventListener('blur', onBlur) - return () => { - globalThis.removeEventListener('keydown', onDown) - globalThis.removeEventListener('keyup', onUp) - globalThis.removeEventListener('blur', onBlur) - } - }, []) - - // Track the edge being reconnected - const edgeReconnectSuccessful = useRef(true) - - // ── Refs for save/export (keeps callbacks stable, avoids re-renders) ── - const graphRef = useRef({ nodes, edges: editorEdges, remoteLinks, inlineAlignmentEdits }) - graphRef.current = { nodes, edges: editorEdges, remoteLinks, inlineAlignmentEdits } - const saveCtxRef = useRef({ caseVersion, edgeType: settings.edgeType, cfItemTypes, cfSubjects, cfConcepts, cfLicenses, cfAssociationGroupings, cfDefinitionsExtensions, loadedFramework }) - saveCtxRef.current = { caseVersion, edgeType: settings.edgeType, cfItemTypes, cfSubjects, cfConcepts, cfLicenses, cfAssociationGroupings, cfDefinitionsExtensions, loadedFramework } - - // Open the CFPackage viewer. Every framework open in the editor has been saved to the - // server, so the server copy (absolute URIs, no OpenCASE extensions) is the export. - const handleViewCFPackage = useCallback(async () => { - if (!onFetchCfPackage) return - setCfPackageDialogOpen(true) - setViewCaseLoading(true) - try { - const pkg = await onFetchCfPackage() - setGeneratedCfPackage(pkg) - } finally { - setViewCaseLoading(false) - } - }, [onFetchCfPackage]) - - // Actually perform the save (network call). Split out from `handleSave` so - // the fork-warning dialog can defer this until the user confirms. - const doSave = useCallback(async (openCasePackage: ReturnType, framework: Framework, plan?: AlignmentStoragePlan) => { - if (onSaveToServer) { - setSaveStatus('saving') - setSaveError(null) - try { - await onSaveToServer(openCasePackage, framework, plan) - baselineFrameworkRef.current = framework - setSaveStatus('success') - clearDirty() - clearInlineAlignmentEdits() - setTimeout(() => setSaveStatus('idle'), 2000) - } catch (err) { - console.error('[Save] Failed to save to server:', err) - setSaveStatus('error') - setSaveError(err instanceof Error ? err.message : 'Failed to save') - // Don't open the CFPackage viewer here — it has nothing to show for a - // failed save and previously opened with stale/empty content, which - // just displayed a misleading "No CFPackage data" placeholder instead - // of the real error (shown via saveError, next to the Save button). - } - } else { - setCfPackageDialogOpen(true) - } - }, [onSaveToServer, clearDirty, clearInlineAlignmentEdits]) - - // Save: Generate CFPackage and POST to server — unless this framework is - // still a pristine mirror and the pending edits touch actual framework - // data (not just canvas layout), in which case warn first: saving will - // fork it into an independent local copy. - const handleSave = useCallback(async () => { - const { nodes: n, edges: e, remoteLinks: rl, inlineAlignmentEdits: inlineEdits } = graphRef.current - const ctx = saveCtxRef.current - const fromGraph = fromEditorGraph({ graph: { nodes: n, edges: e, remoteLinks: rl } }) - const { layout, remoteEditorData } = fromGraph - const withOffCanvas = ctx.loadedFramework ? withOffCanvasAssociations(ctx.loadedFramework, fromGraph.framework) : fromGraph.framework - // Tree View edits to inline associations to other frameworks live outside the graph. - const framework = applyInlineAlignmentEdits(withOffCanvas, inlineEdits) - const cfPackage = frameworkToCfPackage({ - framework, layout, - caseVersion: ctx.caseVersion, edgeType: ctx.edgeType, - cfItemTypes: ctx.cfItemTypes, cfSubjects: ctx.cfSubjects, - cfConcepts: ctx.cfConcepts, cfLicenses: ctx.cfLicenses, cfAssociationGroupings: ctx.cfAssociationGroupings, - definitionsExtensions: ctx.cfDefinitionsExtensions, - remoteEditorData, - }) - const openCasePackage = toOpenCaseFormat(cfPackage) - console.log('[Save] Generated OpenCASE package:', openCasePackage) - - const baseline = baselineFrameworkRef.current - const isPristineMirror = mirrorStatus?.isModifiedFromSource === false && baseline !== null - const storageChanged = baseline !== null && - (baseline.metadata.alignmentStorage ?? 'inline') !== (framework.metadata.alignmentStorage ?? 'inline') - - // Changing where associations to other frameworks are stored can move some on save, which is a - // data change. Ask the server what would move, so the warning only shows when something does. - let plan: AlignmentStoragePlan | undefined - if (isPristineMirror && storageChanged && onPlanAlignmentStorage) { - try { - plan = await onPlanAlignmentStorage(openCasePackage, framework) - } catch (err) { - setSaveStatus('error') - setSaveError(err instanceof Error ? err.message : 'Failed to save') - return - } - } - const moving = plan ? alignmentMoveCount(plan) : 0 - - if (isPristineMirror && (hasFrameworkDataChanged(baseline, framework) || moving > 0)) { - pendingSaveRef.current = { openCasePackage, framework, plan } - setForkWarningMove(plan && moving > 0 ? describeAlignmentMove(plan, moving) : null) - setForkWarningOpen(true) - return - } - - await doSave(openCasePackage, framework, plan) - }, [mirrorStatus, doSave, onPlanAlignmentStorage]) - - // Compute in-use groupings from actual edges (for filter dropdown). - // Pathway highlighting only affects canvas edges, so with the canvas view - // disabled the dropdown is hidden by reporting no groupings in use. - const inUseGroupings = useMemo(() => { - if (!CANVAS_VIEW_ENABLED) return NO_GROUPINGS - const seenIds = new Set() - for (const e of editorEdges) { - const gId = e.data?.cfAssociation?.CFAssociationGroupingURI?.identifier - if (gId) seenIds.add(gId) - } - return cfAssociationGroupings.filter((g) => seenIds.has(g.identifier)) - }, [editorEdges, cfAssociationGroupings]) - - // Auto-clear filter if the active filter is no longer in use - useEffect(() => { - if (activeGroupingFilter && !inUseGroupings.some((g) => g.identifier === activeGroupingFilter)) { - setActiveGroupingFilter(null) - } - }, [activeGroupingFilter, inUseGroupings, setActiveGroupingFilter]) - - // Effective filter: only apply if the grouping is still in use (avoids stale fade on the - // render before the useEffect auto-clear fires) - const effectiveGroupingFilter = activeGroupingFilter && inUseGroupings.some((g) => g.identifier === activeGroupingFilter) - ? activeGroupingFilter - : null - - // Apply the custom labeled edge type to all edges, passing the path style in data. - // Per-element cache: only create new objects for edges whose data actually changed. - // Selection-only changes reuse the previous output so React Flow skips re-rendering. - const edgesCacheRef = useRef(new Map()) - - const edgesWithType = useMemo(() => { - if (!CANVAS_VIEW_ENABLED) return NO_EDGES - const prev = edgesCacheRef.current - const next = new Map() - const globalEdgeType = settings.edgeType - const parallelOffsetsByEdgeId = new Map() - - // Group edges by node pair (direction-agnostic) to fan out parallel labels. - // This keeps multiple associations (e.g. precedes + exactMatchOf) readable. - const byPair = new Map() - for (const edge of allEditorEdges) { - const pairKey = - edge.source < edge.target - ? `${edge.source}__${edge.target}` - : `${edge.target}__${edge.source}` - const arr = byPair.get(pairKey) - if (arr) arr.push(edge) - else byPair.set(pairKey, [edge]) - } - for (const arr of byPair.values()) { - if (arr.length <= 1) continue - const centeredStart = -(arr.length - 1) / 2 - arr - .slice() - .sort((a, b) => a.id.localeCompare(b.id)) - .forEach((edge, index) => { - parallelOffsetsByEdgeId.set(edge.id, { - parallelIndex: centeredStart + index, - parallelCount: arr.length, - }) - }) - } - - const result = allEditorEdges.map((edge) => { - const cached = prev.get(edge.id) - const parallel = parallelOffsetsByEdgeId.get(edge.id) - const parallelIndex = parallel?.parallelIndex ?? 0 - const parallelCount = parallel?.parallelCount ?? 1 - - // Fast path: exact same input + same global params → reuse entire output - if ( - cached && - cached.input === edge && - cached.edgeType === globalEdgeType && - cached.filter === effectiveGroupingFilter && - cached.parallelIndex === parallelIndex && - cached.parallelCount === parallelCount - ) { - next.set(edge.id, cached) - return cached.output - } - - // If only selected/position changed (data ref is same) and global params unchanged, - // reuse the output's data/style but merge the new edge shell - if ( - cached && - edge.data === cached.input.data && - cached.edgeType === globalEdgeType && - cached.filter === effectiveGroupingFilter && - cached.parallelIndex === parallelIndex && - cached.parallelCount === parallelCount - ) { - const resolvedType = edge.data?.isRemoteLink ? 'remoteLink' as const : 'labeled' as const - const output: CaseEditorEdge = { ...edge, type: resolvedType, data: cached.output.data, style: cached.output.style } - next.set(edge.id, { input: edge, edgeType: globalEdgeType, filter: effectiveGroupingFilter, parallelIndex, parallelCount, output }) - return output - } - - // Full recompute - const baseData = { - ...edge.data, - edgeType: edge.data?.edgeType ?? globalEdgeType, - parallelIndex, - parallelCount, - } - let style = edge.style - - if (effectiveGroupingFilter && !edge.data?.isRemoteLink) { - const edgeGroupId = edge.data?.cfAssociation?.CFAssociationGroupingURI?.identifier - const isRootEdge = edge.data?.isFrameworkRootConnection - const matches = edgeGroupId === effectiveGroupingFilter - - if (matches) { - style = { ...style, stroke: '#0d9488', strokeWidth: 3, opacity: 1, transition: 'all 0.2s ease' } - } else if (isRootEdge) { - style = { ...style, opacity: 0.35, transition: 'all 0.2s ease' } - } else { - style = { ...style, opacity: 0.1, transition: 'all 0.2s ease' } - } - } - - const resolvedType = edge.data?.isRemoteLink ? 'remoteLink' as const : 'labeled' as const - const output: CaseEditorEdge = { ...edge, type: resolvedType, data: baseData, style } - next.set(edge.id, { input: edge, edgeType: globalEdgeType, filter: effectiveGroupingFilter, parallelIndex, parallelCount, output }) - return output - }) - - edgesCacheRef.current = next - return result - }, [allEditorEdges, settings.edgeType, effectiveGroupingFilter]) - - // React Flow stays MOUNTED (just CSS-hidden) while Tree View is active, so - // that pan/zoom/selection state survives switching views. But feeding it a - // fresh `nodes`/`edges` array reference on every keystroke — even while - // invisible — makes it redo internal store diffing across the whole graph - // for nothing (confirmed via CPU profile: React Flow's internal selectors/ - // shallow-equality checks dominate keystroke cost at ~7,500 nodes). Freeze - // the props actually delivered to while hidden, and only catch - // up to the latest data the moment the canvas becomes visible again. - const frozenCanvasGraphRef = useRef<{ nodes: CaseEditorNodeType[]; edges: CaseEditorEdge[] }>({ - nodes: nodesWithCallbacks, - edges: edgesWithType, - }) - if (activeView !== 'tree') { - frozenCanvasGraphRef.current = { nodes: nodesWithCallbacks, edges: edgesWithType } - } - const canvasNodes = activeView === 'tree' ? frozenCanvasGraphRef.current.nodes : nodesWithCallbacks - const canvasEdges = activeView === 'tree' ? frozenCanvasGraphRef.current.edges : edgesWithType - - // Stable identity (see comment above) — an inline arrow function here would - // itself defeat the freeze the same way defaultEdgeOptions/proOptions did. - const onReactFlowInit = useCallback((instance: ReactFlowInstance) => { - reactFlowRef.current = instance - setRfReady(true) - }, []) - - // Validate connections - prevent framework-to-framework connections - const nodesWithCallbacksRef = useRef(nodesWithCallbacks) - nodesWithCallbacksRef.current = nodesWithCallbacks - - const isValidConnection = useCallback((connection: Connection) => { - const sourceNode = nodesWithCallbacksRef.current.find((n) => n.id === connection.source) - const targetNode = nodesWithCallbacksRef.current.find((n) => n.id === connection.target) - - const isSourceFramework = - sourceNode?.type === 'caseFrameworkNode' || - sourceNode?.type === 'externalFrameworkNode' - const isTargetFramework = - targetNode?.type === 'caseFrameworkNode' || - targetNode?.type === 'externalFrameworkNode' - - if (isSourceFramework && isTargetFramework) { - return false - } - - return true - }, []) - - // Handle edge reconnection - when user drags an edge endpoint to a new handle/node - const onReconnectStart = useCallback(() => { - edgeReconnectSuccessful.current = false - }, []) - - const onReconnect = useCallback((oldEdge: Edge, newConnection: Connection) => { - edgeReconnectSuccessful.current = true - - // Use our dedicated reconnect action to update the edge in place - const newSource = newConnection.source ?? oldEdge.source - const newTarget = newConnection.target ?? oldEdge.target - const newSourceHandle = newConnection.sourceHandle ?? undefined - const newTargetHandle = newConnection.targetHandle ?? undefined - - reconnectEdgeAction( - oldEdge.id, - newSource, - newTarget, - newSourceHandle, - newTargetHandle - ) - }, [reconnectEdgeAction]) - - const onReconnectEnd = useCallback((_: unknown, _edge: Edge) => { - // If reconnection wasn't successful (dropped in empty space), optionally remove the edge - // For now, we'll keep the edge if reconnection fails (user just cancels) - if (!edgeReconnectSuccessful.current) { - // Edge stays as-is if dropped in empty space - } - edgeReconnectSuccessful.current = true - }, []) - - // During Shift-click toggles we apply the intended node select change directly - // and ignore conflicting select-change echoes from React Flow for a short window. - const suppressSelectEchoRef = useRef(null) - const preserveSelectionDuringDragRef = useRef(null) - const lastNodeClickAtRef = useRef(0) - const lastEdgeClickAtRef = useRef(0) - const lastPointerDownRef = useRef<{ - clientX: number - clientY: number - shiftKey: boolean - at: number - } | null>(null) - const selectionDebugEnabledRef = useRef(false) - - useEffect(() => { - try { - const fromStorage = globalThis.localStorage?.getItem('case.debugSelection') === '1' - const fromQuery = new URLSearchParams(globalThis.location.search).get('debugSelection') === '1' - selectionDebugEnabledRef.current = fromStorage || fromQuery - if (selectionDebugEnabledRef.current) { - console.log('[selection-debug] enabled') - } - } catch { - // best-effort debug toggle - } - }, []) - - const logSelectionDebug = useCallback((event: string, details: Record = {}) => { - if (!selectionDebugEnabledRef.current) return - console.log(`[selection-debug] ${event}`, { - t: Number(globalThis.performance.now().toFixed(1)), - selectedNodeIds: [...selectedNodeIds], - selectedEdgeIds: [...selectedEdgeIds], - ...details, - }) - }, [selectedNodeIds, selectedEdgeIds]) - - const onCanvasPointerDownCapture = useCallback((event: ReactPointerEvent) => { - lastPointerDownRef.current = { - clientX: event.clientX, - clientY: event.clientY, - shiftKey: event.shiftKey, - at: Date.now(), - } - }, []) - - const onNodeClick = useCallback((event: ReactMouseEvent, node: CaseEditorNodeType) => { - lastNodeClickAtRef.current = Date.now() - logSelectionDebug('onNodeClick', { - nodeId: node.id, - shiftKey: event.shiftKey, - button: event.button, - }) - - if (!event.shiftKey) { - suppressSelectEchoRef.current = null - return - } - - event.preventDefault() - event.stopPropagation() - - const wasSelected = selectedNodeIds.includes(node.id) - const intendedNodeIds = wasSelected - ? selectedNodeIds.filter((id) => id !== node.id) - : [...selectedNodeIds, node.id] - const nodeChanges: NodeChange[] = [ - ...selectedNodeIds.map((id) => ({ type: 'select' as const, id, selected: id !== node.id })), - ...(!selectedNodeIds.includes(node.id) ? [{ type: 'select' as const, id: node.id, selected: true }] : []), - ] - const edgeChanges: EdgeChange[] = selectedEdgeIds.map((id) => ({ type: 'select' as const, id, selected: true })) - onNodesChange(nodeChanges) - if (edgeChanges.length > 0) onEdgesChange(edgeChanges) - suppressSelectEchoRef.current = { until: Date.now() + 250 } - logSelectionDebug('onNodeClick/manualToggle', { - nodeId: node.id, - wasSelected, - nextSelected: !wasSelected, - intendedSelectedNodeIds: intendedNodeIds, - reassertedEdgeCount: edgeChanges.length, - suppressEchoMs: 250, - }) - }, [logSelectionDebug, onEdgesChange, onNodesChange, selectedEdgeIds, selectedNodeIds]) - - const onNodeDragStart = useCallback((_: ReactMouseEvent, node: CaseEditorNodeType) => { - const preserve = selectedNodeIds.length > 1 && selectedNodeIds.includes(node.id) - if (!preserve) return - preserveSelectionDuringDragRef.current = { until: Date.now() + 1200 } - logSelectionDebug('onNodeDragStart/preserveMultiSelection', { - nodeId: node.id, - selectedCount: selectedNodeIds.length, - preserveMs: 1200, - }) - }, [logSelectionDebug, selectedNodeIds]) - - const onNodeDragStop = useCallback(() => { - preserveSelectionDuringDragRef.current = null - logSelectionDebug('onNodeDragStop/clearPreserveWindow') - }, [logSelectionDebug]) - - const onEdgeClick = useCallback((event: ReactMouseEvent, edge: Edge) => { - lastEdgeClickAtRef.current = Date.now() - logSelectionDebug('onEdgeClick', { - edgeId: edge.id, - shiftKey: event.shiftKey, - button: event.button, - }) - - if (!event.shiftKey) { - suppressSelectEchoRef.current = null - return - } - - event.preventDefault() - event.stopPropagation() - - const wasSelected = selectedEdgeIds.includes(edge.id) - const intendedEdgeIds = wasSelected - ? selectedEdgeIds.filter((id) => id !== edge.id) - : [...selectedEdgeIds, edge.id] - const edgeChanges: EdgeChange[] = [ - ...selectedEdgeIds.map((id) => ({ type: 'select' as const, id, selected: id !== edge.id })), - ...(!selectedEdgeIds.includes(edge.id) ? [{ type: 'select' as const, id: edge.id, selected: true }] : []), - ] - const nodeChanges: NodeChange[] = selectedNodeIds.map((id) => ({ type: 'select' as const, id, selected: true })) - onEdgesChange(edgeChanges) - if (nodeChanges.length > 0) onNodesChange(nodeChanges) - suppressSelectEchoRef.current = { until: Date.now() + 250 } - logSelectionDebug('onEdgeClick/manualToggle', { - edgeId: edge.id, - wasSelected, - nextSelected: !wasSelected, - intendedSelectedEdgeIds: intendedEdgeIds, - reassertedNodeCount: nodeChanges.length, - suppressEchoMs: 250, - }) - }, [logSelectionDebug, onEdgesChange, onNodesChange, selectedEdgeIds, selectedNodeIds]) - - const onNodesChangeWithSelectionGuard = useCallback((changes: NodeChange[]) => { - const suppressEcho = suppressSelectEchoRef.current - const preserveDuringDrag = preserveSelectionDuringDragRef.current - const hasSelectChanges = changes.some((c) => c.type === 'select') - const selectChanges = changes.filter((c): c is Extract, { type: 'select' }> => c.type === 'select') - logSelectionDebug('onNodesChange/received', { - hasSelectChanges, - suppressActive: Boolean(suppressEcho && Date.now() <= suppressEcho.until), - preserveDuringDragActive: Boolean(preserveDuringDrag && Date.now() <= preserveDuringDrag.until), - shiftHeld: shiftHeldRef.current, - changes: changes.map((c) => c.type === 'select' - ? { type: c.type, id: c.id, selected: c.selected } - : { type: c.type, id: 'id' in c ? c.id : undefined }), - }) - - if ( - !shiftHeldRef.current && - preserveDuringDrag && - Date.now() <= preserveDuringDrag.until && - hasSelectChanges - ) { - const nonSelectChanges = changesToProcess.filter((c) => c.type !== 'select') - const reassertSelected = selectedNodeIds.map((id) => ({ type: 'select' as const, id, selected: true })) - logSelectionDebug('onNodesChange/preserveMultiSelectionDuringDrag', { - selectCount: selectChanges.length, - forwardedNonSelectCount: nonSelectChanges.length, - reassertCount: reassertSelected.length, - }) - onNodesChange([...reassertSelected, ...nonSelectChanges]) - return - } - - // Defensive guard for intermittent React Flow race: - // while Shift is held, we sometimes receive a batch that deselects all - // currently selected nodes (multi false) after marquee selection + rapid click. - // Ignore only those suspicious select changes. - if ( - shiftHeldRef.current && - selectChanges.length > 1 && - selectChanges.every((c) => c.selected === false) - ) { - // If this came from a Shift click on a selected node, convert the blocked - // deselect-all batch into deselecting only the clicked node. - const pointer = lastPointerDownRef.current - if (pointer && pointer.shiftKey && Date.now() - pointer.at <= 500) { - const instance = reactFlowRef.current - const wrap = reactFlowWrapRef.current - if (instance && wrap) { - const viewport = instance.getViewport() - const rect = wrap.getBoundingClientRect() - const flowX = (pointer.clientX - rect.left - viewport.x) / viewport.zoom - const flowY = (pointer.clientY - rect.top - viewport.y) / viewport.zoom - const hitSelectedNodeId = selectedNodeIds.find((id) => { - // Read via graphRef, not the closed-over `nodes`, so this callback's - // identity doesn't change on every keystroke (nodes' reference - // changes on every dispatch, even ones that don't touch positions). - const node = graphRef.current.nodes.find((n) => n.id === id) - if (!node) return false - const anyNode = node as unknown as { - measured?: { width?: number; height?: number } - width?: number - height?: number - style?: { width?: number | string; height?: number | string } - } - const w = - anyNode.measured?.width ?? - (typeof anyNode.width === 'number' ? anyNode.width : undefined) ?? - (typeof anyNode.style?.width === 'number' ? anyNode.style?.width : undefined) ?? - 360 - const h = - anyNode.measured?.height ?? - (typeof anyNode.height === 'number' ? anyNode.height : undefined) ?? - (typeof anyNode.style?.height === 'number' ? anyNode.style?.height : undefined) ?? - 220 - return flowX >= node.position.x && flowX <= node.position.x + w && flowY >= node.position.y && flowY <= node.position.y + h - }) - if (hitSelectedNodeId) { - const targetChanges: NodeChange[] = selectedNodeIds.map((id) => ({ - type: 'select' as const, - id, - selected: id !== hitSelectedNodeId, - })) - suppressSelectEchoRef.current = { until: Date.now() + 300 } - logSelectionDebug('onNodesChange/convertedBlockedBatchToSingleDeselect', { - hitSelectedNodeId, - selectedCount: selectedNodeIds.length, - suppressEchoMs: 300, - }) - onNodesChange(targetChanges) - return - } - } - } - - const nonSelectChanges = changesToProcess.filter((c) => c.type !== 'select') - const reassertSelected = selectedNodeIds.map((id) => ({ type: 'select' as const, id, selected: true })) - suppressSelectEchoRef.current = { until: Date.now() + 300 } - logSelectionDebug('onNodesChange/blockedShiftDeselectAllBatch', { - blockedCount: selectChanges.length, - forwardedNonSelectCount: nonSelectChanges.length, - reassertCount: reassertSelected.length, - suppressEchoMs: 300, - }) - if (reassertSelected.length > 0) onNodesChange(reassertSelected) - if (nonSelectChanges.length > 0) onNodesChange(nonSelectChanges) - return - } - - // Another intermittent Shift race: React Flow may emit a "replace selection" - // batch (one selected:true + many selected:false). Under Shift interactions we - // normalize this into additive behavior by dropping only the false entries. - if ( - shiftHeldRef.current && - selectChanges.some((c) => c.selected === true) && - selectChanges.some((c) => c.selected === false) - ) { - const nonSelectChanges = changesToProcess.filter((c) => c.type !== 'select') as NodeChange[] - suppressSelectEchoRef.current = { until: Date.now() + 300 } - logSelectionDebug('onNodesChange/ignoredShiftMixedBatch', { - originalCount: changes.length, - selectCount: selectChanges.length, - forwardedNonSelectCount: nonSelectChanges.length, - suppressEchoMs: 300, - }) - if (nonSelectChanges.length > 0) onNodesChange(nonSelectChanges) - return - } - - if (suppressEcho && Date.now() <= suppressEcho.until && hasSelectChanges) { - const nonSelectChanges = changesToProcess.filter((c) => c.type !== 'select') - logSelectionDebug('onNodesChange/suppressedSelectEcho', { forwardedNonSelectCount: nonSelectChanges.length }) - if (nonSelectChanges.length > 0) onNodesChange(nonSelectChanges) - return - } - - onNodesChange(changes) - logSelectionDebug('onNodesChange/forwarded', { changeCount: changes.length }) - }, [logSelectionDebug, onNodesChange, selectedNodeIds]) - - const handleRemoteEdgeChanges = useCallback((changes: EdgeChange[]) => { - for (const change of changes) { - if (!('id' in change) || !change.id.startsWith('remote_link_')) continue - - if (change.type === 'remove') { - const linkId = remoteLinkIdFromEdgeId(change.id) - if (linkId) removeRemoteLink(linkId) - setSelectedRemoteEdgeIds((prev) => prev.filter((id) => id !== change.id)) - continue - } - - if (change.type === 'select') { - if (change.selected) { - setSelectedRemoteEdgeIds((prev) => - shiftHeldRef.current - ? [...prev.filter((id) => id !== change.id), change.id] - : [change.id], - ) - const linkId = remoteLinkIdFromEdgeId(change.id) - const link = remoteLinks.find((l) => l.id === linkId) - if (link && !shiftHeldRef.current) { - onNodesChange([ - ...nodesWithCallbacks - .filter((n) => n.selected) - .map((n) => ({ type: 'select' as const, id: n.id, selected: false })), - { type: 'select', id: link.localItemId, selected: true }, - ]) - } - } else { - setSelectedRemoteEdgeIds((prev) => prev.filter((id) => id !== change.id)) - } - } - } - }, [nodesWithCallbacks, onNodesChange, remoteLinks, removeRemoteLink]) - - const onEdgesChangeWithSelectionGuard = useCallback((changes: EdgeChange[]) => { - const remoteChanges = changes.filter((c) => 'id' in c && c.id.startsWith('remote_link_')) - const normalChanges = changes.filter((c) => !('id' in c) || !c.id.startsWith('remote_link_')) - - if (remoteChanges.length > 0) { - handleRemoteEdgeChanges(remoteChanges) - } - - if (normalChanges.length === 0) return - - if (normalChanges.some((c) => c.type === 'select' && c.selected === true)) { - setSelectedRemoteEdgeIds([]) - } - - const changesToProcess = normalChanges - const suppressEcho = suppressSelectEchoRef.current - const preserveDuringDrag = preserveSelectionDuringDragRef.current - const selectChanges = changesToProcess.filter((c): c is Extract => c.type === 'select') - const hasSelectChanges = selectChanges.length > 0 - logSelectionDebug('onEdgesChange/received', { - hasSelectChanges, - shiftHeld: shiftHeldRef.current, - suppressActive: Boolean(suppressEcho && Date.now() <= suppressEcho.until), - preserveDuringDragActive: Boolean(preserveDuringDrag && Date.now() <= preserveDuringDrag.until), - changes: changes.map((c) => c.type === 'select' - ? { type: c.type, id: c.id, selected: c.selected } - : { type: c.type, id: 'id' in c ? c.id : undefined }), - }) - - if ( - !shiftHeldRef.current && - preserveDuringDrag && - Date.now() <= preserveDuringDrag.until && - hasSelectChanges - ) { - const nonSelectChanges = changesToProcess.filter((c) => c.type !== 'select') - const reassertSelected = selectedEdgeIds.map((id) => ({ type: 'select' as const, id, selected: true })) - logSelectionDebug('onEdgesChange/preserveMultiSelectionDuringDrag', { - selectCount: selectChanges.length, - forwardedNonSelectCount: nonSelectChanges.length, - reassertCount: reassertSelected.length, - }) - onEdgesChange([...reassertSelected, ...nonSelectChanges]) - return - } - - // Mirror the node guard: while Shift is held, ignore suspicious edge - // deselect-all batches that can arrive after marquee + rapid toggle. - if ( - shiftHeldRef.current && - selectChanges.length > 1 && - selectChanges.every((c) => c.selected === false) - ) { - const nonSelectChanges = changesToProcess.filter((c) => c.type !== 'select') - const reassertSelected = selectedEdgeIds.map((id) => ({ type: 'select' as const, id, selected: true })) - suppressSelectEchoRef.current = { until: Date.now() + 300 } - logSelectionDebug('onEdgesChange/blockedShiftDeselectAllBatch', { - blockedCount: selectChanges.length, - forwardedNonSelectCount: nonSelectChanges.length, - reassertCount: reassertSelected.length, - suppressEchoMs: 300, - }) - if (reassertSelected.length > 0) onEdgesChange(reassertSelected) - if (nonSelectChanges.length > 0) onEdgesChange(nonSelectChanges) - return - } - - if ( - shiftHeldRef.current && - selectChanges.some((c) => c.selected === true) && - selectChanges.some((c) => c.selected === false) - ) { - const nonSelectChanges = changesToProcess.filter((c) => c.type !== 'select') as EdgeChange[] - suppressSelectEchoRef.current = { until: Date.now() + 300 } - logSelectionDebug('onEdgesChange/ignoredShiftMixedBatch', { - originalCount: changes.length, - selectCount: selectChanges.length, - forwardedNonSelectCount: nonSelectChanges.length, - suppressEchoMs: 300, - }) - if (nonSelectChanges.length > 0) onEdgesChange(nonSelectChanges) - return - } - - if (suppressEcho && Date.now() <= suppressEcho.until && hasSelectChanges) { - const nonSelectChanges = changesToProcess.filter((c) => c.type !== 'select') - logSelectionDebug('onEdgesChange/suppressedSelectEcho', { forwardedNonSelectCount: nonSelectChanges.length }) - if (nonSelectChanges.length > 0) onEdgesChange(nonSelectChanges) - return - } - - onEdgesChange(changesToProcess) - logSelectionDebug('onEdgesChange/forwarded', { changeCount: changesToProcess.length }) - }, [handleRemoteEdgeChanges, logSelectionDebug, onEdgesChange, selectedEdgeIds]) - - const onPaneClick = useCallback((event: ReactMouseEvent) => { - // Ignore Shift-modified pane clicks (they may occur as part of add-to-selection gestures). - if (event.shiftKey) { - logSelectionDebug('onPaneClick/ignoredShift') - return - } - // Ignore pane clicks that arrive right after a node click due to event sequencing. - const now = Date.now() - const sinceNodeClick = now - lastNodeClickAtRef.current - const sinceEdgeClick = now - lastEdgeClickAtRef.current - if (sinceNodeClick < 250 || sinceEdgeClick < 250) { - logSelectionDebug('onPaneClick/ignoredRecentElementClick', { - sinceNodeClickMs: sinceNodeClick, - sinceEdgeClickMs: sinceEdgeClick, - }) - return - } - suppressSelectEchoRef.current = null - setSelectedRemoteEdgeIds([]) - if (selectedNodeIds.length + selectedEdgeIds.length > 0) { - logSelectionDebug('onPaneClick/clearSelection') - clearSelection() - return - } - logSelectionDebug('onPaneClick/noop') - }, [clearSelection, logSelectionDebug, selectedNodeIds, selectedEdgeIds]) - - const [pendingAction, setPendingAction] = useState void - }>(null) - const [archiving, setArchiving] = useState(false) - - // Helper function to get the center of the current viewport in flow coordinates - const getViewportCenter = useCallback(() => { - const instance = reactFlowRef.current - const wrap = reactFlowWrapRef.current - if (!instance || !wrap) return undefined - - const viewport = instance.getViewport() - const wrapRect = wrap.getBoundingClientRect() - - // Convert screen center to flow coordinates - const centerX = (wrapRect.width / 2 - viewport.x) / viewport.zoom - const centerY = (wrapRect.height / 2 - viewport.y) / viewport.zoom - - return { x: centerX, y: centerY } - }, []) - - const linkedFrameworkNodes = useMemo( - () => nodesWithCallbacks.filter((n) => n.type === 'externalFrameworkNode'), - [nodesWithCallbacks], - ) - - const hasSelection = Boolean(selectedNode || selectedEdge || (selectedNodeIds.length + selectedEdgeIds.length > 1)) - const showBrowsePanel = sidePanelMode === 'cgeSearch' || sidePanelMode === 'remoteItems' - const showPropertiesPanel = hasSelection && !showBrowsePanel - const sidePanelOpen = showBrowsePanel || showPropertiesPanel - - const handleAddCgeFrameworkToCanvas = useCallback(async (fw: CgeFrameworkSummary) => { - if (!tenantId) throw new Error('Sign in required') - - const existing = linkedFrameworkNodes.find((n) => n.data.cgeFrameworkId === fw.frameworkId) - if (existing) { - if (existing.data.cacheDocId && !existing.data.cacheError) { - openRemoteItemsPanel(existing.id) - } else { - openExternalFrameworkSettings(existing.id) - } - return - } - - const refId = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}` - const viewportCenter = getViewportCenter() - const nodeId = addExternalFramework({ - refId, - title: fw.title, - cgeFrameworkId: fw.frameworkId, - color: '', - sourceUri: fw.sourceUri, - uri: fw.sourceUri, - source: fw.publisher, - cacheLoading: true, - }, viewportCenter) - - try { - const result = await api.importCgeFramework({ - tenantId, - frameworkId: fw.frameworkId, - sourceUri: fw.sourceUri, - registryId: fw.registryId, - readOnly: true, - subscribe: false, - }) - updateNodeData(nodeId, { - title: result.title ?? fw.title, - cacheDocId: result.docId, - itemCount: result.itemCount, - cachedAt: result.cachedAt, - sourceUri: result.sourceUri ?? fw.sourceUri, - cacheError: null, - cacheLoading: false, - }) - setActiveRemoteFrameworkNodeId(nodeId) - setSidePanelMode('remoteItems') - } catch (e) { - updateNodeData(nodeId, { - cacheError: formatApiErrorMessage(e, 'Failed to download framework from publisher'), - cacheLoading: false, - }) - openExternalFrameworkSettings(nodeId) - } - }, [ - tenantId, - linkedFrameworkNodes, - getViewportCenter, - addExternalFramework, - api, - updateNodeData, - openRemoteItemsPanel, - openExternalFrameworkSettings, - setActiveRemoteFrameworkNodeId, - setSidePanelMode, - ]) - - const handleRefreshActiveRemoteFramework = useCallback(async () => { - const nodeId = activeRemoteFrameworkNodeId ?? selectedNode?.id - const node = linkedFrameworkNodes.find((n) => n.id === nodeId) ?? selectedNode - if (!tenantId || !node || node.type !== 'externalFrameworkNode') return - const cgeFrameworkId = node.data.cgeFrameworkId - if (!cgeFrameworkId) return - setRemoteFrameworkRefreshing(true) - updateNodeData(node.id, { cacheLoading: true, cacheError: null }) - try { - const result = node.data.cacheDocId - ? await api.refreshCgeCache({ - tenantId, - frameworkId: cgeFrameworkId, - skipPublisherAuth: node.data.skipPublisherAuth, - }) - : await api.importCgeFramework({ - tenantId, - frameworkId: cgeFrameworkId, - sourceUri: node.data.sourceUri ?? node.data.uri, - readOnly: true, - subscribe: false, - skipPublisherAuth: node.data.skipPublisherAuth, - }) - updateNodeData(node.id, { - title: result.title ?? node.data.title, - itemCount: result.itemCount, - cachedAt: result.cachedAt, - cacheDocId: result.docId ?? node.data.cacheDocId, - sourceUri: result.sourceUri ?? node.data.sourceUri, - cacheError: null, - cacheLoading: false, - }) - } catch (e) { - updateNodeData(node.id, { - cacheError: formatApiErrorMessage(e, 'Failed to download framework from publisher'), - cacheLoading: false, - }) - } finally { - setRemoteFrameworkRefreshing(false) - } - }, [tenantId, activeRemoteFrameworkNodeId, selectedNode, linkedFrameworkNodes, api, updateNodeData]) - - const handleRemoveActiveRemoteFramework = useCallback(() => { - const nodeId = activeRemoteFrameworkNodeId ?? selectedNode?.id - if (nodeId) removeRemoteFramework(nodeId) - }, [activeRemoteFrameworkNodeId, selectedNode?.id, removeRemoteFramework]) - - // Double-clicking a linked CASE Global framework opens its item browser once - // its cache has downloaded, or its settings panel when the download failed / - // hasn't happened yet. `useCallback` keeps ReactFlowGraph's memo intact. - const onNodeDoubleClick = useCallback((_: ReactMouseEvent, node: CaseEditorNodeType) => { - if (node.type !== 'externalFrameworkNode') return - const ext = node.data - if (ext.cacheDocId && !ext.cacheError) { - openRemoteItemsPanel(node.id) - } else { - openExternalFrameworkSettings(node.id) - } - }, [openRemoteItemsPanel, openExternalFrameworkSettings]) - - const handleRemoteDrop = useCallback((localItemId: string, raw: string) => { - const payload = parseRemoteItemDragPayload(raw) - if (!payload) return - setPendingRemoteDrop({ localItemId, payload }) - }, []) - - const confirmRemoteLink = useCallback((associationType: string) => { - if (!pendingRemoteDrop?.payload) return - const p = pendingRemoteDrop.payload - const linkId = globalThis.crypto?.randomUUID?.() ?? `link_${Date.now()}` - const link: RemoteItemLink = { - id: linkId, - localItemId: pendingRemoteDrop.localItemId, - remoteItemUri: p.uri ?? p.identifier, - remoteItemIdentifier: p.identifier, - remoteFrameworkRefId: p.remoteFrameworkRefId, - associationType, - remoteLabel: p.label, - remoteHumanCodingScheme: p.humanCodingScheme, - remoteFrameworkTitle: p.remoteFrameworkTitle, - remoteFrameworkColor: p.remoteFrameworkColor, - cfAssociationId: linkId, - } - addRemoteLink(link) - setPendingRemoteDrop(null) - }, [pendingRemoteDrop, addRemoteLink]) - - const onPaneDragOver = useCallback((e: React.DragEvent) => { - if (e.dataTransfer.types.includes(REMOTE_ITEM_MIME)) { - e.preventDefault() - e.dataTransfer.dropEffect = 'link' - } - }, []) - - const onPaneDrop = useCallback((e: React.DragEvent) => { - const raw = e.dataTransfer.getData(REMOTE_ITEM_MIME) - if (!raw) return - e.preventDefault() - const instance = reactFlowRef.current - if (!instance) return - const position = instance.screenToFlowPosition({ x: e.clientX, y: e.clientY }) - const targetNode = instance.getIntersectingNodes({ x: position.x, y: position.y, width: 1, height: 1 }) - .find((n) => n.type === 'caseItemNode') - if (targetNode) { - handleRemoteDrop(targetNode.id, raw) - } - }, [handleRemoteDrop]) - - // Keyboard shortcuts for adding items and remote frameworks - useEffect(() => { - const handleKeyDown = (e: KeyboardEvent) => { - // Check if user is typing in an input field - const target = e.target as HTMLElement - if ( - target.tagName === 'INPUT' || - target.tagName === 'TEXTAREA' || - target.isContentEditable - ) { - return - } - - // Check for Cmd/Ctrl modifier - const isMod = e.metaKey || e.ctrlKey - if (!isMod) return - - // Cmd/Ctrl + C: Add new item - if (e.key.toLowerCase() === 'c') { - e.preventDefault() - const viewportCenter = getViewportCenter() - addDetachedItem(viewportCenter) - return - } - - // Cmd/Ctrl + F: Search CASE Global frameworks - if (e.key.toLowerCase() === 'f') { - e.preventDefault() - openCgeSearchPanel() - return - } - } - - globalThis.addEventListener('keydown', handleKeyDown) - return () => globalThis.removeEventListener('keydown', handleKeyDown) - }, [addDetachedItem, getViewportCenter, openCgeSearchPanel]) - - const onBeforeDelete: OnBeforeDelete = useCallback( - async ({ nodes, edges: deletedEdges }) => { - // Read via refs, not the closed-over nodesWithCallbacks/editorEdges, so - // this callback's identity doesn't change on every keystroke (both - // change reference on every dispatch, even ones that don't affect - // what's deletable) — see graphRef/nodesWithCallbacksRef above. - const allNodes = nodesWithCallbacksRef.current - const allEdges = graphRef.current.edges - const includesFramework = nodes.some((n) => n.type === 'caseFrameworkNode') - - const nodeIds = includesFramework ? allNodes.map((n) => n.id) : nodes.map((n) => n.id) - const edgeIds = includesFramework ? allEdges.map((e) => e.id) : deletedEdges.map((e) => e.id) - - const nodeIdSet = new Set(nodeIds) - const deletedItemIdSet = new Set( - (includesFramework ? allNodes : nodes).filter((n) => n.type === 'caseItemNode').map((n) => n.id), - ) - - const childItemCount = allNodes.filter( - (n) => - n.type === 'caseItemNode' && - !nodeIdSet.has(n.id) && - Boolean((n.data as { parentId?: string }).parentId) && - deletedItemIdSet.has((n.data as { parentId?: string }).parentId!), - ).length - - const itemCount = deletedItemIdSet.size - - return new Promise((resolve) => { - setPendingAction({ - nodeIds, - edgeIds, - itemCount, - childItemCount, - reattachChildren: !includesFramework, - isFrameworkArchive: includesFramework, - resolve, - }) - }) - }, - [], - ) - - const closeActionDialog = useCallback(() => { - setPendingAction((pd) => { - pd?.resolve(false) - return null - }) - }, []) - - const confirmAction = useCallback( - async (options: { reattachChildren: boolean }) => { - if (!pendingAction) return - const isArchive = pendingAction.isFrameworkArchive - - if (isArchive) { - // Archive on the server first, then navigate home - if (onArchiveFramework) { - setArchiving(true) - try { - await onArchiveFramework() - } catch (err) { - console.error('[EditorCanvas] Failed to archive framework:', err) - setArchiving(false) - pendingAction.resolve(false) - setPendingAction(null) - return - } - setArchiving(false) - } - pendingAction.resolve(false) - setPendingAction(null) - // Navigation is handled by onArchiveFramework callback - } else { - // Local item removal - deleteElements({ - nodeIds: pendingAction.nodeIds, - edgeIds: pendingAction.edgeIds, - reattachChildren: options.reattachChildren, - }) - pendingAction.resolve(false) - setPendingAction(null) - } - }, - [pendingAction, deleteElements, onArchiveFramework], - ) - - const ensureNodeVisible = useCallback( - (node: CaseEditorNodeType) => { - const instance = reactFlowRef.current - const wrap = reactFlowWrapRef.current - if (!instance || !wrap) return - - const viewport = instance.getViewport() - const zoom = viewport.zoom - - // Node size heuristics: prefer measured/explicit sizes, fall back to style defaults. - const anyNode = node as unknown as { - measured?: { width?: number; height?: number } - width?: number - height?: number - style?: { width?: number | string; height?: number | string } - } - const w = - anyNode.measured?.width ?? - (typeof anyNode.width === 'number' ? anyNode.width : undefined) ?? - (typeof anyNode.style?.width === 'number' ? anyNode.style?.width : undefined) ?? - 360 - const h = - anyNode.measured?.height ?? - (typeof anyNode.height === 'number' ? anyNode.height : undefined) ?? - (typeof anyNode.style?.height === 'number' ? anyNode.style?.height : undefined) ?? - 220 - - const wrapRect = wrap.getBoundingClientRect() - const isMultiSelect = selectedNodeIds.length + selectedEdgeIds.length > 1 - const panelWidth = (selectedNode || selectedEdge || isMultiSelect) ? Math.min(460, globalThis.innerWidth * 0.92) : 0 - - const margin = 24 - const safeTop = 96 // leave room for the floating header - const safeRight = wrapRect.width - panelWidth - margin - const safeLeft = margin - const safeBottom = wrapRect.height - margin - - const nodeX = node.position.x - const nodeY = node.position.y - - const x1 = nodeX * zoom + viewport.x - const x2 = (nodeX + w) * zoom + viewport.x - const y1 = nodeY * zoom + viewport.y - const y2 = (nodeY + h) * zoom + viewport.y - - let dx = 0 - let dy = 0 - - if (x2 > safeRight) dx = x2 - safeRight - if (x1 - dx < safeLeft) dx = x1 - safeLeft - - if (y2 > safeBottom) dy = y2 - safeBottom - if (y1 - dy < safeTop) dy = y1 - safeTop - - if (dx === 0 && dy === 0) return - - instance.setViewport( - { - x: viewport.x - dx, - y: viewport.y - dy, - zoom, - }, - { duration: 220 }, - ) - }, - [selectedNode, selectedEdge, selectedNodeIds, selectedEdgeIds], - ) - - // Auto-pan to keep the selected node visible. No state dispatches — selection - // is derived from the `selected` flags managed by onNodesChange/onEdgesChange. - const onSelectionChangeWithPan: OnSelectionChangeFunc = useCallback( - (params) => { - const selectedNodes = params.nodes ?? [] - const selectedEdges = params.edges ?? [] - const suppressEcho = suppressSelectEchoRef.current - const suppressActive = Boolean(suppressEcho && Date.now() <= suppressEcho.until) - const countMismatch = - selectedNodes.length !== selectedNodeIds.length || - selectedEdges.length !== selectedEdgeIds.length - logSelectionDebug('onSelectionChange', { - nodeCount: selectedNodes.length, - edgeCount: selectedEdges.length, - nodeIds: selectedNodes.map((n) => n.id), - edgeIds: selectedEdges.map((e) => e.id), - shiftHeld: shiftHeldRef.current, - suppressActive, - countMismatch, - }) - // React Flow can briefly emit stale selection snapshots during rapid Shift - // interactions; ignore those to prevent side effects from transient states. - if (shiftHeldRef.current || suppressActive || countMismatch) return - if (selectedNodes.length !== 1 || selectedEdges.length !== 0) return - const selected = selectedNodes[0] - - // Two rAFs: selection state and node measurements may settle after the event. - globalThis.requestAnimationFrame(() => { - globalThis.requestAnimationFrame(() => { - ensureNodeVisible(selected) - }) - }) - }, - [ensureNodeVisible, logSelectionDebug, selectedNodeIds.length, selectedEdgeIds.length], - ) - - // Center on the framework's root node, at a fixed, comfortable zoom — - // regardless of framework size — so the user lands oriented on the root - // instead of a fit-to-everything view that can shrink the root to a speck - // in a large framework. Runs on the very first paint AND whenever the user - // switches layout mode (Hierarchy/Star "views"), since a layout switch - // moves every node and should re-orient the same way a fresh load does. - const centerOnRoot = useCallback(() => { - const instance = reactFlowRef.current - const wrap = reactFlowWrapRef.current - if (!instance || !wrap) return - - const DEFAULT_ROOT_ZOOM = 1 - const animate = didInitialViewportRef.current - const duration = animate ? 200 : 0 - - const center = () => { - const instance2 = reactFlowRef.current - if (!instance2) return - const root = instance2.getNodes().find(isFrameworkNode) - if (!root) return - const { w, h } = getNodeSize(root) - instance2.setCenter(root.position.x + w / 2, root.position.y + h / 2, { - zoom: DEFAULT_ROOT_ZOOM, - duration, - }) - didInitialViewportRef.current = true - } - - // Switching back from Tree View unhides this container (display:none → - // visible) in the same tick that triggers this effect, but the browser - // doesn't recompute layout — and React Flow's own ResizeObserver doesn't - // refresh its cached container size — until a later frame. Centering - // immediately would compute pan/zoom against a stale 0x0 size, so poll - // until the container actually has a measurable size (bounded, in case - // it's genuinely hidden for some other reason). - const MAX_ATTEMPTS = 30 - let attempts = 0 - let rafId: number - - const waitForSizeThenCenter = () => { - const { width, height } = reactFlowWrapRef.current?.getBoundingClientRect() ?? { width: 0, height: 0 } - if ((width > 0 && height > 0) || attempts >= MAX_ATTEMPTS) { - center() - return - } - attempts += 1 - rafId = globalThis.requestAnimationFrame(waitForSizeThenCenter) - } - - // One rAF to let React Flow apply any pending node measurements/positions - // before the size-polling loop starts. - const id = globalThis.requestAnimationFrame(() => { - rafId = globalThis.requestAnimationFrame(waitForSizeThenCenter) - }) - - return () => { - globalThis.cancelAnimationFrame(id) - globalThis.cancelAnimationFrame(rafId) - } - }, []) - - const fitToContents = useCallback(() => { - const instance = reactFlowRef.current - const wrap = reactFlowWrapRef.current - if (!instance || !wrap) return - - const HEADER_OVERLAY_PX = 72 // header height + breathing room - const MAX_INITIAL_ZOOM = 1 // avoid over-zooming when the graph is small (e.g. new/empty framework) - const SAFE_TOP_PX = 96 // keep the framework node just under the floating header - const animate = didInitialViewportRef.current - const fitDuration = animate ? 200 : 0 - const biasDuration = animate ? 160 : 0 - - const fit = () => { - const h = wrap.getBoundingClientRect().height || 800 - const padding = Math.max(0.12, (HEADER_OVERLAY_PX + 12) / h) - instance.fitView({ padding, duration: fitDuration, maxZoom: MAX_INITIAL_ZOOM }) - } - - // Two rAFs to let React Flow apply any pending node measurements/positions. - const id = globalThis.requestAnimationFrame(() => fit()) - const id2 = globalThis.requestAnimationFrame(() => fit()) - - const biasToTop = () => { - const instance2 = reactFlowRef.current - const wrap2 = reactFlowWrapRef.current - if (!instance2 || !wrap2) return - - const nodes = instance2.getNodes() - if (!nodes.length) return - - const getSize = (n: (typeof nodes)[number]) => { - const anyNode = n as unknown as { - measured?: { width?: number; height?: number } - width?: number - height?: number - style?: { width?: number | string; height?: number | string } - } - - const w = - anyNode.measured?.width ?? - (typeof anyNode.width === 'number' ? anyNode.width : undefined) ?? - (typeof anyNode.style?.width === 'number' ? anyNode.style?.width : undefined) ?? - 360 - const h = - anyNode.measured?.height ?? - (typeof anyNode.height === 'number' ? anyNode.height : undefined) ?? - (typeof anyNode.style?.height === 'number' ? anyNode.style?.height : undefined) ?? - 220 - return { w, h } - } - - let minY = Number.POSITIVE_INFINITY - let maxY = Number.NEGATIVE_INFINITY - for (const n of nodes) { - const { h } = getSize(n) - minY = Math.min(minY, n.position.y) - maxY = Math.max(maxY, n.position.y + h) - } - - const viewport = instance2.getViewport() - const zoom = viewport.zoom - - const wrapRect = wrap2.getBoundingClientRect() - const availableH = wrapRect.height - SAFE_TOP_PX - 24 - const contentH = (maxY - minY) * zoom - - // Only apply top bias when the graph is small enough to fit without hiding content. - if (contentH > availableH) return - - const desiredY = SAFE_TOP_PX - minY * zoom - instance2.setViewport({ x: viewport.x, y: desiredY, zoom }, { duration: biasDuration }) - didInitialViewportRef.current = true - } - - // Bias after fit has applied; keep it rAF-based to avoid a visible "jump". - const id3 = globalThis.requestAnimationFrame(() => { - globalThis.requestAnimationFrame(() => { - biasToTop() - }) - }) - - return () => { - globalThis.cancelAnimationFrame(id) - globalThis.cancelAnimationFrame(id2) - globalThis.cancelAnimationFrame(id3) - } - }, []) - - // First paint, and any explicit layout-mode switch (Hierarchy/Star "reset"), - // center on the root node. A layout switch moves every node, so it should - // re-orient the same way a fresh load does. Node-count-only changes (items - // added/removed without a layout switch) instead fall back to fitting the - // whole graph, leaving room for the floating header so the top-most node - // isn't hidden behind it. - useEffect(() => { - if (!rfReady) return - const layoutChanged = prevLayoutVersionRef.current === null || prevLayoutVersionRef.current !== layoutVersion - prevLayoutVersionRef.current = layoutVersion - const cleanup = layoutChanged ? centerOnRoot() : fitToContents() - const onResize = () => { - fitToContents() - } - globalThis.addEventListener('resize', onResize) - return () => { - cleanup?.() - globalThis.removeEventListener('resize', onResize) - } - }, [rfReady, nodesWithCallbacks.length, layoutVersion, fitToContents, centerOnRoot]) - - return ( -
- void changePassword() : undefined} - reserveRightForPanel={sidePanelOpen} - // Settings menu is canvas-only (edge style, view switching), so it's - // hidden while Tree View is the only view (see featureFlags.ts). - showSettings={CANVAS_VIEW_ENABLED} - isDirty={isDirty} - saveStatus={saveStatus} - saveError={saveError} - onSave={handleSave} - onSignIn={undefined} - onSignOut={ - authStatus !== 'authenticated' - ? undefined - : () => { - void signOut() - } - } - onBack={ - onBack - ? () => { - if (isDirty) setLeaveOpen(true) - else onBack() - } - : undefined - } - onOpenSettings={CANVAS_VIEW_ENABLED ? () => setSettingsOpen(true) : undefined} - onResetHierarchy={CANVAS_VIEW_ENABLED ? () => { setActiveView('canvas'); applyHierarchyLayout() } : undefined} - onResetStar={CANVAS_VIEW_ENABLED ? () => { setActiveView('canvas'); applyStarLayout() } : undefined} - onSwitchTreeView={CANVAS_VIEW_ENABLED ? () => setActiveView(activeView === 'tree' ? 'canvas' : 'tree') : undefined} - activeView={activeView} - cfAssociationGroupings={inUseGroupings} - activeGroupingFilter={activeGroupingFilter} - onSetGroupingFilter={setActiveGroupingFilter} - /> - - {activeView === 'tree' ? ( -
- -
- ) : null} - - {/* Not mounted at all while the canvas view is disabled — avoids React - Flow's store setup across every node/edge on framework open. */} - {CANVAS_VIEW_ENABLED ? : null} - - { clearSelection(); closeSidePanel() }} - onChangeNode={updateNodeData} - hideColorBand={activeView === 'tree'} - onViewCFPackage={handleViewCFPackage} - availableLicenses={availableLicenses} - cfItemTypes={cfItemTypes} - ensureCfItemType={ensureCfItemType} - cfSubjects={cfSubjects} - ensureCfSubject={ensureCfSubject} - cfConcepts={cfConcepts} - ensureCfConcept={ensureCfConcept} - remoteLinks={remoteLinks} - onRemoveRemoteLink={removeRemoteLink} - onUpdateRemoteLinkType={updateRemoteLinkType} - onRemoveRemoteFramework={removeRemoteFramework} - onBrowseRemoteItems={openRemoteItemsPanel} - onRefreshRemoteFramework={selectedNode?.type === 'externalFrameworkNode' && selectedNode.data.cgeFrameworkId ? handleRefreshActiveRemoteFramework : undefined} - remoteFrameworkRefreshing={remoteFrameworkRefreshing} - /> - - { clearSelection(); closeSidePanel() }} - onChangeEdge={updateEdgeData} - onFlipEdge={flipEdge} - cfAssociationGroupings={cfAssociationGroupings} - ensureCfAssociationGrouping={ensureCfAssociationGrouping} - /> - - { clearSelection(); closeSidePanel() }} - onDeleteSelected={() => { - const selectedNodes = nodesWithCallbacks.filter((n) => selectedNodeIds.includes(n.id)) - const selectedEdgesForDelete = editorEdges.filter((e) => selectedEdgeIds.includes(e.id)) - void onBeforeDelete({ nodes: selectedNodes, edges: selectedEdgesForDelete }) - }} - onChangeEdge={updateEdgeData} - onChangeNode={updateNodeData} - cfAssociationGroupings={cfAssociationGroupings} - ensureCfAssociationGrouping={ensureCfAssociationGrouping} - /> - - { - const parent = nodesWithCallbacks.find((n) => n.id === addItemDialog.parentId) - if (!parent) return undefined - if (parent.type === 'caseFrameworkNode') return (parent.data as { cfDocument?: CFDocument })?.cfDocument?.title ?? 'Framework' - return ( - (parent.data as { cfItem?: CFItem })?.cfItem?.humanCodingScheme ?? - (parent.data as { cfItem?: CFItem })?.cfItem?.abbreviatedStatement ?? - (parent.data as { cfItem?: CFItem })?.cfItem?.fullStatement ?? - 'Item' - ) - })()} - draft={addItemDialog.draft} - onChange={setAddItemDraft} - onCancel={cancelAddItem} - onCreate={confirmAddItem} - cfItemTypes={cfItemTypes} - cfSubjects={cfSubjects} - /> - - 0} - reattachChildren={pendingAction?.reattachChildren ?? true} - reattachLabel={ - (pendingAction?.childItemCount ?? 0) > 0 - ? `Keep the framework connected by attaching ${pendingAction?.childItemCount} child item${(pendingAction?.childItemCount ?? 0) === 1 ? '' : 's'} to the removed item\u2019s parent` - : 'Keep the framework connected by attaching child items to the removed item\u2019s parent' - } - onReattachChildrenChange={(value) => - setPendingAction((pd) => (pd ? { ...pd, reattachChildren: value } : pd)) - } - onCancel={closeActionDialog} - onConfirm={(options) => void confirmAction({ reattachChildren: options.reattachChildren })} - /> - - setLeaveOpen(false)} - onLeave={() => { - setLeaveOpen(false) - onBack?.() - }} - /> - - { - setForkWarningOpen(false) - pendingSaveRef.current = null - }} - onConfirm={() => { - setForkWarningOpen(false) - const pending = pendingSaveRef.current - pendingSaveRef.current = null - if (pending) void doSave(pending.openCasePackage, pending.framework, pending.plan) - }} - /> - - {/* Edge style is the only setting, and it only affects the canvas. */} - {CANVAS_VIEW_ENABLED ? setSettingsOpen(false)} - onSave={updateSettings} - /> : null} - - {showBrowsePanel ? ( -
- {sidePanelMode === 'cgeSearch' && tenantId ? ( - - ) : null} - {sidePanelMode === 'remoteItems' && tenantId ? ( - n.id === (activeRemoteFrameworkNodeId ?? linkedFrameworkNodes[0]?.id))?.data.cgeFrameworkId) - ? handleRefreshActiveRemoteFramework - : undefined - } - onRemoveFramework={handleRemoveActiveRemoteFramework} - frameworkRefreshing={remoteFrameworkRefreshing} - onOpenFrameworkSettings={() => { - const nodeId = activeRemoteFrameworkNodeId ?? linkedFrameworkNodes[0]?.id - if (nodeId) { - setSelectedRemoteEdgeIds([]) - openExternalFrameworkSettings(nodeId) - } - }} - /> - ) : null} -
- ) : null} - - setPendingRemoteDrop(null)} - onConfirm={confirmRemoteLink} - /> - - { - const viewportCenter = getViewportCenter() - addDetachedItem(viewportCenter) - }} - onAddExternalFramework={() => { - openCgeSearchPanel() - }} - sidePanelOpen={sidePanelOpen} - /> - - { - setCfPackageDialogOpen(false) - setGeneratedCfPackage(null) - }} - cfPackage={generatedCfPackage} - caseVersion={caseVersion} - loading={viewCaseLoading} - /> - -
- ) -} - diff --git a/apps/editor/src/ui/editor/FrameworkEditor.tsx b/apps/editor/src/ui/editor/FrameworkEditor.tsx new file mode 100644 index 0000000..b12cbfd --- /dev/null +++ b/apps/editor/src/ui/editor/FrameworkEditor.tsx @@ -0,0 +1,337 @@ +import { useCallback, useRef, useState } from 'react' +import EditorHeader from '@/ui/editor/components/EditorHeader' +import NodePropertiesPanel from '@/ui/editor/components/NodePropertiesPanel' +import AddItemDialog from '@/ui/editor/components/AddItemDialog' +import ConfirmActionDialog from '@/ui/editor/components/ConfirmActionDialog' +import ConfirmLeaveDialog from '@/ui/editor/components/ConfirmLeaveDialog' +import ViewCFPackageDialog from '@/ui/editor/components/ViewCFPackageDialog' +import TreePanelView, { type CgeTargetSupport } from '@/ui/editor/treePanel/TreePanelView' +import { useEditor } from '@/ui/editor/state/EditorContext' +import type { CaseExtensions, CFDocument, CFItem, CFPackage } from '@/domain/case/types' +import type { HomeFramework } from '@/ui/home/frameworkStore' +import { useAuth } from '@/app/providers/AuthProvider' +import { fromEditorGraph } from '@/ui/editor/state/mapping/fromEditorGraph' +import { frameworkToCfPackage, toOpenCaseFormat } from '@/application/framework/mappers/case/toCasePackage' +import type { Framework } from '@/domain/framework/model/types' +import { hasFrameworkDataChanged } from '@/domain/framework/hasFrameworkDataChanged' +import { withOffCanvasAssociations } from '@/domain/framework/offCanvasAssociations' +import { alignmentMoveCount, type AlignmentStoragePlan } from '@/application/framework/services/AlignmentStorage' +import type { HostedDocumentRef } from '@/domain/framework/externalAlignments' +import { applyInlineAlignmentEdits } from '@/domain/framework/inlineAlignmentEdits' + +type MirrorStatus = { isModifiedFromSource?: boolean; sourcePackageURI?: string } + +type FrameworkEditorProps = { + onBack?: () => void + onSaveToServer?: (cfPackage: ReturnType, framework: Framework, plan?: AlignmentStoragePlan) => Promise + /** Works out which associations a save will move for the framework's alignment storage setting, without saving */ + onPlanAlignmentStorage?: (cfPackage: ReturnType, framework: Framework) => Promise + /** Fetch the published CFPackage from the server (returns CASE JSON with absolute URIs) */ + onFetchCfPackage?: () => Promise + /** All locally-available frameworks — used to populate the crosswalk target selector in tree view */ + availableFrameworks?: HomeFramework[] + /** Server-side framework summaries not yet loaded locally — shown in crosswalk target selector for auto-load */ + serverFrameworks?: Array<{ id: string; title: string }> + /** Load a framework from the server into the local session (called when a server-only crosswalk target is selected) */ + onLoadTargetFramework?: (id: string) => Promise + /** Save a serialized alignment CFPackage to the server */ + onSaveAlignments?: (cfPackage: unknown) => Promise + /** Load existing alignment associations for a target framework pairing */ + onLoadAlignmentsForTarget?: (targetId: string) => Promise<{ + docId: string + associations: Array<{ id: string; fromItemId: string; toItemId: string; toFrameworkId: string; associationType: string; originUri: string; destinationUri: string }> + }> + /** Discover all frameworks that already have saved alignment docs with the given source framework */ + onDiscoverAlignedTargets?: (sourceId: string) => Promise> + /** Resolve item identifiers to the hosted frameworks that hold them — used by the tree view to place inline external alignments */ + onLookupItemDocuments?: (identifiers: string[]) => Promise> + /** Mirror/fork status of the open framework, if it was ever imported */ + mirrorStatus?: MirrorStatus + /** Read-only cached remote framework (CGE cache) */ + readOnly?: boolean + /** Extensions on the open framework's own CFDefinitions object — the editor can't author them, so they're carried through on save */ + cfDefinitionsExtensions?: CaseExtensions + /** The framework as loaded — its associations to nodes outside this framework have no graph edge, so they're carried through on save */ + loadedFramework?: Framework + /** Changes whenever a save moved associations between this framework and its alignment frameworks */ + alignmentsRevision?: number + /** CASE Global search and refresh for the Tree View's target picker */ + cge?: CgeTargetSupport +} + +/** The fork warning's sentence about associations a save will move. */ +function describeAlignmentMove(plan: AlignmentStoragePlan, count: number): string { + const associations = count === 1 ? '1 association' : `${count} associations` + return plan.kind === 'toInline' + ? `${associations} to frameworks on this server will move from alignment frameworks into this framework.` + : `${associations} to frameworks on this server will move from this framework into alignment frameworks.` +} + +/** The framework editor: header, Tree View, item/framework properties, and save. */ +export default function FrameworkEditor({ onBack, onSaveToServer, onPlanAlignmentStorage, onFetchCfPackage, availableFrameworks, serverFrameworks, onLoadTargetFramework, onSaveAlignments, onLoadAlignmentsForTarget, onDiscoverAlignedTargets, onLookupItemDocuments, mirrorStatus, readOnly, cfDefinitionsExtensions, loadedFramework, alignmentsRevision, cge }: Readonly) { + const { status: authStatus, userName, tenantId, signOut, changePassword } = useAuth() + const { + nodes, + edges, + selectedNode, + frameworkInfo, + clearSelection, + updateNodeData, + cfItemTypes, + ensureCfItemType, + cfSubjects, + ensureCfSubject, + cfConcepts, + ensureCfConcept, + cfLicenses, + cfAssociationGroupings, + addItemDialog, + setAddItemDraft, + cancelAddItem, + confirmAddItem, + isDirty, + clearDirty, + caseVersion, + inlineAlignmentEdits, + clearInlineAlignmentEdits, + } = useEditor() + + const [leaveOpen, setLeaveOpen] = useState(false) + const [cfPackageDialogOpen, setCfPackageDialogOpen] = useState(false) + const [generatedCfPackage, setGeneratedCfPackage] = useState(null) + const [viewCaseLoading, setViewCaseLoading] = useState(false) + const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'success' | 'error'>('idle') + const [saveError, setSaveError] = useState(null) + const [forkWarningOpen, setForkWarningOpen] = useState(false) + + // Baseline Framework snapshot for fork-detection — captured once when this + // session's graph first loads, and refreshed after every successful save. + // Only ever needs to change mid-session for a fork itself, and once forked + // mirrorStatus.isModifiedFromSource flips true, permanently disabling the + // gate below — so a single per-mount baseline is sufficient. + const baselineFrameworkRef = useRef(null) + if (baselineFrameworkRef.current === null) { + const baseline = fromEditorGraph({ graph: { nodes, edges } }).framework + baselineFrameworkRef.current = loadedFramework ? withOffCanvasAssociations(loadedFramework, baseline) : baseline + } + const pendingSaveRef = useRef<{ openCasePackage: ReturnType; framework: Framework; plan?: AlignmentStoragePlan } | null>(null) + // What the fork warning says about associations the save will move, if any. + const [forkWarningMove, setForkWarningMove] = useState(null) + + // ── Refs for save/export (keeps callbacks stable, avoids re-renders) ── + const graphRef = useRef({ nodes, edges, inlineAlignmentEdits }) + graphRef.current = { nodes, edges, inlineAlignmentEdits } + const saveCtxRef = useRef({ caseVersion, cfItemTypes, cfSubjects, cfConcepts, cfLicenses, cfAssociationGroupings, cfDefinitionsExtensions, loadedFramework }) + saveCtxRef.current = { caseVersion, cfItemTypes, cfSubjects, cfConcepts, cfLicenses, cfAssociationGroupings, cfDefinitionsExtensions, loadedFramework } + + // Open the CFPackage viewer. Every framework open in the editor has been saved to the + // server, so the server copy (absolute URIs, no OpenCASE extensions) is the export. + const handleViewCFPackage = useCallback(async () => { + if (!onFetchCfPackage) return + setCfPackageDialogOpen(true) + setViewCaseLoading(true) + try { + const pkg = await onFetchCfPackage() + setGeneratedCfPackage(pkg) + } finally { + setViewCaseLoading(false) + } + }, [onFetchCfPackage]) + + // Actually perform the save (network call). Split out from `handleSave` so + // the fork-warning dialog can defer this until the user confirms. + const doSave = useCallback(async (openCasePackage: ReturnType, framework: Framework, plan?: AlignmentStoragePlan) => { + if (onSaveToServer) { + setSaveStatus('saving') + setSaveError(null) + try { + await onSaveToServer(openCasePackage, framework, plan) + baselineFrameworkRef.current = framework + setSaveStatus('success') + clearDirty() + clearInlineAlignmentEdits() + setTimeout(() => setSaveStatus('idle'), 2000) + } catch (err) { + console.error('[Save] Failed to save to server:', err) + setSaveStatus('error') + setSaveError(err instanceof Error ? err.message : 'Failed to save') + } + } else { + setCfPackageDialogOpen(true) + } + }, [onSaveToServer, clearDirty, clearInlineAlignmentEdits]) + + // Save: Generate CFPackage and POST to server — unless this framework is + // still a pristine mirror and the pending edits touch actual framework + // data, in which case warn first: saving will fork it into an independent + // local copy. + const handleSave = useCallback(async () => { + const { nodes: n, edges: e, inlineAlignmentEdits: inlineEdits } = graphRef.current + const ctx = saveCtxRef.current + const fromGraph = fromEditorGraph({ graph: { nodes: n, edges: e } }).framework + const withOffCanvas = ctx.loadedFramework ? withOffCanvasAssociations(ctx.loadedFramework, fromGraph) : fromGraph + // Tree View edits to inline associations to other frameworks live outside the graph. + const framework = applyInlineAlignmentEdits(withOffCanvas, inlineEdits) + const cfPackage = frameworkToCfPackage({ + framework, + caseVersion: ctx.caseVersion, + cfItemTypes: ctx.cfItemTypes, cfSubjects: ctx.cfSubjects, + cfConcepts: ctx.cfConcepts, cfLicenses: ctx.cfLicenses, cfAssociationGroupings: ctx.cfAssociationGroupings, + definitionsExtensions: ctx.cfDefinitionsExtensions, + }) + const openCasePackage = toOpenCaseFormat(cfPackage) + + const baseline = baselineFrameworkRef.current + const isPristineMirror = mirrorStatus?.isModifiedFromSource === false && baseline !== null + const storageChanged = baseline !== null && + (baseline.metadata.alignmentStorage ?? 'inline') !== (framework.metadata.alignmentStorage ?? 'inline') + + // Changing where associations to other frameworks are stored can move some on save, which is a + // data change. Ask the server what would move, so the warning only shows when something does. + let plan: AlignmentStoragePlan | undefined + if (isPristineMirror && storageChanged && onPlanAlignmentStorage) { + try { + plan = await onPlanAlignmentStorage(openCasePackage, framework) + } catch (err) { + setSaveStatus('error') + setSaveError(err instanceof Error ? err.message : 'Failed to save') + return + } + } + const moving = plan ? alignmentMoveCount(plan) : 0 + + if (isPristineMirror && (hasFrameworkDataChanged(baseline, framework) || moving > 0)) { + pendingSaveRef.current = { openCasePackage, framework, plan } + setForkWarningMove(plan && moving > 0 ? describeAlignmentMove(plan, moving) : null) + setForkWarningOpen(true) + return + } + + await doSave(openCasePackage, framework, plan) + }, [mirrorStatus, doSave, onPlanAlignmentStorage]) + + const addItemParentLabel = (() => { + const parent = nodes.find((n) => n.id === addItemDialog.parentId) + if (!parent) return undefined + if (parent.type === 'caseFrameworkNode') return (parent.data as { cfDocument?: CFDocument })?.cfDocument?.title ?? 'Framework' + const cfItem = (parent.data as { cfItem?: CFItem })?.cfItem + return cfItem?.humanCodingScheme ?? cfItem?.abbreviatedStatement ?? cfItem?.fullStatement ?? 'Item' + })() + + return ( +
+ void changePassword() : undefined} + reserveRightForPanel={Boolean(selectedNode)} + isDirty={isDirty} + saveStatus={saveStatus} + saveError={saveError} + onSave={handleSave} + onSignIn={undefined} + onSignOut={ + authStatus !== 'authenticated' + ? undefined + : () => { + void signOut() + } + } + onBack={ + onBack + ? () => { + if (isDirty) setLeaveOpen(true) + else onBack() + } + : undefined + } + /> + +
+ +
+ + + + + + setLeaveOpen(false)} + onLeave={() => { + setLeaveOpen(false) + onBack?.() + }} + /> + + { + setForkWarningOpen(false) + pendingSaveRef.current = null + }} + onConfirm={() => { + setForkWarningOpen(false) + const pending = pendingSaveRef.current + pendingSaveRef.current = null + if (pending) void doSave(pending.openCasePackage, pending.framework, pending.plan) + }} + /> + + { + setCfPackageDialogOpen(false) + setGeneratedCfPackage(null) + }} + cfPackage={generatedCfPackage} + caseVersion={caseVersion} + loading={viewCaseLoading} + /> +
+ ) +} diff --git a/apps/editor/src/ui/editor/components/AddExternalFrameworkDialog.tsx b/apps/editor/src/ui/editor/components/AddExternalFrameworkDialog.tsx deleted file mode 100644 index 3b90c59..0000000 --- a/apps/editor/src/ui/editor/components/AddExternalFrameworkDialog.tsx +++ /dev/null @@ -1,132 +0,0 @@ -import { useState } from 'react' -import { Button } from '@/ui/shared/components/ui/button' -import { Input } from '@/ui/shared/components/ui/input' -import { Label } from '@/ui/shared/components/ui/label' -import { Textarea } from '@/ui/shared/components/ui/textarea' - -export type ExternalFrameworkDraft = { - title: string - uri?: string - description?: string - source?: string -} - -type Props = { - open: boolean - onCancel: () => void - onCreate: (draft: ExternalFrameworkDraft) => void -} - -export default function AddExternalFrameworkDialog({ open, onCancel, onCreate }: Readonly) { - const [draft, setDraft] = useState({ title: '' }) - - const handleCreate = () => { - if (!draft.title.trim()) return - onCreate({ - title: draft.title.trim(), - uri: draft.uri?.trim() || undefined, - description: draft.description?.trim() || undefined, - source: draft.source?.trim() || undefined, - }) - setDraft({ title: '' }) - } - - const handleCancel = () => { - setDraft({ title: '' }) - onCancel() - } - - if (!open) return null - - return ( -
- {/* Backdrop */} -