From 8ce21053c3efb926dd7870ac2526d54dee901116 Mon Sep 17 00:00:00 2001 From: Stan Billiet Date: Mon, 30 Nov 2026 21:19:16 +0100 Subject: [PATCH 1/4] Show self alignments in the Tree View and store new ones inline Associations between two items of the same framework (e.g. precedes or isRelatedTo within it) were never shown: externalAlignmentsOf skips them and the Tree View only draws isChildOf/isPartOf from the editor graph. - selfAlignmentsOf picks them, with the same rules as external alignments. The framework is listed as its own target when it has any. - A drop onto "(this framework)" is stored inline when the framework stores its alignments inline, as CASE 1.1 keeps an association in the document of its origin. With alignment frameworks it still goes to one. - Both helpers take the editor's live items, so items added in this session count as the framework's own. - Inline associations are drawn in teal; the same isRelatedTo link isn't added twice. - Association types follow the CASE 1.1 vocabulary: replacedBy instead of isReplacedBy, plus exemplar, hasSkillLevel and isTranslationOf. --- .../mappers/case/caseToDomainFramework.ts | 4 +- .../framework/externalAlignments.test.ts | 57 +++++++++++ .../domain/framework/externalAlignments.ts | 76 +++++++++++---- .../src/domain/framework/model/types.ts | 6 +- .../TreePanelView.selfAlignments.test.tsx | 95 +++++++++++++++++++ .../src/ui/editor/treePanel/TreePanelView.tsx | 63 +++++++++--- 6 files changed, 266 insertions(+), 35 deletions(-) create mode 100644 apps/editor/src/ui/editor/treePanel/TreePanelView.selfAlignments.test.tsx diff --git a/apps/editor/src/application/framework/mappers/case/caseToDomainFramework.ts b/apps/editor/src/application/framework/mappers/case/caseToDomainFramework.ts index 0b5e4e5..dda6495 100644 --- a/apps/editor/src/application/framework/mappers/case/caseToDomainFramework.ts +++ b/apps/editor/src/application/framework/mappers/case/caseToDomainFramework.ts @@ -25,9 +25,9 @@ function mapAssociationType(rawType?: string): AssociationType { 'ispeerof': 'isPeerOf', 'exactmatchof': 'exactMatchOf', 'replacedby': 'replacedBy', - 'haspart': 'hasPart', 'exemplar': 'exemplar', - 'hasskillevel': 'hasSkillLevel', + 'hasskilllevel': 'hasSkillLevel', + 'istranslationof': 'isTranslationOf', } return knownTypes[t] ?? (rawType as AssociationType) ?? 'isRelatedTo' diff --git a/apps/editor/src/domain/framework/externalAlignments.test.ts b/apps/editor/src/domain/framework/externalAlignments.test.ts index fbb1ac4..e4371ef 100644 --- a/apps/editor/src/domain/framework/externalAlignments.test.ts +++ b/apps/editor/src/domain/framework/externalAlignments.test.ts @@ -4,6 +4,7 @@ import { groupExternalAlignments, hostedLookupCandidates, isRemoteTargetId, + selfAlignmentsOf, type ExternalAlignment, } from './externalAlignments' import type { Association, Framework, Item } from '@/domain/framework/model/types' @@ -106,6 +107,62 @@ describe('externalAlignmentsOf', () => { expect(a.originUri).toBe('https://case.example/CFItems/item-1') expect(a.destinationUri).toBe('urn:case:item:other-item') }) + + it('treats items the caller counts as its own (e.g. added in the editor) as inside the framework', () => { + const fw = framework(items, [ + assoc('to-new', 'item-1', 'new-item'), + assoc('from-new', 'new-item', 'other-item'), + ]) + const isOwnItem = (id: string) => ['item-1', 'item-2', 'new-item'].includes(id) + + expect(externalAlignmentsOf(fw, isOwnItem).map((a) => a.id)).toEqual(['from-new']) + }) +}) + +describe('selfAlignmentsOf', () => { + const items = [item('item-1'), item('item-2'), item('item-3')] + + it('returns non-hierarchical associations between two items of the framework', () => { + const fw = framework(items, [ + assoc('a-1', 'item-1', 'item-2', 'precedes', { destinationTitle: 'Item 2' }), + assoc('a-2', 'item-3', 'item-1', 'isRelatedTo', { destinationTargetType: 'CASE' }), + ]) + + expect(selfAlignmentsOf(fw)).toEqual([ + { + id: 'a-1', + fromItemId: 'item-1', + toItemId: 'item-2', + associationType: 'precedes', + originUri: 'https://case.example/CFItems/item-1', + destinationUri: 'urn:case:item:item-2', + destinationTitle: 'Item 2', + destinationTargetType: undefined, + }, + expect.objectContaining({ id: 'a-2', fromItemId: 'item-3', toItemId: 'item-1' }), + ]) + }) + + it('skips hierarchy, links to itself, the CFDocument, outside nodes and non-CASE targets', () => { + const fw = framework(items, [ + assoc('child', 'item-2', 'item-1', 'isChildOf'), + assoc('part', 'item-3', 'item-1', 'isPartOf'), + assoc('loop', 'item-1', 'item-1'), + assoc('doc', 'item-1', 'doc-1', 'exactMatchOf'), + assoc('outside', 'item-1', 'other-item'), + assoc('incoming', 'other-item', 'item-1'), + assoc('non-case', 'item-1', 'item-2', 'isRelatedTo', { destinationTargetType: 'ext:outcomes' }), + ]) + + expect(selfAlignmentsOf(fw)).toEqual([]) + }) + + it('includes items the caller counts as its own', () => { + const fw = framework(items, [assoc('a-1', 'item-1', 'new-item')]) + + expect(selfAlignmentsOf(fw).map((a) => a.id)).toEqual([]) + expect(selfAlignmentsOf(fw, (id) => id === 'new-item' || fw.items.has(id as ItemId)).map((a) => a.id)).toEqual(['a-1']) + }) }) describe('hostedLookupCandidates', () => { diff --git a/apps/editor/src/domain/framework/externalAlignments.ts b/apps/editor/src/domain/framework/externalAlignments.ts index 93308d3..3f71017 100644 --- a/apps/editor/src/domain/framework/externalAlignments.ts +++ b/apps/editor/src/domain/framework/externalAlignments.ts @@ -1,4 +1,5 @@ -import type { Framework } from '@/domain/framework/model/types' +import type { Association, Framework } from '@/domain/framework/model/types' +import type { ItemId } from '@/domain/shared/types' /** * A non-hierarchical association stored in this framework's own CFPackage @@ -33,6 +34,17 @@ export function isRemoteTargetId(id: string): boolean { return id.startsWith(REMOTE_TARGET_PREFIX) } +/** + * Whether an identifier is one of the framework's own items. Defaults to the + * items of the framework as given; the editor passes its live items, so items + * added in this session count too. + */ +export type IsOwnItem = (identifier: string) => boolean + +function itemsOf(framework: Framework): IsOwnItem { + return (identifier) => framework.items.has(identifier as ItemId) +} + /** * The framework's inline external alignments: non-hierarchical associations * from one of its items to a node that isn't one of its items. @@ -41,36 +53,60 @@ export function isRemoteTargetId(id: string): boolean { * framework's `exactMatchOf` to each subject framework) aren't item-to-item * alignments and are left out. */ -export function externalAlignmentsOf(framework: Framework): ExternalAlignment[] { +export function externalAlignmentsOf(framework: Framework, isOwnItem: IsOwnItem = itemsOf(framework)): ExternalAlignment[] { const frameworkId = String(framework.id) const result: ExternalAlignment[] = [] for (const a of framework.associations.values()) { if (HIERARCHICAL_TYPES.has(a.associationType)) continue - if (!framework.items.has(a.fromItemId)) continue - if (framework.items.has(a.toItemId)) continue - const toItemId = String(a.toItemId) - if (toItemId === frameworkId) continue + if (!isOwnItem(String(a.fromItemId))) continue + if (isOwnItem(String(a.toItemId))) continue + if (String(a.toItemId) === frameworkId) continue - const md = a.metadata ?? {} - const destinationUri = md.destinationUri ?? `urn:case:item:${toItemId}` - if (/\/CFDocuments\//.test(destinationUri)) continue + const alignment = toAlignment(framework, a) + if (/\/CFDocuments\//.test(alignment.destinationUri)) continue + result.push(alignment) + } + return result +} +/** + * The framework's self alignments: non-hierarchical associations from one of + * its items to another of its items (e.g. `precedes` or `isRelatedTo` within + * the framework). CASE 1.1 keeps them in the framework itself, like its inline + * external alignments; the Tree View shows them under the framework as its own + * target. Non-CASE targets aren't items and are left out. + */ +export function selfAlignmentsOf(framework: Framework, isOwnItem: IsOwnItem = itemsOf(framework)): ExternalAlignment[] { + const result: ExternalAlignment[] = [] + for (const a of framework.associations.values()) { + if (HIERARCHICAL_TYPES.has(a.associationType)) continue const fromItemId = String(a.fromItemId) - const itemUri = (framework.items.get(a.fromItemId)?.metadata as Record | undefined)?.caseUri - result.push({ - id: String(a.id), - fromItemId, - toItemId, - associationType: a.associationType, - originUri: md.originUri ?? (typeof itemUri === 'string' ? itemUri : `urn:case:item:${fromItemId}`), - destinationUri, - destinationTitle: md.destinationTitle, - destinationTargetType: md.destinationTargetType, - }) + const toItemId = String(a.toItemId) + if (fromItemId === toItemId || !isOwnItem(fromItemId) || !isOwnItem(toItemId)) continue + const targetType = a.metadata?.destinationTargetType + if (targetType && targetType !== 'CASE') continue + result.push(toAlignment(framework, a)) } return result } +function toAlignment(framework: Framework, a: Association): ExternalAlignment { + const md = a.metadata ?? {} + const fromItemId = String(a.fromItemId) + const toItemId = String(a.toItemId) + const itemUri = (framework.items.get(a.fromItemId)?.metadata as Record | undefined)?.caseUri + return { + id: String(a.id), + fromItemId, + toItemId, + associationType: a.associationType, + originUri: md.originUri ?? (typeof itemUri === 'string' ? itemUri : `urn:case:item:${fromItemId}`), + destinationUri: md.destinationUri ?? `urn:case:item:${toItemId}`, + destinationTitle: md.destinationTitle, + destinationTargetType: md.destinationTargetType, + } +} + /** Destination identifiers worth asking the server about — non-CASE targets can never be hosted. */ export function hostedLookupCandidates(alignments: ExternalAlignment[]): string[] { return [...new Set(alignments.filter((a) => !isNonCaseTarget(a)).map((a) => a.toItemId))] diff --git a/apps/editor/src/domain/framework/model/types.ts b/apps/editor/src/domain/framework/model/types.ts index 69bd085..b0fac0c 100644 --- a/apps/editor/src/domain/framework/model/types.ts +++ b/apps/editor/src/domain/framework/model/types.ts @@ -4,6 +4,7 @@ export type FrameworkStatus = 'Draft' | 'Published' export type ItemType = 'Standard' | 'LearningOutcome' | 'Competency' | 'Skill' +/** The CASE 1.1 association types. */ export type AssociationType = | 'isChildOf' | 'isPartOf' @@ -11,7 +12,10 @@ export type AssociationType = | 'isPeerOf' | 'exactMatchOf' | 'precedes' - | 'isReplacedBy' + | 'replacedBy' + | 'exemplar' + | 'hasSkillLevel' + | 'isTranslationOf' /** * Where a framework stores its associations to other frameworks: in its own diff --git a/apps/editor/src/ui/editor/treePanel/TreePanelView.selfAlignments.test.tsx b/apps/editor/src/ui/editor/treePanel/TreePanelView.selfAlignments.test.tsx new file mode 100644 index 0000000..89bee9f --- /dev/null +++ b/apps/editor/src/ui/editor/treePanel/TreePanelView.selfAlignments.test.tsx @@ -0,0 +1,95 @@ +import { describe, it, expect, beforeAll, vi } from 'vitest' +import '@testing-library/jest-dom' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import TreePanelView from './TreePanelView' +import { EditorProvider, useEditor } from '@/ui/editor/state/EditorContext' +import { toEditorGraph } from '@/ui/editor/state/mapping/toEditorGraph' +import { createHomeFrameworkFromDomain } from '@/ui/home/frameworkStore' +import type { Association, Framework, Item } from '@/domain/framework/model/types' +import type { AssociationId, FrameworkId, ItemId } from '@/domain/shared/types' + +beforeAll(() => { + globalThis.ResizeObserver ??= class { observe() {} unobserve() {} disconnect() {} } as unknown as typeof ResizeObserver +}) + +const item = (id: string, code: string, statement: string): Item => ({ id: id as ItemId, statement, metadata: { humanCodingScheme: code } }) +const assoc = (id: string, from: string, to: string, associationType: Association['associationType']): Association => ({ + id: id as AssociationId, + fromItemId: from as ItemId, + toItemId: to as ItemId, + associationType, +}) + +function makeFramework(alignmentStorage?: 'inline' | 'alignmentFramework'): Framework { + const items = [item('item-1', 'S1.1', 'Describe states of matter'), item('item-2', 'S1.2', 'Explain changes of state'), item('item-3', 'S2.1', 'Identify energy sources')] + return { + id: 'doc-1' as FrameworkId, + metadata: { title: 'Example Science Framework', alignmentStorage }, + items: new Map(items.map((i) => [i.id, i])), + associations: new Map([ + assoc('root-1', 'item-1', 'doc-1', 'isChildOf'), + assoc('root-2', 'item-2', 'doc-1', 'isChildOf'), + assoc('root-3', 'item-3', 'doc-1', 'isChildOf'), + assoc('a-1', 'item-1', 'item-2', 'precedes'), + ].map((a) => [a.id, a])), + status: 'Published', + } +} + +/** Shows the inline alignment edits, so a test can see what a save would store in the framework. */ +function InlineEdits() { + const { inlineAlignmentEdits } = useEditor() + return {inlineAlignmentEdits.added.map((a) => `${a.fromItemId}>${a.toItemId}`).join(',')} +} + +function renderView(framework: Framework, onSaveAlignments = vi.fn()) { + render( + + + + , + ) +} + +const selfTarget = () => screen.getByRole('button', { name: /\(this framework\)/ }) + +function dropOnRightPanel(fromItemId: string, toItemId: string) { + const [, right] = document.querySelectorAll(`[data-item-id="${toItemId}"]`) + const dataTransfer = { getData: () => fromItemId, setData: () => {}, dropEffect: 'copy', effectAllowed: 'copy' } + fireEvent.dragOver(right, { dataTransfer }) + fireEvent.drop(right, { dataTransfer }) +} + +describe('TreePanelView — self alignments', () => { + it('lists the framework as its own target when it has associations between its items', async () => { + renderView(makeFramework()) + + await waitFor(() => expect(selfTarget()).toBeInTheDocument()) + expect(selfTarget()).toHaveTextContent('1') + }) + + it('stores an association dropped onto the framework itself inline', async () => { + const onSaveAlignments = vi.fn() + renderView(makeFramework(), onSaveAlignments) + + await waitFor(() => expect(selfTarget()).toBeInTheDocument()) + fireEvent.click(selfTarget()) + dropOnRightPanel('item-3', 'item-1') + + expect(screen.getByTestId('inline-added')).toHaveTextContent('item-3>item-1') + expect(selfTarget()).toHaveTextContent('2') + expect(screen.queryByRole('button', { name: /save/i })).not.toBeInTheDocument() + }) + + it('keeps using an alignment document when the framework stores its alignments there', async () => { + renderView(makeFramework('alignmentFramework')) + + await waitFor(() => expect(selfTarget()).toBeInTheDocument()) + fireEvent.click(selfTarget()) + dropOnRightPanel('item-3', 'item-1') + + expect(screen.getByTestId('inline-added')).toBeEmptyDOMElement() + expect(screen.getByText('1 association — unsaved')).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument() + }) +}) diff --git a/apps/editor/src/ui/editor/treePanel/TreePanelView.tsx b/apps/editor/src/ui/editor/treePanel/TreePanelView.tsx index f4b4b5c..63da7b0 100644 --- a/apps/editor/src/ui/editor/treePanel/TreePanelView.tsx +++ b/apps/editor/src/ui/editor/treePanel/TreePanelView.tsx @@ -13,6 +13,7 @@ import { groupExternalAlignments, hostedLookupCandidates, isRemoteTargetId, + selfAlignmentsOf, type ExternalAlignmentTarget, type HostedDocumentRef, } from '@/domain/framework/externalAlignments' @@ -50,7 +51,7 @@ const ALIGNMENT_ASSOCIATION_TYPES: Array<{ value: string; label: string }> = [ { value: 'isRelatedTo', label: 'Is Related To' }, { value: 'isPeerOf', label: 'Is Peer Of' }, { value: 'precedes', label: 'Precedes' }, - { value: 'isReplacedBy', label: 'Is Replaced By' }, + { value: 'replacedBy', label: 'Replaced By' }, ] type LineCoord = { @@ -255,6 +256,14 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor const activeFrameworkId = frameworkNodeId + // This framework's items as the editor has them, so items added in this session count as its own. + // Keyed on the identifiers alone: editing an item's text doesn't change which items there are. + const ownItemIdsKey = useMemo(() => cfItems.map((i) => i.identifier).join('\n'), [cfItems]) + const isOwnItem = useMemo(() => { + const ids = new Set(ownItemIdsKey ? ownItemIdsKey.split('\n') : []) + return (id: string) => ids.has(id) + }, [ownItemIdsKey]) + // ── Core state ── const [targets, setTargets] = useState([]) const [expandedTargetId, setExpandedTargetId] = useState(null) @@ -267,10 +276,22 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor const lookedUpIdsRef = useRef>(new Set()) // Bumped when a framework arrives on the server, so remembered misses are looked up again. const [hostedLookupRevision, setHostedLookupRevision] = useState(0) + // Self alignments: associations between two of this framework's own items, stored in it like + // its inline external alignments. They're shown under the framework itself as the target. + const selfAssociations = useMemo( + () => (editedFramework && activeFrameworkId + ? selfAlignmentsOf(editedFramework, isOwnItem).map((a) => ({ ...a, toFrameworkId: activeFrameworkId, inline: true })) + : []), + [editedFramework, activeFrameworkId, isOwnItem], + ) const inlineAssociations = useMemo( - () => externalTargets.flatMap((t) => t.alignments.map((a) => ({ ...a, toFrameworkId: t.id, inline: true }))), - [externalTargets], + () => [ + ...externalTargets.flatMap((t) => t.alignments.map((a) => ({ ...a, toFrameworkId: t.id, inline: true }))), + ...selfAssociations, + ], + [externalTargets, selfAssociations], ) + const inlineAssociationIds = useMemo(() => new Set(inlineAssociations.map((a) => a.id)), [inlineAssociations]) // Everything drawn in the panel: alignment-document associations and inline ones. const shownAssociations = useMemo( () => (inlineAssociations.length > 0 ? [...pendingAssociations, ...inlineAssociations] : pendingAssociations), @@ -633,7 +654,7 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor // says which hosted framework holds each destination; everything else is remote. Each hosted // framework and remote source joins the target list. useEffect(() => { - const alignments = editedFramework ? externalAlignmentsOf(editedFramework) : [] + const alignments = editedFramework ? externalAlignmentsOf(editedFramework, isOwnItem) : [] if (alignments.length === 0) { setExternalTargets([]) return @@ -672,7 +693,16 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor }) } return () => { cancelled = true } - }, [editedFramework, onLookupItemDocuments, hostedLookupRevision]) + }, [editedFramework, isOwnItem, onLookupItemDocuments, hostedLookupRevision]) + + // A framework with self alignments is its own target, like the frameworks its inline alignments point into. + const hasSelfAssociations = selfAssociations.length > 0 + useEffect(() => { + if (!hasSelfAssociations || !activeFrameworkId) return + setTargets((prev) => (prev.some((t) => t.id === activeFrameworkId) + ? prev + : [...prev, { id: activeFrameworkId, alignmentDocId: globalThis.crypto?.randomUUID?.() ?? `align-${Date.now()}-${activeFrameworkId}`, hasUnsavedChanges: false }])) + }, [hasSelfAssociations, activeFrameworkId]) // When expanding a pre-populated target whose framework data isn't loaded yet, fetch it useEffect(() => { @@ -760,15 +790,22 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor const originUri = fromCfItem?.uri ?? `urn:case:item:${fromItemId}` const destinationUri = toCfItem?.uri ?? `urn:case:item:${toItemId}` - // Inline: the association is stored in this framework and saved with it. Self alignments - // aren't associations to another framework and keep going to an alignment document. - if (expandedTargetId !== activeFrameworkId && (storesInline || isRemoteTargetId(expandedTargetId))) { + // Inline: the association is stored in this framework and saved with it — as CASE 1.1 stores an + // association, in the document of its origin. That includes self alignments. + if (storesInline || isRemoteTargetId(expandedTargetId)) { + // The same link already stored here isn't added twice. + const isDuplicate = inlineAssociations.some((a) => + a.toFrameworkId === expandedTargetId && a.fromItemId === fromItemId && a.toItemId === toItemId && a.associationType === 'isRelatedTo') + if (isDuplicate) { + setDragOverItemId(null) + return + } // A remote destination keeps what's known about it from the associations already pointing there. const known = inlineAssociations.find((a) => a.toItemId === toItemId) const knownMetadata = known ? editedFramework?.associations.get(known.id as AssociationId)?.metadata : undefined - if (!isRemoteTargetId(expandedTargetId)) { + if (!isRemoteTargetId(expandedTargetId) && expandedTargetId !== activeFrameworkId) { hostedDocumentsRef.current = { ...hostedDocumentsRef.current, [toItemId]: { identifier: expandedTargetId, title: targetTitle(expandedTargetId) }, @@ -1046,6 +1083,8 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor > {lineCoords.map((line) => { const isHovered = hoveredLineId === line.id + // Teal for associations stored in this framework, purple for those in an alignment document. + const isInline = inlineAssociationIds.has(line.id) return ( {/* Transparent hit area — solid lines collapse one level, dashed lines expand to reveal items */} @@ -1065,7 +1104,7 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor {/* Visible stroke: solid when both items are visible, dashed when proxied via ancestor */} - {assoc.inline && !storesInline && !isRemoteTargetId(assoc.toFrameworkId) ? ( + {assoc.inline && !storesInline && !isRemoteTargetId(assoc.toFrameworkId) && assoc.toFrameworkId !== activeFrameworkId ? ( {label} - {(!assoc.inline || storesInline || isRemoteTargetId(assoc.toFrameworkId)) && ( + {(!assoc.inline || storesInline || isRemoteTargetId(assoc.toFrameworkId) || assoc.toFrameworkId === activeFrameworkId) && (