@cratis/event-models 0.108.3 → 0.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../Model/ActorType.ts","../Model/AssigneeKind.ts","../Model/AutomationTriggerType.ts","../Model/ConcurrencyValueSource.ts","../Model/QueryParameterType.ts","../Model/SliceStatus.ts","../Model/SliceType.ts","../Model/SpecificationErrorRuleKind.ts","../Model/SpecificationRunOutcome.ts","../Reading/InvalidEventModelDocument.ts","../Reading/isKnownValue.ts","../Reading/DocumentNode.ts","../Reading/readBoardItems.ts","../Reading/readActors.ts","../Reading/readJsonSchema.ts","../Reading/readSliceItems.ts","../Reading/readSpecification.ts","../Reading/readSlice.ts","../Reading/readModules.ts","../Reading/readEventModelDocument.ts","../Messages/defaultEventModelMessages.ts","../Messages/EventModelMessagesContext.ts","../Messages/EventModelMessagesProvider.tsx","../Presentation/DetailLevel.ts","../Presentation/detailsVisibility.ts","../Presentation/defaultEventModelPresentation.ts","../Presentation/EventModelPresentationContext.ts","../Presentation/EventModelPresentationProvider.tsx","../Rows/RowType.ts","../Tooltips/AnchoredOverlay.tsx","../Tooltips/GridTooltip.tsx","../Slices/resolveSliceReadOnly.ts","../Board/BoardInteractionContext.ts","../Board/BoardInteractionProvider.tsx","../Board/BoardReadOnlyContext.ts","../Board/BoardProvider.tsx","../Board/useBoard.ts","../Board/BoardCanvas.tsx","../Collections/useCollectionMove.ts","../Collections/CollectionMoveHandle.tsx","../Collections/collectionState.ts","../Collections/useCollectionsArea.ts","../Layout/boardMetrics.ts","../Properties/schemaProperties.ts","../Layout/cardHeight.ts","../Layout/sliceLayout.ts","../RowLabels/actorRows.ts","../Layout/sliceRows.ts","../Viewport/viewportFlushScheduler.ts","../Viewport/useInViewport.ts","../Collections/CollectionViewport.tsx","../Geometry/CurveAxis.ts","../Geometry/connectionCurve.ts","../Geometry/linkGeometry.ts","../Geometry/pillLabelWidth.ts","../Geometry/rowLabelWidth.ts","../RowLabels/ActorRowDragGhost.tsx","../RowLabels/ActorRowDropIndicator.tsx","../RowLabels/actorKinds.ts","../Headers/CollapseButton.tsx","../Headers/DetailsToggle.tsx","../Headers/EditableLabel.tsx","../Headers/EntityErrorIndicator.tsx","../Headers/EntityErrorKind.ts","../Headers/ErroredEntity.tsx","../Headers/PillHeader.tsx","../Pickers/useDismissOnOutsidePointer.ts","../RowLabels/rowTypeName.ts","../RowLabels/RowLabel.tsx","../RowLabels/RowLabelsColumnFrame.tsx","../RowLabels/useActorRowDrag.ts","../RowLabels/RowLabelsColumn.tsx","../Modules/ModuleColumnFrame.tsx","../Modules/ModuleDropIndicator.tsx","../SliceDragging/snapshotSlice.ts","../HeaderDragging/createHeaderDragGhost.ts","../HeaderDragging/HeaderDragGhost.tsx","../HeaderDragging/headerDropIndex.ts","../HeaderDragging/reorderedIds.ts","../HeaderDragging/zoomOfAncestor.ts","../HeaderDragging/useHeaderDragIntent.ts","../Statuses/SliceStatusIcon.tsx","../Menus/MenuDropdown.tsx","../Statuses/changeSliceStatus.ts","../Statuses/sliceStatuses.ts","../Statuses/SliceStatusPicker.tsx","../Modules/ModuleHeaderMenu.tsx","../Features/FeatureSuggestions.tsx","../Modules/ModuleHeader.tsx","../Modules/useModuleDrag.ts","../Modules/moduleAreaState.ts","../Modules/persistModuleChange.ts","../Modules/ModulesArea.tsx","../Modules/moduleWidth.ts","../Modules/ModuleHeaderCell.tsx","../Modules/ModulePlaceholder.tsx","../Modules/ModuleSurface.tsx","../Collections/collectionGridLayout.ts","../Collections/estimateCollectionSize.ts","../Collections/useSliceDetailsVisibility.ts","../Connections/Connectors.tsx","../Connections/FlowNodeActor.ts","../Connections/computeSliceConnections.ts","../Connections/flowNodeOrder.ts","../Connections/SliceConnections.tsx","../Connections/SliceConnectionsContext.tsx","../Connections/useConnectionHighlight.ts","../Features/FeatureColumnFrame.tsx","../Features/FeatureGridSurface.tsx","../Features/FeatureHeaderCell.tsx","../Features/featureDropEdge.ts","../Features/useFeatureDrag.ts","../Features/useFeatureSlotTargets.ts","../Features/featureAreaState.ts","../Features/FeaturesArea.tsx","../SliceTypes/SliceTypeIcon.tsx","../SliceTypes/sliceTypeMenuItems.tsx","../SliceTypes/SliceTypeExplanation.tsx","../SliceTypes/SliceTypeMenu.tsx","../Features/FeatureAddMenu.tsx","../Features/featureHeaderMenuItems.ts","../Features/FeatureHeaderMenu.tsx","../Features/FeatureHeader.tsx","../Specifications/SpecificationRunState.ts","../Specifications/SpecificationRunButton.tsx","../Specifications/SpecificationStatus.tsx","../Specifications/SpecificationHeader.tsx","../Specifications/specificationCollectionState.ts","../Specifications/SpecificationCollection.tsx","../Specifications/SpecificationSection.tsx","../Cards/pascalCaseBreak.ts","../Cards/autoFitTitle.ts","../Cards/useAutoFitTitle.ts","../Cards/Card.tsx","../Cards/cardColors.ts","../Properties/TypeBadge.tsx","../Properties/SchemaTooltipProperties.tsx","../Cards/ArtifactCardKind.ts","../Cards/CardCorner.ts","../Cards/CardActionButton.tsx","../Cards/EventTags.tsx","../Cards/ArtifactCard.tsx","../Cards/CardNameInput.tsx","../Specifications/itemValues.ts","../Pickers/PickerPanel.tsx","../Pickers/EventReferencePicker.tsx","../Specifications/SpecificationAddPicker.tsx","../Specifications/SpecificationItemCard.tsx","../Specifications/SpecificationItemKind.ts","../Specifications/SpecificationRow.tsx","../Specifications/specificationEvents.ts","../Specifications/RemovableSpecificationItem.tsx","../Specifications/GivenSection.tsx","../Specifications/WhenSection.tsx","../Specifications/ruleErrors.ts","../Specifications/SpecificationErrorCard.tsx","../Specifications/ThenSection.tsx","../Collections/SliceLines.tsx","../Collections/CollectionGridSlice.tsx","../Collections/CollectionGridTemplate.tsx","../Collections/CollectionGridFeatureColumn.tsx","../Collections/CollectionGridFeature.tsx","../Collections/CollectionGridModule.tsx","../Collections/localCollapses.ts","../Collections/CollectionGrid.tsx","../Links/linkState.ts","../Links/drawableLinks.ts","../Links/ModuleCollectionLinks.tsx","../StickyNotes/isEditableTarget.ts","../StickyNotes/StickyNoteState.ts","../StickyNotes/StickyNotes.tsx","../Board/BoardCollectionView.tsx","../Board/boardMinimap.ts","../Board/isLargeBoard.ts","../Board/HostedEventModelBoard.tsx","../Board/EventModelBoard.tsx","../Board/BoardToolbar.tsx","../Slices/SliceContext.ts","../Slices/SliceProvider.tsx","../Slices/useSlice.ts","../Slices/SliceHeader.tsx","../SliceDragging/dropIndicatorClassName.ts","../SliceDragging/SliceDragGestureVerdict.ts","../SliceDragging/readSliceDragGesture.ts","../SliceDragging/readSlicePress.ts","../SliceDragging/SliceDragGhost.tsx","../SliceDragging/SliceDropIndicator.tsx","../SliceDragging/SliceDropTarget.tsx","../SliceDragging/sliceMove.ts","../SliceDragging/useSliceDrag.ts","../SliceDragging/useSliceDragIntent.ts","../Slices/SliceColumnFrame.tsx","../Slices/SliceColumn.tsx","../Slices/createOptimisticSlice.ts","../Slices/sliceAreaState.ts","../Slices/SlicesArea.tsx","../Slices/SliceRows.tsx","../Slices/SlicePlaceholder.tsx","../Rows/CellActionButton.tsx","../Rows/CellCornerPlacement.ts","../Rows/CellCorner.tsx","../Rows/CellCornerAction.tsx","../Rows/eventRowAffordances.ts","../Rows/System/triggerBadges.ts","../Icons/CogWheel.tsx","../Rows/System/TriggerKind.ts","../Rows/System/TriggerControl.tsx","../Rows/System/SystemCell.tsx","../Rows/UserExperience/addPrototypeMenuItems.ts","../Rows/UserExperience/AddPrototypeButton.tsx","../Rows/UserExperience/UiCell.tsx","../Rows/Chat/ChatCell.tsx","../Rows/Events/EventsCell.tsx","../Rows/Events/EventCard.tsx","../References/EventNavigateButton.tsx","../References/useReferenceHover.ts","../References/ExternalEventCard.tsx","../Rows/Events/EventReferenceCard.tsx","../Rows/Events/projectedFromTheRight.ts","../Rows/Events/referenceableEvents.ts","../Rows/Events/SliceEvents.tsx","../Rows/Interaction/InteractionCard.tsx","../Rows/Interaction/InteractionCell.tsx","../Rows/Interaction/InteractionMiniCard.ts","../Rows/Interaction/OptionalReadModel.tsx","../Rows/Interaction/SliceInteraction.tsx"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum ActorType {\n UIRole = 0,\n systemRole = 1,\n chatRole = 2,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum AssigneeKind {\n system = 'system',\n agent = 'agent',\n user = 'user',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum AutomationTriggerType {\n timer = 0,\n event = 1,\n custom = 2,\n none = 3,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum ConcurrencyValueSource {\n notSet = 0,\n value = 1,\n commandProperty = 2,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum QueryParameterType {\n text = 0,\n number = 1,\n boolean = 2,\n date = 3,\n time = 4,\n uniqueId = 5,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum SliceStatus {\n notStarted = 0,\n draft = 1,\n readyForImplementation = 2,\n inProgress = 3,\n readyForReview = 4,\n done = 5,\n analysis = 6,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum SliceType {\n stateChange = 0,\n stateView = 1,\n automation = 2,\n translator = 3,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum SpecificationErrorRuleKind {\n commandValidationRule = 0,\n eventUniqueConstraint = 1,\n eventUniqueEventTypeConstraint = 2,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum SpecificationRunOutcome {\n passed = 0,\n failed = 1,\n inconclusive = 2,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport class InvalidEventModelDocument extends Error {\n constructor(readonly path: string, reason: string) {\n super(`Invalid event model document at '${path}': ${reason}`);\n this.name = 'InvalidEventModelDocument';\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Whether a wire value is one of the members of a re-declared enum. A document written by a newer\n// producer may carry a value this package has not heard of; the board draws that as an explicit\n// unknown rather than guessing.\nexport const isKnownValue = (enumeration: Record<string, string | number>, value: string | number): boolean =>\n Object.values(enumeration).includes(value);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Guid } from '@cratis/fundamentals';\nimport { InvalidEventModelDocument } from './InvalidEventModelDocument';\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst isAbsent = (value: unknown): boolean => value === undefined || value === null;\n\n// One object in an event model document, read by key. Only the keys a reader asks for are ever\n// copied into the contract, which is what makes unknown fields from a newer producer harmless.\nexport class DocumentNode {\n private constructor(private readonly _value: Record<string, unknown>, readonly path: string) {\n }\n\n static root(value: unknown): DocumentNode {\n if (!isRecord(value)) {\n throw new InvalidEventModelDocument('$', 'the document must be an object');\n }\n return new DocumentNode(value, '$');\n }\n\n has(key: string): boolean {\n return !isAbsent(this._value[key]);\n }\n\n string(key: string): string {\n return this.optionalString(key) ?? '';\n }\n\n optionalString(key: string): string | undefined {\n const value = this._value[key];\n if (isAbsent(value)) return undefined;\n if (typeof value !== 'string') throw this.invalid(key, 'expected a string');\n return value;\n }\n\n number(key: string): number {\n const value = this._value[key];\n if (isAbsent(value)) return 0;\n if (typeof value !== 'number') throw this.invalid(key, 'expected a number');\n return value;\n }\n\n // Enums are wire values. A number the package does not know is kept as it is — the board shows it\n // as an explicit unknown — so only a missing value or a value of the wrong type is rejected.\n enumValue(key: string): number {\n const value = this._value[key];\n if (typeof value !== 'number') throw this.invalid(key, 'expected a numeric enum value');\n return value;\n }\n\n optionalEnumValue(key: string): number | undefined {\n return this.has(key) ? this.enumValue(key) : undefined;\n }\n\n boolean(key: string): boolean {\n const value = this._value[key];\n if (isAbsent(value)) return false;\n if (typeof value !== 'boolean') throw this.invalid(key, 'expected a boolean');\n return value;\n }\n\n guid(key: string): Guid {\n const value = this.optionalGuid(key);\n if (!value) throw this.invalid(key, 'expected a GUID');\n return value;\n }\n\n optionalGuid(key: string): Guid | undefined {\n const value = this._value[key];\n if (isAbsent(value)) return undefined;\n if (value instanceof Guid) return value;\n if (typeof value !== 'string' || !Guid.isGuid(value)) throw this.invalid(key, 'expected a GUID');\n return Guid.parse(value);\n }\n\n strings(key: string): string[] {\n const value = this._value[key];\n if (isAbsent(value)) return [];\n if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) throw this.invalid(key, 'expected an array of strings');\n return value.map(item => String(item));\n }\n\n record(key: string): Record<string, unknown> {\n const value = this._value[key];\n if (isAbsent(value)) return {};\n if (!isRecord(value)) throw this.invalid(key, 'expected an object');\n return { ...value };\n }\n\n raw(key: string): unknown {\n return this._value[key];\n }\n\n object(key: string): DocumentNode | undefined {\n const value = this._value[key];\n if (isAbsent(value)) return undefined;\n if (!isRecord(value)) throw this.invalid(key, 'expected an object');\n return new DocumentNode(value, `${this.path}.${key}`);\n }\n\n array<T>(key: string, read: (node: DocumentNode) => T): T[] {\n const value = this._value[key];\n if (isAbsent(value)) return [];\n if (!Array.isArray(value)) throw this.invalid(key, 'expected an array');\n return value.map((item, index) => {\n const path = `${this.path}.${key}[${index}]`;\n if (!isRecord(item)) throw new InvalidEventModelDocument(path, 'expected an object');\n return read(new DocumentNode(item, path));\n });\n }\n\n private invalid(key: string, reason: string): InvalidEventModelDocument {\n return new InvalidEventModelDocument(`${this.path}.${key}`, reason);\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ModuleCollectionLink, Position, StickyNote } from '../Model';\nimport type { DocumentNode } from './DocumentNode';\n\nexport const readPosition = (node: DocumentNode | undefined): Position => ({\n x: node?.number('x') ?? 0,\n y: node?.number('y') ?? 0,\n});\n\nexport const readStickyNote = (node: DocumentNode): StickyNote => ({\n id: node.string('id'),\n position: readPosition(node.object('position')),\n width: node.number('width'),\n height: node.number('height'),\n text: node.string('text'),\n});\n\nexport const readModuleCollectionLink = (node: DocumentNode): ModuleCollectionLink => ({\n id: node.guid('id'),\n sourceCollectionId: node.guid('sourceCollectionId'),\n targetCollectionId: node.guid('targetCollectionId'),\n});\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { UIElement } from '@cratis/scene';\nimport type { Actor, PersonaReference, UserExperienceActor } from '../Model';\nimport type { DocumentNode } from './DocumentNode';\n\n// Prototype elements belong to Cratis Scene, which hydrates them when it draws a thumbnail; the board\n// passes them through untouched rather than second-guessing Scene's own shape.\nconst isUIElement = (value: unknown): value is UIElement =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst readPersona = (node: DocumentNode | undefined): PersonaReference | undefined =>\n node ? { id: node.guid('id'), name: node.string('name') } : undefined;\n\nexport const readActor = (node: DocumentNode): Actor => {\n const persona = readPersona(node.object('persona'));\n return {\n id: node.string('id'),\n name: node.string('name'),\n actorType: node.enumValue('actorType'),\n description: node.string('description'),\n ...(persona ? { persona } : {}),\n };\n};\n\nexport const readUserExperienceActor = (node: DocumentNode): UserExperienceActor => {\n const elements = node.raw('elements');\n return {\n id: node.string('id'),\n type: node.enumValue('type'),\n elements: Array.isArray(elements) ? elements.filter(isUIElement) : [],\n layout: node.optionalEnumValue('layout') ?? 0,\n windowWidth: node.number('windowWidth'),\n windowHeight: node.number('windowHeight'),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { JsonSchema } from '@cratis/components/types';\n\nconst emptySchema = (): JsonSchema => ({ type: 'object', properties: {} });\n\nconst isJsonSchema = (value: unknown): value is JsonSchema => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const type: unknown = Reflect.get(value, 'type');\n const properties: unknown = Reflect.get(value, 'properties');\n return (type === undefined || typeof type === 'string')\n && (properties === undefined || (typeof properties === 'object' && properties !== null && !Array.isArray(properties)));\n};\n\n// Schemas arrive as an object, or — from older stored models — as the same object serialized to a\n// string. Anything that is neither reads as an empty object schema, which is what the board already\n// draws for a card whose schema could not be parsed.\nexport const readJsonSchema = (value: unknown): JsonSchema => {\n if (typeof value === 'string') {\n try {\n return readJsonSchema(JSON.parse(value));\n } catch {\n return emptySchema();\n }\n }\n return isJsonSchema(value) ? value : emptySchema();\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type {\n CommandConcurrency,\n CommandItem,\n CommandPropertyRules,\n ConcurrencyBinding,\n EventConstraint,\n EventConstraints,\n EventItem,\n ExternalEventItem,\n QueryItem,\n ReadModelItem\n} from '../Model';\nimport type { DocumentNode } from './DocumentNode';\nimport { readJsonSchema } from './readJsonSchema';\n\nconst readRules = (node: DocumentNode): CommandPropertyRules => ({\n propertyName: node.string('propertyName'),\n rules: node.array('rules', rule => ({ errorMessage: rule.string('errorMessage'), ruleType: rule.string('ruleType') })),\n});\n\nconst readBinding = (node: DocumentNode | undefined): ConcurrencyBinding | undefined =>\n node ? { source: node.enumValue('source'), value: node.string('value') } : undefined;\n\nconst readConcurrency = (node: DocumentNode | undefined): CommandConcurrency | undefined => {\n if (!node) return undefined;\n const scopeId = node.optionalGuid('scopeId');\n const eventSourceType = readBinding(node.object('eventSourceType'));\n const eventStreamType = readBinding(node.object('eventStreamType'));\n const eventStreamId = readBinding(node.object('eventStreamId'));\n return {\n includeEventSource: node.boolean('includeEventSource'),\n ...(scopeId ? { scopeId } : {}),\n ...(eventSourceType ? { eventSourceType } : {}),\n ...(eventStreamType ? { eventStreamType } : {}),\n ...(eventStreamId ? { eventStreamId } : {}),\n };\n};\n\nconst readConstraint = (node: DocumentNode | undefined): EventConstraint | undefined =>\n node ? { name: node.string('name'), message: node.string('message') } : undefined;\n\nconst readConstraints = (node: DocumentNode | undefined): EventConstraints | undefined => {\n if (!node) return undefined;\n const unique = readConstraint(node.object('unique'));\n const uniqueEventType = readConstraint(node.object('uniqueEventType'));\n return {\n ...(unique ? { unique } : {}),\n ...(uniqueEventType ? { uniqueEventType } : {}),\n };\n};\n\nexport const readCommandItem = (node: DocumentNode): CommandItem => {\n const concurrency = readConcurrency(node.object('concurrency'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n schema: readJsonSchema(node.raw('schema')),\n stateSchema: readJsonSchema(node.raw('stateSchema')),\n logicDescription: node.string('logicDescription'),\n ...(node.has('rules') ? { rules: node.array('rules', readRules) } : {}),\n ...(concurrency ? { concurrency } : {}),\n };\n};\n\nexport const readEventItem = (node: DocumentNode): EventItem => {\n const sourceEventId = node.optionalString('sourceEventId');\n const constraints = readConstraints(node.object('constraints'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n schema: readJsonSchema(node.raw('schema')),\n ...(sourceEventId ? { sourceEventId } : {}),\n ...(node.has('tags') ? { tags: node.strings('tags') } : {}),\n ...(constraints ? { constraints } : {}),\n };\n};\n\nexport const readExternalEventItem = (node: DocumentNode): ExternalEventItem => ({\n id: node.guid('id'),\n name: node.string('name'),\n sourceEventId: node.string('sourceEventId'),\n});\n\nexport const readReadModelItem = (node: DocumentNode): ReadModelItem => ({\n id: node.guid('id'),\n name: node.string('name'),\n schema: readJsonSchema(node.raw('schema')),\n materializes: node.boolean('materializes'),\n});\n\nexport const readQueryItem = (node: DocumentNode): QueryItem => ({\n id: node.guid('id'),\n name: node.string('name'),\n parameters: node.array('parameters', parameter => ({\n name: parameter.string('name'),\n type: parameter.enumValue('type'),\n })),\n});\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type {\n SliceSpecification,\n SpecificationCommand,\n SpecificationError,\n SpecificationErrorRuleReference,\n SpecificationGivenEvent,\n SpecificationReadModel\n} from '../Model';\nimport type { DocumentNode } from './DocumentNode';\n\nconst readEventStep = (node: DocumentNode): SpecificationGivenEvent => ({\n id: node.guid('id'),\n name: node.string('name'),\n eventId: node.guid('eventId'),\n values: node.record('values'),\n});\n\n// A specification's \"when\" exists before a command has been chosen for it, so the command it points\n// at can be absent in a stored model.\nconst readCommand = (node: DocumentNode | undefined): SpecificationCommand | undefined => {\n if (!node) return undefined;\n const commandId = node.optionalGuid('commandId');\n return {\n id: node.guid('id'),\n name: node.string('name'),\n values: node.record('values'),\n ...(commandId ? { commandId } : {}),\n };\n};\n\nconst readReadModel = (node: DocumentNode | undefined): SpecificationReadModel | undefined =>\n node\n ? {\n id: node.guid('id'),\n readModelItemId: node.guid('readModelItemId'),\n name: node.string('name'),\n ...(node.has('values') ? { values: node.record('values') } : {}),\n }\n : undefined;\n\nconst readReference = (node: DocumentNode | undefined): SpecificationErrorRuleReference | undefined =>\n node\n ? {\n kind: node.enumValue('kind'),\n itemId: node.guid('itemId'),\n propertyName: node.string('propertyName'),\n ruleType: node.string('ruleType'),\n }\n : undefined;\n\nconst readError = (node: DocumentNode): SpecificationError => {\n const reference = readReference(node.object('reference'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n ...(reference ? { reference } : {}),\n };\n};\n\nexport const readSliceSpecification = (node: DocumentNode): SliceSpecification => {\n const when = readCommand(node.object('when'));\n const givenReadModel = readReadModel(node.object('givenReadModel'));\n const lastRunOutcome = node.optionalEnumValue('lastRunOutcome');\n const lastRunMessage = node.optionalString('lastRunMessage');\n return {\n id: node.guid('id'),\n name: node.string('name'),\n given: node.array('given', readEventStep),\n thenEvents: node.array('thenEvents', readEventStep),\n thenErrors: node.array('thenErrors', readError),\n collapsed: node.boolean('collapsed'),\n ...(when ? { when } : {}),\n ...(givenReadModel ? { givenReadModel } : {}),\n ...(lastRunOutcome !== undefined ? { lastRunOutcome } : {}),\n ...(lastRunMessage !== undefined ? { lastRunMessage } : {}),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Assignee, AutomationTrigger, AutomationTriggerSchedule, Slice } from '../Model';\nimport { AssigneeKind } from '../Model/AssigneeKind';\nimport type { DocumentNode } from './DocumentNode';\nimport { InvalidEventModelDocument } from './InvalidEventModelDocument';\nimport { readUserExperienceActor } from './readActors';\nimport { readCommandItem, readEventItem, readExternalEventItem, readQueryItem, readReadModelItem } from './readSliceItems';\nimport { readSliceSpecification } from './readSpecification';\n\nconst readSchedule = (node: DocumentNode | undefined): AutomationTriggerSchedule | undefined =>\n node\n ? {\n intervalMinutes: node.number('intervalMinutes'),\n intervalHours: node.number('intervalHours'),\n timeOfDay: node.string('timeOfDay'),\n dayOfWeek: node.number('dayOfWeek'),\n dayOfMonth: node.number('dayOfMonth'),\n description: node.string('description'),\n }\n : undefined;\n\nconst readAutomationTrigger = (node: DocumentNode | undefined): AutomationTrigger | undefined => {\n if (!node) return undefined;\n const schedule = readSchedule(node.object('schedule'));\n const eventId = node.optionalGuid('eventId');\n return {\n type: node.enumValue('type'),\n description: node.string('description'),\n ...(schedule ? { schedule } : {}),\n ...(eventId ? { eventId } : {}),\n };\n};\n\nconst readAssigneeKind = (node: DocumentNode): AssigneeKind => {\n const kind = node.string('kind');\n const known = Object.values(AssigneeKind).find(value => value === kind);\n if (!known) throw new InvalidEventModelDocument(`${node.path}.kind`, `unknown assignee kind '${kind}'`);\n return known;\n};\n\nconst readAssignee = (node: DocumentNode | undefined): Assignee | undefined => {\n if (!node) return undefined;\n const avatar = node.optionalString('avatar');\n return {\n id: node.guid('id'),\n name: node.string('name'),\n kind: readAssigneeKind(node),\n ...(avatar ? { avatar } : {}),\n };\n};\n\nexport const readSlice = (node: DocumentNode): Slice => {\n const command = node.object('command');\n const readModel = node.object('readModel');\n const automationTrigger = readAutomationTrigger(node.object('automationTrigger'));\n const assignee = readAssignee(node.object('assignee'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n sliceType: node.enumValue('sliceType'),\n description: node.string('description'),\n status: node.enumValue('status'),\n collapsed: node.boolean('collapsed'),\n sortOrder: node.number('sortOrder'),\n externalEvents: node.array('externalEvents', readExternalEventItem),\n events: node.array('events', readEventItem),\n queries: node.array('queries', readQueryItem),\n actors: node.array('actors', readUserExperienceActor),\n specifications: node.array('specifications', readSliceSpecification),\n commentCount: node.number('commentCount'),\n ...(command ? { command: readCommandItem(command) } : {}),\n ...(readModel ? { readModel: readReadModelItem(readModel) } : {}),\n ...(automationTrigger ? { automationTrigger } : {}),\n ...(assignee ? { assignee } : {}),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Feature, Module, ModuleCollection, ScreenTemplate } from '../Model';\nimport type { DocumentNode } from './DocumentNode';\nimport { readActor } from './readActors';\nimport { readPosition } from './readBoardItems';\nimport { readSlice } from './readSlice';\n\nconst readScreenTemplate = (node: DocumentNode | undefined): ScreenTemplate | undefined =>\n node ? { id: node.string('id'), name: node.string('name') } : undefined;\n\nconst readFeature = (node: DocumentNode): Feature => {\n const screenTemplate = readScreenTemplate(node.object('screenTemplate'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n subFeatures: node.array('subFeatures', readFeature),\n slices: node.array('slices', readSlice),\n collapsed: node.boolean('collapsed'),\n rowCollapsed: node.boolean('rowCollapsed'),\n enabled: node.has('enabled') ? node.boolean('enabled') : true,\n commentCount: node.number('commentCount'),\n ...(screenTemplate ? { screenTemplate } : {}),\n };\n};\n\nconst readModule = (node: DocumentNode): Module => {\n const screenTemplate = readScreenTemplate(node.object('screenTemplate'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n features: node.array('features', readFeature),\n collapsed: node.boolean('collapsed'),\n sortOrder: node.number('sortOrder'),\n commentCount: node.number('commentCount'),\n ...(screenTemplate ? { screenTemplate } : {}),\n };\n};\n\nexport const readModuleCollection = (node: DocumentNode): ModuleCollection => ({\n id: node.guid('id'),\n position: readPosition(node.object('position')),\n modules: node.array('modules', readModule),\n actors: node.array('actors', readActor),\n});\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModel } from '../Model';\nimport { DocumentNode } from './DocumentNode';\nimport { readModuleCollectionLink, readStickyNote } from './readBoardItems';\nimport { readModuleCollection } from './readModules';\n\n// Reads an event model document from JSON — a fixture, a file the Viewer was given, or anything else\n// that did not come through Studio's own adapter. Unknown fields are ignored, enum values the package\n// does not know are kept for the board to show as unknown, and a missing optional section is left\n// absent. A value of the wrong type, or an identifier that is not a GUID, is an error that names\n// where in the document it was found.\nexport const readEventModelDocument = (json: unknown): EventModel => {\n const root = DocumentNode.root(json);\n return {\n id: root.guid('id'),\n name: root.string('name'),\n collections: root.array('collections', readModuleCollection),\n stickyNotes: root.array('stickyNotes', readStickyNote),\n links: root.array('links', readModuleCollectionLink),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModelMessages } from './EventModelMessages';\n\nexport const defaultEventModelMessages: EventModelMessages = {\n collapse: {\n expand: 'Expand',\n collapse: 'Collapse',\n },\n editableLabel: {\n doubleClickToRename: 'Double-click to rename',\n },\n erroredEntity: {\n module: 'module',\n feature: 'feature',\n slice: 'slice',\n couldNotBeRendered: (kind, error) => `This ${kind} could not be rendered: ${error}`,\n failedToRender: 'Failed to render',\n retry: 'Retry',\n },\n stickyNotes: {\n newNote: 'New Note',\n },\n links: {\n dragToLink: 'Drag onto another module collection to link them',\n removeLink: 'Remove link',\n },\n specificationStatus: {\n idle: 'Not run',\n running: 'Running…',\n passed: 'Last run succeeded',\n failed: 'Last run failed',\n inconclusive: 'Last run was inconclusive',\n },\n properties: {\n none: 'No properties',\n },\n references: {\n navigateToOriginal: 'Go to source',\n },\n interaction: {\n command: 'Command',\n readModel: 'Read Model',\n externalEvent: 'External Event',\n open: 'Open',\n doubleClickToRenamePrefix: 'Double-click to rename · Click to open',\n defineReadModel: 'Define read model',\n addExternalEvent: 'Add external event to translate from',\n searchExternalEvents: 'Search external events…',\n noExternalEventsAvailable: 'No events available in other modules',\n },\n events: {\n addEvent: 'Add Event',\n openEvent: 'Open Event:',\n doubleClickToRenamePrefix: 'Double-click to rename · Click to open Event:',\n addExistingEvent: 'Add existing event',\n searchEvents: 'Search events…',\n noEventsAvailable: 'No events available',\n noEventsYet: 'No events yet',\n projectedFromTheRight: 'Produced by a slice to the right. A State View only projects events from slices to its left.',\n },\n prototypes: {\n add: 'Add UI prototype',\n fromScratch: 'From scratch',\n fromScratchDescription: 'Start with an empty prototype',\n fromTemplate: 'From template',\n fromTemplateDescription: 'Start from a copy of an existing screen template',\n noTemplates: 'No templates available',\n },\n triggerControl: {\n add: 'Add trigger',\n edit: 'Edit trigger',\n kinds: {\n timer: { title: 'Timer', description: 'Runs on a fixed schedule with deterministic behavior.' },\n event: { title: 'Event', description: 'Runs when a specific event happens with deterministic behavior.' },\n custom: { title: 'Custom', description: 'Describe the behavior and let generation use the description.' },\n },\n },\n triggers: {\n timer: 'Timer trigger',\n event: 'Event trigger',\n custom: 'Custom trigger',\n },\n statuses: {\n notStarted: 'Not started',\n draft: 'Draft',\n analysis: 'Analysis',\n readyForImplementation: 'Ready for implementation',\n inProgress: 'In progress',\n readyForReview: 'Ready for review',\n done: 'Done',\n titlePrefix: 'Status:',\n change: 'Change status',\n },\n sliceTypes: {\n add: 'Add Slice',\n stateChange: 'State Change',\n stateChangeDescription: 'UI drives a command that produces events',\n stateView: 'State View',\n stateViewDescription: 'UI reads a projection built from events',\n automation: 'Automation',\n automationDescription: 'System reacts to events and issues commands',\n translator: 'Translator',\n translatorDescription: 'Translates external events into internal commands',\n },\n slices: {\n namePlaceholder: 'Slice…',\n empty: 'No slices yet — use + to add one',\n },\n modules: {\n add: 'Add', options: 'Module options', addModule: 'Add module',\n addModuleDescription: 'Add a module to this collection', addFeature: 'Add feature',\n addFeatureDescription: 'Add a feature to this module',\n },\n features: {\n empty: 'No features yet — use + to add one',\n add: 'Add',\n options: 'Feature options',\n addSubFeature: 'Add sub-feature',\n addSubFeatureDescription: 'Add a sub-feature to this feature',\n addSliceDescription: 'Choose a vertical slice type',\n back: 'Back',\n },\n details: {\n show: 'Show details',\n hide: 'Hide details',\n },\n specifications: {\n add: 'Add specification',\n namePlaceholder: 'Specification',\n delete: 'Delete specification',\n given: 'Given',\n when: 'When',\n then: 'Then',\n addItem: 'Add item',\n search: 'Search…',\n noItems: 'No items',\n addError: 'Add error',\n error: 'Error',\n missingRule: 'Rule no longer defined',\n defineReadModel: 'Define read model as given state',\n removeItem: 'Remove',\n },\n rows: {\n ui: 'UI',\n chat: 'Chat',\n system: 'System',\n interaction: 'Interaction',\n events: 'Events',\n },\n actors: {\n add: 'Add Actor',\n ui: 'UI Actor',\n system: 'System Actor',\n chat: 'Chat Actor',\n },\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext, useContext } from 'react';\nimport type { EventModelMessages } from './EventModelMessages';\nimport { defaultEventModelMessages } from './defaultEventModelMessages';\n\nexport const EventModelMessagesContext = createContext<EventModelMessages>(defaultEventModelMessages);\n\nexport const useEventModelMessages = (): EventModelMessages => useContext(EventModelMessagesContext);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport type { EventModelMessages } from './EventModelMessages';\nimport { EventModelMessagesContext } from './EventModelMessagesContext';\n\nexport interface EventModelMessagesProviderProps {\n messages: EventModelMessages;\n children?: React.ReactNode;\n}\n\nexport const EventModelMessagesProvider = ({ messages, children }: EventModelMessagesProviderProps) => (\n <EventModelMessagesContext.Provider value={messages}>{children}</EventModelMessagesContext.Provider>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * The board-level detail level for the event modeling editor.\n * - `full` is the default, fully interactive view.\n * - `overview` is a compact, read-only, high-level view that hides specifications and property/detail\n * cells and disables every building/editing affordance.\n */\nexport type DetailLevel = 'full' | 'overview';\n\nexport const defaultDetailLevel: DetailLevel = 'full';\n\n/**\n * Whether a slice is read-only for the given detail level. The `overview` level forces every slice\n * read-only regardless of its workflow status; the `full` level defers to the slice's own status.\n */\nexport function isSliceReadOnlyForDetailLevel(detailLevel: DetailLevel, statusReadOnly: boolean): boolean {\n return detailLevel === 'overview' || statusReadOnly;\n}\n\n/**\n * Whether property/detail cells are shown for the given detail level. The `overview` level hides them\n * entirely; the `full` level defers to the per-scope details-visibility toggle.\n */\nexport function areSliceDetailsVisibleForDetailLevel(detailLevel: DetailLevel, detailsVisible: boolean): boolean {\n return detailLevel !== 'overview' && detailsVisible;\n}\n\n/** Whether specifications are shown for the given detail level. The `overview` level hides them entirely. */\nexport function areSpecificationsVisibleForDetailLevel(detailLevel: DetailLevel): boolean {\n return detailLevel !== 'overview';\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport interface DetailsVisibilityState {\n global: boolean;\n modules: Record<string, boolean>;\n features: Record<string, boolean>;\n slices: Record<string, boolean>;\n}\n\nexport const defaultDetailsVisibilityState: DetailsVisibilityState = {\n global: false,\n modules: {},\n features: {},\n slices: {},\n};\n\nfunction toggleScope(scope: Record<string, boolean>, id: string): Record<string, boolean> {\n return {\n ...scope,\n [id]: !(scope[id] ?? false),\n };\n}\n\nexport function toggleGlobalDetails(state: DetailsVisibilityState): DetailsVisibilityState {\n return {\n ...state,\n global: !state.global,\n };\n}\n\nexport function toggleModuleDetails(state: DetailsVisibilityState, moduleId: string): DetailsVisibilityState {\n return {\n ...state,\n modules: toggleScope(state.modules, moduleId),\n };\n}\n\nexport function toggleFeatureDetails(state: DetailsVisibilityState, featureId: string): DetailsVisibilityState {\n return {\n ...state,\n features: toggleScope(state.features, featureId),\n };\n}\n\nexport function toggleSliceDetails(state: DetailsVisibilityState, sliceId: string): DetailsVisibilityState {\n return {\n ...state,\n slices: toggleScope(state.slices, sliceId),\n };\n}\n\nexport function areDetailsVisible(\n state: DetailsVisibilityState,\n moduleId: string,\n featureId: string,\n sliceId: string,\n): boolean {\n return state.global\n || Boolean(state.modules[moduleId])\n || Boolean(state.features[featureId])\n || Boolean(state.slices[sliceId]);\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { defaultDetailLevel } from './DetailLevel';\nimport { defaultDetailsVisibilityState } from './detailsVisibility';\nimport type { EventModelPresentation } from './EventModelPresentation';\n\nexport const defaultEventModelPresentation: EventModelPresentation = {\n detailLevel: defaultDetailLevel,\n visualizationMode: 'simplified',\n detailsVisibility: defaultDetailsVisibilityState,\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext, useContext } from 'react';\nimport type { EventModelPresentation } from './EventModelPresentation';\nimport { defaultEventModelPresentation } from './defaultEventModelPresentation';\n\nexport const EventModelPresentationContext = createContext<EventModelPresentation>(defaultEventModelPresentation);\n\nexport const useEventModelPresentation = (): EventModelPresentation => useContext(EventModelPresentationContext);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport type { EventModelPresentation } from './EventModelPresentation';\nimport { EventModelPresentationContext } from './EventModelPresentationContext';\n\nexport interface EventModelPresentationProviderProps {\n presentation: EventModelPresentation;\n children?: React.ReactNode;\n}\n\nexport const EventModelPresentationProvider = ({ presentation, children }: EventModelPresentationProviderProps) => (\n <EventModelPresentationContext.Provider value={presentation}>{children}</EventModelPresentationContext.Provider>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum RowType {\n UI = 'ui',\n Chat = 'chat',\n System = 'system',\n Interaction = 'interaction',\n Events = 'events',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { ReactNode, RefObject, useLayoutEffect, useState } from 'react';\nimport { createPortal } from 'react-dom';\n\n/** The side of the anchor the overlay prefers to open on. */\nexport type AnchoredOverlaySide = 'above' | 'below' | 'left' | 'right';\n\n/** Horizontal alignment relative to the anchor (for above/below overlays). */\nexport type AnchoredOverlayAlign = 'left' | 'right' | 'center';\n\nexport interface AnchoredOverlayProps {\n\n /** The element the overlay anchors to. */\n anchorRef: RefObject<HTMLElement | null>;\n\n /** Whether the overlay is shown. */\n open: boolean;\n\n /** The preferred side; above/below flip when the viewport leaves no room. */\n side?: AnchoredOverlaySide;\n\n /** Horizontal alignment for above/below overlays. */\n align?: AnchoredOverlayAlign;\n\n /** Gap between the anchor and the overlay in pixels. */\n gap?: number;\n\n /** The overlay content. */\n children: ReactNode;\n}\n\n/** Space on the preferred side under which an above/below overlay flips to the other side. */\nconst FLIP_THRESHOLD = 260;\n\ninterface Placement {\n top?: number;\n bottom?: number;\n left: number;\n transform?: string;\n}\n\nfunction computePlacement(anchor: DOMRect, side: AnchoredOverlaySide, align: AnchoredOverlayAlign, gap: number): Placement {\n if (side === 'left' || side === 'right') {\n return {\n top: anchor.top + (anchor.height / 2),\n left: side === 'right' ? anchor.right + gap : anchor.left - gap,\n transform: side === 'right' ? 'translateY(-50%)' : 'translate(-100%, -50%)',\n };\n }\n\n const spaceBelow = window.innerHeight - anchor.bottom - gap;\n const spaceAbove = anchor.top - gap;\n const resolved = side === 'below'\n ? (spaceBelow < FLIP_THRESHOLD && spaceAbove > spaceBelow ? 'above' : 'below')\n : (spaceAbove < FLIP_THRESHOLD && spaceBelow > spaceAbove ? 'below' : 'above');\n\n const horizontal = align === 'center'\n ? { left: anchor.left + (anchor.width / 2), transform: 'translateX(-50%)' }\n : align === 'right'\n ? { left: anchor.right, transform: 'translateX(-100%)' }\n : { left: anchor.left, transform: undefined };\n\n return resolved === 'below'\n ? { top: anchor.bottom + gap, ...horizontal }\n : { bottom: window.innerHeight - anchor.top + gap, ...horizontal };\n}\n\n/**\n * Renders its children into a fixed-position portal on <body>, anchored to an element on the board.\n * Board overlays (menus, pickers, tooltips) must float above everything: the slice columns use\n * content-visibility paint containment for virtualization, which clips any absolutely-positioned\n * descendant to the column box — portaling is what lets an overlay escape (the same approach the\n * Cratis Dropdown takes with appendTo=document.body).\n */\nexport const AnchoredOverlay: React.FC<AnchoredOverlayProps> = ({ anchorRef, open, side = 'below', align = 'left', gap = 8, children }) => {\n const [placement, setPlacement] = useState<Placement | undefined>();\n\n useLayoutEffect(() => {\n if (!open) {\n setPlacement(undefined);\n return;\n }\n const anchor = anchorRef.current?.getBoundingClientRect();\n if (!anchor) return;\n setPlacement(computePlacement(anchor, side, align, gap));\n }, [open, side, align, gap, anchorRef]);\n\n if (!open || !placement) return null;\n\n return createPortal(\n <div\n style={{\n position: 'fixed',\n zIndex: 1300,\n top: placement.top,\n bottom: placement.bottom,\n left: placement.left,\n transform: placement.transform,\n }}\n >\n {children}\n </div>,\n document.body);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './GridTooltip.css';\nimport React, { useRef, useState } from 'react';\nimport { AnchoredOverlay, AnchoredOverlaySide } from './AnchoredOverlay';\n\nexport type GridTooltipPosition = 'top' | 'bottom' | 'left' | 'right';\n\nexport interface GridTooltipProps {\n\n content: React.ReactNode;\n\n position?: GridTooltipPosition;\n\n children: React.ReactNode;\n}\n\nconst sideForPosition: Record<GridTooltipPosition, AnchoredOverlaySide> = {\n top: 'above',\n bottom: 'below',\n left: 'left',\n right: 'right',\n};\n\n/**\n * A small hover tooltip for canvas cards and controls. The bubble portals to <body> through\n * AnchoredOverlay so it floats above the whole canvas — an inline absolutely-positioned bubble would be\n * clipped by paint containment (content-visibility) near a scroll/zoom boundary.\n *\n * Pressing the anchor dismisses the bubble and keeps it dismissed until the pointer leaves. Cards that\n * open an editor on click render it *over* the card without the pointer moving — so the browser never\n * re-hit-tests and the anchor would otherwise stay \"hovered\", leaving the property list floating on top\n * of the editor the user is now typing in.\n *\n * Hover is tracked for mouse pointers only: a touch tap synthesizes an enter with no matching leave,\n * which would strand the bubble on screen on a tablet.\n */\nexport const GridTooltip: React.FC<GridTooltipProps> = ({ content, position = 'top', children }) => {\n const anchorRef = useRef<HTMLSpanElement>(null);\n const [isHovered, setIsHovered] = useState(false);\n const [isDismissed, setIsDismissed] = useState(false);\n\n const handlePointerEnter = (event: React.PointerEvent<HTMLSpanElement>) => {\n if (event.pointerType !== 'mouse') return;\n setIsHovered(true);\n };\n\n const handlePointerLeave = () => {\n setIsHovered(false);\n setIsDismissed(false);\n };\n\n return (\n <span\n ref={anchorRef}\n className='grid-tooltip-root'\n onPointerEnter={handlePointerEnter}\n onPointerLeave={handlePointerLeave}\n onPointerDown={() => setIsDismissed(true)}\n >\n {children}\n <AnchoredOverlay anchorRef={anchorRef} open={isHovered && !isDismissed} side={sideForPosition[position]} gap={6} align='center'>\n <span className='grid-tooltip-bubble' role='tooltip'>\n {content}\n </span>\n </AnchoredOverlay>\n </span>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceStatus } from '../Model';\nimport { type DetailLevel, isSliceReadOnlyForDetailLevel } from '../Presentation';\n\n// A slice's content is read-only when the board is, when the overview detail level is showing, or when its\n// workflow status says the work is under review or finished. Its status pill stays live regardless, so a\n// slice can always be moved out of a read-only status.\nexport const resolveSliceReadOnly = (boardReadOnly: boolean, detailLevel: DetailLevel, status: SliceStatus): boolean =>\n boardReadOnly || isSliceReadOnlyForDetailLevel(detailLevel, status === SliceStatus.readyForReview || status === SliceStatus.done);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext } from 'react';\nimport type { BoardInteraction } from './BoardInteraction';\n\nexport const emptyBoardInteraction: BoardInteraction = { editing: {}, actions: {}, selection: {}, navigation: {} };\n\nexport const BoardInteractionContext = createContext<BoardInteraction>(emptyBoardInteraction);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { useContext, useMemo } from 'react';\nimport type { BoardInteraction } from './BoardInteraction';\nimport { BoardInteractionContext } from './BoardInteractionContext';\n\nexport type BoardInteractionProviderProps = Partial<BoardInteraction> & {\n children?: React.ReactNode;\n};\n\n// Offers editing callbacks, actions, selection and navigation to the board beneath it. Nested providers\n// add to what an outer one offers: whatever an inner one supplies wins, entry by entry.\nexport const BoardInteractionProvider = ({ editing, actions, selection, navigation, children }: BoardInteractionProviderProps) => {\n const outer = useContext(BoardInteractionContext);\n const value = useMemo<BoardInteraction>(() => ({\n editing: { ...outer.editing, ...editing },\n actions: { ...outer.actions, ...actions },\n selection: { ...outer.selection, ...selection },\n navigation: { ...outer.navigation, ...navigation },\n }), [outer, editing, actions, selection, navigation]);\n\n return <BoardInteractionContext.Provider value={value}>{children}</BoardInteractionContext.Provider>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext } from 'react';\n\nexport const BoardReadOnlyContext = createContext(false);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport type { BoardInteraction } from './BoardInteraction';\nimport { BoardInteractionProvider } from './BoardInteractionProvider';\nimport { BoardReadOnlyContext } from './BoardReadOnlyContext';\n\nexport interface BoardProviderProps extends Partial<BoardInteraction> {\n // When set, no editing callback or action is honored and no affordance is drawn.\n readOnly?: boolean;\n children?: React.ReactNode;\n}\n\nexport const BoardProvider = ({ readOnly = false, editing, actions, selection, navigation, children }: BoardProviderProps) => (\n <BoardReadOnlyContext.Provider value={readOnly}>\n <BoardInteractionProvider editing={editing} actions={actions} selection={selection} navigation={navigation}>\n {children}\n </BoardInteractionProvider>\n </BoardReadOnlyContext.Provider>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useContext, useMemo } from 'react';\nimport { useEventModelMessages } from '../Messages';\nimport { useEventModelPresentation } from '../Presentation';\nimport type { BoardContextValue } from './BoardContextValue';\nimport { BoardInteractionContext } from './BoardInteractionContext';\nimport { BoardReadOnlyContext } from './BoardReadOnlyContext';\n\nexport const useBoard = (): BoardContextValue => {\n const readOnly = useContext(BoardReadOnlyContext);\n const presentation = useEventModelPresentation();\n const messages = useEventModelMessages();\n const { editing, actions, selection, navigation } = useContext(BoardInteractionContext);\n return useMemo(() => ({\n readOnly,\n presentation,\n messages,\n editing: readOnly ? {} : editing,\n actions: readOnly ? {} : actions,\n selection,\n navigation,\n }), [readOnly, presentation, messages, editing, actions, selection, navigation]);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Canvas, type CanvasProps } from '@cratis/components/Canvas';\nimport type { BoardCanvasChrome } from './BoardCanvasChrome';\nimport { useBoard } from './useBoard';\n\nexport interface BoardCanvasProps extends Omit<CanvasProps, 'controlsLabels' | 'controlsIcons' | 'controlsGlassSurface' | 'captureAttributes' | 'controlsFollowViewportInsets' | 'readOnly'> {\n chrome?: BoardCanvasChrome;\n}\n\n// The canvas the board is drawn on. It offers help only on an editable board. The canvas itself is never\n// made read-only: that would make the board inert under a panning overlay, while a read-only board still\n// collapses, opens prototypes and shows tooltips - the board withholds the editing on its own.\nexport const BoardCanvas = ({ chrome = {}, onHelp, helpTitle, ...props }: BoardCanvasProps) => {\n const { readOnly } = useBoard();\n return (\n <Canvas\n controlsLabels={chrome.controlsLabels}\n controlsIcons={chrome.controlsIcons}\n controlsGlassSurface={chrome.controlsSurface}\n captureAttributes={chrome.captureAttributes}\n controlsFollowViewportInsets={chrome.controlsFollowViewportInsets}\n onHelp={readOnly ? undefined : onHelp}\n helpTitle={readOnly ? undefined : helpTitle}\n {...props}\n />\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef, type PointerEvent } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { Position } from '../Model';\nimport type { CollectionMoved, CollectionMoving } from './CollectionMoved';\n\nexport interface CollectionMoveHandlers {\n onPointerDown: (event: PointerEvent<HTMLDivElement>) => void;\n onPointerMove: (event: PointerEvent<HTMLDivElement>) => void;\n onPointerUp: () => void;\n}\n\ninterface Move {\n lastX: number;\n lastY: number;\n position: Position;\n moved: boolean;\n}\n\n// Moves a module collection by dragging its handle: every pointer move is reported as a delta in canvas\n// units, and the position it ends at is reported once, when the pointer is let go after actually moving.\nexport function useCollectionMove(\n collectionId: Guid,\n position: Position,\n getZoom: () => number,\n onCollectionMoving?: CollectionMoving,\n onCollectionMoved?: CollectionMoved,\n): CollectionMoveHandlers {\n const move = useRef<Move | undefined>(undefined);\n\n return {\n onPointerDown: event => {\n const target = event.target;\n if (target instanceof Element && target.closest('button, input, .event-modeling-grid-editable-label')) return;\n event.stopPropagation();\n move.current = { lastX: event.clientX, lastY: event.clientY, position, moved: false };\n event.currentTarget.setPointerCapture(event.pointerId);\n },\n onPointerMove: event => {\n const current = move.current;\n if (!current) return;\n const zoom = getZoom();\n const deltaX = (event.clientX - current.lastX) / zoom;\n const deltaY = (event.clientY - current.lastY) / zoom;\n move.current = {\n lastX: event.clientX,\n lastY: event.clientY,\n position: { x: current.position.x + deltaX, y: current.position.y + deltaY },\n moved: true,\n };\n onCollectionMoving?.(collectionId, deltaX, deltaY);\n },\n onPointerUp: () => {\n const current = move.current;\n move.current = undefined;\n if (current?.moved) onCollectionMoved?.(collectionId, current.position);\n },\n };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './CollectionMoveHandle.css';\nimport { useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { Position } from '../Model';\nimport { useBoard } from '../Board';\nimport type { CollectionMoved, CollectionMoving } from './CollectionMoved';\nimport { useCollectionMove } from './useCollectionMove';\n\nexport interface CollectionMoveHandleProps {\n collectionId: Guid;\n // Where the collection is when the drag starts.\n position: Position;\n // Reads the current canvas zoom, so screen drag deltas convert to canvas deltas.\n getZoom: () => number;\n topOffset?: number;\n onCollectionMoving?: CollectionMoving;\n // The handle exists only when the board is editable and this is supplied.\n onCollectionMoved?: CollectionMoved;\n}\n\n// The grip that moves a module collection around the canvas.\nexport const CollectionMoveHandle = ({ onCollectionMoved, ...props }: CollectionMoveHandleProps) => {\n const { readOnly } = useBoard();\n return readOnly || !onCollectionMoved ? undefined : <MoveHandle {...props} onCollectionMoved={onCollectionMoved} />;\n};\n\nconst MoveHandle = ({ collectionId, position, getZoom, topOffset = 0, onCollectionMoving, onCollectionMoved }: CollectionMoveHandleProps) => {\n const [dragging, setDragging] = useState(false);\n const handlers = useCollectionMove(collectionId, position, getZoom, onCollectionMoving, onCollectionMoved);\n\n return (\n <div\n className={`collection-drag-handle ${dragging ? 'collection-drag-handle--dragging' : ''}`}\n style={{ top: `${topOffset}px` }}\n onPointerDown={event => {\n setDragging(true);\n handlers.onPointerDown(event);\n }}\n onPointerMove={handlers.onPointerMove}\n onPointerUp={() => {\n setDragging(false);\n handlers.onPointerUp();\n }}\n >\n <i className='pi pi-arrows-alt' />\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\nimport type { Position } from '../Model';\n\nexport interface CollectionItem {\n id: Guid;\n position: Position;\n}\n\nexport interface CollectionState<T extends CollectionItem> {\n snapshot: T[];\n collections: T[];\n additions: T[];\n locallyMovedAt: ReadonlyMap<string, number>;\n pendingMoveIds: ReadonlySet<string>;\n contentSignature: string;\n}\n\nconst MOVE_GUARD_MS = 4000;\n\nexport const collectionContentSignature = (collections: readonly CollectionItem[]): string =>\n JSON.stringify(collections, (key, value) => key === 'position' ? undefined : value);\n\nexport function createCollectionState<T extends CollectionItem>(snapshot: T[]): CollectionState<T> {\n return { snapshot, collections: snapshot, additions: [], locallyMovedAt: new Map(), pendingMoveIds: new Set(), contentSignature: collectionContentSignature(snapshot) };\n}\n\nexport function reconcileCollections<T extends CollectionItem>(state: CollectionState<T>, snapshot: T[], now: number): CollectionState<T> {\n const signature = collectionContentSignature(snapshot);\n const snapshotById = new Map(snapshot.map(collection => [collection.id.toString(), collection]));\n const localById = new Map(state.collections.map(collection => [collection.id.toString(), collection]));\n const additions = state.additions.filter(collection => !snapshotById.has(collection.id.toString()));\n if (signature !== state.contentSignature) {\n const collections = snapshot.map(remote => {\n const local = localById.get(remote.id.toString());\n return local && now - (state.locallyMovedAt.get(remote.id.toString()) ?? 0) < MOVE_GUARD_MS\n ? { ...remote, position: local.position } : remote;\n });\n return { ...state, snapshot, contentSignature: signature, additions, collections: [...collections, ...additions] };\n }\n let positionsChanged = false;\n const updated = state.collections.map(local => {\n const remote = snapshotById.get(local.id.toString());\n if (!remote || now - (state.locallyMovedAt.get(local.id.toString()) ?? 0) < MOVE_GUARD_MS) return local;\n if ((local.position?.x ?? 0) === (remote.position?.x ?? 0) &&\n (local.position?.y ?? 0) === (remote.position?.y ?? 0)) return local;\n positionsChanged = true;\n return { ...local, position: remote.position };\n });\n return { ...state, snapshot, additions, collections: positionsChanged ? updated : state.collections };\n}\n\nexport function revertCollectionMove<T extends CollectionItem>(state: CollectionState<T>, id: Guid): CollectionState<T> {\n const remote = state.snapshot.find(collection => collection.id.equals(id));\n if (!remote) return state;\n const movedAt = new Map(state.locallyMovedAt);\n movedAt.delete(id.toString());\n return { ...state, locallyMovedAt: movedAt, collections: state.collections.map(collection =>\n collection.id.equals(id) ? { ...collection, position: remote.position } : collection) };\n}\n\nexport function beginCollectionMovePersistence<T extends CollectionItem>(state: CollectionState<T>, id: Guid): CollectionState<T> {\n const key = id.toString();\n if (state.pendingMoveIds.has(key)) return state;\n return { ...state, pendingMoveIds: new Set([...state.pendingMoveIds, key]) };\n}\n\nexport function endCollectionMovePersistence<T extends CollectionItem>(state: CollectionState<T>, id: Guid): CollectionState<T> {\n const key = id.toString();\n if (!state.pendingMoveIds.has(key)) return state;\n const pendingMoveIds = new Set(state.pendingMoveIds);\n pendingMoveIds.delete(key);\n return { ...state, pendingMoveIds };\n}\n\nexport function moveCollection<T extends CollectionItem>(state: CollectionState<T>, id: Guid, deltaX: number, deltaY: number, now: number): CollectionState<T> {\n if (state.pendingMoveIds.has(id.toString())) return state;\n const movedAt = new Map(state.locallyMovedAt);\n movedAt.set(id.toString(), now);\n return { ...state, locallyMovedAt: movedAt, collections: state.collections.map(collection =>\n collection.id.equals(id) ? { ...collection, position: {\n x: (collection.position?.x ?? 0) + deltaX, y: (collection.position?.y ?? 0) + deltaY,\n } } : collection) };\n}\n\n// The cascade is visual only; never persist the displaced coordinates.\nexport const OVERLAP_STEP = 48;\nexport const SAME_SPOT_TOLERANCE = 0.5;\nexport function resolveOverlappingCollections<T extends CollectionItem>(collections: T[]): T[] {\n const occupied: Position[] = [];\n let changed = false;\n const resolved = collections.map(collection => {\n const position = { x: collection.position?.x ?? 0, y: collection.position?.y ?? 0 };\n while (occupied.some(spot => Math.abs(spot.x - position.x) < SAME_SPOT_TOLERANCE && Math.abs(spot.y - position.y) < SAME_SPOT_TOLERANCE)) {\n position.x += OVERLAP_STEP;\n position.y += OVERLAP_STEP;\n }\n occupied.push(position);\n if (position.x === (collection.position?.x ?? 0) && position.y === (collection.position?.y ?? 0)) return collection;\n changed = true;\n return { ...collection, position };\n });\n return changed ? resolved : collections;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState, type SetStateAction } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { beginCollectionMovePersistence, createCollectionState, endCollectionMovePersistence, moveCollection, reconcileCollections, revertCollectionMove, type CollectionItem, type CollectionState } from './collectionState';\n\nexport interface CollectionsAreaOptions<T extends CollectionItem> {\n initialCollections: T[];\n onAddCollection?: (x: number, y: number, collections: T[]) => Promise<T | undefined>;\n onCollectionMoved?: (id: Guid, position: { x: number; y: number }) => Promise<boolean>;\n onCollectionsChange?: (collections: T[]) => void;\n onPersistenceError?: (error: unknown) => void;\n}\n\nexport interface CollectionsArea<T extends CollectionItem> {\n collections: T[];\n pendingMoveIds: ReadonlySet<string>;\n setCollections: (updater: SetStateAction<T[]>) => void;\n addCollection: (x: number, y: number) => Promise<void>;\n moveCollection: (id: Guid, deltaX: number, deltaY: number) => void;\n collectionMoved: (id: Guid, position: { x: number; y: number }) => Promise<void>;\n canMove: boolean;\n canAdd: boolean;\n}\n\nexport function useCollectionsArea<T extends CollectionItem>({\n initialCollections, onAddCollection, onCollectionMoved, onCollectionsChange, onPersistenceError,\n}: CollectionsAreaOptions<T>): CollectionsArea<T> {\n const { readOnly } = useBoard();\n const [visibleState, setVisibleState] = useState(() => createCollectionState(initialCollections));\n const stateRef = useRef<CollectionState<T>>(visibleState);\n const { collections, pendingMoveIds } = visibleState;\n const adding = useRef(false);\n const isFirstNotification = useRef(true);\n const apply = useCallback((transition: (state: CollectionState<T>) => CollectionState<T>) => {\n const next = transition(stateRef.current);\n stateRef.current = next;\n setVisibleState(next);\n }, []);\n useEffect(() => {\n if (initialCollections !== stateRef.current.snapshot) {\n apply(previous => reconcileCollections(previous, initialCollections, Date.now()));\n }\n }, [initialCollections, apply]);\n useEffect(() => {\n if (isFirstNotification.current) {\n isFirstNotification.current = false;\n return;\n }\n onCollectionsChange?.(collections);\n }, [collections, onCollectionsChange]);\n\n // Nested edits update the local tree without replacing the observable snapshot.\n const setCollections = useCallback((updater: SetStateAction<T[]>) => {\n apply(previous => ({ ...previous, collections: typeof updater === 'function' ? updater(previous.collections) : updater }));\n }, [apply]);\n const addCollection = useCallback(async (x: number, y: number) => {\n if (readOnly || !onAddCollection || adding.current) return;\n adding.current = true;\n try {\n const added = await onAddCollection(x, y, stateRef.current.collections);\n if (added) apply(previous => previous.collections.some(collection => collection.id.equals(added.id))\n ? previous : { ...previous,\n additions: [...previous.additions, added], collections: [...previous.collections, added],\n });\n } catch (error) {\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n } finally { adding.current = false; }\n }, [readOnly, onAddCollection, onPersistenceError, apply]);\n const move = useCallback((id: Guid, deltaX: number, deltaY: number) => {\n if (readOnly || !onCollectionMoved || stateRef.current.pendingMoveIds.has(id.toString())) return;\n apply(previous => moveCollection(previous, id, deltaX, deltaY, Date.now()));\n }, [readOnly, onCollectionMoved, apply]);\n const moved = useCallback(async (id: Guid, position: { x: number; y: number }) => {\n if (readOnly || !onCollectionMoved || stateRef.current.pendingMoveIds.has(id.toString())) return;\n apply(previous => beginCollectionMovePersistence(previous, id));\n try {\n const succeeded = await onCollectionMoved(id, position);\n if (!succeeded) apply(previous => revertCollectionMove(previous, id));\n } catch (error) {\n apply(previous => revertCollectionMove(previous, id));\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n } finally { apply(previous => endCollectionMovePersistence(previous, id)); }\n }, [readOnly, onCollectionMoved, onPersistenceError, apply]);\n return { collections, pendingMoveIds, setCollections, addCollection, moveCollection: move, collectionMoved: moved,\n canMove: !readOnly && !!onCollectionMoved, canAdd: !readOnly && !!onAddCollection };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { RowType } from '../Rows/RowType';\n\n// The sizes the board is laid out with, in canvas units.\nexport const boardMetrics = {\n minSliceWidth: 220,\n minPillWidth: 150,\n sliceWidth: 220,\n sliceWidthDouble: 350,\n translatorSliceWidth: 360,\n sliceGap: 8,\n collapsedFeatureWidth: 80,\n collapsedModuleWidth: 100,\n collapsedSliceWidth: 36,\n headerHeight: 44,\n roleRowHeight: 80,\n specificationSectionHeight: 80,\n // How many event cards sit side by side in a cell.\n itemsPerRow: 2,\n uiCardHeight: 84,\n cardHeight: 56,\n cellVerticalPadding: 24,\n} as const satisfies Record<string, number>;\n\n// The height of each row before its content asks for more.\nexport const rowHeights: Readonly<Record<RowType, number>> = {\n [RowType.UI]: 160,\n [RowType.Chat]: 160,\n [RowType.System]: 120,\n [RowType.Interaction]: 160,\n [RowType.Events]: 160,\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { JsonSchema, JsonSchemaProperty } from '@cratis/components/SchemaEditor';\n\nexport interface SchemaProperty {\n name: string;\n type: string;\n}\n\n// The type a property's badge shows. Mirrors the property types the board's schema editors use, so a\n// badge reads the same on the face of a card as in its editor.\nconst typeOf = (value: JsonSchemaProperty): string => {\n const { type, format, items } = value;\n switch (type) {\n case 'string':\n if (format === 'date') return 'date';\n if (format === 'time') return 'time';\n return 'string';\n case 'number':\n case 'integer':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'object':\n return 'object';\n case 'array':\n if (items?.type === 'number' || items?.type === 'integer') return 'numberArray';\n if (items?.type === 'object') return 'objectArray';\n return 'stringArray';\n default:\n return 'string';\n }\n};\n\nconst isSchema = (value: unknown): value is JsonSchema => !!value && typeof value === 'object' && !Array.isArray(value);\n\nconst parse = (schema?: string | JsonSchema): JsonSchema | undefined => {\n if (!schema) return undefined;\n if (typeof schema !== 'string') return schema;\n try {\n const parsed: unknown = JSON.parse(schema);\n return isSchema(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n};\n\n// The top-level properties of a schema, in declaration order. A string that is not a JSON document\n// has none.\nexport const topLevelSchemaProperties = (schema?: string | JsonSchema): SchemaProperty[] => {\n const properties = parse(schema)?.properties;\n return properties ? Object.entries(properties).map(([name, value]) => ({ name, type: typeOf(value) })) : [];\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { JsonSchema } from '@cratis/components/SchemaEditor';\nimport { topLevelSchemaProperties } from '../Properties/schemaProperties';\n\n// What a card is drawn from, as far as its height goes: the schema whose properties it can list.\nexport interface CardLayoutInput {\n schema?: string | JsonSchema;\n}\n\n// The card face and its property list, as the theme and SchemaTooltipProperties draw them.\nconst face = { minHeight: 40, paddingY: 10, titleHeight: 16 } as const;\nconst propertyList = { marginTop: 6, rowHeight: 20, gap: 3, emptyHeight: 13 } as const;\n\n// How tall a card is drawn when it lists its properties - the face's padding and title, then one row per\n// top-level property, or the line saying there are none.\nexport function detailedCardHeight(card: CardLayoutInput): number {\n const count = topLevelSchemaProperties(card.schema).length;\n const list = count === 0 ? propertyList.emptyHeight : count * propertyList.rowHeight + (count - 1) * propertyList.gap;\n return Math.max(face.minHeight, face.paddingY * 2 + face.titleHeight + propertyList.marginTop + list);\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\nimport { RowType } from '../Rows/RowType';\nimport { boardMetrics, rowHeights } from './boardMetrics';\nimport { type CardLayoutInput, detailedCardHeight } from './cardHeight';\n\n// What the layout needs to know about a slice. The cards' schemas only matter when the slice shows the\n// properties of its cards, which makes them taller.\nexport interface SliceLayoutInput {\n sliceType: SliceType;\n events: readonly unknown[];\n command?: CardLayoutInput;\n readModel?: CardLayoutInput;\n}\n\n// The room above and below the cards of the interaction row, which the connectors to the rows around it\n// run through.\nconst interactionConnectorRoom = 24;\nconst cardRowGap = 8;\n\n// How wide a slice's column is: the slice types that draw a command or a translation beside their events\n// always take the wide column, the others grow with their events.\nexport function sliceColumnWidth(slice: SliceLayoutInput | { sliceType: SliceType; eventCount: number }): number {\n if (slice.sliceType === SliceType.translator || slice.sliceType === SliceType.automation || slice.sliceType === SliceType.stateChange) {\n return boardMetrics.translatorSliceWidth;\n }\n const eventCount = 'eventCount' in slice ? slice.eventCount : slice.events.length;\n const baseWidth = eventCount >= boardMetrics.itemsPerRow ? boardMetrics.sliceWidthDouble : boardMetrics.sliceWidth;\n return slice.sliceType === SliceType.stateView ? Math.round(baseWidth * 1.5) : baseWidth;\n}\n\n// How tall a row has to be for one slice. The events row grows as its cards wrap; when the slice shows\n// the properties of its cards, the events and interaction rows grow to hold the taller cards.\nexport function rowHeightForSlice(rowType: RowType, slice: SliceLayoutInput, showDetails = false): number {\n switch (rowType) {\n case RowType.Events: return eventsRowHeight(slice, showDetails);\n case RowType.Interaction: return showDetails ? interactionRowHeight(slice) : rowHeights[rowType];\n default: return rowHeights[rowType];\n }\n}\n\nfunction eventsRowHeight(slice: SliceLayoutInput, showDetails: boolean): number {\n const { events } = slice;\n if (events.length === 0) return rowHeights[RowType.Events];\n const cardRows: number[] = [];\n for (let index = 0; index < events.length; index += boardMetrics.itemsPerRow) {\n const row = events.slice(index, index + boardMetrics.itemsPerRow);\n cardRows.push(showDetails\n ? Math.max(boardMetrics.cardHeight, ...row.map(event => detailedCardHeight(cardOf(event))))\n : boardMetrics.cardHeight);\n }\n const height = cardRows.reduce((total, rowHeight) => total + rowHeight, 0) + (cardRows.length - 1) * cardRowGap;\n return Math.max(rowHeights[RowType.Events], height + boardMetrics.cellVerticalPadding);\n}\n\nfunction interactionRowHeight(slice: SliceLayoutInput): number {\n const cards = [slice.command, slice.readModel].filter(card => card !== undefined);\n if (cards.length === 0) return rowHeights[RowType.Interaction];\n return Math.max(rowHeights[RowType.Interaction], Math.max(...cards.map(detailedCardHeight)) + interactionConnectorRoom * 2);\n}\n\n// An event as a card; anything that does not carry a schema is a card without properties.\nconst cardOf = (event: unknown): CardLayoutInput =>\n event !== null && typeof event === 'object' && 'schema' in event ? event as CardLayoutInput : {};\n\n// The height of each row across a whole collection: the tallest any slice in it needs, so every slice's\n// rows line up. A slice that shows the properties of its cards says so.\nexport function computeGlobalRowHeights(slices: readonly { slice: SliceLayoutInput; showDetails?: boolean }[], contentRows: readonly RowType[]): Record<RowType, number> {\n const result: Record<RowType, number> = { ...rowHeights };\n for (const rowType of contentRows) {\n result[rowType] = slices.length === 0\n ? rowHeights[rowType]\n : Math.max(...slices.map(({ slice, showDetails }) => rowHeightForSlice(rowType, slice, showDetails)));\n }\n return result;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { ActorType } from '../Model';\nimport { RowType } from '../Rows/RowType';\n\n// The kind of actor a row of each actor type holds, and the row an actor of each kind sits in.\nexport const actorTypeOfRow = (rowType: RowType): ActorType | undefined => {\n switch (rowType) {\n case RowType.UI: return ActorType.UIRole;\n case RowType.System: return ActorType.systemRole;\n case RowType.Chat: return ActorType.chatRole;\n default: return undefined;\n }\n};\n\nexport const rowOfActorType = (actorType: ActorType): RowType => {\n switch (actorType) {\n case ActorType.UIRole: return RowType.UI;\n case ActorType.systemRole: return RowType.System;\n case ActorType.chatRole: return RowType.Chat;\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { ActorType, SliceType } from '../Model';\nimport { actorTypeOfRow } from '../RowLabels/actorRows';\nimport { RowType } from '../Rows/RowType';\n\n// Each slice type owns the kinds of actor, and therefore the actor rows, it can take part in. There is no\n// implicit system row and no hard-coded UI row.\nconst supportedActors: Readonly<Record<SliceType, ReadonlySet<ActorType>>> = {\n [SliceType.stateChange]: new Set([ActorType.UIRole, ActorType.systemRole, ActorType.chatRole]),\n [SliceType.stateView]: new Set([ActorType.UIRole, ActorType.systemRole, ActorType.chatRole]),\n [SliceType.automation]: new Set([ActorType.systemRole, ActorType.chatRole]),\n [SliceType.translator]: new Set([ActorType.systemRole, ActorType.chatRole]),\n};\n\nexport const sliceTypeSupportsActor = (sliceType: SliceType, actorType: ActorType): boolean =>\n supportedActors[sliceType].has(actorType);\n\n// Whether a slice of this type draws anything in the row; rows that hold no actors are drawn by every type.\nexport const sliceTypeSupportsRow = (sliceType: SliceType, rowType: RowType): boolean => {\n const actorType = actorTypeOfRow(rowType);\n return actorType === undefined || sliceTypeSupportsActor(sliceType, actorType);\n};\n\n// The actors of a collection that sit in a row; none for a row that holds no actors.\nexport const actorsForRow = <TActor extends { actorType: ActorType }>(actors: readonly TActor[], rowType: RowType): TActor[] => {\n const actorType = actorTypeOfRow(rowType);\n return actorType === undefined ? [] : actors.filter(actor => actor.actorType === actorType);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { startTransition } from 'react';\nimport { canvasGesture } from '@cratis/components/Canvas';\n\ntype ApplyVerdict = (inView: boolean) => void;\n\n// How expensive applying a verdict is. A 'light' subtree (one slice column's body) commits in a few\n// milliseconds and may mount mid-gesture; a 'heavy' one (a whole collection grid) costs tens of\n// milliseconds — enough to break the gesture's frame budget on its own — so it waits for the settle.\nexport type VerdictWeight = 'light' | 'heavy';\n\ninterface PendingVerdict {\n verdict: boolean;\n // Distance from the element to the viewport center, so nearer content mounts first.\n distance: number;\n weight: VerdictWeight;\n}\n\n// A flush frame under this is cheap — the apply budget may grow.\nconst GROW_BELOW_MS = 12;\n\n// A flush frame over this ran long — the apply budget halves.\nconst SHRINK_ABOVE_MS = 24;\n\n// Two flushes further apart than this are not consecutive frames — no cost signal.\nconst CONSECUTIVE_FRAME_MS = 100;\n\nconst INITIAL_APPLY_BUDGET = 1;\nconst MIN_APPLY_BUDGET = 1;\nconst MAX_APPLY_BUDGET = 24;\n\n// While a gesture is in motion only a few mounts run per frame, and only on cheap frames.\nconst GESTURE_APPLY_BUDGET = 3;\n\nconst pending = new Map<ApplyVerdict, PendingVerdict>();\nlet frameScheduled = false;\n\n// The apply budget adapts to what a verdict actually costs on this board: a placeholder-sized mount\n// (a virtualized collection at far zoom) is ~1ms so dozens fit in a frame, while mounting — or\n// tearing down — a full collection grid can cost tens of ms so only one does. The cost of a flush\n// shows up as the gap to the NEXT scheduled flush frame (React commits the batch between the two\n// rAFs), so the budget grows while flush frames stay cheap and halves when one runs long. A fresh\n// burst after a quiet gap may be a different cost regime entirely (cheap placeholders vs heavy\n// grids), so the budget resets rather than starting a new burst at its grown size.\nlet applyBudget = INITIAL_APPLY_BUDGET;\nlet lastFlushAt = 0;\nlet lastFlushApplied = false;\n\nfunction nearestFirst(verdictFilter: (entry: PendingVerdict) => boolean): [ApplyVerdict, PendingVerdict][] {\n return [...pending].filter(([, entry]) => verdictFilter(entry))\n .sort((left, right) => left[1].distance - right[1].distance);\n}\n\nfunction processQueue(): void {\n frameScheduled = false;\n const now = performance.now();\n const frameMs = now - lastFlushAt;\n const consecutive = frameMs < CONSECUTIVE_FRAME_MS;\n if (lastFlushApplied && consecutive) {\n if (frameMs > SHRINK_ABOVE_MS) applyBudget = Math.max(MIN_APPLY_BUDGET, Math.ceil(applyBudget / 2));\n else if (frameMs < GROW_BELOW_MS) applyBudget = Math.min(MAX_APPLY_BUDGET, applyBudget + 1);\n } else if (!consecutive) {\n applyBudget = INITIAL_APPLY_BUDGET;\n }\n lastFlushApplied = false;\n\n // Mid-gesture the queue no longer holds still: MOUNTS — light and heavy alike — run a few per\n // cheap frame, nearest to the viewport first, so content panned into view fills in progressively\n // instead of popping in as one burst at the settle. Heavy mounts are safe here because the\n // mid-gesture path renders them as interruptible transitions; holding them until the settle is\n // what made a continuous trackpad scroll (which keeps the gesture alive indefinitely) show blank\n // frames until the user stopped. Unmounts still wait for the settle — tearing down a subtree is\n // not time-sliceable — and when the last frame ran long this frame mounts nothing, giving the\n // gesture room.\n const gestureActive = canvasGesture.isActive;\n const frameHasRoom = !consecutive || frameMs <= SHRINK_ABOVE_MS;\n if (!gestureActive || frameHasRoom) {\n lastFlushAt = now;\n const budget = gestureActive ? Math.min(applyBudget, GESTURE_APPLY_BUDGET) : applyBudget;\n let applied = 0;\n for (const [apply, entry] of nearestFirst(entry => !gestureActive || entry.verdict)) {\n pending.delete(apply);\n if (gestureActive) {\n // Mid-gesture mounts render as a React transition: the render is time-sliced and\n // interruptible, so a body that takes tens of milliseconds to render fills in\n // across idle slices instead of blocking a gesture frame.\n startTransition(() => apply(entry.verdict));\n } else {\n apply(entry.verdict);\n }\n if (++applied >= budget) break;\n }\n lastFlushApplied = applied > 0;\n }\n\n if (pending.size > 0) schedule();\n}\n\nfunction schedule(): void {\n if (frameScheduled) return;\n frameScheduled = true;\n requestAnimationFrame(processQueue);\n}\n\n// Listens for the end of a canvas gesture from the first verdict on, rather than when the module is\n// loaded, so importing the board does no work until a board is actually drawn.\nlet listeningForGestures = false;\nfunction listenForGestures(): void {\n if (listeningForGestures) return;\n listeningForGestures = true;\n canvasGesture.subscribe(active => {\n if (!active && pending.size > 0) schedule();\n });\n}\n\n// Rate-limits viewport-virtualization verdicts so mounting/unmounting board subtrees never lands as\n// one giant React commit. IntersectionObserver delivers every element's verdict in a single task —\n// after a long pan or a zoom-out that can be hundreds of module bodies at once, and committing them\n// together produced multi-second frames. Queuing the verdicts (latest wins per subscriber) and\n// applying a bounded number per animation frame keeps each commit small, so the board fills in over a\n// few frames instead of freezing. While a canvas gesture is in motion, a small budget of mounts\n// (nearest first, rendered as interruptible transitions) runs per cheap frame; unmounts hold until\n// the gesture settles.\nexport const viewportFlushScheduler = {\n // Queues the latest verdict for a subscriber; an already-queued verdict is replaced.\n request(apply: ApplyVerdict, verdict: boolean, distance = Number.POSITIVE_INFINITY, weight: VerdictWeight = 'light'): void {\n listenForGestures();\n pending.set(apply, { verdict, distance, weight });\n schedule();\n },\n\n // Drops any queued verdict for a subscriber (on unmount).\n cancel(apply: ApplyVerdict): void {\n pending.delete(apply);\n },\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { RefObject, useEffect, useState } from 'react';\nimport { VerdictWeight, viewportFlushScheduler } from './viewportFlushScheduler';\n\n// Tracks whether an element is within (or near) the viewport, so a heavy subtree can be mounted only\n// when it is about to be seen. The board pans/zooms via CSS transforms, and IntersectionObserver reports\n// against the post-transform visual box, so this stays correct through pan and zoom.\n//\n// Starts `false` so the very first paint mounts nothing off-screen — the observer then mounts the\n// on-screen elements on its first callback. `rootMargin` pre-mounts a margin around the viewport so\n// content is ready before it scrolls in (avoids a blank flash while panning).\n//\n// Verdicts are applied through the viewportFlushScheduler: rate-limited to a few subtree\n// mounts per frame — and during a pan/zoom gesture to a small nearest-first mount budget with\n// unmounts held back — so a flood of verdicts after a long pan, or a zoom-out that pulls the whole\n// board into view, fills the board in progressively instead of freezing it in one giant commit.\n// Each verdict carries the element's distance to the viewport center so the scheduler can mount\n// what the user is actually looking at first.\nexport function useInViewport(ref: RefObject<Element | null>, rootMargin = '250% 250%', weight: VerdictWeight = 'light'): boolean {\n const [inView, setInView] = useState(false);\n\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n if (typeof IntersectionObserver === 'undefined') {\n // No observer (e.g. jsdom): render everything rather than hide it.\n setInView(true);\n return;\n }\n const observer = new IntersectionObserver(\n entries => {\n const entry = entries[entries.length - 1];\n if (!entry) return;\n const rect = entry.boundingClientRect;\n const distance = Math.hypot(\n rect.left + (rect.width / 2) - (window.innerWidth / 2),\n rect.top + (rect.height / 2) - (window.innerHeight / 2));\n viewportFlushScheduler.request(setInView, entry.isIntersecting, distance, weight);\n },\n { rootMargin });\n observer.observe(element);\n\n return () => {\n observer.disconnect();\n viewportFlushScheduler.cancel(setInView);\n };\n }, [ref, rootMargin, weight]);\n\n return inView;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { memo, useRef, type ReactNode } from 'react';\nimport { CanvasItem } from '@cratis/components/Canvas';\nimport type { Guid } from '@cratis/fundamentals';\nimport { boardMetrics } from '../Layout';\nimport { useInViewport } from '../Viewport';\nimport type { CollectionItem } from './collectionState';\nimport './CollectionViewport.css';\n\ninterface CollectionModule { id: Guid; name: string }\ninterface ViewportCollection extends CollectionItem { modules: CollectionModule[] }\n\nexport interface CollectionViewportProps<T extends ViewportCollection> {\n collection: T;\n estimatedSize: { width: number; height: number; moduleWidths: number[] };\n measuredSize?: { width: number; height: number };\n onSize?: (id: Guid, width: number, height: number) => void;\n children: ReactNode;\n}\n\nfunction Viewport<T extends ViewportCollection>({ collection, estimatedSize, measuredSize, onSize, children }: CollectionViewportProps<T>) {\n const hostRef = useRef<HTMLDivElement>(null);\n const inView = useInViewport(hostRef, undefined, 'heavy');\n const size = measuredSize ?? estimatedSize;\n return <CanvasItem x={collection.position?.x ?? 0} y={collection.position?.y ?? 0}\n onSize={onSize ? (width, height) => onSize(collection.id, width, height) : undefined}>\n <div ref={hostRef}>\n {inView ? children : <div className='event-model-collection-placeholder'\n style={{ width: size.width, height: size.height }} aria-hidden>\n {collection.modules.map((module, index) => <div className='event-model-collection-placeholder-module'\n key={module.id.toString()} style={{ width: estimatedSize.moduleWidths[index] }}>\n <div className='event-modeling-grid-pill event-modeling-grid-pill--module event-model-collection-placeholder-pill'>{module.name}</div>\n <div className='event-model-collection-placeholder-body'\n style={{ height: Math.max(0, size.height - boardMetrics.headerHeight - 4) }} />\n </div>)}\n </div>}\n </div>\n </CanvasItem>;\n}\n\nexport const CollectionViewport = memo(Viewport);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/** The axis a flow connection curve's end tangents follow. */\nexport enum CurveAxis {\n Horizontal = 'horizontal',\n Vertical = 'vertical',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { CurveAxis } from './CurveAxis';\n\n/** A point in the curve's coordinate space. */\nexport interface CurvePoint {\n x: number;\n y: number;\n}\n\n/**\n * Builds the smooth cubic-bezier path used for flow connections: both end tangents are aligned with\n * the given axis, with the control points placed halfway along that axis. This is the single curve\n * style shared by the connections between the cards inside a slice (vertical flow) and the links\n * between module collections on the canvas (axis follows the dominant direction).\n */\nexport function smoothCurvePath(start: CurvePoint, end: CurvePoint, axis: CurveAxis): string {\n if (axis === CurveAxis.Vertical) {\n const deltaY = end.y - start.y;\n const control1Y = start.y + deltaY * 0.5;\n const control2Y = end.y - deltaY * 0.5;\n return `M ${start.x} ${start.y} C ${start.x} ${control1Y}, ${end.x} ${control2Y}, ${end.x} ${end.y}`;\n }\n\n const deltaX = end.x - start.x;\n const control1X = start.x + deltaX * 0.5;\n const control2X = end.x - deltaX * 0.5;\n return `M ${start.x} ${start.y} C ${control1X} ${start.y}, ${control2X} ${end.y}, ${end.x} ${end.y}`;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { CurveAxis } from './CurveAxis';\n\n/** A rectangle expressed in canvas (world) coordinates. */\nexport interface Rect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** A point expressed in canvas (world) coordinates. */\nexport interface Point {\n x: number;\n y: number;\n}\n\n/** The endpoints of a directed link plus the tangent axis its spline should follow. */\nexport interface SplineEndpoints {\n /** The point on the source rectangle's border the curve leaves from. */\n start: Point;\n /** The point on the target rectangle's border the curve arrives at. */\n end: Point;\n /** The axis the curve's end tangents follow — the dominant direction between the two rectangles. */\n axis: CurveAxis;\n}\n\n/** The center point of a rectangle. */\nexport function centerOf(rect: Rect): Point {\n return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };\n}\n\n/** A zero-size rectangle at a point, so point targets (the drag pointer) reuse the rect-based spline math. */\nexport function rectAt(point: Point): Rect {\n return { x: point.x, y: point.y, width: 0, height: 0 };\n}\n\n/**\n * The part of a collection's measured rectangle that holds the slice content — the specifications\n * rendered below the slice columns are excluded, so anchors and curve endpoints center on the\n * content rather than the full (specification-inclusive) footprint.\n */\nexport function contentRectOf(rect: Rect, contentHeight: number): Rect {\n return { ...rect, height: Math.min(rect.height, contentHeight) };\n}\n\n/** The point a link drag starts from: the right edge of a rectangle, vertically centered. */\nexport function linkAnchor(rect: Rect): Point {\n return { x: rect.x + rect.width, y: rect.y + rect.height / 2 };\n}\n\n/**\n * Computes the spline endpoints between two rectangles: the curve leaves and arrives on the facing\n * edges along the dominant axis between the two centers, at each edge's midpoint, with the tangents\n * following that axis — the same curve style as the connections between the cards inside a slice.\n */\nexport function computeSplineEndpoints(source: Rect, target: Rect): SplineEndpoints {\n const sourceCenter = centerOf(source);\n const targetCenter = centerOf(target);\n const deltaX = targetCenter.x - sourceCenter.x;\n const deltaY = targetCenter.y - sourceCenter.y;\n\n if (Math.abs(deltaX) >= Math.abs(deltaY)) {\n const goingRight = deltaX >= 0;\n return {\n axis: CurveAxis.Horizontal,\n start: { x: goingRight ? source.x + source.width : source.x, y: sourceCenter.y },\n end: { x: goingRight ? target.x : target.x + target.width, y: targetCenter.y },\n };\n }\n\n const goingDown = deltaY >= 0;\n return {\n axis: CurveAxis.Vertical,\n start: { x: sourceCenter.x, y: goingDown ? source.y + source.height : source.y },\n end: { x: targetCenter.x, y: goingDown ? target.y : target.y + target.height },\n };\n}\n\n/** The midpoint between two points. */\nexport function midpoint(a: Point, b: Point): Point {\n return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n}\n\n/** Whether a point lies within a rectangle (borders inclusive). */\nexport function pointInRect(point: Point, rect: Rect): boolean {\n return point.x >= rect.x && point.x <= rect.x + rect.width &&\n point.y >= rect.y && point.y <= rect.y + rect.height;\n}\n\n/** Something a link can connect to — anything carrying a stringifiable id. */\nexport interface Identified {\n id: { toString(): string };\n}\n\n/**\n * Resolves the collection a link drop connects to. Prefers the target directly under the release\n * point, but falls back to the target the affordance last committed to (looked up by id) — so a quick\n * release that lands a hair outside the target, or whose final pointermove the browser coalesced away,\n * still links to what the user was shown \"will connect\" to. Never returns the drag's own source.\n */\nexport function resolveDropTarget<T extends Identified>(\n releaseTarget: T | null,\n lastTargetId: string | null,\n lookup: (id: string) => T | undefined,\n sourceId: string): T | null {\n const target = releaseTarget ?? (lastTargetId ? lookup(lastTargetId) ?? null : null);\n if (!target || target.id.toString() === sourceId) return null;\n return target;\n}\n\n/**\n * The smallest rectangle containing every supplied rectangle and point, expanded by padding on all\n * sides. Returns a zero rectangle when nothing is supplied.\n */\nexport function boundingBox(rects: Rect[], points: Point[], padding: number): Rect {\n const xs: number[] = [];\n const ys: number[] = [];\n for (const rect of rects) {\n xs.push(rect.x, rect.x + rect.width);\n ys.push(rect.y, rect.y + rect.height);\n }\n for (const point of points) {\n xs.push(point.x);\n ys.push(point.y);\n }\n if (xs.length === 0) return { x: 0, y: 0, width: 0, height: 0 };\n\n const minX = Math.min(...xs) - padding;\n const minY = Math.min(...ys) - padding;\n const maxX = Math.max(...xs) + padding;\n const maxY = Math.max(...ys) + padding;\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Measures the rendered pixel width of `text` at the given font. Implemented with real canvas font\n * metrics by {@link defaultMeasureLabelWidth}; injected as a parameter everywhere it is consumed so\n * {@link computePillLabelMinWidth} — and the pure layout functions built on it — stay spec-able without\n * jsdom's lack of real canvas font metrics in Vitest. Mirrors the `MeasureTextWidth` pattern in\n * `@cratis/event-models` (Cards/autoFitTitle.ts).\n */\nexport type MeasureLabelWidth = (text: string, fontSizePx: number, fontWeight: string | number, fontFamily: string) => number;\n\n/** Matches `.event-modeling-grid-pill`'s own font rules (PillHeader.css) — the label measures against it. */\nexport const PILL_LABEL_FONT_SIZE_PX = 12;\n\n/** Matches `.event-modeling-grid-pill`'s `font-weight` (PillHeader.css). */\nexport const PILL_LABEL_FONT_WEIGHT = 600;\n\n/** The pill sets no `font-family` of its own, so it inherits the app root's (see `:root` in index.css). */\nexport const PILL_LABEL_FONT_FAMILY = 'Inter, Avenir, Helvetica, Arial, sans-serif';\n\n/**\n * The fixed-size chrome a pill needs around its label, regardless of label content: the icon clusters\n * either side of the label plus the pill's own horizontal padding.\n *\n * `.event-modeling-grid-pill-left` / `-right` (PillHeader.css) are flex rows of ~20x20 icon buttons with\n * a 4px gap — never content-dependent, so a fixed overhead is a stable, defensible approximation rather\n * than enumerating every conditional button. It is sized for the busiest header as it was drawn when\n * explanation, Mermaid export and enabling were still buttons of their own: 2 icons on the left (the\n * collapse button, the chat button) and 7 on the right: 9 × 20px + 8 × 4px gaps = 212px, plus the pill's\n * own `padding: 0 8px` (16px) = 228px, rounded up a little for sub-pixel layout rounding. Those actions now\n * sit in the header's options menu; the overhead is left as it was so moving them changed no board's\n * layout, and a header now has room to spare rather than none.\n */\nexport const PILL_ICON_CLUSTER_OVERHEAD_PX = 230;\n\nlet measureContext: CanvasRenderingContext2D | null = null;\n\n/** A shared, lazily-created off-screen canvas 2D context for text metrics — the same technique as\n * `Cards/useAutoFitTitle.ts`'s `getMeasureContext()`, kept local here rather than promoted to\n * a shared location: this module is a plain layout-computation function (not a React hook, called during\n * layout, not component render) with a different consumer shape, and there is no second real consumer of\n * a *shared* measurement utility yet to justify the extraction. */\nfunction getMeasureContext(): CanvasRenderingContext2D | null {\n if (measureContext) return measureContext;\n // Some specs run in a plain Node environment (no jsdom) and stub a partial `document` global of\n // their own for unrelated purposes (see Components/Viewport/for_viewport/) — guard on the actual\n // method, not just presence of `document`, so a stub lacking `createElement` degrades gracefully\n // instead of throwing.\n if (typeof document === 'undefined' || typeof document.createElement !== 'function') return null;\n measureContext = document.createElement('canvas').getContext('2d');\n return measureContext;\n}\n\n/** Real canvas-based measurement. jsdom (used by the Vitest specs) has no canvas font metrics and\n * returns 0 width for every measurement — specs that need a real label-width contribution inject a\n * stub {@link MeasureLabelWidth} instead. */\nexport const defaultMeasureLabelWidth: MeasureLabelWidth = (text, fontSizePx, fontWeight, fontFamily) => {\n const context = getMeasureContext();\n if (!context) return 0;\n context.font = `${fontWeight} ${fontSizePx}px ${fontFamily}`;\n return context.measureText(text).width;\n};\n\n/**\n * The minimum pixel width a pill (module or feature header) needs to fit `label` without its\n * `white-space: nowrap; min-width: min-content` content bleeding outside its computed column width —\n * the measured label plus the fixed icon-cluster/padding overhead.\n */\nexport function computePillLabelMinWidth(label: string, measure: MeasureLabelWidth = defaultMeasureLabelWidth): number {\n return Math.ceil(measure(label, PILL_LABEL_FONT_SIZE_PX, PILL_LABEL_FONT_WEIGHT, PILL_LABEL_FONT_FAMILY)) + PILL_ICON_CLUSTER_OVERHEAD_PX;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The width of the column of row labels to the left of every module collection.\nexport const rowLabelWidth = 56;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createPortal } from 'react-dom';\nimport type { ActorRowDragState } from './useActorRowDrag';\n\nexport interface ActorRowDragGhostProps {\n drag?: ActorRowDragState;\n}\n\n// The actor being dragged, drawn over everything beside the pointer as a label with its name.\nexport const ActorRowDragGhost = ({ drag }: ActorRowDragGhostProps) => drag ? createPortal(\n <div\n style={{\n position: 'fixed',\n left: drag.currentX + 16,\n top: drag.currentY - 16,\n height: 32,\n padding: '0 12px',\n background: 'rgba(80,60,160,0.65)',\n border: '1.5px dashed rgba(180,165,255,0.75)',\n borderRadius: 8,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n pointerEvents: 'none',\n zIndex: 9998,\n fontSize: 11,\n fontWeight: 500,\n color: 'rgba(255,255,255,0.9)',\n userSelect: 'none',\n whiteSpace: 'nowrap',\n }}\n >\n {drag.ghostLabel}\n </div>,\n document.body,\n) : undefined;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Where a dragged actor would land, drawn between two actor row labels.\nexport const ActorRowDropIndicator = () => (\n <div\n style={{\n height: 3,\n margin: '2px 4px',\n background: 'rgba(180,165,255,0.85)',\n borderRadius: 2,\n flexShrink: 0,\n }}\n />\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModelMessages } from '../Messages';\nimport { ActorType } from '../Model';\n\nexport interface ActorKind {\n actorType: ActorType;\n label: string;\n // The swatch drawn beside the kind in the menu that adds an actor.\n color: string;\n}\n\n// The kinds of actor a row can be given, in the order the add menu lists them.\nexport const actorKinds = (messages: EventModelMessages): ActorKind[] => [\n { actorType: ActorType.UIRole, label: messages.actors.ui, color: '#e0e7ff' },\n { actorType: ActorType.systemRole, label: messages.actors.system, color: '#dcfce7' },\n { actorType: ActorType.chatRole, label: messages.actors.chat, color: '#fef9c3' },\n];\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './CollapseButton.css';\nimport React from 'react';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface CollapseButtonProps {\n \n collapsed: boolean;\n \n onToggle?: () => void;\n}\n\nexport const CollapseButton: React.FC<CollapseButtonProps> = ({ collapsed, onToggle }) => {\n const messages = useEventModelMessages();\n const label = collapsed ? messages.collapse.expand : messages.collapse.collapse;\n return (\n <button\n onClick={(event) => { event.stopPropagation(); onToggle?.(); }}\n disabled={!onToggle}\n className='event-modeling-grid-collapse-btn'\n title={label}\n aria-label={label}\n aria-expanded={!collapsed}\n >\n {collapsed ? (\n /* Expand icon: arrows pointing outward to corners */\n <svg width='12' height='12' viewBox='0 0 12 12' fill='none' aria-hidden='true'>\n <path d='M5 1L1 1L1 5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' />\n <line x1='1' y1='1' x2='5.5' y2='5.5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n <path d='M7 11L11 11L11 7' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' />\n <line x1='11' y1='11' x2='6.5' y2='6.5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n </svg>\n ) : (\n /* Collapse icon: arrows pointing inward from corners */\n <svg width='12' height='12' viewBox='0 0 12 12' fill='none' aria-hidden='true'>\n <path d='M1 5L5 5L5 1' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' />\n <line x1='5' y1='5' x2='1.5' y2='1.5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n <path d='M11 7L7 7L7 11' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' />\n <line x1='7' y1='7' x2='10.5' y2='10.5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n </svg>\n )}\n </button>\n);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/AddButton.css';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface DetailsToggleProps {\n visible: boolean;\n onToggle: () => void;\n}\n\n// Shows or hides the details of one slice or feature; the details shown are part of the presentation the\n// consumer controls.\nexport const DetailsToggle = ({ visible, onToggle }: DetailsToggleProps) => {\n const messages = useEventModelMessages();\n const label = visible ? messages.details.hide : messages.details.show;\n return (\n <button\n type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n aria-label={label}\n title={label}\n onClick={onToggle}\n style={visible ? { borderColor: 'var(--text-color)', color: 'var(--text-color)' } : undefined}\n >\n <i className='pi pi-list' style={{ fontSize: 10 }} />\n </button>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EditableLabel.css';\nimport React, { useState } from 'react';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface EditableLabelProps {\n\n value: string;\n\n onChange: (value: string) => void;\n\n placeholder?: string;\n\n style?: React.CSSProperties;\n\n validate?: (value: string) => string | undefined;\n\n readOnly?: boolean;\n}\n\nexport const EditableLabel: React.FC<EditableLabelProps> = ({ value, onChange, placeholder = 'Name…', style, validate, readOnly = false }) => {\n const messages = useEventModelMessages();\n const [editing, setEditing] = useState(false);\n const [draft, setDraft] = useState(value);\n const [error, setError] = useState<string | undefined>(undefined);\n\n const commit = () => {\n const trimmed = draft.trim();\n if (!trimmed) {\n setDraft(value);\n setEditing(false);\n setError(undefined);\n return;\n }\n if (validate) {\n const errorMessage = validate(trimmed);\n if (errorMessage) {\n setError(errorMessage);\n return;\n }\n }\n setError(undefined);\n setEditing(false);\n onChange(trimmed);\n };\n\n if (editing && !readOnly) {\n return (\n <input\n autoFocus\n value={draft}\n onChange={event => {\n setDraft(event.target.value);\n setError(undefined);\n }}\n onBlur={commit}\n onKeyDown={event => {\n if (event.key === 'Enter') {\n (event.target as HTMLInputElement).blur();\n return;\n }\n if (event.key === 'Escape') {\n setDraft(value);\n setEditing(false);\n setError(undefined);\n }\n }}\n className={`event-modeling-grid-editable-label-input${error ? ' event-modeling-grid-editable-label-input--error' : ''}`}\n title={error}\n style={style}\n />\n );\n }\n\n return (\n <span\n title={readOnly ? undefined : messages.editableLabel.doubleClickToRename}\n onDoubleClick={readOnly ? undefined : () => {\n setDraft(value);\n setEditing(true);\n setError(undefined);\n }}\n className='event-modeling-grid-editable-label'\n style={style}\n >\n {value || <em className='event-modeling-grid-editable-label-placeholder'>{placeholder}</em>}\n </span>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport { GridTooltip } from '../Tooltips';\nimport './EntityErrorIndicator.css';\n\nexport interface EntityErrorIndicatorProps {\n\n /** The error message to display in the tooltip. */\n error: string;\n}\n\n/**\n * Small error icon that shows a tooltip with the error details.\n * Rendered alongside entity headers (modules, features, slices) when a command fails.\n */\nexport const EntityErrorIndicator: React.FC<EntityErrorIndicatorProps> = ({ error }) => (\n <GridTooltip content={error}>\n <span className='entity-error-indicator'>\n <i className='pi pi-exclamation-triangle' />\n </span>\n </GridTooltip>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/** The level of the board hierarchy an errored placeholder stands in for. */\nexport enum EntityErrorKind {\n Module = 'module',\n Feature = 'feature',\n Slice = 'slice',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ErroredEntity.css';\nimport { EntityErrorKind } from './EntityErrorKind';\nimport { GridTooltip } from '../Tooltips';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface ErroredEntityProps {\n\n /** Which level of the board failed. */\n kind: EntityErrorKind;\n\n /** The name of the module, feature, or slice that failed. */\n label: string;\n\n /** The message describing why it failed; shown on hover. */\n error: string;\n\n /** Rebuilds the entity from its source data. */\n onRetry: () => void;\n}\n\n/**\n * Stands in for a module, feature, or slice whose render failed: it keeps the board's shape, crosses the\n * entity out, and reveals the error on hover — so one broken entity costs the user that entity instead\n * of the whole board.\n */\nexport const ErroredEntity = ({ kind, label, error, onRetry }: ErroredEntityProps) => {\n const messages = useEventModelMessages().erroredEntity;\n return (\n <GridTooltip content={messages.couldNotBeRendered(messages[kind], error)}>\n <div className={`errored-entity errored-entity--${kind}`} role='alert' data-errored-entity={kind}>\n <i className='pi pi-times-circle errored-entity__mark' aria-hidden='true' />\n <span className='errored-entity__label'>{label}</span>\n <span className='errored-entity__hint'>{messages.failedToRender}</span>\n <button type='button' className='errored-entity__retry' onClick={onRetry}>{messages.retry}</button>\n </div>\n </GridTooltip>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport { CollapseButton } from './CollapseButton';\nimport { EditableLabel } from './EditableLabel';\nimport { EntityErrorIndicator } from './EntityErrorIndicator';\nimport './PillHeader.css';\n\nexport type PillHeaderVariant = 'module' | 'feature';\n\nexport interface PillHeaderProps {\n\n variant: PillHeaderVariant;\n\n collapsed: boolean;\n\n onToggle?: () => void;\n\n label: string;\n\n onRenameLabel: (name: string) => void;\n\n // The label can be read but not renamed.\n labelReadOnly?: boolean;\n\n validateLabel?: (name: string) => string | undefined;\n\n labelStyle?: React.CSSProperties;\n\n background: string;\n\n border: string;\n\n height: number;\n\n /** Extra affordances rendered right after the collapse button, before the label — such as the conversation button. */\n leadingContent?: React.ReactNode;\n\n children?: React.ReactNode;\n\n draggable?: boolean;\n\n onPointerDown?: React.PointerEventHandler<HTMLDivElement>;\n\n onPointerMove?: React.PointerEventHandler<HTMLDivElement>;\n\n onPointerUp?: React.PointerEventHandler<HTMLDivElement>;\n\n /** When set, the pill shows a red border and an error indicator icon with the message as tooltip. */\n error?: string;\n}\n\nexport const PillHeader: React.FC<PillHeaderProps> = ({\n variant,\n collapsed,\n onToggle,\n label,\n onRenameLabel,\n labelReadOnly = false,\n validateLabel,\n labelStyle,\n background,\n border,\n height,\n children,\n leadingContent,\n draggable = false,\n onPointerDown,\n onPointerMove,\n onPointerUp,\n error,\n}) => (\n <div\n className={`event-modeling-grid-pill event-modeling-grid-pill--${variant}${collapsed ? ' event-modeling-grid-pill--collapsed' : ''}${draggable ? ' event-modeling-grid-pill--draggable' : ''}${error ? ' event-modeling-grid-pill--error' : ''}`}\n style={{ background, border: error ? '2px solid #ef4444' : border, height }}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n >\n <div className='event-modeling-grid-pill-left'>\n {onToggle && <CollapseButton collapsed={collapsed} onToggle={onToggle} />}\n {leadingContent}\n </div>\n <EditableLabel\n value={label}\n onChange={onRenameLabel}\n validate={validateLabel}\n style={labelStyle}\n readOnly={labelReadOnly}\n />\n <div className='event-modeling-grid-pill-right'>\n {error && <EntityErrorIndicator error={error} />}\n {children}\n </div>\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { type RefObject, useEffect, useRef } from 'react';\n\n// Calls onDismiss when a pointer goes down outside every one of the elements — a trigger and a panel\n// portaled elsewhere count as one. Listens in the capture phase, because cards stop pointerdown from\n// bubbling for their own gestures.\nexport const useDismissOnOutsidePointer = (elements: RefObject<Element | null>[], onDismiss: () => void, enabled: boolean): void => {\n const dismiss = useRef(onDismiss);\n dismiss.current = onDismiss;\n\n useEffect(() => {\n if (!enabled) return;\n const handlePointerDown = (event: PointerEvent) => {\n const present = elements.map(element => element.current).filter(element => !!element);\n const target = event.target;\n const inside = target instanceof Node && present.some(element => element?.contains(target));\n if (present.length > 0 && !inside) dismiss.current();\n };\n document.addEventListener('pointerdown', handlePointerDown, true);\n return () => document.removeEventListener('pointerdown', handlePointerDown, true);\n }, [elements, enabled]);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModelMessages } from '../Messages';\nimport { RowType } from '../Rows/RowType';\n\n// What a row is called on its label until it is given a name of its own.\nexport const rowTypeName = (rowType: RowType, messages: EventModelMessages): string => {\n switch (rowType) {\n case RowType.UI: return messages.rows.ui;\n case RowType.Chat: return messages.rows.chat;\n case RowType.System: return messages.rows.system;\n case RowType.Interaction: return messages.rows.interaction;\n case RowType.Events: return messages.rows.events;\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './RowLabel.css';\nimport { useMemo, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from 'react';\nimport type { ActorType } from '../Model';\nimport { useBoard } from '../Board';\nimport { EditableLabel } from '../Headers';\nimport { GridTooltip } from '../Tooltips';\nimport { rowLabelWidth } from '../Geometry';\nimport { useDismissOnOutsidePointer } from '../Pickers/useDismissOnOutsidePointer';\nimport { RowType } from '../Rows/RowType';\nimport { actorKinds } from './actorKinds';\nimport type { RowLabelBadge } from './RowLabelBadge';\nimport { rowTypeName } from './rowTypeName';\n\n// How far the pointer travels before a press on a label becomes a drag.\nconst dragThreshold = 4;\n\nexport interface RowLabelProps {\n rowType: RowType;\n height?: number;\n // The name of the row, or of the actor it holds; the row type's own name when omitted.\n name?: string;\n // Shown when hovering a name that cannot be edited, such as who an actor is on a read-only board.\n description?: string;\n // Set when the label belongs to an actor rather than to a row with no actors.\n actorId?: string;\n // Renaming exists on actor rows only when the board is editable and this is supplied.\n onRenamed?: (name: string) => void;\n validateName?: (name: string) => string | undefined;\n // The add menu exists on actor rows only when the board is editable and this is supplied.\n onActorAdded?: (actorType: ActorType) => void;\n // An actor's label can be picked up only when the board is editable and this is supplied.\n onDragStart?: (clientX: number, clientY: number) => void;\n // This actor is the one being dragged.\n dragging?: boolean;\n // The badge at the top of an actor row's label.\n badge?: RowLabelBadge;\n // Consumer-rendered persona image; the board never resolves Studio avatars.\n personaAvatar?: ReactNode;\n // What the consumer mounts with the label, such as the dialogs its badge actions open.\n children?: ReactNode;\n}\n\nconst isActorRowType = (rowType: RowType) => rowType === RowType.UI || rowType === RowType.System || rowType === RowType.Chat;\n\n// Vertical (bottom-to-top) via a plain rotation, not writing-mode + rotate(180deg): WebKit shears a vertical\n// writing-mode element under an ancestor transform: scale() (the canvas zoom layer), skewing the label until\n// the next repaint. See RowLabel.css.\nconst editableLabelStyle: CSSProperties = {\n transform: 'rotate(-90deg)',\n whiteSpace: 'nowrap',\n fontSize: 11,\n fontWeight: 600,\n color: 'rgba(255,255,255,0.45)',\n textTransform: 'uppercase',\n letterSpacing: '0.05em',\n textAlign: 'center',\n};\n\nconst swatchStyle = (color: string): CSSProperties => ({\n width: 10,\n height: 10,\n borderRadius: 3,\n background: color,\n border: '1px solid #d1d5db',\n flexShrink: 0,\n display: 'inline-block',\n});\n\nexport const RowLabel = ({\n rowType,\n height,\n name,\n description,\n actorId,\n onRenamed,\n validateName,\n onActorAdded,\n onDragStart,\n dragging = false,\n badge,\n personaAvatar,\n children,\n}: RowLabelProps) => {\n const { readOnly, messages } = useBoard();\n const [addMenuOpen, setAddMenuOpen] = useState(false);\n const [badgeMenuOpen, setBadgeMenuOpen] = useState(false);\n const press = useRef<{ startX: number; startY: number } | undefined>(undefined);\n const pillRef = useRef<HTMLDivElement>(null);\n const addMenuRef = useRef<HTMLDivElement>(null);\n const badgeMenuRef = useRef<HTMLDivElement>(null);\n const addMenuRefs = useMemo(() => [addMenuRef], []);\n const badgeMenuRefs = useMemo(() => [badgeMenuRef], []);\n useDismissOnOutsidePointer(addMenuRefs, () => setAddMenuOpen(false), addMenuOpen);\n useDismissOnOutsidePointer(badgeMenuRefs, () => setBadgeMenuOpen(false), badgeMenuOpen);\n\n const displayName = name ?? rowTypeName(rowType, messages);\n const isActorRow = isActorRowType(rowType);\n const renamed = isActorRow && !readOnly ? onRenamed : undefined;\n const actorAdded = isActorRow && !readOnly ? onActorAdded : undefined;\n const dragStart = actorId && !readOnly ? onDragStart : undefined;\n\n const actions = readOnly ? [] : badge?.actions ?? [];\n const activateBadge = readOnly ? undefined : badge?.onActivate;\n const badgeActive = actions.length > 0 || !!activateBadge;\n // A read-only board shows who an actor is, but offers nothing to do about it.\n const avatar = personaAvatar ?? badge?.avatar;\n const showsBadge = isActorRow && (!!avatar || (!!badge && !readOnly));\n\n const handleBadgeClick = () => {\n if (actions.length > 0) {\n setBadgeMenuOpen(previous => !previous);\n return;\n }\n activateBadge?.();\n };\n\n const handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {\n const target = event.target;\n if (target instanceof Element && (target.tagName === 'INPUT' || target.closest('button'))) return;\n // Claim the gesture so a touch drag here moves the row instead of panning the canvas.\n event.stopPropagation();\n press.current = { startX: event.clientX, startY: event.clientY };\n };\n\n const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {\n const current = press.current;\n if (!current || !dragStart) return;\n const movedY = Math.abs(event.clientY - current.startY);\n const movedX = Math.abs(event.clientX - current.startX);\n if (movedY > dragThreshold || movedX > dragThreshold) {\n press.current = undefined;\n dragStart(event.clientX, event.clientY);\n }\n };\n\n const handlePointerUp = () => {\n press.current = undefined;\n };\n\n return (\n <div\n style={{\n width: rowLabelWidth,\n height,\n flexShrink: 0,\n opacity: dragging ? 0.35 : 1,\n transition: 'opacity 0.15s',\n }}\n className='event-modeling-grid-row-label'\n data-role-row={actorId ? 'true' : undefined}\n data-role-type={actorId ? rowType : undefined}\n data-role-id={actorId}\n >\n <div\n className='event-modeling-grid-row-label-pill'\n ref={pillRef}\n style={dragStart ? { cursor: 'grab' } : undefined}\n onPointerDown={dragStart ? handlePointerDown : undefined}\n onPointerMove={dragStart ? handlePointerMove : undefined}\n onPointerUp={dragStart ? handlePointerUp : undefined}\n >\n {showsBadge && (\n <div className='event-modeling-grid-row-label-info' ref={badgeMenuRef}>\n <button\n className='event-modeling-grid-row-label-info-btn'\n onClick={event => { event.stopPropagation(); handleBadgeClick(); }}\n title={badge?.title ?? displayName}\n aria-label={badge?.title ?? displayName}\n disabled={!badgeActive}\n style={!badgeActive ? { opacity: readOnly ? 1 : 0.4, cursor: 'default' } : undefined}\n >\n {avatar ?? <i className='pi pi-id-card' />}\n </button>\n {badgeMenuOpen && actions.length > 0 && (\n <div className='event-modeling-grid-row-role-menu'>\n {actions.map(action => (\n <button\n key={action.id}\n className={`event-modeling-grid-row-role-menu-option${action.danger ? ' event-modeling-grid-row-role-menu-option--danger' : ''}`}\n onClick={event => {\n event.stopPropagation();\n setBadgeMenuOpen(false);\n if (actorId && pillRef.current) action.onActivate(actorId, pillRef.current.getBoundingClientRect());\n }}\n >\n {action.icon}\n {action.label}\n </button>\n ))}\n </div>\n )}\n </div>\n )}\n <div className='event-modeling-grid-row-label-title'>\n {renamed ? (\n <EditableLabel value={displayName} onChange={renamed} validate={validateName} style={editableLabelStyle} />\n ) : description?.trim() ? (\n <GridTooltip content={description} position='right'>\n <span className='event-modeling-grid-row-label-text'>{displayName}</span>\n </GridTooltip>\n ) : (\n <span className='event-modeling-grid-row-label-text'>{displayName}</span>\n )}\n </div>\n\n {actorAdded && (\n <div className='event-modeling-grid-row-label-add-role' ref={addMenuRef}>\n <button\n className='event-modeling-grid-row-label-add-role-btn'\n onClick={event => { event.stopPropagation(); setAddMenuOpen(previous => !previous); }}\n title={messages.actors.add}\n aria-label={messages.actors.add}\n >\n +\n </button>\n {addMenuOpen && (\n <div className='event-modeling-grid-row-role-menu'>\n {actorKinds(messages).map(({ actorType, label, color }) => (\n <button\n key={actorType}\n className='event-modeling-grid-row-role-menu-option'\n onClick={() => {\n actorAdded(actorType);\n setAddMenuOpen(false);\n }}\n >\n <span style={swatchStyle(color)} />\n {label}\n </button>\n ))}\n </div>\n )}\n </div>\n )}\n </div>\n {children}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './RowLabel.css';\nimport type { ReactNode } from 'react';\nimport { rowLabelWidth } from '../Geometry';\n\nexport interface RowLabelsColumnFrameProps {\n // The space above the first label, so the labels line up with the rows beside them.\n topOffset: number;\n collectionId?: string;\n children?: ReactNode;\n}\n\n// The column of row labels to the left of a module collection.\nexport const RowLabelsColumnFrame = ({ topOffset, collectionId, children }: RowLabelsColumnFrameProps) => (\n <div className='event-modeling-grid-row-labels' data-actor-collection-id={collectionId} style={{ width: rowLabelWidth }}>\n <div style={{ height: topOffset, flexShrink: 0 }} />\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { ActorType } from '../Model';\nimport { useBoard } from '../Board';\nimport { RowType } from '../Rows/RowType';\nimport { rowOfActorType } from './actorRows';\nimport type { ActorsReordered } from './ActorsReordered';\n\n// What a drag needs to know about an actor.\nexport interface DraggableActor {\n id: string;\n name: string;\n actorType: ActorType;\n}\n\nexport interface ActorRowDragState {\n actorId: string;\n rowType: RowType;\n sourceIndex: number;\n ghostLabel: string;\n currentX: number;\n currentY: number;\n // The gap the actor would land in right now: n is before the nth actor of its kind.\n dropIndex: number;\n}\n\nexport type ActorRowDragStart = (actorId: string, clientX: number, clientY: number) => void;\n\nexport interface ActorRowDrag {\n actorDrag?: ActorRowDragState;\n // Undefined when nothing can be told about a move, so no actor label offers to be picked up.\n handleActorDragStart?: ActorRowDragStart;\n}\n\n// The gap a pointer at clientY is over among the actor labels of one row type.\nfunction dropIndexAt(collectionId: Guid, rowType: RowType, clientY: number): number {\n const column = Array.from(document.querySelectorAll<HTMLElement>('[data-actor-collection-id]'))\n .find(candidate => candidate.dataset.actorCollectionId === collectionId.toString());\n const rows = Array.from(column?.querySelectorAll<HTMLElement>(`[data-role-row=\"true\"][data-role-type=\"${rowType}\"]`) ?? []);\n for (let index = 0; index < rows.length; index++) {\n const rect = rows[index].getBoundingClientRect();\n if (clientY < rect.top + rect.height / 2) return index;\n }\n return rows.length;\n}\n\n// The order after moving the actor at sourceIndex into the gap at dropIndex; undefined when it would\n// land where it already is.\nexport function reorderedActorIds(ids: readonly string[], sourceIndex: number, dropIndex: number): string[] | undefined {\n if (sourceIndex < 0 || sourceIndex >= ids.length) return undefined;\n const landingIndex = dropIndex > sourceIndex ? dropIndex - 1 : dropIndex;\n const targetIndex = Math.min(Math.max(landingIndex, 0), ids.length - 1);\n if (targetIndex === sourceIndex) return undefined;\n const reordered = [...ids];\n const [moved] = reordered.splice(sourceIndex, 1);\n reordered.splice(targetIndex, 0, moved);\n return reordered;\n}\n\nexport interface ActorDrop {\n actorType: ActorType;\n orderedIds: string[];\n}\n\n// What dropping an actor into the gap at dropIndex does to the order of the actors of its own kind;\n// undefined when it changes nothing.\nexport function actorDrop(actors: readonly DraggableActor[], actorId: string, dropIndex: number): ActorDrop | undefined {\n const actor = actors.find(candidate => candidate.id === actorId);\n if (!actor) return undefined;\n const sameKind = actors.filter(candidate => candidate.actorType === actor.actorType).map(candidate => candidate.id);\n const orderedIds = reorderedActorIds(sameKind, sameKind.indexOf(actorId), dropIndex);\n return orderedIds && { actorType: actor.actorType, orderedIds };\n}\n\n// Dragging an actor to another place among the actors of its kind in a collection.\nexport function useActorRowDrag(collectionId: Guid, actors: readonly DraggableActor[], onActorsReordered?: ActorsReordered): ActorRowDrag {\n const board = useBoard();\n const [actorDrag, setActorDrag] = useState<ActorRowDragState | undefined>(undefined);\n const actorDragRef = useRef(actorDrag);\n actorDragRef.current = actorDrag;\n const actorsRef = useRef(actors);\n actorsRef.current = actors;\n const collectionIdRef = useRef(collectionId);\n collectionIdRef.current = collectionId;\n const onActorsReorderedRef = useRef(onActorsReordered);\n onActorsReorderedRef.current = onActorsReordered;\n\n const handleActorDragStart = useCallback<ActorRowDragStart>((actorId, clientX, clientY) => {\n const actor = actorsRef.current.find(candidate => candidate.id === actorId);\n if (!actor) return;\n const sameKind = actorsRef.current.filter(candidate => candidate.actorType === actor.actorType);\n const sourceIndex = sameKind.findIndex(candidate => candidate.id === actorId);\n setActorDrag({\n actorId,\n rowType: rowOfActorType(actor.actorType),\n sourceIndex,\n ghostLabel: actor.name,\n currentX: clientX,\n currentY: clientY,\n dropIndex: sourceIndex,\n });\n }, []);\n\n const dragging = actorDrag !== undefined;\n useEffect(() => {\n if (!dragging) return;\n\n const handlePointerMove = (event: PointerEvent) => {\n setActorDrag(previous => previous && {\n ...previous,\n currentX: event.clientX,\n currentY: event.clientY,\n dropIndex: dropIndexAt(collectionIdRef.current, previous.rowType, event.clientY),\n });\n };\n\n const handlePointerUp = () => {\n const drag = actorDragRef.current;\n setActorDrag(undefined);\n if (!drag) return;\n const drop = actorDrop(actorsRef.current, drag.actorId, drag.dropIndex);\n if (drop) onActorsReorderedRef.current?.(collectionIdRef.current, drop.actorType, drop.orderedIds);\n };\n\n window.addEventListener('pointermove', handlePointerMove);\n window.addEventListener('pointerup', handlePointerUp);\n return () => {\n window.removeEventListener('pointermove', handlePointerMove);\n window.removeEventListener('pointerup', handlePointerUp);\n };\n }, [dragging]);\n\n const canDrag = !board.readOnly && onActorsReordered !== undefined;\n return { actorDrag, handleActorDragStart: canDrag ? handleActorDragStart : undefined };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Fragment, useState, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { Actor, ActorType } from '../Model';\nimport { RowType } from '../Rows/RowType';\nimport { actorTypeOfRow } from './actorRows';\nimport { ActorRowDragGhost } from './ActorRowDragGhost';\nimport { ActorRowDropIndicator } from './ActorRowDropIndicator';\nimport { RowLabel, type RowLabelProps } from './RowLabel';\nimport { RowLabelsColumnFrame } from './RowLabelsColumnFrame';\nimport { useActorRowDrag } from './useActorRowDrag';\nimport type { ActorsReordered } from './ActorsReordered';\n\nexport interface RowLabelsColumnProps {\n collectionId: Guid;\n topOffset: number;\n contentRows: readonly RowType[];\n rowHeights: Record<RowType, number>;\n actors: readonly Actor[];\n onActorAdded?: (rowType: RowType, actorType: ActorType) => void;\n onActorRenamed?: (actorId: string, name: string) => void;\n onRowRenamed?: (rowType: RowType, name: string) => void;\n onActorsReordered?: ActorsReordered;\n // Studio-specific identity controls and dialogs are supplied without moving the row's geometry to Studio.\n renderActorLabel?: (actor: Actor, label: RowLabelProps) => ReactNode;\n renderEmptyActorLabel?: (rowType: RowType, label: RowLabelProps) => ReactNode;\n}\n\n// The package owns row assembly, drop feedback and the pointer gesture; the consumer owns persistence.\nexport const RowLabelsColumn = ({\n collectionId, topOffset, contentRows, rowHeights, actors, onActorAdded, onActorRenamed, onRowRenamed,\n onActorsReordered, renderActorLabel, renderEmptyActorLabel,\n}: RowLabelsColumnProps) => {\n const [rowNames, setRowNames] = useState<Partial<Record<RowType, string>>>({});\n const [actorNames, setActorNames] = useState<Record<string, string>>({});\n const { actorDrag, handleActorDragStart } = useActorRowDrag(collectionId, actors, onActorsReordered);\n\n return (\n <RowLabelsColumnFrame topOffset={topOffset} collectionId={collectionId.toString()}>\n <ActorRowDragGhost drag={actorDrag} />\n {contentRows.flatMap(rowType => {\n const actorType = actorTypeOfRow(rowType);\n const rowActors = actorType === undefined ? [] : actors.filter(actor => actor.actorType === actorType);\n const parentLabelProps: RowLabelProps = {\n rowType,\n height: rowHeights[rowType],\n name: rowNames[rowType],\n onRenamed: onRowRenamed ? name => {\n setRowNames(previous => ({ ...previous, [rowType]: name }));\n onRowRenamed(rowType, name);\n } : undefined,\n validateName: name => {\n const otherName = Object.entries(rowNames).find(([key]) => key !== rowType)?.[1];\n return otherName?.toLowerCase() === name.toLowerCase() ? 'Name already in use' : undefined;\n },\n onActorAdded: onActorAdded ? kind => onActorAdded(rowType, kind) : undefined,\n };\n const parentLabel = actorType === undefined || rowActors.length === 0 ? [\n <Fragment key={rowType}>\n {actorType !== undefined && renderEmptyActorLabel\n ? renderEmptyActorLabel(rowType, parentLabelProps)\n : <RowLabel {...parentLabelProps} />}\n </Fragment>,\n ] : [];\n const actorLabels = rowActors.flatMap((actor, index) => {\n const draggingThisType = actorDrag?.rowType === rowType;\n const label: RowLabelProps = {\n rowType,\n height: rowHeights[rowType],\n name: actorNames[actor.id] ?? actor.name,\n description: actor.description,\n actorId: actor.id,\n onRenamed: onActorRenamed ? name => {\n setActorNames(previous => ({ ...previous, [actor.id]: name }));\n onActorRenamed(actor.id, name);\n } : undefined,\n onActorAdded: onActorAdded ? kind => onActorAdded(rowType, kind) : undefined,\n onDragStart: handleActorDragStart ? (clientX, clientY) => handleActorDragStart(actor.id, clientX, clientY) : undefined,\n dragging: actorDrag?.actorId === actor.id,\n };\n return [\n ...(draggingThisType && actorDrag.dropIndex === index ? [<ActorRowDropIndicator key={`drop-${rowType}-${index}`} />] : []),\n <Fragment key={actor.id}>\n {renderActorLabel ? renderActorLabel(actor, label) : <RowLabel {...label} />}\n </Fragment>,\n ...(draggingThisType && index === rowActors.length - 1 && actorDrag.dropIndex === rowActors.length\n ? [<ActorRowDropIndicator key={`drop-${rowType}-end`} />] : []),\n ];\n });\n return [...parentLabel, ...actorLabels];\n })}\n </RowLabelsColumnFrame>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode, Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface ModuleColumnFrameProps {\n moduleId: Guid;\n // Set on the leading module of a collection: a collection has no box of its own, and its leading\n // module is where it starts on the canvas.\n collectionId?: Guid;\n // The gap before the module; the first module in a collection has none.\n marginLeft: number;\n // The module is the one being dragged.\n dragging?: boolean;\n ref?: Ref<HTMLDivElement>;\n children?: ReactNode;\n}\n\n// The column a module's header and features sit in. It carries the attributes a module drag reads the\n// modules of a collection by, and that anything navigating the board finds a module or collection by.\nexport const ModuleColumnFrame = ({ moduleId, collectionId, marginLeft, dragging = false, ref, children }: ModuleColumnFrameProps) => (\n <div\n ref={ref}\n data-module-id={moduleId.toString()}\n data-collection-id={collectionId?.toString()}\n style={{\n marginLeft,\n display: 'flex',\n flexDirection: 'column',\n flexShrink: 0,\n // The dragged column stays in place and fades, so the gap it leaves is where the pointer is\n // rather than where the column used to be.\n opacity: dragging ? 0.4 : undefined,\n }}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceDragging/SliceDragGhost.css';\nimport './ModuleDropIndicator.css';\n\n// Where a dragged module would land, drawn in the gap between two modules.\nexport const ModuleDropIndicator = () => <div className='event-modeling-grid-drop-indicator' />;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The attributes the board hit-tests drop positions with. A ghost is a copy of a real slice, so it\n// carries them too — and the copy lives in `document.body`, where the very `document.querySelectorAll`\n// calls that decide which feature and which position a slice would land in would find it and count it as\n// a real column. Stripping them is what keeps the ghost invisible to the drag it is illustrating.\nexport const HIT_TEST_ATTRIBUTES = [\n 'data-slice-col',\n 'data-slice-id',\n 'data-slice-feature-id',\n 'data-slice-drop-target',\n 'data-slice-module-id',\n 'id',\n];\n\n// The part of an element the ghost preparation touches, so it can be exercised without a document.\nexport interface GhostNode {\n removeAttribute(name: string): void;\n setAttribute(name: string, value: string): void;\n readonly children: ArrayLike<GhostNode>;\n}\n\n// Prepares a copied slice to be shown as a ghost: nothing the board searches for, and nothing anything\n// can interact with.\n// node: The copied element to prepare, and everything inside it.\nexport function prepareGhost(node: GhostNode) {\n for (const attribute of HIT_TEST_ATTRIBUTES) {\n node.removeAttribute(attribute);\n }\n\n // A snapshot is a picture that follows the pointer. Left interactive, a stray input inside it could\n // take focus off the board mid-drag, and a screen reader would read the slice out twice.\n node.removeAttribute('contenteditable');\n node.setAttribute('aria-hidden', 'true');\n node.setAttribute('inert', '');\n\n for (let index = 0; index < node.children.length; index++) {\n prepareGhost(node.children[index]);\n }\n}\n\n// Takes the snapshot of a slice that is dragged around the board: the slice exactly as it looks right\n// now, detached from the document it came from.\n//\n// A slice is a tall column of headers, cells and specifications, and a label-sized placeholder said\n// nothing about which of them was being moved. Copying the live element keeps every bit of that\n// appearance without re-deriving it, because the stylesheet is global and the copy keeps its classes.\n// element: The slice column element to snapshot.\n// Returns The detached copy to render as the ghost.\nexport function createSliceDragGhost(element: HTMLElement): HTMLElement | null {\n const ghost = element.cloneNode(true);\n if (!(ghost instanceof HTMLElement)) return null;\n\n prepareGhost(ghost);\n\n // The live column dims itself while it is being dragged. The ghost is the thing being looked at, so\n // it must not inherit that — its own transparency belongs to whatever renders it.\n ghost.style.opacity = '';\n ghost.style.cursor = 'grabbing';\n\n return ghost;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { prepareGhost } from '../SliceDragging/snapshotSlice';\n\n// Takes the snapshot of a feature or module header that is dragged around the board.\n//\n// A feature or module can own a whole sub-tree of slices underneath its header. Copying all of that would\n// be heavy to drag around, and none of it says what is being moved: the header alone does. So only the\n// header is copied, with the same stripping a slice copy gets, so the copy is invisible to the drag it\n// illustrates.\nexport function createHeaderDragGhost(element: HTMLElement): HTMLElement | null {\n const ghost = element.cloneNode(true);\n if (!(ghost instanceof HTMLElement)) return null;\n\n prepareGhost(ghost);\n\n ghost.style.opacity = '';\n ghost.style.cursor = 'grabbing';\n\n return ghost;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceDragging/SliceDragGhost.css';\nimport './HeaderDragGhost.css';\nimport { useEffect, useRef } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { HeaderDragState } from './HeaderDragState';\n\n// The same tilt a picked-up slice gets.\nconst ghostTiltDegrees = 3;\n\nexport interface HeaderDragGhostProps {\n drag?: HeaderDragState;\n // The height of the labelled stand-in drawn when the header could not be copied.\n headerHeight: number;\n}\n\n// The feature or module being dragged, drawn over everything at the pointer as a tilted copy of just its\n// header; the body underneath stays where it is, the way a slice ghost shows only the slice being moved.\nexport const HeaderDragGhost = ({ drag, headerHeight }: HeaderDragGhostProps) =>\n drag ? createPortal(<HeaderGhost drag={drag} headerHeight={headerHeight} />, document.body) : undefined;\n\nconst HeaderGhost = ({ drag, headerHeight }: { drag: HeaderDragState; headerHeight: number }) => {\n const snapshotHost = useRef<HTMLDivElement | null>(null);\n const ghost = drag.ghost;\n\n // The copy is a detached DOM node rather than markup React owns, so it is placed by hand.\n useEffect(() => {\n const host = snapshotHost.current;\n if (!host || !ghost) return;\n host.replaceChildren(ghost);\n return () => host.replaceChildren();\n }, [ghost]);\n\n return (\n <div\n style={{\n position: 'fixed',\n left: drag.currentX - drag.ghostWidth / 2 * drag.zoom,\n top: drag.headerY,\n width: drag.ghostWidth,\n transform: `scale(${drag.zoom}) rotate(${ghostTiltDegrees}deg)`,\n transformOrigin: '0 0',\n pointerEvents: 'none',\n zIndex: 9998,\n userSelect: 'none',\n }}\n >\n {ghost\n ? <div ref={snapshotHost} className='event-modeling-grid-header-ghost' style={{ width: drag.ghostWidth }} />\n : (\n <div className='event-modeling-grid-slice-ghost-fallback' style={{ width: drag.ghostWidth, height: headerHeight }}>\n <span>{drag.ghostLabel}</span>\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The horizontal extent of one laid-out feature or module, as far as the drop calculation is concerned.\nexport interface HeaderExtent {\n // Left edge, in client coordinates.\n left: number;\n width: number;\n}\n\n// Which gap between features or modules a pointer at clientX is over.\n//\n// Counts gaps, not columns: 0 is before the first and extents.length is after the last, so a drag to the\n// far right has somewhere to land. A column is passed once the pointer is beyond its midpoint, which is\n// what makes the swap happen when the two are visually half-overlapped rather than only once the pointer\n// clears the whole column. The extents are read from the laid-out columns, because a collapsed one is far\n// narrower than an expanded one and nothing says the columns are evenly sized.\nexport const headerDropIndex = (extents: readonly HeaderExtent[], clientX: number): number => {\n for (let index = 0; index < extents.length; index++) {\n if (clientX < extents[index].left + extents[index].width / 2) return index;\n }\n return extents.length;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\n// The order after moving the item at sourceIndex into the gap at dropIndex, where gap n sits before\n// item n and the gap after the last item is the length of the list. Undefined when the item would land\n// where it already is, so nothing is reported for a drop that changes nothing.\nexport function reorderedIds(ids: readonly Guid[], sourceIndex: number, dropIndex: number): Guid[] | undefined {\n if (!Number.isInteger(sourceIndex) || sourceIndex < 0 || sourceIndex >= ids.length) return undefined;\n if (!Number.isInteger(dropIndex)) return undefined;\n\n // Taking the item out closes its own gap, so every gap after it moves one to the left.\n const landingIndex = dropIndex > sourceIndex ? dropIndex - 1 : dropIndex;\n const targetIndex = Math.min(Math.max(landingIndex, 0), ids.length - 1);\n if (targetIndex === sourceIndex) return undefined;\n\n const reordered = [...ids];\n const [moved] = reordered.splice(sourceIndex, 1);\n reordered.splice(targetIndex, 0, moved);\n return reordered;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Reads the board's zoom off the nearest ancestor that scales, so a ghost drawn outside the board\n// matches the size of what it was copied from.\nexport function zoomOfAncestor(element: HTMLElement | null): number {\n let current = element?.parentElement ?? undefined;\n while (current) {\n const scale = current.style.transform.match(/scale\\(([^)]+)\\)/);\n if (scale) return parseFloat(scale[1]);\n current = current.parentElement ?? undefined;\n }\n return 1;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useMemo, useRef, type PointerEvent, type PointerEventHandler } from 'react';\nimport { createHeaderDragGhost } from './createHeaderDragGhost';\nimport type { HeaderDragStart } from './HeaderDragStart';\nimport { zoomOfAncestor } from './zoomOfAncestor';\n\n// How far the pointer travels before a press on a header becomes a drag.\nconst dragThreshold = 4;\n\nexport interface HeaderDragHandlers {\n onPointerDown: PointerEventHandler<HTMLDivElement>;\n onPointerMove: PointerEventHandler<HTMLDivElement>;\n onPointerUp: PointerEventHandler<HTMLDivElement>;\n}\n\ninterface Press {\n startX: number;\n startY: number;\n grabOffsetY: number;\n}\n\n// Turns a press on a header into a drag once the pointer has moved a few pixels. Undefined when there\n// is nothing to report a drag to, so the header takes no press and the board keeps its own gestures.\nexport function useHeaderDragIntent(onDragStart?: (start: HeaderDragStart) => void): HeaderDragHandlers | undefined {\n const press = useRef<Press | undefined>(undefined);\n\n return useMemo(() => {\n if (!onDragStart) return undefined;\n\n return {\n onPointerDown: (event: PointerEvent<HTMLDivElement>) => {\n const target = event.target;\n if (target instanceof Element && (target.tagName === 'INPUT' || target.closest('button'))) return;\n // Claim the gesture so dragging here moves the header instead of panning the board.\n event.stopPropagation();\n const rect = event.currentTarget.getBoundingClientRect();\n press.current = { startX: event.clientX, startY: event.clientY, grabOffsetY: event.clientY - rect.top };\n },\n onPointerMove: (event: PointerEvent<HTMLDivElement>) => {\n const current = press.current;\n if (!current) return;\n const movedX = Math.abs(event.clientX - current.startX);\n const movedY = Math.abs(event.clientY - current.startY);\n if (movedX <= dragThreshold && movedY <= dragThreshold) return;\n\n press.current = undefined;\n const header = event.currentTarget;\n onDragStart({\n clientX: event.clientX,\n clientY: event.clientY,\n width: header.getBoundingClientRect().width,\n headerY: current.startY - current.grabOffsetY,\n zoom: zoomOfAncestor(header),\n ghost: createHeaderDragGhost(header),\n });\n },\n onPointerUp: () => {\n press.current = undefined;\n },\n };\n }, [onDragStart]);\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceStatus } from '../Model';\n\nexport interface SliceStatusIconProps {\n status: SliceStatus;\n}\n\n// Every glyph is drawn in currentColor, so the host decides its color.\nexport const SliceStatusIcon = ({ status }: SliceStatusIconProps) => (\n <svg width='12' height='12' viewBox='0 0 12 12' fill='none' aria-hidden='true' xmlns='http://www.w3.org/2000/svg'>\n <StatusGlyph status={status} />\n </svg>\n);\n\nconst StatusGlyph = ({ status }: SliceStatusIconProps) => {\n switch (status) {\n case SliceStatus.notStarted:\n return <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' strokeDasharray='3 2' />;\n case SliceStatus.draft:\n return <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />;\n case SliceStatus.analysis:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />\n <circle cx='5.2' cy='5.2' r='1.6' stroke='currentColor' strokeWidth='1.2' />\n <line x1='6.5' y1='6.5' x2='8.2' y2='8.2' stroke='currentColor' strokeWidth='1.2' strokeLinecap='round' />\n </>\n );\n case SliceStatus.readyForImplementation:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />\n <line x1='4' y1='6' x2='8' y2='6' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n </>\n );\n case SliceStatus.inProgress:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />\n <path d='M6 1 A5 5 0 0 1 11 6' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' fill='none' />\n </>\n );\n case SliceStatus.readyForReview:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />\n <circle cx='6' cy='6' r='2' fill='currentColor' />\n </>\n );\n case SliceStatus.done:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' fill='currentColor' fillOpacity='0.2' />\n <polyline points='3.5,6 5.2,7.8 8.5,4' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' strokeLinejoin='round' />\n </>\n );\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './MenuDropdown.css';\nimport React, { createContext, ReactNode, useContext, useEffect, useId, useMemo, useRef, useState } from 'react';\nimport { AnchoredOverlay } from '../Tooltips';\nimport { useDismissOnOutsidePointer } from '../Pickers/useDismissOnOutsidePointer';\nimport { Guid } from '@cratis/fundamentals';\n\nexport interface MenuDropdownItem {\n\n id: string | Guid;\n\n label?: string;\n\n description?: string;\n\n icon?: React.ReactNode;\n\n onClick?: () => void;\n\n keepOpen?: boolean;\n\n items?: MenuDropdownItem[];\n\n isSeparator?: boolean;\n\n // Renders the item as a non-interactive section header.\n isHeader?: boolean;\n\n // When defined, renders a radio-like check indicator reflecting the checked state.\n checked?: boolean;\n\n // Renders the item greyed out and non-interactive.\n disabled?: boolean;\n\n // Shown as the item's tooltip — use it to say why a disabled item cannot be used.\n tooltip?: string;\n}\n\nexport interface MenuDropdownProps {\n\n trigger: React.ReactNode;\n\n items: MenuDropdownItem[];\n\n align?: 'left' | 'right';\n\n onClose?: () => void;\n}\n\ninterface MenuDropdownOpenStateContextValue {\n openMenuId: string | undefined;\n setOpenMenuId: React.Dispatch<React.SetStateAction<string | undefined>>;\n}\n\nconst MenuDropdownOpenStateContext = createContext<MenuDropdownOpenStateContextValue | undefined>(undefined);\n\nexport interface MenuDropdownOpenProviderProps {\n children: ReactNode;\n}\n\nexport const toggleOpenMenuId = (currentOpenMenuId: string | undefined, menuId: string): string | undefined =>\n currentOpenMenuId === menuId ? undefined : menuId;\n\nexport const closeOpenMenuId = (currentOpenMenuId: string | undefined, menuId: string): string | undefined =>\n currentOpenMenuId === menuId ? undefined : currentOpenMenuId;\n\nexport const MenuDropdownOpenProvider: React.FC<MenuDropdownOpenProviderProps> = ({ children }) => {\n const [openMenuId, setOpenMenuId] = useState<string>();\n\n return (\n <MenuDropdownOpenStateContext.Provider value={{ openMenuId, setOpenMenuId }}>\n {children}\n </MenuDropdownOpenStateContext.Provider>\n );\n};\n\nexport const MenuDropdown: React.FC<MenuDropdownProps> = ({ trigger, items, align = 'right', onClose }) => {\n const context = useContext(MenuDropdownOpenStateContext);\n const menuId = useId();\n const [localOpen, setLocalOpen] = useState(false);\n const [openSubmenuId, setOpenSubmenuId] = useState<string | undefined>();\n const containerRef = useRef<HTMLDivElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n const open = context ? context.openMenuId === menuId : localOpen;\n const previousOpenRef = useRef(open);\n\n useEffect(() => {\n if (previousOpenRef.current && !open) {\n onClose?.();\n setOpenSubmenuId(undefined);\n }\n previousOpenRef.current = open;\n }, [open, onClose]);\n\n const setOpen = (next: boolean) => {\n if (context) {\n if (next) {\n context.setOpenMenuId(current => toggleOpenMenuId(current, menuId));\n } else {\n context.setOpenMenuId(current => closeOpenMenuId(current, menuId));\n }\n return;\n }\n setLocalOpen(next);\n };\n\n const close = () => setOpen(false);\n\n const outsideRefs = useMemo(() => [containerRef, menuRef], []);\n useDismissOnOutsidePointer(outsideRefs, close, open);\n\n const renderMenuItems = (itemList: MenuDropdownItem[]) => {\n return itemList.map(item => {\n if (item.isSeparator) {\n return <div key={item.id.toString()} className='event-modeling-menu-dropdown-separator' />;\n }\n\n if (item.isHeader) {\n return (\n <div key={item.id.toString()} className='event-modeling-menu-dropdown-header'>\n {item.label}\n </div>\n );\n }\n\n const hasSubmenu = item.items && item.items.length > 0;\n const isSubmenuOpen = openSubmenuId === item.id.toString();\n\n return (\n <div key={item.id.toString()} className='event-modeling-menu-dropdown-item-wrapper'>\n <button\n className={`event-modeling-menu-dropdown-option ${hasSubmenu ? 'event-modeling-menu-dropdown-option--has-submenu' : ''}`}\n disabled={item.disabled}\n title={item.tooltip}\n onClick={() => {\n if (item.disabled) return;\n if (hasSubmenu) {\n setOpenSubmenuId(isSubmenuOpen ? undefined : item.id.toString());\n } else {\n if (!item.keepOpen) close();\n item.onClick?.();\n }\n }}\n >\n {item.icon && (\n <span className='event-modeling-menu-dropdown-option-icon'>{item.icon}</span>\n )}\n <span className='event-modeling-menu-dropdown-option-text'>\n {item.label && <span className='event-modeling-menu-dropdown-option-label'>{item.label}</span>}\n {item.description && (\n <span className='event-modeling-menu-dropdown-option-desc'>{item.description}</span>\n )}\n </span>\n {item.checked !== undefined && (\n <span className='event-modeling-menu-dropdown-option-check'>\n {item.checked && <i className='pi pi-check' />}\n </span>\n )}\n {hasSubmenu && (\n <span className={`event-modeling-menu-dropdown-option-arrow ${isSubmenuOpen ? 'event-modeling-menu-dropdown-option-arrow--open' : ''}`}>\n <i className='pi pi-chevron-right' />\n </span>\n )}\n </button>\n {hasSubmenu && isSubmenuOpen && (\n <div className={`event-modeling-menu-dropdown-submenu ${align === 'right' ? 'event-modeling-menu-dropdown-submenu--left' : ''}`}>\n {renderMenuItems(item.items!)}\n </div>\n )}\n </div>\n );\n });\n };\n\n return (\n <div ref={containerRef} className='event-modeling-menu-dropdown'>\n <div\n className='event-modeling-menu-dropdown-trigger'\n onPointerDown={(event) => event.stopPropagation()}\n onClick={(event) => { event.stopPropagation(); setOpen(!open); }}\n >\n {trigger}\n </div>\n {/* The panel portals to <body> anchored to the trigger, so it floats above everything\n and is never clipped by the slice columns' paint containment. */}\n <AnchoredOverlay anchorRef={containerRef} open={open} side='below' align={align}>\n <div ref={menuRef} className='event-modeling-menu-dropdown-menu'>\n {renderMenuItems(items)}\n </div>\n </AnchoredOverlay>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { SliceStatus } from '../Model';\n\n// Shows the picked status at once and goes back to the one shown before when the consumer says the\n// change did not land.\nexport const changeSliceStatus = async (\n previous: SliceStatus,\n picked: SliceStatus,\n report: (status: SliceStatus) => Promise<boolean | void> | void,\n show: (status: SliceStatus) => void): Promise<void> => {\n show(picked);\n if (await report(picked) === false) show(previous);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceStatus } from '../Model';\nimport type { EventModelMessages } from '../Messages';\n\n// The order statuses are offered in: a drafted slice is analyzed before it is handed on to implementation.\nexport const sliceStatusWorkflowOrder: readonly SliceStatus[] = [\n SliceStatus.notStarted,\n SliceStatus.draft,\n SliceStatus.analysis,\n SliceStatus.readyForImplementation,\n SliceStatus.inProgress,\n SliceStatus.readyForReview,\n SliceStatus.done,\n];\n\nexport const sliceStatusColor = (status: SliceStatus): string => {\n switch (status) {\n case SliceStatus.notStarted: return 'rgba(255,255,255,0.35)';\n case SliceStatus.draft: return '#9333ea';\n case SliceStatus.analysis: return '#6366f1';\n case SliceStatus.readyForImplementation: return '#06b6d4';\n case SliceStatus.inProgress: return '#3b82f6';\n case SliceStatus.readyForReview: return '#f59e0b';\n case SliceStatus.done: return '#10b981';\n }\n};\n\nexport const sliceStatusLabel = (status: SliceStatus, messages: EventModelMessages): string => {\n switch (status) {\n case SliceStatus.notStarted: return messages.statuses.notStarted;\n case SliceStatus.draft: return messages.statuses.draft;\n case SliceStatus.analysis: return messages.statuses.analysis;\n case SliceStatus.readyForImplementation: return messages.statuses.readyForImplementation;\n case SliceStatus.inProgress: return messages.statuses.inProgress;\n case SliceStatus.readyForReview: return messages.statuses.readyForReview;\n case SliceStatus.done: return messages.statuses.done;\n }\n};\n\n// The CSS modifier a status is styled by.\nexport const sliceStatusName = (status: SliceStatus): string => SliceStatus[status];\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceStatusPicker.css';\nimport { useEffect, useState } from 'react';\nimport { SliceStatus } from '../Model';\nimport { useBoard } from '../Board';\nimport { MenuDropdown, type MenuDropdownItem } from '../Menus';\nimport { SliceStatusIcon } from './SliceStatusIcon';\nimport { changeSliceStatus } from './changeSliceStatus';\nimport { sliceStatusColor, sliceStatusLabel, sliceStatusName, sliceStatusWorkflowOrder } from './sliceStatuses';\n\nexport interface SliceStatusPickerProps {\n status: SliceStatus;\n // Picking a status shows it at once. Resolving to false says the change did not land, and the\n // picker goes back to the status it showed before. Without it the status is only drawn.\n onStatusChanged?: (status: SliceStatus) => Promise<boolean | void> | void;\n // The statuses that may be picked; the others are shown disabled. Every status when omitted.\n selectable?: readonly SliceStatus[];\n // Why a status that is not selectable cannot be picked.\n unselectableReason?: string;\n}\n\nexport const SliceStatusPicker = ({ status, onStatusChanged, selectable = sliceStatusWorkflowOrder, unselectableReason }: SliceStatusPickerProps) => {\n const { readOnly, messages } = useBoard();\n const [shown, setShown] = useState(status);\n\n // Follows the status it is given, which also reconciles a change shown optimistically with the\n // one that eventually arrives.\n useEffect(() => setShown(status), [status]);\n\n const title = `${messages.statuses.titlePrefix} ${sliceStatusLabel(shown, messages)}`;\n const className = `event-modeling-slice-status-icon event-modeling-slice-status-icon--${sliceStatusName(shown)}`;\n\n if (readOnly || !onStatusChanged) {\n return (\n <span className={`${className} event-modeling-slice-status-icon--readonly`} title={title} aria-label={sliceStatusLabel(shown, messages)}>\n <SliceStatusIcon status={shown} />\n </span>\n );\n }\n\n const change = (next: SliceStatus) => changeSliceStatus(shown, next, onStatusChanged, setShown);\n\n const items: MenuDropdownItem[] = sliceStatusWorkflowOrder.map(option => ({\n id: sliceStatusName(option),\n label: sliceStatusLabel(option, messages),\n icon: <StatusOptionMark status={option} checked={option === shown} />,\n disabled: !selectable.includes(option),\n tooltip: selectable.includes(option) ? undefined : unselectableReason,\n onClick: () => change(option),\n }));\n\n return (\n <MenuDropdown\n trigger={\n <button className={className} title={title} aria-label={messages.statuses.change}>\n <SliceStatusIcon status={shown} />\n </button>\n }\n items={items}\n align='left'\n />\n );\n};\n\nconst StatusOptionMark = ({ status, checked }: { status: SliceStatus; checked: boolean }) => {\n const color = sliceStatusColor(status);\n return (\n <svg width='12' height='12' viewBox='0 0 12 12' aria-hidden='true'>\n <circle cx='6' cy='6' r='5' fill={color} fillOpacity='0.25' stroke={color} strokeWidth='1.5' />\n {checked && <polyline points='3,6 5,8 9,4' stroke={color} strokeWidth='1.4' strokeLinecap='round' strokeLinejoin='round' fill='none' />}\n </svg>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { MenuDropdown, type MenuDropdownItem } from '../Menus';\nimport { useEventModelMessages } from '../Messages';\nimport type { ModuleHeaderAction } from './ModuleHeaderAction';\n\nexport interface ModuleHeaderMenuProps {\n moduleId: Guid;\n actions: readonly ModuleHeaderAction[];\n onAddModule?: () => void;\n onAddFeature?: () => void;\n kind: 'options' | 'add';\n}\n\nexport const ModuleHeaderMenu = ({ moduleId, actions, onAddModule, onAddFeature, kind }: ModuleHeaderMenuProps) => {\n const messages = useEventModelMessages();\n const triggerRef = useRef<HTMLButtonElement>(null);\n const [selected, setSelected] = useState<string>();\n if (!actions.length && !onAddModule && !onAddFeature) return null;\n const activate = (action: ModuleHeaderAction) => {\n const host = triggerRef.current?.getBoundingClientRect();\n if (host) action.onActivate(moduleId, host);\n };\n const itemsFor = (entries: readonly ModuleHeaderAction[]): MenuDropdownItem[] => entries.map(action => ({\n id: action.id, label: action.label + (action.items ? ' ›' : ''), description: action.description,\n icon: action.icon, disabled: action.disabled, tooltip: action.tooltip, isSeparator: action.isSeparator,\n keepOpen: !!action.items, onClick: () => action.items ? setSelected(action.id) : activate(action),\n }));\n const items: MenuDropdownItem[] = selected ? [\n { id: 'back', label: messages.features.back, keepOpen: true, onClick: () => setSelected(undefined) },\n ...itemsFor(actions.find(action => action.id === selected)?.items ?? []),\n ] : [\n ...(onAddModule ? [{ id: 'module', label: messages.modules.addModule, description: messages.modules.addModuleDescription, onClick: onAddModule }] : []),\n ...(onAddFeature ? [{ id: 'feature', label: messages.modules.addFeature, description: messages.modules.addFeatureDescription, onClick: onAddFeature }] : []),\n ...itemsFor(actions),\n ];\n const label = kind === 'add' ? messages.modules.add : messages.modules.options;\n return <MenuDropdown trigger={<button ref={triggerRef} type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={label} aria-label={label}>{kind === 'add' ? '+' : <svg width='13' height='13' viewBox='0 0 14 14' fill='none' aria-hidden='true'>\n <line x1='2' y1='3.5' x2='12' y2='3.5' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n <line x1='2' y1='7' x2='12' y2='7' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n <line x1='2' y1='10.5' x2='12' y2='10.5' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n </svg>}</button>}\n items={items} align='right' onClose={() => setSelected(undefined)} />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useState } from 'react';\nimport type { FeatureHeaderSuggestion } from './FeatureHeaderSuggestion';\nimport './FeatureSuggestions.css';\n\nconst Suggestion = ({ suggestion }: { suggestion: FeatureHeaderSuggestion }) => {\n const [isAccepting, setIsAccepting] = useState(false);\n const accept = async () => {\n if (isAccepting) return;\n setIsAccepting(true);\n try {\n await suggestion.onAccept();\n } finally {\n setIsAccepting(false);\n }\n };\n return <span className='prediction-ghost' data-suggestion-name={suggestion.name}>\n <button type='button' className='prediction-ghost__accept' disabled={isAccepting}\n aria-label={suggestion.acceptLabel} title={suggestion.rationale ?? suggestion.acceptLabel}\n onClick={() => { void accept(); }}>\n <i className={isAccepting ? 'pi pi-spinner pi-spin' : 'pi pi-bolt'} style={{ fontSize: 9 }} aria-hidden='true' />\n <span>{suggestion.name}</span>\n </button>\n <button type='button' className='prediction-ghost__discard' aria-label={suggestion.discardLabel}\n title={suggestion.discardLabel} onClick={suggestion.onDiscard}>×</button>\n </span>;\n};\n\nexport const FeatureSuggestions = ({ suggestions }: { suggestions: readonly FeatureHeaderSuggestion[] }) =>\n <>{suggestions.map(suggestion => <Suggestion key={suggestion.id} suggestion={suggestion} />)}</>;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Headers/IconButton.css';\nimport '../Rows/AddButton.css';\nimport type { CSSProperties } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceStatus } from '../Model';\nimport { useBoard } from '../Board';\nimport { DetailsToggle, PillHeader } from '../Headers';\nimport { useHeaderDragIntent, type HeaderDragStart } from '../HeaderDragging';\nimport { useEventModelPresentation } from '../Presentation';\nimport { SliceStatusPicker } from '../Statuses';\nimport { ModuleHeaderMenu } from './ModuleHeaderMenu';\nimport { FeatureSuggestions } from '../Features/FeatureSuggestions';\n\nexport interface ModuleHeaderProps {\n moduleId: Guid;\n name: string;\n height: number;\n collapsed: boolean;\n onToggleCollapse?: () => void;\n onAddModule?: () => void;\n onAddFeature?: () => void;\n // Renaming exists only when the board is editable and this is supplied.\n onRenamed?: (moduleId: Guid, name: string) => void;\n // Says why a name cannot be used, such as one another module already has.\n validateName?: (name: string) => string | undefined;\n // The status of the module as a whole, shown but never picked here. Nothing is shown when undefined.\n status?: SliceStatus;\n // The details toggle is drawn when onToggleDetails is supplied.\n detailsVisible?: boolean;\n onToggleDetails?: () => void;\n // The header can be picked up only when the board is editable and this is supplied.\n onDragStart?: (start: HeaderDragStart) => void;\n // Shown on the header when something done to the module failed.\n error?: string;\n}\n\nconst background = 'rgba(255,255,255,0.05)';\nconst border = '1px solid rgba(255,255,255,0.10)';\nconst labelStyle: CSSProperties = { fontSize: 13, fontWeight: 600, color: 'rgba(255,255,255,0.80)', textAlign: 'center' };\n\nexport const ModuleHeader = ({\n moduleId,\n name,\n height,\n collapsed,\n onToggleCollapse,\n onAddModule,\n onAddFeature,\n onRenamed,\n validateName,\n status,\n detailsVisible = false,\n onToggleDetails,\n onDragStart,\n error,\n}: ModuleHeaderProps) => {\n const board = useBoard();\n const { showStatuses = true } = useEventModelPresentation();\n const dragHandlers = useHeaderDragIntent(!board.readOnly && !collapsed ? onDragStart : undefined);\n const renamed = board.readOnly ? undefined : onRenamed;\n const actions = board.actions;\n\n return (\n <PillHeader\n variant='module'\n collapsed={collapsed}\n onToggle={onToggleCollapse}\n leadingContent={!board.readOnly && (actions.moduleHeaderLeading ?? []).map(action => <button\n key={action.id} type='button' className='event-modeling-grid-icon-btn'\n title={action.label} aria-label={action.label} disabled={action.disabled}\n onClick={event => action.onActivate(moduleId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}{action.indicator && <span className='event-modeling-feature-chat-dot' aria-hidden='true' />}</button>)}\n label={name}\n onRenameLabel={value => renamed?.(moduleId, value)}\n labelReadOnly={!renamed}\n validateLabel={validateName}\n labelStyle={labelStyle}\n background={background}\n border={border}\n height={height}\n draggable={dragHandlers !== undefined}\n onPointerDown={dragHandlers?.onPointerDown}\n onPointerMove={dragHandlers?.onPointerMove}\n onPointerUp={dragHandlers?.onPointerUp}\n error={error}\n >\n {showStatuses && status !== undefined && <SliceStatusPicker status={status} />}\n {!board.readOnly && onToggleDetails && <DetailsToggle visible={detailsVisible} onToggle={onToggleDetails} />}\n {!board.readOnly && <ModuleHeaderMenu kind='options' moduleId={moduleId} actions={actions.moduleHeaderMenu ?? []} />}\n {!board.readOnly && (actions.moduleHeaderAfterMenu ?? []).map(action => <button\n key={action.id} type='button' className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={action.label} aria-label={action.label} disabled={action.disabled}\n onClick={event => action.onActivate(moduleId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}</button>)}\n {!board.readOnly && <FeatureSuggestions suggestions={actions.moduleHeaderSuggestions ?? []} />}\n {!board.readOnly && <ModuleHeaderMenu kind='add' moduleId={moduleId} actions={actions.moduleHeaderAdd ?? []}\n onAddModule={onAddModule} onAddFeature={onAddFeature} />}\n </PillHeader>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { headerDropIndex, reorderedIds, type HeaderDragStart, type HeaderDragState } from '../HeaderDragging';\nimport type { ModulesReordered } from './ModulesReordered';\n\nexport interface ModuleDragState extends HeaderDragState {\n moduleId: Guid;\n sourceIndex: number;\n currentY: number;\n // The gap the module would land in right now: n is before the nth module of the collection.\n dropIndex: number;\n}\n\nexport type ModuleDragStart = (moduleId: Guid, label: string, start: HeaderDragStart) => void;\n\nexport interface ModuleDrag {\n moduleDrag?: ModuleDragState;\n // Undefined when nothing can be told about a move, so no module header offers to be picked up.\n handleModuleDragStart?: ModuleDragStart;\n}\n\n// The gap a pointer at clientX is over among the given modules, in the collection's own order. Only this\n// collection's modules count: numbering the gaps across every module on the board put a drag to either end\n// of a collection that is not the leftmost one into a gap belonging to somebody else.\nfunction dropIndexAt(moduleIds: readonly Guid[], clientX: number): number {\n const extents = moduleIds\n .map(id => document.querySelector<HTMLElement>(`[data-module-id=\"${id.toString()}\"]`))\n .filter((element): element is HTMLElement => element !== null)\n .map(element => element.getBoundingClientRect());\n return headerDropIndex(extents, clientX);\n}\n\n// Dragging a module to another place among the modules of its collection.\n// moduleIds: the collection's modules in their current order.\nexport function useModuleDrag(collectionId: Guid, moduleIds: readonly Guid[], onModulesReordered?: ModulesReordered): ModuleDrag {\n const board = useBoard();\n const [moduleDrag, setModuleDrag] = useState<ModuleDragState | undefined>(undefined);\n const moduleDragRef = useRef(moduleDrag);\n moduleDragRef.current = moduleDrag;\n const moduleIdsRef = useRef(moduleIds);\n moduleIdsRef.current = moduleIds;\n const collectionIdRef = useRef(collectionId);\n collectionIdRef.current = collectionId;\n const onModulesReorderedRef = useRef(onModulesReordered);\n onModulesReorderedRef.current = onModulesReordered;\n\n const handleModuleDragStart = useCallback<ModuleDragStart>((moduleId, label, start) => {\n const sourceIndex = moduleIdsRef.current.findIndex(id => id.equals(moduleId));\n if (sourceIndex === -1) return;\n setModuleDrag({\n moduleId,\n sourceIndex,\n ghostLabel: label,\n ghostWidth: start.width,\n ghost: start.ghost,\n currentX: start.clientX,\n currentY: start.clientY,\n dropIndex: sourceIndex,\n headerY: start.headerY,\n zoom: start.zoom,\n });\n }, []);\n\n const dragging = moduleDrag !== undefined;\n useEffect(() => {\n if (!dragging) return;\n\n const handlePointerMove = (event: PointerEvent) => {\n setModuleDrag(previous => previous && {\n ...previous,\n currentX: event.clientX,\n currentY: event.clientY,\n dropIndex: dropIndexAt(moduleIdsRef.current, event.clientX),\n });\n };\n\n const handlePointerUp = () => {\n const drag = moduleDragRef.current;\n setModuleDrag(undefined);\n if (!drag) return;\n const ordered = reorderedIds(moduleIdsRef.current, drag.sourceIndex, drag.dropIndex);\n if (ordered) onModulesReorderedRef.current?.(collectionIdRef.current, ordered);\n };\n\n window.addEventListener('pointermove', handlePointerMove);\n window.addEventListener('pointerup', handlePointerUp);\n return () => {\n window.removeEventListener('pointermove', handlePointerMove);\n window.removeEventListener('pointerup', handlePointerUp);\n };\n }, [dragging]);\n\n const canDrag = !board.readOnly && onModulesReordered !== undefined;\n return { moduleDrag, handleModuleDragStart: canDrag ? handleModuleDragStart : undefined };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface ModuleAreaItem {\n id: Guid;\n name: string;\n collapsed: boolean;\n}\n\nexport interface ModuleAreaState<T extends ModuleAreaItem> {\n snapshot: T[];\n modules: T[];\n additions: T[];\n order?: Guid[];\n collapses: ReadonlyMap<string, boolean>;\n renames: ReadonlyMap<string, string>;\n collapseBarriers: ReadonlyMap<string, boolean>;\n renameBarriers: ReadonlyMap<string, string>;\n orderBarrier?: Guid[];\n}\n\nexport const createModuleAreaState = <T extends ModuleAreaItem>(modules: T[]): ModuleAreaState<T> => ({\n snapshot: modules, modules, additions: [], collapses: new Map(), renames: new Map(),\n collapseBarriers: new Map(), renameBarriers: new Map(),\n});\n\nconst sameOrder = (modules: readonly ModuleAreaItem[], ids: readonly Guid[]) =>\n modules.length === ids.length && modules.every((module, index) => module.id.equals(ids[index]));\n\nexport function reconcileModules<T extends ModuleAreaItem>(state: ModuleAreaState<T>, snapshot: T[]): ModuleAreaState<T> {\n const additions = state.additions.filter(added => !snapshot.some(module => module.id.equals(added.id)));\n // A -> B -> A cannot be acknowledged by the initial A snapshot. Without a sequence number,\n // require a snapshot containing B before accepting a subsequent snapshot containing A.\n const collapseBarriers = new Map([...state.collapseBarriers].filter(([id, value]) =>\n !snapshot.some(module => module.id.toString() === id && module.collapsed === value)));\n const renameBarriers = new Map([...state.renameBarriers].filter(([id, name]) =>\n !snapshot.some(module => module.id.toString() === id && module.name === name)));\n const orderBarrier = state.orderBarrier && sameOrder(snapshot, state.orderBarrier) ? undefined : state.orderBarrier;\n const collapses = new Map([...state.collapses].filter(([id, value]) =>\n state.collapseBarriers.has(id) || !snapshot.some(module => module.id.toString() === id && module.collapsed === value)));\n const renames = new Map([...state.renames].filter(([id, name]) =>\n state.renameBarriers.has(id) || !snapshot.some(module => module.id.toString() === id && module.name === name)));\n const merged = [...snapshot, ...additions].map(module => ({ ...module,\n collapsed: collapses.get(module.id.toString()) ?? module.collapsed,\n name: renames.get(module.id.toString()) ?? module.name,\n }));\n const modules = state.order ? orderModules(merged, state.order) : merged;\n const order = state.order && !state.orderBarrier && sameOrder(snapshot, modules.map(module => module.id))\n ? undefined : state.order;\n return { snapshot, modules, additions, order, collapses, renames, collapseBarriers, renameBarriers, orderBarrier };\n}\n\nexport function setModuleCollapse<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid, collapsed: boolean): ModuleAreaState<T> {\n const key = id.toString();\n const prior = state.collapses.get(key);\n const collapseBarriers = new Map(state.collapseBarriers);\n if (prior !== undefined && state.snapshot.some(module => module.id.equals(id) && module.collapsed === collapsed)) {\n collapseBarriers.set(key, prior);\n }\n return { ...updateModule(state, id, module => ({ ...module, collapsed })),\n collapses: new Map(state.collapses).set(key, collapsed), collapseBarriers };\n}\n\nexport function setModuleRename<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid, name: string): ModuleAreaState<T> {\n const key = id.toString();\n const prior = state.renames.get(key);\n const renameBarriers = new Map(state.renameBarriers);\n if (prior !== undefined && state.snapshot.some(module => module.id.equals(id) && module.name === name)) {\n renameBarriers.set(key, prior);\n }\n return { ...updateModule(state, id, module => ({ ...module, name })),\n renames: new Map(state.renames).set(key, name), renameBarriers };\n}\n\nexport function setModuleOrder<T extends ModuleAreaItem>(state: ModuleAreaState<T>, ids: Guid[]): ModuleAreaState<T> {\n const orderBarrier = state.order && sameOrder(state.snapshot, ids) ? state.order : state.orderBarrier;\n return { ...state, modules: orderModules(state.modules, ids), order: ids, orderBarrier };\n}\n\nexport function revertModuleCollapse<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid): ModuleAreaState<T> {\n const collapses = new Map(state.collapses);\n collapses.delete(id.toString());\n const collapseBarriers = new Map(state.collapseBarriers);\n collapseBarriers.delete(id.toString());\n return reconcileModules({ ...state, collapses, collapseBarriers }, state.snapshot);\n}\n\nexport function revertModuleRename<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid): ModuleAreaState<T> {\n const renames = new Map(state.renames);\n renames.delete(id.toString());\n const renameBarriers = new Map(state.renameBarriers);\n renameBarriers.delete(id.toString());\n return reconcileModules({ ...state, renames, renameBarriers }, state.snapshot);\n}\n\nexport function revertModuleOrder<T extends ModuleAreaItem>(state: ModuleAreaState<T>, priorOrder?: Guid[]): ModuleAreaState<T> {\n return reconcileModules({ ...state, order: priorOrder, orderBarrier: undefined }, state.snapshot);\n}\n\nexport function orderModules<T extends ModuleAreaItem>(modules: T[], ids: readonly Guid[]): T[] {\n return [...ids.flatMap(id => modules.filter(module => module.id.equals(id))),\n ...modules.filter(module => !ids.some(id => id.equals(module.id)))];\n}\n\nexport function updateModule<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid, change: (module: T) => T): ModuleAreaState<T> {\n return { ...state, modules: state.modules.map(module => module.id.equals(id) ? change(module) : module) };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport async function persistModuleChange(\n execute: () => Promise<boolean>, revert: () => void, onPersistenceError: (error: unknown) => void,\n): Promise<void> {\n let succeeded: boolean;\n try {\n succeeded = await execute();\n } catch (error) {\n revert();\n onPersistenceError(error);\n return;\n }\n if (succeeded !== true) revert();\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { HeaderDragGhost, type HeaderDragStart } from '../HeaderDragging';\nimport { boardMetrics } from '../Layout';\nimport { ModuleDropIndicator } from './ModuleDropIndicator';\nimport { useModuleDrag } from './useModuleDrag';\nimport { createModuleAreaState, reconcileModules, revertModuleCollapse, revertModuleOrder, revertModuleRename, setModuleCollapse, setModuleOrder, setModuleRename, type ModuleAreaItem, type ModuleAreaState } from './moduleAreaState';\nimport { persistModuleChange } from './persistModuleChange';\n\nexport interface ModulesAreaProps<T extends ModuleAreaItem> {\n collectionId: Guid;\n initialModules: T[];\n onAddModule?: () => Promise<T | undefined>;\n onModulesReordered?: (orderedIds: Guid[]) => Promise<boolean>;\n onCollapseChanged?: (moduleId: Guid, collapsed: boolean) => Promise<boolean>;\n onRenameModule?: (moduleId: Guid, name: string) => Promise<boolean>;\n onPersistenceError?: (error: unknown) => void;\n renderModule: (module: T, options: {\n index: number;\n dragging: boolean;\n onDragStart?: (start: HeaderDragStart) => void;\n onAddModule?: () => void;\n onToggleCollapse?: () => void;\n onRenamed?: (name: string) => void;\n }) => ReactNode;\n onModulesChanged?: (modules: T[]) => void;\n}\n\nexport function ModulesArea<T extends ModuleAreaItem>({\n collectionId, initialModules, onAddModule, onModulesReordered, onCollapseChanged, onRenameModule,\n onPersistenceError, renderModule, onModulesChanged,\n}: ModulesAreaProps<T>) {\n const { readOnly } = useBoard();\n const reportError = useCallback((error: unknown) => {\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n }, [onPersistenceError]);\n const stateRef = useRef<ModuleAreaState<T>>(createModuleAreaState(initialModules));\n const [state, setState] = useState(stateRef.current);\n const adding = useRef(false);\n const [isAdding, setIsAdding] = useState(false);\n const busyIds = useRef(new Set<string>());\n const [busyModuleIds, setBusyModuleIds] = useState<ReadonlySet<string>>(new Set());\n const reordering = useRef(false);\n const [isReordering, setIsReordering] = useState(false);\n const markBusy = (id: string, busy: boolean) => {\n if (busy) busyIds.current.add(id);\n else busyIds.current.delete(id);\n setBusyModuleIds(new Set(busyIds.current));\n };\n const apply = useCallback((transition: (previous: ModuleAreaState<T>) => ModuleAreaState<T>) => {\n const next = transition(stateRef.current);\n stateRef.current = next;\n setState(next);\n onModulesChanged?.(next.modules);\n }, [onModulesChanged]);\n useEffect(() => {\n if (initialModules !== stateRef.current.snapshot) apply(previous => reconcileModules(previous, initialModules));\n }, [initialModules, apply]);\n\n const add = useCallback(async () => {\n if (readOnly || !onAddModule || adding.current) return;\n adding.current = true;\n setIsAdding(true);\n try {\n const added = await onAddModule();\n if (added) apply(previous => reconcileModules({ ...previous,\n additions: [...previous.additions, added],\n }, previous.snapshot));\n } catch (error) {\n reportError(error);\n } finally {\n adding.current = false;\n setIsAdding(false);\n }\n }, [readOnly, onAddModule, reportError, apply]);\n const toggle = useCallback(async (module: T) => {\n const id = module.id.toString();\n if (!onCollapseChanged || busyIds.current.has(id)) return;\n markBusy(id, true);\n const collapsed = !module.collapsed;\n apply(previous => setModuleCollapse(previous, module.id, collapsed));\n try {\n await persistModuleChange(() => onCollapseChanged(module.id, collapsed),\n () => apply(previous => revertModuleCollapse(previous, module.id)), reportError);\n } finally { markBusy(id, false); }\n }, [onCollapseChanged, reportError, apply]);\n const rename = useCallback(async (module: T, name: string) => {\n const id = module.id.toString();\n if (readOnly || !onRenameModule || busyIds.current.has(id)) return;\n markBusy(id, true);\n apply(previous => setModuleRename(previous, module.id, name));\n try {\n await persistModuleChange(() => onRenameModule(module.id, name),\n () => apply(previous => revertModuleRename(previous, module.id)), reportError);\n } finally { markBusy(id, false); }\n }, [readOnly, onRenameModule, reportError, apply]);\n const reorder = useCallback(async (_collectionId: Guid, ids: Guid[]) => {\n if (readOnly || !onModulesReordered || reordering.current) return;\n reordering.current = true;\n setIsReordering(true);\n const priorOrder = stateRef.current.order;\n apply(previous => setModuleOrder(previous, ids));\n try {\n await persistModuleChange(() => onModulesReordered(ids),\n () => apply(previous => revertModuleOrder(previous, priorOrder)), reportError);\n } finally {\n reordering.current = false;\n setIsReordering(false);\n }\n }, [apply, onModulesReordered, reportError, readOnly]);\n const { moduleDrag, handleModuleDragStart } = useModuleDrag(collectionId, state.modules.map(module => module.id), onModulesReordered && !isReordering ? reorder : undefined);\n\n return <>\n <HeaderDragGhost drag={moduleDrag} headerHeight={boardMetrics.headerHeight} />\n {state.modules.map((module, index) => <div key={module.id.toString()} style={{ display: 'contents' }}>\n {moduleDrag?.dropIndex === index && <ModuleDropIndicator />}\n {renderModule(module, {\n index, dragging: moduleDrag?.moduleId.equals(module.id) ?? false,\n onDragStart: !busyModuleIds.has(module.id.toString()) && handleModuleDragStart\n ? start => handleModuleDragStart(module.id, module.name, start) : undefined,\n onAddModule: !readOnly && !isAdding && onAddModule ? () => { void add(); } : undefined,\n // Collapsing changes nothing but how the board is drawn, so a read-only board allows it too.\n onToggleCollapse: !busyModuleIds.has(module.id.toString()) && onCollapseChanged\n ? () => { void toggle(module); } : undefined,\n onRenamed: !readOnly && !busyModuleIds.has(module.id.toString()) && onRenameModule\n ? name => { void rename(module, name); } : undefined,\n })}\n </div>)}\n {moduleDrag?.dropIndex === state.modules.length && <ModuleDropIndicator />}\n </>;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { boardMetrics } from '../Layout';\nimport { computePillLabelMinWidth, defaultMeasureLabelWidth, type MeasureLabelWidth } from '../Geometry';\n\n// The module header spans its visible feature columns, but cannot be narrower than its label or\n// the empty-feature placeholder. The widths passed in already account for collapsed features.\nexport function moduleWidth(featureWidths: readonly number[], name: string, measure: MeasureLabelWidth = defaultMeasureLabelWidth): number {\n const contents = featureWidths.length ? featureWidths.reduce((width, featureWidth, index) =>\n width + (index ? boardMetrics.sliceGap : 0) + featureWidth, 0) : Math.round(boardMetrics.sliceWidth * 1.5);\n return Math.max(contents, computePillLabelMinWidth(name, measure));\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Headers/HeaderCell.css';\nimport type { ReactNode } from 'react';\n\nexport interface ModuleHeaderCellProps {\n width: number;\n // A collapsed module's cell takes the width of its pill rather than the width it is given.\n collapsed: boolean;\n children?: ReactNode;\n}\n\n// The cell a module's header, and anything the consumer puts under it, sits in.\nexport const ModuleHeaderCell = ({ width, collapsed, children }: ModuleHeaderCellProps) => (\n <div\n className={`event-modeling-grid-header-cell-wrapper${collapsed ? ' event-modeling-grid-header-cell-wrapper--module-collapsed' : ''}`}\n style={{ width: collapsed ? undefined : width }}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ModulePlaceholder.css';\n\nexport interface ModulePlaceholderProps {\n width: number;\n height: number;\n featureWidths: readonly number[];\n}\n\nexport const ModulePlaceholder = ({ width, height, featureWidths }: ModulePlaceholderProps) =>\n <div className='event-modeling-module-placeholder' style={{ width, height }} aria-hidden='true'>\n {featureWidths.map((featureWidth, index) => <div key={index}\n className='event-modeling-module-placeholder__feature' style={{ width: featureWidth }} />)}\n </div>;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode, Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { boardMetrics } from '../Layout';\nimport { ModuleColumnFrame } from './ModuleColumnFrame';\nimport { ModuleHeaderCell } from './ModuleHeaderCell';\n\nexport interface ModuleSurfaceProps {\n moduleId: Guid;\n collectionId: Guid;\n index: number;\n width: number;\n collapsed: boolean;\n dragging?: boolean;\n frameRef?: Ref<HTMLDivElement>;\n header: ReactNode;\n template?: ReactNode;\n content: ReactNode;\n}\n\nexport const ModuleSurface = ({ moduleId, collectionId, index, width, collapsed, dragging,\n frameRef, header, template, content }: ModuleSurfaceProps) =>\n <ModuleColumnFrame ref={frameRef} moduleId={moduleId} collectionId={index === 0 ? collectionId : undefined}\n marginLeft={index ? boardMetrics.sliceGap : 0} dragging={dragging}>\n <ModuleHeaderCell width={width} collapsed={collapsed}>\n {header}\n {!collapsed && template}\n </ModuleHeaderCell>\n {collapsed ? <div style={{ width: boardMetrics.collapsedModuleWidth }} /> : content}\n </ModuleColumnFrame>;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { computePillLabelMinWidth } from '../Geometry';\nimport { boardMetrics, computeGlobalRowHeights, sliceColumnWidth } from '../Layout';\nimport { ActorType, type Feature, type ModuleCollection, type Slice } from '../Model';\nimport { RowType } from '../Rows';\nimport { actorTypeOfRow } from '../RowLabels';\nimport { moduleWidth } from '../Modules';\n\n// A slice of a collection, with the module and feature it sits in.\nexport interface CollectionSlice {\n slice: Slice;\n moduleId: string;\n featureId: string;\n}\n\nexport const collectionSlices = (collection: ModuleCollection): CollectionSlice[] => {\n const visit = (moduleId: string, feature: Feature, seen: Set<string>): CollectionSlice[] => {\n if (seen.has(feature.id.toString())) return [];\n seen.add(feature.id.toString());\n return [\n ...feature.slices.map(slice => ({ slice, moduleId, featureId: feature.id.toString() })),\n ...feature.subFeatures.flatMap(child => visit(moduleId, child, seen)),\n ];\n };\n return collection.modules.flatMap(module => module.features.flatMap(feature => visit(module.id.toString(), feature, new Set())));\n};\n\n// Whether a slice shows the properties of its cards - which the presentation decides per board, module,\n// feature and slice.\nexport type SliceDetailsVisibility = (slice: CollectionSlice) => boolean;\n\nexport const collectionRows = (collection: ModuleCollection): RowType[] => [\n ...(collection.actors.some(actor => actor.actorType === ActorType.UIRole) ? [RowType.UI] : []),\n ...(collection.actors.some(actor => actor.actorType === ActorType.systemRole) ? [RowType.System] : []),\n ...(collection.actors.some(actor => actor.actorType === ActorType.chatRole) ? [RowType.Chat] : []),\n RowType.Interaction, RowType.Events,\n];\n\nexport const collectionRowHeights = (collection: ModuleCollection, showsDetails?: SliceDetailsVisibility) =>\n computeGlobalRowHeights(collectionSlices(collection).map(entry => ({ slice: entry.slice, showDetails: showsDetails?.(entry) ?? false })),\n collectionRows(collection));\n\nexport const collectionContentHeight = (collection: ModuleCollection, rows: readonly RowType[], heights: Readonly<Record<RowType, number>>): number =>\n rows.reduce((total, row) => {\n const actorType = actorTypeOfRow(row);\n const count = actorType === undefined ? 1 : Math.max(1, collection.actors.filter(actor => actor.actorType === actorType).length);\n return total + count * heights[row];\n }, 0);\n\nexport const featureWidth = (feature: Feature): number => {\n if (feature.collapsed) return feature.slices.length\n ? feature.slices.length * boardMetrics.collapsedSliceWidth + (feature.slices.length - 1) * boardMetrics.sliceGap\n : boardMetrics.collapsedFeatureWidth;\n if (!feature.slices.length && feature.subFeatures.length) return 0;\n const labelWidth = computePillLabelMinWidth(feature.name);\n if (!feature.slices.length) return Math.max(Math.round(boardMetrics.sliceWidth * 1.5), labelWidth);\n const slicesWidth = feature.slices.reduce((total, slice, index) => total + (index ? boardMetrics.sliceGap : 0)\n + (slice.collapsed ? boardMetrics.collapsedSliceWidth : sliceColumnWidth(slice)), 0);\n return Math.max(boardMetrics.minPillWidth, labelWidth, slicesWidth);\n};\n\nexport const featureColumns = (features: Feature[]): Feature[] => {\n const seen = new Set<string>();\n const visit = (feature: Feature): Feature[] => {\n if (seen.has(feature.id.toString())) return [];\n seen.add(feature.id.toString());\n return [feature, ...feature.subFeatures.flatMap(visit)];\n };\n return features.flatMap(visit);\n};\n\nexport const collectionModuleWidth = (name: string, features: Feature[]): number =>\n moduleWidth(featureColumns(features).map(featureWidth).filter(width => width > 0), name);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { rowLabelWidth } from '../Geometry';\nimport { boardMetrics } from '../Layout';\nimport type { Feature, ModuleCollection } from '../Model';\nimport { collectionModuleWidth, collectionRowHeights, collectionRows, collectionSlices, type SliceDetailsVisibility } from './collectionGridLayout';\n\nexport interface CollectionSizeEstimate {\n width: number;\n height: number;\n moduleWidths: number[];\n}\n\nconst featureDepth = (features: Feature[]): number => features.length === 0 ? 0\n : 1 + Math.max(...features.map(feature => featureDepth(feature.subFeatures)));\n\n// The estimate sizes the offscreen placeholder, minimap and link anchor until CanvasItem reports a measured size.\n// Specifications extend the measured footprint but do not move the link anchor below the slice content.\n// A presentation that shows the properties of cards makes rows taller; say which slices show them to\n// measure the collection as it is drawn.\nexport const estimateCollectionSize = (collection: ModuleCollection, showsDetails?: SliceDetailsVisibility): CollectionSizeEstimate => {\n const rows = collectionRows(collection);\n const heights = collectionRowHeights(collection, showsDetails);\n const slices = collectionSlices(collection);\n const moduleWidths = collection.modules.map(module => module.collapsed\n ? boardMetrics.collapsedModuleWidth : collectionModuleWidth(module.name, module.features));\n const modulesWidth = moduleWidths.reduce((width, moduleWidth, index) =>\n width + (index ? boardMetrics.sliceGap : 0) + moduleWidth, 0);\n const featureHeaderRows = Math.max(1, ...collection.modules.map(module => featureDepth(module.features)));\n const rowsHeight = rows.reduce((height, row) => height + heights[row], 0);\n return {\n width: (slices.length ? rowLabelWidth : 0) + modulesWidth,\n height: boardMetrics.headerHeight * (1 + featureHeaderRows) + 28 + rowsHeight,\n moduleWidths,\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback } from 'react';\nimport { areDetailsVisible, areSliceDetailsVisibleForDetailLevel, useEventModelPresentation } from '../Presentation';\nimport type { SliceDetailsVisibility } from './collectionGridLayout';\n\n// Which slices show the properties of their cards under the board's presentation - the same rule the\n// slice's cells draw by, so the rows are measured for the cards they hold.\nexport const useSliceDetailsVisibility = (): SliceDetailsVisibility => {\n const { detailLevel, detailsVisibility } = useEventModelPresentation();\n return useCallback(({ slice, moduleId, featureId }) =>\n areSliceDetailsVisibleForDetailLevel(detailLevel, areDetailsVisible(detailsVisibility, moduleId, featureId, slice.id.toString())),\n [detailLevel, detailsVisibility]);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport { SliceType } from '../Model';\nimport { RowType } from '../Rows';\nimport { useEventModelPresentation } from '../Presentation';\nimport './Connectors.css';\n\nexport interface ConnectorProps {\n /**\n * Override the horizontal center of the connector arrow/fill-line.\n * 'left' = 25% (read-model column), 'center' = 50% (default), 'right' = 75% (command column).\n */\n columnPosition?: 'left' | 'center' | 'right';\n}\n\nfunction columnLeft(position?: 'left' | 'center' | 'right'): string | undefined {\n if (position === 'left') return '25%';\n if (position === 'right') return '75%';\n return undefined;\n}\n\n// In 'fillLines' (lines) mode the curved SliceConnections overlay draws all flow\n// lines, so the per-row fill lines and inter-row triangles are suppressed here.\n\nexport const ConnectorIncomingTop: React.FC<ConnectorProps> = ({ columnPosition }) => {\n const { visualizationMode } = useEventModelPresentation();\n if (visualizationMode === 'fillLines') return null;\n const style: React.CSSProperties | undefined = columnPosition ? { left: columnLeft(columnPosition) } : undefined;\n return <div className='event-modeling-grid-flow-triangle event-modeling-grid-flow-triangle--down' style={style} aria-hidden='true' />;\n};\n\nexport const ConnectorOutgoingTop: React.FC<ConnectorProps> = ({ columnPosition }) => {\n const { visualizationMode } = useEventModelPresentation();\n if (visualizationMode === 'fillLines') return null;\n const style: React.CSSProperties | undefined = columnPosition ? { left: columnLeft(columnPosition) } : undefined;\n return <div className='event-modeling-grid-flow-triangle event-modeling-grid-flow-triangle--up' style={style} aria-hidden='true' />;\n};\n\nexport const PassthroughConnector: React.FC<ConnectorProps> = ({ columnPosition }) => {\n const { visualizationMode } = useEventModelPresentation();\n if (visualizationMode === 'fillLines') return null;\n const style: React.CSSProperties | undefined = columnPosition ? { left: columnLeft(columnPosition) } : undefined;\n return <div className='event-modeling-grid-flow-triangle event-modeling-grid-flow-triangle--down' style={style} aria-hidden='true' />;\n};\n\nexport const ConnectorOutgoingBottom: React.FC<ConnectorProps> = () => null;\n\nexport const ConnectorIncomingBottom: React.FC<ConnectorProps> = () => null;\n\nexport interface CellConnectors {\n bottomOutgoing?: boolean; // source side: line card→bottom (downward flow)\n topIncoming?: boolean; // dest side: line top→card+arrowhead (downward flow)\n topOutgoing?: boolean; // source side: line card→top (upward flow)\n bottomIncoming?: boolean; // dest side: line bottom→card+arrowhead (upward flow)\n\n passthrough?: boolean;\n}\n\nexport function cellConnectors(rowType: RowType, sliceType: SliceType, contentRows: RowType[] = []): CellConnectors {\n const hasSystemRow = contentRows.includes(RowType.System);\n\n switch (sliceType) {\n case SliceType.stateChange:\n if (rowType === RowType.UI) return { bottomOutgoing: true };\n if (rowType === RowType.Chat) return { bottomOutgoing: true };\n if (rowType === RowType.System) return hasSystemRow ? { passthrough: true } : {};\n if (rowType === RowType.Interaction) return { topIncoming: true, bottomOutgoing: true };\n if (rowType === RowType.Events) return { topIncoming: true };\n break;\n case SliceType.stateView:\n if (rowType === RowType.UI) return { bottomOutgoing: true };\n if (rowType === RowType.Chat) return { bottomOutgoing: true };\n if (rowType === RowType.System) return hasSystemRow ? { passthrough: true } : {};\n if (rowType === RowType.Interaction) return { topIncoming: true, bottomIncoming: true };\n if (rowType === RowType.Events) return { topOutgoing: true };\n break;\n case SliceType.automation:\n // Interaction row: ReadModel flows upward and Command receives downward flow.\n if (rowType === RowType.Interaction) return { topOutgoing: true, topIncoming: true };\n if (rowType === RowType.System) return { bottomIncoming: true, bottomOutgoing: true };\n if (rowType === RowType.Events) return { topIncoming: true };\n break;\n case SliceType.translator:\n if (rowType === RowType.System) return { bottomOutgoing: true };\n if (rowType === RowType.Interaction) return { topIncoming: true, bottomOutgoing: true };\n if (rowType === RowType.Events) return { topIncoming: true };\n break;\n }\n return {};\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Identifies the role a card plays in a slice's flow, used to anchor the curved\n * connection lines drawn in the \"lines\" visualization mode. The string values\n * are emitted as the `data-flow-node` attribute on the corresponding card element.\n */\nexport enum FlowNodeActor {\n ui = 'ui',\n command = 'command',\n readModel = 'readModel',\n cogwheel = 'cogwheel',\n event = 'event',\n externalEvent = 'externalEvent',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The minimal shape of an event needed to compute slice connections.\n// An event with an empty ConnectionEvent.sourceEventId is an origin (produced) event;\n// an event carrying a non-empty one is a reference that consumes the origin it points at.\nexport interface ConnectionEvent {\n // The identifier of this event item within its slice.\n id: string;\n\n // The display name of the event.\n name: string;\n\n // The id of the origin event this one references, or empty/undefined when this is a produced event.\n sourceEventId?: string;\n}\n\n// The minimal shape of a slice needed to compute connections.\nexport interface ConnectionSlice {\n // The slice identifier.\n id: string;\n\n // The display name of the slice.\n name: string;\n\n // The events owned or referenced by the slice.\n events: ConnectionEvent[];\n\n // The origin event id an automation slice is triggered by, when configured.\n automationTriggerEventId?: string;\n}\n\n// A single produced→consumed link between two slices via one event.\nexport interface SliceConnectionLink {\n // The id of the origin (produced) event that forms the link.\n eventId: string;\n\n // The display name of the event that forms the link.\n eventName: string;\n\n // The id of the slice on the other end of the link.\n sliceId: string;\n\n // The display name of the slice on the other end of the link.\n sliceName: string;\n}\n\n// The connection information for a single slice.\nexport interface SliceConnection {\n // The ids of every slice connected to this one, whether it produces for them or consumes from them.\n connectedSliceIds: ReadonlySet<string>;\n\n // The events this slice consumes, each pointing at the slice that produces it.\n consumed: SliceConnectionLink[];\n\n // The events this slice produces, each pointing at a slice that consumes it.\n produced: SliceConnectionLink[];\n}\n\ninterface MutableSliceConnection {\n connectedSliceIds: Set<string>;\n consumed: SliceConnectionLink[];\n produced: SliceConnectionLink[];\n}\n\ninterface EventOrigin {\n sliceId: string;\n sliceName: string;\n eventName: string;\n}\n\n// Computes the produced→consumed connection graph across a flat list of slices.\n//\n// A slice produces an event (an event with no `sourceEventId`); another slice consumes it either by\n// referencing it (an event whose `sourceEventId` points at the origin) or, for an automation slice,\n// by being triggered by it (`automationTriggerEventId`). Each such link connects the two slices in\n// both directions.\n// slices: The slices to analyze, typically every slice in a module collection.\n// Returns A map from slice id to its SliceConnection.\nexport function computeSliceConnections(slices: readonly ConnectionSlice[]): Map<string, SliceConnection> {\n const connections = new Map<string, MutableSliceConnection>();\n const originByEventId = new Map<string, EventOrigin>();\n\n for (const slice of slices) {\n connections.set(slice.id, { connectedSliceIds: new Set(), consumed: [], produced: [] });\n for (const event of slice.events) {\n if (!event.sourceEventId) {\n originByEventId.set(event.id, { sliceId: slice.id, sliceName: slice.name, eventName: event.name });\n }\n }\n }\n\n const linkConsumerToOrigin = (consumer: ConnectionSlice, originEventId: string) => {\n const origin = originByEventId.get(originEventId);\n if (!origin || origin.sliceId === consumer.id) return;\n\n const consumerConnection = connections.get(consumer.id)!;\n const producerConnection = connections.get(origin.sliceId)!;\n\n consumerConnection.connectedSliceIds.add(origin.sliceId);\n producerConnection.connectedSliceIds.add(consumer.id);\n\n if (!consumerConnection.consumed.some(link => link.eventId === originEventId && link.sliceId === origin.sliceId)) {\n consumerConnection.consumed.push({ eventId: originEventId, eventName: origin.eventName, sliceId: origin.sliceId, sliceName: origin.sliceName });\n }\n if (!producerConnection.produced.some(link => link.eventId === originEventId && link.sliceId === consumer.id)) {\n producerConnection.produced.push({ eventId: originEventId, eventName: origin.eventName, sliceId: consumer.id, sliceName: consumer.name });\n }\n };\n\n for (const slice of slices) {\n for (const event of slice.events) {\n if (event.sourceEventId) {\n linkConsumerToOrigin(slice, event.sourceEventId);\n }\n }\n if (slice.automationTriggerEventId) {\n linkConsumerToOrigin(slice, slice.automationTriggerEventId);\n }\n }\n\n return connections;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\nimport { FlowNodeActor } from './FlowNodeActor';\n\n// The ordered sequence of flow-node roles for a slice type. Connection lines are\n// drawn between consecutive roles that are actually present, following the natural\n// direction of the slice:\n//\n// - State Change: UI → Command → Event(s)\n// - State View: Event(s) → Read Model → UI\n// - Automation: Read Model → Automation (cogwheel) → Command → Event(s)\n// - Translation: External Event → Command → Event(s)\n//\n// Actors that have no card on the canvas (e.g. an undefined UI or read model) are\n// skipped, so the line simply connects the nearest present neighbors.\n// sliceType: The slice type to get the flow order for.\n// Returns The ordered roles for the slice type.\nexport function flowNodeOrder(sliceType: SliceType): FlowNodeActor[] {\n switch (sliceType) {\n case SliceType.stateChange:\n return [FlowNodeActor.ui, FlowNodeActor.command, FlowNodeActor.event];\n case SliceType.stateView:\n return [FlowNodeActor.event, FlowNodeActor.readModel, FlowNodeActor.ui];\n case SliceType.automation:\n return [FlowNodeActor.readModel, FlowNodeActor.cogwheel, FlowNodeActor.command, FlowNodeActor.event];\n case SliceType.translator:\n return [FlowNodeActor.externalEvent, FlowNodeActor.command, FlowNodeActor.event];\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceConnections.css';\nimport React, { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';\nimport { canvasGesture } from '@cratis/components/Canvas';\nimport type { SliceType } from '../Model';\nimport { CurveAxis, smoothCurvePath } from '../Geometry';\nimport { flowNodeOrder } from './flowNodeOrder';\n\nexport interface SliceConnectionsProps {\n\n // The type of slice, which determines the order the flow nodes are connected in.\n sliceType: SliceType;\n\n // A value that changes whenever the slice content that affects layout changes\n // (events, interactions, detail visibility, row heights). Used to trigger a\n // re-measure of the card positions.\n recomputeKey: string;\n}\n\n// A measured card position, in the overlay's local (layout) coordinate space.\ninterface NodeRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n// Builds a smooth cubic-bezier path between two cards with vertical tangents at both ends.\nfunction buildPath(source: NodeRect, target: NodeRect): string {\n const sourceX = source.x + source.width / 2;\n const targetX = target.x + target.width / 2;\n const sourceCenterY = source.y + source.height / 2;\n const targetCenterY = target.y + target.height / 2;\n\n const goingDown = targetCenterY >= sourceCenterY;\n const startY = goingDown ? source.y + source.height : source.y;\n const endY = goingDown ? target.y : target.y + target.height;\n\n return smoothCurvePath({ x: sourceX, y: startY }, { x: targetX, y: endY }, CurveAxis.Vertical);\n}\n\n// Draws the curved connection lines between the cards of a single slice when the\n// editor is in the \"lines\" visualization mode. Instead of straight per-row fill\n// lines and triangles, this renders one smooth curve per connection with an\n// arrowhead at the destination, following the slice type's flow.\nexport const SliceConnections: React.FC<SliceConnectionsProps> = ({ sliceType, recomputeKey }) => {\n const hostRef = useRef<HTMLDivElement>(null);\n const [paths, setPaths] = useState<string[]>([]);\n const markerId = `flow-arrow-${useId().replace(/:/g, '')}`;\n\n const measure = useCallback(() => {\n const host = hostRef.current;\n const column = host?.parentElement;\n if (!host || !column) return;\n\n const hostRect = host.getBoundingClientRect();\n const layoutWidth = host.clientWidth || hostRect.width;\n const scale = layoutWidth ? hostRect.width / layoutWidth : 1;\n\n const toLocal = (element: Element): NodeRect => {\n const rect = element.getBoundingClientRect();\n return {\n x: (rect.left - hostRect.left) / scale,\n y: (rect.top - hostRect.top) / scale,\n width: rect.width / scale,\n height: rect.height / scale,\n };\n };\n\n const order = flowNodeOrder(sliceType);\n const groups = order\n .map(role => Array.from(column.querySelectorAll<HTMLElement>(`[data-flow-node=\"${role}\"]`)).map(toLocal))\n .filter(nodes => nodes.length > 0);\n\n const nextPaths: string[] = [];\n for (let index = 0; index < groups.length - 1; index++) {\n for (const source of groups[index]) {\n for (const target of groups[index + 1]) {\n nextPaths.push(buildPath(source, target));\n }\n }\n }\n\n setPaths(previous =>\n previous.length === nextPaths.length && previous.every((value, i) => value === nextPaths[i])\n ? previous\n : nextPaths);\n }, [sliceType]);\n\n // Observer-driven re-measures coalesce onto one animation frame (a settle re-apply resizes every\n // observed card at once — one measure covers the whole burst), and hold still while a pan/zoom\n // gesture is in motion: measuring forces a layout, and the geometry it would read is mid-gesture\n // anyway. The deferred measure runs when the gesture settles.\n const measureFrameRef = useRef(0);\n const measurePendingGestureRef = useRef(false);\n const scheduleMeasure = useCallback(() => {\n if (canvasGesture.isActive) {\n measurePendingGestureRef.current = true;\n return;\n }\n if (measureFrameRef.current) return;\n measureFrameRef.current = requestAnimationFrame(() => {\n measureFrameRef.current = 0;\n measure();\n });\n }, [measure]);\n\n useEffect(() => () => cancelAnimationFrame(measureFrameRef.current), []);\n\n useEffect(() => canvasGesture.subscribe(active => {\n if (active || !measurePendingGestureRef.current) return;\n measurePendingGestureRef.current = false;\n scheduleMeasure();\n }), [scheduleMeasure]);\n\n useLayoutEffect(() => {\n measure();\n }, [measure, recomputeKey]);\n\n useEffect(() => {\n const host = hostRef.current;\n const column = host?.parentElement;\n if (!host || !column) return;\n\n // Observe the column and each connectable card so the curves re-measure\n // when a card resizes after mount — e.g. a UI prototype thumbnail that\n // renders its preview asynchronously, which the column's fixed height\n // would otherwise hide from the observer.\n const resizeObserver = new ResizeObserver(() => scheduleMeasure());\n const observeCards = () => {\n resizeObserver.disconnect();\n resizeObserver.observe(column);\n column.querySelectorAll('[data-flow-node]').forEach(node => resizeObserver.observe(node));\n };\n observeCards();\n\n // A card can also appear or disappear without changing the column's size —\n // most notably a UI prototype added optimistically, which mounts a new\n // flow node but leaves the slice props (and the row height) unchanged.\n // Watch the column subtree so the curves re-measure when that happens.\n // Mutations inside the overlay itself (the drawn <path> elements) are\n // ignored to avoid a re-measure loop.\n const mutationObserver = new MutationObserver(records => {\n if (records.every(record => host.contains(record.target))) return;\n observeCards();\n scheduleMeasure();\n });\n mutationObserver.observe(column, { childList: true, subtree: true });\n\n window.addEventListener('resize', scheduleMeasure);\n return () => {\n resizeObserver.disconnect();\n mutationObserver.disconnect();\n window.removeEventListener('resize', scheduleMeasure);\n };\n }, [measure, scheduleMeasure, recomputeKey]);\n\n return (\n <div ref={hostRef} className='event-modeling-grid-connections' aria-hidden='true'>\n <svg className='event-modeling-grid-connections__svg' width='100%' height='100%'>\n <defs>\n <marker\n id={markerId}\n markerWidth='9'\n markerHeight='9'\n refX='6'\n refY='4.5'\n orient='auto'\n markerUnits='userSpaceOnUse'\n >\n <path d='M 0 0 L 8 4.5 L 0 9 z' className='event-modeling-grid-connections__arrow' />\n </marker>\n </defs>\n {paths.map((path, index) => (\n <path\n key={index}\n d={path}\n className='event-modeling-grid-connections__line'\n markerEnd={`url(#${markerId})`}\n />\n ))}\n </svg>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { createContext, useContext, useMemo } from 'react';\nimport type { SliceConnection } from './computeSliceConnections';\n\n// Access to the produced→consumed connection graph for the slices in a module collection.\nexport interface SliceConnectionsContextValue {\n // Returns the connection info for a slice, or when the slice has no computed connections.\n getConnection: (sliceId: string) => SliceConnection | undefined;\n}\n\nconst SliceConnectionsContext = createContext<SliceConnectionsContextValue | null>(null);\n\nexport interface SliceConnectionsProviderProps {\n // The connection graph keyed by slice id, typically computed once per module collection.\n connections: Map<string, SliceConnection>;\n children: React.ReactNode;\n}\n\n// Provides the slice connection graph to every slice rendered within a module collection.\nexport const SliceConnectionsProvider = ({ connections, children }: SliceConnectionsProviderProps) => {\n const value = useMemo<SliceConnectionsContextValue>(\n () => ({ getConnection: (sliceId: string) => connections.get(sliceId) }),\n [connections],\n );\n return <SliceConnectionsContext.Provider value={value}>{children}</SliceConnectionsContext.Provider>;\n};\n\n// Returns the connection info for the given slice, or when there is no provider\n// (e.g. Storybook) or the slice is not part of the graph.\nexport const useSliceConnection = (sliceId: string): SliceConnection | undefined => {\n const context = useContext(SliceConnectionsContext);\n return context?.getConnection(sliceId);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ConnectionHighlight.css';\nimport React, { useCallback, useEffect, useRef } from 'react';\n\n// Selector for the board container that scopes the fade-on-hover effect.\nconst BOARD_SELECTOR = '[data-event-model-board]';\n// Class applied to the board while a slice is hovered to fade every non-connected slice column and specification.\nconst HIGHLIGHT_ACTIVE_CLASS = 'event-modeling-board--highlight-slices';\n// Class applied to the hovered slice column, its connected columns, and every specification belonging\n// to one of those slices so they all stay emphasized together.\nconst HIGHLIGHTED_COLUMN_CLASS = 'event-modeling-grid-slice-column--connection-highlighted';\n// Selector matching a slice's own column and every element carrying its specification cards for a\n// given `data-slice-id`. A specification renders as a sibling below its slice column rather than\n// inside it (see SpecificationsContainer), so it needs its own attribute to be found by id.\nconst sliceElementsSelector = (sliceId: string) =>\n `[data-slice-col=\"true\"][data-slice-id=\"${sliceId}\"], [data-slice-spec-col=\"true\"][data-slice-id=\"${sliceId}\"]`;\n\n// Handlers and ref returned to wire a slice column into the connection highlight.\nexport interface ConnectionHighlight {\n // Attach to the slice column element that carries `data-slice-id`.\n ref: React.RefObject<HTMLDivElement | null>;\n // Begin emphasizing this slice and its connections while fading the rest.\n onMouseEnter: () => void;\n // Clear the emphasis.\n onMouseLeave: () => void;\n}\n\ninterface ActiveHighlight {\n board: HTMLElement;\n columns: HTMLElement[];\n}\n\n// Emphasizes a slice column — and its specifications — together with the columns and specifications of\n// the slices it connects to, while a pointer hovers it, fading everything else on the board. Purely\n// presentational: it toggles CSS classes on the board and the matched elements instead of triggering\n// React re-renders, mirroring the per-event dim in EventReference. Own and connected elements\n// are resolved from the DOM by their shared `data-slice-id`, so a slice's specification cards (rendered\n// as siblings below its column, not inside it) light up and dim in lockstep with the column itself.\n// connectedSliceIds: The ids of the slices connected to the hovered slice.\n// Returns The ref and hover handlers to spread onto the slice column.\nexport function useConnectionHighlight(connectedSliceIds: ReadonlySet<string> | undefined): ConnectionHighlight {\n const ref = useRef<HTMLDivElement | null>(null);\n const activeRef = useRef<ActiveHighlight | null>(null);\n\n const clear = useCallback(() => {\n const active = activeRef.current;\n if (!active) return;\n active.board.classList.remove(HIGHLIGHT_ACTIVE_CLASS);\n active.columns.forEach(column => column.classList.remove(HIGHLIGHTED_COLUMN_CLASS));\n activeRef.current = null;\n }, []);\n\n const onMouseEnter = useCallback(() => {\n const element = ref.current;\n if (!element) return;\n const board = element.closest<HTMLElement>(BOARD_SELECTOR);\n if (!board) return;\n\n clear();\n\n const columns: HTMLElement[] = [element];\n element.classList.add(HIGHLIGHTED_COLUMN_CLASS);\n\n // The hovered slice's own specifications are included alongside every connected slice's column\n // and specifications, so all of them are found and emphasized through the same DOM lookup.\n const sliceIds = new Set<string>(connectedSliceIds ?? []);\n const ownSliceId = element.dataset.sliceId;\n if (ownSliceId) sliceIds.add(ownSliceId);\n\n for (const sliceId of sliceIds) {\n board\n .querySelectorAll<HTMLElement>(sliceElementsSelector(sliceId))\n .forEach(matched => {\n if (matched === element) return;\n matched.classList.add(HIGHLIGHTED_COLUMN_CLASS);\n columns.push(matched);\n });\n }\n\n board.classList.add(HIGHLIGHT_ACTIVE_CLASS);\n activeRef.current = { board, columns };\n }, [clear, connectedSliceIds]);\n\n // Clean up if the column unmounts while still hovered.\n useEffect(() => clear, [clear]);\n\n return { ref, onMouseEnter, onMouseLeave: clear };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface FeatureColumnFrameProps {\n featureId: Guid;\n moduleId: Guid;\n // A disabled feature is drawn faded.\n enabled: boolean;\n // The feature is the one being dragged.\n dragging?: boolean;\n children?: ReactNode;\n}\n\n// The column a feature's header row and slices sit in. It carries the attributes a feature drag reads\n// the columns of a module by.\nexport const FeatureColumnFrame = ({ featureId, moduleId, enabled, dragging = false, children }: FeatureColumnFrameProps) => (\n <div\n data-feature-col='true'\n data-feature-id={featureId.toString()}\n data-feature-module-id={moduleId.toString()}\n style={{\n display: 'grid',\n gridRow: '1 / 3',\n gridTemplateRows: 'subgrid',\n minWidth: 0,\n opacity: dragging ? 0.35 : enabled ? 1 : 0.5,\n transition: 'opacity 0.15s',\n }}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './FeatureGridSurface.css';\nimport type { ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { boardMetrics } from '../Layout';\nimport { FeatureColumnFrame } from './FeatureColumnFrame';\n\nexport interface FeatureGridSurfaceProps {\n featureId: Guid;\n moduleId: Guid;\n enabled: boolean;\n collapsed: boolean;\n rowCollapsed: boolean;\n width: number;\n headerVisibility: 'visible' | 'hidden' | 'none';\n header: ReactNode;\n screenTemplate?: ReactNode;\n slices: ReactNode;\n}\n\nexport const FeatureGridSurface = ({ featureId, moduleId, enabled, collapsed, rowCollapsed, width,\n headerVisibility, header, screenTemplate, slices }: FeatureGridSurfaceProps) => (\n <FeatureColumnFrame featureId={featureId} moduleId={moduleId} enabled={enabled}>\n <div className={`event-modeling-grid-header-cell-wrapper${collapsed ? ' event-modeling-grid-header-cell-wrapper--feature-collapsed' : ''}`}\n style={{ width: headerVisibility === 'hidden' ? 0 : width,\n visibility: headerVisibility === 'hidden' ? 'hidden' : 'visible',\n overflow: headerVisibility === 'visible' && !collapsed ? 'visible' : 'hidden' }}>\n {headerVisibility === 'visible' ? header : headerVisibility === 'hidden' ? <div style={{ height: boardMetrics.headerHeight }} /> : null}\n {!collapsed && screenTemplate}\n </div>\n <div className={rowCollapsed ? 'event-modeling-feature-grid-slices--row-collapsed'\n : headerVisibility === 'visible' ? 'event-modeling-feature-grid-slices--header-visible' : undefined}>\n {slices}\n </div>\n </FeatureColumnFrame>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Headers/HeaderCell.css';\nimport type { ReactNode, Ref } from 'react';\nimport type { FeatureDropEdge } from './featureDropEdge';\n\nexport interface FeatureHeaderCellProps {\n width: number;\n collapsed: boolean;\n // The edge that shows a dragged feature would land here.\n dropEdge?: FeatureDropEdge;\n children?: ReactNode;\n ref?: Ref<HTMLDivElement>;\n}\n\n// A thicker, glowing edge than a plain inset line — the same visual weight as the slice drop indicator,\n// so every level of the board shows where a drop would land the same way.\nconst dropEdgeShadow: Record<FeatureDropEdge, string> = {\n before: 'inset 6px 0 0 rgba(180,165,255,0.95), inset 0 0 14px 0 rgba(150,130,255,0.5)',\n after: 'inset -6px 0 0 rgba(180,165,255,0.95), inset 0 0 14px 0 rgba(150,130,255,0.5)',\n};\n\n// The cell a feature's header sits in, spanning the feature and its sub-features.\nexport const FeatureHeaderCell = ({ width, collapsed, dropEdge, children, ref }: FeatureHeaderCellProps) => (\n <div ref={ref}\n className={`event-modeling-grid-header-cell-wrapper${collapsed ? ' event-modeling-grid-header-cell-wrapper--feature-collapsed' : ''}`}\n style={{ width, boxShadow: dropEdge && dropEdgeShadow[dropEdge] }}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport type FeatureDropEdge = 'before' | 'after';\n\n// Which edge of the feature at index shows where a dragged feature would land, if either. Gap n is\n// drawn on the leading edge of feature n; the gap after the last feature on that feature's trailing edge.\nexport function featureDropEdge(dropIndex: number | undefined, index: number, count: number): FeatureDropEdge | undefined {\n if (dropIndex === undefined) return undefined;\n if (dropIndex === index) return 'before';\n if (index === count - 1 && dropIndex === count) return 'after';\n return undefined;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { headerDropIndex, reorderedIds, type HeaderDragStart, type HeaderDragState } from '../HeaderDragging';\nimport type { FeaturesReordered } from './FeaturesReordered';\n\nexport interface FeatureDragState extends HeaderDragState {\n featureId: Guid;\n moduleId: Guid;\n sourceIndex: number;\n currentY: number;\n // The gap the feature would land in right now: n is before the nth feature of the module.\n dropIndex: number;\n}\n\nexport type FeatureDragStart = (featureId: Guid, label: string, start: HeaderDragStart) => void;\n\nexport interface FeatureDrag {\n featureDrag?: FeatureDragState;\n // Undefined when nothing can be told about a move, so no feature header offers to be picked up.\n handleFeatureDragStart?: FeatureDragStart;\n}\n\n// The gap a pointer at clientX is over among the feature columns of one module.\nfunction dropIndexAt(moduleId: Guid, clientX: number): number {\n const columns = Array.from(\n document.querySelectorAll<HTMLElement>(`[data-feature-col=\"true\"][data-feature-module-id=\"${moduleId.toString()}\"]`));\n return headerDropIndex(columns.map(column => column.getBoundingClientRect()), clientX);\n}\n\n// Dragging a feature to another place among the features of its module.\n// featureIds: the module's top-level features in their current order.\nexport function useFeatureDrag(moduleId: Guid, featureIds: readonly Guid[], onFeaturesReordered?: FeaturesReordered): FeatureDrag {\n const board = useBoard();\n const [featureDrag, setFeatureDrag] = useState<FeatureDragState | undefined>(undefined);\n const featureDragRef = useRef(featureDrag);\n featureDragRef.current = featureDrag;\n const featureIdsRef = useRef(featureIds);\n featureIdsRef.current = featureIds;\n const onFeaturesReorderedRef = useRef(onFeaturesReordered);\n onFeaturesReorderedRef.current = onFeaturesReordered;\n\n const handleFeatureDragStart = useCallback<FeatureDragStart>((featureId, label, start) => {\n const sourceIndex = featureIdsRef.current.findIndex(id => id.equals(featureId));\n if (sourceIndex === -1) return;\n setFeatureDrag({\n featureId,\n moduleId,\n sourceIndex,\n ghostLabel: label,\n ghostWidth: start.width,\n ghost: start.ghost,\n currentX: start.clientX,\n currentY: start.clientY,\n dropIndex: sourceIndex,\n headerY: start.headerY,\n zoom: start.zoom,\n });\n }, [moduleId]);\n\n const dragging = featureDrag !== undefined;\n useEffect(() => {\n if (!dragging) return;\n\n const handlePointerMove = (event: PointerEvent) => {\n setFeatureDrag(previous => previous && {\n ...previous,\n currentX: event.clientX,\n currentY: event.clientY,\n dropIndex: dropIndexAt(previous.moduleId, event.clientX),\n });\n };\n\n const handlePointerUp = () => {\n const drag = featureDragRef.current;\n setFeatureDrag(undefined);\n if (!drag) return;\n const ordered = reorderedIds(featureIdsRef.current, drag.sourceIndex, drag.dropIndex);\n if (ordered) onFeaturesReorderedRef.current?.(drag.moduleId, ordered);\n };\n\n window.addEventListener('pointermove', handlePointerMove);\n window.addEventListener('pointerup', handlePointerUp);\n return () => {\n window.removeEventListener('pointermove', handlePointerMove);\n window.removeEventListener('pointerup', handlePointerUp);\n };\n }, [dragging]);\n\n const canDrag = !board.readOnly && onFeaturesReordered !== undefined;\n return { featureDrag, handleFeatureDragStart: canDrag ? handleFeatureDragStart : undefined };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useRef, useState, type RefCallback } from 'react';\n\ntype Slot = 'header' | 'column';\ntype Targets = { header?: HTMLDivElement; column?: HTMLDivElement };\n\nexport function useFeatureSlotTargets() {\n const [targets, setTargets] = useState<Map<string, Targets>>(new Map());\n const callbacks = useRef(new Map<string, RefCallback<HTMLDivElement>>());\n\n const register = useCallback((featureId: string, slot: Slot) => {\n const key = `${slot}:${featureId}`;\n const existing = callbacks.current.get(key);\n if (existing) return existing;\n const callback: RefCallback<HTMLDivElement> = node => {\n setTargets(previous => {\n const current = previous.get(featureId);\n if ((current?.[slot] ?? null) === node) return previous;\n const next = new Map(previous);\n const updated = { ...current, [slot]: node ?? undefined };\n if (!updated.header && !updated.column) next.delete(featureId);\n else next.set(featureId, updated);\n return next;\n });\n };\n callbacks.current.set(key, callback);\n return callback;\n }, []);\n\n return { targets, register };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface FeatureAreaItem<T> {\n id: Guid;\n subFeatures: T[];\n name: string;\n collapsed: boolean;\n}\n\nexport interface FeatureAreaState<T extends FeatureAreaItem<T>> {\n snapshot: T[];\n features: T[];\n pendingAdditions: { feature: T; parentId?: Guid }[];\n order?: Guid[];\n pendingRenames: ReadonlyMap<string, string>;\n pendingCollapses: ReadonlyMap<string, boolean>;\n}\n\nexport const createFeatureAreaState = <T extends FeatureAreaItem<T>>(features: T[]): FeatureAreaState<T> => ({\n snapshot: features, features, pendingAdditions: [], pendingRenames: new Map(), pendingCollapses: new Map(),\n});\n\nexport function updateFeature<T extends FeatureAreaItem<T>>(features: T[], id: Guid, update: (feature: T) => T): T[] {\n let changed = false;\n const result = features.map(feature => {\n if (feature.id.equals(id)) {\n changed = true;\n return update(feature);\n }\n const children = updateFeature(feature.subFeatures, id, update);\n if (children === feature.subFeatures) return feature;\n changed = true;\n return { ...feature, subFeatures: children };\n });\n return changed ? result : features;\n}\n\nexport function insertFeature<T extends FeatureAreaItem<T>>(features: T[], feature: T, parentId?: Guid): T[] {\n if (containsFeature(features, feature.id)) return features;\n if (!parentId) return [...features, feature];\n return updateFeature(features, parentId, parent => ({ ...parent, subFeatures: [...parent.subFeatures, feature] }));\n}\n\nexport function reconcileFeatures<T extends FeatureAreaItem<T>>(state: FeatureAreaState<T>, snapshot: T[]): FeatureAreaState<T> {\n const pendingAdditions = state.pendingAdditions.filter(({ feature }) => !containsFeature(snapshot, feature.id));\n const withAdditions = pendingAdditions.reduce((features, addition) => insertFeature(features, addition.feature, addition.parentId), snapshot);\n const pendingRenames = new Map([...state.pendingRenames].filter(([id, name]) => !hasName(snapshot, id, name)));\n const renamed = [...pendingRenames].reduce((features, [id, name]) => renameFeature(features, id, name), withAdditions);\n const pendingCollapses = new Map([...state.pendingCollapses].filter(([id, collapsed]) => !hasCollapsed(snapshot, id, collapsed)));\n const collapsed = [...pendingCollapses].reduce((features, [id, value]) => collapseFeature(features, id, value), renamed);\n const ordered = state.order ? orderFeatures(collapsed, state.order) : collapsed;\n return { snapshot, features: ordered, pendingAdditions, pendingRenames, pendingCollapses, order: state.order };\n}\n\nexport function revertFeatureRename<T extends FeatureAreaItem<T>>(state: FeatureAreaState<T>, id: Guid): FeatureAreaState<T> {\n const pendingRenames = new Map(state.pendingRenames);\n pendingRenames.delete(id.toString());\n return reconcileFeatures({ ...state, pendingRenames }, state.snapshot);\n}\n\nexport function containsFeature<T extends FeatureAreaItem<T>>(features: T[], id: Guid): boolean {\n return features.some(feature => feature.id.equals(id) || containsFeature(feature.subFeatures, id));\n}\n\nfunction hasName<T extends FeatureAreaItem<T>>(features: T[], id: string, name: string): boolean {\n return features.some(feature => (feature.id.toString() === id && feature.name === name) || hasName(feature.subFeatures, id, name));\n}\n\nfunction hasCollapsed<T extends FeatureAreaItem<T>>(features: T[], id: string, collapsed: boolean): boolean {\n return features.some(feature => (feature.id.toString() === id && feature.collapsed === collapsed) || hasCollapsed(feature.subFeatures, id, collapsed));\n}\n\nexport function collapseFeature<T extends FeatureAreaItem<T>>(features: T[], id: string, collapsed: boolean): T[] {\n let changed = false;\n const updated = features.map(feature => {\n if (feature.id.toString() === id) {\n if (feature.collapsed === collapsed) return feature;\n changed = true;\n return { ...feature, collapsed };\n }\n const children = collapseFeature(feature.subFeatures, id, collapsed);\n if (children === feature.subFeatures) return feature;\n changed = true;\n return { ...feature, subFeatures: children };\n });\n return changed ? updated : features;\n}\n\nexport function renameFeature<T extends FeatureAreaItem<T>>(features: T[], id: string, name: string): T[] {\n let changed = false;\n const renamed = features.map(feature => {\n if (feature.id.toString() === id) {\n if (feature.name === name) return feature;\n changed = true;\n return { ...feature, name };\n }\n const children = renameFeature(feature.subFeatures, id, name);\n if (children === feature.subFeatures) return feature;\n changed = true;\n return { ...feature, subFeatures: children };\n });\n return changed ? renamed : features;\n}\n\nexport function orderFeatures<T extends FeatureAreaItem<T>>(features: T[], ids: Guid[]): T[] {\n const ordered = ids.flatMap(id => features.filter(feature => feature.id.equals(id)));\n return [...ordered, ...features.filter(feature => !ids.some(id => id.equals(feature.id)))];\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './FeaturesArea.css';\nimport { Fragment, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, type ReactNode, type Ref } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { HeaderDragGhost } from '../HeaderDragging';\nimport { boardMetrics } from '../Layout';\nimport { FeatureHeaderCell } from './FeatureHeaderCell';\nimport { featureDropEdge } from './featureDropEdge';\nimport { useFeatureDrag } from './useFeatureDrag';\nimport { useFeatureSlotTargets } from './useFeatureSlotTargets';\nimport { collapseFeature, createFeatureAreaState, insertFeature, orderFeatures, reconcileFeatures, renameFeature, revertFeatureRename, updateFeature, type FeatureAreaItem, type FeatureAreaState } from './featureAreaState';\n\nexport interface FeaturesAreaHandle<T> {\n addFeature: (name?: string) => Promise<void>;\n addSubFeature: (parentId: Guid, name?: string) => Promise<void>;\n updateFeature: (id: Guid, update: (feature: T) => T) => void;\n}\n\nexport interface FeaturesAreaProps<T extends FeatureAreaItem<T>> {\n ref?: Ref<FeaturesAreaHandle<T>>;\n initialFeatures: T[];\n moduleId: Guid;\n widthOf: (feature: T) => number;\n isCollapsed: (feature: T) => boolean;\n forceCollapsed?: boolean;\n onCollapseChanged?: (featureId: Guid, collapsed: boolean) => void;\n occupiesColumn: (feature: T) => boolean;\n renderHeader: (feature: T, options: {\n collapsed: boolean;\n dragging: boolean;\n onDragStart?: NonNullable<ReturnType<typeof useFeatureDrag>['handleFeatureDragStart']>;\n addSubFeature?: (name?: string) => void;\n onRenamed?: (name: string) => void;\n onToggleCollapse?: () => void;\n onCollapseFailed?: () => void;\n }) => ReactNode;\n renderColumn: (feature: T, options: {\n headerVisibility: 'visible' | 'hidden' | 'none';\n addSubFeature?: (name?: string) => void;\n onRenamed?: (name: string) => void;\n onToggleCollapse?: () => void;\n onCollapseFailed?: () => void;\n collapsed: boolean;\n }) => ReactNode;\n renderFeatureBoundary?: (feature: T, content: ReactNode) => ReactNode;\n onAddFeature?: (name?: string, parentId?: Guid) => Promise<T | undefined>;\n onRenameFeature?: (featureId: Guid, name: string) => Promise<void>;\n onFeaturesReordered?: (features: T[]) => void;\n onFeaturesChanged?: (features: T[]) => void;\n}\n\nfunction descendants<T extends FeatureAreaItem<T>>(feature: T, visited: Set<string>): T[] {\n visited.add(feature.id.toString());\n return feature.subFeatures.flatMap(child => {\n if (visited.has(child.id.toString())) return [];\n return [child, ...descendants(child, visited)];\n });\n}\n\nexport function FeaturesArea<T extends FeatureAreaItem<T>>({\n ref, initialFeatures, moduleId, widthOf, isCollapsed, forceCollapsed = false, onCollapseChanged,\n occupiesColumn, renderHeader, renderColumn, renderFeatureBoundary, onAddFeature, onRenameFeature, onFeaturesReordered, onFeaturesChanged,\n}: FeaturesAreaProps<T>) {\n const { readOnly, messages } = useBoard();\n const { targets, register } = useFeatureSlotTargets();\n const stateRef = useRef<FeatureAreaState<T>>(createFeatureAreaState(initialFeatures));\n const [state, setState] = useState(stateRef.current);\n const addingRef = useRef(false);\n const renamingIds = useRef(new Set<string>());\n const apply = useCallback((transition: (previous: FeatureAreaState<T>) => FeatureAreaState<T>) => {\n const next = transition(stateRef.current);\n if (next === stateRef.current) return;\n stateRef.current = next;\n setState(next);\n onFeaturesChanged?.(next.features);\n }, [onFeaturesChanged]);\n useEffect(() => {\n if (initialFeatures !== stateRef.current.snapshot) apply(previous => reconcileFeatures(previous, initialFeatures));\n }, [initialFeatures, apply]);\n\n const addFeature = useCallback(async (name?: string, parentId?: Guid) => {\n if (readOnly || !onAddFeature || addingRef.current) return;\n addingRef.current = true;\n try {\n const added = await onAddFeature(name, parentId);\n if (added) apply(previous => ({ ...previous,\n features: insertFeature(previous.features, added, parentId),\n pendingAdditions: [...previous.pendingAdditions, { feature: added, parentId }],\n }));\n } finally {\n addingRef.current = false;\n }\n }, [readOnly, onAddFeature, apply]);\n useImperativeHandle(ref, () => ({\n addFeature: name => addFeature(name),\n addSubFeature: (parentId, name) => addFeature(name, parentId),\n updateFeature: (id, update) => apply(previous => ({ ...previous, features: updateFeature(previous.features, id, update) })),\n }), [addFeature, apply]);\n\n const revertRename = useCallback((id: Guid) => apply(previous => revertFeatureRename(previous, id)), [apply]);\n const rename = useCallback((id: Guid, name: string) => {\n const key = id.toString();\n if (!onRenameFeature || readOnly || renamingIds.current.has(key)) return;\n renamingIds.current.add(key);\n apply(previous => ({ ...previous,\n features: renameFeature(previous.features, key, name),\n pendingRenames: new Map(previous.pendingRenames).set(key, name),\n }));\n void onRenameFeature(id, name).catch(() => revertRename(id)).finally(() => renamingIds.current.delete(key));\n }, [apply, onRenameFeature, readOnly, revertRename]);\n\n const resolveCollapsed = useCallback((feature: T) => forceCollapsed ||\n (state.pendingCollapses.get(feature.id.toString()) ?? isCollapsed(feature)),\n [forceCollapsed, isCollapsed, state.pendingCollapses]);\n const toggleCollapse = useCallback((feature: T) => {\n const next = !resolveCollapsed(feature);\n apply(previous => ({ ...previous, features: collapseFeature(previous.features, feature.id.toString(), next),\n pendingCollapses: new Map(previous.pendingCollapses).set(feature.id.toString(), next) }));\n onCollapseChanged?.(feature.id, next);\n }, [apply, resolveCollapsed, onCollapseChanged]);\n const revertCollapse = useCallback((feature: T) => {\n apply(previous => {\n const pendingCollapses = new Map(previous.pendingCollapses);\n pendingCollapses.delete(feature.id.toString());\n return reconcileFeatures({ ...previous, pendingCollapses }, previous.snapshot);\n });\n onCollapseChanged?.(feature.id, feature.collapsed);\n }, [apply, onCollapseChanged]);\n\n const features = state.features;\n const groups = useMemo(() => features.map(feature => {\n const children = descendants(feature, new Set());\n const columns = [feature, ...children];\n const visible = columns.filter(occupiesColumn);\n const width = visible.reduce((total, column, index) => total + (index ? boardMetrics.sliceGap : 0) + widthOf(column), 0);\n return { feature, children, width };\n }), [features, occupiesColumn, widthOf]);\n const columns = groups.flatMap(group => [group.feature, ...group.children]).filter(occupiesColumn);\n const parentIds = new Set(groups.filter(group => group.children.length).map(group => group.feature.id.toString()));\n const childIds = new Set(groups.flatMap(group => group.children.map(child => child.id.toString())));\n const featureIds = features.map(feature => feature.id);\n const handleReorder = useCallback((_moduleId: Guid, orderedIds: Guid[]) => {\n apply(previous => ({ ...previous, features: orderFeatures(previous.features, orderedIds), order: orderedIds }));\n onFeaturesReordered?.(orderFeatures(stateRef.current.features, orderedIds));\n }, [apply, onFeaturesReordered]);\n const { featureDrag, handleFeatureDragStart } = useFeatureDrag(moduleId, featureIds, onFeaturesReordered ? handleReorder : undefined);\n\n const headerOptions = (feature: T) => ({\n collapsed: resolveCollapsed(feature),\n dragging: featureDrag?.featureId.equals(feature.id) ?? false,\n onDragStart: handleFeatureDragStart,\n addSubFeature: !readOnly && onAddFeature ? (name?: string) => { void addFeature(name, feature.id); } : undefined,\n onRenamed: !readOnly && onRenameFeature ? (name: string) => rename(feature.id, name) : undefined,\n onToggleCollapse: onCollapseChanged ? () => toggleCollapse(feature) : undefined,\n onCollapseFailed: onCollapseChanged ? () => revertCollapse(feature) : undefined,\n });\n const columnOptions = (feature: T) => {\n const headerVisibility: 'hidden' | 'visible' | 'none' = parentIds.has(feature.id.toString()) ? 'hidden'\n : childIds.has(feature.id.toString()) ? 'visible' : 'none';\n return { ...headerOptions(feature), headerVisibility };\n };\n\n if (!features.length) return <div className='event-modeling-module-empty-placeholder' style={{ marginTop: 4 }}>{messages.features.empty}</div>;\n return <>\n <HeaderDragGhost drag={featureDrag} headerHeight={boardMetrics.headerHeight} />\n <div className='event-modeling-features-area'>\n <div className='event-modeling-features-area__headers' style={{ columnGap: boardMetrics.sliceGap }}>\n {groups.map((group, index) => <FeatureHeaderCell key={group.feature.id.toString()}\n ref={renderFeatureBoundary ? register(group.feature.id.toString(), 'header') : undefined}\n width={group.width} collapsed={resolveCollapsed(group.feature)}\n dropEdge={featureDropEdge(featureDrag?.dropIndex, index, groups.length)}>\n {!renderFeatureBoundary && renderHeader(group.feature, headerOptions(group.feature))}\n </FeatureHeaderCell>)}\n </div>\n <div className='event-modeling-features-area__columns' style={{ columnGap: boardMetrics.sliceGap }}>\n {columns.map(feature => <div key={feature.id.toString()} className='event-modeling-features-area__column'\n ref={renderFeatureBoundary ? register(feature.id.toString(), 'column') : undefined}>\n {!renderFeatureBoundary && renderColumn(feature, columnOptions(feature))}\n </div>)}\n </div>\n </div>\n {renderFeatureBoundary && groups.flatMap(group => [group.feature, ...group.children]).map(feature => {\n const featureTargets = targets.get(feature.id.toString());\n if (!featureTargets || (!childIds.has(feature.id.toString()) && !featureTargets.header) ||\n (occupiesColumn(feature) && !featureTargets.column)) return null;\n return <Fragment key={feature.id.toString()}>{renderFeatureBoundary(feature, <>\n {!childIds.has(feature.id.toString()) && featureTargets.header && createPortal(\n renderHeader(feature, headerOptions(feature)), featureTargets.header)}\n {featureTargets.column && createPortal(renderColumn(feature, columnOptions(feature)), featureTargets.column)}\n </>)}</Fragment>;\n })}\n </>;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\n\nexport interface SliceTypeIconProps {\n type: SliceType;\n}\n\nexport const SliceTypeIcon = ({ type }: SliceTypeIconProps) => (\n <svg viewBox='0 0 24 24' width='18' height='18' fill='none' stroke='currentColor' strokeWidth='2'>\n <SliceTypeGlyph type={type} />\n </svg>\n);\n\nconst SliceTypeGlyph = ({ type }: SliceTypeIconProps) => {\n switch (type) {\n case SliceType.stateChange:\n return (\n <>\n <rect x='3' y='3' width='18' height='5' rx='1' />\n <rect x='6' y='10' width='12' height='4' rx='1' fill='#3b82f6' stroke='#3b82f6' />\n <rect x='6' y='17' width='12' height='4' rx='1' fill='#f59e0b' stroke='#f59e0b' />\n <line x1='12' y1='8' x2='12' y2='10' />\n <line x1='12' y1='14' x2='12' y2='17' />\n <polyline points='10,16 12,17 14,16' />\n </>\n );\n case SliceType.stateView:\n return (\n <>\n <rect x='3' y='3' width='18' height='5' rx='1' />\n <rect x='6' y='10' width='12' height='4' rx='1' fill='#10b981' stroke='#10b981' />\n <rect x='3' y='17' width='8' height='4' rx='1' fill='#f59e0b' stroke='#f59e0b' />\n <rect x='13' y='17' width='8' height='4' rx='1' fill='#f59e0b' stroke='#f59e0b' />\n <line x1='7' y1='14' x2='7' y2='17' />\n <line x1='17' y1='14' x2='17' y2='17' />\n <polyline points='9,14 12,10 15,14' />\n </>\n );\n case SliceType.automation:\n return (\n <>\n <circle cx='12' cy='8' r='3' />\n <circle cx='12' cy='8' r='1.2' fill='currentColor' />\n <rect x='4' y='14' width='7' height='4' rx='1' fill='#10b981' stroke='#10b981' />\n <rect x='13' y='14' width='7' height='4' rx='1' fill='#3b82f6' stroke='#3b82f6' />\n <line x1='9' y1='11' x2='7.5' y2='14' />\n <line x1='15' y1='11' x2='16.5' y2='14' />\n </>\n );\n case SliceType.translator:\n return (\n <>\n <circle cx='12' cy='7' r='3' />\n <circle cx='12' cy='7' r='1.2' fill='currentColor' />\n <rect x='7' y='13' width='10' height='4' rx='1' fill='#3b82f6' stroke='#3b82f6' />\n <rect x='3' y='19' width='8' height='3' rx='1' fill='#eab308' stroke='#eab308' />\n <rect x='13' y='19' width='8' height='3' rx='1' fill='#f59e0b' stroke='#f59e0b' />\n <line x1='9' y1='17' x2='7' y2='19' />\n <line x1='15' y1='17' x2='17' y2='19' />\n </>\n );\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\nimport type { EventModelMessages } from '../Messages';\nimport type { MenuDropdownItem } from '../Menus';\nimport { SliceTypeIcon } from './SliceTypeIcon';\n\nexport const sliceTypes: readonly SliceType[] = [SliceType.stateChange, SliceType.stateView, SliceType.automation, SliceType.translator];\n\nexport const sliceTypeLabel = (type: SliceType, messages: EventModelMessages): string => {\n switch (type) {\n case SliceType.stateChange: return messages.sliceTypes.stateChange;\n case SliceType.stateView: return messages.sliceTypes.stateView;\n case SliceType.automation: return messages.sliceTypes.automation;\n case SliceType.translator: return messages.sliceTypes.translator;\n }\n};\n\nexport const sliceTypeDescription = (type: SliceType, messages: EventModelMessages): string => {\n switch (type) {\n case SliceType.stateChange: return messages.sliceTypes.stateChangeDescription;\n case SliceType.stateView: return messages.sliceTypes.stateViewDescription;\n case SliceType.automation: return messages.sliceTypes.automationDescription;\n case SliceType.translator: return messages.sliceTypes.translatorDescription;\n }\n};\n\n// One menu item per slice type, for any menu that adds a slice.\nexport const sliceTypeMenuItems = (messages: EventModelMessages, onSelect: (type: SliceType) => void): MenuDropdownItem[] =>\n sliceTypes.map(type => ({\n id: String(type),\n label: sliceTypeLabel(type, messages),\n description: sliceTypeDescription(type, messages),\n icon: <SliceTypeIcon type={type} />,\n onClick: () => onSelect(type),\n }));\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceTypeExplanation.css';\nimport type { SliceType } from '../Model';\nimport { useBoard } from '../Board';\nimport { sliceTypeDescription, sliceTypeLabel } from './sliceTypeMenuItems';\n\nexport interface SliceTypeExplanationProps {\n sliceType: SliceType;\n}\n\n// What kind of slice this is, said where its name is — the colors alone do not tell a newcomer.\nexport const SliceTypeExplanation = ({ sliceType }: SliceTypeExplanationProps) => {\n const { messages } = useBoard();\n return (\n <>\n <strong>{sliceTypeLabel(sliceType, messages)}</strong>\n <span className='event-modeling-grid-slice-type-explanation'>{sliceTypeDescription(sliceType, messages)}</span>\n </>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { SliceType } from '../Model';\nimport { useEventModelMessages } from '../Messages';\nimport { MenuDropdown } from '../Menus';\nimport { sliceTypeMenuItems } from './sliceTypeMenuItems';\n\nexport interface SliceTypeMenuProps {\n onSelect: (type: SliceType) => void;\n disabled?: boolean;\n}\n\nexport const SliceTypeMenu = ({ onSelect, disabled = false }: SliceTypeMenuProps) => {\n const messages = useEventModelMessages();\n return (\n <MenuDropdown\n trigger={\n <button className='event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle' title={messages.sliceTypes.add} disabled={disabled}>\n +\n </button>\n }\n items={sliceTypeMenuItems(messages, onSelect)}\n align='right'\n />\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceType } from '../Model';\nimport { MenuDropdown, type MenuDropdownItem } from '../Menus';\nimport { sliceTypeMenuItems } from '../SliceTypes';\nimport { useEventModelMessages } from '../Messages';\nimport type { FeatureHeaderMenuAction } from './FeatureHeaderMenuAction';\n\nexport interface FeatureAddMenuProps {\n featureId: Guid;\n onAddSubFeature?: () => void;\n onAddSlice?: (sliceType: SliceType) => void;\n actions?: readonly FeatureHeaderMenuAction[];\n}\n\nexport const FeatureAddMenu = ({ featureId, onAddSubFeature, onAddSlice, actions = [] }: FeatureAddMenuProps) => {\n const messages = useEventModelMessages();\n const triggerRef = useRef<HTMLButtonElement>(null);\n const [phase, setPhase] = useState<'main' | 'slice' | 'consumer'>('main');\n const [selectedConsumerActionId, setSelectedConsumerActionId] = useState<string>();\n const visibleActions = actions.filter(action => !action.when || action.when(featureId));\n if (!onAddSubFeature && !onAddSlice && visibleActions.length === 0) return null;\n\n const mainItems: MenuDropdownItem[] = [\n ...(onAddSlice ? [{ id: 'slice', label: messages.sliceTypes.add + ' ›', description: messages.features.addSliceDescription,\n keepOpen: true, onClick: () => setPhase('slice') }] : []),\n ...(onAddSubFeature ? [{ id: 'sub-feature', label: messages.features.addSubFeature,\n description: messages.features.addSubFeatureDescription, onClick: onAddSubFeature }] : []),\n ...visibleActions.map(action => ({ id: action.id, label: action.label + (action.items ? ' ›' : ''),\n description: action.description, icon: action.icon, disabled: action.disabled, tooltip: action.tooltip,\n keepOpen: !!action.items, onClick: () => {\n if (!action.items) return activate(action);\n setSelectedConsumerActionId(action.id);\n setPhase('consumer');\n } })),\n ];\n function activate(action: FeatureHeaderMenuAction) {\n const host = triggerRef.current?.getBoundingClientRect();\n if (host) action.onActivate(featureId, host);\n }\n const back: MenuDropdownItem = { id: 'back', label: messages.features.back, keepOpen: true, onClick: () => setPhase('main') };\n const sliceItems = onAddSlice ? [back, ...sliceTypeMenuItems(messages, onAddSlice)] : [back];\n const consumerItems = [back, ...(visibleActions.find(action => action.id === selectedConsumerActionId)?.items ?? [])\n .filter(action => !action.when || action.when(featureId))\n .map(action => ({ id: action.id, label: action.label, icon: action.icon, disabled: action.disabled,\n tooltip: action.tooltip, onClick: () => activate(action) }))];\n\n return <MenuDropdown\n trigger={<button ref={triggerRef} type='button'\n className='event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={messages.features.add} aria-label={messages.features.add}>+</button>}\n items={phase === 'main' ? mainItems : phase === 'slice' ? sliceItems : consumerItems}\n align='right' onClose={() => {\n setPhase('main');\n setSelectedConsumerActionId(undefined);\n }} />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\nimport type { MenuDropdownItem } from '../Menus';\nimport type { FeatureHeaderMenuAction } from './FeatureHeaderMenuAction';\n\nexport const featureHeaderMenuItems = (\n featureId: Guid,\n actions: readonly FeatureHeaderMenuAction[],\n hostRect: () => DOMRect | undefined,\n): MenuDropdownItem[] => actions.filter(action => !action.when || action.when(featureId)).map(action => ({\n id: action.id,\n label: action.label,\n description: action.description,\n icon: action.icon,\n disabled: action.disabled,\n tooltip: action.tooltip,\n isSeparator: action.isSeparator,\n items: action.items ? featureHeaderMenuItems(featureId, action.items, hostRect) : undefined,\n onClick: () => {\n const host = hostRect();\n if (host) action.onActivate(featureId, host);\n },\n}));\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { MenuDropdown } from '../Menus';\nimport { featureHeaderMenuItems } from './featureHeaderMenuItems';\nimport type { FeatureHeaderMenuAction } from './FeatureHeaderMenuAction';\n\nexport interface FeatureHeaderMenuProps {\n featureId: Guid;\n tooltip: string;\n icon: ReactNode;\n actions: readonly FeatureHeaderMenuAction[];\n}\n\nexport const FeatureHeaderMenu = ({ featureId, tooltip, icon, actions }: FeatureHeaderMenuProps) => {\n const triggerRef = useRef<HTMLButtonElement>(null);\n const items = featureHeaderMenuItems(featureId, actions, () => triggerRef.current?.getBoundingClientRect());\n if (items.length === 0) return null;\n\n return <MenuDropdown\n trigger={<button ref={triggerRef} type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={tooltip} aria-label={tooltip}>{icon}</button>}\n items={items} align='right' />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Headers/IconButton.css';\nimport '../Rows/AddButton.css';\nimport type { SliceType } from '../Model';\nimport { FeatureAddMenu } from './FeatureAddMenu';\nimport { FeatureHeaderMenu } from './FeatureHeaderMenu';\nimport { FeatureSuggestions } from './FeatureSuggestions';\nimport './FeatureHeader.css';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceStatus } from '../Model';\nimport { useBoard } from '../Board';\nimport { DetailsToggle, PillHeader } from '../Headers';\nimport { useHeaderDragIntent, type HeaderDragStart } from '../HeaderDragging';\nimport { useEventModelPresentation } from '../Presentation';\nimport { SliceStatusPicker } from '../Statuses';\n\nexport interface FeatureHeaderProps {\n featureId: Guid;\n name: string;\n height: number;\n collapsed: boolean;\n onToggleCollapse?: () => void;\n onRenamed?: (featureId: Guid, name: string) => void;\n status?: SliceStatus;\n detailsVisible?: boolean;\n onToggleDetails?: () => void;\n dragging?: boolean;\n onDragStart?: (start: HeaderDragStart) => void;\n error?: string;\n onAddSubFeature?: () => void;\n onAddSlice?: (sliceType: SliceType) => void;\n}\n\nconst background = 'rgba(160,140,230,0.10)';\nconst border = '1px solid rgba(160,140,230,0.22)';\n\nexport const FeatureHeader = ({\n featureId,\n name,\n height,\n collapsed,\n onToggleCollapse,\n onRenamed,\n status,\n detailsVisible = false,\n onToggleDetails,\n dragging = false,\n onDragStart,\n error,\n onAddSubFeature,\n onAddSlice,\n}: FeatureHeaderProps) => {\n const board = useBoard();\n const { showStatuses = true } = useEventModelPresentation();\n const dragHandlers = useHeaderDragIntent(!board.readOnly && !collapsed ? onDragStart : undefined);\n const renamed = board.readOnly ? undefined : onRenamed;\n const actions = (board.actions.featureHeader ?? []).filter(action => !action.when || action.when(featureId));\n const leadingActions = (board.actions.featureHeaderLeading ?? []).filter(action => !action.when || action.when(featureId));\n const menuActions = board.actions.featureHeaderMenu ?? [];\n\n return (\n <PillHeader\n variant='feature'\n collapsed={collapsed}\n onToggle={onToggleCollapse}\n leadingContent={!board.readOnly && leadingActions.map(action => <button\n key={action.tooltip} type='button' className='event-modeling-grid-icon-btn'\n title={action.disabled ? action.disabledTooltip ?? action.tooltip : action.tooltip} aria-label={action.tooltip} disabled={action.disabled}\n onClick={event => action.onActivate(featureId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}{action.indicator && <span className='event-modeling-feature-chat-dot' aria-hidden='true' />}</button>)}\n label={name}\n onRenameLabel={value => renamed?.(featureId, value)}\n labelReadOnly={!renamed}\n background={background}\n border={border}\n height={height}\n draggable={dragHandlers !== undefined}\n onPointerDown={dragHandlers?.onPointerDown}\n onPointerMove={dragHandlers?.onPointerMove}\n onPointerUp={dragHandlers?.onPointerUp}\n labelStyle={{\n fontSize: 12,\n fontWeight: 600,\n color: 'rgba(180,165,255,0.85)',\n textAlign: 'center',\n opacity: dragging ? 0.65 : 1,\n }}\n error={error}\n >\n {!collapsed && (\n <>\n {showStatuses && status !== undefined && <SliceStatusPicker status={status} />}\n {!board.readOnly && onToggleDetails && <DetailsToggle visible={detailsVisible} onToggle={onToggleDetails} />}\n {!board.readOnly && actions.map(action => <button\n key={action.tooltip} type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={action.disabled ? action.disabledTooltip ?? action.tooltip : action.tooltip} aria-label={action.tooltip} disabled={action.disabled}\n style={action.active ? { borderColor: 'var(--text-color)', color: 'var(--text-color)' } : undefined}\n onClick={event => action.onActivate(featureId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}</button>)}\n {!board.readOnly && <FeatureHeaderMenu featureId={featureId} tooltip={board.messages.features.options}\n icon={<svg width='13' height='13' viewBox='0 0 14 14' fill='none' aria-hidden='true'>\n <line x1='2' y1='3.5' x2='12' y2='3.5' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n <line x1='2' y1='7' x2='12' y2='7' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n <line x1='2' y1='10.5' x2='12' y2='10.5' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n </svg>} actions={menuActions} />}\n {!board.readOnly && (board.actions.featureHeaderAfterMenu ?? []).filter(action => !action.when || action.when(featureId)).map(action => <button\n key={action.tooltip} type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={action.disabled ? action.disabledTooltip ?? action.tooltip : action.tooltip} aria-label={action.tooltip} disabled={action.disabled}\n onClick={event => action.onActivate(featureId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}</button>)}\n {!board.readOnly && <FeatureSuggestions suggestions={board.actions.featureHeaderSuggestions ?? []} />}\n {!board.readOnly && <FeatureAddMenu featureId={featureId} onAddSubFeature={onAddSubFeature}\n onAddSlice={onAddSlice} actions={board.actions.featureHeaderAdd} />}\n </>\n )}\n </PillHeader>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SpecificationRunOutcome } from '../Model';\n\n/**\n * Represents the run state of a specification as shown in the UI.\n */\nexport enum SpecificationRunState {\n /** No run has happened and none is in progress. */\n Idle = 'idle',\n\n /** A run is currently in progress. */\n Running = 'running',\n\n /** The latest run passed. */\n Passed = 'passed',\n\n /** The latest run failed. */\n Failed = 'failed',\n\n /** The latest run could not be conclusively verified. */\n Inconclusive = 'inconclusive',\n}\n\n/**\n * Derives the UI run state from the latest persisted outcome and whether a run is currently in progress.\n * @param outcome The latest persisted outcome, or undefined when no run has completed.\n * @param isRunning Whether a run is currently in progress.\n * @returns The {@link SpecificationRunState}.\n */\nexport function specificationRunState(outcome: SpecificationRunOutcome | undefined, isRunning: boolean): SpecificationRunState {\n if (isRunning) {\n return SpecificationRunState.Running;\n }\n\n switch (outcome) {\n case SpecificationRunOutcome.passed:\n return SpecificationRunState.Passed;\n case SpecificationRunOutcome.failed:\n return SpecificationRunState.Failed;\n case SpecificationRunOutcome.inconclusive:\n return SpecificationRunState.Inconclusive;\n default:\n return SpecificationRunState.Idle;\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SpecificationRunButton.css';\nimport { useRef, useState } from 'react';\nimport { useBoard } from '../Board';\nimport { useSliceReadOnly } from '../Slices';\nimport type { SliceSpecification } from '../Model';\nimport { SpecificationRunState } from './SpecificationRunState';\n\nexport interface SpecificationRunButtonProps {\n state: SpecificationRunState;\n specification: SliceSpecification;\n}\n\nexport const SpecificationRunButton = ({ state, specification }: SpecificationRunButtonProps) => {\n const { actions } = useBoard();\n const readOnly = useSliceReadOnly();\n const inFlight = useRef(false);\n const [isPending, setIsPending] = useState(false);\n const isRunning = state === SpecificationRunState.Running;\n const action = isRunning ? actions.specificationStop : actions.specificationRun;\n if (!action || (action.when && !action.when(specification))) return null;\n\n const activate = async (host: DOMRect) => {\n if (readOnly) return;\n if (isRunning) {\n await action.onActivate(specification.id, host);\n return;\n }\n if (inFlight.current) return;\n inFlight.current = true;\n setIsPending(true);\n try {\n await action.onActivate(specification.id, host);\n } finally {\n inFlight.current = false;\n setIsPending(false);\n }\n };\n\n return <button type='button' className={`spec-run-button spec-run-button--${state}`}\n onClick={event => void activate(event.currentTarget.getBoundingClientRect())}\n disabled={readOnly || (isPending && !isRunning)} aria-label={action.tooltip} title={action.tooltip}>\n {isPending && !isRunning ? <i className='pi pi-spin pi-spinner' /> : action.icon}\n </button>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SpecificationStatus.css';\nimport React from 'react';\nimport { SpecificationRunState } from './SpecificationRunState';\nimport { useEventModelMessages } from '../Messages';\n\nconst ICONS: Record<SpecificationRunState, string> = {\n [SpecificationRunState.Idle]: 'pi pi-minus',\n [SpecificationRunState.Running]: 'pi pi-circle',\n [SpecificationRunState.Passed]: 'pi pi-check',\n [SpecificationRunState.Failed]: 'pi pi-times',\n [SpecificationRunState.Inconclusive]: 'pi pi-exclamation-triangle',\n};\n\nexport interface SpecificationStatusProps {\n /** The current run state of the specification. */\n state: SpecificationRunState;\n\n /** The last run's failure message, surfaced in the tooltip when the run failed. */\n message?: string;\n}\n\n/**\n * A circular status badge that reflects the outcome of a specification's last run — mirroring the slice status\n * badge — showing whether it has not been run, succeeded, or failed (with the failure reason in its tooltip).\n * When failed with a message, renders as a button to make the error more discoverable.\n */\nexport const SpecificationStatus: React.FC<SpecificationStatusProps> = ({ state, message }) => {\n const labels = useEventModelMessages().specificationStatus;\n\n const label = state === SpecificationRunState.Failed && message\n ? `${labels.failed}: ${message}`\n : labels[state];\n\n const hasError = state === SpecificationRunState.Failed && message;\n const className = `spec-status spec-status--${state}${hasError ? ' spec-status--has-error' : ''}`;\n\n return (\n <span className={className} title={label} aria-label={label} role={hasError ? 'button' : undefined} tabIndex={hasError ? 0 : undefined}>\n <i className={ICONS[state]} />\n </span>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './Specification.css';\nimport './SpecificationHeader.css';\nimport type { ReactNode } from 'react';\nimport { useBoard } from '../Board';\nimport { rowLabelWidth } from '../Geometry';\nimport { CollapseButton, EditableLabel } from '../Headers';\nimport { useSliceReadOnly } from '../Slices';\nimport { SpecificationRunState } from './SpecificationRunState';\nimport { SpecificationStatus } from './SpecificationStatus';\n\n// The height of the header row, so what sits in the gutter beside it centers on the header rather than on\n// the whole box, which grows when a failed run's message is shown under it.\nconst headerHeight = 44;\n\nexport interface SpecificationHeaderProps {\n name: string;\n collapsed: boolean;\n onToggleCollapse?: () => void;\n runState: SpecificationRunState;\n // Why the last run failed, shown under the header when it did.\n runMessage?: string;\n // Renaming exists only on an editable slice when this is supplied.\n onRenamed?: (name: string) => void;\n // Deleting exists only on an editable slice when this is supplied.\n onDeleted?: () => void;\n // The consumer's control for running the specification, drawn after its status.\n runControl?: ReactNode;\n // What the consumer draws in the row-label gutter beside the header.\n gutter?: ReactNode;\n}\n\n// The header of one specification: collapse, its name, how its last run went, and what can be done with it.\nexport const SpecificationHeader = ({\n name,\n collapsed,\n onToggleCollapse,\n runState,\n runMessage,\n onRenamed,\n onDeleted,\n runControl,\n gutter,\n}: SpecificationHeaderProps) => {\n const { messages, readOnly: boardReadOnly } = useBoard();\n const readOnly = useSliceReadOnly();\n const renamed = readOnly ? undefined : onRenamed;\n const deleted = readOnly ? undefined : onDeleted;\n\n return (\n <div className='event-modeling-grid-specification-outer-row'>\n <div className='event-modeling-grid-specification-label-gutter' style={{ width: rowLabelWidth, flexShrink: 0, alignSelf: 'flex-start', height: headerHeight, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>\n {gutter}\n </div>\n <div\n className={[\n 'event-modeling-grid-specification-box',\n 'event-modeling-grid-specification-box--header',\n collapsed ? 'event-modeling-grid-specification-box--last' : '',\n ].filter(Boolean).join(' ')}\n style={{ flex: 1, minWidth: 0 }}\n >\n <div className='event-modeling-grid-specification-header'>\n {!boardReadOnly && onToggleCollapse && <CollapseButton collapsed={collapsed} onToggle={readOnly ? undefined : onToggleCollapse} />}\n <div className='event-modeling-grid-specification-header-label'>\n <EditableLabel\n value={name}\n onChange={value => renamed?.(value)}\n placeholder={messages.specifications.namePlaceholder}\n style={{ fontSize: 11, fontWeight: 500, color: 'rgba(255,255,255,0.80)', textAlign: 'center' }}\n readOnly={!renamed}\n />\n </div>\n <SpecificationStatus state={runState} message={runMessage} />\n {runControl}\n {deleted && (\n <button\n type='button'\n className='spec-delete-button'\n onClick={deleted}\n aria-label={messages.specifications.delete}\n title={messages.specifications.delete}\n >\n <i className='pi pi-trash' />\n </button>\n )}\n </div>\n {runState === SpecificationRunState.Failed && runMessage && (\n <div className='spec-header-message' title={runMessage}>{runMessage}</div>\n )}\n </div>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { SliceSpecification } from '../Model';\nimport type { SpecificationEditing } from './SpecificationEditing';\n\nexport const GENERATED_SPECIFICATIONS_ABSORB_WINDOW_MS = 15_000;\n\nexport const specificationContentSize = (specification: SliceSpecification): number =>\n specification.given.length + (specification.when ? 1 : 0) +\n specification.thenEvents.length + specification.thenErrors.length;\n\nexport const followsIncomingSpecifications = (readOnly: boolean, editing: SpecificationEditing): boolean =>\n readOnly || !(editing.onSpecificationAdded || editing.onSpecificationRemoved ||\n editing.onSpecificationRenamed || editing.onSpecificationOpenStateSet || editing.onGivenEventAdded ||\n editing.onGivenEventValuesSet || editing.onGivenReadModelSet || editing.onWhenCommandSet ||\n editing.onWhenCommandValuesSet || editing.onThenEventAdded || editing.onThenEventValuesSet ||\n editing.onThenErrorAdded || editing.onThenRuleErrorAdded || editing.onThenErrorRenamed ||\n editing.onGivenEventRemoved || editing.onGivenReadModelRemoved || editing.onGivenReadModelValuesSet || editing.onThenEventRemoved || editing.onThenReadModelValuesSet ||\n editing.onThenErrorRemoved || editing.onSpecificationItemOpened);\n\nexport const reconcileSpecifications = (\n current: SliceSpecification[], incoming: SliceSpecification[], followsIncoming: boolean,\n withinGenerationWindow: boolean, removedIds: ReadonlySet<string>,\n): SliceSpecification[] => {\n if (followsIncoming) return incoming;\n return withinGenerationWindow ? absorbSpecifications(current, incoming, removedIds) : current;\n};\n\n// During generation the read side may first publish the new card without its rows. Never replace a\n// locally edited card with a smaller snapshot, or discard a card not yet visible in that snapshot.\nexport const absorbSpecifications = (current: SliceSpecification[], incoming: SliceSpecification[], removedIds: ReadonlySet<string> = new Set()): SliceSpecification[] => {\n const visibleIncoming = incoming.filter(specification => !removedIds.has(specification.id.toString()));\n const incomingById = new Map(visibleIncoming.map(specification => [specification.id.toString(), specification]));\n const merged = current.map(specification => {\n const candidate = incomingById.get(specification.id.toString());\n return candidate && specificationContentSize(candidate) > specificationContentSize(specification) ? candidate : specification;\n });\n const known = new Set(current.map(specification => specification.id.toString()));\n const added = visibleIncoming.filter(specification => !known.has(specification.id.toString()));\n return added.length || merged.some((specification, index) => specification !== current[index]) ? [...merged, ...added] : current;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/AddButton.css';\nimport './SpecificationCollection.css';\nimport { useEffect, useRef, useState, type ReactNode } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport type { SliceSpecification } from '../Model';\nimport { useBoard } from '../Board';\nimport { useSliceReadOnly } from '../Slices';\nimport { GridTooltip } from '../Tooltips';\nimport { rowLabelWidth } from '../Geometry';\nimport { SpecificationHeader } from './SpecificationHeader';\nimport { SpecificationRunState } from './SpecificationRunState';\nimport { SpecificationRunButton } from './SpecificationRunButton';\nimport { followsIncomingSpecifications, GENERATED_SPECIFICATIONS_ABSORB_WINDOW_MS, reconcileSpecifications, specificationContentSize } from './specificationCollectionState';\n\nexport interface SpecificationCollectionProps {\n sliceId: Guid;\n width: number;\n collapsed: boolean;\n specifications: SliceSpecification[];\n runInfoFor: (specification: SliceSpecification) => { state: SpecificationRunState; message: string };\n renderRows: (specification: SliceSpecification) => ReactNode;\n}\n\nlet specificationCounter = 1;\n\nexport const SpecificationCollection = ({ sliceId, width, collapsed, specifications: incoming, runInfoFor, renderRows }: SpecificationCollectionProps) => {\n const { editing, actions, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const [specifications, setSpecifications] = useState(incoming);\n const [isGenerating, setIsGenerating] = useState(false);\n const [isRunningAll, setIsRunningAll] = useState(false);\n const [isAdding, setIsAdding] = useState(false);\n const absorbUntil = useRef(0);\n const addInFlight = useRef(false);\n const generateInFlight = useRef(false);\n const runAllInFlight = useRef(false);\n const removedIds = useRef(new Set<string>());\n const followsIncoming = followsIncomingSpecifications(readOnly, editing);\n const visibleSpecifications = followsIncoming ? incoming : specifications;\n\n useEffect(() => {\n setSpecifications(previous => reconcileSpecifications(previous, incoming, followsIncoming,\n Date.now() <= absorbUntil.current, removedIds.current));\n }, [incoming, followsIncoming]);\n\n const add = async () => {\n if (addInFlight.current || !editing.onSpecificationAdded) return;\n addInFlight.current = true;\n setIsAdding(true);\n const specification: SliceSpecification = {\n id: Guid.create(), name: `${messages.specifications.namePlaceholder} ${specificationCounter++}`, collapsed: false,\n given: [], thenEvents: [], thenErrors: [],\n };\n setSpecifications(previous => [...previous, specification]);\n try {\n if (!await editing.onSpecificationAdded(sliceId, specification)) {\n setSpecifications(previous => previous.filter(item => !item.id.equals(specification.id)));\n }\n } catch {\n setSpecifications(previous => previous.filter(item => !item.id.equals(specification.id)));\n } finally {\n addInFlight.current = false;\n setIsAdding(false);\n }\n };\n const remove = (specificationId: Guid) => {\n if (removedIds.current.has(specificationId.toString())) return;\n removedIds.current.add(specificationId.toString());\n absorbUntil.current = 0;\n setSpecifications(previous => previous.filter(specification => !specification.id.equals(specificationId)));\n editing.onSpecificationRemoved?.(sliceId, specificationId);\n };\n const rename = (specificationId: Guid, name: string) => {\n setSpecifications(previous => previous.map(specification => specification.id.equals(specificationId) ? { ...specification, name } : specification));\n editing.onSpecificationRenamed?.(sliceId, specificationId, name);\n };\n const toggle = (specificationId: Guid, isOpen: boolean) => {\n if (readOnly || !editing.onSpecificationOpenStateSet) return;\n setSpecifications(previous => previous.map(specification => specification.id.equals(specificationId) ? { ...specification, collapsed: !isOpen } : specification));\n editing.onSpecificationOpenStateSet?.(sliceId, specificationId, isOpen);\n };\n const generate = async (host: DOMRect) => {\n if (readOnly || generateInFlight.current || !actions.specificationsGenerate) return;\n generateInFlight.current = true;\n setIsGenerating(true);\n try {\n if (await actions.specificationsGenerate.onActivate(sliceId, host)) {\n absorbUntil.current = Date.now() + GENERATED_SPECIFICATIONS_ABSORB_WINDOW_MS;\n }\n } finally {\n generateInFlight.current = false;\n setIsGenerating(false);\n }\n };\n const runAll = async (host: DOMRect) => {\n if (readOnly || runAllInFlight.current || !actions.specificationsRunAll || actions.specificationsRunAll.disabled) return;\n runAllInFlight.current = true;\n setIsRunningAll(true);\n try {\n await actions.specificationsRunAll.onActivate(sliceId, host);\n } finally {\n runAllInFlight.current = false;\n setIsRunningAll(false);\n }\n };\n const generateAction = actions.specificationsGenerate;\n const runAllAction = actions.specificationsRunAll;\n const showGenerate = !readOnly && generateAction && (!generateAction.when || generateAction.when(sliceId));\n\n if (collapsed) return null;\n return <>\n {visibleSpecifications.map((specification, index) => {\n const { state, message } = runInfoFor(specification);\n return <div key={`${specification.id.toString()}:${specificationContentSize(specification)}`}\n data-slice-spec-col='true' data-slice-id={sliceId.toString()}\n className={`event-modeling-grid-specification-wrapper event-modeling-grid-specification-wrapper--${state}`}\n style={{ width: rowLabelWidth + width }}>\n <SpecificationHeader name={specification.name} collapsed={specification.collapsed}\n onToggleCollapse={editing.onSpecificationOpenStateSet ? () => toggle(specification.id, specification.collapsed) : undefined}\n onRenamed={editing.onSpecificationRenamed ? name => rename(specification.id, name) : undefined}\n onDeleted={editing.onSpecificationRemoved ? () => remove(specification.id) : undefined}\n runState={state} runMessage={message}\n runControl={<SpecificationRunButton state={state} specification={specification} />}\n gutter={index === 0 && runAllAction && (!runAllAction.when || runAllAction.when(sliceId)) && <button type='button'\n className='event-modeling-grid-add-button--small spec-run-all-button'\n onClick={event => void runAll(event.currentTarget.getBoundingClientRect())}\n disabled={readOnly || isRunningAll || runAllAction.disabled} aria-label={runAllAction.tooltip} title={runAllAction.tooltip}>\n {runAllAction.icon}\n </button>} />\n {!specification.collapsed && renderRows(specification)}\n </div>;\n })}\n {!readOnly && (editing.onSpecificationAdded || showGenerate) && <div className='event-modeling-grid-specification-add-area'>\n {editing.onSpecificationAdded && <GridTooltip content={messages.specifications.add} position='top'>\n <button type='button' onClick={() => void add()} disabled={isAdding} className='event-modeling-grid-add-button--small' aria-label={messages.specifications.add}>+</button>\n </GridTooltip>}\n {showGenerate && <GridTooltip content={generateAction.tooltip} position='top'>\n <button type='button' onClick={event => void generate(event.currentTarget.getBoundingClientRect())}\n disabled={isGenerating} className='event-modeling-grid-add-button--small' aria-label={generateAction.tooltip}>\n {isGenerating ? <i className='pi pi-spin pi-spinner' /> : generateAction.icon}\n </button>\n </GridTooltip>}\n </div>}\n </>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './Specification.css';\nimport type { ReactNode } from 'react';\nimport { useSliceReadOnly } from '../Slices';\n\nexport interface SpecificationSectionProps {\n // The section's name, such as Given, When or Then.\n headline?: string;\n // The minimum height of the section, so the sections of a specification line up across slices.\n minHeight: number;\n // What the consumer offers for adding to the section. Nothing is offered on a read-only slice.\n actions?: ReactNode;\n // The section's cards.\n children?: ReactNode;\n}\n\n// One section of a specification: its name, its cards, and a row for what can be added to it.\nexport const SpecificationSection = ({ headline, minHeight, actions, children }: SpecificationSectionProps) => {\n const readOnly = useSliceReadOnly();\n return (\n <div className='event-modeling-grid-specification-section' style={{ minHeight }}>\n {headline && <span className='event-modeling-grid-specification-section-headline'>{headline}</span>}\n <div className='event-modeling-grid-specification-section-content'>{children}</div>\n <div className='event-modeling-grid-specification-section-actions'>{readOnly ? undefined : actions}</div>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Finds the index of the best place to break a PascalCase name (e.g. an event or command type name like\n * `CustomerAddressUpdated`) into two lines, so a wrapped card title breaks at a word boundary rather than\n * mid-word. Candidates are ranked in two tiers, closest-to-the-middle first within each tier:\n *\n * 1. A \"word start\" — an uppercase letter directly preceded by a lowercase letter (`...ss|Up...` in\n * `AddressUpdated`). This is the overwhelmingly common case for Cratis event/command names.\n * 2. Any other uppercase letter (index > 0) — a fallback for names built from acronym runs\n * (`HTTPServer`) where tier 1 finds nothing, since there is no lowercase-to-uppercase transition.\n *\n * Returns `null` when the text has no uppercase letter to break before (e.g. a single lowercase word, or\n * text too short to usefully split) — callers fall back to a plain midpoint split in that case.\n */\nexport function nearestPascalCaseBreakIndex(text: string): number | null {\n const middle = text.length / 2;\n const wordStarts: number[] = [];\n const anyUppercase: number[] = [];\n\n for (let index = 1; index < text.length; index++) {\n const character = text[index];\n if (character < 'A' || character > 'Z') continue;\n\n anyUppercase.push(index);\n if (text[index - 1] >= 'a' && text[index - 1] <= 'z') wordStarts.push(index);\n }\n\n const candidates = wordStarts.length > 0 ? wordStarts : anyUppercase;\n if (candidates.length === 0) return null;\n\n return candidates.reduce((closest, candidate) =>\n Math.abs(candidate - middle) < Math.abs(closest - middle) ? candidate : closest);\n}\n\n/**\n * Splits a PascalCase name into two lines at the {@link nearestPascalCaseBreakIndex}. Falls back to an\n * even midpoint split when no uppercase boundary exists, so every name can still be wrapped rather than\n * truncated with an ellipsis.\n */\nexport function splitAtPascalCaseBreak(text: string): [string, string] {\n const breakIndex = nearestPascalCaseBreakIndex(text) ?? Math.ceil(text.length / 2);\n return [text.slice(0, breakIndex), text.slice(breakIndex)];\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { splitAtPascalCaseBreak } from './pascalCaseBreak';\n\n/** The default largest font size a card title renders at — matches the existing card face font size. */\nexport const DEFAULT_MAX_TITLE_FONT_SIZE_PX = 13;\n\n/** The default smallest single-line font size before a title switches to wrapping across two lines. */\nexport const DEFAULT_MIN_TITLE_FONT_SIZE_PX = 10;\n\n/** Measures the rendered pixel width of `text` at `fontSizePx`. Implemented with real font metrics by\n * {@link useAutoFitTitle}; injected here so {@link computeAutoFitTitle} stays a pure, spec-able function. */\nexport type MeasureTextWidth = (text: string, fontSizePx: number) => number;\n\nexport interface AutoFitTitleOptions {\n\n /** The largest font size to try, in pixels. */\n maxFontSizePx: number;\n\n /** The smallest single-line font size to try before falling back to a two-line wrap, in pixels. */\n minFontSizePx: number;\n\n /** The width available to the title, in pixels. */\n availableWidthPx: number;\n}\n\nexport interface AutoFitTitleResult {\n\n /** The font size to render the title at, in pixels. */\n fontSizePx: number;\n\n /** The line(s) to render. A single entry when the title fits on one line; two when it was wrapped. */\n lines: string[];\n}\n\n/**\n * Finds the largest font size (within `options`) at which `text` fits on a single line within\n * `availableWidthPx`, shrinking from `maxFontSizePx` down to `minFontSizePx`. When even `minFontSizePx`\n * does not fit on one line, wraps the text across two lines at the nearest PascalCase word boundary\n * (see {@link splitAtPascalCaseBreak}) and renders those at `minFontSizePx`, rather than shrinking the\n * font further into unreadable territory.\n */\nexport function computeAutoFitTitle(text: string, options: AutoFitTitleOptions, measure: MeasureTextWidth): AutoFitTitleResult {\n const { maxFontSizePx, minFontSizePx, availableWidthPx } = options;\n\n for (let fontSizePx = maxFontSizePx; fontSizePx >= minFontSizePx; fontSizePx--) {\n if (measure(text, fontSizePx) <= availableWidthPx) {\n return { fontSizePx, lines: [text] };\n }\n }\n\n return { fontSizePx: minFontSizePx, lines: splitAtPascalCaseBreak(text) };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { RefObject, useLayoutEffect, useRef, useState } from 'react';\nimport { AutoFitTitleResult, DEFAULT_MAX_TITLE_FONT_SIZE_PX, DEFAULT_MIN_TITLE_FONT_SIZE_PX, computeAutoFitTitle } from './autoFitTitle';\n\nlet measureContext: CanvasRenderingContext2D | null = null;\n\n/** A shared, lazily-created off-screen canvas 2D context for text metrics — cheap to reuse across every card. */\nfunction getMeasureContext(): CanvasRenderingContext2D | null {\n if (measureContext) return measureContext;\n if (typeof document === 'undefined') return null;\n measureContext = document.createElement('canvas').getContext('2d');\n return measureContext;\n}\n\nexport interface UseAutoFitTitleOptions {\n\n /** The CSS font-family the title renders with — must match the element's actual styling for accurate measurement. */\n fontFamily: string;\n\n /** The CSS font-weight the title renders with. */\n fontWeight: string | number;\n\n /** The largest font size to try, in pixels. Defaults to {@link DEFAULT_MAX_TITLE_FONT_SIZE_PX}. */\n maxFontSizePx?: number;\n\n /** The smallest single-line font size before wrapping, in pixels. Defaults to {@link DEFAULT_MIN_TITLE_FONT_SIZE_PX}. */\n minFontSizePx?: number;\n}\n\n/**\n * Measures `text` against the width of the element attached to the returned ref and shrinks/wraps it to\n * fit, via {@link computeAutoFitTitle}. Re-measures whenever the text or font options change.\n *\n * The element the ref attaches to must already be laid out at its final width when this runs (a block\n * element that doesn't grow with its own text content, e.g. `white-space: nowrap; overflow: hidden`) —\n * its `clientWidth` at effect time is taken as the space available to the title.\n */\nexport function useAutoFitTitle<T extends HTMLElement>(text: string, options: UseAutoFitTitleOptions): [RefObject<T | null>, AutoFitTitleResult] {\n const elementRef = useRef<T | null>(null);\n const maxFontSizePx = options.maxFontSizePx ?? DEFAULT_MAX_TITLE_FONT_SIZE_PX;\n const minFontSizePx = options.minFontSizePx ?? DEFAULT_MIN_TITLE_FONT_SIZE_PX;\n const [result, setResult] = useState<AutoFitTitleResult>({ fontSizePx: maxFontSizePx, lines: [text] });\n\n useLayoutEffect(() => {\n const element = elementRef.current;\n const context = getMeasureContext();\n if (!element || !context) return;\n\n const measure = (candidate: string, fontSizePx: number): number => {\n context.font = `${options.fontWeight} ${fontSizePx}px ${options.fontFamily}`;\n return context.measureText(candidate).width;\n };\n\n setResult(computeAutoFitTitle(text, { maxFontSizePx, minFontSizePx, availableWidthPx: element.clientWidth }, measure));\n }, [text, maxFontSizePx, minFontSizePx, options.fontWeight, options.fontFamily]);\n\n return [elementRef, result];\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './Card.css';\nimport React, { useRef, useEffect, useCallback } from 'react';\nimport { useAutoFitTitle } from './useAutoFitTitle';\n\nconst DOUBLE_CLICK_DELAY_MS = 250;\n\n/** Matches `.event-modeling-card__face`'s `font-family` in Card.css — the title measures against it. */\nconst TITLE_FONT_FAMILY = 'Inter, Helvetica, Arial, sans-serif';\n\nexport interface CardProps {\n name: string;\n backgroundColor: string;\n textColor: string;\n isSelected?: boolean;\n disabled?: boolean;\n onSelected?: () => void;\n onStartEdit?: () => void;\n extraContent?: React.ReactNode;\n children?: React.ReactNode;\n ariaLabel?: string;\n ariaPressed?: boolean;\n 'data-event-id'?: string;\n 'data-card-id'?: string;\n 'data-slice-id'?: string;\n}\n\nexport const Card: React.FC<CardProps> = ({\n name,\n backgroundColor,\n textColor,\n isSelected = false,\n disabled = false,\n onSelected,\n onStartEdit,\n extraContent,\n children,\n ariaLabel,\n ariaPressed,\n 'data-event-id': dataEventId,\n 'data-card-id': dataCardId,\n 'data-slice-id': dataSliceId,\n}) => {\n const pendingClick = useRef<ReturnType<typeof setTimeout> | null>(null);\n const isInteractive = Boolean(onSelected ?? onStartEdit) || disabled;\n const [titleRef, titleFit] = useAutoFitTitle<HTMLElement>(name, { fontFamily: TITLE_FONT_FAMILY, fontWeight: 'bold' });\n\n useEffect(() => () => {\n if (pendingClick.current) clearTimeout(pendingClick.current);\n }, []);\n\n const handleClick = useCallback((event: React.MouseEvent) => {\n event.stopPropagation();\n if (pendingClick.current) {\n clearTimeout(pendingClick.current);\n pendingClick.current = null;\n return;\n }\n pendingClick.current = setTimeout(() => {\n pendingClick.current = null;\n onSelected?.();\n }, DOUBLE_CLICK_DELAY_MS);\n }, [onSelected]);\n\n const handleDoubleClick = useCallback((event: React.MouseEvent) => {\n event.stopPropagation();\n if (pendingClick.current) {\n clearTimeout(pendingClick.current);\n pendingClick.current = null;\n }\n onStartEdit?.();\n }, [onStartEdit]);\n\n const selectionStyle: React.CSSProperties = isSelected\n ? { outline: `2px solid ${backgroundColor}`, outlineOffset: 2 }\n : {};\n\n const faceStyle: React.CSSProperties = {\n background: backgroundColor,\n color: textColor,\n };\n\n const faceContent = (\n <>\n <div className='event-modeling-card__face' style={faceStyle}>\n <strong ref={titleRef} className='event-modeling-card__title' style={{ fontSize: titleFit.fontSizePx }}>\n {titleFit.lines.length > 1\n ? titleFit.lines.map((line, index) => <span key={index} className='event-modeling-card__title-line'>{line}</span>)\n : titleFit.lines[0]}\n </strong>\n {extraContent}\n </div>\n {children}\n </>\n );\n\n if (isInteractive) {\n return (\n <button\n className='event-modeling-card'\n style={selectionStyle}\n disabled={disabled}\n onClick={handleClick}\n onDoubleClick={handleDoubleClick}\n aria-label={ariaLabel}\n aria-pressed={ariaPressed}\n data-event-id={dataEventId}\n data-card-id={dataCardId}\n data-slice-id={dataSliceId}\n >\n {faceContent}\n </button>\n );\n }\n\n return (\n <div\n className='event-modeling-card'\n data-event-id={dataEventId}\n data-card-id={dataCardId}\n data-slice-id={dataSliceId}\n >\n {faceContent}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Raw hex values for card colors.\n *\n * These MUST match the CSS custom properties defined in .frontend/index.css\n * (--card-event-bg, --card-command-bg, etc.) so that both JS-driven inline\n * styles and CSS class rules resolve to the same palette.\n */\n\n/** Background and text colors for event-modeling card types. */\nexport interface CardColors {\n /** Card face background color. */\n background: string;\n /** Card face text color. */\n text: string;\n}\n\n/** Event (domain event) card colors — warm orange. */\nexport const eventCardColors: CardColors = {\n background: '#ff9933',\n text: '#2a1500',\n};\n\n/** Command card colors — sky blue. */\nexport const commandCardColors: CardColors = {\n background: '#42b3ff',\n text: '#003d5c',\n};\n\n/** Read model card colors — lime green. */\nexport const readModelCardColors: CardColors = {\n background: '#c8e03a',\n text: '#1f2a00',\n};\n\n/** External event (event from another module the Translator translates from) card colors — yellow, the event-modeling convention for external events. */\nexport const externalEventCardColors: CardColors = {\n background: '#ffd633',\n text: '#4d3d00',\n};\n\n/**\n * Concept card colors — violet, the color the event-model board already gives to the structural\n * (feature) level rather than to any of the event/command/read-model artifacts. A concept is neither of\n * those, so it gets its own place in the same palette instead of borrowing one of theirs.\n */\nexport const conceptCardColors: CardColors = {\n background: '#b4a5ff',\n text: '#1c1040',\n};\n\n/** Error card colors — red. */\nexport const errorCardColors: CardColors = {\n background: '#e05050',\n text: '#ffffff',\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './TypeBadge.css';\nimport React from 'react';\nimport { conceptCardColors } from '../Cards';\n\nconst CalendarIcon = () => (\n <svg viewBox='0 0 12 12' fill='none' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' width='11' height='11'>\n <rect x='1' y='2.5' width='10' height='8.5' rx='1.5' />\n <path d='M1 5.5h10M4 1v3M8 1v3' />\n </svg>\n);\n\nconst ClockIcon = () => (\n <svg viewBox='0 0 12 12' fill='none' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' width='11' height='11'>\n <circle cx='6' cy='6' r='4.5' />\n <path d='M6 3.5v2.5l2 1' />\n </svg>\n);\n\ninterface BadgeConfig {\n content: React.ReactNode;\n color: string;\n background: string;\n}\n\nconst BADGE_MAP: Record<string, BadgeConfig> = {\n // PropertyType enum values\n string: { content: 'Aa', color: '#fff', background: '#0891b2' },\n number: { content: '123', color: '#fff', background: '#dc2626' },\n boolean: { content: 'T/F', color: '#fff', background: '#16a34a' },\n date: { content: <CalendarIcon />, color: '#fff', background: '#ea580c' },\n time: { content: <ClockIcon />, color: '#fff', background: '#7c6d14' },\n object: { content: '{}', color: '#fff', background: '#7c3aed' },\n stringArray: { content: '[A]', color: '#fff', background: '#0e7490' },\n numberArray: { content: '[#]', color: '#fff', background: '#b91c1c' },\n objectArray: { content: '[{}]', color: '#fff', background: '#6d28d9' },\n // JSON Schema type strings (used in event schemas)\n integer: { content: '123', color: '#fff', background: '#dc2626' },\n array: { content: '[ ]', color: '#fff', background: '#6d28d9' },\n null: { content: '∅', color: '#fff', background: '#6b7280' },\n};\n\nconst DEFAULT_CONFIG: BadgeConfig = { content: '#', color: '#fff', background: '#6b7280' };\n\nexport interface TypeBadgeProps {\n\n type: string;\n\n /**\n * The concept the property is typed as. When set, the badge names the concept instead of the primitive\n * it wraps — the primitive stays in the tooltip, since that is what the value still behaves as.\n */\n concept?: string;\n}\n\nexport const TypeBadge: React.FC<TypeBadgeProps> = ({ type, concept }) => {\n if (concept) {\n return (\n <span\n className='type-badge type-badge--concept'\n style={{ color: conceptCardColors.text, background: conceptCardColors.background }}\n title={`${concept} (${type})`}\n >\n {concept}\n </span>\n );\n }\n\n const config = BADGE_MAP[type] ?? DEFAULT_CONFIG;\n return (\n <span\n className='type-badge'\n style={{ color: config.color, background: config.background }}\n title={type}\n >\n {config.content}\n </span>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SchemaTooltipProperties.css';\nimport React, { useMemo } from 'react';\nimport type { JsonSchema } from '@cratis/components/SchemaEditor';\nimport { TypeBadge } from './TypeBadge';\nimport { topLevelSchemaProperties } from './schemaProperties';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface SchemaTooltipPropertiesProps {\n title: React.ReactNode;\n schema?: string | JsonSchema;\n showTitle?: boolean;\n compact?: boolean;\n}\n\nexport const SchemaTooltipProperties: React.FC<SchemaTooltipPropertiesProps> = ({ title, schema, showTitle = true, compact = false }) => {\n const messages = useEventModelMessages();\n const properties = useMemo(() => topLevelSchemaProperties(schema), [schema]);\n\n return (\n <div className={`schema-tooltip-properties${compact ? ' schema-tooltip-properties--compact' : ''}`}>\n {showTitle && <div className='schema-tooltip-properties__title'>{title}</div>}\n {properties.length > 0 ? (\n <div className='schema-tooltip-properties__list'>\n {properties.map(property => (\n <div key={`${property.name}-${property.type}`} className='schema-tooltip-properties__row'>\n <TypeBadge type={property.type} />\n <span className='schema-tooltip-properties__name'>{property.name}</span>\n </div>\n ))}\n </div>\n ) : (\n <div className='schema-tooltip-properties__empty'>{messages.properties.none}</div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum ArtifactCardKind {\n command = 'command',\n readModel = 'readModel',\n event = 'event',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Where on the card's top edge an action sits. Actions at the same corner line up inward from it, in the\n// order they are given.\nexport enum CardCorner {\n start = 'start',\n end = 'end',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { CardAction } from './CardAction';\nimport { CardCorner } from './CardCorner';\n\nexport interface CardActionButtonProps {\n action: CardAction;\n corner: CardCorner;\n slot: number;\n onActivate: () => void;\n}\n\n// Actions sit 24 pixels apart, the first one overhanging the corner by 6.\nconst slotOffset = (slot: number) => slot * 24 - 6;\n\nexport const CardActionButton = ({ action, corner, slot, onActivate }: CardActionButtonProps) => {\n const className = [\n 'event-modeling-card-action',\n action.active && 'event-modeling-card-action--active',\n action.disabled && 'event-modeling-card-action--disabled',\n ].filter(Boolean).join(' ');\n\n return (\n <button\n className={className}\n data-corner={corner}\n style={{ [corner === CardCorner.start ? 'left' : 'right']: slotOffset(slot) }}\n disabled={action.disabled || action.busy}\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n onActivate();\n }}\n aria-label={action.tooltip}\n title={action.tooltip}\n >\n <i className={action.icon} />\n </button>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EventTags.css';\n\nexport interface EventTagsProps {\n /** The tags to render. */\n tags?: readonly string[];\n}\n\n/**\n * Renders the tags of an event type as a row of chips on the event card.\n */\nexport const EventTags = ({ tags }: EventTagsProps) => {\n if (!tags || tags.length === 0) {\n return null;\n }\n\n return (\n <div className='event-modeling-event-tags'>\n {tags.map(tag => (\n <span key={tag} className='event-modeling-event-tag' title={tag}>{tag}</span>\n ))}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ArtifactCard.css';\nimport React, { useRef } from 'react';\nimport type { JsonSchema } from '@cratis/components/SchemaEditor';\nimport type { Guid } from '@cratis/fundamentals';\nimport { SchemaTooltipProperties } from '../Properties';\nimport { useSliceReadOnly } from '../Slices';\nimport { ArtifactCardKind } from './ArtifactCardKind';\nimport { Card, type CardProps } from './Card';\nimport type { CardAction } from './CardAction';\nimport { CardActionButton } from './CardActionButton';\nimport { CardCorner } from './CardCorner';\nimport { commandCardColors, eventCardColors, readModelCardColors } from './cardColors';\nimport { EventTags } from './EventTags';\n\nexport interface ArtifactCardProps extends Omit<CardProps, 'backgroundColor' | 'textColor' | 'extraContent'> {\n kind: ArtifactCardKind;\n artifactId?: Guid;\n // A line of text under the name, such as a description or the names of the properties.\n summary?: string;\n tags?: readonly string[];\n schema?: string | JsonSchema;\n showDetails?: boolean;\n actions?: readonly CardAction[];\n // Clicking the card of an editable slice activates it instead of selecting it.\n onActivate?: (artifactId: Guid, host: DOMRect) => void;\n}\n\nconst colors = {\n [ArtifactCardKind.command]: commandCardColors,\n [ArtifactCardKind.readModel]: readModelCardColors,\n [ArtifactCardKind.event]: eventCardColors,\n};\n\nconst anchorClassName = {\n [ArtifactCardKind.command]: 'event-modeling-command',\n [ArtifactCardKind.readModel]: 'event-modeling-read-model',\n [ArtifactCardKind.event]: 'event-modeling-event',\n};\n\nconst summaryStyle: React.CSSProperties = { fontSize: 11, opacity: 0.8, marginTop: 4 };\n\nexport const ArtifactCard = ({ kind, artifactId, summary, tags, schema, showDetails = false, actions = [], onActivate, onSelected, ...cardProps }: ArtifactCardProps) => {\n const readOnly = useSliceReadOnly();\n const host = useRef<HTMLDivElement>(null);\n const hostRect = () => host.current?.getBoundingClientRect() ?? new DOMRect();\n const drawn = readOnly ? [] : actions.filter(action => !action.when || (!!artifactId && action.when(artifactId)));\n const inCorner = (corner: CardCorner) => drawn.filter(action => (action.corner ?? CardCorner.end) === corner);\n\n const card = (\n <div ref={host}>\n <Card\n backgroundColor={colors[kind].background}\n textColor={colors[kind].text}\n extraContent={(\n <>\n <EventTags tags={tags} />\n {summary && <div style={summaryStyle}>{summary}</div>}\n {showDetails && <SchemaTooltipProperties title={cardProps.name} schema={schema} showTitle={false} compact={true} />}\n </>\n )}\n onSelected={() => {\n if (onActivate && artifactId && !readOnly) {\n onActivate(artifactId, hostRect());\n return;\n }\n onSelected?.();\n }}\n {...cardProps}\n />\n </div>\n );\n\n // An event card has only ever been anchored when it has actions to anchor; the others always are.\n if (kind === ArtifactCardKind.event && drawn.length === 0) return card;\n\n return (\n <div className={anchorClassName[kind]} data-artifact-kind={kind}>\n {card}\n {[CardCorner.start, CardCorner.end].flatMap(corner => inCorner(corner).map((action, slot) => (\n <CardActionButton\n key={`${corner}-${slot}`}\n action={action}\n corner={corner}\n slot={slot}\n onActivate={() => artifactId && action.onActivate(artifactId, hostRect())}\n />\n )))}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\n\nexport interface CardNameInputProps {\n value: string;\n backgroundColor: string;\n textColor: string;\n nameError?: string;\n onChange: (value: string) => void;\n onCommit: () => void;\n onCancel: () => void;\n}\n\n// A card-shaped text field for renaming a card in place: Enter commits, Escape cancels, leaving commits.\nexport const CardNameInput: React.FC<CardNameInputProps> = ({\n value,\n backgroundColor,\n textColor,\n nameError,\n onChange,\n onCommit,\n onCancel,\n}) => (\n <div\n style={{\n width: 'var(--card-width)',\n minHeight: 'var(--card-min-height)',\n padding: 'var(--card-padding-y) var(--card-padding-x)',\n borderRadius: 'var(--card-radius)',\n boxSizing: 'border-box',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'center',\n background: backgroundColor,\n boxShadow: '0 1px 4px rgba(0,0,0,0.18)',\n }}\n >\n <input\n autoFocus\n value={value}\n onChange={event => onChange(event.target.value)}\n onBlur={onCommit}\n onKeyDown={event => {\n if (event.key === 'Enter') onCommit();\n if (event.key === 'Escape') onCancel();\n }}\n onClick={event => event.stopPropagation()}\n title={nameError}\n style={{\n border: nameError ? '2px solid #f87171' : 'none',\n borderRadius: nameError ? 3 : 0,\n outline: 'none',\n background: 'transparent',\n width: '100%',\n fontWeight: 'bold',\n fontSize: 'var(--card-font-size)',\n lineHeight: 'var(--card-line-height)',\n fontFamily: 'Inter, Helvetica, Arial, sans-serif',\n color: textColor,\n textAlign: 'center',\n }}\n />\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The values set on each item of a section, by item id, as they are set here and as the items carried them.\nexport type ItemValues = Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n\nexport const itemValuesOf = (items: readonly { id: { toString(): string }; values: Record<string, unknown> }[]): ItemValues =>\n Object.fromEntries(items.map(item => [item.id.toString(), item.values]));\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './PickerPanel.css';\nimport React, { useMemo, useRef, useState } from 'react';\nimport { AnchoredOverlay } from '../Tooltips';\nimport { useDismissOnOutsidePointer } from './useDismissOnOutsidePointer';\n\n// More options than this and the panel offers a search field.\nconst searchThreshold = 5;\n\nexport interface PickerTriggerProps {\n open: boolean;\n toggle: () => void;\n}\n\nexport interface PickerPanelProps<TOption> {\n options: readonly TOption[];\n // What an option is called, shown in the list and matched by the search.\n nameOf: (option: TOption) => string;\n // The color marking each option.\n color: string;\n searchPlaceholder: string;\n emptyLabel: string;\n onSelect: (option: TOption) => void;\n // List items drawn after the options, whatever the search. Receives close, to call once one is used.\n footer?: (close: () => void) => React.ReactNode;\n // Draws what opens the panel. The panel floats above it, aligned to its right edge.\n trigger: (props: PickerTriggerProps) => React.ReactNode;\n}\n\nexport const PickerPanel = <TOption,>({ options, nameOf, color, searchPlaceholder, emptyLabel, onSelect, footer, trigger }: PickerPanelProps<TOption>) => {\n const [open, setOpen] = useState(false);\n const [filter, setFilter] = useState('');\n const container = useRef<HTMLDivElement>(null);\n const panel = useRef<HTMLDivElement>(null);\n const showSearch = options.length > searchThreshold;\n const close = () => {\n setOpen(false);\n setFilter('');\n };\n\n const outside = useMemo(() => [container, panel], []);\n useDismissOnOutsidePointer(outside, close, open);\n\n const filtered = filter ? options.filter(option => nameOf(option).toLowerCase().includes(filter.toLowerCase())) : options;\n const select = (option: TOption) => {\n onSelect(option);\n close();\n };\n\n return (\n <div ref={container} className='event-modeling-grid-event-picker' style={{ position: 'relative' }}>\n {trigger({ open, toggle: () => setOpen(previous => !previous) })}\n\n {/* Portaled above the trigger so the panel floats over the whole board instead of\n being clipped by the slice column's paint containment. */}\n <AnchoredOverlay anchorRef={container} open={open} side='above' align='right' gap={4}>\n <div ref={panel} className='event-modeling-grid-event-picker-dropdown'>\n {showSearch && (\n <input\n className='event-modeling-grid-event-picker-search'\n placeholder={searchPlaceholder}\n value={filter}\n onChange={changeEvent => setFilter(changeEvent.target.value)}\n autoFocus\n onClick={clickEvent => clickEvent.stopPropagation()}\n />\n )}\n <ul className='event-modeling-grid-event-picker-list'>\n {filtered.map((option, position) => (\n <li key={`${position}-${nameOf(option)}`}>\n <button className='event-modeling-grid-event-picker-item' style={{ borderLeft: `3px solid ${color}` }} onClick={() => select(option)}>\n {nameOf(option)}\n </button>\n </li>\n ))}\n {filtered.length === 0 && <li className='event-modeling-grid-event-picker-empty'>{emptyLabel}</li>}\n {footer?.(close)}\n </ul>\n </div>\n </AnchoredOverlay>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EventReferencePicker.css';\nimport { eventCardColors } from '../Cards';\nimport { GridTooltip } from '../Tooltips';\nimport { PickerPanel } from './PickerPanel';\n\nexport interface EventReferencePickerProps<TOption> {\n options: readonly TOption[];\n nameOf: (option: TOption) => string;\n onSelect: (option: TOption) => void;\n // Names the button that opens the picker.\n label: string;\n searchPlaceholder: string;\n emptyLabel: string;\n // When set, the picker opens from a dashed card carrying this text instead of a small plus button,\n // because picking an event is the only thing the empty row offers.\n placeholder?: string;\n}\n\n// Lets the user pick an existing event. The consumer decides which events are offered and what picking\n// one does.\nexport const EventReferencePicker = <TOption,>({ options, nameOf, onSelect, label, searchPlaceholder, emptyLabel, placeholder }: EventReferencePickerProps<TOption>) => (\n <PickerPanel\n options={options}\n nameOf={nameOf}\n color={eventCardColors.background}\n searchPlaceholder={searchPlaceholder}\n emptyLabel={emptyLabel}\n onSelect={onSelect}\n trigger={({ toggle }) => placeholder !== undefined\n ? (\n <div className='event-modeling-grid-optional-event-reference'>\n <div className='event-modeling-grid-optional-event-reference__card'>\n <span>{placeholder}</span>\n </div>\n <button\n type='button'\n className='event-modeling-grid-optional-event-reference__define-btn'\n aria-label={label}\n title={label}\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n toggle();\n }}\n >\n <i className='pi pi-plus' />\n </button>\n </div>\n )\n : (\n <GridTooltip content={label} position='top'>\n <button onClick={toggle} className='event-modeling-grid-add-button--small' aria-label={label}>\n +\n </button>\n </GridTooltip>\n )}\n />\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { CSSProperties } from 'react';\nimport { errorCardColors, eventCardColors } from '../Cards';\nimport { useEventModelMessages } from '../Messages';\nimport { PickerPanel } from '../Pickers';\nimport { GridTooltip } from '../Tooltips';\n\n// What a specification section can be given from its add button, beside the options it lists.\nexport interface SpecificationAddExtra {\n label: string;\n onChosen: () => void;\n}\n\nexport interface SpecificationAddPickerProps<TOption> {\n options: readonly TOption[];\n nameOf: (option: TOption) => string;\n onChosen: (option: TOption) => void;\n // Errors, listed after the options, set apart by the error color.\n errors?: readonly SpecificationAddExtra[];\n}\n\nconst errorStyle: CSSProperties = { borderLeft: `3px solid ${errorCardColors.background}` };\n\n// The add button of a specification section: a searchable list of what can be added, with any errors\n// listed after it.\nexport const SpecificationAddPicker = <TOption,>({ options, nameOf, onChosen, errors = [] }: SpecificationAddPickerProps<TOption>) => {\n const messages = useEventModelMessages().specifications;\n return (\n <PickerPanel\n options={options}\n nameOf={nameOf}\n color={eventCardColors.background}\n searchPlaceholder={messages.search}\n emptyLabel={messages.noItems}\n onSelect={onChosen}\n footer={close => errors.length > 0 && (\n <>\n <li className='event-modeling-grid-event-picker-separator' />\n {errors.map((error, index) => (\n <li key={index}>\n <button\n className='event-modeling-grid-event-picker-item'\n style={errorStyle}\n onClick={() => {\n error.onChosen();\n close();\n }}\n >\n {error.label}\n </button>\n </li>\n ))}\n </>\n )}\n trigger={({ toggle }) => (\n <GridTooltip content={messages.addItem} position='top'>\n <button onClick={toggle} className='event-modeling-grid-add-button--small' aria-label={messages.addItem}>\n +\n </button>\n </GridTooltip>\n )}\n />\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef } from 'react';\nimport { Card, type CardColors } from '../Cards';\nimport { useSliceReadOnly } from '../Slices';\n\nexport interface SpecificationItemCardProps {\n name: string;\n colors: CardColors;\n // Opens the item's values from the card's viewport rectangle. Offered only while the slice is editable.\n onOpen?: (host: DOMRect) => void;\n}\n\n// An item of a specification section: an event, command or read model whose values can be opened.\nexport const SpecificationItemCard = ({ name, colors, onOpen }: SpecificationItemCardProps) => {\n const readOnly = useSliceReadOnly();\n const container = useRef<HTMLDivElement>(null);\n const opens = !readOnly && !!onOpen;\n\n return (\n <div ref={container}>\n <Card\n name={name}\n backgroundColor={colors.background}\n textColor={colors.text}\n onSelected={opens ? () => {\n const host = container.current?.getBoundingClientRect();\n if (host) onOpen?.(host);\n } : undefined}\n />\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The kinds of item whose values a specification can set.\nexport enum SpecificationItemKind {\n event = 'event',\n command = 'command',\n readModel = 'readModel',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode } from 'react';\nimport { boardMetrics } from '../Layout';\nimport { rowLabelWidth } from '../Geometry';\nimport { SpecificationSection } from './SpecificationSection';\n\nexport interface SpecificationRowProps {\n headline: string;\n actions?: ReactNode;\n isLast?: boolean;\n children?: ReactNode;\n}\n\n// One of a specification's Given, When and Then sections, set in from the board's row labels.\nexport const SpecificationRow = ({ headline, actions, isLast = false, children }: SpecificationRowProps) => (\n <div className='event-modeling-grid-specification-outer-row'>\n <div className='event-modeling-grid-specification-label-gutter' style={{ width: rowLabelWidth, flexShrink: 0 }} />\n <div className={`event-modeling-grid-specification-box event-modeling-grid-specification-box--section${isLast ? ' event-modeling-grid-specification-box--last' : ''}`} style={{ flex: 1 }}>\n <SpecificationSection headline={headline} minHeight={boardMetrics.specificationSectionHeight} actions={actions}>\n {children}\n </SpecificationSection>\n </div>\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventItem } from '../Model';\n\n// The events a Given section can start from: the events produced, not merely referenced, by the slice and\n// every slice before it, each once, in order. A precondition names the event that produces it.\nexport const producedEventsUniqueById = (events: readonly EventItem[]): EventItem[] => {\n const seen = new Set<string>();\n return events.filter(event => {\n const key = event.id.toString();\n if (event.sourceEventId || seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n};\n\n// Whether a Given section offers the slice's read model as the state it starts from: whenever the slice\n// has a read model and the section does not have it yet, whatever the slice type.\nexport const offersReadModelInGiven = (hasSliceReadModel: boolean, hasGivenReadModel: boolean): boolean =>\n hasSliceReadModel && !hasGivenReadModel;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './RemovableSpecificationItem.css';\nimport type { ReactNode } from 'react';\nimport { useBoard } from '../Board';\nimport { useSliceReadOnly } from '../Slices';\n\nexport interface RemovableSpecificationItemProps {\n // The item's name, so the button says what it removes.\n name: string;\n // Offered only when supplied and the slice is editable.\n onRemoved?: () => void;\n children: ReactNode;\n}\n\n// A Given or Then item with a button that takes it back out of the specification.\nexport const RemovableSpecificationItem = ({ name, onRemoved, children }: RemovableSpecificationItemProps) => {\n const { messages } = useBoard();\n const readOnly = useSliceReadOnly();\n if (readOnly || !onRemoved) return <>{children}</>;\n\n const label = `${messages.specifications.removeItem} ${name}`;\n return (\n <div className='spec-item-removable'>\n {children}\n <button\n type='button'\n className='spec-item-remove-button'\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n onRemoved();\n }}\n aria-label={label}\n title={label}\n >\n <i className='pi pi-times' />\n </button>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useMemo, useState } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { eventCardColors, readModelCardColors } from '../Cards';\nimport type { EventItem, ReadModelItem, SliceSpecification, SpecificationGivenEvent, SpecificationReadModel } from '../Model';\nimport { SliceType } from '../Model';\nimport { useSliceReadOnly } from '../Slices';\nimport { GridTooltip } from '../Tooltips';\nimport { itemValuesOf, type ItemValues } from './itemValues';\nimport { SpecificationAddPicker } from './SpecificationAddPicker';\nimport { SpecificationItemCard } from './SpecificationItemCard';\nimport { SpecificationItemKind } from './SpecificationItemKind';\nimport { SpecificationRow } from './SpecificationRow';\nimport { offersReadModelInGiven, producedEventsUniqueById } from './specificationEvents';\nimport { RemovableSpecificationItem } from './RemovableSpecificationItem';\n\nexport interface GivenSectionProps {\n sliceId: Guid;\n sliceType: SliceType;\n specification: SliceSpecification;\n // The events of the slice and every slice before it.\n events: readonly EventItem[];\n readModel?: ReadModelItem;\n // A same-session rename of the read model placed in Given.\n renamedReadModelName?: string;\n}\n\n// A specification's Given section: the events it starts from and, where the slice has one, its read model.\n// Only a State Change adds events; the event cards show their events' current names.\nexport const GivenSection = ({ sliceId, sliceType, specification, events, readModel, renamedReadModelName }: GivenSectionProps) => {\n const { editing, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const {\n onGivenEventAdded, onGivenEventValuesSet, onGivenReadModelSet, onGivenReadModelValuesSet, onGivenEventRemoved,\n onGivenReadModelRemoved, onSpecificationItemOpened,\n } = editing;\n const [given, setGiven] = useState<SpecificationGivenEvent[]>(specification.given);\n const [givenReadModel, setGivenReadModel] = useState<SpecificationReadModel | undefined>(specification.givenReadModel);\n const [values, setValues] = useState<ItemValues>(() => ({\n ...itemValuesOf(specification.given),\n ...(specification.givenReadModel ? { [specification.givenReadModel.id.toString()]: specification.givenReadModel.values ?? {} } : {}),\n }));\n const followsIncoming = readOnly || !(onGivenEventAdded || onGivenEventValuesSet || onGivenReadModelSet || onGivenReadModelValuesSet ||\n onGivenEventRemoved || onGivenReadModelRemoved || onSpecificationItemOpened);\n const visibleGiven = followsIncoming ? specification.given : given;\n const visibleReadModel = followsIncoming ? specification.givenReadModel : givenReadModel;\n const offered = useMemo(() => producedEventsUniqueById(events), [events]);\n const eventsById = useMemo(() => new Map(offered.map(event => [event.id.toString(), event])), [offered]);\n\n const open = (itemId: Guid, kind: SpecificationItemKind, name: string, host: DOMRect, schema: EventItem['schema'] | undefined, onValuesSet: (set: Record<string, unknown>) => void) =>\n onSpecificationItemOpened?.({\n sliceId,\n specificationId: specification.id,\n itemId,\n kind,\n name,\n schema,\n values: values[itemId.toString()] ?? {},\n host,\n onValuesSet: set => {\n setValues(previous => ({ ...previous, [itemId.toString()]: set }));\n onValuesSet(set);\n },\n });\n\n const addEvent = (event: EventItem) => {\n const itemId = Guid.create();\n setGiven(previous => [...previous, { id: itemId, eventId: event.id, name: event.name, values: {} }]);\n onGivenEventAdded?.(sliceId, specification.id, itemId, event.id, event.name);\n };\n\n // Closing a read model's values, from the define button or its card, sets it as the Given state with those values.\n const setReadModel = (set: Record<string, unknown>) => {\n if (!readModel) return;\n setGivenReadModel({ id: readModel.id, readModelItemId: readModel.id, name: readModel.name, values: set });\n onGivenReadModelSet?.(sliceId, specification.id, readModel.id, readModel.name);\n onGivenReadModelValuesSet?.(sliceId, specification.id, set);\n };\n const removeEvent = (itemId: Guid) => {\n setGiven(previous => previous.filter(item => !item.id.equals(itemId)));\n onGivenEventRemoved?.(sliceId, specification.id, itemId);\n };\n const removeReadModel = () => {\n setGivenReadModel(undefined);\n onGivenReadModelRemoved?.(sliceId, specification.id);\n };\n const setEventValues = (itemId: Guid) => (set: Record<string, unknown>) =>\n onGivenEventValuesSet?.(sliceId, specification.id, itemId, set);\n\n const offersEvents = !readOnly && sliceType === SliceType.stateChange && !!onGivenEventAdded;\n const offersReadModel = !readOnly && !!readModel && !!onGivenReadModelSet && !!onSpecificationItemOpened\n && offersReadModelInGiven(true, !!visibleReadModel);\n\n // The read model shows under its current name.\n const givenReadModelName = visibleReadModel && (renamedReadModelName ?? visibleReadModel.name);\n const givenReadModelId = visibleReadModel?.id ?? visibleReadModel?.readModelItemId;\n const readModelCard = visibleReadModel && givenReadModelId && givenReadModelName !== undefined && (\n <RemovableSpecificationItem key={givenReadModelId.toString()} name={givenReadModelName} onRemoved={onGivenReadModelRemoved ? removeReadModel : undefined}>\n <SpecificationItemCard\n name={givenReadModelName}\n colors={readModelCardColors}\n onOpen={!readOnly && onSpecificationItemOpened && onGivenReadModelSet ? host => open(givenReadModelId, SpecificationItemKind.readModel, givenReadModelName, host, readModel?.schema, setReadModel) : undefined}\n />\n </RemovableSpecificationItem>\n );\n const eventCards = visibleGiven.map(item => {\n const name = eventsById.get(item.eventId.toString())?.name ?? item.name;\n return (\n <RemovableSpecificationItem key={item.id.toString()} name={name} onRemoved={onGivenEventRemoved ? () => removeEvent(item.id) : undefined}>\n <SpecificationItemCard\n name={name}\n colors={eventCardColors}\n onOpen={!readOnly && onSpecificationItemOpened && onGivenEventValuesSet ? host => open(item.id, SpecificationItemKind.event, name, host, eventsById.get(item.eventId.toString())?.schema, setEventValues(item.id)) : undefined}\n />\n </RemovableSpecificationItem>\n );\n });\n\n return (\n <SpecificationRow\n headline={messages.specifications.given}\n actions={(\n <>\n {offersEvents && (\n <SpecificationAddPicker options={offered} nameOf={event => event.name} onChosen={addEvent} />\n )}\n {offersReadModel && readModel && (\n <GridTooltip content={messages.specifications.defineReadModel} position='top'>\n <button\n onClick={clickEvent => open(readModel.id, SpecificationItemKind.readModel, readModel.name, clickEvent.currentTarget.getBoundingClientRect(), readModel.schema, setReadModel)}\n className='event-modeling-grid-add-button--small'\n aria-label={messages.specifications.defineReadModel}\n >\n <i className='pi pi-table' style={{ fontSize: 10 }} />\n </button>\n </GridTooltip>\n )}\n </>\n )}\n >\n {readModelCard}\n {eventCards}\n </SpecificationRow>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useState } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { commandCardColors, eventCardColors } from '../Cards';\nimport type { CommandItem, EventItem, SliceSpecification, SpecificationCommand } from '../Model';\nimport { SliceType } from '../Model';\nimport { useSliceReadOnly } from '../Slices';\nimport { SpecificationAddPicker } from './SpecificationAddPicker';\nimport { SpecificationItemCard } from './SpecificationItemCard';\nimport { SpecificationItemKind } from './SpecificationItemKind';\nimport { SpecificationRow } from './SpecificationRow';\n\nexport interface WhenSectionProps {\n sliceId: Guid;\n sliceType: SliceType;\n specification: SliceSpecification;\n command?: CommandItem;\n // A same-session rename of the command referenced by an existing When item.\n renamedCommandName?: string;\n // Events pinned to the When section of a State View slice.\n events?: readonly EventItem[];\n}\n\nexport const WhenSection = ({ sliceId, sliceType, specification, command, renamedCommandName, events = [] }: WhenSectionProps) => {\n const { editing, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const { onWhenCommandSet, onWhenCommandValuesSet, onSpecificationItemOpened } = editing;\n const [when, setWhen] = useState<SpecificationCommand | undefined>(specification.when);\n const [values, setValues] = useState<Record<string, unknown>>(specification.when?.values ?? {});\n const followsIncoming = readOnly || !(onWhenCommandSet || onWhenCommandValuesSet || onSpecificationItemOpened);\n const visibleWhen = followsIncoming ? specification.when : when;\n\n const setCommand = (chosen: CommandItem) => {\n const itemId = Guid.create();\n setWhen({ id: itemId, commandId: chosen.id, name: chosen.name, values: {} });\n setValues({});\n onWhenCommandSet?.(sliceId, specification.id, itemId, chosen.id, chosen.name);\n };\n\n const openCommand = (itemId: Guid, sourceCommandId: Guid | undefined, name: string, host: DOMRect, currentValues: Record<string, unknown>) =>\n onSpecificationItemOpened?.({\n sliceId,\n specificationId: specification.id,\n itemId,\n kind: SpecificationItemKind.command,\n name,\n schema: sourceCommandId && command?.id.equals(sourceCommandId) ? command.schema : undefined,\n values: currentValues,\n host,\n onValuesSet: updatedValues => {\n if (when?.id.equals(itemId)) {\n setValues(updatedValues);\n }\n onWhenCommandValuesSet?.(sliceId, specification.id, updatedValues);\n },\n });\n\n const pinnedCommand = sliceType === SliceType.stateChange ? command : undefined;\n const pinnedEvents = sliceType === SliceType.stateView ? events : [];\n const whenName = visibleWhen && (visibleWhen.commandId && command?.id.equals(visibleWhen.commandId) ? renamedCommandName ?? visibleWhen.name : visibleWhen.name);\n const canOpen = !readOnly && !!onSpecificationItemOpened && !!onWhenCommandValuesSet;\n\n return (\n <SpecificationRow\n headline={messages.specifications.when}\n actions={!readOnly && sliceType !== SliceType.stateChange && sliceType !== SliceType.stateView && !visibleWhen && command && onWhenCommandSet && (\n <SpecificationAddPicker options={[command]} nameOf={item => item.name} onChosen={setCommand} />\n )}\n >\n {visibleWhen && whenName && (\n <SpecificationItemCard\n key={visibleWhen.id.toString()}\n name={whenName}\n colors={commandCardColors}\n onOpen={canOpen ? host => openCommand(visibleWhen.id, visibleWhen.commandId, whenName, host, values) : undefined}\n />\n )}\n {pinnedCommand && (\n <SpecificationItemCard\n key={pinnedCommand.id.toString()}\n name={pinnedCommand.name}\n colors={commandCardColors}\n onOpen={canOpen ? host => openCommand(pinnedCommand.id, pinnedCommand.id, pinnedCommand.name, host, values) : undefined}\n />\n )}\n {pinnedEvents.map(event => (\n <SpecificationItemCard key={event.id.toString()} name={event.name} colors={eventCardColors} />\n ))}\n </SpecificationRow>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\nimport { type CommandItem, type EventItem, SpecificationErrorRuleKind, type SpecificationErrorRuleReference } from '../Model';\n\n// A rule or constraint a specification's Then section can expect to be broken.\nexport interface RuleErrorOption {\n // Stored on the error, so it survives a rename of the rule or constraint.\n reference: SpecificationErrorRuleReference;\n label: string;\n}\n\n// A rule's kind, such as notEmpty, as a readable label: Not empty.\nexport const humanizeRuleType = (ruleType: string): string => {\n if (!ruleType) return '';\n const spaced = ruleType.replace(/([A-Z])/g, ' $1').trim();\n return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();\n};\n\nconst referenceTo = (kind: SpecificationErrorRuleKind, itemId: Guid, propertyName = '', ruleType = ''): SpecificationErrorRuleReference =>\n ({ kind, itemId, propertyName, ruleType });\n\nconst commandRuleOptions = (command: CommandItem | undefined): RuleErrorOption[] =>\n command\n ? (command.rules ?? []).flatMap(propertyRules => propertyRules.rules.map(rule => ({\n reference: referenceTo(SpecificationErrorRuleKind.commandValidationRule, command.id, propertyRules.propertyName, rule.ruleType),\n label: `${propertyRules.propertyName}: ${humanizeRuleType(rule.ruleType)}`,\n })))\n : [];\n\n// Every rule and constraint defined on a slice: one per command validation rule and one per event\n// constraint.\nexport const ruleErrorOptions = (command: CommandItem | undefined, events: readonly EventItem[]): RuleErrorOption[] => [\n ...commandRuleOptions(command),\n ...events.flatMap(event => [\n ...(event.constraints?.unique ? [{\n reference: referenceTo(SpecificationErrorRuleKind.eventUniqueConstraint, event.id),\n label: event.constraints.unique.name,\n }] : []),\n ...(event.constraints?.uniqueEventType ? [{\n reference: referenceTo(SpecificationErrorRuleKind.eventUniqueEventTypeConstraint, event.id),\n label: event.constraints.uniqueEventType.name,\n }] : []),\n ]),\n];\n\n// What an error expecting a rule or constraint is called now, so a renamed constraint shows under its\n// current name. Nothing when the constraint no longer exists.\nexport const ruleErrorLabel = (reference: SpecificationErrorRuleReference, events: readonly EventItem[]): string | undefined => {\n switch (reference.kind) {\n case SpecificationErrorRuleKind.commandValidationRule:\n return `${reference.propertyName}: ${humanizeRuleType(reference.ruleType)}`;\n case SpecificationErrorRuleKind.eventUniqueConstraint:\n return events.find(event => event.id.equals(reference.itemId))?.constraints?.unique?.name;\n case SpecificationErrorRuleKind.eventUniqueEventTypeConstraint:\n return events.find(event => event.id.equals(reference.itemId))?.constraints?.uniqueEventType?.name;\n default:\n return undefined;\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useEffect, useState } from 'react';\nimport { Card, CardNameInput, errorCardColors } from '../Cards';\nimport { useSliceReadOnly } from '../Slices';\n\nexport interface SpecificationErrorCardProps {\n name: string;\n // Offered only when supplied and the slice is editable; the card then renames in place with a\n // double-click.\n onRenamed?: (name: string) => void;\n}\n\n// An error a specification expects, described in free text.\nexport const SpecificationErrorCard = ({ name, onRenamed }: SpecificationErrorCardProps) => {\n const readOnly = useSliceReadOnly();\n const [editing, setEditing] = useState(false);\n const [shownName, setShownName] = useState(name);\n\n useEffect(() => setShownName(name), [name]);\n\n if (editing) {\n // An empty or unchanged name ends the edit without renaming; the name shows as typed until the\n // error's name next changes.\n const commit = () => {\n const trimmed = shownName.trim();\n setEditing(false);\n if (!trimmed || trimmed === name) return;\n onRenamed?.(trimmed);\n };\n return (\n <CardNameInput\n value={shownName}\n backgroundColor={errorCardColors.background}\n textColor={errorCardColors.text}\n onChange={setShownName}\n onCommit={commit}\n onCancel={() => {\n setShownName(name);\n setEditing(false);\n }}\n />\n );\n }\n\n return (\n <Card\n name={shownName}\n backgroundColor={errorCardColors.background}\n textColor={errorCardColors.text}\n onStartEdit={onRenamed ? () => setEditing(true) : undefined}\n disabled={readOnly}\n />\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useMemo, useState, type ReactNode } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { Card, errorCardColors, eventCardColors, readModelCardColors } from '../Cards';\nimport type { CommandItem, EventItem, ReadModelItem, SliceSpecification, SpecificationError, SpecificationErrorRuleReference, SpecificationThenEvent } from '../Model';\nimport { SliceType } from '../Model';\nimport { useSliceReadOnly } from '../Slices';\nimport { GridTooltip } from '../Tooltips';\nimport { itemValuesOf, type ItemValues } from './itemValues';\nimport { ruleErrorLabel, ruleErrorOptions } from './ruleErrors';\nimport { SpecificationAddPicker } from './SpecificationAddPicker';\nimport { SpecificationErrorCard } from './SpecificationErrorCard';\nimport { SpecificationItemCard } from './SpecificationItemCard';\nimport { SpecificationItemKind } from './SpecificationItemKind';\nimport { SpecificationRow } from './SpecificationRow';\nimport { RemovableSpecificationItem } from './RemovableSpecificationItem';\n\nexport interface ThenSectionProps {\n sliceId: Guid;\n sliceType: SliceType;\n specification: SliceSpecification;\n events: readonly EventItem[];\n command?: CommandItem;\n readModel?: ReadModelItem;\n // Names changed during this session, keyed by the referenced event's id.\n renamedEventNames?: Readonly<Record<string, string>>;\n // What the consumer adds after the section's own cards, for expectations the board does not draw itself.\n extra?: ReactNode;\n}\n\nexport const ThenSection = ({ sliceId, sliceType, specification, events, command, readModel, renamedEventNames = {}, extra }: ThenSectionProps) => {\n const { editing, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const {\n onThenEventAdded, onThenEventValuesSet, onThenErrorAdded, onThenRuleErrorAdded, onThenErrorRenamed,\n onThenEventRemoved, onThenErrorRemoved, onThenReadModelValuesSet, onSpecificationItemOpened,\n } = editing;\n const [thenEvents, setThenEvents] = useState<SpecificationThenEvent[]>(specification.thenEvents);\n const [thenErrors, setThenErrors] = useState<SpecificationError[]>(specification.thenErrors);\n const [values, setValues] = useState<ItemValues>(() => itemValuesOf(specification.thenEvents));\n const [readModelValues, setReadModelValues] = useState<Record<string, unknown>>({});\n const followsIncoming = readOnly || !(onThenEventAdded || onThenEventValuesSet || onThenErrorAdded ||\n onThenRuleErrorAdded || onThenErrorRenamed || onThenEventRemoved || onThenErrorRemoved || onThenReadModelValuesSet ||\n onSpecificationItemOpened);\n const visibleEvents = followsIncoming ? specification.thenEvents : thenEvents;\n const visibleErrors = followsIncoming ? specification.thenErrors : thenErrors;\n const eventsById = useMemo(() => new Map(events.map(event => [event.id.toString(), event])), [events]);\n const rules = useMemo(() => ruleErrorOptions(command, events), [command, events]);\n const canAdd = !readOnly && sliceType !== SliceType.stateView;\n\n const addEvent = (event: EventItem) => {\n const itemId = Guid.create();\n setThenEvents(previous => [...previous, { id: itemId, eventId: event.id, name: event.name, values: {} }]);\n onThenEventAdded?.(sliceId, specification.id, itemId, event.id, event.name);\n };\n const addError = () => {\n const itemId = Guid.create();\n const name = messages.specifications.error;\n setThenErrors(previous => [...previous, { id: itemId, name }]);\n onThenErrorAdded?.(sliceId, specification.id, itemId, name);\n };\n const addRuleError = (reference: SpecificationErrorRuleReference) => {\n const itemId = Guid.create();\n setThenErrors(previous => [...previous, { id: itemId, name: '', reference }]);\n onThenRuleErrorAdded?.(sliceId, specification.id, itemId, reference);\n };\n const renameError = (itemId: Guid, name: string) => {\n setThenErrors(previous => previous.map(error => error.id.equals(itemId) ? { ...error, name } : error));\n onThenErrorRenamed?.(sliceId, specification.id, itemId, name);\n };\n\n const removeEvent = (itemId: Guid) => {\n setThenEvents(previous => previous.filter(event => !event.id.equals(itemId)));\n onThenEventRemoved?.(sliceId, specification.id, itemId);\n };\n const removeError = (itemId: Guid) => {\n setThenErrors(previous => previous.filter(error => !error.id.equals(itemId)));\n onThenErrorRemoved?.(sliceId, specification.id, itemId);\n };\n\n const eventCards = visibleEvents.map(item => {\n const source = eventsById.get(item.eventId.toString());\n const name = renamedEventNames[item.eventId.toString()] ?? item.name;\n return (\n <RemovableSpecificationItem key={item.id.toString()} name={name} onRemoved={onThenEventRemoved ? () => removeEvent(item.id) : undefined}>\n <SpecificationItemCard\n name={name}\n colors={eventCardColors}\n onOpen={!readOnly && onSpecificationItemOpened && onThenEventValuesSet ? host => onSpecificationItemOpened({\n sliceId, specificationId: specification.id, itemId: item.id,\n kind: SpecificationItemKind.event, name, schema: source?.schema,\n values: values[item.id.toString()] ?? {}, host,\n onValuesSet: updatedValues => {\n setValues(previous => ({ ...previous, [item.id.toString()]: updatedValues }));\n onThenEventValuesSet?.(sliceId, specification.id, item.id, updatedValues);\n },\n }) : undefined}\n />\n </RemovableSpecificationItem>\n );\n });\n const errorCards = visibleErrors.map(item => {\n const name = item.reference ? ruleErrorLabel(item.reference, events) ?? messages.specifications.missingRule : item.name;\n return (\n <RemovableSpecificationItem key={item.id.toString()} name={name} onRemoved={onThenErrorRemoved ? () => removeError(item.id) : undefined}>\n {item.reference\n ? <Card name={name} backgroundColor={errorCardColors.background} textColor={errorCardColors.text} />\n : <SpecificationErrorCard name={item.name} onRenamed={!readOnly && onThenErrorRenamed ? newName => renameError(item.id, newName) : undefined} />}\n </RemovableSpecificationItem>\n );\n });\n\n const errorOptions = [\n ...(onThenErrorAdded ? [{ label: messages.specifications.addError, onChosen: addError }] : []),\n ...(onThenRuleErrorAdded ? rules.map(rule => ({ label: rule.label, onChosen: () => addRuleError(rule.reference) })) : []),\n ];\n const actions = canAdd && (sliceType === SliceType.stateChange\n ? (onThenEventAdded || errorOptions.length > 0) && <SpecificationAddPicker options={onThenEventAdded ? events : []} nameOf={event => event.name} onChosen={addEvent} errors={errorOptions} />\n : onThenErrorAdded && (\n <GridTooltip content={messages.specifications.addItem} position='top'>\n <button onClick={addError} className='event-modeling-grid-add-button--small' aria-label={messages.specifications.addItem}>+</button>\n </GridTooltip>\n ));\n\n return (\n <SpecificationRow headline={messages.specifications.then} actions={actions} isLast>\n {eventCards}\n {errorCards}\n {sliceType === SliceType.stateView && readModel && (\n <SpecificationItemCard\n key={readModel.id.toString()}\n name={readModel.name}\n colors={readModelCardColors}\n onOpen={!readOnly && onSpecificationItemOpened ? host => onSpecificationItemOpened({\n sliceId, specificationId: specification.id, itemId: readModel.id,\n kind: SpecificationItemKind.readModel, name: readModel.name,\n schema: readModel.schema, values: readModelValues, host,\n onValuesSet: set => {\n setReadModelValues(set);\n onThenReadModelValuesSet?.(sliceId, specification.id, readModel.id, readModel.name, set);\n },\n }) : undefined}\n />\n )}\n {extra}\n </SpecificationRow>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceConnections } from '../Connections';\nimport type { Slice } from '../Model';\nimport { useEventModelPresentation } from '../Presentation';\n\nexport interface SliceLinesProps {\n slice: Slice;\n collapsed: boolean;\n showDetails: boolean;\n}\n\n// The curved lines a slice's cards are connected with when the board is drawn with lines rather than\n// arrows. A host that draws its own overlay over the slice body supplies it through the slots instead.\nexport const SliceLines = ({ slice, collapsed, showDetails }: SliceLinesProps) => {\n const { visualizationMode } = useEventModelPresentation();\n if (visualizationMode !== 'fillLines' || collapsed) return null;\n // Anything that moves a card changes the key, so the lines are measured again.\n const recomputeKey = [\n slice.id.toString(),\n slice.events.map(event => event.id.toString()).join(','),\n slice.actors.map(actor => `${actor.id}:${actor.elements.length}`).join(','),\n showDetails ? 'details' : '',\n slice.automationTrigger?.type ?? '',\n slice.command?.id.toString() ?? '',\n slice.readModel?.id.toString() ?? '',\n ].join(';');\n return <SliceConnections sliceType={slice.sliceType} recomputeKey={recomputeKey} />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { type EventItem, type Slice, SliceType } from '../Model';\nimport { BoardInteractionProvider } from '../Board';\nimport { boardMetrics } from '../Layout';\nimport { RowType } from '../Rows';\nimport { SliceColumn, SliceHeader, SliceRows } from '../Slices';\nimport { GivenSection, SpecificationCollection, specificationRunState, ThenSection, WhenSection } from '../Specifications';\nimport { ChatCell, SystemCell, SliceInteraction, SliceEvents, UiCell } from '../Rows';\nimport type { Feature, Module, ModuleCollection } from '../Model';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridSliceHeaderControls } from './CollectionGridSliceHeaderControls';\nimport { collectionContentHeight } from './collectionGridLayout';\nimport { SliceLines } from './SliceLines';\nimport { areDetailsVisible, areSliceDetailsVisibleForDetailLevel, useEventModelPresentation } from '../Presentation';\n\nexport interface CollectionGridSliceProps {\n slice: Slice;\n collapsed: boolean;\n moduleId: Module['id'];\n featureId: Feature['id'];\n collection: ModuleCollection;\n rows: RowType[];\n heights: Record<RowType, number>;\n priorEvents: EventItem[];\n // The events produced after this slice in its collection; a State View projecting one of them is out of order.\n followingEvents?: EventItem[];\n externalEvents: EventItem[];\n slots?: CollectionGridSlots;\n controls?: CollectionGridSliceHeaderControls;\n}\n\nexport const CollectionGridSlice = ({ slice, collapsed, moduleId, featureId, collection, rows, heights, priorEvents, followingEvents = [], externalEvents, slots, controls }: CollectionGridSliceProps) => {\n const { detailLevel, detailsVisibility } = useEventModelPresentation();\n // The same per-slice rule Studio's own cells applied: any enclosing scope, or the board as a whole, turns details on.\n const showDetails = areSliceDetailsVisibleForDetailLevel(detailLevel,\n areDetailsVisible(detailsVisibility, moduleId.toString(), featureId.toString(), slice.id.toString()));\n const column = <SliceColumn featureId={featureId} slice={slice} eventCount={slice.events.length} collapsed={collapsed}\n isDragging={controls?.isDragging} onSliceDragStart={controls?.onSliceDragStart}\n collapsedWidth={boardMetrics.collapsedSliceWidth}\n header={slots?.sliceHeader?.(slice, controls ?? { collapsed, sliceCollapsed: slice.collapsed, isDragging: false }) ??\n <BoardInteractionProvider editing={{\n onSliceAdded: controls?.onAddSlice ? (_id, sliceType) => controls.onAddSlice?.(sliceType, slice.id) : undefined,\n onSliceOpenStateSet: controls?.onToggleCollapse ? () => controls.onToggleCollapse?.() : undefined,\n onSliceRenamed: controls?.onRenamed ? (_id, name) => controls.onRenamed?.(name) : undefined,\n }}>\n <SliceHeader slice={slice} height={boardMetrics.headerHeight} collapsed={collapsed} onToggleCollapse={controls?.onToggleCollapse} />\n </BoardInteractionProvider>} headerHeight={boardMetrics.headerHeight}\n body={inView => inView ? <>\n {slots?.sliceBodyOverlay ? slots.sliceBodyOverlay(slice, collapsed) : <SliceLines slice={slice} collapsed={collapsed} showDetails={showDetails} />}\n <SliceRows sliceType={slice.sliceType} contentRows={rows} rowHeights={heights}\n actors={collection.actors} renderCell={cell => {\n const shared = { conn: cell.conn, rowHeight: cell.rowHeight, collapsed };\n const detailed = { ...shared, showDetails };\n if (slots?.sliceCell) {\n const supplied = slots.sliceCell(slice, cell);\n if (supplied !== undefined) return supplied;\n }\n switch (cell.rowType) {\n case RowType.UI: {\n const prototype = slice.actors.find(actor => actor.id === cell.actor?.id);\n return <UiCell {...shared} actorId={cell.actor?.id ?? ''}\n elements={prototype?.elements ?? []}\n layout={prototype?.layout} windowSize={prototype ? { width: prototype.windowWidth, height: prototype.windowHeight } : undefined} />;\n }\n // The system acts in automations and translators; a state change or view only passes through its row.\n case RowType.System: return <SystemCell {...shared} sliceType={slice.sliceType}\n isSystemSlice={!!cell.actor && (slice.sliceType === SliceType.automation || slice.sliceType === SliceType.translator)}\n triggerType={slice.automationTrigger?.type} />;\n case RowType.Chat: return <ChatCell {...shared} sliceId={slice.id} />;\n case RowType.Interaction: return <SliceInteraction {...detailed} slice={slice} externalEventOptions={externalEvents} />;\n case RowType.Events: return <SliceEvents {...detailed} slice={slice} priorEvents={priorEvents} followingEvents={followingEvents} />;\n }\n }} /></> : <div style={{ height: collectionContentHeight(collection, rows, heights) }} aria-hidden='true' />}\n specifications={(inView, width) => slots?.specifications\n ? slots.specifications(slice, inView, width, controls?.sliceCollapsed ?? slice.collapsed)\n : (inView && <SpecificationCollection sliceId={slice.id} width={width} collapsed={controls?.sliceCollapsed ?? slice.collapsed}\n specifications={slice.specifications}\n runInfoFor={specification => ({ state: specificationRunState(specification.lastRunOutcome, false),\n message: specification.lastRunMessage ?? '' })}\n renderRows={specification => <>\n <GivenSection sliceId={slice.id} sliceType={slice.sliceType} specification={specification}\n events={[...priorEvents, ...slice.events]} readModel={slice.readModel}\n renamedReadModelName={slice.readModel?.name} />\n <WhenSection sliceId={slice.id} sliceType={slice.sliceType} specification={specification}\n command={slice.command} renamedCommandName={slice.command?.name} events={slice.events} />\n <ThenSection sliceId={slice.id} sliceType={slice.sliceType} specification={specification}\n events={slice.events} command={slice.command} readModel={slice.readModel}\n renamedEventNames={Object.fromEntries(slice.events.map(event => [event.id.toString(), event.name]))} />\n </>} />)} />;\n return slots?.sliceBoundary ? slots.sliceBoundary(slice, column) : column;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ScreenTemplate } from '../Model';\nimport './CollectionGridTemplate.css';\n\nexport interface CollectionGridTemplateProps {\n template: ScreenTemplate;\n width: number;\n}\n\nexport const CollectionGridTemplate = ({ template, width }: CollectionGridTemplateProps) =>\n <div className='event-modeling-collection-grid-template' style={{ width }}>\n <div className='event-modeling-collection-grid-template__bar'>\n <i className='pi pi-window-maximize' aria-hidden='true' />\n <span className='event-modeling-collection-grid-template__name'>{template.name}</span>\n </div>\n </div>;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useRef, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { FeatureGridSurface, type FeaturesAreaProps } from '../Features';\nimport { SlicesArea, duplicateSliceName, type SlicesAreaHandle } from '../Slices';\nimport { SliceType, type EventItem, type Feature, type ModuleCollection, type Slice } from '../Model';\nimport { RowType } from '../Rows';\nimport { CollectionGridSlice } from './CollectionGridSlice';\nimport { CollectionGridTemplate } from './CollectionGridTemplate';\nimport { featureWidth } from './collectionGridLayout';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridEditor } from './CollectionGridEditor';\nimport type { CollectionGridFeatureHeaderControls } from './CollectionGridFeatureHeaderControls';\n\nexport interface CollectionGridFeatureColumnProps {\n feature: Feature;\n options: Parameters<FeaturesAreaProps<Feature>['renderColumn']>[1];\n moduleId: Guid;\n collection: ModuleCollection;\n rows: RowType[];\n heights: Record<RowType, number>;\n slices: Slice[];\n externalEvents: EventItem[];\n slots?: CollectionGridSlots;\n editor: CollectionGridEditor;\n onSliceArea: (handle: SlicesAreaHandle<Slice> | null) => void;\n sliceAreas: ReadonlyMap<string, SlicesAreaHandle<Slice>>;\n renderHeader: (controls: CollectionGridFeatureHeaderControls) => ReactNode;\n onSlicesChanged?: (slices: Slice[]) => void;\n}\n\nexport const CollectionGridFeatureColumn = ({ feature, options, moduleId, collection, rows, heights,\n slices, externalEvents, slots, editor, onSliceArea, sliceAreas, renderHeader, onSlicesChanged }: CollectionGridFeatureColumnProps) => {\n const areaRef = useRef<SlicesAreaHandle<Slice>>(null);\n const priorEvents = (sliceId: Guid) => slices.slice(0, slices.findIndex(slice => slice.id.equals(sliceId)))\n .filter(slice => slice.sliceType === SliceType.stateChange).flatMap(slice => slice.events);\n const followingEvents = (sliceId: Guid) => slices.slice(slices.findIndex(slice => slice.id.equals(sliceId)) + 1)\n .filter(slice => slice.sliceType === SliceType.stateChange).flatMap(slice => slice.events);\n const persistMove = useCallback(async (slice: Slice, targetFeatureId: Guid, targetIndex: number): Promise<boolean> => {\n const target = sliceAreas.get(targetFeatureId.toString());\n target?.moveIn(slice, targetIndex);\n try {\n const succeeded = await editor.onMoveSlice?.(slice, feature.id, targetFeatureId, targetIndex) ?? false;\n target?.completeMoveIn(slice.id, succeeded);\n return succeeded;\n } catch {\n target?.completeMoveIn(slice.id, false);\n return false;\n }\n }, [editor.onMoveSlice, feature.id, sliceAreas]);\n const moveToFeature = useCallback((slice: Slice, targetFeatureId: Guid) => {\n if (!editor.onMoveSlice || targetFeatureId.equals(feature.id) || !areaRef.current?.moveOut(slice.id)) return;\n void persistMove(slice, targetFeatureId, Number.MAX_SAFE_INTEGER)\n .then(succeeded => areaRef.current?.completeMoveOut(slice.id, succeeded));\n }, [editor.onMoveSlice, feature.id, persistMove]);\n const headerControls = {\n ...options, dragging: false,\n onAddSubFeature: options.addSubFeature,\n onAddSlice: undefined,\n };\n return <FeatureGridSurface featureId={feature.id} moduleId={moduleId} enabled={feature.enabled}\n collapsed={options.collapsed} rowCollapsed={feature.rowCollapsed} width={featureWidth(feature)}\n headerVisibility={options.headerVisibility}\n header={renderHeader(headerControls)}\n screenTemplate={slots?.featureTemplate\n ? slots.featureTemplate(feature, featureWidth(feature))\n : feature.screenTemplate && <CollectionGridTemplate template={feature.screenTemplate} width={featureWidth(feature)} />}\n slices={<SlicesArea ref={handle => { areaRef.current = handle; onSliceArea(handle); }}\n initialSlices={feature.slices} moduleId={moduleId} featureId={feature.id}\n featureCollapsed={options.collapsed} hideEmptyPlaceholder={options.headerVisibility === 'hidden'}\n createSlice={slice => slice} onSlicesChanged={onSlicesChanged}\n onAddSlice={editor.onAddSlice ? (slice, afterSliceId) => editor.onAddSlice?.(feature.id, slice, afterSliceId) ?? Promise.resolve(undefined) : undefined}\n onReorderSlices={editor.onReorderSlices ? sliceIds => editor.onReorderSlices?.(feature.id, sliceIds) ?? Promise.resolve(false) : undefined}\n onMoveSlice={editor.onMoveSlice ? persistMove : undefined}\n validateSliceDrop={editor.validateSliceDrop}\n renderSlice={(slice, sliceOptions) => <CollectionGridSlice slice={slice} collapsed={sliceOptions.collapsed}\n moduleId={moduleId} featureId={feature.id} collection={collection} rows={rows} heights={heights}\n priorEvents={priorEvents(slice.id)} followingEvents={followingEvents(slice.id)} externalEvents={externalEvents} slots={slots}\n controls={{ collapsed: sliceOptions.collapsed, sliceCollapsed: sliceOptions.sliceCollapsed,\n isDragging: sliceOptions.isDragging, onSliceDragStart: sliceOptions.onSliceDragStart,\n onAddSlice: editor.onAddSlice ? sliceOptions.addSlice : undefined,\n onToggleCollapse: editor.onSliceCollapseChanged ? () => {\n areaRef.current?.updateSlices(previous => previous.map(candidate => candidate.id.equals(slice.id)\n ? { ...candidate, collapsed: !sliceOptions.sliceCollapsed } : candidate));\n editor.onSliceCollapseChanged?.(feature.id, slice.id, !sliceOptions.sliceCollapsed);\n } : undefined,\n onRenamed: editor.onSliceRenamed ? name => {\n areaRef.current?.updateSlices(previous => previous.map(candidate => candidate.id.equals(slice.id)\n ? { ...candidate, name } : candidate));\n editor.onSliceRenamed?.(feature.id, slice.id, name);\n } : undefined,\n onMoveToFeature: editor.onMoveSlice ? targetId => moveToFeature(slice, targetId) : undefined,\n onDuplicated: editor.onSliceDuplicated ? newId => {\n editor.onSliceDuplicated?.(feature.id, slice.id, newId);\n areaRef.current?.addProjectedSlice({ ...slice, id: newId,\n name: duplicateSliceName(feature.slices.map(candidate => candidate.name), slice.name),\n specifications: [], commentCount: 0, collapsed: false }, slice.id);\n } : undefined,\n }} />}\n />}\n />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useImperativeHandle, useRef, type Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { FeaturesArea, FeatureHeader, type FeaturesAreaHandle } from '../Features';\nimport type { SliceNames, SlicesAreaHandle } from '../Slices';\nimport { boardMetrics } from '../Layout';\nimport { SliceType, type Feature, type ModuleCollection, type Slice } from '../Model';\nimport { RowType } from '../Rows';\nimport { collectionSlices, featureWidth } from './collectionGridLayout';\nimport { CollectionGridFeatureColumn } from './CollectionGridFeatureColumn';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridEditor } from './CollectionGridEditor';\nimport type { CollectionGridFeatureHeaderControls } from './CollectionGridFeatureHeaderControls';\n\nexport interface CollectionGridFeatureProps {\n ref?: Ref<FeaturesAreaHandle<Feature>>;\n moduleId: Guid;\n collection: ModuleCollection;\n features: Feature[];\n rows: RowType[];\n heights: Record<RowType, number>;\n slots?: CollectionGridSlots;\n editor: CollectionGridEditor;\n onFeaturesChanged?: (features: Feature[]) => void;\n}\n\nexport const CollectionGridFeature = ({ ref, moduleId, collection, features, rows, heights, slots, editor,\n onFeaturesChanged }: CollectionGridFeatureProps) => {\n const sliceAreas = useRef(new Map<string, SlicesAreaHandle<Slice>>());\n const areaRef = useRef<FeaturesAreaHandle<Feature>>(null);\n useImperativeHandle(ref, () => ({\n addFeature: name => areaRef.current?.addFeature(name) ?? Promise.resolve(),\n addSubFeature: (parentId, name) => areaRef.current?.addSubFeature(parentId, name) ?? Promise.resolve(),\n updateFeature: (id, update) => areaRef.current?.updateFeature(id, update),\n }), []);\n const slices = collectionSlices(collection).map(entry => entry.slice);\n const externalEvents = collectionSlices({ ...collection,\n modules: collection.modules.filter(module => !module.id.equals(moduleId)) })\n .flatMap(entry => entry.slice.events);\n const addSlice = (featureId: Guid) => editor.onAddSlice\n ? (sliceType: SliceType, names?: SliceNames) => sliceAreas.current.get(featureId.toString())?.addSlice(sliceType, undefined, names)\n : undefined;\n const renderHeader = (feature: Feature, controls: CollectionGridFeatureHeaderControls) =>\n slots?.featureHeader?.(feature, controls) ?? <FeatureHeader\n featureId={feature.id} name={feature.name} height={boardMetrics.headerHeight}\n collapsed={controls.collapsed} dragging={controls.dragging} onDragStart={controls.onDragStart}\n onToggleCollapse={controls.onToggleCollapse}\n onRenamed={controls.onRenamed ? (_id, name) => controls.onRenamed?.(name) : undefined}\n onAddSubFeature={controls.onAddSubFeature ? () => controls.onAddSubFeature?.() : undefined}\n onAddSlice={controls.onAddSlice} />;\n return <FeaturesArea ref={areaRef} initialFeatures={features} moduleId={moduleId} widthOf={featureWidth}\n isCollapsed={feature => feature.collapsed} occupiesColumn={feature => featureWidth(feature) > 0}\n onFeaturesChanged={onFeaturesChanged}\n renderFeatureBoundary={slots?.featureBoundary}\n onAddFeature={editor.onAddFeature ? (name, parentId) => editor.onAddFeature?.(moduleId, name, parentId) ?? Promise.resolve(undefined) : undefined}\n onRenameFeature={editor.onRenameFeature}\n onCollapseChanged={editor.onFeatureCollapseChanged}\n onFeaturesReordered={editor.onFeaturesReordered ? changed => editor.onFeaturesReordered?.(moduleId, changed) : undefined}\n renderHeader={(feature, options) => renderHeader(feature, {\n ...options,\n onDragStart: options.onDragStart ? start => options.onDragStart?.(feature.id, feature.name, start) : undefined,\n onAddSubFeature: options.addSubFeature,\n onAddSlice: addSlice(feature.id),\n })}\n renderColumn={(feature, options) => <CollectionGridFeatureColumn\n feature={feature} options={options} moduleId={moduleId} collection={collection}\n rows={rows} heights={heights} slices={slices} externalEvents={externalEvents}\n slots={slots} editor={editor} sliceAreas={sliceAreas.current}\n onSlicesChanged={changed => areaRef.current?.updateFeature(feature.id, previous => ({ ...previous, slices: changed }))}\n onSliceArea={handle => {\n if (handle) sliceAreas.current.set(feature.id.toString(), handle);\n else sliceAreas.current.delete(feature.id.toString());\n }}\n renderHeader={controls => renderHeader(feature, { ...controls, onAddSlice: addSlice(feature.id) })}\n />}\n />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { ModuleHeader, ModulePlaceholder, ModuleSurface } from '../Modules';\nimport { boardMetrics } from '../Layout';\nimport { useInViewport } from '../Viewport';\nimport type { Feature, Module, ModuleCollection } from '../Model';\nimport { RowType } from '../Rows';\nimport { CollectionGridFeature } from './CollectionGridFeature';\nimport { collectionContentHeight, collectionModuleWidth, featureColumns, featureWidth } from './collectionGridLayout';\nimport { CollectionGridTemplate } from './CollectionGridTemplate';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridEditor } from './CollectionGridEditor';\nimport type { FeaturesAreaHandle } from '../Features';\nimport type { HeaderDragStart } from '../HeaderDragging';\n\nexport interface CollectionGridModuleProps {\n module: Module;\n liveFeatures?: Feature[];\n index: number;\n collection: ModuleCollection;\n rows: RowType[];\n heights: Record<RowType, number>;\n slots?: CollectionGridSlots;\n editor: CollectionGridEditor;\n dragging?: boolean;\n onDragStart?: (start: HeaderDragStart) => void;\n onAddModule?: () => void;\n onToggleCollapse?: () => void;\n onRenamed?: (name: string) => void;\n onFeaturesChanged?: (moduleId: Guid, features: Feature[]) => void;\n}\n\nexport const CollectionGridModule = ({ module, liveFeatures, index, collection, rows, heights, slots, editor, dragging,\n onDragStart, onAddModule, onToggleCollapse, onRenamed, onFeaturesChanged }: CollectionGridModuleProps) => {\n const frameRef = useRef<HTMLDivElement>(null);\n const featuresRef = useRef<FeaturesAreaHandle<Feature>>(null);\n const onAddFeature = editor.onAddFeature ? (name?: string) => { void featuresRef.current?.addFeature(name); } : undefined;\n const inView = useInViewport(frameRef, undefined, 'heavy');\n const width = collectionModuleWidth(module.name, liveFeatures ?? module.features);\n const surface = <ModuleSurface moduleId={module.id} collectionId={collection.id} index={index} width={width}\n collapsed={module.collapsed} dragging={dragging} frameRef={frameRef}\n header={slots?.moduleHeader?.(module, { onDragStart, onAddModule, onAddFeature, onToggleCollapse, onRenamed }) ??\n <ModuleHeader moduleId={module.id} name={module.name}\n height={boardMetrics.headerHeight} collapsed={module.collapsed} onAddModule={onAddModule}\n onToggleCollapse={onToggleCollapse} onRenamed={onRenamed ? (_id, name) => onRenamed(name) : undefined}\n onDragStart={onDragStart} onAddFeature={onAddFeature} />}\n template={slots?.moduleTemplate\n ? slots.moduleTemplate(module, width)\n : module.screenTemplate && <CollectionGridTemplate template={module.screenTemplate} width={width} />}\n content={inView ? <CollectionGridFeature ref={featuresRef} moduleId={module.id} collection={collection} features={module.features}\n rows={rows} heights={heights} slots={slots} editor={editor}\n onFeaturesChanged={features => onFeaturesChanged?.(module.id, features)} />\n : <ModulePlaceholder width={width} height={collectionContentHeight(collection, rows, heights)}\n featureWidths={featureColumns(liveFeatures ?? module.features).map(featureWidth).filter(value => value > 0)} />} />;\n return slots?.moduleBoundary ? slots.moduleBoundary(module, surface) : surface;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Feature, Module } from '../Model';\n\n// What a read-only board has collapsed or expanded itself, by the id of the module, feature or slice.\nexport type LocalCollapses = ReadonlyMap<string, boolean>;\n\nconst collapsedOf = (collapses: LocalCollapses, item: { id: { toString(): string }; collapsed: boolean }) =>\n collapses.get(item.id.toString()) ?? item.collapsed;\n\nconst withFeatureCollapses = (collapses: LocalCollapses, feature: Feature): Feature => ({\n ...feature,\n collapsed: collapsedOf(collapses, feature),\n slices: feature.slices.map(slice => ({ ...slice, collapsed: collapsedOf(collapses, slice) })),\n subFeatures: feature.subFeatures.map(child => withFeatureCollapses(collapses, child)),\n});\n\n// The modules as a read-only board draws them: as the document has them, with what the board has\n// collapsed or expanded itself on top. Applied to every document that arrives, so a choice survives\n// the document changing.\nexport function withLocalCollapses(modules: readonly Module[], collapses: LocalCollapses): Module[] {\n if (collapses.size === 0) return [...modules];\n return modules.map(module => ({\n ...module,\n collapsed: collapsedOf(collapses, module),\n features: module.features.map(feature => withFeatureCollapses(collapses, feature)),\n }));\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { BoardReadOnlyContext } from '../Board/BoardReadOnlyContext';\nimport { computeSliceConnections, SliceConnectionsProvider } from '../Connections';\nimport { ModulesArea } from '../Modules';\nimport { RowLabelsColumn, type RowLabelsColumnProps } from '../RowLabels';\nimport type { Feature, Module, ModuleCollection } from '../Model';\nimport { CollectionMoveHandle } from './CollectionMoveHandle';\nimport { CollectionGridModule } from './CollectionGridModule';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridEditor } from './CollectionGridEditor';\nimport { collectionRowHeights, collectionRows, collectionSlices } from './collectionGridLayout';\nimport { useSliceDetailsVisibility } from './useSliceDetailsVisibility';\nimport { type LocalCollapses, withLocalCollapses } from './localCollapses';\nimport './CollectionGrid.css';\n\nexport interface CollectionGridProps extends CollectionGridEditor {\n collection: ModuleCollection;\n getZoom?: () => number;\n slots?: CollectionGridSlots;\n onDeselect?: () => void;\n onCollectionMoving?: (id: Guid, deltaX: number, deltaY: number) => void;\n onCollectionMoved?: (id: Guid, position: { x: number; y: number }) => void;\n canMove?: boolean;\n onAddModule?: () => Promise<Module | undefined>;\n onModulesReordered?: (ids: Guid[]) => Promise<boolean>;\n onCollapseChanged?: (id: Guid, collapsed: boolean) => Promise<boolean>;\n onRenameModule?: (id: Guid, name: string) => Promise<boolean>;\n onModulesChanged?: (modules: Module[]) => void;\n onFeaturesChanged?: (moduleId: Guid, features: Feature[]) => void;\n onPersistenceError?: (error: unknown) => void;\n rowLabels?: (props: RowLabelsColumnProps) => ReactNode;\n onActorsReordered?: RowLabelsColumnProps['onActorsReordered'];\n}\n\nconst defaultZoom = () => 1;\n\nexport const CollectionGrid = ({ collection, getZoom = defaultZoom, slots, onDeselect, onCollectionMoving,\n onCollectionMoved, canMove, onAddModule, onModulesReordered, onCollapseChanged, onRenameModule,\n onModulesChanged, onFeaturesChanged, onPersistenceError, rowLabels, onActorsReordered,\n onAddFeature, onRenameFeature, onFeatureCollapseChanged, onFeaturesReordered,\n onAddSlice, onReorderSlices, onMoveSlice, validateSliceDrop, onSliceCollapseChanged, onSliceRenamed, onSliceDuplicated }: CollectionGridProps) => {\n const { readOnly } = useBoard();\n // Collapsing only changes how the board is drawn, so a read-only board does it on its own.\n const [localCollapses, setLocalCollapses] = useState<LocalCollapses>(new Map());\n const collapseLocally = useCallback((id: Guid, collapsed: boolean) =>\n setLocalCollapses(previous => new Map(previous).set(id.toString(), collapsed)), []);\n const readOnlyModules = useMemo(() => withLocalCollapses(collection.modules, localCollapses), [collection.modules, localCollapses]);\n const editor: CollectionGridEditor = readOnly ? {\n onFeatureCollapseChanged: collapseLocally,\n onSliceCollapseChanged: (_featureId, sliceId, collapsed) => collapseLocally(sliceId, collapsed),\n } : {\n onAddFeature, onRenameFeature, onFeatureCollapseChanged, onFeaturesReordered,\n onAddSlice, onReorderSlices, onMoveSlice, validateSliceDrop, onSliceCollapseChanged, onSliceRenamed, onSliceDuplicated,\n };\n const [modules, setModules] = useState(collection.modules);\n const [liveFeatures, setLiveFeatures] = useState<ReadonlyMap<string, Feature[]>>(new Map());\n const contentRef = useRef<HTMLDivElement>(null);\n const [labelOffset, setLabelOffset] = useState(0);\n const hasEditor = !!(onAddModule || onModulesReordered || onCollapseChanged || onRenameModule ||\n onActorsReordered || onAddFeature || onRenameFeature || onFeatureCollapseChanged || onFeaturesReordered ||\n onAddSlice || onReorderSlices || onMoveSlice || onSliceCollapseChanged || onSliceRenamed || onSliceDuplicated ||\n (canMove && onCollectionMoving && onCollectionMoved));\n const followsIncoming = readOnly || !hasEditor;\n const incomingModules = readOnly ? readOnlyModules : collection.modules;\n const visibleModules = (followsIncoming ? incomingModules : modules).map(module => ({ ...module,\n features: followsIncoming ? module.features : liveFeatures.get(module.id.toString()) ?? module.features,\n }));\n const visibleCollection = { ...collection, modules: visibleModules };\n const rows = collectionRows(visibleCollection);\n const showsDetails = useSliceDetailsVisibility();\n const heights = collectionRowHeights(visibleCollection, showsDetails);\n const slices = collectionSlices(visibleCollection);\n const showLabels = slices.length > 0 && visibleModules.some(module => !module.collapsed);\n const connections = computeSliceConnections(slices.map(({ slice }) => ({\n id: slice.id.toString(), name: slice.name,\n events: slice.events.map(event => ({ id: event.id.toString(), name: event.name,\n sourceEventId: event.sourceEventId ? event.sourceEventId.toString() : undefined })),\n automationTriggerEventId: slice.automationTrigger?.eventId?.toString(),\n })));\n\n useEffect(() => {\n const container = contentRef.current;\n if (!container) return;\n const measure = () => {\n const header = container.querySelector<HTMLElement>('.event-modeling-grid-slice-column-header');\n if (!header) { setLabelOffset(0); return; }\n setLabelOffset(Math.max(0, Math.round((header.getBoundingClientRect().bottom\n - container.getBoundingClientRect().top) / getZoom() - 4)));\n };\n measure();\n const observer = new ResizeObserver(measure);\n observer.observe(container);\n const slicesArea = container.querySelector<HTMLElement>('.event-modeling-grid-slices-area');\n if (slicesArea) observer.observe(slicesArea);\n return () => observer.disconnect();\n }, [modules, liveFeatures, getZoom]);\n\n const labelProps: RowLabelsColumnProps = { collectionId: collection.id, topOffset: labelOffset,\n contentRows: rows, rowHeights: heights, actors: collection.actors,\n onActorsReordered: readOnly ? undefined : onActorsReordered };\n return <BoardReadOnlyContext.Provider value={readOnly || !hasEditor}>\n <div className='event-modeling-grid-container event-modeling-collection-grid' onClick={onDeselect}>\n {showLabels && !readOnly && canMove && onCollectionMoving && onCollectionMoved &&\n <CollectionMoveHandle collectionId={collection.id} position={collection.position} getZoom={getZoom}\n onCollectionMoving={onCollectionMoving} onCollectionMoved={onCollectionMoved} />}\n <div className='event-modeling-grid-content-row' ref={contentRef}>\n {showLabels && (rowLabels ? rowLabels(labelProps) : <RowLabelsColumn {...labelProps} />)}\n <div className='event-modeling-grid-slices-area'>\n <SliceConnectionsProvider connections={connections}>\n <ModulesArea collectionId={collection.id} initialModules={incomingModules}\n onAddModule={onAddModule} onModulesReordered={onModulesReordered}\n onCollapseChanged={readOnly ? (id, collapsed) => { collapseLocally(id, collapsed); return Promise.resolve(true); } : onCollapseChanged}\n onRenameModule={onRenameModule}\n onPersistenceError={onPersistenceError}\n onModulesChanged={changed => { setModules(changed); onModulesChanged?.(changed); }}\n renderModule={(module, options) => <CollectionGridModule\n module={module} liveFeatures={liveFeatures.get(module.id.toString())} index={options.index}\n collection={visibleCollection} rows={rows} heights={heights} slots={slots}\n dragging={options.dragging} onDragStart={options.onDragStart}\n onAddModule={options.onAddModule} onToggleCollapse={options.onToggleCollapse}\n onRenamed={options.onRenamed}\n editor={editor}\n onFeaturesChanged={(moduleId, features) => {\n setLiveFeatures(previous => new Map(previous).set(moduleId.toString(), features));\n onFeaturesChanged?.(moduleId, features);\n }} />}\n />\n </SliceConnectionsProvider>\n </div>\n </div>\n </div>\n </BoardReadOnlyContext.Provider>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\nimport type { ModuleCollectionLink } from '../Model';\n\nexport interface LinkState {\n snapshot: ModuleCollectionLink[];\n additions: ModuleCollectionLink[];\n removals: ReadonlySet<string>;\n pending: ReadonlySet<string>;\n // A locally created link may be removed before its creation ever appears in the query.\n // Absence only acknowledges a removal after this id has first been observed in a snapshot.\n observedRemovals: ReadonlySet<string>;\n}\n\nexport const linkPair = (sourceCollectionId: Guid, targetCollectionId: Guid): string =>\n `${sourceCollectionId.toString()}:${targetCollectionId.toString()}`;\n\nexport const visibleLinks = (state: LinkState): ModuleCollectionLink[] => [\n ...state.snapshot.filter(link => !state.removals.has(link.id.toString()) &&\n !state.additions.some(added => linkPair(added.sourceCollectionId, added.targetCollectionId) === linkPair(link.sourceCollectionId, link.targetCollectionId))),\n ...state.additions.filter(link => !state.removals.has(link.id.toString())),\n];\n\nexport const createLinkState = (snapshot: ModuleCollectionLink[]): LinkState => ({\n snapshot, additions: [], removals: new Set(), pending: new Set(), observedRemovals: new Set(),\n});\n\n// An observable snapshot can lag a successful command. Retain local links until the matching\n// server pair arrives and keep deleted links hidden until the server actually omits them.\nexport const reconcileLinks = (state: LinkState, snapshot: ModuleCollectionLink[]): LinkState => {\n const snapshotIds = new Set(snapshot.map(link => link.id.toString()));\n const observedRemovals = new Set([...state.observedRemovals, ...[...state.removals].filter(id => snapshotIds.has(id))]);\n const removals = new Set([...state.removals].filter(id =>\n snapshotIds.has(id) || state.pending.has(id) || !observedRemovals.has(id)));\n return {\n ...state,\n snapshot,\n additions: state.additions.filter(added => !snapshot.some(link =>\n linkPair(link.sourceCollectionId, link.targetCollectionId) === linkPair(added.sourceCollectionId, added.targetCollectionId))),\n removals,\n observedRemovals: new Set([...observedRemovals].filter(id => removals.has(id))),\n };\n};\n\nexport const beginLink = (state: LinkState, link: ModuleCollectionLink): LinkState => {\n const pair = linkPair(link.sourceCollectionId, link.targetCollectionId);\n if (state.pending.has(pair) || visibleLinks(state).some(existing =>\n linkPair(existing.sourceCollectionId, existing.targetCollectionId) === pair)) return state;\n return { ...state, additions: [...state.additions, link], pending: new Set([...state.pending, pair]) };\n};\n\nexport const finishLink = (state: LinkState, link: ModuleCollectionLink, persistedId?: Guid): LinkState => {\n const pair = linkPair(link.sourceCollectionId, link.targetCollectionId);\n const pending = new Set(state.pending);\n pending.delete(pair);\n const additions = state.additions.flatMap(added => added.id.toString() === link.id.toString()\n ? (persistedId ? [{ ...added, id: persistedId }] : []) : [added]);\n return reconcileLinks({ ...state, pending, additions }, state.snapshot);\n};\n\nexport const beginUnlink = (state: LinkState, id: Guid): LinkState => {\n const key = id.toString();\n if (state.pending.has(key) || !visibleLinks(state).some(link => link.id.toString() === key)) return state;\n return {\n ...state,\n removals: new Set([...state.removals, key]),\n pending: new Set([...state.pending, key]),\n observedRemovals: state.snapshot.some(link => link.id.toString() === key)\n ? new Set([...state.observedRemovals, key]) : state.observedRemovals,\n };\n};\n\nexport const finishUnlink = (state: LinkState, id: Guid, succeeded: boolean): LinkState => {\n const key = id.toString();\n const pending = new Set(state.pending);\n pending.delete(key);\n const removals = new Set(state.removals);\n if (!succeeded) removals.delete(key);\n const additions = succeeded ? state.additions.filter(link => link.id.toString() !== key) : state.additions;\n return reconcileLinks({ ...state, pending, removals, additions }, state.snapshot);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ModuleCollectionLink } from '../Model';\nimport { computeSplineEndpoints, midpoint, smoothCurvePath, type Point, type Rect } from '../Geometry';\n\nexport interface DrawableLink {\n link: ModuleCollectionLink;\n path: string;\n // Where the remove affordance sits: for this curve's symmetric control points the midpoint of the\n // endpoints is the curve's halfway point, so the affordance sits exactly on the drawn spline.\n center: Point;\n}\n\n// The links that can be drawn: a link whose source or target collection is not placed yet is skipped\n// rather than drawn to nowhere.\nexport const drawableLinks = (links: ModuleCollectionLink[], contentOf: (collectionId: string) => Rect | undefined): DrawableLink[] =>\n links.flatMap(link => {\n const source = contentOf(link.sourceCollectionId.toString());\n const target = contentOf(link.targetCollectionId.toString());\n if (!source || !target) return [];\n const spline = computeSplineEndpoints(source, target);\n return [{ link, path: smoothCurvePath(spline.start, spline.end, spline.axis), center: midpoint(spline.start, spline.end) }];\n });\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ModuleCollectionLinks.css';\nimport React, { useEffect, useId, useMemo, useRef, useState } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport type { ModuleCollectionLink, Position } from '../Model';\nimport { beginLink as beginOptimisticLink, beginUnlink, createLinkState, finishLink, finishUnlink, linkPair, reconcileLinks, visibleLinks, type LinkState } from './linkState';\nimport { useBoard } from '../Board';\nimport { drawableLinks } from './drawableLinks';\nimport {\n smoothCurvePath,\n boundingBox,\n computeSplineEndpoints,\n linkAnchor,\n pointInRect,\n rectAt,\n resolveDropTarget,\n type Point,\n type Rect,\n} from '../Geometry';\n\n// How far outside the outermost collection the drawing surface extends, so an in-progress drag line\n// toward an empty part of the board is not clipped.\nconst SVG_PADDING = 2000;\n\n// A module collection as the links see it: where it is, and which part of it is slice content.\nexport interface LinkedCollectionPlacement {\n id: Guid;\n position: Position;\n width: number;\n height: number;\n // The estimated content height excludes specifications below the slice columns.\n contentHeight: number;\n}\n\ninterface PlacedCollection {\n id: Guid;\n rect: Rect;\n content: Rect;\n}\n\nexport interface ModuleCollectionLinksProps {\n links: ModuleCollectionLink[];\n collections: LinkedCollectionPlacement[];\n // Reads the current canvas zoom, so screen drag deltas convert to world deltas.\n getZoom: () => number;\n // Linking two collections exists only when the board is editable and this is supplied.\n onCollectionsLinked?: (sourceCollectionId: Guid, targetCollectionId: Guid) => Promise<Guid | undefined>;\n // Return false on command failure so the optimistic removal can be restored.\n onCollectionsUnlinked?: (linkId: Guid) => Promise<boolean>;\n onPersistenceError?: (error: unknown) => void;\n}\n\n/** State of an in-progress drag-to-connect gesture. */\ninterface LinkDrag {\n sourceId: string;\n pointer: Point;\n targetId: string | null;\n}\n\n// Draws directed arrows between linked module collections in the canvas content coordinate space, and\n// hosts the gestures that ask to create (drag a collection's handle onto another) and remove (the\n// affordance at a link's midpoint) a link.\nexport const ModuleCollectionLinks = ({ links, collections, getZoom, onCollectionsLinked, onCollectionsUnlinked, onPersistenceError }: ModuleCollectionLinksProps) => {\n const board = useBoard();\n const messages = board.messages.links;\n const onLink = board.readOnly ? undefined : onCollectionsLinked;\n const onUnlink = board.readOnly ? undefined : onCollectionsUnlinked;\n\n const [drag, setDrag] = useState<LinkDrag | null>(null);\n const [linkState, setLinkState] = useState(() => createLinkState(links));\n const linkStateRef = useRef<LinkState>(linkState);\n const apply = (transition: (state: LinkState) => LinkState) => {\n const next = transition(linkStateRef.current);\n linkStateRef.current = next;\n setLinkState(next);\n };\n useEffect(() => {\n if (links !== linkStateRef.current.snapshot) apply(state => reconcileLinks(state, links));\n }, [links]);\n const displayedLinks = visibleLinks(linkState);\n const dragOriginRef = useRef<{ sourceId: Guid; anchor: Point; startClientX: number; startClientY: number } | null>(null);\n // The target the affordance last committed to, tracked synchronously so the drop can honor exactly\n // what the user was shown even if the release coordinate lands a hair outside it (see endLink).\n const lastTargetIdRef = useRef<string | null>(null);\n\n const markerId = `module-collection-link-arrow-${useId().replace(/:/g, '')}`;\n\n const rects = useMemo(() => new Map(collections.map((collection): [string, PlacedCollection] => {\n const rect = { x: collection.position.x, y: collection.position.y, width: collection.width, height: collection.height };\n return [collection.id.toString(), { id: collection.id, rect, content: { ...rect, height: Math.min(rect.height, collection.contentHeight) } }];\n })), [collections]);\n\n const drawable = useMemo(() => drawableLinks(displayedLinks, id => rects.get(id)?.content), [displayedLinks, rects]);\n\n const findTarget = (pointer: Point, sourceId: Guid): PlacedCollection | null => {\n for (const entry of rects.values()) {\n if (entry.id.toString() === sourceId.toString()) continue;\n if (pointInRect(pointer, entry.rect)) return entry;\n }\n return null;\n };\n\n const pointerFromEvent = (event: React.PointerEvent, origin: { anchor: Point; startClientX: number; startClientY: number }): Point => {\n const zoom = getZoom() || 1;\n return {\n x: origin.anchor.x + (event.clientX - origin.startClientX) / zoom,\n y: origin.anchor.y + (event.clientY - origin.startClientY) / zoom,\n };\n };\n\n const startLinkDrag = (sourceId: Guid, anchor: Point) => (event: React.PointerEvent) => {\n if (linkStateRef.current.pending.size > 0) return;\n event.stopPropagation();\n event.preventDefault();\n event.currentTarget.setPointerCapture(event.pointerId);\n dragOriginRef.current = { sourceId, anchor, startClientX: event.clientX, startClientY: event.clientY };\n lastTargetIdRef.current = null;\n setDrag({ sourceId: sourceId.toString(), pointer: anchor, targetId: null });\n };\n\n const updateLink = (event: React.PointerEvent) => {\n const origin = dragOriginRef.current;\n if (!origin) return;\n const pointer = pointerFromEvent(event, origin);\n const target = findTarget(pointer, origin.sourceId);\n lastTargetIdRef.current = target?.id.toString() ?? null;\n setDrag({ sourceId: origin.sourceId.toString(), pointer, targetId: target?.id.toString() ?? null });\n };\n\n const endLink = async (event: React.PointerEvent) => {\n const origin = dragOriginRef.current;\n const lastTargetId = lastTargetIdRef.current;\n dragOriginRef.current = null;\n lastTargetIdRef.current = null;\n setDrag(null);\n if (!origin) return;\n // Honor the target the affordance committed to: prefer a fresh hit-test at the release point,\n // but fall back to the last highlighted target. A quick release can land a hair outside the\n // target — or have its final pointermove coalesced away by the browser — even though the user\n // was shown \"will connect\"; without this fallback that gesture silently created no link.\n const releaseTarget = findTarget(pointerFromEvent(event, origin), origin.sourceId);\n const target = resolveDropTarget(releaseTarget, lastTargetId, id => rects.get(id), origin.sourceId.toString());\n if (!target) return;\n if (!onLink || linkStateRef.current.pending.size > 0) return;\n const optimisticLink = { id: Guid.create(), sourceCollectionId: origin.sourceId, targetCollectionId: target.id };\n const pair = linkPair(origin.sourceId, target.id);\n if (linkStateRef.current.pending.has(pair) || visibleLinks(linkStateRef.current).some(link =>\n linkPair(link.sourceCollectionId, link.targetCollectionId) === pair)) return;\n apply(state => beginOptimisticLink(state, optimisticLink));\n try {\n const persistedId = await onLink(origin.sourceId, target.id);\n apply(state => finishLink(state, optimisticLink, persistedId));\n } catch (error) {\n apply(state => finishLink(state, optimisticLink));\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n }\n };\n\n const removeLink = async (id: Guid) => {\n if (!onUnlink || linkStateRef.current.pending.size > 0) return;\n apply(state => beginUnlink(state, id));\n try {\n const succeeded = await onUnlink(id);\n apply(state => finishUnlink(state, id, succeeded));\n } catch (error) {\n apply(state => finishUnlink(state, id, false));\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n }\n };\n\n const cancelLink = () => {\n dragOriginRef.current = null;\n lastTargetIdRef.current = null;\n setDrag(null);\n };\n\n const collectionRects = Array.from(rects.values());\n if (collectionRects.length === 0) return null;\n\n const box = boundingBox(collectionRects.map(entry => entry.rect), drag ? [drag.pointer] : [], SVG_PADDING);\n const dragSource = drag ? rects.get(drag.sourceId) : undefined;\n const dropTarget = drag?.targetId ? rects.get(drag.targetId) : undefined;\n\n return (\n <div className='module-collection-link-layer'>\n <svg\n className='module-collection-link-layer__svg'\n style={{ left: box.x, top: box.y, width: box.width, height: box.height }}\n viewBox={`${box.x} ${box.y} ${box.width} ${box.height}`}\n aria-hidden='true'>\n <defs>\n <marker id={markerId} markerWidth='10' markerHeight='10' refX='8' refY='4' orient='auto' markerUnits='userSpaceOnUse'>\n <path d='M 0 0 L 9 4 L 0 8 z' className='module-collection-link-layer__arrow-head' />\n </marker>\n </defs>\n {drawable.map(({ link, path }) => (\n <path\n key={link.id.toString()}\n d={path}\n className='module-collection-link-layer__arrow'\n markerEnd={`url(#${markerId})`}\n />\n ))}\n {drag && dragSource && (\n (() => {\n const spline = computeSplineEndpoints(dragSource.content, rectAt(drag.pointer));\n return (\n <path\n d={smoothCurvePath(spline.start, spline.end, spline.axis)}\n className='module-collection-link-layer__preview'\n markerEnd={`url(#${markerId})`}\n />\n );\n })()\n )}\n </svg>\n\n {dropTarget && (\n <div\n className='module-collection-link-layer__drop-target'\n style={{ left: dropTarget.rect.x, top: dropTarget.rect.y, width: dropTarget.rect.width, height: dropTarget.rect.height }}\n />\n )}\n\n {onLink && linkState.pending.size === 0 && collectionRects.map(({ id, content }) => {\n const anchor = linkAnchor(content);\n return (\n <div\n key={id.toString()}\n className='module-collection-link-layer__handle'\n style={{ left: anchor.x, top: anchor.y }}\n title={messages.dragToLink}\n onPointerDown={startLinkDrag(id, anchor)}\n onPointerMove={updateLink}\n onPointerUp={endLink}\n onPointerCancel={cancelLink}\n />\n );\n })}\n\n {onUnlink && linkState.pending.size === 0 && drawable.map(({ link, center }) => (\n <button\n key={link.id.toString()}\n type='button'\n className='module-collection-link-layer__delete'\n style={{ left: center.x, top: center.y }}\n title={messages.removeLink}\n onPointerDown={event => event.stopPropagation()}\n onClick={() => void removeLink(link.id)}>\n <i className='pi pi-times' />\n </button>\n ))}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Whether a key pressed on target is typing into a field, which must never delete the note behind it.\nexport const isEditableTarget = (target: EventTarget | null): boolean =>\n typeof Element !== 'undefined' && target instanceof Element && !!target.closest('input, textarea, [contenteditable=\"true\"]');\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { StickyNote } from '../Model';\n\nconst LOCAL_EDIT_GUARD_MS = 4000;\n\nconst sameNote = (first: StickyNote, second: StickyNote) =>\n first.id === second.id && first.text === second.text &&\n first.position.x === second.position.x && first.position.y === second.position.y &&\n first.width === second.width && first.height === second.height;\n\ninterface PendingNote {\n note: StickyNote | null;\n created: boolean;\n inFlight: boolean;\n expiresAt: number;\n}\n\n// Deletion tombstones last for the mounted session; edits have a bounded local guard because an\n// observable snapshot carries no causal revision with which to distinguish an echo from another edit.\nexport class StickyNoteState {\n private remote: readonly StickyNote[];\n private readonly pending = new Map<string, PendingNote>();\n\n constructor(notes: readonly StickyNote[], private readonly now: () => number = Date.now) {\n this.remote = notes;\n }\n\n get notes(): StickyNote[] {\n const remoteIds = new Set(this.remote.map(note => note.id));\n return [\n ...this.remote.flatMap(note => {\n const local = this.pending.get(note.id)?.note;\n return local === null ? [] : [local ?? note];\n }),\n ...[...this.pending.entries()].flatMap(([id, change]) => change.note && !remoteIds.has(id) ? [change.note] : []),\n ];\n }\n\n get(id: string): StickyNote | undefined {\n return this.notes.find(note => note.id === id);\n }\n\n change(id: string, note: StickyNote | null): void {\n this.pending.set(id, {\n note,\n created: this.pending.get(id)?.created ?? !this.remote.some(remote => remote.id === id),\n inFlight: false,\n expiresAt: this.now() + LOCAL_EDIT_GUARD_MS,\n });\n }\n\n begin(id: string, note: StickyNote | null): void {\n const pending = this.pending.get(id);\n if (pending?.note === note) pending.inFlight = true;\n }\n\n settle(id: string, note: StickyNote | null): void {\n const pending = this.pending.get(id);\n if (!pending || pending.note !== note) return;\n pending.inFlight = false;\n pending.expiresAt = this.now() + LOCAL_EDIT_GUARD_MS;\n const remote = this.remote.find(candidate => candidate.id === id);\n if (note && remote && sameNote(note, remote)) this.pending.delete(id);\n }\n\n reconcile(notes: readonly StickyNote[]): void {\n this.remote = notes;\n for (const [id, pending] of this.pending) {\n if (pending.note === null || pending.inFlight) continue;\n const remote = notes.find(note => note.id === id);\n if (remote && sameNote(pending.note, remote)) this.pending.delete(id);\n }\n this.expire();\n }\n\n expire(): void {\n for (const [id, pending] of this.pending) {\n if (pending.note === null || pending.inFlight || this.now() < pending.expiresAt) continue;\n if (pending.created && !this.remote.some(note => note.id === id)) continue;\n this.pending.delete(id);\n }\n }\n\n get nextExpiration(): number | undefined {\n const deadlines = [...this.pending.entries()]\n .filter(([id, pending]) => pending.note !== null && !pending.inFlight &&\n (!pending.created || this.remote.some(note => note.id === id)))\n .map(([, pending]) => pending.expiresAt);\n return deadlines.length ? Math.min(...deadlines) : undefined;\n }\n\n rollback(id: string, change: StickyNote | null): void {\n if (this.pending.get(id)?.note === change) this.pending.delete(id);\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, type SyntheticEvent } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { CanvasItem, Note } from '@cratis/components/Canvas';\nimport { ProgressSpinner } from '@cratis/components/Display';\nimport type { Position, StickyNote } from '../Model';\nimport { useBoard } from '../Board';\nimport { useDismissOnOutsidePointer } from '../Pickers/useDismissOnOutsidePointer';\nimport { isEditableTarget } from './isEditableTarget';\nimport type { StickyNoteBounds } from './StickyNoteBounds';\nimport type { StickyNoteHandle } from './StickyNoteHandle';\nimport { StickyNoteState } from './StickyNoteState';\nimport './StickyNotes.css';\n\nexport interface StickyNotesProps {\n notes: readonly StickyNote[];\n}\n\nconst DEFAULT_SIZE = 50;\nconst ignore = () => undefined;\nconst stop = (event: SyntheticEvent) => event.stopPropagation();\ntype ChangeResult = Promise<boolean | void> | boolean | void;\n\n// The board owns selection and local edits; its consumer only persists finished gestures. Observable\n// snapshots are merged per note; edit guards are bounded, while deletion tombstones last for this mount.\nexport const StickyNotes = forwardRef<StickyNoteHandle, StickyNotesProps>(({ notes }, handle) => {\n const { editing, actions, messages } = useBoard();\n const state = useRef(new StickyNoteState(notes));\n const inFlight = useRef(new Set<string>());\n const creating = useRef(false);\n const movedIds = useRef(new Set<string>());\n const resizedIds = useRef(new Set<string>());\n const [revision, refresh] = useState(0);\n const [selectedId, setSelectedId] = useState<string | undefined>();\n const [expandedId, setExpandedId] = useState<string | undefined>();\n const container = useRef<HTMLDivElement>(null);\n const containers = useMemo(() => [container], []);\n const repaint = useCallback(() => refresh(previous => previous + 1), []);\n\n useEffect(() => {\n state.current.reconcile(notes);\n repaint();\n }, [notes, repaint]);\n\n useEffect(() => {\n const deadline = state.current.nextExpiration;\n if (deadline === undefined) return;\n const timer = setTimeout(() => {\n state.current.expire();\n repaint();\n }, Math.max(0, deadline - Date.now()));\n return () => clearTimeout(timer);\n }, [revision, repaint]);\n\n const persist = useCallback((id: string, change: StickyNote | null, execute: () => ChangeResult) => {\n if (inFlight.current.has(id)) return Promise.resolve();\n inFlight.current.add(id);\n state.current.change(id, change);\n state.current.begin(id, change);\n repaint();\n // An unsuccessful command must not leave an optimistic edit masquerading as persisted state.\n return Promise.resolve().then(execute).then(success => {\n if (success === false) {\n state.current.rollback(id, change);\n if (!state.current.get(id)) setSelectedId(previous => previous === id ? undefined : previous);\n repaint();\n }\n return success !== false;\n }).catch(error => {\n state.current.rollback(id, change);\n if (!state.current.get(id)) setSelectedId(previous => previous === id ? undefined : previous);\n repaint();\n if (actions.stickyNoteError) actions.stickyNoteError(error);\n else console.error(error);\n return false;\n }).finally(() => {\n state.current.settle(id, change);\n inFlight.current.delete(id);\n repaint();\n });\n }, [actions, repaint]);\n\n useImperativeHandle(handle, () => ({\n add(center: Position) {\n const add = editing.onStickyNoteAdded;\n if (!add || creating.current) return;\n creating.current = true;\n actions.stickyNoteCreatingChanged?.(true);\n const note: StickyNote = {\n id: Guid.create().toString(),\n position: { x: center.x - DEFAULT_SIZE / 2, y: center.y - DEFAULT_SIZE / 2 },\n width: DEFAULT_SIZE,\n height: DEFAULT_SIZE,\n text: messages.stickyNotes.newNote,\n };\n setSelectedId(note.id);\n void persist(note.id, note, () => add(note)).then(succeeded => {\n if (succeeded) actions.stickyNoteCreated?.(note);\n }).finally(() => {\n creating.current = false;\n actions.stickyNoteCreatingChanged?.(false);\n });\n },\n }), [editing, actions, messages, persist]);\n\n const select = editing.onStickyNoteMoved || editing.onStickyNoteResized || editing.onStickyNoteTextChanged || editing.onStickyNoteRemoved\n ? setSelectedId : undefined;\n useDismissOnOutsidePointer(containers, () => select?.(undefined), selectedId !== undefined && !!select);\n\n const move = (id: string, position: Position) => {\n const note = state.current.get(id);\n if (!note || inFlight.current.has(id) || (note.position.x === position.x && note.position.y === position.y)) return;\n movedIds.current.add(id);\n state.current.change(id, { ...note, position });\n repaint();\n };\n const resize = (id: string, bounds: StickyNoteBounds) => {\n const note = state.current.get(id);\n if (!note || inFlight.current.has(id) || (note.position.x === bounds.position.x && note.position.y === bounds.position.y && note.width === bounds.width && note.height === bounds.height)) return;\n resizedIds.current.add(id);\n state.current.change(id, { ...note, ...bounds });\n repaint();\n };\n const moveEnd = (id: string) => {\n if (!movedIds.current.delete(id)) return;\n const note = state.current.get(id);\n if (note && editing.onStickyNoteMoved) void persist(id, note, () => editing.onStickyNoteMoved?.(id, note.position));\n };\n const resizeEnd = (id: string) => {\n if (!resizedIds.current.delete(id)) return;\n const note = state.current.get(id);\n if (note && editing.onStickyNoteResized) void persist(id, note, () => editing.onStickyNoteResized?.(id, {\n position: note.position, width: note.width, height: note.height,\n }));\n };\n const changeText = (id: string, text: string) => {\n const note = state.current.get(id);\n if (note && note.text !== text && editing.onStickyNoteTextChanged) {\n void persist(id, { ...note, text }, () => editing.onStickyNoteTextChanged?.(id, text));\n }\n };\n const remove = useCallback((id: string) => {\n if (!state.current.get(id) || !editing.onStickyNoteRemoved || inFlight.current.has(id)) return;\n setSelectedId(previous => previous === id ? undefined : previous);\n void persist(id, null, () => editing.onStickyNoteRemoved?.(id));\n }, [editing, persist]);\n\n useEffect(() => {\n if (!editing.onStickyNoteRemoved || selectedId === undefined) return;\n const onKeyDown = (event: KeyboardEvent) => {\n if ((event.key !== 'Delete' && event.key !== 'Backspace') || isEditableTarget(event.target)) return;\n event.preventDefault();\n remove(selectedId);\n };\n document.addEventListener('keydown', onKeyDown);\n return () => document.removeEventListener('keydown', onKeyDown);\n }, [selectedId, editing, remove]);\n\n return (\n <div ref={container} className='event-model-sticky-notes'>\n {state.current.notes.map(note => {\n const x = note.position?.x ?? 0;\n const y = note.position?.y ?? 0;\n return (\n <CanvasItem key={note.id} x={x} y={y} zIndex={expandedId === note.id ? 3 : 2}>\n <div\n data-sticky-note-id={note.id}\n className={inFlight.current.has(note.id) ? 'event-model-sticky-note--busy' : undefined}\n aria-busy={inFlight.current.has(note.id)}\n onDoubleClickCapture={editing.onStickyNoteTextChanged && !inFlight.current.has(note.id) ? undefined : stop}\n >\n <Note\n note={{ id: note.id, x, y, width: note.width, height: note.height, text: note.text }}\n selected={selectedId === note.id && !!editing.onStickyNoteResized && !inFlight.current.has(note.id)}\n onSelect={select ?? ignore}\n onMove={editing.onStickyNoteMoved ? (id, x, y) => move(id, { x, y }) : ignore}\n onMoveEnd={editing.onStickyNoteMoved ? moveEnd : undefined}\n onResize={editing.onStickyNoteResized ? (id, x, y, width, height) => resize(id, { position: { x, y }, width, height }) : ignore}\n onResizeEnd={editing.onStickyNoteResized ? resizeEnd : undefined}\n onTextChange={editing.onStickyNoteTextChanged ? changeText : ignore}\n onExpandedChange={(id, expanded) => setExpandedId(previous => expanded ? id : previous === id ? undefined : previous)}\n />\n {inFlight.current.has(note.id) && <span className='event-model-sticky-note__progress' aria-hidden='true'><ProgressSpinner className='event-model-sticky-note__spinner' /></span>}\n </div>\n </CanvasItem>\n );\n })}\n </div>\n );\n});\n\nStickyNotes.displayName = 'StickyNotes';\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { memo, useCallback, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { CollectionGrid, CollectionViewport, type CollectionSizeEstimate } from '../Collections';\nimport type { BoardCollection, CollectionGridContent, CollectionGridRenderer } from './BoardCollections';\n\nexport interface BoardCollectionViewProps {\n collection: BoardCollection;\n estimatedSize: CollectionSizeEstimate;\n measuredSize?: { width: number; height: number };\n onSize: (id: Guid, width: number, height: number) => void;\n getZoom: () => number;\n canMove: boolean;\n onCollectionMoving?: (id: Guid, deltaX: number, deltaY: number) => void;\n onCollectionMoved?: (id: Guid, position: { x: number; y: number }) => void;\n content: (grid: CollectionGridRenderer) => ReactNode;\n}\n\n// Memoized so a collection being dragged, or a size being measured, re-renders only that collection.\nexport const BoardCollectionView = memo(({ collection, estimatedSize, measuredSize, onSize, getZoom, canMove,\n onCollectionMoving, onCollectionMoved, content }: BoardCollectionViewProps) => {\n const grid = useCallback((gridContent: CollectionGridContent) => <CollectionGrid {...gridContent} getZoom={getZoom}\n canMove={canMove} onCollectionMoving={onCollectionMoving} onCollectionMoved={onCollectionMoved} />,\n [getZoom, canMove, onCollectionMoving, onCollectionMoved]);\n return <CollectionViewport collection={collection} estimatedSize={estimatedSize} measuredSize={measuredSize} onSize={onSize}>\n {content(grid)}\n </CollectionViewport>;\n});\n\nBoardCollectionView.displayName = 'BoardCollectionView';\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Position } from '../Model';\n\nexport interface BoardMinimapItem {\n x: number;\n y: number;\n width: number;\n height: number;\n color: string;\n}\n\nexport interface BoardMinimap {\n items: BoardMinimapItem[];\n worldWidth: number;\n worldHeight: number;\n}\n\n// The canvas minimap's own world size; the board only grows it when collections reach past it.\nconst MINIMUM_WORLD_WIDTH = 4000;\nconst MINIMUM_WORLD_HEIGHT = 3000;\nconst WORLD_PADDING = 200;\nconst COLLECTION_COLOR = 'rgba(100, 160, 255, 0.35)';\n\n// Sized from estimates rather than measurements, so collections that were never scrolled into view still show.\nexport const boardMinimap = (collections: readonly { position?: Position; size: { width: number; height: number } }[]): BoardMinimap => {\n const items = collections.map(({ position, size }) => ({\n x: position?.x ?? 0, y: position?.y ?? 0, width: size.width, height: size.height, color: COLLECTION_COLOR,\n }));\n return {\n items,\n worldWidth: Math.max(MINIMUM_WORLD_WIDTH, ...items.map(item => item.x + item.width + WORLD_PADDING)),\n worldHeight: Math.max(MINIMUM_WORLD_HEIGHT, ...items.map(item => item.y + item.height + WORLD_PADDING)),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Feature, ModuleCollection } from '../Model';\n\n// Above this many slices the glass control pill's per-frame capture stalls pan and zoom.\nexport const LARGE_BOARD_SLICE_COUNT = 40;\n\nconst countFeatureSlices = (features: readonly Feature[]): number =>\n features.reduce((total, feature) => total + feature.slices.length + countFeatureSlices(feature.subFeatures), 0);\n\nexport const countCollectionSlices = (collection: ModuleCollection): number =>\n collection.modules.reduce((total, module) => total + countFeatureSlices(module.features), 0);\n\nexport const isLargeBoard = (sliceCount: number): boolean => sliceCount > LARGE_BOARD_SLICE_COUNT;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Fragment, useCallback, useImperativeHandle, useMemo, useRef, useState, type ReactNode, type Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { resolveOverlappingCollections, useCollectionsArea, type CollectionSizeEstimate } from '../Collections';\nimport { ModuleCollectionLinks, type LinkedCollectionPlacement } from '../Links';\nimport type { ModuleCollectionLink, StickyNote } from '../Model';\nimport { StickyNotes, type StickyNoteHandle } from '../StickyNotes';\nimport { BoardCanvas } from './BoardCanvas';\nimport { BoardCollectionView } from './BoardCollectionView';\nimport type { BoardCollection, BoardCollections, CollectionGridRenderer } from './BoardCollections';\nimport type { EventModelBoardCanvas, EventModelBoardInteractions } from './EventModelBoardEditor';\nimport type { EventModelBoardHandle } from './EventModelBoardHandle';\nimport { BoardProvider } from './BoardProvider';\nimport { boardMinimap } from './boardMinimap';\nimport { isLargeBoard } from './isLargeBoard';\n\nexport interface HostedEventModelBoardProps<T extends BoardCollection> {\n id: Guid;\n collections: BoardCollections<T>;\n links: ModuleCollectionLink[];\n stickyNotes: readonly StickyNote[];\n readOnly?: boolean;\n editor?: EventModelBoardInteractions;\n canvas?: EventModelBoardCanvas;\n showMinimap?: boolean;\n handle?: Ref<EventModelBoardHandle>;\n}\n\ntype ContentProps<T extends BoardCollection> = Omit<HostedEventModelBoardProps<T>, 'id' | 'readOnly' | 'showMinimap'> &\n { readOnly: boolean; showMinimap: boolean };\n\n// Caches a derived value per collection object, so an unchanged collection keeps the same value and its memoized view.\nfunction usePerCollection<T extends object, R>(derive: (collection: T) => R): (collection: T) => R {\n return useMemo(() => {\n const cache = new WeakMap<T, R>();\n return (collection: T) => {\n const cached = cache.get(collection);\n if (cached !== undefined) return cached;\n const value = derive(collection);\n cache.set(collection, value);\n return value;\n };\n }, [derive]);\n}\n\nconst HostedEventModelBoardContent = <T extends BoardCollection>({ collections: host, links, stickyNotes, readOnly, editor,\n canvas, showMinimap, handle }: ContentProps<T>) => {\n const linkEditor = readOnly ? undefined : editor?.links;\n const area = useCollectionsArea<T>({\n initialCollections: host.initialCollections,\n onAddCollection: host.onAddCollection,\n onCollectionMoved: host.onCollectionMoved,\n onCollectionsChange: host.onCollectionsChange,\n onPersistenceError: host.onPersistenceError,\n });\n const { collections, pendingMoveIds, canMove, moveCollection, collectionMoved, addCollection } = area;\n const [sizes, setSizes] = useState<ReadonlyMap<string, { width: number; height: number }>>(new Map());\n const zoom = useRef(canvas?.initialZoom ?? 1);\n const getZoom = useCallback(() => zoom.current, []);\n const stickyNotesRef = useRef<StickyNoteHandle | null>(null);\n useImperativeHandle(handle, () => ({\n addCollection,\n addStickyNote: center => stickyNotesRef.current?.add(center),\n }), [addCollection]);\n const onSize = useCallback((id: Guid, width: number, height: number) => {\n setSizes(previous => {\n const key = id.toString();\n const existing = previous.get(key);\n if (existing?.width === width && existing.height === height) return previous;\n return new Map(previous).set(key, { width, height });\n });\n }, []);\n const estimateOf = usePerCollection<T, CollectionSizeEstimate>(host.estimateSize);\n const { renderCollection } = host;\n const contentOf = usePerCollection<T, (grid: CollectionGridRenderer) => ReactNode>(\n useCallback((collection: T) => (grid: CollectionGridRenderer) => renderCollection(collection, grid), [renderCollection]));\n const placed = useMemo(() => resolveOverlappingCollections(collections), [collections]);\n const minimap = useMemo(() => boardMinimap(placed.map(collection => ({ position: collection.position, size: estimateOf(collection) }))),\n [placed, estimateOf]);\n const { countSlices } = host;\n const largeBoard = useMemo(() => isLargeBoard(collections.reduce((total, collection) => total + countSlices(collection), 0)),\n [collections, countSlices]);\n const placements = useMemo(() => placed.flatMap((collection): LinkedCollectionPlacement[] => {\n const measured = sizes.get(collection.id.toString());\n if (!measured) return [];\n return [{ id: collection.id, position: collection.position, width: measured.width,\n height: measured.height, contentHeight: estimateOf(collection).height }];\n }), [placed, sizes, estimateOf]);\n const onTransformChange = canvas?.onTransformChange;\n const handleTransformChange = useCallback((nextZoom: number, pan: { x: number; y: number }) => {\n zoom.current = nextZoom;\n onTransformChange?.(nextZoom, pan);\n }, [onTransformChange]);\n\n const content = <>\n {placed.map(collection => <BoardCollectionView key={collection.id.toString()} collection={collection}\n estimatedSize={estimateOf(collection)} measuredSize={sizes.get(collection.id.toString())} onSize={onSize}\n getZoom={getZoom} canMove={canMove && !pendingMoveIds.has(collection.id.toString())}\n onCollectionMoving={canMove ? moveCollection : undefined} onCollectionMoved={canMove ? collectionMoved : undefined}\n content={contentOf(collection)} />)}\n <ModuleCollectionLinks links={links} collections={placements} getZoom={getZoom} {...linkEditor} />\n <StickyNotes ref={stickyNotesRef} notes={stickyNotes} />\n </>;\n\n return <BoardCanvas controlsPlacement='bottom-right' disableControlsGlass={largeBoard} {...canvas}\n style={{ width: '100%', height: '100%', ...canvas?.style }}\n showMinimap={showMinimap} minimapItems={minimap.items}\n minimapWorldWidth={minimap.worldWidth} minimapWorldHeight={minimap.worldHeight}\n onTransformChange={handleTransformChange}>\n {host.area ? host.area(area, content) : <Fragment>{content}</Fragment>}\n </BoardCanvas>;\n};\n\n// The one board tree for any host: collections in the host's own shape, drawn with the package's grid.\nexport const HostedEventModelBoard = <T extends BoardCollection>({ id, readOnly = false, showMinimap = true, editor, ...props }: HostedEventModelBoardProps<T>) => (\n <BoardProvider readOnly={readOnly} editing={readOnly ? undefined : editor?.editing}\n actions={readOnly ? undefined : editor?.actions} selection={editor?.selection} navigation={editor?.navigation}>\n <HostedEventModelBoardContent<T> key={id.toString()} readOnly={readOnly} showMinimap={showMinimap} editor={editor} {...props} />\n </BoardProvider>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useMemo, type Ref } from 'react';\nimport { estimateCollectionSize, useSliceDetailsVisibility } from '../Collections';\nimport type { EventModel, ModuleCollection } from '../Model';\nimport type { BoardCollections, CollectionGridRenderer } from './BoardCollections';\nimport type { EventModelBoardCanvas, EventModelBoardEditor } from './EventModelBoardEditor';\nimport type { EventModelBoardHandle } from './EventModelBoardHandle';\nimport { HostedEventModelBoard } from './HostedEventModelBoard';\nimport { countCollectionSlices } from './isLargeBoard';\n\nexport interface EventModelBoardProps {\n document: EventModel;\n readOnly?: boolean;\n editor?: EventModelBoardEditor;\n canvas?: EventModelBoardCanvas;\n showMinimap?: boolean;\n handle?: Ref<EventModelBoardHandle>;\n}\n\n// Draws a whole event model document; the editor factory and boundary are never called in read-only mode.\nexport const EventModelBoard = ({ document, readOnly = false, editor, canvas, showMinimap = true, handle }: EventModelBoardProps) => {\n const collectionEditor = readOnly ? undefined : editor?.collection;\n const collectionBoundary = readOnly ? undefined : editor?.collectionBoundary;\n const persistence = readOnly ? undefined : editor?.collections;\n const renderCollection = useCallback((collection: ModuleCollection, grid: CollectionGridRenderer) => {\n const content = grid({ collection, ...collectionEditor?.(collection) });\n return collectionBoundary ? collectionBoundary(collection, content) : content;\n }, [collectionEditor, collectionBoundary]);\n // Collections are estimated as the presentation draws them, so a board showing properties is not\n // measured as if it did not.\n const showsDetails = useSliceDetailsVisibility();\n const estimateSize = useCallback((collection: ModuleCollection) => estimateCollectionSize(collection, showsDetails), [showsDetails]);\n const collections = useMemo<BoardCollections<ModuleCollection>>(() => ({\n initialCollections: document.collections,\n estimateSize,\n countSlices: countCollectionSlices,\n renderCollection,\n ...persistence,\n }), [document.collections, estimateSize, renderCollection, persistence]);\n return <HostedEventModelBoard id={document.id} collections={collections} links={document.links}\n stickyNotes={document.stickyNotes} readOnly={readOnly} editor={editor} canvas={canvas}\n showMinimap={showMinimap} handle={handle} />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode } from 'react';\nimport { ToolbarSlot } from '@cratis/components/Toolbar';\nimport { useBoard } from './useBoard';\n\nexport interface BoardToolbarProps {\n // The toolbar layout the consumer's tools are placed in.\n slotName: string;\n order?: number;\n children?: ReactNode;\n}\n\n// The consumer's tools for the board, such as adding a sticky note. They are offered only on an editable\n// board: a read-only board is often shown inside something else, and tools placed in the host's toolbar\n// would reach a board that is not really open.\nexport const BoardToolbar = ({ slotName, order, children }: BoardToolbarProps) => {\n const { readOnly } = useBoard();\n return readOnly ? undefined : <ToolbarSlot slotName={slotName} order={order}>{children}</ToolbarSlot>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext } from 'react';\nimport type { SliceContextValue } from './SliceContextValue';\n\nexport const SliceContext = createContext<SliceContextValue | undefined>(undefined);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { useMemo } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceStatus, SliceType } from '../Model';\nimport { useBoard } from '../Board';\nimport { resolveSliceReadOnly } from './resolveSliceReadOnly';\nimport { SliceContext } from './SliceContext';\nimport type { SliceContextValue } from './SliceContextValue';\n\nexport interface SliceProviderProps {\n sliceId: Guid;\n sliceType: SliceType;\n status: SliceStatus;\n children?: React.ReactNode;\n}\n\nexport const SliceProvider = ({ sliceId, sliceType, status, children }: SliceProviderProps) => {\n const { readOnly: boardReadOnly, presentation } = useBoard();\n const readOnly = resolveSliceReadOnly(boardReadOnly, presentation.detailLevel, status);\n const value = useMemo<SliceContextValue>(() => ({ readOnly, sliceId, sliceType }), [readOnly, sliceId, sliceType]);\n return <SliceContext.Provider value={value}>{children}</SliceContext.Provider>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useContext } from 'react';\nimport { useBoard } from '../Board';\nimport { SliceContext } from './SliceContext';\nimport type { SliceContextValue } from './SliceContextValue';\n\nexport const useSlice = (): SliceContextValue => {\n const { readOnly } = useBoard();\n return useContext(SliceContext) ?? { readOnly };\n};\n\nexport const useSliceReadOnly = (): boolean => useSlice().readOnly;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/AddButton.css';\nimport './SliceHeader.css';\nimport React from 'react';\nimport type { SliceStatus } from '../Model';\nimport type { SliceHeaderSlice } from './SliceHeaderSlice';\nimport { useBoard } from '../Board';\nimport { CollapseButton, EditableLabel, EntityErrorIndicator } from '../Headers';\nimport { SliceStatusPicker } from '../Statuses';\nimport { SliceTypeExplanation, SliceTypeMenu } from '../SliceTypes';\nimport { GridTooltip } from '../Tooltips';\nimport { useSlice } from './useSlice';\nimport { useEventModelPresentation } from '../Presentation';\n\nexport interface SliceHeaderProps {\n slice: SliceHeaderSlice;\n height: number;\n collapsed: boolean;\n\n // The statuses that may be picked, and why the others cannot. Every status when omitted.\n selectableStatuses?: readonly SliceStatus[];\n unselectableStatusReason?: string;\n // Shown on the header when something done to the slice failed.\n error?: string;\n // What the consumer adds after the collapse button, and between the status and the add menu.\n leading?: React.ReactNode;\n trailing?: React.ReactNode;\n // Collapses or expands the slice on a read-only board, which collapses on its own rather than through editing.\n onToggleCollapse?: () => void;\n}\n\nconst nameStyle: React.CSSProperties = { fontSize: 11, fontWeight: 500, color: 'rgba(255,255,255,0.80)', textAlign: 'center' };\n\nexport const SliceHeader = ({\n slice,\n height,\n collapsed,\n selectableStatuses,\n unselectableStatusReason,\n error,\n leading,\n trailing,\n onToggleCollapse,\n}: SliceHeaderProps) => {\n const board = useBoard();\n const { showStatuses = true } = useEventModelPresentation();\n const { readOnly } = useSlice();\n const { editing, actions } = board;\n const renamed = editing.onSliceRenamed;\n const statusChanged = editing.onSliceStatusChanged;\n const sliceAdded = editing.onSliceAdded;\n const toggleCollapse = editing.onSliceOpenStateSet;\n const headerActions = (actions.sliceHeader ?? []).filter(action => !action.when || action.when(slice));\n\n return (\n <div\n className='event-modeling-grid-slice-column-header'\n style={{ height, cursor: collapsed || readOnly ? 'default' : 'grab', ...(error ? { border: '2px solid #ef4444' } : {}) }}\n >\n <div className='event-modeling-grid-slice-column-header-left'>\n <CollapseButton collapsed={collapsed} onToggle={board.readOnly ? onToggleCollapse : !readOnly && toggleCollapse ? () => toggleCollapse(slice.id, !collapsed) : undefined} />\n {!collapsed && leading}\n </div>\n\n {!collapsed && (\n <div className='event-modeling-grid-slice-column-header-center'>\n <GridTooltip content={<SliceTypeExplanation sliceType={slice.sliceType} />} position='bottom'>\n <EditableLabel\n value={slice.name}\n onChange={value => renamed?.(slice.id, value)}\n placeholder={board.messages.slices.namePlaceholder}\n style={nameStyle}\n readOnly={readOnly || !renamed}\n />\n </GridTooltip>\n {error && <EntityErrorIndicator error={error} />}\n </div>\n )}\n\n {!collapsed && (\n <div className='event-modeling-grid-slice-column-header-right'>\n {showStatuses && <SliceStatusPicker\n status={slice.status}\n onStatusChanged={statusChanged ? next => statusChanged(slice.id, next) : undefined}\n selectable={selectableStatuses}\n unselectableReason={unselectableStatusReason} />}\n {!board.readOnly && trailing}\n {!board.readOnly && headerActions.map(action => (\n <button\n key={action.tooltip}\n type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={action.tooltip}\n aria-label={action.tooltip}\n disabled={readOnly || action.disabled}\n onClick={event => action.onActivate(slice.id, event.currentTarget.getBoundingClientRect())}\n >{action.icon}</button>\n ))}\n {!board.readOnly && sliceAdded && <SliceTypeMenu onSelect={sliceType => sliceAdded(slice.id, sliceType)} disabled={readOnly} />}\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The marker showing where a dragged slice would land.\nconst BASE = 'event-modeling-grid-slice-drop-indicator';\n\n// Names the drop marker for the drag in flight — the same marker in red when the slice cannot legally\n// land there, so the place being pointed at and the answer about it are the one thing being looked at.\n// isValid: Whether the slice may be dropped at this position.\n// Returns The class name for the drop marker.\nexport const dropIndicatorClassName = (isValid: boolean) => isValid ? BASE : `${BASE} ${BASE}--invalid`;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// What a press on a slice has turned out to be, once the pointer has moved.\nexport enum SliceDragGestureVerdict {\n // Not enough has happened yet to tell a click, a drag and a pan apart.\n pending = 'pending',\n\n // The slice is being picked up — start the reorder drag.\n commit = 'commit',\n\n // The gesture belongs to something else — let go of it entirely.\n abandon = 'abandon',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceDragGestureVerdict } from './SliceDragGestureVerdict';\n\n// How far a mouse or pen must travel before a press turns into a drag rather than a click.\nexport const DRAG_THRESHOLD = 4;\n\n// How long a finger must rest on a slice before it picks it up.\nexport const TOUCH_LONG_PRESS_MS = 450;\n\n// How far a finger may drift during the long press without the gesture being read as a pan. Generous\n// next to the mouse threshold because a finger held still on glass still wanders a few pixels.\nexport const TOUCH_LONG_PRESS_TOLERANCE = 10;\n\n// Reads what a press on a slice has become, from how far the pointer has travelled since it went down.\n//\n// The two input kinds answer opposite questions. A mouse has a button, so movement while it is held is\n// unambiguously a drag and commits as soon as it clears the click threshold. A finger has none: one\n// finger anywhere on the board pans it, so movement means the board is being panned, and the only way a\n// finger can mean \"pick this up\" is by staying put long enough for the caller's long-press timer to fire.\n// pointerType: The pointer type reported by the event (`mouse`, `pen` or `touch`).\n// deltaX: How far the pointer has travelled horizontally since it went down.\n// deltaY: How far the pointer has travelled vertically since it went down.\n// Returns What the gesture has turned out to be.\nexport function readSliceDragGesture(pointerType: string, deltaX: number, deltaY: number): SliceDragGestureVerdict {\n const travelledX = Math.abs(deltaX);\n const travelledY = Math.abs(deltaY);\n\n if (pointerType === 'touch') {\n return travelledX > TOUCH_LONG_PRESS_TOLERANCE || travelledY > TOUCH_LONG_PRESS_TOLERANCE\n ? SliceDragGestureVerdict.abandon\n : SliceDragGestureVerdict.pending;\n }\n\n return travelledX > DRAG_THRESHOLD || travelledY > DRAG_THRESHOLD\n ? SliceDragGestureVerdict.commit\n : SliceDragGestureVerdict.pending;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Elements whose own gesture a press belongs to, so a drag must never start from one.\nexport const INTERACTIVE_SELECTOR = 'input, textarea, select, button, a, [role=\"button\"], [contenteditable=\"true\"], .p-dropdown, .p-checkbox';\n\n// The part of a pressed element a press reading looks at, so it can be exercised without a document.\nexport interface PressedElement {\n closest(selectors: string): unknown;\n}\n\n// What a pointer event carries that says where a press on a slice landed.\nexport interface SlicePressEvent {\n // The element the press landed on — a genuinely interactive one owns the press itself.\n target: PressedElement | null;\n clientX: number;\n clientY: number;\n pointerId: number;\n pointerType: string;\n // The top edge of the slice's surface, so a ghost keeps the offset the slice was grabbed at.\n elementTop: number;\n}\n\n// Where a press on a slice started, once it is known to be the slice's own to answer.\nexport interface SlicePress {\n startX: number;\n startY: number;\n grabOffsetY: number;\n pointerId: number;\n pointerType: string;\n}\n\n// Reads where a press on a slice's surface started, or that the slice has no business answering it.\n//\n// A slice is picked up from anywhere on it — its title and its cells included, which are editable labels\n// (Cratis/StudioIssues#237). Only genuinely interactive elements keep their own gesture.\n//\n// Reading a press deliberately decides nothing about the pointer it arrived on: a press is still only a\n// press, and it may yet turn out to be the double click that opens a label for editing. Claiming the\n// pointer here would retarget that click at the slice and the label would never see it, so the pointer\n// is taken only once the gesture has proven itself a drag.\n// event: Where the press landed and what pressed.\n// disabled: Whether the slice can be dragged at all — a collapsed column cannot.\n// Returns Where the press started, or `null` when the press is not the slice's to answer.\nexport function readSlicePress(event: SlicePressEvent, disabled: boolean): SlicePress | null {\n if (disabled) return null;\n if (event.target?.closest(INTERACTIVE_SELECTOR)) return null;\n\n return {\n startX: event.clientX,\n startY: event.clientY,\n grabOffsetY: event.clientY - event.elementTop,\n pointerId: event.pointerId,\n pointerType: event.pointerType,\n };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceDragGhost.css';\nimport { useEffect, useRef } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { SliceDragState } from './useSliceDrag';\n\n// Just enough tilt that the copy under the pointer reads as lifted off the board rather than as a second\n// slice sitting on it.\nconst ghostTiltDegrees = 3;\n\nexport interface SliceDragGhostProps {\n drag?: SliceDragState;\n // The height of the labelled stand-in drawn when the slice could not be copied.\n headerHeight: number;\n}\n\n// The slice being dragged, drawn over everything at the pointer: dimmed and tilted, red with the reason\n// when the consumer's rule says it should not land where it is.\nexport const SliceDragGhost = ({ drag, headerHeight }: SliceDragGhostProps) =>\n drag ? createPortal(<SliceGhost drag={drag} headerHeight={headerHeight} />, document.body) : undefined;\n\nconst SliceGhost = ({ drag, headerHeight }: { drag: SliceDragState; headerHeight: number }) => {\n const isInvalid = !drag.isValid;\n const snapshotHost = useRef<HTMLDivElement | null>(null);\n const ghost = drag.ghost;\n\n // The snapshot is a detached DOM node rather than markup React owns, so it is placed by hand. Cloning\n // the live slice is what makes the thing under the pointer look like the slice being moved instead of\n // a label-sized stand-in; re-deriving that appearance in JSX would mean maintaining a second slice.\n useEffect(() => {\n const host = snapshotHost.current;\n if (!host || !ghost) return;\n host.replaceChildren(ghost);\n return () => host.replaceChildren();\n }, [ghost]);\n\n return (\n <div\n style={{\n position: 'fixed',\n left: drag.currentX - drag.ghostWidth / 2 * drag.zoom,\n top: drag.headerY,\n transform: `scale(${drag.zoom}) rotate(${ghostTiltDegrees}deg)`,\n transformOrigin: '0 0',\n pointerEvents: 'none',\n zIndex: 9998,\n userSelect: 'none',\n }}\n >\n {ghost\n ? (\n <div\n ref={snapshotHost}\n className={`event-modeling-grid-slice-ghost${isInvalid ? ' event-modeling-grid-slice-ghost--invalid' : ''}`}\n style={{ width: drag.ghostWidth }}\n />\n )\n : (\n <div\n className={`event-modeling-grid-slice-ghost-fallback${isInvalid ? ' event-modeling-grid-slice-ghost-fallback--invalid' : ''}`}\n style={{ width: drag.ghostWidth, height: headerHeight }}\n >\n {isInvalid && <i className='pi pi-ban' aria-hidden='true' />}\n <span>{drag.ghostLabel}</span>\n </div>\n )}\n {isInvalid && drag.invalidReason && (\n <div className='event-modeling-grid-slice-ghost-reason' style={{ maxWidth: drag.ghostWidth }}>\n {drag.invalidReason}\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { dropIndicatorClassName } from './dropIndicatorClassName';\n\nexport interface SliceDropIndicatorProps {\n isValid: boolean;\n marginLeft: number;\n}\n\n// The gap a dragged slice would drop into.\nexport const SliceDropIndicator = ({ isValid, marginLeft }: SliceDropIndicatorProps) => (\n <div className={dropIndicatorClassName(isValid)} style={{ marginLeft }} />\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface SliceDropTargetProps {\n moduleId: Guid;\n featureId: Guid;\n // Highlighted while a dragged slice is over it.\n active?: boolean;\n busy?: boolean;\n acceptsReorder?: boolean;\n acceptsMove?: boolean;\n style?: React.CSSProperties;\n className?: string;\n children?: React.ReactNode;\n}\n\n// Where the slices of one feature are laid out, and what a slice drag finds to drop into.\nexport const SliceDropTarget = ({ moduleId, featureId, active = false, busy = false, acceptsReorder = true, acceptsMove = true, style, className, children }: SliceDropTargetProps) => (\n <div\n data-slice-drop-target='true'\n data-slice-module-id={moduleId.toString()}\n data-slice-feature-id={featureId.toString()}\n data-slice-accepts-reorder={acceptsReorder}\n data-slice-accepts-move={acceptsMove}\n aria-busy={busy || undefined}\n className={[active && 'event-modeling-grid-slice-drop-target--active', className].filter(Boolean).join(' ') || undefined}\n style={style}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface SliceDropPosition {\n featureId: Guid;\n targetFeatureId: Guid;\n sourceIndex: number;\n dropIndex: number;\n}\n\n// Where a dropped slice ends up, or nothing when it was put back where it was. The drop index counts the\n// gaps between slices as they stand, so within a feature a slice dropped after itself lands one earlier.\nexport const sliceMove = (position: SliceDropPosition): { index: number } | undefined => {\n if (!position.targetFeatureId.equals(position.featureId)) return { index: position.dropIndex };\n const index = position.dropIndex > position.sourceIndex ? position.dropIndex - 1 : position.dropIndex;\n return index === position.sourceIndex ? undefined : { index };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport type { SliceDropVerdict } from './SliceDropVerdict';\nimport type { SliceMoved } from './SliceMoved';\nimport type { ValidateSliceDrop } from './ValidateSliceDrop';\nimport { sliceMove } from './sliceMove';\n\n// Minimal feature shape required for slice drag behavior.\nexport interface DraggableFeature {\n id: Guid;\n slices: ReadonlyArray<{ id: Guid }>;\n}\n\n// Internal drag state tracked during a slice reorder gesture.\nexport interface SliceDragState {\n sliceId: Guid;\n moduleId: Guid;\n featureId: Guid;\n targetFeatureId: Guid;\n sourceIndex: number;\n ghostLabel: string;\n ghostWidth: number;\n // A detached copy of the slice as it looked when it was picked up, rendered as the thing being moved.\n ghost: HTMLElement | null;\n currentX: number;\n currentY: number;\n dropIndex: number;\n headerY: number;\n zoom: number;\n // False when the consumer's rule says the slice should not land at the drop position, and why.\n isValid: boolean;\n invalidReason?: string;\n}\n\n// Encapsulates the pointer-driven slice reorder drag behavior for a single feature.\nexport function useSliceDrag(\n feature: DraggableFeature,\n moduleId: Guid,\n onSliceMoved?: SliceMoved,\n validateSliceDrop?: ValidateSliceDrop,\n) {\n const [sliceDrag, setSliceDrag] = useState<SliceDragState>();\n const sliceDragRef = useRef<SliceDragState | undefined>(undefined);\n sliceDragRef.current = sliceDrag;\n\n const validateDropRef = useRef<ValidateSliceDrop | undefined>(validateSliceDrop);\n validateDropRef.current = validateSliceDrop;\n const movedRef = useRef<SliceMoved | undefined>(onSliceMoved);\n movedRef.current = onSliceMoved;\n const { readOnly } = useBoard();\n\n // Validation advises where a slice may land; it must never take the gesture down with it. A\n // throwing validator once made every slice undraggable because the exception escaped the\n // pointer handler before the drag state was even set (Cratis/StudioIssues#237).\n const safeValidateDrop = useCallback((draggedSliceId: Guid, targetFeatureId: Guid, dropIndex: number): SliceDropVerdict | undefined => {\n try {\n return validateDropRef.current?.(draggedSliceId, targetFeatureId, dropIndex);\n } catch (error) {\n console.error('Slice drop validation failed — allowing the drop', error);\n return undefined;\n }\n }, []);\n\n const targetSupportsDrop = useCallback((moduleId: Guid, sourceFeatureId: Guid, targetFeatureId: Guid): boolean => {\n const target = document.querySelector<HTMLElement>(`[data-slice-drop-target=\"true\"][data-slice-module-id=\"${moduleId.toString()}\"][data-slice-feature-id=\"${targetFeatureId.toString()}\"]`);\n return targetFeatureId.equals(sourceFeatureId)\n ? target?.dataset.sliceAcceptsReorder === 'true' : target?.dataset.sliceAcceptsMove === 'true';\n }, []);\n\n const handleSliceDragStart = useCallback((sliceId: Guid, sliceName: string, clientX: number, clientY: number, columnWidth: number, headerY: number, zoom: number, ghost: HTMLElement | null = null) => {\n const sourceIndex = feature.slices.findIndex(s => s.id.equals(sliceId));\n if (sourceIndex === -1) return;\n const validation = safeValidateDrop(sliceId, feature.id, sourceIndex);\n setSliceDrag({\n sliceId,\n moduleId,\n featureId: feature.id,\n targetFeatureId: feature.id,\n sourceIndex,\n ghostLabel: sliceName,\n ghostWidth: columnWidth,\n ghost,\n currentX: clientX,\n currentY: clientY,\n dropIndex: sourceIndex,\n headerY,\n zoom,\n isValid: (validation?.isValid ?? true) && targetSupportsDrop(moduleId, feature.id, feature.id),\n invalidReason: validation?.reason,\n });\n }, [feature, moduleId, safeValidateDrop, targetSupportsDrop]);\n\n const computeDropFeatureId = useCallback((moduleId: Guid, clientX: number): Guid => {\n const targets = Array.from(\n document.querySelectorAll<HTMLElement>(`[data-slice-drop-target=\"true\"][data-slice-module-id=\"${moduleId.toString()}\"]`)\n );\n if (targets.length === 0) return feature.id;\n for (let index = 0; index < targets.length; index++) {\n const rect = targets[index].getBoundingClientRect();\n if (clientX < rect.left + rect.width / 2) {\n return Guid.parse(targets[index].dataset.sliceFeatureId!);\n }\n }\n return Guid.parse(targets[targets.length - 1].dataset.sliceFeatureId!);\n }, [feature.id]);\n\n const computeDropIndex = useCallback((featureId: Guid, clientX: number): number => {\n const cols = Array.from(\n document.querySelectorAll<HTMLElement>(`[data-slice-col=\"true\"][data-slice-feature-id=\"${featureId.toString()}\"]`)\n );\n if (cols.length === 0) return 0;\n for (let index = 0; index < cols.length; index++) {\n const rect = cols[index].getBoundingClientRect();\n if (clientX < rect.left + rect.width / 2) return index;\n }\n return cols.length;\n }, []);\n\n useEffect(() => {\n if (!sliceDrag) return;\n\n const handlePointerMove = (event: PointerEvent) => {\n const drag = sliceDragRef.current;\n if (!drag) return;\n const targetFeatureId = computeDropFeatureId(drag.moduleId, event.clientX);\n const dropIndex = computeDropIndex(targetFeatureId, event.clientX);\n const validation = safeValidateDrop(drag.sliceId, targetFeatureId, dropIndex);\n setSliceDrag(previous => previous ? {\n ...previous,\n currentX: event.clientX,\n currentY: event.clientY,\n targetFeatureId,\n dropIndex,\n isValid: (validation?.isValid ?? true) && targetSupportsDrop(drag.moduleId, drag.featureId, targetFeatureId),\n invalidReason: validation?.reason,\n } : undefined);\n };\n\n const handlePointerUp = () => {\n const drag = sliceDragRef.current;\n const move = drag && sliceMove(drag);\n if (drag && move && targetSupportsDrop(drag.moduleId, drag.featureId, drag.targetFeatureId)) movedRef.current?.(drag.sliceId, drag.featureId, drag.targetFeatureId, move.index);\n setSliceDrag(undefined);\n };\n\n // Capture phase, and on window: the slice that started the drag stops these events from bubbling\n // any further, so the canvas underneath does not pan through the same gesture on a touch device.\n // A bubble-phase listener here would be stopped along with it.\n window.addEventListener('pointermove', handlePointerMove, true);\n window.addEventListener('pointerup', handlePointerUp, true);\n window.addEventListener('pointercancel', handlePointerUp, true);\n return () => {\n window.removeEventListener('pointermove', handlePointerMove, true);\n window.removeEventListener('pointerup', handlePointerUp, true);\n window.removeEventListener('pointercancel', handlePointerUp, true);\n };\n }, [sliceDrag, computeDropFeatureId, computeDropIndex, safeValidateDrop, targetSupportsDrop]);\n\n // A slice can only be picked up on an editable board whose consumer is told where it went.\n return { sliceDrag, handleSliceDragStart: readOnly || !onSliceMoved ? undefined : handleSliceDragStart };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useEffect, useRef, useState } from 'react';\nimport type React from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { createSliceDragGhost } from './snapshotSlice';\nimport { readSliceDragGesture, TOUCH_LONG_PRESS_MS } from './readSliceDragGesture';\nimport { readSlicePress, type SlicePress } from './readSlicePress';\nimport { SliceDragGestureVerdict } from './SliceDragGestureVerdict';\n\n// Fired once a drag gesture is committed to, handing off to the reorder drag state machine.\nexport type SliceDragStartHandler = (\n sliceId: Guid,\n sliceName: string,\n clientX: number,\n clientY: number,\n columnWidth: number,\n headerY: number,\n zoom: number,\n ghost: HTMLElement | null,\n) => void;\n\n// A press the slice has taken on, and how far it has got towards becoming a drag.\ninterface DragIntent extends SlicePress {\n // The slice's surface the press landed on, which the ghost is snapshotted from.\n element: HTMLElement;\n // True once the gesture has been claimed, so moves stop reaching the canvas underneath.\n committed: boolean;\n}\n\n// Pointer handlers meant to be attached to a slice's outer surface to detect a reorder-drag gesture.\nexport interface SliceDragIntentHandlers {\n onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => void;\n onPointerMove: (event: React.PointerEvent<HTMLDivElement>) => void;\n onPointerUp: () => void;\n onContextMenu: (event: React.MouseEvent<HTMLDivElement>) => void;\n}\n\n// Decides whether a press on a slice is the start of a reorder drag, and hands off to `onSliceDragStart`\n// once it is.\n//\n// A slice is picked up from anywhere on its surface — its title and its cells included. Those are\n// editable labels, and excluding them left almost nothing of a slice to grab (Cratis/StudioIssues#237);\n// they open on a double click, which the movement threshold never mistakes for a drag. Only genuinely\n// interactive elements keep their own gesture.\n//\n// Mouse and pen keep the gesture away from the canvas on the press, so it cannot also start a pan, and\n// commit once the pointer leaves the click threshold. Touch cannot do that: one finger anywhere on the\n// board pans it, so claiming a touch on the press would make a board of slices impossible to scroll. A\n// finger has to rest on the slice instead — the long press is what separates \"move this\" from \"move the\n// board\" — and only when it fires does the gesture stop reaching the canvas underneath.\n//\n// Until a press has proven itself a drag it is watched from the window, and the pointer is captured only\n// once it has. Capturing on the press instead retargets every later event at the slice, and a browser\n// fires `click` — and therefore `dblclick` — at the common ancestor of where the pointer went down and\n// came up. A press that went down on a label came up on the captured slice, so the double click landed\n// on the slice and the label it started on never saw the gesture that opens it for renaming.\n// sliceId: The slice being pressed.\n// sliceName: The slice's name, shown on the ghost when it cannot be snapshotted.\n// columnWidth: The rendered width of the slice column.\n// disabled: Whether the slice can be dragged at all — a collapsed column cannot, nor one without an id.\n// onSliceDragStart: Called once the gesture is committed to.\n// Returns The pointer handlers to attach to the slice's outer surface.\nexport function useSliceDragIntent(\n sliceId: Guid | undefined,\n sliceName: string,\n columnWidth: number,\n disabled: boolean,\n onSliceDragStart?: SliceDragStartHandler,\n): SliceDragIntentHandlers {\n const [dragIntent, setDragIntent] = useState<DragIntent | null>(null);\n const longPressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const startDrag = useRef(onSliceDragStart);\n startDrag.current = onSliceDragStart;\n\n const cancelLongPress = () => {\n if (longPressTimer.current !== null) {\n clearTimeout(longPressTimer.current);\n longPressTimer.current = null;\n }\n };\n\n const begin = (intent: DragIntent, clientX: number, clientY: number) => {\n cancelLongPress();\n setDragIntent({ ...intent, committed: true });\n intent.element.setPointerCapture(intent.pointerId);\n if (!sliceId) return;\n startDrag.current?.(\n sliceId,\n sliceName,\n clientX,\n clientY,\n columnWidth,\n intent.startY - intent.grabOffsetY,\n zoomOf(intent.element),\n createSliceDragGhost(intent.element));\n };\n\n // A press that has not yet earned the slice is watched from the window rather than from the slice,\n // because the slice does not hold the pointer yet: a finger's moves are the canvas's until the long\n // press fires, and a mouse that leaves the column mid-gesture stops delivering moves here at all. The\n // window sees every move either way, so a fast drag out of a narrow header still picks the slice up\n // and a finger that swiped off it does not get the board yanked away when the timer goes off.\n useEffect(() => {\n if (!dragIntent || dragIntent.committed) return;\n\n const settle = (event: PointerEvent) => {\n if (event.pointerId !== dragIntent.pointerId) return;\n const verdict = readSliceDragGesture(\n dragIntent.pointerType,\n event.clientX - dragIntent.startX,\n event.clientY - dragIntent.startY);\n if (verdict === SliceDragGestureVerdict.abandon) setDragIntent(null);\n if (verdict === SliceDragGestureVerdict.commit) begin(dragIntent, event.clientX, event.clientY);\n };\n\n const release = (event: PointerEvent) => {\n if (event.pointerId === dragIntent.pointerId) setDragIntent(null);\n };\n\n window.addEventListener('pointermove', settle, true);\n window.addEventListener('pointerup', release, true);\n window.addEventListener('pointercancel', release, true);\n return () => {\n window.removeEventListener('pointermove', settle, true);\n window.removeEventListener('pointerup', release, true);\n window.removeEventListener('pointercancel', release, true);\n };\n }, [dragIntent]);\n\n // The pending press is what the timer belongs to: it is armed when one starts, and torn down with it\n // however it ends — committed, abandoned, or the slice unmounted mid-press.\n useEffect(() => {\n if (!dragIntent || dragIntent.committed || dragIntent.pointerType !== 'touch') return cancelLongPress;\n longPressTimer.current = setTimeout(\n () => begin(dragIntent, dragIntent.startX, dragIntent.startY),\n TOUCH_LONG_PRESS_MS);\n // Keyed on the press alone: `begin` is rebuilt every render but reads only what it is handed\n // and the latest handler ref, so re-arming the timer on an unrelated render would be wrong.\n return cancelLongPress;\n }, [dragIntent]);\n\n const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n const element = event.currentTarget;\n if (!sliceId) return;\n const press = readSlicePress({\n target: event.target instanceof Element ? event.target : null,\n clientX: event.clientX,\n clientY: event.clientY,\n pointerId: event.pointerId,\n pointerType: event.pointerType,\n elementTop: element.getBoundingClientRect().top,\n }, disabled);\n if (!press) return;\n\n setDragIntent({ ...press, element, committed: false });\n\n // A touch is deliberately not held off the canvas yet: until the long press fires this is still\n // the canvas's gesture, and swallowing it here is what used to make the board unpannable over a\n // slice. The pointer itself stays untaken for every kind of press until the gesture commits.\n if (event.pointerType === 'touch') return;\n\n event.stopPropagation();\n };\n\n // A pending press is settled from the window listener above, where every move reaches. By the time\n // moves arrive here the drag owns the gesture, so the canvas must not also pan through it — the drag\n // state machine listens in the capture phase, so it still sees every move this stops.\n const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n if (dragIntent?.committed) event.stopPropagation();\n };\n\n const onPointerUp = () => setDragIntent(null);\n\n // A long press on a touch device is also how a context menu is asked for. The slice answers the press\n // by picking itself up, so the menu would land on top of a drag already in flight.\n const onContextMenu = (event: React.MouseEvent<HTMLDivElement>) => {\n if (dragIntent?.committed) event.preventDefault();\n };\n\n return { onPointerDown, onPointerMove, onPointerUp, onContextMenu };\n}\n\n// Reads the board's current zoom off the nearest ancestor that scales, so the ghost matches the board.\nfunction zoomOf(element: HTMLElement): number {\n let current: HTMLElement | null = element.parentElement;\n while (current) {\n const scale = current.style.transform.match(/scale\\(([^)]+)\\)/);\n if (scale) return parseFloat(scale[1]);\n current = current.parentElement;\n }\n return 1;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceColumnFrame.css';\nimport React from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceStatus } from '../Model';\nimport { sliceStatusName } from '../Statuses';\nimport { useSliceDragIntent, type SliceDragStartHandler } from '../SliceDragging';\nimport { useSlice } from './useSlice';\n\nexport interface SliceColumnFrameProps {\n featureId: Guid;\n name: string;\n status: SliceStatus;\n width: number;\n collapsed: boolean;\n // The slice is the one being dragged, so the column dims while its ghost follows the pointer.\n isDragging?: boolean;\n // Without it the slice cannot be picked up.\n onDragStart?: SliceDragStartHandler;\n ref?: React.Ref<HTMLDivElement>;\n onMouseEnter?: () => void;\n onMouseLeave?: () => void;\n onFocusCapture?: (event: React.FocusEvent<HTMLDivElement>) => void;\n onBlurCapture?: (event: React.FocusEvent<HTMLDivElement>) => void;\n children?: React.ReactNode;\n}\n\n// The dashed frame around one slice, tinted by its status, and what a slice drag picks up. A drag finds\n// the columns of a feature by the attributes it carries.\nexport const SliceColumnFrame = ({\n featureId,\n name,\n status,\n width,\n collapsed,\n isDragging = false,\n onDragStart,\n ref,\n onMouseEnter,\n onMouseLeave,\n onFocusCapture,\n onBlurCapture,\n children,\n}: SliceColumnFrameProps) => {\n const { sliceId } = useSlice();\n // A slice nobody is told about moving is not picked up at all, so a press on it pans the board instead.\n const drag = useSliceDragIntent(sliceId, name, width, collapsed || !onDragStart, onDragStart);\n\n return (\n <div\n ref={ref}\n data-slice-col='true'\n data-slice-feature-id={featureId.toString()}\n data-slice-id={sliceId?.toString()}\n className={`event-modeling-grid-slice-column event-modeling-grid-slice-column--${sliceStatusName(status)}${collapsed ? ' event-modeling-grid-slice-column--collapsed' : ''}`}\n style={{ width, cursor: collapsed || !onDragStart ? 'default' : 'grab', transition: 'opacity 0.15s', ...(isDragging ? { opacity: 0.35 } : {}) }}\n onMouseEnter={onMouseEnter}\n onMouseLeave={onMouseLeave}\n onFocusCapture={onFocusCapture}\n onBlurCapture={onBlurCapture}\n onPointerDown={drag.onPointerDown}\n onPointerMove={drag.onPointerMove}\n onPointerUp={drag.onPointerUp}\n onPointerCancel={drag.onPointerUp}\n onContextMenu={drag.onContextMenu}\n >\n {children}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useEffect, useRef, useState, type FocusEvent, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceHeaderSlice } from './SliceHeaderSlice';\nimport { useBoard } from '../Board';\nimport { sliceColumnWidth } from '../Layout';\nimport { useConnectionHighlight, useSliceConnection } from '../Connections';\nimport { useInViewport } from '../Viewport';\nimport type { SliceDragStartHandler } from '../SliceDragging';\nimport { SliceProvider } from './SliceProvider';\nimport { SliceColumnFrame } from './SliceColumnFrame';\nimport { SliceHeader } from './SliceHeader';\n\nexport interface SliceColumnProps {\n featureId: Guid;\n slice: SliceHeaderSlice;\n eventCount: number;\n collapsed: boolean;\n isDragging?: boolean;\n onSliceDragStart?: SliceDragStartHandler;\n header?: ReactNode;\n headerHeight?: number;\n body: ReactNode | ((inView: boolean) => ReactNode);\n specifications?: ReactNode | ((inView: boolean, width: number) => ReactNode);\n collapsedWidth: number;\n}\n\n// The frame, highlight and viewport lifetime of one contract slice. The consumer supplies the content\n// until the slices area moves into the package; off-screen bodies can render a sized placeholder.\nexport const SliceColumn = ({ featureId, slice, eventCount, collapsed, isDragging = false, onSliceDragStart, header, headerHeight = 44, body, specifications, collapsedWidth }: SliceColumnProps) => {\n const { readOnly } = useBoard();\n const connection = useSliceConnection(slice.id.toString());\n const { ref: highlightRef, onMouseEnter: applyHighlight, onMouseLeave: clearHighlight } = useConnectionHighlight(connection?.connectedSliceIds);\n const columnRef = useRef<HTMLDivElement>(null);\n const inView = useInViewport(columnRef);\n const [isEditing, setIsEditing] = useState(false);\n const isHoveredRef = useRef(false);\n const specificationsWidth = sliceColumnWidth({ sliceType: slice.sliceType, eventCount });\n\n const handleMouseEnter = () => {\n isHoveredRef.current = true;\n applyHighlight();\n };\n const handleMouseLeave = () => {\n isHoveredRef.current = false;\n if (!isEditing) clearHighlight();\n };\n const handleBlurCapture = (event: FocusEvent<HTMLDivElement>) => {\n const next = event.relatedTarget;\n if (!(next instanceof Node) || !event.currentTarget.contains(next)) setIsEditing(false);\n };\n\n useEffect(() => {\n if (!isEditing && !isHoveredRef.current) clearHighlight();\n }, [isEditing, clearHighlight]);\n\n return (\n <SliceProvider sliceId={slice.id} sliceType={slice.sliceType} status={slice.status}>\n <div ref={columnRef} style={{ display: 'flex', flexDirection: 'column', alignItems: 'stretch', flexShrink: 0 }}>\n <SliceColumnFrame\n ref={highlightRef}\n featureId={featureId}\n name={slice.name}\n status={slice.status}\n width={collapsed ? collapsedWidth : specificationsWidth}\n collapsed={collapsed}\n isDragging={isDragging}\n onDragStart={readOnly ? undefined : onSliceDragStart}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onFocusCapture={() => setIsEditing(true)}\n onBlurCapture={handleBlurCapture}\n >\n {header ?? <SliceHeader slice={slice} height={headerHeight} collapsed={collapsed} />}\n {typeof body === 'function' ? body(inView) : inView && body}\n </SliceColumnFrame>\n {typeof specifications === 'function' ? specifications(inView, specificationsWidth) : inView && specifications}\n </div>\n </SliceProvider>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Guid } from '@cratis/fundamentals';\nimport { SliceStatus, SliceType, type Slice } from '../Model';\nimport type { SliceNames } from './SliceNames';\n\n// A slice is displayed before persistence returns its real id. The Studio adapter converts this\n// contract value to the shape its editor kits need; no server or generated type reaches the board.\nexport const createOptimisticSlice = (sliceType: SliceType, names?: SliceNames): Slice => {\n const commandId = Guid.create();\n const eventId = Guid.create();\n const readModelId = Guid.create();\n return {\n id: Guid.create(),\n name: names?.name?.trim() || (sliceType === SliceType.stateChange ? 'State Change' :\n sliceType === SliceType.stateView ? 'State View' : sliceType === SliceType.automation ? 'Automation' : 'Translator'),\n sliceType, description: '', status: SliceStatus.notStarted, collapsed: false, sortOrder: Number.MAX_SAFE_INTEGER,\n command: sliceType === SliceType.stateView ? undefined : {\n id: commandId, name: names?.commandName?.trim() || 'Command', schema: {}, stateSchema: {}, rules: [], logicDescription: '',\n },\n readModel: sliceType === SliceType.stateView ? {\n id: readModelId, name: names?.readModelName?.trim() || 'Read Model', schema: {}, materializes: true,\n } : undefined,\n events: sliceType === SliceType.stateChange ? [{ id: eventId, name: names?.eventName?.trim() || 'Event', schema: {}, sourceEventId: '' }] : [],\n externalEvents: [], actors: [], queries: [], specifications: [], commentCount: 0,\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface SliceAreaItem {\n id: Guid;\n name: string;\n collapsed: boolean;\n}\n\ninterface PendingAddition<T> {\n slice: T;\n afterSliceId?: Guid;\n confirmed: boolean;\n}\n\ninterface PendingMove<T> {\n slice: T;\n index: number;\n confirmed: boolean;\n}\n\nexport interface SliceAreaState<T extends SliceAreaItem> {\n slices: T[];\n snapshot: T[];\n additions: PendingAddition<T>[];\n outgoing: PendingMove<T>[];\n incoming: PendingMove<T>[];\n order?: { ids: Guid[]; confirmed: boolean };\n}\n\nconst matches = (first: Guid, second: Guid) => first.equals(second);\nconst contains = <T extends SliceAreaItem>(slices: T[], id: Guid) => slices.some(slice => matches(slice.id, id));\n\nexport const createSliceAreaState = <T extends SliceAreaItem>(slices: T[]): SliceAreaState<T> =>\n ({ slices, snapshot: slices, additions: [], outgoing: [], incoming: [] });\n\nexport const insertSlice = <T extends SliceAreaItem>(slices: T[], slice: T, afterSliceId?: Guid): T[] => {\n if (!afterSliceId) return [...slices, slice];\n const index = slices.findIndex(existing => existing.id.equals(afterSliceId));\n if (index < 0) return [...slices, slice];\n const next = [...slices];\n next.splice(index + 1, 0, slice);\n return next;\n};\n\nexport const settleAddedSlice = <T extends SliceAreaItem>(slices: T[], temporaryId: Guid, persistedId?: Guid): T[] =>\n persistedId\n ? slices.map(slice => slice.id.equals(temporaryId) ? { ...slice, id: persistedId } : slice)\n : slices.filter(slice => !slice.id.equals(temporaryId));\n\nexport const addPendingSlice = <T extends SliceAreaItem>(state: SliceAreaState<T>, slice: T, afterSliceId?: Guid): SliceAreaState<T> => ({\n ...state, slices: insertSlice(state.slices, slice, afterSliceId),\n additions: [...state.additions, { slice, afterSliceId, confirmed: false }],\n});\n\nexport const addProjectedSlice = <T extends SliceAreaItem>(state: SliceAreaState<T>, slice: T, afterSliceId?: Guid): SliceAreaState<T> =>\n contains(state.slices, slice.id) ? state : {\n ...state, slices: insertSlice(state.slices, slice, afterSliceId),\n additions: [...state.additions, { slice, afterSliceId, confirmed: true }],\n };\n\nexport const completeAddedSlice = <T extends SliceAreaItem>(state: SliceAreaState<T>, temporaryId: Guid, persistedId?: Guid): SliceAreaState<T> => {\n const next = {\n ...state,\n slices: settleAddedSlice(state.slices, temporaryId, persistedId),\n additions: persistedId\n ? state.additions.map(addition => matches(addition.slice.id, temporaryId)\n ? { ...addition, slice: { ...addition.slice, id: persistedId }, confirmed: true } : addition)\n : state.additions.filter(addition => !matches(addition.slice.id, temporaryId)),\n order: state.order && persistedId ? {\n ...state.order, ids: state.order.ids.map(id => matches(id, temporaryId) ? persistedId : id),\n } : state.order,\n };\n return persistedId ? reconcileSliceSnapshot(next, state.snapshot) : next;\n};\n\nexport const moveSliceInArea = <T extends SliceAreaItem>(slices: T[], fromIndex: number, toIndex: number): T[] => {\n if (!Number.isInteger(fromIndex) || fromIndex < 0 || fromIndex >= slices.length) return slices;\n const requestedIndex = Number.isInteger(toIndex) ? toIndex : fromIndex;\n const targetIndex = Math.min(Math.max(requestedIndex, 0), slices.length - 1);\n if (fromIndex === targetIndex) return slices;\n const next = [...slices];\n next.splice(targetIndex, 0, ...next.splice(fromIndex, 1));\n return next;\n};\n\nexport const reorderPendingSlices = <T extends SliceAreaItem>(state: SliceAreaState<T>, fromIndex: number, toIndex: number): SliceAreaState<T> => {\n const slices = moveSliceInArea(state.slices, fromIndex, toIndex);\n return slices === state.slices ? state : { ...state, slices, order: { ids: slices.map(slice => slice.id), confirmed: false } };\n};\n\nexport const completeReorder = <T extends SliceAreaItem>(state: SliceAreaState<T>, succeeded: boolean): SliceAreaState<T> =>\n succeeded ? reconcileSliceSnapshot({ ...state, order: state.order && { ...state.order, confirmed: true } }, state.snapshot)\n : reconcileSliceSnapshot({ ...state, order: undefined }, state.snapshot);\n\nexport const movePendingSliceOut = <T extends SliceAreaItem>(state: SliceAreaState<T>, id: Guid): SliceAreaState<T> => {\n const index = state.slices.findIndex(slice => matches(slice.id, id));\n if (index < 0) return state;\n return { ...state, slices: state.slices.filter(slice => !matches(slice.id, id)),\n outgoing: [...state.outgoing, { slice: state.slices[index], index, confirmed: false }] };\n};\n\nexport const completeMoveOut = <T extends SliceAreaItem>(state: SliceAreaState<T>, id: Guid, succeeded: boolean): SliceAreaState<T> => {\n const move = state.outgoing.find(entry => matches(entry.slice.id, id));\n if (!move) return state;\n const next = { ...state,\n slices: succeeded ? state.slices : insertAt(state.slices, move.slice, move.index),\n outgoing: succeeded ? state.outgoing.map(entry => matches(entry.slice.id, id) ? { ...entry, confirmed: true } : entry)\n : state.outgoing.filter(entry => !matches(entry.slice.id, id)),\n };\n return succeeded ? reconcileSliceSnapshot(next, state.snapshot) : next;\n};\n\nconst insertAt = <T extends SliceAreaItem>(slices: T[], slice: T, index: number): T[] => {\n if (contains(slices, slice.id)) return slices;\n const next = [...slices];\n next.splice(Math.min(Math.max(index, 0), next.length), 0, slice);\n return next;\n};\n\nexport const movePendingSliceIn = <T extends SliceAreaItem>(state: SliceAreaState<T>, slice: T, index: number): SliceAreaState<T> => {\n if (contains(state.slices, slice.id) || state.incoming.some(entry => matches(entry.slice.id, slice.id))) return state;\n return { ...state, slices: insertAt(state.slices, slice, index),\n incoming: [...state.incoming, { slice, index, confirmed: false }] };\n};\n\nexport const completeMoveIn = <T extends SliceAreaItem>(state: SliceAreaState<T>, id: Guid, succeeded: boolean): SliceAreaState<T> => {\n if (!state.incoming.some(entry => matches(entry.slice.id, id))) return state;\n const next = {\n ...state,\n slices: succeeded ? state.slices : state.slices.filter(slice => !matches(slice.id, id)),\n incoming: succeeded ? state.incoming.map(entry => matches(entry.slice.id, id) ? { ...entry, confirmed: true } : entry)\n : state.incoming.filter(entry => !matches(entry.slice.id, id)),\n };\n return succeeded ? reconcileSliceSnapshot(next, state.snapshot) : next;\n};\n\nexport const reconcileSliceSnapshot = <T extends SliceAreaItem>(state: SliceAreaState<T>, snapshot: T[]): SliceAreaState<T> => {\n const additions = state.additions.filter(entry => !entry.confirmed || !contains(snapshot, entry.slice.id));\n const outgoing = state.outgoing.filter(entry => !entry.confirmed || contains(snapshot, entry.slice.id));\n const incoming = state.incoming.filter(entry => !entry.confirmed || !contains(snapshot, entry.slice.id));\n const orderedIds = state.order?.ids.filter(id => contains(snapshot, id));\n const projectedIds = snapshot.filter(slice => orderedIds?.some(id => matches(id, slice.id))).map(slice => slice.id);\n const orderCaughtUp = orderedIds !== undefined && orderedIds.length > 0\n && orderedIds.every((id, index) => matches(id, projectedIds[index]));\n const order = state.order?.confirmed && orderCaughtUp ? undefined : state.order;\n const current = (id: Guid, fallback: T) => state.slices.find(slice => matches(slice.id, id)) ?? fallback;\n const visible = snapshot.filter(slice => !outgoing.some(entry => matches(entry.slice.id, slice.id)))\n .map(slice => state.additions.some(entry => matches(entry.slice.id, slice.id)) || state.incoming.some(entry => matches(entry.slice.id, slice.id))\n ? current(slice.id, slice) : slice);\n const withIncoming = incoming.reduce((slices, entry) => insertAt(slices, current(entry.slice.id, entry.slice), entry.index), visible);\n const withAdditions = additions.reduce((slices, entry) => contains(slices, entry.slice.id) ? slices\n : insertSlice(slices, current(entry.slice.id, entry.slice), entry.afterSliceId), withIncoming);\n const slices = order ? reorderByIds(withAdditions, order.ids) : withAdditions;\n return { slices, snapshot, additions, outgoing, incoming, order };\n};\n\nconst reorderByIds = <T extends SliceAreaItem>(slices: T[], ids: Guid[]): T[] => {\n const ordered = ids.map(id => slices.find(slice => matches(slice.id, id))).filter((slice): slice is T => slice !== undefined);\n let position = 0;\n return slices.map(slice => ids.some(id => matches(id, slice.id)) ? ordered[position++] : slice);\n};\n\nexport const duplicateSliceName = (names: string[], original: string): string => {\n const baseName = original.replace(/\\s*\\(\\d+\\)$/, '').trimEnd();\n const pattern = new RegExp(`^${baseName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\s+\\\\((\\\\d+)\\\\)$`);\n const used = new Set(names.map(name => pattern.exec(name)).filter(match => match !== null).map(match => Number(match[1])));\n const number = Array.from({ length: used.size + 1 }, (_, index) => index + 1).find(candidate => !used.has(candidate));\n return `${baseName} (${number})`;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SlicesArea.css';\nimport { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, type ReactNode, type Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { boardMetrics } from '../Layout';\nimport { SliceDragGhost, SliceDropIndicator, SliceDropTarget, useSliceDrag, type ValidateSliceDrop } from '../SliceDragging';\nimport type { Slice, SliceType } from '../Model';\nimport { createOptimisticSlice } from './createOptimisticSlice';\nimport type { SliceNames } from './SliceNames';\nimport { addPendingSlice, addProjectedSlice, completeAddedSlice, completeMoveIn, completeMoveOut, completeReorder, createSliceAreaState, movePendingSliceIn, movePendingSliceOut, reconcileSliceSnapshot, reorderPendingSlices, type SliceAreaItem, type SliceAreaState } from './sliceAreaState';\n\nexport interface SlicesAreaHandle<T extends SliceAreaItem> {\n addSlice: (sliceType: SliceType, afterSliceId?: Guid, names?: SliceNames) => void;\n updateSlices: (update: (previous: T[]) => T[]) => void;\n addProjectedSlice: (slice: T, afterSliceId?: Guid) => void;\n moveIn: (slice: T, index: number) => void;\n completeMoveIn: (id: Guid, succeeded: boolean) => void;\n moveOut: (id: Guid) => boolean;\n completeMoveOut: (id: Guid, succeeded: boolean) => void;\n}\n\nexport interface SlicesAreaProps<T extends SliceAreaItem> {\n initialSlices: T[];\n ref?: Ref<SlicesAreaHandle<T>>;\n moduleId: Guid;\n featureId: Guid;\n featureCollapsed: boolean;\n hideEmptyPlaceholder?: boolean;\n onSlicesChanged?: (slices: T[]) => void;\n createSlice: (slice: Slice) => T;\n onAddSlice?: (slice: T, afterSliceId?: Guid) => Promise<Guid | undefined>;\n onReorderSlices?: (sliceIds: Guid[]) => Promise<boolean>;\n onMoveSlice?: (slice: T, targetFeatureId: Guid, targetIndex: number) => Promise<boolean>;\n validateSliceDrop?: ValidateSliceDrop;\n renderSlice: (slice: T, options: {\n collapsed: boolean;\n sliceCollapsed: boolean;\n isDragging: boolean;\n onSliceDragStart: ReturnType<typeof useSliceDrag>['handleSliceDragStart'];\n addSlice: SlicesAreaHandle<T>['addSlice'];\n updateSlices: SlicesAreaHandle<T>['updateSlices'];\n }) => ReactNode;\n}\n\n// The feature's slice row owns the optimistic list and drag geometry. Persistence and the Studio-specific\n// content of each column are supplied by the consumer until the feature level moves into the board.\nexport function SlicesArea<T extends SliceAreaItem>({\n ref, initialSlices, moduleId, featureId, featureCollapsed, hideEmptyPlaceholder = false,\n onSlicesChanged, createSlice, onAddSlice, onReorderSlices, onMoveSlice, validateSliceDrop, renderSlice,\n}: SlicesAreaProps<T>) {\n const { readOnly, messages } = useBoard();\n const stateRef = useRef<SliceAreaState<T>>(createSliceAreaState(initialSlices));\n const lastReportedSlices = useRef<T[] | undefined>(undefined);\n const [state, setState] = useState(stateRef.current);\n const { slices } = state;\n const addingRef = useRef(false);\n const [adding, setAdding] = useState(false);\n const apply = useCallback((transition: (previous: SliceAreaState<T>) => SliceAreaState<T>) => {\n const previous = stateRef.current;\n const next = transition(previous);\n if (next === previous) return;\n stateRef.current = next;\n setState(next);\n if (next.slices !== previous.slices) {\n lastReportedSlices.current = next.slices;\n onSlicesChanged?.(next.slices);\n }\n }, [onSlicesChanged]);\n useEffect(() => {\n if (initialSlices === lastReportedSlices.current || initialSlices === stateRef.current.snapshot) return;\n apply(previous => {\n if (!previous.additions.length && !previous.incoming.length && !previous.outgoing.length && !previous.order\n && previous.slices.length === initialSlices.length\n && previous.slices.every((slice, index) => slice === initialSlices[index])) {\n return { ...previous, snapshot: initialSlices };\n }\n return reconcileSliceSnapshot(previous, initialSlices);\n });\n }, [initialSlices, apply]);\n\n const updateSlices = useCallback((update: (previous: T[]) => T[]) => {\n apply(previous => {\n const slices = update(previous.slices);\n return slices === previous.slices ? previous : { ...previous, slices };\n });\n }, [apply]);\n const addProjected = useCallback((slice: T, afterSliceId?: Guid) => apply(previous => addProjectedSlice(previous, slice, afterSliceId)), [apply]);\n const moveIn = useCallback((slice: T, index: number) => apply(previous => movePendingSliceIn(previous, slice, index)), [apply]);\n const completeIncoming = useCallback((id: Guid, succeeded: boolean) => apply(previous => completeMoveIn(previous, id, succeeded)), [apply]);\n const moveOut = useCallback((id: Guid): boolean => {\n if ([...stateRef.current.additions, ...stateRef.current.incoming].some(entry => entry.slice.id.equals(id))\n || !stateRef.current.slices.some(slice => slice.id.equals(id))) return false;\n apply(previous => movePendingSliceOut(previous, id));\n return true;\n }, [apply]);\n const completeOutgoing = useCallback((id: Guid, succeeded: boolean) => apply(previous => completeMoveOut(previous, id, succeeded)), [apply]);\n\n const addSlice = useCallback((sliceType: SliceType, afterSliceId?: Guid, names?: SliceNames) => {\n if (readOnly || !onAddSlice || addingRef.current) return;\n addingRef.current = true;\n setAdding(true);\n const slice = createSlice(createOptimisticSlice(sliceType, names));\n apply(previous => addPendingSlice(previous, slice, afterSliceId));\n void Promise.resolve().then(() => onAddSlice(slice, afterSliceId)).then(realId => {\n apply(previous => completeAddedSlice(previous, slice.id, realId));\n }).catch(() => apply(previous => completeAddedSlice(previous, slice.id)))\n .finally(() => { addingRef.current = false; setAdding(false); });\n }, [readOnly, createSlice, onAddSlice, apply]);\n\n useImperativeHandle(ref, () => ({ addSlice, updateSlices, addProjectedSlice: addProjected, moveIn, completeMoveIn: completeIncoming, moveOut, completeMoveOut: completeOutgoing }),\n [addSlice, updateSlices, addProjected, moveIn, completeIncoming, moveOut, completeOutgoing]);\n\n const feature = useMemo(() => ({ id: featureId, slices }), [featureId, slices]);\n const handleMoved = useCallback((sliceId: Guid, sourceFeatureId: Guid, targetFeatureId: Guid, targetIndex: number) => {\n if (readOnly || !sourceFeatureId.equals(featureId)) return;\n const sourceIndex = stateRef.current.slices.findIndex(slice => slice.id.equals(sliceId));\n if (sourceIndex < 0 || [...stateRef.current.additions, ...stateRef.current.incoming].some(entry => entry.slice.id.equals(sliceId))) return;\n if (targetFeatureId.equals(featureId)) {\n if (!onReorderSlices || (stateRef.current.order && !stateRef.current.order.confirmed)) return;\n const next = reorderPendingSlices(stateRef.current, sourceIndex, targetIndex);\n if (next === stateRef.current) return;\n apply(() => next);\n void Promise.resolve().then(() => onReorderSlices(next.slices.map(slice => slice.id)))\n .then(succeeded => apply(previous => completeReorder(previous, succeeded)))\n .catch(() => apply(previous => completeReorder(previous, false)));\n } else if (onMoveSlice) {\n const slice = stateRef.current.slices[sourceIndex];\n if (!moveOut(sliceId)) return;\n void Promise.resolve().then(() => onMoveSlice(slice, targetFeatureId, targetIndex))\n .then(succeeded => completeOutgoing(sliceId, succeeded))\n .catch(() => completeOutgoing(sliceId, false));\n }\n }, [readOnly, featureId, onReorderSlices, onMoveSlice, apply, moveOut, completeOutgoing]);\n const { sliceDrag, handleSliceDragStart } = useSliceDrag(feature, moduleId,\n onReorderSlices || onMoveSlice ? handleMoved : undefined, validateSliceDrop);\n\n if (!slices.length) {\n if (featureCollapsed) return null;\n if (hideEmptyPlaceholder) return <SliceDropTarget moduleId={moduleId} featureId={featureId} acceptsReorder={!readOnly && !!onReorderSlices} acceptsMove={!readOnly && !!onMoveSlice} style={{ width: 0, flexShrink: 0 }} />;\n return (\n <SliceDropTarget moduleId={moduleId} featureId={featureId} busy={adding} acceptsReorder={!readOnly && !!onReorderSlices} acceptsMove={!readOnly && !!onMoveSlice} className='event-modeling-slices-empty' style={{ width: Math.round(boardMetrics.sliceWidth * 1.5) }}>\n {messages.slices.empty}\n </SliceDropTarget>\n );\n }\n\n return (\n <>\n <SliceDragGhost drag={sliceDrag} headerHeight={boardMetrics.headerHeight} />\n <SliceDropTarget moduleId={moduleId} featureId={featureId} busy={adding} acceptsReorder={!readOnly && !!onReorderSlices} acceptsMove={!readOnly && !!onMoveSlice} active={sliceDrag?.targetFeatureId.equals(featureId)} style={{ display: 'flex', flexDirection: 'row', alignItems: 'flex-start' }}>\n {slices.flatMap((slice, index) => {\n const isDraggingThisFeature = sliceDrag?.targetFeatureId.equals(featureId) ?? false;\n const marginLeft = index === 0 ? 0 : boardMetrics.sliceGap;\n const elements: ReactNode[] = [];\n if (isDraggingThisFeature && sliceDrag?.dropIndex === index) elements.push(\n <SliceDropIndicator key={`drop-${index}`} isValid={sliceDrag.isValid} marginLeft={marginLeft > 0 ? Math.max(marginLeft - 6, 0) : 0} />);\n const sliceCollapsed = slice.collapsed;\n elements.push(\n <div key={slice.id.toString()} style={{ marginLeft: isDraggingThisFeature && sliceDrag?.dropIndex === index ? 2 : marginLeft }}>\n {renderSlice(slice, { collapsed: featureCollapsed || sliceCollapsed, sliceCollapsed,\n isDragging: sliceDrag?.sliceId.equals(slice.id) ?? false,\n onSliceDragStart: [...state.additions, ...state.incoming].some(entry => entry.slice.id.equals(slice.id)) ? undefined : handleSliceDragStart,\n addSlice, updateSlices })}\n </div>);\n if (isDraggingThisFeature && index === slices.length - 1 && sliceDrag?.dropIndex === slices.length) elements.push(\n <SliceDropIndicator key='drop-end' isValid={sliceDrag.isValid} marginLeft={2} />);\n return elements;\n })}\n </SliceDropTarget>\n </>\n );\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/SliceCell.css';\nimport { Fragment, type ReactNode } from 'react';\nimport type { ActorType, SliceType } from '../Model';\nimport { cellConnectors, type CellConnectors } from '../Connections';\nimport { actorsForRow, sliceTypeSupportsRow } from '../Layout';\nimport { RowType } from '../Rows/RowType';\n\n// What a row's cell is drawn with.\nexport interface SliceRowCell<TActor> {\n rowType: RowType;\n conn: CellConnectors;\n rowHeight: number;\n // The actor the cell belongs to; undefined for a row that holds no actors, or an actor row that has none yet.\n actor?: TActor;\n}\n\nexport interface SliceRowsProps<TActor extends { id: { toString(): string }; actorType: ActorType }> {\n sliceType: SliceType;\n contentRows: readonly RowType[];\n rowHeights: Readonly<Record<RowType, number>>;\n // The collection's actors; each actor row draws one cell per actor of its kind.\n actors: readonly TActor[];\n // Draws the cell of one row; the board decides which rows a slice draws, and how many cells each gets.\n renderCell: (cell: SliceRowCell<TActor>) => ReactNode;\n}\n\nconst emptyClass: Partial<Record<RowType, string>> = {\n [RowType.UI]: 'ui',\n [RowType.Chat]: 'chat',\n [RowType.System]: 'system',\n};\n\n// A slice's cells, one row after another. A row the slice type takes no part in keeps its height with an\n// empty cell, so the rows of every slice line up.\nexport const SliceRows = <TActor extends { id: { toString(): string }; actorType: ActorType }>({ sliceType, contentRows, rowHeights, actors, renderCell }: SliceRowsProps<TActor>) => (\n <>\n {contentRows.flatMap(rowType => {\n const conn = cellConnectors(rowType, sliceType, [...contentRows]);\n const rowHeight = rowHeights[rowType];\n const actorKind = emptyClass[rowType];\n\n if (actorKind === undefined) {\n return [<Fragment key={`row:${rowType}`}>{renderCell({ rowType, conn, rowHeight })}</Fragment>];\n }\n const rowActors = actorsForRow(actors, rowType);\n if (!sliceTypeSupportsRow(sliceType, rowType)) {\n return Array.from({ length: Math.max(1, rowActors.length) }, (_, index) =>\n <div key={`row:${actorKind}:${index}`} className={`event-modeling-grid-slice-cell event-modeling-grid-slice-cell--${actorKind}`} style={{ height: rowHeight }} />);\n }\n if (rowActors.length === 0) {\n return [<Fragment key={`row:${actorKind}`}>{renderCell({ rowType, conn, rowHeight })}</Fragment>];\n }\n return rowActors.map(actor => <Fragment key={`role:${actor.id.toString()}`}>{renderCell({ rowType, conn, rowHeight, actor })}</Fragment>);\n })}\n </>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SlicePlaceholder.css';\nimport React from 'react';\nimport { SliceType } from '../Model';\nimport { commandCardColors, eventCardColors, readModelCardColors } from '../Cards/cardColors';\nimport { RowType } from '../Rows/RowType';\n\n// What a placeholder needs to know about the slice it stands in for.\nexport interface SlicePlaceholderSlice {\n sliceType: SliceType;\n // Whether the slice has a command, and whether it has a read model.\n hasCommand: boolean;\n hasReadModel: boolean;\n eventCount: number;\n}\n\nexport interface SlicePlaceholderProps {\n\n // The slice whose content the silhouettes stand in for.\n slice: SlicePlaceholderSlice;\n\n // The rows the column renders, in order.\n contentRows: readonly RowType[];\n\n // The height of each row, so the placeholder occupies exactly the real body's box.\n rowHeights: Readonly<Record<RowType, number>>;\n}\n\nconst SILHOUETTE_ALPHA = '38';\n\nfunction interactionColor(slice: SlicePlaceholderSlice): string | undefined {\n if (slice.sliceType === SliceType.stateChange && slice.hasCommand) return commandCardColors.background;\n if (slice.sliceType === SliceType.stateView && slice.hasReadModel) return readModelCardColors.background;\n return undefined;\n}\n\n// The off-screen stand-in for a slice column's virtualized body: one cell-shaped row per content\n// row, with faint card/chip silhouettes where the real body shows the command/read-model card and\n// event chips — so content scrolling toward the viewport reads as a soft preview of the real cards\n// rather than empty space, and the swap to the mounted body is a fade rather than a pop.\nexport const SlicePlaceholder: React.FC<SlicePlaceholderProps> = ({ slice, contentRows, rowHeights }) => (\n <>\n {contentRows.map(rowType => {\n const cardColor = rowType === RowType.Interaction ? interactionColor(slice) : undefined;\n const eventCount = rowType === RowType.Events ? Math.min(slice.eventCount, 3) : 0;\n\n return (\n <div\n key={rowType}\n className='event-modeling-grid-slice-cell event-modeling-grid-slice-placeholder-row'\n style={{ height: rowHeights[rowType] }}\n aria-hidden\n >\n {cardColor && (\n <span\n className='event-modeling-grid-slice-placeholder-card'\n style={{ background: `${cardColor}${SILHOUETTE_ALPHA}` }}\n />\n )}\n {eventCount > 0 && (\n <span className='event-modeling-grid-slice-placeholder-chips'>\n {Array.from({ length: eventCount }, (_, index) => (\n <span\n key={index}\n className='event-modeling-grid-slice-placeholder-chip'\n style={{ background: `${eventCardColors.background}${SILHOUETTE_ALPHA}` }}\n />\n ))}\n </span>\n )}\n </div>\n );\n })}\n </>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './AddButton.css';\nimport React, { useRef } from 'react';\nimport { GridTooltip } from '../Tooltips';\nimport { useSlice } from '../Slices';\nimport type { CellAction } from './CellAction';\n\nexport interface CellActionButtonProps {\n action: CellAction;\n}\n\nconst iconStyle: React.CSSProperties = { fontSize: 10 };\n\n// Draws nothing when the slice is read-only or outside a slice.\nexport const CellActionButton = ({ action }: CellActionButtonProps) => {\n const { readOnly, sliceId } = useSlice();\n const button = useRef<HTMLButtonElement>(null);\n if (readOnly || !sliceId) return undefined;\n\n return (\n <GridTooltip content={action.tooltip} position='top'>\n <button\n ref={button}\n type='button'\n className='event-modeling-grid-add-button--small'\n aria-label={action.tooltip}\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n action.onActivate(sliceId, button.current?.getBoundingClientRect() ?? new DOMRect());\n }}\n >\n {action.icon ? <i className={action.icon} style={iconStyle} /> : '+'}\n </button>\n </GridTooltip>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The bottom-right corner holds what adds to the cell; the top-right corner holds what acts on it.\nexport enum CellCornerPlacement {\n add = 'add',\n top = 'top',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './CellCorner.css';\nimport React from 'react';\nimport { CellCornerPlacement } from './CellCornerPlacement';\n\nexport interface CellCornerProps {\n placement: CellCornerPlacement;\n children?: React.ReactNode;\n}\n\nexport const CellCorner = ({ placement, children }: CellCornerProps) => (\n <div className={placement === CellCornerPlacement.add\n ? 'event-modeling-grid-slice-cell-add-corner'\n : 'event-modeling-grid-slice-cell-action-corner event-modeling-grid-slice-cell-action-corner--top'}>\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useSlice } from '../Slices';\nimport type { CellAction } from './CellAction';\nimport { CellActionButton } from './CellActionButton';\nimport { CellCorner } from './CellCorner';\nimport type { CellCornerPlacement } from './CellCornerPlacement';\n\nexport interface CellCornerActionProps {\n placement: CellCornerPlacement;\n action: CellAction;\n}\n\n// A corner holding a single action; nothing at all is drawn when the slice is read-only.\nexport const CellCornerAction = ({ placement, action }: CellCornerActionProps) => {\n const { readOnly, sliceId } = useSlice();\n if (readOnly || !sliceId) return undefined;\n\n return (\n <CellCorner placement={placement}>\n <CellActionButton action={action} />\n </CellCorner>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\n\n// Only a State View references events other slices produce; every other slice type adds its own.\nexport const usesEventReferencePicker = (sliceType: SliceType): boolean =>\n sliceType === SliceType.stateView;\n\nexport const showsAddNewEventButton = (sliceType: SliceType): boolean =>\n !usesEventReferencePicker(sliceType);\n\n// While a State View has no events yet, referencing its first one is the row's only offer, so it is drawn\n// as a dashed card rather than a small button.\nexport const showsEventReferencePlaceholder = (sliceType: SliceType, eventCount: number): boolean =>\n usesEventReferencePicker(sliceType) && eventCount === 0;\n\n// A Translator's interaction row offers events from other modules to translate from.\nexport const showsExternalEventPicker = (sliceType: SliceType): boolean =>\n sliceType === SliceType.translator;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { AutomationTriggerType } from '../../Model';\nimport type { EventModelMessages } from '../../Messages';\n\n// The PrimeIcons glyph each kind of trigger is drawn with; there is none for an automation without one.\nexport const triggerIcon = (type: AutomationTriggerType): string | undefined => {\n switch (type) {\n case AutomationTriggerType.timer: return 'pi pi-clock';\n case AutomationTriggerType.event: return 'pi pi-bolt';\n case AutomationTriggerType.custom: return 'pi pi-pencil';\n case AutomationTriggerType.none: return undefined;\n }\n};\n\nexport const triggerTitle = (type: AutomationTriggerType, messages: EventModelMessages): string => {\n switch (type) {\n case AutomationTriggerType.timer: return messages.triggers.timer;\n case AutomationTriggerType.event: return messages.triggers.event;\n case AutomationTriggerType.custom: return messages.triggers.custom;\n case AutomationTriggerType.none: return '';\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './CogWheel.css';\n\n// The system actor's mark.\nexport const CogWheel = () => (\n <span className='event-modeling-grid-cogwheel-icon'>\n <svg viewBox='0 0 64 64' width='72' height='72' fill='currentColor' xmlns='http://www.w3.org/2000/svg'>\n <path d='M54.2 27.4l-4.1-.7a18 18 0 0 0-1.2-2.9l2.4-3.4a2 2 0 0 0-.2-2.6l-4.8-4.8a2 2 0 0 0-2.6-.2l-3.4 2.4a18 18 0 0 0-2.9-1.2l-.7-4.1A2 2 0 0 0 35 8h-6a2 2 0 0 0-2 1.7l-.7 4.1a18 18 0 0 0-2.9 1.2l-3.4-2.4a2 2 0 0 0-2.6.2l-4.8 4.8a2 2 0 0 0-.2 2.6l2.4 3.4a18 18 0 0 0-1.2 2.9l-4.1.7A2 2 0 0 0 8 29v6a2 2 0 0 0 1.7 2l4.1.7a18 18 0 0 0 1.2 2.9l-2.4 3.4a2 2 0 0 0 .2 2.6l4.8 4.8a2 2 0 0 0 2.6.2l3.4-2.4a18 18 0 0 0 2.9 1.2l.7 4.1A2 2 0 0 0 29 56h6a2 2 0 0 0 2-1.7l.7-4.1a18 18 0 0 0 2.9-1.2l3.4 2.4a2 2 0 0 0 2.6-.2l4.8-4.8a2 2 0 0 0 .2-2.6l-2.4-3.4a18 18 0 0 0 1.2-2.9l4.1-.7A2 2 0 0 0 56 35v-6a2 2 0 0 0-1.8-1.6zM32 42a10 10 0 1 1 0-20 10 10 0 0 1 0 20z' />\n </svg>\n </span>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The kinds of trigger an automation can be given.\nexport enum TriggerKind {\n timer = 'timer',\n event = 'event',\n custom = 'custom',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './TriggerControl.css';\nimport { useRef, useState, type PointerEvent } from 'react';\nimport { AutomationTriggerType } from '../../Model';\nimport { useEventModelMessages } from '../../Messages';\nimport { useDismissOnOutsidePointer } from '../../Pickers/useDismissOnOutsidePointer';\nimport { TriggerKind } from './TriggerKind';\nimport { triggerIcon } from './triggerBadges';\n\nexport interface TriggerControlProps {\n // How the automation is set off now; none, or no value, when it has no trigger yet.\n triggerType?: AutomationTriggerType;\n onTriggerKindChosen: (kind: TriggerKind) => void;\n onTriggerOpened: () => void;\n}\n\nconst kinds = [TriggerKind.timer, TriggerKind.event, TriggerKind.custom] as const;\n\n// An automation's trigger in the corner of its system cell: a button for the trigger it has, which opens\n// it, or one that offers the kinds of trigger it can be given.\nexport const TriggerControl = ({ triggerType, onTriggerKindChosen, onTriggerOpened }: TriggerControlProps) => {\n const messages = useEventModelMessages();\n const [open, setOpen] = useState(false);\n const container = useRef<HTMLDivElement>(null);\n const elements = useRef([container]).current;\n useDismissOnOutsidePointer(elements, () => setOpen(false), open);\n const icon = triggerType === undefined ? undefined : triggerIcon(triggerType);\n const onPointerDown = (handle: () => void) => (event: PointerEvent) => {\n event.stopPropagation();\n handle();\n };\n\n if (icon) {\n return (\n <div className='system-row-cell__trigger-wrapper'>\n <button\n className='system-row-cell__trigger-btn system-row-cell__trigger-btn--active'\n title={messages.triggerControl.edit}\n onPointerDown={onPointerDown(onTriggerOpened)}\n >\n <i className={icon} />\n </button>\n </div>\n );\n }\n\n return (\n <div ref={container} className='system-row-cell__trigger-wrapper'>\n <button\n className='system-row-cell__trigger-btn'\n title={messages.triggerControl.add}\n onPointerDown={onPointerDown(() => setOpen(previous => !previous))}\n >\n <i className='pi pi-plus' />\n </button>\n {open && (\n <div className='system-row-cell__trigger-menu'>\n {kinds.map(kind => (\n <div\n key={kind}\n className='system-row-cell__trigger-menu-item'\n onPointerDown={onPointerDown(() => {\n setOpen(false);\n onTriggerKindChosen(kind);\n })}\n >\n <div className='system-row-cell__trigger-menu-item-title'>{messages.triggerControl.kinds[kind].title}</div>\n <div className='system-row-cell__trigger-menu-item-description'>{messages.triggerControl.kinds[kind].description}</div>\n </div>\n ))}\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport './SystemCell.css';\nimport React from 'react';\nimport { useBoard } from '../../Board';\nimport { type CellConnectors, ConnectorIncomingBottom, ConnectorIncomingTop, ConnectorOutgoingBottom, ConnectorOutgoingTop, FlowNodeActor, PassthroughConnector } from '../../Connections';\nimport { CogWheel } from '../../Icons';\nimport { type AutomationTriggerType, SliceType } from '../../Model';\nimport { useEventModelMessages } from '../../Messages';\nimport { useSlice } from '../../Slices';\nimport { TriggerControl } from './TriggerControl';\nimport { triggerIcon, triggerTitle } from './triggerBadges';\n\nexport interface SystemCellProps {\n sliceType: SliceType;\n // Whether the system acts in this slice; only then is the cogwheel drawn.\n isSystemSlice: boolean;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // How the automation is set off: a badge when the slice cannot be edited, and a button that opens it when\n // it can.\n triggerType?: AutomationTriggerType;\n}\n\nexport const SystemCell = ({ sliceType, isSystemSlice, collapsed = false, conn, rowHeight, triggerType }: SystemCellProps) => {\n const { readOnly, sliceId } = useSlice();\n const { onTriggerKindChosen, onTriggerOpened } = useBoard().editing;\n const messages = useEventModelMessages();\n const badge = triggerType === undefined ? undefined : triggerIcon(triggerType);\n const cellStyle: React.CSSProperties = { height: rowHeight };\n const isAutomation = isSystemSlice && sliceType === SliceType.automation;\n\n if (collapsed) {\n return (\n <div style={cellStyle} className='event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--system event-modeling-grid-slice-cell--collapsed'>\n {isSystemSlice && <CogWheel />}\n </div>\n );\n }\n\n return (\n <div\n style={cellStyle}\n data-card-id='system'\n data-slice-id={sliceId?.toString()}\n className='event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--system'\n >\n {conn.topOutgoing && <ConnectorOutgoingTop />}\n {conn.topIncoming && <ConnectorIncomingTop />}\n {/* An automation's interaction row below is split — read model on the left, command on the\n right — so the bottom connectors sit over those column centers for the fill lines to align. */}\n {sliceType === SliceType.automation\n ? <>\n {conn.bottomIncoming && <ConnectorIncomingBottom columnPosition='left' />}\n {conn.bottomOutgoing && <ConnectorOutgoingBottom columnPosition='right' />}\n </>\n : <>\n {conn.bottomOutgoing && <ConnectorOutgoingBottom />}\n {conn.bottomIncoming && <ConnectorIncomingBottom />}\n </>\n }\n {conn.passthrough && <PassthroughConnector />}\n {isSystemSlice && (\n sliceType === SliceType.automation\n ? <span data-flow-node={FlowNodeActor.cogwheel} className='system-row-cell__cogwheel'><CogWheel /></span>\n : <CogWheel />\n )}\n {isAutomation && !readOnly && sliceId && onTriggerKindChosen && onTriggerOpened && (\n <TriggerControl\n triggerType={triggerType}\n onTriggerKindChosen={kind => onTriggerKindChosen(sliceId, kind)}\n onTriggerOpened={() => onTriggerOpened(sliceId)}\n />\n )}\n {/* A board that cannot be edited still shows a configured trigger, as a badge rather than a button. */}\n {isAutomation && readOnly && triggerType !== undefined && badge && (\n <div className='system-row-cell__trigger-wrapper'>\n <span className='system-row-cell__trigger-btn system-row-cell__trigger-btn--active system-row-cell__trigger-btn--readonly' title={triggerTitle(triggerType, messages)}>\n <i className={badge} />\n </span>\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModelMessages } from '../../Messages';\nimport type { MenuDropdownItem } from '../../Menus';\nimport type { PrototypeTemplate } from './PrototypeTemplate';\n\n// What the add button's menu does for each way of adding a UI prototype.\nexport interface AddPrototypeMenuActions {\n onFromScratch: () => void;\n onFromTemplate: (template: PrototypeTemplate) => void;\n}\n\n// The menu offered from the add button of an actor's UI cell: start from scratch, or from one of the\n// templates the consumer offers.\nexport const addPrototypeMenuItems = (\n templates: readonly PrototypeTemplate[],\n messages: EventModelMessages['prototypes'],\n actions: AddPrototypeMenuActions): MenuDropdownItem[] => [\n {\n id: 'from-scratch',\n label: messages.fromScratch,\n description: messages.fromScratchDescription,\n onClick: actions.onFromScratch,\n },\n {\n id: 'from-template',\n label: messages.fromTemplate,\n description: messages.fromTemplateDescription,\n items: templates.length > 0\n ? templates.map(template => ({\n id: template.id,\n label: template.name,\n onClick: () => actions.onFromTemplate(template),\n }))\n : [{\n id: 'no-templates',\n label: messages.noTemplates,\n }],\n },\n];\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef } from 'react';\nimport { useEventModelMessages } from '../../Messages';\nimport { MenuDropdown } from '../../Menus';\nimport { GridTooltip } from '../../Tooltips';\nimport { addPrototypeMenuItems } from './addPrototypeMenuItems';\nimport type { PrototypeTemplate } from './PrototypeTemplate';\n\nexport interface AddPrototypeButtonProps {\n templates: readonly PrototypeTemplate[];\n // Each receives the viewport rectangle of the button, so the editor can open from there.\n onFromScratch: (host: DOMRect) => void;\n onFromTemplate: (template: PrototypeTemplate, host: DOMRect) => void;\n}\n\n// The add button of an actor's UI cell: a menu offering to start a prototype from scratch or from a\n// template.\nexport const AddPrototypeButton = ({ templates, onFromScratch, onFromTemplate }: AddPrototypeButtonProps) => {\n const messages = useEventModelMessages().prototypes;\n const trigger = useRef<HTMLButtonElement>(null);\n const host = () => trigger.current?.getBoundingClientRect() ?? new DOMRect();\n const items = addPrototypeMenuItems(templates, messages, {\n onFromScratch: () => onFromScratch(host()),\n onFromTemplate: template => onFromTemplate(template, host()),\n });\n\n return (\n <GridTooltip content={messages.add} position='top'>\n <MenuDropdown\n align='right'\n items={items}\n trigger={\n <button ref={trigger} aria-label={messages.add} className='event-modeling-grid-add-button--small'>\n +\n </button>\n }\n />\n </GridTooltip>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport './UiCell.css';\nimport React, { useRef, useState } from 'react';\nimport { PrototypePreview, PrototypeThumbnail, useSceneMessages, type PrototypeLayout } from '@cratis/scene/Prototypes';\nimport type { UIElement, IComponent } from '@cratis/scene';\nimport { type CellConnectors, ConnectorIncomingBottom, ConnectorOutgoingBottom, FlowNodeActor } from '../../Connections';\nimport { useBoard } from '../../Board';\nimport { useSlice } from '../../Slices';\nimport { CellCorner } from '../CellCorner';\nimport { CellCornerPlacement } from '../CellCornerPlacement';\nimport { AddPrototypeButton } from './AddPrototypeButton';\n\nexport interface UiCellProps {\n // What the actor sees in this slice; the cell shows a thumbnail of it.\n elements: readonly (UIElement | IComponent)[];\n windowSize?: { width: number; height: number };\n layout?: PrototypeLayout;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // The actor whose prototype this is; opening and adding a prototype report it.\n actorId: string;\n}\n\nexport const UiCell = ({ elements, windowSize, layout, collapsed = false, conn, rowHeight, actorId }: UiCellProps) => {\n const { readOnly, sliceId } = useSlice();\n const { editing, actions, readOnly: boardReadOnly } = useBoard();\n const { onPrototypeOpened, onPrototypeAdded } = editing;\n const thumbnail = useRef<HTMLDivElement>(null);\n const [previewFrom, setPreviewFrom] = useState<DOMRect>();\n const messages = useSceneMessages().prototypeThumbnail;\n const cellStyle: React.CSSProperties = { height: rowHeight };\n const className = 'event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--ui';\n\n if (collapsed) return <div style={cellStyle} className={className} />;\n\n const hasContent = elements.length > 0;\n const opens = !readOnly && !!sliceId && !!onPrototypeOpened;\n // A board that cannot edit the prototype still lets it be looked at, full size.\n const open = opens && sliceId && onPrototypeOpened\n ? () => onPrototypeOpened(sliceId, actorId, thumbnail.current?.getBoundingClientRect() ?? new DOMRect())\n : boardReadOnly\n ? () => setPreviewFrom(thumbnail.current?.getBoundingClientRect() ?? new DOMRect())\n : undefined;\n\n return (\n <div style={cellStyle} className={className}>\n {conn.bottomOutgoing && hasContent && <ConnectorOutgoingBottom />}\n {conn.bottomIncoming && hasContent && <ConnectorIncomingBottom />}\n <div className='event-modeling-grid-slice-cell-items'>\n {hasContent && (\n <div ref={thumbnail} className={`event-modeling-grid-ui-preview${open ? ' event-modeling-grid-ui-preview--clickable' : ''}`} data-flow-node={FlowNodeActor.ui}>\n <PrototypeThumbnail\n elements={[...elements]}\n windowSize={windowSize}\n layout={layout}\n onClick={open}\n openTitle={boardReadOnly ? messages.openPreview : undefined}\n />\n </div>\n )}\n {previewFrom && (\n <PrototypePreview\n elements={elements}\n windowSize={windowSize}\n layout={layout}\n sourceRect={previewFrom}\n onClose={() => setPreviewFrom(undefined)}\n />\n )}\n </div>\n {!readOnly && sliceId && onPrototypeAdded && !hasContent && (\n <CellCorner placement={CellCornerPlacement.add}>\n <AddPrototypeButton\n templates={actions.prototypeTemplates ?? []}\n onFromScratch={host => onPrototypeAdded(sliceId, actorId, host)}\n onFromTemplate={(template, host) => template.onChosen(sliceId, actorId, host)}\n />\n </CellCorner>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport type { Guid } from '@cratis/fundamentals';\nimport { type CellConnectors, ConnectorIncomingBottom, ConnectorOutgoingBottom } from '../../Connections';\n\nexport interface ChatCellProps {\n sliceId: Guid;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n}\n\nconst ChatIcon = () => (\n <svg width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' style={{ opacity: 0.25 }} aria-hidden='true'>\n <path d='M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z' />\n </svg>\n);\n\n// A slice's cell in the chat row: the chat mark, with the connectors that pass through it.\nexport const ChatCell = ({ sliceId, collapsed = false, conn, rowHeight }: ChatCellProps) => {\n const className = 'event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--chat';\n if (collapsed) {\n return (\n <div style={{ height: rowHeight }} className={className}>\n <ChatIcon />\n </div>\n );\n }\n return (\n <div style={{ height: rowHeight }} data-card-id='chat' data-slice-id={sliceId.toString()} className={className}>\n {conn.bottomOutgoing && <ConnectorOutgoingBottom />}\n {conn.bottomIncoming && <ConnectorIncomingBottom />}\n <ChatIcon />\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport type { ReactNode } from 'react';\nimport { type CellConnectors, ConnectorIncomingTop, ConnectorOutgoingTop } from '../../Connections';\n\nexport interface EventsCellProps {\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // How many events the slice has; a collapsed slice draws one small mark per event.\n eventCount: number;\n // The event cards, drawn only while the slice is expanded.\n children?: ReactNode;\n // What the consumer draws after the cards, and in the cell's corners.\n after?: ReactNode;\n corners?: ReactNode;\n}\n\n// A slice's cell in the events row: its event cards between the connectors, and the consumer's corner\n// actions. A collapsed slice shows a small mark for each event.\nexport const EventsCell = ({ collapsed = false, conn, rowHeight, eventCount, children, after, corners }: EventsCellProps) => {\n const className = 'event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--events';\n if (collapsed) {\n return (\n <div style={{ height: rowHeight }} className={className}>\n {Array.from({ length: eventCount }, (_, index) => (\n <div key={index} className='event-modeling-grid-mini-card event-modeling-grid-mini-card--event' />\n ))}\n </div>\n );\n }\n const hasItems = eventCount > 0;\n return (\n <div style={{ height: rowHeight }} className={className}>\n {conn.topIncoming && hasItems && <ConnectorIncomingTop />}\n {conn.topOutgoing && hasItems && <ConnectorOutgoingTop />}\n <div className='event-modeling-grid-slice-cell-cards'>\n {children}\n {after}\n </div>\n {corners}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EventCard.css';\nimport { useEffect, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../../Board';\nimport { ArtifactCard, ArtifactCardKind, CardNameInput, eventCardColors } from '../../Cards';\nimport { FlowNodeActor } from '../../Connections/FlowNodeActor';\nimport type { EventItem } from '../../Model';\nimport { SchemaTooltipProperties } from '../../Properties';\nimport { useSliceReadOnly } from '../../Slices';\nimport { GridTooltip } from '../../Tooltips';\n\nexport interface EventCardProps {\n sliceId: Guid;\n event: EventItem;\n // An event a slice only consumes is not its to rename.\n renameable: boolean;\n showDetails?: boolean;\n}\n\n// An event the slice owns. It is renamed in place with a double-click, shows whether it is selected, and\n// offers whatever the consumer supplies for event cards; clicking it activates it.\nexport const EventCard = ({ sliceId, event, renameable, showDetails = false }: EventCardProps) => {\n const { editing, actions, selection, messages } = useBoard();\n const sliceReadOnly = useSliceReadOnly();\n const [name, setName] = useState(event.name);\n const [editingName, setEditingName] = useState<string | undefined>(undefined);\n\n useEffect(() => setName(event.name), [event.name]);\n\n const onEventRenamed = editing.onEventRenamed;\n const canRename = renameable && !sliceReadOnly && !!onEventRenamed;\n const isSelected = !!selection.selectedArtifactId?.equals(event.id);\n\n const commit = () => {\n const trimmed = editingName?.trim() ?? '';\n setEditingName(undefined);\n if (!trimmed || !onEventRenamed) return;\n setName(onEventRenamed(sliceId, event.id, trimmed) ?? trimmed);\n };\n\n if (editingName !== undefined) {\n return (\n <div className='event-modeling-grid-event-wrapper'>\n <CardNameInput\n value={editingName}\n backgroundColor={eventCardColors.background}\n textColor={eventCardColors.text}\n onChange={setEditingName}\n onCommit={commit}\n onCancel={() => setEditingName(undefined)}\n />\n </div>\n );\n }\n\n return (\n <div className='event-modeling-grid-event-wrapper' data-flow-node={FlowNodeActor.event}>\n <GridTooltip\n content={(\n <SchemaTooltipProperties\n title={canRename ? `${messages.events.doubleClickToRenamePrefix} ${name}` : name}\n schema={event.schema}\n />\n )}\n position='top'\n >\n <ArtifactCard\n kind={ArtifactCardKind.event}\n artifactId={event.id}\n name={name}\n tags={event.tags}\n schema={event.schema}\n showDetails={showDetails}\n actions={actions.eventCard?.actions}\n onActivate={actions.eventCard?.onActivate}\n isSelected={isSelected}\n onStartEdit={canRename ? () => setEditingName(name) : undefined}\n ariaLabel={`${messages.events.openEvent} ${name}`}\n ariaPressed={isSelected}\n data-event-id={event.id.toString()}\n />\n </GridTooltip>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './References.css';\nimport React from 'react';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface EventNavigateButtonProps {\n onClick: (clickEvent: React.MouseEvent) => void;\n}\n\n// The circular navigate-to-origin button rendered on a referencing card (a State View event reference or a\n// Translator external event). Visible on hover of the enclosing `.event-modeling-grid-event-wrapper--reference`.\nexport const EventNavigateButton: React.FC<EventNavigateButtonProps> = ({ onClick }) => {\n const messages = useEventModelMessages();\n return (\n <button\n className='event-modeling-grid-event-navigate-button'\n aria-label={messages.references.navigateToOriginal}\n title={messages.references.navigateToOriginal}\n onClick={onClick}\n >\n <i className='pi pi-arrow-up-right' style={{ transform: 'scaleX(-1)' }} />\n </button>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { useCallback, useRef } from 'react';\nimport { Guid } from '@cratis/fundamentals';\n\n// Selector for the board container that scopes the dim-on-hover effect. Exported so the guided tour can\n// stage the same dim, driven by the script's clock instead of a real hover, to demonstrate the affordance\n// on a board a viewer cannot touch.\nexport const REFERENCE_DIM_BOARD_SELECTOR = '[data-event-model-board]';\n// Class applied to the board while a reference is hovered to dim every other card.\nexport const REFERENCE_DIM_CLASS = 'event-modeling-board--dim-others';\n// Class applied to the origin event and the hovered reference so they stay visible while dimmed.\nexport const REFERENCE_UNDIMMED_CLASS = 'event-modeling-event--undimmed';\n\nexport interface ReferenceHover {\n ref: React.RefObject<HTMLDivElement | null>;\n onMouseEnter: () => void;\n onMouseLeave: () => void;\n handleNavigate: (clickEvent: React.MouseEvent) => void;\n}\n\n// Dims the board except the referenced origin event while the referencing card is hovered, and navigates\n// to that origin on demand. Shared by State View event references and Translator external events so both\n// get the same affordance; the origin card is resolved from the DOM by its `data-event-id`.\nexport function useReferenceHover(sourceEventId: Guid, onNavigate?: (sourceEventId: Guid) => void): ReferenceHover {\n const wrapperRef = useRef<HTMLDivElement>(null);\n const dimStateRef = useRef<{ board: HTMLElement; origin: HTMLElement | null } | null>(null);\n\n const onMouseEnter = useCallback(() => {\n const wrapper = wrapperRef.current;\n if (!wrapper) return;\n const board = wrapper.closest(REFERENCE_DIM_BOARD_SELECTOR) as HTMLElement | null;\n if (!board) return;\n\n const originCard = board.querySelector(`[data-event-id=\"${sourceEventId.toString()}\"]`);\n const origin = originCard?.closest('.event-modeling-grid-event-wrapper') as HTMLElement | null;\n\n board.classList.add(REFERENCE_DIM_CLASS);\n wrapper.classList.add(REFERENCE_UNDIMMED_CLASS);\n origin?.classList.add(REFERENCE_UNDIMMED_CLASS);\n dimStateRef.current = { board, origin };\n }, [sourceEventId]);\n\n const onMouseLeave = useCallback(() => {\n const state = dimStateRef.current;\n if (state) {\n state.board.classList.remove(REFERENCE_DIM_CLASS);\n state.origin?.classList.remove(REFERENCE_UNDIMMED_CLASS);\n dimStateRef.current = null;\n }\n wrapperRef.current?.classList.remove(REFERENCE_UNDIMMED_CLASS);\n }, []);\n\n const handleNavigate = useCallback((clickEvent: React.MouseEvent) => {\n clickEvent.stopPropagation();\n onMouseLeave();\n onNavigate?.(sourceEventId);\n }, [onMouseLeave, onNavigate, sourceEventId]);\n\n return { ref: wrapperRef, onMouseEnter, onMouseLeave, handleNavigate };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/Events/EventCard.css';\nimport './References.css';\nimport React from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { Card, externalEventCardColors } from '../Cards';\nimport { useReferenceHover } from './useReferenceHover';\nimport { EventNavigateButton } from './EventNavigateButton';\n\nexport interface ExternalEventCardProps {\n id: Guid;\n\n name: string;\n\n // The origin event this external event translates from; when present, the navigate affordance is shown.\n sourceEventId?: Guid;\n\n isSelected?: boolean;\n\n onSelected?: () => void;\n\n // Flies the board to the origin event and pulse-highlights it.\n onNavigate?: (sourceEventId: Guid) => void;\n\n ariaLabel?: string;\n\n 'data-card-id'?: string;\n\n 'data-slice-id'?: string;\n}\n\n// An external event card on a Translator slice. It references an event owned by another module, so it\n// gets the same board-dim-on-hover and navigate-to-origin affordance as a State View event reference.\nexport const ExternalEventCard: React.FC<ExternalEventCardProps> = ({\n id,\n name,\n sourceEventId,\n isSelected = false,\n onSelected,\n onNavigate,\n ariaLabel,\n ...cardProps\n}) => {\n const hasNavigation = !!sourceEventId && !sourceEventId.equals(Guid.empty) && !!onNavigate;\n const hover = useReferenceHover(sourceEventId ?? Guid.empty, onNavigate);\n\n return (\n <div\n ref={hover.ref}\n className='event-modeling-grid-event-wrapper event-modeling-grid-event-wrapper--reference'\n onMouseEnter={hasNavigation ? hover.onMouseEnter : undefined}\n onMouseLeave={hasNavigation ? hover.onMouseLeave : undefined}\n >\n <Card\n name={name}\n backgroundColor={externalEventCardColors.background}\n textColor={externalEventCardColors.text}\n isSelected={isSelected}\n onSelected={onSelected}\n ariaLabel={ariaLabel}\n {...cardProps}\n />\n {hasNavigation && <EventNavigateButton onClick={hover.handleNavigate} />}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EventCard.css';\nimport './EventReferenceCard.css';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../../Board';\nimport { Card, eventCardColors } from '../../Cards';\nimport { FlowNodeActor } from '../../Connections/FlowNodeActor';\nimport type { EventItem } from '../../Model';\nimport { SchemaTooltipProperties } from '../../Properties';\nimport { EventNavigateButton, useReferenceHover } from '../../References';\nimport { GridTooltip } from '../../Tooltips';\n\nexport interface EventReferenceCardProps {\n // An event of the slice that refers to an event another slice owns.\n event: EventItem;\n // Whether clicking the reference selects it.\n selectable: boolean;\n showDetails?: boolean;\n // Whether the event is produced by a slice to the right of this one, which a State View may not project.\n projectedFromTheRight?: boolean;\n}\n\n// An event owned by another slice and referenced from this one, drawn with a dashed border and slightly\n// faded. Hovering it dims the board around the original, and its button flies the board there.\nexport const EventReferenceCard = ({ event, selectable, showDetails = false, projectedFromTheRight = false }: EventReferenceCardProps) => {\n const { selection, navigation, messages } = useBoard();\n const sourceEventId = Guid.parse(event.sourceEventId ?? Guid.empty.toString());\n const hover = useReferenceHover(sourceEventId, navigation.onNavigateToEvent);\n const isSelected = !!selection.selectedArtifactId?.equals(event.id);\n const onArtifactSelected = selection.onArtifactSelected;\n\n return (\n <div\n ref={hover.ref}\n className={`event-modeling-grid-event-wrapper event-modeling-grid-event-wrapper--reference event-modeling-event-reference${projectedFromTheRight ? ' event-modeling-event-reference--out-of-order' : ''}`}\n data-out-of-order={projectedFromTheRight || undefined}\n title={projectedFromTheRight ? messages.events.projectedFromTheRight : undefined}\n data-flow-node={FlowNodeActor.event}\n onMouseEnter={hover.onMouseEnter}\n onMouseLeave={hover.onMouseLeave}\n >\n <GridTooltip content={<SchemaTooltipProperties title={event.name} schema={event.schema} />} position='top'>\n <Card\n name={event.name}\n backgroundColor={eventCardColors.background}\n textColor={eventCardColors.text}\n isSelected={isSelected}\n onSelected={selectable && onArtifactSelected ? () => onArtifactSelected(event.id) : undefined}\n ariaLabel={`${messages.events.openEvent} ${event.name}`}\n ariaPressed={isSelected}\n data-event-id={event.id.toString()}\n extraContent={showDetails ? (\n <SchemaTooltipProperties title={event.name} schema={event.schema} showTitle={false} compact={true} />\n ) : undefined}\n />\n </GridTooltip>\n {projectedFromTheRight && (\n <span className='event-modeling-event-reference__warning' role='img' aria-label={messages.events.projectedFromTheRight}>!</span>\n )}\n <EventNavigateButton onClick={hover.handleNavigate} />\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { type EventItem, type Slice, SliceType } from '../../Model';\n\n// The ids of a State View's references whose event is produced by a slice to its right. A State View only\n// projects events from slices to its left, so a reorder that moved the producer past it leaves these behind.\n// An event produced in another collection is not on this timeline and is never flagged.\nexport const projectedFromTheRightOf = (slice: Slice, priorEvents: readonly EventItem[], followingEvents: readonly EventItem[]): Set<string> => {\n if (slice.sliceType !== SliceType.stateView) return new Set();\n const before = new Set(priorEvents.map(event => event.id.toString()));\n const after = new Set(followingEvents.map(event => event.id.toString()));\n return new Set(slice.events\n .filter(event => !!event.sourceEventId && after.has(event.sourceEventId) && !before.has(event.sourceEventId))\n .map(event => event.id.toString()));\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventItem, Slice } from '../../Model';\n\n// The events a slice can still reference: not already referenced, and not sharing a name with one of the\n// slice's own events, since a reference arrives as an event of the same name.\nexport const referenceableEvents = (slice: Slice, priorEvents: readonly EventItem[]): EventItem[] => {\n const referenced = new Set(slice.events.flatMap(event => event.sourceEventId ? [event.sourceEventId] : []));\n const names = new Set(slice.events.map(event => event.name));\n return priorEvents.filter(event => !referenced.has(event.id.toString()) && !names.has(event.name));\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useBoard } from '../../Board';\nimport type { CellConnectors } from '../../Connections';\nimport { type EventItem, type Slice, SliceType } from '../../Model';\nimport { EventReferencePicker } from '../../Pickers';\nimport { useSliceReadOnly } from '../../Slices';\nimport { CellActionButton } from '../CellActionButton';\nimport { CellCorner } from '../CellCorner';\nimport { CellCornerAction } from '../CellCornerAction';\nimport { CellCornerPlacement } from '../CellCornerPlacement';\nimport { showsEventReferencePlaceholder, usesEventReferencePicker } from '../eventRowAffordances';\nimport { EventCard } from './EventCard';\nimport { EventReferenceCard } from './EventReferenceCard';\nimport { projectedFromTheRightOf } from './projectedFromTheRight';\nimport { referenceableEvents } from './referenceableEvents';\nimport { EventsCell } from './EventsCell';\n\nexport interface SliceEventsProps {\n slice: Slice;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // The events produced before this slice in its module, which a State View may reference.\n priorEvents: readonly EventItem[];\n // The events produced after this slice in its module collection.\n followingEvents?: readonly EventItem[];\n showDetails?: boolean;\n}\n\n// A slice's events row: the events it owns, the events it references, and the ways to add either.\nexport const SliceEvents = ({ slice, collapsed = false, conn, rowHeight, priorEvents, followingEvents = [], showDetails = false }: SliceEventsProps) => {\n const { editing, actions, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const { onEventAdded, onEventReferenced } = editing;\n const offersPicker = usesEventReferencePicker(slice.sliceType);\n const placeholder = showsEventReferencePlaceholder(slice.sliceType, slice.events.length);\n const options = referenceableEvents(slice, priorEvents);\n const projectedFromTheRight = projectedFromTheRightOf(slice, priorEvents, followingEvents);\n const rowActions = (actions.eventsRow ?? []).filter(action => !action.when || action.when(slice));\n const picker = (withPlaceholder: boolean) => onEventReferenced && (\n <EventReferencePicker\n options={options}\n nameOf={option => option.name}\n onSelect={option => onEventReferenced(slice.id, option)}\n label={messages.events.addExistingEvent}\n searchPlaceholder={messages.events.searchEvents}\n emptyLabel={messages.events.noEventsAvailable}\n placeholder={withPlaceholder ? messages.events.noEventsYet : undefined}\n />\n );\n\n return (\n <EventsCell\n collapsed={collapsed}\n conn={conn}\n rowHeight={rowHeight}\n eventCount={slice.events.length}\n after={!readOnly && placeholder && picker(true)}\n corners={(\n <>\n {!readOnly && rowActions.length > 0 && (\n <CellCorner placement={CellCornerPlacement.top}>\n {rowActions.map(action => <CellActionButton key={action.tooltip} action={action} />)}\n </CellCorner>\n )}\n {!readOnly && !offersPicker && onEventAdded && (\n <CellCornerAction\n placement={CellCornerPlacement.add}\n action={{ tooltip: messages.events.addEvent, onActivate: sliceId => onEventAdded(sliceId) }}\n />\n )}\n {!readOnly && offersPicker && !placeholder && onEventReferenced && (\n <CellCorner placement={CellCornerPlacement.add}>{picker(false)}</CellCorner>\n )}\n </>\n )}\n >\n {slice.events.map(event => event.sourceEventId\n ? (\n <EventReferenceCard\n key={event.id.toString()}\n event={event}\n selectable={slice.sliceType !== SliceType.stateView}\n showDetails={showDetails}\n projectedFromTheRight={projectedFromTheRight.has(event.id.toString())}\n />\n )\n : (\n <EventCard\n key={event.id.toString()}\n sliceId={slice.id}\n event={event}\n renameable={slice.sliceType !== SliceType.stateView}\n showDetails={showDetails}\n />\n ))}\n </EventsCell>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useEffect, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { JsonSchema } from '@cratis/components/types';\nimport { useBoard } from '../../Board';\nimport { ArtifactCard, ArtifactCardKind, CardNameInput, commandCardColors, readModelCardColors } from '../../Cards';\nimport { FlowNodeActor } from '../../Connections/FlowNodeActor';\nimport { SchemaTooltipProperties } from '../../Properties';\nimport { useSliceReadOnly } from '../../Slices';\nimport { GridTooltip } from '../../Tooltips';\n\n// The kinds of card an interaction card can be; external events are drawn by their own card.\nexport type InteractionCardKind = ArtifactCardKind.command | ArtifactCardKind.readModel;\n\nexport interface InteractionCardProps {\n sliceId: Guid;\n kind: InteractionCardKind;\n artifactId: Guid;\n name: string;\n schema: JsonSchema;\n showDetails?: boolean;\n // Offered only when supplied and the slice is editable.\n onRenamed?: (name: string) => void;\n}\n\n// A slice's command or read model. It is renamed in place with a double-click, shows whether it is\n// selected, and offers whatever the consumer supplies for its kind of card; clicking it activates it.\nexport const InteractionCard = ({ sliceId, kind, artifactId, name, schema, showDetails = false, onRenamed }: InteractionCardProps) => {\n const { actions, selection, messages } = useBoard();\n const sliceReadOnly = useSliceReadOnly();\n const [shownName, setShownName] = useState(name);\n const [editingName, setEditingName] = useState<string | undefined>(undefined);\n\n useEffect(() => setShownName(name), [name]);\n\n const isCommand = kind === ArtifactCardKind.command;\n const surface = isCommand ? actions.commandCard : actions.readModelCard;\n const colors = isCommand ? commandCardColors : readModelCardColors;\n const label = isCommand ? messages.interaction.command : messages.interaction.readModel;\n const canRename = !sliceReadOnly && !!onRenamed;\n const onArtifactSelected = selection.onArtifactSelected;\n\n const commit = () => {\n const trimmed = editingName?.trim() ?? '';\n setEditingName(undefined);\n if (!trimmed || !onRenamed) return;\n onRenamed(trimmed);\n setShownName(trimmed);\n };\n\n if (editingName !== undefined) {\n return (\n <CardNameInput\n value={editingName}\n backgroundColor={colors.background}\n textColor={colors.text}\n onChange={setEditingName}\n onCommit={commit}\n onCancel={() => setEditingName(undefined)}\n />\n );\n }\n\n return (\n <GridTooltip\n content={<SchemaTooltipProperties title={`${messages.interaction.doubleClickToRenamePrefix} ${label}: ${shownName}`} schema={schema} />}\n position='top'\n >\n <div data-flow-node={isCommand ? FlowNodeActor.command : FlowNodeActor.readModel}>\n <ArtifactCard\n kind={kind}\n artifactId={artifactId}\n name={shownName}\n schema={schema}\n showDetails={showDetails}\n actions={surface?.actions}\n onActivate={surface?.onActivate}\n isSelected={!!selection.selectedArtifactId?.equals(artifactId)}\n onSelected={onArtifactSelected ? () => onArtifactSelected(artifactId) : undefined}\n onStartEdit={canRename ? () => setEditingName(shownName) : undefined}\n ariaLabel={`${messages.interaction.open} ${label}: ${shownName}`}\n data-card-id={artifactId.toString()}\n data-slice-id={sliceId.toString()}\n />\n </div>\n </GridTooltip>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport type { ReactNode } from 'react';\nimport { type CellConnectors, ConnectorIncomingBottom, ConnectorIncomingTop, ConnectorOutgoingBottom, ConnectorOutgoingTop } from '../../Connections';\nimport { InteractionMiniCard } from './InteractionMiniCard';\n\n// How a slice's interaction cell arranges its cards.\nexport type InteractionLayout =\n // The cards centered, with the connectors running through the whole cell.\n | { kind: 'centered'; cards: ReactNode; corners?: ReactNode; hasItems: boolean }\n // A read model and a command side by side, each connector over its own card.\n | { kind: 'sideBySide'; cards: ReactNode; readModelOnTop: boolean; commandBelow: boolean; hasLeftCard: boolean; hasRightCard: boolean }\n // The external events on the left and the slice's own command on the right, each with its own corner.\n | { kind: 'split'; left: ReactNode; leftCorner?: ReactNode; right: ReactNode; rightCorner?: ReactNode; hasItems: boolean };\n\nexport interface InteractionCellProps {\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // What a collapsed cell draws, one small mark per card.\n miniCards: readonly InteractionMiniCard[];\n layout: InteractionLayout;\n}\n\nconst centered = 'event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--interaction';\n\n// A slice's cell in the interaction row: its command and read-model cards between the connectors.\nexport const InteractionCell = ({ collapsed = false, conn, rowHeight, miniCards, layout }: InteractionCellProps) => {\n const style = { height: rowHeight };\n if (collapsed) {\n return (\n <div style={style} className={centered}>\n {miniCards.map((kind, index) => <div key={index} className={`event-modeling-grid-mini-card event-modeling-grid-mini-card--${kind}`} />)}\n </div>\n );\n }\n\n if (layout.kind === 'sideBySide') {\n return (\n <div style={style} className={centered}>\n {conn.topOutgoing && layout.readModelOnTop && <ConnectorOutgoingTop columnPosition={layout.hasRightCard ? 'left' : 'center'} />}\n {conn.topIncoming && layout.commandBelow && <ConnectorIncomingTop columnPosition={layout.hasLeftCard ? 'right' : 'center'} />}\n <div className='event-modeling-grid-slice-cell-cards'>{layout.cards}</div>\n </div>\n );\n }\n\n const connectors = layout.hasItems && (\n <>\n {conn.topOutgoing && <ConnectorOutgoingTop />}\n {conn.topIncoming && <ConnectorIncomingTop />}\n {conn.bottomOutgoing && <ConnectorOutgoingBottom />}\n {conn.bottomIncoming && <ConnectorIncomingBottom />}\n </>\n );\n\n if (layout.kind === 'split') {\n return (\n <div style={style} className='event-modeling-grid-slice-cell event-modeling-grid-slice-cell--translator event-modeling-grid-slice-cell--interaction'>\n {connectors}\n <div className='event-modeling-grid-slice-cell--translator-external'>\n <div className='event-modeling-grid-slice-cell-cards'>{layout.left}</div>\n {layout.leftCorner}\n </div>\n <div className='event-modeling-grid-slice-cell--translator-regular'>\n <div className='event-modeling-grid-slice-cell-cards'>{layout.right}</div>\n {layout.rightCorner}\n </div>\n </div>\n );\n }\n\n return (\n <div style={style} className={centered}>\n {connectors}\n <div className='event-modeling-grid-slice-cell-cards'>{layout.cards}</div>\n {layout.corners}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// What a collapsed interaction cell draws a small mark for.\nexport enum InteractionMiniCard {\n command = 'command',\n readModel = 'readmodel',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './OptionalReadModel.css';\nimport { useRef } from 'react';\n\nexport interface OptionalReadModelProps {\n // Drawn on the placeholder card.\n label: string;\n // The define button's accessible name and tooltip.\n defineLabel: string;\n // Receives the viewport rectangle of the placeholder card, so an editor can open from it.\n onDefine: (host: DOMRect) => void;\n}\n\n// A placeholder card where a slice may define a read model it does not have yet, with a button to define it.\nexport const OptionalReadModel = ({ label, defineLabel, onDefine }: OptionalReadModelProps) => {\n const card = useRef<HTMLDivElement>(null);\n return (\n <div className='event-modeling-grid-optional-read-model' ref={card}>\n <div className='event-modeling-grid-optional-read-model__card'>\n <span>{label}</span>\n </div>\n <button\n type='button'\n className='event-modeling-grid-optional-read-model__define-btn'\n aria-label={defineLabel}\n title={defineLabel}\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n onDefine(card.current?.getBoundingClientRect() ?? new DOMRect());\n }}\n >\n <i className='pi pi-pencil' />\n </button>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../../Board';\nimport { ArtifactCardKind } from '../../Cards';\nimport type { CellConnectors } from '../../Connections';\nimport { FlowNodeActor } from '../../Connections/FlowNodeActor';\nimport { type EventItem, type ExternalEventItem, type Slice, SliceType } from '../../Model';\nimport { EventReferencePicker } from '../../Pickers';\nimport { SchemaTooltipProperties } from '../../Properties';\nimport { ExternalEventCard } from '../../References';\nimport { useSliceReadOnly } from '../../Slices';\nimport { GridTooltip } from '../../Tooltips';\nimport { CellActionButton } from '../CellActionButton';\nimport { CellCorner } from '../CellCorner';\nimport { CellCornerPlacement } from '../CellCornerPlacement';\nimport { showsExternalEventPicker } from '../eventRowAffordances';\nimport { InteractionCard } from './InteractionCard';\nimport { InteractionCell } from './InteractionCell';\nimport { InteractionMiniCard } from './InteractionMiniCard';\nimport { OptionalReadModel } from './OptionalReadModel';\n\nexport interface SliceInteractionProps {\n slice: Slice;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // The events of other modules a Translator can translate from.\n externalEventOptions?: readonly EventItem[];\n showDetails?: boolean;\n}\n\n// The mark a collapsed cell draws per card, in the order the cards are drawn.\nconst miniCardsOf = (slice: Slice): InteractionMiniCard[] => {\n switch (slice.sliceType) {\n case SliceType.stateChange: return slice.command ? [InteractionMiniCard.command] : [];\n case SliceType.stateView: return slice.readModel ? [InteractionMiniCard.readModel] : [];\n case SliceType.automation: return [\n ...(slice.readModel ? [InteractionMiniCard.readModel] : []),\n ...(slice.command ? [InteractionMiniCard.command] : []),\n ];\n default: return [\n ...slice.externalEvents.map(() => InteractionMiniCard.readModel),\n ...(slice.command ? [InteractionMiniCard.command] : []),\n ];\n }\n};\n\n// A slice's interaction row: its command, its read model, and a Translator's external events, laid out\n// for the slice type, with the ways to add what the slice may still have.\nexport const SliceInteraction = ({ slice, collapsed = false, conn, rowHeight, externalEventOptions = [], showDetails = false }: SliceInteractionProps) => {\n const { editing, actions, selection, navigation, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const { onCommandRenamed, onReadModelRenamed, onReadModelAdded, onExternalEventAdded } = editing;\n const rowActions = (actions.interactionRow ?? []).filter(action => !action.when || action.when(slice));\n const miniCards = miniCardsOf(slice);\n const onArtifactSelected = selection.onArtifactSelected;\n\n const { command, readModel } = slice;\n const commandCard = command && (\n <InteractionCard\n key={command.id.toString()}\n sliceId={slice.id}\n kind={ArtifactCardKind.command}\n artifactId={command.id}\n name={command.name}\n schema={command.schema}\n showDetails={showDetails}\n onRenamed={onCommandRenamed && (name => onCommandRenamed(slice.id, command.id, name))}\n />\n );\n const readModelCard = readModel && (\n <InteractionCard\n key={readModel.id.toString()}\n sliceId={slice.id}\n kind={ArtifactCardKind.readModel}\n artifactId={readModel.id}\n name={readModel.name}\n schema={readModel.schema}\n showDetails={showDetails}\n onRenamed={onReadModelRenamed && (name => onReadModelRenamed(slice.id, readModel.id, name))}\n />\n );\n const externalEventCard = (external: ExternalEventItem) => {\n const label = `${messages.interaction.open} ${messages.interaction.externalEvent}: ${external.name}`;\n const schema = externalEventOptions.find(option => option.name === external.name)?.schema;\n return (\n <GridTooltip\n key={external.id.toString()}\n content={<SchemaTooltipProperties title={`${messages.interaction.doubleClickToRenamePrefix} ${messages.interaction.externalEvent}: ${external.name}`} schema={schema} />}\n position='top'\n >\n <div data-flow-node={FlowNodeActor.externalEvent}>\n <ExternalEventCard\n id={external.id}\n name={external.name}\n sourceEventId={external.sourceEventId ? Guid.parse(external.sourceEventId) : undefined}\n onNavigate={navigation.onNavigateToEvent}\n isSelected={!!selection.selectedArtifactId?.equals(external.id)}\n onSelected={onArtifactSelected ? () => onArtifactSelected(external.id) : undefined}\n ariaLabel={label}\n data-card-id={external.id.toString()}\n data-slice-id={slice.id.toString()}\n />\n </div>\n </GridTooltip>\n );\n };\n const corner: ReactNode = !readOnly && rowActions.length > 0 && (\n <CellCorner placement={CellCornerPlacement.add}>\n {rowActions.map(action => <CellActionButton key={action.tooltip} action={action} />)}\n </CellCorner>\n );\n\n if (slice.sliceType === SliceType.automation && !collapsed) {\n const offersReadModel = !readOnly && !slice.readModel && !!slice.command && !!onReadModelAdded;\n return (\n <InteractionCell\n conn={conn}\n rowHeight={rowHeight}\n miniCards={miniCards}\n layout={{\n kind: 'sideBySide',\n readModelOnTop: !!slice.readModel,\n commandBelow: !!slice.command,\n hasLeftCard: !!slice.readModel || offersReadModel,\n hasRightCard: !!slice.command,\n cards: (\n <>\n {readModelCard}\n {offersReadModel && (\n <OptionalReadModel\n label={messages.interaction.readModel}\n defineLabel={messages.interaction.defineReadModel}\n onDefine={host => onReadModelAdded(slice.id, host)}\n />\n )}\n {commandCard}\n </>\n ),\n }}\n />\n );\n }\n\n if (slice.sliceType === SliceType.translator && !collapsed) {\n const added = new Set(slice.externalEvents.map(external => external.name));\n return (\n <InteractionCell\n conn={conn}\n rowHeight={rowHeight}\n miniCards={miniCards}\n layout={{\n kind: 'split',\n hasItems: slice.externalEvents.length > 0 || !!slice.command,\n left: slice.externalEvents.map(externalEventCard),\n leftCorner: !readOnly && showsExternalEventPicker(slice.sliceType) && onExternalEventAdded && (\n <CellCorner placement={CellCornerPlacement.add}>\n <EventReferencePicker\n options={externalEventOptions.filter(option => !added.has(option.name))}\n nameOf={option => option.name}\n onSelect={option => onExternalEventAdded(slice.id, option)}\n label={messages.interaction.addExternalEvent}\n searchPlaceholder={messages.interaction.searchExternalEvents}\n emptyLabel={messages.interaction.noExternalEventsAvailable}\n />\n </CellCorner>\n ),\n right: commandCard,\n rightCorner: corner,\n }}\n />\n );\n }\n\n const cards = slice.sliceType === SliceType.stateView\n ? readModelCard\n : slice.sliceType === SliceType.automation\n ? <>{readModelCard}{commandCard}</>\n : slice.sliceType === SliceType.translator\n ? <>{slice.externalEvents.map(externalEventCard)}{commandCard}</>\n : commandCard;\n\n return (\n <InteractionCell\n collapsed={collapsed}\n conn={conn}\n rowHeight={rowHeight}\n miniCards={miniCards}\n layout={{ kind: 'centered', hasItems: miniCards.length > 0, cards, corners: corner }}\n />\n );\n};\n"],"mappings":";;;;;;;;AAGA,IAAY,KAAL,0BAAA,GAAA;AACH,SAAA,EAAA,EAAA,SAAA,CAAA,IAAA,UACA,EAAA,EAAA,aAAA,CAAA,IAAA,cACA,EAAA,EAAA,WAAA,CAAA,IAAA;AACJ,GAAA,CAAA,CAAA,GCJY,KAAL,0BAAA,GAAA;AACH,SAAA,EAAA,SAAA,UACA,EAAA,QAAA,SACA,EAAA,OAAA;AACJ,GAAA,CAAA,CAAA,GCJY,KAAL,0BAAA,GAAA;AACH,SAAA,EAAA,EAAA,QAAA,CAAA,IAAA,SACA,EAAA,EAAA,QAAA,CAAA,IAAA,SACA,EAAA,EAAA,SAAA,CAAA,IAAA,UACA,EAAA,EAAA,OAAA,CAAA,IAAA;AACJ,GAAA,CAAA,CAAA,GCLY,KAAL,0BAAA,GAAA;AACH,SAAA,EAAA,EAAA,SAAA,CAAA,IAAA,UACA,EAAA,EAAA,QAAA,CAAA,IAAA,SACA,EAAA,EAAA,kBAAA,CAAA,IAAA;AACJ,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AAI,CAAC;AAAA,YACtE,QAAA,CAAQ,MAAU,EAAO;AAAA,YACzB,UAAA,CAAU,MAAU,EAAqB,EAAM,IAAI,CAAM;AAAA,YACzD,OAAO,EAAS,YAAY;AAAA,YAC5B,mBAAmB,EAAS,YAAY;AAAA,YACxC,YAAY,EAAS,YAAY;AAAA,UACpC,CAAA;AAAA,QACO,CAAA;AAAA,QAEhB,OAAO;AAAA,QACP,aAAa;AAAA,MACjB;AAAA,IACH,CAAA;AAAA,EAET;AAEA,QAAM,IAAQ,EAAM,cAAc,EAAU,YACtC,IACA,EAAM,cAAc,EAAU,aAC1B,gBAAA,EAAA,GAAA,EAAA,UAAA,CAAG,GAAe,CAAc,EAAA,CAAA,IAChC,EAAM,cAAc,EAAU,aAC1B,gBAAA,EAAA,GAAA,EAAA,UAAA,CAAG,EAAM,eAAe,IAAI,CAAiB,GAAG,CAAc,EAAA,CAAA,IAC9D;AAEd,SACI,gBAAA,EAAC,IAAD;AAAA,IACe,WAAA;AAAA,IACL,MAAA;AAAA,IACK,WAAA;AAAA,IACA,WAAA;AAAA,IACX,QAAQ;AAAA,MAAE,MAAM;AAAA,MAAY,UAAU,EAAU,SAAS;AAAA,MAAG,OAAA;AAAA,MAAO,SAAS;AAAA,IAAO;AAAA,EACtF,CAAA;AAET"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../Model/ActorType.ts","../Model/AssigneeKind.ts","../Model/AutomationTriggerType.ts","../Model/ConcurrencyValueSource.ts","../Model/QueryParameterType.ts","../Model/SliceStatus.ts","../Model/SliceType.ts","../Model/SpecificationErrorRuleKind.ts","../Model/SpecificationRunOutcome.ts","../Reading/InvalidEventModelDocument.ts","../Reading/isKnownValue.ts","../Reading/DocumentNode.ts","../Reading/readBoardItems.ts","../Reading/readActors.ts","../Reading/readJsonSchema.ts","../Reading/readSliceItems.ts","../Reading/readSpecification.ts","../Reading/readSlice.ts","../Reading/readModules.ts","../Reading/readEventModelDocument.ts","../Messages/defaultViewOptionsMessages.ts","../Messages/defaultEventModelMessages.ts","../Messages/EventModelMessagesContext.ts","../Messages/EventModelMessagesProvider.tsx","../Presentation/DetailLevel.ts","../Presentation/detailsVisibility.ts","../Presentation/defaultEventModelPresentation.ts","../Presentation/EventModelPresentationContext.ts","../Presentation/EventModelPresentationChangeContext.ts","../Presentation/EventModelPresentationProvider.tsx","../Rows/RowType.ts","../Tooltips/AnchoredOverlay.tsx","../Tooltips/GridTooltip.tsx","../Slices/resolveSliceReadOnly.ts","../Board/BoardInteractionContext.ts","../Board/BoardInteractionProvider.tsx","../Board/BoardReadOnlyContext.ts","../Board/BoardProvider.tsx","../Board/useBoard.ts","../Board/BoardCanvas.tsx","../Collections/useCollectionMove.ts","../Collections/CollectionMoveHandle.tsx","../Collections/collectionState.ts","../Collections/useCollectionsArea.ts","../Layout/boardMetrics.ts","../Properties/schemaProperties.ts","../Layout/cardHeight.ts","../Layout/sliceLayout.ts","../RowLabels/actorRows.ts","../Layout/sliceRows.ts","../Viewport/viewportFlushScheduler.ts","../Viewport/useInViewport.ts","../Collections/CollectionViewport.tsx","../Geometry/CurveAxis.ts","../Geometry/connectionCurve.ts","../Geometry/linkGeometry.ts","../Geometry/pillLabelWidth.ts","../Geometry/rowLabelWidth.ts","../RowLabels/ActorRowDragGhost.tsx","../RowLabels/ActorRowDropIndicator.tsx","../RowLabels/actorKinds.ts","../Headers/CollapseButton.tsx","../Headers/DetailsToggle.tsx","../Headers/EditableLabel.tsx","../Headers/EntityErrorIndicator.tsx","../Headers/EntityErrorKind.ts","../Headers/ErroredEntity.tsx","../Headers/PillHeader.tsx","../Pickers/useDismissOnOutsidePointer.ts","../RowLabels/rowTypeName.ts","../RowLabels/RowLabel.tsx","../RowLabels/RowLabelsColumnFrame.tsx","../RowLabels/useActorRowDrag.ts","../RowLabels/RowLabelsColumn.tsx","../Modules/ModuleColumnFrame.tsx","../Modules/ModuleDropIndicator.tsx","../SliceDragging/snapshotSlice.ts","../HeaderDragging/createHeaderDragGhost.ts","../HeaderDragging/HeaderDragGhost.tsx","../HeaderDragging/headerDropIndex.ts","../HeaderDragging/reorderedIds.ts","../HeaderDragging/zoomOfAncestor.ts","../HeaderDragging/useHeaderDragIntent.ts","../Statuses/SliceStatusIcon.tsx","../Menus/MenuDropdown.tsx","../Statuses/changeSliceStatus.ts","../Statuses/sliceStatuses.ts","../Statuses/SliceStatusPicker.tsx","../Modules/ModuleHeaderMenu.tsx","../Features/FeatureSuggestions.tsx","../Modules/ModuleHeader.tsx","../Modules/useModuleDrag.ts","../Modules/moduleAreaState.ts","../Modules/persistModuleChange.ts","../Modules/ModulesArea.tsx","../Modules/moduleWidth.ts","../Modules/ModuleHeaderCell.tsx","../Modules/ModulePlaceholder.tsx","../Modules/ModuleSurface.tsx","../Collections/collectionGridLayout.ts","../Collections/estimateCollectionSize.ts","../Collections/useSliceDetailsVisibility.ts","../Connections/Connectors.tsx","../Connections/FlowNodeActor.ts","../Connections/computeSliceConnections.ts","../Connections/flowNodeOrder.ts","../Connections/SliceConnections.tsx","../Connections/SliceConnectionsContext.tsx","../Connections/useConnectionHighlight.ts","../Features/FeatureColumnFrame.tsx","../Features/FeatureGridSurface.tsx","../Features/FeatureHeaderCell.tsx","../Features/featureDropEdge.ts","../Features/useFeatureDrag.ts","../Features/useFeatureSlotTargets.ts","../Features/featureAreaState.ts","../Features/FeaturesArea.tsx","../SliceTypes/SliceTypeIcon.tsx","../SliceTypes/sliceTypeMenuItems.tsx","../SliceTypes/SliceTypeExplanation.tsx","../SliceTypes/SliceTypeMenu.tsx","../Features/FeatureAddMenu.tsx","../Features/featureHeaderMenuItems.ts","../Features/FeatureHeaderMenu.tsx","../Features/FeatureHeader.tsx","../Specifications/SpecificationRunState.ts","../Specifications/SpecificationRunButton.tsx","../Specifications/SpecificationStatus.tsx","../Specifications/SpecificationHeader.tsx","../Specifications/specificationCollectionState.ts","../Specifications/SpecificationCollection.tsx","../Specifications/SpecificationSection.tsx","../Cards/pascalCaseBreak.ts","../Cards/autoFitTitle.ts","../Cards/useAutoFitTitle.ts","../Cards/Card.tsx","../Cards/cardColors.ts","../Properties/TypeBadge.tsx","../Properties/SchemaTooltipProperties.tsx","../Cards/ArtifactCardKind.ts","../Cards/CardCorner.ts","../Cards/CardActionButton.tsx","../Cards/EventTags.tsx","../Cards/ArtifactCard.tsx","../Cards/CardNameInput.tsx","../Specifications/itemValues.ts","../Pickers/PickerPanel.tsx","../Pickers/EventReferencePicker.tsx","../Specifications/SpecificationAddPicker.tsx","../Specifications/SpecificationItemCard.tsx","../Specifications/SpecificationItemKind.ts","../Specifications/SpecificationRow.tsx","../Specifications/specificationEvents.ts","../Specifications/RemovableSpecificationItem.tsx","../Specifications/GivenSection.tsx","../Specifications/WhenSection.tsx","../Specifications/ruleErrors.ts","../Specifications/SpecificationErrorCard.tsx","../Specifications/ThenSection.tsx","../Collections/SliceLines.tsx","../Collections/CollectionGridSlice.tsx","../Collections/CollectionGridTemplate.tsx","../Collections/CollectionGridFeatureColumn.tsx","../Collections/CollectionGridFeature.tsx","../Collections/CollectionGridModule.tsx","../Collections/localCollapses.ts","../Collections/CollectionGrid.tsx","../Icons/CogWheel.tsx","../Icons/CratisLogo.tsx","../Board/BoardViewOptions.tsx","../Board/BoardOverlay.tsx","../Links/linkState.ts","../Links/drawableLinks.ts","../Links/ModuleCollectionLinks.tsx","../StickyNotes/isEditableTarget.ts","../StickyNotes/StickyNoteState.ts","../StickyNotes/StickyNotes.tsx","../Board/BoardCollectionView.tsx","../Board/boardMinimap.ts","../Board/isLargeBoard.ts","../Board/HostedEventModelBoard.tsx","../Board/EventModelBoard.tsx","../Board/BoardToolbar.tsx","../Slices/SliceContext.ts","../Slices/SliceProvider.tsx","../Slices/useSlice.ts","../Slices/SliceHeader.tsx","../SliceDragging/dropIndicatorClassName.ts","../SliceDragging/SliceDragGestureVerdict.ts","../SliceDragging/readSliceDragGesture.ts","../SliceDragging/readSlicePress.ts","../SliceDragging/SliceDragGhost.tsx","../SliceDragging/SliceDropIndicator.tsx","../SliceDragging/SliceDropTarget.tsx","../SliceDragging/sliceMove.ts","../SliceDragging/useSliceDrag.ts","../SliceDragging/useSliceDragIntent.ts","../Slices/SliceColumnFrame.tsx","../Slices/SliceColumn.tsx","../Slices/createOptimisticSlice.ts","../Slices/sliceAreaState.ts","../Slices/SlicesArea.tsx","../Slices/SliceRows.tsx","../Slices/SlicePlaceholder.tsx","../Rows/CellActionButton.tsx","../Rows/CellCornerPlacement.ts","../Rows/CellCorner.tsx","../Rows/CellCornerAction.tsx","../Rows/eventRowAffordances.ts","../Rows/System/triggerBadges.ts","../Rows/System/TriggerKind.ts","../Rows/System/TriggerControl.tsx","../Rows/System/SystemCell.tsx","../Rows/UserExperience/addPrototypeMenuItems.ts","../Rows/UserExperience/AddPrototypeButton.tsx","../Rows/UserExperience/UiCell.tsx","../Rows/Chat/ChatCell.tsx","../Rows/Events/EventsCell.tsx","../Rows/Events/EventCard.tsx","../References/EventNavigateButton.tsx","../References/useReferenceHover.ts","../References/ExternalEventCard.tsx","../Rows/Events/EventReferenceCard.tsx","../Rows/Events/projectedFromTheRight.ts","../Rows/Events/referenceableEvents.ts","../Rows/Events/SliceEvents.tsx","../Rows/Interaction/InteractionCard.tsx","../Rows/Interaction/InteractionCell.tsx","../Rows/Interaction/InteractionMiniCard.ts","../Rows/Interaction/OptionalReadModel.tsx","../Rows/Interaction/SliceInteraction.tsx"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum ActorType {\n UIRole = 0,\n systemRole = 1,\n chatRole = 2,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum AssigneeKind {\n system = 'system',\n agent = 'agent',\n user = 'user',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum AutomationTriggerType {\n timer = 0,\n event = 1,\n custom = 2,\n none = 3,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum ConcurrencyValueSource {\n notSet = 0,\n value = 1,\n commandProperty = 2,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum QueryParameterType {\n text = 0,\n number = 1,\n boolean = 2,\n date = 3,\n time = 4,\n uniqueId = 5,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum SliceStatus {\n notStarted = 0,\n draft = 1,\n readyForImplementation = 2,\n inProgress = 3,\n readyForReview = 4,\n done = 5,\n analysis = 6,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum SliceType {\n stateChange = 0,\n stateView = 1,\n automation = 2,\n translator = 3,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum SpecificationErrorRuleKind {\n commandValidationRule = 0,\n eventUniqueConstraint = 1,\n eventUniqueEventTypeConstraint = 2,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum SpecificationRunOutcome {\n passed = 0,\n failed = 1,\n inconclusive = 2,\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport class InvalidEventModelDocument extends Error {\n constructor(readonly path: string, reason: string) {\n super(`Invalid event model document at '${path}': ${reason}`);\n this.name = 'InvalidEventModelDocument';\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Whether a wire value is one of the members of a re-declared enum. A document written by a newer\n// producer may carry a value this package has not heard of; the board draws that as an explicit\n// unknown rather than guessing.\nexport const isKnownValue = (enumeration: Record<string, string | number>, value: string | number): boolean =>\n Object.values(enumeration).includes(value);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Guid } from '@cratis/fundamentals';\nimport { InvalidEventModelDocument } from './InvalidEventModelDocument';\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst isAbsent = (value: unknown): boolean => value === undefined || value === null;\n\n// One object in an event model document, read by key. Only the keys a reader asks for are ever\n// copied into the contract, which is what makes unknown fields from a newer producer harmless.\nexport class DocumentNode {\n private constructor(private readonly _value: Record<string, unknown>, readonly path: string) {\n }\n\n static root(value: unknown): DocumentNode {\n if (!isRecord(value)) {\n throw new InvalidEventModelDocument('$', 'the document must be an object');\n }\n return new DocumentNode(value, '$');\n }\n\n has(key: string): boolean {\n return !isAbsent(this._value[key]);\n }\n\n string(key: string): string {\n return this.optionalString(key) ?? '';\n }\n\n optionalString(key: string): string | undefined {\n const value = this._value[key];\n if (isAbsent(value)) return undefined;\n if (typeof value !== 'string') throw this.invalid(key, 'expected a string');\n return value;\n }\n\n number(key: string): number {\n const value = this._value[key];\n if (isAbsent(value)) return 0;\n if (typeof value !== 'number') throw this.invalid(key, 'expected a number');\n return value;\n }\n\n // Enums are wire values. A number the package does not know is kept as it is — the board shows it\n // as an explicit unknown — so only a missing value or a value of the wrong type is rejected.\n enumValue(key: string): number {\n const value = this._value[key];\n if (typeof value !== 'number') throw this.invalid(key, 'expected a numeric enum value');\n return value;\n }\n\n optionalEnumValue(key: string): number | undefined {\n return this.has(key) ? this.enumValue(key) : undefined;\n }\n\n boolean(key: string): boolean {\n const value = this._value[key];\n if (isAbsent(value)) return false;\n if (typeof value !== 'boolean') throw this.invalid(key, 'expected a boolean');\n return value;\n }\n\n guid(key: string): Guid {\n const value = this.optionalGuid(key);\n if (!value) throw this.invalid(key, 'expected a GUID');\n return value;\n }\n\n optionalGuid(key: string): Guid | undefined {\n const value = this._value[key];\n if (isAbsent(value)) return undefined;\n if (value instanceof Guid) return value;\n if (typeof value !== 'string' || !Guid.isGuid(value)) throw this.invalid(key, 'expected a GUID');\n return Guid.parse(value);\n }\n\n strings(key: string): string[] {\n const value = this._value[key];\n if (isAbsent(value)) return [];\n if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) throw this.invalid(key, 'expected an array of strings');\n return value.map(item => String(item));\n }\n\n record(key: string): Record<string, unknown> {\n const value = this._value[key];\n if (isAbsent(value)) return {};\n if (!isRecord(value)) throw this.invalid(key, 'expected an object');\n return { ...value };\n }\n\n raw(key: string): unknown {\n return this._value[key];\n }\n\n object(key: string): DocumentNode | undefined {\n const value = this._value[key];\n if (isAbsent(value)) return undefined;\n if (!isRecord(value)) throw this.invalid(key, 'expected an object');\n return new DocumentNode(value, `${this.path}.${key}`);\n }\n\n array<T>(key: string, read: (node: DocumentNode) => T): T[] {\n const value = this._value[key];\n if (isAbsent(value)) return [];\n if (!Array.isArray(value)) throw this.invalid(key, 'expected an array');\n return value.map((item, index) => {\n const path = `${this.path}.${key}[${index}]`;\n if (!isRecord(item)) throw new InvalidEventModelDocument(path, 'expected an object');\n return read(new DocumentNode(item, path));\n });\n }\n\n private invalid(key: string, reason: string): InvalidEventModelDocument {\n return new InvalidEventModelDocument(`${this.path}.${key}`, reason);\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ModuleCollectionLink, Position, StickyNote } from '../Model';\nimport type { DocumentNode } from './DocumentNode';\n\nexport const readPosition = (node: DocumentNode | undefined): Position => ({\n x: node?.number('x') ?? 0,\n y: node?.number('y') ?? 0,\n});\n\nexport const readStickyNote = (node: DocumentNode): StickyNote => ({\n id: node.string('id'),\n position: readPosition(node.object('position')),\n width: node.number('width'),\n height: node.number('height'),\n text: node.string('text'),\n});\n\nexport const readModuleCollectionLink = (node: DocumentNode): ModuleCollectionLink => ({\n id: node.guid('id'),\n sourceCollectionId: node.guid('sourceCollectionId'),\n targetCollectionId: node.guid('targetCollectionId'),\n});\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { UIElement } from '@cratis/scene';\nimport type { Actor, PersonaReference, UserExperienceActor } from '../Model';\nimport type { DocumentNode } from './DocumentNode';\n\n// Prototype elements belong to Cratis Scene, which hydrates them when it draws a thumbnail; the board\n// passes them through untouched rather than second-guessing Scene's own shape.\nconst isUIElement = (value: unknown): value is UIElement =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst readPersona = (node: DocumentNode | undefined): PersonaReference | undefined =>\n node ? { id: node.guid('id'), name: node.string('name') } : undefined;\n\nexport const readActor = (node: DocumentNode): Actor => {\n const persona = readPersona(node.object('persona'));\n return {\n id: node.string('id'),\n name: node.string('name'),\n actorType: node.enumValue('actorType'),\n description: node.string('description'),\n ...(persona ? { persona } : {}),\n };\n};\n\nexport const readUserExperienceActor = (node: DocumentNode): UserExperienceActor => {\n const elements = node.raw('elements');\n return {\n id: node.string('id'),\n type: node.enumValue('type'),\n elements: Array.isArray(elements) ? elements.filter(isUIElement) : [],\n layout: node.optionalEnumValue('layout') ?? 0,\n windowWidth: node.number('windowWidth'),\n windowHeight: node.number('windowHeight'),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { JsonSchema } from '@cratis/components/types';\n\nconst emptySchema = (): JsonSchema => ({ type: 'object', properties: {} });\n\nconst isJsonSchema = (value: unknown): value is JsonSchema => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const type: unknown = Reflect.get(value, 'type');\n const properties: unknown = Reflect.get(value, 'properties');\n return (type === undefined || typeof type === 'string')\n && (properties === undefined || (typeof properties === 'object' && properties !== null && !Array.isArray(properties)));\n};\n\n// Schemas arrive as an object, or — from older stored models — as the same object serialized to a\n// string. Anything that is neither reads as an empty object schema, which is what the board already\n// draws for a card whose schema could not be parsed.\nexport const readJsonSchema = (value: unknown): JsonSchema => {\n if (typeof value === 'string') {\n try {\n return readJsonSchema(JSON.parse(value));\n } catch {\n return emptySchema();\n }\n }\n return isJsonSchema(value) ? value : emptySchema();\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type {\n CommandConcurrency,\n CommandItem,\n CommandPropertyRules,\n ConcurrencyBinding,\n EventConstraint,\n EventConstraints,\n EventItem,\n ExternalEventItem,\n QueryItem,\n ReadModelItem\n} from '../Model';\nimport type { DocumentNode } from './DocumentNode';\nimport { readJsonSchema } from './readJsonSchema';\n\nconst readRules = (node: DocumentNode): CommandPropertyRules => ({\n propertyName: node.string('propertyName'),\n rules: node.array('rules', rule => ({ errorMessage: rule.string('errorMessage'), ruleType: rule.string('ruleType') })),\n});\n\nconst readBinding = (node: DocumentNode | undefined): ConcurrencyBinding | undefined =>\n node ? { source: node.enumValue('source'), value: node.string('value') } : undefined;\n\nconst readConcurrency = (node: DocumentNode | undefined): CommandConcurrency | undefined => {\n if (!node) return undefined;\n const scopeId = node.optionalGuid('scopeId');\n const eventSourceType = readBinding(node.object('eventSourceType'));\n const eventStreamType = readBinding(node.object('eventStreamType'));\n const eventStreamId = readBinding(node.object('eventStreamId'));\n return {\n includeEventSource: node.boolean('includeEventSource'),\n ...(scopeId ? { scopeId } : {}),\n ...(eventSourceType ? { eventSourceType } : {}),\n ...(eventStreamType ? { eventStreamType } : {}),\n ...(eventStreamId ? { eventStreamId } : {}),\n };\n};\n\nconst readConstraint = (node: DocumentNode | undefined): EventConstraint | undefined =>\n node ? { name: node.string('name'), message: node.string('message') } : undefined;\n\nconst readConstraints = (node: DocumentNode | undefined): EventConstraints | undefined => {\n if (!node) return undefined;\n const unique = readConstraint(node.object('unique'));\n const uniqueEventType = readConstraint(node.object('uniqueEventType'));\n return {\n ...(unique ? { unique } : {}),\n ...(uniqueEventType ? { uniqueEventType } : {}),\n };\n};\n\nexport const readCommandItem = (node: DocumentNode): CommandItem => {\n const concurrency = readConcurrency(node.object('concurrency'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n schema: readJsonSchema(node.raw('schema')),\n stateSchema: readJsonSchema(node.raw('stateSchema')),\n logicDescription: node.string('logicDescription'),\n ...(node.has('rules') ? { rules: node.array('rules', readRules) } : {}),\n ...(concurrency ? { concurrency } : {}),\n };\n};\n\nexport const readEventItem = (node: DocumentNode): EventItem => {\n const sourceEventId = node.optionalString('sourceEventId');\n const constraints = readConstraints(node.object('constraints'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n schema: readJsonSchema(node.raw('schema')),\n ...(sourceEventId ? { sourceEventId } : {}),\n ...(node.has('tags') ? { tags: node.strings('tags') } : {}),\n ...(constraints ? { constraints } : {}),\n };\n};\n\nexport const readExternalEventItem = (node: DocumentNode): ExternalEventItem => ({\n id: node.guid('id'),\n name: node.string('name'),\n sourceEventId: node.string('sourceEventId'),\n});\n\nexport const readReadModelItem = (node: DocumentNode): ReadModelItem => ({\n id: node.guid('id'),\n name: node.string('name'),\n schema: readJsonSchema(node.raw('schema')),\n materializes: node.boolean('materializes'),\n});\n\nexport const readQueryItem = (node: DocumentNode): QueryItem => ({\n id: node.guid('id'),\n name: node.string('name'),\n parameters: node.array('parameters', parameter => ({\n name: parameter.string('name'),\n type: parameter.enumValue('type'),\n })),\n});\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type {\n SliceSpecification,\n SpecificationCommand,\n SpecificationError,\n SpecificationErrorRuleReference,\n SpecificationGivenEvent,\n SpecificationReadModel\n} from '../Model';\nimport type { DocumentNode } from './DocumentNode';\n\nconst readEventStep = (node: DocumentNode): SpecificationGivenEvent => ({\n id: node.guid('id'),\n name: node.string('name'),\n eventId: node.guid('eventId'),\n values: node.record('values'),\n});\n\n// A specification's \"when\" exists before a command has been chosen for it, so the command it points\n// at can be absent in a stored model.\nconst readCommand = (node: DocumentNode | undefined): SpecificationCommand | undefined => {\n if (!node) return undefined;\n const commandId = node.optionalGuid('commandId');\n return {\n id: node.guid('id'),\n name: node.string('name'),\n values: node.record('values'),\n ...(commandId ? { commandId } : {}),\n };\n};\n\nconst readReadModel = (node: DocumentNode | undefined): SpecificationReadModel | undefined =>\n node\n ? {\n id: node.guid('id'),\n readModelItemId: node.guid('readModelItemId'),\n name: node.string('name'),\n ...(node.has('values') ? { values: node.record('values') } : {}),\n }\n : undefined;\n\nconst readReference = (node: DocumentNode | undefined): SpecificationErrorRuleReference | undefined =>\n node\n ? {\n kind: node.enumValue('kind'),\n itemId: node.guid('itemId'),\n propertyName: node.string('propertyName'),\n ruleType: node.string('ruleType'),\n }\n : undefined;\n\nconst readError = (node: DocumentNode): SpecificationError => {\n const reference = readReference(node.object('reference'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n ...(reference ? { reference } : {}),\n };\n};\n\nexport const readSliceSpecification = (node: DocumentNode): SliceSpecification => {\n const when = readCommand(node.object('when'));\n const givenReadModel = readReadModel(node.object('givenReadModel'));\n const lastRunOutcome = node.optionalEnumValue('lastRunOutcome');\n const lastRunMessage = node.optionalString('lastRunMessage');\n return {\n id: node.guid('id'),\n name: node.string('name'),\n given: node.array('given', readEventStep),\n thenEvents: node.array('thenEvents', readEventStep),\n thenErrors: node.array('thenErrors', readError),\n collapsed: node.boolean('collapsed'),\n ...(when ? { when } : {}),\n ...(givenReadModel ? { givenReadModel } : {}),\n ...(lastRunOutcome !== undefined ? { lastRunOutcome } : {}),\n ...(lastRunMessage !== undefined ? { lastRunMessage } : {}),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Assignee, AutomationTrigger, AutomationTriggerSchedule, Slice } from '../Model';\nimport { AssigneeKind } from '../Model/AssigneeKind';\nimport type { DocumentNode } from './DocumentNode';\nimport { InvalidEventModelDocument } from './InvalidEventModelDocument';\nimport { readUserExperienceActor } from './readActors';\nimport { readCommandItem, readEventItem, readExternalEventItem, readQueryItem, readReadModelItem } from './readSliceItems';\nimport { readSliceSpecification } from './readSpecification';\n\nconst readSchedule = (node: DocumentNode | undefined): AutomationTriggerSchedule | undefined =>\n node\n ? {\n intervalMinutes: node.number('intervalMinutes'),\n intervalHours: node.number('intervalHours'),\n timeOfDay: node.string('timeOfDay'),\n dayOfWeek: node.number('dayOfWeek'),\n dayOfMonth: node.number('dayOfMonth'),\n description: node.string('description'),\n }\n : undefined;\n\nconst readAutomationTrigger = (node: DocumentNode | undefined): AutomationTrigger | undefined => {\n if (!node) return undefined;\n const schedule = readSchedule(node.object('schedule'));\n const eventId = node.optionalGuid('eventId');\n return {\n type: node.enumValue('type'),\n description: node.string('description'),\n ...(schedule ? { schedule } : {}),\n ...(eventId ? { eventId } : {}),\n };\n};\n\nconst readAssigneeKind = (node: DocumentNode): AssigneeKind => {\n const kind = node.string('kind');\n const known = Object.values(AssigneeKind).find(value => value === kind);\n if (!known) throw new InvalidEventModelDocument(`${node.path}.kind`, `unknown assignee kind '${kind}'`);\n return known;\n};\n\nconst readAssignee = (node: DocumentNode | undefined): Assignee | undefined => {\n if (!node) return undefined;\n const avatar = node.optionalString('avatar');\n return {\n id: node.guid('id'),\n name: node.string('name'),\n kind: readAssigneeKind(node),\n ...(avatar ? { avatar } : {}),\n };\n};\n\nexport const readSlice = (node: DocumentNode): Slice => {\n const command = node.object('command');\n const readModel = node.object('readModel');\n const automationTrigger = readAutomationTrigger(node.object('automationTrigger'));\n const assignee = readAssignee(node.object('assignee'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n sliceType: node.enumValue('sliceType'),\n description: node.string('description'),\n status: node.enumValue('status'),\n collapsed: node.boolean('collapsed'),\n sortOrder: node.number('sortOrder'),\n externalEvents: node.array('externalEvents', readExternalEventItem),\n events: node.array('events', readEventItem),\n queries: node.array('queries', readQueryItem),\n actors: node.array('actors', readUserExperienceActor),\n specifications: node.array('specifications', readSliceSpecification),\n commentCount: node.number('commentCount'),\n ...(command ? { command: readCommandItem(command) } : {}),\n ...(readModel ? { readModel: readReadModelItem(readModel) } : {}),\n ...(automationTrigger ? { automationTrigger } : {}),\n ...(assignee ? { assignee } : {}),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Feature, Module, ModuleCollection, ScreenTemplate } from '../Model';\nimport type { DocumentNode } from './DocumentNode';\nimport { readActor } from './readActors';\nimport { readPosition } from './readBoardItems';\nimport { readSlice } from './readSlice';\n\nconst readScreenTemplate = (node: DocumentNode | undefined): ScreenTemplate | undefined =>\n node ? { id: node.string('id'), name: node.string('name') } : undefined;\n\nconst readFeature = (node: DocumentNode): Feature => {\n const screenTemplate = readScreenTemplate(node.object('screenTemplate'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n subFeatures: node.array('subFeatures', readFeature),\n slices: node.array('slices', readSlice),\n collapsed: node.boolean('collapsed'),\n rowCollapsed: node.boolean('rowCollapsed'),\n enabled: node.has('enabled') ? node.boolean('enabled') : true,\n commentCount: node.number('commentCount'),\n ...(screenTemplate ? { screenTemplate } : {}),\n };\n};\n\nconst readModule = (node: DocumentNode): Module => {\n const screenTemplate = readScreenTemplate(node.object('screenTemplate'));\n return {\n id: node.guid('id'),\n name: node.string('name'),\n features: node.array('features', readFeature),\n collapsed: node.boolean('collapsed'),\n sortOrder: node.number('sortOrder'),\n commentCount: node.number('commentCount'),\n ...(screenTemplate ? { screenTemplate } : {}),\n };\n};\n\nexport const readModuleCollection = (node: DocumentNode): ModuleCollection => ({\n id: node.guid('id'),\n position: readPosition(node.object('position')),\n modules: node.array('modules', readModule),\n actors: node.array('actors', readActor),\n});\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModel } from '../Model';\nimport { DocumentNode } from './DocumentNode';\nimport { readModuleCollectionLink, readStickyNote } from './readBoardItems';\nimport { readModuleCollection } from './readModules';\n\n// Reads an event model document from JSON — a fixture, a file the Viewer was given, or anything else\n// that did not come through Studio's own adapter. Unknown fields are ignored, enum values the package\n// does not know are kept for the board to show as unknown, and a missing optional section is left\n// absent. A value of the wrong type, or an identifier that is not a GUID, is an error that names\n// where in the document it was found.\nexport const readEventModelDocument = (json: unknown): EventModel => {\n const root = DocumentNode.root(json);\n return {\n id: root.guid('id'),\n name: root.string('name'),\n collections: root.array('collections', readModuleCollection),\n stickyNotes: root.array('stickyNotes', readStickyNote),\n links: root.array('links', readModuleCollectionLink),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ViewOptionsMessages } from './ViewOptionsMessages';\n\nexport const defaultViewOptionsMessages: ViewOptionsMessages = {\n view: 'View',\n detailLevel: 'Detail level',\n full: 'Full',\n overview: 'Overview',\n properties: 'Properties',\n visualization: 'Visualization',\n arrows: 'Arrows',\n lines: 'Lines',\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModelMessages } from './EventModelMessages';\nimport { defaultViewOptionsMessages } from './defaultViewOptionsMessages';\n\nexport const defaultEventModelMessages: EventModelMessages = {\n collapse: {\n expand: 'Expand',\n collapse: 'Collapse',\n },\n editableLabel: {\n doubleClickToRename: 'Double-click to rename',\n },\n erroredEntity: {\n module: 'module',\n feature: 'feature',\n slice: 'slice',\n couldNotBeRendered: (kind, error) => `This ${kind} could not be rendered: ${error}`,\n failedToRender: 'Failed to render',\n retry: 'Retry',\n },\n stickyNotes: {\n newNote: 'New Note',\n },\n links: {\n dragToLink: 'Drag onto another module collection to link them',\n removeLink: 'Remove link',\n },\n specificationStatus: {\n idle: 'Not run',\n running: 'Running…',\n passed: 'Last run succeeded',\n failed: 'Last run failed',\n inconclusive: 'Last run was inconclusive',\n },\n properties: {\n none: 'No properties',\n },\n references: {\n navigateToOriginal: 'Go to source',\n },\n interaction: {\n command: 'Command',\n readModel: 'Read Model',\n externalEvent: 'External Event',\n open: 'Open',\n doubleClickToRenamePrefix: 'Double-click to rename · Click to open',\n defineReadModel: 'Define read model',\n addExternalEvent: 'Add external event to translate from',\n searchExternalEvents: 'Search external events…',\n noExternalEventsAvailable: 'No events available in other modules',\n },\n events: {\n addEvent: 'Add Event',\n openEvent: 'Open Event:',\n doubleClickToRenamePrefix: 'Double-click to rename · Click to open Event:',\n addExistingEvent: 'Add existing event',\n searchEvents: 'Search events…',\n noEventsAvailable: 'No events available',\n noEventsYet: 'No events yet',\n projectedFromTheRight: 'Produced by a slice to the right. A State View only projects events from slices to its left.',\n },\n prototypes: {\n add: 'Add UI prototype',\n fromScratch: 'From scratch',\n fromScratchDescription: 'Start with an empty prototype',\n fromTemplate: 'From template',\n fromTemplateDescription: 'Start from a copy of an existing screen template',\n noTemplates: 'No templates available',\n },\n triggerControl: {\n add: 'Add trigger',\n edit: 'Edit trigger',\n kinds: {\n timer: { title: 'Timer', description: 'Runs on a fixed schedule with deterministic behavior.' },\n event: { title: 'Event', description: 'Runs when a specific event happens with deterministic behavior.' },\n custom: { title: 'Custom', description: 'Describe the behavior and let generation use the description.' },\n },\n },\n triggers: {\n timer: 'Timer trigger',\n event: 'Event trigger',\n custom: 'Custom trigger',\n },\n statuses: {\n notStarted: 'Not started',\n draft: 'Draft',\n analysis: 'Analysis',\n readyForImplementation: 'Ready for implementation',\n inProgress: 'In progress',\n readyForReview: 'Ready for review',\n done: 'Done',\n titlePrefix: 'Status:',\n change: 'Change status',\n },\n sliceTypes: {\n add: 'Add Slice',\n stateChange: 'State Change',\n stateChangeDescription: 'UI drives a command that produces events',\n stateView: 'State View',\n stateViewDescription: 'UI reads a projection built from events',\n automation: 'Automation',\n automationDescription: 'System reacts to events and issues commands',\n translator: 'Translator',\n translatorDescription: 'Translates external events into internal commands',\n },\n slices: {\n namePlaceholder: 'Slice…',\n empty: 'No slices yet — use + to add one',\n },\n modules: {\n add: 'Add', options: 'Module options', addModule: 'Add module',\n addModuleDescription: 'Add a module to this collection', addFeature: 'Add feature',\n addFeatureDescription: 'Add a feature to this module',\n },\n features: {\n empty: 'No features yet — use + to add one',\n add: 'Add',\n options: 'Feature options',\n addSubFeature: 'Add sub-feature',\n addSubFeatureDescription: 'Add a sub-feature to this feature',\n addSliceDescription: 'Choose a vertical slice type',\n back: 'Back',\n },\n details: {\n show: 'Show details',\n hide: 'Hide details',\n },\n specifications: {\n add: 'Add specification',\n namePlaceholder: 'Specification',\n delete: 'Delete specification',\n given: 'Given',\n when: 'When',\n then: 'Then',\n addItem: 'Add item',\n search: 'Search…',\n noItems: 'No items',\n addError: 'Add error',\n error: 'Error',\n missingRule: 'Rule no longer defined',\n defineReadModel: 'Define read model as given state',\n removeItem: 'Remove',\n },\n rows: {\n ui: 'UI',\n chat: 'Chat',\n system: 'System',\n interaction: 'Interaction',\n events: 'Events',\n },\n actors: {\n add: 'Add Actor',\n ui: 'UI Actor',\n system: 'System Actor',\n chat: 'Chat Actor',\n },\n viewOptions: defaultViewOptionsMessages,\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext, useContext } from 'react';\nimport type { EventModelMessages } from './EventModelMessages';\nimport { defaultEventModelMessages } from './defaultEventModelMessages';\n\nexport const EventModelMessagesContext = createContext<EventModelMessages>(defaultEventModelMessages);\n\nexport const useEventModelMessages = (): EventModelMessages => useContext(EventModelMessagesContext);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport type { EventModelMessages } from './EventModelMessages';\nimport { EventModelMessagesContext } from './EventModelMessagesContext';\n\nexport interface EventModelMessagesProviderProps {\n messages: EventModelMessages;\n children?: React.ReactNode;\n}\n\nexport const EventModelMessagesProvider = ({ messages, children }: EventModelMessagesProviderProps) => (\n <EventModelMessagesContext.Provider value={messages}>{children}</EventModelMessagesContext.Provider>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * The board-level detail level for the event modeling editor.\n * - `full` is the default, fully interactive view.\n * - `overview` is a compact, read-only, high-level view that hides specifications and property/detail\n * cells and disables every building/editing affordance.\n */\nexport type DetailLevel = 'full' | 'overview';\n\nexport const defaultDetailLevel: DetailLevel = 'full';\n\n/**\n * Whether a slice is read-only for the given detail level. The `overview` level forces every slice\n * read-only regardless of its workflow status; the `full` level defers to the slice's own status.\n */\nexport function isSliceReadOnlyForDetailLevel(detailLevel: DetailLevel, statusReadOnly: boolean): boolean {\n return detailLevel === 'overview' || statusReadOnly;\n}\n\n/**\n * Whether property/detail cells are shown for the given detail level. The `overview` level hides them\n * entirely; the `full` level defers to the per-scope details-visibility toggle.\n */\nexport function areSliceDetailsVisibleForDetailLevel(detailLevel: DetailLevel, detailsVisible: boolean): boolean {\n return detailLevel !== 'overview' && detailsVisible;\n}\n\n/** Whether specifications are shown for the given detail level. The `overview` level hides them entirely. */\nexport function areSpecificationsVisibleForDetailLevel(detailLevel: DetailLevel): boolean {\n return detailLevel !== 'overview';\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport interface DetailsVisibilityState {\n global: boolean;\n modules: Record<string, boolean>;\n features: Record<string, boolean>;\n slices: Record<string, boolean>;\n}\n\nexport const defaultDetailsVisibilityState: DetailsVisibilityState = {\n global: false,\n modules: {},\n features: {},\n slices: {},\n};\n\nfunction toggleScope(scope: Record<string, boolean>, id: string): Record<string, boolean> {\n return {\n ...scope,\n [id]: !(scope[id] ?? false),\n };\n}\n\nexport function toggleGlobalDetails(state: DetailsVisibilityState): DetailsVisibilityState {\n return {\n ...state,\n global: !state.global,\n };\n}\n\nexport function toggleModuleDetails(state: DetailsVisibilityState, moduleId: string): DetailsVisibilityState {\n return {\n ...state,\n modules: toggleScope(state.modules, moduleId),\n };\n}\n\nexport function toggleFeatureDetails(state: DetailsVisibilityState, featureId: string): DetailsVisibilityState {\n return {\n ...state,\n features: toggleScope(state.features, featureId),\n };\n}\n\nexport function toggleSliceDetails(state: DetailsVisibilityState, sliceId: string): DetailsVisibilityState {\n return {\n ...state,\n slices: toggleScope(state.slices, sliceId),\n };\n}\n\nexport function areDetailsVisible(\n state: DetailsVisibilityState,\n moduleId: string,\n featureId: string,\n sliceId: string,\n): boolean {\n return state.global\n || Boolean(state.modules[moduleId])\n || Boolean(state.features[featureId])\n || Boolean(state.slices[sliceId]);\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { defaultDetailLevel } from './DetailLevel';\nimport { defaultDetailsVisibilityState } from './detailsVisibility';\nimport type { EventModelPresentation } from './EventModelPresentation';\n\nexport const defaultEventModelPresentation: EventModelPresentation = {\n detailLevel: defaultDetailLevel,\n visualizationMode: 'simplified',\n detailsVisibility: defaultDetailsVisibilityState,\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext, useContext } from 'react';\nimport type { EventModelPresentation } from './EventModelPresentation';\nimport { defaultEventModelPresentation } from './defaultEventModelPresentation';\n\nexport const EventModelPresentationContext = createContext<EventModelPresentation>(defaultEventModelPresentation);\n\nexport const useEventModelPresentation = (): EventModelPresentation => useContext(EventModelPresentationContext);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext, useContext } from 'react';\nimport type { EventModelPresentationChange } from './EventModelPresentationChange';\n\n// Who changes the presentation when the board's own view options are used. Left out, the board keeps\n// the change to itself.\nexport const EventModelPresentationChangeContext = createContext<EventModelPresentationChange | undefined>(undefined);\n\nexport const useEventModelPresentationChange = (): EventModelPresentationChange | undefined => useContext(EventModelPresentationChangeContext);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport type { EventModelPresentation } from './EventModelPresentation';\nimport type { EventModelPresentationChange } from './EventModelPresentationChange';\nimport { EventModelPresentationChangeContext } from './EventModelPresentationChangeContext';\nimport { EventModelPresentationContext } from './EventModelPresentationContext';\n\nexport interface EventModelPresentationProviderProps {\n presentation: EventModelPresentation;\n // Called when the board's own view options ask for another presentation. The consumer decides\n // whether to show it - and where to keep it.\n onChange?: EventModelPresentationChange;\n children?: React.ReactNode;\n}\n\nexport const EventModelPresentationProvider = ({ presentation, onChange, children }: EventModelPresentationProviderProps) => (\n <EventModelPresentationContext.Provider value={presentation}>\n <EventModelPresentationChangeContext.Provider value={onChange}>{children}</EventModelPresentationChangeContext.Provider>\n </EventModelPresentationContext.Provider>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum RowType {\n UI = 'ui',\n Chat = 'chat',\n System = 'system',\n Interaction = 'interaction',\n Events = 'events',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { ReactNode, RefObject, useLayoutEffect, useState } from 'react';\nimport { createPortal } from 'react-dom';\n\n/** The side of the anchor the overlay prefers to open on. */\nexport type AnchoredOverlaySide = 'above' | 'below' | 'left' | 'right';\n\n/** Horizontal alignment relative to the anchor (for above/below overlays). */\nexport type AnchoredOverlayAlign = 'left' | 'right' | 'center';\n\nexport interface AnchoredOverlayProps {\n\n /** The element the overlay anchors to. */\n anchorRef: RefObject<HTMLElement | null>;\n\n /** Whether the overlay is shown. */\n open: boolean;\n\n /** The preferred side; above/below flip when the viewport leaves no room. */\n side?: AnchoredOverlaySide;\n\n /** Horizontal alignment for above/below overlays. */\n align?: AnchoredOverlayAlign;\n\n /** Gap between the anchor and the overlay in pixels. */\n gap?: number;\n\n /** The overlay content. */\n children: ReactNode;\n}\n\n/** Space on the preferred side under which an above/below overlay flips to the other side. */\nconst FLIP_THRESHOLD = 260;\n\ninterface Placement {\n top?: number;\n bottom?: number;\n left: number;\n transform?: string;\n}\n\nfunction computePlacement(anchor: DOMRect, side: AnchoredOverlaySide, align: AnchoredOverlayAlign, gap: number): Placement {\n if (side === 'left' || side === 'right') {\n return {\n top: anchor.top + (anchor.height / 2),\n left: side === 'right' ? anchor.right + gap : anchor.left - gap,\n transform: side === 'right' ? 'translateY(-50%)' : 'translate(-100%, -50%)',\n };\n }\n\n const spaceBelow = window.innerHeight - anchor.bottom - gap;\n const spaceAbove = anchor.top - gap;\n const resolved = side === 'below'\n ? (spaceBelow < FLIP_THRESHOLD && spaceAbove > spaceBelow ? 'above' : 'below')\n : (spaceAbove < FLIP_THRESHOLD && spaceBelow > spaceAbove ? 'below' : 'above');\n\n const horizontal = align === 'center'\n ? { left: anchor.left + (anchor.width / 2), transform: 'translateX(-50%)' }\n : align === 'right'\n ? { left: anchor.right, transform: 'translateX(-100%)' }\n : { left: anchor.left, transform: undefined };\n\n return resolved === 'below'\n ? { top: anchor.bottom + gap, ...horizontal }\n : { bottom: window.innerHeight - anchor.top + gap, ...horizontal };\n}\n\n/**\n * Renders its children into a fixed-position portal on <body>, anchored to an element on the board.\n * Board overlays (menus, pickers, tooltips) must float above everything: the slice columns use\n * content-visibility paint containment for virtualization, which clips any absolutely-positioned\n * descendant to the column box — portaling is what lets an overlay escape (the same approach the\n * Cratis Dropdown takes with appendTo=document.body).\n */\nexport const AnchoredOverlay: React.FC<AnchoredOverlayProps> = ({ anchorRef, open, side = 'below', align = 'left', gap = 8, children }) => {\n const [placement, setPlacement] = useState<Placement | undefined>();\n\n useLayoutEffect(() => {\n if (!open) {\n setPlacement(undefined);\n return;\n }\n const anchor = anchorRef.current?.getBoundingClientRect();\n if (!anchor) return;\n setPlacement(computePlacement(anchor, side, align, gap));\n }, [open, side, align, gap, anchorRef]);\n\n if (!open || !placement) return null;\n\n return createPortal(\n <div\n style={{\n position: 'fixed',\n zIndex: 1300,\n top: placement.top,\n bottom: placement.bottom,\n left: placement.left,\n transform: placement.transform,\n }}\n >\n {children}\n </div>,\n document.body);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './GridTooltip.css';\nimport React, { useRef, useState } from 'react';\nimport { AnchoredOverlay, AnchoredOverlaySide } from './AnchoredOverlay';\n\nexport type GridTooltipPosition = 'top' | 'bottom' | 'left' | 'right';\n\nexport interface GridTooltipProps {\n\n content: React.ReactNode;\n\n position?: GridTooltipPosition;\n\n children: React.ReactNode;\n}\n\nconst sideForPosition: Record<GridTooltipPosition, AnchoredOverlaySide> = {\n top: 'above',\n bottom: 'below',\n left: 'left',\n right: 'right',\n};\n\n/**\n * A small hover tooltip for canvas cards and controls. The bubble portals to <body> through\n * AnchoredOverlay so it floats above the whole canvas — an inline absolutely-positioned bubble would be\n * clipped by paint containment (content-visibility) near a scroll/zoom boundary.\n *\n * Pressing the anchor dismisses the bubble and keeps it dismissed until the pointer leaves. Cards that\n * open an editor on click render it *over* the card without the pointer moving — so the browser never\n * re-hit-tests and the anchor would otherwise stay \"hovered\", leaving the property list floating on top\n * of the editor the user is now typing in.\n *\n * Hover is tracked for mouse pointers only: a touch tap synthesizes an enter with no matching leave,\n * which would strand the bubble on screen on a tablet.\n */\nexport const GridTooltip: React.FC<GridTooltipProps> = ({ content, position = 'top', children }) => {\n const anchorRef = useRef<HTMLSpanElement>(null);\n const [isHovered, setIsHovered] = useState(false);\n const [isDismissed, setIsDismissed] = useState(false);\n\n const handlePointerEnter = (event: React.PointerEvent<HTMLSpanElement>) => {\n if (event.pointerType !== 'mouse') return;\n setIsHovered(true);\n };\n\n const handlePointerLeave = () => {\n setIsHovered(false);\n setIsDismissed(false);\n };\n\n return (\n <span\n ref={anchorRef}\n className='grid-tooltip-root'\n onPointerEnter={handlePointerEnter}\n onPointerLeave={handlePointerLeave}\n onPointerDown={() => setIsDismissed(true)}\n >\n {children}\n <AnchoredOverlay anchorRef={anchorRef} open={isHovered && !isDismissed} side={sideForPosition[position]} gap={6} align='center'>\n <span className='grid-tooltip-bubble' role='tooltip'>\n {content}\n </span>\n </AnchoredOverlay>\n </span>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceStatus } from '../Model';\nimport { type DetailLevel, isSliceReadOnlyForDetailLevel } from '../Presentation';\n\n// A slice's content is read-only when the board is, when the overview detail level is showing, or when its\n// workflow status says the work is under review or finished. Its status pill stays live regardless, so a\n// slice can always be moved out of a read-only status.\nexport const resolveSliceReadOnly = (boardReadOnly: boolean, detailLevel: DetailLevel, status: SliceStatus): boolean =>\n boardReadOnly || isSliceReadOnlyForDetailLevel(detailLevel, status === SliceStatus.readyForReview || status === SliceStatus.done);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext } from 'react';\nimport type { BoardInteraction } from './BoardInteraction';\n\nexport const emptyBoardInteraction: BoardInteraction = { editing: {}, actions: {}, selection: {}, navigation: {} };\n\nexport const BoardInteractionContext = createContext<BoardInteraction>(emptyBoardInteraction);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { useContext, useMemo } from 'react';\nimport type { BoardInteraction } from './BoardInteraction';\nimport { BoardInteractionContext } from './BoardInteractionContext';\n\nexport type BoardInteractionProviderProps = Partial<BoardInteraction> & {\n children?: React.ReactNode;\n};\n\n// Offers editing callbacks, actions, selection and navigation to the board beneath it. Nested providers\n// add to what an outer one offers: whatever an inner one supplies wins, entry by entry.\nexport const BoardInteractionProvider = ({ editing, actions, selection, navigation, children }: BoardInteractionProviderProps) => {\n const outer = useContext(BoardInteractionContext);\n const value = useMemo<BoardInteraction>(() => ({\n editing: { ...outer.editing, ...editing },\n actions: { ...outer.actions, ...actions },\n selection: { ...outer.selection, ...selection },\n navigation: { ...outer.navigation, ...navigation },\n }), [outer, editing, actions, selection, navigation]);\n\n return <BoardInteractionContext.Provider value={value}>{children}</BoardInteractionContext.Provider>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext } from 'react';\n\nexport const BoardReadOnlyContext = createContext(false);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport type { BoardInteraction } from './BoardInteraction';\nimport { BoardInteractionProvider } from './BoardInteractionProvider';\nimport { BoardReadOnlyContext } from './BoardReadOnlyContext';\n\nexport interface BoardProviderProps extends Partial<BoardInteraction> {\n // When set, no editing callback or action is honored and no affordance is drawn.\n readOnly?: boolean;\n children?: React.ReactNode;\n}\n\nexport const BoardProvider = ({ readOnly = false, editing, actions, selection, navigation, children }: BoardProviderProps) => (\n <BoardReadOnlyContext.Provider value={readOnly}>\n <BoardInteractionProvider editing={editing} actions={actions} selection={selection} navigation={navigation}>\n {children}\n </BoardInteractionProvider>\n </BoardReadOnlyContext.Provider>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useContext, useMemo } from 'react';\nimport { useEventModelMessages } from '../Messages';\nimport { useEventModelPresentation } from '../Presentation';\nimport type { BoardContextValue } from './BoardContextValue';\nimport { BoardInteractionContext } from './BoardInteractionContext';\nimport { BoardReadOnlyContext } from './BoardReadOnlyContext';\n\nexport const useBoard = (): BoardContextValue => {\n const readOnly = useContext(BoardReadOnlyContext);\n const presentation = useEventModelPresentation();\n const messages = useEventModelMessages();\n const { editing, actions, selection, navigation } = useContext(BoardInteractionContext);\n return useMemo(() => ({\n readOnly,\n presentation,\n messages,\n editing: readOnly ? {} : editing,\n actions: readOnly ? {} : actions,\n selection,\n navigation,\n }), [readOnly, presentation, messages, editing, actions, selection, navigation]);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Canvas, type CanvasProps } from '@cratis/components/Canvas';\nimport type { BoardCanvasChrome } from './BoardCanvasChrome';\nimport { useBoard } from './useBoard';\n\nexport interface BoardCanvasProps extends Omit<CanvasProps, 'controlsLabels' | 'controlsIcons' | 'controlsGlassSurface' | 'captureAttributes' | 'controlsFollowViewportInsets' | 'readOnly'> {\n chrome?: BoardCanvasChrome;\n}\n\n// The canvas the board is drawn on. It offers help only on an editable board. The canvas itself is never\n// made read-only: that would make the board inert under a panning overlay, while a read-only board still\n// collapses, opens prototypes and shows tooltips - the board withholds the editing on its own.\nexport const BoardCanvas = ({ chrome = {}, onHelp, helpTitle, ...props }: BoardCanvasProps) => {\n const { readOnly } = useBoard();\n return (\n <Canvas\n controlsLabels={chrome.controlsLabels}\n controlsIcons={chrome.controlsIcons}\n controlsGlassSurface={chrome.controlsSurface}\n captureAttributes={chrome.captureAttributes}\n controlsFollowViewportInsets={chrome.controlsFollowViewportInsets}\n onHelp={readOnly ? undefined : onHelp}\n helpTitle={readOnly ? undefined : helpTitle}\n {...props}\n />\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef, type PointerEvent } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { Position } from '../Model';\nimport type { CollectionMoved, CollectionMoving } from './CollectionMoved';\n\nexport interface CollectionMoveHandlers {\n onPointerDown: (event: PointerEvent<HTMLDivElement>) => void;\n onPointerMove: (event: PointerEvent<HTMLDivElement>) => void;\n onPointerUp: () => void;\n}\n\ninterface Move {\n lastX: number;\n lastY: number;\n position: Position;\n moved: boolean;\n}\n\n// Moves a module collection by dragging its handle: every pointer move is reported as a delta in canvas\n// units, and the position it ends at is reported once, when the pointer is let go after actually moving.\nexport function useCollectionMove(\n collectionId: Guid,\n position: Position,\n getZoom: () => number,\n onCollectionMoving?: CollectionMoving,\n onCollectionMoved?: CollectionMoved,\n): CollectionMoveHandlers {\n const move = useRef<Move | undefined>(undefined);\n\n return {\n onPointerDown: event => {\n const target = event.target;\n if (target instanceof Element && target.closest('button, input, .event-modeling-grid-editable-label')) return;\n event.stopPropagation();\n move.current = { lastX: event.clientX, lastY: event.clientY, position, moved: false };\n event.currentTarget.setPointerCapture(event.pointerId);\n },\n onPointerMove: event => {\n const current = move.current;\n if (!current) return;\n const zoom = getZoom();\n const deltaX = (event.clientX - current.lastX) / zoom;\n const deltaY = (event.clientY - current.lastY) / zoom;\n move.current = {\n lastX: event.clientX,\n lastY: event.clientY,\n position: { x: current.position.x + deltaX, y: current.position.y + deltaY },\n moved: true,\n };\n onCollectionMoving?.(collectionId, deltaX, deltaY);\n },\n onPointerUp: () => {\n const current = move.current;\n move.current = undefined;\n if (current?.moved) onCollectionMoved?.(collectionId, current.position);\n },\n };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './CollectionMoveHandle.css';\nimport { useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { Position } from '../Model';\nimport type { CollectionMoved, CollectionMoving } from './CollectionMoved';\nimport { useCollectionMove } from './useCollectionMove';\n\nexport interface CollectionMoveHandleProps {\n collectionId: Guid;\n // Where the collection is when the drag starts.\n position: Position;\n // Reads the current canvas zoom, so screen drag deltas convert to canvas deltas.\n getZoom: () => number;\n topOffset?: number;\n onCollectionMoving?: CollectionMoving;\n // The handle exists only when this is supplied. On a read-only board the move stays with the viewer.\n onCollectionMoved?: CollectionMoved;\n}\n\n// The grip that moves a module collection around the canvas.\nexport const CollectionMoveHandle = ({ onCollectionMoved, ...props }: CollectionMoveHandleProps) =>\n !onCollectionMoved ? undefined : <MoveHandle {...props} onCollectionMoved={onCollectionMoved} />;\n\nconst MoveHandle = ({ collectionId, position, getZoom, topOffset = 0, onCollectionMoving, onCollectionMoved }: CollectionMoveHandleProps) => {\n const [dragging, setDragging] = useState(false);\n const handlers = useCollectionMove(collectionId, position, getZoom, onCollectionMoving, onCollectionMoved);\n\n return (\n <div\n className={`collection-drag-handle ${dragging ? 'collection-drag-handle--dragging' : ''}`}\n style={{ top: `${topOffset}px` }}\n onPointerDown={event => {\n setDragging(true);\n handlers.onPointerDown(event);\n }}\n onPointerMove={handlers.onPointerMove}\n onPointerUp={() => {\n setDragging(false);\n handlers.onPointerUp();\n }}\n >\n <i className='pi pi-arrows-alt' />\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\nimport type { Position } from '../Model';\n\nexport interface CollectionItem {\n id: Guid;\n position: Position;\n}\n\nexport interface CollectionState<T extends CollectionItem> {\n snapshot: T[];\n collections: T[];\n additions: T[];\n locallyMovedAt: ReadonlyMap<string, number>;\n pendingMoveIds: ReadonlySet<string>;\n contentSignature: string;\n}\n\nconst MOVE_GUARD_MS = 4000;\n\nexport const collectionContentSignature = (collections: readonly CollectionItem[]): string =>\n JSON.stringify(collections, (key, value) => key === 'position' ? undefined : value);\n\nexport function createCollectionState<T extends CollectionItem>(snapshot: T[]): CollectionState<T> {\n return { snapshot, collections: snapshot, additions: [], locallyMovedAt: new Map(), pendingMoveIds: new Set(), contentSignature: collectionContentSignature(snapshot) };\n}\n\nconst isGuarded = <T extends CollectionItem>(state: CollectionState<T>, id: Guid, now: number, guardMs: number) => {\n const movedAt = state.locallyMovedAt.get(id.toString());\n return movedAt !== undefined && now - movedAt < guardMs;\n};\n\nexport function reconcileCollections<T extends CollectionItem>(state: CollectionState<T>, snapshot: T[], now: number, guardMs = MOVE_GUARD_MS): CollectionState<T> {\n const signature = collectionContentSignature(snapshot);\n const snapshotById = new Map(snapshot.map(collection => [collection.id.toString(), collection]));\n const localById = new Map(state.collections.map(collection => [collection.id.toString(), collection]));\n const additions = state.additions.filter(collection => !snapshotById.has(collection.id.toString()));\n if (signature !== state.contentSignature) {\n const collections = snapshot.map(remote => {\n const local = localById.get(remote.id.toString());\n return local && isGuarded(state, remote.id, now, guardMs)\n ? { ...remote, position: local.position } : remote;\n });\n return { ...state, snapshot, contentSignature: signature, additions, collections: [...collections, ...additions] };\n }\n let positionsChanged = false;\n const updated = state.collections.map(local => {\n const remote = snapshotById.get(local.id.toString());\n if (!remote || isGuarded(state, local.id, now, guardMs)) return local;\n if ((local.position?.x ?? 0) === (remote.position?.x ?? 0) &&\n (local.position?.y ?? 0) === (remote.position?.y ?? 0)) return local;\n positionsChanged = true;\n return { ...local, position: remote.position };\n });\n return { ...state, snapshot, additions, collections: positionsChanged ? updated : state.collections };\n}\n\nexport function revertCollectionMove<T extends CollectionItem>(state: CollectionState<T>, id: Guid): CollectionState<T> {\n const remote = state.snapshot.find(collection => collection.id.equals(id));\n if (!remote) return state;\n const movedAt = new Map(state.locallyMovedAt);\n movedAt.delete(id.toString());\n return { ...state, locallyMovedAt: movedAt, collections: state.collections.map(collection =>\n collection.id.equals(id) ? { ...collection, position: remote.position } : collection) };\n}\n\nexport function beginCollectionMovePersistence<T extends CollectionItem>(state: CollectionState<T>, id: Guid): CollectionState<T> {\n const key = id.toString();\n if (state.pendingMoveIds.has(key)) return state;\n return { ...state, pendingMoveIds: new Set([...state.pendingMoveIds, key]) };\n}\n\nexport function endCollectionMovePersistence<T extends CollectionItem>(state: CollectionState<T>, id: Guid): CollectionState<T> {\n const key = id.toString();\n if (!state.pendingMoveIds.has(key)) return state;\n const pendingMoveIds = new Set(state.pendingMoveIds);\n pendingMoveIds.delete(key);\n return { ...state, pendingMoveIds };\n}\n\nexport function moveCollection<T extends CollectionItem>(state: CollectionState<T>, id: Guid, deltaX: number, deltaY: number, now: number): CollectionState<T> {\n if (state.pendingMoveIds.has(id.toString())) return state;\n const movedAt = new Map(state.locallyMovedAt);\n movedAt.set(id.toString(), now);\n return { ...state, locallyMovedAt: movedAt, collections: state.collections.map(collection =>\n collection.id.equals(id) ? { ...collection, position: {\n x: (collection.position?.x ?? 0) + deltaX, y: (collection.position?.y ?? 0) + deltaY,\n } } : collection) };\n}\n\n// The cascade is visual only; never persist the displaced coordinates.\nexport const OVERLAP_STEP = 48;\nexport const SAME_SPOT_TOLERANCE = 0.5;\nexport function resolveOverlappingCollections<T extends CollectionItem>(collections: T[]): T[] {\n const occupied: Position[] = [];\n let changed = false;\n const resolved = collections.map(collection => {\n const position = { x: collection.position?.x ?? 0, y: collection.position?.y ?? 0 };\n while (occupied.some(spot => Math.abs(spot.x - position.x) < SAME_SPOT_TOLERANCE && Math.abs(spot.y - position.y) < SAME_SPOT_TOLERANCE)) {\n position.x += OVERLAP_STEP;\n position.y += OVERLAP_STEP;\n }\n occupied.push(position);\n if (position.x === (collection.position?.x ?? 0) && position.y === (collection.position?.y ?? 0)) return collection;\n changed = true;\n return { ...collection, position };\n });\n return changed ? resolved : collections;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState, type SetStateAction } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { beginCollectionMovePersistence, createCollectionState, endCollectionMovePersistence, moveCollection, reconcileCollections, revertCollectionMove, type CollectionItem, type CollectionState } from './collectionState';\n\nexport interface CollectionsAreaOptions<T extends CollectionItem> {\n initialCollections: T[];\n onAddCollection?: (x: number, y: number, collections: T[]) => Promise<T | undefined>;\n onCollectionMoved?: (id: Guid, position: { x: number; y: number }) => Promise<boolean>;\n onCollectionsChange?: (collections: T[]) => void;\n onPersistenceError?: (error: unknown) => void;\n}\n\nexport interface CollectionsArea<T extends CollectionItem> {\n collections: T[];\n pendingMoveIds: ReadonlySet<string>;\n setCollections: (updater: SetStateAction<T[]>) => void;\n addCollection: (x: number, y: number) => Promise<void>;\n moveCollection: (id: Guid, deltaX: number, deltaY: number) => void;\n collectionMoved: (id: Guid, position: { x: number; y: number }) => Promise<void>;\n canMove: boolean;\n canAdd: boolean;\n}\n\nexport function useCollectionsArea<T extends CollectionItem>({\n initialCollections, onAddCollection, onCollectionMoved, onCollectionsChange, onPersistenceError,\n}: CollectionsAreaOptions<T>): CollectionsArea<T> {\n const { readOnly } = useBoard();\n const [visibleState, setVisibleState] = useState(() => createCollectionState(initialCollections));\n const stateRef = useRef<CollectionState<T>>(visibleState);\n const { collections, pendingMoveIds } = visibleState;\n const adding = useRef(false);\n const isFirstNotification = useRef(true);\n const apply = useCallback((transition: (state: CollectionState<T>) => CollectionState<T>) => {\n const next = transition(stateRef.current);\n stateRef.current = next;\n setVisibleState(next);\n }, []);\n useEffect(() => {\n if (initialCollections !== stateRef.current.snapshot) {\n apply(previous => reconcileCollections(previous, initialCollections, Date.now(), readOnly ? Infinity : undefined));\n }\n }, [initialCollections, apply, readOnly]);\n useEffect(() => {\n if (isFirstNotification.current) {\n isFirstNotification.current = false;\n return;\n }\n onCollectionsChange?.(collections);\n }, [collections, onCollectionsChange]);\n\n // Nested edits update the local tree without replacing the observable snapshot.\n const setCollections = useCallback((updater: SetStateAction<T[]>) => {\n apply(previous => ({ ...previous, collections: typeof updater === 'function' ? updater(previous.collections) : updater }));\n }, [apply]);\n const addCollection = useCallback(async (x: number, y: number) => {\n if (readOnly || !onAddCollection || adding.current) return;\n adding.current = true;\n try {\n const added = await onAddCollection(x, y, stateRef.current.collections);\n if (added) apply(previous => previous.collections.some(collection => collection.id.equals(added.id))\n ? previous : { ...previous,\n additions: [...previous.additions, added], collections: [...previous.collections, added],\n });\n } catch (error) {\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n } finally { adding.current = false; }\n }, [readOnly, onAddCollection, onPersistenceError, apply]);\n // A read-only board moves collections for the viewer alone: nothing is persisted, and the moved\n // position outlives later snapshots.\n const move = useCallback((id: Guid, deltaX: number, deltaY: number) => {\n if ((!readOnly && !onCollectionMoved) || stateRef.current.pendingMoveIds.has(id.toString())) return;\n apply(previous => moveCollection(previous, id, deltaX, deltaY, Date.now()));\n }, [readOnly, onCollectionMoved, apply]);\n const moved = useCallback(async (id: Guid, position: { x: number; y: number }) => {\n if (readOnly || !onCollectionMoved || stateRef.current.pendingMoveIds.has(id.toString())) return;\n apply(previous => beginCollectionMovePersistence(previous, id));\n try {\n const succeeded = await onCollectionMoved(id, position);\n if (!succeeded) apply(previous => revertCollectionMove(previous, id));\n } catch (error) {\n apply(previous => revertCollectionMove(previous, id));\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n } finally { apply(previous => endCollectionMovePersistence(previous, id)); }\n }, [readOnly, onCollectionMoved, onPersistenceError, apply]);\n return { collections, pendingMoveIds, setCollections, addCollection, moveCollection: move, collectionMoved: moved,\n canMove: readOnly || !!onCollectionMoved, canAdd: !readOnly && !!onAddCollection };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { RowType } from '../Rows/RowType';\n\n// The sizes the board is laid out with, in canvas units.\nexport const boardMetrics = {\n minSliceWidth: 220,\n minPillWidth: 150,\n sliceWidth: 220,\n sliceWidthDouble: 350,\n translatorSliceWidth: 360,\n sliceGap: 8,\n collapsedFeatureWidth: 80,\n collapsedModuleWidth: 100,\n collapsedSliceWidth: 36,\n headerHeight: 44,\n roleRowHeight: 80,\n specificationSectionHeight: 80,\n // How many event cards sit side by side in a cell.\n itemsPerRow: 2,\n uiCardHeight: 84,\n cardHeight: 56,\n cellVerticalPadding: 24,\n} as const satisfies Record<string, number>;\n\n// The height of each row before its content asks for more.\nexport const rowHeights: Readonly<Record<RowType, number>> = {\n [RowType.UI]: 160,\n [RowType.Chat]: 160,\n [RowType.System]: 120,\n [RowType.Interaction]: 160,\n [RowType.Events]: 160,\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { JsonSchema, JsonSchemaProperty } from '@cratis/components/SchemaEditor';\n\nexport interface SchemaProperty {\n name: string;\n type: string;\n}\n\n// The type a property's badge shows. Mirrors the property types the board's schema editors use, so a\n// badge reads the same on the face of a card as in its editor.\nconst typeOf = (value: JsonSchemaProperty): string => {\n const { type, format, items } = value;\n switch (type) {\n case 'string':\n if (format === 'date') return 'date';\n if (format === 'time') return 'time';\n return 'string';\n case 'number':\n case 'integer':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'object':\n return 'object';\n case 'array':\n if (items?.type === 'number' || items?.type === 'integer') return 'numberArray';\n if (items?.type === 'object') return 'objectArray';\n return 'stringArray';\n default:\n return 'string';\n }\n};\n\nconst isSchema = (value: unknown): value is JsonSchema => !!value && typeof value === 'object' && !Array.isArray(value);\n\nconst parse = (schema?: string | JsonSchema): JsonSchema | undefined => {\n if (!schema) return undefined;\n if (typeof schema !== 'string') return schema;\n try {\n const parsed: unknown = JSON.parse(schema);\n return isSchema(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n};\n\n// The top-level properties of a schema, in declaration order. A string that is not a JSON document\n// has none.\nexport const topLevelSchemaProperties = (schema?: string | JsonSchema): SchemaProperty[] => {\n const properties = parse(schema)?.properties;\n return properties ? Object.entries(properties).map(([name, value]) => ({ name, type: typeOf(value) })) : [];\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { JsonSchema } from '@cratis/components/SchemaEditor';\nimport { topLevelSchemaProperties } from '../Properties/schemaProperties';\n\n// What a card is drawn from, as far as its height goes: the schema whose properties it can list.\nexport interface CardLayoutInput {\n schema?: string | JsonSchema;\n}\n\n// The card face and its property list, as the theme and SchemaTooltipProperties draw them.\nconst face = { minHeight: 40, paddingY: 10, titleHeight: 16 } as const;\nconst propertyList = { marginTop: 6, rowHeight: 20, gap: 3, emptyHeight: 13 } as const;\n\n// How tall a card is drawn when it lists its properties - the face's padding and title, then one row per\n// top-level property, or the line saying there are none.\nexport function detailedCardHeight(card: CardLayoutInput): number {\n const count = topLevelSchemaProperties(card.schema).length;\n const list = count === 0 ? propertyList.emptyHeight : count * propertyList.rowHeight + (count - 1) * propertyList.gap;\n return Math.max(face.minHeight, face.paddingY * 2 + face.titleHeight + propertyList.marginTop + list);\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\nimport { RowType } from '../Rows/RowType';\nimport { boardMetrics, rowHeights } from './boardMetrics';\nimport { type CardLayoutInput, detailedCardHeight } from './cardHeight';\n\n// What the layout needs to know about a slice. The cards' schemas only matter when the slice shows the\n// properties of its cards, which makes them taller.\nexport interface SliceLayoutInput {\n sliceType: SliceType;\n events: readonly unknown[];\n command?: CardLayoutInput;\n readModel?: CardLayoutInput;\n}\n\n// The room above and below the cards of the interaction row, which the connectors to the rows around it\n// run through.\nconst interactionConnectorRoom = 24;\nconst cardRowGap = 8;\n\n// How wide a slice's column is: the slice types that draw a command or a translation beside their events\n// always take the wide column, the others grow with their events.\nexport function sliceColumnWidth(slice: SliceLayoutInput | { sliceType: SliceType; eventCount: number }): number {\n if (slice.sliceType === SliceType.translator || slice.sliceType === SliceType.automation || slice.sliceType === SliceType.stateChange) {\n return boardMetrics.translatorSliceWidth;\n }\n const eventCount = 'eventCount' in slice ? slice.eventCount : slice.events.length;\n const baseWidth = eventCount >= boardMetrics.itemsPerRow ? boardMetrics.sliceWidthDouble : boardMetrics.sliceWidth;\n return slice.sliceType === SliceType.stateView ? Math.round(baseWidth * 1.5) : baseWidth;\n}\n\n// How tall a row has to be for one slice. The events row grows as its cards wrap; when the slice shows\n// the properties of its cards, the events and interaction rows grow to hold the taller cards.\nexport function rowHeightForSlice(rowType: RowType, slice: SliceLayoutInput, showDetails = false): number {\n switch (rowType) {\n case RowType.Events: return eventsRowHeight(slice, showDetails);\n case RowType.Interaction: return showDetails ? interactionRowHeight(slice) : rowHeights[rowType];\n default: return rowHeights[rowType];\n }\n}\n\nfunction eventsRowHeight(slice: SliceLayoutInput, showDetails: boolean): number {\n const { events } = slice;\n if (events.length === 0) return rowHeights[RowType.Events];\n const cardRows: number[] = [];\n for (let index = 0; index < events.length; index += boardMetrics.itemsPerRow) {\n const row = events.slice(index, index + boardMetrics.itemsPerRow);\n cardRows.push(showDetails\n ? Math.max(boardMetrics.cardHeight, ...row.map(event => detailedCardHeight(cardOf(event))))\n : boardMetrics.cardHeight);\n }\n const height = cardRows.reduce((total, rowHeight) => total + rowHeight, 0) + (cardRows.length - 1) * cardRowGap;\n return Math.max(rowHeights[RowType.Events], height + boardMetrics.cellVerticalPadding);\n}\n\nfunction interactionRowHeight(slice: SliceLayoutInput): number {\n const cards = [slice.command, slice.readModel].filter(card => card !== undefined);\n if (cards.length === 0) return rowHeights[RowType.Interaction];\n return Math.max(rowHeights[RowType.Interaction], Math.max(...cards.map(detailedCardHeight)) + interactionConnectorRoom * 2);\n}\n\n// An event as a card; anything that does not carry a schema is a card without properties.\nconst cardOf = (event: unknown): CardLayoutInput =>\n event !== null && typeof event === 'object' && 'schema' in event ? event as CardLayoutInput : {};\n\n// The height of each row across a whole collection: the tallest any slice in it needs, so every slice's\n// rows line up. A slice that shows the properties of its cards says so.\nexport function computeGlobalRowHeights(slices: readonly { slice: SliceLayoutInput; showDetails?: boolean }[], contentRows: readonly RowType[]): Record<RowType, number> {\n const result: Record<RowType, number> = { ...rowHeights };\n for (const rowType of contentRows) {\n result[rowType] = slices.length === 0\n ? rowHeights[rowType]\n : Math.max(...slices.map(({ slice, showDetails }) => rowHeightForSlice(rowType, slice, showDetails)));\n }\n return result;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { ActorType } from '../Model';\nimport { RowType } from '../Rows/RowType';\n\n// The kind of actor a row of each actor type holds, and the row an actor of each kind sits in.\nexport const actorTypeOfRow = (rowType: RowType): ActorType | undefined => {\n switch (rowType) {\n case RowType.UI: return ActorType.UIRole;\n case RowType.System: return ActorType.systemRole;\n case RowType.Chat: return ActorType.chatRole;\n default: return undefined;\n }\n};\n\nexport const rowOfActorType = (actorType: ActorType): RowType => {\n switch (actorType) {\n case ActorType.UIRole: return RowType.UI;\n case ActorType.systemRole: return RowType.System;\n case ActorType.chatRole: return RowType.Chat;\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { ActorType, SliceType } from '../Model';\nimport { actorTypeOfRow } from '../RowLabels/actorRows';\nimport { RowType } from '../Rows/RowType';\n\n// Each slice type owns the kinds of actor, and therefore the actor rows, it can take part in. There is no\n// implicit system row and no hard-coded UI row.\nconst supportedActors: Readonly<Record<SliceType, ReadonlySet<ActorType>>> = {\n [SliceType.stateChange]: new Set([ActorType.UIRole, ActorType.systemRole, ActorType.chatRole]),\n [SliceType.stateView]: new Set([ActorType.UIRole, ActorType.systemRole, ActorType.chatRole]),\n [SliceType.automation]: new Set([ActorType.systemRole, ActorType.chatRole]),\n [SliceType.translator]: new Set([ActorType.systemRole, ActorType.chatRole]),\n};\n\nexport const sliceTypeSupportsActor = (sliceType: SliceType, actorType: ActorType): boolean =>\n supportedActors[sliceType].has(actorType);\n\n// Whether a slice of this type draws anything in the row; rows that hold no actors are drawn by every type.\nexport const sliceTypeSupportsRow = (sliceType: SliceType, rowType: RowType): boolean => {\n const actorType = actorTypeOfRow(rowType);\n return actorType === undefined || sliceTypeSupportsActor(sliceType, actorType);\n};\n\n// The actors of a collection that sit in a row; none for a row that holds no actors.\nexport const actorsForRow = <TActor extends { actorType: ActorType }>(actors: readonly TActor[], rowType: RowType): TActor[] => {\n const actorType = actorTypeOfRow(rowType);\n return actorType === undefined ? [] : actors.filter(actor => actor.actorType === actorType);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { startTransition } from 'react';\nimport { canvasGesture } from '@cratis/components/Canvas';\n\ntype ApplyVerdict = (inView: boolean) => void;\n\n// How expensive applying a verdict is. A 'light' subtree (one slice column's body) commits in a few\n// milliseconds and may mount mid-gesture; a 'heavy' one (a whole collection grid) costs tens of\n// milliseconds — enough to break the gesture's frame budget on its own — so it waits for the settle.\nexport type VerdictWeight = 'light' | 'heavy';\n\ninterface PendingVerdict {\n verdict: boolean;\n // Distance from the element to the viewport center, so nearer content mounts first.\n distance: number;\n weight: VerdictWeight;\n}\n\n// A flush frame under this is cheap — the apply budget may grow.\nconst GROW_BELOW_MS = 12;\n\n// A flush frame over this ran long — the apply budget halves.\nconst SHRINK_ABOVE_MS = 24;\n\n// Two flushes further apart than this are not consecutive frames — no cost signal.\nconst CONSECUTIVE_FRAME_MS = 100;\n\nconst INITIAL_APPLY_BUDGET = 1;\nconst MIN_APPLY_BUDGET = 1;\nconst MAX_APPLY_BUDGET = 24;\n\n// While a gesture is in motion only a few mounts run per frame, and only on cheap frames.\nconst GESTURE_APPLY_BUDGET = 3;\n\nconst pending = new Map<ApplyVerdict, PendingVerdict>();\nlet frameScheduled = false;\n\n// The apply budget adapts to what a verdict actually costs on this board: a placeholder-sized mount\n// (a virtualized collection at far zoom) is ~1ms so dozens fit in a frame, while mounting — or\n// tearing down — a full collection grid can cost tens of ms so only one does. The cost of a flush\n// shows up as the gap to the NEXT scheduled flush frame (React commits the batch between the two\n// rAFs), so the budget grows while flush frames stay cheap and halves when one runs long. A fresh\n// burst after a quiet gap may be a different cost regime entirely (cheap placeholders vs heavy\n// grids), so the budget resets rather than starting a new burst at its grown size.\nlet applyBudget = INITIAL_APPLY_BUDGET;\nlet lastFlushAt = 0;\nlet lastFlushApplied = false;\n\nfunction nearestFirst(verdictFilter: (entry: PendingVerdict) => boolean): [ApplyVerdict, PendingVerdict][] {\n return [...pending].filter(([, entry]) => verdictFilter(entry))\n .sort((left, right) => left[1].distance - right[1].distance);\n}\n\nfunction processQueue(): void {\n frameScheduled = false;\n const now = performance.now();\n const frameMs = now - lastFlushAt;\n const consecutive = frameMs < CONSECUTIVE_FRAME_MS;\n if (lastFlushApplied && consecutive) {\n if (frameMs > SHRINK_ABOVE_MS) applyBudget = Math.max(MIN_APPLY_BUDGET, Math.ceil(applyBudget / 2));\n else if (frameMs < GROW_BELOW_MS) applyBudget = Math.min(MAX_APPLY_BUDGET, applyBudget + 1);\n } else if (!consecutive) {\n applyBudget = INITIAL_APPLY_BUDGET;\n }\n lastFlushApplied = false;\n\n // Mid-gesture the queue no longer holds still: MOUNTS — light and heavy alike — run a few per\n // cheap frame, nearest to the viewport first, so content panned into view fills in progressively\n // instead of popping in as one burst at the settle. Heavy mounts are safe here because the\n // mid-gesture path renders them as interruptible transitions; holding them until the settle is\n // what made a continuous trackpad scroll (which keeps the gesture alive indefinitely) show blank\n // frames until the user stopped. Unmounts still wait for the settle — tearing down a subtree is\n // not time-sliceable — and when the last frame ran long this frame mounts nothing, giving the\n // gesture room.\n const gestureActive = canvasGesture.isActive;\n const frameHasRoom = !consecutive || frameMs <= SHRINK_ABOVE_MS;\n if (!gestureActive || frameHasRoom) {\n lastFlushAt = now;\n const budget = gestureActive ? Math.min(applyBudget, GESTURE_APPLY_BUDGET) : applyBudget;\n let applied = 0;\n for (const [apply, entry] of nearestFirst(entry => !gestureActive || entry.verdict)) {\n pending.delete(apply);\n if (gestureActive) {\n // Mid-gesture mounts render as a React transition: the render is time-sliced and\n // interruptible, so a body that takes tens of milliseconds to render fills in\n // across idle slices instead of blocking a gesture frame.\n startTransition(() => apply(entry.verdict));\n } else {\n apply(entry.verdict);\n }\n if (++applied >= budget) break;\n }\n lastFlushApplied = applied > 0;\n }\n\n if (pending.size > 0) schedule();\n}\n\nfunction schedule(): void {\n if (frameScheduled) return;\n frameScheduled = true;\n requestAnimationFrame(processQueue);\n}\n\n// Listens for the end of a canvas gesture from the first verdict on, rather than when the module is\n// loaded, so importing the board does no work until a board is actually drawn.\nlet listeningForGestures = false;\nfunction listenForGestures(): void {\n if (listeningForGestures) return;\n listeningForGestures = true;\n canvasGesture.subscribe(active => {\n if (!active && pending.size > 0) schedule();\n });\n}\n\n// Rate-limits viewport-virtualization verdicts so mounting/unmounting board subtrees never lands as\n// one giant React commit. IntersectionObserver delivers every element's verdict in a single task —\n// after a long pan or a zoom-out that can be hundreds of module bodies at once, and committing them\n// together produced multi-second frames. Queuing the verdicts (latest wins per subscriber) and\n// applying a bounded number per animation frame keeps each commit small, so the board fills in over a\n// few frames instead of freezing. While a canvas gesture is in motion, a small budget of mounts\n// (nearest first, rendered as interruptible transitions) runs per cheap frame; unmounts hold until\n// the gesture settles.\nexport const viewportFlushScheduler = {\n // Queues the latest verdict for a subscriber; an already-queued verdict is replaced.\n request(apply: ApplyVerdict, verdict: boolean, distance = Number.POSITIVE_INFINITY, weight: VerdictWeight = 'light'): void {\n listenForGestures();\n pending.set(apply, { verdict, distance, weight });\n schedule();\n },\n\n // Drops any queued verdict for a subscriber (on unmount).\n cancel(apply: ApplyVerdict): void {\n pending.delete(apply);\n },\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { RefObject, useEffect, useState } from 'react';\nimport { VerdictWeight, viewportFlushScheduler } from './viewportFlushScheduler';\n\n// Tracks whether an element is within (or near) the viewport, so a heavy subtree can be mounted only\n// when it is about to be seen. The board pans/zooms via CSS transforms, and IntersectionObserver reports\n// against the post-transform visual box, so this stays correct through pan and zoom.\n//\n// Starts `false` so the very first paint mounts nothing off-screen — the observer then mounts the\n// on-screen elements on its first callback. `rootMargin` pre-mounts a margin around the viewport so\n// content is ready before it scrolls in (avoids a blank flash while panning).\n//\n// Verdicts are applied through the viewportFlushScheduler: rate-limited to a few subtree\n// mounts per frame — and during a pan/zoom gesture to a small nearest-first mount budget with\n// unmounts held back — so a flood of verdicts after a long pan, or a zoom-out that pulls the whole\n// board into view, fills the board in progressively instead of freezing it in one giant commit.\n// Each verdict carries the element's distance to the viewport center so the scheduler can mount\n// what the user is actually looking at first.\nexport function useInViewport(ref: RefObject<Element | null>, rootMargin = '250% 250%', weight: VerdictWeight = 'light'): boolean {\n const [inView, setInView] = useState(false);\n\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n if (typeof IntersectionObserver === 'undefined') {\n // No observer (e.g. jsdom): render everything rather than hide it.\n setInView(true);\n return;\n }\n const observer = new IntersectionObserver(\n entries => {\n const entry = entries[entries.length - 1];\n if (!entry) return;\n const rect = entry.boundingClientRect;\n const distance = Math.hypot(\n rect.left + (rect.width / 2) - (window.innerWidth / 2),\n rect.top + (rect.height / 2) - (window.innerHeight / 2));\n viewportFlushScheduler.request(setInView, entry.isIntersecting, distance, weight);\n },\n { rootMargin });\n observer.observe(element);\n\n return () => {\n observer.disconnect();\n viewportFlushScheduler.cancel(setInView);\n };\n }, [ref, rootMargin, weight]);\n\n return inView;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { memo, useRef, type ReactNode } from 'react';\nimport { CanvasItem } from '@cratis/components/Canvas';\nimport type { Guid } from '@cratis/fundamentals';\nimport { boardMetrics } from '../Layout';\nimport { useInViewport } from '../Viewport';\nimport type { CollectionItem } from './collectionState';\nimport './CollectionViewport.css';\n\ninterface CollectionModule { id: Guid; name: string }\ninterface ViewportCollection extends CollectionItem { modules: CollectionModule[] }\n\nexport interface CollectionViewportProps<T extends ViewportCollection> {\n collection: T;\n estimatedSize: { width: number; height: number; moduleWidths: number[] };\n measuredSize?: { width: number; height: number };\n onSize?: (id: Guid, width: number, height: number) => void;\n children: ReactNode;\n}\n\nfunction Viewport<T extends ViewportCollection>({ collection, estimatedSize, measuredSize, onSize, children }: CollectionViewportProps<T>) {\n const hostRef = useRef<HTMLDivElement>(null);\n const inView = useInViewport(hostRef, undefined, 'heavy');\n const size = measuredSize ?? estimatedSize;\n return <CanvasItem x={collection.position?.x ?? 0} y={collection.position?.y ?? 0}\n onSize={onSize ? (width, height) => onSize(collection.id, width, height) : undefined}>\n <div ref={hostRef}>\n {inView ? children : <div className='event-model-collection-placeholder'\n style={{ width: size.width, height: size.height }} aria-hidden>\n {collection.modules.map((module, index) => <div className='event-model-collection-placeholder-module'\n key={module.id.toString()} style={{ width: estimatedSize.moduleWidths[index] }}>\n <div className='event-modeling-grid-pill event-modeling-grid-pill--module event-model-collection-placeholder-pill'>{module.name}</div>\n <div className='event-model-collection-placeholder-body'\n style={{ height: Math.max(0, size.height - boardMetrics.headerHeight - 4) }} />\n </div>)}\n </div>}\n </div>\n </CanvasItem>;\n}\n\nexport const CollectionViewport = memo(Viewport);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/** The axis a flow connection curve's end tangents follow. */\nexport enum CurveAxis {\n Horizontal = 'horizontal',\n Vertical = 'vertical',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { CurveAxis } from './CurveAxis';\n\n/** A point in the curve's coordinate space. */\nexport interface CurvePoint {\n x: number;\n y: number;\n}\n\n/**\n * Builds the smooth cubic-bezier path used for flow connections: both end tangents are aligned with\n * the given axis, with the control points placed halfway along that axis. This is the single curve\n * style shared by the connections between the cards inside a slice (vertical flow) and the links\n * between module collections on the canvas (axis follows the dominant direction).\n */\nexport function smoothCurvePath(start: CurvePoint, end: CurvePoint, axis: CurveAxis): string {\n if (axis === CurveAxis.Vertical) {\n const deltaY = end.y - start.y;\n const control1Y = start.y + deltaY * 0.5;\n const control2Y = end.y - deltaY * 0.5;\n return `M ${start.x} ${start.y} C ${start.x} ${control1Y}, ${end.x} ${control2Y}, ${end.x} ${end.y}`;\n }\n\n const deltaX = end.x - start.x;\n const control1X = start.x + deltaX * 0.5;\n const control2X = end.x - deltaX * 0.5;\n return `M ${start.x} ${start.y} C ${control1X} ${start.y}, ${control2X} ${end.y}, ${end.x} ${end.y}`;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { CurveAxis } from './CurveAxis';\n\n/** A rectangle expressed in canvas (world) coordinates. */\nexport interface Rect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** A point expressed in canvas (world) coordinates. */\nexport interface Point {\n x: number;\n y: number;\n}\n\n/** The endpoints of a directed link plus the tangent axis its spline should follow. */\nexport interface SplineEndpoints {\n /** The point on the source rectangle's border the curve leaves from. */\n start: Point;\n /** The point on the target rectangle's border the curve arrives at. */\n end: Point;\n /** The axis the curve's end tangents follow — the dominant direction between the two rectangles. */\n axis: CurveAxis;\n}\n\n/** The center point of a rectangle. */\nexport function centerOf(rect: Rect): Point {\n return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };\n}\n\n/** A zero-size rectangle at a point, so point targets (the drag pointer) reuse the rect-based spline math. */\nexport function rectAt(point: Point): Rect {\n return { x: point.x, y: point.y, width: 0, height: 0 };\n}\n\n/**\n * The part of a collection's measured rectangle that holds the slice content — the specifications\n * rendered below the slice columns are excluded, so anchors and curve endpoints center on the\n * content rather than the full (specification-inclusive) footprint.\n */\nexport function contentRectOf(rect: Rect, contentHeight: number): Rect {\n return { ...rect, height: Math.min(rect.height, contentHeight) };\n}\n\n/** The point a link drag starts from: the right edge of a rectangle, vertically centered. */\nexport function linkAnchor(rect: Rect): Point {\n return { x: rect.x + rect.width, y: rect.y + rect.height / 2 };\n}\n\n/**\n * Computes the spline endpoints between two rectangles: the curve leaves and arrives on the facing\n * edges along the dominant axis between the two centers, at each edge's midpoint, with the tangents\n * following that axis — the same curve style as the connections between the cards inside a slice.\n */\nexport function computeSplineEndpoints(source: Rect, target: Rect): SplineEndpoints {\n const sourceCenter = centerOf(source);\n const targetCenter = centerOf(target);\n const deltaX = targetCenter.x - sourceCenter.x;\n const deltaY = targetCenter.y - sourceCenter.y;\n\n if (Math.abs(deltaX) >= Math.abs(deltaY)) {\n const goingRight = deltaX >= 0;\n return {\n axis: CurveAxis.Horizontal,\n start: { x: goingRight ? source.x + source.width : source.x, y: sourceCenter.y },\n end: { x: goingRight ? target.x : target.x + target.width, y: targetCenter.y },\n };\n }\n\n const goingDown = deltaY >= 0;\n return {\n axis: CurveAxis.Vertical,\n start: { x: sourceCenter.x, y: goingDown ? source.y + source.height : source.y },\n end: { x: targetCenter.x, y: goingDown ? target.y : target.y + target.height },\n };\n}\n\n/** The midpoint between two points. */\nexport function midpoint(a: Point, b: Point): Point {\n return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n}\n\n/** Whether a point lies within a rectangle (borders inclusive). */\nexport function pointInRect(point: Point, rect: Rect): boolean {\n return point.x >= rect.x && point.x <= rect.x + rect.width &&\n point.y >= rect.y && point.y <= rect.y + rect.height;\n}\n\n/** Something a link can connect to — anything carrying a stringifiable id. */\nexport interface Identified {\n id: { toString(): string };\n}\n\n/**\n * Resolves the collection a link drop connects to. Prefers the target directly under the release\n * point, but falls back to the target the affordance last committed to (looked up by id) — so a quick\n * release that lands a hair outside the target, or whose final pointermove the browser coalesced away,\n * still links to what the user was shown \"will connect\" to. Never returns the drag's own source.\n */\nexport function resolveDropTarget<T extends Identified>(\n releaseTarget: T | null,\n lastTargetId: string | null,\n lookup: (id: string) => T | undefined,\n sourceId: string): T | null {\n const target = releaseTarget ?? (lastTargetId ? lookup(lastTargetId) ?? null : null);\n if (!target || target.id.toString() === sourceId) return null;\n return target;\n}\n\n/**\n * The smallest rectangle containing every supplied rectangle and point, expanded by padding on all\n * sides. Returns a zero rectangle when nothing is supplied.\n */\nexport function boundingBox(rects: Rect[], points: Point[], padding: number): Rect {\n const xs: number[] = [];\n const ys: number[] = [];\n for (const rect of rects) {\n xs.push(rect.x, rect.x + rect.width);\n ys.push(rect.y, rect.y + rect.height);\n }\n for (const point of points) {\n xs.push(point.x);\n ys.push(point.y);\n }\n if (xs.length === 0) return { x: 0, y: 0, width: 0, height: 0 };\n\n const minX = Math.min(...xs) - padding;\n const minY = Math.min(...ys) - padding;\n const maxX = Math.max(...xs) + padding;\n const maxY = Math.max(...ys) + padding;\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Measures the rendered pixel width of `text` at the given font. Implemented with real canvas font\n * metrics by {@link defaultMeasureLabelWidth}; injected as a parameter everywhere it is consumed so\n * {@link computePillLabelMinWidth} — and the pure layout functions built on it — stay spec-able without\n * jsdom's lack of real canvas font metrics in Vitest. Mirrors the `MeasureTextWidth` pattern in\n * `@cratis/event-models` (Cards/autoFitTitle.ts).\n */\nexport type MeasureLabelWidth = (text: string, fontSizePx: number, fontWeight: string | number, fontFamily: string) => number;\n\n/** Matches `.event-modeling-grid-pill`'s own font rules (PillHeader.css) — the label measures against it. */\nexport const PILL_LABEL_FONT_SIZE_PX = 12;\n\n/** Matches `.event-modeling-grid-pill`'s `font-weight` (PillHeader.css). */\nexport const PILL_LABEL_FONT_WEIGHT = 600;\n\n/** The pill sets no `font-family` of its own, so it inherits the app root's (see `:root` in index.css). */\nexport const PILL_LABEL_FONT_FAMILY = 'Inter, Avenir, Helvetica, Arial, sans-serif';\n\n/**\n * The fixed-size chrome a pill needs around its label, regardless of label content: the icon clusters\n * either side of the label plus the pill's own horizontal padding.\n *\n * `.event-modeling-grid-pill-left` / `-right` (PillHeader.css) are flex rows of ~20x20 icon buttons with\n * a 4px gap — never content-dependent, so a fixed overhead is a stable, defensible approximation rather\n * than enumerating every conditional button. It is sized for the busiest header as it was drawn when\n * explanation, Mermaid export and enabling were still buttons of their own: 2 icons on the left (the\n * collapse button, the chat button) and 7 on the right: 9 × 20px + 8 × 4px gaps = 212px, plus the pill's\n * own `padding: 0 8px` (16px) = 228px, rounded up a little for sub-pixel layout rounding. Those actions now\n * sit in the header's options menu; the overhead is left as it was so moving them changed no board's\n * layout, and a header now has room to spare rather than none.\n */\nexport const PILL_ICON_CLUSTER_OVERHEAD_PX = 230;\n\nlet measureContext: CanvasRenderingContext2D | null = null;\n\n/** A shared, lazily-created off-screen canvas 2D context for text metrics — the same technique as\n * `Cards/useAutoFitTitle.ts`'s `getMeasureContext()`, kept local here rather than promoted to\n * a shared location: this module is a plain layout-computation function (not a React hook, called during\n * layout, not component render) with a different consumer shape, and there is no second real consumer of\n * a *shared* measurement utility yet to justify the extraction. */\nfunction getMeasureContext(): CanvasRenderingContext2D | null {\n if (measureContext) return measureContext;\n // Some specs run in a plain Node environment (no jsdom) and stub a partial `document` global of\n // their own for unrelated purposes (see Components/Viewport/for_viewport/) — guard on the actual\n // method, not just presence of `document`, so a stub lacking `createElement` degrades gracefully\n // instead of throwing.\n if (typeof document === 'undefined' || typeof document.createElement !== 'function') return null;\n measureContext = document.createElement('canvas').getContext('2d');\n return measureContext;\n}\n\n/** Real canvas-based measurement. jsdom (used by the Vitest specs) has no canvas font metrics and\n * returns 0 width for every measurement — specs that need a real label-width contribution inject a\n * stub {@link MeasureLabelWidth} instead. */\nexport const defaultMeasureLabelWidth: MeasureLabelWidth = (text, fontSizePx, fontWeight, fontFamily) => {\n const context = getMeasureContext();\n if (!context) return 0;\n context.font = `${fontWeight} ${fontSizePx}px ${fontFamily}`;\n return context.measureText(text).width;\n};\n\n/**\n * The minimum pixel width a pill (module or feature header) needs to fit `label` without its\n * `white-space: nowrap; min-width: min-content` content bleeding outside its computed column width —\n * the measured label plus the fixed icon-cluster/padding overhead.\n */\nexport function computePillLabelMinWidth(label: string, measure: MeasureLabelWidth = defaultMeasureLabelWidth): number {\n return Math.ceil(measure(label, PILL_LABEL_FONT_SIZE_PX, PILL_LABEL_FONT_WEIGHT, PILL_LABEL_FONT_FAMILY)) + PILL_ICON_CLUSTER_OVERHEAD_PX;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The width of the column of row labels to the left of every module collection.\nexport const rowLabelWidth = 56;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createPortal } from 'react-dom';\nimport type { ActorRowDragState } from './useActorRowDrag';\n\nexport interface ActorRowDragGhostProps {\n drag?: ActorRowDragState;\n}\n\n// The actor being dragged, drawn over everything beside the pointer as a label with its name.\nexport const ActorRowDragGhost = ({ drag }: ActorRowDragGhostProps) => drag ? createPortal(\n <div\n style={{\n position: 'fixed',\n left: drag.currentX + 16,\n top: drag.currentY - 16,\n height: 32,\n padding: '0 12px',\n background: 'rgba(80,60,160,0.65)',\n border: '1.5px dashed rgba(180,165,255,0.75)',\n borderRadius: 8,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n pointerEvents: 'none',\n zIndex: 9998,\n fontSize: 11,\n fontWeight: 500,\n color: 'rgba(255,255,255,0.9)',\n userSelect: 'none',\n whiteSpace: 'nowrap',\n }}\n >\n {drag.ghostLabel}\n </div>,\n document.body,\n) : undefined;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Where a dragged actor would land, drawn between two actor row labels.\nexport const ActorRowDropIndicator = () => (\n <div\n style={{\n height: 3,\n margin: '2px 4px',\n background: 'rgba(180,165,255,0.85)',\n borderRadius: 2,\n flexShrink: 0,\n }}\n />\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModelMessages } from '../Messages';\nimport { ActorType } from '../Model';\n\nexport interface ActorKind {\n actorType: ActorType;\n label: string;\n // The swatch drawn beside the kind in the menu that adds an actor.\n color: string;\n}\n\n// The kinds of actor a row can be given, in the order the add menu lists them.\nexport const actorKinds = (messages: EventModelMessages): ActorKind[] => [\n { actorType: ActorType.UIRole, label: messages.actors.ui, color: '#e0e7ff' },\n { actorType: ActorType.systemRole, label: messages.actors.system, color: '#dcfce7' },\n { actorType: ActorType.chatRole, label: messages.actors.chat, color: '#fef9c3' },\n];\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './CollapseButton.css';\nimport React from 'react';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface CollapseButtonProps {\n \n collapsed: boolean;\n \n onToggle?: () => void;\n}\n\nexport const CollapseButton: React.FC<CollapseButtonProps> = ({ collapsed, onToggle }) => {\n const messages = useEventModelMessages();\n const label = collapsed ? messages.collapse.expand : messages.collapse.collapse;\n return (\n <button\n onClick={(event) => { event.stopPropagation(); onToggle?.(); }}\n disabled={!onToggle}\n className='event-modeling-grid-collapse-btn'\n title={label}\n aria-label={label}\n aria-expanded={!collapsed}\n >\n {collapsed ? (\n /* Expand icon: arrows pointing outward to corners */\n <svg width='12' height='12' viewBox='0 0 12 12' fill='none' aria-hidden='true'>\n <path d='M5 1L1 1L1 5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' />\n <line x1='1' y1='1' x2='5.5' y2='5.5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n <path d='M7 11L11 11L11 7' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' />\n <line x1='11' y1='11' x2='6.5' y2='6.5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n </svg>\n ) : (\n /* Collapse icon: arrows pointing inward from corners */\n <svg width='12' height='12' viewBox='0 0 12 12' fill='none' aria-hidden='true'>\n <path d='M1 5L5 5L5 1' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' />\n <line x1='5' y1='5' x2='1.5' y2='1.5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n <path d='M11 7L7 7L7 11' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' />\n <line x1='7' y1='7' x2='10.5' y2='10.5' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n </svg>\n )}\n </button>\n);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/AddButton.css';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface DetailsToggleProps {\n visible: boolean;\n onToggle: () => void;\n}\n\n// Shows or hides the details of one slice or feature; the details shown are part of the presentation the\n// consumer controls.\nexport const DetailsToggle = ({ visible, onToggle }: DetailsToggleProps) => {\n const messages = useEventModelMessages();\n const label = visible ? messages.details.hide : messages.details.show;\n return (\n <button\n type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n aria-label={label}\n title={label}\n onClick={onToggle}\n style={visible ? { borderColor: 'var(--text-color)', color: 'var(--text-color)' } : undefined}\n >\n <i className='pi pi-list' style={{ fontSize: 10 }} />\n </button>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EditableLabel.css';\nimport React, { useState } from 'react';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface EditableLabelProps {\n\n value: string;\n\n onChange: (value: string) => void;\n\n placeholder?: string;\n\n style?: React.CSSProperties;\n\n validate?: (value: string) => string | undefined;\n\n readOnly?: boolean;\n}\n\nexport const EditableLabel: React.FC<EditableLabelProps> = ({ value, onChange, placeholder = 'Name…', style, validate, readOnly = false }) => {\n const messages = useEventModelMessages();\n const [editing, setEditing] = useState(false);\n const [draft, setDraft] = useState(value);\n const [error, setError] = useState<string | undefined>(undefined);\n\n const commit = () => {\n const trimmed = draft.trim();\n if (!trimmed) {\n setDraft(value);\n setEditing(false);\n setError(undefined);\n return;\n }\n if (validate) {\n const errorMessage = validate(trimmed);\n if (errorMessage) {\n setError(errorMessage);\n return;\n }\n }\n setError(undefined);\n setEditing(false);\n onChange(trimmed);\n };\n\n if (editing && !readOnly) {\n return (\n <input\n autoFocus\n value={draft}\n onChange={event => {\n setDraft(event.target.value);\n setError(undefined);\n }}\n onBlur={commit}\n onKeyDown={event => {\n if (event.key === 'Enter') {\n (event.target as HTMLInputElement).blur();\n return;\n }\n if (event.key === 'Escape') {\n setDraft(value);\n setEditing(false);\n setError(undefined);\n }\n }}\n className={`event-modeling-grid-editable-label-input${error ? ' event-modeling-grid-editable-label-input--error' : ''}`}\n title={error}\n style={style}\n />\n );\n }\n\n return (\n <span\n title={readOnly ? undefined : messages.editableLabel.doubleClickToRename}\n onDoubleClick={readOnly ? undefined : () => {\n setDraft(value);\n setEditing(true);\n setError(undefined);\n }}\n className='event-modeling-grid-editable-label'\n style={style}\n >\n {value || <em className='event-modeling-grid-editable-label-placeholder'>{placeholder}</em>}\n </span>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport { GridTooltip } from '../Tooltips';\nimport './EntityErrorIndicator.css';\n\nexport interface EntityErrorIndicatorProps {\n\n /** The error message to display in the tooltip. */\n error: string;\n}\n\n/**\n * Small error icon that shows a tooltip with the error details.\n * Rendered alongside entity headers (modules, features, slices) when a command fails.\n */\nexport const EntityErrorIndicator: React.FC<EntityErrorIndicatorProps> = ({ error }) => (\n <GridTooltip content={error}>\n <span className='entity-error-indicator'>\n <i className='pi pi-exclamation-triangle' />\n </span>\n </GridTooltip>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/** The level of the board hierarchy an errored placeholder stands in for. */\nexport enum EntityErrorKind {\n Module = 'module',\n Feature = 'feature',\n Slice = 'slice',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ErroredEntity.css';\nimport { EntityErrorKind } from './EntityErrorKind';\nimport { GridTooltip } from '../Tooltips';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface ErroredEntityProps {\n\n /** Which level of the board failed. */\n kind: EntityErrorKind;\n\n /** The name of the module, feature, or slice that failed. */\n label: string;\n\n /** The message describing why it failed; shown on hover. */\n error: string;\n\n /** Rebuilds the entity from its source data. */\n onRetry: () => void;\n}\n\n/**\n * Stands in for a module, feature, or slice whose render failed: it keeps the board's shape, crosses the\n * entity out, and reveals the error on hover — so one broken entity costs the user that entity instead\n * of the whole board.\n */\nexport const ErroredEntity = ({ kind, label, error, onRetry }: ErroredEntityProps) => {\n const messages = useEventModelMessages().erroredEntity;\n return (\n <GridTooltip content={messages.couldNotBeRendered(messages[kind], error)}>\n <div className={`errored-entity errored-entity--${kind}`} role='alert' data-errored-entity={kind}>\n <i className='pi pi-times-circle errored-entity__mark' aria-hidden='true' />\n <span className='errored-entity__label'>{label}</span>\n <span className='errored-entity__hint'>{messages.failedToRender}</span>\n <button type='button' className='errored-entity__retry' onClick={onRetry}>{messages.retry}</button>\n </div>\n </GridTooltip>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport { CollapseButton } from './CollapseButton';\nimport { EditableLabel } from './EditableLabel';\nimport { EntityErrorIndicator } from './EntityErrorIndicator';\nimport './PillHeader.css';\n\nexport type PillHeaderVariant = 'module' | 'feature';\n\nexport interface PillHeaderProps {\n\n variant: PillHeaderVariant;\n\n collapsed: boolean;\n\n onToggle?: () => void;\n\n label: string;\n\n onRenameLabel: (name: string) => void;\n\n // The label can be read but not renamed.\n labelReadOnly?: boolean;\n\n validateLabel?: (name: string) => string | undefined;\n\n labelStyle?: React.CSSProperties;\n\n background: string;\n\n border: string;\n\n height: number;\n\n /** Extra affordances rendered right after the collapse button, before the label — such as the conversation button. */\n leadingContent?: React.ReactNode;\n\n children?: React.ReactNode;\n\n draggable?: boolean;\n\n onPointerDown?: React.PointerEventHandler<HTMLDivElement>;\n\n onPointerMove?: React.PointerEventHandler<HTMLDivElement>;\n\n onPointerUp?: React.PointerEventHandler<HTMLDivElement>;\n\n /** When set, the pill shows a red border and an error indicator icon with the message as tooltip. */\n error?: string;\n}\n\nexport const PillHeader: React.FC<PillHeaderProps> = ({\n variant,\n collapsed,\n onToggle,\n label,\n onRenameLabel,\n labelReadOnly = false,\n validateLabel,\n labelStyle,\n background,\n border,\n height,\n children,\n leadingContent,\n draggable = false,\n onPointerDown,\n onPointerMove,\n onPointerUp,\n error,\n}) => (\n <div\n className={`event-modeling-grid-pill event-modeling-grid-pill--${variant}${collapsed ? ' event-modeling-grid-pill--collapsed' : ''}${draggable ? ' event-modeling-grid-pill--draggable' : ''}${error ? ' event-modeling-grid-pill--error' : ''}`}\n style={{ background, border: error ? '2px solid #ef4444' : border, height }}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n >\n <div className='event-modeling-grid-pill-left'>\n {onToggle && <CollapseButton collapsed={collapsed} onToggle={onToggle} />}\n {leadingContent}\n </div>\n <EditableLabel\n value={label}\n onChange={onRenameLabel}\n validate={validateLabel}\n style={labelStyle}\n readOnly={labelReadOnly}\n />\n <div className='event-modeling-grid-pill-right'>\n {error && <EntityErrorIndicator error={error} />}\n {children}\n </div>\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { type RefObject, useEffect, useRef } from 'react';\n\n// Calls onDismiss when a pointer goes down outside every one of the elements — a trigger and a panel\n// portaled elsewhere count as one. Listens in the capture phase, because cards stop pointerdown from\n// bubbling for their own gestures.\nexport const useDismissOnOutsidePointer = (elements: RefObject<Element | null>[], onDismiss: () => void, enabled: boolean): void => {\n const dismiss = useRef(onDismiss);\n dismiss.current = onDismiss;\n\n useEffect(() => {\n if (!enabled) return;\n const handlePointerDown = (event: PointerEvent) => {\n const present = elements.map(element => element.current).filter(element => !!element);\n const target = event.target;\n const inside = target instanceof Node && present.some(element => element?.contains(target));\n if (present.length > 0 && !inside) dismiss.current();\n };\n document.addEventListener('pointerdown', handlePointerDown, true);\n return () => document.removeEventListener('pointerdown', handlePointerDown, true);\n }, [elements, enabled]);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModelMessages } from '../Messages';\nimport { RowType } from '../Rows/RowType';\n\n// What a row is called on its label until it is given a name of its own.\nexport const rowTypeName = (rowType: RowType, messages: EventModelMessages): string => {\n switch (rowType) {\n case RowType.UI: return messages.rows.ui;\n case RowType.Chat: return messages.rows.chat;\n case RowType.System: return messages.rows.system;\n case RowType.Interaction: return messages.rows.interaction;\n case RowType.Events: return messages.rows.events;\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './RowLabel.css';\nimport { useMemo, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from 'react';\nimport type { ActorType } from '../Model';\nimport { useBoard } from '../Board';\nimport { EditableLabel } from '../Headers';\nimport { GridTooltip } from '../Tooltips';\nimport { rowLabelWidth } from '../Geometry';\nimport { useDismissOnOutsidePointer } from '../Pickers/useDismissOnOutsidePointer';\nimport { RowType } from '../Rows/RowType';\nimport { actorKinds } from './actorKinds';\nimport type { RowLabelBadge } from './RowLabelBadge';\nimport { rowTypeName } from './rowTypeName';\n\n// How far the pointer travels before a press on a label becomes a drag.\nconst dragThreshold = 4;\n\nexport interface RowLabelProps {\n rowType: RowType;\n height?: number;\n // The name of the row, or of the actor it holds; the row type's own name when omitted.\n name?: string;\n // Shown when hovering a name that cannot be edited, such as who an actor is on a read-only board.\n description?: string;\n // Set when the label belongs to an actor rather than to a row with no actors.\n actorId?: string;\n // Renaming exists on actor rows only when the board is editable and this is supplied.\n onRenamed?: (name: string) => void;\n validateName?: (name: string) => string | undefined;\n // The add menu exists on actor rows only when the board is editable and this is supplied.\n onActorAdded?: (actorType: ActorType) => void;\n // An actor's label can be picked up only when the board is editable and this is supplied.\n onDragStart?: (clientX: number, clientY: number) => void;\n // This actor is the one being dragged.\n dragging?: boolean;\n // The badge at the top of an actor row's label.\n badge?: RowLabelBadge;\n // Consumer-rendered persona image; the board never resolves Studio avatars.\n personaAvatar?: ReactNode;\n // What the consumer mounts with the label, such as the dialogs its badge actions open.\n children?: ReactNode;\n}\n\nconst isActorRowType = (rowType: RowType) => rowType === RowType.UI || rowType === RowType.System || rowType === RowType.Chat;\n\n// Vertical (bottom-to-top) via a plain rotation, not writing-mode + rotate(180deg): WebKit shears a vertical\n// writing-mode element under an ancestor transform: scale() (the canvas zoom layer), skewing the label until\n// the next repaint. See RowLabel.css.\nconst editableLabelStyle: CSSProperties = {\n transform: 'rotate(-90deg)',\n whiteSpace: 'nowrap',\n fontSize: 11,\n fontWeight: 600,\n color: 'rgba(255,255,255,0.45)',\n textTransform: 'uppercase',\n letterSpacing: '0.05em',\n textAlign: 'center',\n};\n\nconst swatchStyle = (color: string): CSSProperties => ({\n width: 10,\n height: 10,\n borderRadius: 3,\n background: color,\n border: '1px solid #d1d5db',\n flexShrink: 0,\n display: 'inline-block',\n});\n\nexport const RowLabel = ({\n rowType,\n height,\n name,\n description,\n actorId,\n onRenamed,\n validateName,\n onActorAdded,\n onDragStart,\n dragging = false,\n badge,\n personaAvatar,\n children,\n}: RowLabelProps) => {\n const { readOnly, messages } = useBoard();\n const [addMenuOpen, setAddMenuOpen] = useState(false);\n const [badgeMenuOpen, setBadgeMenuOpen] = useState(false);\n const press = useRef<{ startX: number; startY: number } | undefined>(undefined);\n const pillRef = useRef<HTMLDivElement>(null);\n const addMenuRef = useRef<HTMLDivElement>(null);\n const badgeMenuRef = useRef<HTMLDivElement>(null);\n const addMenuRefs = useMemo(() => [addMenuRef], []);\n const badgeMenuRefs = useMemo(() => [badgeMenuRef], []);\n useDismissOnOutsidePointer(addMenuRefs, () => setAddMenuOpen(false), addMenuOpen);\n useDismissOnOutsidePointer(badgeMenuRefs, () => setBadgeMenuOpen(false), badgeMenuOpen);\n\n const displayName = name ?? rowTypeName(rowType, messages);\n const isActorRow = isActorRowType(rowType);\n const renamed = isActorRow && !readOnly ? onRenamed : undefined;\n const actorAdded = isActorRow && !readOnly ? onActorAdded : undefined;\n const dragStart = actorId && !readOnly ? onDragStart : undefined;\n\n const actions = readOnly ? [] : badge?.actions ?? [];\n const activateBadge = readOnly ? undefined : badge?.onActivate;\n const badgeActive = actions.length > 0 || !!activateBadge;\n // A read-only board shows who an actor is, but offers nothing to do about it.\n const avatar = personaAvatar ?? badge?.avatar;\n const showsBadge = isActorRow && (!!avatar || (!!badge && !readOnly));\n\n const handleBadgeClick = () => {\n if (actions.length > 0) {\n setBadgeMenuOpen(previous => !previous);\n return;\n }\n activateBadge?.();\n };\n\n const handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {\n const target = event.target;\n if (target instanceof Element && (target.tagName === 'INPUT' || target.closest('button'))) return;\n // Claim the gesture so a touch drag here moves the row instead of panning the canvas.\n event.stopPropagation();\n press.current = { startX: event.clientX, startY: event.clientY };\n };\n\n const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {\n const current = press.current;\n if (!current || !dragStart) return;\n const movedY = Math.abs(event.clientY - current.startY);\n const movedX = Math.abs(event.clientX - current.startX);\n if (movedY > dragThreshold || movedX > dragThreshold) {\n press.current = undefined;\n dragStart(event.clientX, event.clientY);\n }\n };\n\n const handlePointerUp = () => {\n press.current = undefined;\n };\n\n return (\n <div\n style={{\n width: rowLabelWidth,\n height,\n flexShrink: 0,\n opacity: dragging ? 0.35 : 1,\n transition: 'opacity 0.15s',\n }}\n className='event-modeling-grid-row-label'\n data-role-row={actorId ? 'true' : undefined}\n data-role-type={actorId ? rowType : undefined}\n data-role-id={actorId}\n >\n <div\n className='event-modeling-grid-row-label-pill'\n ref={pillRef}\n style={dragStart ? { cursor: 'grab' } : undefined}\n onPointerDown={dragStart ? handlePointerDown : undefined}\n onPointerMove={dragStart ? handlePointerMove : undefined}\n onPointerUp={dragStart ? handlePointerUp : undefined}\n >\n {showsBadge && (\n <div className='event-modeling-grid-row-label-info' ref={badgeMenuRef}>\n <button\n className='event-modeling-grid-row-label-info-btn'\n onClick={event => { event.stopPropagation(); handleBadgeClick(); }}\n title={badge?.title ?? displayName}\n aria-label={badge?.title ?? displayName}\n disabled={!badgeActive}\n style={!badgeActive ? { opacity: readOnly ? 1 : 0.4, cursor: 'default' } : undefined}\n >\n {avatar ?? <i className='pi pi-id-card' />}\n </button>\n {badgeMenuOpen && actions.length > 0 && (\n <div className='event-modeling-grid-row-role-menu'>\n {actions.map(action => (\n <button\n key={action.id}\n className={`event-modeling-grid-row-role-menu-option${action.danger ? ' event-modeling-grid-row-role-menu-option--danger' : ''}`}\n onClick={event => {\n event.stopPropagation();\n setBadgeMenuOpen(false);\n if (actorId && pillRef.current) action.onActivate(actorId, pillRef.current.getBoundingClientRect());\n }}\n >\n {action.icon}\n {action.label}\n </button>\n ))}\n </div>\n )}\n </div>\n )}\n <div className='event-modeling-grid-row-label-title'>\n {renamed ? (\n <EditableLabel value={displayName} onChange={renamed} validate={validateName} style={editableLabelStyle} />\n ) : description?.trim() ? (\n <GridTooltip content={description} position='right'>\n <span className='event-modeling-grid-row-label-text'>{displayName}</span>\n </GridTooltip>\n ) : (\n <span className='event-modeling-grid-row-label-text'>{displayName}</span>\n )}\n </div>\n\n {actorAdded && (\n <div className='event-modeling-grid-row-label-add-role' ref={addMenuRef}>\n <button\n className='event-modeling-grid-row-label-add-role-btn'\n onClick={event => { event.stopPropagation(); setAddMenuOpen(previous => !previous); }}\n title={messages.actors.add}\n aria-label={messages.actors.add}\n >\n +\n </button>\n {addMenuOpen && (\n <div className='event-modeling-grid-row-role-menu'>\n {actorKinds(messages).map(({ actorType, label, color }) => (\n <button\n key={actorType}\n className='event-modeling-grid-row-role-menu-option'\n onClick={() => {\n actorAdded(actorType);\n setAddMenuOpen(false);\n }}\n >\n <span style={swatchStyle(color)} />\n {label}\n </button>\n ))}\n </div>\n )}\n </div>\n )}\n </div>\n {children}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './RowLabel.css';\nimport type { ReactNode } from 'react';\nimport { rowLabelWidth } from '../Geometry';\n\nexport interface RowLabelsColumnFrameProps {\n // The space above the first label, so the labels line up with the rows beside them.\n topOffset: number;\n collectionId?: string;\n children?: ReactNode;\n}\n\n// The column of row labels to the left of a module collection.\nexport const RowLabelsColumnFrame = ({ topOffset, collectionId, children }: RowLabelsColumnFrameProps) => (\n <div className='event-modeling-grid-row-labels' data-actor-collection-id={collectionId} style={{ width: rowLabelWidth }}>\n <div style={{ height: topOffset, flexShrink: 0 }} />\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { ActorType } from '../Model';\nimport { useBoard } from '../Board';\nimport { RowType } from '../Rows/RowType';\nimport { rowOfActorType } from './actorRows';\nimport type { ActorsReordered } from './ActorsReordered';\n\n// What a drag needs to know about an actor.\nexport interface DraggableActor {\n id: string;\n name: string;\n actorType: ActorType;\n}\n\nexport interface ActorRowDragState {\n actorId: string;\n rowType: RowType;\n sourceIndex: number;\n ghostLabel: string;\n currentX: number;\n currentY: number;\n // The gap the actor would land in right now: n is before the nth actor of its kind.\n dropIndex: number;\n}\n\nexport type ActorRowDragStart = (actorId: string, clientX: number, clientY: number) => void;\n\nexport interface ActorRowDrag {\n actorDrag?: ActorRowDragState;\n // Undefined when nothing can be told about a move, so no actor label offers to be picked up.\n handleActorDragStart?: ActorRowDragStart;\n}\n\n// The gap a pointer at clientY is over among the actor labels of one row type.\nfunction dropIndexAt(collectionId: Guid, rowType: RowType, clientY: number): number {\n const column = Array.from(document.querySelectorAll<HTMLElement>('[data-actor-collection-id]'))\n .find(candidate => candidate.dataset.actorCollectionId === collectionId.toString());\n const rows = Array.from(column?.querySelectorAll<HTMLElement>(`[data-role-row=\"true\"][data-role-type=\"${rowType}\"]`) ?? []);\n for (let index = 0; index < rows.length; index++) {\n const rect = rows[index].getBoundingClientRect();\n if (clientY < rect.top + rect.height / 2) return index;\n }\n return rows.length;\n}\n\n// The order after moving the actor at sourceIndex into the gap at dropIndex; undefined when it would\n// land where it already is.\nexport function reorderedActorIds(ids: readonly string[], sourceIndex: number, dropIndex: number): string[] | undefined {\n if (sourceIndex < 0 || sourceIndex >= ids.length) return undefined;\n const landingIndex = dropIndex > sourceIndex ? dropIndex - 1 : dropIndex;\n const targetIndex = Math.min(Math.max(landingIndex, 0), ids.length - 1);\n if (targetIndex === sourceIndex) return undefined;\n const reordered = [...ids];\n const [moved] = reordered.splice(sourceIndex, 1);\n reordered.splice(targetIndex, 0, moved);\n return reordered;\n}\n\nexport interface ActorDrop {\n actorType: ActorType;\n orderedIds: string[];\n}\n\n// What dropping an actor into the gap at dropIndex does to the order of the actors of its own kind;\n// undefined when it changes nothing.\nexport function actorDrop(actors: readonly DraggableActor[], actorId: string, dropIndex: number): ActorDrop | undefined {\n const actor = actors.find(candidate => candidate.id === actorId);\n if (!actor) return undefined;\n const sameKind = actors.filter(candidate => candidate.actorType === actor.actorType).map(candidate => candidate.id);\n const orderedIds = reorderedActorIds(sameKind, sameKind.indexOf(actorId), dropIndex);\n return orderedIds && { actorType: actor.actorType, orderedIds };\n}\n\n// Dragging an actor to another place among the actors of its kind in a collection.\nexport function useActorRowDrag(collectionId: Guid, actors: readonly DraggableActor[], onActorsReordered?: ActorsReordered): ActorRowDrag {\n const board = useBoard();\n const [actorDrag, setActorDrag] = useState<ActorRowDragState | undefined>(undefined);\n const actorDragRef = useRef(actorDrag);\n actorDragRef.current = actorDrag;\n const actorsRef = useRef(actors);\n actorsRef.current = actors;\n const collectionIdRef = useRef(collectionId);\n collectionIdRef.current = collectionId;\n const onActorsReorderedRef = useRef(onActorsReordered);\n onActorsReorderedRef.current = onActorsReordered;\n\n const handleActorDragStart = useCallback<ActorRowDragStart>((actorId, clientX, clientY) => {\n const actor = actorsRef.current.find(candidate => candidate.id === actorId);\n if (!actor) return;\n const sameKind = actorsRef.current.filter(candidate => candidate.actorType === actor.actorType);\n const sourceIndex = sameKind.findIndex(candidate => candidate.id === actorId);\n setActorDrag({\n actorId,\n rowType: rowOfActorType(actor.actorType),\n sourceIndex,\n ghostLabel: actor.name,\n currentX: clientX,\n currentY: clientY,\n dropIndex: sourceIndex,\n });\n }, []);\n\n const dragging = actorDrag !== undefined;\n useEffect(() => {\n if (!dragging) return;\n\n const handlePointerMove = (event: PointerEvent) => {\n setActorDrag(previous => previous && {\n ...previous,\n currentX: event.clientX,\n currentY: event.clientY,\n dropIndex: dropIndexAt(collectionIdRef.current, previous.rowType, event.clientY),\n });\n };\n\n const handlePointerUp = () => {\n const drag = actorDragRef.current;\n setActorDrag(undefined);\n if (!drag) return;\n const drop = actorDrop(actorsRef.current, drag.actorId, drag.dropIndex);\n if (drop) onActorsReorderedRef.current?.(collectionIdRef.current, drop.actorType, drop.orderedIds);\n };\n\n window.addEventListener('pointermove', handlePointerMove);\n window.addEventListener('pointerup', handlePointerUp);\n return () => {\n window.removeEventListener('pointermove', handlePointerMove);\n window.removeEventListener('pointerup', handlePointerUp);\n };\n }, [dragging]);\n\n const canDrag = !board.readOnly && onActorsReordered !== undefined;\n return { actorDrag, handleActorDragStart: canDrag ? handleActorDragStart : undefined };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Fragment, useState, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { Actor, ActorType } from '../Model';\nimport { RowType } from '../Rows/RowType';\nimport { actorTypeOfRow } from './actorRows';\nimport { ActorRowDragGhost } from './ActorRowDragGhost';\nimport { ActorRowDropIndicator } from './ActorRowDropIndicator';\nimport { RowLabel, type RowLabelProps } from './RowLabel';\nimport { RowLabelsColumnFrame } from './RowLabelsColumnFrame';\nimport { useActorRowDrag } from './useActorRowDrag';\nimport type { ActorsReordered } from './ActorsReordered';\n\nexport interface RowLabelsColumnProps {\n collectionId: Guid;\n topOffset: number;\n contentRows: readonly RowType[];\n rowHeights: Record<RowType, number>;\n actors: readonly Actor[];\n onActorAdded?: (rowType: RowType, actorType: ActorType) => void;\n onActorRenamed?: (actorId: string, name: string) => void;\n onRowRenamed?: (rowType: RowType, name: string) => void;\n onActorsReordered?: ActorsReordered;\n // Studio-specific identity controls and dialogs are supplied without moving the row's geometry to Studio.\n renderActorLabel?: (actor: Actor, label: RowLabelProps) => ReactNode;\n renderEmptyActorLabel?: (rowType: RowType, label: RowLabelProps) => ReactNode;\n}\n\n// The package owns row assembly, drop feedback and the pointer gesture; the consumer owns persistence.\nexport const RowLabelsColumn = ({\n collectionId, topOffset, contentRows, rowHeights, actors, onActorAdded, onActorRenamed, onRowRenamed,\n onActorsReordered, renderActorLabel, renderEmptyActorLabel,\n}: RowLabelsColumnProps) => {\n const [rowNames, setRowNames] = useState<Partial<Record<RowType, string>>>({});\n const [actorNames, setActorNames] = useState<Record<string, string>>({});\n const { actorDrag, handleActorDragStart } = useActorRowDrag(collectionId, actors, onActorsReordered);\n\n return (\n <RowLabelsColumnFrame topOffset={topOffset} collectionId={collectionId.toString()}>\n <ActorRowDragGhost drag={actorDrag} />\n {contentRows.flatMap(rowType => {\n const actorType = actorTypeOfRow(rowType);\n const rowActors = actorType === undefined ? [] : actors.filter(actor => actor.actorType === actorType);\n const parentLabelProps: RowLabelProps = {\n rowType,\n height: rowHeights[rowType],\n name: rowNames[rowType],\n onRenamed: onRowRenamed ? name => {\n setRowNames(previous => ({ ...previous, [rowType]: name }));\n onRowRenamed(rowType, name);\n } : undefined,\n validateName: name => {\n const otherName = Object.entries(rowNames).find(([key]) => key !== rowType)?.[1];\n return otherName?.toLowerCase() === name.toLowerCase() ? 'Name already in use' : undefined;\n },\n onActorAdded: onActorAdded ? kind => onActorAdded(rowType, kind) : undefined,\n };\n const parentLabel = actorType === undefined || rowActors.length === 0 ? [\n <Fragment key={rowType}>\n {actorType !== undefined && renderEmptyActorLabel\n ? renderEmptyActorLabel(rowType, parentLabelProps)\n : <RowLabel {...parentLabelProps} />}\n </Fragment>,\n ] : [];\n const actorLabels = rowActors.flatMap((actor, index) => {\n const draggingThisType = actorDrag?.rowType === rowType;\n const label: RowLabelProps = {\n rowType,\n height: rowHeights[rowType],\n name: actorNames[actor.id] ?? actor.name,\n description: actor.description,\n actorId: actor.id,\n onRenamed: onActorRenamed ? name => {\n setActorNames(previous => ({ ...previous, [actor.id]: name }));\n onActorRenamed(actor.id, name);\n } : undefined,\n onActorAdded: onActorAdded ? kind => onActorAdded(rowType, kind) : undefined,\n onDragStart: handleActorDragStart ? (clientX, clientY) => handleActorDragStart(actor.id, clientX, clientY) : undefined,\n dragging: actorDrag?.actorId === actor.id,\n };\n return [\n ...(draggingThisType && actorDrag.dropIndex === index ? [<ActorRowDropIndicator key={`drop-${rowType}-${index}`} />] : []),\n <Fragment key={actor.id}>\n {renderActorLabel ? renderActorLabel(actor, label) : <RowLabel {...label} />}\n </Fragment>,\n ...(draggingThisType && index === rowActors.length - 1 && actorDrag.dropIndex === rowActors.length\n ? [<ActorRowDropIndicator key={`drop-${rowType}-end`} />] : []),\n ];\n });\n return [...parentLabel, ...actorLabels];\n })}\n </RowLabelsColumnFrame>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode, Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface ModuleColumnFrameProps {\n moduleId: Guid;\n // Set on the leading module of a collection: a collection has no box of its own, and its leading\n // module is where it starts on the canvas.\n collectionId?: Guid;\n // The gap before the module; the first module in a collection has none.\n marginLeft: number;\n // The module is the one being dragged.\n dragging?: boolean;\n ref?: Ref<HTMLDivElement>;\n children?: ReactNode;\n}\n\n// The column a module's header and features sit in. It carries the attributes a module drag reads the\n// modules of a collection by, and that anything navigating the board finds a module or collection by.\nexport const ModuleColumnFrame = ({ moduleId, collectionId, marginLeft, dragging = false, ref, children }: ModuleColumnFrameProps) => (\n <div\n ref={ref}\n data-module-id={moduleId.toString()}\n data-collection-id={collectionId?.toString()}\n style={{\n marginLeft,\n display: 'flex',\n flexDirection: 'column',\n flexShrink: 0,\n // The dragged column stays in place and fades, so the gap it leaves is where the pointer is\n // rather than where the column used to be.\n opacity: dragging ? 0.4 : undefined,\n }}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceDragging/SliceDragGhost.css';\nimport './ModuleDropIndicator.css';\n\n// Where a dragged module would land, drawn in the gap between two modules.\nexport const ModuleDropIndicator = () => <div className='event-modeling-grid-drop-indicator' />;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The attributes the board hit-tests drop positions with. A ghost is a copy of a real slice, so it\n// carries them too — and the copy lives in `document.body`, where the very `document.querySelectorAll`\n// calls that decide which feature and which position a slice would land in would find it and count it as\n// a real column. Stripping them is what keeps the ghost invisible to the drag it is illustrating.\nexport const HIT_TEST_ATTRIBUTES = [\n 'data-slice-col',\n 'data-slice-id',\n 'data-slice-feature-id',\n 'data-slice-drop-target',\n 'data-slice-module-id',\n 'id',\n];\n\n// The part of an element the ghost preparation touches, so it can be exercised without a document.\nexport interface GhostNode {\n removeAttribute(name: string): void;\n setAttribute(name: string, value: string): void;\n readonly children: ArrayLike<GhostNode>;\n}\n\n// Prepares a copied slice to be shown as a ghost: nothing the board searches for, and nothing anything\n// can interact with.\n// node: The copied element to prepare, and everything inside it.\nexport function prepareGhost(node: GhostNode) {\n for (const attribute of HIT_TEST_ATTRIBUTES) {\n node.removeAttribute(attribute);\n }\n\n // A snapshot is a picture that follows the pointer. Left interactive, a stray input inside it could\n // take focus off the board mid-drag, and a screen reader would read the slice out twice.\n node.removeAttribute('contenteditable');\n node.setAttribute('aria-hidden', 'true');\n node.setAttribute('inert', '');\n\n for (let index = 0; index < node.children.length; index++) {\n prepareGhost(node.children[index]);\n }\n}\n\n// Takes the snapshot of a slice that is dragged around the board: the slice exactly as it looks right\n// now, detached from the document it came from.\n//\n// A slice is a tall column of headers, cells and specifications, and a label-sized placeholder said\n// nothing about which of them was being moved. Copying the live element keeps every bit of that\n// appearance without re-deriving it, because the stylesheet is global and the copy keeps its classes.\n// element: The slice column element to snapshot.\n// Returns The detached copy to render as the ghost.\nexport function createSliceDragGhost(element: HTMLElement): HTMLElement | null {\n const ghost = element.cloneNode(true);\n if (!(ghost instanceof HTMLElement)) return null;\n\n prepareGhost(ghost);\n\n // The live column dims itself while it is being dragged. The ghost is the thing being looked at, so\n // it must not inherit that — its own transparency belongs to whatever renders it.\n ghost.style.opacity = '';\n ghost.style.cursor = 'grabbing';\n\n return ghost;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { prepareGhost } from '../SliceDragging/snapshotSlice';\n\n// Takes the snapshot of a feature or module header that is dragged around the board.\n//\n// A feature or module can own a whole sub-tree of slices underneath its header. Copying all of that would\n// be heavy to drag around, and none of it says what is being moved: the header alone does. So only the\n// header is copied, with the same stripping a slice copy gets, so the copy is invisible to the drag it\n// illustrates.\nexport function createHeaderDragGhost(element: HTMLElement): HTMLElement | null {\n const ghost = element.cloneNode(true);\n if (!(ghost instanceof HTMLElement)) return null;\n\n prepareGhost(ghost);\n\n ghost.style.opacity = '';\n ghost.style.cursor = 'grabbing';\n\n return ghost;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceDragging/SliceDragGhost.css';\nimport './HeaderDragGhost.css';\nimport { useEffect, useRef } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { HeaderDragState } from './HeaderDragState';\n\n// The same tilt a picked-up slice gets.\nconst ghostTiltDegrees = 3;\n\nexport interface HeaderDragGhostProps {\n drag?: HeaderDragState;\n // The height of the labelled stand-in drawn when the header could not be copied.\n headerHeight: number;\n}\n\n// The feature or module being dragged, drawn over everything at the pointer as a tilted copy of just its\n// header; the body underneath stays where it is, the way a slice ghost shows only the slice being moved.\nexport const HeaderDragGhost = ({ drag, headerHeight }: HeaderDragGhostProps) =>\n drag ? createPortal(<HeaderGhost drag={drag} headerHeight={headerHeight} />, document.body) : undefined;\n\nconst HeaderGhost = ({ drag, headerHeight }: { drag: HeaderDragState; headerHeight: number }) => {\n const snapshotHost = useRef<HTMLDivElement | null>(null);\n const ghost = drag.ghost;\n\n // The copy is a detached DOM node rather than markup React owns, so it is placed by hand.\n useEffect(() => {\n const host = snapshotHost.current;\n if (!host || !ghost) return;\n host.replaceChildren(ghost);\n return () => host.replaceChildren();\n }, [ghost]);\n\n return (\n <div\n style={{\n position: 'fixed',\n left: drag.currentX - drag.ghostWidth / 2 * drag.zoom,\n top: drag.headerY,\n width: drag.ghostWidth,\n transform: `scale(${drag.zoom}) rotate(${ghostTiltDegrees}deg)`,\n transformOrigin: '0 0',\n pointerEvents: 'none',\n zIndex: 9998,\n userSelect: 'none',\n }}\n >\n {ghost\n ? <div ref={snapshotHost} className='event-modeling-grid-header-ghost' style={{ width: drag.ghostWidth }} />\n : (\n <div className='event-modeling-grid-slice-ghost-fallback' style={{ width: drag.ghostWidth, height: headerHeight }}>\n <span>{drag.ghostLabel}</span>\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The horizontal extent of one laid-out feature or module, as far as the drop calculation is concerned.\nexport interface HeaderExtent {\n // Left edge, in client coordinates.\n left: number;\n width: number;\n}\n\n// Which gap between features or modules a pointer at clientX is over.\n//\n// Counts gaps, not columns: 0 is before the first and extents.length is after the last, so a drag to the\n// far right has somewhere to land. A column is passed once the pointer is beyond its midpoint, which is\n// what makes the swap happen when the two are visually half-overlapped rather than only once the pointer\n// clears the whole column. The extents are read from the laid-out columns, because a collapsed one is far\n// narrower than an expanded one and nothing says the columns are evenly sized.\nexport const headerDropIndex = (extents: readonly HeaderExtent[], clientX: number): number => {\n for (let index = 0; index < extents.length; index++) {\n if (clientX < extents[index].left + extents[index].width / 2) return index;\n }\n return extents.length;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\n// The order after moving the item at sourceIndex into the gap at dropIndex, where gap n sits before\n// item n and the gap after the last item is the length of the list. Undefined when the item would land\n// where it already is, so nothing is reported for a drop that changes nothing.\nexport function reorderedIds(ids: readonly Guid[], sourceIndex: number, dropIndex: number): Guid[] | undefined {\n if (!Number.isInteger(sourceIndex) || sourceIndex < 0 || sourceIndex >= ids.length) return undefined;\n if (!Number.isInteger(dropIndex)) return undefined;\n\n // Taking the item out closes its own gap, so every gap after it moves one to the left.\n const landingIndex = dropIndex > sourceIndex ? dropIndex - 1 : dropIndex;\n const targetIndex = Math.min(Math.max(landingIndex, 0), ids.length - 1);\n if (targetIndex === sourceIndex) return undefined;\n\n const reordered = [...ids];\n const [moved] = reordered.splice(sourceIndex, 1);\n reordered.splice(targetIndex, 0, moved);\n return reordered;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Reads the board's zoom off the nearest ancestor that scales, so a ghost drawn outside the board\n// matches the size of what it was copied from.\nexport function zoomOfAncestor(element: HTMLElement | null): number {\n let current = element?.parentElement ?? undefined;\n while (current) {\n const scale = current.style.transform.match(/scale\\(([^)]+)\\)/);\n if (scale) return parseFloat(scale[1]);\n current = current.parentElement ?? undefined;\n }\n return 1;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useMemo, useRef, type PointerEvent, type PointerEventHandler } from 'react';\nimport { createHeaderDragGhost } from './createHeaderDragGhost';\nimport type { HeaderDragStart } from './HeaderDragStart';\nimport { zoomOfAncestor } from './zoomOfAncestor';\n\n// How far the pointer travels before a press on a header becomes a drag.\nconst dragThreshold = 4;\n\nexport interface HeaderDragHandlers {\n onPointerDown: PointerEventHandler<HTMLDivElement>;\n onPointerMove: PointerEventHandler<HTMLDivElement>;\n onPointerUp: PointerEventHandler<HTMLDivElement>;\n}\n\ninterface Press {\n startX: number;\n startY: number;\n grabOffsetY: number;\n}\n\n// Turns a press on a header into a drag once the pointer has moved a few pixels. Undefined when there\n// is nothing to report a drag to, so the header takes no press and the board keeps its own gestures.\nexport function useHeaderDragIntent(onDragStart?: (start: HeaderDragStart) => void): HeaderDragHandlers | undefined {\n const press = useRef<Press | undefined>(undefined);\n\n return useMemo(() => {\n if (!onDragStart) return undefined;\n\n return {\n onPointerDown: (event: PointerEvent<HTMLDivElement>) => {\n const target = event.target;\n if (target instanceof Element && (target.tagName === 'INPUT' || target.closest('button'))) return;\n // Claim the gesture so dragging here moves the header instead of panning the board.\n event.stopPropagation();\n const rect = event.currentTarget.getBoundingClientRect();\n press.current = { startX: event.clientX, startY: event.clientY, grabOffsetY: event.clientY - rect.top };\n },\n onPointerMove: (event: PointerEvent<HTMLDivElement>) => {\n const current = press.current;\n if (!current) return;\n const movedX = Math.abs(event.clientX - current.startX);\n const movedY = Math.abs(event.clientY - current.startY);\n if (movedX <= dragThreshold && movedY <= dragThreshold) return;\n\n press.current = undefined;\n const header = event.currentTarget;\n onDragStart({\n clientX: event.clientX,\n clientY: event.clientY,\n width: header.getBoundingClientRect().width,\n headerY: current.startY - current.grabOffsetY,\n zoom: zoomOfAncestor(header),\n ghost: createHeaderDragGhost(header),\n });\n },\n onPointerUp: () => {\n press.current = undefined;\n },\n };\n }, [onDragStart]);\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceStatus } from '../Model';\n\nexport interface SliceStatusIconProps {\n status: SliceStatus;\n}\n\n// Every glyph is drawn in currentColor, so the host decides its color.\nexport const SliceStatusIcon = ({ status }: SliceStatusIconProps) => (\n <svg width='12' height='12' viewBox='0 0 12 12' fill='none' aria-hidden='true' xmlns='http://www.w3.org/2000/svg'>\n <StatusGlyph status={status} />\n </svg>\n);\n\nconst StatusGlyph = ({ status }: SliceStatusIconProps) => {\n switch (status) {\n case SliceStatus.notStarted:\n return <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' strokeDasharray='3 2' />;\n case SliceStatus.draft:\n return <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />;\n case SliceStatus.analysis:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />\n <circle cx='5.2' cy='5.2' r='1.6' stroke='currentColor' strokeWidth='1.2' />\n <line x1='6.5' y1='6.5' x2='8.2' y2='8.2' stroke='currentColor' strokeWidth='1.2' strokeLinecap='round' />\n </>\n );\n case SliceStatus.readyForImplementation:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />\n <line x1='4' y1='6' x2='8' y2='6' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' />\n </>\n );\n case SliceStatus.inProgress:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />\n <path d='M6 1 A5 5 0 0 1 11 6' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' fill='none' />\n </>\n );\n case SliceStatus.readyForReview:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' />\n <circle cx='6' cy='6' r='2' fill='currentColor' />\n </>\n );\n case SliceStatus.done:\n return (\n <>\n <circle cx='6' cy='6' r='5' stroke='currentColor' strokeWidth='1.5' fill='currentColor' fillOpacity='0.2' />\n <polyline points='3.5,6 5.2,7.8 8.5,4' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' strokeLinejoin='round' />\n </>\n );\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './MenuDropdown.css';\nimport React, { createContext, ReactNode, useContext, useEffect, useId, useMemo, useRef, useState } from 'react';\nimport { AnchoredOverlay } from '../Tooltips';\nimport { useDismissOnOutsidePointer } from '../Pickers/useDismissOnOutsidePointer';\nimport { Guid } from '@cratis/fundamentals';\n\nexport interface MenuDropdownItem {\n\n id: string | Guid;\n\n label?: string;\n\n description?: string;\n\n icon?: React.ReactNode;\n\n onClick?: () => void;\n\n keepOpen?: boolean;\n\n items?: MenuDropdownItem[];\n\n isSeparator?: boolean;\n\n // Renders the item as a non-interactive section header.\n isHeader?: boolean;\n\n // When defined, renders a radio-like check indicator reflecting the checked state.\n checked?: boolean;\n\n // Renders the item greyed out and non-interactive.\n disabled?: boolean;\n\n // Shown as the item's tooltip — use it to say why a disabled item cannot be used.\n tooltip?: string;\n}\n\nexport interface MenuDropdownProps {\n\n trigger: React.ReactNode;\n\n items: MenuDropdownItem[];\n\n align?: 'left' | 'right';\n\n onClose?: () => void;\n}\n\ninterface MenuDropdownOpenStateContextValue {\n openMenuId: string | undefined;\n setOpenMenuId: React.Dispatch<React.SetStateAction<string | undefined>>;\n}\n\nconst MenuDropdownOpenStateContext = createContext<MenuDropdownOpenStateContextValue | undefined>(undefined);\n\nexport interface MenuDropdownOpenProviderProps {\n children: ReactNode;\n}\n\nexport const toggleOpenMenuId = (currentOpenMenuId: string | undefined, menuId: string): string | undefined =>\n currentOpenMenuId === menuId ? undefined : menuId;\n\nexport const closeOpenMenuId = (currentOpenMenuId: string | undefined, menuId: string): string | undefined =>\n currentOpenMenuId === menuId ? undefined : currentOpenMenuId;\n\nexport const MenuDropdownOpenProvider: React.FC<MenuDropdownOpenProviderProps> = ({ children }) => {\n const [openMenuId, setOpenMenuId] = useState<string>();\n\n return (\n <MenuDropdownOpenStateContext.Provider value={{ openMenuId, setOpenMenuId }}>\n {children}\n </MenuDropdownOpenStateContext.Provider>\n );\n};\n\nexport const MenuDropdown: React.FC<MenuDropdownProps> = ({ trigger, items, align = 'right', onClose }) => {\n const context = useContext(MenuDropdownOpenStateContext);\n const menuId = useId();\n const [localOpen, setLocalOpen] = useState(false);\n const [openSubmenuId, setOpenSubmenuId] = useState<string | undefined>();\n const containerRef = useRef<HTMLDivElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n const open = context ? context.openMenuId === menuId : localOpen;\n const previousOpenRef = useRef(open);\n\n useEffect(() => {\n if (previousOpenRef.current && !open) {\n onClose?.();\n setOpenSubmenuId(undefined);\n }\n previousOpenRef.current = open;\n }, [open, onClose]);\n\n const setOpen = (next: boolean) => {\n if (context) {\n if (next) {\n context.setOpenMenuId(current => toggleOpenMenuId(current, menuId));\n } else {\n context.setOpenMenuId(current => closeOpenMenuId(current, menuId));\n }\n return;\n }\n setLocalOpen(next);\n };\n\n const close = () => setOpen(false);\n\n const outsideRefs = useMemo(() => [containerRef, menuRef], []);\n useDismissOnOutsidePointer(outsideRefs, close, open);\n\n const renderMenuItems = (itemList: MenuDropdownItem[]) => {\n return itemList.map(item => {\n if (item.isSeparator) {\n return <div key={item.id.toString()} className='event-modeling-menu-dropdown-separator' />;\n }\n\n if (item.isHeader) {\n return (\n <div key={item.id.toString()} className='event-modeling-menu-dropdown-header'>\n {item.label}\n </div>\n );\n }\n\n const hasSubmenu = item.items && item.items.length > 0;\n const isSubmenuOpen = openSubmenuId === item.id.toString();\n\n return (\n <div key={item.id.toString()} className='event-modeling-menu-dropdown-item-wrapper'>\n <button\n className={`event-modeling-menu-dropdown-option ${hasSubmenu ? 'event-modeling-menu-dropdown-option--has-submenu' : ''}`}\n disabled={item.disabled}\n title={item.tooltip}\n onClick={() => {\n if (item.disabled) return;\n if (hasSubmenu) {\n setOpenSubmenuId(isSubmenuOpen ? undefined : item.id.toString());\n } else {\n if (!item.keepOpen) close();\n item.onClick?.();\n }\n }}\n >\n {item.icon && (\n <span className='event-modeling-menu-dropdown-option-icon'>{item.icon}</span>\n )}\n <span className='event-modeling-menu-dropdown-option-text'>\n {item.label && <span className='event-modeling-menu-dropdown-option-label'>{item.label}</span>}\n {item.description && (\n <span className='event-modeling-menu-dropdown-option-desc'>{item.description}</span>\n )}\n </span>\n {item.checked !== undefined && (\n <span className='event-modeling-menu-dropdown-option-check'>\n {item.checked && <i className='pi pi-check' />}\n </span>\n )}\n {hasSubmenu && (\n <span className={`event-modeling-menu-dropdown-option-arrow ${isSubmenuOpen ? 'event-modeling-menu-dropdown-option-arrow--open' : ''}`}>\n <i className='pi pi-chevron-right' />\n </span>\n )}\n </button>\n {hasSubmenu && isSubmenuOpen && (\n <div className={`event-modeling-menu-dropdown-submenu ${align === 'right' ? 'event-modeling-menu-dropdown-submenu--left' : ''}`}>\n {renderMenuItems(item.items!)}\n </div>\n )}\n </div>\n );\n });\n };\n\n return (\n <div ref={containerRef} className='event-modeling-menu-dropdown'>\n <div\n className='event-modeling-menu-dropdown-trigger'\n onPointerDown={(event) => event.stopPropagation()}\n onClick={(event) => { event.stopPropagation(); setOpen(!open); }}\n >\n {trigger}\n </div>\n {/* The panel portals to <body> anchored to the trigger, so it floats above everything\n and is never clipped by the slice columns' paint containment. */}\n <AnchoredOverlay anchorRef={containerRef} open={open} side='below' align={align}>\n <div ref={menuRef} className='event-modeling-menu-dropdown-menu'>\n {renderMenuItems(items)}\n </div>\n </AnchoredOverlay>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { SliceStatus } from '../Model';\n\n// Shows the picked status at once and goes back to the one shown before when the consumer says the\n// change did not land.\nexport const changeSliceStatus = async (\n previous: SliceStatus,\n picked: SliceStatus,\n report: (status: SliceStatus) => Promise<boolean | void> | void,\n show: (status: SliceStatus) => void): Promise<void> => {\n show(picked);\n if (await report(picked) === false) show(previous);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceStatus } from '../Model';\nimport type { EventModelMessages } from '../Messages';\n\n// The order statuses are offered in: a drafted slice is analyzed before it is handed on to implementation.\nexport const sliceStatusWorkflowOrder: readonly SliceStatus[] = [\n SliceStatus.notStarted,\n SliceStatus.draft,\n SliceStatus.analysis,\n SliceStatus.readyForImplementation,\n SliceStatus.inProgress,\n SliceStatus.readyForReview,\n SliceStatus.done,\n];\n\nexport const sliceStatusColor = (status: SliceStatus): string => {\n switch (status) {\n case SliceStatus.notStarted: return 'rgba(255,255,255,0.35)';\n case SliceStatus.draft: return '#9333ea';\n case SliceStatus.analysis: return '#6366f1';\n case SliceStatus.readyForImplementation: return '#06b6d4';\n case SliceStatus.inProgress: return '#3b82f6';\n case SliceStatus.readyForReview: return '#f59e0b';\n case SliceStatus.done: return '#10b981';\n }\n};\n\nexport const sliceStatusLabel = (status: SliceStatus, messages: EventModelMessages): string => {\n switch (status) {\n case SliceStatus.notStarted: return messages.statuses.notStarted;\n case SliceStatus.draft: return messages.statuses.draft;\n case SliceStatus.analysis: return messages.statuses.analysis;\n case SliceStatus.readyForImplementation: return messages.statuses.readyForImplementation;\n case SliceStatus.inProgress: return messages.statuses.inProgress;\n case SliceStatus.readyForReview: return messages.statuses.readyForReview;\n case SliceStatus.done: return messages.statuses.done;\n }\n};\n\n// The CSS modifier a status is styled by.\nexport const sliceStatusName = (status: SliceStatus): string => SliceStatus[status];\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceStatusPicker.css';\nimport { useEffect, useState } from 'react';\nimport { SliceStatus } from '../Model';\nimport { useBoard } from '../Board';\nimport { MenuDropdown, type MenuDropdownItem } from '../Menus';\nimport { SliceStatusIcon } from './SliceStatusIcon';\nimport { changeSliceStatus } from './changeSliceStatus';\nimport { sliceStatusColor, sliceStatusLabel, sliceStatusName, sliceStatusWorkflowOrder } from './sliceStatuses';\n\nexport interface SliceStatusPickerProps {\n status: SliceStatus;\n // Picking a status shows it at once. Resolving to false says the change did not land, and the\n // picker goes back to the status it showed before. Without it the status is only drawn.\n onStatusChanged?: (status: SliceStatus) => Promise<boolean | void> | void;\n // The statuses that may be picked; the others are shown disabled. Every status when omitted.\n selectable?: readonly SliceStatus[];\n // Why a status that is not selectable cannot be picked.\n unselectableReason?: string;\n}\n\nexport const SliceStatusPicker = ({ status, onStatusChanged, selectable = sliceStatusWorkflowOrder, unselectableReason }: SliceStatusPickerProps) => {\n const { readOnly, messages } = useBoard();\n const [shown, setShown] = useState(status);\n\n // Follows the status it is given, which also reconciles a change shown optimistically with the\n // one that eventually arrives.\n useEffect(() => setShown(status), [status]);\n\n const title = `${messages.statuses.titlePrefix} ${sliceStatusLabel(shown, messages)}`;\n const className = `event-modeling-slice-status-icon event-modeling-slice-status-icon--${sliceStatusName(shown)}`;\n\n if (readOnly || !onStatusChanged) {\n return (\n <span className={`${className} event-modeling-slice-status-icon--readonly`} title={title} aria-label={sliceStatusLabel(shown, messages)}>\n <SliceStatusIcon status={shown} />\n </span>\n );\n }\n\n const change = (next: SliceStatus) => changeSliceStatus(shown, next, onStatusChanged, setShown);\n\n const items: MenuDropdownItem[] = sliceStatusWorkflowOrder.map(option => ({\n id: sliceStatusName(option),\n label: sliceStatusLabel(option, messages),\n icon: <StatusOptionMark status={option} checked={option === shown} />,\n disabled: !selectable.includes(option),\n tooltip: selectable.includes(option) ? undefined : unselectableReason,\n onClick: () => change(option),\n }));\n\n return (\n <MenuDropdown\n trigger={\n <button className={className} title={title} aria-label={messages.statuses.change}>\n <SliceStatusIcon status={shown} />\n </button>\n }\n items={items}\n align='left'\n />\n );\n};\n\nconst StatusOptionMark = ({ status, checked }: { status: SliceStatus; checked: boolean }) => {\n const color = sliceStatusColor(status);\n return (\n <svg width='12' height='12' viewBox='0 0 12 12' aria-hidden='true'>\n <circle cx='6' cy='6' r='5' fill={color} fillOpacity='0.25' stroke={color} strokeWidth='1.5' />\n {checked && <polyline points='3,6 5,8 9,4' stroke={color} strokeWidth='1.4' strokeLinecap='round' strokeLinejoin='round' fill='none' />}\n </svg>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { MenuDropdown, type MenuDropdownItem } from '../Menus';\nimport { useEventModelMessages } from '../Messages';\nimport type { ModuleHeaderAction } from './ModuleHeaderAction';\n\nexport interface ModuleHeaderMenuProps {\n moduleId: Guid;\n actions: readonly ModuleHeaderAction[];\n onAddModule?: () => void;\n onAddFeature?: () => void;\n kind: 'options' | 'add';\n}\n\nexport const ModuleHeaderMenu = ({ moduleId, actions, onAddModule, onAddFeature, kind }: ModuleHeaderMenuProps) => {\n const messages = useEventModelMessages();\n const triggerRef = useRef<HTMLButtonElement>(null);\n const [selected, setSelected] = useState<string>();\n if (!actions.length && !onAddModule && !onAddFeature) return null;\n const activate = (action: ModuleHeaderAction) => {\n const host = triggerRef.current?.getBoundingClientRect();\n if (host) action.onActivate(moduleId, host);\n };\n const itemsFor = (entries: readonly ModuleHeaderAction[]): MenuDropdownItem[] => entries.map(action => ({\n id: action.id, label: action.label + (action.items ? ' ›' : ''), description: action.description,\n icon: action.icon, disabled: action.disabled, tooltip: action.tooltip, isSeparator: action.isSeparator,\n keepOpen: !!action.items, onClick: () => action.items ? setSelected(action.id) : activate(action),\n }));\n const items: MenuDropdownItem[] = selected ? [\n { id: 'back', label: messages.features.back, keepOpen: true, onClick: () => setSelected(undefined) },\n ...itemsFor(actions.find(action => action.id === selected)?.items ?? []),\n ] : [\n ...(onAddModule ? [{ id: 'module', label: messages.modules.addModule, description: messages.modules.addModuleDescription, onClick: onAddModule }] : []),\n ...(onAddFeature ? [{ id: 'feature', label: messages.modules.addFeature, description: messages.modules.addFeatureDescription, onClick: onAddFeature }] : []),\n ...itemsFor(actions),\n ];\n const label = kind === 'add' ? messages.modules.add : messages.modules.options;\n return <MenuDropdown trigger={<button ref={triggerRef} type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={label} aria-label={label}>{kind === 'add' ? '+' : <svg width='13' height='13' viewBox='0 0 14 14' fill='none' aria-hidden='true'>\n <line x1='2' y1='3.5' x2='12' y2='3.5' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n <line x1='2' y1='7' x2='12' y2='7' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n <line x1='2' y1='10.5' x2='12' y2='10.5' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n </svg>}</button>}\n items={items} align='right' onClose={() => setSelected(undefined)} />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useState } from 'react';\nimport type { FeatureHeaderSuggestion } from './FeatureHeaderSuggestion';\nimport './FeatureSuggestions.css';\n\nconst Suggestion = ({ suggestion }: { suggestion: FeatureHeaderSuggestion }) => {\n const [isAccepting, setIsAccepting] = useState(false);\n const accept = async () => {\n if (isAccepting) return;\n setIsAccepting(true);\n try {\n await suggestion.onAccept();\n } finally {\n setIsAccepting(false);\n }\n };\n return <span className='prediction-ghost' data-suggestion-name={suggestion.name}>\n <button type='button' className='prediction-ghost__accept' disabled={isAccepting}\n aria-label={suggestion.acceptLabel} title={suggestion.rationale ?? suggestion.acceptLabel}\n onClick={() => { void accept(); }}>\n <i className={isAccepting ? 'pi pi-spinner pi-spin' : 'pi pi-bolt'} style={{ fontSize: 9 }} aria-hidden='true' />\n <span>{suggestion.name}</span>\n </button>\n <button type='button' className='prediction-ghost__discard' aria-label={suggestion.discardLabel}\n title={suggestion.discardLabel} onClick={suggestion.onDiscard}>×</button>\n </span>;\n};\n\nexport const FeatureSuggestions = ({ suggestions }: { suggestions: readonly FeatureHeaderSuggestion[] }) =>\n <>{suggestions.map(suggestion => <Suggestion key={suggestion.id} suggestion={suggestion} />)}</>;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Headers/IconButton.css';\nimport '../Rows/AddButton.css';\nimport type { CSSProperties } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceStatus } from '../Model';\nimport { useBoard } from '../Board';\nimport { DetailsToggle, PillHeader } from '../Headers';\nimport { useHeaderDragIntent, type HeaderDragStart } from '../HeaderDragging';\nimport { useEventModelPresentation } from '../Presentation';\nimport { SliceStatusPicker } from '../Statuses';\nimport { ModuleHeaderMenu } from './ModuleHeaderMenu';\nimport { FeatureSuggestions } from '../Features/FeatureSuggestions';\n\nexport interface ModuleHeaderProps {\n moduleId: Guid;\n name: string;\n height: number;\n collapsed: boolean;\n onToggleCollapse?: () => void;\n onAddModule?: () => void;\n onAddFeature?: () => void;\n // Renaming exists only when the board is editable and this is supplied.\n onRenamed?: (moduleId: Guid, name: string) => void;\n // Says why a name cannot be used, such as one another module already has.\n validateName?: (name: string) => string | undefined;\n // The status of the module as a whole, shown but never picked here. Nothing is shown when undefined.\n status?: SliceStatus;\n // The details toggle is drawn when onToggleDetails is supplied.\n detailsVisible?: boolean;\n onToggleDetails?: () => void;\n // The header can be picked up only when the board is editable and this is supplied.\n onDragStart?: (start: HeaderDragStart) => void;\n // Shown on the header when something done to the module failed.\n error?: string;\n}\n\nconst background = 'rgba(255,255,255,0.05)';\nconst border = '1px solid rgba(255,255,255,0.10)';\nconst labelStyle: CSSProperties = { fontSize: 13, fontWeight: 600, color: 'rgba(255,255,255,0.80)', textAlign: 'center' };\n\nexport const ModuleHeader = ({\n moduleId,\n name,\n height,\n collapsed,\n onToggleCollapse,\n onAddModule,\n onAddFeature,\n onRenamed,\n validateName,\n status,\n detailsVisible = false,\n onToggleDetails,\n onDragStart,\n error,\n}: ModuleHeaderProps) => {\n const board = useBoard();\n const { showStatuses = true } = useEventModelPresentation();\n const dragHandlers = useHeaderDragIntent(!board.readOnly && !collapsed ? onDragStart : undefined);\n const renamed = board.readOnly ? undefined : onRenamed;\n const actions = board.actions;\n\n return (\n <PillHeader\n variant='module'\n collapsed={collapsed}\n onToggle={onToggleCollapse}\n leadingContent={!board.readOnly && (actions.moduleHeaderLeading ?? []).map(action => <button\n key={action.id} type='button' className='event-modeling-grid-icon-btn'\n title={action.label} aria-label={action.label} disabled={action.disabled}\n onClick={event => action.onActivate(moduleId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}{action.indicator && <span className='event-modeling-feature-chat-dot' aria-hidden='true' />}</button>)}\n label={name}\n onRenameLabel={value => renamed?.(moduleId, value)}\n labelReadOnly={!renamed}\n validateLabel={validateName}\n labelStyle={labelStyle}\n background={background}\n border={border}\n height={height}\n draggable={dragHandlers !== undefined}\n onPointerDown={dragHandlers?.onPointerDown}\n onPointerMove={dragHandlers?.onPointerMove}\n onPointerUp={dragHandlers?.onPointerUp}\n error={error}\n >\n {showStatuses && status !== undefined && <SliceStatusPicker status={status} />}\n {!board.readOnly && onToggleDetails && <DetailsToggle visible={detailsVisible} onToggle={onToggleDetails} />}\n {!board.readOnly && <ModuleHeaderMenu kind='options' moduleId={moduleId} actions={actions.moduleHeaderMenu ?? []} />}\n {!board.readOnly && (actions.moduleHeaderAfterMenu ?? []).map(action => <button\n key={action.id} type='button' className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={action.label} aria-label={action.label} disabled={action.disabled}\n onClick={event => action.onActivate(moduleId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}</button>)}\n {!board.readOnly && <FeatureSuggestions suggestions={actions.moduleHeaderSuggestions ?? []} />}\n {!board.readOnly && <ModuleHeaderMenu kind='add' moduleId={moduleId} actions={actions.moduleHeaderAdd ?? []}\n onAddModule={onAddModule} onAddFeature={onAddFeature} />}\n </PillHeader>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { headerDropIndex, reorderedIds, type HeaderDragStart, type HeaderDragState } from '../HeaderDragging';\nimport type { ModulesReordered } from './ModulesReordered';\n\nexport interface ModuleDragState extends HeaderDragState {\n moduleId: Guid;\n sourceIndex: number;\n currentY: number;\n // The gap the module would land in right now: n is before the nth module of the collection.\n dropIndex: number;\n}\n\nexport type ModuleDragStart = (moduleId: Guid, label: string, start: HeaderDragStart) => void;\n\nexport interface ModuleDrag {\n moduleDrag?: ModuleDragState;\n // Undefined when nothing can be told about a move, so no module header offers to be picked up.\n handleModuleDragStart?: ModuleDragStart;\n}\n\n// The gap a pointer at clientX is over among the given modules, in the collection's own order. Only this\n// collection's modules count: numbering the gaps across every module on the board put a drag to either end\n// of a collection that is not the leftmost one into a gap belonging to somebody else.\nfunction dropIndexAt(moduleIds: readonly Guid[], clientX: number): number {\n const extents = moduleIds\n .map(id => document.querySelector<HTMLElement>(`[data-module-id=\"${id.toString()}\"]`))\n .filter((element): element is HTMLElement => element !== null)\n .map(element => element.getBoundingClientRect());\n return headerDropIndex(extents, clientX);\n}\n\n// Dragging a module to another place among the modules of its collection.\n// moduleIds: the collection's modules in their current order.\nexport function useModuleDrag(collectionId: Guid, moduleIds: readonly Guid[], onModulesReordered?: ModulesReordered): ModuleDrag {\n const board = useBoard();\n const [moduleDrag, setModuleDrag] = useState<ModuleDragState | undefined>(undefined);\n const moduleDragRef = useRef(moduleDrag);\n moduleDragRef.current = moduleDrag;\n const moduleIdsRef = useRef(moduleIds);\n moduleIdsRef.current = moduleIds;\n const collectionIdRef = useRef(collectionId);\n collectionIdRef.current = collectionId;\n const onModulesReorderedRef = useRef(onModulesReordered);\n onModulesReorderedRef.current = onModulesReordered;\n\n const handleModuleDragStart = useCallback<ModuleDragStart>((moduleId, label, start) => {\n const sourceIndex = moduleIdsRef.current.findIndex(id => id.equals(moduleId));\n if (sourceIndex === -1) return;\n setModuleDrag({\n moduleId,\n sourceIndex,\n ghostLabel: label,\n ghostWidth: start.width,\n ghost: start.ghost,\n currentX: start.clientX,\n currentY: start.clientY,\n dropIndex: sourceIndex,\n headerY: start.headerY,\n zoom: start.zoom,\n });\n }, []);\n\n const dragging = moduleDrag !== undefined;\n useEffect(() => {\n if (!dragging) return;\n\n const handlePointerMove = (event: PointerEvent) => {\n setModuleDrag(previous => previous && {\n ...previous,\n currentX: event.clientX,\n currentY: event.clientY,\n dropIndex: dropIndexAt(moduleIdsRef.current, event.clientX),\n });\n };\n\n const handlePointerUp = () => {\n const drag = moduleDragRef.current;\n setModuleDrag(undefined);\n if (!drag) return;\n const ordered = reorderedIds(moduleIdsRef.current, drag.sourceIndex, drag.dropIndex);\n if (ordered) onModulesReorderedRef.current?.(collectionIdRef.current, ordered);\n };\n\n window.addEventListener('pointermove', handlePointerMove);\n window.addEventListener('pointerup', handlePointerUp);\n return () => {\n window.removeEventListener('pointermove', handlePointerMove);\n window.removeEventListener('pointerup', handlePointerUp);\n };\n }, [dragging]);\n\n const canDrag = !board.readOnly && onModulesReordered !== undefined;\n return { moduleDrag, handleModuleDragStart: canDrag ? handleModuleDragStart : undefined };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface ModuleAreaItem {\n id: Guid;\n name: string;\n collapsed: boolean;\n}\n\nexport interface ModuleAreaState<T extends ModuleAreaItem> {\n snapshot: T[];\n modules: T[];\n additions: T[];\n order?: Guid[];\n collapses: ReadonlyMap<string, boolean>;\n renames: ReadonlyMap<string, string>;\n collapseBarriers: ReadonlyMap<string, boolean>;\n renameBarriers: ReadonlyMap<string, string>;\n orderBarrier?: Guid[];\n}\n\nexport const createModuleAreaState = <T extends ModuleAreaItem>(modules: T[]): ModuleAreaState<T> => ({\n snapshot: modules, modules, additions: [], collapses: new Map(), renames: new Map(),\n collapseBarriers: new Map(), renameBarriers: new Map(),\n});\n\nconst sameOrder = (modules: readonly ModuleAreaItem[], ids: readonly Guid[]) =>\n modules.length === ids.length && modules.every((module, index) => module.id.equals(ids[index]));\n\nexport function reconcileModules<T extends ModuleAreaItem>(state: ModuleAreaState<T>, snapshot: T[]): ModuleAreaState<T> {\n const additions = state.additions.filter(added => !snapshot.some(module => module.id.equals(added.id)));\n // A -> B -> A cannot be acknowledged by the initial A snapshot. Without a sequence number,\n // require a snapshot containing B before accepting a subsequent snapshot containing A.\n const collapseBarriers = new Map([...state.collapseBarriers].filter(([id, value]) =>\n !snapshot.some(module => module.id.toString() === id && module.collapsed === value)));\n const renameBarriers = new Map([...state.renameBarriers].filter(([id, name]) =>\n !snapshot.some(module => module.id.toString() === id && module.name === name)));\n const orderBarrier = state.orderBarrier && sameOrder(snapshot, state.orderBarrier) ? undefined : state.orderBarrier;\n const collapses = new Map([...state.collapses].filter(([id, value]) =>\n state.collapseBarriers.has(id) || !snapshot.some(module => module.id.toString() === id && module.collapsed === value)));\n const renames = new Map([...state.renames].filter(([id, name]) =>\n state.renameBarriers.has(id) || !snapshot.some(module => module.id.toString() === id && module.name === name)));\n const merged = [...snapshot, ...additions].map(module => ({ ...module,\n collapsed: collapses.get(module.id.toString()) ?? module.collapsed,\n name: renames.get(module.id.toString()) ?? module.name,\n }));\n const modules = state.order ? orderModules(merged, state.order) : merged;\n const order = state.order && !state.orderBarrier && sameOrder(snapshot, modules.map(module => module.id))\n ? undefined : state.order;\n return { snapshot, modules, additions, order, collapses, renames, collapseBarriers, renameBarriers, orderBarrier };\n}\n\nexport function setModuleCollapse<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid, collapsed: boolean): ModuleAreaState<T> {\n const key = id.toString();\n const prior = state.collapses.get(key);\n const collapseBarriers = new Map(state.collapseBarriers);\n if (prior !== undefined && state.snapshot.some(module => module.id.equals(id) && module.collapsed === collapsed)) {\n collapseBarriers.set(key, prior);\n }\n return { ...updateModule(state, id, module => ({ ...module, collapsed })),\n collapses: new Map(state.collapses).set(key, collapsed), collapseBarriers };\n}\n\nexport function setModuleRename<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid, name: string): ModuleAreaState<T> {\n const key = id.toString();\n const prior = state.renames.get(key);\n const renameBarriers = new Map(state.renameBarriers);\n if (prior !== undefined && state.snapshot.some(module => module.id.equals(id) && module.name === name)) {\n renameBarriers.set(key, prior);\n }\n return { ...updateModule(state, id, module => ({ ...module, name })),\n renames: new Map(state.renames).set(key, name), renameBarriers };\n}\n\nexport function setModuleOrder<T extends ModuleAreaItem>(state: ModuleAreaState<T>, ids: Guid[]): ModuleAreaState<T> {\n const orderBarrier = state.order && sameOrder(state.snapshot, ids) ? state.order : state.orderBarrier;\n return { ...state, modules: orderModules(state.modules, ids), order: ids, orderBarrier };\n}\n\nexport function revertModuleCollapse<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid): ModuleAreaState<T> {\n const collapses = new Map(state.collapses);\n collapses.delete(id.toString());\n const collapseBarriers = new Map(state.collapseBarriers);\n collapseBarriers.delete(id.toString());\n return reconcileModules({ ...state, collapses, collapseBarriers }, state.snapshot);\n}\n\nexport function revertModuleRename<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid): ModuleAreaState<T> {\n const renames = new Map(state.renames);\n renames.delete(id.toString());\n const renameBarriers = new Map(state.renameBarriers);\n renameBarriers.delete(id.toString());\n return reconcileModules({ ...state, renames, renameBarriers }, state.snapshot);\n}\n\nexport function revertModuleOrder<T extends ModuleAreaItem>(state: ModuleAreaState<T>, priorOrder?: Guid[]): ModuleAreaState<T> {\n return reconcileModules({ ...state, order: priorOrder, orderBarrier: undefined }, state.snapshot);\n}\n\nexport function orderModules<T extends ModuleAreaItem>(modules: T[], ids: readonly Guid[]): T[] {\n return [...ids.flatMap(id => modules.filter(module => module.id.equals(id))),\n ...modules.filter(module => !ids.some(id => id.equals(module.id)))];\n}\n\nexport function updateModule<T extends ModuleAreaItem>(state: ModuleAreaState<T>, id: Guid, change: (module: T) => T): ModuleAreaState<T> {\n return { ...state, modules: state.modules.map(module => module.id.equals(id) ? change(module) : module) };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport async function persistModuleChange(\n execute: () => Promise<boolean>, revert: () => void, onPersistenceError: (error: unknown) => void,\n): Promise<void> {\n let succeeded: boolean;\n try {\n succeeded = await execute();\n } catch (error) {\n revert();\n onPersistenceError(error);\n return;\n }\n if (succeeded !== true) revert();\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { HeaderDragGhost, type HeaderDragStart } from '../HeaderDragging';\nimport { boardMetrics } from '../Layout';\nimport { ModuleDropIndicator } from './ModuleDropIndicator';\nimport { useModuleDrag } from './useModuleDrag';\nimport { createModuleAreaState, reconcileModules, revertModuleCollapse, revertModuleOrder, revertModuleRename, setModuleCollapse, setModuleOrder, setModuleRename, type ModuleAreaItem, type ModuleAreaState } from './moduleAreaState';\nimport { persistModuleChange } from './persistModuleChange';\n\nexport interface ModulesAreaProps<T extends ModuleAreaItem> {\n collectionId: Guid;\n initialModules: T[];\n onAddModule?: () => Promise<T | undefined>;\n onModulesReordered?: (orderedIds: Guid[]) => Promise<boolean>;\n onCollapseChanged?: (moduleId: Guid, collapsed: boolean) => Promise<boolean>;\n onRenameModule?: (moduleId: Guid, name: string) => Promise<boolean>;\n onPersistenceError?: (error: unknown) => void;\n renderModule: (module: T, options: {\n index: number;\n dragging: boolean;\n onDragStart?: (start: HeaderDragStart) => void;\n onAddModule?: () => void;\n onToggleCollapse?: () => void;\n onRenamed?: (name: string) => void;\n }) => ReactNode;\n onModulesChanged?: (modules: T[]) => void;\n}\n\nexport function ModulesArea<T extends ModuleAreaItem>({\n collectionId, initialModules, onAddModule, onModulesReordered, onCollapseChanged, onRenameModule,\n onPersistenceError, renderModule, onModulesChanged,\n}: ModulesAreaProps<T>) {\n const { readOnly } = useBoard();\n const reportError = useCallback((error: unknown) => {\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n }, [onPersistenceError]);\n const stateRef = useRef<ModuleAreaState<T>>(createModuleAreaState(initialModules));\n const [state, setState] = useState(stateRef.current);\n const adding = useRef(false);\n const [isAdding, setIsAdding] = useState(false);\n const busyIds = useRef(new Set<string>());\n const [busyModuleIds, setBusyModuleIds] = useState<ReadonlySet<string>>(new Set());\n const reordering = useRef(false);\n const [isReordering, setIsReordering] = useState(false);\n const markBusy = (id: string, busy: boolean) => {\n if (busy) busyIds.current.add(id);\n else busyIds.current.delete(id);\n setBusyModuleIds(new Set(busyIds.current));\n };\n const apply = useCallback((transition: (previous: ModuleAreaState<T>) => ModuleAreaState<T>) => {\n const next = transition(stateRef.current);\n stateRef.current = next;\n setState(next);\n onModulesChanged?.(next.modules);\n }, [onModulesChanged]);\n useEffect(() => {\n if (initialModules !== stateRef.current.snapshot) apply(previous => reconcileModules(previous, initialModules));\n }, [initialModules, apply]);\n\n const add = useCallback(async () => {\n if (readOnly || !onAddModule || adding.current) return;\n adding.current = true;\n setIsAdding(true);\n try {\n const added = await onAddModule();\n if (added) apply(previous => reconcileModules({ ...previous,\n additions: [...previous.additions, added],\n }, previous.snapshot));\n } catch (error) {\n reportError(error);\n } finally {\n adding.current = false;\n setIsAdding(false);\n }\n }, [readOnly, onAddModule, reportError, apply]);\n const toggle = useCallback(async (module: T) => {\n const id = module.id.toString();\n if (!onCollapseChanged || busyIds.current.has(id)) return;\n markBusy(id, true);\n const collapsed = !module.collapsed;\n apply(previous => setModuleCollapse(previous, module.id, collapsed));\n try {\n await persistModuleChange(() => onCollapseChanged(module.id, collapsed),\n () => apply(previous => revertModuleCollapse(previous, module.id)), reportError);\n } finally { markBusy(id, false); }\n }, [onCollapseChanged, reportError, apply]);\n const rename = useCallback(async (module: T, name: string) => {\n const id = module.id.toString();\n if (readOnly || !onRenameModule || busyIds.current.has(id)) return;\n markBusy(id, true);\n apply(previous => setModuleRename(previous, module.id, name));\n try {\n await persistModuleChange(() => onRenameModule(module.id, name),\n () => apply(previous => revertModuleRename(previous, module.id)), reportError);\n } finally { markBusy(id, false); }\n }, [readOnly, onRenameModule, reportError, apply]);\n const reorder = useCallback(async (_collectionId: Guid, ids: Guid[]) => {\n if (readOnly || !onModulesReordered || reordering.current) return;\n reordering.current = true;\n setIsReordering(true);\n const priorOrder = stateRef.current.order;\n apply(previous => setModuleOrder(previous, ids));\n try {\n await persistModuleChange(() => onModulesReordered(ids),\n () => apply(previous => revertModuleOrder(previous, priorOrder)), reportError);\n } finally {\n reordering.current = false;\n setIsReordering(false);\n }\n }, [apply, onModulesReordered, reportError, readOnly]);\n const { moduleDrag, handleModuleDragStart } = useModuleDrag(collectionId, state.modules.map(module => module.id), onModulesReordered && !isReordering ? reorder : undefined);\n\n return <>\n <HeaderDragGhost drag={moduleDrag} headerHeight={boardMetrics.headerHeight} />\n {state.modules.map((module, index) => <div key={module.id.toString()} style={{ display: 'contents' }}>\n {moduleDrag?.dropIndex === index && <ModuleDropIndicator />}\n {renderModule(module, {\n index, dragging: moduleDrag?.moduleId.equals(module.id) ?? false,\n onDragStart: !busyModuleIds.has(module.id.toString()) && handleModuleDragStart\n ? start => handleModuleDragStart(module.id, module.name, start) : undefined,\n onAddModule: !readOnly && !isAdding && onAddModule ? () => { void add(); } : undefined,\n // Collapsing changes nothing but how the board is drawn, so a read-only board allows it too.\n onToggleCollapse: !busyModuleIds.has(module.id.toString()) && onCollapseChanged\n ? () => { void toggle(module); } : undefined,\n onRenamed: !readOnly && !busyModuleIds.has(module.id.toString()) && onRenameModule\n ? name => { void rename(module, name); } : undefined,\n })}\n </div>)}\n {moduleDrag?.dropIndex === state.modules.length && <ModuleDropIndicator />}\n </>;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { boardMetrics } from '../Layout';\nimport { computePillLabelMinWidth, defaultMeasureLabelWidth, type MeasureLabelWidth } from '../Geometry';\n\n// The module header spans its visible feature columns, but cannot be narrower than its label or\n// the empty-feature placeholder. The widths passed in already account for collapsed features.\nexport function moduleWidth(featureWidths: readonly number[], name: string, measure: MeasureLabelWidth = defaultMeasureLabelWidth): number {\n const contents = featureWidths.length ? featureWidths.reduce((width, featureWidth, index) =>\n width + (index ? boardMetrics.sliceGap : 0) + featureWidth, 0) : Math.round(boardMetrics.sliceWidth * 1.5);\n return Math.max(contents, computePillLabelMinWidth(name, measure));\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Headers/HeaderCell.css';\nimport type { ReactNode } from 'react';\n\nexport interface ModuleHeaderCellProps {\n width: number;\n // A collapsed module's cell takes the width of its pill rather than the width it is given.\n collapsed: boolean;\n children?: ReactNode;\n}\n\n// The cell a module's header, and anything the consumer puts under it, sits in.\nexport const ModuleHeaderCell = ({ width, collapsed, children }: ModuleHeaderCellProps) => (\n <div\n className={`event-modeling-grid-header-cell-wrapper${collapsed ? ' event-modeling-grid-header-cell-wrapper--module-collapsed' : ''}`}\n style={{ width: collapsed ? undefined : width }}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ModulePlaceholder.css';\n\nexport interface ModulePlaceholderProps {\n width: number;\n height: number;\n featureWidths: readonly number[];\n}\n\nexport const ModulePlaceholder = ({ width, height, featureWidths }: ModulePlaceholderProps) =>\n <div className='event-modeling-module-placeholder' style={{ width, height }} aria-hidden='true'>\n {featureWidths.map((featureWidth, index) => <div key={index}\n className='event-modeling-module-placeholder__feature' style={{ width: featureWidth }} />)}\n </div>;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode, Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { boardMetrics } from '../Layout';\nimport { ModuleColumnFrame } from './ModuleColumnFrame';\nimport { ModuleHeaderCell } from './ModuleHeaderCell';\n\nexport interface ModuleSurfaceProps {\n moduleId: Guid;\n collectionId: Guid;\n index: number;\n width: number;\n collapsed: boolean;\n dragging?: boolean;\n frameRef?: Ref<HTMLDivElement>;\n header: ReactNode;\n template?: ReactNode;\n content: ReactNode;\n}\n\nexport const ModuleSurface = ({ moduleId, collectionId, index, width, collapsed, dragging,\n frameRef, header, template, content }: ModuleSurfaceProps) =>\n <ModuleColumnFrame ref={frameRef} moduleId={moduleId} collectionId={index === 0 ? collectionId : undefined}\n marginLeft={index ? boardMetrics.sliceGap : 0} dragging={dragging}>\n <ModuleHeaderCell width={width} collapsed={collapsed}>\n {header}\n {!collapsed && template}\n </ModuleHeaderCell>\n {collapsed ? <div style={{ width: boardMetrics.collapsedModuleWidth }} /> : content}\n </ModuleColumnFrame>;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { computePillLabelMinWidth } from '../Geometry';\nimport { boardMetrics, computeGlobalRowHeights, sliceColumnWidth } from '../Layout';\nimport { ActorType, type Feature, type ModuleCollection, type Slice } from '../Model';\nimport { RowType } from '../Rows';\nimport { actorTypeOfRow } from '../RowLabels';\nimport { moduleWidth } from '../Modules';\n\n// A slice of a collection, with the module and feature it sits in.\nexport interface CollectionSlice {\n slice: Slice;\n moduleId: string;\n featureId: string;\n}\n\nexport const collectionSlices = (collection: ModuleCollection): CollectionSlice[] => {\n const visit = (moduleId: string, feature: Feature, seen: Set<string>): CollectionSlice[] => {\n if (seen.has(feature.id.toString())) return [];\n seen.add(feature.id.toString());\n return [\n ...feature.slices.map(slice => ({ slice, moduleId, featureId: feature.id.toString() })),\n ...feature.subFeatures.flatMap(child => visit(moduleId, child, seen)),\n ];\n };\n return collection.modules.flatMap(module => module.features.flatMap(feature => visit(module.id.toString(), feature, new Set())));\n};\n\n// Whether a slice shows the properties of its cards - which the presentation decides per board, module,\n// feature and slice.\nexport type SliceDetailsVisibility = (slice: CollectionSlice) => boolean;\n\nexport const collectionRows = (collection: ModuleCollection): RowType[] => [\n ...(collection.actors.some(actor => actor.actorType === ActorType.UIRole) ? [RowType.UI] : []),\n ...(collection.actors.some(actor => actor.actorType === ActorType.systemRole) ? [RowType.System] : []),\n ...(collection.actors.some(actor => actor.actorType === ActorType.chatRole) ? [RowType.Chat] : []),\n RowType.Interaction, RowType.Events,\n];\n\nexport const collectionRowHeights = (collection: ModuleCollection, showsDetails?: SliceDetailsVisibility) =>\n computeGlobalRowHeights(collectionSlices(collection).map(entry => ({ slice: entry.slice, showDetails: showsDetails?.(entry) ?? false })),\n collectionRows(collection));\n\nexport const collectionContentHeight = (collection: ModuleCollection, rows: readonly RowType[], heights: Readonly<Record<RowType, number>>): number =>\n rows.reduce((total, row) => {\n const actorType = actorTypeOfRow(row);\n const count = actorType === undefined ? 1 : Math.max(1, collection.actors.filter(actor => actor.actorType === actorType).length);\n return total + count * heights[row];\n }, 0);\n\nexport const featureWidth = (feature: Feature): number => {\n if (feature.collapsed) return feature.slices.length\n ? feature.slices.length * boardMetrics.collapsedSliceWidth + (feature.slices.length - 1) * boardMetrics.sliceGap\n : boardMetrics.collapsedFeatureWidth;\n if (!feature.slices.length && feature.subFeatures.length) return 0;\n const labelWidth = computePillLabelMinWidth(feature.name);\n if (!feature.slices.length) return Math.max(Math.round(boardMetrics.sliceWidth * 1.5), labelWidth);\n const slicesWidth = feature.slices.reduce((total, slice, index) => total + (index ? boardMetrics.sliceGap : 0)\n + (slice.collapsed ? boardMetrics.collapsedSliceWidth : sliceColumnWidth(slice)), 0);\n return Math.max(boardMetrics.minPillWidth, labelWidth, slicesWidth);\n};\n\nexport const featureColumns = (features: Feature[]): Feature[] => {\n const seen = new Set<string>();\n const visit = (feature: Feature): Feature[] => {\n if (seen.has(feature.id.toString())) return [];\n seen.add(feature.id.toString());\n return [feature, ...feature.subFeatures.flatMap(visit)];\n };\n return features.flatMap(visit);\n};\n\nexport const collectionModuleWidth = (name: string, features: Feature[]): number =>\n moduleWidth(featureColumns(features).map(featureWidth).filter(width => width > 0), name);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { rowLabelWidth } from '../Geometry';\nimport { boardMetrics } from '../Layout';\nimport type { Feature, ModuleCollection } from '../Model';\nimport { collectionModuleWidth, collectionRowHeights, collectionRows, collectionSlices, type SliceDetailsVisibility } from './collectionGridLayout';\n\nexport interface CollectionSizeEstimate {\n width: number;\n height: number;\n moduleWidths: number[];\n}\n\nconst featureDepth = (features: Feature[]): number => features.length === 0 ? 0\n : 1 + Math.max(...features.map(feature => featureDepth(feature.subFeatures)));\n\n// The estimate sizes the offscreen placeholder, minimap and link anchor until CanvasItem reports a measured size.\n// Specifications extend the measured footprint but do not move the link anchor below the slice content.\n// A presentation that shows the properties of cards makes rows taller; say which slices show them to\n// measure the collection as it is drawn.\nexport const estimateCollectionSize = (collection: ModuleCollection, showsDetails?: SliceDetailsVisibility): CollectionSizeEstimate => {\n const rows = collectionRows(collection);\n const heights = collectionRowHeights(collection, showsDetails);\n const slices = collectionSlices(collection);\n const moduleWidths = collection.modules.map(module => module.collapsed\n ? boardMetrics.collapsedModuleWidth : collectionModuleWidth(module.name, module.features));\n const modulesWidth = moduleWidths.reduce((width, moduleWidth, index) =>\n width + (index ? boardMetrics.sliceGap : 0) + moduleWidth, 0);\n const featureHeaderRows = Math.max(1, ...collection.modules.map(module => featureDepth(module.features)));\n const rowsHeight = rows.reduce((height, row) => height + heights[row], 0);\n return {\n width: (slices.length ? rowLabelWidth : 0) + modulesWidth,\n height: boardMetrics.headerHeight * (1 + featureHeaderRows) + 28 + rowsHeight,\n moduleWidths,\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback } from 'react';\nimport { areDetailsVisible, areSliceDetailsVisibleForDetailLevel, useEventModelPresentation } from '../Presentation';\nimport type { SliceDetailsVisibility } from './collectionGridLayout';\n\n// Which slices show the properties of their cards under the board's presentation - the same rule the\n// slice's cells draw by, so the rows are measured for the cards they hold.\nexport const useSliceDetailsVisibility = (): SliceDetailsVisibility => {\n const { detailLevel, detailsVisibility } = useEventModelPresentation();\n return useCallback(({ slice, moduleId, featureId }) =>\n areSliceDetailsVisibleForDetailLevel(detailLevel, areDetailsVisible(detailsVisibility, moduleId, featureId, slice.id.toString())),\n [detailLevel, detailsVisibility]);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport { SliceType } from '../Model';\nimport { RowType } from '../Rows';\nimport { useEventModelPresentation } from '../Presentation';\nimport './Connectors.css';\n\nexport interface ConnectorProps {\n /**\n * Override the horizontal center of the connector arrow/fill-line.\n * 'left' = 25% (read-model column), 'center' = 50% (default), 'right' = 75% (command column).\n */\n columnPosition?: 'left' | 'center' | 'right';\n}\n\nfunction columnLeft(position?: 'left' | 'center' | 'right'): string | undefined {\n if (position === 'left') return '25%';\n if (position === 'right') return '75%';\n return undefined;\n}\n\n// In 'fillLines' (lines) mode the curved SliceConnections overlay draws all flow\n// lines, so the per-row fill lines and inter-row triangles are suppressed here.\n\nexport const ConnectorIncomingTop: React.FC<ConnectorProps> = ({ columnPosition }) => {\n const { visualizationMode } = useEventModelPresentation();\n if (visualizationMode === 'fillLines') return null;\n const style: React.CSSProperties | undefined = columnPosition ? { left: columnLeft(columnPosition) } : undefined;\n return <div className='event-modeling-grid-flow-triangle event-modeling-grid-flow-triangle--down' style={style} aria-hidden='true' />;\n};\n\nexport const ConnectorOutgoingTop: React.FC<ConnectorProps> = ({ columnPosition }) => {\n const { visualizationMode } = useEventModelPresentation();\n if (visualizationMode === 'fillLines') return null;\n const style: React.CSSProperties | undefined = columnPosition ? { left: columnLeft(columnPosition) } : undefined;\n return <div className='event-modeling-grid-flow-triangle event-modeling-grid-flow-triangle--up' style={style} aria-hidden='true' />;\n};\n\nexport const PassthroughConnector: React.FC<ConnectorProps> = ({ columnPosition }) => {\n const { visualizationMode } = useEventModelPresentation();\n if (visualizationMode === 'fillLines') return null;\n const style: React.CSSProperties | undefined = columnPosition ? { left: columnLeft(columnPosition) } : undefined;\n return <div className='event-modeling-grid-flow-triangle event-modeling-grid-flow-triangle--down' style={style} aria-hidden='true' />;\n};\n\nexport const ConnectorOutgoingBottom: React.FC<ConnectorProps> = () => null;\n\nexport const ConnectorIncomingBottom: React.FC<ConnectorProps> = () => null;\n\nexport interface CellConnectors {\n bottomOutgoing?: boolean; // source side: line card→bottom (downward flow)\n topIncoming?: boolean; // dest side: line top→card+arrowhead (downward flow)\n topOutgoing?: boolean; // source side: line card→top (upward flow)\n bottomIncoming?: boolean; // dest side: line bottom→card+arrowhead (upward flow)\n\n passthrough?: boolean;\n}\n\nexport function cellConnectors(rowType: RowType, sliceType: SliceType, contentRows: RowType[] = []): CellConnectors {\n const hasSystemRow = contentRows.includes(RowType.System);\n\n switch (sliceType) {\n case SliceType.stateChange:\n if (rowType === RowType.UI) return { bottomOutgoing: true };\n if (rowType === RowType.Chat) return { bottomOutgoing: true };\n if (rowType === RowType.System) return hasSystemRow ? { passthrough: true } : {};\n if (rowType === RowType.Interaction) return { topIncoming: true, bottomOutgoing: true };\n if (rowType === RowType.Events) return { topIncoming: true };\n break;\n case SliceType.stateView:\n if (rowType === RowType.UI) return { bottomOutgoing: true };\n if (rowType === RowType.Chat) return { bottomOutgoing: true };\n if (rowType === RowType.System) return hasSystemRow ? { passthrough: true } : {};\n if (rowType === RowType.Interaction) return { topIncoming: true, bottomIncoming: true };\n if (rowType === RowType.Events) return { topOutgoing: true };\n break;\n case SliceType.automation:\n // Interaction row: ReadModel flows upward and Command receives downward flow.\n if (rowType === RowType.Interaction) return { topOutgoing: true, topIncoming: true };\n if (rowType === RowType.System) return { bottomIncoming: true, bottomOutgoing: true };\n if (rowType === RowType.Events) return { topIncoming: true };\n break;\n case SliceType.translator:\n if (rowType === RowType.System) return { bottomOutgoing: true };\n if (rowType === RowType.Interaction) return { topIncoming: true, bottomOutgoing: true };\n if (rowType === RowType.Events) return { topIncoming: true };\n break;\n }\n return {};\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Identifies the role a card plays in a slice's flow, used to anchor the curved\n * connection lines drawn in the \"lines\" visualization mode. The string values\n * are emitted as the `data-flow-node` attribute on the corresponding card element.\n */\nexport enum FlowNodeActor {\n ui = 'ui',\n command = 'command',\n readModel = 'readModel',\n cogwheel = 'cogwheel',\n event = 'event',\n externalEvent = 'externalEvent',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The minimal shape of an event needed to compute slice connections.\n// An event with an empty ConnectionEvent.sourceEventId is an origin (produced) event;\n// an event carrying a non-empty one is a reference that consumes the origin it points at.\nexport interface ConnectionEvent {\n // The identifier of this event item within its slice.\n id: string;\n\n // The display name of the event.\n name: string;\n\n // The id of the origin event this one references, or empty/undefined when this is a produced event.\n sourceEventId?: string;\n}\n\n// The minimal shape of a slice needed to compute connections.\nexport interface ConnectionSlice {\n // The slice identifier.\n id: string;\n\n // The display name of the slice.\n name: string;\n\n // The events owned or referenced by the slice.\n events: ConnectionEvent[];\n\n // The origin event id an automation slice is triggered by, when configured.\n automationTriggerEventId?: string;\n}\n\n// A single produced→consumed link between two slices via one event.\nexport interface SliceConnectionLink {\n // The id of the origin (produced) event that forms the link.\n eventId: string;\n\n // The display name of the event that forms the link.\n eventName: string;\n\n // The id of the slice on the other end of the link.\n sliceId: string;\n\n // The display name of the slice on the other end of the link.\n sliceName: string;\n}\n\n// The connection information for a single slice.\nexport interface SliceConnection {\n // The ids of every slice connected to this one, whether it produces for them or consumes from them.\n connectedSliceIds: ReadonlySet<string>;\n\n // The events this slice consumes, each pointing at the slice that produces it.\n consumed: SliceConnectionLink[];\n\n // The events this slice produces, each pointing at a slice that consumes it.\n produced: SliceConnectionLink[];\n}\n\ninterface MutableSliceConnection {\n connectedSliceIds: Set<string>;\n consumed: SliceConnectionLink[];\n produced: SliceConnectionLink[];\n}\n\ninterface EventOrigin {\n sliceId: string;\n sliceName: string;\n eventName: string;\n}\n\n// Computes the produced→consumed connection graph across a flat list of slices.\n//\n// A slice produces an event (an event with no `sourceEventId`); another slice consumes it either by\n// referencing it (an event whose `sourceEventId` points at the origin) or, for an automation slice,\n// by being triggered by it (`automationTriggerEventId`). Each such link connects the two slices in\n// both directions.\n// slices: The slices to analyze, typically every slice in a module collection.\n// Returns A map from slice id to its SliceConnection.\nexport function computeSliceConnections(slices: readonly ConnectionSlice[]): Map<string, SliceConnection> {\n const connections = new Map<string, MutableSliceConnection>();\n const originByEventId = new Map<string, EventOrigin>();\n\n for (const slice of slices) {\n connections.set(slice.id, { connectedSliceIds: new Set(), consumed: [], produced: [] });\n for (const event of slice.events) {\n if (!event.sourceEventId) {\n originByEventId.set(event.id, { sliceId: slice.id, sliceName: slice.name, eventName: event.name });\n }\n }\n }\n\n const linkConsumerToOrigin = (consumer: ConnectionSlice, originEventId: string) => {\n const origin = originByEventId.get(originEventId);\n if (!origin || origin.sliceId === consumer.id) return;\n\n const consumerConnection = connections.get(consumer.id)!;\n const producerConnection = connections.get(origin.sliceId)!;\n\n consumerConnection.connectedSliceIds.add(origin.sliceId);\n producerConnection.connectedSliceIds.add(consumer.id);\n\n if (!consumerConnection.consumed.some(link => link.eventId === originEventId && link.sliceId === origin.sliceId)) {\n consumerConnection.consumed.push({ eventId: originEventId, eventName: origin.eventName, sliceId: origin.sliceId, sliceName: origin.sliceName });\n }\n if (!producerConnection.produced.some(link => link.eventId === originEventId && link.sliceId === consumer.id)) {\n producerConnection.produced.push({ eventId: originEventId, eventName: origin.eventName, sliceId: consumer.id, sliceName: consumer.name });\n }\n };\n\n for (const slice of slices) {\n for (const event of slice.events) {\n if (event.sourceEventId) {\n linkConsumerToOrigin(slice, event.sourceEventId);\n }\n }\n if (slice.automationTriggerEventId) {\n linkConsumerToOrigin(slice, slice.automationTriggerEventId);\n }\n }\n\n return connections;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\nimport { FlowNodeActor } from './FlowNodeActor';\n\n// The ordered sequence of flow-node roles for a slice type. Connection lines are\n// drawn between consecutive roles that are actually present, following the natural\n// direction of the slice:\n//\n// - State Change: UI → Command → Event(s)\n// - State View: Event(s) → Read Model → UI\n// - Automation: Read Model → Automation (cogwheel) → Command → Event(s)\n// - Translation: External Event → Command → Event(s)\n//\n// Actors that have no card on the canvas (e.g. an undefined UI or read model) are\n// skipped, so the line simply connects the nearest present neighbors.\n// sliceType: The slice type to get the flow order for.\n// Returns The ordered roles for the slice type.\nexport function flowNodeOrder(sliceType: SliceType): FlowNodeActor[] {\n switch (sliceType) {\n case SliceType.stateChange:\n return [FlowNodeActor.ui, FlowNodeActor.command, FlowNodeActor.event];\n case SliceType.stateView:\n return [FlowNodeActor.event, FlowNodeActor.readModel, FlowNodeActor.ui];\n case SliceType.automation:\n return [FlowNodeActor.readModel, FlowNodeActor.cogwheel, FlowNodeActor.command, FlowNodeActor.event];\n case SliceType.translator:\n return [FlowNodeActor.externalEvent, FlowNodeActor.command, FlowNodeActor.event];\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceConnections.css';\nimport React, { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';\nimport { canvasGesture } from '@cratis/components/Canvas';\nimport type { SliceType } from '../Model';\nimport { CurveAxis, smoothCurvePath } from '../Geometry';\nimport { flowNodeOrder } from './flowNodeOrder';\n\nexport interface SliceConnectionsProps {\n\n // The type of slice, which determines the order the flow nodes are connected in.\n sliceType: SliceType;\n\n // A value that changes whenever the slice content that affects layout changes\n // (events, interactions, detail visibility, row heights). Used to trigger a\n // re-measure of the card positions.\n recomputeKey: string;\n}\n\n// A measured card position, in the overlay's local (layout) coordinate space.\ninterface NodeRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n// Builds a smooth cubic-bezier path between two cards with vertical tangents at both ends.\nfunction buildPath(source: NodeRect, target: NodeRect): string {\n const sourceX = source.x + source.width / 2;\n const targetX = target.x + target.width / 2;\n const sourceCenterY = source.y + source.height / 2;\n const targetCenterY = target.y + target.height / 2;\n\n const goingDown = targetCenterY >= sourceCenterY;\n const startY = goingDown ? source.y + source.height : source.y;\n const endY = goingDown ? target.y : target.y + target.height;\n\n return smoothCurvePath({ x: sourceX, y: startY }, { x: targetX, y: endY }, CurveAxis.Vertical);\n}\n\n// Draws the curved connection lines between the cards of a single slice when the\n// editor is in the \"lines\" visualization mode. Instead of straight per-row fill\n// lines and triangles, this renders one smooth curve per connection with an\n// arrowhead at the destination, following the slice type's flow.\nexport const SliceConnections: React.FC<SliceConnectionsProps> = ({ sliceType, recomputeKey }) => {\n const hostRef = useRef<HTMLDivElement>(null);\n const [paths, setPaths] = useState<string[]>([]);\n const markerId = `flow-arrow-${useId().replace(/:/g, '')}`;\n\n const measure = useCallback(() => {\n const host = hostRef.current;\n const column = host?.parentElement;\n if (!host || !column) return;\n\n const hostRect = host.getBoundingClientRect();\n const layoutWidth = host.clientWidth || hostRect.width;\n const scale = layoutWidth ? hostRect.width / layoutWidth : 1;\n\n const toLocal = (element: Element): NodeRect => {\n const rect = element.getBoundingClientRect();\n return {\n x: (rect.left - hostRect.left) / scale,\n y: (rect.top - hostRect.top) / scale,\n width: rect.width / scale,\n height: rect.height / scale,\n };\n };\n\n const order = flowNodeOrder(sliceType);\n const groups = order\n .map(role => Array.from(column.querySelectorAll<HTMLElement>(`[data-flow-node=\"${role}\"]`)).map(toLocal))\n .filter(nodes => nodes.length > 0);\n\n const nextPaths: string[] = [];\n for (let index = 0; index < groups.length - 1; index++) {\n for (const source of groups[index]) {\n for (const target of groups[index + 1]) {\n nextPaths.push(buildPath(source, target));\n }\n }\n }\n\n setPaths(previous =>\n previous.length === nextPaths.length && previous.every((value, i) => value === nextPaths[i])\n ? previous\n : nextPaths);\n }, [sliceType]);\n\n // Observer-driven re-measures coalesce onto one animation frame (a settle re-apply resizes every\n // observed card at once — one measure covers the whole burst), and hold still while a pan/zoom\n // gesture is in motion: measuring forces a layout, and the geometry it would read is mid-gesture\n // anyway. The deferred measure runs when the gesture settles.\n const measureFrameRef = useRef(0);\n const measurePendingGestureRef = useRef(false);\n const scheduleMeasure = useCallback(() => {\n if (canvasGesture.isActive) {\n measurePendingGestureRef.current = true;\n return;\n }\n if (measureFrameRef.current) return;\n measureFrameRef.current = requestAnimationFrame(() => {\n measureFrameRef.current = 0;\n measure();\n });\n }, [measure]);\n\n useEffect(() => () => cancelAnimationFrame(measureFrameRef.current), []);\n\n useEffect(() => canvasGesture.subscribe(active => {\n if (active || !measurePendingGestureRef.current) return;\n measurePendingGestureRef.current = false;\n scheduleMeasure();\n }), [scheduleMeasure]);\n\n useLayoutEffect(() => {\n measure();\n }, [measure, recomputeKey]);\n\n useEffect(() => {\n const host = hostRef.current;\n const column = host?.parentElement;\n if (!host || !column) return;\n\n // Observe the column and each connectable card so the curves re-measure\n // when a card resizes after mount — e.g. a UI prototype thumbnail that\n // renders its preview asynchronously, which the column's fixed height\n // would otherwise hide from the observer.\n const resizeObserver = new ResizeObserver(() => scheduleMeasure());\n const observeCards = () => {\n resizeObserver.disconnect();\n resizeObserver.observe(column);\n column.querySelectorAll('[data-flow-node]').forEach(node => resizeObserver.observe(node));\n };\n observeCards();\n\n // A card can also appear or disappear without changing the column's size —\n // most notably a UI prototype added optimistically, which mounts a new\n // flow node but leaves the slice props (and the row height) unchanged.\n // Watch the column subtree so the curves re-measure when that happens.\n // Mutations inside the overlay itself (the drawn <path> elements) are\n // ignored to avoid a re-measure loop.\n const mutationObserver = new MutationObserver(records => {\n if (records.every(record => host.contains(record.target))) return;\n observeCards();\n scheduleMeasure();\n });\n mutationObserver.observe(column, { childList: true, subtree: true });\n\n window.addEventListener('resize', scheduleMeasure);\n return () => {\n resizeObserver.disconnect();\n mutationObserver.disconnect();\n window.removeEventListener('resize', scheduleMeasure);\n };\n }, [measure, scheduleMeasure, recomputeKey]);\n\n return (\n <div ref={hostRef} className='event-modeling-grid-connections' aria-hidden='true'>\n <svg className='event-modeling-grid-connections__svg' width='100%' height='100%'>\n <defs>\n <marker\n id={markerId}\n markerWidth='9'\n markerHeight='9'\n refX='6'\n refY='4.5'\n orient='auto'\n markerUnits='userSpaceOnUse'\n >\n <path d='M 0 0 L 8 4.5 L 0 9 z' className='event-modeling-grid-connections__arrow' />\n </marker>\n </defs>\n {paths.map((path, index) => (\n <path\n key={index}\n d={path}\n className='event-modeling-grid-connections__line'\n markerEnd={`url(#${markerId})`}\n />\n ))}\n </svg>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { createContext, useContext, useMemo } from 'react';\nimport type { SliceConnection } from './computeSliceConnections';\n\n// Access to the produced→consumed connection graph for the slices in a module collection.\nexport interface SliceConnectionsContextValue {\n // Returns the connection info for a slice, or when the slice has no computed connections.\n getConnection: (sliceId: string) => SliceConnection | undefined;\n}\n\nconst SliceConnectionsContext = createContext<SliceConnectionsContextValue | null>(null);\n\nexport interface SliceConnectionsProviderProps {\n // The connection graph keyed by slice id, typically computed once per module collection.\n connections: Map<string, SliceConnection>;\n children: React.ReactNode;\n}\n\n// Provides the slice connection graph to every slice rendered within a module collection.\nexport const SliceConnectionsProvider = ({ connections, children }: SliceConnectionsProviderProps) => {\n const value = useMemo<SliceConnectionsContextValue>(\n () => ({ getConnection: (sliceId: string) => connections.get(sliceId) }),\n [connections],\n );\n return <SliceConnectionsContext.Provider value={value}>{children}</SliceConnectionsContext.Provider>;\n};\n\n// Returns the connection info for the given slice, or when there is no provider\n// (e.g. Storybook) or the slice is not part of the graph.\nexport const useSliceConnection = (sliceId: string): SliceConnection | undefined => {\n const context = useContext(SliceConnectionsContext);\n return context?.getConnection(sliceId);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ConnectionHighlight.css';\nimport React, { useCallback, useEffect, useRef } from 'react';\n\n// Selector for the board container that scopes the fade-on-hover effect.\nconst BOARD_SELECTOR = '[data-event-model-board]';\n// Class applied to the board while a slice is hovered to fade every non-connected slice column and specification.\nconst HIGHLIGHT_ACTIVE_CLASS = 'event-modeling-board--highlight-slices';\n// Class applied to the hovered slice column, its connected columns, and every specification belonging\n// to one of those slices so they all stay emphasized together.\nconst HIGHLIGHTED_COLUMN_CLASS = 'event-modeling-grid-slice-column--connection-highlighted';\n// Selector matching a slice's own column and every element carrying its specification cards for a\n// given `data-slice-id`. A specification renders as a sibling below its slice column rather than\n// inside it (see SpecificationsContainer), so it needs its own attribute to be found by id.\nconst sliceElementsSelector = (sliceId: string) =>\n `[data-slice-col=\"true\"][data-slice-id=\"${sliceId}\"], [data-slice-spec-col=\"true\"][data-slice-id=\"${sliceId}\"]`;\n\n// Handlers and ref returned to wire a slice column into the connection highlight.\nexport interface ConnectionHighlight {\n // Attach to the slice column element that carries `data-slice-id`.\n ref: React.RefObject<HTMLDivElement | null>;\n // Begin emphasizing this slice and its connections while fading the rest.\n onMouseEnter: () => void;\n // Clear the emphasis.\n onMouseLeave: () => void;\n}\n\ninterface ActiveHighlight {\n board: HTMLElement;\n columns: HTMLElement[];\n}\n\n// Emphasizes a slice column — and its specifications — together with the columns and specifications of\n// the slices it connects to, while a pointer hovers it, fading everything else on the board. Purely\n// presentational: it toggles CSS classes on the board and the matched elements instead of triggering\n// React re-renders, mirroring the per-event dim in EventReference. Own and connected elements\n// are resolved from the DOM by their shared `data-slice-id`, so a slice's specification cards (rendered\n// as siblings below its column, not inside it) light up and dim in lockstep with the column itself.\n// connectedSliceIds: The ids of the slices connected to the hovered slice.\n// Returns The ref and hover handlers to spread onto the slice column.\nexport function useConnectionHighlight(connectedSliceIds: ReadonlySet<string> | undefined): ConnectionHighlight {\n const ref = useRef<HTMLDivElement | null>(null);\n const activeRef = useRef<ActiveHighlight | null>(null);\n\n const clear = useCallback(() => {\n const active = activeRef.current;\n if (!active) return;\n active.board.classList.remove(HIGHLIGHT_ACTIVE_CLASS);\n active.columns.forEach(column => column.classList.remove(HIGHLIGHTED_COLUMN_CLASS));\n activeRef.current = null;\n }, []);\n\n const onMouseEnter = useCallback(() => {\n const element = ref.current;\n if (!element) return;\n const board = element.closest<HTMLElement>(BOARD_SELECTOR);\n if (!board) return;\n\n clear();\n\n const columns: HTMLElement[] = [element];\n element.classList.add(HIGHLIGHTED_COLUMN_CLASS);\n\n // The hovered slice's own specifications are included alongside every connected slice's column\n // and specifications, so all of them are found and emphasized through the same DOM lookup.\n const sliceIds = new Set<string>(connectedSliceIds ?? []);\n const ownSliceId = element.dataset.sliceId;\n if (ownSliceId) sliceIds.add(ownSliceId);\n\n for (const sliceId of sliceIds) {\n board\n .querySelectorAll<HTMLElement>(sliceElementsSelector(sliceId))\n .forEach(matched => {\n if (matched === element) return;\n matched.classList.add(HIGHLIGHTED_COLUMN_CLASS);\n columns.push(matched);\n });\n }\n\n board.classList.add(HIGHLIGHT_ACTIVE_CLASS);\n activeRef.current = { board, columns };\n }, [clear, connectedSliceIds]);\n\n // Clean up if the column unmounts while still hovered.\n useEffect(() => clear, [clear]);\n\n return { ref, onMouseEnter, onMouseLeave: clear };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface FeatureColumnFrameProps {\n featureId: Guid;\n moduleId: Guid;\n // A disabled feature is drawn faded.\n enabled: boolean;\n // The feature is the one being dragged.\n dragging?: boolean;\n children?: ReactNode;\n}\n\n// The column a feature's header row and slices sit in. It carries the attributes a feature drag reads\n// the columns of a module by.\nexport const FeatureColumnFrame = ({ featureId, moduleId, enabled, dragging = false, children }: FeatureColumnFrameProps) => (\n <div\n data-feature-col='true'\n data-feature-id={featureId.toString()}\n data-feature-module-id={moduleId.toString()}\n style={{\n display: 'grid',\n gridRow: '1 / 3',\n gridTemplateRows: 'subgrid',\n minWidth: 0,\n opacity: dragging ? 0.35 : enabled ? 1 : 0.5,\n transition: 'opacity 0.15s',\n }}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './FeatureGridSurface.css';\nimport type { ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { boardMetrics } from '../Layout';\nimport { FeatureColumnFrame } from './FeatureColumnFrame';\n\nexport interface FeatureGridSurfaceProps {\n featureId: Guid;\n moduleId: Guid;\n enabled: boolean;\n collapsed: boolean;\n rowCollapsed: boolean;\n width: number;\n headerVisibility: 'visible' | 'hidden' | 'none';\n header: ReactNode;\n screenTemplate?: ReactNode;\n slices: ReactNode;\n}\n\nexport const FeatureGridSurface = ({ featureId, moduleId, enabled, collapsed, rowCollapsed, width,\n headerVisibility, header, screenTemplate, slices }: FeatureGridSurfaceProps) => (\n <FeatureColumnFrame featureId={featureId} moduleId={moduleId} enabled={enabled}>\n <div className={`event-modeling-grid-header-cell-wrapper${collapsed ? ' event-modeling-grid-header-cell-wrapper--feature-collapsed' : ''}`}\n style={{ width: headerVisibility === 'hidden' ? 0 : width,\n visibility: headerVisibility === 'hidden' ? 'hidden' : 'visible',\n overflow: headerVisibility === 'visible' && !collapsed ? 'visible' : 'hidden' }}>\n {headerVisibility === 'visible' ? header : headerVisibility === 'hidden' ? <div style={{ height: boardMetrics.headerHeight }} /> : null}\n {!collapsed && screenTemplate}\n </div>\n <div className={rowCollapsed ? 'event-modeling-feature-grid-slices--row-collapsed'\n : headerVisibility === 'visible' ? 'event-modeling-feature-grid-slices--header-visible' : undefined}>\n {slices}\n </div>\n </FeatureColumnFrame>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Headers/HeaderCell.css';\nimport type { ReactNode, Ref } from 'react';\nimport type { FeatureDropEdge } from './featureDropEdge';\n\nexport interface FeatureHeaderCellProps {\n width: number;\n collapsed: boolean;\n // The edge that shows a dragged feature would land here.\n dropEdge?: FeatureDropEdge;\n children?: ReactNode;\n ref?: Ref<HTMLDivElement>;\n}\n\n// A thicker, glowing edge than a plain inset line — the same visual weight as the slice drop indicator,\n// so every level of the board shows where a drop would land the same way.\nconst dropEdgeShadow: Record<FeatureDropEdge, string> = {\n before: 'inset 6px 0 0 rgba(180,165,255,0.95), inset 0 0 14px 0 rgba(150,130,255,0.5)',\n after: 'inset -6px 0 0 rgba(180,165,255,0.95), inset 0 0 14px 0 rgba(150,130,255,0.5)',\n};\n\n// The cell a feature's header sits in, spanning the feature and its sub-features.\nexport const FeatureHeaderCell = ({ width, collapsed, dropEdge, children, ref }: FeatureHeaderCellProps) => (\n <div ref={ref}\n className={`event-modeling-grid-header-cell-wrapper${collapsed ? ' event-modeling-grid-header-cell-wrapper--feature-collapsed' : ''}`}\n style={{ width, boxShadow: dropEdge && dropEdgeShadow[dropEdge] }}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport type FeatureDropEdge = 'before' | 'after';\n\n// Which edge of the feature at index shows where a dragged feature would land, if either. Gap n is\n// drawn on the leading edge of feature n; the gap after the last feature on that feature's trailing edge.\nexport function featureDropEdge(dropIndex: number | undefined, index: number, count: number): FeatureDropEdge | undefined {\n if (dropIndex === undefined) return undefined;\n if (dropIndex === index) return 'before';\n if (index === count - 1 && dropIndex === count) return 'after';\n return undefined;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { headerDropIndex, reorderedIds, type HeaderDragStart, type HeaderDragState } from '../HeaderDragging';\nimport type { FeaturesReordered } from './FeaturesReordered';\n\nexport interface FeatureDragState extends HeaderDragState {\n featureId: Guid;\n moduleId: Guid;\n sourceIndex: number;\n currentY: number;\n // The gap the feature would land in right now: n is before the nth feature of the module.\n dropIndex: number;\n}\n\nexport type FeatureDragStart = (featureId: Guid, label: string, start: HeaderDragStart) => void;\n\nexport interface FeatureDrag {\n featureDrag?: FeatureDragState;\n // Undefined when nothing can be told about a move, so no feature header offers to be picked up.\n handleFeatureDragStart?: FeatureDragStart;\n}\n\n// The gap a pointer at clientX is over among the feature columns of one module.\nfunction dropIndexAt(moduleId: Guid, clientX: number): number {\n const columns = Array.from(\n document.querySelectorAll<HTMLElement>(`[data-feature-col=\"true\"][data-feature-module-id=\"${moduleId.toString()}\"]`));\n return headerDropIndex(columns.map(column => column.getBoundingClientRect()), clientX);\n}\n\n// Dragging a feature to another place among the features of its module.\n// featureIds: the module's top-level features in their current order.\nexport function useFeatureDrag(moduleId: Guid, featureIds: readonly Guid[], onFeaturesReordered?: FeaturesReordered): FeatureDrag {\n const board = useBoard();\n const [featureDrag, setFeatureDrag] = useState<FeatureDragState | undefined>(undefined);\n const featureDragRef = useRef(featureDrag);\n featureDragRef.current = featureDrag;\n const featureIdsRef = useRef(featureIds);\n featureIdsRef.current = featureIds;\n const onFeaturesReorderedRef = useRef(onFeaturesReordered);\n onFeaturesReorderedRef.current = onFeaturesReordered;\n\n const handleFeatureDragStart = useCallback<FeatureDragStart>((featureId, label, start) => {\n const sourceIndex = featureIdsRef.current.findIndex(id => id.equals(featureId));\n if (sourceIndex === -1) return;\n setFeatureDrag({\n featureId,\n moduleId,\n sourceIndex,\n ghostLabel: label,\n ghostWidth: start.width,\n ghost: start.ghost,\n currentX: start.clientX,\n currentY: start.clientY,\n dropIndex: sourceIndex,\n headerY: start.headerY,\n zoom: start.zoom,\n });\n }, [moduleId]);\n\n const dragging = featureDrag !== undefined;\n useEffect(() => {\n if (!dragging) return;\n\n const handlePointerMove = (event: PointerEvent) => {\n setFeatureDrag(previous => previous && {\n ...previous,\n currentX: event.clientX,\n currentY: event.clientY,\n dropIndex: dropIndexAt(previous.moduleId, event.clientX),\n });\n };\n\n const handlePointerUp = () => {\n const drag = featureDragRef.current;\n setFeatureDrag(undefined);\n if (!drag) return;\n const ordered = reorderedIds(featureIdsRef.current, drag.sourceIndex, drag.dropIndex);\n if (ordered) onFeaturesReorderedRef.current?.(drag.moduleId, ordered);\n };\n\n window.addEventListener('pointermove', handlePointerMove);\n window.addEventListener('pointerup', handlePointerUp);\n return () => {\n window.removeEventListener('pointermove', handlePointerMove);\n window.removeEventListener('pointerup', handlePointerUp);\n };\n }, [dragging]);\n\n const canDrag = !board.readOnly && onFeaturesReordered !== undefined;\n return { featureDrag, handleFeatureDragStart: canDrag ? handleFeatureDragStart : undefined };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useRef, useState, type RefCallback } from 'react';\n\ntype Slot = 'header' | 'column';\ntype Targets = { header?: HTMLDivElement; column?: HTMLDivElement };\n\nexport function useFeatureSlotTargets() {\n const [targets, setTargets] = useState<Map<string, Targets>>(new Map());\n const callbacks = useRef(new Map<string, RefCallback<HTMLDivElement>>());\n\n const register = useCallback((featureId: string, slot: Slot) => {\n const key = `${slot}:${featureId}`;\n const existing = callbacks.current.get(key);\n if (existing) return existing;\n const callback: RefCallback<HTMLDivElement> = node => {\n setTargets(previous => {\n const current = previous.get(featureId);\n if ((current?.[slot] ?? null) === node) return previous;\n const next = new Map(previous);\n const updated = { ...current, [slot]: node ?? undefined };\n if (!updated.header && !updated.column) next.delete(featureId);\n else next.set(featureId, updated);\n return next;\n });\n };\n callbacks.current.set(key, callback);\n return callback;\n }, []);\n\n return { targets, register };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface FeatureAreaItem<T> {\n id: Guid;\n subFeatures: T[];\n name: string;\n collapsed: boolean;\n}\n\nexport interface FeatureAreaState<T extends FeatureAreaItem<T>> {\n snapshot: T[];\n features: T[];\n pendingAdditions: { feature: T; parentId?: Guid }[];\n order?: Guid[];\n pendingRenames: ReadonlyMap<string, string>;\n pendingCollapses: ReadonlyMap<string, boolean>;\n}\n\nexport const createFeatureAreaState = <T extends FeatureAreaItem<T>>(features: T[]): FeatureAreaState<T> => ({\n snapshot: features, features, pendingAdditions: [], pendingRenames: new Map(), pendingCollapses: new Map(),\n});\n\nexport function updateFeature<T extends FeatureAreaItem<T>>(features: T[], id: Guid, update: (feature: T) => T): T[] {\n let changed = false;\n const result = features.map(feature => {\n if (feature.id.equals(id)) {\n changed = true;\n return update(feature);\n }\n const children = updateFeature(feature.subFeatures, id, update);\n if (children === feature.subFeatures) return feature;\n changed = true;\n return { ...feature, subFeatures: children };\n });\n return changed ? result : features;\n}\n\nexport function insertFeature<T extends FeatureAreaItem<T>>(features: T[], feature: T, parentId?: Guid): T[] {\n if (containsFeature(features, feature.id)) return features;\n if (!parentId) return [...features, feature];\n return updateFeature(features, parentId, parent => ({ ...parent, subFeatures: [...parent.subFeatures, feature] }));\n}\n\nexport function reconcileFeatures<T extends FeatureAreaItem<T>>(state: FeatureAreaState<T>, snapshot: T[]): FeatureAreaState<T> {\n const pendingAdditions = state.pendingAdditions.filter(({ feature }) => !containsFeature(snapshot, feature.id));\n const withAdditions = pendingAdditions.reduce((features, addition) => insertFeature(features, addition.feature, addition.parentId), snapshot);\n const pendingRenames = new Map([...state.pendingRenames].filter(([id, name]) => !hasName(snapshot, id, name)));\n const renamed = [...pendingRenames].reduce((features, [id, name]) => renameFeature(features, id, name), withAdditions);\n const pendingCollapses = new Map([...state.pendingCollapses].filter(([id, collapsed]) => !hasCollapsed(snapshot, id, collapsed)));\n const collapsed = [...pendingCollapses].reduce((features, [id, value]) => collapseFeature(features, id, value), renamed);\n const ordered = state.order ? orderFeatures(collapsed, state.order) : collapsed;\n return { snapshot, features: ordered, pendingAdditions, pendingRenames, pendingCollapses, order: state.order };\n}\n\nexport function revertFeatureRename<T extends FeatureAreaItem<T>>(state: FeatureAreaState<T>, id: Guid): FeatureAreaState<T> {\n const pendingRenames = new Map(state.pendingRenames);\n pendingRenames.delete(id.toString());\n return reconcileFeatures({ ...state, pendingRenames }, state.snapshot);\n}\n\nexport function containsFeature<T extends FeatureAreaItem<T>>(features: T[], id: Guid): boolean {\n return features.some(feature => feature.id.equals(id) || containsFeature(feature.subFeatures, id));\n}\n\nfunction hasName<T extends FeatureAreaItem<T>>(features: T[], id: string, name: string): boolean {\n return features.some(feature => (feature.id.toString() === id && feature.name === name) || hasName(feature.subFeatures, id, name));\n}\n\nfunction hasCollapsed<T extends FeatureAreaItem<T>>(features: T[], id: string, collapsed: boolean): boolean {\n return features.some(feature => (feature.id.toString() === id && feature.collapsed === collapsed) || hasCollapsed(feature.subFeatures, id, collapsed));\n}\n\nexport function collapseFeature<T extends FeatureAreaItem<T>>(features: T[], id: string, collapsed: boolean): T[] {\n let changed = false;\n const updated = features.map(feature => {\n if (feature.id.toString() === id) {\n if (feature.collapsed === collapsed) return feature;\n changed = true;\n return { ...feature, collapsed };\n }\n const children = collapseFeature(feature.subFeatures, id, collapsed);\n if (children === feature.subFeatures) return feature;\n changed = true;\n return { ...feature, subFeatures: children };\n });\n return changed ? updated : features;\n}\n\nexport function renameFeature<T extends FeatureAreaItem<T>>(features: T[], id: string, name: string): T[] {\n let changed = false;\n const renamed = features.map(feature => {\n if (feature.id.toString() === id) {\n if (feature.name === name) return feature;\n changed = true;\n return { ...feature, name };\n }\n const children = renameFeature(feature.subFeatures, id, name);\n if (children === feature.subFeatures) return feature;\n changed = true;\n return { ...feature, subFeatures: children };\n });\n return changed ? renamed : features;\n}\n\nexport function orderFeatures<T extends FeatureAreaItem<T>>(features: T[], ids: Guid[]): T[] {\n const ordered = ids.flatMap(id => features.filter(feature => feature.id.equals(id)));\n return [...ordered, ...features.filter(feature => !ids.some(id => id.equals(feature.id)))];\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './FeaturesArea.css';\nimport { Fragment, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, type ReactNode, type Ref } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { HeaderDragGhost } from '../HeaderDragging';\nimport { boardMetrics } from '../Layout';\nimport { FeatureHeaderCell } from './FeatureHeaderCell';\nimport { featureDropEdge } from './featureDropEdge';\nimport { useFeatureDrag } from './useFeatureDrag';\nimport { useFeatureSlotTargets } from './useFeatureSlotTargets';\nimport { collapseFeature, createFeatureAreaState, insertFeature, orderFeatures, reconcileFeatures, renameFeature, revertFeatureRename, updateFeature, type FeatureAreaItem, type FeatureAreaState } from './featureAreaState';\n\nexport interface FeaturesAreaHandle<T> {\n addFeature: (name?: string) => Promise<void>;\n addSubFeature: (parentId: Guid, name?: string) => Promise<void>;\n updateFeature: (id: Guid, update: (feature: T) => T) => void;\n}\n\nexport interface FeaturesAreaProps<T extends FeatureAreaItem<T>> {\n ref?: Ref<FeaturesAreaHandle<T>>;\n initialFeatures: T[];\n moduleId: Guid;\n widthOf: (feature: T) => number;\n isCollapsed: (feature: T) => boolean;\n forceCollapsed?: boolean;\n onCollapseChanged?: (featureId: Guid, collapsed: boolean) => void;\n occupiesColumn: (feature: T) => boolean;\n renderHeader: (feature: T, options: {\n collapsed: boolean;\n dragging: boolean;\n onDragStart?: NonNullable<ReturnType<typeof useFeatureDrag>['handleFeatureDragStart']>;\n addSubFeature?: (name?: string) => void;\n onRenamed?: (name: string) => void;\n onToggleCollapse?: () => void;\n onCollapseFailed?: () => void;\n }) => ReactNode;\n renderColumn: (feature: T, options: {\n headerVisibility: 'visible' | 'hidden' | 'none';\n addSubFeature?: (name?: string) => void;\n onRenamed?: (name: string) => void;\n onToggleCollapse?: () => void;\n onCollapseFailed?: () => void;\n collapsed: boolean;\n }) => ReactNode;\n renderFeatureBoundary?: (feature: T, content: ReactNode) => ReactNode;\n onAddFeature?: (name?: string, parentId?: Guid) => Promise<T | undefined>;\n onRenameFeature?: (featureId: Guid, name: string) => Promise<void>;\n onFeaturesReordered?: (features: T[]) => void;\n onFeaturesChanged?: (features: T[]) => void;\n}\n\nfunction descendants<T extends FeatureAreaItem<T>>(feature: T, visited: Set<string>): T[] {\n visited.add(feature.id.toString());\n return feature.subFeatures.flatMap(child => {\n if (visited.has(child.id.toString())) return [];\n return [child, ...descendants(child, visited)];\n });\n}\n\nexport function FeaturesArea<T extends FeatureAreaItem<T>>({\n ref, initialFeatures, moduleId, widthOf, isCollapsed, forceCollapsed = false, onCollapseChanged,\n occupiesColumn, renderHeader, renderColumn, renderFeatureBoundary, onAddFeature, onRenameFeature, onFeaturesReordered, onFeaturesChanged,\n}: FeaturesAreaProps<T>) {\n const { readOnly, messages } = useBoard();\n const { targets, register } = useFeatureSlotTargets();\n const stateRef = useRef<FeatureAreaState<T>>(createFeatureAreaState(initialFeatures));\n const [state, setState] = useState(stateRef.current);\n const addingRef = useRef(false);\n const renamingIds = useRef(new Set<string>());\n const apply = useCallback((transition: (previous: FeatureAreaState<T>) => FeatureAreaState<T>) => {\n const next = transition(stateRef.current);\n if (next === stateRef.current) return;\n stateRef.current = next;\n setState(next);\n onFeaturesChanged?.(next.features);\n }, [onFeaturesChanged]);\n useEffect(() => {\n if (initialFeatures !== stateRef.current.snapshot) apply(previous => reconcileFeatures(previous, initialFeatures));\n }, [initialFeatures, apply]);\n\n const addFeature = useCallback(async (name?: string, parentId?: Guid) => {\n if (readOnly || !onAddFeature || addingRef.current) return;\n addingRef.current = true;\n try {\n const added = await onAddFeature(name, parentId);\n if (added) apply(previous => ({ ...previous,\n features: insertFeature(previous.features, added, parentId),\n pendingAdditions: [...previous.pendingAdditions, { feature: added, parentId }],\n }));\n } finally {\n addingRef.current = false;\n }\n }, [readOnly, onAddFeature, apply]);\n useImperativeHandle(ref, () => ({\n addFeature: name => addFeature(name),\n addSubFeature: (parentId, name) => addFeature(name, parentId),\n updateFeature: (id, update) => apply(previous => ({ ...previous, features: updateFeature(previous.features, id, update) })),\n }), [addFeature, apply]);\n\n const revertRename = useCallback((id: Guid) => apply(previous => revertFeatureRename(previous, id)), [apply]);\n const rename = useCallback((id: Guid, name: string) => {\n const key = id.toString();\n if (!onRenameFeature || readOnly || renamingIds.current.has(key)) return;\n renamingIds.current.add(key);\n apply(previous => ({ ...previous,\n features: renameFeature(previous.features, key, name),\n pendingRenames: new Map(previous.pendingRenames).set(key, name),\n }));\n void onRenameFeature(id, name).catch(() => revertRename(id)).finally(() => renamingIds.current.delete(key));\n }, [apply, onRenameFeature, readOnly, revertRename]);\n\n const resolveCollapsed = useCallback((feature: T) => forceCollapsed ||\n (state.pendingCollapses.get(feature.id.toString()) ?? isCollapsed(feature)),\n [forceCollapsed, isCollapsed, state.pendingCollapses]);\n const toggleCollapse = useCallback((feature: T) => {\n const next = !resolveCollapsed(feature);\n apply(previous => ({ ...previous, features: collapseFeature(previous.features, feature.id.toString(), next),\n pendingCollapses: new Map(previous.pendingCollapses).set(feature.id.toString(), next) }));\n onCollapseChanged?.(feature.id, next);\n }, [apply, resolveCollapsed, onCollapseChanged]);\n const revertCollapse = useCallback((feature: T) => {\n apply(previous => {\n const pendingCollapses = new Map(previous.pendingCollapses);\n pendingCollapses.delete(feature.id.toString());\n return reconcileFeatures({ ...previous, pendingCollapses }, previous.snapshot);\n });\n onCollapseChanged?.(feature.id, feature.collapsed);\n }, [apply, onCollapseChanged]);\n\n const features = state.features;\n const groups = useMemo(() => features.map(feature => {\n const children = descendants(feature, new Set());\n const columns = [feature, ...children];\n const visible = columns.filter(occupiesColumn);\n const width = visible.reduce((total, column, index) => total + (index ? boardMetrics.sliceGap : 0) + widthOf(column), 0);\n return { feature, children, width };\n }), [features, occupiesColumn, widthOf]);\n const columns = groups.flatMap(group => [group.feature, ...group.children]).filter(occupiesColumn);\n const parentIds = new Set(groups.filter(group => group.children.length).map(group => group.feature.id.toString()));\n const childIds = new Set(groups.flatMap(group => group.children.map(child => child.id.toString())));\n const featureIds = features.map(feature => feature.id);\n const handleReorder = useCallback((_moduleId: Guid, orderedIds: Guid[]) => {\n apply(previous => ({ ...previous, features: orderFeatures(previous.features, orderedIds), order: orderedIds }));\n onFeaturesReordered?.(orderFeatures(stateRef.current.features, orderedIds));\n }, [apply, onFeaturesReordered]);\n const { featureDrag, handleFeatureDragStart } = useFeatureDrag(moduleId, featureIds, onFeaturesReordered ? handleReorder : undefined);\n\n const headerOptions = (feature: T) => ({\n collapsed: resolveCollapsed(feature),\n dragging: featureDrag?.featureId.equals(feature.id) ?? false,\n onDragStart: handleFeatureDragStart,\n addSubFeature: !readOnly && onAddFeature ? (name?: string) => { void addFeature(name, feature.id); } : undefined,\n onRenamed: !readOnly && onRenameFeature ? (name: string) => rename(feature.id, name) : undefined,\n onToggleCollapse: onCollapseChanged ? () => toggleCollapse(feature) : undefined,\n onCollapseFailed: onCollapseChanged ? () => revertCollapse(feature) : undefined,\n });\n const columnOptions = (feature: T) => {\n const headerVisibility: 'hidden' | 'visible' | 'none' = parentIds.has(feature.id.toString()) ? 'hidden'\n : childIds.has(feature.id.toString()) ? 'visible' : 'none';\n return { ...headerOptions(feature), headerVisibility };\n };\n\n if (!features.length) return <div className='event-modeling-module-empty-placeholder' style={{ marginTop: 4 }}>{messages.features.empty}</div>;\n return <>\n <HeaderDragGhost drag={featureDrag} headerHeight={boardMetrics.headerHeight} />\n <div className='event-modeling-features-area'>\n <div className='event-modeling-features-area__headers' style={{ columnGap: boardMetrics.sliceGap }}>\n {groups.map((group, index) => <FeatureHeaderCell key={group.feature.id.toString()}\n ref={renderFeatureBoundary ? register(group.feature.id.toString(), 'header') : undefined}\n width={group.width} collapsed={resolveCollapsed(group.feature)}\n dropEdge={featureDropEdge(featureDrag?.dropIndex, index, groups.length)}>\n {!renderFeatureBoundary && renderHeader(group.feature, headerOptions(group.feature))}\n </FeatureHeaderCell>)}\n </div>\n <div className='event-modeling-features-area__columns' style={{ columnGap: boardMetrics.sliceGap }}>\n {columns.map(feature => <div key={feature.id.toString()} className='event-modeling-features-area__column'\n ref={renderFeatureBoundary ? register(feature.id.toString(), 'column') : undefined}>\n {!renderFeatureBoundary && renderColumn(feature, columnOptions(feature))}\n </div>)}\n </div>\n </div>\n {renderFeatureBoundary && groups.flatMap(group => [group.feature, ...group.children]).map(feature => {\n const featureTargets = targets.get(feature.id.toString());\n if (!featureTargets || (!childIds.has(feature.id.toString()) && !featureTargets.header) ||\n (occupiesColumn(feature) && !featureTargets.column)) return null;\n return <Fragment key={feature.id.toString()}>{renderFeatureBoundary(feature, <>\n {!childIds.has(feature.id.toString()) && featureTargets.header && createPortal(\n renderHeader(feature, headerOptions(feature)), featureTargets.header)}\n {featureTargets.column && createPortal(renderColumn(feature, columnOptions(feature)), featureTargets.column)}\n </>)}</Fragment>;\n })}\n </>;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\n\nexport interface SliceTypeIconProps {\n type: SliceType;\n}\n\nexport const SliceTypeIcon = ({ type }: SliceTypeIconProps) => (\n <svg viewBox='0 0 24 24' width='18' height='18' fill='none' stroke='currentColor' strokeWidth='2'>\n <SliceTypeGlyph type={type} />\n </svg>\n);\n\nconst SliceTypeGlyph = ({ type }: SliceTypeIconProps) => {\n switch (type) {\n case SliceType.stateChange:\n return (\n <>\n <rect x='3' y='3' width='18' height='5' rx='1' />\n <rect x='6' y='10' width='12' height='4' rx='1' fill='#3b82f6' stroke='#3b82f6' />\n <rect x='6' y='17' width='12' height='4' rx='1' fill='#f59e0b' stroke='#f59e0b' />\n <line x1='12' y1='8' x2='12' y2='10' />\n <line x1='12' y1='14' x2='12' y2='17' />\n <polyline points='10,16 12,17 14,16' />\n </>\n );\n case SliceType.stateView:\n return (\n <>\n <rect x='3' y='3' width='18' height='5' rx='1' />\n <rect x='6' y='10' width='12' height='4' rx='1' fill='#10b981' stroke='#10b981' />\n <rect x='3' y='17' width='8' height='4' rx='1' fill='#f59e0b' stroke='#f59e0b' />\n <rect x='13' y='17' width='8' height='4' rx='1' fill='#f59e0b' stroke='#f59e0b' />\n <line x1='7' y1='14' x2='7' y2='17' />\n <line x1='17' y1='14' x2='17' y2='17' />\n <polyline points='9,14 12,10 15,14' />\n </>\n );\n case SliceType.automation:\n return (\n <>\n <circle cx='12' cy='8' r='3' />\n <circle cx='12' cy='8' r='1.2' fill='currentColor' />\n <rect x='4' y='14' width='7' height='4' rx='1' fill='#10b981' stroke='#10b981' />\n <rect x='13' y='14' width='7' height='4' rx='1' fill='#3b82f6' stroke='#3b82f6' />\n <line x1='9' y1='11' x2='7.5' y2='14' />\n <line x1='15' y1='11' x2='16.5' y2='14' />\n </>\n );\n case SliceType.translator:\n return (\n <>\n <circle cx='12' cy='7' r='3' />\n <circle cx='12' cy='7' r='1.2' fill='currentColor' />\n <rect x='7' y='13' width='10' height='4' rx='1' fill='#3b82f6' stroke='#3b82f6' />\n <rect x='3' y='19' width='8' height='3' rx='1' fill='#eab308' stroke='#eab308' />\n <rect x='13' y='19' width='8' height='3' rx='1' fill='#f59e0b' stroke='#f59e0b' />\n <line x1='9' y1='17' x2='7' y2='19' />\n <line x1='15' y1='17' x2='17' y2='19' />\n </>\n );\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\nimport type { EventModelMessages } from '../Messages';\nimport type { MenuDropdownItem } from '../Menus';\nimport { SliceTypeIcon } from './SliceTypeIcon';\n\nexport const sliceTypes: readonly SliceType[] = [SliceType.stateChange, SliceType.stateView, SliceType.automation, SliceType.translator];\n\nexport const sliceTypeLabel = (type: SliceType, messages: EventModelMessages): string => {\n switch (type) {\n case SliceType.stateChange: return messages.sliceTypes.stateChange;\n case SliceType.stateView: return messages.sliceTypes.stateView;\n case SliceType.automation: return messages.sliceTypes.automation;\n case SliceType.translator: return messages.sliceTypes.translator;\n }\n};\n\nexport const sliceTypeDescription = (type: SliceType, messages: EventModelMessages): string => {\n switch (type) {\n case SliceType.stateChange: return messages.sliceTypes.stateChangeDescription;\n case SliceType.stateView: return messages.sliceTypes.stateViewDescription;\n case SliceType.automation: return messages.sliceTypes.automationDescription;\n case SliceType.translator: return messages.sliceTypes.translatorDescription;\n }\n};\n\n// One menu item per slice type, for any menu that adds a slice.\nexport const sliceTypeMenuItems = (messages: EventModelMessages, onSelect: (type: SliceType) => void): MenuDropdownItem[] =>\n sliceTypes.map(type => ({\n id: String(type),\n label: sliceTypeLabel(type, messages),\n description: sliceTypeDescription(type, messages),\n icon: <SliceTypeIcon type={type} />,\n onClick: () => onSelect(type),\n }));\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceTypeExplanation.css';\nimport type { SliceType } from '../Model';\nimport { useBoard } from '../Board';\nimport { sliceTypeDescription, sliceTypeLabel } from './sliceTypeMenuItems';\n\nexport interface SliceTypeExplanationProps {\n sliceType: SliceType;\n}\n\n// What kind of slice this is, said where its name is — the colors alone do not tell a newcomer.\nexport const SliceTypeExplanation = ({ sliceType }: SliceTypeExplanationProps) => {\n const { messages } = useBoard();\n return (\n <>\n <strong>{sliceTypeLabel(sliceType, messages)}</strong>\n <span className='event-modeling-grid-slice-type-explanation'>{sliceTypeDescription(sliceType, messages)}</span>\n </>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { SliceType } from '../Model';\nimport { useEventModelMessages } from '../Messages';\nimport { MenuDropdown } from '../Menus';\nimport { sliceTypeMenuItems } from './sliceTypeMenuItems';\n\nexport interface SliceTypeMenuProps {\n onSelect: (type: SliceType) => void;\n disabled?: boolean;\n}\n\nexport const SliceTypeMenu = ({ onSelect, disabled = false }: SliceTypeMenuProps) => {\n const messages = useEventModelMessages();\n return (\n <MenuDropdown\n trigger={\n <button className='event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle' title={messages.sliceTypes.add} disabled={disabled}>\n +\n </button>\n }\n items={sliceTypeMenuItems(messages, onSelect)}\n align='right'\n />\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceType } from '../Model';\nimport { MenuDropdown, type MenuDropdownItem } from '../Menus';\nimport { sliceTypeMenuItems } from '../SliceTypes';\nimport { useEventModelMessages } from '../Messages';\nimport type { FeatureHeaderMenuAction } from './FeatureHeaderMenuAction';\n\nexport interface FeatureAddMenuProps {\n featureId: Guid;\n onAddSubFeature?: () => void;\n onAddSlice?: (sliceType: SliceType) => void;\n actions?: readonly FeatureHeaderMenuAction[];\n}\n\nexport const FeatureAddMenu = ({ featureId, onAddSubFeature, onAddSlice, actions = [] }: FeatureAddMenuProps) => {\n const messages = useEventModelMessages();\n const triggerRef = useRef<HTMLButtonElement>(null);\n const [phase, setPhase] = useState<'main' | 'slice' | 'consumer'>('main');\n const [selectedConsumerActionId, setSelectedConsumerActionId] = useState<string>();\n const visibleActions = actions.filter(action => !action.when || action.when(featureId));\n if (!onAddSubFeature && !onAddSlice && visibleActions.length === 0) return null;\n\n const mainItems: MenuDropdownItem[] = [\n ...(onAddSlice ? [{ id: 'slice', label: messages.sliceTypes.add + ' ›', description: messages.features.addSliceDescription,\n keepOpen: true, onClick: () => setPhase('slice') }] : []),\n ...(onAddSubFeature ? [{ id: 'sub-feature', label: messages.features.addSubFeature,\n description: messages.features.addSubFeatureDescription, onClick: onAddSubFeature }] : []),\n ...visibleActions.map(action => ({ id: action.id, label: action.label + (action.items ? ' ›' : ''),\n description: action.description, icon: action.icon, disabled: action.disabled, tooltip: action.tooltip,\n keepOpen: !!action.items, onClick: () => {\n if (!action.items) return activate(action);\n setSelectedConsumerActionId(action.id);\n setPhase('consumer');\n } })),\n ];\n function activate(action: FeatureHeaderMenuAction) {\n const host = triggerRef.current?.getBoundingClientRect();\n if (host) action.onActivate(featureId, host);\n }\n const back: MenuDropdownItem = { id: 'back', label: messages.features.back, keepOpen: true, onClick: () => setPhase('main') };\n const sliceItems = onAddSlice ? [back, ...sliceTypeMenuItems(messages, onAddSlice)] : [back];\n const consumerItems = [back, ...(visibleActions.find(action => action.id === selectedConsumerActionId)?.items ?? [])\n .filter(action => !action.when || action.when(featureId))\n .map(action => ({ id: action.id, label: action.label, icon: action.icon, disabled: action.disabled,\n tooltip: action.tooltip, onClick: () => activate(action) }))];\n\n return <MenuDropdown\n trigger={<button ref={triggerRef} type='button'\n className='event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={messages.features.add} aria-label={messages.features.add}>+</button>}\n items={phase === 'main' ? mainItems : phase === 'slice' ? sliceItems : consumerItems}\n align='right' onClose={() => {\n setPhase('main');\n setSelectedConsumerActionId(undefined);\n }} />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\nimport type { MenuDropdownItem } from '../Menus';\nimport type { FeatureHeaderMenuAction } from './FeatureHeaderMenuAction';\n\nexport const featureHeaderMenuItems = (\n featureId: Guid,\n actions: readonly FeatureHeaderMenuAction[],\n hostRect: () => DOMRect | undefined,\n): MenuDropdownItem[] => actions.filter(action => !action.when || action.when(featureId)).map(action => ({\n id: action.id,\n label: action.label,\n description: action.description,\n icon: action.icon,\n disabled: action.disabled,\n tooltip: action.tooltip,\n isSeparator: action.isSeparator,\n items: action.items ? featureHeaderMenuItems(featureId, action.items, hostRect) : undefined,\n onClick: () => {\n const host = hostRect();\n if (host) action.onActivate(featureId, host);\n },\n}));\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { MenuDropdown } from '../Menus';\nimport { featureHeaderMenuItems } from './featureHeaderMenuItems';\nimport type { FeatureHeaderMenuAction } from './FeatureHeaderMenuAction';\n\nexport interface FeatureHeaderMenuProps {\n featureId: Guid;\n tooltip: string;\n icon: ReactNode;\n actions: readonly FeatureHeaderMenuAction[];\n}\n\nexport const FeatureHeaderMenu = ({ featureId, tooltip, icon, actions }: FeatureHeaderMenuProps) => {\n const triggerRef = useRef<HTMLButtonElement>(null);\n const items = featureHeaderMenuItems(featureId, actions, () => triggerRef.current?.getBoundingClientRect());\n if (items.length === 0) return null;\n\n return <MenuDropdown\n trigger={<button ref={triggerRef} type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={tooltip} aria-label={tooltip}>{icon}</button>}\n items={items} align='right' />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Headers/IconButton.css';\nimport '../Rows/AddButton.css';\nimport type { SliceType } from '../Model';\nimport { FeatureAddMenu } from './FeatureAddMenu';\nimport { FeatureHeaderMenu } from './FeatureHeaderMenu';\nimport { FeatureSuggestions } from './FeatureSuggestions';\nimport './FeatureHeader.css';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceStatus } from '../Model';\nimport { useBoard } from '../Board';\nimport { DetailsToggle, PillHeader } from '../Headers';\nimport { useHeaderDragIntent, type HeaderDragStart } from '../HeaderDragging';\nimport { useEventModelPresentation } from '../Presentation';\nimport { SliceStatusPicker } from '../Statuses';\n\nexport interface FeatureHeaderProps {\n featureId: Guid;\n name: string;\n height: number;\n collapsed: boolean;\n onToggleCollapse?: () => void;\n onRenamed?: (featureId: Guid, name: string) => void;\n status?: SliceStatus;\n detailsVisible?: boolean;\n onToggleDetails?: () => void;\n dragging?: boolean;\n onDragStart?: (start: HeaderDragStart) => void;\n error?: string;\n onAddSubFeature?: () => void;\n onAddSlice?: (sliceType: SliceType) => void;\n}\n\nconst background = 'rgba(160,140,230,0.10)';\nconst border = '1px solid rgba(160,140,230,0.22)';\n\nexport const FeatureHeader = ({\n featureId,\n name,\n height,\n collapsed,\n onToggleCollapse,\n onRenamed,\n status,\n detailsVisible = false,\n onToggleDetails,\n dragging = false,\n onDragStart,\n error,\n onAddSubFeature,\n onAddSlice,\n}: FeatureHeaderProps) => {\n const board = useBoard();\n const { showStatuses = true } = useEventModelPresentation();\n const dragHandlers = useHeaderDragIntent(!board.readOnly && !collapsed ? onDragStart : undefined);\n const renamed = board.readOnly ? undefined : onRenamed;\n const actions = (board.actions.featureHeader ?? []).filter(action => !action.when || action.when(featureId));\n const leadingActions = (board.actions.featureHeaderLeading ?? []).filter(action => !action.when || action.when(featureId));\n const menuActions = board.actions.featureHeaderMenu ?? [];\n\n return (\n <PillHeader\n variant='feature'\n collapsed={collapsed}\n onToggle={onToggleCollapse}\n leadingContent={!board.readOnly && leadingActions.map(action => <button\n key={action.tooltip} type='button' className='event-modeling-grid-icon-btn'\n title={action.disabled ? action.disabledTooltip ?? action.tooltip : action.tooltip} aria-label={action.tooltip} disabled={action.disabled}\n onClick={event => action.onActivate(featureId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}{action.indicator && <span className='event-modeling-feature-chat-dot' aria-hidden='true' />}</button>)}\n label={name}\n onRenameLabel={value => renamed?.(featureId, value)}\n labelReadOnly={!renamed}\n background={background}\n border={border}\n height={height}\n draggable={dragHandlers !== undefined}\n onPointerDown={dragHandlers?.onPointerDown}\n onPointerMove={dragHandlers?.onPointerMove}\n onPointerUp={dragHandlers?.onPointerUp}\n labelStyle={{\n fontSize: 12,\n fontWeight: 600,\n color: 'rgba(180,165,255,0.85)',\n textAlign: 'center',\n opacity: dragging ? 0.65 : 1,\n }}\n error={error}\n >\n {!collapsed && (\n <>\n {showStatuses && status !== undefined && <SliceStatusPicker status={status} />}\n {!board.readOnly && onToggleDetails && <DetailsToggle visible={detailsVisible} onToggle={onToggleDetails} />}\n {!board.readOnly && actions.map(action => <button\n key={action.tooltip} type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={action.disabled ? action.disabledTooltip ?? action.tooltip : action.tooltip} aria-label={action.tooltip} disabled={action.disabled}\n style={action.active ? { borderColor: 'var(--text-color)', color: 'var(--text-color)' } : undefined}\n onClick={event => action.onActivate(featureId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}</button>)}\n {!board.readOnly && <FeatureHeaderMenu featureId={featureId} tooltip={board.messages.features.options}\n icon={<svg width='13' height='13' viewBox='0 0 14 14' fill='none' aria-hidden='true'>\n <line x1='2' y1='3.5' x2='12' y2='3.5' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n <line x1='2' y1='7' x2='12' y2='7' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n <line x1='2' y1='10.5' x2='12' y2='10.5' stroke='currentColor' strokeWidth='1.4' strokeLinecap='round' />\n </svg>} actions={menuActions} />}\n {!board.readOnly && (board.actions.featureHeaderAfterMenu ?? []).filter(action => !action.when || action.when(featureId)).map(action => <button\n key={action.tooltip} type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={action.disabled ? action.disabledTooltip ?? action.tooltip : action.tooltip} aria-label={action.tooltip} disabled={action.disabled}\n onClick={event => action.onActivate(featureId, event.currentTarget.getBoundingClientRect())}\n >{action.icon}</button>)}\n {!board.readOnly && <FeatureSuggestions suggestions={board.actions.featureHeaderSuggestions ?? []} />}\n {!board.readOnly && <FeatureAddMenu featureId={featureId} onAddSubFeature={onAddSubFeature}\n onAddSlice={onAddSlice} actions={board.actions.featureHeaderAdd} />}\n </>\n )}\n </PillHeader>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SpecificationRunOutcome } from '../Model';\n\n/**\n * Represents the run state of a specification as shown in the UI.\n */\nexport enum SpecificationRunState {\n /** No run has happened and none is in progress. */\n Idle = 'idle',\n\n /** A run is currently in progress. */\n Running = 'running',\n\n /** The latest run passed. */\n Passed = 'passed',\n\n /** The latest run failed. */\n Failed = 'failed',\n\n /** The latest run could not be conclusively verified. */\n Inconclusive = 'inconclusive',\n}\n\n/**\n * Derives the UI run state from the latest persisted outcome and whether a run is currently in progress.\n * @param outcome The latest persisted outcome, or undefined when no run has completed.\n * @param isRunning Whether a run is currently in progress.\n * @returns The {@link SpecificationRunState}.\n */\nexport function specificationRunState(outcome: SpecificationRunOutcome | undefined, isRunning: boolean): SpecificationRunState {\n if (isRunning) {\n return SpecificationRunState.Running;\n }\n\n switch (outcome) {\n case SpecificationRunOutcome.passed:\n return SpecificationRunState.Passed;\n case SpecificationRunOutcome.failed:\n return SpecificationRunState.Failed;\n case SpecificationRunOutcome.inconclusive:\n return SpecificationRunState.Inconclusive;\n default:\n return SpecificationRunState.Idle;\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SpecificationRunButton.css';\nimport { useRef, useState } from 'react';\nimport { useBoard } from '../Board';\nimport { useSliceReadOnly } from '../Slices';\nimport type { SliceSpecification } from '../Model';\nimport { SpecificationRunState } from './SpecificationRunState';\n\nexport interface SpecificationRunButtonProps {\n state: SpecificationRunState;\n specification: SliceSpecification;\n}\n\nexport const SpecificationRunButton = ({ state, specification }: SpecificationRunButtonProps) => {\n const { actions } = useBoard();\n const readOnly = useSliceReadOnly();\n const inFlight = useRef(false);\n const [isPending, setIsPending] = useState(false);\n const isRunning = state === SpecificationRunState.Running;\n const action = isRunning ? actions.specificationStop : actions.specificationRun;\n if (!action || (action.when && !action.when(specification))) return null;\n\n const activate = async (host: DOMRect) => {\n if (readOnly) return;\n if (isRunning) {\n await action.onActivate(specification.id, host);\n return;\n }\n if (inFlight.current) return;\n inFlight.current = true;\n setIsPending(true);\n try {\n await action.onActivate(specification.id, host);\n } finally {\n inFlight.current = false;\n setIsPending(false);\n }\n };\n\n return <button type='button' className={`spec-run-button spec-run-button--${state}`}\n onClick={event => void activate(event.currentTarget.getBoundingClientRect())}\n disabled={readOnly || (isPending && !isRunning)} aria-label={action.tooltip} title={action.tooltip}>\n {isPending && !isRunning ? <i className='pi pi-spin pi-spinner' /> : action.icon}\n </button>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SpecificationStatus.css';\nimport React from 'react';\nimport { SpecificationRunState } from './SpecificationRunState';\nimport { useEventModelMessages } from '../Messages';\n\nconst ICONS: Record<SpecificationRunState, string> = {\n [SpecificationRunState.Idle]: 'pi pi-minus',\n [SpecificationRunState.Running]: 'pi pi-circle',\n [SpecificationRunState.Passed]: 'pi pi-check',\n [SpecificationRunState.Failed]: 'pi pi-times',\n [SpecificationRunState.Inconclusive]: 'pi pi-exclamation-triangle',\n};\n\nexport interface SpecificationStatusProps {\n /** The current run state of the specification. */\n state: SpecificationRunState;\n\n /** The last run's failure message, surfaced in the tooltip when the run failed. */\n message?: string;\n}\n\n/**\n * A circular status badge that reflects the outcome of a specification's last run — mirroring the slice status\n * badge — showing whether it has not been run, succeeded, or failed (with the failure reason in its tooltip).\n * When failed with a message, renders as a button to make the error more discoverable.\n */\nexport const SpecificationStatus: React.FC<SpecificationStatusProps> = ({ state, message }) => {\n const labels = useEventModelMessages().specificationStatus;\n\n const label = state === SpecificationRunState.Failed && message\n ? `${labels.failed}: ${message}`\n : labels[state];\n\n const hasError = state === SpecificationRunState.Failed && message;\n const className = `spec-status spec-status--${state}${hasError ? ' spec-status--has-error' : ''}`;\n\n return (\n <span className={className} title={label} aria-label={label} role={hasError ? 'button' : undefined} tabIndex={hasError ? 0 : undefined}>\n <i className={ICONS[state]} />\n </span>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './Specification.css';\nimport './SpecificationHeader.css';\nimport type { ReactNode } from 'react';\nimport { useBoard } from '../Board';\nimport { rowLabelWidth } from '../Geometry';\nimport { CollapseButton, EditableLabel } from '../Headers';\nimport { useSliceReadOnly } from '../Slices';\nimport { SpecificationRunState } from './SpecificationRunState';\nimport { SpecificationStatus } from './SpecificationStatus';\n\n// The height of the header row, so what sits in the gutter beside it centers on the header rather than on\n// the whole box, which grows when a failed run's message is shown under it.\nconst headerHeight = 44;\n\nexport interface SpecificationHeaderProps {\n name: string;\n collapsed: boolean;\n onToggleCollapse?: () => void;\n runState: SpecificationRunState;\n // Why the last run failed, shown under the header when it did.\n runMessage?: string;\n // Renaming exists only on an editable slice when this is supplied.\n onRenamed?: (name: string) => void;\n // Deleting exists only on an editable slice when this is supplied.\n onDeleted?: () => void;\n // The consumer's control for running the specification, drawn after its status.\n runControl?: ReactNode;\n // What the consumer draws in the row-label gutter beside the header.\n gutter?: ReactNode;\n}\n\n// The header of one specification: collapse, its name, how its last run went, and what can be done with it.\nexport const SpecificationHeader = ({\n name,\n collapsed,\n onToggleCollapse,\n runState,\n runMessage,\n onRenamed,\n onDeleted,\n runControl,\n gutter,\n}: SpecificationHeaderProps) => {\n const { messages, readOnly: boardReadOnly } = useBoard();\n const readOnly = useSliceReadOnly();\n const renamed = readOnly ? undefined : onRenamed;\n const deleted = readOnly ? undefined : onDeleted;\n\n return (\n <div className='event-modeling-grid-specification-outer-row'>\n <div className='event-modeling-grid-specification-label-gutter' style={{ width: rowLabelWidth, flexShrink: 0, alignSelf: 'flex-start', height: headerHeight, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>\n {gutter}\n </div>\n <div\n className={[\n 'event-modeling-grid-specification-box',\n 'event-modeling-grid-specification-box--header',\n collapsed ? 'event-modeling-grid-specification-box--last' : '',\n ].filter(Boolean).join(' ')}\n style={{ flex: 1, minWidth: 0 }}\n >\n <div className='event-modeling-grid-specification-header'>\n {!boardReadOnly && onToggleCollapse && <CollapseButton collapsed={collapsed} onToggle={readOnly ? undefined : onToggleCollapse} />}\n <div className='event-modeling-grid-specification-header-label'>\n <EditableLabel\n value={name}\n onChange={value => renamed?.(value)}\n placeholder={messages.specifications.namePlaceholder}\n style={{ fontSize: 11, fontWeight: 500, color: 'rgba(255,255,255,0.80)', textAlign: 'center' }}\n readOnly={!renamed}\n />\n </div>\n <SpecificationStatus state={runState} message={runMessage} />\n {runControl}\n {deleted && (\n <button\n type='button'\n className='spec-delete-button'\n onClick={deleted}\n aria-label={messages.specifications.delete}\n title={messages.specifications.delete}\n >\n <i className='pi pi-trash' />\n </button>\n )}\n </div>\n {runState === SpecificationRunState.Failed && runMessage && (\n <div className='spec-header-message' title={runMessage}>{runMessage}</div>\n )}\n </div>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { SliceSpecification } from '../Model';\nimport type { SpecificationEditing } from './SpecificationEditing';\n\nexport const GENERATED_SPECIFICATIONS_ABSORB_WINDOW_MS = 15_000;\n\nexport const specificationContentSize = (specification: SliceSpecification): number =>\n specification.given.length + (specification.when ? 1 : 0) +\n specification.thenEvents.length + specification.thenErrors.length;\n\nexport const followsIncomingSpecifications = (readOnly: boolean, editing: SpecificationEditing): boolean =>\n readOnly || !(editing.onSpecificationAdded || editing.onSpecificationRemoved ||\n editing.onSpecificationRenamed || editing.onSpecificationOpenStateSet || editing.onGivenEventAdded ||\n editing.onGivenEventValuesSet || editing.onGivenReadModelSet || editing.onWhenCommandSet ||\n editing.onWhenCommandValuesSet || editing.onThenEventAdded || editing.onThenEventValuesSet ||\n editing.onThenErrorAdded || editing.onThenRuleErrorAdded || editing.onThenErrorRenamed ||\n editing.onGivenEventRemoved || editing.onGivenReadModelRemoved || editing.onGivenReadModelValuesSet || editing.onThenEventRemoved || editing.onThenReadModelValuesSet ||\n editing.onThenErrorRemoved || editing.onSpecificationItemOpened);\n\nexport const reconcileSpecifications = (\n current: SliceSpecification[], incoming: SliceSpecification[], followsIncoming: boolean,\n withinGenerationWindow: boolean, removedIds: ReadonlySet<string>,\n): SliceSpecification[] => {\n if (followsIncoming) return incoming;\n return withinGenerationWindow ? absorbSpecifications(current, incoming, removedIds) : current;\n};\n\n// During generation the read side may first publish the new card without its rows. Never replace a\n// locally edited card with a smaller snapshot, or discard a card not yet visible in that snapshot.\nexport const absorbSpecifications = (current: SliceSpecification[], incoming: SliceSpecification[], removedIds: ReadonlySet<string> = new Set()): SliceSpecification[] => {\n const visibleIncoming = incoming.filter(specification => !removedIds.has(specification.id.toString()));\n const incomingById = new Map(visibleIncoming.map(specification => [specification.id.toString(), specification]));\n const merged = current.map(specification => {\n const candidate = incomingById.get(specification.id.toString());\n return candidate && specificationContentSize(candidate) > specificationContentSize(specification) ? candidate : specification;\n });\n const known = new Set(current.map(specification => specification.id.toString()));\n const added = visibleIncoming.filter(specification => !known.has(specification.id.toString()));\n return added.length || merged.some((specification, index) => specification !== current[index]) ? [...merged, ...added] : current;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/AddButton.css';\nimport './SpecificationCollection.css';\nimport { useEffect, useRef, useState, type ReactNode } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport type { SliceSpecification } from '../Model';\nimport { useBoard } from '../Board';\nimport { useSliceReadOnly } from '../Slices';\nimport { GridTooltip } from '../Tooltips';\nimport { rowLabelWidth } from '../Geometry';\nimport { SpecificationHeader } from './SpecificationHeader';\nimport { SpecificationRunState } from './SpecificationRunState';\nimport { SpecificationRunButton } from './SpecificationRunButton';\nimport { followsIncomingSpecifications, GENERATED_SPECIFICATIONS_ABSORB_WINDOW_MS, reconcileSpecifications, specificationContentSize } from './specificationCollectionState';\n\nexport interface SpecificationCollectionProps {\n sliceId: Guid;\n width: number;\n collapsed: boolean;\n specifications: SliceSpecification[];\n runInfoFor: (specification: SliceSpecification) => { state: SpecificationRunState; message: string };\n renderRows: (specification: SliceSpecification) => ReactNode;\n}\n\nlet specificationCounter = 1;\n\nexport const SpecificationCollection = ({ sliceId, width, collapsed, specifications: incoming, runInfoFor, renderRows }: SpecificationCollectionProps) => {\n const { editing, actions, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const [specifications, setSpecifications] = useState(incoming);\n const [isGenerating, setIsGenerating] = useState(false);\n const [isRunningAll, setIsRunningAll] = useState(false);\n const [isAdding, setIsAdding] = useState(false);\n const absorbUntil = useRef(0);\n const addInFlight = useRef(false);\n const generateInFlight = useRef(false);\n const runAllInFlight = useRef(false);\n const removedIds = useRef(new Set<string>());\n const followsIncoming = followsIncomingSpecifications(readOnly, editing);\n const visibleSpecifications = followsIncoming ? incoming : specifications;\n\n useEffect(() => {\n setSpecifications(previous => reconcileSpecifications(previous, incoming, followsIncoming,\n Date.now() <= absorbUntil.current, removedIds.current));\n }, [incoming, followsIncoming]);\n\n const add = async () => {\n if (addInFlight.current || !editing.onSpecificationAdded) return;\n addInFlight.current = true;\n setIsAdding(true);\n const specification: SliceSpecification = {\n id: Guid.create(), name: `${messages.specifications.namePlaceholder} ${specificationCounter++}`, collapsed: false,\n given: [], thenEvents: [], thenErrors: [],\n };\n setSpecifications(previous => [...previous, specification]);\n try {\n if (!await editing.onSpecificationAdded(sliceId, specification)) {\n setSpecifications(previous => previous.filter(item => !item.id.equals(specification.id)));\n }\n } catch {\n setSpecifications(previous => previous.filter(item => !item.id.equals(specification.id)));\n } finally {\n addInFlight.current = false;\n setIsAdding(false);\n }\n };\n const remove = (specificationId: Guid) => {\n if (removedIds.current.has(specificationId.toString())) return;\n removedIds.current.add(specificationId.toString());\n absorbUntil.current = 0;\n setSpecifications(previous => previous.filter(specification => !specification.id.equals(specificationId)));\n editing.onSpecificationRemoved?.(sliceId, specificationId);\n };\n const rename = (specificationId: Guid, name: string) => {\n setSpecifications(previous => previous.map(specification => specification.id.equals(specificationId) ? { ...specification, name } : specification));\n editing.onSpecificationRenamed?.(sliceId, specificationId, name);\n };\n const toggle = (specificationId: Guid, isOpen: boolean) => {\n if (readOnly || !editing.onSpecificationOpenStateSet) return;\n setSpecifications(previous => previous.map(specification => specification.id.equals(specificationId) ? { ...specification, collapsed: !isOpen } : specification));\n editing.onSpecificationOpenStateSet?.(sliceId, specificationId, isOpen);\n };\n const generate = async (host: DOMRect) => {\n if (readOnly || generateInFlight.current || !actions.specificationsGenerate) return;\n generateInFlight.current = true;\n setIsGenerating(true);\n try {\n if (await actions.specificationsGenerate.onActivate(sliceId, host)) {\n absorbUntil.current = Date.now() + GENERATED_SPECIFICATIONS_ABSORB_WINDOW_MS;\n }\n } finally {\n generateInFlight.current = false;\n setIsGenerating(false);\n }\n };\n const runAll = async (host: DOMRect) => {\n if (readOnly || runAllInFlight.current || !actions.specificationsRunAll || actions.specificationsRunAll.disabled) return;\n runAllInFlight.current = true;\n setIsRunningAll(true);\n try {\n await actions.specificationsRunAll.onActivate(sliceId, host);\n } finally {\n runAllInFlight.current = false;\n setIsRunningAll(false);\n }\n };\n const generateAction = actions.specificationsGenerate;\n const runAllAction = actions.specificationsRunAll;\n const showGenerate = !readOnly && generateAction && (!generateAction.when || generateAction.when(sliceId));\n\n if (collapsed) return null;\n return <>\n {visibleSpecifications.map((specification, index) => {\n const { state, message } = runInfoFor(specification);\n return <div key={`${specification.id.toString()}:${specificationContentSize(specification)}`}\n data-slice-spec-col='true' data-slice-id={sliceId.toString()}\n className={`event-modeling-grid-specification-wrapper event-modeling-grid-specification-wrapper--${state}`}\n style={{ width: rowLabelWidth + width }}>\n <SpecificationHeader name={specification.name} collapsed={specification.collapsed}\n onToggleCollapse={editing.onSpecificationOpenStateSet ? () => toggle(specification.id, specification.collapsed) : undefined}\n onRenamed={editing.onSpecificationRenamed ? name => rename(specification.id, name) : undefined}\n onDeleted={editing.onSpecificationRemoved ? () => remove(specification.id) : undefined}\n runState={state} runMessage={message}\n runControl={<SpecificationRunButton state={state} specification={specification} />}\n gutter={index === 0 && runAllAction && (!runAllAction.when || runAllAction.when(sliceId)) && <button type='button'\n className='event-modeling-grid-add-button--small spec-run-all-button'\n onClick={event => void runAll(event.currentTarget.getBoundingClientRect())}\n disabled={readOnly || isRunningAll || runAllAction.disabled} aria-label={runAllAction.tooltip} title={runAllAction.tooltip}>\n {runAllAction.icon}\n </button>} />\n {!specification.collapsed && renderRows(specification)}\n </div>;\n })}\n {!readOnly && (editing.onSpecificationAdded || showGenerate) && <div className='event-modeling-grid-specification-add-area'>\n {editing.onSpecificationAdded && <GridTooltip content={messages.specifications.add} position='top'>\n <button type='button' onClick={() => void add()} disabled={isAdding} className='event-modeling-grid-add-button--small' aria-label={messages.specifications.add}>+</button>\n </GridTooltip>}\n {showGenerate && <GridTooltip content={generateAction.tooltip} position='top'>\n <button type='button' onClick={event => void generate(event.currentTarget.getBoundingClientRect())}\n disabled={isGenerating} className='event-modeling-grid-add-button--small' aria-label={generateAction.tooltip}>\n {isGenerating ? <i className='pi pi-spin pi-spinner' /> : generateAction.icon}\n </button>\n </GridTooltip>}\n </div>}\n </>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './Specification.css';\nimport type { ReactNode } from 'react';\nimport { useSliceReadOnly } from '../Slices';\n\nexport interface SpecificationSectionProps {\n // The section's name, such as Given, When or Then.\n headline?: string;\n // The minimum height of the section, so the sections of a specification line up across slices.\n minHeight: number;\n // What the consumer offers for adding to the section. Nothing is offered on a read-only slice.\n actions?: ReactNode;\n // The section's cards.\n children?: ReactNode;\n}\n\n// One section of a specification: its name, its cards, and a row for what can be added to it.\nexport const SpecificationSection = ({ headline, minHeight, actions, children }: SpecificationSectionProps) => {\n const readOnly = useSliceReadOnly();\n return (\n <div className='event-modeling-grid-specification-section' style={{ minHeight }}>\n {headline && <span className='event-modeling-grid-specification-section-headline'>{headline}</span>}\n <div className='event-modeling-grid-specification-section-content'>{children}</div>\n <div className='event-modeling-grid-specification-section-actions'>{readOnly ? undefined : actions}</div>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Finds the index of the best place to break a PascalCase name (e.g. an event or command type name like\n * `CustomerAddressUpdated`) into two lines, so a wrapped card title breaks at a word boundary rather than\n * mid-word. Candidates are ranked in two tiers, closest-to-the-middle first within each tier:\n *\n * 1. A \"word start\" — an uppercase letter directly preceded by a lowercase letter (`...ss|Up...` in\n * `AddressUpdated`). This is the overwhelmingly common case for Cratis event/command names.\n * 2. Any other uppercase letter (index > 0) — a fallback for names built from acronym runs\n * (`HTTPServer`) where tier 1 finds nothing, since there is no lowercase-to-uppercase transition.\n *\n * Returns `null` when the text has no uppercase letter to break before (e.g. a single lowercase word, or\n * text too short to usefully split) — callers fall back to a plain midpoint split in that case.\n */\nexport function nearestPascalCaseBreakIndex(text: string): number | null {\n const middle = text.length / 2;\n const wordStarts: number[] = [];\n const anyUppercase: number[] = [];\n\n for (let index = 1; index < text.length; index++) {\n const character = text[index];\n if (character < 'A' || character > 'Z') continue;\n\n anyUppercase.push(index);\n if (text[index - 1] >= 'a' && text[index - 1] <= 'z') wordStarts.push(index);\n }\n\n const candidates = wordStarts.length > 0 ? wordStarts : anyUppercase;\n if (candidates.length === 0) return null;\n\n return candidates.reduce((closest, candidate) =>\n Math.abs(candidate - middle) < Math.abs(closest - middle) ? candidate : closest);\n}\n\n/**\n * Splits a PascalCase name into two lines at the {@link nearestPascalCaseBreakIndex}. Falls back to an\n * even midpoint split when no uppercase boundary exists, so every name can still be wrapped rather than\n * truncated with an ellipsis.\n */\nexport function splitAtPascalCaseBreak(text: string): [string, string] {\n const breakIndex = nearestPascalCaseBreakIndex(text) ?? Math.ceil(text.length / 2);\n return [text.slice(0, breakIndex), text.slice(breakIndex)];\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { splitAtPascalCaseBreak } from './pascalCaseBreak';\n\n/** The default largest font size a card title renders at — matches the existing card face font size. */\nexport const DEFAULT_MAX_TITLE_FONT_SIZE_PX = 13;\n\n/** The default smallest single-line font size before a title switches to wrapping across two lines. */\nexport const DEFAULT_MIN_TITLE_FONT_SIZE_PX = 10;\n\n/** Measures the rendered pixel width of `text` at `fontSizePx`. Implemented with real font metrics by\n * {@link useAutoFitTitle}; injected here so {@link computeAutoFitTitle} stays a pure, spec-able function. */\nexport type MeasureTextWidth = (text: string, fontSizePx: number) => number;\n\nexport interface AutoFitTitleOptions {\n\n /** The largest font size to try, in pixels. */\n maxFontSizePx: number;\n\n /** The smallest single-line font size to try before falling back to a two-line wrap, in pixels. */\n minFontSizePx: number;\n\n /** The width available to the title, in pixels. */\n availableWidthPx: number;\n}\n\nexport interface AutoFitTitleResult {\n\n /** The font size to render the title at, in pixels. */\n fontSizePx: number;\n\n /** The line(s) to render. A single entry when the title fits on one line; two when it was wrapped. */\n lines: string[];\n}\n\n/**\n * Finds the largest font size (within `options`) at which `text` fits on a single line within\n * `availableWidthPx`, shrinking from `maxFontSizePx` down to `minFontSizePx`. When even `minFontSizePx`\n * does not fit on one line, wraps the text across two lines at the nearest PascalCase word boundary\n * (see {@link splitAtPascalCaseBreak}) and renders those at `minFontSizePx`, rather than shrinking the\n * font further into unreadable territory.\n */\nexport function computeAutoFitTitle(text: string, options: AutoFitTitleOptions, measure: MeasureTextWidth): AutoFitTitleResult {\n const { maxFontSizePx, minFontSizePx, availableWidthPx } = options;\n\n for (let fontSizePx = maxFontSizePx; fontSizePx >= minFontSizePx; fontSizePx--) {\n if (measure(text, fontSizePx) <= availableWidthPx) {\n return { fontSizePx, lines: [text] };\n }\n }\n\n return { fontSizePx: minFontSizePx, lines: splitAtPascalCaseBreak(text) };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { RefObject, useLayoutEffect, useRef, useState } from 'react';\nimport { AutoFitTitleResult, DEFAULT_MAX_TITLE_FONT_SIZE_PX, DEFAULT_MIN_TITLE_FONT_SIZE_PX, computeAutoFitTitle } from './autoFitTitle';\n\nlet measureContext: CanvasRenderingContext2D | null = null;\n\n/** A shared, lazily-created off-screen canvas 2D context for text metrics — cheap to reuse across every card. */\nfunction getMeasureContext(): CanvasRenderingContext2D | null {\n if (measureContext) return measureContext;\n if (typeof document === 'undefined') return null;\n measureContext = document.createElement('canvas').getContext('2d');\n return measureContext;\n}\n\nexport interface UseAutoFitTitleOptions {\n\n /** The CSS font-family the title renders with — must match the element's actual styling for accurate measurement. */\n fontFamily: string;\n\n /** The CSS font-weight the title renders with. */\n fontWeight: string | number;\n\n /** The largest font size to try, in pixels. Defaults to {@link DEFAULT_MAX_TITLE_FONT_SIZE_PX}. */\n maxFontSizePx?: number;\n\n /** The smallest single-line font size before wrapping, in pixels. Defaults to {@link DEFAULT_MIN_TITLE_FONT_SIZE_PX}. */\n minFontSizePx?: number;\n}\n\n/**\n * Measures `text` against the width of the element attached to the returned ref and shrinks/wraps it to\n * fit, via {@link computeAutoFitTitle}. Re-measures whenever the text or font options change.\n *\n * The element the ref attaches to must already be laid out at its final width when this runs (a block\n * element that doesn't grow with its own text content, e.g. `white-space: nowrap; overflow: hidden`) —\n * its `clientWidth` at effect time is taken as the space available to the title.\n */\nexport function useAutoFitTitle<T extends HTMLElement>(text: string, options: UseAutoFitTitleOptions): [RefObject<T | null>, AutoFitTitleResult] {\n const elementRef = useRef<T | null>(null);\n const maxFontSizePx = options.maxFontSizePx ?? DEFAULT_MAX_TITLE_FONT_SIZE_PX;\n const minFontSizePx = options.minFontSizePx ?? DEFAULT_MIN_TITLE_FONT_SIZE_PX;\n const [result, setResult] = useState<AutoFitTitleResult>({ fontSizePx: maxFontSizePx, lines: [text] });\n\n useLayoutEffect(() => {\n const element = elementRef.current;\n const context = getMeasureContext();\n if (!element || !context) return;\n\n const measure = (candidate: string, fontSizePx: number): number => {\n context.font = `${options.fontWeight} ${fontSizePx}px ${options.fontFamily}`;\n return context.measureText(candidate).width;\n };\n\n setResult(computeAutoFitTitle(text, { maxFontSizePx, minFontSizePx, availableWidthPx: element.clientWidth }, measure));\n }, [text, maxFontSizePx, minFontSizePx, options.fontWeight, options.fontFamily]);\n\n return [elementRef, result];\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './Card.css';\nimport React, { useRef, useEffect, useCallback } from 'react';\nimport { useAutoFitTitle } from './useAutoFitTitle';\n\nconst DOUBLE_CLICK_DELAY_MS = 250;\n\n/** Matches `.event-modeling-card__face`'s `font-family` in Card.css — the title measures against it. */\nconst TITLE_FONT_FAMILY = 'Inter, Helvetica, Arial, sans-serif';\n\nexport interface CardProps {\n name: string;\n backgroundColor: string;\n textColor: string;\n isSelected?: boolean;\n disabled?: boolean;\n onSelected?: () => void;\n onStartEdit?: () => void;\n extraContent?: React.ReactNode;\n children?: React.ReactNode;\n ariaLabel?: string;\n ariaPressed?: boolean;\n 'data-event-id'?: string;\n 'data-card-id'?: string;\n 'data-slice-id'?: string;\n}\n\nexport const Card: React.FC<CardProps> = ({\n name,\n backgroundColor,\n textColor,\n isSelected = false,\n disabled = false,\n onSelected,\n onStartEdit,\n extraContent,\n children,\n ariaLabel,\n ariaPressed,\n 'data-event-id': dataEventId,\n 'data-card-id': dataCardId,\n 'data-slice-id': dataSliceId,\n}) => {\n const pendingClick = useRef<ReturnType<typeof setTimeout> | null>(null);\n const isInteractive = Boolean(onSelected ?? onStartEdit) || disabled;\n const [titleRef, titleFit] = useAutoFitTitle<HTMLElement>(name, { fontFamily: TITLE_FONT_FAMILY, fontWeight: 'bold' });\n\n useEffect(() => () => {\n if (pendingClick.current) clearTimeout(pendingClick.current);\n }, []);\n\n const handleClick = useCallback((event: React.MouseEvent) => {\n event.stopPropagation();\n if (pendingClick.current) {\n clearTimeout(pendingClick.current);\n pendingClick.current = null;\n return;\n }\n pendingClick.current = setTimeout(() => {\n pendingClick.current = null;\n onSelected?.();\n }, DOUBLE_CLICK_DELAY_MS);\n }, [onSelected]);\n\n const handleDoubleClick = useCallback((event: React.MouseEvent) => {\n event.stopPropagation();\n if (pendingClick.current) {\n clearTimeout(pendingClick.current);\n pendingClick.current = null;\n }\n onStartEdit?.();\n }, [onStartEdit]);\n\n const selectionStyle: React.CSSProperties = isSelected\n ? { outline: `2px solid ${backgroundColor}`, outlineOffset: 2 }\n : {};\n\n const faceStyle: React.CSSProperties = {\n background: backgroundColor,\n color: textColor,\n };\n\n const faceContent = (\n <>\n <div className='event-modeling-card__face' style={faceStyle}>\n <strong ref={titleRef} className='event-modeling-card__title' style={{ fontSize: titleFit.fontSizePx }}>\n {titleFit.lines.length > 1\n ? titleFit.lines.map((line, index) => <span key={index} className='event-modeling-card__title-line'>{line}</span>)\n : titleFit.lines[0]}\n </strong>\n {extraContent}\n </div>\n {children}\n </>\n );\n\n if (isInteractive) {\n return (\n <button\n className='event-modeling-card'\n style={selectionStyle}\n disabled={disabled}\n onClick={handleClick}\n onDoubleClick={handleDoubleClick}\n aria-label={ariaLabel}\n aria-pressed={ariaPressed}\n data-event-id={dataEventId}\n data-card-id={dataCardId}\n data-slice-id={dataSliceId}\n >\n {faceContent}\n </button>\n );\n }\n\n return (\n <div\n className='event-modeling-card'\n data-event-id={dataEventId}\n data-card-id={dataCardId}\n data-slice-id={dataSliceId}\n >\n {faceContent}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Raw hex values for card colors.\n *\n * These MUST match the CSS custom properties defined in .frontend/index.css\n * (--card-event-bg, --card-command-bg, etc.) so that both JS-driven inline\n * styles and CSS class rules resolve to the same palette.\n */\n\n/** Background and text colors for event-modeling card types. */\nexport interface CardColors {\n /** Card face background color. */\n background: string;\n /** Card face text color. */\n text: string;\n}\n\n/** Event (domain event) card colors — warm orange. */\nexport const eventCardColors: CardColors = {\n background: '#ff9933',\n text: '#2a1500',\n};\n\n/** Command card colors — sky blue. */\nexport const commandCardColors: CardColors = {\n background: '#42b3ff',\n text: '#003d5c',\n};\n\n/** Read model card colors — lime green. */\nexport const readModelCardColors: CardColors = {\n background: '#c8e03a',\n text: '#1f2a00',\n};\n\n/** External event (event from another module the Translator translates from) card colors — yellow, the event-modeling convention for external events. */\nexport const externalEventCardColors: CardColors = {\n background: '#ffd633',\n text: '#4d3d00',\n};\n\n/**\n * Concept card colors — violet, the color the event-model board already gives to the structural\n * (feature) level rather than to any of the event/command/read-model artifacts. A concept is neither of\n * those, so it gets its own place in the same palette instead of borrowing one of theirs.\n */\nexport const conceptCardColors: CardColors = {\n background: '#b4a5ff',\n text: '#1c1040',\n};\n\n/** Error card colors — red. */\nexport const errorCardColors: CardColors = {\n background: '#e05050',\n text: '#ffffff',\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './TypeBadge.css';\nimport React from 'react';\nimport { conceptCardColors } from '../Cards';\n\nconst CalendarIcon = () => (\n <svg viewBox='0 0 12 12' fill='none' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' width='11' height='11'>\n <rect x='1' y='2.5' width='10' height='8.5' rx='1.5' />\n <path d='M1 5.5h10M4 1v3M8 1v3' />\n </svg>\n);\n\nconst ClockIcon = () => (\n <svg viewBox='0 0 12 12' fill='none' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' width='11' height='11'>\n <circle cx='6' cy='6' r='4.5' />\n <path d='M6 3.5v2.5l2 1' />\n </svg>\n);\n\ninterface BadgeConfig {\n content: React.ReactNode;\n color: string;\n background: string;\n}\n\nconst BADGE_MAP: Record<string, BadgeConfig> = {\n // PropertyType enum values\n string: { content: 'Aa', color: '#fff', background: '#0891b2' },\n number: { content: '123', color: '#fff', background: '#dc2626' },\n boolean: { content: 'T/F', color: '#fff', background: '#16a34a' },\n date: { content: <CalendarIcon />, color: '#fff', background: '#ea580c' },\n time: { content: <ClockIcon />, color: '#fff', background: '#7c6d14' },\n object: { content: '{}', color: '#fff', background: '#7c3aed' },\n stringArray: { content: '[A]', color: '#fff', background: '#0e7490' },\n numberArray: { content: '[#]', color: '#fff', background: '#b91c1c' },\n objectArray: { content: '[{}]', color: '#fff', background: '#6d28d9' },\n // JSON Schema type strings (used in event schemas)\n integer: { content: '123', color: '#fff', background: '#dc2626' },\n array: { content: '[ ]', color: '#fff', background: '#6d28d9' },\n null: { content: '∅', color: '#fff', background: '#6b7280' },\n};\n\nconst DEFAULT_CONFIG: BadgeConfig = { content: '#', color: '#fff', background: '#6b7280' };\n\nexport interface TypeBadgeProps {\n\n type: string;\n\n /**\n * The concept the property is typed as. When set, the badge names the concept instead of the primitive\n * it wraps — the primitive stays in the tooltip, since that is what the value still behaves as.\n */\n concept?: string;\n}\n\nexport const TypeBadge: React.FC<TypeBadgeProps> = ({ type, concept }) => {\n if (concept) {\n return (\n <span\n className='type-badge type-badge--concept'\n style={{ color: conceptCardColors.text, background: conceptCardColors.background }}\n title={`${concept} (${type})`}\n >\n {concept}\n </span>\n );\n }\n\n const config = BADGE_MAP[type] ?? DEFAULT_CONFIG;\n return (\n <span\n className='type-badge'\n style={{ color: config.color, background: config.background }}\n title={type}\n >\n {config.content}\n </span>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SchemaTooltipProperties.css';\nimport React, { useMemo } from 'react';\nimport type { JsonSchema } from '@cratis/components/SchemaEditor';\nimport { TypeBadge } from './TypeBadge';\nimport { topLevelSchemaProperties } from './schemaProperties';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface SchemaTooltipPropertiesProps {\n title: React.ReactNode;\n schema?: string | JsonSchema;\n showTitle?: boolean;\n compact?: boolean;\n}\n\nexport const SchemaTooltipProperties: React.FC<SchemaTooltipPropertiesProps> = ({ title, schema, showTitle = true, compact = false }) => {\n const messages = useEventModelMessages();\n const properties = useMemo(() => topLevelSchemaProperties(schema), [schema]);\n\n return (\n <div className={`schema-tooltip-properties${compact ? ' schema-tooltip-properties--compact' : ''}`}>\n {showTitle && <div className='schema-tooltip-properties__title'>{title}</div>}\n {properties.length > 0 ? (\n <div className='schema-tooltip-properties__list'>\n {properties.map(property => (\n <div key={`${property.name}-${property.type}`} className='schema-tooltip-properties__row'>\n <TypeBadge type={property.type} />\n <span className='schema-tooltip-properties__name'>{property.name}</span>\n </div>\n ))}\n </div>\n ) : (\n <div className='schema-tooltip-properties__empty'>{messages.properties.none}</div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport enum ArtifactCardKind {\n command = 'command',\n readModel = 'readModel',\n event = 'event',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Where on the card's top edge an action sits. Actions at the same corner line up inward from it, in the\n// order they are given.\nexport enum CardCorner {\n start = 'start',\n end = 'end',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { CardAction } from './CardAction';\nimport { CardCorner } from './CardCorner';\n\nexport interface CardActionButtonProps {\n action: CardAction;\n corner: CardCorner;\n slot: number;\n onActivate: () => void;\n}\n\n// Actions sit 24 pixels apart, the first one overhanging the corner by 6.\nconst slotOffset = (slot: number) => slot * 24 - 6;\n\nexport const CardActionButton = ({ action, corner, slot, onActivate }: CardActionButtonProps) => {\n const className = [\n 'event-modeling-card-action',\n action.active && 'event-modeling-card-action--active',\n action.disabled && 'event-modeling-card-action--disabled',\n ].filter(Boolean).join(' ');\n\n return (\n <button\n className={className}\n data-corner={corner}\n style={{ [corner === CardCorner.start ? 'left' : 'right']: slotOffset(slot) }}\n disabled={action.disabled || action.busy}\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n onActivate();\n }}\n aria-label={action.tooltip}\n title={action.tooltip}\n >\n <i className={action.icon} />\n </button>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EventTags.css';\n\nexport interface EventTagsProps {\n /** The tags to render. */\n tags?: readonly string[];\n}\n\n/**\n * Renders the tags of an event type as a row of chips on the event card.\n */\nexport const EventTags = ({ tags }: EventTagsProps) => {\n if (!tags || tags.length === 0) {\n return null;\n }\n\n return (\n <div className='event-modeling-event-tags'>\n {tags.map(tag => (\n <span key={tag} className='event-modeling-event-tag' title={tag}>{tag}</span>\n ))}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ArtifactCard.css';\nimport React, { useRef } from 'react';\nimport type { JsonSchema } from '@cratis/components/SchemaEditor';\nimport type { Guid } from '@cratis/fundamentals';\nimport { SchemaTooltipProperties } from '../Properties';\nimport { useSliceReadOnly } from '../Slices';\nimport { ArtifactCardKind } from './ArtifactCardKind';\nimport { Card, type CardProps } from './Card';\nimport type { CardAction } from './CardAction';\nimport { CardActionButton } from './CardActionButton';\nimport { CardCorner } from './CardCorner';\nimport { commandCardColors, eventCardColors, readModelCardColors } from './cardColors';\nimport { EventTags } from './EventTags';\n\nexport interface ArtifactCardProps extends Omit<CardProps, 'backgroundColor' | 'textColor' | 'extraContent'> {\n kind: ArtifactCardKind;\n artifactId?: Guid;\n // A line of text under the name, such as a description or the names of the properties.\n summary?: string;\n tags?: readonly string[];\n schema?: string | JsonSchema;\n showDetails?: boolean;\n actions?: readonly CardAction[];\n // Clicking the card of an editable slice activates it instead of selecting it.\n onActivate?: (artifactId: Guid, host: DOMRect) => void;\n}\n\nconst colors = {\n [ArtifactCardKind.command]: commandCardColors,\n [ArtifactCardKind.readModel]: readModelCardColors,\n [ArtifactCardKind.event]: eventCardColors,\n};\n\nconst anchorClassName = {\n [ArtifactCardKind.command]: 'event-modeling-command',\n [ArtifactCardKind.readModel]: 'event-modeling-read-model',\n [ArtifactCardKind.event]: 'event-modeling-event',\n};\n\nconst summaryStyle: React.CSSProperties = { fontSize: 11, opacity: 0.8, marginTop: 4 };\n\nexport const ArtifactCard = ({ kind, artifactId, summary, tags, schema, showDetails = false, actions = [], onActivate, onSelected, ...cardProps }: ArtifactCardProps) => {\n const readOnly = useSliceReadOnly();\n const host = useRef<HTMLDivElement>(null);\n const hostRect = () => host.current?.getBoundingClientRect() ?? new DOMRect();\n const drawn = readOnly ? [] : actions.filter(action => !action.when || (!!artifactId && action.when(artifactId)));\n const inCorner = (corner: CardCorner) => drawn.filter(action => (action.corner ?? CardCorner.end) === corner);\n\n const card = (\n <div ref={host}>\n <Card\n backgroundColor={colors[kind].background}\n textColor={colors[kind].text}\n extraContent={(\n <>\n <EventTags tags={tags} />\n {summary && <div style={summaryStyle}>{summary}</div>}\n {showDetails && <SchemaTooltipProperties title={cardProps.name} schema={schema} showTitle={false} compact={true} />}\n </>\n )}\n onSelected={() => {\n if (onActivate && artifactId && !readOnly) {\n onActivate(artifactId, hostRect());\n return;\n }\n onSelected?.();\n }}\n {...cardProps}\n />\n </div>\n );\n\n // An event card has only ever been anchored when it has actions to anchor; the others always are.\n if (kind === ArtifactCardKind.event && drawn.length === 0) return card;\n\n return (\n <div className={anchorClassName[kind]} data-artifact-kind={kind}>\n {card}\n {[CardCorner.start, CardCorner.end].flatMap(corner => inCorner(corner).map((action, slot) => (\n <CardActionButton\n key={`${corner}-${slot}`}\n action={action}\n corner={corner}\n slot={slot}\n onActivate={() => artifactId && action.onActivate(artifactId, hostRect())}\n />\n )))}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\n\nexport interface CardNameInputProps {\n value: string;\n backgroundColor: string;\n textColor: string;\n nameError?: string;\n onChange: (value: string) => void;\n onCommit: () => void;\n onCancel: () => void;\n}\n\n// A card-shaped text field for renaming a card in place: Enter commits, Escape cancels, leaving commits.\nexport const CardNameInput: React.FC<CardNameInputProps> = ({\n value,\n backgroundColor,\n textColor,\n nameError,\n onChange,\n onCommit,\n onCancel,\n}) => (\n <div\n style={{\n width: 'var(--card-width)',\n minHeight: 'var(--card-min-height)',\n padding: 'var(--card-padding-y) var(--card-padding-x)',\n borderRadius: 'var(--card-radius)',\n boxSizing: 'border-box',\n display: 'flex',\n flexDirection: 'column',\n justifyContent: 'center',\n background: backgroundColor,\n boxShadow: '0 1px 4px rgba(0,0,0,0.18)',\n }}\n >\n <input\n autoFocus\n value={value}\n onChange={event => onChange(event.target.value)}\n onBlur={onCommit}\n onKeyDown={event => {\n if (event.key === 'Enter') onCommit();\n if (event.key === 'Escape') onCancel();\n }}\n onClick={event => event.stopPropagation()}\n title={nameError}\n style={{\n border: nameError ? '2px solid #f87171' : 'none',\n borderRadius: nameError ? 3 : 0,\n outline: 'none',\n background: 'transparent',\n width: '100%',\n fontWeight: 'bold',\n fontSize: 'var(--card-font-size)',\n lineHeight: 'var(--card-line-height)',\n fontFamily: 'Inter, Helvetica, Arial, sans-serif',\n color: textColor,\n textAlign: 'center',\n }}\n />\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The values set on each item of a section, by item id, as they are set here and as the items carried them.\nexport type ItemValues = Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n\nexport const itemValuesOf = (items: readonly { id: { toString(): string }; values: Record<string, unknown> }[]): ItemValues =>\n Object.fromEntries(items.map(item => [item.id.toString(), item.values]));\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './PickerPanel.css';\nimport React, { useMemo, useRef, useState } from 'react';\nimport { AnchoredOverlay } from '../Tooltips';\nimport { useDismissOnOutsidePointer } from './useDismissOnOutsidePointer';\n\n// More options than this and the panel offers a search field.\nconst searchThreshold = 5;\n\nexport interface PickerTriggerProps {\n open: boolean;\n toggle: () => void;\n}\n\nexport interface PickerPanelProps<TOption> {\n options: readonly TOption[];\n // What an option is called, shown in the list and matched by the search.\n nameOf: (option: TOption) => string;\n // The color marking each option.\n color: string;\n searchPlaceholder: string;\n emptyLabel: string;\n onSelect: (option: TOption) => void;\n // List items drawn after the options, whatever the search. Receives close, to call once one is used.\n footer?: (close: () => void) => React.ReactNode;\n // Draws what opens the panel. The panel floats above it, aligned to its right edge.\n trigger: (props: PickerTriggerProps) => React.ReactNode;\n}\n\nexport const PickerPanel = <TOption,>({ options, nameOf, color, searchPlaceholder, emptyLabel, onSelect, footer, trigger }: PickerPanelProps<TOption>) => {\n const [open, setOpen] = useState(false);\n const [filter, setFilter] = useState('');\n const container = useRef<HTMLDivElement>(null);\n const panel = useRef<HTMLDivElement>(null);\n const showSearch = options.length > searchThreshold;\n const close = () => {\n setOpen(false);\n setFilter('');\n };\n\n const outside = useMemo(() => [container, panel], []);\n useDismissOnOutsidePointer(outside, close, open);\n\n const filtered = filter ? options.filter(option => nameOf(option).toLowerCase().includes(filter.toLowerCase())) : options;\n const select = (option: TOption) => {\n onSelect(option);\n close();\n };\n\n return (\n <div ref={container} className='event-modeling-grid-event-picker' style={{ position: 'relative' }}>\n {trigger({ open, toggle: () => setOpen(previous => !previous) })}\n\n {/* Portaled above the trigger so the panel floats over the whole board instead of\n being clipped by the slice column's paint containment. */}\n <AnchoredOverlay anchorRef={container} open={open} side='above' align='right' gap={4}>\n <div ref={panel} className='event-modeling-grid-event-picker-dropdown'>\n {showSearch && (\n <input\n className='event-modeling-grid-event-picker-search'\n placeholder={searchPlaceholder}\n value={filter}\n onChange={changeEvent => setFilter(changeEvent.target.value)}\n autoFocus\n onClick={clickEvent => clickEvent.stopPropagation()}\n />\n )}\n <ul className='event-modeling-grid-event-picker-list'>\n {filtered.map((option, position) => (\n <li key={`${position}-${nameOf(option)}`}>\n <button className='event-modeling-grid-event-picker-item' style={{ borderLeft: `3px solid ${color}` }} onClick={() => select(option)}>\n {nameOf(option)}\n </button>\n </li>\n ))}\n {filtered.length === 0 && <li className='event-modeling-grid-event-picker-empty'>{emptyLabel}</li>}\n {footer?.(close)}\n </ul>\n </div>\n </AnchoredOverlay>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EventReferencePicker.css';\nimport { eventCardColors } from '../Cards';\nimport { GridTooltip } from '../Tooltips';\nimport { PickerPanel } from './PickerPanel';\n\nexport interface EventReferencePickerProps<TOption> {\n options: readonly TOption[];\n nameOf: (option: TOption) => string;\n onSelect: (option: TOption) => void;\n // Names the button that opens the picker.\n label: string;\n searchPlaceholder: string;\n emptyLabel: string;\n // When set, the picker opens from a dashed card carrying this text instead of a small plus button,\n // because picking an event is the only thing the empty row offers.\n placeholder?: string;\n}\n\n// Lets the user pick an existing event. The consumer decides which events are offered and what picking\n// one does.\nexport const EventReferencePicker = <TOption,>({ options, nameOf, onSelect, label, searchPlaceholder, emptyLabel, placeholder }: EventReferencePickerProps<TOption>) => (\n <PickerPanel\n options={options}\n nameOf={nameOf}\n color={eventCardColors.background}\n searchPlaceholder={searchPlaceholder}\n emptyLabel={emptyLabel}\n onSelect={onSelect}\n trigger={({ toggle }) => placeholder !== undefined\n ? (\n <div className='event-modeling-grid-optional-event-reference'>\n <div className='event-modeling-grid-optional-event-reference__card'>\n <span>{placeholder}</span>\n </div>\n <button\n type='button'\n className='event-modeling-grid-optional-event-reference__define-btn'\n aria-label={label}\n title={label}\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n toggle();\n }}\n >\n <i className='pi pi-plus' />\n </button>\n </div>\n )\n : (\n <GridTooltip content={label} position='top'>\n <button onClick={toggle} className='event-modeling-grid-add-button--small' aria-label={label}>\n +\n </button>\n </GridTooltip>\n )}\n />\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { CSSProperties } from 'react';\nimport { errorCardColors, eventCardColors } from '../Cards';\nimport { useEventModelMessages } from '../Messages';\nimport { PickerPanel } from '../Pickers';\nimport { GridTooltip } from '../Tooltips';\n\n// What a specification section can be given from its add button, beside the options it lists.\nexport interface SpecificationAddExtra {\n label: string;\n onChosen: () => void;\n}\n\nexport interface SpecificationAddPickerProps<TOption> {\n options: readonly TOption[];\n nameOf: (option: TOption) => string;\n onChosen: (option: TOption) => void;\n // Errors, listed after the options, set apart by the error color.\n errors?: readonly SpecificationAddExtra[];\n}\n\nconst errorStyle: CSSProperties = { borderLeft: `3px solid ${errorCardColors.background}` };\n\n// The add button of a specification section: a searchable list of what can be added, with any errors\n// listed after it.\nexport const SpecificationAddPicker = <TOption,>({ options, nameOf, onChosen, errors = [] }: SpecificationAddPickerProps<TOption>) => {\n const messages = useEventModelMessages().specifications;\n return (\n <PickerPanel\n options={options}\n nameOf={nameOf}\n color={eventCardColors.background}\n searchPlaceholder={messages.search}\n emptyLabel={messages.noItems}\n onSelect={onChosen}\n footer={close => errors.length > 0 && (\n <>\n <li className='event-modeling-grid-event-picker-separator' />\n {errors.map((error, index) => (\n <li key={index}>\n <button\n className='event-modeling-grid-event-picker-item'\n style={errorStyle}\n onClick={() => {\n error.onChosen();\n close();\n }}\n >\n {error.label}\n </button>\n </li>\n ))}\n </>\n )}\n trigger={({ toggle }) => (\n <GridTooltip content={messages.addItem} position='top'>\n <button onClick={toggle} className='event-modeling-grid-add-button--small' aria-label={messages.addItem}>\n +\n </button>\n </GridTooltip>\n )}\n />\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef } from 'react';\nimport { Card, type CardColors } from '../Cards';\nimport { useSliceReadOnly } from '../Slices';\n\nexport interface SpecificationItemCardProps {\n name: string;\n colors: CardColors;\n // Opens the item's values from the card's viewport rectangle. Offered only while the slice is editable.\n onOpen?: (host: DOMRect) => void;\n}\n\n// An item of a specification section: an event, command or read model whose values can be opened.\nexport const SpecificationItemCard = ({ name, colors, onOpen }: SpecificationItemCardProps) => {\n const readOnly = useSliceReadOnly();\n const container = useRef<HTMLDivElement>(null);\n const opens = !readOnly && !!onOpen;\n\n return (\n <div ref={container}>\n <Card\n name={name}\n backgroundColor={colors.background}\n textColor={colors.text}\n onSelected={opens ? () => {\n const host = container.current?.getBoundingClientRect();\n if (host) onOpen?.(host);\n } : undefined}\n />\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The kinds of item whose values a specification can set.\nexport enum SpecificationItemKind {\n event = 'event',\n command = 'command',\n readModel = 'readModel',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode } from 'react';\nimport { boardMetrics } from '../Layout';\nimport { rowLabelWidth } from '../Geometry';\nimport { SpecificationSection } from './SpecificationSection';\n\nexport interface SpecificationRowProps {\n headline: string;\n actions?: ReactNode;\n isLast?: boolean;\n children?: ReactNode;\n}\n\n// One of a specification's Given, When and Then sections, set in from the board's row labels.\nexport const SpecificationRow = ({ headline, actions, isLast = false, children }: SpecificationRowProps) => (\n <div className='event-modeling-grid-specification-outer-row'>\n <div className='event-modeling-grid-specification-label-gutter' style={{ width: rowLabelWidth, flexShrink: 0 }} />\n <div className={`event-modeling-grid-specification-box event-modeling-grid-specification-box--section${isLast ? ' event-modeling-grid-specification-box--last' : ''}`} style={{ flex: 1 }}>\n <SpecificationSection headline={headline} minHeight={boardMetrics.specificationSectionHeight} actions={actions}>\n {children}\n </SpecificationSection>\n </div>\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventItem } from '../Model';\n\n// The events a Given section can start from: the events produced, not merely referenced, by the slice and\n// every slice before it, each once, in order. A precondition names the event that produces it.\nexport const producedEventsUniqueById = (events: readonly EventItem[]): EventItem[] => {\n const seen = new Set<string>();\n return events.filter(event => {\n const key = event.id.toString();\n if (event.sourceEventId || seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n};\n\n// Whether a Given section offers the slice's read model as the state it starts from: whenever the slice\n// has a read model and the section does not have it yet, whatever the slice type.\nexport const offersReadModelInGiven = (hasSliceReadModel: boolean, hasGivenReadModel: boolean): boolean =>\n hasSliceReadModel && !hasGivenReadModel;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './RemovableSpecificationItem.css';\nimport type { ReactNode } from 'react';\nimport { useBoard } from '../Board';\nimport { useSliceReadOnly } from '../Slices';\n\nexport interface RemovableSpecificationItemProps {\n // The item's name, so the button says what it removes.\n name: string;\n // Offered only when supplied and the slice is editable.\n onRemoved?: () => void;\n children: ReactNode;\n}\n\n// A Given or Then item with a button that takes it back out of the specification.\nexport const RemovableSpecificationItem = ({ name, onRemoved, children }: RemovableSpecificationItemProps) => {\n const { messages } = useBoard();\n const readOnly = useSliceReadOnly();\n if (readOnly || !onRemoved) return <>{children}</>;\n\n const label = `${messages.specifications.removeItem} ${name}`;\n return (\n <div className='spec-item-removable'>\n {children}\n <button\n type='button'\n className='spec-item-remove-button'\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n onRemoved();\n }}\n aria-label={label}\n title={label}\n >\n <i className='pi pi-times' />\n </button>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useMemo, useState } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { eventCardColors, readModelCardColors } from '../Cards';\nimport type { EventItem, ReadModelItem, SliceSpecification, SpecificationGivenEvent, SpecificationReadModel } from '../Model';\nimport { SliceType } from '../Model';\nimport { useSliceReadOnly } from '../Slices';\nimport { GridTooltip } from '../Tooltips';\nimport { itemValuesOf, type ItemValues } from './itemValues';\nimport { SpecificationAddPicker } from './SpecificationAddPicker';\nimport { SpecificationItemCard } from './SpecificationItemCard';\nimport { SpecificationItemKind } from './SpecificationItemKind';\nimport { SpecificationRow } from './SpecificationRow';\nimport { offersReadModelInGiven, producedEventsUniqueById } from './specificationEvents';\nimport { RemovableSpecificationItem } from './RemovableSpecificationItem';\n\nexport interface GivenSectionProps {\n sliceId: Guid;\n sliceType: SliceType;\n specification: SliceSpecification;\n // The events of the slice and every slice before it.\n events: readonly EventItem[];\n readModel?: ReadModelItem;\n // A same-session rename of the read model placed in Given.\n renamedReadModelName?: string;\n}\n\n// A specification's Given section: the events it starts from and, where the slice has one, its read model.\n// Only a State Change adds events; the event cards show their events' current names.\nexport const GivenSection = ({ sliceId, sliceType, specification, events, readModel, renamedReadModelName }: GivenSectionProps) => {\n const { editing, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const {\n onGivenEventAdded, onGivenEventValuesSet, onGivenReadModelSet, onGivenReadModelValuesSet, onGivenEventRemoved,\n onGivenReadModelRemoved, onSpecificationItemOpened,\n } = editing;\n const [given, setGiven] = useState<SpecificationGivenEvent[]>(specification.given);\n const [givenReadModel, setGivenReadModel] = useState<SpecificationReadModel | undefined>(specification.givenReadModel);\n const [values, setValues] = useState<ItemValues>(() => ({\n ...itemValuesOf(specification.given),\n ...(specification.givenReadModel ? { [specification.givenReadModel.id.toString()]: specification.givenReadModel.values ?? {} } : {}),\n }));\n const followsIncoming = readOnly || !(onGivenEventAdded || onGivenEventValuesSet || onGivenReadModelSet || onGivenReadModelValuesSet ||\n onGivenEventRemoved || onGivenReadModelRemoved || onSpecificationItemOpened);\n const visibleGiven = followsIncoming ? specification.given : given;\n const visibleReadModel = followsIncoming ? specification.givenReadModel : givenReadModel;\n const offered = useMemo(() => producedEventsUniqueById(events), [events]);\n const eventsById = useMemo(() => new Map(offered.map(event => [event.id.toString(), event])), [offered]);\n\n const open = (itemId: Guid, kind: SpecificationItemKind, name: string, host: DOMRect, schema: EventItem['schema'] | undefined, onValuesSet: (set: Record<string, unknown>) => void) =>\n onSpecificationItemOpened?.({\n sliceId,\n specificationId: specification.id,\n itemId,\n kind,\n name,\n schema,\n values: values[itemId.toString()] ?? {},\n host,\n onValuesSet: set => {\n setValues(previous => ({ ...previous, [itemId.toString()]: set }));\n onValuesSet(set);\n },\n });\n\n const addEvent = (event: EventItem) => {\n const itemId = Guid.create();\n setGiven(previous => [...previous, { id: itemId, eventId: event.id, name: event.name, values: {} }]);\n onGivenEventAdded?.(sliceId, specification.id, itemId, event.id, event.name);\n };\n\n // Closing a read model's values, from the define button or its card, sets it as the Given state with those values.\n const setReadModel = (set: Record<string, unknown>) => {\n if (!readModel) return;\n setGivenReadModel({ id: readModel.id, readModelItemId: readModel.id, name: readModel.name, values: set });\n onGivenReadModelSet?.(sliceId, specification.id, readModel.id, readModel.name);\n onGivenReadModelValuesSet?.(sliceId, specification.id, set);\n };\n const removeEvent = (itemId: Guid) => {\n setGiven(previous => previous.filter(item => !item.id.equals(itemId)));\n onGivenEventRemoved?.(sliceId, specification.id, itemId);\n };\n const removeReadModel = () => {\n setGivenReadModel(undefined);\n onGivenReadModelRemoved?.(sliceId, specification.id);\n };\n const setEventValues = (itemId: Guid) => (set: Record<string, unknown>) =>\n onGivenEventValuesSet?.(sliceId, specification.id, itemId, set);\n\n const offersEvents = !readOnly && sliceType === SliceType.stateChange && !!onGivenEventAdded;\n const offersReadModel = !readOnly && !!readModel && !!onGivenReadModelSet && !!onSpecificationItemOpened\n && offersReadModelInGiven(true, !!visibleReadModel);\n\n // The read model shows under its current name.\n const givenReadModelName = visibleReadModel && (renamedReadModelName ?? visibleReadModel.name);\n const givenReadModelId = visibleReadModel?.id ?? visibleReadModel?.readModelItemId;\n const readModelCard = visibleReadModel && givenReadModelId && givenReadModelName !== undefined && (\n <RemovableSpecificationItem key={givenReadModelId.toString()} name={givenReadModelName} onRemoved={onGivenReadModelRemoved ? removeReadModel : undefined}>\n <SpecificationItemCard\n name={givenReadModelName}\n colors={readModelCardColors}\n onOpen={!readOnly && onSpecificationItemOpened && onGivenReadModelSet ? host => open(givenReadModelId, SpecificationItemKind.readModel, givenReadModelName, host, readModel?.schema, setReadModel) : undefined}\n />\n </RemovableSpecificationItem>\n );\n const eventCards = visibleGiven.map(item => {\n const name = eventsById.get(item.eventId.toString())?.name ?? item.name;\n return (\n <RemovableSpecificationItem key={item.id.toString()} name={name} onRemoved={onGivenEventRemoved ? () => removeEvent(item.id) : undefined}>\n <SpecificationItemCard\n name={name}\n colors={eventCardColors}\n onOpen={!readOnly && onSpecificationItemOpened && onGivenEventValuesSet ? host => open(item.id, SpecificationItemKind.event, name, host, eventsById.get(item.eventId.toString())?.schema, setEventValues(item.id)) : undefined}\n />\n </RemovableSpecificationItem>\n );\n });\n\n return (\n <SpecificationRow\n headline={messages.specifications.given}\n actions={(\n <>\n {offersEvents && (\n <SpecificationAddPicker options={offered} nameOf={event => event.name} onChosen={addEvent} />\n )}\n {offersReadModel && readModel && (\n <GridTooltip content={messages.specifications.defineReadModel} position='top'>\n <button\n onClick={clickEvent => open(readModel.id, SpecificationItemKind.readModel, readModel.name, clickEvent.currentTarget.getBoundingClientRect(), readModel.schema, setReadModel)}\n className='event-modeling-grid-add-button--small'\n aria-label={messages.specifications.defineReadModel}\n >\n <i className='pi pi-table' style={{ fontSize: 10 }} />\n </button>\n </GridTooltip>\n )}\n </>\n )}\n >\n {readModelCard}\n {eventCards}\n </SpecificationRow>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useState } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { commandCardColors, eventCardColors } from '../Cards';\nimport type { CommandItem, EventItem, SliceSpecification, SpecificationCommand } from '../Model';\nimport { SliceType } from '../Model';\nimport { useSliceReadOnly } from '../Slices';\nimport { SpecificationAddPicker } from './SpecificationAddPicker';\nimport { SpecificationItemCard } from './SpecificationItemCard';\nimport { SpecificationItemKind } from './SpecificationItemKind';\nimport { SpecificationRow } from './SpecificationRow';\n\nexport interface WhenSectionProps {\n sliceId: Guid;\n sliceType: SliceType;\n specification: SliceSpecification;\n command?: CommandItem;\n // A same-session rename of the command referenced by an existing When item.\n renamedCommandName?: string;\n // Events pinned to the When section of a State View slice.\n events?: readonly EventItem[];\n}\n\nexport const WhenSection = ({ sliceId, sliceType, specification, command, renamedCommandName, events = [] }: WhenSectionProps) => {\n const { editing, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const { onWhenCommandSet, onWhenCommandValuesSet, onSpecificationItemOpened } = editing;\n const [when, setWhen] = useState<SpecificationCommand | undefined>(specification.when);\n const [values, setValues] = useState<Record<string, unknown>>(specification.when?.values ?? {});\n const followsIncoming = readOnly || !(onWhenCommandSet || onWhenCommandValuesSet || onSpecificationItemOpened);\n const visibleWhen = followsIncoming ? specification.when : when;\n\n const setCommand = (chosen: CommandItem) => {\n const itemId = Guid.create();\n setWhen({ id: itemId, commandId: chosen.id, name: chosen.name, values: {} });\n setValues({});\n onWhenCommandSet?.(sliceId, specification.id, itemId, chosen.id, chosen.name);\n };\n\n const openCommand = (itemId: Guid, sourceCommandId: Guid | undefined, name: string, host: DOMRect, currentValues: Record<string, unknown>) =>\n onSpecificationItemOpened?.({\n sliceId,\n specificationId: specification.id,\n itemId,\n kind: SpecificationItemKind.command,\n name,\n schema: sourceCommandId && command?.id.equals(sourceCommandId) ? command.schema : undefined,\n values: currentValues,\n host,\n onValuesSet: updatedValues => {\n if (when?.id.equals(itemId)) {\n setValues(updatedValues);\n }\n onWhenCommandValuesSet?.(sliceId, specification.id, updatedValues);\n },\n });\n\n const pinnedCommand = sliceType === SliceType.stateChange ? command : undefined;\n const pinnedEvents = sliceType === SliceType.stateView ? events : [];\n const whenName = visibleWhen && (visibleWhen.commandId && command?.id.equals(visibleWhen.commandId) ? renamedCommandName ?? visibleWhen.name : visibleWhen.name);\n const canOpen = !readOnly && !!onSpecificationItemOpened && !!onWhenCommandValuesSet;\n\n return (\n <SpecificationRow\n headline={messages.specifications.when}\n actions={!readOnly && sliceType !== SliceType.stateChange && sliceType !== SliceType.stateView && !visibleWhen && command && onWhenCommandSet && (\n <SpecificationAddPicker options={[command]} nameOf={item => item.name} onChosen={setCommand} />\n )}\n >\n {visibleWhen && whenName && (\n <SpecificationItemCard\n key={visibleWhen.id.toString()}\n name={whenName}\n colors={commandCardColors}\n onOpen={canOpen ? host => openCommand(visibleWhen.id, visibleWhen.commandId, whenName, host, values) : undefined}\n />\n )}\n {pinnedCommand && (\n <SpecificationItemCard\n key={pinnedCommand.id.toString()}\n name={pinnedCommand.name}\n colors={commandCardColors}\n onOpen={canOpen ? host => openCommand(pinnedCommand.id, pinnedCommand.id, pinnedCommand.name, host, values) : undefined}\n />\n )}\n {pinnedEvents.map(event => (\n <SpecificationItemCard key={event.id.toString()} name={event.name} colors={eventCardColors} />\n ))}\n </SpecificationRow>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\nimport { type CommandItem, type EventItem, SpecificationErrorRuleKind, type SpecificationErrorRuleReference } from '../Model';\n\n// A rule or constraint a specification's Then section can expect to be broken.\nexport interface RuleErrorOption {\n // Stored on the error, so it survives a rename of the rule or constraint.\n reference: SpecificationErrorRuleReference;\n label: string;\n}\n\n// A rule's kind, such as notEmpty, as a readable label: Not empty.\nexport const humanizeRuleType = (ruleType: string): string => {\n if (!ruleType) return '';\n const spaced = ruleType.replace(/([A-Z])/g, ' $1').trim();\n return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();\n};\n\nconst referenceTo = (kind: SpecificationErrorRuleKind, itemId: Guid, propertyName = '', ruleType = ''): SpecificationErrorRuleReference =>\n ({ kind, itemId, propertyName, ruleType });\n\nconst commandRuleOptions = (command: CommandItem | undefined): RuleErrorOption[] =>\n command\n ? (command.rules ?? []).flatMap(propertyRules => propertyRules.rules.map(rule => ({\n reference: referenceTo(SpecificationErrorRuleKind.commandValidationRule, command.id, propertyRules.propertyName, rule.ruleType),\n label: `${propertyRules.propertyName}: ${humanizeRuleType(rule.ruleType)}`,\n })))\n : [];\n\n// Every rule and constraint defined on a slice: one per command validation rule and one per event\n// constraint.\nexport const ruleErrorOptions = (command: CommandItem | undefined, events: readonly EventItem[]): RuleErrorOption[] => [\n ...commandRuleOptions(command),\n ...events.flatMap(event => [\n ...(event.constraints?.unique ? [{\n reference: referenceTo(SpecificationErrorRuleKind.eventUniqueConstraint, event.id),\n label: event.constraints.unique.name,\n }] : []),\n ...(event.constraints?.uniqueEventType ? [{\n reference: referenceTo(SpecificationErrorRuleKind.eventUniqueEventTypeConstraint, event.id),\n label: event.constraints.uniqueEventType.name,\n }] : []),\n ]),\n];\n\n// What an error expecting a rule or constraint is called now, so a renamed constraint shows under its\n// current name. Nothing when the constraint no longer exists.\nexport const ruleErrorLabel = (reference: SpecificationErrorRuleReference, events: readonly EventItem[]): string | undefined => {\n switch (reference.kind) {\n case SpecificationErrorRuleKind.commandValidationRule:\n return `${reference.propertyName}: ${humanizeRuleType(reference.ruleType)}`;\n case SpecificationErrorRuleKind.eventUniqueConstraint:\n return events.find(event => event.id.equals(reference.itemId))?.constraints?.unique?.name;\n case SpecificationErrorRuleKind.eventUniqueEventTypeConstraint:\n return events.find(event => event.id.equals(reference.itemId))?.constraints?.uniqueEventType?.name;\n default:\n return undefined;\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useEffect, useState } from 'react';\nimport { Card, CardNameInput, errorCardColors } from '../Cards';\nimport { useSliceReadOnly } from '../Slices';\n\nexport interface SpecificationErrorCardProps {\n name: string;\n // Offered only when supplied and the slice is editable; the card then renames in place with a\n // double-click.\n onRenamed?: (name: string) => void;\n}\n\n// An error a specification expects, described in free text.\nexport const SpecificationErrorCard = ({ name, onRenamed }: SpecificationErrorCardProps) => {\n const readOnly = useSliceReadOnly();\n const [editing, setEditing] = useState(false);\n const [shownName, setShownName] = useState(name);\n\n useEffect(() => setShownName(name), [name]);\n\n if (editing) {\n // An empty or unchanged name ends the edit without renaming; the name shows as typed until the\n // error's name next changes.\n const commit = () => {\n const trimmed = shownName.trim();\n setEditing(false);\n if (!trimmed || trimmed === name) return;\n onRenamed?.(trimmed);\n };\n return (\n <CardNameInput\n value={shownName}\n backgroundColor={errorCardColors.background}\n textColor={errorCardColors.text}\n onChange={setShownName}\n onCommit={commit}\n onCancel={() => {\n setShownName(name);\n setEditing(false);\n }}\n />\n );\n }\n\n return (\n <Card\n name={shownName}\n backgroundColor={errorCardColors.background}\n textColor={errorCardColors.text}\n onStartEdit={onRenamed ? () => setEditing(true) : undefined}\n disabled={readOnly}\n />\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useMemo, useState, type ReactNode } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { Card, errorCardColors, eventCardColors, readModelCardColors } from '../Cards';\nimport type { CommandItem, EventItem, ReadModelItem, SliceSpecification, SpecificationError, SpecificationErrorRuleReference, SpecificationThenEvent } from '../Model';\nimport { SliceType } from '../Model';\nimport { useSliceReadOnly } from '../Slices';\nimport { GridTooltip } from '../Tooltips';\nimport { itemValuesOf, type ItemValues } from './itemValues';\nimport { ruleErrorLabel, ruleErrorOptions } from './ruleErrors';\nimport { SpecificationAddPicker } from './SpecificationAddPicker';\nimport { SpecificationErrorCard } from './SpecificationErrorCard';\nimport { SpecificationItemCard } from './SpecificationItemCard';\nimport { SpecificationItemKind } from './SpecificationItemKind';\nimport { SpecificationRow } from './SpecificationRow';\nimport { RemovableSpecificationItem } from './RemovableSpecificationItem';\n\nexport interface ThenSectionProps {\n sliceId: Guid;\n sliceType: SliceType;\n specification: SliceSpecification;\n events: readonly EventItem[];\n command?: CommandItem;\n readModel?: ReadModelItem;\n // Names changed during this session, keyed by the referenced event's id.\n renamedEventNames?: Readonly<Record<string, string>>;\n // What the consumer adds after the section's own cards, for expectations the board does not draw itself.\n extra?: ReactNode;\n}\n\nexport const ThenSection = ({ sliceId, sliceType, specification, events, command, readModel, renamedEventNames = {}, extra }: ThenSectionProps) => {\n const { editing, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const {\n onThenEventAdded, onThenEventValuesSet, onThenErrorAdded, onThenRuleErrorAdded, onThenErrorRenamed,\n onThenEventRemoved, onThenErrorRemoved, onThenReadModelValuesSet, onSpecificationItemOpened,\n } = editing;\n const [thenEvents, setThenEvents] = useState<SpecificationThenEvent[]>(specification.thenEvents);\n const [thenErrors, setThenErrors] = useState<SpecificationError[]>(specification.thenErrors);\n const [values, setValues] = useState<ItemValues>(() => itemValuesOf(specification.thenEvents));\n const [readModelValues, setReadModelValues] = useState<Record<string, unknown>>({});\n const followsIncoming = readOnly || !(onThenEventAdded || onThenEventValuesSet || onThenErrorAdded ||\n onThenRuleErrorAdded || onThenErrorRenamed || onThenEventRemoved || onThenErrorRemoved || onThenReadModelValuesSet ||\n onSpecificationItemOpened);\n const visibleEvents = followsIncoming ? specification.thenEvents : thenEvents;\n const visibleErrors = followsIncoming ? specification.thenErrors : thenErrors;\n const eventsById = useMemo(() => new Map(events.map(event => [event.id.toString(), event])), [events]);\n const rules = useMemo(() => ruleErrorOptions(command, events), [command, events]);\n const canAdd = !readOnly && sliceType !== SliceType.stateView;\n\n const addEvent = (event: EventItem) => {\n const itemId = Guid.create();\n setThenEvents(previous => [...previous, { id: itemId, eventId: event.id, name: event.name, values: {} }]);\n onThenEventAdded?.(sliceId, specification.id, itemId, event.id, event.name);\n };\n const addError = () => {\n const itemId = Guid.create();\n const name = messages.specifications.error;\n setThenErrors(previous => [...previous, { id: itemId, name }]);\n onThenErrorAdded?.(sliceId, specification.id, itemId, name);\n };\n const addRuleError = (reference: SpecificationErrorRuleReference) => {\n const itemId = Guid.create();\n setThenErrors(previous => [...previous, { id: itemId, name: '', reference }]);\n onThenRuleErrorAdded?.(sliceId, specification.id, itemId, reference);\n };\n const renameError = (itemId: Guid, name: string) => {\n setThenErrors(previous => previous.map(error => error.id.equals(itemId) ? { ...error, name } : error));\n onThenErrorRenamed?.(sliceId, specification.id, itemId, name);\n };\n\n const removeEvent = (itemId: Guid) => {\n setThenEvents(previous => previous.filter(event => !event.id.equals(itemId)));\n onThenEventRemoved?.(sliceId, specification.id, itemId);\n };\n const removeError = (itemId: Guid) => {\n setThenErrors(previous => previous.filter(error => !error.id.equals(itemId)));\n onThenErrorRemoved?.(sliceId, specification.id, itemId);\n };\n\n const eventCards = visibleEvents.map(item => {\n const source = eventsById.get(item.eventId.toString());\n const name = renamedEventNames[item.eventId.toString()] ?? item.name;\n return (\n <RemovableSpecificationItem key={item.id.toString()} name={name} onRemoved={onThenEventRemoved ? () => removeEvent(item.id) : undefined}>\n <SpecificationItemCard\n name={name}\n colors={eventCardColors}\n onOpen={!readOnly && onSpecificationItemOpened && onThenEventValuesSet ? host => onSpecificationItemOpened({\n sliceId, specificationId: specification.id, itemId: item.id,\n kind: SpecificationItemKind.event, name, schema: source?.schema,\n values: values[item.id.toString()] ?? {}, host,\n onValuesSet: updatedValues => {\n setValues(previous => ({ ...previous, [item.id.toString()]: updatedValues }));\n onThenEventValuesSet?.(sliceId, specification.id, item.id, updatedValues);\n },\n }) : undefined}\n />\n </RemovableSpecificationItem>\n );\n });\n const errorCards = visibleErrors.map(item => {\n const name = item.reference ? ruleErrorLabel(item.reference, events) ?? messages.specifications.missingRule : item.name;\n return (\n <RemovableSpecificationItem key={item.id.toString()} name={name} onRemoved={onThenErrorRemoved ? () => removeError(item.id) : undefined}>\n {item.reference\n ? <Card name={name} backgroundColor={errorCardColors.background} textColor={errorCardColors.text} />\n : <SpecificationErrorCard name={item.name} onRenamed={!readOnly && onThenErrorRenamed ? newName => renameError(item.id, newName) : undefined} />}\n </RemovableSpecificationItem>\n );\n });\n\n const errorOptions = [\n ...(onThenErrorAdded ? [{ label: messages.specifications.addError, onChosen: addError }] : []),\n ...(onThenRuleErrorAdded ? rules.map(rule => ({ label: rule.label, onChosen: () => addRuleError(rule.reference) })) : []),\n ];\n const actions = canAdd && (sliceType === SliceType.stateChange\n ? (onThenEventAdded || errorOptions.length > 0) && <SpecificationAddPicker options={onThenEventAdded ? events : []} nameOf={event => event.name} onChosen={addEvent} errors={errorOptions} />\n : onThenErrorAdded && (\n <GridTooltip content={messages.specifications.addItem} position='top'>\n <button onClick={addError} className='event-modeling-grid-add-button--small' aria-label={messages.specifications.addItem}>+</button>\n </GridTooltip>\n ));\n\n return (\n <SpecificationRow headline={messages.specifications.then} actions={actions} isLast>\n {eventCards}\n {errorCards}\n {sliceType === SliceType.stateView && readModel && (\n <SpecificationItemCard\n key={readModel.id.toString()}\n name={readModel.name}\n colors={readModelCardColors}\n onOpen={!readOnly && onSpecificationItemOpened ? host => onSpecificationItemOpened({\n sliceId, specificationId: specification.id, itemId: readModel.id,\n kind: SpecificationItemKind.readModel, name: readModel.name,\n schema: readModel.schema, values: readModelValues, host,\n onValuesSet: set => {\n setReadModelValues(set);\n onThenReadModelValuesSet?.(sliceId, specification.id, readModel.id, readModel.name, set);\n },\n }) : undefined}\n />\n )}\n {extra}\n </SpecificationRow>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceConnections } from '../Connections';\nimport type { Slice } from '../Model';\nimport { useEventModelPresentation } from '../Presentation';\n\nexport interface SliceLinesProps {\n slice: Slice;\n collapsed: boolean;\n showDetails: boolean;\n}\n\n// The curved lines a slice's cards are connected with when the board is drawn with lines rather than\n// arrows. A host that draws its own overlay over the slice body supplies it through the slots instead.\nexport const SliceLines = ({ slice, collapsed, showDetails }: SliceLinesProps) => {\n const { visualizationMode } = useEventModelPresentation();\n if (visualizationMode !== 'fillLines' || collapsed) return null;\n // Anything that moves a card changes the key, so the lines are measured again.\n const recomputeKey = [\n slice.id.toString(),\n slice.events.map(event => event.id.toString()).join(','),\n slice.actors.map(actor => `${actor.id}:${actor.elements.length}`).join(','),\n showDetails ? 'details' : '',\n slice.automationTrigger?.type ?? '',\n slice.command?.id.toString() ?? '',\n slice.readModel?.id.toString() ?? '',\n ].join(';');\n return <SliceConnections sliceType={slice.sliceType} recomputeKey={recomputeKey} />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { type EventItem, type Slice, SliceType } from '../Model';\nimport { BoardInteractionProvider } from '../Board';\nimport { boardMetrics } from '../Layout';\nimport { RowType } from '../Rows';\nimport { SliceColumn, SliceHeader, SliceRows } from '../Slices';\nimport { GivenSection, SpecificationCollection, specificationRunState, ThenSection, WhenSection } from '../Specifications';\nimport { ChatCell, SystemCell, SliceInteraction, SliceEvents, UiCell } from '../Rows';\nimport type { Feature, Module, ModuleCollection } from '../Model';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridSliceHeaderControls } from './CollectionGridSliceHeaderControls';\nimport { collectionContentHeight } from './collectionGridLayout';\nimport { SliceLines } from './SliceLines';\nimport { areDetailsVisible, areSliceDetailsVisibleForDetailLevel, useEventModelPresentation } from '../Presentation';\n\nexport interface CollectionGridSliceProps {\n slice: Slice;\n collapsed: boolean;\n moduleId: Module['id'];\n featureId: Feature['id'];\n collection: ModuleCollection;\n rows: RowType[];\n heights: Record<RowType, number>;\n priorEvents: EventItem[];\n // The events produced after this slice in its collection; a State View projecting one of them is out of order.\n followingEvents?: EventItem[];\n externalEvents: EventItem[];\n slots?: CollectionGridSlots;\n controls?: CollectionGridSliceHeaderControls;\n}\n\nexport const CollectionGridSlice = ({ slice, collapsed, moduleId, featureId, collection, rows, heights, priorEvents, followingEvents = [], externalEvents, slots, controls }: CollectionGridSliceProps) => {\n const { detailLevel, detailsVisibility } = useEventModelPresentation();\n // The same per-slice rule Studio's own cells applied: any enclosing scope, or the board as a whole, turns details on.\n const showDetails = areSliceDetailsVisibleForDetailLevel(detailLevel,\n areDetailsVisible(detailsVisibility, moduleId.toString(), featureId.toString(), slice.id.toString()));\n const column = <SliceColumn featureId={featureId} slice={slice} eventCount={slice.events.length} collapsed={collapsed}\n isDragging={controls?.isDragging} onSliceDragStart={controls?.onSliceDragStart}\n collapsedWidth={boardMetrics.collapsedSliceWidth}\n header={slots?.sliceHeader?.(slice, controls ?? { collapsed, sliceCollapsed: slice.collapsed, isDragging: false }) ??\n <BoardInteractionProvider editing={{\n onSliceAdded: controls?.onAddSlice ? (_id, sliceType) => controls.onAddSlice?.(sliceType, slice.id) : undefined,\n onSliceOpenStateSet: controls?.onToggleCollapse ? () => controls.onToggleCollapse?.() : undefined,\n onSliceRenamed: controls?.onRenamed ? (_id, name) => controls.onRenamed?.(name) : undefined,\n }}>\n <SliceHeader slice={slice} height={boardMetrics.headerHeight} collapsed={collapsed} onToggleCollapse={controls?.onToggleCollapse} />\n </BoardInteractionProvider>} headerHeight={boardMetrics.headerHeight}\n body={inView => inView ? <>\n {slots?.sliceBodyOverlay ? slots.sliceBodyOverlay(slice, collapsed) : <SliceLines slice={slice} collapsed={collapsed} showDetails={showDetails} />}\n <SliceRows sliceType={slice.sliceType} contentRows={rows} rowHeights={heights}\n actors={collection.actors} renderCell={cell => {\n const shared = { conn: cell.conn, rowHeight: cell.rowHeight, collapsed };\n const detailed = { ...shared, showDetails };\n if (slots?.sliceCell) {\n const supplied = slots.sliceCell(slice, cell);\n if (supplied !== undefined) return supplied;\n }\n switch (cell.rowType) {\n case RowType.UI: {\n const prototype = slice.actors.find(actor => actor.id === cell.actor?.id);\n return <UiCell {...shared} actorId={cell.actor?.id ?? ''}\n elements={prototype?.elements ?? []}\n layout={prototype?.layout} windowSize={prototype ? { width: prototype.windowWidth, height: prototype.windowHeight } : undefined} />;\n }\n // The system acts in automations and translators; a state change or view only passes through its row.\n case RowType.System: return <SystemCell {...shared} sliceType={slice.sliceType}\n isSystemSlice={!!cell.actor && (slice.sliceType === SliceType.automation || slice.sliceType === SliceType.translator)}\n triggerType={slice.automationTrigger?.type} />;\n case RowType.Chat: return <ChatCell {...shared} sliceId={slice.id} />;\n case RowType.Interaction: return <SliceInteraction {...detailed} slice={slice} externalEventOptions={externalEvents} />;\n case RowType.Events: return <SliceEvents {...detailed} slice={slice} priorEvents={priorEvents} followingEvents={followingEvents} />;\n }\n }} /></> : <div style={{ height: collectionContentHeight(collection, rows, heights) }} aria-hidden='true' />}\n specifications={(inView, width) => slots?.specifications\n ? slots.specifications(slice, inView, width, controls?.sliceCollapsed ?? slice.collapsed)\n : (inView && <SpecificationCollection sliceId={slice.id} width={width} collapsed={controls?.sliceCollapsed ?? slice.collapsed}\n specifications={slice.specifications}\n runInfoFor={specification => ({ state: specificationRunState(specification.lastRunOutcome, false),\n message: specification.lastRunMessage ?? '' })}\n renderRows={specification => <>\n <GivenSection sliceId={slice.id} sliceType={slice.sliceType} specification={specification}\n events={[...priorEvents, ...slice.events]} readModel={slice.readModel}\n renamedReadModelName={slice.readModel?.name} />\n <WhenSection sliceId={slice.id} sliceType={slice.sliceType} specification={specification}\n command={slice.command} renamedCommandName={slice.command?.name} events={slice.events} />\n <ThenSection sliceId={slice.id} sliceType={slice.sliceType} specification={specification}\n events={slice.events} command={slice.command} readModel={slice.readModel}\n renamedEventNames={Object.fromEntries(slice.events.map(event => [event.id.toString(), event.name]))} />\n </>} />)} />;\n return slots?.sliceBoundary ? slots.sliceBoundary(slice, column) : column;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ScreenTemplate } from '../Model';\nimport './CollectionGridTemplate.css';\n\nexport interface CollectionGridTemplateProps {\n template: ScreenTemplate;\n width: number;\n}\n\nexport const CollectionGridTemplate = ({ template, width }: CollectionGridTemplateProps) =>\n <div className='event-modeling-collection-grid-template' style={{ width }}>\n <div className='event-modeling-collection-grid-template__bar'>\n <i className='pi pi-window-maximize' aria-hidden='true' />\n <span className='event-modeling-collection-grid-template__name'>{template.name}</span>\n </div>\n </div>;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useRef, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { FeatureGridSurface, type FeaturesAreaProps } from '../Features';\nimport { SlicesArea, duplicateSliceName, type SlicesAreaHandle } from '../Slices';\nimport { SliceType, type EventItem, type Feature, type ModuleCollection, type Slice } from '../Model';\nimport { RowType } from '../Rows';\nimport { CollectionGridSlice } from './CollectionGridSlice';\nimport { CollectionGridTemplate } from './CollectionGridTemplate';\nimport { featureWidth } from './collectionGridLayout';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridEditor } from './CollectionGridEditor';\nimport type { CollectionGridFeatureHeaderControls } from './CollectionGridFeatureHeaderControls';\n\nexport interface CollectionGridFeatureColumnProps {\n feature: Feature;\n options: Parameters<FeaturesAreaProps<Feature>['renderColumn']>[1];\n moduleId: Guid;\n collection: ModuleCollection;\n rows: RowType[];\n heights: Record<RowType, number>;\n slices: Slice[];\n externalEvents: EventItem[];\n slots?: CollectionGridSlots;\n editor: CollectionGridEditor;\n onSliceArea: (handle: SlicesAreaHandle<Slice> | null) => void;\n sliceAreas: ReadonlyMap<string, SlicesAreaHandle<Slice>>;\n renderHeader: (controls: CollectionGridFeatureHeaderControls) => ReactNode;\n onSlicesChanged?: (slices: Slice[]) => void;\n}\n\nexport const CollectionGridFeatureColumn = ({ feature, options, moduleId, collection, rows, heights,\n slices, externalEvents, slots, editor, onSliceArea, sliceAreas, renderHeader, onSlicesChanged }: CollectionGridFeatureColumnProps) => {\n const areaRef = useRef<SlicesAreaHandle<Slice>>(null);\n const priorEvents = (sliceId: Guid) => slices.slice(0, slices.findIndex(slice => slice.id.equals(sliceId)))\n .filter(slice => slice.sliceType === SliceType.stateChange).flatMap(slice => slice.events);\n const followingEvents = (sliceId: Guid) => slices.slice(slices.findIndex(slice => slice.id.equals(sliceId)) + 1)\n .filter(slice => slice.sliceType === SliceType.stateChange).flatMap(slice => slice.events);\n const persistMove = useCallback(async (slice: Slice, targetFeatureId: Guid, targetIndex: number): Promise<boolean> => {\n const target = sliceAreas.get(targetFeatureId.toString());\n target?.moveIn(slice, targetIndex);\n try {\n const succeeded = await editor.onMoveSlice?.(slice, feature.id, targetFeatureId, targetIndex) ?? false;\n target?.completeMoveIn(slice.id, succeeded);\n return succeeded;\n } catch {\n target?.completeMoveIn(slice.id, false);\n return false;\n }\n }, [editor.onMoveSlice, feature.id, sliceAreas]);\n const moveToFeature = useCallback((slice: Slice, targetFeatureId: Guid) => {\n if (!editor.onMoveSlice || targetFeatureId.equals(feature.id) || !areaRef.current?.moveOut(slice.id)) return;\n void persistMove(slice, targetFeatureId, Number.MAX_SAFE_INTEGER)\n .then(succeeded => areaRef.current?.completeMoveOut(slice.id, succeeded));\n }, [editor.onMoveSlice, feature.id, persistMove]);\n const headerControls = {\n ...options, dragging: false,\n onAddSubFeature: options.addSubFeature,\n onAddSlice: undefined,\n };\n return <FeatureGridSurface featureId={feature.id} moduleId={moduleId} enabled={feature.enabled}\n collapsed={options.collapsed} rowCollapsed={feature.rowCollapsed} width={featureWidth(feature)}\n headerVisibility={options.headerVisibility}\n header={renderHeader(headerControls)}\n screenTemplate={slots?.featureTemplate\n ? slots.featureTemplate(feature, featureWidth(feature))\n : feature.screenTemplate && <CollectionGridTemplate template={feature.screenTemplate} width={featureWidth(feature)} />}\n slices={<SlicesArea ref={handle => { areaRef.current = handle; onSliceArea(handle); }}\n initialSlices={feature.slices} moduleId={moduleId} featureId={feature.id}\n featureCollapsed={options.collapsed} hideEmptyPlaceholder={options.headerVisibility === 'hidden'}\n createSlice={slice => slice} onSlicesChanged={onSlicesChanged}\n onAddSlice={editor.onAddSlice ? (slice, afterSliceId) => editor.onAddSlice?.(feature.id, slice, afterSliceId) ?? Promise.resolve(undefined) : undefined}\n onReorderSlices={editor.onReorderSlices ? sliceIds => editor.onReorderSlices?.(feature.id, sliceIds) ?? Promise.resolve(false) : undefined}\n onMoveSlice={editor.onMoveSlice ? persistMove : undefined}\n validateSliceDrop={editor.validateSliceDrop}\n renderSlice={(slice, sliceOptions) => <CollectionGridSlice slice={slice} collapsed={sliceOptions.collapsed}\n moduleId={moduleId} featureId={feature.id} collection={collection} rows={rows} heights={heights}\n priorEvents={priorEvents(slice.id)} followingEvents={followingEvents(slice.id)} externalEvents={externalEvents} slots={slots}\n controls={{ collapsed: sliceOptions.collapsed, sliceCollapsed: sliceOptions.sliceCollapsed,\n isDragging: sliceOptions.isDragging, onSliceDragStart: sliceOptions.onSliceDragStart,\n onAddSlice: editor.onAddSlice ? sliceOptions.addSlice : undefined,\n onToggleCollapse: editor.onSliceCollapseChanged ? () => {\n areaRef.current?.updateSlices(previous => previous.map(candidate => candidate.id.equals(slice.id)\n ? { ...candidate, collapsed: !sliceOptions.sliceCollapsed } : candidate));\n editor.onSliceCollapseChanged?.(feature.id, slice.id, !sliceOptions.sliceCollapsed);\n } : undefined,\n onRenamed: editor.onSliceRenamed ? name => {\n areaRef.current?.updateSlices(previous => previous.map(candidate => candidate.id.equals(slice.id)\n ? { ...candidate, name } : candidate));\n editor.onSliceRenamed?.(feature.id, slice.id, name);\n } : undefined,\n onMoveToFeature: editor.onMoveSlice ? targetId => moveToFeature(slice, targetId) : undefined,\n onDuplicated: editor.onSliceDuplicated ? newId => {\n editor.onSliceDuplicated?.(feature.id, slice.id, newId);\n areaRef.current?.addProjectedSlice({ ...slice, id: newId,\n name: duplicateSliceName(feature.slices.map(candidate => candidate.name), slice.name),\n specifications: [], commentCount: 0, collapsed: false }, slice.id);\n } : undefined,\n }} />}\n />}\n />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useImperativeHandle, useRef, type Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { FeaturesArea, FeatureHeader, type FeaturesAreaHandle } from '../Features';\nimport type { SliceNames, SlicesAreaHandle } from '../Slices';\nimport { boardMetrics } from '../Layout';\nimport { SliceType, type Feature, type ModuleCollection, type Slice } from '../Model';\nimport { RowType } from '../Rows';\nimport { collectionSlices, featureWidth } from './collectionGridLayout';\nimport { CollectionGridFeatureColumn } from './CollectionGridFeatureColumn';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridEditor } from './CollectionGridEditor';\nimport type { CollectionGridFeatureHeaderControls } from './CollectionGridFeatureHeaderControls';\n\nexport interface CollectionGridFeatureProps {\n ref?: Ref<FeaturesAreaHandle<Feature>>;\n moduleId: Guid;\n collection: ModuleCollection;\n features: Feature[];\n rows: RowType[];\n heights: Record<RowType, number>;\n slots?: CollectionGridSlots;\n editor: CollectionGridEditor;\n onFeaturesChanged?: (features: Feature[]) => void;\n}\n\nexport const CollectionGridFeature = ({ ref, moduleId, collection, features, rows, heights, slots, editor,\n onFeaturesChanged }: CollectionGridFeatureProps) => {\n const sliceAreas = useRef(new Map<string, SlicesAreaHandle<Slice>>());\n const areaRef = useRef<FeaturesAreaHandle<Feature>>(null);\n useImperativeHandle(ref, () => ({\n addFeature: name => areaRef.current?.addFeature(name) ?? Promise.resolve(),\n addSubFeature: (parentId, name) => areaRef.current?.addSubFeature(parentId, name) ?? Promise.resolve(),\n updateFeature: (id, update) => areaRef.current?.updateFeature(id, update),\n }), []);\n const slices = collectionSlices(collection).map(entry => entry.slice);\n const externalEvents = collectionSlices({ ...collection,\n modules: collection.modules.filter(module => !module.id.equals(moduleId)) })\n .flatMap(entry => entry.slice.events);\n const addSlice = (featureId: Guid) => editor.onAddSlice\n ? (sliceType: SliceType, names?: SliceNames) => sliceAreas.current.get(featureId.toString())?.addSlice(sliceType, undefined, names)\n : undefined;\n const renderHeader = (feature: Feature, controls: CollectionGridFeatureHeaderControls) =>\n slots?.featureHeader?.(feature, controls) ?? <FeatureHeader\n featureId={feature.id} name={feature.name} height={boardMetrics.headerHeight}\n collapsed={controls.collapsed} dragging={controls.dragging} onDragStart={controls.onDragStart}\n onToggleCollapse={controls.onToggleCollapse}\n onRenamed={controls.onRenamed ? (_id, name) => controls.onRenamed?.(name) : undefined}\n onAddSubFeature={controls.onAddSubFeature ? () => controls.onAddSubFeature?.() : undefined}\n onAddSlice={controls.onAddSlice} />;\n return <FeaturesArea ref={areaRef} initialFeatures={features} moduleId={moduleId} widthOf={featureWidth}\n isCollapsed={feature => feature.collapsed} occupiesColumn={feature => featureWidth(feature) > 0}\n onFeaturesChanged={onFeaturesChanged}\n renderFeatureBoundary={slots?.featureBoundary}\n onAddFeature={editor.onAddFeature ? (name, parentId) => editor.onAddFeature?.(moduleId, name, parentId) ?? Promise.resolve(undefined) : undefined}\n onRenameFeature={editor.onRenameFeature}\n onCollapseChanged={editor.onFeatureCollapseChanged}\n onFeaturesReordered={editor.onFeaturesReordered ? changed => editor.onFeaturesReordered?.(moduleId, changed) : undefined}\n renderHeader={(feature, options) => renderHeader(feature, {\n ...options,\n onDragStart: options.onDragStart ? start => options.onDragStart?.(feature.id, feature.name, start) : undefined,\n onAddSubFeature: options.addSubFeature,\n onAddSlice: addSlice(feature.id),\n })}\n renderColumn={(feature, options) => <CollectionGridFeatureColumn\n feature={feature} options={options} moduleId={moduleId} collection={collection}\n rows={rows} heights={heights} slices={slices} externalEvents={externalEvents}\n slots={slots} editor={editor} sliceAreas={sliceAreas.current}\n onSlicesChanged={changed => areaRef.current?.updateFeature(feature.id, previous => ({ ...previous, slices: changed }))}\n onSliceArea={handle => {\n if (handle) sliceAreas.current.set(feature.id.toString(), handle);\n else sliceAreas.current.delete(feature.id.toString());\n }}\n renderHeader={controls => renderHeader(feature, { ...controls, onAddSlice: addSlice(feature.id) })}\n />}\n />;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { ModuleHeader, ModulePlaceholder, ModuleSurface } from '../Modules';\nimport { boardMetrics } from '../Layout';\nimport { useInViewport } from '../Viewport';\nimport type { Feature, Module, ModuleCollection } from '../Model';\nimport { RowType } from '../Rows';\nimport { CollectionGridFeature } from './CollectionGridFeature';\nimport { collectionContentHeight, collectionModuleWidth, featureColumns, featureWidth } from './collectionGridLayout';\nimport { CollectionGridTemplate } from './CollectionGridTemplate';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridEditor } from './CollectionGridEditor';\nimport type { FeaturesAreaHandle } from '../Features';\nimport type { HeaderDragStart } from '../HeaderDragging';\n\nexport interface CollectionGridModuleProps {\n module: Module;\n liveFeatures?: Feature[];\n index: number;\n collection: ModuleCollection;\n rows: RowType[];\n heights: Record<RowType, number>;\n slots?: CollectionGridSlots;\n editor: CollectionGridEditor;\n dragging?: boolean;\n onDragStart?: (start: HeaderDragStart) => void;\n onAddModule?: () => void;\n onToggleCollapse?: () => void;\n onRenamed?: (name: string) => void;\n onFeaturesChanged?: (moduleId: Guid, features: Feature[]) => void;\n}\n\nexport const CollectionGridModule = ({ module, liveFeatures, index, collection, rows, heights, slots, editor, dragging,\n onDragStart, onAddModule, onToggleCollapse, onRenamed, onFeaturesChanged }: CollectionGridModuleProps) => {\n const frameRef = useRef<HTMLDivElement>(null);\n const featuresRef = useRef<FeaturesAreaHandle<Feature>>(null);\n const onAddFeature = editor.onAddFeature ? (name?: string) => { void featuresRef.current?.addFeature(name); } : undefined;\n const inView = useInViewport(frameRef, undefined, 'heavy');\n const width = collectionModuleWidth(module.name, liveFeatures ?? module.features);\n const surface = <ModuleSurface moduleId={module.id} collectionId={collection.id} index={index} width={width}\n collapsed={module.collapsed} dragging={dragging} frameRef={frameRef}\n header={slots?.moduleHeader?.(module, { onDragStart, onAddModule, onAddFeature, onToggleCollapse, onRenamed }) ??\n <ModuleHeader moduleId={module.id} name={module.name}\n height={boardMetrics.headerHeight} collapsed={module.collapsed} onAddModule={onAddModule}\n onToggleCollapse={onToggleCollapse} onRenamed={onRenamed ? (_id, name) => onRenamed(name) : undefined}\n onDragStart={onDragStart} onAddFeature={onAddFeature} />}\n template={slots?.moduleTemplate\n ? slots.moduleTemplate(module, width)\n : module.screenTemplate && <CollectionGridTemplate template={module.screenTemplate} width={width} />}\n content={inView ? <CollectionGridFeature ref={featuresRef} moduleId={module.id} collection={collection} features={module.features}\n rows={rows} heights={heights} slots={slots} editor={editor}\n onFeaturesChanged={features => onFeaturesChanged?.(module.id, features)} />\n : <ModulePlaceholder width={width} height={collectionContentHeight(collection, rows, heights)}\n featureWidths={featureColumns(liveFeatures ?? module.features).map(featureWidth).filter(value => value > 0)} />} />;\n return slots?.moduleBoundary ? slots.moduleBoundary(module, surface) : surface;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Feature, Module } from '../Model';\n\n// What a read-only board has collapsed or expanded itself, by the id of the module, feature or slice.\nexport type LocalCollapses = ReadonlyMap<string, boolean>;\n\nconst collapsedOf = (collapses: LocalCollapses, item: { id: { toString(): string }; collapsed: boolean }) =>\n collapses.get(item.id.toString()) ?? item.collapsed;\n\nconst withFeatureCollapses = (collapses: LocalCollapses, feature: Feature): Feature => ({\n ...feature,\n collapsed: collapsedOf(collapses, feature),\n slices: feature.slices.map(slice => ({ ...slice, collapsed: collapsedOf(collapses, slice) })),\n subFeatures: feature.subFeatures.map(child => withFeatureCollapses(collapses, child)),\n});\n\n// The modules as a read-only board draws them: as the document has them, with what the board has\n// collapsed or expanded itself on top. Applied to every document that arrives, so a choice survives\n// the document changing.\nexport function withLocalCollapses(modules: readonly Module[], collapses: LocalCollapses): Module[] {\n if (collapses.size === 0) return [...modules];\n return modules.map(module => ({\n ...module,\n collapsed: collapsedOf(collapses, module),\n features: module.features.map(feature => withFeatureCollapses(collapses, feature)),\n }));\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { BoardReadOnlyContext } from '../Board/BoardReadOnlyContext';\nimport { computeSliceConnections, SliceConnectionsProvider } from '../Connections';\nimport { ModulesArea } from '../Modules';\nimport { RowLabelsColumn, type RowLabelsColumnProps } from '../RowLabels';\nimport type { Feature, Module, ModuleCollection } from '../Model';\nimport { CollectionMoveHandle } from './CollectionMoveHandle';\nimport { CollectionGridModule } from './CollectionGridModule';\nimport type { CollectionGridSlots } from './CollectionGridSlots';\nimport type { CollectionGridEditor } from './CollectionGridEditor';\nimport { collectionRowHeights, collectionRows, collectionSlices } from './collectionGridLayout';\nimport { useSliceDetailsVisibility } from './useSliceDetailsVisibility';\nimport { type LocalCollapses, withLocalCollapses } from './localCollapses';\nimport './CollectionGrid.css';\n\nexport interface CollectionGridProps extends CollectionGridEditor {\n collection: ModuleCollection;\n getZoom?: () => number;\n slots?: CollectionGridSlots;\n onDeselect?: () => void;\n onCollectionMoving?: (id: Guid, deltaX: number, deltaY: number) => void;\n onCollectionMoved?: (id: Guid, position: { x: number; y: number }) => void;\n canMove?: boolean;\n onAddModule?: () => Promise<Module | undefined>;\n onModulesReordered?: (ids: Guid[]) => Promise<boolean>;\n onCollapseChanged?: (id: Guid, collapsed: boolean) => Promise<boolean>;\n onRenameModule?: (id: Guid, name: string) => Promise<boolean>;\n onModulesChanged?: (modules: Module[]) => void;\n onFeaturesChanged?: (moduleId: Guid, features: Feature[]) => void;\n onPersistenceError?: (error: unknown) => void;\n rowLabels?: (props: RowLabelsColumnProps) => ReactNode;\n onActorsReordered?: RowLabelsColumnProps['onActorsReordered'];\n}\n\nconst defaultZoom = () => 1;\n\nexport const CollectionGrid = ({ collection, getZoom = defaultZoom, slots, onDeselect, onCollectionMoving,\n onCollectionMoved, canMove, onAddModule, onModulesReordered, onCollapseChanged, onRenameModule,\n onModulesChanged, onFeaturesChanged, onPersistenceError, rowLabels, onActorsReordered,\n onAddFeature, onRenameFeature, onFeatureCollapseChanged, onFeaturesReordered,\n onAddSlice, onReorderSlices, onMoveSlice, validateSliceDrop, onSliceCollapseChanged, onSliceRenamed, onSliceDuplicated }: CollectionGridProps) => {\n const { readOnly } = useBoard();\n // Collapsing only changes how the board is drawn, so a read-only board does it on its own.\n const [localCollapses, setLocalCollapses] = useState<LocalCollapses>(new Map());\n const collapseLocally = useCallback((id: Guid, collapsed: boolean) =>\n setLocalCollapses(previous => new Map(previous).set(id.toString(), collapsed)), []);\n const readOnlyModules = useMemo(() => withLocalCollapses(collection.modules, localCollapses), [collection.modules, localCollapses]);\n const editor: CollectionGridEditor = readOnly ? {\n onFeatureCollapseChanged: collapseLocally,\n onSliceCollapseChanged: (_featureId, sliceId, collapsed) => collapseLocally(sliceId, collapsed),\n } : {\n onAddFeature, onRenameFeature, onFeatureCollapseChanged, onFeaturesReordered,\n onAddSlice, onReorderSlices, onMoveSlice, validateSliceDrop, onSliceCollapseChanged, onSliceRenamed, onSliceDuplicated,\n };\n const [modules, setModules] = useState(collection.modules);\n const [liveFeatures, setLiveFeatures] = useState<ReadonlyMap<string, Feature[]>>(new Map());\n const contentRef = useRef<HTMLDivElement>(null);\n const [labelOffset, setLabelOffset] = useState(0);\n const hasEditor = !!(onAddModule || onModulesReordered || onCollapseChanged || onRenameModule ||\n onActorsReordered || onAddFeature || onRenameFeature || onFeatureCollapseChanged || onFeaturesReordered ||\n onAddSlice || onReorderSlices || onMoveSlice || onSliceCollapseChanged || onSliceRenamed || onSliceDuplicated ||\n (canMove && onCollectionMoving && onCollectionMoved));\n const followsIncoming = readOnly || !hasEditor;\n const incomingModules = readOnly ? readOnlyModules : collection.modules;\n const visibleModules = (followsIncoming ? incomingModules : modules).map(module => ({ ...module,\n features: followsIncoming ? module.features : liveFeatures.get(module.id.toString()) ?? module.features,\n }));\n const visibleCollection = { ...collection, modules: visibleModules };\n const rows = collectionRows(visibleCollection);\n const showsDetails = useSliceDetailsVisibility();\n const heights = collectionRowHeights(visibleCollection, showsDetails);\n const slices = collectionSlices(visibleCollection);\n const showLabels = slices.length > 0 && visibleModules.some(module => !module.collapsed);\n const connections = computeSliceConnections(slices.map(({ slice }) => ({\n id: slice.id.toString(), name: slice.name,\n events: slice.events.map(event => ({ id: event.id.toString(), name: event.name,\n sourceEventId: event.sourceEventId ? event.sourceEventId.toString() : undefined })),\n automationTriggerEventId: slice.automationTrigger?.eventId?.toString(),\n })));\n\n useEffect(() => {\n const container = contentRef.current;\n if (!container) return;\n const measure = () => {\n const header = container.querySelector<HTMLElement>('.event-modeling-grid-slice-column-header');\n if (!header) { setLabelOffset(0); return; }\n setLabelOffset(Math.max(0, Math.round((header.getBoundingClientRect().bottom\n - container.getBoundingClientRect().top) / getZoom() - 4)));\n };\n measure();\n const observer = new ResizeObserver(measure);\n observer.observe(container);\n const slicesArea = container.querySelector<HTMLElement>('.event-modeling-grid-slices-area');\n if (slicesArea) observer.observe(slicesArea);\n return () => observer.disconnect();\n }, [modules, liveFeatures, getZoom]);\n\n const labelProps: RowLabelsColumnProps = { collectionId: collection.id, topOffset: labelOffset,\n contentRows: rows, rowHeights: heights, actors: collection.actors,\n onActorsReordered: readOnly ? undefined : onActorsReordered };\n return <BoardReadOnlyContext.Provider value={readOnly || !hasEditor}>\n <div className='event-modeling-grid-container event-modeling-collection-grid' onClick={onDeselect}>\n {canMove && onCollectionMoving && onCollectionMoved &&\n <CollectionMoveHandle collectionId={collection.id} position={collection.position} getZoom={getZoom}\n onCollectionMoving={onCollectionMoving} onCollectionMoved={onCollectionMoved} />}\n <div className='event-modeling-grid-content-row' ref={contentRef}>\n {showLabels && (rowLabels ? rowLabels(labelProps) : <RowLabelsColumn {...labelProps} />)}\n <div className='event-modeling-grid-slices-area'>\n <SliceConnectionsProvider connections={connections}>\n <ModulesArea collectionId={collection.id} initialModules={incomingModules}\n onAddModule={onAddModule} onModulesReordered={onModulesReordered}\n onCollapseChanged={readOnly ? (id, collapsed) => { collapseLocally(id, collapsed); return Promise.resolve(true); } : onCollapseChanged}\n onRenameModule={onRenameModule}\n onPersistenceError={onPersistenceError}\n onModulesChanged={changed => { setModules(changed); onModulesChanged?.(changed); }}\n renderModule={(module, options) => <CollectionGridModule\n module={module} liveFeatures={liveFeatures.get(module.id.toString())} index={options.index}\n collection={visibleCollection} rows={rows} heights={heights} slots={slots}\n dragging={options.dragging} onDragStart={options.onDragStart}\n onAddModule={options.onAddModule} onToggleCollapse={options.onToggleCollapse}\n onRenamed={options.onRenamed}\n editor={editor}\n onFeaturesChanged={(moduleId, features) => {\n setLiveFeatures(previous => new Map(previous).set(moduleId.toString(), features));\n onFeaturesChanged?.(moduleId, features);\n }} />}\n />\n </SliceConnectionsProvider>\n </div>\n </div>\n </div>\n </BoardReadOnlyContext.Provider>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './CogWheel.css';\n\n// The system actor's mark.\nexport const CogWheel = () => (\n <span className='event-modeling-grid-cogwheel-icon'>\n <svg viewBox='0 0 64 64' width='72' height='72' fill='currentColor' xmlns='http://www.w3.org/2000/svg'>\n <path d='M54.2 27.4l-4.1-.7a18 18 0 0 0-1.2-2.9l2.4-3.4a2 2 0 0 0-.2-2.6l-4.8-4.8a2 2 0 0 0-2.6-.2l-3.4 2.4a18 18 0 0 0-2.9-1.2l-.7-4.1A2 2 0 0 0 35 8h-6a2 2 0 0 0-2 1.7l-.7 4.1a18 18 0 0 0-2.9 1.2l-3.4-2.4a2 2 0 0 0-2.6.2l-4.8 4.8a2 2 0 0 0-.2 2.6l2.4 3.4a18 18 0 0 0-1.2 2.9l-4.1.7A2 2 0 0 0 8 29v6a2 2 0 0 0 1.7 2l4.1.7a18 18 0 0 0 1.2 2.9l-2.4 3.4a2 2 0 0 0 .2 2.6l4.8 4.8a2 2 0 0 0 2.6.2l3.4-2.4a18 18 0 0 0 2.9 1.2l.7 4.1A2 2 0 0 0 29 56h6a2 2 0 0 0 2-1.7l.7-4.1a18 18 0 0 0 2.9-1.2l3.4 2.4a2 2 0 0 0 2.6-.2l4.8-4.8a2 2 0 0 0 .2-2.6l-2.4-3.4a18 18 0 0 0 1.2-2.9l4.1-.7A2 2 0 0 0 56 35v-6a2 2 0 0 0-1.8-1.6zM32 42a10 10 0 1 1 0-20 10 10 0 0 1 0 20z' />\n </svg>\n </span>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nexport interface CratisLogoProps {\n className?: string;\n title?: string;\n}\n\n// The full Cratis logo, drawn in the current text color.\nexport const CratisLogo = ({ className, title = 'Cratis' }: CratisLogoProps) => (\n <svg className={className} viewBox='0 0 600 328' fill='currentColor' role='img' aria-label={title} xmlns='http://www.w3.org/2000/svg'>\n <g transform='translate(0,328) scale(0.1,-0.1)'>\n <path d='M974 2789 c-319 -182 -592 -343 -607 -358 -16 -14 -34 -35 -40 -46 -8 -14 -10 -229 -9 -735 l3 -715 23 -35 c18 -26 74 -64 222 -151 110 -64 374 -219 589 -344 214 -126 400 -231 413 -233 13 -3 31 3 42 13 19 17 20 33 20 307 0 233 -3 294 -15 317 -10 21 -93 74 -327 211 -172 101 -324 194 -338 207 l-25 23 0 401 0 401 27 23 c14 12 161 100 327 194 177 101 310 184 325 202 l26 31 0 293 c0 318 -1 325 -55 325 -12 0 -283 -149 -601 -331z' />\n <path d='M4830 2314 c-62 -23 -90 -58 -90 -115 0 -22 10 -41 34 -65 30 -30 40 -34 85 -34 59 0 95 19 117 61 25 49 12 105 -32 134 -25 16 -91 27 -114 19z' />\n <path d='M4310 2080 l0 -80 -55 0 -55 0 0 -80 0 -80 55 0 55 0 0 -168 c0 -164 1 -170 28 -223 22 -44 36 -58 81 -81 45 -24 66 -28 131 -28 77 0 134 12 157 34 8 8 5 28 -14 79 -21 55 -29 67 -42 61 -9 -4 -35 -9 -57 -12 -34 -3 -46 1 -63 19 -19 21 -21 34 -21 171 l0 148 80 0 80 0 0 80 0 80 -80 0 -80 0 0 80 0 80 -100 0 -100 0 0 -80z' />\n <path d='M1495 2019 c-178 -98 -219 -126 -237 -157 -15 -26 -18 -57 -18 -215 0 -175 1 -186 23 -218 30 -45 326 -219 372 -219 34 0 319 157 361 199 24 23 24 26 24 230 l0 207 -27 31 c-39 44 -319 203 -358 203 -19 0 -73 -24 -140 -61z' />\n <path d='M2635 2006 c-110 -35 -200 -116 -230 -207 -22 -64 -22 -180 -1 -238 35 -96 124 -178 225 -208 79 -23 231 -15 291 16 53 27 106 75 126 113 l14 27 -74 40 c-40 23 -76 41 -79 41 -2 0 -22 -18 -44 -39 -30 -30 -50 -41 -86 -46 -135 -20 -230 129 -167 261 49 101 177 119 259 37 l35 -35 69 33 c37 19 72 39 78 45 13 15 -41 87 -90 119 -21 15 -60 33 -87 41 -58 17 -184 17 -239 0z' />\n <path d='M3405 2008 c-16 -6 -47 -22 -67 -35 l-38 -23 0 30 0 30 -100 0 -100 0 0 -330 0 -330 99 0 99 0 4 183 c3 159 6 187 24 222 25 49 89 85 151 85 l43 0 0 90 0 90 -42 -1 c-24 0 -56 -5 -73 -11z' />\n <path d='M3705 2007 c-61 -16 -145 -55 -145 -68 0 -7 56 -126 64 -136 1 -1 25 9 53 23 61 31 155 42 206 25 43 -14 77 -53 77 -87 0 -24 -1 -24 -108 -24 -173 0 -262 -34 -302 -116 -45 -92 -9 -203 83 -255 33 -18 62 -24 128 -27 97 -5 144 6 189 45 l30 25 0 -31 0 -31 96 0 96 0 -5 228 c-2 125 -10 243 -16 263 -19 63 -65 115 -128 145 -51 25 -70 29 -163 31 -60 1 -127 -3 -155 -10z m255 -425 c0 -71 -86 -123 -168 -100 -42 12 -61 33 -62 69 0 25 21 51 50 62 8 3 52 6 98 6 l82 1 0 -38z' />\n <path d='M5207 2006 c-66 -19 -119 -58 -146 -107 -19 -34 -23 -52 -19 -109 3 -60 8 -73 33 -101 42 -44 94 -65 210 -84 109 -19 145 -35 145 -66 0 -55 -151 -63 -272 -15 -36 14 -67 26 -69 26 -9 0 -73 -140 -67 -146 4 -3 37 -17 75 -31 90 -34 269 -44 353 -19 119 35 172 95 172 194 0 124 -50 164 -249 202 -56 10 -112 24 -123 30 -31 17 -22 51 20 73 45 23 149 17 216 -12 26 -12 48 -21 51 -21 5 0 63 129 63 140 0 5 -26 19 -57 31 -73 28 -261 36 -336 15z' />\n <path d='M4760 1680 l0 -330 100 0 100 0 0 330 0 330 -100 0 -100 0 0 -330z' />\n </g>\n </svg>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { ToolbarButton } from '@cratis/components/Toolbar';\nimport { defaultViewOptionsMessages, useEventModelMessages } from '../Messages';\nimport { MenuDropdown, type MenuDropdownItem } from '../Menus';\nimport { toggleGlobalDetails, type EventModelPresentation, type EventModelPresentationChange } from '../Presentation';\n\nexport interface BoardViewOptionsProps {\n presentation: EventModelPresentation;\n onChange: EventModelPresentationChange;\n}\n\n// The view options Cratis Studio offers above the board: how much of each slice is drawn, whether\n// properties are shown, and whether connections are drawn as arrows or as lines.\nexport const BoardViewOptions = ({ presentation, onChange }: BoardViewOptionsProps) => {\n const messages = useEventModelMessages().viewOptions ?? defaultViewOptionsMessages;\n const items: MenuDropdownItem[] = [\n { id: 'detail-level-header', isHeader: true, label: messages.detailLevel },\n {\n id: 'detail-level-full', label: messages.full, icon: <i className='pi pi-th-large' />, checked: presentation.detailLevel === 'full',\n onClick: () => onChange({ ...presentation, detailLevel: 'full' }),\n },\n {\n id: 'detail-level-overview', label: messages.overview, icon: <i className='pi pi-bars' />, checked: presentation.detailLevel === 'overview',\n onClick: () => onChange({ ...presentation, detailLevel: 'overview' }),\n },\n { id: 'properties-separator', isSeparator: true },\n { id: 'properties-header', isHeader: true, label: messages.properties },\n {\n id: 'properties', label: messages.properties, icon: <i className='pi pi-list' />, checked: presentation.detailsVisibility.global,\n onClick: () => onChange({ ...presentation, detailsVisibility: toggleGlobalDetails(presentation.detailsVisibility) }),\n },\n { id: 'visualization-separator', isSeparator: true },\n { id: 'visualization-header', isHeader: true, label: messages.visualization },\n {\n id: 'visualization-arrows', label: messages.arrows, icon: <i className='pi pi-arrow-right' />, checked: presentation.visualizationMode === 'simplified',\n onClick: () => onChange({ ...presentation, visualizationMode: 'simplified' }),\n },\n {\n id: 'visualization-lines', label: messages.lines, icon: <i className='pi pi-share-alt' />, checked: presentation.visualizationMode === 'fillLines',\n onClick: () => onChange({ ...presentation, visualizationMode: 'fillLines' }),\n },\n ];\n return (\n <MenuDropdown\n trigger={<ToolbarButton icon='pi pi-eye' title={messages.view} tooltipPosition='bottom' />}\n items={items}\n align='right' />\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './BoardOverlay.css';\nimport { useState, type ReactNode } from 'react';\nimport { Toolbar } from '@cratis/components/Toolbar';\nimport { CratisLogo } from '../Icons';\nimport {\n EventModelPresentationProvider,\n useEventModelPresentation,\n useEventModelPresentationChange,\n} from '../Presentation';\nimport { BoardViewOptions } from './BoardViewOptions';\n\nexport interface BoardOverlayProps {\n // Shows the Cratis logo in the upper left of the board.\n showLogo: boolean;\n // Offers the board's view options in the toolbar in the upper right of the board.\n showViewOptions: boolean;\n // The consumer's own tools, placed in the toolbar in the upper right of the board.\n toolbar?: ReactNode;\n children: ReactNode;\n}\n\n// What is drawn over the board rather than on it: the logo and the toolbar. The view options change the\n// presentation through EventModelPresentationProvider's onChange when the consumer gives one, and keep\n// the change on the board when it does not.\nexport const BoardOverlay = ({ showLogo, showViewOptions, toolbar, children }: BoardOverlayProps) => {\n const presentation = useEventModelPresentation();\n const change = useEventModelPresentationChange();\n const [own, setOwn] = useState(presentation);\n const shown = change ? presentation : own;\n const onChange = change ?? setOwn;\n const hasToolbar = showViewOptions || toolbar !== undefined;\n return (\n <EventModelPresentationProvider presentation={shown} onChange={onChange}>\n <div className='event-model-board'>\n {children}\n {showLogo && <CratisLogo className='event-model-board__logo' />}\n {hasToolbar && (\n <div className='event-model-board__toolbar' onPointerDown={event => event.stopPropagation()}>\n <Toolbar orientation='horizontal' aria-label='Board'>\n {toolbar}\n {showViewOptions && <BoardViewOptions presentation={shown} onChange={onChange} />}\n </Toolbar>\n </div>\n )}\n </div>\n </EventModelPresentationProvider>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\nimport type { ModuleCollectionLink } from '../Model';\n\nexport interface LinkState {\n snapshot: ModuleCollectionLink[];\n additions: ModuleCollectionLink[];\n removals: ReadonlySet<string>;\n pending: ReadonlySet<string>;\n // A locally created link may be removed before its creation ever appears in the query.\n // Absence only acknowledges a removal after this id has first been observed in a snapshot.\n observedRemovals: ReadonlySet<string>;\n}\n\nexport const linkPair = (sourceCollectionId: Guid, targetCollectionId: Guid): string =>\n `${sourceCollectionId.toString()}:${targetCollectionId.toString()}`;\n\nexport const visibleLinks = (state: LinkState): ModuleCollectionLink[] => [\n ...state.snapshot.filter(link => !state.removals.has(link.id.toString()) &&\n !state.additions.some(added => linkPair(added.sourceCollectionId, added.targetCollectionId) === linkPair(link.sourceCollectionId, link.targetCollectionId))),\n ...state.additions.filter(link => !state.removals.has(link.id.toString())),\n];\n\nexport const createLinkState = (snapshot: ModuleCollectionLink[]): LinkState => ({\n snapshot, additions: [], removals: new Set(), pending: new Set(), observedRemovals: new Set(),\n});\n\n// An observable snapshot can lag a successful command. Retain local links until the matching\n// server pair arrives and keep deleted links hidden until the server actually omits them.\nexport const reconcileLinks = (state: LinkState, snapshot: ModuleCollectionLink[]): LinkState => {\n const snapshotIds = new Set(snapshot.map(link => link.id.toString()));\n const observedRemovals = new Set([...state.observedRemovals, ...[...state.removals].filter(id => snapshotIds.has(id))]);\n const removals = new Set([...state.removals].filter(id =>\n snapshotIds.has(id) || state.pending.has(id) || !observedRemovals.has(id)));\n return {\n ...state,\n snapshot,\n additions: state.additions.filter(added => !snapshot.some(link =>\n linkPair(link.sourceCollectionId, link.targetCollectionId) === linkPair(added.sourceCollectionId, added.targetCollectionId))),\n removals,\n observedRemovals: new Set([...observedRemovals].filter(id => removals.has(id))),\n };\n};\n\nexport const beginLink = (state: LinkState, link: ModuleCollectionLink): LinkState => {\n const pair = linkPair(link.sourceCollectionId, link.targetCollectionId);\n if (state.pending.has(pair) || visibleLinks(state).some(existing =>\n linkPair(existing.sourceCollectionId, existing.targetCollectionId) === pair)) return state;\n return { ...state, additions: [...state.additions, link], pending: new Set([...state.pending, pair]) };\n};\n\nexport const finishLink = (state: LinkState, link: ModuleCollectionLink, persistedId?: Guid): LinkState => {\n const pair = linkPair(link.sourceCollectionId, link.targetCollectionId);\n const pending = new Set(state.pending);\n pending.delete(pair);\n const additions = state.additions.flatMap(added => added.id.toString() === link.id.toString()\n ? (persistedId ? [{ ...added, id: persistedId }] : []) : [added]);\n return reconcileLinks({ ...state, pending, additions }, state.snapshot);\n};\n\nexport const beginUnlink = (state: LinkState, id: Guid): LinkState => {\n const key = id.toString();\n if (state.pending.has(key) || !visibleLinks(state).some(link => link.id.toString() === key)) return state;\n return {\n ...state,\n removals: new Set([...state.removals, key]),\n pending: new Set([...state.pending, key]),\n observedRemovals: state.snapshot.some(link => link.id.toString() === key)\n ? new Set([...state.observedRemovals, key]) : state.observedRemovals,\n };\n};\n\nexport const finishUnlink = (state: LinkState, id: Guid, succeeded: boolean): LinkState => {\n const key = id.toString();\n const pending = new Set(state.pending);\n pending.delete(key);\n const removals = new Set(state.removals);\n if (!succeeded) removals.delete(key);\n const additions = succeeded ? state.additions.filter(link => link.id.toString() !== key) : state.additions;\n return reconcileLinks({ ...state, pending, removals, additions }, state.snapshot);\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ModuleCollectionLink } from '../Model';\nimport { computeSplineEndpoints, midpoint, smoothCurvePath, type Point, type Rect } from '../Geometry';\n\nexport interface DrawableLink {\n link: ModuleCollectionLink;\n path: string;\n // Where the remove affordance sits: for this curve's symmetric control points the midpoint of the\n // endpoints is the curve's halfway point, so the affordance sits exactly on the drawn spline.\n center: Point;\n}\n\n// The links that can be drawn: a link whose source or target collection is not placed yet is skipped\n// rather than drawn to nowhere.\nexport const drawableLinks = (links: ModuleCollectionLink[], contentOf: (collectionId: string) => Rect | undefined): DrawableLink[] =>\n links.flatMap(link => {\n const source = contentOf(link.sourceCollectionId.toString());\n const target = contentOf(link.targetCollectionId.toString());\n if (!source || !target) return [];\n const spline = computeSplineEndpoints(source, target);\n return [{ link, path: smoothCurvePath(spline.start, spline.end, spline.axis), center: midpoint(spline.start, spline.end) }];\n });\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './ModuleCollectionLinks.css';\nimport React, { useEffect, useId, useMemo, useRef, useState } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport type { ModuleCollectionLink, Position } from '../Model';\nimport { beginLink as beginOptimisticLink, beginUnlink, createLinkState, finishLink, finishUnlink, linkPair, reconcileLinks, visibleLinks, type LinkState } from './linkState';\nimport { useBoard } from '../Board';\nimport { drawableLinks } from './drawableLinks';\nimport {\n smoothCurvePath,\n boundingBox,\n computeSplineEndpoints,\n linkAnchor,\n pointInRect,\n rectAt,\n resolveDropTarget,\n type Point,\n type Rect,\n} from '../Geometry';\n\n// How far outside the outermost collection the drawing surface extends, so an in-progress drag line\n// toward an empty part of the board is not clipped.\nconst SVG_PADDING = 2000;\n\n// A module collection as the links see it: where it is, and which part of it is slice content.\nexport interface LinkedCollectionPlacement {\n id: Guid;\n position: Position;\n width: number;\n height: number;\n // The estimated content height excludes specifications below the slice columns.\n contentHeight: number;\n}\n\ninterface PlacedCollection {\n id: Guid;\n rect: Rect;\n content: Rect;\n}\n\nexport interface ModuleCollectionLinksProps {\n links: ModuleCollectionLink[];\n collections: LinkedCollectionPlacement[];\n // Reads the current canvas zoom, so screen drag deltas convert to world deltas.\n getZoom: () => number;\n // Linking two collections exists only when the board is editable and this is supplied.\n onCollectionsLinked?: (sourceCollectionId: Guid, targetCollectionId: Guid) => Promise<Guid | undefined>;\n // Return false on command failure so the optimistic removal can be restored.\n onCollectionsUnlinked?: (linkId: Guid) => Promise<boolean>;\n onPersistenceError?: (error: unknown) => void;\n}\n\n/** State of an in-progress drag-to-connect gesture. */\ninterface LinkDrag {\n sourceId: string;\n pointer: Point;\n targetId: string | null;\n}\n\n// Draws directed arrows between linked module collections in the canvas content coordinate space, and\n// hosts the gestures that ask to create (drag a collection's handle onto another) and remove (the\n// affordance at a link's midpoint) a link.\nexport const ModuleCollectionLinks = ({ links, collections, getZoom, onCollectionsLinked, onCollectionsUnlinked, onPersistenceError }: ModuleCollectionLinksProps) => {\n const board = useBoard();\n const messages = board.messages.links;\n const onLink = board.readOnly ? undefined : onCollectionsLinked;\n const onUnlink = board.readOnly ? undefined : onCollectionsUnlinked;\n\n const [drag, setDrag] = useState<LinkDrag | null>(null);\n const [linkState, setLinkState] = useState(() => createLinkState(links));\n const linkStateRef = useRef<LinkState>(linkState);\n const apply = (transition: (state: LinkState) => LinkState) => {\n const next = transition(linkStateRef.current);\n linkStateRef.current = next;\n setLinkState(next);\n };\n useEffect(() => {\n if (links !== linkStateRef.current.snapshot) apply(state => reconcileLinks(state, links));\n }, [links]);\n const displayedLinks = visibleLinks(linkState);\n const dragOriginRef = useRef<{ sourceId: Guid; anchor: Point; startClientX: number; startClientY: number } | null>(null);\n // The target the affordance last committed to, tracked synchronously so the drop can honor exactly\n // what the user was shown even if the release coordinate lands a hair outside it (see endLink).\n const lastTargetIdRef = useRef<string | null>(null);\n\n const markerId = `module-collection-link-arrow-${useId().replace(/:/g, '')}`;\n\n const rects = useMemo(() => new Map(collections.map((collection): [string, PlacedCollection] => {\n const rect = { x: collection.position.x, y: collection.position.y, width: collection.width, height: collection.height };\n return [collection.id.toString(), { id: collection.id, rect, content: { ...rect, height: Math.min(rect.height, collection.contentHeight) } }];\n })), [collections]);\n\n const drawable = useMemo(() => drawableLinks(displayedLinks, id => rects.get(id)?.content), [displayedLinks, rects]);\n\n const findTarget = (pointer: Point, sourceId: Guid): PlacedCollection | null => {\n for (const entry of rects.values()) {\n if (entry.id.toString() === sourceId.toString()) continue;\n if (pointInRect(pointer, entry.rect)) return entry;\n }\n return null;\n };\n\n const pointerFromEvent = (event: React.PointerEvent, origin: { anchor: Point; startClientX: number; startClientY: number }): Point => {\n const zoom = getZoom() || 1;\n return {\n x: origin.anchor.x + (event.clientX - origin.startClientX) / zoom,\n y: origin.anchor.y + (event.clientY - origin.startClientY) / zoom,\n };\n };\n\n const startLinkDrag = (sourceId: Guid, anchor: Point) => (event: React.PointerEvent) => {\n if (linkStateRef.current.pending.size > 0) return;\n event.stopPropagation();\n event.preventDefault();\n event.currentTarget.setPointerCapture(event.pointerId);\n dragOriginRef.current = { sourceId, anchor, startClientX: event.clientX, startClientY: event.clientY };\n lastTargetIdRef.current = null;\n setDrag({ sourceId: sourceId.toString(), pointer: anchor, targetId: null });\n };\n\n const updateLink = (event: React.PointerEvent) => {\n const origin = dragOriginRef.current;\n if (!origin) return;\n const pointer = pointerFromEvent(event, origin);\n const target = findTarget(pointer, origin.sourceId);\n lastTargetIdRef.current = target?.id.toString() ?? null;\n setDrag({ sourceId: origin.sourceId.toString(), pointer, targetId: target?.id.toString() ?? null });\n };\n\n const endLink = async (event: React.PointerEvent) => {\n const origin = dragOriginRef.current;\n const lastTargetId = lastTargetIdRef.current;\n dragOriginRef.current = null;\n lastTargetIdRef.current = null;\n setDrag(null);\n if (!origin) return;\n // Honor the target the affordance committed to: prefer a fresh hit-test at the release point,\n // but fall back to the last highlighted target. A quick release can land a hair outside the\n // target — or have its final pointermove coalesced away by the browser — even though the user\n // was shown \"will connect\"; without this fallback that gesture silently created no link.\n const releaseTarget = findTarget(pointerFromEvent(event, origin), origin.sourceId);\n const target = resolveDropTarget(releaseTarget, lastTargetId, id => rects.get(id), origin.sourceId.toString());\n if (!target) return;\n if (!onLink || linkStateRef.current.pending.size > 0) return;\n const optimisticLink = { id: Guid.create(), sourceCollectionId: origin.sourceId, targetCollectionId: target.id };\n const pair = linkPair(origin.sourceId, target.id);\n if (linkStateRef.current.pending.has(pair) || visibleLinks(linkStateRef.current).some(link =>\n linkPair(link.sourceCollectionId, link.targetCollectionId) === pair)) return;\n apply(state => beginOptimisticLink(state, optimisticLink));\n try {\n const persistedId = await onLink(origin.sourceId, target.id);\n apply(state => finishLink(state, optimisticLink, persistedId));\n } catch (error) {\n apply(state => finishLink(state, optimisticLink));\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n }\n };\n\n const removeLink = async (id: Guid) => {\n if (!onUnlink || linkStateRef.current.pending.size > 0) return;\n apply(state => beginUnlink(state, id));\n try {\n const succeeded = await onUnlink(id);\n apply(state => finishUnlink(state, id, succeeded));\n } catch (error) {\n apply(state => finishUnlink(state, id, false));\n if (onPersistenceError) onPersistenceError(error);\n else throw error;\n }\n };\n\n const cancelLink = () => {\n dragOriginRef.current = null;\n lastTargetIdRef.current = null;\n setDrag(null);\n };\n\n const collectionRects = Array.from(rects.values());\n if (collectionRects.length === 0) return null;\n\n const box = boundingBox(collectionRects.map(entry => entry.rect), drag ? [drag.pointer] : [], SVG_PADDING);\n const dragSource = drag ? rects.get(drag.sourceId) : undefined;\n const dropTarget = drag?.targetId ? rects.get(drag.targetId) : undefined;\n\n return (\n <div className='module-collection-link-layer'>\n <svg\n className='module-collection-link-layer__svg'\n style={{ left: box.x, top: box.y, width: box.width, height: box.height }}\n viewBox={`${box.x} ${box.y} ${box.width} ${box.height}`}\n aria-hidden='true'>\n <defs>\n <marker id={markerId} markerWidth='10' markerHeight='10' refX='8' refY='4' orient='auto' markerUnits='userSpaceOnUse'>\n <path d='M 0 0 L 9 4 L 0 8 z' className='module-collection-link-layer__arrow-head' />\n </marker>\n </defs>\n {drawable.map(({ link, path }) => (\n <path\n key={link.id.toString()}\n d={path}\n className='module-collection-link-layer__arrow'\n markerEnd={`url(#${markerId})`}\n />\n ))}\n {drag && dragSource && (\n (() => {\n const spline = computeSplineEndpoints(dragSource.content, rectAt(drag.pointer));\n return (\n <path\n d={smoothCurvePath(spline.start, spline.end, spline.axis)}\n className='module-collection-link-layer__preview'\n markerEnd={`url(#${markerId})`}\n />\n );\n })()\n )}\n </svg>\n\n {dropTarget && (\n <div\n className='module-collection-link-layer__drop-target'\n style={{ left: dropTarget.rect.x, top: dropTarget.rect.y, width: dropTarget.rect.width, height: dropTarget.rect.height }}\n />\n )}\n\n {onLink && linkState.pending.size === 0 && collectionRects.map(({ id, content }) => {\n const anchor = linkAnchor(content);\n return (\n <div\n key={id.toString()}\n className='module-collection-link-layer__handle'\n style={{ left: anchor.x, top: anchor.y }}\n title={messages.dragToLink}\n onPointerDown={startLinkDrag(id, anchor)}\n onPointerMove={updateLink}\n onPointerUp={endLink}\n onPointerCancel={cancelLink}\n />\n );\n })}\n\n {onUnlink && linkState.pending.size === 0 && drawable.map(({ link, center }) => (\n <button\n key={link.id.toString()}\n type='button'\n className='module-collection-link-layer__delete'\n style={{ left: center.x, top: center.y }}\n title={messages.removeLink}\n onPointerDown={event => event.stopPropagation()}\n onClick={() => void removeLink(link.id)}>\n <i className='pi pi-times' />\n </button>\n ))}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Whether a key pressed on target is typing into a field, which must never delete the note behind it.\nexport const isEditableTarget = (target: EventTarget | null): boolean =>\n typeof Element !== 'undefined' && target instanceof Element && !!target.closest('input, textarea, [contenteditable=\"true\"]');\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { StickyNote } from '../Model';\n\nconst LOCAL_EDIT_GUARD_MS = 4000;\n\nconst sameNote = (first: StickyNote, second: StickyNote) =>\n first.id === second.id && first.text === second.text &&\n first.position.x === second.position.x && first.position.y === second.position.y &&\n first.width === second.width && first.height === second.height;\n\ninterface PendingNote {\n note: StickyNote | null;\n created: boolean;\n inFlight: boolean;\n expiresAt: number;\n}\n\n// Deletion tombstones last for the mounted session; edits have a bounded local guard because an\n// observable snapshot carries no causal revision with which to distinguish an echo from another edit.\nexport class StickyNoteState {\n private remote: readonly StickyNote[];\n private readonly pending = new Map<string, PendingNote>();\n\n constructor(notes: readonly StickyNote[], private readonly now: () => number = Date.now) {\n this.remote = notes;\n }\n\n get notes(): StickyNote[] {\n const remoteIds = new Set(this.remote.map(note => note.id));\n return [\n ...this.remote.flatMap(note => {\n const local = this.pending.get(note.id)?.note;\n return local === null ? [] : [local ?? note];\n }),\n ...[...this.pending.entries()].flatMap(([id, change]) => change.note && !remoteIds.has(id) ? [change.note] : []),\n ];\n }\n\n get(id: string): StickyNote | undefined {\n return this.notes.find(note => note.id === id);\n }\n\n change(id: string, note: StickyNote | null): void {\n this.pending.set(id, {\n note,\n created: this.pending.get(id)?.created ?? !this.remote.some(remote => remote.id === id),\n inFlight: false,\n expiresAt: this.now() + LOCAL_EDIT_GUARD_MS,\n });\n }\n\n begin(id: string, note: StickyNote | null): void {\n const pending = this.pending.get(id);\n if (pending?.note === note) pending.inFlight = true;\n }\n\n settle(id: string, note: StickyNote | null): void {\n const pending = this.pending.get(id);\n if (!pending || pending.note !== note) return;\n pending.inFlight = false;\n pending.expiresAt = this.now() + LOCAL_EDIT_GUARD_MS;\n const remote = this.remote.find(candidate => candidate.id === id);\n if (note && remote && sameNote(note, remote)) this.pending.delete(id);\n }\n\n reconcile(notes: readonly StickyNote[]): void {\n this.remote = notes;\n for (const [id, pending] of this.pending) {\n if (pending.note === null || pending.inFlight) continue;\n const remote = notes.find(note => note.id === id);\n if (remote && sameNote(pending.note, remote)) this.pending.delete(id);\n }\n this.expire();\n }\n\n expire(): void {\n for (const [id, pending] of this.pending) {\n if (pending.note === null || pending.inFlight || this.now() < pending.expiresAt) continue;\n if (pending.created && !this.remote.some(note => note.id === id)) continue;\n this.pending.delete(id);\n }\n }\n\n get nextExpiration(): number | undefined {\n const deadlines = [...this.pending.entries()]\n .filter(([id, pending]) => pending.note !== null && !pending.inFlight &&\n (!pending.created || this.remote.some(note => note.id === id)))\n .map(([, pending]) => pending.expiresAt);\n return deadlines.length ? Math.min(...deadlines) : undefined;\n }\n\n rollback(id: string, change: StickyNote | null): void {\n if (this.pending.get(id)?.note === change) this.pending.delete(id);\n }\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, type SyntheticEvent } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { CanvasItem, Note } from '@cratis/components/Canvas';\nimport { ProgressSpinner } from '@cratis/components/Display';\nimport type { Position, StickyNote } from '../Model';\nimport { useBoard } from '../Board';\nimport { useDismissOnOutsidePointer } from '../Pickers/useDismissOnOutsidePointer';\nimport { isEditableTarget } from './isEditableTarget';\nimport type { StickyNoteBounds } from './StickyNoteBounds';\nimport type { StickyNoteHandle } from './StickyNoteHandle';\nimport { StickyNoteState } from './StickyNoteState';\nimport './StickyNotes.css';\n\nexport interface StickyNotesProps {\n notes: readonly StickyNote[];\n}\n\nconst DEFAULT_SIZE = 50;\nconst ignore = () => undefined;\nconst stop = (event: SyntheticEvent) => event.stopPropagation();\ntype ChangeResult = Promise<boolean | void> | boolean | void;\n\n// The board owns selection and local edits; its consumer only persists finished gestures. Observable\n// snapshots are merged per note; edit guards are bounded, while deletion tombstones last for this mount.\nexport const StickyNotes = forwardRef<StickyNoteHandle, StickyNotesProps>(({ notes }, handle) => {\n const { editing, actions, messages } = useBoard();\n const state = useRef(new StickyNoteState(notes));\n const inFlight = useRef(new Set<string>());\n const creating = useRef(false);\n const movedIds = useRef(new Set<string>());\n const resizedIds = useRef(new Set<string>());\n const [revision, refresh] = useState(0);\n const [selectedId, setSelectedId] = useState<string | undefined>();\n const [expandedId, setExpandedId] = useState<string | undefined>();\n const container = useRef<HTMLDivElement>(null);\n const containers = useMemo(() => [container], []);\n const repaint = useCallback(() => refresh(previous => previous + 1), []);\n\n useEffect(() => {\n state.current.reconcile(notes);\n repaint();\n }, [notes, repaint]);\n\n useEffect(() => {\n const deadline = state.current.nextExpiration;\n if (deadline === undefined) return;\n const timer = setTimeout(() => {\n state.current.expire();\n repaint();\n }, Math.max(0, deadline - Date.now()));\n return () => clearTimeout(timer);\n }, [revision, repaint]);\n\n const persist = useCallback((id: string, change: StickyNote | null, execute: () => ChangeResult) => {\n if (inFlight.current.has(id)) return Promise.resolve();\n inFlight.current.add(id);\n state.current.change(id, change);\n state.current.begin(id, change);\n repaint();\n // An unsuccessful command must not leave an optimistic edit masquerading as persisted state.\n return Promise.resolve().then(execute).then(success => {\n if (success === false) {\n state.current.rollback(id, change);\n if (!state.current.get(id)) setSelectedId(previous => previous === id ? undefined : previous);\n repaint();\n }\n return success !== false;\n }).catch(error => {\n state.current.rollback(id, change);\n if (!state.current.get(id)) setSelectedId(previous => previous === id ? undefined : previous);\n repaint();\n if (actions.stickyNoteError) actions.stickyNoteError(error);\n else console.error(error);\n return false;\n }).finally(() => {\n state.current.settle(id, change);\n inFlight.current.delete(id);\n repaint();\n });\n }, [actions, repaint]);\n\n useImperativeHandle(handle, () => ({\n add(center: Position) {\n const add = editing.onStickyNoteAdded;\n if (!add || creating.current) return;\n creating.current = true;\n actions.stickyNoteCreatingChanged?.(true);\n const note: StickyNote = {\n id: Guid.create().toString(),\n position: { x: center.x - DEFAULT_SIZE / 2, y: center.y - DEFAULT_SIZE / 2 },\n width: DEFAULT_SIZE,\n height: DEFAULT_SIZE,\n text: messages.stickyNotes.newNote,\n };\n setSelectedId(note.id);\n void persist(note.id, note, () => add(note)).then(succeeded => {\n if (succeeded) actions.stickyNoteCreated?.(note);\n }).finally(() => {\n creating.current = false;\n actions.stickyNoteCreatingChanged?.(false);\n });\n },\n }), [editing, actions, messages, persist]);\n\n const select = editing.onStickyNoteMoved || editing.onStickyNoteResized || editing.onStickyNoteTextChanged || editing.onStickyNoteRemoved\n ? setSelectedId : undefined;\n useDismissOnOutsidePointer(containers, () => select?.(undefined), selectedId !== undefined && !!select);\n\n const move = (id: string, position: Position) => {\n const note = state.current.get(id);\n if (!note || inFlight.current.has(id) || (note.position.x === position.x && note.position.y === position.y)) return;\n movedIds.current.add(id);\n state.current.change(id, { ...note, position });\n repaint();\n };\n const resize = (id: string, bounds: StickyNoteBounds) => {\n const note = state.current.get(id);\n if (!note || inFlight.current.has(id) || (note.position.x === bounds.position.x && note.position.y === bounds.position.y && note.width === bounds.width && note.height === bounds.height)) return;\n resizedIds.current.add(id);\n state.current.change(id, { ...note, ...bounds });\n repaint();\n };\n const moveEnd = (id: string) => {\n if (!movedIds.current.delete(id)) return;\n const note = state.current.get(id);\n if (note && editing.onStickyNoteMoved) void persist(id, note, () => editing.onStickyNoteMoved?.(id, note.position));\n };\n const resizeEnd = (id: string) => {\n if (!resizedIds.current.delete(id)) return;\n const note = state.current.get(id);\n if (note && editing.onStickyNoteResized) void persist(id, note, () => editing.onStickyNoteResized?.(id, {\n position: note.position, width: note.width, height: note.height,\n }));\n };\n const changeText = (id: string, text: string) => {\n const note = state.current.get(id);\n if (note && note.text !== text && editing.onStickyNoteTextChanged) {\n void persist(id, { ...note, text }, () => editing.onStickyNoteTextChanged?.(id, text));\n }\n };\n const remove = useCallback((id: string) => {\n if (!state.current.get(id) || !editing.onStickyNoteRemoved || inFlight.current.has(id)) return;\n setSelectedId(previous => previous === id ? undefined : previous);\n void persist(id, null, () => editing.onStickyNoteRemoved?.(id));\n }, [editing, persist]);\n\n useEffect(() => {\n if (!editing.onStickyNoteRemoved || selectedId === undefined) return;\n const onKeyDown = (event: KeyboardEvent) => {\n if ((event.key !== 'Delete' && event.key !== 'Backspace') || isEditableTarget(event.target)) return;\n event.preventDefault();\n remove(selectedId);\n };\n document.addEventListener('keydown', onKeyDown);\n return () => document.removeEventListener('keydown', onKeyDown);\n }, [selectedId, editing, remove]);\n\n return (\n <div ref={container} className='event-model-sticky-notes'>\n {state.current.notes.map(note => {\n const x = note.position?.x ?? 0;\n const y = note.position?.y ?? 0;\n return (\n <CanvasItem key={note.id} x={x} y={y} zIndex={expandedId === note.id ? 3 : 2}>\n <div\n data-sticky-note-id={note.id}\n className={inFlight.current.has(note.id) ? 'event-model-sticky-note--busy' : undefined}\n aria-busy={inFlight.current.has(note.id)}\n onDoubleClickCapture={editing.onStickyNoteTextChanged && !inFlight.current.has(note.id) ? undefined : stop}\n >\n <Note\n note={{ id: note.id, x, y, width: note.width, height: note.height, text: note.text }}\n selected={selectedId === note.id && !!editing.onStickyNoteResized && !inFlight.current.has(note.id)}\n onSelect={select ?? ignore}\n onMove={editing.onStickyNoteMoved ? (id, x, y) => move(id, { x, y }) : ignore}\n onMoveEnd={editing.onStickyNoteMoved ? moveEnd : undefined}\n onResize={editing.onStickyNoteResized ? (id, x, y, width, height) => resize(id, { position: { x, y }, width, height }) : ignore}\n onResizeEnd={editing.onStickyNoteResized ? resizeEnd : undefined}\n onTextChange={editing.onStickyNoteTextChanged ? changeText : ignore}\n onExpandedChange={(id, expanded) => setExpandedId(previous => expanded ? id : previous === id ? undefined : previous)}\n />\n {inFlight.current.has(note.id) && <span className='event-model-sticky-note__progress' aria-hidden='true'><ProgressSpinner className='event-model-sticky-note__spinner' /></span>}\n </div>\n </CanvasItem>\n );\n })}\n </div>\n );\n});\n\nStickyNotes.displayName = 'StickyNotes';\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { memo, useCallback, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { CollectionGrid, CollectionViewport, type CollectionSizeEstimate } from '../Collections';\nimport type { BoardCollection, CollectionGridContent, CollectionGridRenderer } from './BoardCollections';\n\nexport interface BoardCollectionViewProps {\n collection: BoardCollection;\n estimatedSize: CollectionSizeEstimate;\n measuredSize?: { width: number; height: number };\n onSize: (id: Guid, width: number, height: number) => void;\n getZoom: () => number;\n canMove: boolean;\n onCollectionMoving?: (id: Guid, deltaX: number, deltaY: number) => void;\n onCollectionMoved?: (id: Guid, position: { x: number; y: number }) => void;\n content: (grid: CollectionGridRenderer) => ReactNode;\n}\n\n// Memoized so a collection being dragged, or a size being measured, re-renders only that collection.\nexport const BoardCollectionView = memo(({ collection, estimatedSize, measuredSize, onSize, getZoom, canMove,\n onCollectionMoving, onCollectionMoved, content }: BoardCollectionViewProps) => {\n const grid = useCallback((gridContent: CollectionGridContent) => <CollectionGrid {...gridContent} getZoom={getZoom}\n canMove={canMove} onCollectionMoving={onCollectionMoving} onCollectionMoved={onCollectionMoved} />,\n [getZoom, canMove, onCollectionMoving, onCollectionMoved]);\n return <CollectionViewport collection={collection} estimatedSize={estimatedSize} measuredSize={measuredSize} onSize={onSize}>\n {content(grid)}\n </CollectionViewport>;\n});\n\nBoardCollectionView.displayName = 'BoardCollectionView';\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Position } from '../Model';\n\nexport interface BoardMinimapItem {\n x: number;\n y: number;\n width: number;\n height: number;\n color: string;\n}\n\nexport interface BoardMinimap {\n items: BoardMinimapItem[];\n worldWidth: number;\n worldHeight: number;\n}\n\n// The canvas minimap's own world size; the board only grows it when collections reach past it.\nconst MINIMUM_WORLD_WIDTH = 4000;\nconst MINIMUM_WORLD_HEIGHT = 3000;\nconst WORLD_PADDING = 200;\nconst COLLECTION_COLOR = 'rgba(100, 160, 255, 0.35)';\n\n// Sized from estimates rather than measurements, so collections that were never scrolled into view still show.\nexport const boardMinimap = (collections: readonly { position?: Position; size: { width: number; height: number } }[]): BoardMinimap => {\n const items = collections.map(({ position, size }) => ({\n x: position?.x ?? 0, y: position?.y ?? 0, width: size.width, height: size.height, color: COLLECTION_COLOR,\n }));\n return {\n items,\n worldWidth: Math.max(MINIMUM_WORLD_WIDTH, ...items.map(item => item.x + item.width + WORLD_PADDING)),\n worldHeight: Math.max(MINIMUM_WORLD_HEIGHT, ...items.map(item => item.y + item.height + WORLD_PADDING)),\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Feature, ModuleCollection } from '../Model';\n\n// Above this many slices the glass control pill's per-frame capture stalls pan and zoom.\nexport const LARGE_BOARD_SLICE_COUNT = 40;\n\nconst countFeatureSlices = (features: readonly Feature[]): number =>\n features.reduce((total, feature) => total + feature.slices.length + countFeatureSlices(feature.subFeatures), 0);\n\nexport const countCollectionSlices = (collection: ModuleCollection): number =>\n collection.modules.reduce((total, module) => total + countFeatureSlices(module.features), 0);\n\nexport const isLargeBoard = (sliceCount: number): boolean => sliceCount > LARGE_BOARD_SLICE_COUNT;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Fragment, useCallback, useImperativeHandle, useMemo, useRef, useState, type ReactNode, type Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { resolveOverlappingCollections, useCollectionsArea, type CollectionSizeEstimate } from '../Collections';\nimport { ModuleCollectionLinks, type LinkedCollectionPlacement } from '../Links';\nimport type { ModuleCollectionLink, StickyNote } from '../Model';\nimport { StickyNotes, type StickyNoteHandle } from '../StickyNotes';\nimport { BoardCanvas } from './BoardCanvas';\nimport { BoardOverlay } from './BoardOverlay';\nimport { BoardCollectionView } from './BoardCollectionView';\nimport type { BoardCollection, BoardCollections, CollectionGridRenderer } from './BoardCollections';\nimport type { EventModelBoardCanvas, EventModelBoardInteractions } from './EventModelBoardEditor';\nimport type { EventModelBoardHandle } from './EventModelBoardHandle';\nimport { BoardProvider } from './BoardProvider';\nimport { boardMinimap } from './boardMinimap';\nimport { isLargeBoard } from './isLargeBoard';\n\nexport interface HostedEventModelBoardProps<T extends BoardCollection> {\n id: Guid;\n collections: BoardCollections<T>;\n links: ModuleCollectionLink[];\n stickyNotes: readonly StickyNote[];\n readOnly?: boolean;\n editor?: EventModelBoardInteractions;\n canvas?: EventModelBoardCanvas;\n showMinimap?: boolean;\n // Shows the Cratis logo in the upper left of the board. Off unless asked for.\n showLogo?: boolean;\n // Offers the view options - detail level, properties and how connections are drawn - in the toolbar\n // in the upper right of the board. Off unless asked for.\n showViewOptions?: boolean;\n // The consumer's own tools, placed in the toolbar in the upper right of the board.\n toolbar?: ReactNode;\n handle?: Ref<EventModelBoardHandle>;\n}\n\ntype ContentProps<T extends BoardCollection> = Omit<HostedEventModelBoardProps<T>, 'id' | 'readOnly' | 'showMinimap' | 'showLogo' | 'showViewOptions' | 'toolbar'> &\n { readOnly: boolean; showMinimap: boolean };\n\n// Caches a derived value per collection object, so an unchanged collection keeps the same value and its memoized view.\nfunction usePerCollection<T extends object, R>(derive: (collection: T) => R): (collection: T) => R {\n return useMemo(() => {\n const cache = new WeakMap<T, R>();\n return (collection: T) => {\n const cached = cache.get(collection);\n if (cached !== undefined) return cached;\n const value = derive(collection);\n cache.set(collection, value);\n return value;\n };\n }, [derive]);\n}\n\nconst HostedEventModelBoardContent = <T extends BoardCollection>({ collections: host, links, stickyNotes, readOnly, editor,\n canvas, showMinimap, handle }: ContentProps<T>) => {\n const linkEditor = readOnly ? undefined : editor?.links;\n const area = useCollectionsArea<T>({\n initialCollections: host.initialCollections,\n onAddCollection: host.onAddCollection,\n onCollectionMoved: host.onCollectionMoved,\n onCollectionsChange: host.onCollectionsChange,\n onPersistenceError: host.onPersistenceError,\n });\n const { collections, pendingMoveIds, canMove, moveCollection, collectionMoved, addCollection } = area;\n const [sizes, setSizes] = useState<ReadonlyMap<string, { width: number; height: number }>>(new Map());\n const zoom = useRef(canvas?.initialZoom ?? 1);\n const getZoom = useCallback(() => zoom.current, []);\n const stickyNotesRef = useRef<StickyNoteHandle | null>(null);\n useImperativeHandle(handle, () => ({\n addCollection,\n addStickyNote: center => stickyNotesRef.current?.add(center),\n }), [addCollection]);\n const onSize = useCallback((id: Guid, width: number, height: number) => {\n setSizes(previous => {\n const key = id.toString();\n const existing = previous.get(key);\n if (existing?.width === width && existing.height === height) return previous;\n return new Map(previous).set(key, { width, height });\n });\n }, []);\n const estimateOf = usePerCollection<T, CollectionSizeEstimate>(host.estimateSize);\n const { renderCollection } = host;\n const contentOf = usePerCollection<T, (grid: CollectionGridRenderer) => ReactNode>(\n useCallback((collection: T) => (grid: CollectionGridRenderer) => renderCollection(collection, grid), [renderCollection]));\n const placed = useMemo(() => resolveOverlappingCollections(collections), [collections]);\n const minimap = useMemo(() => boardMinimap(placed.map(collection => ({ position: collection.position, size: estimateOf(collection) }))),\n [placed, estimateOf]);\n const { countSlices } = host;\n const largeBoard = useMemo(() => isLargeBoard(collections.reduce((total, collection) => total + countSlices(collection), 0)),\n [collections, countSlices]);\n const placements = useMemo(() => placed.flatMap((collection): LinkedCollectionPlacement[] => {\n const measured = sizes.get(collection.id.toString());\n if (!measured) return [];\n return [{ id: collection.id, position: collection.position, width: measured.width,\n height: measured.height, contentHeight: estimateOf(collection).height }];\n }), [placed, sizes, estimateOf]);\n const onTransformChange = canvas?.onTransformChange;\n const handleTransformChange = useCallback((nextZoom: number, pan: { x: number; y: number }) => {\n zoom.current = nextZoom;\n onTransformChange?.(nextZoom, pan);\n }, [onTransformChange]);\n\n const content = <>\n {placed.map(collection => <BoardCollectionView key={collection.id.toString()} collection={collection}\n estimatedSize={estimateOf(collection)} measuredSize={sizes.get(collection.id.toString())} onSize={onSize}\n getZoom={getZoom} canMove={canMove && !pendingMoveIds.has(collection.id.toString())}\n onCollectionMoving={canMove ? moveCollection : undefined} onCollectionMoved={canMove ? collectionMoved : undefined}\n content={contentOf(collection)} />)}\n <ModuleCollectionLinks links={links} collections={placements} getZoom={getZoom} {...linkEditor} />\n <StickyNotes ref={stickyNotesRef} notes={stickyNotes} />\n </>;\n\n return <BoardCanvas controlsPlacement='bottom-right' disableControlsGlass={largeBoard} {...canvas}\n style={{ width: '100%', height: '100%', ...canvas?.style }}\n showMinimap={showMinimap} minimapItems={minimap.items}\n minimapWorldWidth={minimap.worldWidth} minimapWorldHeight={minimap.worldHeight}\n onTransformChange={handleTransformChange}>\n {host.area ? host.area(area, content) : <Fragment>{content}</Fragment>}\n </BoardCanvas>;\n};\n\n// The one board tree for any host: collections in the host's own shape, drawn with the package's grid.\n// Nothing is drawn over the board unless the consumer asks for it.\nexport const HostedEventModelBoard = <T extends BoardCollection>({ id, readOnly = false, showMinimap = true, showLogo = false,\n showViewOptions = false, toolbar, editor, ...props }: HostedEventModelBoardProps<T>) => {\n const board = (\n <BoardProvider readOnly={readOnly} editing={readOnly ? undefined : editor?.editing}\n actions={readOnly ? undefined : editor?.actions} selection={editor?.selection} navigation={editor?.navigation}>\n <HostedEventModelBoardContent<T> key={id.toString()} readOnly={readOnly} showMinimap={showMinimap} editor={editor} {...props} />\n </BoardProvider>\n );\n if (!showLogo && !showViewOptions && toolbar === undefined) return board;\n return <BoardOverlay showLogo={showLogo} showViewOptions={showViewOptions} toolbar={toolbar}>{board}</BoardOverlay>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useMemo, type ReactNode, type Ref } from 'react';\nimport { estimateCollectionSize, useSliceDetailsVisibility } from '../Collections';\nimport type { EventModel, ModuleCollection } from '../Model';\nimport type { BoardCollections, CollectionGridRenderer } from './BoardCollections';\nimport type { EventModelBoardCanvas, EventModelBoardEditor } from './EventModelBoardEditor';\nimport type { EventModelBoardHandle } from './EventModelBoardHandle';\nimport { BoardOverlay } from './BoardOverlay';\nimport { HostedEventModelBoard } from './HostedEventModelBoard';\nimport { countCollectionSlices } from './isLargeBoard';\n\nexport interface EventModelBoardProps {\n document: EventModel;\n readOnly?: boolean;\n editor?: EventModelBoardEditor;\n canvas?: EventModelBoardCanvas;\n showMinimap?: boolean;\n // Shows the Cratis logo in the upper left of the board. Off unless asked for.\n showLogo?: boolean;\n // Offers the view options - detail level, properties and how connections are drawn - in the toolbar\n // in the upper right of the board. They change the presentation through EventModelPresentationProvider's\n // onChange, or on the board itself when there is none. Off unless asked for.\n showViewOptions?: boolean;\n // The consumer's own tools, placed in the toolbar in the upper right of the board.\n toolbar?: ReactNode;\n handle?: Ref<EventModelBoardHandle>;\n}\n\ntype ContentProps = Omit<EventModelBoardProps, 'showLogo' | 'showViewOptions' | 'toolbar'>;\n\nconst EventModelBoardContent = ({ document, readOnly = false, editor, canvas, showMinimap = true, handle }: ContentProps) => {\n const collectionEditor = readOnly ? undefined : editor?.collection;\n const collectionBoundary = readOnly ? undefined : editor?.collectionBoundary;\n const persistence = readOnly ? undefined : editor?.collections;\n const renderCollection = useCallback((collection: ModuleCollection, grid: CollectionGridRenderer) => {\n const content = grid({ collection, ...collectionEditor?.(collection) });\n return collectionBoundary ? collectionBoundary(collection, content) : content;\n }, [collectionEditor, collectionBoundary]);\n // Collections are estimated as the presentation draws them, so a board showing properties is not\n // measured as if it did not.\n const showsDetails = useSliceDetailsVisibility();\n const estimateSize = useCallback((collection: ModuleCollection) => estimateCollectionSize(collection, showsDetails), [showsDetails]);\n const collections = useMemo<BoardCollections<ModuleCollection>>(() => ({\n initialCollections: document.collections,\n estimateSize,\n countSlices: countCollectionSlices,\n renderCollection,\n ...persistence,\n }), [document.collections, estimateSize, renderCollection, persistence]);\n return <HostedEventModelBoard id={document.id} collections={collections} links={document.links}\n stickyNotes={document.stickyNotes} readOnly={readOnly} editor={editor} canvas={canvas}\n showMinimap={showMinimap} handle={handle} />;\n};\n\n// Draws a whole event model document; the editor factory and boundary are never called in read-only mode.\n// What is drawn over it wraps the whole board, so the board is sized for the presentation it is shown in.\nexport const EventModelBoard = ({ showLogo = false, showViewOptions = false, toolbar, ...props }: EventModelBoardProps) => {\n if (!showLogo && !showViewOptions && toolbar === undefined) return <EventModelBoardContent {...props} />;\n return (\n <BoardOverlay showLogo={showLogo} showViewOptions={showViewOptions} toolbar={toolbar}>\n <EventModelBoardContent {...props} />\n </BoardOverlay>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode } from 'react';\nimport { ToolbarSlot } from '@cratis/components/Toolbar';\nimport { useBoard } from './useBoard';\n\nexport interface BoardToolbarProps {\n // The toolbar layout the consumer's tools are placed in.\n slotName: string;\n order?: number;\n children?: ReactNode;\n}\n\n// The consumer's tools for the board, such as adding a sticky note. They are offered only on an editable\n// board: a read-only board is often shown inside something else, and tools placed in the host's toolbar\n// would reach a board that is not really open.\nexport const BoardToolbar = ({ slotName, order, children }: BoardToolbarProps) => {\n const { readOnly } = useBoard();\n return readOnly ? undefined : <ToolbarSlot slotName={slotName} order={order}>{children}</ToolbarSlot>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { createContext } from 'react';\nimport type { SliceContextValue } from './SliceContextValue';\n\nexport const SliceContext = createContext<SliceContextValue | undefined>(undefined);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { useMemo } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceStatus, SliceType } from '../Model';\nimport { useBoard } from '../Board';\nimport { resolveSliceReadOnly } from './resolveSliceReadOnly';\nimport { SliceContext } from './SliceContext';\nimport type { SliceContextValue } from './SliceContextValue';\n\nexport interface SliceProviderProps {\n sliceId: Guid;\n sliceType: SliceType;\n status: SliceStatus;\n children?: React.ReactNode;\n}\n\nexport const SliceProvider = ({ sliceId, sliceType, status, children }: SliceProviderProps) => {\n const { readOnly: boardReadOnly, presentation } = useBoard();\n const readOnly = resolveSliceReadOnly(boardReadOnly, presentation.detailLevel, status);\n const value = useMemo<SliceContextValue>(() => ({ readOnly, sliceId, sliceType }), [readOnly, sliceId, sliceType]);\n return <SliceContext.Provider value={value}>{children}</SliceContext.Provider>;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useContext } from 'react';\nimport { useBoard } from '../Board';\nimport { SliceContext } from './SliceContext';\nimport type { SliceContextValue } from './SliceContextValue';\n\nexport const useSlice = (): SliceContextValue => {\n const { readOnly } = useBoard();\n return useContext(SliceContext) ?? { readOnly };\n};\n\nexport const useSliceReadOnly = (): boolean => useSlice().readOnly;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/AddButton.css';\nimport './SliceHeader.css';\nimport React from 'react';\nimport type { SliceStatus } from '../Model';\nimport type { SliceHeaderSlice } from './SliceHeaderSlice';\nimport { useBoard } from '../Board';\nimport { CollapseButton, EditableLabel, EntityErrorIndicator } from '../Headers';\nimport { SliceStatusPicker } from '../Statuses';\nimport { SliceTypeExplanation, SliceTypeMenu } from '../SliceTypes';\nimport { GridTooltip } from '../Tooltips';\nimport { useSlice } from './useSlice';\nimport { useEventModelPresentation } from '../Presentation';\n\nexport interface SliceHeaderProps {\n slice: SliceHeaderSlice;\n height: number;\n collapsed: boolean;\n\n // The statuses that may be picked, and why the others cannot. Every status when omitted.\n selectableStatuses?: readonly SliceStatus[];\n unselectableStatusReason?: string;\n // Shown on the header when something done to the slice failed.\n error?: string;\n // What the consumer adds after the collapse button, and between the status and the add menu.\n leading?: React.ReactNode;\n trailing?: React.ReactNode;\n // Collapses or expands the slice on a read-only board, which collapses on its own rather than through editing.\n onToggleCollapse?: () => void;\n}\n\nconst nameStyle: React.CSSProperties = { fontSize: 11, fontWeight: 500, color: 'rgba(255,255,255,0.80)', textAlign: 'center' };\n\nexport const SliceHeader = ({\n slice,\n height,\n collapsed,\n selectableStatuses,\n unselectableStatusReason,\n error,\n leading,\n trailing,\n onToggleCollapse,\n}: SliceHeaderProps) => {\n const board = useBoard();\n const { showStatuses = true } = useEventModelPresentation();\n const { readOnly } = useSlice();\n const { editing, actions } = board;\n const renamed = editing.onSliceRenamed;\n const statusChanged = editing.onSliceStatusChanged;\n const sliceAdded = editing.onSliceAdded;\n const toggleCollapse = editing.onSliceOpenStateSet;\n const headerActions = (actions.sliceHeader ?? []).filter(action => !action.when || action.when(slice));\n\n return (\n <div\n className='event-modeling-grid-slice-column-header'\n style={{ height, cursor: collapsed || readOnly ? 'default' : 'grab', ...(error ? { border: '2px solid #ef4444' } : {}) }}\n >\n <div className='event-modeling-grid-slice-column-header-left'>\n <CollapseButton collapsed={collapsed} onToggle={board.readOnly ? onToggleCollapse : !readOnly && toggleCollapse ? () => toggleCollapse(slice.id, !collapsed) : undefined} />\n {!collapsed && leading}\n </div>\n\n {!collapsed && (\n <div className='event-modeling-grid-slice-column-header-center'>\n <GridTooltip content={<SliceTypeExplanation sliceType={slice.sliceType} />} position='bottom'>\n <EditableLabel\n value={slice.name}\n onChange={value => renamed?.(slice.id, value)}\n placeholder={board.messages.slices.namePlaceholder}\n style={nameStyle}\n readOnly={readOnly || !renamed}\n />\n </GridTooltip>\n {error && <EntityErrorIndicator error={error} />}\n </div>\n )}\n\n {!collapsed && (\n <div className='event-modeling-grid-slice-column-header-right'>\n {showStatuses && <SliceStatusPicker\n status={slice.status}\n onStatusChanged={statusChanged ? next => statusChanged(slice.id, next) : undefined}\n selectable={selectableStatuses}\n unselectableReason={unselectableStatusReason} />}\n {!board.readOnly && trailing}\n {!board.readOnly && headerActions.map(action => (\n <button\n key={action.tooltip}\n type='button'\n className='event-modeling-grid-add-button event-modeling-grid-add-button--small event-modeling-grid-add-button--no-circle'\n title={action.tooltip}\n aria-label={action.tooltip}\n disabled={readOnly || action.disabled}\n onClick={event => action.onActivate(slice.id, event.currentTarget.getBoundingClientRect())}\n >{action.icon}</button>\n ))}\n {!board.readOnly && sliceAdded && <SliceTypeMenu onSelect={sliceType => sliceAdded(slice.id, sliceType)} disabled={readOnly} />}\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The marker showing where a dragged slice would land.\nconst BASE = 'event-modeling-grid-slice-drop-indicator';\n\n// Names the drop marker for the drag in flight — the same marker in red when the slice cannot legally\n// land there, so the place being pointed at and the answer about it are the one thing being looked at.\n// isValid: Whether the slice may be dropped at this position.\n// Returns The class name for the drop marker.\nexport const dropIndicatorClassName = (isValid: boolean) => isValid ? BASE : `${BASE} ${BASE}--invalid`;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// What a press on a slice has turned out to be, once the pointer has moved.\nexport enum SliceDragGestureVerdict {\n // Not enough has happened yet to tell a click, a drag and a pan apart.\n pending = 'pending',\n\n // The slice is being picked up — start the reorder drag.\n commit = 'commit',\n\n // The gesture belongs to something else — let go of it entirely.\n abandon = 'abandon',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceDragGestureVerdict } from './SliceDragGestureVerdict';\n\n// How far a mouse or pen must travel before a press turns into a drag rather than a click.\nexport const DRAG_THRESHOLD = 4;\n\n// How long a finger must rest on a slice before it picks it up.\nexport const TOUCH_LONG_PRESS_MS = 450;\n\n// How far a finger may drift during the long press without the gesture being read as a pan. Generous\n// next to the mouse threshold because a finger held still on glass still wanders a few pixels.\nexport const TOUCH_LONG_PRESS_TOLERANCE = 10;\n\n// Reads what a press on a slice has become, from how far the pointer has travelled since it went down.\n//\n// The two input kinds answer opposite questions. A mouse has a button, so movement while it is held is\n// unambiguously a drag and commits as soon as it clears the click threshold. A finger has none: one\n// finger anywhere on the board pans it, so movement means the board is being panned, and the only way a\n// finger can mean \"pick this up\" is by staying put long enough for the caller's long-press timer to fire.\n// pointerType: The pointer type reported by the event (`mouse`, `pen` or `touch`).\n// deltaX: How far the pointer has travelled horizontally since it went down.\n// deltaY: How far the pointer has travelled vertically since it went down.\n// Returns What the gesture has turned out to be.\nexport function readSliceDragGesture(pointerType: string, deltaX: number, deltaY: number): SliceDragGestureVerdict {\n const travelledX = Math.abs(deltaX);\n const travelledY = Math.abs(deltaY);\n\n if (pointerType === 'touch') {\n return travelledX > TOUCH_LONG_PRESS_TOLERANCE || travelledY > TOUCH_LONG_PRESS_TOLERANCE\n ? SliceDragGestureVerdict.abandon\n : SliceDragGestureVerdict.pending;\n }\n\n return travelledX > DRAG_THRESHOLD || travelledY > DRAG_THRESHOLD\n ? SliceDragGestureVerdict.commit\n : SliceDragGestureVerdict.pending;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// Elements whose own gesture a press belongs to, so a drag must never start from one.\nexport const INTERACTIVE_SELECTOR = 'input, textarea, select, button, a, [role=\"button\"], [contenteditable=\"true\"], .p-dropdown, .p-checkbox';\n\n// The part of a pressed element a press reading looks at, so it can be exercised without a document.\nexport interface PressedElement {\n closest(selectors: string): unknown;\n}\n\n// What a pointer event carries that says where a press on a slice landed.\nexport interface SlicePressEvent {\n // The element the press landed on — a genuinely interactive one owns the press itself.\n target: PressedElement | null;\n clientX: number;\n clientY: number;\n pointerId: number;\n pointerType: string;\n // The top edge of the slice's surface, so a ghost keeps the offset the slice was grabbed at.\n elementTop: number;\n}\n\n// Where a press on a slice started, once it is known to be the slice's own to answer.\nexport interface SlicePress {\n startX: number;\n startY: number;\n grabOffsetY: number;\n pointerId: number;\n pointerType: string;\n}\n\n// Reads where a press on a slice's surface started, or that the slice has no business answering it.\n//\n// A slice is picked up from anywhere on it — its title and its cells included, which are editable labels\n// (Cratis/StudioIssues#237). Only genuinely interactive elements keep their own gesture.\n//\n// Reading a press deliberately decides nothing about the pointer it arrived on: a press is still only a\n// press, and it may yet turn out to be the double click that opens a label for editing. Claiming the\n// pointer here would retarget that click at the slice and the label would never see it, so the pointer\n// is taken only once the gesture has proven itself a drag.\n// event: Where the press landed and what pressed.\n// disabled: Whether the slice can be dragged at all — a collapsed column cannot.\n// Returns Where the press started, or `null` when the press is not the slice's to answer.\nexport function readSlicePress(event: SlicePressEvent, disabled: boolean): SlicePress | null {\n if (disabled) return null;\n if (event.target?.closest(INTERACTIVE_SELECTOR)) return null;\n\n return {\n startX: event.clientX,\n startY: event.clientY,\n grabOffsetY: event.clientY - event.elementTop,\n pointerId: event.pointerId,\n pointerType: event.pointerType,\n };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceDragGhost.css';\nimport { useEffect, useRef } from 'react';\nimport { createPortal } from 'react-dom';\nimport type { SliceDragState } from './useSliceDrag';\n\n// Just enough tilt that the copy under the pointer reads as lifted off the board rather than as a second\n// slice sitting on it.\nconst ghostTiltDegrees = 3;\n\nexport interface SliceDragGhostProps {\n drag?: SliceDragState;\n // The height of the labelled stand-in drawn when the slice could not be copied.\n headerHeight: number;\n}\n\n// The slice being dragged, drawn over everything at the pointer: dimmed and tilted, red with the reason\n// when the consumer's rule says it should not land where it is.\nexport const SliceDragGhost = ({ drag, headerHeight }: SliceDragGhostProps) =>\n drag ? createPortal(<SliceGhost drag={drag} headerHeight={headerHeight} />, document.body) : undefined;\n\nconst SliceGhost = ({ drag, headerHeight }: { drag: SliceDragState; headerHeight: number }) => {\n const isInvalid = !drag.isValid;\n const snapshotHost = useRef<HTMLDivElement | null>(null);\n const ghost = drag.ghost;\n\n // The snapshot is a detached DOM node rather than markup React owns, so it is placed by hand. Cloning\n // the live slice is what makes the thing under the pointer look like the slice being moved instead of\n // a label-sized stand-in; re-deriving that appearance in JSX would mean maintaining a second slice.\n useEffect(() => {\n const host = snapshotHost.current;\n if (!host || !ghost) return;\n host.replaceChildren(ghost);\n return () => host.replaceChildren();\n }, [ghost]);\n\n return (\n <div\n style={{\n position: 'fixed',\n left: drag.currentX - drag.ghostWidth / 2 * drag.zoom,\n top: drag.headerY,\n transform: `scale(${drag.zoom}) rotate(${ghostTiltDegrees}deg)`,\n transformOrigin: '0 0',\n pointerEvents: 'none',\n zIndex: 9998,\n userSelect: 'none',\n }}\n >\n {ghost\n ? (\n <div\n ref={snapshotHost}\n className={`event-modeling-grid-slice-ghost${isInvalid ? ' event-modeling-grid-slice-ghost--invalid' : ''}`}\n style={{ width: drag.ghostWidth }}\n />\n )\n : (\n <div\n className={`event-modeling-grid-slice-ghost-fallback${isInvalid ? ' event-modeling-grid-slice-ghost-fallback--invalid' : ''}`}\n style={{ width: drag.ghostWidth, height: headerHeight }}\n >\n {isInvalid && <i className='pi pi-ban' aria-hidden='true' />}\n <span>{drag.ghostLabel}</span>\n </div>\n )}\n {isInvalid && drag.invalidReason && (\n <div className='event-modeling-grid-slice-ghost-reason' style={{ maxWidth: drag.ghostWidth }}>\n {drag.invalidReason}\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { dropIndicatorClassName } from './dropIndicatorClassName';\n\nexport interface SliceDropIndicatorProps {\n isValid: boolean;\n marginLeft: number;\n}\n\n// The gap a dragged slice would drop into.\nexport const SliceDropIndicator = ({ isValid, marginLeft }: SliceDropIndicatorProps) => (\n <div className={dropIndicatorClassName(isValid)} style={{ marginLeft }} />\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React from 'react';\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface SliceDropTargetProps {\n moduleId: Guid;\n featureId: Guid;\n // Highlighted while a dragged slice is over it.\n active?: boolean;\n busy?: boolean;\n acceptsReorder?: boolean;\n acceptsMove?: boolean;\n style?: React.CSSProperties;\n className?: string;\n children?: React.ReactNode;\n}\n\n// Where the slices of one feature are laid out, and what a slice drag finds to drop into.\nexport const SliceDropTarget = ({ moduleId, featureId, active = false, busy = false, acceptsReorder = true, acceptsMove = true, style, className, children }: SliceDropTargetProps) => (\n <div\n data-slice-drop-target='true'\n data-slice-module-id={moduleId.toString()}\n data-slice-feature-id={featureId.toString()}\n data-slice-accepts-reorder={acceptsReorder}\n data-slice-accepts-move={acceptsMove}\n aria-busy={busy || undefined}\n className={[active && 'event-modeling-grid-slice-drop-target--active', className].filter(Boolean).join(' ') || undefined}\n style={style}\n >\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface SliceDropPosition {\n featureId: Guid;\n targetFeatureId: Guid;\n sourceIndex: number;\n dropIndex: number;\n}\n\n// Where a dropped slice ends up, or nothing when it was put back where it was. The drop index counts the\n// gaps between slices as they stand, so within a feature a slice dropped after itself lands one earlier.\nexport const sliceMove = (position: SliceDropPosition): { index: number } | undefined => {\n if (!position.targetFeatureId.equals(position.featureId)) return { index: position.dropIndex };\n const index = position.dropIndex > position.sourceIndex ? position.dropIndex - 1 : position.dropIndex;\n return index === position.sourceIndex ? undefined : { index };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport type { SliceDropVerdict } from './SliceDropVerdict';\nimport type { SliceMoved } from './SliceMoved';\nimport type { ValidateSliceDrop } from './ValidateSliceDrop';\nimport { sliceMove } from './sliceMove';\n\n// Minimal feature shape required for slice drag behavior.\nexport interface DraggableFeature {\n id: Guid;\n slices: ReadonlyArray<{ id: Guid }>;\n}\n\n// Internal drag state tracked during a slice reorder gesture.\nexport interface SliceDragState {\n sliceId: Guid;\n moduleId: Guid;\n featureId: Guid;\n targetFeatureId: Guid;\n sourceIndex: number;\n ghostLabel: string;\n ghostWidth: number;\n // A detached copy of the slice as it looked when it was picked up, rendered as the thing being moved.\n ghost: HTMLElement | null;\n currentX: number;\n currentY: number;\n dropIndex: number;\n headerY: number;\n zoom: number;\n // False when the consumer's rule says the slice should not land at the drop position, and why.\n isValid: boolean;\n invalidReason?: string;\n}\n\n// Encapsulates the pointer-driven slice reorder drag behavior for a single feature.\nexport function useSliceDrag(\n feature: DraggableFeature,\n moduleId: Guid,\n onSliceMoved?: SliceMoved,\n validateSliceDrop?: ValidateSliceDrop,\n) {\n const [sliceDrag, setSliceDrag] = useState<SliceDragState>();\n const sliceDragRef = useRef<SliceDragState | undefined>(undefined);\n sliceDragRef.current = sliceDrag;\n\n const validateDropRef = useRef<ValidateSliceDrop | undefined>(validateSliceDrop);\n validateDropRef.current = validateSliceDrop;\n const movedRef = useRef<SliceMoved | undefined>(onSliceMoved);\n movedRef.current = onSliceMoved;\n const { readOnly } = useBoard();\n\n // Validation advises where a slice may land; it must never take the gesture down with it. A\n // throwing validator once made every slice undraggable because the exception escaped the\n // pointer handler before the drag state was even set (Cratis/StudioIssues#237).\n const safeValidateDrop = useCallback((draggedSliceId: Guid, targetFeatureId: Guid, dropIndex: number): SliceDropVerdict | undefined => {\n try {\n return validateDropRef.current?.(draggedSliceId, targetFeatureId, dropIndex);\n } catch (error) {\n console.error('Slice drop validation failed — allowing the drop', error);\n return undefined;\n }\n }, []);\n\n const targetSupportsDrop = useCallback((moduleId: Guid, sourceFeatureId: Guid, targetFeatureId: Guid): boolean => {\n const target = document.querySelector<HTMLElement>(`[data-slice-drop-target=\"true\"][data-slice-module-id=\"${moduleId.toString()}\"][data-slice-feature-id=\"${targetFeatureId.toString()}\"]`);\n return targetFeatureId.equals(sourceFeatureId)\n ? target?.dataset.sliceAcceptsReorder === 'true' : target?.dataset.sliceAcceptsMove === 'true';\n }, []);\n\n const handleSliceDragStart = useCallback((sliceId: Guid, sliceName: string, clientX: number, clientY: number, columnWidth: number, headerY: number, zoom: number, ghost: HTMLElement | null = null) => {\n const sourceIndex = feature.slices.findIndex(s => s.id.equals(sliceId));\n if (sourceIndex === -1) return;\n const validation = safeValidateDrop(sliceId, feature.id, sourceIndex);\n setSliceDrag({\n sliceId,\n moduleId,\n featureId: feature.id,\n targetFeatureId: feature.id,\n sourceIndex,\n ghostLabel: sliceName,\n ghostWidth: columnWidth,\n ghost,\n currentX: clientX,\n currentY: clientY,\n dropIndex: sourceIndex,\n headerY,\n zoom,\n isValid: (validation?.isValid ?? true) && targetSupportsDrop(moduleId, feature.id, feature.id),\n invalidReason: validation?.reason,\n });\n }, [feature, moduleId, safeValidateDrop, targetSupportsDrop]);\n\n const computeDropFeatureId = useCallback((moduleId: Guid, clientX: number): Guid => {\n const targets = Array.from(\n document.querySelectorAll<HTMLElement>(`[data-slice-drop-target=\"true\"][data-slice-module-id=\"${moduleId.toString()}\"]`)\n );\n if (targets.length === 0) return feature.id;\n for (let index = 0; index < targets.length; index++) {\n const rect = targets[index].getBoundingClientRect();\n if (clientX < rect.left + rect.width / 2) {\n return Guid.parse(targets[index].dataset.sliceFeatureId!);\n }\n }\n return Guid.parse(targets[targets.length - 1].dataset.sliceFeatureId!);\n }, [feature.id]);\n\n const computeDropIndex = useCallback((featureId: Guid, clientX: number): number => {\n const cols = Array.from(\n document.querySelectorAll<HTMLElement>(`[data-slice-col=\"true\"][data-slice-feature-id=\"${featureId.toString()}\"]`)\n );\n if (cols.length === 0) return 0;\n for (let index = 0; index < cols.length; index++) {\n const rect = cols[index].getBoundingClientRect();\n if (clientX < rect.left + rect.width / 2) return index;\n }\n return cols.length;\n }, []);\n\n useEffect(() => {\n if (!sliceDrag) return;\n\n const handlePointerMove = (event: PointerEvent) => {\n const drag = sliceDragRef.current;\n if (!drag) return;\n const targetFeatureId = computeDropFeatureId(drag.moduleId, event.clientX);\n const dropIndex = computeDropIndex(targetFeatureId, event.clientX);\n const validation = safeValidateDrop(drag.sliceId, targetFeatureId, dropIndex);\n setSliceDrag(previous => previous ? {\n ...previous,\n currentX: event.clientX,\n currentY: event.clientY,\n targetFeatureId,\n dropIndex,\n isValid: (validation?.isValid ?? true) && targetSupportsDrop(drag.moduleId, drag.featureId, targetFeatureId),\n invalidReason: validation?.reason,\n } : undefined);\n };\n\n const handlePointerUp = () => {\n const drag = sliceDragRef.current;\n const move = drag && sliceMove(drag);\n if (drag && move && targetSupportsDrop(drag.moduleId, drag.featureId, drag.targetFeatureId)) movedRef.current?.(drag.sliceId, drag.featureId, drag.targetFeatureId, move.index);\n setSliceDrag(undefined);\n };\n\n // Capture phase, and on window: the slice that started the drag stops these events from bubbling\n // any further, so the canvas underneath does not pan through the same gesture on a touch device.\n // A bubble-phase listener here would be stopped along with it.\n window.addEventListener('pointermove', handlePointerMove, true);\n window.addEventListener('pointerup', handlePointerUp, true);\n window.addEventListener('pointercancel', handlePointerUp, true);\n return () => {\n window.removeEventListener('pointermove', handlePointerMove, true);\n window.removeEventListener('pointerup', handlePointerUp, true);\n window.removeEventListener('pointercancel', handlePointerUp, true);\n };\n }, [sliceDrag, computeDropFeatureId, computeDropIndex, safeValidateDrop, targetSupportsDrop]);\n\n // A slice can only be picked up on an editable board whose consumer is told where it went.\n return { sliceDrag, handleSliceDragStart: readOnly || !onSliceMoved ? undefined : handleSliceDragStart };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useEffect, useRef, useState } from 'react';\nimport type React from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { createSliceDragGhost } from './snapshotSlice';\nimport { readSliceDragGesture, TOUCH_LONG_PRESS_MS } from './readSliceDragGesture';\nimport { readSlicePress, type SlicePress } from './readSlicePress';\nimport { SliceDragGestureVerdict } from './SliceDragGestureVerdict';\n\n// Fired once a drag gesture is committed to, handing off to the reorder drag state machine.\nexport type SliceDragStartHandler = (\n sliceId: Guid,\n sliceName: string,\n clientX: number,\n clientY: number,\n columnWidth: number,\n headerY: number,\n zoom: number,\n ghost: HTMLElement | null,\n) => void;\n\n// A press the slice has taken on, and how far it has got towards becoming a drag.\ninterface DragIntent extends SlicePress {\n // The slice's surface the press landed on, which the ghost is snapshotted from.\n element: HTMLElement;\n // True once the gesture has been claimed, so moves stop reaching the canvas underneath.\n committed: boolean;\n}\n\n// Pointer handlers meant to be attached to a slice's outer surface to detect a reorder-drag gesture.\nexport interface SliceDragIntentHandlers {\n onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => void;\n onPointerMove: (event: React.PointerEvent<HTMLDivElement>) => void;\n onPointerUp: () => void;\n onContextMenu: (event: React.MouseEvent<HTMLDivElement>) => void;\n}\n\n// Decides whether a press on a slice is the start of a reorder drag, and hands off to `onSliceDragStart`\n// once it is.\n//\n// A slice is picked up from anywhere on its surface — its title and its cells included. Those are\n// editable labels, and excluding them left almost nothing of a slice to grab (Cratis/StudioIssues#237);\n// they open on a double click, which the movement threshold never mistakes for a drag. Only genuinely\n// interactive elements keep their own gesture.\n//\n// Mouse and pen keep the gesture away from the canvas on the press, so it cannot also start a pan, and\n// commit once the pointer leaves the click threshold. Touch cannot do that: one finger anywhere on the\n// board pans it, so claiming a touch on the press would make a board of slices impossible to scroll. A\n// finger has to rest on the slice instead — the long press is what separates \"move this\" from \"move the\n// board\" — and only when it fires does the gesture stop reaching the canvas underneath.\n//\n// Until a press has proven itself a drag it is watched from the window, and the pointer is captured only\n// once it has. Capturing on the press instead retargets every later event at the slice, and a browser\n// fires `click` — and therefore `dblclick` — at the common ancestor of where the pointer went down and\n// came up. A press that went down on a label came up on the captured slice, so the double click landed\n// on the slice and the label it started on never saw the gesture that opens it for renaming.\n// sliceId: The slice being pressed.\n// sliceName: The slice's name, shown on the ghost when it cannot be snapshotted.\n// columnWidth: The rendered width of the slice column.\n// disabled: Whether the slice can be dragged at all — a collapsed column cannot, nor one without an id.\n// onSliceDragStart: Called once the gesture is committed to.\n// Returns The pointer handlers to attach to the slice's outer surface.\nexport function useSliceDragIntent(\n sliceId: Guid | undefined,\n sliceName: string,\n columnWidth: number,\n disabled: boolean,\n onSliceDragStart?: SliceDragStartHandler,\n): SliceDragIntentHandlers {\n const [dragIntent, setDragIntent] = useState<DragIntent | null>(null);\n const longPressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const startDrag = useRef(onSliceDragStart);\n startDrag.current = onSliceDragStart;\n\n const cancelLongPress = () => {\n if (longPressTimer.current !== null) {\n clearTimeout(longPressTimer.current);\n longPressTimer.current = null;\n }\n };\n\n const begin = (intent: DragIntent, clientX: number, clientY: number) => {\n cancelLongPress();\n setDragIntent({ ...intent, committed: true });\n intent.element.setPointerCapture(intent.pointerId);\n if (!sliceId) return;\n startDrag.current?.(\n sliceId,\n sliceName,\n clientX,\n clientY,\n columnWidth,\n intent.startY - intent.grabOffsetY,\n zoomOf(intent.element),\n createSliceDragGhost(intent.element));\n };\n\n // A press that has not yet earned the slice is watched from the window rather than from the slice,\n // because the slice does not hold the pointer yet: a finger's moves are the canvas's until the long\n // press fires, and a mouse that leaves the column mid-gesture stops delivering moves here at all. The\n // window sees every move either way, so a fast drag out of a narrow header still picks the slice up\n // and a finger that swiped off it does not get the board yanked away when the timer goes off.\n useEffect(() => {\n if (!dragIntent || dragIntent.committed) return;\n\n const settle = (event: PointerEvent) => {\n if (event.pointerId !== dragIntent.pointerId) return;\n const verdict = readSliceDragGesture(\n dragIntent.pointerType,\n event.clientX - dragIntent.startX,\n event.clientY - dragIntent.startY);\n if (verdict === SliceDragGestureVerdict.abandon) setDragIntent(null);\n if (verdict === SliceDragGestureVerdict.commit) begin(dragIntent, event.clientX, event.clientY);\n };\n\n const release = (event: PointerEvent) => {\n if (event.pointerId === dragIntent.pointerId) setDragIntent(null);\n };\n\n window.addEventListener('pointermove', settle, true);\n window.addEventListener('pointerup', release, true);\n window.addEventListener('pointercancel', release, true);\n return () => {\n window.removeEventListener('pointermove', settle, true);\n window.removeEventListener('pointerup', release, true);\n window.removeEventListener('pointercancel', release, true);\n };\n }, [dragIntent]);\n\n // The pending press is what the timer belongs to: it is armed when one starts, and torn down with it\n // however it ends — committed, abandoned, or the slice unmounted mid-press.\n useEffect(() => {\n if (!dragIntent || dragIntent.committed || dragIntent.pointerType !== 'touch') return cancelLongPress;\n longPressTimer.current = setTimeout(\n () => begin(dragIntent, dragIntent.startX, dragIntent.startY),\n TOUCH_LONG_PRESS_MS);\n // Keyed on the press alone: `begin` is rebuilt every render but reads only what it is handed\n // and the latest handler ref, so re-arming the timer on an unrelated render would be wrong.\n return cancelLongPress;\n }, [dragIntent]);\n\n const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n const element = event.currentTarget;\n if (!sliceId) return;\n const press = readSlicePress({\n target: event.target instanceof Element ? event.target : null,\n clientX: event.clientX,\n clientY: event.clientY,\n pointerId: event.pointerId,\n pointerType: event.pointerType,\n elementTop: element.getBoundingClientRect().top,\n }, disabled);\n if (!press) return;\n\n setDragIntent({ ...press, element, committed: false });\n\n // A touch is deliberately not held off the canvas yet: until the long press fires this is still\n // the canvas's gesture, and swallowing it here is what used to make the board unpannable over a\n // slice. The pointer itself stays untaken for every kind of press until the gesture commits.\n if (event.pointerType === 'touch') return;\n\n event.stopPropagation();\n };\n\n // A pending press is settled from the window listener above, where every move reaches. By the time\n // moves arrive here the drag owns the gesture, so the canvas must not also pan through it — the drag\n // state machine listens in the capture phase, so it still sees every move this stops.\n const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n if (dragIntent?.committed) event.stopPropagation();\n };\n\n const onPointerUp = () => setDragIntent(null);\n\n // A long press on a touch device is also how a context menu is asked for. The slice answers the press\n // by picking itself up, so the menu would land on top of a drag already in flight.\n const onContextMenu = (event: React.MouseEvent<HTMLDivElement>) => {\n if (dragIntent?.committed) event.preventDefault();\n };\n\n return { onPointerDown, onPointerMove, onPointerUp, onContextMenu };\n}\n\n// Reads the board's current zoom off the nearest ancestor that scales, so the ghost matches the board.\nfunction zoomOf(element: HTMLElement): number {\n let current: HTMLElement | null = element.parentElement;\n while (current) {\n const scale = current.style.transform.match(/scale\\(([^)]+)\\)/);\n if (scale) return parseFloat(scale[1]);\n current = current.parentElement;\n }\n return 1;\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SliceColumnFrame.css';\nimport React from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceStatus } from '../Model';\nimport { sliceStatusName } from '../Statuses';\nimport { useSliceDragIntent, type SliceDragStartHandler } from '../SliceDragging';\nimport { useSlice } from './useSlice';\n\nexport interface SliceColumnFrameProps {\n featureId: Guid;\n name: string;\n status: SliceStatus;\n width: number;\n collapsed: boolean;\n // The slice is the one being dragged, so the column dims while its ghost follows the pointer.\n isDragging?: boolean;\n // Without it the slice cannot be picked up.\n onDragStart?: SliceDragStartHandler;\n ref?: React.Ref<HTMLDivElement>;\n onMouseEnter?: () => void;\n onMouseLeave?: () => void;\n onFocusCapture?: (event: React.FocusEvent<HTMLDivElement>) => void;\n onBlurCapture?: (event: React.FocusEvent<HTMLDivElement>) => void;\n children?: React.ReactNode;\n}\n\n// The dashed frame around one slice, tinted by its status, and what a slice drag picks up. A drag finds\n// the columns of a feature by the attributes it carries.\nexport const SliceColumnFrame = ({\n featureId,\n name,\n status,\n width,\n collapsed,\n isDragging = false,\n onDragStart,\n ref,\n onMouseEnter,\n onMouseLeave,\n onFocusCapture,\n onBlurCapture,\n children,\n}: SliceColumnFrameProps) => {\n const { sliceId } = useSlice();\n // A slice nobody is told about moving is not picked up at all, so a press on it pans the board instead.\n const drag = useSliceDragIntent(sliceId, name, width, collapsed || !onDragStart, onDragStart);\n\n return (\n <div\n ref={ref}\n data-slice-col='true'\n data-slice-feature-id={featureId.toString()}\n data-slice-id={sliceId?.toString()}\n className={`event-modeling-grid-slice-column event-modeling-grid-slice-column--${sliceStatusName(status)}${collapsed ? ' event-modeling-grid-slice-column--collapsed' : ''}`}\n style={{ width, cursor: collapsed || !onDragStart ? 'default' : 'grab', transition: 'opacity 0.15s', ...(isDragging ? { opacity: 0.35 } : {}) }}\n onMouseEnter={onMouseEnter}\n onMouseLeave={onMouseLeave}\n onFocusCapture={onFocusCapture}\n onBlurCapture={onBlurCapture}\n onPointerDown={drag.onPointerDown}\n onPointerMove={drag.onPointerMove}\n onPointerUp={drag.onPointerUp}\n onPointerCancel={drag.onPointerUp}\n onContextMenu={drag.onContextMenu}\n >\n {children}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useEffect, useRef, useState, type FocusEvent, type ReactNode } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { SliceHeaderSlice } from './SliceHeaderSlice';\nimport { useBoard } from '../Board';\nimport { sliceColumnWidth } from '../Layout';\nimport { useConnectionHighlight, useSliceConnection } from '../Connections';\nimport { useInViewport } from '../Viewport';\nimport type { SliceDragStartHandler } from '../SliceDragging';\nimport { SliceProvider } from './SliceProvider';\nimport { SliceColumnFrame } from './SliceColumnFrame';\nimport { SliceHeader } from './SliceHeader';\n\nexport interface SliceColumnProps {\n featureId: Guid;\n slice: SliceHeaderSlice;\n eventCount: number;\n collapsed: boolean;\n isDragging?: boolean;\n onSliceDragStart?: SliceDragStartHandler;\n header?: ReactNode;\n headerHeight?: number;\n body: ReactNode | ((inView: boolean) => ReactNode);\n specifications?: ReactNode | ((inView: boolean, width: number) => ReactNode);\n collapsedWidth: number;\n}\n\n// The frame, highlight and viewport lifetime of one contract slice. The consumer supplies the content\n// until the slices area moves into the package; off-screen bodies can render a sized placeholder.\nexport const SliceColumn = ({ featureId, slice, eventCount, collapsed, isDragging = false, onSliceDragStart, header, headerHeight = 44, body, specifications, collapsedWidth }: SliceColumnProps) => {\n const { readOnly } = useBoard();\n const connection = useSliceConnection(slice.id.toString());\n const { ref: highlightRef, onMouseEnter: applyHighlight, onMouseLeave: clearHighlight } = useConnectionHighlight(connection?.connectedSliceIds);\n const columnRef = useRef<HTMLDivElement>(null);\n const inView = useInViewport(columnRef);\n const [isEditing, setIsEditing] = useState(false);\n const isHoveredRef = useRef(false);\n const specificationsWidth = sliceColumnWidth({ sliceType: slice.sliceType, eventCount });\n\n const handleMouseEnter = () => {\n isHoveredRef.current = true;\n applyHighlight();\n };\n const handleMouseLeave = () => {\n isHoveredRef.current = false;\n if (!isEditing) clearHighlight();\n };\n const handleBlurCapture = (event: FocusEvent<HTMLDivElement>) => {\n const next = event.relatedTarget;\n if (!(next instanceof Node) || !event.currentTarget.contains(next)) setIsEditing(false);\n };\n\n useEffect(() => {\n if (!isEditing && !isHoveredRef.current) clearHighlight();\n }, [isEditing, clearHighlight]);\n\n return (\n <SliceProvider sliceId={slice.id} sliceType={slice.sliceType} status={slice.status}>\n <div ref={columnRef} style={{ display: 'flex', flexDirection: 'column', alignItems: 'stretch', flexShrink: 0 }}>\n <SliceColumnFrame\n ref={highlightRef}\n featureId={featureId}\n name={slice.name}\n status={slice.status}\n width={collapsed ? collapsedWidth : specificationsWidth}\n collapsed={collapsed}\n isDragging={isDragging}\n onDragStart={readOnly ? undefined : onSliceDragStart}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onFocusCapture={() => setIsEditing(true)}\n onBlurCapture={handleBlurCapture}\n >\n {header ?? <SliceHeader slice={slice} height={headerHeight} collapsed={collapsed} />}\n {typeof body === 'function' ? body(inView) : inView && body}\n </SliceColumnFrame>\n {typeof specifications === 'function' ? specifications(inView, specificationsWidth) : inView && specifications}\n </div>\n </SliceProvider>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Guid } from '@cratis/fundamentals';\nimport { SliceStatus, SliceType, type Slice } from '../Model';\nimport type { SliceNames } from './SliceNames';\n\n// A slice is displayed before persistence returns its real id. The Studio adapter converts this\n// contract value to the shape its editor kits need; no server or generated type reaches the board.\nexport const createOptimisticSlice = (sliceType: SliceType, names?: SliceNames): Slice => {\n const commandId = Guid.create();\n const eventId = Guid.create();\n const readModelId = Guid.create();\n return {\n id: Guid.create(),\n name: names?.name?.trim() || (sliceType === SliceType.stateChange ? 'State Change' :\n sliceType === SliceType.stateView ? 'State View' : sliceType === SliceType.automation ? 'Automation' : 'Translator'),\n sliceType, description: '', status: SliceStatus.notStarted, collapsed: false, sortOrder: Number.MAX_SAFE_INTEGER,\n command: sliceType === SliceType.stateView ? undefined : {\n id: commandId, name: names?.commandName?.trim() || 'Command', schema: {}, stateSchema: {}, rules: [], logicDescription: '',\n },\n readModel: sliceType === SliceType.stateView ? {\n id: readModelId, name: names?.readModelName?.trim() || 'Read Model', schema: {}, materializes: true,\n } : undefined,\n events: sliceType === SliceType.stateChange ? [{ id: eventId, name: names?.eventName?.trim() || 'Event', schema: {}, sourceEventId: '' }] : [],\n externalEvents: [], actors: [], queries: [], specifications: [], commentCount: 0,\n };\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { Guid } from '@cratis/fundamentals';\n\nexport interface SliceAreaItem {\n id: Guid;\n name: string;\n collapsed: boolean;\n}\n\ninterface PendingAddition<T> {\n slice: T;\n afterSliceId?: Guid;\n confirmed: boolean;\n}\n\ninterface PendingMove<T> {\n slice: T;\n index: number;\n confirmed: boolean;\n}\n\nexport interface SliceAreaState<T extends SliceAreaItem> {\n slices: T[];\n snapshot: T[];\n additions: PendingAddition<T>[];\n outgoing: PendingMove<T>[];\n incoming: PendingMove<T>[];\n order?: { ids: Guid[]; confirmed: boolean };\n}\n\nconst matches = (first: Guid, second: Guid) => first.equals(second);\nconst contains = <T extends SliceAreaItem>(slices: T[], id: Guid) => slices.some(slice => matches(slice.id, id));\n\nexport const createSliceAreaState = <T extends SliceAreaItem>(slices: T[]): SliceAreaState<T> =>\n ({ slices, snapshot: slices, additions: [], outgoing: [], incoming: [] });\n\nexport const insertSlice = <T extends SliceAreaItem>(slices: T[], slice: T, afterSliceId?: Guid): T[] => {\n if (!afterSliceId) return [...slices, slice];\n const index = slices.findIndex(existing => existing.id.equals(afterSliceId));\n if (index < 0) return [...slices, slice];\n const next = [...slices];\n next.splice(index + 1, 0, slice);\n return next;\n};\n\nexport const settleAddedSlice = <T extends SliceAreaItem>(slices: T[], temporaryId: Guid, persistedId?: Guid): T[] =>\n persistedId\n ? slices.map(slice => slice.id.equals(temporaryId) ? { ...slice, id: persistedId } : slice)\n : slices.filter(slice => !slice.id.equals(temporaryId));\n\nexport const addPendingSlice = <T extends SliceAreaItem>(state: SliceAreaState<T>, slice: T, afterSliceId?: Guid): SliceAreaState<T> => ({\n ...state, slices: insertSlice(state.slices, slice, afterSliceId),\n additions: [...state.additions, { slice, afterSliceId, confirmed: false }],\n});\n\nexport const addProjectedSlice = <T extends SliceAreaItem>(state: SliceAreaState<T>, slice: T, afterSliceId?: Guid): SliceAreaState<T> =>\n contains(state.slices, slice.id) ? state : {\n ...state, slices: insertSlice(state.slices, slice, afterSliceId),\n additions: [...state.additions, { slice, afterSliceId, confirmed: true }],\n };\n\nexport const completeAddedSlice = <T extends SliceAreaItem>(state: SliceAreaState<T>, temporaryId: Guid, persistedId?: Guid): SliceAreaState<T> => {\n const next = {\n ...state,\n slices: settleAddedSlice(state.slices, temporaryId, persistedId),\n additions: persistedId\n ? state.additions.map(addition => matches(addition.slice.id, temporaryId)\n ? { ...addition, slice: { ...addition.slice, id: persistedId }, confirmed: true } : addition)\n : state.additions.filter(addition => !matches(addition.slice.id, temporaryId)),\n order: state.order && persistedId ? {\n ...state.order, ids: state.order.ids.map(id => matches(id, temporaryId) ? persistedId : id),\n } : state.order,\n };\n return persistedId ? reconcileSliceSnapshot(next, state.snapshot) : next;\n};\n\nexport const moveSliceInArea = <T extends SliceAreaItem>(slices: T[], fromIndex: number, toIndex: number): T[] => {\n if (!Number.isInteger(fromIndex) || fromIndex < 0 || fromIndex >= slices.length) return slices;\n const requestedIndex = Number.isInteger(toIndex) ? toIndex : fromIndex;\n const targetIndex = Math.min(Math.max(requestedIndex, 0), slices.length - 1);\n if (fromIndex === targetIndex) return slices;\n const next = [...slices];\n next.splice(targetIndex, 0, ...next.splice(fromIndex, 1));\n return next;\n};\n\nexport const reorderPendingSlices = <T extends SliceAreaItem>(state: SliceAreaState<T>, fromIndex: number, toIndex: number): SliceAreaState<T> => {\n const slices = moveSliceInArea(state.slices, fromIndex, toIndex);\n return slices === state.slices ? state : { ...state, slices, order: { ids: slices.map(slice => slice.id), confirmed: false } };\n};\n\nexport const completeReorder = <T extends SliceAreaItem>(state: SliceAreaState<T>, succeeded: boolean): SliceAreaState<T> =>\n succeeded ? reconcileSliceSnapshot({ ...state, order: state.order && { ...state.order, confirmed: true } }, state.snapshot)\n : reconcileSliceSnapshot({ ...state, order: undefined }, state.snapshot);\n\nexport const movePendingSliceOut = <T extends SliceAreaItem>(state: SliceAreaState<T>, id: Guid): SliceAreaState<T> => {\n const index = state.slices.findIndex(slice => matches(slice.id, id));\n if (index < 0) return state;\n return { ...state, slices: state.slices.filter(slice => !matches(slice.id, id)),\n outgoing: [...state.outgoing, { slice: state.slices[index], index, confirmed: false }] };\n};\n\nexport const completeMoveOut = <T extends SliceAreaItem>(state: SliceAreaState<T>, id: Guid, succeeded: boolean): SliceAreaState<T> => {\n const move = state.outgoing.find(entry => matches(entry.slice.id, id));\n if (!move) return state;\n const next = { ...state,\n slices: succeeded ? state.slices : insertAt(state.slices, move.slice, move.index),\n outgoing: succeeded ? state.outgoing.map(entry => matches(entry.slice.id, id) ? { ...entry, confirmed: true } : entry)\n : state.outgoing.filter(entry => !matches(entry.slice.id, id)),\n };\n return succeeded ? reconcileSliceSnapshot(next, state.snapshot) : next;\n};\n\nconst insertAt = <T extends SliceAreaItem>(slices: T[], slice: T, index: number): T[] => {\n if (contains(slices, slice.id)) return slices;\n const next = [...slices];\n next.splice(Math.min(Math.max(index, 0), next.length), 0, slice);\n return next;\n};\n\nexport const movePendingSliceIn = <T extends SliceAreaItem>(state: SliceAreaState<T>, slice: T, index: number): SliceAreaState<T> => {\n if (contains(state.slices, slice.id) || state.incoming.some(entry => matches(entry.slice.id, slice.id))) return state;\n return { ...state, slices: insertAt(state.slices, slice, index),\n incoming: [...state.incoming, { slice, index, confirmed: false }] };\n};\n\nexport const completeMoveIn = <T extends SliceAreaItem>(state: SliceAreaState<T>, id: Guid, succeeded: boolean): SliceAreaState<T> => {\n if (!state.incoming.some(entry => matches(entry.slice.id, id))) return state;\n const next = {\n ...state,\n slices: succeeded ? state.slices : state.slices.filter(slice => !matches(slice.id, id)),\n incoming: succeeded ? state.incoming.map(entry => matches(entry.slice.id, id) ? { ...entry, confirmed: true } : entry)\n : state.incoming.filter(entry => !matches(entry.slice.id, id)),\n };\n return succeeded ? reconcileSliceSnapshot(next, state.snapshot) : next;\n};\n\nexport const reconcileSliceSnapshot = <T extends SliceAreaItem>(state: SliceAreaState<T>, snapshot: T[]): SliceAreaState<T> => {\n const additions = state.additions.filter(entry => !entry.confirmed || !contains(snapshot, entry.slice.id));\n const outgoing = state.outgoing.filter(entry => !entry.confirmed || contains(snapshot, entry.slice.id));\n const incoming = state.incoming.filter(entry => !entry.confirmed || !contains(snapshot, entry.slice.id));\n const orderedIds = state.order?.ids.filter(id => contains(snapshot, id));\n const projectedIds = snapshot.filter(slice => orderedIds?.some(id => matches(id, slice.id))).map(slice => slice.id);\n const orderCaughtUp = orderedIds !== undefined && orderedIds.length > 0\n && orderedIds.every((id, index) => matches(id, projectedIds[index]));\n const order = state.order?.confirmed && orderCaughtUp ? undefined : state.order;\n const current = (id: Guid, fallback: T) => state.slices.find(slice => matches(slice.id, id)) ?? fallback;\n const visible = snapshot.filter(slice => !outgoing.some(entry => matches(entry.slice.id, slice.id)))\n .map(slice => state.additions.some(entry => matches(entry.slice.id, slice.id)) || state.incoming.some(entry => matches(entry.slice.id, slice.id))\n ? current(slice.id, slice) : slice);\n const withIncoming = incoming.reduce((slices, entry) => insertAt(slices, current(entry.slice.id, entry.slice), entry.index), visible);\n const withAdditions = additions.reduce((slices, entry) => contains(slices, entry.slice.id) ? slices\n : insertSlice(slices, current(entry.slice.id, entry.slice), entry.afterSliceId), withIncoming);\n const slices = order ? reorderByIds(withAdditions, order.ids) : withAdditions;\n return { slices, snapshot, additions, outgoing, incoming, order };\n};\n\nconst reorderByIds = <T extends SliceAreaItem>(slices: T[], ids: Guid[]): T[] => {\n const ordered = ids.map(id => slices.find(slice => matches(slice.id, id))).filter((slice): slice is T => slice !== undefined);\n let position = 0;\n return slices.map(slice => ids.some(id => matches(id, slice.id)) ? ordered[position++] : slice);\n};\n\nexport const duplicateSliceName = (names: string[], original: string): string => {\n const baseName = original.replace(/\\s*\\(\\d+\\)$/, '').trimEnd();\n const pattern = new RegExp(`^${baseName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\s+\\\\((\\\\d+)\\\\)$`);\n const used = new Set(names.map(name => pattern.exec(name)).filter(match => match !== null).map(match => Number(match[1])));\n const number = Array.from({ length: used.size + 1 }, (_, index) => index + 1).find(candidate => !used.has(candidate));\n return `${baseName} (${number})`;\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SlicesArea.css';\nimport { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, type ReactNode, type Ref } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../Board';\nimport { boardMetrics } from '../Layout';\nimport { SliceDragGhost, SliceDropIndicator, SliceDropTarget, useSliceDrag, type ValidateSliceDrop } from '../SliceDragging';\nimport type { Slice, SliceType } from '../Model';\nimport { createOptimisticSlice } from './createOptimisticSlice';\nimport type { SliceNames } from './SliceNames';\nimport { addPendingSlice, addProjectedSlice, completeAddedSlice, completeMoveIn, completeMoveOut, completeReorder, createSliceAreaState, movePendingSliceIn, movePendingSliceOut, reconcileSliceSnapshot, reorderPendingSlices, type SliceAreaItem, type SliceAreaState } from './sliceAreaState';\n\nexport interface SlicesAreaHandle<T extends SliceAreaItem> {\n addSlice: (sliceType: SliceType, afterSliceId?: Guid, names?: SliceNames) => void;\n updateSlices: (update: (previous: T[]) => T[]) => void;\n addProjectedSlice: (slice: T, afterSliceId?: Guid) => void;\n moveIn: (slice: T, index: number) => void;\n completeMoveIn: (id: Guid, succeeded: boolean) => void;\n moveOut: (id: Guid) => boolean;\n completeMoveOut: (id: Guid, succeeded: boolean) => void;\n}\n\nexport interface SlicesAreaProps<T extends SliceAreaItem> {\n initialSlices: T[];\n ref?: Ref<SlicesAreaHandle<T>>;\n moduleId: Guid;\n featureId: Guid;\n featureCollapsed: boolean;\n hideEmptyPlaceholder?: boolean;\n onSlicesChanged?: (slices: T[]) => void;\n createSlice: (slice: Slice) => T;\n onAddSlice?: (slice: T, afterSliceId?: Guid) => Promise<Guid | undefined>;\n onReorderSlices?: (sliceIds: Guid[]) => Promise<boolean>;\n onMoveSlice?: (slice: T, targetFeatureId: Guid, targetIndex: number) => Promise<boolean>;\n validateSliceDrop?: ValidateSliceDrop;\n renderSlice: (slice: T, options: {\n collapsed: boolean;\n sliceCollapsed: boolean;\n isDragging: boolean;\n onSliceDragStart: ReturnType<typeof useSliceDrag>['handleSliceDragStart'];\n addSlice: SlicesAreaHandle<T>['addSlice'];\n updateSlices: SlicesAreaHandle<T>['updateSlices'];\n }) => ReactNode;\n}\n\n// The feature's slice row owns the optimistic list and drag geometry. Persistence and the Studio-specific\n// content of each column are supplied by the consumer until the feature level moves into the board.\nexport function SlicesArea<T extends SliceAreaItem>({\n ref, initialSlices, moduleId, featureId, featureCollapsed, hideEmptyPlaceholder = false,\n onSlicesChanged, createSlice, onAddSlice, onReorderSlices, onMoveSlice, validateSliceDrop, renderSlice,\n}: SlicesAreaProps<T>) {\n const { readOnly, messages } = useBoard();\n const stateRef = useRef<SliceAreaState<T>>(createSliceAreaState(initialSlices));\n const lastReportedSlices = useRef<T[] | undefined>(undefined);\n const [state, setState] = useState(stateRef.current);\n const { slices } = state;\n const addingRef = useRef(false);\n const [adding, setAdding] = useState(false);\n const apply = useCallback((transition: (previous: SliceAreaState<T>) => SliceAreaState<T>) => {\n const previous = stateRef.current;\n const next = transition(previous);\n if (next === previous) return;\n stateRef.current = next;\n setState(next);\n if (next.slices !== previous.slices) {\n lastReportedSlices.current = next.slices;\n onSlicesChanged?.(next.slices);\n }\n }, [onSlicesChanged]);\n useEffect(() => {\n if (initialSlices === lastReportedSlices.current || initialSlices === stateRef.current.snapshot) return;\n apply(previous => {\n if (!previous.additions.length && !previous.incoming.length && !previous.outgoing.length && !previous.order\n && previous.slices.length === initialSlices.length\n && previous.slices.every((slice, index) => slice === initialSlices[index])) {\n return { ...previous, snapshot: initialSlices };\n }\n return reconcileSliceSnapshot(previous, initialSlices);\n });\n }, [initialSlices, apply]);\n\n const updateSlices = useCallback((update: (previous: T[]) => T[]) => {\n apply(previous => {\n const slices = update(previous.slices);\n return slices === previous.slices ? previous : { ...previous, slices };\n });\n }, [apply]);\n const addProjected = useCallback((slice: T, afterSliceId?: Guid) => apply(previous => addProjectedSlice(previous, slice, afterSliceId)), [apply]);\n const moveIn = useCallback((slice: T, index: number) => apply(previous => movePendingSliceIn(previous, slice, index)), [apply]);\n const completeIncoming = useCallback((id: Guid, succeeded: boolean) => apply(previous => completeMoveIn(previous, id, succeeded)), [apply]);\n const moveOut = useCallback((id: Guid): boolean => {\n if ([...stateRef.current.additions, ...stateRef.current.incoming].some(entry => entry.slice.id.equals(id))\n || !stateRef.current.slices.some(slice => slice.id.equals(id))) return false;\n apply(previous => movePendingSliceOut(previous, id));\n return true;\n }, [apply]);\n const completeOutgoing = useCallback((id: Guid, succeeded: boolean) => apply(previous => completeMoveOut(previous, id, succeeded)), [apply]);\n\n const addSlice = useCallback((sliceType: SliceType, afterSliceId?: Guid, names?: SliceNames) => {\n if (readOnly || !onAddSlice || addingRef.current) return;\n addingRef.current = true;\n setAdding(true);\n const slice = createSlice(createOptimisticSlice(sliceType, names));\n apply(previous => addPendingSlice(previous, slice, afterSliceId));\n void Promise.resolve().then(() => onAddSlice(slice, afterSliceId)).then(realId => {\n apply(previous => completeAddedSlice(previous, slice.id, realId));\n }).catch(() => apply(previous => completeAddedSlice(previous, slice.id)))\n .finally(() => { addingRef.current = false; setAdding(false); });\n }, [readOnly, createSlice, onAddSlice, apply]);\n\n useImperativeHandle(ref, () => ({ addSlice, updateSlices, addProjectedSlice: addProjected, moveIn, completeMoveIn: completeIncoming, moveOut, completeMoveOut: completeOutgoing }),\n [addSlice, updateSlices, addProjected, moveIn, completeIncoming, moveOut, completeOutgoing]);\n\n const feature = useMemo(() => ({ id: featureId, slices }), [featureId, slices]);\n const handleMoved = useCallback((sliceId: Guid, sourceFeatureId: Guid, targetFeatureId: Guid, targetIndex: number) => {\n if (readOnly || !sourceFeatureId.equals(featureId)) return;\n const sourceIndex = stateRef.current.slices.findIndex(slice => slice.id.equals(sliceId));\n if (sourceIndex < 0 || [...stateRef.current.additions, ...stateRef.current.incoming].some(entry => entry.slice.id.equals(sliceId))) return;\n if (targetFeatureId.equals(featureId)) {\n if (!onReorderSlices || (stateRef.current.order && !stateRef.current.order.confirmed)) return;\n const next = reorderPendingSlices(stateRef.current, sourceIndex, targetIndex);\n if (next === stateRef.current) return;\n apply(() => next);\n void Promise.resolve().then(() => onReorderSlices(next.slices.map(slice => slice.id)))\n .then(succeeded => apply(previous => completeReorder(previous, succeeded)))\n .catch(() => apply(previous => completeReorder(previous, false)));\n } else if (onMoveSlice) {\n const slice = stateRef.current.slices[sourceIndex];\n if (!moveOut(sliceId)) return;\n void Promise.resolve().then(() => onMoveSlice(slice, targetFeatureId, targetIndex))\n .then(succeeded => completeOutgoing(sliceId, succeeded))\n .catch(() => completeOutgoing(sliceId, false));\n }\n }, [readOnly, featureId, onReorderSlices, onMoveSlice, apply, moveOut, completeOutgoing]);\n const { sliceDrag, handleSliceDragStart } = useSliceDrag(feature, moduleId,\n onReorderSlices || onMoveSlice ? handleMoved : undefined, validateSliceDrop);\n\n if (!slices.length) {\n if (featureCollapsed) return null;\n if (hideEmptyPlaceholder) return <SliceDropTarget moduleId={moduleId} featureId={featureId} acceptsReorder={!readOnly && !!onReorderSlices} acceptsMove={!readOnly && !!onMoveSlice} style={{ width: 0, flexShrink: 0 }} />;\n return (\n <SliceDropTarget moduleId={moduleId} featureId={featureId} busy={adding} acceptsReorder={!readOnly && !!onReorderSlices} acceptsMove={!readOnly && !!onMoveSlice} className='event-modeling-slices-empty' style={{ width: Math.round(boardMetrics.sliceWidth * 1.5) }}>\n {messages.slices.empty}\n </SliceDropTarget>\n );\n }\n\n return (\n <>\n <SliceDragGhost drag={sliceDrag} headerHeight={boardMetrics.headerHeight} />\n <SliceDropTarget moduleId={moduleId} featureId={featureId} busy={adding} acceptsReorder={!readOnly && !!onReorderSlices} acceptsMove={!readOnly && !!onMoveSlice} active={sliceDrag?.targetFeatureId.equals(featureId)} style={{ display: 'flex', flexDirection: 'row', alignItems: 'flex-start' }}>\n {slices.flatMap((slice, index) => {\n const isDraggingThisFeature = sliceDrag?.targetFeatureId.equals(featureId) ?? false;\n const marginLeft = index === 0 ? 0 : boardMetrics.sliceGap;\n const elements: ReactNode[] = [];\n if (isDraggingThisFeature && sliceDrag?.dropIndex === index) elements.push(\n <SliceDropIndicator key={`drop-${index}`} isValid={sliceDrag.isValid} marginLeft={marginLeft > 0 ? Math.max(marginLeft - 6, 0) : 0} />);\n const sliceCollapsed = slice.collapsed;\n elements.push(\n <div key={slice.id.toString()} style={{ marginLeft: isDraggingThisFeature && sliceDrag?.dropIndex === index ? 2 : marginLeft }}>\n {renderSlice(slice, { collapsed: featureCollapsed || sliceCollapsed, sliceCollapsed,\n isDragging: sliceDrag?.sliceId.equals(slice.id) ?? false,\n onSliceDragStart: [...state.additions, ...state.incoming].some(entry => entry.slice.id.equals(slice.id)) ? undefined : handleSliceDragStart,\n addSlice, updateSlices })}\n </div>);\n if (isDraggingThisFeature && index === slices.length - 1 && sliceDrag?.dropIndex === slices.length) elements.push(\n <SliceDropIndicator key='drop-end' isValid={sliceDrag.isValid} marginLeft={2} />);\n return elements;\n })}\n </SliceDropTarget>\n </>\n );\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/SliceCell.css';\nimport { Fragment, type ReactNode } from 'react';\nimport type { ActorType, SliceType } from '../Model';\nimport { cellConnectors, type CellConnectors } from '../Connections';\nimport { actorsForRow, sliceTypeSupportsRow } from '../Layout';\nimport { RowType } from '../Rows/RowType';\n\n// What a row's cell is drawn with.\nexport interface SliceRowCell<TActor> {\n rowType: RowType;\n conn: CellConnectors;\n rowHeight: number;\n // The actor the cell belongs to; undefined for a row that holds no actors, or an actor row that has none yet.\n actor?: TActor;\n}\n\nexport interface SliceRowsProps<TActor extends { id: { toString(): string }; actorType: ActorType }> {\n sliceType: SliceType;\n contentRows: readonly RowType[];\n rowHeights: Readonly<Record<RowType, number>>;\n // The collection's actors; each actor row draws one cell per actor of its kind.\n actors: readonly TActor[];\n // Draws the cell of one row; the board decides which rows a slice draws, and how many cells each gets.\n renderCell: (cell: SliceRowCell<TActor>) => ReactNode;\n}\n\nconst emptyClass: Partial<Record<RowType, string>> = {\n [RowType.UI]: 'ui',\n [RowType.Chat]: 'chat',\n [RowType.System]: 'system',\n};\n\n// A slice's cells, one row after another. A row the slice type takes no part in keeps its height with an\n// empty cell, so the rows of every slice line up.\nexport const SliceRows = <TActor extends { id: { toString(): string }; actorType: ActorType }>({ sliceType, contentRows, rowHeights, actors, renderCell }: SliceRowsProps<TActor>) => (\n <>\n {contentRows.flatMap(rowType => {\n const conn = cellConnectors(rowType, sliceType, [...contentRows]);\n const rowHeight = rowHeights[rowType];\n const actorKind = emptyClass[rowType];\n\n if (actorKind === undefined) {\n return [<Fragment key={`row:${rowType}`}>{renderCell({ rowType, conn, rowHeight })}</Fragment>];\n }\n const rowActors = actorsForRow(actors, rowType);\n if (!sliceTypeSupportsRow(sliceType, rowType)) {\n return Array.from({ length: Math.max(1, rowActors.length) }, (_, index) =>\n <div key={`row:${actorKind}:${index}`} className={`event-modeling-grid-slice-cell event-modeling-grid-slice-cell--${actorKind}`} style={{ height: rowHeight }} />);\n }\n if (rowActors.length === 0) {\n return [<Fragment key={`row:${actorKind}`}>{renderCell({ rowType, conn, rowHeight })}</Fragment>];\n }\n return rowActors.map(actor => <Fragment key={`role:${actor.id.toString()}`}>{renderCell({ rowType, conn, rowHeight, actor })}</Fragment>);\n })}\n </>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './SlicePlaceholder.css';\nimport React from 'react';\nimport { SliceType } from '../Model';\nimport { commandCardColors, eventCardColors, readModelCardColors } from '../Cards/cardColors';\nimport { RowType } from '../Rows/RowType';\n\n// What a placeholder needs to know about the slice it stands in for.\nexport interface SlicePlaceholderSlice {\n sliceType: SliceType;\n // Whether the slice has a command, and whether it has a read model.\n hasCommand: boolean;\n hasReadModel: boolean;\n eventCount: number;\n}\n\nexport interface SlicePlaceholderProps {\n\n // The slice whose content the silhouettes stand in for.\n slice: SlicePlaceholderSlice;\n\n // The rows the column renders, in order.\n contentRows: readonly RowType[];\n\n // The height of each row, so the placeholder occupies exactly the real body's box.\n rowHeights: Readonly<Record<RowType, number>>;\n}\n\nconst SILHOUETTE_ALPHA = '38';\n\nfunction interactionColor(slice: SlicePlaceholderSlice): string | undefined {\n if (slice.sliceType === SliceType.stateChange && slice.hasCommand) return commandCardColors.background;\n if (slice.sliceType === SliceType.stateView && slice.hasReadModel) return readModelCardColors.background;\n return undefined;\n}\n\n// The off-screen stand-in for a slice column's virtualized body: one cell-shaped row per content\n// row, with faint card/chip silhouettes where the real body shows the command/read-model card and\n// event chips — so content scrolling toward the viewport reads as a soft preview of the real cards\n// rather than empty space, and the swap to the mounted body is a fade rather than a pop.\nexport const SlicePlaceholder: React.FC<SlicePlaceholderProps> = ({ slice, contentRows, rowHeights }) => (\n <>\n {contentRows.map(rowType => {\n const cardColor = rowType === RowType.Interaction ? interactionColor(slice) : undefined;\n const eventCount = rowType === RowType.Events ? Math.min(slice.eventCount, 3) : 0;\n\n return (\n <div\n key={rowType}\n className='event-modeling-grid-slice-cell event-modeling-grid-slice-placeholder-row'\n style={{ height: rowHeights[rowType] }}\n aria-hidden\n >\n {cardColor && (\n <span\n className='event-modeling-grid-slice-placeholder-card'\n style={{ background: `${cardColor}${SILHOUETTE_ALPHA}` }}\n />\n )}\n {eventCount > 0 && (\n <span className='event-modeling-grid-slice-placeholder-chips'>\n {Array.from({ length: eventCount }, (_, index) => (\n <span\n key={index}\n className='event-modeling-grid-slice-placeholder-chip'\n style={{ background: `${eventCardColors.background}${SILHOUETTE_ALPHA}` }}\n />\n ))}\n </span>\n )}\n </div>\n );\n })}\n </>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './AddButton.css';\nimport React, { useRef } from 'react';\nimport { GridTooltip } from '../Tooltips';\nimport { useSlice } from '../Slices';\nimport type { CellAction } from './CellAction';\n\nexport interface CellActionButtonProps {\n action: CellAction;\n}\n\nconst iconStyle: React.CSSProperties = { fontSize: 10 };\n\n// Draws nothing when the slice is read-only or outside a slice.\nexport const CellActionButton = ({ action }: CellActionButtonProps) => {\n const { readOnly, sliceId } = useSlice();\n const button = useRef<HTMLButtonElement>(null);\n if (readOnly || !sliceId) return undefined;\n\n return (\n <GridTooltip content={action.tooltip} position='top'>\n <button\n ref={button}\n type='button'\n className='event-modeling-grid-add-button--small'\n aria-label={action.tooltip}\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n action.onActivate(sliceId, button.current?.getBoundingClientRect() ?? new DOMRect());\n }}\n >\n {action.icon ? <i className={action.icon} style={iconStyle} /> : '+'}\n </button>\n </GridTooltip>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The bottom-right corner holds what adds to the cell; the top-right corner holds what acts on it.\nexport enum CellCornerPlacement {\n add = 'add',\n top = 'top',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './CellCorner.css';\nimport React from 'react';\nimport { CellCornerPlacement } from './CellCornerPlacement';\n\nexport interface CellCornerProps {\n placement: CellCornerPlacement;\n children?: React.ReactNode;\n}\n\nexport const CellCorner = ({ placement, children }: CellCornerProps) => (\n <div className={placement === CellCornerPlacement.add\n ? 'event-modeling-grid-slice-cell-add-corner'\n : 'event-modeling-grid-slice-cell-action-corner event-modeling-grid-slice-cell-action-corner--top'}>\n {children}\n </div>\n);\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useSlice } from '../Slices';\nimport type { CellAction } from './CellAction';\nimport { CellActionButton } from './CellActionButton';\nimport { CellCorner } from './CellCorner';\nimport type { CellCornerPlacement } from './CellCornerPlacement';\n\nexport interface CellCornerActionProps {\n placement: CellCornerPlacement;\n action: CellAction;\n}\n\n// A corner holding a single action; nothing at all is drawn when the slice is read-only.\nexport const CellCornerAction = ({ placement, action }: CellCornerActionProps) => {\n const { readOnly, sliceId } = useSlice();\n if (readOnly || !sliceId) return undefined;\n\n return (\n <CellCorner placement={placement}>\n <CellActionButton action={action} />\n </CellCorner>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { SliceType } from '../Model';\n\n// Only a State View references events other slices produce; every other slice type adds its own.\nexport const usesEventReferencePicker = (sliceType: SliceType): boolean =>\n sliceType === SliceType.stateView;\n\nexport const showsAddNewEventButton = (sliceType: SliceType): boolean =>\n !usesEventReferencePicker(sliceType);\n\n// While a State View has no events yet, referencing its first one is the row's only offer, so it is drawn\n// as a dashed card rather than a small button.\nexport const showsEventReferencePlaceholder = (sliceType: SliceType, eventCount: number): boolean =>\n usesEventReferencePicker(sliceType) && eventCount === 0;\n\n// A Translator's interaction row offers events from other modules to translate from.\nexport const showsExternalEventPicker = (sliceType: SliceType): boolean =>\n sliceType === SliceType.translator;\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { AutomationTriggerType } from '../../Model';\nimport type { EventModelMessages } from '../../Messages';\n\n// The PrimeIcons glyph each kind of trigger is drawn with; there is none for an automation without one.\nexport const triggerIcon = (type: AutomationTriggerType): string | undefined => {\n switch (type) {\n case AutomationTriggerType.timer: return 'pi pi-clock';\n case AutomationTriggerType.event: return 'pi pi-bolt';\n case AutomationTriggerType.custom: return 'pi pi-pencil';\n case AutomationTriggerType.none: return undefined;\n }\n};\n\nexport const triggerTitle = (type: AutomationTriggerType, messages: EventModelMessages): string => {\n switch (type) {\n case AutomationTriggerType.timer: return messages.triggers.timer;\n case AutomationTriggerType.event: return messages.triggers.event;\n case AutomationTriggerType.custom: return messages.triggers.custom;\n case AutomationTriggerType.none: return '';\n }\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// The kinds of trigger an automation can be given.\nexport enum TriggerKind {\n timer = 'timer',\n event = 'event',\n custom = 'custom',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './TriggerControl.css';\nimport { useRef, useState, type PointerEvent } from 'react';\nimport { AutomationTriggerType } from '../../Model';\nimport { useEventModelMessages } from '../../Messages';\nimport { useDismissOnOutsidePointer } from '../../Pickers/useDismissOnOutsidePointer';\nimport { TriggerKind } from './TriggerKind';\nimport { triggerIcon } from './triggerBadges';\n\nexport interface TriggerControlProps {\n // How the automation is set off now; none, or no value, when it has no trigger yet.\n triggerType?: AutomationTriggerType;\n onTriggerKindChosen: (kind: TriggerKind) => void;\n onTriggerOpened: () => void;\n}\n\nconst kinds = [TriggerKind.timer, TriggerKind.event, TriggerKind.custom] as const;\n\n// An automation's trigger in the corner of its system cell: a button for the trigger it has, which opens\n// it, or one that offers the kinds of trigger it can be given.\nexport const TriggerControl = ({ triggerType, onTriggerKindChosen, onTriggerOpened }: TriggerControlProps) => {\n const messages = useEventModelMessages();\n const [open, setOpen] = useState(false);\n const container = useRef<HTMLDivElement>(null);\n const elements = useRef([container]).current;\n useDismissOnOutsidePointer(elements, () => setOpen(false), open);\n const icon = triggerType === undefined ? undefined : triggerIcon(triggerType);\n const onPointerDown = (handle: () => void) => (event: PointerEvent) => {\n event.stopPropagation();\n handle();\n };\n\n if (icon) {\n return (\n <div className='system-row-cell__trigger-wrapper'>\n <button\n className='system-row-cell__trigger-btn system-row-cell__trigger-btn--active'\n title={messages.triggerControl.edit}\n onPointerDown={onPointerDown(onTriggerOpened)}\n >\n <i className={icon} />\n </button>\n </div>\n );\n }\n\n return (\n <div ref={container} className='system-row-cell__trigger-wrapper'>\n <button\n className='system-row-cell__trigger-btn'\n title={messages.triggerControl.add}\n onPointerDown={onPointerDown(() => setOpen(previous => !previous))}\n >\n <i className='pi pi-plus' />\n </button>\n {open && (\n <div className='system-row-cell__trigger-menu'>\n {kinds.map(kind => (\n <div\n key={kind}\n className='system-row-cell__trigger-menu-item'\n onPointerDown={onPointerDown(() => {\n setOpen(false);\n onTriggerKindChosen(kind);\n })}\n >\n <div className='system-row-cell__trigger-menu-item-title'>{messages.triggerControl.kinds[kind].title}</div>\n <div className='system-row-cell__trigger-menu-item-description'>{messages.triggerControl.kinds[kind].description}</div>\n </div>\n ))}\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport './SystemCell.css';\nimport React from 'react';\nimport { useBoard } from '../../Board';\nimport { type CellConnectors, ConnectorIncomingBottom, ConnectorIncomingTop, ConnectorOutgoingBottom, ConnectorOutgoingTop, FlowNodeActor, PassthroughConnector } from '../../Connections';\nimport { CogWheel } from '../../Icons';\nimport { type AutomationTriggerType, SliceType } from '../../Model';\nimport { useEventModelMessages } from '../../Messages';\nimport { useSlice } from '../../Slices';\nimport { TriggerControl } from './TriggerControl';\nimport { triggerIcon, triggerTitle } from './triggerBadges';\n\nexport interface SystemCellProps {\n sliceType: SliceType;\n // Whether the system acts in this slice; only then is the cogwheel drawn.\n isSystemSlice: boolean;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // How the automation is set off: a badge when the slice cannot be edited, and a button that opens it when\n // it can.\n triggerType?: AutomationTriggerType;\n}\n\nexport const SystemCell = ({ sliceType, isSystemSlice, collapsed = false, conn, rowHeight, triggerType }: SystemCellProps) => {\n const { readOnly, sliceId } = useSlice();\n const { onTriggerKindChosen, onTriggerOpened } = useBoard().editing;\n const messages = useEventModelMessages();\n const badge = triggerType === undefined ? undefined : triggerIcon(triggerType);\n const cellStyle: React.CSSProperties = { height: rowHeight };\n const isAutomation = isSystemSlice && sliceType === SliceType.automation;\n\n if (collapsed) {\n return (\n <div style={cellStyle} className='event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--system event-modeling-grid-slice-cell--collapsed'>\n {isSystemSlice && <CogWheel />}\n </div>\n );\n }\n\n return (\n <div\n style={cellStyle}\n data-card-id='system'\n data-slice-id={sliceId?.toString()}\n className='event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--system'\n >\n {conn.topOutgoing && <ConnectorOutgoingTop />}\n {conn.topIncoming && <ConnectorIncomingTop />}\n {/* An automation's interaction row below is split — read model on the left, command on the\n right — so the bottom connectors sit over those column centers for the fill lines to align. */}\n {sliceType === SliceType.automation\n ? <>\n {conn.bottomIncoming && <ConnectorIncomingBottom columnPosition='left' />}\n {conn.bottomOutgoing && <ConnectorOutgoingBottom columnPosition='right' />}\n </>\n : <>\n {conn.bottomOutgoing && <ConnectorOutgoingBottom />}\n {conn.bottomIncoming && <ConnectorIncomingBottom />}\n </>\n }\n {conn.passthrough && <PassthroughConnector />}\n {isSystemSlice && (\n sliceType === SliceType.automation\n ? <span data-flow-node={FlowNodeActor.cogwheel} className='system-row-cell__cogwheel'><CogWheel /></span>\n : <CogWheel />\n )}\n {isAutomation && !readOnly && sliceId && onTriggerKindChosen && onTriggerOpened && (\n <TriggerControl\n triggerType={triggerType}\n onTriggerKindChosen={kind => onTriggerKindChosen(sliceId, kind)}\n onTriggerOpened={() => onTriggerOpened(sliceId)}\n />\n )}\n {/* A board that cannot be edited still shows a configured trigger, as a badge rather than a button. */}\n {isAutomation && readOnly && triggerType !== undefined && badge && (\n <div className='system-row-cell__trigger-wrapper'>\n <span className='system-row-cell__trigger-btn system-row-cell__trigger-btn--active system-row-cell__trigger-btn--readonly' title={triggerTitle(triggerType, messages)}>\n <i className={badge} />\n </span>\n </div>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventModelMessages } from '../../Messages';\nimport type { MenuDropdownItem } from '../../Menus';\nimport type { PrototypeTemplate } from './PrototypeTemplate';\n\n// What the add button's menu does for each way of adding a UI prototype.\nexport interface AddPrototypeMenuActions {\n onFromScratch: () => void;\n onFromTemplate: (template: PrototypeTemplate) => void;\n}\n\n// The menu offered from the add button of an actor's UI cell: start from scratch, or from one of the\n// templates the consumer offers.\nexport const addPrototypeMenuItems = (\n templates: readonly PrototypeTemplate[],\n messages: EventModelMessages['prototypes'],\n actions: AddPrototypeMenuActions): MenuDropdownItem[] => [\n {\n id: 'from-scratch',\n label: messages.fromScratch,\n description: messages.fromScratchDescription,\n onClick: actions.onFromScratch,\n },\n {\n id: 'from-template',\n label: messages.fromTemplate,\n description: messages.fromTemplateDescription,\n items: templates.length > 0\n ? templates.map(template => ({\n id: template.id,\n label: template.name,\n onClick: () => actions.onFromTemplate(template),\n }))\n : [{\n id: 'no-templates',\n label: messages.noTemplates,\n }],\n },\n];\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useRef } from 'react';\nimport { useEventModelMessages } from '../../Messages';\nimport { MenuDropdown } from '../../Menus';\nimport { GridTooltip } from '../../Tooltips';\nimport { addPrototypeMenuItems } from './addPrototypeMenuItems';\nimport type { PrototypeTemplate } from './PrototypeTemplate';\n\nexport interface AddPrototypeButtonProps {\n templates: readonly PrototypeTemplate[];\n // Each receives the viewport rectangle of the button, so the editor can open from there.\n onFromScratch: (host: DOMRect) => void;\n onFromTemplate: (template: PrototypeTemplate, host: DOMRect) => void;\n}\n\n// The add button of an actor's UI cell: a menu offering to start a prototype from scratch or from a\n// template.\nexport const AddPrototypeButton = ({ templates, onFromScratch, onFromTemplate }: AddPrototypeButtonProps) => {\n const messages = useEventModelMessages().prototypes;\n const trigger = useRef<HTMLButtonElement>(null);\n const host = () => trigger.current?.getBoundingClientRect() ?? new DOMRect();\n const items = addPrototypeMenuItems(templates, messages, {\n onFromScratch: () => onFromScratch(host()),\n onFromTemplate: template => onFromTemplate(template, host()),\n });\n\n return (\n <GridTooltip content={messages.add} position='top'>\n <MenuDropdown\n align='right'\n items={items}\n trigger={\n <button ref={trigger} aria-label={messages.add} className='event-modeling-grid-add-button--small'>\n +\n </button>\n }\n />\n </GridTooltip>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport './UiCell.css';\nimport React, { useRef, useState } from 'react';\nimport { PrototypePreview, PrototypeThumbnail, useSceneMessages, type PrototypeLayout } from '@cratis/scene/Prototypes';\nimport type { UIElement, IComponent } from '@cratis/scene';\nimport { type CellConnectors, ConnectorIncomingBottom, ConnectorOutgoingBottom, FlowNodeActor } from '../../Connections';\nimport { useBoard } from '../../Board';\nimport { useSlice } from '../../Slices';\nimport { CellCorner } from '../CellCorner';\nimport { CellCornerPlacement } from '../CellCornerPlacement';\nimport { AddPrototypeButton } from './AddPrototypeButton';\n\nexport interface UiCellProps {\n // What the actor sees in this slice; the cell shows a thumbnail of it.\n elements: readonly (UIElement | IComponent)[];\n windowSize?: { width: number; height: number };\n layout?: PrototypeLayout;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // The actor whose prototype this is; opening and adding a prototype report it.\n actorId: string;\n}\n\nexport const UiCell = ({ elements, windowSize, layout, collapsed = false, conn, rowHeight, actorId }: UiCellProps) => {\n const { readOnly, sliceId } = useSlice();\n const { editing, actions, readOnly: boardReadOnly } = useBoard();\n const { onPrototypeOpened, onPrototypeAdded } = editing;\n const thumbnail = useRef<HTMLDivElement>(null);\n const [previewFrom, setPreviewFrom] = useState<DOMRect>();\n const messages = useSceneMessages().prototypeThumbnail;\n const cellStyle: React.CSSProperties = { height: rowHeight };\n const className = 'event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--ui';\n\n if (collapsed) return <div style={cellStyle} className={className} />;\n\n const hasContent = elements.length > 0;\n const opens = !readOnly && !!sliceId && !!onPrototypeOpened;\n // A board that cannot edit the prototype still lets it be looked at, full size.\n const open = opens && sliceId && onPrototypeOpened\n ? () => onPrototypeOpened(sliceId, actorId, thumbnail.current?.getBoundingClientRect() ?? new DOMRect())\n : boardReadOnly\n ? () => setPreviewFrom(thumbnail.current?.getBoundingClientRect() ?? new DOMRect())\n : undefined;\n\n return (\n <div style={cellStyle} className={className}>\n {conn.bottomOutgoing && hasContent && <ConnectorOutgoingBottom />}\n {conn.bottomIncoming && hasContent && <ConnectorIncomingBottom />}\n <div className='event-modeling-grid-slice-cell-items'>\n {hasContent && (\n <div ref={thumbnail} className={`event-modeling-grid-ui-preview${open ? ' event-modeling-grid-ui-preview--clickable' : ''}`} data-flow-node={FlowNodeActor.ui}>\n <PrototypeThumbnail\n elements={[...elements]}\n windowSize={windowSize}\n layout={layout}\n onClick={open}\n openTitle={boardReadOnly ? messages.openPreview : undefined}\n />\n </div>\n )}\n {previewFrom && (\n <PrototypePreview\n elements={elements}\n windowSize={windowSize}\n layout={layout}\n sourceRect={previewFrom}\n onClose={() => setPreviewFrom(undefined)}\n />\n )}\n </div>\n {!readOnly && sliceId && onPrototypeAdded && !hasContent && (\n <CellCorner placement={CellCornerPlacement.add}>\n <AddPrototypeButton\n templates={actions.prototypeTemplates ?? []}\n onFromScratch={host => onPrototypeAdded(sliceId, actorId, host)}\n onFromTemplate={(template, host) => template.onChosen(sliceId, actorId, host)}\n />\n </CellCorner>\n )}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport type { Guid } from '@cratis/fundamentals';\nimport { type CellConnectors, ConnectorIncomingBottom, ConnectorOutgoingBottom } from '../../Connections';\n\nexport interface ChatCellProps {\n sliceId: Guid;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n}\n\nconst ChatIcon = () => (\n <svg width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round' strokeLinejoin='round' style={{ opacity: 0.25 }} aria-hidden='true'>\n <path d='M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z' />\n </svg>\n);\n\n// A slice's cell in the chat row: the chat mark, with the connectors that pass through it.\nexport const ChatCell = ({ sliceId, collapsed = false, conn, rowHeight }: ChatCellProps) => {\n const className = 'event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--chat';\n if (collapsed) {\n return (\n <div style={{ height: rowHeight }} className={className}>\n <ChatIcon />\n </div>\n );\n }\n return (\n <div style={{ height: rowHeight }} data-card-id='chat' data-slice-id={sliceId.toString()} className={className}>\n {conn.bottomOutgoing && <ConnectorOutgoingBottom />}\n {conn.bottomIncoming && <ConnectorIncomingBottom />}\n <ChatIcon />\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport type { ReactNode } from 'react';\nimport { type CellConnectors, ConnectorIncomingTop, ConnectorOutgoingTop } from '../../Connections';\n\nexport interface EventsCellProps {\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // How many events the slice has; a collapsed slice draws one small mark per event.\n eventCount: number;\n // The event cards, drawn only while the slice is expanded.\n children?: ReactNode;\n // What the consumer draws after the cards, and in the cell's corners.\n after?: ReactNode;\n corners?: ReactNode;\n}\n\n// A slice's cell in the events row: its event cards between the connectors, and the consumer's corner\n// actions. A collapsed slice shows a small mark for each event.\nexport const EventsCell = ({ collapsed = false, conn, rowHeight, eventCount, children, after, corners }: EventsCellProps) => {\n const className = 'event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--events';\n if (collapsed) {\n return (\n <div style={{ height: rowHeight }} className={className}>\n {Array.from({ length: eventCount }, (_, index) => (\n <div key={index} className='event-modeling-grid-mini-card event-modeling-grid-mini-card--event' />\n ))}\n </div>\n );\n }\n const hasItems = eventCount > 0;\n return (\n <div style={{ height: rowHeight }} className={className}>\n {conn.topIncoming && hasItems && <ConnectorIncomingTop />}\n {conn.topOutgoing && hasItems && <ConnectorOutgoingTop />}\n <div className='event-modeling-grid-slice-cell-cards'>\n {children}\n {after}\n </div>\n {corners}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EventCard.css';\nimport { useEffect, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../../Board';\nimport { ArtifactCard, ArtifactCardKind, CardNameInput, eventCardColors } from '../../Cards';\nimport { FlowNodeActor } from '../../Connections/FlowNodeActor';\nimport type { EventItem } from '../../Model';\nimport { SchemaTooltipProperties } from '../../Properties';\nimport { useSliceReadOnly } from '../../Slices';\nimport { GridTooltip } from '../../Tooltips';\n\nexport interface EventCardProps {\n sliceId: Guid;\n event: EventItem;\n // An event a slice only consumes is not its to rename.\n renameable: boolean;\n showDetails?: boolean;\n}\n\n// An event the slice owns. It is renamed in place with a double-click, shows whether it is selected, and\n// offers whatever the consumer supplies for event cards; clicking it activates it.\nexport const EventCard = ({ sliceId, event, renameable, showDetails = false }: EventCardProps) => {\n const { editing, actions, selection, messages } = useBoard();\n const sliceReadOnly = useSliceReadOnly();\n const [name, setName] = useState(event.name);\n const [editingName, setEditingName] = useState<string | undefined>(undefined);\n\n useEffect(() => setName(event.name), [event.name]);\n\n const onEventRenamed = editing.onEventRenamed;\n const canRename = renameable && !sliceReadOnly && !!onEventRenamed;\n const isSelected = !!selection.selectedArtifactId?.equals(event.id);\n\n const commit = () => {\n const trimmed = editingName?.trim() ?? '';\n setEditingName(undefined);\n if (!trimmed || !onEventRenamed) return;\n setName(onEventRenamed(sliceId, event.id, trimmed) ?? trimmed);\n };\n\n if (editingName !== undefined) {\n return (\n <div className='event-modeling-grid-event-wrapper'>\n <CardNameInput\n value={editingName}\n backgroundColor={eventCardColors.background}\n textColor={eventCardColors.text}\n onChange={setEditingName}\n onCommit={commit}\n onCancel={() => setEditingName(undefined)}\n />\n </div>\n );\n }\n\n return (\n <div className='event-modeling-grid-event-wrapper' data-flow-node={FlowNodeActor.event}>\n <GridTooltip\n content={(\n <SchemaTooltipProperties\n title={canRename ? `${messages.events.doubleClickToRenamePrefix} ${name}` : name}\n schema={event.schema}\n />\n )}\n position='top'\n >\n <ArtifactCard\n kind={ArtifactCardKind.event}\n artifactId={event.id}\n name={name}\n tags={event.tags}\n schema={event.schema}\n showDetails={showDetails}\n actions={actions.eventCard?.actions}\n onActivate={actions.eventCard?.onActivate}\n isSelected={isSelected}\n onStartEdit={canRename ? () => setEditingName(name) : undefined}\n ariaLabel={`${messages.events.openEvent} ${name}`}\n ariaPressed={isSelected}\n data-event-id={event.id.toString()}\n />\n </GridTooltip>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './References.css';\nimport React from 'react';\nimport { useEventModelMessages } from '../Messages';\n\nexport interface EventNavigateButtonProps {\n onClick: (clickEvent: React.MouseEvent) => void;\n}\n\n// The circular navigate-to-origin button rendered on a referencing card (a State View event reference or a\n// Translator external event). Visible on hover of the enclosing `.event-modeling-grid-event-wrapper--reference`.\nexport const EventNavigateButton: React.FC<EventNavigateButtonProps> = ({ onClick }) => {\n const messages = useEventModelMessages();\n return (\n <button\n className='event-modeling-grid-event-navigate-button'\n aria-label={messages.references.navigateToOriginal}\n title={messages.references.navigateToOriginal}\n onClick={onClick}\n >\n <i className='pi pi-arrow-up-right' style={{ transform: 'scaleX(-1)' }} />\n </button>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport React, { useCallback, useRef } from 'react';\nimport { Guid } from '@cratis/fundamentals';\n\n// Selector for the board container that scopes the dim-on-hover effect. Exported so the guided tour can\n// stage the same dim, driven by the script's clock instead of a real hover, to demonstrate the affordance\n// on a board a viewer cannot touch.\nexport const REFERENCE_DIM_BOARD_SELECTOR = '[data-event-model-board]';\n// Class applied to the board while a reference is hovered to dim every other card.\nexport const REFERENCE_DIM_CLASS = 'event-modeling-board--dim-others';\n// Class applied to the origin event and the hovered reference so they stay visible while dimmed.\nexport const REFERENCE_UNDIMMED_CLASS = 'event-modeling-event--undimmed';\n\nexport interface ReferenceHover {\n ref: React.RefObject<HTMLDivElement | null>;\n onMouseEnter: () => void;\n onMouseLeave: () => void;\n handleNavigate: (clickEvent: React.MouseEvent) => void;\n}\n\n// Dims the board except the referenced origin event while the referencing card is hovered, and navigates\n// to that origin on demand. Shared by State View event references and Translator external events so both\n// get the same affordance; the origin card is resolved from the DOM by its `data-event-id`.\nexport function useReferenceHover(sourceEventId: Guid, onNavigate?: (sourceEventId: Guid) => void): ReferenceHover {\n const wrapperRef = useRef<HTMLDivElement>(null);\n const dimStateRef = useRef<{ board: HTMLElement; origin: HTMLElement | null } | null>(null);\n\n const onMouseEnter = useCallback(() => {\n const wrapper = wrapperRef.current;\n if (!wrapper) return;\n const board = wrapper.closest(REFERENCE_DIM_BOARD_SELECTOR) as HTMLElement | null;\n if (!board) return;\n\n const originCard = board.querySelector(`[data-event-id=\"${sourceEventId.toString()}\"]`);\n const origin = originCard?.closest('.event-modeling-grid-event-wrapper') as HTMLElement | null;\n\n board.classList.add(REFERENCE_DIM_CLASS);\n wrapper.classList.add(REFERENCE_UNDIMMED_CLASS);\n origin?.classList.add(REFERENCE_UNDIMMED_CLASS);\n dimStateRef.current = { board, origin };\n }, [sourceEventId]);\n\n const onMouseLeave = useCallback(() => {\n const state = dimStateRef.current;\n if (state) {\n state.board.classList.remove(REFERENCE_DIM_CLASS);\n state.origin?.classList.remove(REFERENCE_UNDIMMED_CLASS);\n dimStateRef.current = null;\n }\n wrapperRef.current?.classList.remove(REFERENCE_UNDIMMED_CLASS);\n }, []);\n\n const handleNavigate = useCallback((clickEvent: React.MouseEvent) => {\n clickEvent.stopPropagation();\n onMouseLeave();\n onNavigate?.(sourceEventId);\n }, [onMouseLeave, onNavigate, sourceEventId]);\n\n return { ref: wrapperRef, onMouseEnter, onMouseLeave, handleNavigate };\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../Rows/Events/EventCard.css';\nimport './References.css';\nimport React from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { Card, externalEventCardColors } from '../Cards';\nimport { useReferenceHover } from './useReferenceHover';\nimport { EventNavigateButton } from './EventNavigateButton';\n\nexport interface ExternalEventCardProps {\n id: Guid;\n\n name: string;\n\n // The origin event this external event translates from; when present, the navigate affordance is shown.\n sourceEventId?: Guid;\n\n isSelected?: boolean;\n\n onSelected?: () => void;\n\n // Flies the board to the origin event and pulse-highlights it.\n onNavigate?: (sourceEventId: Guid) => void;\n\n ariaLabel?: string;\n\n 'data-card-id'?: string;\n\n 'data-slice-id'?: string;\n}\n\n// An external event card on a Translator slice. It references an event owned by another module, so it\n// gets the same board-dim-on-hover and navigate-to-origin affordance as a State View event reference.\nexport const ExternalEventCard: React.FC<ExternalEventCardProps> = ({\n id,\n name,\n sourceEventId,\n isSelected = false,\n onSelected,\n onNavigate,\n ariaLabel,\n ...cardProps\n}) => {\n const hasNavigation = !!sourceEventId && !sourceEventId.equals(Guid.empty) && !!onNavigate;\n const hover = useReferenceHover(sourceEventId ?? Guid.empty, onNavigate);\n\n return (\n <div\n ref={hover.ref}\n className='event-modeling-grid-event-wrapper event-modeling-grid-event-wrapper--reference'\n onMouseEnter={hasNavigation ? hover.onMouseEnter : undefined}\n onMouseLeave={hasNavigation ? hover.onMouseLeave : undefined}\n >\n <Card\n name={name}\n backgroundColor={externalEventCardColors.background}\n textColor={externalEventCardColors.text}\n isSelected={isSelected}\n onSelected={onSelected}\n ariaLabel={ariaLabel}\n {...cardProps}\n />\n {hasNavigation && <EventNavigateButton onClick={hover.handleNavigate} />}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './EventCard.css';\nimport './EventReferenceCard.css';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../../Board';\nimport { Card, eventCardColors } from '../../Cards';\nimport { FlowNodeActor } from '../../Connections/FlowNodeActor';\nimport type { EventItem } from '../../Model';\nimport { SchemaTooltipProperties } from '../../Properties';\nimport { EventNavigateButton, useReferenceHover } from '../../References';\nimport { GridTooltip } from '../../Tooltips';\n\nexport interface EventReferenceCardProps {\n // An event of the slice that refers to an event another slice owns.\n event: EventItem;\n // Whether clicking the reference selects it.\n selectable: boolean;\n showDetails?: boolean;\n // Whether the event is produced by a slice to the right of this one, which a State View may not project.\n projectedFromTheRight?: boolean;\n}\n\n// An event owned by another slice and referenced from this one, drawn with a dashed border and slightly\n// faded. Hovering it dims the board around the original, and its button flies the board there.\nexport const EventReferenceCard = ({ event, selectable, showDetails = false, projectedFromTheRight = false }: EventReferenceCardProps) => {\n const { selection, navigation, messages } = useBoard();\n const sourceEventId = Guid.parse(event.sourceEventId ?? Guid.empty.toString());\n const hover = useReferenceHover(sourceEventId, navigation.onNavigateToEvent);\n const isSelected = !!selection.selectedArtifactId?.equals(event.id);\n const onArtifactSelected = selection.onArtifactSelected;\n\n return (\n <div\n ref={hover.ref}\n className={`event-modeling-grid-event-wrapper event-modeling-grid-event-wrapper--reference event-modeling-event-reference${projectedFromTheRight ? ' event-modeling-event-reference--out-of-order' : ''}`}\n data-out-of-order={projectedFromTheRight || undefined}\n title={projectedFromTheRight ? messages.events.projectedFromTheRight : undefined}\n data-flow-node={FlowNodeActor.event}\n onMouseEnter={hover.onMouseEnter}\n onMouseLeave={hover.onMouseLeave}\n >\n <GridTooltip content={<SchemaTooltipProperties title={event.name} schema={event.schema} />} position='top'>\n <Card\n name={event.name}\n backgroundColor={eventCardColors.background}\n textColor={eventCardColors.text}\n isSelected={isSelected}\n onSelected={selectable && onArtifactSelected ? () => onArtifactSelected(event.id) : undefined}\n ariaLabel={`${messages.events.openEvent} ${event.name}`}\n ariaPressed={isSelected}\n data-event-id={event.id.toString()}\n extraContent={showDetails ? (\n <SchemaTooltipProperties title={event.name} schema={event.schema} showTitle={false} compact={true} />\n ) : undefined}\n />\n </GridTooltip>\n {projectedFromTheRight && (\n <span className='event-modeling-event-reference__warning' role='img' aria-label={messages.events.projectedFromTheRight}>!</span>\n )}\n <EventNavigateButton onClick={hover.handleNavigate} />\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { type EventItem, type Slice, SliceType } from '../../Model';\n\n// The ids of a State View's references whose event is produced by a slice to its right. A State View only\n// projects events from slices to its left, so a reorder that moved the producer past it leaves these behind.\n// An event produced in another collection is not on this timeline and is never flagged.\nexport const projectedFromTheRightOf = (slice: Slice, priorEvents: readonly EventItem[], followingEvents: readonly EventItem[]): Set<string> => {\n if (slice.sliceType !== SliceType.stateView) return new Set();\n const before = new Set(priorEvents.map(event => event.id.toString()));\n const after = new Set(followingEvents.map(event => event.id.toString()));\n return new Set(slice.events\n .filter(event => !!event.sourceEventId && after.has(event.sourceEventId) && !before.has(event.sourceEventId))\n .map(event => event.id.toString()));\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { EventItem, Slice } from '../../Model';\n\n// The events a slice can still reference: not already referenced, and not sharing a name with one of the\n// slice's own events, since a reference arrives as an event of the same name.\nexport const referenceableEvents = (slice: Slice, priorEvents: readonly EventItem[]): EventItem[] => {\n const referenced = new Set(slice.events.flatMap(event => event.sourceEventId ? [event.sourceEventId] : []));\n const names = new Set(slice.events.map(event => event.name));\n return priorEvents.filter(event => !referenced.has(event.id.toString()) && !names.has(event.name));\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useBoard } from '../../Board';\nimport type { CellConnectors } from '../../Connections';\nimport { type EventItem, type Slice, SliceType } from '../../Model';\nimport { EventReferencePicker } from '../../Pickers';\nimport { useSliceReadOnly } from '../../Slices';\nimport { CellActionButton } from '../CellActionButton';\nimport { CellCorner } from '../CellCorner';\nimport { CellCornerAction } from '../CellCornerAction';\nimport { CellCornerPlacement } from '../CellCornerPlacement';\nimport { showsEventReferencePlaceholder, usesEventReferencePicker } from '../eventRowAffordances';\nimport { EventCard } from './EventCard';\nimport { EventReferenceCard } from './EventReferenceCard';\nimport { projectedFromTheRightOf } from './projectedFromTheRight';\nimport { referenceableEvents } from './referenceableEvents';\nimport { EventsCell } from './EventsCell';\n\nexport interface SliceEventsProps {\n slice: Slice;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // The events produced before this slice in its module, which a State View may reference.\n priorEvents: readonly EventItem[];\n // The events produced after this slice in its module collection.\n followingEvents?: readonly EventItem[];\n showDetails?: boolean;\n}\n\n// A slice's events row: the events it owns, the events it references, and the ways to add either.\nexport const SliceEvents = ({ slice, collapsed = false, conn, rowHeight, priorEvents, followingEvents = [], showDetails = false }: SliceEventsProps) => {\n const { editing, actions, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const { onEventAdded, onEventReferenced } = editing;\n const offersPicker = usesEventReferencePicker(slice.sliceType);\n const placeholder = showsEventReferencePlaceholder(slice.sliceType, slice.events.length);\n const options = referenceableEvents(slice, priorEvents);\n const projectedFromTheRight = projectedFromTheRightOf(slice, priorEvents, followingEvents);\n const rowActions = (actions.eventsRow ?? []).filter(action => !action.when || action.when(slice));\n const picker = (withPlaceholder: boolean) => onEventReferenced && (\n <EventReferencePicker\n options={options}\n nameOf={option => option.name}\n onSelect={option => onEventReferenced(slice.id, option)}\n label={messages.events.addExistingEvent}\n searchPlaceholder={messages.events.searchEvents}\n emptyLabel={messages.events.noEventsAvailable}\n placeholder={withPlaceholder ? messages.events.noEventsYet : undefined}\n />\n );\n\n return (\n <EventsCell\n collapsed={collapsed}\n conn={conn}\n rowHeight={rowHeight}\n eventCount={slice.events.length}\n after={!readOnly && placeholder && picker(true)}\n corners={(\n <>\n {!readOnly && rowActions.length > 0 && (\n <CellCorner placement={CellCornerPlacement.top}>\n {rowActions.map(action => <CellActionButton key={action.tooltip} action={action} />)}\n </CellCorner>\n )}\n {!readOnly && !offersPicker && onEventAdded && (\n <CellCornerAction\n placement={CellCornerPlacement.add}\n action={{ tooltip: messages.events.addEvent, onActivate: sliceId => onEventAdded(sliceId) }}\n />\n )}\n {!readOnly && offersPicker && !placeholder && onEventReferenced && (\n <CellCorner placement={CellCornerPlacement.add}>{picker(false)}</CellCorner>\n )}\n </>\n )}\n >\n {slice.events.map(event => event.sourceEventId\n ? (\n <EventReferenceCard\n key={event.id.toString()}\n event={event}\n selectable={slice.sliceType !== SliceType.stateView}\n showDetails={showDetails}\n projectedFromTheRight={projectedFromTheRight.has(event.id.toString())}\n />\n )\n : (\n <EventCard\n key={event.id.toString()}\n sliceId={slice.id}\n event={event}\n renameable={slice.sliceType !== SliceType.stateView}\n showDetails={showDetails}\n />\n ))}\n </EventsCell>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { useEffect, useState } from 'react';\nimport type { Guid } from '@cratis/fundamentals';\nimport type { JsonSchema } from '@cratis/components/types';\nimport { useBoard } from '../../Board';\nimport { ArtifactCard, ArtifactCardKind, CardNameInput, commandCardColors, readModelCardColors } from '../../Cards';\nimport { FlowNodeActor } from '../../Connections/FlowNodeActor';\nimport { SchemaTooltipProperties } from '../../Properties';\nimport { useSliceReadOnly } from '../../Slices';\nimport { GridTooltip } from '../../Tooltips';\n\n// The kinds of card an interaction card can be; external events are drawn by their own card.\nexport type InteractionCardKind = ArtifactCardKind.command | ArtifactCardKind.readModel;\n\nexport interface InteractionCardProps {\n sliceId: Guid;\n kind: InteractionCardKind;\n artifactId: Guid;\n name: string;\n schema: JsonSchema;\n showDetails?: boolean;\n // Offered only when supplied and the slice is editable.\n onRenamed?: (name: string) => void;\n}\n\n// A slice's command or read model. It is renamed in place with a double-click, shows whether it is\n// selected, and offers whatever the consumer supplies for its kind of card; clicking it activates it.\nexport const InteractionCard = ({ sliceId, kind, artifactId, name, schema, showDetails = false, onRenamed }: InteractionCardProps) => {\n const { actions, selection, messages } = useBoard();\n const sliceReadOnly = useSliceReadOnly();\n const [shownName, setShownName] = useState(name);\n const [editingName, setEditingName] = useState<string | undefined>(undefined);\n\n useEffect(() => setShownName(name), [name]);\n\n const isCommand = kind === ArtifactCardKind.command;\n const surface = isCommand ? actions.commandCard : actions.readModelCard;\n const colors = isCommand ? commandCardColors : readModelCardColors;\n const label = isCommand ? messages.interaction.command : messages.interaction.readModel;\n const canRename = !sliceReadOnly && !!onRenamed;\n const onArtifactSelected = selection.onArtifactSelected;\n\n const commit = () => {\n const trimmed = editingName?.trim() ?? '';\n setEditingName(undefined);\n if (!trimmed || !onRenamed) return;\n onRenamed(trimmed);\n setShownName(trimmed);\n };\n\n if (editingName !== undefined) {\n return (\n <CardNameInput\n value={editingName}\n backgroundColor={colors.background}\n textColor={colors.text}\n onChange={setEditingName}\n onCommit={commit}\n onCancel={() => setEditingName(undefined)}\n />\n );\n }\n\n return (\n <GridTooltip\n content={<SchemaTooltipProperties title={`${messages.interaction.doubleClickToRenamePrefix} ${label}: ${shownName}`} schema={schema} />}\n position='top'\n >\n <div data-flow-node={isCommand ? FlowNodeActor.command : FlowNodeActor.readModel}>\n <ArtifactCard\n kind={kind}\n artifactId={artifactId}\n name={shownName}\n schema={schema}\n showDetails={showDetails}\n actions={surface?.actions}\n onActivate={surface?.onActivate}\n isSelected={!!selection.selectedArtifactId?.equals(artifactId)}\n onSelected={onArtifactSelected ? () => onArtifactSelected(artifactId) : undefined}\n onStartEdit={canRename ? () => setEditingName(shownName) : undefined}\n ariaLabel={`${messages.interaction.open} ${label}: ${shownName}`}\n data-card-id={artifactId.toString()}\n data-slice-id={sliceId.toString()}\n />\n </div>\n </GridTooltip>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport '../SliceCell.css';\nimport type { ReactNode } from 'react';\nimport { type CellConnectors, ConnectorIncomingBottom, ConnectorIncomingTop, ConnectorOutgoingBottom, ConnectorOutgoingTop } from '../../Connections';\nimport { InteractionMiniCard } from './InteractionMiniCard';\n\n// How a slice's interaction cell arranges its cards.\nexport type InteractionLayout =\n // The cards centered, with the connectors running through the whole cell.\n | { kind: 'centered'; cards: ReactNode; corners?: ReactNode; hasItems: boolean }\n // A read model and a command side by side, each connector over its own card.\n | { kind: 'sideBySide'; cards: ReactNode; readModelOnTop: boolean; commandBelow: boolean; hasLeftCard: boolean; hasRightCard: boolean }\n // The external events on the left and the slice's own command on the right, each with its own corner.\n | { kind: 'split'; left: ReactNode; leftCorner?: ReactNode; right: ReactNode; rightCorner?: ReactNode; hasItems: boolean };\n\nexport interface InteractionCellProps {\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // What a collapsed cell draws, one small mark per card.\n miniCards: readonly InteractionMiniCard[];\n layout: InteractionLayout;\n}\n\nconst centered = 'event-modeling-grid-slice-cell event-modeling-grid-slice-cell--centered event-modeling-grid-slice-cell--interaction';\n\n// A slice's cell in the interaction row: its command and read-model cards between the connectors.\nexport const InteractionCell = ({ collapsed = false, conn, rowHeight, miniCards, layout }: InteractionCellProps) => {\n const style = { height: rowHeight };\n if (collapsed) {\n return (\n <div style={style} className={centered}>\n {miniCards.map((kind, index) => <div key={index} className={`event-modeling-grid-mini-card event-modeling-grid-mini-card--${kind}`} />)}\n </div>\n );\n }\n\n if (layout.kind === 'sideBySide') {\n return (\n <div style={style} className={centered}>\n {conn.topOutgoing && layout.readModelOnTop && <ConnectorOutgoingTop columnPosition={layout.hasRightCard ? 'left' : 'center'} />}\n {conn.topIncoming && layout.commandBelow && <ConnectorIncomingTop columnPosition={layout.hasLeftCard ? 'right' : 'center'} />}\n <div className='event-modeling-grid-slice-cell-cards'>{layout.cards}</div>\n </div>\n );\n }\n\n const connectors = layout.hasItems && (\n <>\n {conn.topOutgoing && <ConnectorOutgoingTop />}\n {conn.topIncoming && <ConnectorIncomingTop />}\n {conn.bottomOutgoing && <ConnectorOutgoingBottom />}\n {conn.bottomIncoming && <ConnectorIncomingBottom />}\n </>\n );\n\n if (layout.kind === 'split') {\n return (\n <div style={style} className='event-modeling-grid-slice-cell event-modeling-grid-slice-cell--translator event-modeling-grid-slice-cell--interaction'>\n {connectors}\n <div className='event-modeling-grid-slice-cell--translator-external'>\n <div className='event-modeling-grid-slice-cell-cards'>{layout.left}</div>\n {layout.leftCorner}\n </div>\n <div className='event-modeling-grid-slice-cell--translator-regular'>\n <div className='event-modeling-grid-slice-cell-cards'>{layout.right}</div>\n {layout.rightCorner}\n </div>\n </div>\n );\n }\n\n return (\n <div style={style} className={centered}>\n {connectors}\n <div className='event-modeling-grid-slice-cell-cards'>{layout.cards}</div>\n {layout.corners}\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n// What a collapsed interaction cell draws a small mark for.\nexport enum InteractionMiniCard {\n command = 'command',\n readModel = 'readmodel',\n}\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport './OptionalReadModel.css';\nimport { useRef } from 'react';\n\nexport interface OptionalReadModelProps {\n // Drawn on the placeholder card.\n label: string;\n // The define button's accessible name and tooltip.\n defineLabel: string;\n // Receives the viewport rectangle of the placeholder card, so an editor can open from it.\n onDefine: (host: DOMRect) => void;\n}\n\n// A placeholder card where a slice may define a read model it does not have yet, with a button to define it.\nexport const OptionalReadModel = ({ label, defineLabel, onDefine }: OptionalReadModelProps) => {\n const card = useRef<HTMLDivElement>(null);\n return (\n <div className='event-modeling-grid-optional-read-model' ref={card}>\n <div className='event-modeling-grid-optional-read-model__card'>\n <span>{label}</span>\n </div>\n <button\n type='button'\n className='event-modeling-grid-optional-read-model__define-btn'\n aria-label={defineLabel}\n title={defineLabel}\n onClick={clickEvent => {\n clickEvent.stopPropagation();\n onDefine(card.current?.getBoundingClientRect() ?? new DOMRect());\n }}\n >\n <i className='pi pi-pencil' />\n </button>\n </div>\n );\n};\n","// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport type { ReactNode } from 'react';\nimport { Guid } from '@cratis/fundamentals';\nimport { useBoard } from '../../Board';\nimport { ArtifactCardKind } from '../../Cards';\nimport type { CellConnectors } from '../../Connections';\nimport { FlowNodeActor } from '../../Connections/FlowNodeActor';\nimport { type EventItem, type ExternalEventItem, type Slice, SliceType } from '../../Model';\nimport { EventReferencePicker } from '../../Pickers';\nimport { SchemaTooltipProperties } from '../../Properties';\nimport { ExternalEventCard } from '../../References';\nimport { useSliceReadOnly } from '../../Slices';\nimport { GridTooltip } from '../../Tooltips';\nimport { CellActionButton } from '../CellActionButton';\nimport { CellCorner } from '../CellCorner';\nimport { CellCornerPlacement } from '../CellCornerPlacement';\nimport { showsExternalEventPicker } from '../eventRowAffordances';\nimport { InteractionCard } from './InteractionCard';\nimport { InteractionCell } from './InteractionCell';\nimport { InteractionMiniCard } from './InteractionMiniCard';\nimport { OptionalReadModel } from './OptionalReadModel';\n\nexport interface SliceInteractionProps {\n slice: Slice;\n collapsed?: boolean;\n conn: CellConnectors;\n rowHeight: number;\n // The events of other modules a Translator can translate from.\n externalEventOptions?: readonly EventItem[];\n showDetails?: boolean;\n}\n\n// The mark a collapsed cell draws per card, in the order the cards are drawn.\nconst miniCardsOf = (slice: Slice): InteractionMiniCard[] => {\n switch (slice.sliceType) {\n case SliceType.stateChange: return slice.command ? [InteractionMiniCard.command] : [];\n case SliceType.stateView: return slice.readModel ? [InteractionMiniCard.readModel] : [];\n case SliceType.automation: return [\n ...(slice.readModel ? [InteractionMiniCard.readModel] : []),\n ...(slice.command ? [InteractionMiniCard.command] : []),\n ];\n default: return [\n ...slice.externalEvents.map(() => InteractionMiniCard.readModel),\n ...(slice.command ? [InteractionMiniCard.command] : []),\n ];\n }\n};\n\n// A slice's interaction row: its command, its read model, and a Translator's external events, laid out\n// for the slice type, with the ways to add what the slice may still have.\nexport const SliceInteraction = ({ slice, collapsed = false, conn, rowHeight, externalEventOptions = [], showDetails = false }: SliceInteractionProps) => {\n const { editing, actions, selection, navigation, messages } = useBoard();\n const readOnly = useSliceReadOnly();\n const { onCommandRenamed, onReadModelRenamed, onReadModelAdded, onExternalEventAdded } = editing;\n const rowActions = (actions.interactionRow ?? []).filter(action => !action.when || action.when(slice));\n const miniCards = miniCardsOf(slice);\n const onArtifactSelected = selection.onArtifactSelected;\n\n const { command, readModel } = slice;\n const commandCard = command && (\n <InteractionCard\n key={command.id.toString()}\n sliceId={slice.id}\n kind={ArtifactCardKind.command}\n artifactId={command.id}\n name={command.name}\n schema={command.schema}\n showDetails={showDetails}\n onRenamed={onCommandRenamed && (name => onCommandRenamed(slice.id, command.id, name))}\n />\n );\n const readModelCard = readModel && (\n <InteractionCard\n key={readModel.id.toString()}\n sliceId={slice.id}\n kind={ArtifactCardKind.readModel}\n artifactId={readModel.id}\n name={readModel.name}\n schema={readModel.schema}\n showDetails={showDetails}\n onRenamed={onReadModelRenamed && (name => onReadModelRenamed(slice.id, readModel.id, name))}\n />\n );\n const externalEventCard = (external: ExternalEventItem) => {\n const label = `${messages.interaction.open} ${messages.interaction.externalEvent}: ${external.name}`;\n const schema = externalEventOptions.find(option => option.name === external.name)?.schema;\n return (\n <GridTooltip\n key={external.id.toString()}\n content={<SchemaTooltipProperties title={`${messages.interaction.doubleClickToRenamePrefix} ${messages.interaction.externalEvent}: ${external.name}`} schema={schema} />}\n position='top'\n >\n <div data-flow-node={FlowNodeActor.externalEvent}>\n <ExternalEventCard\n id={external.id}\n name={external.name}\n sourceEventId={external.sourceEventId ? Guid.parse(external.sourceEventId) : undefined}\n onNavigate={navigation.onNavigateToEvent}\n isSelected={!!selection.selectedArtifactId?.equals(external.id)}\n onSelected={onArtifactSelected ? () => onArtifactSelected(external.id) : undefined}\n ariaLabel={label}\n data-card-id={external.id.toString()}\n data-slice-id={slice.id.toString()}\n />\n </div>\n </GridTooltip>\n );\n };\n const corner: ReactNode = !readOnly && rowActions.length > 0 && (\n <CellCorner placement={CellCornerPlacement.add}>\n {rowActions.map(action => <CellActionButton key={action.tooltip} action={action} />)}\n </CellCorner>\n );\n\n if (slice.sliceType === SliceType.automation && !collapsed) {\n const offersReadModel = !readOnly && !slice.readModel && !!slice.command && !!onReadModelAdded;\n return (\n <InteractionCell\n conn={conn}\n rowHeight={rowHeight}\n miniCards={miniCards}\n layout={{\n kind: 'sideBySide',\n readModelOnTop: !!slice.readModel,\n commandBelow: !!slice.command,\n hasLeftCard: !!slice.readModel || offersReadModel,\n hasRightCard: !!slice.command,\n cards: (\n <>\n {readModelCard}\n {offersReadModel && (\n <OptionalReadModel\n label={messages.interaction.readModel}\n defineLabel={messages.interaction.defineReadModel}\n onDefine={host => onReadModelAdded(slice.id, host)}\n />\n )}\n {commandCard}\n </>\n ),\n }}\n />\n );\n }\n\n if (slice.sliceType === SliceType.translator && !collapsed) {\n const added = new Set(slice.externalEvents.map(external => external.name));\n return (\n <InteractionCell\n conn={conn}\n rowHeight={rowHeight}\n miniCards={miniCards}\n layout={{\n kind: 'split',\n hasItems: slice.externalEvents.length > 0 || !!slice.command,\n left: slice.externalEvents.map(externalEventCard),\n leftCorner: !readOnly && showsExternalEventPicker(slice.sliceType) && onExternalEventAdded && (\n <CellCorner placement={CellCornerPlacement.add}>\n <EventReferencePicker\n options={externalEventOptions.filter(option => !added.has(option.name))}\n nameOf={option => option.name}\n onSelect={option => onExternalEventAdded(slice.id, option)}\n label={messages.interaction.addExternalEvent}\n searchPlaceholder={messages.interaction.searchExternalEvents}\n emptyLabel={messages.interaction.noExternalEventsAvailable}\n />\n </CellCorner>\n ),\n right: commandCard,\n rightCorner: corner,\n }}\n />\n );\n }\n\n const cards = slice.sliceType === SliceType.stateView\n ? readModelCard\n : slice.sliceType === SliceType.automation\n ? <>{readModelCard}{commandCard}</>\n : slice.sliceType === SliceType.translator\n ? <>{slice.externalEvents.map(externalEventCard)}{commandCard}</>\n : commandCard;\n\n return (\n <InteractionCell\n collapsed={collapsed}\n conn={conn}\n rowHeight={rowHeight}\n miniCards={miniCards}\n layout={{ kind: 'centered', hasItems: miniCards.length > 0, cards, corners: corner }}\n />\n );\n};\n"],"mappings":";;;;;;;;AAGA,IAAY,KAAL,0BAAA,GAAA;AACH,SAAA,EAAA,EAAA,SAAA,CAAA,IAAA,UACA,EAAA,EAAA,aAAA,CAAA,IAAA,cACA,EAAA,EAAA,WAAA,CAAA,IAAA;AACJ,GAAA,CAAA,CAAA,GCJY,KAAL,0BAAA,GAAA;AACH,SAAA,EAAA,SAAA,UACA,EAAA,QAAA,SACA,EAAA,OAAA;AACJ,GAAA,CAAA,CAAA,GCJY,KAAL,0BAAA,GAAA;AACH,SAAA,EAAA,EAAA,QAAA,CAAA,IAAA,SACA,EAAA,EAAA,QAAA,CAAA,IAAA,SACA,EAAA,EAAA,S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