diff --git a/apps/editor/docs/associations.md b/apps/editor/docs/associations.md index 8517b61..75b0c4d 100644 --- a/apps/editor/docs/associations.md +++ b/apps/editor/docs/associations.md @@ -13,7 +13,7 @@ How the editor and server handle a framework's associations: what gets imported, | **Owner** (source) | The framework whose associations an alignment framework holds. An alignment framework always belongs to exactly one owner. | | **External association** | An association from one of a framework's items to a node in a *different* framework. It can be stored inline or in an alignment framework. | | **Hosted** / **remote** | Whether the framework an association points into is on this OpenCASE server (hosted) or not (remote). This is about where the destination lives, not where the association is stored. | -| **Self alignment** | An association between two items of the *same* framework that the author drew in the Tree View (not `isChildOf`). | +| **Self alignment** | A non-hierarchical association between two items of the *same* framework (not `isChildOf` or `isPartOf`), such as `precedes` from one item to another. | | **Structure** | The `isChildOf` associations that make up a framework's tree. They are always inline and are never treated as alignments. | "Inline / alignment framework" describes **where an association is stored**. "Hosted / remote" describes **where its destination lives**. The two are independent: an inline association can point at a hosted or a remote framework. @@ -121,6 +121,12 @@ The right-hand panel lists **Associated Frameworks**. Each entry is a target the The view also applies the edits made in this session (`applyInlineAlignmentEdits`), so it shows the associations as they'll be saved. +### Self alignments + +`selfAlignmentsOf(framework)` picks the inline associations between two of the framework's own items, with the same rules (no `isChildOf`/`isPartOf`, no links to a CFDocument, no non-CASE targets). When there are any, the framework is listed as its own target, ` (this framework)`, and the associations are drawn between the left and right copies of its tree. The Tree View passes the editor's live items to both helpers, so an item added in this session counts as one of the framework's own. + +Inline associations are drawn in teal, associations in an alignment framework in purple. + ### Hosted or remote The URI can't tell us: imported associations keep their source's URIs (e.g. `https://case.example.org/…`) even when the target framework has been imported here too. Instead the editor asks the server: @@ -135,7 +141,7 @@ On opening, `handleDiscoverAlignedTargets` lists the alignment frameworks that i ## Authoring in the Tree View -The author expands a target and drags an item from the left panel onto an item on the right. The association type defaults to `isRelatedTo`. The badge popover lets the author change the type (Exact Match Of, Is Related To, Is Peer Of, Precedes, Is Replaced By) or remove the association. `isChildOf` can't be authored here, so it never ends up in an alignment framework. +The author expands a target and drags an item from the left panel onto an item on the right. The association type defaults to `isRelatedTo`. The badge popover lets the author change the type (Exact Match Of, Is Related To, Is Peer Of, Precedes, Replaced By) or remove the association. `isChildOf` can't be authored here, so it never ends up in an alignment framework. Where the new association goes: @@ -143,13 +149,27 @@ Where the new association goes: |---|---|---| | Hosted framework | Inline | That target's alignment framework | | Remote | Inline | Inline | -| This framework (self) | Alignment framework | Alignment framework | +| This framework (self) | Inline | Alignment framework | **Inline** associations are kept in `editorReducer` as `InlineAlignmentEdits` (`added`, `removedIds`, `typeChanges`). They mark the framework dirty, are applied to it when it's saved, and are cleared after a successful save. Every edit is idempotent, so applying it to a framework that already has it changes nothing. **Alignment framework** associations are saved separately, with the target's own **Save** button in the Associated Frameworks list. `buildAlignmentFrameworkPackage` writes the alignment framework, owned by this framework. If the last association is removed, the alignment framework is deleted. -Inline associations to hosted frameworks are read-only while the setting is `alignmentFramework`. That only happens between switching the setting and saving, after which they've moved. +Inline associations to hosted frameworks are read-only while the setting is `alignmentFramework`. That only happens between switching the setting and saving, after which they've moved. Inline self alignments stay editable: saving never moves them. + +The same link (same items, type `isRelatedTo`) isn't added twice when it's dropped again. + +## Authoring in the item panel + +An item's properties panel has an **Associations** section (`ItemAssociationsSection`, from `itemAssociationsOf` in `src/domain/framework/itemAssociations.ts`): + +- **Outgoing:** the item's non-hierarchical associations, to an item of this framework, an item of another framework, or a non-CASE target (`targetType: "ext:…"`). The author can change their type or remove them. Associations to other frameworks are read-only while the setting is `alignmentFramework`, as in the Tree View. +- **Incoming:** associations from other items of this framework to this one, read-only. They're edited on the item they start from, which is one click away. +- **Add association:** a type from the CASE 1.1 vocabulary (without `isChildOf`/`isPartOf`) and a destination in this framework, in another framework, or a non-CASE target with an identifier, URI, optional title and a `targetType` that follows the CASE 1.1 pattern `ext:<name>`. An association that the item already has is refused. + +Everything is stored inline through the same `InlineAlignmentEdits` as the Tree View, so it's saved with the framework, as CASE 1.1 stores an association in the document of its origin. The section is read-only for a read-only framework. + +With the setting `alignmentFramework`, the section only shows what's stored in the framework itself, and the form only offers a non-CASE target (those are always inline). Associations to items on this server, this framework's own included, are added in the Tree View, which puts them in the alignment frameworks. --- @@ -204,7 +224,8 @@ Associations interact with forking in four ways: | Import (inline setting, `ext:opencase`) | `apps/opencase/src/application/case/endpoints/ImportFramework.ts` | | Hosted lookup endpoint | `apps/opencase/src/application/case/endpoints/LookupItemDocuments.ts`, `CFItemsManagementController.lookupDocuments` | | Fork identifiers and data-change detection (server) | `apps/opencase/src/application/case/services/mirrorFork.ts`, `CreateFramework.ts` | -| Inline external associations, hosted/remote grouping | `src/domain/framework/externalAlignments.ts` | +| Inline external associations and self alignments, hosted/remote grouping | `src/domain/framework/externalAlignments.ts` | +| An item's associations (item panel) | `src/domain/framework/itemAssociations.ts`, `src/ui/editor/components/ItemAssociationsSection.tsx` | | 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` | 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/application/framework/services/AlignmentStorage.test.ts b/apps/editor/src/application/framework/services/AlignmentStorage.test.ts index a239412..7e3e25d 100644 --- a/apps/editor/src/application/framework/services/AlignmentStorage.test.ts +++ b/apps/editor/src/application/framework/services/AlignmentStorage.test.ts @@ -109,6 +109,21 @@ describe('saveWithAlignmentStorage', () => { expect(associationIds(af)).toEqual(['to-math']) }) + it('keeps self alignments in the framework when the others move into alignment frameworks', async () => { + const withinScience: CFAssociation = { + ...toMath, + identifier: 'within', + destinationNodeURI: { title: 'SCI.2', identifier: 'sci-2', uri: '/ims/case/v1p1/CFItems/sci-2' }, + } + const framework = science('alignmentFramework', [toMath, withinScience]) + framework.items.set('sci-2' as ItemId, { id: 'sci-2' as ItemId, statement: 'SCI.2' }) + const { port, stored, saveFramework } = fakeServer([toMath, withinScience]) + await saveWithAlignmentStorage({ framework, cfPackage: { CFAssociations: [toMath, withinScience] }, saveFramework, port }) + + expect(associationIds(stored.get('doc-sci'))).toEqual(['within']) + expect(associationIds(stored.get('af-new-1'))).toEqual(['to-math']) + }) + it('adds to the alignment framework it already owns for that target', async () => { const earlier = { ...toMath, identifier: 'earlier' } const { port, stored, saveFramework } = fakeServer([toMath], [alignmentFramework('doc-math', [earlier])]) 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<string, unknown> | 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<string, unknown> | 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/itemAssociations.test.ts b/apps/editor/src/domain/framework/itemAssociations.test.ts new file mode 100644 index 0000000..9ce3029 --- /dev/null +++ b/apps/editor/src/domain/framework/itemAssociations.test.ts @@ -0,0 +1,132 @@ +import { describe, it, expect } from 'vitest' +import { associationCountsByItem, hasItemAssociation, isNonCaseTargetType, itemAssociationsOf, newItemAssociation } from './itemAssociations' +import type { Association, Framework, Item } from '@/domain/framework/model/types' +import type { AssociationId, FrameworkId, ItemId } from '@/domain/shared/types' + +const item = (id: string): Item => ({ id: id as ItemId, statement: id }) +const assoc = (id: string, from: string, to: string, associationType: Association['associationType'] = 'isRelatedTo', metadata?: Association['metadata']): Association => ({ + id: id as AssociationId, + fromItemId: from as ItemId, + toItemId: to as ItemId, + associationType, + metadata, +}) +const framework = (associations: Association[]): Framework => ({ + id: 'doc-1' as FrameworkId, + metadata: { title: 'Doc' }, + items: new Map([item('item-1'), item('item-2'), item('item-3')].map((i) => [i.id, i])), + associations: new Map(associations.map((a) => [a.id, a])), + status: 'Published', +}) + +describe('itemAssociationsOf', () => { + it('splits an item\'s associations into outgoing and incoming, with where the other end is', () => { + const fw = framework([ + assoc('self', 'item-1', 'item-2', 'precedes'), + assoc('other', 'item-1', 'other-item', 'exactMatchOf', { destinationUri: 'https://case.example/CFItems/other-item', destinationTitle: 'Other' }), + assoc('non-case', 'item-1', 'LO-3.1', 'isRelatedTo', { destinationUri: 'https://goals.example.org/LO-3.1', destinationTargetType: 'ext:outcomes' }), + assoc('in', 'item-3', 'item-1', 'isRelatedTo', { originTitle: 'Item 3' }), + ]) + + const { outgoing, incoming } = itemAssociationsOf(fw, 'item-1') + + expect(outgoing).toEqual([ + { id: 'self', associationType: 'precedes', otherId: 'item-2', otherUri: undefined, otherTitle: undefined, otherKind: 'self' }, + { id: 'other', associationType: 'exactMatchOf', otherId: 'other-item', otherUri: 'https://case.example/CFItems/other-item', otherTitle: 'Other', otherKind: 'otherFramework' }, + { id: 'non-case', associationType: 'isRelatedTo', otherId: 'LO-3.1', otherUri: 'https://goals.example.org/LO-3.1', otherTitle: undefined, otherKind: 'nonCase', targetType: 'ext:outcomes' }, + ]) + expect(incoming).toEqual([ + { id: 'in', associationType: 'isRelatedTo', otherId: 'item-3', otherUri: undefined, otherTitle: 'Item 3', otherKind: 'self' }, + ]) + }) + + it('leaves out hierarchy, links to its own CFDocument and incoming links from outside the framework', () => { + const fw = framework([ + assoc('child', 'item-1', 'item-2', 'isChildOf'), + assoc('part', 'item-1', 'item-3', 'isPartOf'), + assoc('root', 'item-1', 'doc-1', 'exactMatchOf'), + assoc('from-outside', 'other-item', 'item-1'), + ]) + + expect(itemAssociationsOf(fw, 'item-1')).toEqual({ outgoing: [], incoming: [] }) + }) + + it('counts items the caller says are the framework\'s own (e.g. added in the editor) as self', () => { + const fw = framework([assoc('a-1', 'item-1', 'new-item')]) + + const { outgoing } = itemAssociationsOf(fw, 'item-1', (id) => id === 'new-item' || fw.items.has(id as ItemId)) + expect(outgoing.map((a) => a.otherKind)).toEqual(['self']) + }) +}) + +describe('associationCountsByItem', () => { + it('counts each association at both ends that are items of the framework', () => { + const fw = framework([ + assoc('self', 'item-1', 'item-2', 'precedes'), + assoc('other', 'item-1', 'other-item', 'exactMatchOf'), + assoc('non-case', 'item-3', 'LO-3.1', 'isRelatedTo', { destinationTargetType: 'ext:outcomes' }), + assoc('child', 'item-2', 'item-1', 'isChildOf'), + assoc('root', 'item-1', 'doc-1', 'isChildOf'), + assoc('to-doc', 'item-3', 'doc-1', 'exactMatchOf'), + ]) + + expect(Object.fromEntries(associationCountsByItem(fw))).toEqual({ 'item-1': 2, 'item-2': 1, 'item-3': 1 }) + }) +}) + +describe('hasItemAssociation', () => { + it('matches origin, destination and type', () => { + const fw = framework([assoc('a-1', 'item-1', 'item-2', 'precedes')]) + + expect(hasItemAssociation(fw, 'item-1', 'item-2', 'precedes')).toBe(true) + expect(hasItemAssociation(fw, 'item-1', 'item-2', 'isRelatedTo')).toBe(false) + expect(hasItemAssociation(fw, 'item-2', 'item-1', 'precedes')).toBe(false) + }) +}) + +describe('newItemAssociation', () => { + it('stores the node URIs, title and a non-CASE targetType', () => { + const a = newItemAssociation({ + id: 'a-1', + fromItemId: 'item-1', + originUri: 'https://case.example/CFItems/item-1', + associationType: 'isRelatedTo', + destination: { identifier: 'LO-3.1', uri: 'https://goals.example.org/LO-3.1', title: 'Learning outcome 3.1', targetType: 'ext:outcomes' }, + }) + + expect(a).toEqual({ + id: 'a-1', + fromItemId: 'item-1', + toItemId: 'LO-3.1', + associationType: 'isRelatedTo', + metadata: { + originUri: 'https://case.example/CFItems/item-1', + destinationUri: 'https://goals.example.org/LO-3.1', + destinationTitle: 'Learning outcome 3.1', + destinationTargetType: 'ext:outcomes', + }, + }) + }) + + it('leaves out title and targetType when there are none', () => { + const a = newItemAssociation({ + id: 'a-1', + fromItemId: 'item-1', + originUri: 'urn:case:item:item-1', + associationType: 'precedes', + destination: { identifier: 'item-2', uri: 'urn:case:item:item-2' }, + }) + + expect(a.metadata).toEqual({ originUri: 'urn:case:item:item-1', destinationUri: 'urn:case:item:item-2' }) + }) +}) + +describe('isNonCaseTargetType', () => { + it('follows the CASE 1.1 pattern for extended target types', () => { + expect(isNonCaseTargetType('ext:outcomes')).toBe(true) + expect(isNonCaseTargetType('ext:learning-goals.v2')).toBe(true) + expect(isNonCaseTargetType('CASE')).toBe(false) + expect(isNonCaseTargetType('ext:')).toBe(false) + expect(isNonCaseTargetType('outcomes')).toBe(false) + }) +}) diff --git a/apps/editor/src/domain/framework/itemAssociations.ts b/apps/editor/src/domain/framework/itemAssociations.ts new file mode 100644 index 0000000..cad480f --- /dev/null +++ b/apps/editor/src/domain/framework/itemAssociations.ts @@ -0,0 +1,158 @@ +import type { Association, AssociationType, Framework } from '@/domain/framework/model/types' +import type { AssociationId, ItemId } from '@/domain/shared/types' +import type { IsOwnItem } from '@/domain/framework/externalAlignments' + +const HIERARCHICAL_TYPES = new Set(['isChildOf', 'isPartOf']) + +/** + * Association types an author can pick for a relation from an item. The CASE 1.1 + * vocabulary without the hierarchical types, which the tree itself expresses. + */ +export const ITEM_ASSOCIATION_TYPES: ReadonlyArray<{ value: string; label: string }> = [ + { value: 'isRelatedTo', label: 'Is Related To' }, + { value: 'exactMatchOf', label: 'Exact Match Of' }, + { value: 'isPeerOf', label: 'Is Peer Of' }, + { value: 'precedes', label: 'Precedes' }, + { value: 'replacedBy', label: 'Replaced By' }, + { value: 'exemplar', label: 'Exemplar' }, + { value: 'hasSkillLevel', label: 'Has Skill Level' }, + { value: 'isTranslationOf', label: 'Is Translation Of' }, +] + +/** CASE 1.1 `targetType` of a non-CASE node: `ext:` followed by a name. */ +const NON_CASE_TARGET_TYPE = /^ext:[A-Za-z0-9._|-]+$/ + +export function isNonCaseTargetType(value: string): boolean { + return NON_CASE_TARGET_TYPE.test(value) +} + +/** Where the other end of an item's association is. */ +export type AssociationEndKind = 'self' | 'otherFramework' | 'nonCase' + +/** One of an item's associations, seen from the item. */ +export type ItemAssociation = { + id: string + associationType: string + /** The other end: the destination of an outgoing association, the origin of an incoming one. */ + otherId: string + otherUri?: string + /** Title stored on the association for the other end. */ + otherTitle?: string + otherKind: AssociationEndKind + /** CASE 1.1 targetType of a non-CASE destination. */ + targetType?: string +} + +/** + * An item's non-hierarchical associations in its framework: the ones it is the + * origin of, which are stored with it and edited from it, and the ones from + * other items of the framework that point at it. + */ +export function itemAssociationsOf( + framework: Framework, + itemId: string, + isOwnItem: IsOwnItem = (id) => framework.items.has(id as ItemId), +): { outgoing: ItemAssociation[]; incoming: ItemAssociation[] } { + const frameworkId = String(framework.id) + const outgoing: ItemAssociation[] = [] + const incoming: ItemAssociation[] = [] + for (const a of framework.associations.values()) { + if (HIERARCHICAL_TYPES.has(a.associationType)) continue + const fromItemId = String(a.fromItemId) + const toItemId = String(a.toItemId) + if (fromItemId === toItemId) continue + const md = a.metadata ?? {} + + if (fromItemId === itemId && toItemId !== frameworkId) { + const targetType = md.destinationTargetType + const isNonCase = Boolean(targetType) && targetType !== 'CASE' + outgoing.push({ + id: String(a.id), + associationType: a.associationType, + otherId: toItemId, + otherUri: md.destinationUri, + otherTitle: md.destinationTitle, + otherKind: isNonCase ? 'nonCase' : isOwnItem(toItemId) ? 'self' : 'otherFramework', + ...(isNonCase ? { targetType } : {}), + }) + } else if (toItemId === itemId && isOwnItem(fromItemId)) { + incoming.push({ + id: String(a.id), + associationType: a.associationType, + otherId: fromItemId, + otherUri: md.originUri, + otherTitle: md.originTitle, + otherKind: 'self', + }) + } + } + return { outgoing, incoming } +} + +/** + * How many non-hierarchical associations each of the framework's items takes + * part in, at either end: the ones it starts and the ones from its other items + * that point at it. Links to its own CFDocument don't count. + */ +export function associationCountsByItem( + framework: Framework, + isOwnItem: IsOwnItem = (id) => framework.items.has(id as ItemId), +): Map<string, number> { + const frameworkId = String(framework.id) + const counts = new Map<string, number>() + const add = (id: string) => counts.set(id, (counts.get(id) ?? 0) + 1) + for (const a of framework.associations.values()) { + if (HIERARCHICAL_TYPES.has(a.associationType)) continue + const fromItemId = String(a.fromItemId) + const toItemId = String(a.toItemId) + if (fromItemId === toItemId || toItemId === frameworkId) continue + if (isOwnItem(fromItemId)) add(fromItemId) + if (isOwnItem(toItemId)) add(toItemId) + } + return counts +} + +/** True if the item already has this association to this destination. */ +export function hasItemAssociation( + framework: Framework, + fromItemId: string, + toItemId: string, + associationType: string, +): boolean { + for (const a of framework.associations.values()) { + if (String(a.fromItemId) === fromItemId && String(a.toItemId) === toItemId && a.associationType === associationType) return true + } + return false +} + +/** The node an author picked as the destination of a new association. */ +export type AssociationDestination = { + identifier: string + uri: string + title?: string + /** CASE 1.1 targetType; left out for CASE items. */ + targetType?: string +} + +/** A new association from one of the framework's items, as it's stored in the framework. */ +export function newItemAssociation(params: { + id: string + fromItemId: string + originUri: string + associationType: string + destination: AssociationDestination +}): Association { + const { id, fromItemId, originUri, associationType, destination } = params + return { + id: id as AssociationId, + fromItemId: fromItemId as ItemId, + toItemId: destination.identifier as ItemId, + associationType: associationType as AssociationType, + metadata: { + originUri, + destinationUri: destination.uri, + ...(destination.title ? { destinationTitle: destination.title.slice(0, 200) } : {}), + ...(destination.targetType ? { destinationTargetType: destination.targetType } : {}), + }, + } +} 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/FrameworkEditor.tsx b/apps/editor/src/ui/editor/FrameworkEditor.tsx index b12cbfd..c954ab1 100644 --- a/apps/editor/src/ui/editor/FrameworkEditor.tsx +++ b/apps/editor/src/ui/editor/FrameworkEditor.tsx @@ -1,4 +1,4 @@ -import { useCallback, useRef, useState } from 'react' +import { useCallback, useMemo, 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' @@ -6,6 +6,7 @@ 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 type { ItemAssociationsSupport } from '@/ui/editor/components/ItemAssociationsSection' import { useEditor } from '@/ui/editor/state/EditorContext' import type { CaseExtensions, CFDocument, CFItem, CFPackage } from '@/domain/case/types' import type { HomeFramework } from '@/ui/home/frameworkStore' @@ -118,6 +119,12 @@ export default function FrameworkEditor({ onBack, onSaveToServer, onPlanAlignmen // What the fork warning says about associations the save will move, if any. const [forkWarningMove, setForkWarningMove] = useState<string | null>(null) + // Memoized so the item panel (React.memo) doesn't re-render for it. + const itemAssociations = useMemo<ItemAssociationsSupport>( + () => ({ loadedFramework, availableFrameworks, serverFrameworks, onLoadTargetFramework, readOnly }), + [loadedFramework, availableFrameworks, serverFrameworks, onLoadTargetFramework, readOnly], + ) + // ── Refs for save/export (keeps callbacks stable, avoids re-renders) ── const graphRef = useRef({ nodes, edges, inlineAlignmentEdits }) graphRef.current = { nodes, edges, inlineAlignmentEdits } @@ -283,6 +290,7 @@ export default function FrameworkEditor({ onBack, onSaveToServer, onPlanAlignmen ensureCfSubject={ensureCfSubject} cfConcepts={cfConcepts} ensureCfConcept={ensureCfConcept} + associations={itemAssociations} /> <AddItemDialog diff --git a/apps/editor/src/ui/editor/components/ItemAssociationsSection.test.tsx b/apps/editor/src/ui/editor/components/ItemAssociationsSection.test.tsx new file mode 100644 index 0000000..3ab3d2b --- /dev/null +++ b/apps/editor/src/ui/editor/components/ItemAssociationsSection.test.tsx @@ -0,0 +1,130 @@ +import { describe, it, expect } from 'vitest' +import '@testing-library/jest-dom' +import { render, screen, fireEvent, within } from '@testing-library/react' +import ItemAssociationsSection from './ItemAssociationsSection' +import { EditorProvider } from '@/ui/editor/state/EditorContext' +import { toEditorGraph } from '@/ui/editor/state/mapping/toEditorGraph' +import type { Association, Framework, Item } from '@/domain/framework/model/types' +import type { AssociationId, FrameworkId, ItemId } from '@/domain/shared/types' + +const item = (id: string, code: string, statement: string): Item => ({ + id: id as ItemId, + statement, + metadata: { humanCodingScheme: code, caseUri: `https://case.example/ims/case/v1p1/CFItems/${id}` }, +}) +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'), + assoc('a-2', 'item-3', 'item-1', 'isRelatedTo'), + ].map((a) => [a.id, a])), + status: 'Published', + } +} + +function renderSection(readOnly = false, alignmentStorage?: 'inline' | 'alignmentFramework') { + const framework = makeFramework(alignmentStorage) + return render( + <EditorProvider initialGraph={toEditorGraph({ framework })} graphKey="doc-1"> + <ItemAssociationsSection itemId="item-1" loadedFramework={framework} readOnly={readOnly} /> + </EditorProvider>, + ) +} + +const outgoing = () => screen.getByRole('list', { name: 'Outgoing associations' }) + +describe('ItemAssociationsSection', () => { + it('lists the item\'s associations within the framework, outgoing and incoming', () => { + renderSection() + + const row = within(outgoing()).getByText('Explain changes of state').closest('li')! + expect(within(row).getByLabelText('Association type')).toHaveValue('precedes') + expect(within(row).getByText('This framework')).toBeInTheDocument() + + const incoming = screen.getByRole('list', { name: 'Incoming associations' }) + expect(within(incoming).getByText('Identify energy sources')).toBeInTheDocument() + }) + + it('adds an association to another item of the framework, once', () => { + renderSection() + + fireEvent.change(screen.getByLabelText('Association type for the new association'), { target: { value: 'isPeerOf' } }) + fireEvent.change(screen.getByLabelText('Search items'), { target: { value: 'energy' } }) + fireEvent.click(within(screen.getByRole('listbox', { name: 'Items' })).getByText('Identify energy sources')) + fireEvent.click(screen.getByRole('button', { name: 'Add association' })) + + const row = within(outgoing()).getByText('Identify energy sources').closest('li')! + expect(within(row).getByLabelText('Association type')).toHaveValue('isPeerOf') + + fireEvent.change(screen.getByLabelText('Association type for the new association'), { target: { value: 'isPeerOf' } }) + fireEvent.change(screen.getByLabelText('Search items'), { target: { value: 'energy' } }) + fireEvent.click(within(screen.getByRole('listbox', { name: 'Items' })).getByText('Identify energy sources')) + fireEvent.click(screen.getByRole('button', { name: 'Add association' })) + expect(screen.getByText('This item already has that association.')).toBeInTheDocument() + }) + + it('adds a non-CASE target once its target type follows the CASE 1.1 pattern', () => { + renderSection() + + fireEvent.click(screen.getByRole('tab', { name: 'Non-CASE target' })) + fireEvent.change(screen.getByLabelText('Identifier'), { target: { value: 'LO-3.1.2' } }) + fireEvent.change(screen.getByLabelText('URI'), { target: { value: 'https://goals.example.org/LO-3.1.2' } }) + fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Learning outcome 3.1.2' } }) + fireEvent.change(screen.getByLabelText('Target type'), { target: { value: 'outcomes' } }) + fireEvent.click(screen.getByRole('button', { name: 'Add association' })) + expect(screen.getByText(/The target type starts with "ext:"/)).toBeInTheDocument() + + fireEvent.change(screen.getByLabelText('Target type'), { target: { value: 'ext:outcomes' } }) + fireEvent.click(screen.getByRole('button', { name: 'Add association' })) + + const row = within(outgoing()).getByText('Learning outcome 3.1.2').closest('li')! + expect(within(row).getByText('LO-3.1.2')).toBeInTheDocument() + expect(within(row).getByText('ext:outcomes')).toBeInTheDocument() + }) + + it('removes an association', () => { + renderSection() + + const row = within(outgoing()).getByText('Explain changes of state').closest('li')! + fireEvent.click(within(row).getByRole('button', { name: 'Remove association' })) + + expect(screen.queryByRole('list', { name: 'Outgoing associations' })).not.toBeInTheDocument() + expect(screen.getByText('No associations from this item yet.')).toBeInTheDocument() + }) + + it('with alignment frameworks, adds only non-CASE targets and keeps self alignments editable', () => { + renderSection(false, 'alignmentFramework') + + expect(screen.getAllByRole('tab').map((t) => t.textContent)).toEqual(['Non-CASE target']) + expect(screen.getByLabelText('Identifier')).toBeInTheDocument() + expect(screen.getByText(/Those are shown and added in the Tree View/)).toBeInTheDocument() + const row = within(outgoing()).getByText('Explain changes of state').closest('li')! + expect(within(row).getByRole('button', { name: 'Remove association' })).toBeInTheDocument() + }) + + it('only shows associations for a read-only framework', () => { + renderSection(true) + + expect(within(outgoing()).getByText('Explain changes of state')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Remove association' })).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Add association' })).not.toBeInTheDocument() + }) +}) diff --git a/apps/editor/src/ui/editor/components/ItemAssociationsSection.tsx b/apps/editor/src/ui/editor/components/ItemAssociationsSection.tsx new file mode 100644 index 0000000..97257da --- /dev/null +++ b/apps/editor/src/ui/editor/components/ItemAssociationsSection.tsx @@ -0,0 +1,418 @@ +import { useMemo, useState } from 'react' +import { X } from 'lucide-react' +import { Button } from '@/ui/shared/components/ui/button' +import { useEditor } from '@/ui/editor/state/EditorContext' +import type { Framework } from '@/domain/framework/model/types' +import type { HomeFramework } from '@/ui/home/frameworkStore' +import { applyInlineAlignmentEdits } from '@/domain/framework/inlineAlignmentEdits' +import { + ITEM_ASSOCIATION_TYPES, + hasItemAssociation, + isNonCaseTargetType, + itemAssociationsOf, + newItemAssociation, + type AssociationDestination, + type ItemAssociation, +} from '@/domain/framework/itemAssociations' +import SidebarSection from './SidebarSection' + +/** What the item panel needs to show and edit an item's associations. */ +export type ItemAssociationsSupport = { + /** The framework as loaded; this session's association edits are applied on top. */ + loadedFramework?: Framework + /** Frameworks loaded in this session, for destinations in another framework. */ + availableFrameworks?: HomeFramework[] + /** Frameworks on the server that aren't loaded yet. */ + serverFrameworks?: Array<{ id: string; title: string }> + onLoadTargetFramework?: (id: string) => Promise<void> + readOnly?: boolean +} + +type Props = ItemAssociationsSupport & { + itemId: string + accentColor?: string +} + +type Scope = 'self' | 'otherFramework' | 'nonCase' + +type ItemOption = { identifier: string; uri: string; code?: string; statement: string } + +const INPUT_CLS = 'w-full rounded-lg border border-black/15 bg-white px-2.5 py-1.5 text-sm text-slate-900 focus-visible:outline-2 focus-visible:outline-violet-700/40 focus-visible:outline-offset-2' +const KIND_CLS: Record<ItemAssociation['otherKind'], string> = { + self: 'bg-teal-50 text-teal-800', + otherFramework: 'bg-slate-100 text-slate-700', + nonCase: 'bg-amber-50 text-amber-800', +} +const MAX_OPTIONS = 50 + +const typeLabel = (value: string) => ITEM_ASSOCIATION_TYPES.find((t) => t.value === value)?.label ?? value + +function frameworkItemOptions(framework: Framework): ItemOption[] { + return [...framework.items.values()].map((item) => { + const md = (item.metadata ?? {}) as Record<string, unknown> + return { + identifier: String(item.id), + uri: typeof md.caseUri === 'string' && md.caseUri ? md.caseUri : `urn:case:item:${String(item.id)}`, + code: typeof md.humanCodingScheme === 'string' ? md.humanCodingScheme : undefined, + statement: item.statement, + } + }) +} + +function matches(option: ItemOption, query: string): boolean { + if (!query) return true + const q = query.toLowerCase() + return (option.code?.toLowerCase().includes(q) ?? false) || option.statement.toLowerCase().includes(q) +} + +/** + * An item's associations in the item panel: the ones it is the origin of (kept + * with it, as CASE 1.1 stores an association in the document of its origin), + * the ones other items of the framework have to it, and a form to add one to an + * item of this framework, an item of another framework, or a non-CASE target. + */ +export default function ItemAssociationsSection({ + itemId, accentColor, loadedFramework, availableFrameworks = [], serverFrameworks = [], onLoadTargetFramework, readOnly, +}: Readonly<Props>) { + const { + cfItems, + cfDocument, + frameworkNodeId, + inlineAlignmentEdits, + addInlineAlignment, + removeInlineAlignment, + updateInlineAlignmentType, + selectNode, + } = useEditor() + + // With alignment frameworks, associations to items on this server (this framework's included) are + // kept there and authored in the Tree View; only non-CASE targets are added here, and always inline. + const storesInline = (cfDocument?.alignmentStorage ?? 'inline') === 'inline' + const cfItemsById = useMemo(() => new Map(cfItems.map((i) => [i.identifier, i])), [cfItems]) + const editedFramework = useMemo( + () => (loadedFramework ? applyInlineAlignmentEdits(loadedFramework, inlineAlignmentEdits) : undefined), + [loadedFramework, inlineAlignmentEdits], + ) + const { outgoing, incoming } = useMemo( + () => (editedFramework ? itemAssociationsOf(editedFramework, itemId, (id) => cfItemsById.has(id)) : { outgoing: [], incoming: [] }), + [editedFramework, itemId, cfItemsById], + ) + + const otherFrameworks = useMemo(() => { + const loaded = availableFrameworks + .filter((f) => f.id !== frameworkNodeId && f.cfDocument?.frameworkType !== 'Alignment') + .map((f) => ({ id: f.id, title: f.cfDocument.title ?? f.id })) + const loadedIds = new Set(availableFrameworks.map((f) => f.id)) + const notLoaded = serverFrameworks.filter((f) => f.id !== frameworkNodeId && !loadedIds.has(f.id)) + return [...loaded, ...notLoaded].sort((a, b) => a.title.localeCompare(b.title)) + }, [availableFrameworks, serverFrameworks, frameworkNodeId]) + + // The framework that holds a destination, among the frameworks loaded in this session. + const findInOtherFrameworks = (identifier: string) => { + for (const f of availableFrameworks) { + if (f.id === frameworkNodeId) continue + const item = f.framework.items.get(identifier as Parameters<typeof f.framework.items.get>[0]) + if (item) return { frameworkTitle: f.cfDocument.title ?? f.id, item } + } + return null + } + + // ── Add form ── + const [chosenScope, setScope] = useState<Scope>('self') + const scopes: Array<[Scope, string]> = storesInline + ? [['self', 'This framework'], ['otherFramework', 'Another framework'], ['nonCase', 'Non-CASE target']] + : [['nonCase', 'Non-CASE target']] + const scope: Scope = scopes.some(([value]) => value === chosenScope) ? chosenScope : scopes[0][0] + const [associationType, setAssociationType] = useState('isRelatedTo') + const [query, setQuery] = useState('') + const [pickedId, setPickedId] = useState<string | null>(null) + const [otherFrameworkId, setOtherFrameworkId] = useState('') + const [loadingFramework, setLoadingFramework] = useState(false) + const [nonCase, setNonCase] = useState({ identifier: '', uri: '', title: '', targetType: '' }) + const [error, setError] = useState<string | null>(null) + + const scopeOptions = useMemo<ItemOption[]>(() => { + if (scope === 'self') { + return cfItems + .filter((i) => i.identifier !== itemId) + .map((i) => ({ identifier: i.identifier, uri: i.uri || `urn:case:item:${i.identifier}`, code: i.humanCodingScheme, statement: i.fullStatement })) + } + if (scope === 'otherFramework') { + const f = availableFrameworks.find((x) => x.id === otherFrameworkId) + return f ? frameworkItemOptions(f.framework) : [] + } + return [] + }, [scope, cfItems, itemId, availableFrameworks, otherFrameworkId]) + + const shownOptions = useMemo(() => scopeOptions.filter((o) => matches(o, query.trim())).slice(0, MAX_OPTIONS), [scopeOptions, query]) + const otherFrameworkLoaded = availableFrameworks.some((f) => f.id === otherFrameworkId) + + const resetForm = () => { + setQuery('') + setPickedId(null) + setNonCase({ identifier: '', uri: '', title: '', targetType: '' }) + setError(null) + } + + const changeScope = (next: Scope) => { + setScope(next) + resetForm() + } + + const pickOtherFramework = async (id: string) => { + setOtherFrameworkId(id) + setPickedId(null) + setError(null) + if (!id || availableFrameworks.some((f) => f.id === id) || !onLoadTargetFramework) return + setLoadingFramework(true) + try { + await onLoadTargetFramework(id) + } catch { + setError('That framework could not be loaded.') + } finally { + setLoadingFramework(false) + } + } + + const handleAdd = () => { + if (!editedFramework) return + let destination: AssociationDestination + if (scope === 'nonCase') { + const identifier = nonCase.identifier.trim() + const uri = nonCase.uri.trim() + const targetType = nonCase.targetType.trim() + if (!identifier || !uri || !targetType) { + setError('Enter an identifier, a URI and a target type.') + return + } + if (!isNonCaseTargetType(targetType)) { + setError('The target type starts with "ext:", for example ext:outcomes.') + return + } + destination = { identifier, uri, title: nonCase.title.trim() || identifier, targetType } + } else { + const option = scopeOptions.find((o) => o.identifier === pickedId) + if (!option) { + setError('Choose a destination first.') + return + } + destination = { identifier: option.identifier, uri: option.uri, title: option.code ?? option.statement } + } + + if (hasItemAssociation(editedFramework, itemId, destination.identifier, associationType)) { + setError('This item already has that association.') + return + } + const origin = cfItemsById.get(itemId) + addInlineAlignment(newItemAssociation({ + id: globalThis.crypto?.randomUUID?.() ?? `assoc-${Date.now()}`, + fromItemId: itemId, + originUri: origin?.uri || `urn:case:item:${itemId}`, + associationType, + destination, + })) + resetForm() + } + + // ── Rendering ── + const describe = (a: ItemAssociation) => { + if (a.otherKind === 'self') { + const item = cfItemsById.get(a.otherId) + return { code: item?.humanCodingScheme, text: item ? item.fullStatement : (a.otherTitle ?? a.otherId), chip: 'This framework' } + } + if (a.otherKind === 'nonCase') { + const text = a.otherTitle && a.otherTitle !== a.otherId ? a.otherTitle : (a.otherUri ?? '') + return { code: a.otherId, text, chip: a.targetType ?? 'Non-CASE' } + } + const found = findInOtherFrameworks(a.otherId) + const md = (found?.item.metadata ?? {}) as Record<string, unknown> + return { + code: typeof md.humanCodingScheme === 'string' ? md.humanCodingScheme : undefined, + text: found?.item.statement ?? a.otherTitle ?? a.otherId, + chip: found?.frameworkTitle ?? 'Other framework', + } + } + + const isEditable = (a: ItemAssociation) => !readOnly && (storesInline || a.otherKind !== 'otherFramework') + + const typeOptions = (current: string) => ( + <> + {ITEM_ASSOCIATION_TYPES.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)} + {!ITEM_ASSOCIATION_TYPES.some((t) => t.value === current) && <option value={current}>{current}</option>} + </> + ) + + return ( + <SidebarSection + title="Associations" + subtitle="Relations from this item, saved with the framework." + accentColor={accentColor} + defaultOpen + > + <div className="space-y-3 text-sm"> + <div> + <div className="mb-1 text-xs font-medium text-slate-500">Outgoing</div> + {outgoing.length === 0 ? ( + <p className="text-slate-500">No associations from this item yet.</p> + ) : ( + <ul className="divide-y divide-black/5" aria-label="Outgoing associations"> + {outgoing.map((a) => { + const d = describe(a) + const editable = isEditable(a) + return ( + <li key={a.id} className="flex items-center gap-2 py-1.5"> + {editable ? ( + <select + className="w-[118px] shrink-0 rounded-md border border-black/10 bg-white px-1.5 py-1 text-xs" + value={a.associationType} + onChange={(e) => updateInlineAlignmentType(a.id, e.target.value)} + aria-label="Association type" + > + {typeOptions(a.associationType)} + </select> + ) : ( + <span className="w-[118px] shrink-0 truncate text-xs text-slate-600">{typeLabel(a.associationType)}</span> + )} + <span className="min-w-0 flex-1 truncate" title={d.text}> + {d.code ? <><span className="font-mono text-xs text-slate-500">{d.code}</span>{' '}</> : null} + {d.text} + </span> + <span className={`max-w-[110px] shrink-0 truncate rounded-full px-2 py-0.5 text-[11px] font-medium ${KIND_CLS[a.otherKind]}`} title={d.chip}> + {d.chip} + </span> + {editable ? ( + <button + type="button" + className="shrink-0 rounded p-1 text-slate-400 hover:bg-slate-200 hover:text-slate-600" + onClick={() => removeInlineAlignment(a.id)} + aria-label="Remove association" + title="Remove association" + > + <X className="h-3.5 w-3.5" /> + </button> + ) : null} + </li> + ) + })} + </ul> + )} + {!storesInline ? ( + <p className="mt-1 text-xs text-slate-500">This framework keeps its associations to items on this server in alignment frameworks. Those are shown and added in the Tree View.</p> + ) : null} + </div> + + {incoming.length > 0 ? ( + <div> + <div className="mb-1 text-xs font-medium text-slate-500">Incoming</div> + <ul className="divide-y divide-black/5" aria-label="Incoming associations"> + {incoming.map((a) => { + const d = describe(a) + return ( + <li key={a.id} className="flex items-center gap-2 py-1.5"> + <span className="w-[118px] shrink-0 truncate text-xs text-slate-600">{typeLabel(a.associationType)}</span> + <button + type="button" + className="min-w-0 flex-1 truncate text-left hover:underline" + onClick={() => selectNode(a.otherId)} + title={`Open ${d.text}`} + > + <span className="text-slate-500">from </span> + {d.code ? <><span className="font-mono text-xs text-slate-500">{d.code}</span>{' '}</> : null} + {d.text} + </button> + </li> + ) + })} + </ul> + </div> + ) : null} + + {!readOnly && editedFramework ? ( + <div className="rounded-lg bg-white p-3 shadow-[0_1px_2px_rgba(0,0,0,0.04)]"> + <div className="mb-2 text-xs font-medium text-slate-500">Add association</div> + <div className="mb-2 flex flex-wrap gap-1 rounded-lg bg-slate-100 p-0.5 text-xs" role="tablist" aria-label="Destination"> + {scopes.map(([value, label]) => ( + <button + key={value} + type="button" + role="tab" + aria-selected={scope === value} + className={`flex-1 rounded-md px-2 py-1 ${scope === value ? 'bg-white font-medium text-slate-900 shadow-sm' : 'text-slate-600'}`} + onClick={() => changeScope(value)} + > + {label} + </button> + ))} + </div> + + <div className="space-y-2"> + <select + className={INPUT_CLS} + value={associationType} + onChange={(e) => setAssociationType(e.target.value)} + aria-label="Association type for the new association" + > + {typeOptions(associationType)} + </select> + + {scope === 'otherFramework' ? ( + <select + className={INPUT_CLS} + value={otherFrameworkId} + onChange={(e) => { void pickOtherFramework(e.target.value) }} + aria-label="Framework" + > + <option value="">Choose a framework…</option> + {otherFrameworks.map((f) => <option key={f.id} value={f.id}>{f.title}</option>)} + </select> + ) : null} + + {scope === 'nonCase' ? ( + <div className="space-y-2"> + <input className={INPUT_CLS} placeholder="Identifier, e.g. LO-3.1.2" value={nonCase.identifier} onChange={(e) => { setNonCase({ ...nonCase, identifier: e.target.value }); setError(null) }} aria-label="Identifier" /> + <input className={`${INPUT_CLS} font-mono`} placeholder="https://goals.example.org/LO-3.1.2" value={nonCase.uri} onChange={(e) => { setNonCase({ ...nonCase, uri: e.target.value }); setError(null) }} aria-label="URI" /> + <input className={INPUT_CLS} placeholder="Title (optional)" value={nonCase.title} onChange={(e) => setNonCase({ ...nonCase, title: e.target.value })} aria-label="Title" /> + <input className={`${INPUT_CLS} font-mono`} placeholder="ext:outcomes" value={nonCase.targetType} onChange={(e) => { setNonCase({ ...nonCase, targetType: e.target.value }); setError(null) }} aria-label="Target type" /> + </div> + ) : (scope === 'self' || otherFrameworkLoaded) ? ( + <div> + <input + className={INPUT_CLS} + placeholder="Search by code or statement" + value={query} + onChange={(e) => { setQuery(e.target.value); setError(null) }} + aria-label="Search items" + /> + <ul className="mt-1 max-h-48 overflow-auto rounded-lg border border-black/10 bg-white" role="listbox" aria-label="Items"> + {shownOptions.length === 0 ? ( + <li className="px-2.5 py-1.5 text-slate-500">No matching items.</li> + ) : shownOptions.map((o) => ( + <li key={o.identifier} role="option" aria-selected={pickedId === o.identifier}> + <button + type="button" + className={`block w-full truncate px-2.5 py-1.5 text-left ${pickedId === o.identifier ? 'bg-violet-50 text-violet-900' : 'hover:bg-slate-50'}`} + onClick={() => { setPickedId(o.identifier); setError(null) }} + title={o.statement} + > + {o.code ? <><span className="font-mono text-xs text-slate-500">{o.code}</span>{' '}</> : null} + {o.statement} + </button> + </li> + ))} + </ul> + </div> + ) : loadingFramework ? ( + <p className="text-slate-500">Loading framework…</p> + ) : null} + + {error ? <p className="text-sm text-red-700">{error}</p> : null} + <div className="flex justify-end"> + <Button size="xs" onClick={handleAdd}>Add association</Button> + </div> + </div> + </div> + ) : null} + </div> + </SidebarSection> + ) +} diff --git a/apps/editor/src/ui/editor/components/NodePropertiesPanel.tsx b/apps/editor/src/ui/editor/components/NodePropertiesPanel.tsx index 1562e7f..b910995 100644 --- a/apps/editor/src/ui/editor/components/NodePropertiesPanel.tsx +++ b/apps/editor/src/ui/editor/components/NodePropertiesPanel.tsx @@ -20,6 +20,7 @@ import { EDUCATION_LEVEL_OPTIONS } from '@/ui/editor/terminology/educationLevels import type { EducationLevelOption } from '@/ui/editor/terminology/educationLevels' import { getAppConfig } from '@/app/config' import SidebarSection from './SidebarSection' +import ItemAssociationsSection, { type ItemAssociationsSupport } from './ItemAssociationsSection' /* ── Shared styling constants ── */ const INPUT_CLS = 'w-full rounded-xl border border-black/15 bg-white px-3 py-2.5 text-base text-slate-900 focus-visible:outline-2 focus-visible:outline-violet-700/40 focus-visible:outline-offset-2' @@ -38,11 +39,13 @@ type Props = { ensureCfSubject?: (_title: string) => CFSubject | null cfConcepts?: CFConcept[] ensureCfConcept?: (_title: string) => CFConcept | null + /** Shows an item's associations and lets the author add, change and remove them. */ + associations?: ItemAssociationsSupport } export default memo(function NodePropertiesPanel({ node, onClose, onChangeNode, onViewCFPackage, availableLicenses, - cfItemTypes = [], ensureCfItemType, cfSubjects = [], ensureCfSubject, cfConcepts = [], ensureCfConcept, + cfItemTypes = [], ensureCfItemType, cfSubjects = [], ensureCfSubject, cfConcepts = [], ensureCfConcept, associations, }: Readonly<Props>) { const [copied, setCopied] = useState<null | 'code' | 'uri' | 'opencase'>(null) const [conceptInput, setConceptInput] = useState('') @@ -381,6 +384,11 @@ export default memo(function NodePropertiesPanel({ )} </SidebarSection> + {/* ── Item associations (items only) ── */} + {!isFramework && cfItem && associations ? ( + <ItemAssociationsSection key={node.id} itemId={node.id} accentColor={accentColor} {...associations} /> + ) : null} + {/* ── Item lifecycle (items only) ── */} {!isFramework && cfItem ? ( <SidebarSection title="Lifecycle" subtitle="Validity dates and license for this item." accentColor={accentColor} defaultOpen={false}> diff --git a/apps/editor/src/ui/editor/treePanel/FrameworkTreeItem.tsx b/apps/editor/src/ui/editor/treePanel/FrameworkTreeItem.tsx index e353cac..663318a 100644 --- a/apps/editor/src/ui/editor/treePanel/FrameworkTreeItem.tsx +++ b/apps/editor/src/ui/editor/treePanel/FrameworkTreeItem.tsx @@ -1,5 +1,5 @@ import { memo, useState } from 'react' -import { ChevronDown, ChevronRight, ExternalLink, Link, Plus } from 'lucide-react' +import { ChevronDown, ChevronRight, ExternalLink, Link, Link2, Plus } from 'lucide-react' import type { FrameworkTreeNode } from '@/domain/framework/treeDerivation' import type { CFItem } from '@/domain/case/types' @@ -23,6 +23,8 @@ type Props = { associationCounts?: Map<string, number> /** Called when the association-count badge is clicked */ onBadgeClick?: (_id: string, _e: React.MouseEvent<HTMLButtonElement>) => void + /** How many associations each item takes part in, whatever they point to. Shown when it has no badge for the expanded target. */ + relationCounts?: Map<string, number> /** Show a link out to the item's URI (for rows that aren't on this server) */ showUriLinks?: boolean } @@ -44,6 +46,7 @@ function FrameworkTreeItem({ dragOverItemId, associationCounts, onBadgeClick, + relationCounts, showUriLinks, }: Readonly<Props>) { const [hovered, setHovered] = useState(false) @@ -53,6 +56,7 @@ function FrameworkTreeItem({ const hasChildren = node.children.length > 0 const isDraggedOver = dragOverItemId === node.id const associationCount = associationCounts?.get(node.id) ?? 0 + const relationCount = relationCounts?.get(node.id) ?? 0 const linkUri = showUriLinks && cfItem?.uri && /^https?:\/\//.test(cfItem.uri) ? cfItem.uri : undefined const rowClass = [ @@ -146,6 +150,19 @@ function FrameworkTreeItem({ {associationCount} </button> )} + {associationCount === 0 && relationCount > 0 && ( + <button + type="button" + className="shrink-0 inline-flex items-center gap-0.5 rounded-full bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-600 hover:bg-slate-200 transition-colors focus:outline-none focus:ring-1 focus:ring-slate-400" + title={`${relationCount} association${relationCount !== 1 ? 's' : ''} — click to see them`} + aria-label={`${relationCount} association${relationCount !== 1 ? 's' : ''}`} + onClick={(e) => { e.stopPropagation(); onSelect?.(node.id) }} + tabIndex={-1} + > + <Link2 className="h-2.5 w-2.5" /> + {relationCount} + </button> + )} {linkUri && ( <a href={linkUri} @@ -212,6 +229,7 @@ function FrameworkTreeItem({ dragOverItemId={dragOverItemId} associationCounts={associationCounts} onBadgeClick={onBadgeClick} + relationCounts={relationCounts} showUriLinks={showUriLinks} /> ))} @@ -243,6 +261,7 @@ function areEqual(prev: Readonly<Props>, next: Readonly<Props>): boolean { prev.dragOverItemId === next.dragOverItemId && prev.associationCounts === next.associationCounts && prev.onBadgeClick === next.onBadgeClick && + prev.relationCounts === next.relationCounts && prev.showUriLinks === next.showUriLinks && prev.cfItemsById.get(next.node.id) === next.cfItemsById.get(next.node.id) ) diff --git a/apps/editor/src/ui/editor/treePanel/FrameworkTreeList.tsx b/apps/editor/src/ui/editor/treePanel/FrameworkTreeList.tsx index 2481532..922ccd4 100644 --- a/apps/editor/src/ui/editor/treePanel/FrameworkTreeList.tsx +++ b/apps/editor/src/ui/editor/treePanel/FrameworkTreeList.tsx @@ -38,6 +38,8 @@ type Props = { associationCounts?: Map<string, number> /** Called when an association-count badge is clicked */ onBadgeClick?: (_id: string, _e: React.MouseEvent<HTMLButtonElement>) => void + /** How many associations each item takes part in, whatever they point to */ + relationCounts?: Map<string, number> /** Show a link out to each item's URI (for rows that aren't on this server) */ showUriLinks?: boolean } @@ -67,6 +69,7 @@ export default function FrameworkTreeList({ dragOverItemId, associationCounts, onBadgeClick, + relationCounts, showUriLinks, }: Readonly<Props>) { const frameworkSelected = frameworkNodeId !== null && selectedId === frameworkNodeId @@ -145,6 +148,7 @@ export default function FrameworkTreeList({ dragOverItemId={dragOverItemId} associationCounts={associationCounts} onBadgeClick={onBadgeClick} + relationCounts={relationCounts} showUriLinks={showUriLinks} /> ))} 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..8a7bf1a --- /dev/null +++ b/apps/editor/src/ui/editor/treePanel/TreePanelView.selfAlignments.test.tsx @@ -0,0 +1,109 @@ +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, selectedNodeId } = useEditor() + return ( + <> + <output data-testid="inline-added">{inlineAlignmentEdits.added.map((a) => `${a.fromItemId}>${a.toItemId}`).join(',')}</output> + <output data-testid="selected">{selectedNodeId ?? ''}</output> + </> + ) +} + +function renderView(framework: Framework, onSaveAlignments = vi.fn()) { + render( + <EditorProvider initialGraph={toEditorGraph({ framework })} graphKey="doc-1"> + <TreePanelView availableFrameworks={[createHomeFrameworkFromDomain(framework)]} loadedFramework={framework} onSaveAlignments={onSaveAlignments} /> + <InlineEdits /> + </EditorProvider>, + ) +} + +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('marks items that have associations and opens one from its marker', async () => { + renderView(makeFramework()) + + const markers = await screen.findAllByRole('button', { name: '1 association' }) + expect(markers).toHaveLength(2) + fireEvent.click(markers[0]) + expect(screen.getByTestId('selected')).toHaveTextContent('item-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..de8ea27 100644 --- a/apps/editor/src/ui/editor/treePanel/TreePanelView.tsx +++ b/apps/editor/src/ui/editor/treePanel/TreePanelView.tsx @@ -7,12 +7,14 @@ import type { HomeFramework } from '@/ui/home/frameworkStore' import type { Association, AssociationType, Framework } from '@/domain/framework/model/types' import type { AssociationId, ItemId } from '@/domain/shared/types' import { applyInlineAlignmentEdits } from '@/domain/framework/inlineAlignmentEdits' +import { associationCountsByItem } from '@/domain/framework/itemAssociations' import { buildAlignmentFrameworkPackage } from '@/domain/framework/alignmentFrameworks' import { externalAlignmentsOf, groupExternalAlignments, hostedLookupCandidates, isRemoteTargetId, + selfAlignmentsOf, type ExternalAlignmentTarget, type HostedDocumentRef, } from '@/domain/framework/externalAlignments' @@ -50,7 +52,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 +257,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<TargetEntry[]>([]) const [expandedTargetId, setExpandedTargetId] = useState<string | null>(null) @@ -267,10 +277,22 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor const lookedUpIdsRef = useRef<Set<string>>(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<PendingAssociation[]>( + () => (editedFramework && activeFrameworkId + ? selfAlignmentsOf(editedFramework, isOwnItem).map((a) => ({ ...a, toFrameworkId: activeFrameworkId, inline: true })) + : []), + [editedFramework, activeFrameworkId, isOwnItem], + ) const inlineAssociations = useMemo<PendingAssociation[]>( - () => 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), @@ -470,6 +492,18 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor return counts }, [shownAssociations, expandedTargetId]) + // How many associations each item of this framework takes part in, whatever they point to: those + // stored in it (as they'll be saved) and those in its alignment frameworks. Shown on the item in the tree. + const relationCounts = useMemo(() => { + const counts = editedFramework ? associationCountsByItem(editedFramework, isOwnItem) : new Map<string, number>() + const add = (id: string) => counts.set(id, (counts.get(id) ?? 0) + 1) + for (const a of pendingAssociations) { + add(a.fromItemId) + if (a.toFrameworkId === activeFrameworkId && a.toItemId !== a.fromItemId) add(a.toItemId) + } + return counts + }, [editedFramework, isOwnItem, pendingAssociations, activeFrameworkId]) + // ── SVG line calculation ── const recalculateLines = useCallback(() => { @@ -633,7 +667,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 +706,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 +803,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 +1096,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 ( <g key={line.id}> {/* Transparent hit area — solid lines collapse one level, dashed lines expand to reveal items */} @@ -1065,7 +1117,7 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor {/* Visible stroke: solid when both items are visible, dashed when proxied via ancestor */} <path d={line.d} - stroke={isHovered ? '#9333ea' : '#c084fc'} + stroke={isInline ? (isHovered ? '#0f766e' : '#2dd4bf') : (isHovered ? '#9333ea' : '#c084fc')} strokeWidth={isHovered ? 2.5 : 1.5} strokeDasharray={line.isDashed ? '5 3' : undefined} fill="none" @@ -1097,6 +1149,7 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor isDraggable={Boolean(expandedTargetFramework) || expandedRemoteTarget !== null} onDragStart={handleLeftDragStart} associationCounts={leftAssociationCounts} + relationCounts={relationCounts} onBadgeClick={handleLeftBadgeClick} belowHeaderSlot={( <button @@ -1290,7 +1343,7 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor key={assoc.id} className="flex items-center gap-2 rounded-lg px-1 py-1.5 hover:bg-slate-50" > - {assoc.inline && !storesInline && !isRemoteTargetId(assoc.toFrameworkId) ? ( + {assoc.inline && !storesInline && !isRemoteTargetId(assoc.toFrameworkId) && assoc.toFrameworkId !== activeFrameworkId ? ( <span className="shrink-0 rounded-full bg-purple-100 px-1.5 py-0.5 text-[10px] font-medium text-purple-700" title="Stored in this framework — shown read-only" @@ -1321,7 +1374,7 @@ export default function TreePanelView({ availableFrameworks = [], serverFramewor > {label} </span> - {(!assoc.inline || storesInline || isRemoteTargetId(assoc.toFrameworkId)) && ( + {(!assoc.inline || storesInline || isRemoteTargetId(assoc.toFrameworkId) || assoc.toFrameworkId === activeFrameworkId) && ( <button type="button" className="shrink-0 rounded p-0.5 text-slate-400 hover:bg-slate-200 hover:text-slate-600 focus:outline-none"