@miragon/value-chain-renderer 0.6.0 → 0.7.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":["svgCreate","ICONS","Diagram","ElementFactory","BaseRenderer","TextUtil","SelectionModule","ZoomScrollModule","MoveCanvasModule","ModelingModule","MoveModule","OutlineModule","BendpointsModule","AutoScrollModule","GridSnappingModule","SnappingModule","KeyboardMoveSelectionModule","KeyboardMoveModule","CroppingConnectionDocking","BaseLayouter","CommandInterceptor","RulesModule","RuleProvider","ConnectModule","AutoPlaceModule","CreateModule","ConnectionPreviewModule","PaletteModule","HandToolModule","LassoToolModule","SpaceToolModule","GlobalConnectModule","ContextPadModule","PopupMenuModule","DirectEditingModule","AlignElementsModule","DistributeElementsModule","KeyboardModule","EditorActionsModule","KeyboardBindings","OrderingProvider","CopyPasteModule","ResizeModule","EXPORT_PADDING","EMPTY_EXPORT","LIVE_CANVAS_ATTRIBUTES","saveSVG","source","canvas","child","box","bounds","clone","attribute","viewport","isObject","value","isVcShape","element","\"vcType\"","isStep","isOrgUnit","isVcConnection","isVcElement","VcBaseViewer","options","name","event","priority","callback","valid","validateDocument","document","labelEditing","previous","warnings","error","target","importer","container","sizeToCss","modules","VcElementFactory","elementFactory","connection","point","DEFAULT_STEP_SIZE","label","DEFAULT_ORG_UNIT_SIZE","ID_ALPHABET","ID_LENGTH","PREFIXES","randomSuffix","bytes","byte","VcDiagramElementFactory","elementRegistry","withId","attrs","type","vcType","prefix","id","vcModelModule","notchDepth","height","width","chevronPath","chevronPathAt","labelInset","depth","d","my","y","x","ellipsePathAt","rx","ry","cx","hell","COLORS","FONT","COLOR_OPTIONS","VC_RENDER_PRIORITY","ARROW_PATH","rendererInstances","VcRenderer","eventBus","graphicsFactory","fonts","font","destroyed","faces","shape","stroke","orgUnit","path","create","attr","append","visuals","inset","svg","line","createLine","first","rest","color","defs","marker","arrow","vcDrawModule","VcBounds","elements","getBBox","padding","vcBoundsModule","ROOT_ID","FIT_PADDING","SMALLEST_FIT_ZOOM","VcImporter","vcElementFactory","vcBounds","config","root","documentExtensions","metaExtensions","shapeById","connectionIndex","roots","other","scale","VcExporter","connections","imported","connectionExtensions","extensions","elementExtensions","link","CURRENT_SCHEMA_VERSION","svgToPng","svgSize","url","image","resolve","reject","context","blob","blobToBase64","reader","ioModule","Viewer","NavigatedViewer","UpdatePropertiesHandler","old","key","properties","setOrDelete","oldProperties","UPDATE_PROPERTIES","VcModeling","commandStack","TRUNK_MARGIN","BUS_MIN_STUB","EXIT_MARGIN","VcLayouter","connectionDocking","hints","waypoints","isHierarchy","stub","result","allFinite","fallback","getMid","interior","sourceMid","targetMid","children","hierarchyChildren","group","isRowArrangement","withoutRedundantPoints","connectPoints","bottom","topmost","busY","minChildX","trunkX","connectRectangles","hierarchyDropSpan","tops","ROW_TOLERANCE_Y","centerX","span","points","VcConnectionTypeBehavior","modeling","VcHierarchyRelayoutBehavior","layouter","shapes","parents","hierarchyEdges","incoming","parent","edge","sameWaypoints","a","b","index","vcModelingModule","VcRules","vcConnect","hasConnection","endpointsAllowed","isRoot","pending","ignore","vcRulesModule","VcConnect","connect","vcConnectModule","VcAppend","autoPlace","factory","newShape","BEFORE_DEFAULT","SEQUENCE_GAP_X","HIERARCHY_GAP_Y","SIBLING_GAP_Y","SIBLING_GAP_X","DECONFLICT_STEP_Y","DECONFLICT_MARGIN","VcAutoPlaceBehavior","desired","anchor","rightmost","bottommost","steps","candidate","position","attempt","step","best","vcAppendModule","connectionPreview","injector","canConnect","LUCIDE","CHROME_ICON","PALETTE_TOOL_ICON","lucideIcon","glyph","viewBox","content","preview","ICONS","paletteEntryHtml","draggable","iconSvg","contextPadEntryHtml","KEYBOARD_CREATE_OFFSET","VcPaletteProvider","handTool","lassoTool","spaceTool","globalConnect","selection","palette","creator","isKeyboardClick","createStep","createOrgUnit","centre","created","area","middle","start","end","size","insets","vcPaletteModule","COLOR_PICKER_PROVIDER_ID","swatch","VcColorPickerProvider","vcModeling","popupMenu","entries","option","ALIGN_MENU_PROVIDER_ID","alignIcon","ICONS$1","VcAlignMenuProvider","alignElements","distributeElements","align","icon","VcContextPadProvider","vcAppend","readOnly","contextPad","startConnect","mouse","\"delete\"","\"align\"","appendDrag","vcContextPadModule","VcLabelEditingProvider","directEditing","canExecute","open","edit","active","textbox","\"fontSize\"","bbox","zoom","sanitizeLabel","newText","text","vcLabelEditingModule","vcColorPickerModule","vcAlignMenuModule","UNDO_REDO_ACTIONS","VcKeyboardBindings","keyboard","boundActions","editorActions","action","addListener","listener","bindTool","isKey","keys","hasModifier","isCmd","HIGH_PRIORITY","VcEditorActions","lock","unlocked","register","service","serviceName","allowed","run","tool","selected","vcKeyboardModule","VcOrderingProvider","newParent","vcOrderingModule","VcCopyPasteBehavior","\"vcLabel\"","\"color\"","\"link\"","vcCopyPasteModule","VcResizeBehavior","MIN_STEP_SIZE","minDimensions","vcResizeModule","READ_ONLY_CHANGED_EVENT","LOCK_PRIORITY","EDIT_RULES","VcReadOnly","bus","optional","vcReadOnlyModule","Modeler","VALUE_CHAIN_NOTATION","BLANK_DOCUMENT_NAME","createCollaborativeModeler","collaborative","diagramOptions","createCollaborativeViewer","documentOf","createEmptyDocument","parseDocumentJSON","diagram","contentListeners","lastExport","meta","MODELER_API_VERSION","editable","elementInfo","shapeIds","host","warning","serializeDocument","state","isViewState","isFiniteNumber","exportEntry","JSON_EXPORT_LABEL","diagramMenu","actions","exports","ARROWS","commandKeyLabel","platform","keyNames","percentOfActualSize","lang","viewKeys","ctrl","plus","minus","shift","editKeys","fileGroup","chrome","messages","diagramShortcuts","view","DIALOG_CLASS","TITLE_ID","tag","className","shortcutTable","section","headingId","heading","table","body","row","dialogContent","panel","header","title","close","onClose","createShortcutsDialog","dialog","build"],"sources":["../src/io/saveSvg.ts","../src/model/di-types.ts","../src/VcBaseViewer.ts","../src/model/VcElementFactory.ts","../src/model/VcDiagramElementFactory.ts","../src/model/index.ts","../src/draw/geometry.ts","../src/theme/cd-tokens.generated.json","../src/draw/styles.ts","../src/draw/VcRenderer.ts","../src/draw/index.ts","../src/bounds/VcBounds.ts","../src/bounds/index.ts","../src/io/types.ts","../src/io/VcImporter.ts","../src/io/VcExporter.ts","../src/io/png.ts","../src/io/index.ts","../src/Viewer.ts","../src/NavigatedViewer.ts","../src/modeling/cmd/UpdatePropertiesHandler.ts","../src/modeling/VcModeling.ts","../src/modeling/VcLayouter.ts","../src/modeling/VcConnectionTypeBehavior.ts","../src/modeling/VcHierarchyRelayoutBehavior.ts","../src/modeling/index.ts","../src/rules/VcRules.ts","../src/rules/index.ts","../src/connect/VcConnect.ts","../src/connect/index.ts","../src/append/VcAppend.ts","../src/append/VcAutoPlaceBehavior.ts","../src/append/VcCreatePreviewBehavior.ts","../src/append/index.ts","../src/draw/lucide.ts","../src/draw/icons.ts","../src/palette/VcPaletteProvider.ts","../src/palette/index.ts","../src/popup/VcColorPickerProvider.ts","../src/popup/VcAlignMenuProvider.ts","../src/context-pad/VcContextPadProvider.ts","../src/context-pad/index.ts","../src/label-editing/VcLabelEditingProvider.ts","../src/label-editing/index.ts","../src/popup/index.ts","../src/keyboard/VcKeyboardBindings.ts","../src/keyboard/VcEditorActions.ts","../src/keyboard/index.ts","../src/ordering/VcOrderingProvider.ts","../src/ordering/index.ts","../src/copy-paste/VcCopyPasteBehavior.ts","../src/copy-paste/index.ts","../src/resize/VcResizeBehavior.ts","../src/resize/index.ts","../src/read-only/VcReadOnly.ts","../src/read-only/index.ts","../src/Modeler.ts","../src/collaborative/CollaborativeValueChain.ts","../src/diagram-menu/menu.ts","../src/diagram-menu/shortcuts.ts","../src/diagram-menu/ShortcutsDialog.ts"],"sourcesContent":["import type Canvas from 'diagram-js/lib/core/Canvas';\nimport type VcBounds from '../bounds/VcBounds.js';\n\nconst EXPORT_PADDING = 20;\n\n/** What the empty canvas exports: a blank sheet of this size at the origin. */\nconst EMPTY_EXPORT = { x: 0, y: 0, width: 800, height: 600 };\n\n/** Attributes the live canvas carries for keyboard and screen-reader use, not for a picture. */\nconst LIVE_CANVAS_ATTRIBUTES = ['tabindex', 'role', 'aria-label', 'aria-roledescription'];\n\n/**\n * Standalone SVG export: clones the live SVG, sets a viewBox around the diagram contents and\n * strips the pan/zoom transform. Fonts and colours are SVG presentation attributes, so the\n * result renders identically outside the editor and stays light in every mode.\n */\nexport function saveSVG(canvas: Canvas, bounds: Pick<VcBounds, 'contentBounds'>): { svg: string } {\n // The canvas's own <svg> child: a host chrome may move the palette, with its icon <svg>s, in\n // front of it inside the same container.\n const source = [...canvas.getContainer().children].find(\n (child): child is SVGSVGElement => child instanceof SVGSVGElement,\n );\n if (!source) {\n throw new Error('No SVG found in the canvas container.');\n }\n\n const box = bounds.contentBounds(EXPORT_PADDING) ?? EMPTY_EXPORT;\n\n const clone = source.cloneNode(true) as SVGSVGElement;\n for (const attribute of LIVE_CANVAS_ATTRIBUTES) {\n clone.removeAttribute(attribute);\n }\n clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');\n clone.setAttribute('viewBox', `${box.x} ${box.y} ${box.width} ${box.height}`);\n clone.setAttribute('width', String(box.width));\n clone.setAttribute('height', String(box.height));\n\n const viewport = clone.querySelector<SVGGElement>('.viewport');\n if (viewport) {\n viewport.removeAttribute('transform');\n }\n\n const svg = new XMLSerializer().serializeToString(clone);\n return { svg: `<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n${svg}` };\n}\n","import type { Connection, Shape } from 'diagram-js/lib/model/Types';\nimport type {\n ChainConnection,\n ConnectionType,\n DiagramElement,\n} from '@miragon/value-chain-schema-model';\n\nexport type VcShapeType = 'step' | 'orgUnit';\n\n/**\n * Runtime model: diagram-js elements carry the editable domain truth as flat properties\n * (`vcType`, `vcLabel`, `color`, `link`). The `businessObject` is only an import-time\n * snapshot used as fallback for fields the UI cannot edit.\n */\nexport interface VcShape extends Shape {\n vcType: VcShapeType;\n vcLabel: string;\n color?: string;\n link?: string;\n businessObject?: DiagramElement;\n}\n\nexport interface VcConnection extends Connection {\n vcType: ConnectionType;\n businessObject?: ChainConnection;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nexport function isVcShape(element: unknown): element is VcShape {\n return isObject(element) && (element['vcType'] === 'step' || element['vcType'] === 'orgUnit');\n}\n\nexport function isStep(element: unknown): element is VcShape & { vcType: 'step' } {\n return isObject(element) && element['vcType'] === 'step';\n}\n\nexport function isOrgUnit(element: unknown): element is VcShape & { vcType: 'orgUnit' } {\n return isObject(element) && element['vcType'] === 'orgUnit';\n}\n\nexport function isVcConnection(element: unknown): element is VcConnection {\n return (\n isObject(element) &&\n (element['vcType'] === 'sequence' ||\n element['vcType'] === 'hierarchy' ||\n element['vcType'] === 'assignment') &&\n 'waypoints' in element\n );\n}\n\nexport function isVcElement(element: unknown): element is VcShape | VcConnection {\n return isVcShape(element) || isVcConnection(element);\n}\n","import Diagram from 'diagram-js/lib/Diagram';\nimport type { ModuleDeclaration } from 'didi';\nimport type { CollaborativeModelerOptions } from '@miragon/modeler-api';\nimport type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { EventBusEventCallback } from 'diagram-js/lib/core/EventBus';\nimport {\n validateDocument,\n type Point,\n type ValueChainDocument,\n} from '@miragon/value-chain-schema-model';\nimport type VcBounds from './bounds/VcBounds.js';\nimport type VcImporter from './io/VcImporter.js';\nimport type VcExporter from './io/VcExporter.js';\nimport { saveSVG } from './io/saveSvg.js';\nimport type { ImportWarning } from './io/types.js';\nimport type VcLabelEditingProvider from './label-editing/VcLabelEditingProvider.js';\nimport { isVcElement } from './model/di-types.js';\n\n/**\n * `freeArea`, `fitOnImport` and `undoRedoKeys` as `@miragon/modeler-api` 1.2 names them:\n * `freeArea` is where Enter or Space on a creating palette entry places the element (the centre of\n * the canvas area the host's chrome leaves free, guide §5.5; default the centre of the visible\n * canvas), `fitOnImport: false` leaves the view after an import to the host, and\n * `undoRedoKeys: false` leaves Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z and Ctrl+Y to a host that owns the\n * history (the VS Code document).\n */\nexport interface VcViewerOptions extends CollaborativeModelerOptions {\n /** Host element. If missing, a detached <div> is created (attach later via attachTo). */\n container?: HTMLElement;\n width?: number | string;\n height?: number | string;\n /** Concatenated to the end of the module list (extension point). */\n additionalModules?: ModuleDeclaration[];\n /**\n * @deprecated Use `freeArea: { center }`; accepted until the next minor release. Given both,\n * `freeArea` wins.\n */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\ninterface CommandStackLike {\n clear(emit?: boolean): void;\n}\n\ninterface PopupMenuLike {\n close(): void;\n}\n\n/**\n * DI bootstrap and lifecycle shared by Viewer/NavigatedViewer/Modeler. The diagram is\n * created lazily on first access; `_getModules()` is a method (not a class field) to\n * avoid subclass field-initialization-order problems.\n */\nexport abstract class VcBaseViewer {\n protected abstract _getModules(): ModuleDeclaration[];\n\n private _diagram: Diagram | undefined;\n private readonly _container: HTMLElement;\n private readonly _options: VcViewerOptions;\n\n constructor(options: VcViewerOptions = {}) {\n this._options = options;\n this._container = this._createContainer(options);\n }\n\n get container(): HTMLElement {\n return this._container;\n }\n\n get<T>(name: string): T {\n return this._ensureDiagram().get<T>(name);\n }\n\n /** Like get(), but returns null instead of throwing when the service is absent. */\n getOptional<T>(name: string): T | null {\n return (this._ensureDiagram().get<T>(name, false) as T | null) ?? null;\n }\n\n on<T = unknown>(event: string, callback: EventBusEventCallback<T>, priority = 1000): void {\n this.get<EventBus>('eventBus').on(event, priority, callback as EventBusEventCallback<unknown>);\n }\n\n off<T = unknown>(event: string, callback: EventBusEventCallback<T>): void {\n this.get<EventBus>('eventBus').off(event, callback as EventBusEventCallback<unknown>);\n }\n\n /**\n * Replaces the current diagram contents and erases the undo history, silently: no\n * `commandStack.changed`, since an import is no edit a host should save. The document is\n * validated before the canvas is touched, so a rejected one leaves no trace; an open label edit\n * is taken down without committing and reopened afterwards when its element is still there.\n */\n importDocument(document: ValueChainDocument): ImportWarning[] {\n const valid = validateDocument(document);\n const labelEditing = this.getOptional<VcLabelEditingProvider>('vcLabelEditingProvider');\n const previous = this._currentDocument();\n labelEditing?.suspend();\n this.getOptional<PopupMenuLike>('popupMenu')?.close();\n let warnings: ImportWarning[];\n try {\n warnings = this._render(valid);\n } catch (error) {\n if (previous) {\n this._render(previous);\n }\n throw error;\n }\n labelEditing?.resumeAfterImport();\n return warnings;\n }\n\n exportDocument(): ValueChainDocument {\n return this.get<VcExporter>('vcExporter').export();\n }\n\n saveSVG(): { svg: string } {\n return saveSVG(this.get<Canvas>('canvas'), this.get<VcBounds>('vcBounds'));\n }\n\n /** Zooms to fit the diagram, never above 100%. */\n fitViewport(): void {\n const canvas = this.get<Canvas>('canvas');\n const hasContent = this.get<ElementRegistry>('elementRegistry').getAll().some(isVcElement);\n if (!hasContent) {\n return;\n }\n canvas.zoom('fit-viewport');\n if (canvas.zoom() > 1) {\n canvas.zoom(1);\n }\n }\n\n clear(): void {\n this.get<VcImporter>('vcImporter').clear();\n this.getOptional<CommandStackLike>('commandStack')?.clear();\n }\n\n attachTo(target: HTMLElement): void {\n this.detach();\n target.appendChild(this._container);\n this.get<Canvas>('canvas').resized();\n }\n\n detach(): void {\n this._container.parentNode?.removeChild(this._container);\n }\n\n destroy(): void {\n this._diagram?.destroy();\n this._diagram = undefined;\n this.detach();\n }\n\n private _render(document: ValueChainDocument): ImportWarning[] {\n const importer = this.get<VcImporter>('vcImporter');\n importer.clear();\n const warnings = importer.import(document);\n this.getOptional<CommandStackLike>('commandStack')?.clear(false);\n this.get<EventBus>('eventBus').fire('import.done', { warnings });\n return warnings;\n }\n\n private _currentDocument(): ValueChainDocument | undefined {\n try {\n return this.exportDocument();\n } catch {\n return undefined;\n }\n }\n\n private _createContainer(options: VcViewerOptions): HTMLElement {\n const container = options.container ?? document.createElement('div');\n container.classList.add('vc-container');\n container.style.width = sizeToCss(options.width ?? '100%');\n container.style.height = sizeToCss(options.height ?? (options.container ? '100%' : '600px'));\n return container;\n }\n\n private _ensureDiagram(): Diagram {\n if (!this._diagram) {\n const modules = [...this._getModules(), ...(this._options.additionalModules ?? [])];\n this._diagram = new Diagram({\n canvas: { container: this._container },\n modules,\n vcPalette: {\n freeArea: this._options.freeArea,\n freeRectCenter: this._options.freeRectCenter,\n },\n vcKeyboard: { undoRedoKeys: this._options.undoRedoKeys ?? true },\n vcImport: { fitOnImport: this._options.fitOnImport ?? true },\n });\n }\n return this._diagram;\n }\n}\n\nfunction sizeToCss(value: number | string): string {\n return typeof value === 'number' ? `${value}px` : value;\n}\n","import type ElementFactory from 'diagram-js/lib/core/ElementFactory';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport {\n DEFAULT_ORG_UNIT_SIZE,\n DEFAULT_STEP_SIZE,\n type ChainConnection,\n type DiagramElement,\n} from '@miragon/value-chain-schema-model';\nimport type { VcConnection, VcShape } from './di-types.js';\n\n/**\n * Domain-aware factory: builds diagram-js shapes/connections from schema-model elements\n * (import) and blank ones for palette/context-pad creation.\n */\nexport default class VcElementFactory {\n static $inject = ['elementFactory'];\n\n constructor(private readonly elementFactory: ElementFactory) {}\n\n createElement(element: DiagramElement): VcShape {\n return this.elementFactory.createShape({\n id: element.id,\n x: element.bounds.x,\n y: element.bounds.y,\n width: element.bounds.width,\n height: element.bounds.height,\n vcType: element.elementType,\n vcLabel: element.name,\n ...(element.color !== undefined ? { color: element.color } : {}),\n ...(element.elementType === 'step' && element.link !== undefined\n ? { link: element.link }\n : {}),\n businessObject: element,\n }) as VcShape;\n }\n\n createConnection(connection: ChainConnection, source: Shape, target: Shape): VcConnection {\n return this.elementFactory.createConnection({\n id: connection.id,\n source,\n target,\n waypoints: connection.waypoints.map((point) => ({ x: point.x, y: point.y })),\n vcType: connection.connectionType,\n businessObject: connection,\n }) as VcConnection;\n }\n\n /**\n * A blank step for interactive creation: no id/position — diagram-js assigns the id,\n * the create/auto-place interaction assigns the position.\n */\n createNewStep(label = ''): VcShape {\n return this.elementFactory.createShape({\n width: DEFAULT_STEP_SIZE.width,\n height: DEFAULT_STEP_SIZE.height,\n vcType: 'step',\n vcLabel: label,\n }) as VcShape;\n }\n\n /** A blank organizational unit for interactive creation. */\n createNewOrgUnit(label = ''): VcShape {\n return this.elementFactory.createShape({\n width: DEFAULT_ORG_UNIT_SIZE.width,\n height: DEFAULT_ORG_UNIT_SIZE.height,\n vcType: 'orgUnit',\n vcLabel: label,\n }) as VcShape;\n }\n}\n","import ElementFactory from 'diagram-js/lib/core/ElementFactory';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type { Connection, Label, Root, Shape } from 'diagram-js/lib/model/Types';\n\nconst ID_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';\nconst ID_LENGTH = 8;\n\n/** The id prefix of a new element: its value chain type where it has one. */\nconst PREFIXES: Readonly<Record<string, string>> = {\n step: 'step',\n orgUnit: 'org',\n sequence: 'sequence',\n hierarchy: 'hierarchy',\n assignment: 'assignment',\n};\n\nfunction randomSuffix(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(ID_LENGTH));\n return Array.from(bytes, (byte) => ID_ALPHABET[byte % ID_ALPHABET.length]).join('');\n}\n\n/**\n * Replaces the stock elementFactory: an element created on the canvas gets a random id (for\n * example `step_k3x9q2mf`), probed against the element registry. Two people editing one document\n * at the same time thus never create two elements with the same id, which a per-instance counter\n * (`shape_1` on both sides) would.\n */\nexport default class VcDiagramElementFactory extends ElementFactory {\n static $inject = ['elementRegistry'];\n\n constructor(private readonly elementRegistry: ElementRegistry) {\n super();\n }\n\n override create(type: 'root', attrs?: Partial<Root>): Root;\n override create(type: 'shape', attrs?: Partial<Shape>): Shape;\n override create(type: 'connection', attrs?: Partial<Connection>): Connection;\n override create(type: 'label', attrs?: Partial<Label>): Label;\n override create(\n type: 'root' | 'shape' | 'connection' | 'label',\n attrs?: Partial<Root & Shape & Connection & Label>,\n ): Root | Shape | Connection | Label {\n const withId = attrs?.id ? attrs : { ...attrs, id: this.unusedId(type, attrs) };\n switch (type) {\n case 'root':\n return super.create(type, withId);\n case 'shape':\n return super.create(type, withId);\n case 'connection':\n return super.create(type, withId);\n case 'label':\n return super.create(type, withId);\n }\n }\n\n private unusedId(type: string, attrs: Record<string, unknown> | undefined): string {\n const vcType = attrs?.['vcType'];\n const prefix = (typeof vcType === 'string' && PREFIXES[vcType]) || type;\n let id: string;\n do {\n id = `${prefix}_${randomSuffix()}`;\n } while (this.elementRegistry.get(id));\n return id;\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport VcElementFactory from './VcElementFactory.js';\nimport VcDiagramElementFactory from './VcDiagramElementFactory.js';\n\n/**\n * Domain-aware element creation (schema-model element → diagram-js element) plus an\n * elementFactory override with registry-probed id generation.\n */\nexport const vcModelModule: ModuleDeclaration = {\n elementFactory: ['type', VcDiagramElementFactory],\n vcElementFactory: ['type', VcElementFactory],\n};\n\nexport { default as VcElementFactory } from './VcElementFactory.js';\nexport { default as VcDiagramElementFactory } from './VcDiagramElementFactory.js';\nexport * from './di-types.js';\n","/**\n * Chevron (\"Blockpfeil\") geometry of a value chain step: flat top/bottom, a point on the\n * right and a matching notch cut into the left edge. Point/notch depth is half the height\n * (45° edges, the canonical ARIS/PowerPoint look), clamped so narrow steps don't degenerate.\n */\nexport function notchDepth(width: number, height: number): number {\n return Math.min(height / 2, 0.4 * width);\n}\n\n/** Shape-local chevron path for a step of the given size. */\nexport function chevronPath(width: number, height: number): string {\n return chevronPathAt(0, 0, width, height);\n}\n\n/**\n * Horizontal label inset. Less than the full notch depth: lines sit around the vertical\n * middle where the 45° notch/point edges leave `fontSize`-dependent extra room.\n */\nexport function labelInset(width: number, height: number): number {\n const depth = notchDepth(width, height);\n return Math.max(7, depth - 5);\n}\n\n/** Absolute chevron path, as consumed by diagram-js outline/cropping via getShapePath. */\nexport function chevronPathAt(x: number, y: number, width: number, height: number): string {\n const d = notchDepth(width, height);\n const my = y + height / 2;\n return [\n `M${x},${y}`,\n `L${x + width - d},${y}`,\n `L${x + width},${my}`,\n `L${x + width - d},${y + height}`,\n `L${x},${y + height}`,\n `L${x + d},${my}`,\n 'Z',\n ].join('');\n}\n\n/** Ellipse path (organizational unit), arc-based so cropping intersects exactly. */\nexport function ellipsePathAt(x: number, y: number, width: number, height: number): string {\n const rx = width / 2;\n const ry = height / 2;\n const cx = x + rx;\n return [\n `M${cx},${y}`,\n `A${rx},${ry} 0 0 1 ${cx},${y + height}`,\n `A${rx},${ry} 0 0 1 ${cx},${y}`,\n 'Z',\n ].join('');\n}\n","{\n \"$description\": \"AUTOMATISCH GENERIERT aus brand/tokens.json. Nicht von Hand ändern, sondern die Quelle bearbeiten und `npm run tokens:build` laufen lassen. Rollen (--cd-ui-*) je Modus, für Renderer, Exporte, Drift-Tests und Hosts. Renderer zeichnen und exportieren mit hell, dunkel kommt nur über CSS. hochkontrast enthält die Rollen, die sich bei data-cd-kontrast=\\\"hoch\\\" ändern. fest sind die Farben, die in beiden Modi gleich bleiben. shell sind die Maße und Ebenen der App-Shell der Modeler (Einpassen, Breakpoint, z-index), mit denselben Werten wie --cd-shell-* in der CSS.\",\n \"hell\": {\n \"--cd-ui-grund\": \"#F9F7F7\",\n \"--cd-ui-flaeche\": \"#FFFFFF\",\n \"--cd-ui-flaeche-hoch\": \"#FFFFFF\",\n \"--cd-ui-hover\": \"#EEF1FD\",\n \"--cd-ui-plot\": \"#FFFFFF\",\n \"--cd-ui-seite\": \"#FFFFFF\",\n \"--cd-ui-abschnitt\": \"#F9F7F7\",\n \"--cd-ui-linie\": \"#E6E2E2\",\n \"--cd-ui-kontur\": \"#8F8A8A\",\n \"--cd-ui-text\": \"#1D1D1D\",\n \"--cd-ui-text-leise\": \"#6B6666\",\n \"--cd-ui-link\": \"#2B50D4\",\n \"--cd-ui-icon-akzent\": \"#335DE5\",\n \"--cd-ui-fokus\": \"#2B50D4\",\n \"--cd-ui-interaktion\": \"#335DE5\",\n \"--cd-ui-success\": \"#00E676\",\n \"--cd-ui-warning\": \"#FFB000\",\n \"--cd-ui-danger\": \"#CD1839\",\n \"--cd-ui-info\": \"#335DE5\",\n \"--cd-ui-success-flaeche\": \"#DAFBEB\",\n \"--cd-ui-warning-flaeche\": \"#FFF1D2\",\n \"--cd-ui-danger-flaeche\": \"#FBEEF0\",\n \"--cd-ui-info-flaeche\": \"#EEF1FD\",\n \"--cd-ui-wortmarke\": \"#00E676\",\n \"--cd-ui-backdrop\": \"rgba(29, 29, 29, 0.42)\",\n \"--cd-ui-chrome-deckkraft\": \"84%\"\n },\n \"dunkel\": {\n \"--cd-ui-grund\": \"#1D1D1D\",\n \"--cd-ui-flaeche\": \"#282828\",\n \"--cd-ui-flaeche-hoch\": \"#2F2F2F\",\n \"--cd-ui-hover\": \"#383838\",\n \"--cd-ui-plot\": \"#1D1D1D\",\n \"--cd-ui-seite\": \"#1D1D1D\",\n \"--cd-ui-abschnitt\": \"#282828\",\n \"--cd-ui-linie\": \"#464646\",\n \"--cd-ui-kontur\": \"#8F8A8A\",\n \"--cd-ui-text\": \"#FFFFFF\",\n \"--cd-ui-text-leise\": \"#BBBBBB\",\n \"--cd-ui-link\": \"#00E676\",\n \"--cd-ui-icon-akzent\": \"#00E676\",\n \"--cd-ui-fokus\": \"#6B8AFF\",\n \"--cd-ui-interaktion\": \"#6B8AFF\",\n \"--cd-ui-success\": \"#00E676\",\n \"--cd-ui-warning\": \"#FFB000\",\n \"--cd-ui-danger\": \"#FB6D73\",\n \"--cd-ui-info\": \"#6B8AFF\",\n \"--cd-ui-success-flaeche\": \"#282828\",\n \"--cd-ui-warning-flaeche\": \"#282828\",\n \"--cd-ui-danger-flaeche\": \"#282828\",\n \"--cd-ui-info-flaeche\": \"#282828\",\n \"--cd-ui-wortmarke\": \"#FFFFFF\",\n \"--cd-ui-backdrop\": \"rgba(29, 29, 29, 0.6)\",\n \"--cd-ui-chrome-deckkraft\": \"100%\"\n },\n \"hochkontrast\": {\n \"hell\": {\n \"--cd-ui-linie\": \"#8F8A8A\",\n \"--cd-ui-kontur\": \"#1D1D1D\",\n \"--cd-ui-text-leise\": \"#1D1D1D\",\n \"--cd-ui-chrome-deckkraft\": \"100%\"\n },\n \"dunkel\": {\n \"--cd-ui-linie\": \"#8F8A8A\",\n \"--cd-ui-kontur\": \"#FFFFFF\",\n \"--cd-ui-text-leise\": \"#FFFFFF\",\n \"--cd-ui-chrome-deckkraft\": \"100%\"\n }\n },\n \"fest\": {\n \"--cd-blau\": \"#335DE5\",\n \"--cd-gruen\": \"#00E676\",\n \"--cd-grau\": \"#F9F7F7\",\n \"--cd-schwarz\": \"#1D1D1D\",\n \"--cd-weiss\": \"#FFFFFF\",\n \"--cd-blau-link\": \"#2B50D4\",\n \"--cd-blau-hell\": \"#6B8AFF\",\n \"--cd-success\": \"#00E676\",\n \"--cd-success-soft\": \"#DAFBEB\",\n \"--cd-success-hell\": \"#00E676\",\n \"--cd-warning\": \"#FFB000\",\n \"--cd-warning-soft\": \"#FFF1D2\",\n \"--cd-warning-hell\": \"#FFB000\",\n \"--cd-danger\": \"#CD1839\",\n \"--cd-danger-soft\": \"#FBEEF0\",\n \"--cd-danger-hell\": \"#FB6D73\",\n \"--cd-info\": \"#335DE5\",\n \"--cd-info-soft\": \"#EEF1FD\",\n \"--cd-info-hell\": \"#6B8AFF\",\n \"--cd-linie\": \"#E6E2E2\",\n \"--cd-kontur\": \"#8F8A8A\",\n \"--cd-text-leise\": \"#6B6666\"\n },\n \"shell\": {\n \"--cd-shell-rand\": \"12px\",\n \"--cd-shell-luecke\": \"8px\",\n \"--cd-shell-zeile\": \"40px\",\n \"--cd-shell-ziel\": \"32px\",\n \"--cd-shell-eintrag\": \"36px\",\n \"--cd-shell-frei\": \"64px\",\n \"--cd-shell-menue-breite\": \"248px\",\n \"--cd-shell-inspector-breite\": \"288px\",\n \"--cd-shell-einpassen-oben\": \"88px\",\n \"--cd-shell-einpassen-oben-schmal\": \"140px\",\n \"--cd-shell-einpassen-seite\": \"24px\",\n \"--cd-shell-einpassen-unten\": \"64px\",\n \"--cd-shell-einpassen-unten-web\": \"92px\",\n \"--cd-shell-schmal\": \"760px\",\n \"--cd-shell-sehr-schmal\": \"440px\",\n \"--cd-shell-niedrig\": \"820px\",\n \"--cd-shell-ebene-inseln\": \"20\",\n \"--cd-shell-ebene-inspector\": \"25\",\n \"--cd-shell-ebene-reihe\": \"30\",\n \"--cd-shell-ebene-aufklapper\": \"40\",\n \"--cd-shell-ebene-dialog\": \"50\",\n \"--cd-shell-ebene-toast\": \"60\"\n }\n}\n","import { hell } from '../theme/cd-tokens.generated.json';\n\n/**\n * Canvas colours, the light roles of the vendored design tokens (guide §10.1): contours,\n * connections and labels in the text role, element fills in the plot role. The renderer writes\n * them as presentation values, so exports look the same everywhere and stay light in every mode.\n */\nexport const COLORS = {\n ink: hell['--cd-ui-text'],\n fill: hell['--cd-ui-plot'],\n} as const;\n\n/**\n * The family goes onto every SVG text node, since SVG text does not inherit the container's font\n * (guide §4). \"Geist Variable\" is the name `@fontsource-variable/geist` registers; the hosts load\n * it, and an exported SVG opened elsewhere falls back to \"Geist\" or a system sans.\n */\nexport const FONT = {\n family: \"'Geist Variable', 'Geist', ui-sans-serif, system-ui, sans-serif\",\n size: 12,\n lineHeight: 1.2,\n} as const;\n\nexport const STROKE_WIDTH = 2;\n\nexport const LABEL_PADDING = 7;\n\n/** Accent colors offered by the color picker (stroke + label tint; fill stays white). */\nexport const COLOR_OPTIONS: ReadonlyArray<{ label: string; color?: string }> = [\n { label: 'Default' },\n { label: 'Blue', color: 'hsl(205, 100%, 45%)' },\n { label: 'Green', color: 'hsl(150, 86%, 34%)' },\n { label: 'Orange', color: 'hsl(29, 89%, 44%)' },\n { label: 'Red', color: 'hsl(360, 100%, 45%)' },\n { label: 'Purple', color: 'hsl(287, 65%, 44%)' },\n];\n","import BaseRenderer from 'diagram-js/lib/draw/BaseRenderer';\nimport TextUtil from 'diagram-js/lib/util/Text';\nimport { createLine } from 'diagram-js/lib/util/RenderUtil';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type GraphicsFactory from 'diagram-js/lib/core/GraphicsFactory';\nimport type { Connection, Element, Shape } from 'diagram-js/lib/model/Types';\nimport { append as svgAppend, attr as svgAttr, create as svgCreate } from 'tiny-svg';\nimport { chevronPath, chevronPathAt, ellipsePathAt, labelInset } from './geometry.js';\nimport { COLORS, FONT, LABEL_PADDING, STROKE_WIDTH } from './styles.js';\nimport {\n isOrgUnit,\n isVcConnection,\n isVcShape,\n type VcConnection,\n type VcShape,\n} from '../model/di-types.js';\n\n/** BaseRenderer default is 1000; 1500 wins the render.shape/render.connection event. */\nconst VC_RENDER_PRIORITY = 1500;\n\n/** Arrowhead geometry mirrors the bpmn-js sequence flow marker. */\nconst ARROW_PATH = 'M 1 5 L 11 10 L 1 15 Z';\n\nlet rendererInstances = 0;\n\nexport default class VcRenderer extends BaseRenderer {\n static $inject = ['eventBus', 'elementRegistry', 'graphicsFactory'];\n\n private readonly textUtil = new TextUtil({\n style: {\n fontFamily: FONT.family,\n fontSize: FONT.size,\n fontWeight: 'normal',\n lineHeight: FONT.lineHeight,\n },\n });\n\n /** Unique per instance so marker ids never collide across diagrams on one page. */\n private readonly markerSuffix = `${(rendererInstances += 1)}`;\n\n constructor(\n eventBus: EventBus,\n private readonly elementRegistry: ElementRegistry,\n private readonly graphicsFactory: GraphicsFactory,\n ) {\n super(eventBus, VC_RENDER_PRIORITY);\n this.relayoutLabelsWhenTheFontArrives(eventBus);\n }\n\n /**\n * A label drawn before the web font arrived was measured in the fallback font: its lines sit off\n * centre, and may wrap differently, once the font renders. Such labels are laid out again then.\n */\n private relayoutLabelsWhenTheFontArrives(eventBus: EventBus): void {\n const fonts = typeof document === 'undefined' ? undefined : document.fonts;\n const font = `${FONT.size}px ${FONT.family}`;\n if (!fonts || fonts.check(font)) {\n return;\n }\n let destroyed = false;\n eventBus.on('diagram.destroy', () => {\n destroyed = true;\n });\n fonts.load(font).then(\n (faces) => {\n if (destroyed || faces.length === 0) {\n return;\n }\n for (const element of this.elementRegistry.getAll()) {\n if (isVcShape(element) && element.vcLabel) {\n this.graphicsFactory.update(\n 'shape',\n element,\n this.elementRegistry.getGraphics(element),\n );\n }\n }\n },\n () => undefined,\n );\n }\n\n override canRender(element: Element): boolean {\n return isVcShape(element) || isVcConnection(element);\n }\n\n override drawShape(visuals: SVGElement, element: Shape): SVGElement {\n const shape = element as VcShape;\n const stroke = shape.color ?? COLORS.ink;\n const orgUnit = isOrgUnit(shape);\n\n const path = svgCreate('path');\n svgAttr(path, {\n d: orgUnit\n ? ellipsePathAt(0, 0, shape.width, shape.height)\n : chevronPath(shape.width, shape.height),\n fill: COLORS.fill,\n stroke,\n 'stroke-width': STROKE_WIDTH,\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round',\n });\n svgAppend(visuals, path);\n\n if (shape.vcLabel) {\n const inset = orgUnit ? LABEL_PADDING + 5 : labelInset(shape.width, shape.height);\n const label = this.textUtil.createText(shape.vcLabel, {\n box: { width: shape.width, height: shape.height },\n align: 'center-middle',\n padding: {\n top: LABEL_PADDING,\n bottom: LABEL_PADDING,\n left: inset,\n right: inset,\n },\n style: { fill: stroke },\n });\n svgAppend(visuals, label);\n }\n\n return path;\n }\n\n override drawConnection(visuals: SVGElement, element: Connection): SVGElement {\n const connection = element as VcConnection;\n const stroke = COLORS.ink;\n\n const attrs: Record<string, string | number> = {\n stroke,\n 'stroke-width': STROKE_WIDTH,\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round',\n fill: 'none',\n };\n if (connection.vcType === 'sequence') {\n attrs['stroke-dasharray'] = '8, 5';\n }\n // assignments (org unit ↔ step) are plain lines without an arrowhead\n if (connection.vcType !== 'assignment') {\n const svg = visuals.ownerSVGElement;\n if (svg) {\n attrs['marker-end'] = this.arrowMarker(svg, stroke);\n }\n }\n\n const line = createLine(connection.waypoints, attrs);\n svgAppend(visuals, line);\n return line;\n }\n\n override getShapePath(shape: Shape): string {\n if (isOrgUnit(shape)) {\n return ellipsePathAt(shape.x, shape.y, shape.width, shape.height);\n }\n return chevronPathAt(shape.x, shape.y, shape.width, shape.height);\n }\n\n override getConnectionPath(connection: Connection): string {\n const [first, ...rest] = connection.waypoints;\n if (!first) {\n return '';\n }\n return `M${first.x},${first.y}${rest.map((point) => `L${point.x},${point.y}`).join('')}`;\n }\n\n private arrowMarker(svg: SVGSVGElement, color: string): string {\n const id = `vc-arrow-${this.markerSuffix}-${color.replace(/[^a-zA-Z0-9]/g, '')}`;\n if (!svg.querySelector(`marker[id=\"${id}\"]`)) {\n let defs = svg.querySelector('defs');\n if (!defs) {\n defs = svgCreate('defs') as SVGDefsElement;\n svgAppend(svg, defs);\n }\n const marker = svgCreate('marker');\n svgAttr(marker, {\n id,\n viewBox: '0 0 20 20',\n refX: 11,\n refY: 10,\n markerWidth: 10,\n markerHeight: 10,\n orient: 'auto',\n });\n const arrow = svgCreate('path');\n svgAttr(arrow, {\n d: ARROW_PATH,\n fill: color,\n stroke: color,\n 'stroke-width': 1,\n 'stroke-linejoin': 'round',\n });\n svgAppend(marker, arrow);\n svgAppend(defs, marker);\n }\n return `url(#${id})`;\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport VcRenderer from './VcRenderer.js';\n\n/** SVG rendering of value chain steps and connections (BaseRenderer subclass). */\nexport const vcDrawModule: ModuleDeclaration = {\n __init__: ['vcRenderer'],\n vcRenderer: ['type', VcRenderer],\n};\n\nexport { default as VcRenderer } from './VcRenderer.js';\nexport { chevronPath, chevronPathAt, ellipsePathAt, notchDepth } from './geometry.js';\nexport { COLORS, COLOR_OPTIONS, FONT } from './styles.js';\n","import type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { getBBox } from 'diagram-js/lib/util/Elements';\nimport type { Bounds } from '@miragon/value-chain-schema-model';\nimport { isVcElement, isVcShape } from '../model/di-types.js';\n\n/**\n * The extent of the diagram's content: every step, org unit and connection (waypoints included).\n * One source for the import's fit, the SVG export's frame and a host's fit, which pass their own\n * margin.\n */\nexport default class VcBounds {\n static $inject = ['elementRegistry'];\n\n constructor(private readonly elementRegistry: ElementRegistry) {}\n\n /** No step and no org unit on the canvas. */\n isEmpty(): boolean {\n return !this.elementRegistry.getAll().some(isVcShape);\n }\n\n /** The tight bounds of the content grown by `padding` on every side; undefined while empty. */\n contentBounds(padding = 0): Bounds | undefined {\n if (this.isEmpty()) {\n return undefined;\n }\n const elements = this.elementRegistry.filter(isVcElement) as Element[];\n const { x, y, width, height } = getBBox(elements);\n return {\n x: x - padding,\n y: y - padding,\n width: width + 2 * padding,\n height: height + 2 * padding,\n };\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport VcBounds from './VcBounds.js';\n\n/** Content bounds of the diagram (import fit, SVG export, a host's fit). */\nexport const vcBoundsModule: ModuleDeclaration = {\n vcBounds: ['type', VcBounds],\n};\n\nexport { default as VcBounds } from './VcBounds.js';\n","/** The id of the canvas root; the schema reserves it (RESERVED_IDS), so no element can take it. */\nexport const ROOT_ID = 'vc-root';\n\nexport interface ImportWarning {\n message: string;\n connectionId?: string;\n}\n\n/** Document-level data kept on the root element while editing. */\nexport interface RootBusinessObject {\n name: string;\n /** The document's fields beyond the schema, written back on export. */\n extensions?: Record<string, unknown>;\n /** The meta fields beyond the schema, written back on export. */\n metaExtensions?: Record<string, unknown>;\n}\n","import type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementFactory from 'diagram-js/lib/core/ElementFactory';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Root, Shape } from 'diagram-js/lib/model/Types';\nimport {\n documentExtensions,\n metaExtensions,\n type ValueChainDocument,\n} from '@miragon/value-chain-schema-model';\nimport type VcBounds from '../bounds/VcBounds.js';\nimport type VcElementFactory from '../model/VcElementFactory.js';\nimport { isVcConnection, isVcShape } from '../model/di-types.js';\nimport { ROOT_ID, type ImportWarning, type RootBusinessObject } from './types.js';\n\n/** The margin around the content when an import fits the view, in diagram units. */\nconst FIT_PADDING = 20;\n\n/**\n * diagram-js reads its zoom back rounded to three decimals: a fit below 0.0005 would read back as\n * zoom 0 and a NaN viewbox. Content wider than about a thousand viewports shows its centre here.\n */\nconst SMALLEST_FIT_ZOOM = 0.001;\n\ntype DiagramRoot = Root & { businessObject?: RootBusinessObject };\n\nexport interface VcImportConfig {\n /** Fit the view to the content after every import (default true); false leaves it to the host. */\n fitOnImport?: boolean | undefined;\n}\n\n/**\n * Renders a validated value chain document onto the canvas. Deliberately bypasses the command\n * stack — importing must not create undo entries.\n */\nexport default class VcImporter {\n static $inject = [\n 'canvas',\n 'elementFactory',\n 'vcElementFactory',\n 'elementRegistry',\n 'eventBus',\n 'vcBounds',\n 'config.vcImport',\n ];\n\n constructor(\n private readonly canvas: Canvas,\n private readonly elementFactory: ElementFactory,\n private readonly vcElementFactory: VcElementFactory,\n private readonly elementRegistry: ElementRegistry,\n private readonly eventBus: EventBus,\n private readonly vcBounds: VcBounds,\n private readonly config: VcImportConfig | undefined,\n ) {}\n\n import(document: ValueChainDocument): ImportWarning[] {\n const warnings: ImportWarning[] = [];\n this.eventBus.fire('import.render.start', { document });\n\n const root = this.diagramRoot();\n root.businessObject = {\n name: document.meta.name,\n extensions: documentExtensions(document),\n metaExtensions: metaExtensions(document.meta),\n };\n\n const shapeById = new Map<string, Shape>();\n for (const element of document.elements) {\n const shape = this.vcElementFactory.createElement(element);\n this.canvas.addShape(shape, root);\n shapeById.set(element.id, shape);\n }\n\n let connectionIndex = 0;\n for (const connection of document.connections) {\n const source = shapeById.get(connection.source);\n const target = shapeById.get(connection.target);\n if (!source || !target) {\n warnings.push({\n message: `Skipped connection \"${connection.id}\": unresolved endpoint.`,\n connectionId: connection.id,\n });\n continue;\n }\n const element = this.vcElementFactory.createConnection(connection, source, target);\n // Insert connections at the front of the children so they paint behind the steps.\n this.canvas.addConnection(element, root, connectionIndex);\n connectionIndex += 1;\n }\n\n if (this.config?.fitOnImport !== false) {\n this.fitToContent();\n }\n this.eventBus.fire('import.render.done', { document, warnings });\n return warnings;\n }\n\n /** Removes all imported elements and document meta, tolerating elements already gone. */\n clear(): void {\n const roots = new Set<unknown>(this.canvas.getRootElements());\n for (const element of [...this.elementRegistry.getAll()]) {\n if (roots.has(element)) {\n if (element.id === ROOT_ID) {\n element.businessObject = undefined;\n }\n continue;\n }\n try {\n if (isVcConnection(element)) {\n this.canvas.removeConnection(element);\n } else if (isVcShape(element)) {\n this.canvas.removeShape(element);\n }\n } catch {\n // already removed along with a previous element\n }\n }\n }\n\n /**\n * The diagram's root, created on the first import. Any other root goes: diagram-js creates an\n * implicit one whenever something asks for the root before the first import (an export, a\n * palette create), and it would otherwise stay behind in the registry.\n */\n private diagramRoot(): DiagramRoot {\n let root = this.elementRegistry.get(ROOT_ID) as DiagramRoot | undefined;\n if (!root) {\n root = this.elementFactory.createRoot({ id: ROOT_ID }) as DiagramRoot;\n this.canvas.setRootElement(root);\n }\n for (const other of this.canvas.getRootElements()) {\n if (other !== root) {\n this.canvas.removeRootElement(other);\n }\n }\n return root;\n }\n\n /**\n * Centres the content at the largest zoom that shows all of it, never above 100% (guide §5.9),\n * so the same document always opens in the same view; an empty diagram shows its origin at\n * 100%. Hosts with chrome of their own refit with their insets afterwards.\n */\n private fitToContent(): void {\n const { width, height } = this.canvas.getSize();\n if (!(width > 0 && height > 0)) {\n return;\n }\n const bounds = this.vcBounds.contentBounds(FIT_PADDING);\n if (!bounds) {\n this.canvas.viewbox({ x: 0, y: 0, width, height });\n return;\n }\n const scale = Math.max(\n Math.min(width / bounds.width, height / bounds.height, 1),\n SMALLEST_FIT_ZOOM,\n );\n this.canvas.viewbox({\n x: bounds.x + bounds.width / 2 - width / 2 / scale,\n y: bounds.y + bounds.height / 2 - height / 2 / scale,\n width: width / scale,\n height: height / scale,\n });\n }\n}\n","import type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport {\n CURRENT_SCHEMA_VERSION,\n connectionExtensions,\n elementExtensions,\n validateDocument,\n type ChainConnection,\n type DiagramElement,\n type ValueChainDocument,\n} from '@miragon/value-chain-schema-model';\nimport { isVcConnection, isVcShape } from '../model/di-types.js';\nimport { ROOT_ID, type RootBusinessObject } from './types.js';\n\n/**\n * Rebuilds a schema-model document from the live diagram. The diagram-js element\n * properties are the source of truth; businessObject backfills what the UI cannot edit:\n * a step's `link` and every field beyond the schema (vendor extensions), which the\n * export writes back unchanged.\n */\nexport default class VcExporter {\n static $inject = ['elementRegistry'];\n\n constructor(private readonly elementRegistry: ElementRegistry) {}\n\n export(): ValueChainDocument {\n const elements: DiagramElement[] = [];\n const connections: ChainConnection[] = [];\n\n for (const element of this.elementRegistry.getAll()) {\n if (element.id === ROOT_ID) {\n continue;\n }\n if (isVcConnection(element)) {\n if (!element.source || !element.target) {\n continue;\n }\n const imported = element.businessObject;\n connections.push({\n ...(imported ? connectionExtensions(imported) : {}),\n id: element.id,\n connectionType: element.vcType,\n source: element.source.id,\n target: element.target.id,\n waypoints: element.waypoints.map((point) => ({ x: point.x, y: point.y })),\n });\n } else if (isVcShape(element)) {\n const imported = element.businessObject;\n const extensions = imported ? elementExtensions(imported) : {};\n const bounds = {\n x: element.x,\n y: element.y,\n width: element.width,\n height: element.height,\n };\n const color = element.color !== undefined ? { color: element.color } : {};\n if (element.vcType === 'orgUnit') {\n elements.push({\n ...extensions,\n id: element.id,\n elementType: 'orgUnit',\n name: element.vcLabel,\n bounds,\n ...color,\n });\n } else {\n const link =\n element.link ?? (imported?.elementType === 'step' ? imported.link : undefined);\n elements.push({\n ...extensions,\n id: element.id,\n elementType: 'step',\n name: element.vcLabel,\n bounds,\n ...color,\n ...(link !== undefined ? { link } : {}),\n });\n }\n }\n }\n\n const root = this.rootData();\n\n return validateDocument({\n ...root?.extensions,\n schemaVersion: CURRENT_SCHEMA_VERSION,\n meta: { ...root?.metaExtensions, name: root?.name ?? 'Untitled value chain' },\n elements,\n connections,\n });\n }\n\n /** Read without `canvas.getRootElement()`, which would create an implicit root before import. */\n private rootData(): RootBusinessObject | undefined {\n const root = this.elementRegistry.get(ROOT_ID) as\n { businessObject?: RootBusinessObject } | undefined;\n return root?.businessObject;\n }\n}\n","import { COLORS } from '../draw/styles.js';\n\n/**\n * Rasterizes an exported SVG (`saveSVG`) to a PNG at `scale` × its size, on the diagram's white\n * fill, so a PNG looks like the SVG in every viewer and stays light in every mode.\n */\nexport async function svgToPng(svg: string, scale = 2): Promise<Blob> {\n const { width, height } = svgSize(svg);\n const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));\n try {\n const image = new Image();\n image.width = width;\n image.height = height;\n await new Promise<void>((resolve, reject) => {\n image.onload = () => resolve();\n image.onerror = () => reject(new Error('Could not render the SVG.'));\n image.src = url;\n });\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(width * scale);\n canvas.height = Math.round(height * scale);\n const context = canvas.getContext('2d');\n if (!context) throw new Error('Canvas 2D context not available.');\n context.fillStyle = COLORS.fill;\n context.fillRect(0, 0, canvas.width, canvas.height);\n context.drawImage(image, 0, 0, canvas.width, canvas.height);\n const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/png'));\n if (!blob) throw new Error('PNG generation failed.');\n return blob;\n } finally {\n URL.revokeObjectURL(url);\n }\n}\n\nfunction svgSize(svg: string): { width: number; height: number } {\n const width = /width=\"(\\d+(?:\\.\\d+)?)\"/.exec(svg);\n const height = /height=\"(\\d+(?:\\.\\d+)?)\"/.exec(svg);\n return { width: width ? Number(width[1]) : 1000, height: height ? Number(height[1]) : 700 };\n}\n\n/** Blob -> Base64 (without the data-URL prefix), e.g. to post it to a VS Code extension host. */\nexport function blobToBase64(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(String(reader.result).split(',')[1] ?? '');\n reader.onerror = () => reject(new Error('Could not read the export blob.'));\n reader.readAsDataURL(blob);\n });\n}\n","import type { ModuleDeclaration } from 'didi';\nimport { vcBoundsModule } from '../bounds/index.js';\nimport VcImporter from './VcImporter.js';\nimport VcExporter from './VcExporter.js';\n\n/** Document import/export between schema-model and the canvas. */\nexport const ioModule: ModuleDeclaration = {\n __depends__: [vcBoundsModule],\n vcImporter: ['type', VcImporter],\n vcExporter: ['type', VcExporter],\n};\n\nexport { default as VcImporter, type VcImportConfig } from './VcImporter.js';\nexport { default as VcExporter } from './VcExporter.js';\nexport { saveSVG } from './saveSvg.js';\nexport { svgToPng, blobToBase64 } from './png.js';\nexport { ROOT_ID, type ImportWarning, type RootBusinessObject } from './types.js';\n","import type { ModuleDeclaration } from 'didi';\nimport { VcBaseViewer } from './VcBaseViewer.js';\nimport { vcModelModule } from './model/index.js';\nimport { vcDrawModule } from './draw/index.js';\nimport { ioModule } from './io/index.js';\n\n/** Read-only rendering of value chain documents. */\nexport class Viewer extends VcBaseViewer {\n protected _getModules(): ModuleDeclaration[] {\n return [vcModelModule, vcDrawModule, ioModule];\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport SelectionModule from 'diagram-js/lib/features/selection';\nimport ZoomScrollModule from 'diagram-js/lib/navigation/zoomscroll';\nimport MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas';\nimport { Viewer } from './Viewer.js';\n\n/** Viewer plus canvas navigation (zoom, pan, selection). */\nexport class NavigatedViewer extends Viewer {\n protected override _getModules(): ModuleDeclaration[] {\n return [...super._getModules(), SelectionModule, ZoomScrollModule, MoveCanvasModule];\n }\n}\n","import type { Element } from 'diagram-js/lib/model/Types';\n\nexport interface UpdatePropertiesContext {\n element: Element;\n properties: Record<string, unknown>;\n oldProperties?: Record<string, unknown>;\n}\n\n/**\n * Generic undoable property update: `execute` remembers the previous values,\n * `revert` restores them. Returned elements trigger `elements.changed` → re-render.\n */\nexport default class UpdatePropertiesHandler {\n execute(context: UpdatePropertiesContext): Element[] {\n const { element, properties } = context;\n const target = element as unknown as Record<string, unknown>;\n const old: Record<string, unknown> = {};\n for (const key of Object.keys(properties)) {\n old[key] = target[key];\n setOrDelete(target, key, properties[key]);\n }\n context.oldProperties = old;\n return [element];\n }\n\n revert(context: UpdatePropertiesContext): Element[] {\n const { element, oldProperties } = context;\n const target = element as unknown as Record<string, unknown>;\n if (oldProperties) {\n for (const key of Object.keys(oldProperties)) {\n setOrDelete(target, key, oldProperties[key]);\n }\n }\n return [element];\n }\n}\n\nfunction setOrDelete(target: Record<string, unknown>, key: string, value: unknown): void {\n if (value === undefined) {\n delete target[key];\n } else {\n target[key] = value;\n }\n}\n","import type CommandStack from 'diagram-js/lib/command/CommandStack';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport UpdatePropertiesHandler from './cmd/UpdatePropertiesHandler.js';\nimport type { VcConnection, VcShape } from '../model/di-types.js';\n\nconst UPDATE_PROPERTIES = 'element.updateProperties';\n\n/** High-level undoable domain mutations; everything funnels through one command. */\nexport default class VcModeling {\n static $inject = ['commandStack'];\n\n constructor(private readonly commandStack: CommandStack) {\n commandStack.registerHandler(UPDATE_PROPERTIES, UpdatePropertiesHandler);\n }\n\n updateProperties(element: Element, properties: Record<string, unknown>): void {\n this.commandStack.execute(UPDATE_PROPERTIES, { element, properties });\n }\n\n updateLabel(element: VcShape, label: string): void {\n if (label === element.vcLabel) {\n return;\n }\n this.updateProperties(element, { vcLabel: label });\n }\n\n setColor(element: VcShape, color: string | undefined): void {\n if (color === element.color) {\n return;\n }\n this.updateProperties(element, { color });\n }\n\n /** Re-routing happens in the same undo step via VcConnectionTypeBehavior. */\n setConnectionType(connection: VcConnection, type: ConnectionType): void {\n if (type === connection.vcType) {\n return;\n }\n this.updateProperties(connection, { vcType: type });\n }\n}\n","import BaseLayouter from 'diagram-js/lib/layout/BaseLayouter';\nimport type CroppingConnectionDocking from 'diagram-js/lib/layout/CroppingConnectionDocking';\nimport { getMid } from 'diagram-js/lib/layout/LayoutUtil';\nimport {\n connectPoints,\n connectRectangles,\n withoutRedundantPoints,\n} from 'diagram-js/lib/layout/ManhattanLayout';\nimport type { Connection, Shape } from 'diagram-js/lib/model/Types';\nimport type { Point } from 'diagram-js/lib/util/Types';\nimport { notchDepth } from '../draw/geometry.js';\n\n/** Horizontal distance of the column trunk from the leftmost sub-step. */\nconst TRUNK_MARGIN = 25;\n\n/**\n * Minimum gap between the center exit and the leftmost sub-step for the trunk to run\n * straight down under the exit (kink-free column).\n */\nexport const TRUNK_CLEARANCE = 10;\n\n/** Minimum stub length below the parent before the bus/trunk elbow. */\nconst BUS_MIN_STUB = 10;\n\n/** Keeps the drop-span boundary away from the parent's corners/point. */\nconst EXIT_MARGIN = 10;\n\nexport interface VcLayoutHints {\n source?: Shape;\n target?: Shape;\n connectionStart?: Point;\n connectionEnd?: Point;\n waypoints?: Point[];\n}\n\n/**\n * Connection routing:\n * - sequence (\"ist Vorgänger von\"): straight line, user bendpoints survive re-layouts;\n * - hierarchy (\"ist prozessorientiert übergeordnet\"): always re-routed orthogonally\n * (ARIS cascade look — down from the parent, across, down into the sub-step).\n * Both are cropped at the chevron contour via the renderer's getShapePath.\n */\nexport default class VcLayouter extends BaseLayouter {\n static $inject = ['connectionDocking'];\n\n constructor(private readonly connectionDocking: CroppingConnectionDocking) {\n super();\n }\n\n override layoutConnection(connection: Connection, hints: VcLayoutHints = {}): Point[] {\n const source = hints.source ?? (connection.source as Shape | undefined);\n const target = hints.target ?? (connection.target as Shape | undefined);\n if (!source || !target) {\n return connection.waypoints?.map((point) => ({ x: point.x, y: point.y })) ?? [];\n }\n\n const waypoints = isHierarchy(connection)\n ? this.hierarchyWaypoints(source, target, hints)\n : this.sequenceWaypoints(connection, source, target, hints);\n\n const stub = { ...connection, source, target, waypoints } as Connection;\n let result = waypoints;\n try {\n result = this.connectionDocking.getCroppedWaypoints(stub, source, target);\n } catch {\n // fall through to the uncropped waypoints\n }\n\n // Non-finite coordinates (e.g. anchors adjusted against degenerate zero-size old\n // bounds, see diagram-js AttachUtil.getNewAttachPoint) must never reach the model:\n // once a waypoint is NaN, every handle/bendpoint render throws. Fall back to a\n // plain mid-to-mid line in that case.\n if (!allFinite(result)) {\n const fallback = [getMid(source), getMid(target)];\n return allFinite(fallback) ? fallback : [];\n }\n return result;\n }\n\n /**\n * Straight line between the shape mids, cropped to the contours afterwards.\n * The connectionStart/End anchor hints diagram-js passes on move (old cropped\n * waypoint + delta) are ignored on purpose: such a point can land in the chevron's\n * notch cutout where cropping finds no intersection, leaving the arrowhead hidden\n * behind the shape. Mid-to-mid always crops reliably; user bendpoints survive.\n */\n private sequenceWaypoints(\n connection: Connection,\n source: Shape,\n target: Shape,\n hints: VcLayoutHints,\n ): Point[] {\n const interior = (hints.waypoints ?? connection.waypoints ?? [])\n .slice(1, -1)\n .map((point) => ({ x: point.x, y: point.y }));\n return [getMid(source), ...interior, getMid(target)];\n }\n\n /**\n * Adaptive hierarchy routing. Every edge exits the parent at its BOTTOM CENTER;\n * the sub-steps' arrangement picks how it continues:\n * - horizontal row (aligned tops / single child under the parent's span): down to a\n * shared bus halfway to the children, across, and down into each sub-step's top;\n * - vertical column (ARIS rake, the default): straight down under the exit whenever\n * all children sit right of the center (no kink), otherwise via a bus to a shared\n * trunk left of all children; then a horizontal arm into each left notch.\n * Anchor hints are ignored on purpose: hierarchy edges always re-route from the\n * current geometry.\n */\n private hierarchyWaypoints(source: Shape, target: Shape, _hints: VcLayoutHints): Point[] {\n const sourceMid = getMid(source);\n const targetMid = getMid(target);\n\n if (target.y >= source.y + source.height) {\n const children = hierarchyChildren(source);\n const group = children.length ? children : [target];\n\n if (isRowArrangement(group, source)) {\n return withoutRedundantPoints(connectPoints(sourceMid, targetMid, 'v:v'));\n }\n\n const bottom = source.y + source.height;\n const topmost = Math.min(...group.map((child) => child.y));\n const busY = Math.max(bottom + BUS_MIN_STUB, (bottom + topmost) / 2);\n const minChildX = Math.min(...group.map((child) => child.x));\n const trunkX =\n sourceMid.x <= minChildX - TRUNK_CLEARANCE ? sourceMid.x : minChildX - TRUNK_MARGIN;\n return withoutRedundantPoints([\n sourceMid,\n { x: sourceMid.x, y: busY },\n { x: trunkX, y: busY },\n { x: trunkX, y: targetMid.y },\n targetMid,\n ]);\n }\n\n return withoutRedundantPoints(\n connectRectangles(source, target, sourceMid, targetMid, { preferredLayouts: ['v:v'] }),\n );\n }\n}\n\n/**\n * The x range of the parent's bottom edge in which a sub-step's hierarchy edge is\n * drawn as a straight vertical drop (row notation) instead of the rake.\n */\nexport function hierarchyDropSpan(source: Shape): { min: number; max: number } {\n return {\n min: source.x + EXIT_MARGIN,\n max: source.x + source.width - notchDepth(source.width, source.height) - EXIT_MARGIN,\n };\n}\n\n/** All sub-steps connected to the given step via hierarchy edges. */\nexport function hierarchyChildren(source: Shape): Shape[] {\n return (source.outgoing ?? [])\n .filter((connection) => isHierarchy(connection))\n .map((connection) => connection.target as Shape)\n .filter((target): target is Shape => !!target);\n}\n\n/**\n * A horizontal row: several children with aligned tops, or a single child sitting\n * inside the parent's drop span. Shared by routing and auto-placement so both always\n * agree on the arrangement.\n */\nexport function isRowArrangement(children: Shape[], source: Shape): boolean {\n if (!children.length) {\n return false;\n }\n if (children.length >= 2) {\n const tops = children.map((child) => child.y);\n return Math.max(...tops) - Math.min(...tops) <= ROW_TOLERANCE_Y;\n }\n const child = children[0]!;\n const centerX = child.x + child.width / 2;\n const span = hierarchyDropSpan(source);\n return centerX >= span.min && centerX <= span.max;\n}\n\n/** Row detection tolerance for \"aligned tops\". */\nconst ROW_TOLERANCE_Y = 10;\n\nfunction isHierarchy(connection: Connection): boolean {\n return (connection as { vcType?: string }).vcType === 'hierarchy';\n}\n\nfunction allFinite(points: Point[]): boolean {\n return points.every((point) => Number.isFinite(point.x) && Number.isFinite(point.y));\n}\n","import CommandInterceptor from 'diagram-js/lib/command/CommandInterceptor';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type Modeling from 'diagram-js/lib/features/modeling/Modeling';\nimport type { Connection } from 'diagram-js/lib/model/Types';\nimport { isVcConnection } from '../model/di-types.js';\n\ninterface UpdatePropertiesContext {\n element?: unknown;\n properties?: Record<string, unknown>;\n}\n\n/**\n * Switching a connection's type changes its routing (straight/dashed vs rake).\n * Re-layout nested inside the updateProperties command, so type change and new\n * route form a single undo step.\n */\nexport default class VcConnectionTypeBehavior extends CommandInterceptor {\n static override $inject = ['eventBus', 'modeling'];\n\n constructor(eventBus: EventBus, modeling: Modeling) {\n super(eventBus);\n\n this.postExecute(\n ['element.updateProperties'],\n (context: UpdatePropertiesContext) => {\n const { element, properties } = context;\n if (properties && 'vcType' in properties && isVcConnection(element)) {\n modeling.layoutConnection(element as Connection);\n }\n },\n true,\n );\n }\n}\n","import CommandInterceptor from 'diagram-js/lib/command/CommandInterceptor';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type Modeling from 'diagram-js/lib/features/modeling/Modeling';\nimport type { Connection, Shape } from 'diagram-js/lib/model/Types';\nimport type { Point } from 'diagram-js/lib/util/Types';\nimport type VcLayouter from './VcLayouter.js';\nimport { isVcConnection, isVcShape } from '../model/di-types.js';\n\ninterface CommandContext {\n shape?: unknown;\n shapes?: unknown[];\n elements?: unknown[];\n connection?: unknown;\n}\n\n/**\n * Hierarchy routing depends on the whole sibling group (row vs column), but diagram-js\n * only re-layouts the edges of the shape that moved. This behavior re-layouts ALL\n * hierarchy edges of every affected parent — nested into the triggering command, so\n * arrangement flips stay one undo step and no sibling keeps a stale route.\n */\nexport default class VcHierarchyRelayoutBehavior extends CommandInterceptor {\n static override $inject = ['eventBus', 'modeling', 'layouter'];\n\n constructor(\n eventBus: EventBus,\n private readonly modeling: Modeling,\n private readonly layouter: VcLayouter,\n ) {\n super(eventBus);\n\n this.postExecuted(\n ['shape.move', 'elements.move', 'shape.resize', 'connection.create', 'connection.delete'],\n (context: CommandContext) => this.relayoutAffected(context),\n true,\n );\n }\n\n private relayoutAffected(context: CommandContext): void {\n const shapes = [context.shape, ...(context.shapes ?? []), ...(context.elements ?? [])].filter(\n isVcShape,\n );\n\n const connection = context.connection;\n const parents = new Set<Shape>();\n\n if (isVcConnection(connection) && connection.vcType === 'hierarchy' && connection.source) {\n parents.add(connection.source as Shape);\n }\n\n for (const shape of shapes) {\n if (hierarchyEdges(shape as Shape).length) {\n parents.add(shape as Shape);\n }\n for (const incoming of (shape as Shape).incoming ?? []) {\n if (isVcConnection(incoming) && incoming.vcType === 'hierarchy' && incoming.source) {\n parents.add(incoming.source as Shape);\n }\n }\n }\n\n for (const parent of parents) {\n for (const edge of hierarchyEdges(parent)) {\n const fresh = this.layouter.layoutConnection(edge);\n if (!sameWaypoints(fresh, edge.waypoints ?? [])) {\n this.modeling.layoutConnection(edge);\n }\n }\n }\n }\n}\n\nfunction hierarchyEdges(shape: Shape): Connection[] {\n return ((shape.outgoing ?? []) as Connection[]).filter(\n (connection) => isVcConnection(connection) && connection.vcType === 'hierarchy',\n );\n}\n\nfunction sameWaypoints(a: Point[], b: Point[]): boolean {\n return (\n a.length === b.length &&\n a.every((point, index) => point.x === b[index]!.x && point.y === b[index]!.y)\n );\n}\n","import type { ModuleDeclaration } from 'didi';\nimport CroppingConnectionDocking from 'diagram-js/lib/layout/CroppingConnectionDocking';\nimport VcModeling from './VcModeling.js';\nimport VcLayouter from './VcLayouter.js';\nimport VcConnectionTypeBehavior from './VcConnectionTypeBehavior.js';\nimport VcHierarchyRelayoutBehavior from './VcHierarchyRelayoutBehavior.js';\n\n/**\n * Domain mutations + connection layout. Overrides the stock `layouter` and registers\n * `connectionDocking` (also consumed by bendpoints and connection previews).\n */\nexport const vcModelingModule: ModuleDeclaration = {\n __init__: ['vcModeling', 'vcConnectionTypeBehavior', 'vcHierarchyRelayoutBehavior'],\n vcModeling: ['type', VcModeling],\n vcConnectionTypeBehavior: ['type', VcConnectionTypeBehavior],\n vcHierarchyRelayoutBehavior: ['type', VcHierarchyRelayoutBehavior],\n layouter: ['type', VcLayouter],\n connectionDocking: ['type', CroppingConnectionDocking],\n};\n\nexport { default as VcModeling } from './VcModeling.js';\nexport {\n default as VcLayouter,\n hierarchyDropSpan,\n hierarchyChildren,\n isRowArrangement,\n} from './VcLayouter.js';\nexport { default as VcConnectionTypeBehavior } from './VcConnectionTypeBehavior.js';\nexport { default as VcHierarchyRelayoutBehavior } from './VcHierarchyRelayoutBehavior.js';\n","import RuleProvider from 'diagram-js/lib/features/rules/RuleProvider';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport {\n isOrgUnit,\n isStep,\n isVcConnection,\n isVcShape,\n type VcConnection,\n type VcShape,\n} from '../model/di-types.js';\nimport type VcConnect from '../connect/VcConnect.js';\n\ninterface ConnectContext {\n source?: Element;\n target?: Element;\n connection?: Element;\n}\n\nexport default class VcRules extends RuleProvider {\n static override $inject = ['eventBus', 'vcConnect'];\n\n constructor(\n eventBus: EventBus,\n private readonly vcConnect: VcConnect,\n ) {\n super(eventBus);\n }\n\n override init(): void {\n this.addRule('connection.start', (context: ConnectContext) => isVcShape(context.source));\n\n this.addRule('connection.create', (context: ConnectContext) => {\n const { source, target } = context;\n const type = this.resolveType(source, target);\n if (!type || hasConnection(source as VcShape, target as VcShape, type)) {\n return false;\n }\n return { vcType: type };\n });\n\n this.addRule('connection.reconnect', (context: ConnectContext) => {\n const { source, target, connection } = context;\n if (!isVcConnection(connection) || !isVcShape(source) || !isVcShape(target)) {\n return false;\n }\n if (source === target || !endpointsAllowed(connection.vcType, source, target)) {\n return false;\n }\n return !hasConnection(source, target, connection.vcType, connection);\n });\n\n this.addRule('connection.updateWaypoints', (context: ConnectContext) =>\n isVcConnection(context.connection),\n );\n\n // Elements live directly on the root — no containment.\n this.addRule('shape.create', (context: { target?: Element }) => isRoot(context.target));\n this.addRule('elements.create', (context: { target?: Element }) => isRoot(context.target));\n\n this.addRule(['shape.move', 'elements.move'], () => true);\n this.addRule('shape.resize', (context: { shape?: Element }) => isVcShape(context.shape));\n\n this.addRule(['elements.align', 'elements.distribute'], (context: { elements?: Element[] }) =>\n (context.elements ?? []).filter(isVcShape),\n );\n }\n\n /**\n * The relation type follows from the endpoint kinds: step→step uses the pending\n * connect type, an org unit on either end always yields an assignment.\n */\n private resolveType(\n source: Element | undefined,\n target: Element | undefined,\n ): ConnectionType | null {\n if (!isVcShape(source) || !isVcShape(target) || source === target) {\n return null;\n }\n if (isStep(source) && isStep(target)) {\n const pending = this.vcConnect.pendingType;\n return pending === 'assignment' ? null : pending;\n }\n if ((isStep(source) && isOrgUnit(target)) || (isOrgUnit(source) && isStep(target))) {\n return 'assignment';\n }\n return null;\n }\n}\n\nfunction isRoot(element: Element | undefined): boolean {\n return !!element && !isVcShape(element) && !isVcConnection(element) && !element.parent;\n}\n\nfunction endpointsAllowed(type: ConnectionType, source: VcShape, target: VcShape): boolean {\n if (type === 'assignment') {\n return (isStep(source) && isOrgUnit(target)) || (isOrgUnit(source) && isStep(target));\n }\n return isStep(source) && isStep(target);\n}\n\nfunction hasConnection(\n source: VcShape,\n target: VcShape,\n type: ConnectionType,\n ignore?: VcConnection,\n): boolean {\n const links = [\n ...(source.outgoing ?? []),\n ...(type === 'assignment' ? (source.incoming ?? []) : []),\n ];\n return links.some(\n (connection) =>\n connection !== ignore &&\n isVcConnection(connection) &&\n connection.vcType === type &&\n (connection.target === target || connection.source === target),\n );\n}\n","import type { ModuleDeclaration } from 'didi';\nimport RulesModule from 'diagram-js/lib/features/rules';\nimport VcRules from './VcRules.js';\n\nexport const vcRulesModule: ModuleDeclaration = {\n __depends__: [RulesModule],\n __init__: ['vcRules'],\n vcRules: ['type', VcRules],\n};\n\nexport { default as VcRules } from './VcRules.js';\n","import type Connect from 'diagram-js/lib/features/connect/Connect';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport type { VcShape } from '../model/di-types.js';\n\n/**\n * Typed wrapper around the diagram-js connect interaction. The rule provider reads\n * `pendingType` while a connect/create drag is running to stamp the right connection\n * type; it resets to the default once the interaction is over.\n */\nexport default class VcConnect {\n static $inject = ['connect', 'eventBus'];\n\n pendingType: ConnectionType = 'sequence';\n\n constructor(\n private readonly connect: Connect,\n eventBus: EventBus,\n ) {\n eventBus.on(['connect.cleanup', 'create.cleanup', 'global-connect.cleanup'], () => {\n this.pendingType = 'sequence';\n });\n }\n\n start(event: MouseEvent | Event, source: VcShape, type: ConnectionType): void {\n this.pendingType = type;\n this.connect.start(event as MouseEvent, source);\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport ConnectModule from 'diagram-js/lib/features/connect';\nimport VcConnect from './VcConnect.js';\n\nexport const vcConnectModule: ModuleDeclaration = {\n __depends__: [ConnectModule],\n __init__: ['vcConnect'],\n vcConnect: ['type', VcConnect],\n};\n\nexport { default as VcConnect } from './VcConnect.js';\n","import type AutoPlace from 'diagram-js/lib/features/auto-place/AutoPlace';\nimport type Create from 'diagram-js/lib/features/create/Create';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport type VcElementFactory from '../model/VcElementFactory.js';\nimport type VcConnect from '../connect/VcConnect.js';\nimport type { VcShape } from '../model/di-types.js';\n\n/**\n * Append interactions à la bpmn.io: click places the new element automatically\n * (auto-place, label editing opens via the label-editing provider); dragging places\n * it manually with a live connection preview. `assignment` appends an organizational\n * unit; the other types append a step.\n */\nexport default class VcAppend {\n static $inject = ['autoPlace', 'create', 'vcElementFactory', 'vcConnect'];\n\n constructor(\n private readonly autoPlace: AutoPlace,\n private readonly create: Create,\n private readonly factory: VcElementFactory,\n private readonly vcConnect: VcConnect,\n ) {}\n\n append(source: VcShape, type: ConnectionType): Shape {\n this.vcConnect.pendingType = type;\n const newShape = this.autoPlace.append(source as Shape, this.createShape(type) as Shape, {\n connection: { vcType: type },\n }) as Shape;\n this.vcConnect.pendingType = 'sequence';\n return newShape;\n }\n\n startAppendDrag(event: Event, source: VcShape, type: ConnectionType): void {\n this.vcConnect.pendingType = type;\n this.create.start(event as MouseEvent, this.createShape(type) as Shape, {\n source: source as Shape,\n });\n }\n\n private createShape(type: ConnectionType): VcShape {\n return type === 'assignment' ? this.factory.createNewOrgUnit() : this.factory.createNewStep();\n }\n}\n","import type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport type { Point } from 'diagram-js/lib/util/Types';\nimport { isVcShape, type VcShape } from '../model/di-types.js';\nimport { hierarchyChildren, isRowArrangement, TRUNK_CLEARANCE } from '../modeling/VcLayouter.js';\nimport type VcConnect from '../connect/VcConnect.js';\n\n/** Runs before the diagram-js default (priority 100). */\nconst BEFORE_DEFAULT = 200;\n\nconst SEQUENCE_GAP_X = 45;\nconst HIERARCHY_GAP_Y = 45;\n\nconst SIBLING_GAP_Y = 30;\nconst SIBLING_GAP_X = 20;\nconst DECONFLICT_STEP_Y = 30;\nconst DECONFLICT_MARGIN = 10;\n\n/**\n * Placement of appended steps:\n * - sequence: to the right of the source (reading direction),\n * - hierarchy: follows the existing arrangement of the parent's sub-steps — a\n * horizontal row keeps growing to the right, a vertical column (ARIS rake,\n * the default) keeps growing downwards.\n * All placements nudge downwards until the spot is free of other steps.\n */\nexport default class VcAutoPlaceBehavior {\n static $inject = ['eventBus', 'vcConnect', 'elementRegistry'];\n\n constructor(eventBus: EventBus, vcConnect: VcConnect, elementRegistry: ElementRegistry) {\n eventBus.on(\n 'autoPlace',\n BEFORE_DEFAULT,\n (context: { source: Shape; shape: Shape }): Point | undefined => {\n const { source, shape } = context;\n if (!isVcShape(source)) {\n return undefined;\n }\n\n const desired = this.desiredPosition(vcConnect.pendingType, source, shape);\n return this.deconflict(desired, shape);\n },\n );\n\n this.elementRegistry = elementRegistry;\n }\n\n private readonly elementRegistry: ElementRegistry;\n\n private desiredPosition(type: string, source: VcShape, shape: Shape): Point {\n if (type === 'hierarchy') {\n return this.hierarchyPosition(source, shape);\n }\n if (type === 'assignment') {\n return this.assignmentPosition(source, shape);\n }\n return this.sequencePosition(source, shape);\n }\n\n private sequencePosition(source: VcShape, shape: Shape): Point {\n return {\n x: source.x + source.width + SEQUENCE_GAP_X + shape.width / 2,\n y: source.y + source.height / 2,\n };\n }\n\n /** Organizational units sit centered below their step (Wikipedia notation). */\n private assignmentPosition(source: VcShape, shape: Shape): Point {\n return {\n x: source.x + source.width / 2,\n y: source.y + source.height + HIERARCHY_GAP_Y + shape.height / 2,\n };\n }\n\n private hierarchyPosition(source: VcShape, shape: Shape): Point {\n const children = hierarchyChildren(source);\n if (!children.length) {\n return {\n x: source.x + source.width / 2 + TRUNK_CLEARANCE + shape.width / 2,\n y: source.y + source.height + HIERARCHY_GAP_Y + shape.height / 2,\n };\n }\n\n if (isRowArrangement(children, source)) {\n const anchor = rightmost(children)!;\n return {\n x: anchor.x + anchor.width + SIBLING_GAP_X + shape.width / 2,\n y: anchor.y + shape.height / 2,\n };\n }\n\n const anchor = bottommost(children)!;\n return {\n x: anchor.x + shape.width / 2,\n y: anchor.y + anchor.height + SIBLING_GAP_Y + shape.height / 2,\n };\n }\n\n /** Nudges the position downwards until the new shape overlaps no existing step. */\n private deconflict(position: Point, shape: Shape): Point {\n const steps = this.elementRegistry.getAll().filter(isVcShape);\n const candidate = { ...position };\n for (let attempt = 0; attempt < 50; attempt += 1) {\n const bounds = {\n x: candidate.x - shape.width / 2 - DECONFLICT_MARGIN,\n y: candidate.y - shape.height / 2 - DECONFLICT_MARGIN,\n width: shape.width + DECONFLICT_MARGIN * 2,\n height: shape.height + DECONFLICT_MARGIN * 2,\n };\n const conflict = steps.some(\n (step) =>\n step.x < bounds.x + bounds.width &&\n step.x + step.width > bounds.x &&\n step.y < bounds.y + bounds.height &&\n step.y + step.height > bounds.y,\n );\n if (!conflict) {\n break;\n }\n candidate.y += DECONFLICT_STEP_Y;\n }\n return candidate;\n }\n}\n\nfunction rightmost(shapes: Shape[]): Shape | undefined {\n return shapes.reduce<Shape | undefined>(\n (best, shape) => (!best || shape.x + shape.width > best.x + best.width ? shape : best),\n undefined,\n );\n}\n\nfunction bottommost(shapes: Shape[]): Shape | undefined {\n return shapes.reduce<Shape | undefined>(\n (best, shape) => (!best || shape.y + shape.height > best.y + best.height ? shape : best),\n undefined,\n );\n}\n","import type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport { getMid } from 'diagram-js/lib/layout/LayoutUtil';\n\ninterface ConnectionPreviewLike {\n drawPreview(context: object, canConnect: unknown, hints: object): void;\n cleanUp(context: object): void;\n}\n\ninterface CreateEvent {\n x: number;\n y: number;\n context: {\n source?: Shape;\n shape?: Shape;\n canExecute?: boolean | { connect?: unknown };\n };\n}\n\n/** Drag-append UX: live connection preview from the source while dragging a new step. */\nexport default class VcCreatePreviewBehavior {\n static $inject = ['injector', 'eventBus'];\n\n constructor(injector: { get<T>(name: string, strict: boolean): T | null }, eventBus: EventBus) {\n const connectionPreview = injector.get<ConnectionPreviewLike>('connectionPreview', false);\n if (!connectionPreview) {\n return;\n }\n\n eventBus.on('create.move', (event: CreateEvent) => {\n const { context } = event;\n const source = context.source;\n if (!source) {\n return;\n }\n const canConnect =\n typeof context.canExecute === 'object' ? context.canExecute?.connect : false;\n // noCropping: there is no positioned target shape yet, and cropping against an\n // undefined target would throw inside CroppingConnectionDocking.\n connectionPreview.drawPreview(context, canConnect ?? false, {\n source,\n connectionStart: getMid(source),\n connectionEnd: { x: event.x, y: event.y },\n noCropping: true,\n });\n });\n\n eventBus.on(['create.end', 'create.cancel', 'create.cleanup'], (event: CreateEvent) => {\n connectionPreview.cleanUp(event.context);\n });\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport AutoPlaceModule from 'diagram-js/lib/features/auto-place';\nimport CreateModule from 'diagram-js/lib/features/create';\nimport ConnectionPreviewModule from 'diagram-js/lib/features/connection-preview';\nimport VcAppend from './VcAppend.js';\nimport VcAutoPlaceBehavior from './VcAutoPlaceBehavior.js';\nimport VcCreatePreviewBehavior from './VcCreatePreviewBehavior.js';\n\nexport const vcAppendModule: ModuleDeclaration = {\n __depends__: [AutoPlaceModule, CreateModule, ConnectionPreviewModule],\n __init__: ['vcAutoPlaceBehavior', 'vcCreatePreviewBehavior'],\n vcAppend: ['type', VcAppend],\n vcAutoPlaceBehavior: ['type', VcAutoPlaceBehavior],\n vcCreatePreviewBehavior: ['type', VcCreatePreviewBehavior],\n};\n\nexport { default as VcAppend } from './VcAppend.js';\n","/*! @miragon/value-chain-renderer icon geometry\n * Lucide (lucide-static 1.59.0) @license ISC\n * Copyright (c) 2026 Lucide Icons and Contributors\n * Derived from Feather, as Lucide's LICENSE lists them: trash and x. Feather @license MIT\n * Copyright (c) 2013-present Cole Bemis */\n\n/*\n * The Lucide icons of the palette tools, the context pad and the shortcuts dialog, copied\n * unchanged from `icon-nodes.json` so the renderer has no icon runtime dependency. Renderers\n * never import the modeler shell, so they cannot take its copy.\n */\nexport const LUCIDE = {\n 'square-dashed-mouse-pointer':\n '<path d=\"M12.034 12.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.943l-3.444 1.068a1 1 0 0 0-.66.66l-1.067 3.443a.5.5 0 0 1-.943.033z\"/>' +\n '<path d=\"M5 3a2 2 0 0 0-2 2\"/><path d=\"M19 3a2 2 0 0 1 2 2\"/><path d=\"M5 21a2 2 0 0 1-2-2\"/>' +\n '<path d=\"M9 3h1\"/><path d=\"M9 21h2\"/><path d=\"M14 3h1\"/><path d=\"M3 9v1\"/>' +\n '<path d=\"M21 9v2\"/><path d=\"M3 14v1\"/>',\n hand:\n '<path d=\"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2\"/>' +\n '<path d=\"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2\"/>' +\n '<path d=\"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8\"/>' +\n '<path d=\"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15\"/>',\n 'unfold-horizontal':\n '<path d=\"M16 12h6\"/><path d=\"M8 12H2\"/><path d=\"M12 2v2\"/><path d=\"M12 8v2\"/>' +\n '<path d=\"M12 14v2\"/><path d=\"M12 20v2\"/><path d=\"m19 15 3-3-3-3\"/><path d=\"m5 9-3 3 3 3\"/>',\n workflow:\n '<rect width=\"8\" height=\"8\" x=\"3\" y=\"3\" rx=\"2\"/><path d=\"M7 11v4a2 2 0 0 0 2 2h4\"/>' +\n '<rect width=\"8\" height=\"8\" x=\"13\" y=\"13\" rx=\"2\"/>',\n palette:\n '<path d=\"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z\"/>' +\n '<circle cx=\"13.5\" cy=\"6.5\" r=\".5\" fill=\"currentColor\"/>' +\n '<circle cx=\"17.5\" cy=\"10.5\" r=\".5\" fill=\"currentColor\"/>' +\n '<circle cx=\"6.5\" cy=\"12.5\" r=\".5\" fill=\"currentColor\"/>' +\n '<circle cx=\"8.5\" cy=\"7.5\" r=\".5\" fill=\"currentColor\"/>',\n trash:\n '<path d=\"M10 11v6\"/><path d=\"M14 11v6\"/><path d=\"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6\"/>' +\n '<path d=\"M3 6h18\"/><path d=\"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\"/>',\n 'arrow-left-right':\n '<path d=\"M8 3 4 7l4 4\"/><path d=\"M4 7h16\"/><path d=\"m16 21 4-4-4-4\"/><path d=\"M20 17H4\"/>',\n 'align-start-vertical':\n '<rect width=\"9\" height=\"6\" x=\"6\" y=\"14\" rx=\"2\"/><rect width=\"16\" height=\"6\" x=\"6\" y=\"4\" rx=\"2\"/>' +\n '<path d=\"M2 2v20\"/>',\n x: '<path d=\"M18 6 6 18\"/><path d=\"m6 6 12 12\"/>',\n} as const;\n\nexport type LucideIconName = keyof typeof LUCIDE;\n\nexport interface LucideIconOptions {\n /** Rendered width and height in px. */\n size: number;\n /** Stroke width on the 24 grid. */\n strokeWidth: number;\n}\n\n/**\n * Guide §11: chrome icons are 16px at stroke 2.5 and palette tools 20px at stroke 2, both\n * 1.67px on screen. `currentColor`, so the surrounding role (rest, hover, pressed) decides.\n */\nexport const CHROME_ICON: LucideIconOptions = { size: 16, strokeWidth: 2.5 };\nexport const PALETTE_TOOL_ICON: LucideIconOptions = { size: 20, strokeWidth: 2 };\n\nexport function lucideIcon(name: LucideIconName, options: LucideIconOptions = CHROME_ICON): string {\n return (\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${options.size}\" height=\"${options.size}\" ` +\n `viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"${options.strokeWidth}\" ` +\n `stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">` +\n `${LUCIDE[name]}</svg>`\n );\n}\n","import { CHROME_ICON, PALETTE_TOOL_ICON, lucideIcon } from './lucide.js';\nimport { COLORS } from './styles.js';\n\n/**\n * Notation glyphs of the context pad (append and connect): the value chain's own shapes and\n * relations, which Lucide has no icon for. Drawn on the 24 grid like Lucide and set at the\n * chrome size, so they weigh the same as the Lucide icons next to them.\n */\nfunction glyph(content: string, viewBox = '0 0 24 24'): string {\n return (\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${CHROME_ICON.size}\" height=\"${CHROME_ICON.size}\" ` +\n `viewBox=\"${viewBox}\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"${CHROME_ICON.strokeWidth}\" ` +\n `stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">${content}</svg>`\n );\n}\n\n/**\n * Palette previews of the creating entries (guide §5.5): the shape as the canvas draws it,\n * white with the ink contour, so the palette shows what it creates.\n */\nfunction preview(content: string): string {\n return (\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" ` +\n `fill=\"${COLORS.fill}\" stroke=\"${COLORS.ink}\" stroke-width=\"1.5\" stroke-linecap=\"round\" ` +\n `stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">${content}</svg>`\n );\n}\n\n/** Chevron used wherever a step is depicted (matches the canvas shape). */\nconst CHEVRON = 'M3 7 h12 l6 5 -6 5 H3 l4.5 -5 Z';\n\nexport const ICONS = {\n handTool: lucideIcon('hand', PALETTE_TOOL_ICON),\n lassoTool: lucideIcon('square-dashed-mouse-pointer', PALETTE_TOOL_ICON),\n spaceTool: lucideIcon('unfold-horizontal', PALETTE_TOOL_ICON),\n globalConnect: lucideIcon('workflow', PALETTE_TOOL_ICON),\n createStep: preview(`<path d=\"${CHEVRON}\"/>`),\n createOrgUnit: preview('<ellipse cx=\"12\" cy=\"12\" rx=\"9.5\" ry=\"6.5\"/>'),\n appendStep: glyph(\n '<path d=\"M2.5 12 h4.5 m-2 -2 2 2 -2 2\" stroke-dasharray=\"2.6 2\"/>' +\n '<path d=\"M9 7 h8 l4 5 -4 5 H9 l3 -5 Z\"/>',\n ),\n appendSubStep: glyph(\n '<path d=\"M7 3 v8.5 h2.5\" />' +\n '<path d=\"M11 7 h7.5 l3 4.5 -3 4.5 H11 l2.5 -4.5 Z\" transform=\"translate(-1.5 0.5)\"/>',\n '0 0 22 22',\n ),\n connectSequence: glyph(\n '<path d=\"M4 19 L17.5 5.5\" stroke-dasharray=\"3 2.6\"/><path d=\"M13 5 h5.5 v5.5\" />',\n ),\n connectHierarchy: glyph('<path d=\"M6 4 v14 h11.5 m-3.5 -3.5 3.5 3.5 -3.5 3.5\"/>'),\n appendOrgUnit: glyph('<path d=\"M12 3.5 v5\"/><ellipse cx=\"12\" cy=\"15\" rx=\"8.5\" ry=\"5.5\"/>'),\n toggleType: lucideIcon('arrow-left-right'),\n align: lucideIcon('align-start-vertical'),\n color: lucideIcon('palette'),\n trash: lucideIcon('trash'),\n} as const;\n\n/** No native `title`: the palette's tooltip (diagram-js or a host's chrome) names the entry. */\nexport function paletteEntryHtml(iconSvg: string, draggable = false): string {\n return (\n `<div class=\"entry vc-palette-entry\"${draggable ? ' draggable=\"true\"' : ''}>` +\n `${iconSvg}</div>`\n );\n}\n\nexport function contextPadEntryHtml(iconSvg: string, draggable = false): string {\n return `<div class=\"entry vc-cp-entry\"${draggable ? ' draggable=\"true\"' : ''}>${iconSvg}</div>`;\n}\n","import type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type Palette from 'diagram-js/lib/features/palette/Palette';\nimport type PaletteProvider from 'diagram-js/lib/features/palette/PaletteProvider';\nimport type Create from 'diagram-js/lib/features/create/Create';\nimport type HandTool from 'diagram-js/lib/features/hand-tool/HandTool';\nimport type LassoTool from 'diagram-js/lib/features/lasso-tool/LassoTool';\nimport type SpaceTool from 'diagram-js/lib/features/space-tool/SpaceTool';\nimport type GlobalConnect from 'diagram-js/lib/features/global-connect/GlobalConnect';\nimport type Modeling from 'diagram-js/lib/features/modeling/Modeling';\nimport type Selection from 'diagram-js/lib/features/selection/Selection';\nimport type { Element, Shape } from 'diagram-js/lib/model/Types';\nimport type { FreeArea, FreeAreaInsets } from '@miragon/modeler-api';\nimport type { Point } from '@miragon/value-chain-schema-model';\nimport type VcElementFactory from '../model/VcElementFactory.js';\nimport { isVcShape, type VcShape } from '../model/di-types.js';\nimport { ICONS, paletteEntryHtml } from '../draw/icons.js';\n\ninterface PaletteEntry {\n group: string;\n html?: string;\n title?: string;\n shortcut?: string;\n action?: Record<string, (event: Event) => void>;\n}\n\nexport interface VcPaletteConfig {\n /**\n * The canvas area the host's chrome leaves free: Enter or Space on a creating entry places the\n * element in its centre (guide §5.5). Without it, or while its centre is undefined, the element\n * lands in the centre of the visible canvas.\n */\n freeArea?: FreeArea | undefined;\n /** @deprecated Use `freeArea: { center }`. Given both, `freeArea` wins. */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\ninterface DirectEditingLike {\n activate(element: Element): boolean;\n}\n\ninterface EditLock {\n isReadOnly(): boolean;\n}\n\n/** Guide §5.5: a keyboard-created element lands this far down-right of one already centred there. */\nconst KEYBOARD_CREATE_OFFSET = 24;\n\n/**\n * Tools first (Lasso, Hand, Space, Connect), then the creating entries. Tool entry keys end in\n * `-tool` in the group `tools`, so the active tool gets highlighted. Titles and shortcuts are\n * separate fields, so a tooltip shows the key as a chip.\n */\nexport default class VcPaletteProvider {\n static $inject = [\n 'palette',\n 'create',\n 'vcElementFactory',\n 'handTool',\n 'lassoTool',\n 'spaceTool',\n 'globalConnect',\n 'canvas',\n 'modeling',\n 'selection',\n 'elementRegistry',\n 'injector',\n 'config.vcPalette',\n ];\n\n constructor(\n palette: Palette,\n private readonly create: Create,\n private readonly factory: VcElementFactory,\n private readonly handTool: HandTool,\n private readonly lassoTool: LassoTool,\n private readonly spaceTool: SpaceTool,\n private readonly globalConnect: GlobalConnect,\n private readonly canvas: Canvas,\n private readonly modeling: Modeling,\n private readonly selection: Selection,\n private readonly elementRegistry: ElementRegistry,\n private readonly injector: { get<T>(name: string, strict?: boolean): T | null },\n private readonly config: VcPaletteConfig | undefined,\n ) {\n palette.registerProvider(this as unknown as PaletteProvider);\n }\n\n getPaletteEntries(): Record<string, PaletteEntry> {\n const creator = (newShape: () => VcShape) => (event: Event) => {\n if (this.editLock()?.isReadOnly()) {\n return;\n }\n const shape = newShape();\n if (isKeyboardClick(event)) {\n this.placeInFreeRect(shape);\n return;\n }\n this.create.start(event as MouseEvent, shape as Shape);\n };\n const createStep = creator(() => this.factory.createNewStep());\n const createOrgUnit = creator(() => this.factory.createNewOrgUnit());\n\n return {\n 'lasso-tool': {\n group: 'tools',\n title: 'Lasso',\n shortcut: 'L',\n html: paletteEntryHtml(ICONS.lassoTool),\n action: { click: (event) => this.lassoTool.activateSelection(event as MouseEvent, false) },\n },\n 'hand-tool': {\n group: 'tools',\n title: 'Hand',\n shortcut: 'H',\n html: paletteEntryHtml(ICONS.handTool),\n action: { click: (event) => this.handTool.activateHand(event as MouseEvent, false, false) },\n },\n 'space-tool': {\n group: 'tools',\n title: 'Create or remove space',\n shortcut: 'S',\n html: paletteEntryHtml(ICONS.spaceTool),\n action: {\n click: (event) => this.spaceTool.activateSelection(event as MouseEvent, false, false),\n },\n },\n 'global-connect-tool': {\n group: 'tools',\n title: 'Connect',\n shortcut: 'C',\n html: paletteEntryHtml(ICONS.globalConnect),\n action: { click: (event) => this.globalConnect.start(event as MouseEvent, false) },\n },\n 'create.step': {\n group: 'value-chain',\n title: 'Step',\n html: paletteEntryHtml(ICONS.createStep, true),\n action: { click: createStep, dragstart: createStep },\n },\n 'create.org-unit': {\n group: 'value-chain',\n title: 'Organizational unit',\n html: paletteEntryHtml(ICONS.createOrgUnit, true),\n action: { click: createOrgUnit, dragstart: createOrgUnit },\n },\n };\n }\n\n /**\n * Enter or Space on a creating entry (guide §5.5): diagram-js's create follows the pointer and\n * never ends without one, so the element goes straight to the centre of the free rectangle,\n * selected, with the focus on the canvas and its label editor open.\n */\n private placeInFreeRect(shape: VcShape): void {\n const centre = this.freeAreaCentre() ?? this.visibleCentre();\n const position = { x: centre.x, y: centre.y };\n while (this.centreTaken(position)) {\n position.x += KEYBOARD_CREATE_OFFSET;\n position.y += KEYBOARD_CREATE_OFFSET;\n }\n const created = this.modeling.createShape(\n shape as Shape,\n position,\n this.canvas.getRootElement() as Shape,\n );\n this.selection.select(created);\n this.canvas.focus();\n this.injector.get<DirectEditingLike>('directEditing', false)?.activate(created);\n }\n\n private freeAreaCentre(): Point | undefined {\n const area = this.config?.freeArea;\n if (area?.center) return area.center();\n if (area?.insets) return this.centreWithin(area.insets());\n return this.config?.freeRectCenter?.();\n }\n\n /** The centre of the container without `insets`, in diagram coordinates, as a fit centres. */\n private centreWithin(insets: FreeAreaInsets): Point | undefined {\n const { width, height } = this.canvas.getSize();\n if (!(width > 0 && height > 0)) return undefined;\n // An axis the insets leave no room on centres in the whole container instead.\n const middle = (size: number, start: number, end: number): number =>\n start + end < size ? start + (size - start - end) / 2 : size / 2;\n const { x, y, scale } = this.canvas.viewbox();\n return {\n x: x + middle(width, insets.left, insets.right) / scale,\n y: y + middle(height, insets.top, insets.bottom) / scale,\n };\n }\n\n private visibleCentre(): Point {\n const { x, y, width, height } = this.canvas.viewbox();\n return { x: x + width / 2, y: y + height / 2 };\n }\n\n private centreTaken(point: Point): boolean {\n return this.elementRegistry\n .filter(isVcShape)\n .some(\n (element) =>\n Math.abs(element.x + element.width / 2 - point.x) < 1 &&\n Math.abs(element.y + element.height / 2 - point.y) < 1,\n );\n }\n\n private editLock(): EditLock | null {\n return this.injector.get<EditLock>('vcReadOnly', false);\n }\n}\n\n/** The click a host's chrome synthesises for Enter or Space on an entry: no pointer, detail 0. */\nfunction isKeyboardClick(event: Event): boolean {\n return event.type === 'click' && (event as MouseEvent).detail === 0;\n}\n","import type { ModuleDeclaration } from 'didi';\nimport PaletteModule from 'diagram-js/lib/features/palette';\nimport CreateModule from 'diagram-js/lib/features/create';\nimport HandToolModule from 'diagram-js/lib/features/hand-tool';\nimport LassoToolModule from 'diagram-js/lib/features/lasso-tool';\nimport SpaceToolModule from 'diagram-js/lib/features/space-tool';\nimport GlobalConnectModule from 'diagram-js/lib/features/global-connect';\nimport VcPaletteProvider from './VcPaletteProvider.js';\n\nexport const vcPaletteModule: ModuleDeclaration = {\n __depends__: [\n PaletteModule,\n CreateModule,\n HandToolModule,\n LassoToolModule,\n SpaceToolModule,\n GlobalConnectModule,\n ],\n __init__: ['vcPaletteProvider'],\n vcPaletteProvider: ['type', VcPaletteProvider],\n};\n\nexport { default as VcPaletteProvider, type VcPaletteConfig } from './VcPaletteProvider.js';\n","import type PopupMenu from 'diagram-js/lib/features/popup-menu/PopupMenu';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { COLOR_OPTIONS, COLORS } from '../draw/styles.js';\nimport { isVcShape } from '../model/di-types.js';\nimport type VcModeling from '../modeling/VcModeling.js';\n\nexport const COLOR_PICKER_PROVIDER_ID = 'vc-color-picker';\n\ninterface PopupMenuEntry {\n label: string;\n group?: string;\n imageHtml?: string;\n action: () => void;\n}\n\nfunction swatch(color: string): string {\n return (\n `<svg viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" aria-hidden=\"true\">` +\n `<rect x=\"1\" y=\"1\" width=\"14\" height=\"14\" rx=\"2\" fill=\"${COLORS.fill}\" ` +\n `stroke=\"${color}\" stroke-width=\"2\"/></svg>`\n );\n}\n\nexport default class VcColorPickerProvider {\n static $inject = ['popupMenu', 'vcModeling'];\n\n constructor(\n popupMenu: PopupMenu,\n private readonly vcModeling: VcModeling,\n ) {\n popupMenu.registerProvider(COLOR_PICKER_PROVIDER_ID, this);\n }\n\n getPopupMenuEntries(target: Element | Element[]): Record<string, PopupMenuEntry> {\n const element = Array.isArray(target) ? target[0] : target;\n if (!isVcShape(element)) {\n return {};\n }\n\n const entries: Record<string, PopupMenuEntry> = {};\n for (const option of COLOR_OPTIONS) {\n entries[`color-${option.label.toLowerCase()}`] = {\n label: option.label,\n imageHtml: swatch(option.color ?? COLORS.ink),\n action: () => this.vcModeling.setColor(element, option.color),\n };\n }\n return entries;\n }\n}\n","import type PopupMenu from 'diagram-js/lib/features/popup-menu/PopupMenu';\nimport type AlignElements from 'diagram-js/lib/features/align-elements/AlignElements';\nimport type DistributeElements from 'diagram-js/lib/features/distribute-elements/DistributeElements';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { isVcShape } from '../model/di-types.js';\n\nexport const ALIGN_MENU_PROVIDER_ID = 'vc-align-elements';\n\ninterface PopupMenuEntry {\n label: string;\n group?: string;\n imageHtml?: string;\n action: () => void;\n}\n\nfunction alignIcon(content: string): string {\n return (\n '<svg viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" ' +\n `stroke-width=\"1.3\" stroke-linecap=\"round\" aria-hidden=\"true\">${content}</svg>`\n );\n}\n\nconst ICONS = {\n left: alignIcon(\n '<path d=\"M3 2v12\"/><rect x=\"5\" y=\"4\" width=\"8\" height=\"3\"/><rect x=\"5\" y=\"9\" width=\"5\" height=\"3\"/>',\n ),\n center: alignIcon(\n '<path d=\"M8 2v12\"/><rect x=\"4\" y=\"4\" width=\"8\" height=\"3\"/><rect x=\"5.5\" y=\"9\" width=\"5\" height=\"3\"/>',\n ),\n right: alignIcon(\n '<path d=\"M13 2v12\"/><rect x=\"3\" y=\"4\" width=\"8\" height=\"3\"/><rect x=\"6\" y=\"9\" width=\"5\" height=\"3\"/>',\n ),\n top: alignIcon(\n '<path d=\"M2 3h12\"/><rect x=\"4\" y=\"5\" width=\"3\" height=\"8\"/><rect x=\"9\" y=\"5\" width=\"3\" height=\"5\"/>',\n ),\n middle: alignIcon(\n '<path d=\"M2 8h12\"/><rect x=\"4\" y=\"4\" width=\"3\" height=\"8\"/><rect x=\"9\" y=\"5.5\" width=\"3\" height=\"5\"/>',\n ),\n bottom: alignIcon(\n '<path d=\"M2 13h12\"/><rect x=\"4\" y=\"3\" width=\"3\" height=\"8\"/><rect x=\"9\" y=\"6\" width=\"3\" height=\"5\"/>',\n ),\n horizontal: alignIcon(\n '<rect x=\"2\" y=\"5\" width=\"3\" height=\"6\"/><rect x=\"6.5\" y=\"5\" width=\"3\" height=\"6\"/><rect x=\"11\" y=\"5\" width=\"3\" height=\"6\"/>',\n ),\n vertical: alignIcon(\n '<rect x=\"5\" y=\"2\" width=\"6\" height=\"3\"/><rect x=\"5\" y=\"6.5\" width=\"6\" height=\"3\"/><rect x=\"5\" y=\"11\" width=\"6\" height=\"3\"/>',\n ),\n} as const;\n\n/** Align/distribute menu for multi-selections, opened from the context pad. */\nexport default class VcAlignMenuProvider {\n static $inject = ['popupMenu', 'alignElements', 'distributeElements'];\n\n constructor(\n popupMenu: PopupMenu,\n private readonly alignElements: AlignElements,\n private readonly distributeElements: DistributeElements,\n ) {\n popupMenu.registerProvider(ALIGN_MENU_PROVIDER_ID, this);\n }\n\n getPopupMenuEntries(target: Element | Element[]): Record<string, PopupMenuEntry> {\n const elements = (Array.isArray(target) ? target : [target]).filter(isVcShape) as Element[];\n if (elements.length < 2) {\n return {};\n }\n\n const align = (type: string, label: string, icon: string): PopupMenuEntry => ({\n label,\n group: 'align',\n imageHtml: icon,\n action: () => this.alignElements.trigger(elements, type as never),\n });\n\n const entries: Record<string, PopupMenuEntry> = {\n 'align-left': align('left', 'Align left', ICONS.left),\n 'align-center': align('center', 'Align center', ICONS.center),\n 'align-right': align('right', 'Align right', ICONS.right),\n 'align-top': align('top', 'Align top', ICONS.top),\n 'align-middle': align('middle', 'Align middle', ICONS.middle),\n 'align-bottom': align('bottom', 'Align bottom', ICONS.bottom),\n };\n\n if (elements.length >= 3) {\n entries['distribute-horizontally'] = {\n label: 'Distribute horizontally',\n group: 'distribute',\n imageHtml: ICONS.horizontal,\n action: () => this.distributeElements.trigger(elements, 'horizontal'),\n };\n entries['distribute-vertically'] = {\n label: 'Distribute vertically',\n group: 'distribute',\n imageHtml: ICONS.vertical,\n action: () => this.distributeElements.trigger(elements, 'vertical'),\n };\n }\n\n return entries;\n }\n}\n","import type ContextPad from 'diagram-js/lib/features/context-pad/ContextPad';\nimport type ContextPadProvider from 'diagram-js/lib/features/context-pad/ContextPadProvider';\nimport type Modeling from 'diagram-js/lib/features/modeling/Modeling';\nimport type PopupMenu from 'diagram-js/lib/features/popup-menu/PopupMenu';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport {\n isOrgUnit,\n isStep,\n isVcConnection,\n isVcShape,\n type VcConnection,\n type VcShape,\n} from '../model/di-types.js';\nimport { contextPadEntryHtml, ICONS } from '../draw/icons.js';\nimport { COLOR_PICKER_PROVIDER_ID } from '../popup/VcColorPickerProvider.js';\nimport { ALIGN_MENU_PROVIDER_ID } from '../popup/VcAlignMenuProvider.js';\nimport type VcAppend from '../append/VcAppend.js';\nimport type VcConnect from '../connect/VcConnect.js';\nimport type VcModeling from '../modeling/VcModeling.js';\nimport type VcReadOnly from '../read-only/VcReadOnly.js';\n\ninterface ContextPadEntry {\n group: string;\n html?: string;\n title?: string;\n action: Record<string, (event: Event, element?: Element) => void>;\n}\n\ntype Entries = Record<string, ContextPadEntry>;\n\nexport default class VcContextPadProvider {\n static $inject = [\n 'contextPad',\n 'modeling',\n 'popupMenu',\n 'vcAppend',\n 'vcConnect',\n 'vcModeling',\n 'vcReadOnly',\n ];\n\n constructor(\n contextPad: ContextPad,\n private readonly modeling: Modeling,\n private readonly popupMenu: PopupMenu,\n private readonly vcAppend: VcAppend,\n private readonly vcConnect: VcConnect,\n private readonly vcModeling: VcModeling,\n private readonly readOnly: Pick<VcReadOnly, 'isReadOnly'>,\n ) {\n contextPad.registerProvider(this as unknown as ContextPadProvider);\n }\n\n getContextPadEntries(element: Element): Entries {\n const entries: Entries = {};\n if (this.readOnly.isReadOnly()) {\n return entries;\n }\n\n if (isStep(element)) {\n this.addStepEntries(entries, element);\n }\n\n if (isOrgUnit(element)) {\n const startConnect = (event: Event): void => {\n this.vcConnect.start(event, element, 'assignment');\n };\n entries['connect.assignment'] = {\n group: 'connect',\n title: 'Connect to step',\n html: contextPadEntryHtml(ICONS.connectHierarchy, true),\n action: { click: startConnect, dragstart: startConnect },\n };\n }\n\n if (isVcShape(element)) {\n entries['set-color'] = {\n group: 'edit',\n title: 'Set color',\n html: contextPadEntryHtml(ICONS.color),\n action: {\n click: (event: Event) => {\n const mouse = event as MouseEvent;\n this.popupMenu.open(element, COLOR_PICKER_PROVIDER_ID, {\n x: mouse.clientX,\n y: mouse.clientY,\n });\n },\n },\n };\n }\n\n if (isVcConnection(element) && element.vcType !== 'assignment') {\n const connection = element as VcConnection;\n const other: ConnectionType = connection.vcType === 'sequence' ? 'hierarchy' : 'sequence';\n entries['toggle-type'] = {\n group: 'edit',\n title: `Switch to \"${other === 'sequence' ? 'is predecessor of' : 'is process-oriented superior'}\"`,\n html: contextPadEntryHtml(ICONS.toggleType),\n action: { click: () => this.vcModeling.setConnectionType(connection, other) },\n };\n }\n\n if (isVcShape(element) || isVcConnection(element)) {\n entries['delete'] = {\n group: 'edit',\n title: 'Delete',\n html: contextPadEntryHtml(ICONS.trash),\n action: { click: () => this.modeling.removeElements([element]) },\n };\n }\n\n return entries;\n }\n\n getMultiElementContextPadEntries(elements: Element[]): Entries {\n const entries: Entries = {};\n if (this.readOnly.isReadOnly()) {\n return entries;\n }\n\n if (elements.filter(isVcShape).length >= 2) {\n entries['align'] = {\n group: 'edit',\n title: 'Align / distribute',\n html: contextPadEntryHtml(ICONS.align),\n action: {\n click: (event: Event) => {\n const mouse = event as MouseEvent;\n this.popupMenu.open(elements, ALIGN_MENU_PROVIDER_ID, {\n x: mouse.clientX,\n y: mouse.clientY,\n });\n },\n },\n };\n }\n\n entries['delete'] = {\n group: 'edit',\n title: 'Delete',\n html: contextPadEntryHtml(ICONS.trash),\n action: { click: () => this.modeling.removeElements([...elements]) },\n };\n\n return entries;\n }\n\n private addStepEntries(entries: Entries, shape: VcShape): void {\n const append = (type: ConnectionType) => () => {\n this.vcAppend.append(shape, type);\n };\n const appendDrag = (type: ConnectionType) => (event: Event) => {\n this.vcAppend.startAppendDrag(event, shape, type);\n };\n const connect = (type: ConnectionType) => (event: Event) => {\n this.vcConnect.start(event, shape, type);\n };\n\n entries['append.step'] = {\n group: 'model',\n title: 'Append step (is predecessor of)',\n html: contextPadEntryHtml(ICONS.appendStep, true),\n action: { click: append('sequence'), dragstart: appendDrag('sequence') },\n };\n\n entries['append.sub-step'] = {\n group: 'model',\n title: 'Append sub-step (is process-oriented superior)',\n html: contextPadEntryHtml(ICONS.appendSubStep, true),\n action: { click: append('hierarchy'), dragstart: appendDrag('hierarchy') },\n };\n\n entries['append.org-unit'] = {\n group: 'model',\n title: 'Append organizational unit',\n html: contextPadEntryHtml(ICONS.appendOrgUnit, true),\n action: { click: append('assignment'), dragstart: appendDrag('assignment') },\n };\n\n entries['connect.sequence'] = {\n group: 'connect',\n title: 'Connect (is predecessor of)',\n html: contextPadEntryHtml(ICONS.connectSequence, true),\n action: { click: connect('sequence'), dragstart: connect('sequence') },\n };\n\n entries['connect.hierarchy'] = {\n group: 'connect',\n title: 'Connect (is process-oriented superior)',\n html: contextPadEntryHtml(ICONS.connectHierarchy, true),\n action: { click: connect('hierarchy'), dragstart: connect('hierarchy') },\n };\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport ContextPadModule from 'diagram-js/lib/features/context-pad';\nimport PopupMenuModule from 'diagram-js/lib/features/popup-menu';\nimport VcContextPadProvider from './VcContextPadProvider.js';\n\nexport const vcContextPadModule: ModuleDeclaration = {\n __depends__: [ContextPadModule, PopupMenuModule],\n __init__: ['vcContextPadProvider'],\n vcContextPadProvider: ['type', VcContextPadProvider],\n};\n\nexport { default as VcContextPadProvider } from './VcContextPadProvider.js';\n","import type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { labelInset } from '../draw/geometry.js';\nimport { FONT, LABEL_PADDING } from '../draw/styles.js';\nimport { isOrgUnit, isVcShape, type VcShape } from '../model/di-types.js';\nimport type VcModeling from '../modeling/VcModeling.js';\n\ninterface DirectEditingLike {\n registerProvider(provider: unknown): void;\n activate(element: Element): boolean;\n isActive(element?: Element): boolean;\n complete(): void;\n cancel(): void;\n getValue(): string;\n /** diagram-js-direct-editing internals: the edit open right now and its text box. */\n _active?: { element: Element; context: EditingContext } | null;\n _textbox?: { parent: HTMLElement; content: HTMLElement };\n}\n\ninterface EditingContext {\n bounds: { x: number; y: number; width: number; height: number };\n text: string;\n style?: Record<string, string>;\n options?: Record<string, unknown>;\n}\n\n/** A label edit open right now: the element and the text typed so far, not yet committed. */\nexport interface OpenLabelEdit {\n element: VcShape;\n text: string;\n}\n\n/** An open edit taken down for an import: the id of its element and the uncommitted text. */\ninterface SuspendedEdit {\n elementId: string;\n text: string;\n}\n\n/**\n * In-place label editing via diagram-js-direct-editing: double click (or E) opens a centered\n * text box over the shape's label area; editing commits through the command stack (undoable).\n * Only the user's own gestures commit (Enter, leaving the text box, a click or drag on the\n * canvas); a view change keeps the edit open and moves the text box along. An import takes an open\n * edit down without committing it and reopens it on the element with the same id, with the typed\n * text, when the imported diagram still has that element.\n */\nexport default class VcLabelEditingProvider {\n static $inject = ['directEditing', 'canvas', 'eventBus', 'vcModeling', 'elementRegistry'];\n\n private suspended: SuspendedEdit | null = null;\n private resumeTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n private readonly directEditing: DirectEditingLike,\n private readonly canvas: Canvas,\n eventBus: EventBus,\n private readonly vcModeling: VcModeling,\n private readonly elementRegistry: ElementRegistry,\n ) {\n directEditing.registerProvider(this);\n\n eventBus.on('element.dblclick', (event: { element?: Element }) => {\n if (event.element && isVcShape(event.element)) {\n directEditing.activate(event.element);\n }\n });\n\n // Open editing on freshly appended/created-with-source steps (after the default\n // handlers at priority 1000 have created the shape).\n eventBus.on('autoPlace.end', 500, (event: { shape?: Element }) => {\n if (event.shape && isVcShape(event.shape)) {\n directEditing.activate(event.shape);\n }\n });\n eventBus.on(\n 'create.end',\n 500,\n (event: { context: { source?: Element; shape?: Element; canExecute?: unknown } }) => {\n const { source, shape, canExecute } = event.context;\n if (source && canExecute && shape && isVcShape(shape)) {\n directEditing.activate(shape);\n }\n },\n );\n\n // Interacting elsewhere commits (does not discard) the pending edit.\n eventBus.on(['element.mousedown', 'drag.init', 'autoPlace.start', 'popupMenu.open'], () => {\n if (directEditing.isActive()) {\n directEditing.complete();\n }\n });\n\n // diagram-js cannot tell a host's fit or restore from a wheel zoom, and a host's view change\n // must not write half-typed input into the document (contract L5): the edit stays open.\n eventBus.on('canvas.viewbox.changed', () => this.followView());\n\n // Model changed underneath the editor (undo/redo via chrome or API) — discard the\n // pending edit instead of committing against a possibly removed element.\n eventBus.on('commandStack.changed', () => {\n if (directEditing.isActive()) {\n directEditing.cancel();\n }\n });\n\n // Before the canvas tears down: a field still open would commit onto the destroyed diagram.\n eventBus.on('diagram.destroy', 1500, () => {\n clearTimeout(this.resumeTimer);\n this.suspended = null;\n if (directEditing.isActive()) {\n directEditing.cancel();\n }\n });\n }\n\n /** The edit open right now, or undefined. */\n openEdit(): OpenLabelEdit | undefined {\n const element = this.directEditing._active?.element;\n if (!this.directEditing.isActive() || !isVcShape(element)) {\n return undefined;\n }\n return { element, text: this.directEditing.getValue() };\n }\n\n /**\n * Takes an open edit down WITHOUT committing it, for an import that replaces the diagram: its\n * element is about to be removed, and a later commit would apply the typed text to a detached\n * shape. Hosts re-import remote states while the user types; `resumeAfterImport` brings the\n * editor back with the typed text.\n */\n suspend(): void {\n clearTimeout(this.resumeTimer);\n const open = this.openEdit();\n if (!open) {\n return;\n }\n this.suspended = { elementId: open.element.id, text: open.text };\n this.directEditing.cancel();\n }\n\n /**\n * Reopens a suspended edit on the element with the same id, if the imported diagram still has\n * it. Deferred to the next task, so the text box opens in the view and selection the host\n * restores around the import.\n */\n resumeAfterImport(): void {\n clearTimeout(this.resumeTimer);\n if (!this.suspended) {\n return;\n }\n this.resumeTimer = setTimeout(() => {\n const edit = this.suspended;\n this.suspended = null;\n if (edit && !this.directEditing.isActive()) {\n this.resume(edit);\n }\n }, 0);\n }\n\n private resume(edit: SuspendedEdit): void {\n const element = this.elementRegistry.get(edit.elementId);\n if (!isVcShape(element) || !this.directEditing.activate(element)) {\n return;\n }\n const content = this.directEditing._textbox?.content;\n if (!content) {\n return;\n }\n content.innerText = edit.text;\n const selection = content.ownerDocument.getSelection();\n selection?.selectAllChildren(content);\n selection?.collapseToEnd();\n }\n\n /** Puts the open text box over its element again in the current view, with the typed text. */\n private followView(): void {\n const active = this.directEditing._active;\n const textbox = this.directEditing._textbox;\n if (!active || !textbox) {\n return;\n }\n const context = this.activate(active.element);\n if (!context) {\n return;\n }\n const { x, y, width, height } = context.bounds;\n Object.assign(textbox.parent.style, {\n left: `${x}px`,\n top: `${y}px`,\n width: `${width}px`,\n height: `${height}px`,\n });\n textbox.content.style.fontSize = context.style?.['fontSize'] ?? '';\n // complete() compares the box against this to tell an edit from a mere look at the label.\n active.context.bounds = context.bounds;\n }\n\n activate(element: Element): EditingContext | undefined {\n if (!isVcShape(element)) {\n return undefined;\n }\n const shape = element;\n const bbox = this.canvas.getAbsoluteBBox(shape);\n const zoom = this.canvas.zoom();\n const rawInset = isOrgUnit(shape) ? LABEL_PADDING + 5 : labelInset(shape.width, shape.height);\n const inset = rawInset * zoom;\n\n const bounds = {\n x: bbox.x + inset,\n y: bbox.y,\n width: bbox.width - inset * 2,\n height: bbox.height,\n };\n\n // The text box writes its fill and border as inline styles, so the roles come in here.\n const style = {\n fontFamily: FONT.family,\n fontSize: `${FONT.size * zoom}px`,\n fontWeight: 'normal',\n lineHeight: String(FONT.lineHeight),\n textAlign: 'center',\n backgroundColor: 'var(--cd-ui-flaeche-hoch)',\n border: '1px solid var(--cd-ui-interaktion)',\n };\n\n return {\n bounds,\n style,\n options: { centerVertically: true },\n text: shape.vcLabel || '',\n };\n }\n\n update(element: Element, newText: string): void {\n this.vcModeling.updateLabel(element as VcShape, sanitizeLabel(newText));\n }\n}\n\nfunction sanitizeLabel(text: string): string {\n return text.replace(/\\r\\n?/g, '\\n').trim();\n}\n","import type { ModuleDeclaration } from 'didi';\nimport DirectEditingModule from 'diagram-js-direct-editing';\nimport VcLabelEditingProvider from './VcLabelEditingProvider.js';\n\nexport const vcLabelEditingModule: ModuleDeclaration = {\n __depends__: [DirectEditingModule],\n __init__: ['vcLabelEditingProvider'],\n vcLabelEditingProvider: ['type', VcLabelEditingProvider],\n};\n\nexport { default as VcLabelEditingProvider, type OpenLabelEdit } from './VcLabelEditingProvider.js';\n","import type { ModuleDeclaration } from 'didi';\nimport PopupMenuModule from 'diagram-js/lib/features/popup-menu';\nimport AlignElementsModule from 'diagram-js/lib/features/align-elements';\nimport DistributeElementsModule from 'diagram-js/lib/features/distribute-elements';\nimport VcColorPickerProvider from './VcColorPickerProvider.js';\nimport VcAlignMenuProvider from './VcAlignMenuProvider.js';\n\nexport const vcColorPickerModule: ModuleDeclaration = {\n __depends__: [PopupMenuModule],\n __init__: ['vcColorPickerProvider'],\n vcColorPickerProvider: ['type', VcColorPickerProvider],\n};\n\nexport const vcAlignMenuModule: ModuleDeclaration = {\n __depends__: [PopupMenuModule, AlignElementsModule, DistributeElementsModule],\n __init__: ['vcAlignMenuProvider'],\n vcAlignMenuProvider: ['type', VcAlignMenuProvider],\n};\n\nexport {\n default as VcColorPickerProvider,\n COLOR_PICKER_PROVIDER_ID,\n} from './VcColorPickerProvider.js';\nexport { default as VcAlignMenuProvider, ALIGN_MENU_PROVIDER_ID } from './VcAlignMenuProvider.js';\n","import KeyboardBindings from 'diagram-js/lib/features/keyboard/KeyboardBindings';\nimport { hasModifier, isCmd, isKey } from 'diagram-js/lib/features/keyboard/KeyboardUtil';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type Keyboard from 'diagram-js/lib/features/keyboard/Keyboard';\nimport type EditorActions from 'diagram-js/lib/features/editor-actions/EditorActions';\n\ninterface KeyContext {\n keyEvent: KeyboardEvent;\n}\n\nexport interface VcKeyboardConfig {\n /**\n * Bind Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z and Ctrl+Y to the canvas command stack (default true). A\n * host that owns the history (the VS Code document) passes false, so the keys reach it.\n */\n undoRedoKeys?: boolean | undefined;\n}\n\nconst UNDO_REDO_ACTIONS = new Set(['undo', 'redo']);\n\n/**\n * Default diagram-js bindings (undo/redo/copy/paste/zoom/delete) plus the single-key tool\n * shortcuts L lasso, H hand, S space, C connect, E label editing, and Cmd/Ctrl+A for select all.\n * The keyboard listens on the focused canvas only.\n */\nexport default class VcKeyboardBindings extends KeyboardBindings {\n static override $inject = ['eventBus', 'keyboard', 'config.vcKeyboard'];\n\n private readonly undoRedoKeys: boolean;\n\n constructor(eventBus: EventBus, keyboard: Keyboard, config: VcKeyboardConfig | undefined) {\n super(eventBus, keyboard);\n this.undoRedoKeys = config?.undoRedoKeys ?? true;\n }\n\n override registerBindings(keyboard: Keyboard, editorActions: EditorActions): void {\n // Hiding undo and redo from the stock bindings leaves the keys unprevented, so they travel on\n // to whoever owns the history.\n const boundActions = this.undoRedoKeys\n ? editorActions\n : (Object.create(editorActions, {\n isRegistered: {\n value: (action: string) =>\n !UNDO_REDO_ACTIONS.has(action) && editorActions.isRegistered(action),\n },\n }) as EditorActions);\n super.registerBindings(keyboard, boundActions);\n\n const addListener = (action: string, listener: (context: KeyContext) => boolean | void) => {\n if (editorActions.isRegistered(action)) {\n keyboard.addListener(listener as never);\n }\n };\n\n const bindTool = (action: string, keys: string[]): void => {\n addListener(action, (context) => {\n const event = context.keyEvent;\n if (isKey(keys, event) && !hasModifier(event)) {\n editorActions.trigger(action, {});\n return true;\n }\n return undefined as unknown as boolean;\n });\n };\n\n bindTool('lassoTool', ['l', 'L']);\n bindTool('handTool', ['h', 'H']);\n bindTool('spaceTool', ['s', 'S']);\n bindTool('globalConnectTool', ['c', 'C']);\n bindTool('directEditing', ['e', 'E']);\n\n // diagram-js binds no select all; an unhandled Cmd/Ctrl+A would select the page's text.\n addListener('selectAll', (context) => {\n const event = context.keyEvent;\n if (isCmd(event) && isKey(['a', 'A'], event) && !event.shiftKey && !event.altKey) {\n editorActions.trigger('selectAll', {});\n return true;\n }\n return undefined as unknown as boolean;\n });\n }\n}\n","import type EventBus from 'diagram-js/lib/core/EventBus';\nimport type EditorActions from 'diagram-js/lib/features/editor-actions/EditorActions';\nimport type { Injector } from 'didi';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { isVcElement } from '../model/di-types.js';\n\n/** Runs before KeyboardBindings' listener (priority 500) checks registered actions. */\nconst HIGH_PRIORITY = 1500;\n\ninterface ToggleTool {\n toggle(): void;\n}\n\ninterface EditLock {\n isReadOnly(): boolean;\n}\n\n/**\n * Registers the tool, editing and selection actions the keyboard bindings and hosts rely on.\n * Under the edit lock (`vcReadOnly`) the space tool, the connect tool and the label editor stay\n * shut; the hand, the lasso and select all keep working.\n */\nexport default class VcEditorActions {\n static $inject = ['eventBus', 'injector'];\n\n constructor(eventBus: EventBus, injector: Injector) {\n eventBus.on('editorActions.init', HIGH_PRIORITY, (event: { editorActions: EditorActions }) => {\n const { editorActions } = event;\n const lock = injector.get<EditLock>('vcReadOnly', false);\n const unlocked = () => !lock?.isReadOnly();\n\n const register = (\n name: string,\n serviceName: string,\n run: (service: never) => void,\n allowed: () => boolean = () => true,\n ) => {\n const service = injector.get(serviceName, false);\n if (service) {\n editorActions.register({\n [name]: () => {\n if (allowed()) run(service as never);\n },\n });\n }\n };\n\n register('handTool', 'handTool', (tool: ToggleTool) => tool.toggle());\n register('lassoTool', 'lassoTool', (tool: ToggleTool) => tool.toggle());\n register('spaceTool', 'spaceTool', (tool: ToggleTool) => tool.toggle(), unlocked);\n register('globalConnectTool', 'globalConnect', (tool: ToggleTool) => tool.toggle(), unlocked);\n\n const elementRegistry = injector.get('elementRegistry', false) as {\n filter(fn: (element: Element) => boolean): Element[];\n } | null;\n const selection = injector.get('selection', false) as {\n get(): Element[];\n select(elements: Element[]): void;\n } | null;\n if (elementRegistry && selection) {\n editorActions.register({\n selectAll: () => selection.select(elementRegistry.filter(isVcElement)),\n });\n }\n\n const directEditing = injector.get('directEditing', false) as {\n activate(element: Element): void;\n } | null;\n if (directEditing && selection) {\n editorActions.register({\n directEditing: () => {\n const selected = selection.get();\n if (unlocked() && selected.length === 1 && selected[0]) {\n directEditing.activate(selected[0]);\n }\n },\n });\n }\n });\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport KeyboardModule from 'diagram-js/lib/features/keyboard';\nimport EditorActionsModule from 'diagram-js/lib/features/editor-actions';\nimport VcKeyboardBindings from './VcKeyboardBindings.js';\nimport VcEditorActions from './VcEditorActions.js';\n\n/** Overrides the stock `keyboardBindings` with the tool shortcuts and select all. */\nexport const vcKeyboardModule: ModuleDeclaration = {\n __depends__: [KeyboardModule, EditorActionsModule],\n __init__: ['vcEditorActions'],\n keyboardBindings: ['type', VcKeyboardBindings],\n vcEditorActions: ['type', VcEditorActions],\n};\n\nexport { default as VcKeyboardBindings, type VcKeyboardConfig } from './VcKeyboardBindings.js';\nexport { default as VcEditorActions } from './VcEditorActions.js';\n","import OrderingProvider from 'diagram-js/lib/features/ordering/OrderingProvider';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Element, Shape } from 'diagram-js/lib/model/Types';\nimport { isVcConnection } from '../model/di-types.js';\n\n/** Keeps connections behind steps during interactive edits (mirrors the import order). */\nexport default class VcOrderingProvider extends OrderingProvider {\n static override $inject = ['eventBus'];\n\n constructor(eventBus: EventBus) {\n super(eventBus);\n }\n\n override getOrdering(element: Element, newParent: Shape): { parent: Shape; index?: number } {\n if (isVcConnection(element)) {\n const siblings = (newParent.children ?? []) as Element[];\n const index = siblings.filter((child) => child !== element && isVcConnection(child)).length;\n return { parent: newParent, index };\n }\n return { parent: newParent };\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport VcOrderingProvider from './VcOrderingProvider.js';\n\nexport const vcOrderingModule: ModuleDeclaration = {\n __init__: ['vcOrderingProvider'],\n vcOrderingProvider: ['type', VcOrderingProvider],\n};\n\nexport { default as VcOrderingProvider } from './VcOrderingProvider.js';\n","import type EventBus from 'diagram-js/lib/core/EventBus';\nimport { isVcConnection, isVcShape } from '../model/di-types.js';\n\ninterface CopyContext {\n descriptor: Record<string, unknown>;\n element: unknown;\n}\n\n/**\n * Copy/paste support: diagram-js turns copy descriptors into element attrs on paste,\n * so carrying the flat domain properties across is all that is needed.\n */\nexport default class VcCopyPasteBehavior {\n static $inject = ['eventBus'];\n\n constructor(eventBus: EventBus) {\n eventBus.on('copyPaste.copyElement', (context: CopyContext) => {\n const { descriptor, element } = context;\n if (isVcShape(element)) {\n descriptor['vcType'] = element.vcType;\n descriptor['vcLabel'] = element.vcLabel;\n if (element.color !== undefined) {\n descriptor['color'] = element.color;\n }\n if (element.link !== undefined) {\n descriptor['link'] = element.link;\n }\n } else if (isVcConnection(element)) {\n descriptor['vcType'] = element.vcType;\n }\n });\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport CopyPasteModule from 'diagram-js/lib/features/copy-paste';\nimport VcCopyPasteBehavior from './VcCopyPasteBehavior.js';\n\nexport const vcCopyPasteModule: ModuleDeclaration = {\n __depends__: [CopyPasteModule],\n __init__: ['vcCopyPasteBehavior'],\n vcCopyPasteBehavior: ['type', VcCopyPasteBehavior],\n};\n\nexport { default as VcCopyPasteBehavior } from './VcCopyPasteBehavior.js';\n","import type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport { MIN_STEP_SIZE } from '@miragon/value-chain-schema-model';\nimport { isVcShape } from '../model/di-types.js';\n\ninterface ResizeStartEvent {\n context: {\n shape?: unknown;\n minDimensions?: { width: number; height: number };\n };\n}\n\n/** Enforces the minimum step size while resizing and while using the space tool. */\nexport default class VcResizeBehavior {\n static $inject = ['eventBus'];\n\n constructor(eventBus: EventBus) {\n eventBus.on('resize.start', (event: ResizeStartEvent) => {\n if (isVcShape(event.context.shape)) {\n event.context.minDimensions = { ...MIN_STEP_SIZE };\n }\n });\n\n eventBus.on(\n 'spaceTool.getMinDimensions',\n (event: { shapes: Shape[] }): Record<string, { width: number; height: number }> => {\n const minDimensions: Record<string, { width: number; height: number }> = {};\n for (const shape of event.shapes) {\n if (isVcShape(shape)) {\n minDimensions[shape.id] = { ...MIN_STEP_SIZE };\n }\n }\n return minDimensions;\n },\n );\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport ResizeModule from 'diagram-js/lib/features/resize';\nimport VcResizeBehavior from './VcResizeBehavior.js';\n\nexport const vcResizeModule: ModuleDeclaration = {\n __depends__: [ResizeModule],\n __init__: ['vcResizeBehavior'],\n vcResizeBehavior: ['type', VcResizeBehavior],\n};\n\nexport { default as VcResizeBehavior } from './VcResizeBehavior.js';\n","import RuleProvider from 'diagram-js/lib/features/rules/RuleProvider';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Injector } from 'didi';\n\n/** Fired with `{ readOnly }` whenever the lock changes. */\nexport const READ_ONLY_CHANGED_EVENT = 'valueChain.readOnly.changed';\n\n/** Above every edit rule of the renderer and diagram-js, so the lock wins. */\nconst LOCK_PRIORITY = 5000;\n\nconst EDIT_RULES = [\n 'elements.move',\n 'shape.move',\n 'shape.resize',\n 'shape.create',\n 'elements.create',\n 'shape.append',\n 'connection.start',\n 'connection.create',\n 'connection.reconnect',\n 'connection.updateWaypoints',\n 'elements.delete',\n 'elements.align',\n 'elements.distribute',\n];\n\ninterface Closable {\n close(): void;\n}\n\ninterface Cancellable {\n cancel(): void;\n}\n\n/**\n * Locks every edit on the canvas while the document behind it cannot be saved from the canvas\n * (an invalid file in an IDE host, guide §13.5): the rules veto move, resize, create, connect,\n * reconnect, waypoints, delete, align and distribute; paste, the label editor and the context pad\n * stay shut, and the editing keys and tools check `isReadOnly()`. Selection, lasso, hand, zoom,\n * copy and export keep working.\n */\nexport default class VcReadOnly extends RuleProvider {\n static override $inject = ['eventBus', 'injector'];\n\n private readOnly = false;\n\n constructor(\n private readonly bus: EventBus,\n private readonly injector: Injector,\n ) {\n super(bus);\n bus.on('copyPaste.pasteElements', LOCK_PRIORITY, () => (this.readOnly ? false : undefined));\n bus.on('directEditing.activate.allowed', LOCK_PRIORITY, () =>\n this.readOnly ? false : undefined,\n );\n }\n\n override init(): void {\n this.addRule(EDIT_RULES, LOCK_PRIORITY, () => (this.readOnly ? false : undefined));\n }\n\n isReadOnly(): boolean {\n return this.readOnly;\n }\n\n setReadOnly(readOnly: boolean): void {\n if (this.readOnly === readOnly) {\n return;\n }\n this.readOnly = readOnly;\n if (readOnly) {\n this.interruptEdits();\n }\n this.bus.fire(READ_ONLY_CHANGED_EVENT, { readOnly });\n }\n\n /** What was already under way when the lock arrived must not land on the locked canvas. */\n private interruptEdits(): void {\n const optional = <T>(name: string): T | undefined => this.injector.get<T>(name, false);\n optional<Cancellable>('directEditing')?.cancel();\n optional<Cancellable>('dragging')?.cancel();\n optional<Closable>('popupMenu')?.close();\n optional<Closable>('contextPad')?.close();\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport RulesModule from 'diagram-js/lib/features/rules';\nimport VcReadOnly from './VcReadOnly.js';\n\n/** The canvas edit lock (an invalid file in an IDE host). */\nexport const vcReadOnlyModule: ModuleDeclaration = {\n __depends__: [RulesModule],\n __init__: ['vcReadOnly'],\n vcReadOnly: ['type', VcReadOnly],\n};\n\nexport { default as VcReadOnly, READ_ONLY_CHANGED_EVENT } from './VcReadOnly.js';\n","import type { ModuleDeclaration } from 'didi';\nimport type CommandStack from 'diagram-js/lib/command/CommandStack';\nimport ModelingModule from 'diagram-js/lib/features/modeling';\nimport MoveModule from 'diagram-js/lib/features/move';\nimport OutlineModule from 'diagram-js/lib/features/outline';\nimport BendpointsModule from 'diagram-js/lib/features/bendpoints';\nimport AutoScrollModule from 'diagram-js/lib/features/auto-scroll';\nimport GridSnappingModule from 'diagram-js/lib/features/grid-snapping';\nimport SnappingModule from 'diagram-js/lib/features/snapping';\nimport KeyboardMoveSelectionModule from 'diagram-js/lib/features/keyboard-move-selection';\nimport KeyboardMoveModule from 'diagram-js/lib/navigation/keyboard-move';\nimport { NavigatedViewer } from './NavigatedViewer.js';\nimport { vcModelingModule } from './modeling/index.js';\nimport { vcRulesModule } from './rules/index.js';\nimport { vcConnectModule } from './connect/index.js';\nimport { vcAppendModule } from './append/index.js';\nimport { vcPaletteModule } from './palette/index.js';\nimport { vcContextPadModule } from './context-pad/index.js';\nimport { vcLabelEditingModule } from './label-editing/index.js';\nimport { vcAlignMenuModule, vcColorPickerModule } from './popup/index.js';\nimport { vcKeyboardModule } from './keyboard/index.js';\nimport { vcOrderingModule } from './ordering/index.js';\nimport { vcCopyPasteModule } from './copy-paste/index.js';\nimport { vcResizeModule } from './resize/index.js';\nimport { vcReadOnlyModule } from './read-only/index.js';\n\n/**\n * The full value chain editor, with the edit lock for a document the canvas cannot save\n * (`vcReadOnly`).\n */\nexport class Modeler extends NavigatedViewer {\n protected override _getModules(): ModuleDeclaration[] {\n return [\n ...super._getModules(),\n // stock diagram-js editing features\n ModelingModule,\n MoveModule,\n OutlineModule,\n BendpointsModule,\n AutoScrollModule,\n GridSnappingModule,\n SnappingModule,\n KeyboardMoveSelectionModule,\n KeyboardMoveModule,\n // value chain specific modules\n vcReadOnlyModule,\n vcModelingModule,\n vcRulesModule,\n vcConnectModule,\n vcAppendModule,\n vcPaletteModule,\n vcContextPadModule,\n vcLabelEditingModule,\n vcColorPickerModule,\n vcAlignMenuModule,\n vcKeyboardModule,\n vcOrderingModule,\n vcCopyPasteModule,\n vcResizeModule,\n ];\n }\n\n undo(): void {\n this.get<CommandStack>('commandStack').undo();\n }\n\n redo(): void {\n this.get<CommandStack>('commandStack').redo();\n }\n\n canUndo(): boolean {\n return this.get<CommandStack>('commandStack').canUndo();\n }\n\n canRedo(): boolean {\n return this.get<CommandStack>('commandStack').canRedo();\n }\n}\n","import {\n MODELER_API_VERSION,\n type CollaborativeModeler,\n type CollaborativeModelerOptions,\n type ElementBounds,\n type ElementInfo,\n type ElementsSurface,\n type ImportResult,\n type ModelerMeta,\n} from '@miragon/modeler-api';\nimport type { ModuleDeclaration } from 'didi';\nimport type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type Selection from 'diagram-js/lib/features/selection/Selection';\nimport {\n createEmptyDocument,\n parseDocumentJSON,\n serializeDocument,\n type Point,\n type ValueChainDocument,\n} from '@miragon/value-chain-schema-model';\nimport { Modeler } from '../Modeler.js';\nimport { NavigatedViewer } from '../NavigatedViewer.js';\nimport type { VcViewerOptions } from '../VcBaseViewer.js';\nimport { isVcShape, type VcShape } from '../model/di-types.js';\n\n/** Stable notation id in `meta.notation` of the collaborative-modeler contract. */\nexport const VALUE_CHAIN_NOTATION = 'value-chain';\n\n/** What a blank text (a file just created in the explorer) opens as. */\nexport const BLANK_DOCUMENT_NAME = 'New value chain';\n\n/**\n * The contract's factory options (`freeArea`, `fitOnImport`, `undoRedoKeys`, see\n * `VcViewerOptions`) plus the renderer's own. The viewer ignores the two that need editing.\n */\nexport interface CollaborativeValueChainOptions extends CollaborativeModelerOptions {\n /** Appended to the renderer's own modules (e.g. a host's chrome module). */\n additionalModules?: ModuleDeclaration[] | undefined;\n /**\n * @deprecated Use `freeArea: { center }`; accepted until the next minor release. Given both,\n * `freeArea` wins.\n */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\n/** The contract surface plus the wrapped diagram for host-specific wiring. */\nexport interface CollaborativeValueChainModeler extends CollaborativeModeler {\n readonly elements: ElementsSurface & Required<Pick<ElementsSurface, 'bounds'>>;\n readonly diagram: Modeler | NavigatedViewer;\n}\n\ninterface ViewState {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** The editing mount (`meta.editable: true`) of the collaborative-modeler contract. */\nexport function createCollaborativeModeler(\n options: CollaborativeValueChainOptions = {},\n): CollaborativeValueChainModeler {\n return collaborative(\n new Modeler({\n ...diagramOptions(options),\n undoRedoKeys: options.undoRedoKeys ?? true,\n freeArea: options.freeArea,\n freeRectCenter: options.freeRectCenter,\n }),\n true,\n );\n}\n\n/** The read-only mount (`meta.editable: false`): imports, exports and reveals, never edits. */\nexport function createCollaborativeViewer(\n options: CollaborativeValueChainOptions = {},\n): CollaborativeValueChainModeler {\n return collaborative(new NavigatedViewer(diagramOptions(options)), false);\n}\n\nfunction diagramOptions(options: CollaborativeValueChainOptions): VcViewerOptions {\n return {\n width: '100%',\n height: '100%',\n additionalModules: options.additionalModules ?? [],\n fitOnImport: options.fitOnImport ?? true,\n };\n}\n\n/** Blank text is an empty diagram; anything else must be a valid document. */\nfunction documentOf(text: string): ValueChainDocument {\n return text.trim() === '' ? createEmptyDocument(BLANK_DOCUMENT_NAME) : parseDocumentJSON(text);\n}\n\nfunction collaborative(\n diagram: Modeler | NavigatedViewer,\n editable: boolean,\n): CollaborativeValueChainModeler {\n const eventBus = diagram.get<EventBus>('eventBus');\n const canvas = diagram.get<Canvas>('canvas');\n const elementRegistry = diagram.get<ElementRegistry>('elementRegistry');\n const selection = diagram.get<Selection>('selection');\n const contentListeners = new Set<() => void>();\n let destroyed = false;\n let lastExport = '';\n\n const meta: ModelerMeta = {\n notation: VALUE_CHAIN_NOTATION,\n apiVersion: MODELER_API_VERSION,\n editable,\n };\n\n if (editable) {\n // Imports erase the history without this event, so every delivery is a user's change.\n eventBus.on('commandStack.changed', () => {\n for (const listener of [...contentListeners]) listener();\n });\n }\n\n const elements: CollaborativeValueChainModeler['elements'] = {\n list: () =>\n destroyed ? [] : (elementRegistry.getAll() as unknown[]).filter(isVcShape).map(elementInfo),\n reveal(id) {\n if (destroyed) return false;\n const element = elementRegistry.get(id);\n if (!isVcShape(element)) return false;\n selection.select(element);\n canvas.scrollToElement(element);\n return true;\n },\n selection: () => (destroyed ? [] : shapeIds(selection.get())),\n onSelection(callback) {\n const listener = (event: unknown) =>\n callback(shapeIds((event as { newSelection?: unknown[] }).newSelection ?? []));\n eventBus.on('selection.changed', listener);\n return () => eventBus.off('selection.changed', listener);\n },\n bounds(id): ElementBounds | undefined {\n if (destroyed) return undefined;\n const element = elementRegistry.get(id);\n if (!isVcShape(element)) return undefined;\n const { x, y, width, height } = element;\n return { x, y, width, height };\n },\n };\n\n return {\n meta,\n elements,\n diagram,\n attachTo(host) {\n host.appendChild(diagram.container);\n canvas.resized();\n },\n importText(text): Promise<ImportResult> {\n if (destroyed) return Promise.reject(new Error('The modeler was destroyed.'));\n try {\n const warnings = diagram.importDocument(documentOf(text));\n return Promise.resolve({ warnings: warnings.map((warning) => warning.message) });\n } catch (error) {\n return Promise.reject(error instanceof Error ? error : new Error(String(error)));\n }\n },\n exportText() {\n // Asking a destroyed diagram would build a new one on the detached container.\n if (destroyed) return lastExport;\n return serializeDocument(diagram.exportDocument());\n },\n onContentChanged(callback) {\n if (!editable) return () => undefined;\n contentListeners.add(callback);\n return () => contentListeners.delete(callback);\n },\n getViewState(): ViewState | undefined {\n if (destroyed) return undefined;\n try {\n const { x, y, width, height } = canvas.viewbox();\n const state = { x, y, width, height };\n return isViewState(state) ? state : undefined;\n } catch {\n return undefined;\n }\n },\n setViewState(state) {\n if (destroyed || !isViewState(state)) return;\n canvas.viewbox({ x: state.x, y: state.y, width: state.width, height: state.height });\n },\n destroy() {\n if (destroyed) return;\n try {\n lastExport = serializeDocument(diagram.exportDocument());\n } catch {\n lastExport = '';\n }\n destroyed = true;\n contentListeners.clear();\n diagram.destroy();\n },\n };\n}\n\nfunction shapeIds(selected: readonly unknown[]): string[] {\n return selected.filter(isVcShape).map((element) => element.id);\n}\n\nfunction elementInfo(element: VcShape): ElementInfo {\n return element.vcLabel ? { id: element.id, name: element.vcLabel } : { id: element.id };\n}\n\nfunction isViewState(state: unknown): state is ViewState {\n if (typeof state !== 'object' || state === null) return false;\n const { x, y, width, height } = state as Record<string, unknown>;\n return (\n isFiniteNumber(x) &&\n isFiniteNumber(y) &&\n isFiniteNumber(width) &&\n isFiniteNumber(height) &&\n width > 0 &&\n height > 0\n );\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n","/*\n * The diagram's entries of the chrome menu (guide §5.4), the same in every host. The types mirror\n * the menu groups of `@miragon/modeler-shell` structurally, so an app hands the result to the\n * shell as it is while the renderer never imports the shell. Value chains have no Model entries:\n * no document setting is edited from the menu.\n */\n\n/** The icons the guide gives these entries (guide §5.14, the shell's common set). */\nexport type DiagramMenuIcon = 'file-image' | 'file-code-corner' | 'keyboard';\n\ninterface DiagramMenuItem {\n readonly id: string;\n readonly label: string;\n readonly icon?: DiagramMenuIcon;\n}\n\nexport interface DiagramMenuAction extends DiagramMenuItem {\n readonly kind: 'action';\n readonly shortcut?: string;\n onSelect(): void;\n}\n\nexport interface DiagramMenuDialog extends DiagramMenuItem {\n readonly kind: 'dialog';\n onSelect(): void;\n}\n\nexport interface DiagramMenu {\n readonly export: readonly DiagramMenuAction[];\n readonly help: readonly DiagramMenuDialog[];\n}\n\nexport interface DiagramExport {\n onSelect(): void;\n /** The chip of an app key that runs the same export, e.g. \"⌘S\". */\n readonly shortcut?: string | undefined;\n}\n\n/**\n * The exports a host offers, in the guide's order: PNG first (the more frequent target), then SVG,\n * then the document itself where the host is not the file (the web app).\n */\nexport interface DiagramExports {\n readonly png: DiagramExport;\n readonly svg: DiagramExport;\n readonly json?: DiagramExport | undefined;\n}\n\nexport interface DiagramMenuActions {\n readonly exports: DiagramExports;\n showKeyboardShortcuts(): void;\n}\n\nfunction exportEntry(\n id: string,\n label: string,\n action: DiagramExport,\n icon?: DiagramMenuIcon,\n): DiagramMenuAction {\n return {\n kind: 'action',\n id,\n label,\n ...(icon ? { icon } : {}),\n ...(action.shortcut ? { shortcut: action.shortcut } : {}),\n onSelect: () => action.onSelect(),\n };\n}\n\n/** The label of the JSON export, also its row in the shortcuts dialog's File group. */\nexport const JSON_EXPORT_LABEL = 'Export as JSON';\n\n/** The menu groups of the diagram (guide §5.4): Export with PNG first, Help. */\nexport function diagramMenu(actions: DiagramMenuActions): DiagramMenu {\n const { exports } = actions;\n return {\n export: [\n exportEntry('export-png', 'Export as PNG', exports.png, 'file-image'),\n exportEntry('export-svg', 'Export as SVG', exports.svg, 'file-code-corner'),\n ...(exports.json ? [exportEntry('export-json', JSON_EXPORT_LABEL, exports.json)] : []),\n ],\n help: [\n {\n kind: 'dialog',\n id: 'keyboard-shortcuts',\n label: 'Keyboard shortcuts…',\n icon: 'keyboard',\n onSelect: () => actions.showKeyboardShortcuts(),\n },\n ],\n };\n}\n","import { JSON_EXPORT_LABEL } from './menu.js';\n\n/*\n * Every shortcut of the diagram for the \"Keyboard shortcuts…\" dialog (guide §5.4): one table per\n * group, the keys as chips like the chrome tooltip's (guide §5.6). The chrome's texts and key\n * names come in structurally (a `@miragon/modeler-shell` handle fits), so the View rows say what\n * the zoom panel's tooltips say.\n */\n\nexport type ShortcutPlatform = 'mac' | 'other';\n\nexport interface ShortcutKeyNames {\n readonly ctrl: string;\n readonly shift: string;\n readonly plus: string;\n readonly minus: string;\n}\n\n/** What the shortcuts need of the chrome around the diagram. */\nexport interface ShortcutsChrome {\n readonly platform: ShortcutPlatform;\n /** The tool's UI language, for the percentage in \"Zoom to 100%\". */\n readonly lang: string;\n readonly messages: {\n readonly zoomIn: string;\n readonly zoomOut: string;\n zoomToActual(percent: string): string;\n readonly fit: string;\n /** The File group's \"Open…\" (the shell's `messages.openFile`); default \"Open…\". */\n readonly openFile?: string | undefined;\n readonly keyNames: ShortcutKeyNames;\n };\n}\n\nexport interface ShortcutRow {\n readonly action: string;\n /** Alternative key combinations, each shown as its own chip. */\n readonly keys: readonly string[];\n}\n\nexport interface ShortcutGroup {\n readonly title: string;\n readonly rows: readonly ShortcutRow[];\n}\n\nexport interface DiagramShortcutOptions {\n /** The web app's file keys: Cmd/Ctrl+O opens a file, Cmd/Ctrl+S exports the JSON document. */\n readonly fileKeys?: boolean | undefined;\n}\n\nconst ARROWS = ['←', '↑', '→', '↓'] as const;\n\n/** \"⌘O\" on macOS, \"Ctrl+O\" elsewhere: the chip of a Cmd/Ctrl key the app binds itself. */\nfunction commandKeyLabel(\n key: string,\n platform: ShortcutPlatform,\n keyNames: Pick<ShortcutKeyNames, 'ctrl'>,\n): string {\n return platform === 'mac' ? `⌘${key}` : `${keyNames.ctrl}+${key}`;\n}\n\nfunction percentOfActualSize(lang: string): string {\n try {\n return new Intl.NumberFormat(lang, { style: 'percent' }).format(1);\n } catch {\n return new Intl.NumberFormat('en', { style: 'percent' }).format(1);\n }\n}\n\n/** The chrome's zoom and fit keys as its tooltips name them (guide §5.8). */\nfunction viewKeys(platform: ShortcutPlatform, keyNames: ShortcutKeyNames) {\n if (platform === 'mac') {\n return { zoomIn: '⌘+', zoomOut: '⌘−', zoomToActual: '⌘0', fit: '⇧1' };\n }\n const { ctrl, shift, plus, minus } = keyNames;\n return {\n zoomIn: `${ctrl}+${plus}`,\n zoomOut: `${ctrl}+${minus}`,\n zoomToActual: `${ctrl}+0`,\n fit: `${shift}+1`,\n };\n}\n\nfunction editKeys(platform: ShortcutPlatform, keyNames: ShortcutKeyNames) {\n if (platform === 'mac') {\n return {\n undo: ['⌘Z'],\n redo: ['⌘⇧Z'],\n selectAll: ['⌘A'],\n copy: ['⌘C'],\n cut: ['⌘X'],\n paste: ['⌘V'],\n duplicate: ['⌘D'],\n remove: ['⌫'],\n coarseMove: ARROWS.map((arrow) => `⇧${arrow}`),\n moveCanvas: ARROWS.map((arrow) => `⌘${arrow}`),\n lassoDrag: ['⇧ Drag'],\n };\n }\n const { ctrl, shift } = keyNames;\n return {\n undo: [`${ctrl}+Z`],\n redo: [`${ctrl}+${shift}+Z`, `${ctrl}+Y`],\n selectAll: [`${ctrl}+A`],\n copy: [`${ctrl}+C`],\n cut: [`${ctrl}+X`],\n paste: [`${ctrl}+V`],\n duplicate: [`${ctrl}+D`],\n remove: ['Del', 'Backspace'],\n coarseMove: ARROWS.map((arrow) => `${shift}+${arrow}`),\n moveCanvas: ARROWS.map((arrow) => `${ctrl}+${arrow}`),\n lassoDrag: [`${shift}+Drag`],\n };\n}\n\nfunction fileGroup(chrome: ShortcutsChrome): ShortcutGroup {\n const { platform, messages } = chrome;\n return {\n title: 'File',\n rows: [\n {\n action: messages.openFile ?? 'Open…',\n keys: [commandKeyLabel('O', platform, messages.keyNames)],\n },\n { action: JSON_EXPORT_LABEL, keys: [commandKeyLabel('S', platform, messages.keyNames)] },\n ],\n };\n}\n\n/**\n * Every shortcut of the diagram, grouped as guide §5.4 asks (View, Edit, the notation's tools),\n * after the web app's File keys where it binds them.\n */\nexport function diagramShortcuts(\n chrome: ShortcutsChrome,\n options: DiagramShortcutOptions = {},\n): ShortcutGroup[] {\n const { platform, messages } = chrome;\n const view = viewKeys(platform, messages.keyNames);\n const edit = editKeys(platform, messages.keyNames);\n return [\n ...(options.fileKeys ? [fileGroup(chrome)] : []),\n {\n title: 'View',\n rows: [\n { action: messages.zoomIn, keys: [view.zoomIn] },\n { action: messages.zoomOut, keys: [view.zoomOut] },\n {\n action: messages.zoomToActual(percentOfActualSize(chrome.lang)),\n keys: [view.zoomToActual],\n },\n { action: messages.fit, keys: [view.fit] },\n { action: 'Move the canvas', keys: edit.moveCanvas },\n ],\n },\n {\n title: 'Edit',\n rows: [\n { action: 'Undo', keys: edit.undo },\n { action: 'Redo', keys: edit.redo },\n { action: 'Select all', keys: edit.selectAll },\n { action: 'Copy', keys: edit.copy },\n { action: 'Cut', keys: edit.cut },\n { action: 'Paste', keys: edit.paste },\n { action: 'Duplicate', keys: edit.duplicate },\n { action: 'Delete', keys: edit.remove },\n { action: 'Edit label', keys: ['E', 'Double-click'] },\n { action: 'Move selection', keys: ARROWS },\n { action: 'Move selection in large steps', keys: edit.coarseMove },\n ],\n },\n {\n title: 'Tools',\n rows: [\n { action: 'Lasso', keys: ['L'] },\n { action: 'Lasso by dragging', keys: edit.lassoDrag },\n { action: 'Hand', keys: ['H'] },\n { action: 'Hand while held', keys: ['Space'] },\n { action: 'Create or remove space', keys: ['S'] },\n { action: 'Connect', keys: ['C'] },\n ],\n },\n ];\n}\n","import { lucideIcon } from '../draw/lucide.js';\nimport {\n diagramShortcuts,\n type DiagramShortcutOptions,\n type ShortcutGroup,\n type ShortcutsChrome,\n} from './shortcuts.js';\n\nconst DIALOG_CLASS = 'vc-shortcuts';\nconst TITLE_ID = 'vc-shortcuts-title';\n\n/** What the dialog needs of the chrome around the diagram; a `@miragon/modeler-shell` handle fits. */\nexport interface ShortcutsDialogChrome extends ShortcutsChrome {\n /** Where the dialog lives (the shell root), so it shares the chrome's mode and fonts. */\n readonly root: HTMLElement;\n readonly messages: ShortcutsChrome['messages'] & { readonly close: string };\n /** The control the focus returns to once the dialog closes. */\n readonly menu: { readonly trigger: HTMLElement };\n}\n\nexport interface ShortcutsDialog {\n open(): void;\n isOpen(): boolean;\n close(): void;\n destroy(): void;\n}\n\nfunction element<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n className: string,\n text?: string,\n): HTMLElementTagNameMap[K] {\n const created = document.createElement(tag);\n created.className = className;\n if (text !== undefined) created.textContent = text;\n return created;\n}\n\nfunction shortcutTable(group: ShortcutGroup, index: number): HTMLElement {\n const section = element('section', `${DIALOG_CLASS}-group`);\n const headingId = `${TITLE_ID}-group-${index}`;\n const heading = element('h4', `${DIALOG_CLASS}-group-title`, group.title);\n heading.id = headingId;\n const table = element('table', `${DIALOG_CLASS}-table`);\n table.setAttribute('aria-labelledby', headingId);\n const body = table.createTBody();\n for (const row of group.rows) {\n const line = body.insertRow();\n const action = element('th', `${DIALOG_CLASS}-action`, row.action);\n action.scope = 'row';\n const keys = element('td', `${DIALOG_CLASS}-keys`);\n for (const key of row.keys) keys.append(element('kbd', `${DIALOG_CLASS}-key`, key));\n line.append(action, keys);\n }\n section.append(heading, table);\n return section;\n}\n\nfunction dialogContent(\n chrome: ShortcutsDialogChrome,\n options: DiagramShortcutOptions,\n onClose: () => void,\n): HTMLElement {\n const panel = element('div', `${DIALOG_CLASS}-panel`);\n const header = element('header', `${DIALOG_CLASS}-header`);\n const title = element('h3', `${DIALOG_CLASS}-title`, 'Keyboard shortcuts');\n title.id = TITLE_ID;\n const close = element('button', `${DIALOG_CLASS}-close`);\n close.type = 'button';\n close.setAttribute('aria-label', chrome.messages.close);\n close.innerHTML = lucideIcon('x');\n close.addEventListener('click', onClose);\n header.append(title, close);\n\n const body = element('div', `${DIALOG_CLASS}-body`);\n body.append(...diagramShortcuts(chrome, options).map(shortcutTable));\n panel.append(header, body);\n return panel;\n}\n\n/**\n * The \"Keyboard shortcuts…\" dialog of the Help group (guide §5.4, §8), a native modal <dialog>\n * inside the chrome's root: the browser keeps the focus inside it, closes it on Escape and puts it\n * in the top layer. Built on the first open and kept (closed) afterwards; the host calls\n * `destroy()` with the diagram's teardown, since the chrome removes only what it added itself.\n */\nexport function createShortcutsDialog(\n chrome: ShortcutsDialogChrome,\n options: DiagramShortcutOptions = {},\n): ShortcutsDialog {\n let dialog: HTMLDialogElement | undefined;\n\n function build(): HTMLDialogElement {\n const created = element('dialog', DIALOG_CLASS);\n created.setAttribute('aria-labelledby', TITLE_ID);\n created.append(dialogContent(chrome, options, () => created.close()));\n // A click on the backdrop targets the <dialog> itself; the panel covers all of its own box.\n created.addEventListener('click', (event) => {\n if (event.target === created) created.close();\n });\n created.addEventListener('close', () => {\n if (!chrome.menu.trigger.hidden) chrome.menu.trigger.focus({ preventScroll: true });\n });\n chrome.root.append(created);\n return created;\n }\n\n return {\n open() {\n dialog ??= build();\n if (!dialog.open) dialog.showModal();\n },\n close() {\n dialog?.close();\n },\n isOpen: () => dialog?.open === true,\n destroy() {\n dialog?.remove();\n dialog = undefined;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAM2C,KAAiB,IAGjBC,KAAe;CAAE,GAAG;CAAG,GAAG;CAAG,OAAO;CAAK,QAAQ;AAAI,GAGrDC,KAAyB;CAAC;CAAY;CAAQ;CAAc;AAAsB;AAOxF,SAAgBC,EAAQ,GAAgB,GAA0D;CAGhG,IAAMC,IAAS,CAAC,GAAGC,EAAO,aAAa,CAAC,CAAC,QAAQ,CAAC,CAAC,MAChD,MAAkCC,aAAiB,aACtD;CACA,IAAI,CAACF,GACH,MAAU,MAAM,uCAAuC;CAGzD,IAAMG,IAAMC,EAAO,cAAcR,EAAc,KAAKC,IAE9CQ,IAAQL,EAAO,UAAU,EAAI;CACnC,KAAK,IAAMM,KAAaR,IACtB,EAAM,gBAAgBQ,CAAS;CAKjC,AAH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AAIvP,EAAM,WAAWuP,KAASA,EAAQ,MAAM;EAC9C,CAAC,GACDA,EAAQ,iBAAiB,eAAe;GACtC,AAAKuI,EAAO,KAAK,QAAQ,UAAQA,EAAO,KAAK,QAAQ,MAAM,EAAE,eAAe,GAAK,CAAC;EACpF,CAAC,GACDA,EAAO,KAAK,OAAOvI,CAAO,GACnBA;CACT;CAEA,OAAO;EACL,OAAO;GAEL,AADA,MAAW8J,EAAM,GACZD,EAAO,QAAMA,EAAO,UAAU;EACrC;EACA,QAAQ;GACN,GAAQ,MAAM;EAChB;EACA,cAAcA,GAAQ,SAAS;EAC/B,UAAU;GAER,AADAA,GAAQ,OAAO,GACf,IAAS,KAAA;EACX;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["svgCreate","ICONS","Diagram","ElementFactory","BaseRenderer","TextUtil","SelectionModule","ZoomScrollModule","MoveCanvasModule","ModelingModule","MoveModule","OutlineModule","BendpointsModule","AutoScrollModule","GridSnappingModule","SnappingModule","KeyboardMoveSelectionModule","KeyboardMoveModule","CroppingConnectionDocking","BaseLayouter","CommandInterceptor","RulesModule","RuleProvider","ConnectModule","AutoPlaceModule","CreateModule","ConnectionPreviewModule","PaletteModule","HandToolModule","LassoToolModule","SpaceToolModule","GlobalConnectModule","ContextPadModule","PopupMenuModule","DirectEditingModule","AlignElementsModule","DistributeElementsModule","KeyboardModule","EditorActionsModule","KeyboardBindings","OrderingProvider","CopyPasteModule","ResizeModule","EXPORT_PADDING","EMPTY_EXPORT","LIVE_CANVAS_ATTRIBUTES","saveSVG","source","canvas","child","box","bounds","clone","attribute","viewport","isObject","value","isVcShape","element","\"vcType\"","isStep","isOrgUnit","isVcConnection","isVcElement","VcBaseViewer","options","name","event","priority","callback","valid","validateDocument","document","labelEditing","previous","warnings","error","target","importer","container","sizeToCss","modules","VcElementFactory","elementFactory","connection","point","DEFAULT_STEP_SIZE","label","DEFAULT_ORG_UNIT_SIZE","ID_ALPHABET","ID_LENGTH","PREFIXES","randomSuffix","bytes","byte","VcDiagramElementFactory","elementRegistry","withId","attrs","type","vcType","prefix","id","vcModelModule","notchDepth","height","width","chevronPath","chevronPathAt","labelInset","depth","d","my","y","x","ellipsePathAt","rx","ry","cx","hell","COLORS","FONT","COLOR_OPTIONS","VC_RENDER_PRIORITY","ARROW_PATH","rendererInstances","VcRenderer","eventBus","graphicsFactory","fonts","font","destroyed","faces","shape","stroke","orgUnit","path","create","attr","append","visuals","inset","svg","line","createLine","first","rest","color","defs","marker","arrow","vcDrawModule","VcBounds","elements","getBBox","padding","vcBoundsModule","ROOT_ID","FIT_PADDING","SMALLEST_FIT_ZOOM","VcImporter","vcElementFactory","vcBounds","config","root","documentExtensions","metaExtensions","shapeById","connectionIndex","roots","other","scale","VcExporter","connections","imported","connectionExtensions","extensions","elementExtensions","link","CURRENT_SCHEMA_VERSION","svgToPng","svgSize","url","image","resolve","reject","context","blob","blobToBase64","reader","ioModule","Viewer","NavigatedViewer","UpdatePropertiesHandler","old","key","properties","setOrDelete","oldProperties","UPDATE_PROPERTIES","VcModeling","commandStack","TRUNK_MARGIN","BUS_MIN_STUB","EXIT_MARGIN","VcLayouter","connectionDocking","hints","waypoints","isHierarchy","stub","result","allFinite","fallback","getMid","interior","sourceMid","targetMid","children","hierarchyChildren","group","isRowArrangement","withoutRedundantPoints","connectPoints","bottom","topmost","busY","minChildX","trunkX","connectRectangles","hierarchyDropSpan","tops","ROW_TOLERANCE_Y","centerX","span","points","VcConnectionTypeBehavior","modeling","VcHierarchyRelayoutBehavior","layouter","shapes","parents","hierarchyEdges","incoming","parent","edge","sameWaypoints","a","b","index","vcModelingModule","VcRules","vcConnect","hasConnection","endpointsAllowed","isRoot","pending","ignore","vcRulesModule","VcConnect","connect","vcConnectModule","VcAppend","autoPlace","factory","newShape","BEFORE_DEFAULT","SEQUENCE_GAP_X","HIERARCHY_GAP_Y","SIBLING_GAP_Y","SIBLING_GAP_X","DECONFLICT_STEP_Y","DECONFLICT_MARGIN","VcAutoPlaceBehavior","desired","anchor","rightmost","bottommost","steps","candidate","position","attempt","step","best","vcAppendModule","connectionPreview","injector","canConnect","LUCIDE","CHROME_ICON","PALETTE_TOOL_ICON","lucideIcon","glyph","viewBox","content","preview","ICONS","paletteEntryHtml","draggable","iconSvg","contextPadEntryHtml","KEYBOARD_CREATE_OFFSET","VcPaletteProvider","handTool","lassoTool","spaceTool","globalConnect","selection","palette","creator","isKeyboardClick","createStep","createOrgUnit","centre","created","area","middle","start","end","size","insets","vcPaletteModule","COLOR_PICKER_PROVIDER_ID","swatch","VcColorPickerProvider","vcModeling","popupMenu","entries","option","ALIGN_MENU_PROVIDER_ID","alignIcon","ICONS$1","VcAlignMenuProvider","alignElements","distributeElements","align","icon","VcContextPadProvider","vcAppend","readOnly","contextPad","startConnect","mouse","\"delete\"","\"align\"","appendDrag","vcContextPadModule","VcLabelEditingProvider","directEditing","canExecute","open","edit","active","textbox","\"fontSize\"","bbox","zoom","sanitizeLabel","newText","text","vcLabelEditingModule","vcColorPickerModule","vcAlignMenuModule","UNDO_REDO_ACTIONS","VcKeyboardBindings","keyboard","boundActions","editorActions","action","addListener","listener","bindTool","isKey","keys","hasModifier","isCmd","HIGH_PRIORITY","VcEditorActions","lock","unlocked","register","service","serviceName","allowed","run","tool","selected","vcKeyboardModule","VcOrderingProvider","newParent","vcOrderingModule","VcCopyPasteBehavior","\"vcLabel\"","\"color\"","\"link\"","vcCopyPasteModule","VcResizeBehavior","MIN_STEP_SIZE","minDimensions","vcResizeModule","READ_ONLY_CHANGED_EVENT","LOCK_PRIORITY","EDIT_RULES","VcReadOnly","bus","optional","vcReadOnlyModule","Modeler","VALUE_CHAIN_NOTATION","BLANK_DOCUMENT_NAME","createCollaborativeModeler","collaborative","diagramOptions","createCollaborativeViewer","documentOf","createEmptyDocument","parseDocumentJSON","diagram","contentListeners","lastExport","meta","MODELER_API_VERSION","editable","elementInfo","shapeIds","host","warning","serializeDocument","state","isViewState","isFiniteNumber","exportEntry","JSON_EXPORT_LABEL","diagramMenu","actions","exports","ARROWS","commandKeyLabel","platform","keyNames","percentOfActualSize","lang","viewKeys","ctrl","plus","minus","shift","editKeys","fileGroup","chrome","messages","diagramShortcuts","view","DIALOG_CLASS","TITLE_ID","tag","className","shortcutTable","section","headingId","heading","table","body","row","dialogContent","panel","header","title","close","onClose","createShortcutsDialog","dialog","build"],"sources":["../src/io/saveSvg.ts","../src/model/di-types.ts","../src/VcBaseViewer.ts","../src/model/VcElementFactory.ts","../src/model/VcDiagramElementFactory.ts","../src/model/index.ts","../src/draw/geometry.ts","../src/theme/cd-tokens.generated.json","../src/draw/styles.ts","../src/draw/VcRenderer.ts","../src/draw/index.ts","../src/bounds/VcBounds.ts","../src/bounds/index.ts","../src/io/types.ts","../src/io/VcImporter.ts","../src/io/VcExporter.ts","../src/io/png.ts","../src/io/index.ts","../src/Viewer.ts","../src/NavigatedViewer.ts","../src/modeling/cmd/UpdatePropertiesHandler.ts","../src/modeling/VcModeling.ts","../src/modeling/VcLayouter.ts","../src/modeling/VcConnectionTypeBehavior.ts","../src/modeling/VcHierarchyRelayoutBehavior.ts","../src/modeling/index.ts","../src/rules/VcRules.ts","../src/rules/index.ts","../src/connect/VcConnect.ts","../src/connect/index.ts","../src/append/VcAppend.ts","../src/append/VcAutoPlaceBehavior.ts","../src/append/VcCreatePreviewBehavior.ts","../src/append/index.ts","../src/draw/lucide.ts","../src/draw/icons.ts","../src/palette/VcPaletteProvider.ts","../src/palette/index.ts","../src/popup/VcColorPickerProvider.ts","../src/popup/VcAlignMenuProvider.ts","../src/context-pad/VcContextPadProvider.ts","../src/context-pad/index.ts","../src/label-editing/VcLabelEditingProvider.ts","../src/label-editing/index.ts","../src/popup/index.ts","../src/keyboard/VcKeyboardBindings.ts","../src/keyboard/VcEditorActions.ts","../src/keyboard/index.ts","../src/ordering/VcOrderingProvider.ts","../src/ordering/index.ts","../src/copy-paste/VcCopyPasteBehavior.ts","../src/copy-paste/index.ts","../src/resize/VcResizeBehavior.ts","../src/resize/index.ts","../src/read-only/VcReadOnly.ts","../src/read-only/index.ts","../src/Modeler.ts","../src/collaborative/CollaborativeValueChain.ts","../src/diagram-menu/menu.ts","../src/diagram-menu/shortcuts.ts","../src/diagram-menu/ShortcutsDialog.ts"],"sourcesContent":["import type Canvas from 'diagram-js/lib/core/Canvas';\nimport type VcBounds from '../bounds/VcBounds.js';\n\nconst EXPORT_PADDING = 20;\n\n/** What the empty canvas exports: a blank sheet of this size at the origin. */\nconst EMPTY_EXPORT = { x: 0, y: 0, width: 800, height: 600 };\n\n/** Attributes the live canvas carries for keyboard and screen-reader use, not for a picture. */\nconst LIVE_CANVAS_ATTRIBUTES = ['tabindex', 'role', 'aria-label', 'aria-roledescription'];\n\n/**\n * Standalone SVG export: clones the live SVG, sets a viewBox around the diagram contents and\n * strips the pan/zoom transform. Fonts and colours are SVG presentation attributes, so the\n * result renders identically outside the editor and stays light in every mode.\n */\nexport function saveSVG(canvas: Canvas, bounds: Pick<VcBounds, 'contentBounds'>): { svg: string } {\n // The canvas's own <svg> child: a host chrome may move the palette, with its icon <svg>s, in\n // front of it inside the same container.\n const source = [...canvas.getContainer().children].find(\n (child): child is SVGSVGElement => child instanceof SVGSVGElement,\n );\n if (!source) {\n throw new Error('No SVG found in the canvas container.');\n }\n\n const box = bounds.contentBounds(EXPORT_PADDING) ?? EMPTY_EXPORT;\n\n const clone = source.cloneNode(true) as SVGSVGElement;\n for (const attribute of LIVE_CANVAS_ATTRIBUTES) {\n clone.removeAttribute(attribute);\n }\n clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');\n clone.setAttribute('viewBox', `${box.x} ${box.y} ${box.width} ${box.height}`);\n clone.setAttribute('width', String(box.width));\n clone.setAttribute('height', String(box.height));\n\n const viewport = clone.querySelector<SVGGElement>('.viewport');\n if (viewport) {\n viewport.removeAttribute('transform');\n }\n\n const svg = new XMLSerializer().serializeToString(clone);\n return { svg: `<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n${svg}` };\n}\n","import type { Connection, Shape } from 'diagram-js/lib/model/Types';\nimport type {\n ChainConnection,\n ConnectionType,\n DiagramElement,\n} from '@miragon/value-chain-schema-model';\n\nexport type VcShapeType = 'step' | 'orgUnit';\n\n/**\n * Runtime model: diagram-js elements carry the editable domain truth as flat properties\n * (`vcType`, `vcLabel`, `color`, `link`). The `businessObject` is only an import-time\n * snapshot used as fallback for fields the UI cannot edit.\n */\nexport interface VcShape extends Shape {\n vcType: VcShapeType;\n vcLabel: string;\n color?: string;\n link?: string;\n businessObject?: DiagramElement;\n}\n\nexport interface VcConnection extends Connection {\n vcType: ConnectionType;\n businessObject?: ChainConnection;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nexport function isVcShape(element: unknown): element is VcShape {\n return isObject(element) && (element['vcType'] === 'step' || element['vcType'] === 'orgUnit');\n}\n\nexport function isStep(element: unknown): element is VcShape & { vcType: 'step' } {\n return isObject(element) && element['vcType'] === 'step';\n}\n\nexport function isOrgUnit(element: unknown): element is VcShape & { vcType: 'orgUnit' } {\n return isObject(element) && element['vcType'] === 'orgUnit';\n}\n\nexport function isVcConnection(element: unknown): element is VcConnection {\n return (\n isObject(element) &&\n (element['vcType'] === 'sequence' ||\n element['vcType'] === 'hierarchy' ||\n element['vcType'] === 'assignment') &&\n 'waypoints' in element\n );\n}\n\nexport function isVcElement(element: unknown): element is VcShape | VcConnection {\n return isVcShape(element) || isVcConnection(element);\n}\n","import Diagram from 'diagram-js/lib/Diagram';\nimport type { ModuleDeclaration } from 'didi';\nimport type { CollaborativeModelerOptions } from '@miragon/modeler-api';\nimport type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { EventBusEventCallback } from 'diagram-js/lib/core/EventBus';\nimport {\n validateDocument,\n type Point,\n type ValueChainDocument,\n} from '@miragon/value-chain-schema-model';\nimport type VcBounds from './bounds/VcBounds.js';\nimport type VcImporter from './io/VcImporter.js';\nimport type VcExporter from './io/VcExporter.js';\nimport { saveSVG } from './io/saveSvg.js';\nimport type { ImportWarning } from './io/types.js';\nimport type VcLabelEditingProvider from './label-editing/VcLabelEditingProvider.js';\nimport { isVcElement } from './model/di-types.js';\n\n/**\n * `freeArea`, `fitOnImport` and `undoRedoKeys` as `@miragon/modeler-api` 1.2 names them:\n * `freeArea` is where Enter or Space on a creating palette entry places the element (the centre of\n * the canvas area the host's chrome leaves free, guide §5.5; default the centre of the visible\n * canvas), `fitOnImport: false` leaves the view after an import to the host, and\n * `undoRedoKeys: false` leaves Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z and Ctrl+Y to a host that owns the\n * history (the VS Code document).\n */\nexport interface VcViewerOptions extends CollaborativeModelerOptions {\n /** Host element. If missing, a detached <div> is created (attach later via attachTo). */\n container?: HTMLElement;\n width?: number | string;\n height?: number | string;\n /** Concatenated to the end of the module list (extension point). */\n additionalModules?: ModuleDeclaration[];\n /**\n * @deprecated Use `freeArea: { center }`; accepted until the next minor release. Given both,\n * `freeArea` wins.\n */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\ninterface CommandStackLike {\n clear(emit?: boolean): void;\n}\n\ninterface PopupMenuLike {\n close(): void;\n}\n\n/**\n * DI bootstrap and lifecycle shared by Viewer/NavigatedViewer/Modeler. The diagram is\n * created lazily on first access; `_getModules()` is a method (not a class field) to\n * avoid subclass field-initialization-order problems.\n */\nexport abstract class VcBaseViewer {\n protected abstract _getModules(): ModuleDeclaration[];\n\n private _diagram: Diagram | undefined;\n private readonly _container: HTMLElement;\n private readonly _options: VcViewerOptions;\n\n constructor(options: VcViewerOptions = {}) {\n this._options = options;\n this._container = this._createContainer(options);\n }\n\n get container(): HTMLElement {\n return this._container;\n }\n\n get<T>(name: string): T {\n return this._ensureDiagram().get<T>(name);\n }\n\n /** Like get(), but returns null instead of throwing when the service is absent. */\n getOptional<T>(name: string): T | null {\n return (this._ensureDiagram().get<T>(name, false) as T | null) ?? null;\n }\n\n on<T = unknown>(event: string, callback: EventBusEventCallback<T>, priority = 1000): void {\n this.get<EventBus>('eventBus').on(event, priority, callback as EventBusEventCallback<unknown>);\n }\n\n off<T = unknown>(event: string, callback: EventBusEventCallback<T>): void {\n this.get<EventBus>('eventBus').off(event, callback as EventBusEventCallback<unknown>);\n }\n\n /**\n * Replaces the current diagram contents and erases the undo history, silently: no\n * `commandStack.changed`, since an import is no edit a host should save. The document is\n * validated before the canvas is touched, so a rejected one leaves no trace; an open label edit\n * is taken down without committing and reopened afterwards when its element is still there.\n */\n importDocument(document: ValueChainDocument): ImportWarning[] {\n const valid = validateDocument(document);\n const labelEditing = this.getOptional<VcLabelEditingProvider>('vcLabelEditingProvider');\n const previous = this._currentDocument();\n labelEditing?.suspend();\n this.getOptional<PopupMenuLike>('popupMenu')?.close();\n let warnings: ImportWarning[];\n try {\n warnings = this._render(valid);\n } catch (error) {\n if (previous) {\n this._render(previous);\n }\n throw error;\n }\n labelEditing?.resumeAfterImport();\n return warnings;\n }\n\n exportDocument(): ValueChainDocument {\n return this.get<VcExporter>('vcExporter').export();\n }\n\n saveSVG(): { svg: string } {\n return saveSVG(this.get<Canvas>('canvas'), this.get<VcBounds>('vcBounds'));\n }\n\n /** Zooms to fit the diagram, never above 100%. */\n fitViewport(): void {\n const canvas = this.get<Canvas>('canvas');\n const hasContent = this.get<ElementRegistry>('elementRegistry').getAll().some(isVcElement);\n if (!hasContent) {\n return;\n }\n canvas.zoom('fit-viewport');\n if (canvas.zoom() > 1) {\n canvas.zoom(1);\n }\n }\n\n clear(): void {\n this.get<VcImporter>('vcImporter').clear();\n this.getOptional<CommandStackLike>('commandStack')?.clear();\n }\n\n attachTo(target: HTMLElement): void {\n this.detach();\n target.appendChild(this._container);\n this.get<Canvas>('canvas').resized();\n }\n\n detach(): void {\n this._container.parentNode?.removeChild(this._container);\n }\n\n destroy(): void {\n this._diagram?.destroy();\n this._diagram = undefined;\n this.detach();\n }\n\n private _render(document: ValueChainDocument): ImportWarning[] {\n const importer = this.get<VcImporter>('vcImporter');\n importer.clear();\n const warnings = importer.import(document);\n this.getOptional<CommandStackLike>('commandStack')?.clear(false);\n this.get<EventBus>('eventBus').fire('import.done', { warnings });\n return warnings;\n }\n\n private _currentDocument(): ValueChainDocument | undefined {\n try {\n return this.exportDocument();\n } catch {\n return undefined;\n }\n }\n\n private _createContainer(options: VcViewerOptions): HTMLElement {\n const container = options.container ?? document.createElement('div');\n container.classList.add('vc-container');\n container.style.width = sizeToCss(options.width ?? '100%');\n container.style.height = sizeToCss(options.height ?? (options.container ? '100%' : '600px'));\n return container;\n }\n\n private _ensureDiagram(): Diagram {\n if (!this._diagram) {\n const modules = [...this._getModules(), ...(this._options.additionalModules ?? [])];\n this._diagram = new Diagram({\n canvas: { container: this._container },\n modules,\n vcPalette: {\n freeArea: this._options.freeArea,\n freeRectCenter: this._options.freeRectCenter,\n },\n vcKeyboard: { undoRedoKeys: this._options.undoRedoKeys ?? true },\n vcImport: { fitOnImport: this._options.fitOnImport ?? true },\n });\n }\n return this._diagram;\n }\n}\n\nfunction sizeToCss(value: number | string): string {\n return typeof value === 'number' ? `${value}px` : value;\n}\n","import type ElementFactory from 'diagram-js/lib/core/ElementFactory';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport {\n DEFAULT_ORG_UNIT_SIZE,\n DEFAULT_STEP_SIZE,\n type ChainConnection,\n type DiagramElement,\n} from '@miragon/value-chain-schema-model';\nimport type { VcConnection, VcShape } from './di-types.js';\n\n/**\n * Domain-aware factory: builds diagram-js shapes/connections from schema-model elements\n * (import) and blank ones for palette/context-pad creation.\n */\nexport default class VcElementFactory {\n static $inject = ['elementFactory'];\n\n constructor(private readonly elementFactory: ElementFactory) {}\n\n createElement(element: DiagramElement): VcShape {\n return this.elementFactory.createShape({\n id: element.id,\n x: element.bounds.x,\n y: element.bounds.y,\n width: element.bounds.width,\n height: element.bounds.height,\n vcType: element.elementType,\n vcLabel: element.name,\n ...(element.color !== undefined ? { color: element.color } : {}),\n ...(element.elementType === 'step' && element.link !== undefined\n ? { link: element.link }\n : {}),\n businessObject: element,\n }) as VcShape;\n }\n\n createConnection(connection: ChainConnection, source: Shape, target: Shape): VcConnection {\n return this.elementFactory.createConnection({\n id: connection.id,\n source,\n target,\n waypoints: connection.waypoints.map((point) => ({ x: point.x, y: point.y })),\n vcType: connection.connectionType,\n businessObject: connection,\n }) as VcConnection;\n }\n\n /**\n * A blank step for interactive creation: no id/position — diagram-js assigns the id,\n * the create/auto-place interaction assigns the position.\n */\n createNewStep(label = ''): VcShape {\n return this.elementFactory.createShape({\n width: DEFAULT_STEP_SIZE.width,\n height: DEFAULT_STEP_SIZE.height,\n vcType: 'step',\n vcLabel: label,\n }) as VcShape;\n }\n\n /** A blank organizational unit for interactive creation. */\n createNewOrgUnit(label = ''): VcShape {\n return this.elementFactory.createShape({\n width: DEFAULT_ORG_UNIT_SIZE.width,\n height: DEFAULT_ORG_UNIT_SIZE.height,\n vcType: 'orgUnit',\n vcLabel: label,\n }) as VcShape;\n }\n}\n","import ElementFactory from 'diagram-js/lib/core/ElementFactory';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type { Connection, Label, Root, Shape } from 'diagram-js/lib/model/Types';\n\nconst ID_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';\nconst ID_LENGTH = 8;\n\n/** The id prefix of a new element: its value chain type where it has one. */\nconst PREFIXES: Readonly<Record<string, string>> = {\n step: 'step',\n orgUnit: 'org',\n sequence: 'sequence',\n hierarchy: 'hierarchy',\n assignment: 'assignment',\n};\n\nfunction randomSuffix(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(ID_LENGTH));\n return Array.from(bytes, (byte) => ID_ALPHABET[byte % ID_ALPHABET.length]).join('');\n}\n\n/**\n * Replaces the stock elementFactory: an element created on the canvas gets a random id (for\n * example `step_k3x9q2mf`), probed against the element registry. Two people editing one document\n * at the same time thus never create two elements with the same id, which a per-instance counter\n * (`shape_1` on both sides) would.\n */\nexport default class VcDiagramElementFactory extends ElementFactory {\n static $inject = ['elementRegistry'];\n\n constructor(private readonly elementRegistry: ElementRegistry) {\n super();\n }\n\n override create(type: 'root', attrs?: Partial<Root>): Root;\n override create(type: 'shape', attrs?: Partial<Shape>): Shape;\n override create(type: 'connection', attrs?: Partial<Connection>): Connection;\n override create(type: 'label', attrs?: Partial<Label>): Label;\n override create(\n type: 'root' | 'shape' | 'connection' | 'label',\n attrs?: Partial<Root & Shape & Connection & Label>,\n ): Root | Shape | Connection | Label {\n const withId = attrs?.id ? attrs : { ...attrs, id: this.unusedId(type, attrs) };\n switch (type) {\n case 'root':\n return super.create(type, withId);\n case 'shape':\n return super.create(type, withId);\n case 'connection':\n return super.create(type, withId);\n case 'label':\n return super.create(type, withId);\n }\n }\n\n private unusedId(type: string, attrs: Record<string, unknown> | undefined): string {\n const vcType = attrs?.['vcType'];\n const prefix = (typeof vcType === 'string' && PREFIXES[vcType]) || type;\n let id: string;\n do {\n id = `${prefix}_${randomSuffix()}`;\n } while (this.elementRegistry.get(id));\n return id;\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport VcElementFactory from './VcElementFactory.js';\nimport VcDiagramElementFactory from './VcDiagramElementFactory.js';\n\n/**\n * Domain-aware element creation (schema-model element → diagram-js element) plus an\n * elementFactory override with registry-probed id generation.\n */\nexport const vcModelModule: ModuleDeclaration = {\n elementFactory: ['type', VcDiagramElementFactory],\n vcElementFactory: ['type', VcElementFactory],\n};\n\nexport { default as VcElementFactory } from './VcElementFactory.js';\nexport { default as VcDiagramElementFactory } from './VcDiagramElementFactory.js';\nexport * from './di-types.js';\n","/**\n * Chevron (\"Blockpfeil\") geometry of a value chain step: flat top/bottom, a point on the\n * right and a matching notch cut into the left edge. Point/notch depth is half the height\n * (45° edges, the canonical ARIS/PowerPoint look), clamped so narrow steps don't degenerate.\n */\nexport function notchDepth(width: number, height: number): number {\n return Math.min(height / 2, 0.4 * width);\n}\n\n/** Shape-local chevron path for a step of the given size. */\nexport function chevronPath(width: number, height: number): string {\n return chevronPathAt(0, 0, width, height);\n}\n\n/**\n * Horizontal label inset. Less than the full notch depth: lines sit around the vertical\n * middle where the 45° notch/point edges leave `fontSize`-dependent extra room.\n */\nexport function labelInset(width: number, height: number): number {\n const depth = notchDepth(width, height);\n return Math.max(7, depth - 5);\n}\n\n/** Absolute chevron path, as consumed by diagram-js outline/cropping via getShapePath. */\nexport function chevronPathAt(x: number, y: number, width: number, height: number): string {\n const d = notchDepth(width, height);\n const my = y + height / 2;\n return [\n `M${x},${y}`,\n `L${x + width - d},${y}`,\n `L${x + width},${my}`,\n `L${x + width - d},${y + height}`,\n `L${x},${y + height}`,\n `L${x + d},${my}`,\n 'Z',\n ].join('');\n}\n\n/** Ellipse path (organizational unit), arc-based so cropping intersects exactly. */\nexport function ellipsePathAt(x: number, y: number, width: number, height: number): string {\n const rx = width / 2;\n const ry = height / 2;\n const cx = x + rx;\n return [\n `M${cx},${y}`,\n `A${rx},${ry} 0 0 1 ${cx},${y + height}`,\n `A${rx},${ry} 0 0 1 ${cx},${y}`,\n 'Z',\n ].join('');\n}\n","{\n \"$description\": \"AUTOMATISCH GENERIERT aus brand/tokens.json. Nicht von Hand ändern, sondern die Quelle bearbeiten und `npm run tokens:build` laufen lassen. Rollen (--cd-ui-*) je Modus, für Renderer, Exporte, Drift-Tests und Hosts. Renderer zeichnen und exportieren mit hell, dunkel kommt nur über CSS. hochkontrast enthält die Rollen, die sich bei data-cd-kontrast=\\\"hoch\\\" ändern. fest sind die Farben, die in beiden Modi gleich bleiben. shell sind die Maße und Ebenen der App-Shell der Modeler (Einpassen, Breakpoint, z-index), mit denselben Werten wie --cd-shell-* in der CSS.\",\n \"hell\": {\n \"--cd-ui-grund\": \"#F9F7F7\",\n \"--cd-ui-flaeche\": \"#FFFFFF\",\n \"--cd-ui-flaeche-hoch\": \"#FFFFFF\",\n \"--cd-ui-hover\": \"#EEF1FD\",\n \"--cd-ui-plot\": \"#FFFFFF\",\n \"--cd-ui-seite\": \"#FFFFFF\",\n \"--cd-ui-abschnitt\": \"#F9F7F7\",\n \"--cd-ui-linie\": \"#E6E2E2\",\n \"--cd-ui-kontur\": \"#8F8A8A\",\n \"--cd-ui-text\": \"#1D1D1D\",\n \"--cd-ui-text-leise\": \"#6B6666\",\n \"--cd-ui-link\": \"#2B50D4\",\n \"--cd-ui-icon-akzent\": \"#335DE5\",\n \"--cd-ui-fokus\": \"#2B50D4\",\n \"--cd-ui-interaktion\": \"#335DE5\",\n \"--cd-ui-success\": \"#00E676\",\n \"--cd-ui-warning\": \"#FFB000\",\n \"--cd-ui-danger\": \"#CD1839\",\n \"--cd-ui-info\": \"#335DE5\",\n \"--cd-ui-success-flaeche\": \"#DAFBEB\",\n \"--cd-ui-warning-flaeche\": \"#FFF1D2\",\n \"--cd-ui-danger-flaeche\": \"#FBEEF0\",\n \"--cd-ui-info-flaeche\": \"#EEF1FD\",\n \"--cd-ui-wortmarke\": \"#00E676\",\n \"--cd-ui-backdrop\": \"rgba(29, 29, 29, 0.42)\",\n \"--cd-ui-chrome-deckkraft\": \"84%\"\n },\n \"dunkel\": {\n \"--cd-ui-grund\": \"#1D1D1D\",\n \"--cd-ui-flaeche\": \"#282828\",\n \"--cd-ui-flaeche-hoch\": \"#2F2F2F\",\n \"--cd-ui-hover\": \"#383838\",\n \"--cd-ui-plot\": \"#1D1D1D\",\n \"--cd-ui-seite\": \"#1D1D1D\",\n \"--cd-ui-abschnitt\": \"#282828\",\n \"--cd-ui-linie\": \"#464646\",\n \"--cd-ui-kontur\": \"#8F8A8A\",\n \"--cd-ui-text\": \"#FFFFFF\",\n \"--cd-ui-text-leise\": \"#BBBBBB\",\n \"--cd-ui-link\": \"#00E676\",\n \"--cd-ui-icon-akzent\": \"#00E676\",\n \"--cd-ui-fokus\": \"#6B8AFF\",\n \"--cd-ui-interaktion\": \"#6B8AFF\",\n \"--cd-ui-success\": \"#00E676\",\n \"--cd-ui-warning\": \"#FFB000\",\n \"--cd-ui-danger\": \"#FB6D73\",\n \"--cd-ui-info\": \"#6B8AFF\",\n \"--cd-ui-success-flaeche\": \"#282828\",\n \"--cd-ui-warning-flaeche\": \"#282828\",\n \"--cd-ui-danger-flaeche\": \"#282828\",\n \"--cd-ui-info-flaeche\": \"#282828\",\n \"--cd-ui-wortmarke\": \"#FFFFFF\",\n \"--cd-ui-backdrop\": \"rgba(29, 29, 29, 0.6)\",\n \"--cd-ui-chrome-deckkraft\": \"100%\"\n },\n \"hochkontrast\": {\n \"hell\": {\n \"--cd-ui-linie\": \"#8F8A8A\",\n \"--cd-ui-kontur\": \"#1D1D1D\",\n \"--cd-ui-text-leise\": \"#1D1D1D\",\n \"--cd-ui-chrome-deckkraft\": \"100%\"\n },\n \"dunkel\": {\n \"--cd-ui-linie\": \"#8F8A8A\",\n \"--cd-ui-kontur\": \"#FFFFFF\",\n \"--cd-ui-text-leise\": \"#FFFFFF\",\n \"--cd-ui-chrome-deckkraft\": \"100%\"\n }\n },\n \"fest\": {\n \"--cd-blau\": \"#335DE5\",\n \"--cd-gruen\": \"#00E676\",\n \"--cd-grau\": \"#F9F7F7\",\n \"--cd-schwarz\": \"#1D1D1D\",\n \"--cd-weiss\": \"#FFFFFF\",\n \"--cd-blau-link\": \"#2B50D4\",\n \"--cd-blau-hell\": \"#6B8AFF\",\n \"--cd-success\": \"#00E676\",\n \"--cd-success-soft\": \"#DAFBEB\",\n \"--cd-success-hell\": \"#00E676\",\n \"--cd-warning\": \"#FFB000\",\n \"--cd-warning-soft\": \"#FFF1D2\",\n \"--cd-warning-hell\": \"#FFB000\",\n \"--cd-danger\": \"#CD1839\",\n \"--cd-danger-soft\": \"#FBEEF0\",\n \"--cd-danger-hell\": \"#FB6D73\",\n \"--cd-info\": \"#335DE5\",\n \"--cd-info-soft\": \"#EEF1FD\",\n \"--cd-info-hell\": \"#6B8AFF\",\n \"--cd-linie\": \"#E6E2E2\",\n \"--cd-kontur\": \"#8F8A8A\",\n \"--cd-text-leise\": \"#6B6666\"\n },\n \"shell\": {\n \"--cd-shell-rand\": \"12px\",\n \"--cd-shell-luecke\": \"8px\",\n \"--cd-shell-zeile\": \"40px\",\n \"--cd-shell-ziel\": \"32px\",\n \"--cd-shell-eintrag\": \"36px\",\n \"--cd-shell-frei\": \"64px\",\n \"--cd-shell-menue-breite\": \"248px\",\n \"--cd-shell-inspector-breite\": \"288px\",\n \"--cd-shell-einpassen-oben\": \"88px\",\n \"--cd-shell-einpassen-oben-schmal\": \"140px\",\n \"--cd-shell-einpassen-seite\": \"24px\",\n \"--cd-shell-einpassen-unten\": \"64px\",\n \"--cd-shell-einpassen-unten-web\": \"92px\",\n \"--cd-shell-schmal\": \"760px\",\n \"--cd-shell-sehr-schmal\": \"440px\",\n \"--cd-shell-niedrig\": \"820px\",\n \"--cd-shell-ebene-inseln\": \"20\",\n \"--cd-shell-ebene-inspector\": \"25\",\n \"--cd-shell-ebene-reihe\": \"30\",\n \"--cd-shell-ebene-aufklapper\": \"40\",\n \"--cd-shell-ebene-dialog\": \"50\",\n \"--cd-shell-ebene-toast\": \"60\"\n }\n}\n","import { hell } from '../theme/cd-tokens.generated.json';\n\n/**\n * Canvas colours, the light roles of the vendored design tokens (guide §10.1): contours,\n * connections and labels in the text role, element fills in the plot role. The renderer writes\n * them as presentation values, so exports look the same everywhere and stay light in every mode.\n */\nexport const COLORS = {\n ink: hell['--cd-ui-text'],\n fill: hell['--cd-ui-plot'],\n} as const;\n\n/**\n * The family goes onto every SVG text node, since SVG text does not inherit the container's font\n * (guide §4). \"Geist Variable\" is the name `@fontsource-variable/geist` registers; the hosts load\n * it, and an exported SVG opened elsewhere falls back to \"Geist\" or a system sans.\n */\nexport const FONT = {\n family: \"'Geist Variable', 'Geist', ui-sans-serif, system-ui, sans-serif\",\n size: 12,\n lineHeight: 1.2,\n} as const;\n\nexport const STROKE_WIDTH = 2;\n\nexport const LABEL_PADDING = 7;\n\n/** Accent colors offered by the color picker (stroke + label tint; fill stays white). */\nexport const COLOR_OPTIONS: ReadonlyArray<{ label: string; color?: string }> = [\n { label: 'Default' },\n { label: 'Blue', color: 'hsl(205, 100%, 45%)' },\n { label: 'Green', color: 'hsl(150, 86%, 34%)' },\n { label: 'Orange', color: 'hsl(29, 89%, 44%)' },\n { label: 'Red', color: 'hsl(360, 100%, 45%)' },\n { label: 'Purple', color: 'hsl(287, 65%, 44%)' },\n];\n","import BaseRenderer from 'diagram-js/lib/draw/BaseRenderer';\nimport TextUtil from 'diagram-js/lib/util/Text';\nimport { createLine } from 'diagram-js/lib/util/RenderUtil';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type GraphicsFactory from 'diagram-js/lib/core/GraphicsFactory';\nimport type { Connection, Element, Shape } from 'diagram-js/lib/model/Types';\nimport { append as svgAppend, attr as svgAttr, create as svgCreate } from 'tiny-svg';\nimport { chevronPath, chevronPathAt, ellipsePathAt, labelInset } from './geometry.js';\nimport { COLORS, FONT, LABEL_PADDING, STROKE_WIDTH } from './styles.js';\nimport {\n isOrgUnit,\n isVcConnection,\n isVcShape,\n type VcConnection,\n type VcShape,\n} from '../model/di-types.js';\n\n/** BaseRenderer default is 1000; 1500 wins the render.shape/render.connection event. */\nconst VC_RENDER_PRIORITY = 1500;\n\n/** Arrowhead geometry mirrors the bpmn-js sequence flow marker. */\nconst ARROW_PATH = 'M 1 5 L 11 10 L 1 15 Z';\n\nlet rendererInstances = 0;\n\nexport default class VcRenderer extends BaseRenderer {\n static $inject = ['eventBus', 'elementRegistry', 'graphicsFactory'];\n\n private readonly textUtil = new TextUtil({\n style: {\n fontFamily: FONT.family,\n fontSize: FONT.size,\n fontWeight: 'normal',\n lineHeight: FONT.lineHeight,\n },\n });\n\n /** Unique per instance so marker ids never collide across diagrams on one page. */\n private readonly markerSuffix = `${(rendererInstances += 1)}`;\n\n constructor(\n eventBus: EventBus,\n private readonly elementRegistry: ElementRegistry,\n private readonly graphicsFactory: GraphicsFactory,\n ) {\n super(eventBus, VC_RENDER_PRIORITY);\n this.relayoutLabelsWhenTheFontArrives(eventBus);\n }\n\n /**\n * A label drawn before the web font arrived was measured in the fallback font: its lines sit off\n * centre, and may wrap differently, once the font renders. Such labels are laid out again then.\n */\n private relayoutLabelsWhenTheFontArrives(eventBus: EventBus): void {\n const fonts = typeof document === 'undefined' ? undefined : document.fonts;\n const font = `${FONT.size}px ${FONT.family}`;\n if (!fonts || fonts.check(font)) {\n return;\n }\n let destroyed = false;\n eventBus.on('diagram.destroy', () => {\n destroyed = true;\n });\n fonts.load(font).then(\n (faces) => {\n if (destroyed || faces.length === 0) {\n return;\n }\n for (const element of this.elementRegistry.getAll()) {\n if (isVcShape(element) && element.vcLabel) {\n this.graphicsFactory.update(\n 'shape',\n element,\n this.elementRegistry.getGraphics(element),\n );\n }\n }\n },\n () => undefined,\n );\n }\n\n override canRender(element: Element): boolean {\n return isVcShape(element) || isVcConnection(element);\n }\n\n override drawShape(visuals: SVGElement, element: Shape): SVGElement {\n const shape = element as VcShape;\n const stroke = shape.color ?? COLORS.ink;\n const orgUnit = isOrgUnit(shape);\n\n const path = svgCreate('path');\n svgAttr(path, {\n d: orgUnit\n ? ellipsePathAt(0, 0, shape.width, shape.height)\n : chevronPath(shape.width, shape.height),\n fill: COLORS.fill,\n stroke,\n 'stroke-width': STROKE_WIDTH,\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round',\n });\n svgAppend(visuals, path);\n\n if (shape.vcLabel) {\n const inset = orgUnit ? LABEL_PADDING + 5 : labelInset(shape.width, shape.height);\n const label = this.textUtil.createText(shape.vcLabel, {\n box: { width: shape.width, height: shape.height },\n align: 'center-middle',\n padding: {\n top: LABEL_PADDING,\n bottom: LABEL_PADDING,\n left: inset,\n right: inset,\n },\n style: { fill: stroke },\n });\n svgAppend(visuals, label);\n }\n\n return path;\n }\n\n override drawConnection(visuals: SVGElement, element: Connection): SVGElement {\n const connection = element as VcConnection;\n const stroke = COLORS.ink;\n\n const attrs: Record<string, string | number> = {\n stroke,\n 'stroke-width': STROKE_WIDTH,\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round',\n fill: 'none',\n };\n if (connection.vcType === 'sequence') {\n attrs['stroke-dasharray'] = '8, 5';\n }\n // assignments (org unit ↔ step) are plain lines without an arrowhead\n if (connection.vcType !== 'assignment') {\n const svg = visuals.ownerSVGElement;\n if (svg) {\n attrs['marker-end'] = this.arrowMarker(svg, stroke);\n }\n }\n\n const line = createLine(connection.waypoints, attrs);\n svgAppend(visuals, line);\n return line;\n }\n\n override getShapePath(shape: Shape): string {\n if (isOrgUnit(shape)) {\n return ellipsePathAt(shape.x, shape.y, shape.width, shape.height);\n }\n return chevronPathAt(shape.x, shape.y, shape.width, shape.height);\n }\n\n override getConnectionPath(connection: Connection): string {\n const [first, ...rest] = connection.waypoints;\n if (!first) {\n return '';\n }\n return `M${first.x},${first.y}${rest.map((point) => `L${point.x},${point.y}`).join('')}`;\n }\n\n private arrowMarker(svg: SVGSVGElement, color: string): string {\n const id = `vc-arrow-${this.markerSuffix}-${color.replace(/[^a-zA-Z0-9]/g, '')}`;\n if (!svg.querySelector(`marker[id=\"${id}\"]`)) {\n let defs = svg.querySelector('defs');\n if (!defs) {\n defs = svgCreate('defs') as SVGDefsElement;\n svgAppend(svg, defs);\n }\n const marker = svgCreate('marker');\n svgAttr(marker, {\n id,\n viewBox: '0 0 20 20',\n refX: 11,\n refY: 10,\n markerWidth: 10,\n markerHeight: 10,\n orient: 'auto',\n });\n const arrow = svgCreate('path');\n svgAttr(arrow, {\n d: ARROW_PATH,\n fill: color,\n stroke: color,\n 'stroke-width': 1,\n 'stroke-linejoin': 'round',\n });\n svgAppend(marker, arrow);\n svgAppend(defs, marker);\n }\n return `url(#${id})`;\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport VcRenderer from './VcRenderer.js';\n\n/** SVG rendering of value chain steps and connections (BaseRenderer subclass). */\nexport const vcDrawModule: ModuleDeclaration = {\n __init__: ['vcRenderer'],\n vcRenderer: ['type', VcRenderer],\n};\n\nexport { default as VcRenderer } from './VcRenderer.js';\nexport { chevronPath, chevronPathAt, ellipsePathAt, notchDepth } from './geometry.js';\nexport { COLORS, COLOR_OPTIONS, FONT } from './styles.js';\n","import type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { getBBox } from 'diagram-js/lib/util/Elements';\nimport type { Bounds } from '@miragon/value-chain-schema-model';\nimport { isVcElement, isVcShape } from '../model/di-types.js';\n\n/**\n * The extent of the diagram's content: every step, org unit and connection (waypoints included).\n * One source for the import's fit, the SVG export's frame and a host's fit, which pass their own\n * margin.\n */\nexport default class VcBounds {\n static $inject = ['elementRegistry'];\n\n constructor(private readonly elementRegistry: ElementRegistry) {}\n\n /** No step and no org unit on the canvas. */\n isEmpty(): boolean {\n return !this.elementRegistry.getAll().some(isVcShape);\n }\n\n /** The tight bounds of the content grown by `padding` on every side; undefined while empty. */\n contentBounds(padding = 0): Bounds | undefined {\n if (this.isEmpty()) {\n return undefined;\n }\n const elements = this.elementRegistry.filter(isVcElement) as Element[];\n const { x, y, width, height } = getBBox(elements);\n return {\n x: x - padding,\n y: y - padding,\n width: width + 2 * padding,\n height: height + 2 * padding,\n };\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport VcBounds from './VcBounds.js';\n\n/** Content bounds of the diagram (import fit, SVG export, a host's fit). */\nexport const vcBoundsModule: ModuleDeclaration = {\n vcBounds: ['type', VcBounds],\n};\n\nexport { default as VcBounds } from './VcBounds.js';\n","/** The id of the canvas root; the schema reserves it (RESERVED_IDS), so no element can take it. */\nexport const ROOT_ID = 'vc-root';\n\nexport interface ImportWarning {\n message: string;\n connectionId?: string;\n}\n\n/** Document-level data kept on the root element while editing. */\nexport interface RootBusinessObject {\n name: string;\n /** The document's fields beyond the schema, written back on export. */\n extensions?: Record<string, unknown>;\n /** The meta fields beyond the schema, written back on export. */\n metaExtensions?: Record<string, unknown>;\n}\n","import type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementFactory from 'diagram-js/lib/core/ElementFactory';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Root, Shape } from 'diagram-js/lib/model/Types';\nimport {\n documentExtensions,\n metaExtensions,\n type ValueChainDocument,\n} from '@miragon/value-chain-schema-model';\nimport type VcBounds from '../bounds/VcBounds.js';\nimport type VcElementFactory from '../model/VcElementFactory.js';\nimport { isVcConnection, isVcShape } from '../model/di-types.js';\nimport { ROOT_ID, type ImportWarning, type RootBusinessObject } from './types.js';\n\n/** The margin around the content when an import fits the view, in diagram units. */\nconst FIT_PADDING = 20;\n\n/**\n * diagram-js reads its zoom back rounded to three decimals: a fit below 0.0005 would read back as\n * zoom 0 and a NaN viewbox. Content wider than about a thousand viewports shows its centre here.\n */\nconst SMALLEST_FIT_ZOOM = 0.001;\n\ntype DiagramRoot = Root & { businessObject?: RootBusinessObject };\n\nexport interface VcImportConfig {\n /** Fit the view to the content after every import (default true); false leaves it to the host. */\n fitOnImport?: boolean | undefined;\n}\n\n/**\n * Renders a validated value chain document onto the canvas. Deliberately bypasses the command\n * stack — importing must not create undo entries.\n */\nexport default class VcImporter {\n static $inject = [\n 'canvas',\n 'elementFactory',\n 'vcElementFactory',\n 'elementRegistry',\n 'eventBus',\n 'vcBounds',\n 'config.vcImport',\n ];\n\n constructor(\n private readonly canvas: Canvas,\n private readonly elementFactory: ElementFactory,\n private readonly vcElementFactory: VcElementFactory,\n private readonly elementRegistry: ElementRegistry,\n private readonly eventBus: EventBus,\n private readonly vcBounds: VcBounds,\n private readonly config: VcImportConfig | undefined,\n ) {}\n\n import(document: ValueChainDocument): ImportWarning[] {\n const warnings: ImportWarning[] = [];\n this.eventBus.fire('import.render.start', { document });\n\n const root = this.diagramRoot();\n root.businessObject = {\n name: document.meta.name,\n extensions: documentExtensions(document),\n metaExtensions: metaExtensions(document.meta),\n };\n\n const shapeById = new Map<string, Shape>();\n for (const element of document.elements) {\n const shape = this.vcElementFactory.createElement(element);\n this.canvas.addShape(shape, root);\n shapeById.set(element.id, shape);\n }\n\n let connectionIndex = 0;\n for (const connection of document.connections) {\n const source = shapeById.get(connection.source);\n const target = shapeById.get(connection.target);\n if (!source || !target) {\n warnings.push({\n message: `Skipped connection \"${connection.id}\": unresolved endpoint.`,\n connectionId: connection.id,\n });\n continue;\n }\n const element = this.vcElementFactory.createConnection(connection, source, target);\n // Insert connections at the front of the children so they paint behind the steps.\n this.canvas.addConnection(element, root, connectionIndex);\n connectionIndex += 1;\n }\n\n if (this.config?.fitOnImport !== false) {\n this.fitToContent();\n }\n this.eventBus.fire('import.render.done', { document, warnings });\n return warnings;\n }\n\n /** Removes all imported elements and document meta, tolerating elements already gone. */\n clear(): void {\n const roots = new Set<unknown>(this.canvas.getRootElements());\n for (const element of [...this.elementRegistry.getAll()]) {\n if (roots.has(element)) {\n if (element.id === ROOT_ID) {\n element.businessObject = undefined;\n }\n continue;\n }\n try {\n if (isVcConnection(element)) {\n this.canvas.removeConnection(element);\n } else if (isVcShape(element)) {\n this.canvas.removeShape(element);\n }\n } catch {\n // already removed along with a previous element\n }\n }\n }\n\n /**\n * The diagram's root, created on the first import. Any other root goes: diagram-js creates an\n * implicit one whenever something asks for the root before the first import (an export, a\n * palette create), and it would otherwise stay behind in the registry.\n */\n private diagramRoot(): DiagramRoot {\n let root = this.elementRegistry.get(ROOT_ID) as DiagramRoot | undefined;\n if (!root) {\n root = this.elementFactory.createRoot({ id: ROOT_ID }) as DiagramRoot;\n this.canvas.setRootElement(root);\n }\n for (const other of this.canvas.getRootElements()) {\n if (other !== root) {\n this.canvas.removeRootElement(other);\n }\n }\n return root;\n }\n\n /**\n * Centres the content at the largest zoom that shows all of it, never above 100% (guide §5.9),\n * so the same document always opens in the same view; an empty diagram shows its origin at\n * 100%. Hosts with chrome of their own refit with their insets afterwards.\n */\n private fitToContent(): void {\n const { width, height } = this.canvas.getSize();\n if (!(width > 0 && height > 0)) {\n return;\n }\n const bounds = this.vcBounds.contentBounds(FIT_PADDING);\n if (!bounds) {\n this.canvas.viewbox({ x: 0, y: 0, width, height });\n return;\n }\n const scale = Math.max(\n Math.min(width / bounds.width, height / bounds.height, 1),\n SMALLEST_FIT_ZOOM,\n );\n this.canvas.viewbox({\n x: bounds.x + bounds.width / 2 - width / 2 / scale,\n y: bounds.y + bounds.height / 2 - height / 2 / scale,\n width: width / scale,\n height: height / scale,\n });\n }\n}\n","import type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport {\n CURRENT_SCHEMA_VERSION,\n connectionExtensions,\n elementExtensions,\n validateDocument,\n type ChainConnection,\n type DiagramElement,\n type ValueChainDocument,\n} from '@miragon/value-chain-schema-model';\nimport { isVcConnection, isVcShape } from '../model/di-types.js';\nimport { ROOT_ID, type RootBusinessObject } from './types.js';\n\n/**\n * Rebuilds a schema-model document from the live diagram. The diagram-js element\n * properties are the source of truth; businessObject backfills what the UI cannot edit:\n * a step's `link` and every field beyond the schema (vendor extensions), which the\n * export writes back unchanged.\n */\nexport default class VcExporter {\n static $inject = ['elementRegistry'];\n\n constructor(private readonly elementRegistry: ElementRegistry) {}\n\n export(): ValueChainDocument {\n const elements: DiagramElement[] = [];\n const connections: ChainConnection[] = [];\n\n for (const element of this.elementRegistry.getAll()) {\n if (element.id === ROOT_ID) {\n continue;\n }\n if (isVcConnection(element)) {\n if (!element.source || !element.target) {\n continue;\n }\n const imported = element.businessObject;\n connections.push({\n ...(imported ? connectionExtensions(imported) : {}),\n id: element.id,\n connectionType: element.vcType,\n source: element.source.id,\n target: element.target.id,\n waypoints: element.waypoints.map((point) => ({ x: point.x, y: point.y })),\n });\n } else if (isVcShape(element)) {\n const imported = element.businessObject;\n const extensions = imported ? elementExtensions(imported) : {};\n const bounds = {\n x: element.x,\n y: element.y,\n width: element.width,\n height: element.height,\n };\n const color = element.color !== undefined ? { color: element.color } : {};\n if (element.vcType === 'orgUnit') {\n elements.push({\n ...extensions,\n id: element.id,\n elementType: 'orgUnit',\n name: element.vcLabel,\n bounds,\n ...color,\n });\n } else {\n const link =\n element.link ?? (imported?.elementType === 'step' ? imported.link : undefined);\n elements.push({\n ...extensions,\n id: element.id,\n elementType: 'step',\n name: element.vcLabel,\n bounds,\n ...color,\n ...(link !== undefined ? { link } : {}),\n });\n }\n }\n }\n\n const root = this.rootData();\n\n return validateDocument({\n ...root?.extensions,\n schemaVersion: CURRENT_SCHEMA_VERSION,\n meta: { ...root?.metaExtensions, name: root?.name ?? 'Untitled value chain' },\n elements,\n connections,\n });\n }\n\n /** Read without `canvas.getRootElement()`, which would create an implicit root before import. */\n private rootData(): RootBusinessObject | undefined {\n const root = this.elementRegistry.get(ROOT_ID) as\n { businessObject?: RootBusinessObject } | undefined;\n return root?.businessObject;\n }\n}\n","import { COLORS } from '../draw/styles.js';\n\n/**\n * Rasterizes an exported SVG (`saveSVG`) to a PNG at `scale` × its size, on the diagram's white\n * fill, so a PNG looks like the SVG in every viewer and stays light in every mode.\n */\nexport async function svgToPng(svg: string, scale = 2): Promise<Blob> {\n const { width, height } = svgSize(svg);\n const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));\n try {\n const image = new Image();\n image.width = width;\n image.height = height;\n await new Promise<void>((resolve, reject) => {\n image.onload = () => resolve();\n image.onerror = () => reject(new Error('Could not render the SVG.'));\n image.src = url;\n });\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(width * scale);\n canvas.height = Math.round(height * scale);\n const context = canvas.getContext('2d');\n if (!context) throw new Error('Canvas 2D context not available.');\n context.fillStyle = COLORS.fill;\n context.fillRect(0, 0, canvas.width, canvas.height);\n context.drawImage(image, 0, 0, canvas.width, canvas.height);\n const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/png'));\n if (!blob) throw new Error('PNG generation failed.');\n return blob;\n } finally {\n URL.revokeObjectURL(url);\n }\n}\n\nfunction svgSize(svg: string): { width: number; height: number } {\n const width = /width=\"(\\d+(?:\\.\\d+)?)\"/.exec(svg);\n const height = /height=\"(\\d+(?:\\.\\d+)?)\"/.exec(svg);\n return { width: width ? Number(width[1]) : 1000, height: height ? Number(height[1]) : 700 };\n}\n\n/** Blob -> Base64 (without the data-URL prefix), e.g. to post it to a VS Code extension host. */\nexport function blobToBase64(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(String(reader.result).split(',')[1] ?? '');\n reader.onerror = () => reject(new Error('Could not read the export blob.'));\n reader.readAsDataURL(blob);\n });\n}\n","import type { ModuleDeclaration } from 'didi';\nimport { vcBoundsModule } from '../bounds/index.js';\nimport VcImporter from './VcImporter.js';\nimport VcExporter from './VcExporter.js';\n\n/** Document import/export between schema-model and the canvas. */\nexport const ioModule: ModuleDeclaration = {\n __depends__: [vcBoundsModule],\n vcImporter: ['type', VcImporter],\n vcExporter: ['type', VcExporter],\n};\n\nexport { default as VcImporter, type VcImportConfig } from './VcImporter.js';\nexport { default as VcExporter } from './VcExporter.js';\nexport { saveSVG } from './saveSvg.js';\nexport { svgToPng, blobToBase64 } from './png.js';\nexport { ROOT_ID, type ImportWarning, type RootBusinessObject } from './types.js';\n","import type { ModuleDeclaration } from 'didi';\nimport { VcBaseViewer } from './VcBaseViewer.js';\nimport { vcModelModule } from './model/index.js';\nimport { vcDrawModule } from './draw/index.js';\nimport { ioModule } from './io/index.js';\n\n/** Read-only rendering of value chain documents. */\nexport class Viewer extends VcBaseViewer {\n protected _getModules(): ModuleDeclaration[] {\n return [vcModelModule, vcDrawModule, ioModule];\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport SelectionModule from 'diagram-js/lib/features/selection';\nimport ZoomScrollModule from 'diagram-js/lib/navigation/zoomscroll';\nimport MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas';\nimport { Viewer } from './Viewer.js';\n\n/** Viewer plus canvas navigation (zoom, pan, selection). */\nexport class NavigatedViewer extends Viewer {\n protected override _getModules(): ModuleDeclaration[] {\n return [...super._getModules(), SelectionModule, ZoomScrollModule, MoveCanvasModule];\n }\n}\n","import type { Element } from 'diagram-js/lib/model/Types';\n\nexport interface UpdatePropertiesContext {\n element: Element;\n properties: Record<string, unknown>;\n oldProperties?: Record<string, unknown>;\n}\n\n/**\n * Generic undoable property update: `execute` remembers the previous values,\n * `revert` restores them. Returned elements trigger `elements.changed` → re-render.\n */\nexport default class UpdatePropertiesHandler {\n execute(context: UpdatePropertiesContext): Element[] {\n const { element, properties } = context;\n const target = element as unknown as Record<string, unknown>;\n const old: Record<string, unknown> = {};\n for (const key of Object.keys(properties)) {\n old[key] = target[key];\n setOrDelete(target, key, properties[key]);\n }\n context.oldProperties = old;\n return [element];\n }\n\n revert(context: UpdatePropertiesContext): Element[] {\n const { element, oldProperties } = context;\n const target = element as unknown as Record<string, unknown>;\n if (oldProperties) {\n for (const key of Object.keys(oldProperties)) {\n setOrDelete(target, key, oldProperties[key]);\n }\n }\n return [element];\n }\n}\n\nfunction setOrDelete(target: Record<string, unknown>, key: string, value: unknown): void {\n if (value === undefined) {\n delete target[key];\n } else {\n target[key] = value;\n }\n}\n","import type CommandStack from 'diagram-js/lib/command/CommandStack';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport UpdatePropertiesHandler from './cmd/UpdatePropertiesHandler.js';\nimport type { VcConnection, VcShape } from '../model/di-types.js';\n\nconst UPDATE_PROPERTIES = 'element.updateProperties';\n\n/** High-level undoable domain mutations; everything funnels through one command. */\nexport default class VcModeling {\n static $inject = ['commandStack'];\n\n constructor(private readonly commandStack: CommandStack) {\n commandStack.registerHandler(UPDATE_PROPERTIES, UpdatePropertiesHandler);\n }\n\n updateProperties(element: Element, properties: Record<string, unknown>): void {\n this.commandStack.execute(UPDATE_PROPERTIES, { element, properties });\n }\n\n updateLabel(element: VcShape, label: string): void {\n if (label === element.vcLabel) {\n return;\n }\n this.updateProperties(element, { vcLabel: label });\n }\n\n setColor(element: VcShape, color: string | undefined): void {\n if (color === element.color) {\n return;\n }\n this.updateProperties(element, { color });\n }\n\n /** Re-routing happens in the same undo step via VcConnectionTypeBehavior. */\n setConnectionType(connection: VcConnection, type: ConnectionType): void {\n if (type === connection.vcType) {\n return;\n }\n this.updateProperties(connection, { vcType: type });\n }\n}\n","import BaseLayouter from 'diagram-js/lib/layout/BaseLayouter';\nimport type CroppingConnectionDocking from 'diagram-js/lib/layout/CroppingConnectionDocking';\nimport { getMid } from 'diagram-js/lib/layout/LayoutUtil';\nimport {\n connectPoints,\n connectRectangles,\n withoutRedundantPoints,\n} from 'diagram-js/lib/layout/ManhattanLayout';\nimport type { Connection, Shape } from 'diagram-js/lib/model/Types';\nimport type { Point } from 'diagram-js/lib/util/Types';\nimport { notchDepth } from '../draw/geometry.js';\n\n/** Horizontal distance of the column trunk from the leftmost sub-step. */\nconst TRUNK_MARGIN = 25;\n\n/**\n * Minimum gap between the center exit and the leftmost sub-step for the trunk to run\n * straight down under the exit (kink-free column).\n */\nexport const TRUNK_CLEARANCE = 10;\n\n/** Minimum stub length below the parent before the bus/trunk elbow. */\nconst BUS_MIN_STUB = 10;\n\n/** Keeps the drop-span boundary away from the parent's corners/point. */\nconst EXIT_MARGIN = 10;\n\nexport interface VcLayoutHints {\n source?: Shape;\n target?: Shape;\n connectionStart?: Point;\n connectionEnd?: Point;\n waypoints?: Point[];\n}\n\n/**\n * Connection routing:\n * - sequence (\"ist Vorgänger von\"): straight line, user bendpoints survive re-layouts;\n * - hierarchy (\"ist prozessorientiert übergeordnet\"): always re-routed orthogonally\n * (ARIS cascade look — down from the parent, across, down into the sub-step).\n * Both are cropped at the chevron contour via the renderer's getShapePath.\n */\nexport default class VcLayouter extends BaseLayouter {\n static $inject = ['connectionDocking'];\n\n constructor(private readonly connectionDocking: CroppingConnectionDocking) {\n super();\n }\n\n override layoutConnection(connection: Connection, hints: VcLayoutHints = {}): Point[] {\n const source = hints.source ?? (connection.source as Shape | undefined);\n const target = hints.target ?? (connection.target as Shape | undefined);\n if (!source || !target) {\n return connection.waypoints?.map((point) => ({ x: point.x, y: point.y })) ?? [];\n }\n\n const waypoints = isHierarchy(connection)\n ? this.hierarchyWaypoints(source, target, hints)\n : this.sequenceWaypoints(connection, source, target, hints);\n\n const stub = { ...connection, source, target, waypoints } as Connection;\n let result = waypoints;\n try {\n result = this.connectionDocking.getCroppedWaypoints(stub, source, target);\n } catch {\n // fall through to the uncropped waypoints\n }\n\n // Non-finite coordinates (e.g. anchors adjusted against degenerate zero-size old\n // bounds, see diagram-js AttachUtil.getNewAttachPoint) must never reach the model:\n // once a waypoint is NaN, every handle/bendpoint render throws. Fall back to a\n // plain mid-to-mid line in that case.\n if (!allFinite(result)) {\n const fallback = [getMid(source), getMid(target)];\n return allFinite(fallback) ? fallback : [];\n }\n return result;\n }\n\n /**\n * Straight line between the shape mids, cropped to the contours afterwards.\n * The connectionStart/End anchor hints diagram-js passes on move (old cropped\n * waypoint + delta) are ignored on purpose: such a point can land in the chevron's\n * notch cutout where cropping finds no intersection, leaving the arrowhead hidden\n * behind the shape. Mid-to-mid always crops reliably; user bendpoints survive.\n */\n private sequenceWaypoints(\n connection: Connection,\n source: Shape,\n target: Shape,\n hints: VcLayoutHints,\n ): Point[] {\n const interior = (hints.waypoints ?? connection.waypoints ?? [])\n .slice(1, -1)\n .map((point) => ({ x: point.x, y: point.y }));\n return [getMid(source), ...interior, getMid(target)];\n }\n\n /**\n * Adaptive hierarchy routing. Every edge exits the parent at its BOTTOM CENTER;\n * the sub-steps' arrangement picks how it continues:\n * - horizontal row (aligned tops / single child under the parent's span): down to a\n * shared bus halfway to the children, across, and down into each sub-step's top;\n * - vertical column (ARIS rake, the default): straight down under the exit whenever\n * all children sit right of the center (no kink), otherwise via a bus to a shared\n * trunk left of all children; then a horizontal arm into each left notch.\n * Anchor hints are ignored on purpose: hierarchy edges always re-route from the\n * current geometry.\n */\n private hierarchyWaypoints(source: Shape, target: Shape, _hints: VcLayoutHints): Point[] {\n const sourceMid = getMid(source);\n const targetMid = getMid(target);\n\n if (target.y >= source.y + source.height) {\n const children = hierarchyChildren(source);\n const group = children.length ? children : [target];\n\n if (isRowArrangement(group, source)) {\n return withoutRedundantPoints(connectPoints(sourceMid, targetMid, 'v:v'));\n }\n\n const bottom = source.y + source.height;\n const topmost = Math.min(...group.map((child) => child.y));\n const busY = Math.max(bottom + BUS_MIN_STUB, (bottom + topmost) / 2);\n const minChildX = Math.min(...group.map((child) => child.x));\n const trunkX =\n sourceMid.x <= minChildX - TRUNK_CLEARANCE ? sourceMid.x : minChildX - TRUNK_MARGIN;\n return withoutRedundantPoints([\n sourceMid,\n { x: sourceMid.x, y: busY },\n { x: trunkX, y: busY },\n { x: trunkX, y: targetMid.y },\n targetMid,\n ]);\n }\n\n return withoutRedundantPoints(\n connectRectangles(source, target, sourceMid, targetMid, { preferredLayouts: ['v:v'] }),\n );\n }\n}\n\n/**\n * The x range of the parent's bottom edge in which a sub-step's hierarchy edge is\n * drawn as a straight vertical drop (row notation) instead of the rake.\n */\nexport function hierarchyDropSpan(source: Shape): { min: number; max: number } {\n return {\n min: source.x + EXIT_MARGIN,\n max: source.x + source.width - notchDepth(source.width, source.height) - EXIT_MARGIN,\n };\n}\n\n/** All sub-steps connected to the given step via hierarchy edges. */\nexport function hierarchyChildren(source: Shape): Shape[] {\n return (source.outgoing ?? [])\n .filter((connection) => isHierarchy(connection))\n .map((connection) => connection.target as Shape)\n .filter((target): target is Shape => !!target);\n}\n\n/**\n * A horizontal row: several children with aligned tops, or a single child sitting\n * inside the parent's drop span. Shared by routing and auto-placement so both always\n * agree on the arrangement.\n */\nexport function isRowArrangement(children: Shape[], source: Shape): boolean {\n if (!children.length) {\n return false;\n }\n if (children.length >= 2) {\n const tops = children.map((child) => child.y);\n return Math.max(...tops) - Math.min(...tops) <= ROW_TOLERANCE_Y;\n }\n const child = children[0]!;\n const centerX = child.x + child.width / 2;\n const span = hierarchyDropSpan(source);\n return centerX >= span.min && centerX <= span.max;\n}\n\n/** Row detection tolerance for \"aligned tops\". */\nconst ROW_TOLERANCE_Y = 10;\n\nfunction isHierarchy(connection: Connection): boolean {\n return (connection as { vcType?: string }).vcType === 'hierarchy';\n}\n\nfunction allFinite(points: Point[]): boolean {\n return points.every((point) => Number.isFinite(point.x) && Number.isFinite(point.y));\n}\n","import CommandInterceptor from 'diagram-js/lib/command/CommandInterceptor';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type Modeling from 'diagram-js/lib/features/modeling/Modeling';\nimport type { Connection } from 'diagram-js/lib/model/Types';\nimport { isVcConnection } from '../model/di-types.js';\n\ninterface UpdatePropertiesContext {\n element?: unknown;\n properties?: Record<string, unknown>;\n}\n\n/**\n * Switching a connection's type changes its routing (straight/dashed vs rake).\n * Re-layout nested inside the updateProperties command, so type change and new\n * route form a single undo step.\n */\nexport default class VcConnectionTypeBehavior extends CommandInterceptor {\n static override $inject = ['eventBus', 'modeling'];\n\n constructor(eventBus: EventBus, modeling: Modeling) {\n super(eventBus);\n\n this.postExecute(\n ['element.updateProperties'],\n (context: UpdatePropertiesContext) => {\n const { element, properties } = context;\n if (properties && 'vcType' in properties && isVcConnection(element)) {\n modeling.layoutConnection(element as Connection);\n }\n },\n true,\n );\n }\n}\n","import CommandInterceptor from 'diagram-js/lib/command/CommandInterceptor';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type Modeling from 'diagram-js/lib/features/modeling/Modeling';\nimport type { Connection, Shape } from 'diagram-js/lib/model/Types';\nimport type { Point } from 'diagram-js/lib/util/Types';\nimport type VcLayouter from './VcLayouter.js';\nimport { isVcConnection, isVcShape } from '../model/di-types.js';\n\ninterface CommandContext {\n shape?: unknown;\n shapes?: unknown[];\n elements?: unknown[];\n connection?: unknown;\n}\n\n/**\n * Hierarchy routing depends on the whole sibling group (row vs column), but diagram-js\n * only re-layouts the edges of the shape that moved. This behavior re-layouts ALL\n * hierarchy edges of every affected parent — nested into the triggering command, so\n * arrangement flips stay one undo step and no sibling keeps a stale route.\n */\nexport default class VcHierarchyRelayoutBehavior extends CommandInterceptor {\n static override $inject = ['eventBus', 'modeling', 'layouter'];\n\n constructor(\n eventBus: EventBus,\n private readonly modeling: Modeling,\n private readonly layouter: VcLayouter,\n ) {\n super(eventBus);\n\n this.postExecuted(\n ['shape.move', 'elements.move', 'shape.resize', 'connection.create', 'connection.delete'],\n (context: CommandContext) => this.relayoutAffected(context),\n true,\n );\n }\n\n private relayoutAffected(context: CommandContext): void {\n const shapes = [context.shape, ...(context.shapes ?? []), ...(context.elements ?? [])].filter(\n isVcShape,\n );\n\n const connection = context.connection;\n const parents = new Set<Shape>();\n\n if (isVcConnection(connection) && connection.vcType === 'hierarchy' && connection.source) {\n parents.add(connection.source as Shape);\n }\n\n for (const shape of shapes) {\n if (hierarchyEdges(shape as Shape).length) {\n parents.add(shape as Shape);\n }\n for (const incoming of (shape as Shape).incoming ?? []) {\n if (isVcConnection(incoming) && incoming.vcType === 'hierarchy' && incoming.source) {\n parents.add(incoming.source as Shape);\n }\n }\n }\n\n for (const parent of parents) {\n for (const edge of hierarchyEdges(parent)) {\n const fresh = this.layouter.layoutConnection(edge);\n if (!sameWaypoints(fresh, edge.waypoints ?? [])) {\n this.modeling.layoutConnection(edge);\n }\n }\n }\n }\n}\n\nfunction hierarchyEdges(shape: Shape): Connection[] {\n return ((shape.outgoing ?? []) as Connection[]).filter(\n (connection) => isVcConnection(connection) && connection.vcType === 'hierarchy',\n );\n}\n\nfunction sameWaypoints(a: Point[], b: Point[]): boolean {\n return (\n a.length === b.length &&\n a.every((point, index) => point.x === b[index]!.x && point.y === b[index]!.y)\n );\n}\n","import type { ModuleDeclaration } from 'didi';\nimport CroppingConnectionDocking from 'diagram-js/lib/layout/CroppingConnectionDocking';\nimport VcModeling from './VcModeling.js';\nimport VcLayouter from './VcLayouter.js';\nimport VcConnectionTypeBehavior from './VcConnectionTypeBehavior.js';\nimport VcHierarchyRelayoutBehavior from './VcHierarchyRelayoutBehavior.js';\n\n/**\n * Domain mutations + connection layout. Overrides the stock `layouter` and registers\n * `connectionDocking` (also consumed by bendpoints and connection previews).\n */\nexport const vcModelingModule: ModuleDeclaration = {\n __init__: ['vcModeling', 'vcConnectionTypeBehavior', 'vcHierarchyRelayoutBehavior'],\n vcModeling: ['type', VcModeling],\n vcConnectionTypeBehavior: ['type', VcConnectionTypeBehavior],\n vcHierarchyRelayoutBehavior: ['type', VcHierarchyRelayoutBehavior],\n layouter: ['type', VcLayouter],\n connectionDocking: ['type', CroppingConnectionDocking],\n};\n\nexport { default as VcModeling } from './VcModeling.js';\nexport {\n default as VcLayouter,\n hierarchyDropSpan,\n hierarchyChildren,\n isRowArrangement,\n} from './VcLayouter.js';\nexport { default as VcConnectionTypeBehavior } from './VcConnectionTypeBehavior.js';\nexport { default as VcHierarchyRelayoutBehavior } from './VcHierarchyRelayoutBehavior.js';\n","import RuleProvider from 'diagram-js/lib/features/rules/RuleProvider';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport {\n isOrgUnit,\n isStep,\n isVcConnection,\n isVcShape,\n type VcConnection,\n type VcShape,\n} from '../model/di-types.js';\nimport type VcConnect from '../connect/VcConnect.js';\n\ninterface ConnectContext {\n source?: Element;\n target?: Element;\n connection?: Element;\n}\n\nexport default class VcRules extends RuleProvider {\n static override $inject = ['eventBus', 'vcConnect'];\n\n constructor(\n eventBus: EventBus,\n private readonly vcConnect: VcConnect,\n ) {\n super(eventBus);\n }\n\n override init(): void {\n this.addRule('connection.start', (context: ConnectContext) => isVcShape(context.source));\n\n this.addRule('connection.create', (context: ConnectContext) => {\n const { source, target } = context;\n const type = this.resolveType(source, target);\n if (!type || hasConnection(source as VcShape, target as VcShape, type)) {\n return false;\n }\n return { vcType: type };\n });\n\n this.addRule('connection.reconnect', (context: ConnectContext) => {\n const { source, target, connection } = context;\n if (!isVcConnection(connection) || !isVcShape(source) || !isVcShape(target)) {\n return false;\n }\n if (source === target || !endpointsAllowed(connection.vcType, source, target)) {\n return false;\n }\n return !hasConnection(source, target, connection.vcType, connection);\n });\n\n this.addRule('connection.updateWaypoints', (context: ConnectContext) =>\n isVcConnection(context.connection),\n );\n\n // Elements live directly on the root — no containment.\n this.addRule('shape.create', (context: { target?: Element }) => isRoot(context.target));\n this.addRule('elements.create', (context: { target?: Element }) => isRoot(context.target));\n\n this.addRule(['shape.move', 'elements.move'], () => true);\n this.addRule('shape.resize', (context: { shape?: Element }) => isVcShape(context.shape));\n\n this.addRule(['elements.align', 'elements.distribute'], (context: { elements?: Element[] }) =>\n (context.elements ?? []).filter(isVcShape),\n );\n }\n\n /**\n * The relation type follows from the endpoint kinds: step→step uses the pending\n * connect type, an org unit on either end always yields an assignment.\n */\n private resolveType(\n source: Element | undefined,\n target: Element | undefined,\n ): ConnectionType | null {\n if (!isVcShape(source) || !isVcShape(target) || source === target) {\n return null;\n }\n if (isStep(source) && isStep(target)) {\n const pending = this.vcConnect.pendingType;\n return pending === 'assignment' ? null : pending;\n }\n if ((isStep(source) && isOrgUnit(target)) || (isOrgUnit(source) && isStep(target))) {\n return 'assignment';\n }\n return null;\n }\n}\n\nfunction isRoot(element: Element | undefined): boolean {\n return !!element && !isVcShape(element) && !isVcConnection(element) && !element.parent;\n}\n\nfunction endpointsAllowed(type: ConnectionType, source: VcShape, target: VcShape): boolean {\n if (type === 'assignment') {\n return (isStep(source) && isOrgUnit(target)) || (isOrgUnit(source) && isStep(target));\n }\n return isStep(source) && isStep(target);\n}\n\nfunction hasConnection(\n source: VcShape,\n target: VcShape,\n type: ConnectionType,\n ignore?: VcConnection,\n): boolean {\n const links = [\n ...(source.outgoing ?? []),\n ...(type === 'assignment' ? (source.incoming ?? []) : []),\n ];\n return links.some(\n (connection) =>\n connection !== ignore &&\n isVcConnection(connection) &&\n connection.vcType === type &&\n (connection.target === target || connection.source === target),\n );\n}\n","import type { ModuleDeclaration } from 'didi';\nimport RulesModule from 'diagram-js/lib/features/rules';\nimport VcRules from './VcRules.js';\n\nexport const vcRulesModule: ModuleDeclaration = {\n __depends__: [RulesModule],\n __init__: ['vcRules'],\n vcRules: ['type', VcRules],\n};\n\nexport { default as VcRules } from './VcRules.js';\n","import type Connect from 'diagram-js/lib/features/connect/Connect';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport type { VcShape } from '../model/di-types.js';\n\n/**\n * Typed wrapper around the diagram-js connect interaction. The rule provider reads\n * `pendingType` while a connect/create drag is running to stamp the right connection\n * type; it resets to the default once the interaction is over.\n */\nexport default class VcConnect {\n static $inject = ['connect', 'eventBus'];\n\n pendingType: ConnectionType = 'sequence';\n\n constructor(\n private readonly connect: Connect,\n eventBus: EventBus,\n ) {\n eventBus.on(['connect.cleanup', 'create.cleanup', 'global-connect.cleanup'], () => {\n this.pendingType = 'sequence';\n });\n }\n\n start(event: MouseEvent | Event, source: VcShape, type: ConnectionType): void {\n this.pendingType = type;\n this.connect.start(event as MouseEvent, source);\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport ConnectModule from 'diagram-js/lib/features/connect';\nimport VcConnect from './VcConnect.js';\n\nexport const vcConnectModule: ModuleDeclaration = {\n __depends__: [ConnectModule],\n __init__: ['vcConnect'],\n vcConnect: ['type', VcConnect],\n};\n\nexport { default as VcConnect } from './VcConnect.js';\n","import type AutoPlace from 'diagram-js/lib/features/auto-place/AutoPlace';\nimport type Create from 'diagram-js/lib/features/create/Create';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport type VcElementFactory from '../model/VcElementFactory.js';\nimport type VcConnect from '../connect/VcConnect.js';\nimport type { VcShape } from '../model/di-types.js';\n\n/**\n * Append interactions à la bpmn.io: click places the new element automatically\n * (auto-place, label editing opens via the label-editing provider); dragging places\n * it manually with a live connection preview. `assignment` appends an organizational\n * unit; the other types append a step.\n */\nexport default class VcAppend {\n static $inject = ['autoPlace', 'create', 'vcElementFactory', 'vcConnect'];\n\n constructor(\n private readonly autoPlace: AutoPlace,\n private readonly create: Create,\n private readonly factory: VcElementFactory,\n private readonly vcConnect: VcConnect,\n ) {}\n\n append(source: VcShape, type: ConnectionType): Shape {\n this.vcConnect.pendingType = type;\n const newShape = this.autoPlace.append(source as Shape, this.createShape(type) as Shape, {\n connection: { vcType: type },\n }) as Shape;\n this.vcConnect.pendingType = 'sequence';\n return newShape;\n }\n\n startAppendDrag(event: Event, source: VcShape, type: ConnectionType): void {\n this.vcConnect.pendingType = type;\n this.create.start(event as MouseEvent, this.createShape(type) as Shape, {\n source: source as Shape,\n });\n }\n\n private createShape(type: ConnectionType): VcShape {\n return type === 'assignment' ? this.factory.createNewOrgUnit() : this.factory.createNewStep();\n }\n}\n","import type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport type { Point } from 'diagram-js/lib/util/Types';\nimport { isVcShape, type VcShape } from '../model/di-types.js';\nimport { hierarchyChildren, isRowArrangement, TRUNK_CLEARANCE } from '../modeling/VcLayouter.js';\nimport type VcConnect from '../connect/VcConnect.js';\n\n/** Runs before the diagram-js default (priority 100). */\nconst BEFORE_DEFAULT = 200;\n\nconst SEQUENCE_GAP_X = 45;\nconst HIERARCHY_GAP_Y = 45;\n\nconst SIBLING_GAP_Y = 30;\nconst SIBLING_GAP_X = 20;\nconst DECONFLICT_STEP_Y = 30;\nconst DECONFLICT_MARGIN = 10;\n\n/**\n * Placement of appended steps:\n * - sequence: to the right of the source (reading direction),\n * - hierarchy: follows the existing arrangement of the parent's sub-steps — a\n * horizontal row keeps growing to the right, a vertical column (ARIS rake,\n * the default) keeps growing downwards.\n * All placements nudge downwards until the spot is free of other steps.\n */\nexport default class VcAutoPlaceBehavior {\n static $inject = ['eventBus', 'vcConnect', 'elementRegistry'];\n\n constructor(eventBus: EventBus, vcConnect: VcConnect, elementRegistry: ElementRegistry) {\n eventBus.on(\n 'autoPlace',\n BEFORE_DEFAULT,\n (context: { source: Shape; shape: Shape }): Point | undefined => {\n const { source, shape } = context;\n if (!isVcShape(source)) {\n return undefined;\n }\n\n const desired = this.desiredPosition(vcConnect.pendingType, source, shape);\n return this.deconflict(desired, shape);\n },\n );\n\n this.elementRegistry = elementRegistry;\n }\n\n private readonly elementRegistry: ElementRegistry;\n\n private desiredPosition(type: string, source: VcShape, shape: Shape): Point {\n if (type === 'hierarchy') {\n return this.hierarchyPosition(source, shape);\n }\n if (type === 'assignment') {\n return this.assignmentPosition(source, shape);\n }\n return this.sequencePosition(source, shape);\n }\n\n private sequencePosition(source: VcShape, shape: Shape): Point {\n return {\n x: source.x + source.width + SEQUENCE_GAP_X + shape.width / 2,\n y: source.y + source.height / 2,\n };\n }\n\n /** Organizational units sit centered below their step (Wikipedia notation). */\n private assignmentPosition(source: VcShape, shape: Shape): Point {\n return {\n x: source.x + source.width / 2,\n y: source.y + source.height + HIERARCHY_GAP_Y + shape.height / 2,\n };\n }\n\n private hierarchyPosition(source: VcShape, shape: Shape): Point {\n const children = hierarchyChildren(source);\n if (!children.length) {\n return {\n x: source.x + source.width / 2 + TRUNK_CLEARANCE + shape.width / 2,\n y: source.y + source.height + HIERARCHY_GAP_Y + shape.height / 2,\n };\n }\n\n if (isRowArrangement(children, source)) {\n const anchor = rightmost(children)!;\n return {\n x: anchor.x + anchor.width + SIBLING_GAP_X + shape.width / 2,\n y: anchor.y + shape.height / 2,\n };\n }\n\n const anchor = bottommost(children)!;\n return {\n x: anchor.x + shape.width / 2,\n y: anchor.y + anchor.height + SIBLING_GAP_Y + shape.height / 2,\n };\n }\n\n /** Nudges the position downwards until the new shape overlaps no existing step. */\n private deconflict(position: Point, shape: Shape): Point {\n const steps = this.elementRegistry.getAll().filter(isVcShape);\n const candidate = { ...position };\n for (let attempt = 0; attempt < 50; attempt += 1) {\n const bounds = {\n x: candidate.x - shape.width / 2 - DECONFLICT_MARGIN,\n y: candidate.y - shape.height / 2 - DECONFLICT_MARGIN,\n width: shape.width + DECONFLICT_MARGIN * 2,\n height: shape.height + DECONFLICT_MARGIN * 2,\n };\n const conflict = steps.some(\n (step) =>\n step.x < bounds.x + bounds.width &&\n step.x + step.width > bounds.x &&\n step.y < bounds.y + bounds.height &&\n step.y + step.height > bounds.y,\n );\n if (!conflict) {\n break;\n }\n candidate.y += DECONFLICT_STEP_Y;\n }\n return candidate;\n }\n}\n\nfunction rightmost(shapes: Shape[]): Shape | undefined {\n return shapes.reduce<Shape | undefined>(\n (best, shape) => (!best || shape.x + shape.width > best.x + best.width ? shape : best),\n undefined,\n );\n}\n\nfunction bottommost(shapes: Shape[]): Shape | undefined {\n return shapes.reduce<Shape | undefined>(\n (best, shape) => (!best || shape.y + shape.height > best.y + best.height ? shape : best),\n undefined,\n );\n}\n","import type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport { getMid } from 'diagram-js/lib/layout/LayoutUtil';\n\ninterface ConnectionPreviewLike {\n drawPreview(context: object, canConnect: unknown, hints: object): void;\n cleanUp(context: object): void;\n}\n\ninterface CreateEvent {\n x: number;\n y: number;\n context: {\n source?: Shape;\n shape?: Shape;\n canExecute?: boolean | { connect?: unknown };\n };\n}\n\n/** Drag-append UX: live connection preview from the source while dragging a new step. */\nexport default class VcCreatePreviewBehavior {\n static $inject = ['injector', 'eventBus'];\n\n constructor(injector: { get<T>(name: string, strict: boolean): T | null }, eventBus: EventBus) {\n const connectionPreview = injector.get<ConnectionPreviewLike>('connectionPreview', false);\n if (!connectionPreview) {\n return;\n }\n\n eventBus.on('create.move', (event: CreateEvent) => {\n const { context } = event;\n const source = context.source;\n if (!source) {\n return;\n }\n const canConnect =\n typeof context.canExecute === 'object' ? context.canExecute?.connect : false;\n // noCropping: there is no positioned target shape yet, and cropping against an\n // undefined target would throw inside CroppingConnectionDocking.\n connectionPreview.drawPreview(context, canConnect ?? false, {\n source,\n connectionStart: getMid(source),\n connectionEnd: { x: event.x, y: event.y },\n noCropping: true,\n });\n });\n\n eventBus.on(['create.end', 'create.cancel', 'create.cleanup'], (event: CreateEvent) => {\n connectionPreview.cleanUp(event.context);\n });\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport AutoPlaceModule from 'diagram-js/lib/features/auto-place';\nimport CreateModule from 'diagram-js/lib/features/create';\nimport ConnectionPreviewModule from 'diagram-js/lib/features/connection-preview';\nimport VcAppend from './VcAppend.js';\nimport VcAutoPlaceBehavior from './VcAutoPlaceBehavior.js';\nimport VcCreatePreviewBehavior from './VcCreatePreviewBehavior.js';\n\nexport const vcAppendModule: ModuleDeclaration = {\n __depends__: [AutoPlaceModule, CreateModule, ConnectionPreviewModule],\n __init__: ['vcAutoPlaceBehavior', 'vcCreatePreviewBehavior'],\n vcAppend: ['type', VcAppend],\n vcAutoPlaceBehavior: ['type', VcAutoPlaceBehavior],\n vcCreatePreviewBehavior: ['type', VcCreatePreviewBehavior],\n};\n\nexport { default as VcAppend } from './VcAppend.js';\n","/*! @miragon/value-chain-renderer icon geometry\n * Lucide (lucide-static 1.59.0) @license ISC\n * Copyright (c) 2026 Lucide Icons and Contributors\n * Derived from Feather, as Lucide's LICENSE lists them: trash and x. Feather @license MIT\n * Copyright (c) 2013-present Cole Bemis */\n\n/*\n * The Lucide icons of the palette tools, the context pad and the shortcuts dialog, copied\n * unchanged from `icon-nodes.json` so the renderer has no icon runtime dependency. Renderers\n * never import the modeler shell, so they cannot take its copy.\n */\nexport const LUCIDE = {\n 'square-dashed-mouse-pointer':\n '<path d=\"M12.034 12.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.943l-3.444 1.068a1 1 0 0 0-.66.66l-1.067 3.443a.5.5 0 0 1-.943.033z\"/>' +\n '<path d=\"M5 3a2 2 0 0 0-2 2\"/><path d=\"M19 3a2 2 0 0 1 2 2\"/><path d=\"M5 21a2 2 0 0 1-2-2\"/>' +\n '<path d=\"M9 3h1\"/><path d=\"M9 21h2\"/><path d=\"M14 3h1\"/><path d=\"M3 9v1\"/>' +\n '<path d=\"M21 9v2\"/><path d=\"M3 14v1\"/>',\n hand:\n '<path d=\"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2\"/>' +\n '<path d=\"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2\"/>' +\n '<path d=\"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8\"/>' +\n '<path d=\"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15\"/>',\n 'unfold-horizontal':\n '<path d=\"M16 12h6\"/><path d=\"M8 12H2\"/><path d=\"M12 2v2\"/><path d=\"M12 8v2\"/>' +\n '<path d=\"M12 14v2\"/><path d=\"M12 20v2\"/><path d=\"m19 15 3-3-3-3\"/><path d=\"m5 9-3 3 3 3\"/>',\n workflow:\n '<rect width=\"8\" height=\"8\" x=\"3\" y=\"3\" rx=\"2\"/><path d=\"M7 11v4a2 2 0 0 0 2 2h4\"/>' +\n '<rect width=\"8\" height=\"8\" x=\"13\" y=\"13\" rx=\"2\"/>',\n palette:\n '<path d=\"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z\"/>' +\n '<circle cx=\"13.5\" cy=\"6.5\" r=\".5\" fill=\"currentColor\"/>' +\n '<circle cx=\"17.5\" cy=\"10.5\" r=\".5\" fill=\"currentColor\"/>' +\n '<circle cx=\"6.5\" cy=\"12.5\" r=\".5\" fill=\"currentColor\"/>' +\n '<circle cx=\"8.5\" cy=\"7.5\" r=\".5\" fill=\"currentColor\"/>',\n trash:\n '<path d=\"M10 11v6\"/><path d=\"M14 11v6\"/><path d=\"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6\"/>' +\n '<path d=\"M3 6h18\"/><path d=\"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\"/>',\n 'arrow-left-right':\n '<path d=\"M8 3 4 7l4 4\"/><path d=\"M4 7h16\"/><path d=\"m16 21 4-4-4-4\"/><path d=\"M20 17H4\"/>',\n 'align-start-vertical':\n '<rect width=\"9\" height=\"6\" x=\"6\" y=\"14\" rx=\"2\"/><rect width=\"16\" height=\"6\" x=\"6\" y=\"4\" rx=\"2\"/>' +\n '<path d=\"M2 2v20\"/>',\n x: '<path d=\"M18 6 6 18\"/><path d=\"m6 6 12 12\"/>',\n} as const;\n\nexport type LucideIconName = keyof typeof LUCIDE;\n\nexport interface LucideIconOptions {\n /** Rendered width and height in px. */\n size: number;\n /** Stroke width on the 24 grid. */\n strokeWidth: number;\n}\n\n/**\n * Guide §11: chrome icons are 16px at stroke 2.5 and palette tools 20px at stroke 2, both\n * 1.67px on screen. `currentColor`, so the surrounding role (rest, hover, pressed) decides.\n */\nexport const CHROME_ICON: LucideIconOptions = { size: 16, strokeWidth: 2.5 };\nexport const PALETTE_TOOL_ICON: LucideIconOptions = { size: 20, strokeWidth: 2 };\n\nexport function lucideIcon(name: LucideIconName, options: LucideIconOptions = CHROME_ICON): string {\n return (\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${options.size}\" height=\"${options.size}\" ` +\n `viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"${options.strokeWidth}\" ` +\n `stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">` +\n `${LUCIDE[name]}</svg>`\n );\n}\n","import { CHROME_ICON, PALETTE_TOOL_ICON, lucideIcon } from './lucide.js';\nimport { COLORS } from './styles.js';\n\n/**\n * Notation glyphs of the context pad (append and connect): the value chain's own shapes and\n * relations, which Lucide has no icon for. Drawn on the 24 grid like Lucide and set at the\n * chrome size, so they weigh the same as the Lucide icons next to them.\n */\nfunction glyph(content: string, viewBox = '0 0 24 24'): string {\n return (\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${CHROME_ICON.size}\" height=\"${CHROME_ICON.size}\" ` +\n `viewBox=\"${viewBox}\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"${CHROME_ICON.strokeWidth}\" ` +\n `stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">${content}</svg>`\n );\n}\n\n/**\n * Palette previews of the creating entries (guide §5.5): the shape as the canvas draws it,\n * white with the ink contour, so the palette shows what it creates.\n */\nfunction preview(content: string): string {\n return (\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" ` +\n `fill=\"${COLORS.fill}\" stroke=\"${COLORS.ink}\" stroke-width=\"1.5\" stroke-linecap=\"round\" ` +\n `stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">${content}</svg>`\n );\n}\n\n/** Chevron used wherever a step is depicted (matches the canvas shape). */\nconst CHEVRON = 'M3 7 h12 l6 5 -6 5 H3 l4.5 -5 Z';\n\nexport const ICONS = {\n handTool: lucideIcon('hand', PALETTE_TOOL_ICON),\n lassoTool: lucideIcon('square-dashed-mouse-pointer', PALETTE_TOOL_ICON),\n spaceTool: lucideIcon('unfold-horizontal', PALETTE_TOOL_ICON),\n globalConnect: lucideIcon('workflow', PALETTE_TOOL_ICON),\n createStep: preview(`<path d=\"${CHEVRON}\"/>`),\n createOrgUnit: preview('<ellipse cx=\"12\" cy=\"12\" rx=\"9.5\" ry=\"6.5\"/>'),\n appendStep: glyph(\n '<path d=\"M2.5 12 h4.5 m-2 -2 2 2 -2 2\" stroke-dasharray=\"2.6 2\"/>' +\n '<path d=\"M9 7 h8 l4 5 -4 5 H9 l3 -5 Z\"/>',\n ),\n appendSubStep: glyph(\n '<path d=\"M7 3 v8.5 h2.5\" />' +\n '<path d=\"M11 7 h7.5 l3 4.5 -3 4.5 H11 l2.5 -4.5 Z\" transform=\"translate(-1.5 0.5)\"/>',\n '0 0 22 22',\n ),\n connectSequence: glyph(\n '<path d=\"M4 19 L17.5 5.5\" stroke-dasharray=\"3 2.6\"/><path d=\"M13 5 h5.5 v5.5\" />',\n ),\n connectHierarchy: glyph('<path d=\"M6 4 v14 h11.5 m-3.5 -3.5 3.5 3.5 -3.5 3.5\"/>'),\n appendOrgUnit: glyph('<path d=\"M12 3.5 v5\"/><ellipse cx=\"12\" cy=\"15\" rx=\"8.5\" ry=\"5.5\"/>'),\n toggleType: lucideIcon('arrow-left-right'),\n align: lucideIcon('align-start-vertical'),\n color: lucideIcon('palette'),\n trash: lucideIcon('trash'),\n} as const;\n\n/** No native `title`: the palette's tooltip (diagram-js or a host's chrome) names the entry. */\nexport function paletteEntryHtml(iconSvg: string, draggable = false): string {\n return (\n `<div class=\"entry vc-palette-entry\"${draggable ? ' draggable=\"true\"' : ''}>` +\n `${iconSvg}</div>`\n );\n}\n\nexport function contextPadEntryHtml(iconSvg: string, draggable = false): string {\n return `<div class=\"entry vc-cp-entry\"${draggable ? ' draggable=\"true\"' : ''}>${iconSvg}</div>`;\n}\n","import type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type Palette from 'diagram-js/lib/features/palette/Palette';\nimport type PaletteProvider from 'diagram-js/lib/features/palette/PaletteProvider';\nimport type Create from 'diagram-js/lib/features/create/Create';\nimport type HandTool from 'diagram-js/lib/features/hand-tool/HandTool';\nimport type LassoTool from 'diagram-js/lib/features/lasso-tool/LassoTool';\nimport type SpaceTool from 'diagram-js/lib/features/space-tool/SpaceTool';\nimport type GlobalConnect from 'diagram-js/lib/features/global-connect/GlobalConnect';\nimport type Modeling from 'diagram-js/lib/features/modeling/Modeling';\nimport type Selection from 'diagram-js/lib/features/selection/Selection';\nimport type { Element, Shape } from 'diagram-js/lib/model/Types';\nimport type { FreeArea, FreeAreaInsets } from '@miragon/modeler-api';\nimport type { Point } from '@miragon/value-chain-schema-model';\nimport type VcElementFactory from '../model/VcElementFactory.js';\nimport { isVcShape, type VcShape } from '../model/di-types.js';\nimport { ICONS, paletteEntryHtml } from '../draw/icons.js';\n\ninterface PaletteEntry {\n group: string;\n html?: string;\n title?: string;\n shortcut?: string;\n action?: Record<string, (event: Event) => void>;\n}\n\nexport interface VcPaletteConfig {\n /**\n * The canvas area the host's chrome leaves free: Enter or Space on a creating entry places the\n * element in its centre (guide §5.5). Without it, or while its centre is undefined, the element\n * lands in the centre of the visible canvas.\n */\n freeArea?: FreeArea | undefined;\n /** @deprecated Use `freeArea: { center }`. Given both, `freeArea` wins. */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\ninterface DirectEditingLike {\n activate(element: Element): boolean;\n}\n\ninterface EditLock {\n isReadOnly(): boolean;\n}\n\n/** Guide §5.5: a keyboard-created element lands this far down-right of one already centred there. */\nconst KEYBOARD_CREATE_OFFSET = 24;\n\n/**\n * Tools first (Lasso, Hand, Space, Connect), then the creating entries. Tool entry keys end in\n * `-tool` in the group `tools`, so the active tool gets highlighted. Titles and shortcuts are\n * separate fields, so a tooltip shows the key as a chip.\n */\nexport default class VcPaletteProvider {\n static $inject = [\n 'palette',\n 'create',\n 'vcElementFactory',\n 'handTool',\n 'lassoTool',\n 'spaceTool',\n 'globalConnect',\n 'canvas',\n 'modeling',\n 'selection',\n 'elementRegistry',\n 'injector',\n 'config.vcPalette',\n ];\n\n constructor(\n palette: Palette,\n private readonly create: Create,\n private readonly factory: VcElementFactory,\n private readonly handTool: HandTool,\n private readonly lassoTool: LassoTool,\n private readonly spaceTool: SpaceTool,\n private readonly globalConnect: GlobalConnect,\n private readonly canvas: Canvas,\n private readonly modeling: Modeling,\n private readonly selection: Selection,\n private readonly elementRegistry: ElementRegistry,\n private readonly injector: { get<T>(name: string, strict?: boolean): T | null },\n private readonly config: VcPaletteConfig | undefined,\n ) {\n palette.registerProvider(this as unknown as PaletteProvider);\n }\n\n getPaletteEntries(): Record<string, PaletteEntry> {\n const creator = (newShape: () => VcShape) => (event: Event) => {\n if (this.editLock()?.isReadOnly()) {\n return;\n }\n const shape = newShape();\n if (isKeyboardClick(event)) {\n this.placeInFreeRect(shape);\n return;\n }\n this.create.start(event as MouseEvent, shape as Shape);\n };\n const createStep = creator(() => this.factory.createNewStep());\n const createOrgUnit = creator(() => this.factory.createNewOrgUnit());\n\n return {\n 'lasso-tool': {\n group: 'tools',\n title: 'Lasso',\n shortcut: 'L',\n html: paletteEntryHtml(ICONS.lassoTool),\n action: { click: (event) => this.lassoTool.activateSelection(event as MouseEvent, false) },\n },\n 'hand-tool': {\n group: 'tools',\n title: 'Hand',\n shortcut: 'H',\n html: paletteEntryHtml(ICONS.handTool),\n action: { click: (event) => this.handTool.activateHand(event as MouseEvent, false, false) },\n },\n 'space-tool': {\n group: 'tools',\n title: 'Create or remove space',\n shortcut: 'S',\n html: paletteEntryHtml(ICONS.spaceTool),\n action: {\n click: (event) => this.spaceTool.activateSelection(event as MouseEvent, false, false),\n },\n },\n 'global-connect-tool': {\n group: 'tools',\n title: 'Connect',\n shortcut: 'C',\n html: paletteEntryHtml(ICONS.globalConnect),\n action: { click: (event) => this.globalConnect.start(event as MouseEvent, false) },\n },\n 'create.step': {\n group: 'value-chain',\n title: 'Step',\n html: paletteEntryHtml(ICONS.createStep, true),\n action: { click: createStep, dragstart: createStep },\n },\n 'create.org-unit': {\n group: 'value-chain',\n title: 'Organizational unit',\n html: paletteEntryHtml(ICONS.createOrgUnit, true),\n action: { click: createOrgUnit, dragstart: createOrgUnit },\n },\n };\n }\n\n /**\n * Enter or Space on a creating entry (guide §5.5): diagram-js's create follows the pointer and\n * never ends without one, so the element goes straight to the centre of the free rectangle,\n * selected, with the focus on the canvas and its label editor open.\n */\n private placeInFreeRect(shape: VcShape): void {\n const centre = this.freeAreaCentre() ?? this.visibleCentre();\n const position = { x: centre.x, y: centre.y };\n while (this.centreTaken(position)) {\n position.x += KEYBOARD_CREATE_OFFSET;\n position.y += KEYBOARD_CREATE_OFFSET;\n }\n const created = this.modeling.createShape(\n shape as Shape,\n position,\n this.canvas.getRootElement() as Shape,\n );\n this.selection.select(created);\n this.canvas.focus();\n this.injector.get<DirectEditingLike>('directEditing', false)?.activate(created);\n }\n\n private freeAreaCentre(): Point | undefined {\n const area = this.config?.freeArea;\n if (area?.center) return area.center();\n if (area?.insets) return this.centreWithin(area.insets());\n return this.config?.freeRectCenter?.();\n }\n\n /** The centre of the container without `insets`, in diagram coordinates, as a fit centres. */\n private centreWithin(insets: FreeAreaInsets): Point | undefined {\n const { width, height } = this.canvas.getSize();\n if (!(width > 0 && height > 0)) return undefined;\n // An axis the insets leave no room on centres in the whole container instead.\n const middle = (size: number, start: number, end: number): number =>\n start + end < size ? start + (size - start - end) / 2 : size / 2;\n const { x, y, scale } = this.canvas.viewbox();\n return {\n x: x + middle(width, insets.left, insets.right) / scale,\n y: y + middle(height, insets.top, insets.bottom) / scale,\n };\n }\n\n private visibleCentre(): Point {\n const { x, y, width, height } = this.canvas.viewbox();\n return { x: x + width / 2, y: y + height / 2 };\n }\n\n private centreTaken(point: Point): boolean {\n return this.elementRegistry\n .filter(isVcShape)\n .some(\n (element) =>\n Math.abs(element.x + element.width / 2 - point.x) < 1 &&\n Math.abs(element.y + element.height / 2 - point.y) < 1,\n );\n }\n\n private editLock(): EditLock | null {\n return this.injector.get<EditLock>('vcReadOnly', false);\n }\n}\n\n/** The click a host's chrome synthesises for Enter or Space on an entry: no pointer, detail 0. */\nfunction isKeyboardClick(event: Event): boolean {\n return event.type === 'click' && (event as MouseEvent).detail === 0;\n}\n","import type { ModuleDeclaration } from 'didi';\nimport PaletteModule from 'diagram-js/lib/features/palette';\nimport CreateModule from 'diagram-js/lib/features/create';\nimport HandToolModule from 'diagram-js/lib/features/hand-tool';\nimport LassoToolModule from 'diagram-js/lib/features/lasso-tool';\nimport SpaceToolModule from 'diagram-js/lib/features/space-tool';\nimport GlobalConnectModule from 'diagram-js/lib/features/global-connect';\nimport VcPaletteProvider from './VcPaletteProvider.js';\n\nexport const vcPaletteModule: ModuleDeclaration = {\n __depends__: [\n PaletteModule,\n CreateModule,\n HandToolModule,\n LassoToolModule,\n SpaceToolModule,\n GlobalConnectModule,\n ],\n __init__: ['vcPaletteProvider'],\n vcPaletteProvider: ['type', VcPaletteProvider],\n};\n\nexport { default as VcPaletteProvider, type VcPaletteConfig } from './VcPaletteProvider.js';\n","import type PopupMenu from 'diagram-js/lib/features/popup-menu/PopupMenu';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { COLOR_OPTIONS, COLORS } from '../draw/styles.js';\nimport { isVcShape } from '../model/di-types.js';\nimport type VcModeling from '../modeling/VcModeling.js';\n\nexport const COLOR_PICKER_PROVIDER_ID = 'vc-color-picker';\n\ninterface PopupMenuEntry {\n label: string;\n group?: string;\n imageHtml?: string;\n action: () => void;\n}\n\nfunction swatch(color: string): string {\n return (\n `<svg viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" aria-hidden=\"true\">` +\n `<rect x=\"1\" y=\"1\" width=\"14\" height=\"14\" rx=\"2\" fill=\"${COLORS.fill}\" ` +\n `stroke=\"${color}\" stroke-width=\"2\"/></svg>`\n );\n}\n\nexport default class VcColorPickerProvider {\n static $inject = ['popupMenu', 'vcModeling'];\n\n constructor(\n popupMenu: PopupMenu,\n private readonly vcModeling: VcModeling,\n ) {\n popupMenu.registerProvider(COLOR_PICKER_PROVIDER_ID, this);\n }\n\n getPopupMenuEntries(target: Element | Element[]): Record<string, PopupMenuEntry> {\n const element = Array.isArray(target) ? target[0] : target;\n if (!isVcShape(element)) {\n return {};\n }\n\n const entries: Record<string, PopupMenuEntry> = {};\n for (const option of COLOR_OPTIONS) {\n entries[`color-${option.label.toLowerCase()}`] = {\n label: option.label,\n imageHtml: swatch(option.color ?? COLORS.ink),\n action: () => this.vcModeling.setColor(element, option.color),\n };\n }\n return entries;\n }\n}\n","import type PopupMenu from 'diagram-js/lib/features/popup-menu/PopupMenu';\nimport type AlignElements from 'diagram-js/lib/features/align-elements/AlignElements';\nimport type DistributeElements from 'diagram-js/lib/features/distribute-elements/DistributeElements';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { isVcShape } from '../model/di-types.js';\n\nexport const ALIGN_MENU_PROVIDER_ID = 'vc-align-elements';\n\ninterface PopupMenuEntry {\n label: string;\n group?: string;\n imageHtml?: string;\n action: () => void;\n}\n\nfunction alignIcon(content: string): string {\n return (\n '<svg viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" ' +\n `stroke-width=\"1.3\" stroke-linecap=\"round\" aria-hidden=\"true\">${content}</svg>`\n );\n}\n\nconst ICONS = {\n left: alignIcon(\n '<path d=\"M3 2v12\"/><rect x=\"5\" y=\"4\" width=\"8\" height=\"3\"/><rect x=\"5\" y=\"9\" width=\"5\" height=\"3\"/>',\n ),\n center: alignIcon(\n '<path d=\"M8 2v12\"/><rect x=\"4\" y=\"4\" width=\"8\" height=\"3\"/><rect x=\"5.5\" y=\"9\" width=\"5\" height=\"3\"/>',\n ),\n right: alignIcon(\n '<path d=\"M13 2v12\"/><rect x=\"3\" y=\"4\" width=\"8\" height=\"3\"/><rect x=\"6\" y=\"9\" width=\"5\" height=\"3\"/>',\n ),\n top: alignIcon(\n '<path d=\"M2 3h12\"/><rect x=\"4\" y=\"5\" width=\"3\" height=\"8\"/><rect x=\"9\" y=\"5\" width=\"3\" height=\"5\"/>',\n ),\n middle: alignIcon(\n '<path d=\"M2 8h12\"/><rect x=\"4\" y=\"4\" width=\"3\" height=\"8\"/><rect x=\"9\" y=\"5.5\" width=\"3\" height=\"5\"/>',\n ),\n bottom: alignIcon(\n '<path d=\"M2 13h12\"/><rect x=\"4\" y=\"3\" width=\"3\" height=\"8\"/><rect x=\"9\" y=\"6\" width=\"3\" height=\"5\"/>',\n ),\n horizontal: alignIcon(\n '<rect x=\"2\" y=\"5\" width=\"3\" height=\"6\"/><rect x=\"6.5\" y=\"5\" width=\"3\" height=\"6\"/><rect x=\"11\" y=\"5\" width=\"3\" height=\"6\"/>',\n ),\n vertical: alignIcon(\n '<rect x=\"5\" y=\"2\" width=\"6\" height=\"3\"/><rect x=\"5\" y=\"6.5\" width=\"6\" height=\"3\"/><rect x=\"5\" y=\"11\" width=\"6\" height=\"3\"/>',\n ),\n} as const;\n\n/** Align/distribute menu for multi-selections, opened from the context pad. */\nexport default class VcAlignMenuProvider {\n static $inject = ['popupMenu', 'alignElements', 'distributeElements'];\n\n constructor(\n popupMenu: PopupMenu,\n private readonly alignElements: AlignElements,\n private readonly distributeElements: DistributeElements,\n ) {\n popupMenu.registerProvider(ALIGN_MENU_PROVIDER_ID, this);\n }\n\n getPopupMenuEntries(target: Element | Element[]): Record<string, PopupMenuEntry> {\n const elements = (Array.isArray(target) ? target : [target]).filter(isVcShape) as Element[];\n if (elements.length < 2) {\n return {};\n }\n\n const align = (type: string, label: string, icon: string): PopupMenuEntry => ({\n label,\n group: 'align',\n imageHtml: icon,\n action: () => this.alignElements.trigger(elements, type as never),\n });\n\n const entries: Record<string, PopupMenuEntry> = {\n 'align-left': align('left', 'Align left', ICONS.left),\n 'align-center': align('center', 'Align center', ICONS.center),\n 'align-right': align('right', 'Align right', ICONS.right),\n 'align-top': align('top', 'Align top', ICONS.top),\n 'align-middle': align('middle', 'Align middle', ICONS.middle),\n 'align-bottom': align('bottom', 'Align bottom', ICONS.bottom),\n };\n\n if (elements.length >= 3) {\n entries['distribute-horizontally'] = {\n label: 'Distribute horizontally',\n group: 'distribute',\n imageHtml: ICONS.horizontal,\n action: () => this.distributeElements.trigger(elements, 'horizontal'),\n };\n entries['distribute-vertically'] = {\n label: 'Distribute vertically',\n group: 'distribute',\n imageHtml: ICONS.vertical,\n action: () => this.distributeElements.trigger(elements, 'vertical'),\n };\n }\n\n return entries;\n }\n}\n","import type ContextPad from 'diagram-js/lib/features/context-pad/ContextPad';\nimport type ContextPadProvider from 'diagram-js/lib/features/context-pad/ContextPadProvider';\nimport type Modeling from 'diagram-js/lib/features/modeling/Modeling';\nimport type PopupMenu from 'diagram-js/lib/features/popup-menu/PopupMenu';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport type { ConnectionType } from '@miragon/value-chain-schema-model';\nimport {\n isOrgUnit,\n isStep,\n isVcConnection,\n isVcShape,\n type VcConnection,\n type VcShape,\n} from '../model/di-types.js';\nimport { contextPadEntryHtml, ICONS } from '../draw/icons.js';\nimport { COLOR_PICKER_PROVIDER_ID } from '../popup/VcColorPickerProvider.js';\nimport { ALIGN_MENU_PROVIDER_ID } from '../popup/VcAlignMenuProvider.js';\nimport type VcAppend from '../append/VcAppend.js';\nimport type VcConnect from '../connect/VcConnect.js';\nimport type VcModeling from '../modeling/VcModeling.js';\nimport type VcReadOnly from '../read-only/VcReadOnly.js';\n\ninterface ContextPadEntry {\n group: string;\n html?: string;\n title?: string;\n action: Record<string, (event: Event, element?: Element) => void>;\n}\n\ntype Entries = Record<string, ContextPadEntry>;\n\nexport default class VcContextPadProvider {\n static $inject = [\n 'contextPad',\n 'modeling',\n 'popupMenu',\n 'vcAppend',\n 'vcConnect',\n 'vcModeling',\n 'vcReadOnly',\n ];\n\n constructor(\n contextPad: ContextPad,\n private readonly modeling: Modeling,\n private readonly popupMenu: PopupMenu,\n private readonly vcAppend: VcAppend,\n private readonly vcConnect: VcConnect,\n private readonly vcModeling: VcModeling,\n private readonly readOnly: Pick<VcReadOnly, 'isReadOnly'>,\n ) {\n contextPad.registerProvider(this as unknown as ContextPadProvider);\n }\n\n getContextPadEntries(element: Element): Entries {\n const entries: Entries = {};\n if (this.readOnly.isReadOnly()) {\n return entries;\n }\n\n if (isStep(element)) {\n this.addStepEntries(entries, element);\n }\n\n if (isOrgUnit(element)) {\n const startConnect = (event: Event): void => {\n this.vcConnect.start(event, element, 'assignment');\n };\n entries['connect.assignment'] = {\n group: 'connect',\n title: 'Connect to step',\n html: contextPadEntryHtml(ICONS.connectHierarchy, true),\n action: { click: startConnect, dragstart: startConnect },\n };\n }\n\n if (isVcShape(element)) {\n entries['set-color'] = {\n group: 'edit',\n title: 'Set color',\n html: contextPadEntryHtml(ICONS.color),\n action: {\n click: (event: Event) => {\n const mouse = event as MouseEvent;\n this.popupMenu.open(element, COLOR_PICKER_PROVIDER_ID, {\n x: mouse.clientX,\n y: mouse.clientY,\n });\n },\n },\n };\n }\n\n if (isVcConnection(element) && element.vcType !== 'assignment') {\n const connection = element as VcConnection;\n const other: ConnectionType = connection.vcType === 'sequence' ? 'hierarchy' : 'sequence';\n entries['toggle-type'] = {\n group: 'edit',\n title: `Switch to \"${other === 'sequence' ? 'is predecessor of' : 'is process-oriented superior'}\"`,\n html: contextPadEntryHtml(ICONS.toggleType),\n action: { click: () => this.vcModeling.setConnectionType(connection, other) },\n };\n }\n\n if (isVcShape(element) || isVcConnection(element)) {\n entries['delete'] = {\n group: 'edit',\n title: 'Delete',\n html: contextPadEntryHtml(ICONS.trash),\n action: { click: () => this.modeling.removeElements([element]) },\n };\n }\n\n return entries;\n }\n\n getMultiElementContextPadEntries(elements: Element[]): Entries {\n const entries: Entries = {};\n if (this.readOnly.isReadOnly()) {\n return entries;\n }\n\n if (elements.filter(isVcShape).length >= 2) {\n entries['align'] = {\n group: 'edit',\n title: 'Align / distribute',\n html: contextPadEntryHtml(ICONS.align),\n action: {\n click: (event: Event) => {\n const mouse = event as MouseEvent;\n this.popupMenu.open(elements, ALIGN_MENU_PROVIDER_ID, {\n x: mouse.clientX,\n y: mouse.clientY,\n });\n },\n },\n };\n }\n\n entries['delete'] = {\n group: 'edit',\n title: 'Delete',\n html: contextPadEntryHtml(ICONS.trash),\n action: { click: () => this.modeling.removeElements([...elements]) },\n };\n\n return entries;\n }\n\n private addStepEntries(entries: Entries, shape: VcShape): void {\n const append = (type: ConnectionType) => () => {\n this.vcAppend.append(shape, type);\n };\n const appendDrag = (type: ConnectionType) => (event: Event) => {\n this.vcAppend.startAppendDrag(event, shape, type);\n };\n const connect = (type: ConnectionType) => (event: Event) => {\n this.vcConnect.start(event, shape, type);\n };\n\n entries['append.step'] = {\n group: 'model',\n title: 'Append step (is predecessor of)',\n html: contextPadEntryHtml(ICONS.appendStep, true),\n action: { click: append('sequence'), dragstart: appendDrag('sequence') },\n };\n\n entries['append.sub-step'] = {\n group: 'model',\n title: 'Append sub-step (is process-oriented superior)',\n html: contextPadEntryHtml(ICONS.appendSubStep, true),\n action: { click: append('hierarchy'), dragstart: appendDrag('hierarchy') },\n };\n\n entries['append.org-unit'] = {\n group: 'model',\n title: 'Append organizational unit',\n html: contextPadEntryHtml(ICONS.appendOrgUnit, true),\n action: { click: append('assignment'), dragstart: appendDrag('assignment') },\n };\n\n entries['connect.sequence'] = {\n group: 'connect',\n title: 'Connect (is predecessor of)',\n html: contextPadEntryHtml(ICONS.connectSequence, true),\n action: { click: connect('sequence'), dragstart: connect('sequence') },\n };\n\n entries['connect.hierarchy'] = {\n group: 'connect',\n title: 'Connect (is process-oriented superior)',\n html: contextPadEntryHtml(ICONS.connectHierarchy, true),\n action: { click: connect('hierarchy'), dragstart: connect('hierarchy') },\n };\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport ContextPadModule from 'diagram-js/lib/features/context-pad';\nimport PopupMenuModule from 'diagram-js/lib/features/popup-menu';\nimport VcContextPadProvider from './VcContextPadProvider.js';\n\nexport const vcContextPadModule: ModuleDeclaration = {\n __depends__: [ContextPadModule, PopupMenuModule],\n __init__: ['vcContextPadProvider'],\n vcContextPadProvider: ['type', VcContextPadProvider],\n};\n\nexport { default as VcContextPadProvider } from './VcContextPadProvider.js';\n","import type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { labelInset } from '../draw/geometry.js';\nimport { FONT, LABEL_PADDING } from '../draw/styles.js';\nimport { isOrgUnit, isVcShape, type VcShape } from '../model/di-types.js';\nimport type VcModeling from '../modeling/VcModeling.js';\n\ninterface DirectEditingLike {\n registerProvider(provider: unknown): void;\n activate(element: Element): boolean;\n isActive(element?: Element): boolean;\n complete(): void;\n cancel(): void;\n getValue(): string;\n /** diagram-js-direct-editing internals: the edit open right now and its text box. */\n _active?: { element: Element; context: EditingContext } | null;\n _textbox?: { parent: HTMLElement; content: HTMLElement };\n}\n\ninterface EditingContext {\n bounds: { x: number; y: number; width: number; height: number };\n text: string;\n style?: Record<string, string>;\n options?: Record<string, unknown>;\n}\n\n/** A label edit open right now: the element and the text typed so far, not yet committed. */\nexport interface OpenLabelEdit {\n element: VcShape;\n text: string;\n}\n\n/** An open edit taken down for an import: the id of its element and the uncommitted text. */\ninterface SuspendedEdit {\n elementId: string;\n text: string;\n}\n\n/**\n * In-place label editing via diagram-js-direct-editing: double click (or E) opens a centered\n * text box over the shape's label area; editing commits through the command stack (undoable).\n * Only the user's own gestures commit (Enter, leaving the text box, a click or drag on the\n * canvas); a view change keeps the edit open and moves the text box along. An import takes an open\n * edit down without committing it and reopens it on the element with the same id, with the typed\n * text, when the imported diagram still has that element.\n */\nexport default class VcLabelEditingProvider {\n static $inject = ['directEditing', 'canvas', 'eventBus', 'vcModeling', 'elementRegistry'];\n\n private suspended: SuspendedEdit | null = null;\n private resumeTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n private readonly directEditing: DirectEditingLike,\n private readonly canvas: Canvas,\n eventBus: EventBus,\n private readonly vcModeling: VcModeling,\n private readonly elementRegistry: ElementRegistry,\n ) {\n directEditing.registerProvider(this);\n\n eventBus.on('element.dblclick', (event: { element?: Element }) => {\n if (event.element && isVcShape(event.element)) {\n directEditing.activate(event.element);\n }\n });\n\n // Open editing on freshly appended/created-with-source steps (after the default\n // handlers at priority 1000 have created the shape).\n eventBus.on('autoPlace.end', 500, (event: { shape?: Element }) => {\n if (event.shape && isVcShape(event.shape)) {\n directEditing.activate(event.shape);\n }\n });\n eventBus.on(\n 'create.end',\n 500,\n (event: { context: { source?: Element; shape?: Element; canExecute?: unknown } }) => {\n const { source, shape, canExecute } = event.context;\n if (source && canExecute && shape && isVcShape(shape)) {\n directEditing.activate(shape);\n }\n },\n );\n\n // Interacting elsewhere commits (does not discard) the pending edit.\n eventBus.on(['element.mousedown', 'drag.init', 'autoPlace.start', 'popupMenu.open'], () => {\n if (directEditing.isActive()) {\n directEditing.complete();\n }\n });\n\n // diagram-js cannot tell a host's fit or restore from a wheel zoom, and a host's view change\n // must not write half-typed input into the document (contract L5): the edit stays open.\n eventBus.on('canvas.viewbox.changed', () => this.followView());\n\n // Model changed underneath the editor (undo/redo via chrome or API) — discard the\n // pending edit instead of committing against a possibly removed element.\n eventBus.on('commandStack.changed', () => {\n if (directEditing.isActive()) {\n directEditing.cancel();\n }\n });\n\n // Before the canvas tears down: a field still open would commit onto the destroyed diagram.\n eventBus.on('diagram.destroy', 1500, () => {\n clearTimeout(this.resumeTimer);\n this.suspended = null;\n if (directEditing.isActive()) {\n directEditing.cancel();\n }\n });\n }\n\n /** The edit open right now, or undefined. */\n openEdit(): OpenLabelEdit | undefined {\n const element = this.directEditing._active?.element;\n if (!this.directEditing.isActive() || !isVcShape(element)) {\n return undefined;\n }\n return { element, text: this.directEditing.getValue() };\n }\n\n /**\n * Takes an open edit down WITHOUT committing it, for an import that replaces the diagram: its\n * element is about to be removed, and a later commit would apply the typed text to a detached\n * shape. Hosts re-import remote states while the user types; `resumeAfterImport` brings the\n * editor back with the typed text.\n */\n suspend(): void {\n clearTimeout(this.resumeTimer);\n const open = this.openEdit();\n if (!open) {\n return;\n }\n this.suspended = { elementId: open.element.id, text: open.text };\n this.directEditing.cancel();\n }\n\n /**\n * Reopens a suspended edit on the element with the same id, if the imported diagram still has\n * it. Deferred to the next task, so the text box opens in the view and selection the host\n * restores around the import.\n */\n resumeAfterImport(): void {\n clearTimeout(this.resumeTimer);\n if (!this.suspended) {\n return;\n }\n this.resumeTimer = setTimeout(() => {\n const edit = this.suspended;\n this.suspended = null;\n if (edit && !this.directEditing.isActive()) {\n this.resume(edit);\n }\n }, 0);\n }\n\n private resume(edit: SuspendedEdit): void {\n const element = this.elementRegistry.get(edit.elementId);\n if (!isVcShape(element) || !this.directEditing.activate(element)) {\n return;\n }\n const content = this.directEditing._textbox?.content;\n if (!content) {\n return;\n }\n content.innerText = edit.text;\n const selection = content.ownerDocument.getSelection();\n selection?.selectAllChildren(content);\n selection?.collapseToEnd();\n }\n\n /** Puts the open text box over its element again in the current view, with the typed text. */\n private followView(): void {\n const active = this.directEditing._active;\n const textbox = this.directEditing._textbox;\n if (!active || !textbox) {\n return;\n }\n const context = this.activate(active.element);\n if (!context) {\n return;\n }\n const { x, y, width, height } = context.bounds;\n Object.assign(textbox.parent.style, {\n left: `${x}px`,\n top: `${y}px`,\n width: `${width}px`,\n height: `${height}px`,\n });\n textbox.content.style.fontSize = context.style?.['fontSize'] ?? '';\n // complete() compares the box against this to tell an edit from a mere look at the label.\n active.context.bounds = context.bounds;\n }\n\n activate(element: Element): EditingContext | undefined {\n if (!isVcShape(element)) {\n return undefined;\n }\n const shape = element;\n const bbox = this.canvas.getAbsoluteBBox(shape);\n const zoom = this.canvas.zoom();\n const rawInset = isOrgUnit(shape) ? LABEL_PADDING + 5 : labelInset(shape.width, shape.height);\n const inset = rawInset * zoom;\n\n const bounds = {\n x: bbox.x + inset,\n y: bbox.y,\n width: bbox.width - inset * 2,\n height: bbox.height,\n };\n\n // The text box writes its fill and border as inline styles, so the roles come in here.\n const style = {\n fontFamily: FONT.family,\n fontSize: `${FONT.size * zoom}px`,\n fontWeight: 'normal',\n lineHeight: String(FONT.lineHeight),\n textAlign: 'center',\n backgroundColor: 'var(--cd-ui-flaeche-hoch)',\n border: '1px solid var(--cd-ui-interaktion)',\n };\n\n return {\n bounds,\n style,\n options: { centerVertically: true },\n text: shape.vcLabel || '',\n };\n }\n\n update(element: Element, newText: string): void {\n this.vcModeling.updateLabel(element as VcShape, sanitizeLabel(newText));\n }\n}\n\nfunction sanitizeLabel(text: string): string {\n return text.replace(/\\r\\n?/g, '\\n').trim();\n}\n","import type { ModuleDeclaration } from 'didi';\nimport DirectEditingModule from 'diagram-js-direct-editing';\nimport VcLabelEditingProvider from './VcLabelEditingProvider.js';\n\nexport const vcLabelEditingModule: ModuleDeclaration = {\n __depends__: [DirectEditingModule],\n __init__: ['vcLabelEditingProvider'],\n vcLabelEditingProvider: ['type', VcLabelEditingProvider],\n};\n\nexport { default as VcLabelEditingProvider, type OpenLabelEdit } from './VcLabelEditingProvider.js';\n","import type { ModuleDeclaration } from 'didi';\nimport PopupMenuModule from 'diagram-js/lib/features/popup-menu';\nimport AlignElementsModule from 'diagram-js/lib/features/align-elements';\nimport DistributeElementsModule from 'diagram-js/lib/features/distribute-elements';\nimport VcColorPickerProvider from './VcColorPickerProvider.js';\nimport VcAlignMenuProvider from './VcAlignMenuProvider.js';\n\nexport const vcColorPickerModule: ModuleDeclaration = {\n __depends__: [PopupMenuModule],\n __init__: ['vcColorPickerProvider'],\n vcColorPickerProvider: ['type', VcColorPickerProvider],\n};\n\nexport const vcAlignMenuModule: ModuleDeclaration = {\n __depends__: [PopupMenuModule, AlignElementsModule, DistributeElementsModule],\n __init__: ['vcAlignMenuProvider'],\n vcAlignMenuProvider: ['type', VcAlignMenuProvider],\n};\n\nexport {\n default as VcColorPickerProvider,\n COLOR_PICKER_PROVIDER_ID,\n} from './VcColorPickerProvider.js';\nexport { default as VcAlignMenuProvider, ALIGN_MENU_PROVIDER_ID } from './VcAlignMenuProvider.js';\n","import KeyboardBindings from 'diagram-js/lib/features/keyboard/KeyboardBindings';\nimport { hasModifier, isCmd, isKey } from 'diagram-js/lib/features/keyboard/KeyboardUtil';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type Keyboard from 'diagram-js/lib/features/keyboard/Keyboard';\nimport type EditorActions from 'diagram-js/lib/features/editor-actions/EditorActions';\n\ninterface KeyContext {\n keyEvent: KeyboardEvent;\n}\n\nexport interface VcKeyboardConfig {\n /**\n * Bind Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z and Ctrl+Y to the canvas command stack (default true). A\n * host that owns the history (the VS Code document) passes false, so the keys reach it.\n */\n undoRedoKeys?: boolean | undefined;\n}\n\nconst UNDO_REDO_ACTIONS = new Set(['undo', 'redo']);\n\n/**\n * Default diagram-js bindings (undo/redo/copy/paste/zoom/delete) plus the single-key tool\n * shortcuts L lasso, H hand, S space, C connect, E label editing, and Cmd/Ctrl+A for select all.\n * The keyboard listens on the focused canvas only.\n */\nexport default class VcKeyboardBindings extends KeyboardBindings {\n static override $inject = ['eventBus', 'keyboard', 'config.vcKeyboard'];\n\n private readonly undoRedoKeys: boolean;\n\n constructor(eventBus: EventBus, keyboard: Keyboard, config: VcKeyboardConfig | undefined) {\n super(eventBus, keyboard);\n this.undoRedoKeys = config?.undoRedoKeys ?? true;\n }\n\n override registerBindings(keyboard: Keyboard, editorActions: EditorActions): void {\n // Hiding undo and redo from the stock bindings leaves the keys unprevented, so they travel on\n // to whoever owns the history.\n const boundActions = this.undoRedoKeys\n ? editorActions\n : (Object.create(editorActions, {\n isRegistered: {\n value: (action: string) =>\n !UNDO_REDO_ACTIONS.has(action) && editorActions.isRegistered(action),\n },\n }) as EditorActions);\n super.registerBindings(keyboard, boundActions);\n\n const addListener = (action: string, listener: (context: KeyContext) => boolean | void) => {\n if (editorActions.isRegistered(action)) {\n keyboard.addListener(listener as never);\n }\n };\n\n const bindTool = (action: string, keys: string[]): void => {\n addListener(action, (context) => {\n const event = context.keyEvent;\n if (isKey(keys, event) && !hasModifier(event)) {\n editorActions.trigger(action, {});\n return true;\n }\n return undefined as unknown as boolean;\n });\n };\n\n bindTool('lassoTool', ['l', 'L']);\n bindTool('handTool', ['h', 'H']);\n bindTool('spaceTool', ['s', 'S']);\n bindTool('globalConnectTool', ['c', 'C']);\n bindTool('directEditing', ['e', 'E']);\n\n // diagram-js binds no select all; an unhandled Cmd/Ctrl+A would select the page's text.\n addListener('selectAll', (context) => {\n const event = context.keyEvent;\n if (isCmd(event) && isKey(['a', 'A'], event) && !event.shiftKey && !event.altKey) {\n editorActions.trigger('selectAll', {});\n return true;\n }\n return undefined as unknown as boolean;\n });\n }\n}\n","import type EventBus from 'diagram-js/lib/core/EventBus';\nimport type EditorActions from 'diagram-js/lib/features/editor-actions/EditorActions';\nimport type { Injector } from 'didi';\nimport type { Element } from 'diagram-js/lib/model/Types';\nimport { isVcElement } from '../model/di-types.js';\n\n/** Runs before KeyboardBindings' listener (priority 500) checks registered actions. */\nconst HIGH_PRIORITY = 1500;\n\ninterface ToggleTool {\n toggle(): void;\n}\n\ninterface EditLock {\n isReadOnly(): boolean;\n}\n\n/**\n * Registers the tool, editing and selection actions the keyboard bindings and hosts rely on.\n * Under the edit lock (`vcReadOnly`) the space tool, the connect tool and the label editor stay\n * shut; the hand, the lasso and select all keep working.\n */\nexport default class VcEditorActions {\n static $inject = ['eventBus', 'injector'];\n\n constructor(eventBus: EventBus, injector: Injector) {\n eventBus.on('editorActions.init', HIGH_PRIORITY, (event: { editorActions: EditorActions }) => {\n const { editorActions } = event;\n const lock = injector.get<EditLock>('vcReadOnly', false);\n const unlocked = () => !lock?.isReadOnly();\n\n const register = (\n name: string,\n serviceName: string,\n run: (service: never) => void,\n allowed: () => boolean = () => true,\n ) => {\n const service = injector.get(serviceName, false);\n if (service) {\n editorActions.register({\n [name]: () => {\n if (allowed()) run(service as never);\n },\n });\n }\n };\n\n register('handTool', 'handTool', (tool: ToggleTool) => tool.toggle());\n register('lassoTool', 'lassoTool', (tool: ToggleTool) => tool.toggle());\n register('spaceTool', 'spaceTool', (tool: ToggleTool) => tool.toggle(), unlocked);\n register('globalConnectTool', 'globalConnect', (tool: ToggleTool) => tool.toggle(), unlocked);\n\n const elementRegistry = injector.get('elementRegistry', false) as {\n filter(fn: (element: Element) => boolean): Element[];\n } | null;\n const selection = injector.get('selection', false) as {\n get(): Element[];\n select(elements: Element[]): void;\n } | null;\n if (elementRegistry && selection) {\n editorActions.register({\n selectAll: () => selection.select(elementRegistry.filter(isVcElement)),\n });\n }\n\n const directEditing = injector.get('directEditing', false) as {\n activate(element: Element): void;\n } | null;\n if (directEditing && selection) {\n editorActions.register({\n directEditing: () => {\n const selected = selection.get();\n if (unlocked() && selected.length === 1 && selected[0]) {\n directEditing.activate(selected[0]);\n }\n },\n });\n }\n });\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport KeyboardModule from 'diagram-js/lib/features/keyboard';\nimport EditorActionsModule from 'diagram-js/lib/features/editor-actions';\nimport VcKeyboardBindings from './VcKeyboardBindings.js';\nimport VcEditorActions from './VcEditorActions.js';\n\n/** Overrides the stock `keyboardBindings` with the tool shortcuts and select all. */\nexport const vcKeyboardModule: ModuleDeclaration = {\n __depends__: [KeyboardModule, EditorActionsModule],\n __init__: ['vcEditorActions'],\n keyboardBindings: ['type', VcKeyboardBindings],\n vcEditorActions: ['type', VcEditorActions],\n};\n\nexport { default as VcKeyboardBindings, type VcKeyboardConfig } from './VcKeyboardBindings.js';\nexport { default as VcEditorActions } from './VcEditorActions.js';\n","import OrderingProvider from 'diagram-js/lib/features/ordering/OrderingProvider';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Element, Shape } from 'diagram-js/lib/model/Types';\nimport { isVcConnection } from '../model/di-types.js';\n\n/** Keeps connections behind steps during interactive edits (mirrors the import order). */\nexport default class VcOrderingProvider extends OrderingProvider {\n static override $inject = ['eventBus'];\n\n constructor(eventBus: EventBus) {\n super(eventBus);\n }\n\n override getOrdering(element: Element, newParent: Shape): { parent: Shape; index?: number } {\n if (isVcConnection(element)) {\n const siblings = (newParent.children ?? []) as Element[];\n const index = siblings.filter((child) => child !== element && isVcConnection(child)).length;\n return { parent: newParent, index };\n }\n return { parent: newParent };\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport VcOrderingProvider from './VcOrderingProvider.js';\n\nexport const vcOrderingModule: ModuleDeclaration = {\n __init__: ['vcOrderingProvider'],\n vcOrderingProvider: ['type', VcOrderingProvider],\n};\n\nexport { default as VcOrderingProvider } from './VcOrderingProvider.js';\n","import type EventBus from 'diagram-js/lib/core/EventBus';\nimport { isVcConnection, isVcShape } from '../model/di-types.js';\n\ninterface CopyContext {\n descriptor: Record<string, unknown>;\n element: unknown;\n}\n\n/**\n * Copy/paste support: diagram-js turns copy descriptors into element attrs on paste,\n * so carrying the flat domain properties across is all that is needed.\n */\nexport default class VcCopyPasteBehavior {\n static $inject = ['eventBus'];\n\n constructor(eventBus: EventBus) {\n eventBus.on('copyPaste.copyElement', (context: CopyContext) => {\n const { descriptor, element } = context;\n if (isVcShape(element)) {\n descriptor['vcType'] = element.vcType;\n descriptor['vcLabel'] = element.vcLabel;\n if (element.color !== undefined) {\n descriptor['color'] = element.color;\n }\n if (element.link !== undefined) {\n descriptor['link'] = element.link;\n }\n } else if (isVcConnection(element)) {\n descriptor['vcType'] = element.vcType;\n }\n });\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport CopyPasteModule from 'diagram-js/lib/features/copy-paste';\nimport VcCopyPasteBehavior from './VcCopyPasteBehavior.js';\n\nexport const vcCopyPasteModule: ModuleDeclaration = {\n __depends__: [CopyPasteModule],\n __init__: ['vcCopyPasteBehavior'],\n vcCopyPasteBehavior: ['type', VcCopyPasteBehavior],\n};\n\nexport { default as VcCopyPasteBehavior } from './VcCopyPasteBehavior.js';\n","import type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Shape } from 'diagram-js/lib/model/Types';\nimport { MIN_STEP_SIZE } from '@miragon/value-chain-schema-model';\nimport { isVcShape } from '../model/di-types.js';\n\ninterface ResizeStartEvent {\n context: {\n shape?: unknown;\n minDimensions?: { width: number; height: number };\n };\n}\n\n/** Enforces the minimum step size while resizing and while using the space tool. */\nexport default class VcResizeBehavior {\n static $inject = ['eventBus'];\n\n constructor(eventBus: EventBus) {\n eventBus.on('resize.start', (event: ResizeStartEvent) => {\n if (isVcShape(event.context.shape)) {\n event.context.minDimensions = { ...MIN_STEP_SIZE };\n }\n });\n\n eventBus.on(\n 'spaceTool.getMinDimensions',\n (event: { shapes: Shape[] }): Record<string, { width: number; height: number }> => {\n const minDimensions: Record<string, { width: number; height: number }> = {};\n for (const shape of event.shapes) {\n if (isVcShape(shape)) {\n minDimensions[shape.id] = { ...MIN_STEP_SIZE };\n }\n }\n return minDimensions;\n },\n );\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport ResizeModule from 'diagram-js/lib/features/resize';\nimport VcResizeBehavior from './VcResizeBehavior.js';\n\nexport const vcResizeModule: ModuleDeclaration = {\n __depends__: [ResizeModule],\n __init__: ['vcResizeBehavior'],\n vcResizeBehavior: ['type', VcResizeBehavior],\n};\n\nexport { default as VcResizeBehavior } from './VcResizeBehavior.js';\n","import RuleProvider from 'diagram-js/lib/features/rules/RuleProvider';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type { Injector } from 'didi';\n\n/** Fired with `{ readOnly }` whenever the lock changes. */\nexport const READ_ONLY_CHANGED_EVENT = 'valueChain.readOnly.changed';\n\n/** Above every edit rule of the renderer and diagram-js, so the lock wins. */\nconst LOCK_PRIORITY = 5000;\n\nconst EDIT_RULES = [\n 'elements.move',\n 'shape.move',\n 'shape.resize',\n 'shape.create',\n 'elements.create',\n 'shape.append',\n 'connection.start',\n 'connection.create',\n 'connection.reconnect',\n 'connection.updateWaypoints',\n 'elements.delete',\n 'elements.align',\n 'elements.distribute',\n];\n\ninterface Closable {\n close(): void;\n}\n\ninterface Cancellable {\n cancel(): void;\n}\n\n/**\n * Locks every edit on the canvas while the document behind it cannot be saved from the canvas\n * (an invalid file in an IDE host, guide §13.5): the rules veto move, resize, create, connect,\n * reconnect, waypoints, delete, align and distribute; paste, the label editor and the context pad\n * stay shut, and the editing keys and tools check `isReadOnly()`. Selection, lasso, hand, zoom,\n * copy and export keep working.\n */\nexport default class VcReadOnly extends RuleProvider {\n static override $inject = ['eventBus', 'injector'];\n\n private readOnly = false;\n\n constructor(\n private readonly bus: EventBus,\n private readonly injector: Injector,\n ) {\n super(bus);\n bus.on('copyPaste.pasteElements', LOCK_PRIORITY, () => (this.readOnly ? false : undefined));\n bus.on('directEditing.activate.allowed', LOCK_PRIORITY, () =>\n this.readOnly ? false : undefined,\n );\n }\n\n override init(): void {\n this.addRule(EDIT_RULES, LOCK_PRIORITY, () => (this.readOnly ? false : undefined));\n }\n\n isReadOnly(): boolean {\n return this.readOnly;\n }\n\n setReadOnly(readOnly: boolean): void {\n if (this.readOnly === readOnly) {\n return;\n }\n this.readOnly = readOnly;\n if (readOnly) {\n this.interruptEdits();\n }\n this.bus.fire(READ_ONLY_CHANGED_EVENT, { readOnly });\n }\n\n /** What was already under way when the lock arrived must not land on the locked canvas. */\n private interruptEdits(): void {\n const optional = <T>(name: string): T | undefined => this.injector.get<T>(name, false);\n optional<Cancellable>('directEditing')?.cancel();\n optional<Cancellable>('dragging')?.cancel();\n optional<Closable>('popupMenu')?.close();\n optional<Closable>('contextPad')?.close();\n }\n}\n","import type { ModuleDeclaration } from 'didi';\nimport RulesModule from 'diagram-js/lib/features/rules';\nimport VcReadOnly from './VcReadOnly.js';\n\n/** The canvas edit lock (an invalid file in an IDE host). */\nexport const vcReadOnlyModule: ModuleDeclaration = {\n __depends__: [RulesModule],\n __init__: ['vcReadOnly'],\n vcReadOnly: ['type', VcReadOnly],\n};\n\nexport { default as VcReadOnly, READ_ONLY_CHANGED_EVENT } from './VcReadOnly.js';\n","import type { ModuleDeclaration } from 'didi';\nimport type CommandStack from 'diagram-js/lib/command/CommandStack';\nimport ModelingModule from 'diagram-js/lib/features/modeling';\nimport MoveModule from 'diagram-js/lib/features/move';\nimport OutlineModule from 'diagram-js/lib/features/outline';\nimport BendpointsModule from 'diagram-js/lib/features/bendpoints';\nimport AutoScrollModule from 'diagram-js/lib/features/auto-scroll';\nimport GridSnappingModule from 'diagram-js/lib/features/grid-snapping';\nimport SnappingModule from 'diagram-js/lib/features/snapping';\nimport KeyboardMoveSelectionModule from 'diagram-js/lib/features/keyboard-move-selection';\nimport KeyboardMoveModule from 'diagram-js/lib/navigation/keyboard-move';\nimport { NavigatedViewer } from './NavigatedViewer.js';\nimport { vcModelingModule } from './modeling/index.js';\nimport { vcRulesModule } from './rules/index.js';\nimport { vcConnectModule } from './connect/index.js';\nimport { vcAppendModule } from './append/index.js';\nimport { vcPaletteModule } from './palette/index.js';\nimport { vcContextPadModule } from './context-pad/index.js';\nimport { vcLabelEditingModule } from './label-editing/index.js';\nimport { vcAlignMenuModule, vcColorPickerModule } from './popup/index.js';\nimport { vcKeyboardModule } from './keyboard/index.js';\nimport { vcOrderingModule } from './ordering/index.js';\nimport { vcCopyPasteModule } from './copy-paste/index.js';\nimport { vcResizeModule } from './resize/index.js';\nimport { vcReadOnlyModule } from './read-only/index.js';\n\n/**\n * The full value chain editor, with the edit lock for a document the canvas cannot save\n * (`vcReadOnly`).\n */\nexport class Modeler extends NavigatedViewer {\n protected override _getModules(): ModuleDeclaration[] {\n return [\n ...super._getModules(),\n // stock diagram-js editing features\n ModelingModule,\n MoveModule,\n OutlineModule,\n BendpointsModule,\n AutoScrollModule,\n GridSnappingModule,\n SnappingModule,\n KeyboardMoveSelectionModule,\n KeyboardMoveModule,\n // value chain specific modules\n vcReadOnlyModule,\n vcModelingModule,\n vcRulesModule,\n vcConnectModule,\n vcAppendModule,\n vcPaletteModule,\n vcContextPadModule,\n vcLabelEditingModule,\n vcColorPickerModule,\n vcAlignMenuModule,\n vcKeyboardModule,\n vcOrderingModule,\n vcCopyPasteModule,\n vcResizeModule,\n ];\n }\n\n undo(): void {\n this.get<CommandStack>('commandStack').undo();\n }\n\n redo(): void {\n this.get<CommandStack>('commandStack').redo();\n }\n\n canUndo(): boolean {\n return this.get<CommandStack>('commandStack').canUndo();\n }\n\n canRedo(): boolean {\n return this.get<CommandStack>('commandStack').canRedo();\n }\n}\n","import {\n MODELER_API_VERSION,\n type CollaborativeModeler,\n type CollaborativeModelerOptions,\n type ElementBounds,\n type ElementInfo,\n type ElementsSurface,\n type ImportResult,\n type ModelerMeta,\n} from '@miragon/modeler-api';\nimport type { ModuleDeclaration } from 'didi';\nimport type Canvas from 'diagram-js/lib/core/Canvas';\nimport type ElementRegistry from 'diagram-js/lib/core/ElementRegistry';\nimport type EventBus from 'diagram-js/lib/core/EventBus';\nimport type Selection from 'diagram-js/lib/features/selection/Selection';\nimport {\n createEmptyDocument,\n parseDocumentJSON,\n serializeDocument,\n type Point,\n type ValueChainDocument,\n} from '@miragon/value-chain-schema-model';\nimport { Modeler } from '../Modeler.js';\nimport { NavigatedViewer } from '../NavigatedViewer.js';\nimport type { VcViewerOptions } from '../VcBaseViewer.js';\nimport type VcBounds from '../bounds/VcBounds.js';\nimport { isVcShape, type VcShape } from '../model/di-types.js';\n\n/** Stable notation id in `meta.notation` of the collaborative-modeler contract. */\nexport const VALUE_CHAIN_NOTATION = 'value-chain';\n\n/** What a blank text (a file just created in the explorer) opens as. */\nexport const BLANK_DOCUMENT_NAME = 'New value chain';\n\n/**\n * The contract's factory options (`freeArea`, `fitOnImport`, `undoRedoKeys`, see\n * `VcViewerOptions`) plus the renderer's own. The viewer ignores the two that need editing.\n */\nexport interface CollaborativeValueChainOptions extends CollaborativeModelerOptions {\n /** Appended to the renderer's own modules (e.g. a host's chrome module). */\n additionalModules?: ModuleDeclaration[] | undefined;\n /**\n * @deprecated Use `freeArea: { center }`; accepted until the next minor release. Given both,\n * `freeArea` wins.\n */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\n/** The contract surface plus the wrapped diagram for host-specific wiring. */\nexport interface CollaborativeValueChainModeler extends CollaborativeModeler {\n readonly elements: ElementsSurface & Required<Pick<ElementsSurface, 'bounds'>>;\n /**\n * The tight box around every step, org unit and connection (waypoints included) in diagram\n * coordinates, without a margin of its own; undefined while the diagram has no element. Label\n * text that overflows its shape is not part of the box, as in the SVG export.\n */\n contentBounds(): ElementBounds | undefined;\n readonly diagram: Modeler | NavigatedViewer;\n}\n\ninterface ViewState {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** The editing mount (`meta.editable: true`) of the collaborative-modeler contract. */\nexport function createCollaborativeModeler(\n options: CollaborativeValueChainOptions = {},\n): CollaborativeValueChainModeler {\n return collaborative(\n new Modeler({\n ...diagramOptions(options),\n undoRedoKeys: options.undoRedoKeys ?? true,\n freeArea: options.freeArea,\n freeRectCenter: options.freeRectCenter,\n }),\n true,\n );\n}\n\n/** The read-only mount (`meta.editable: false`): imports, exports and reveals, never edits. */\nexport function createCollaborativeViewer(\n options: CollaborativeValueChainOptions = {},\n): CollaborativeValueChainModeler {\n return collaborative(new NavigatedViewer(diagramOptions(options)), false);\n}\n\nfunction diagramOptions(options: CollaborativeValueChainOptions): VcViewerOptions {\n return {\n width: '100%',\n height: '100%',\n additionalModules: options.additionalModules ?? [],\n fitOnImport: options.fitOnImport ?? true,\n };\n}\n\n/** Blank text is an empty diagram; anything else must be a valid document. */\nfunction documentOf(text: string): ValueChainDocument {\n return text.trim() === '' ? createEmptyDocument(BLANK_DOCUMENT_NAME) : parseDocumentJSON(text);\n}\n\nfunction collaborative(\n diagram: Modeler | NavigatedViewer,\n editable: boolean,\n): CollaborativeValueChainModeler {\n const eventBus = diagram.get<EventBus>('eventBus');\n const canvas = diagram.get<Canvas>('canvas');\n const elementRegistry = diagram.get<ElementRegistry>('elementRegistry');\n const selection = diagram.get<Selection>('selection');\n const vcBounds = diagram.get<VcBounds>('vcBounds');\n const contentListeners = new Set<() => void>();\n let destroyed = false;\n let lastExport = '';\n\n const meta: ModelerMeta = {\n notation: VALUE_CHAIN_NOTATION,\n apiVersion: MODELER_API_VERSION,\n editable,\n };\n\n if (editable) {\n // Imports erase the history without this event, so every delivery is a user's change.\n eventBus.on('commandStack.changed', () => {\n for (const listener of [...contentListeners]) listener();\n });\n }\n\n const elements: CollaborativeValueChainModeler['elements'] = {\n list: () =>\n destroyed ? [] : (elementRegistry.getAll() as unknown[]).filter(isVcShape).map(elementInfo),\n reveal(id) {\n if (destroyed) return false;\n const element = elementRegistry.get(id);\n if (!isVcShape(element)) return false;\n selection.select(element);\n canvas.scrollToElement(element);\n return true;\n },\n selection: () => (destroyed ? [] : shapeIds(selection.get())),\n onSelection(callback) {\n const listener = (event: unknown) =>\n callback(shapeIds((event as { newSelection?: unknown[] }).newSelection ?? []));\n eventBus.on('selection.changed', listener);\n return () => eventBus.off('selection.changed', listener);\n },\n bounds(id): ElementBounds | undefined {\n if (destroyed) return undefined;\n const element = elementRegistry.get(id);\n if (!isVcShape(element)) return undefined;\n const { x, y, width, height } = element;\n return { x, y, width, height };\n },\n };\n\n return {\n meta,\n elements,\n diagram,\n attachTo(host) {\n host.appendChild(diagram.container);\n canvas.resized();\n },\n importText(text): Promise<ImportResult> {\n if (destroyed) return Promise.reject(new Error('The modeler was destroyed.'));\n try {\n const warnings = diagram.importDocument(documentOf(text));\n return Promise.resolve({ warnings: warnings.map((warning) => warning.message) });\n } catch (error) {\n return Promise.reject(error instanceof Error ? error : new Error(String(error)));\n }\n },\n exportText() {\n // Asking a destroyed diagram would build a new one on the detached container.\n if (destroyed) return lastExport;\n return serializeDocument(diagram.exportDocument());\n },\n onContentChanged(callback) {\n if (!editable) return () => undefined;\n contentListeners.add(callback);\n return () => contentListeners.delete(callback);\n },\n getViewState(): ViewState | undefined {\n if (destroyed) return undefined;\n try {\n const { x, y, width, height } = canvas.viewbox();\n const state = { x, y, width, height };\n return isViewState(state) ? state : undefined;\n } catch {\n return undefined;\n }\n },\n setViewState(state) {\n if (destroyed || !isViewState(state)) return;\n canvas.viewbox({ x: state.x, y: state.y, width: state.width, height: state.height });\n },\n contentBounds(): ElementBounds | undefined {\n // A host's fit adds its own insets (contract 1.3), so no padding here.\n return destroyed ? undefined : vcBounds.contentBounds(0);\n },\n destroy() {\n if (destroyed) return;\n try {\n lastExport = serializeDocument(diagram.exportDocument());\n } catch {\n lastExport = '';\n }\n destroyed = true;\n contentListeners.clear();\n diagram.destroy();\n },\n };\n}\n\nfunction shapeIds(selected: readonly unknown[]): string[] {\n return selected.filter(isVcShape).map((element) => element.id);\n}\n\nfunction elementInfo(element: VcShape): ElementInfo {\n return element.vcLabel ? { id: element.id, name: element.vcLabel } : { id: element.id };\n}\n\nfunction isViewState(state: unknown): state is ViewState {\n if (typeof state !== 'object' || state === null) return false;\n const { x, y, width, height } = state as Record<string, unknown>;\n return (\n isFiniteNumber(x) &&\n isFiniteNumber(y) &&\n isFiniteNumber(width) &&\n isFiniteNumber(height) &&\n width > 0 &&\n height > 0\n );\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n","/*\n * The diagram's entries of the chrome menu (guide §5.4), the same in every host. The types mirror\n * the menu groups of `@miragon/modeler-shell` structurally, so an app hands the result to the\n * shell as it is while the renderer never imports the shell. Value chains have no Model entries:\n * no document setting is edited from the menu.\n */\n\n/** The icons the guide gives these entries (guide §5.14, the shell's common set). */\nexport type DiagramMenuIcon = 'file-image' | 'file-code-corner' | 'keyboard';\n\ninterface DiagramMenuItem {\n readonly id: string;\n readonly label: string;\n readonly icon?: DiagramMenuIcon;\n}\n\nexport interface DiagramMenuAction extends DiagramMenuItem {\n readonly kind: 'action';\n readonly shortcut?: string;\n onSelect(): void;\n}\n\nexport interface DiagramMenuDialog extends DiagramMenuItem {\n readonly kind: 'dialog';\n onSelect(): void;\n}\n\nexport interface DiagramMenu {\n readonly export: readonly DiagramMenuAction[];\n readonly help: readonly DiagramMenuDialog[];\n}\n\nexport interface DiagramExport {\n onSelect(): void;\n /** The chip of an app key that runs the same export, e.g. \"⌘S\". */\n readonly shortcut?: string | undefined;\n}\n\n/**\n * The exports a host offers, in the guide's order: PNG first (the more frequent target), then SVG,\n * then the document itself where the host is not the file (the web app).\n */\nexport interface DiagramExports {\n readonly png: DiagramExport;\n readonly svg: DiagramExport;\n readonly json?: DiagramExport | undefined;\n}\n\nexport interface DiagramMenuActions {\n readonly exports: DiagramExports;\n showKeyboardShortcuts(): void;\n}\n\nfunction exportEntry(\n id: string,\n label: string,\n action: DiagramExport,\n icon?: DiagramMenuIcon,\n): DiagramMenuAction {\n return {\n kind: 'action',\n id,\n label,\n ...(icon ? { icon } : {}),\n ...(action.shortcut ? { shortcut: action.shortcut } : {}),\n onSelect: () => action.onSelect(),\n };\n}\n\n/** The label of the JSON export, also its row in the shortcuts dialog's File group. */\nexport const JSON_EXPORT_LABEL = 'Export as JSON';\n\n/** The menu groups of the diagram (guide §5.4): Export with PNG first, Help. */\nexport function diagramMenu(actions: DiagramMenuActions): DiagramMenu {\n const { exports } = actions;\n return {\n export: [\n exportEntry('export-png', 'Export as PNG', exports.png, 'file-image'),\n exportEntry('export-svg', 'Export as SVG', exports.svg, 'file-code-corner'),\n ...(exports.json ? [exportEntry('export-json', JSON_EXPORT_LABEL, exports.json)] : []),\n ],\n help: [\n {\n kind: 'dialog',\n id: 'keyboard-shortcuts',\n label: 'Keyboard shortcuts…',\n icon: 'keyboard',\n onSelect: () => actions.showKeyboardShortcuts(),\n },\n ],\n };\n}\n","import { JSON_EXPORT_LABEL } from './menu.js';\n\n/*\n * Every shortcut of the diagram for the \"Keyboard shortcuts…\" dialog (guide §5.4): one table per\n * group, the keys as chips like the chrome tooltip's (guide §5.6). The chrome's texts and key\n * names come in structurally (a `@miragon/modeler-shell` handle fits), so the View rows say what\n * the zoom panel's tooltips say.\n */\n\nexport type ShortcutPlatform = 'mac' | 'other';\n\nexport interface ShortcutKeyNames {\n readonly ctrl: string;\n readonly shift: string;\n readonly plus: string;\n readonly minus: string;\n}\n\n/** What the shortcuts need of the chrome around the diagram. */\nexport interface ShortcutsChrome {\n readonly platform: ShortcutPlatform;\n /** The tool's UI language, for the percentage in \"Zoom to 100%\". */\n readonly lang: string;\n readonly messages: {\n readonly zoomIn: string;\n readonly zoomOut: string;\n zoomToActual(percent: string): string;\n readonly fit: string;\n /** The File group's \"Open…\" (the shell's `messages.openFile`); default \"Open…\". */\n readonly openFile?: string | undefined;\n readonly keyNames: ShortcutKeyNames;\n };\n}\n\nexport interface ShortcutRow {\n readonly action: string;\n /** Alternative key combinations, each shown as its own chip. */\n readonly keys: readonly string[];\n}\n\nexport interface ShortcutGroup {\n readonly title: string;\n readonly rows: readonly ShortcutRow[];\n}\n\nexport interface DiagramShortcutOptions {\n /** The web app's file keys: Cmd/Ctrl+O opens a file, Cmd/Ctrl+S exports the JSON document. */\n readonly fileKeys?: boolean | undefined;\n}\n\nconst ARROWS = ['←', '↑', '→', '↓'] as const;\n\n/** \"⌘O\" on macOS, \"Ctrl+O\" elsewhere: the chip of a Cmd/Ctrl key the app binds itself. */\nfunction commandKeyLabel(\n key: string,\n platform: ShortcutPlatform,\n keyNames: Pick<ShortcutKeyNames, 'ctrl'>,\n): string {\n return platform === 'mac' ? `⌘${key}` : `${keyNames.ctrl}+${key}`;\n}\n\nfunction percentOfActualSize(lang: string): string {\n try {\n return new Intl.NumberFormat(lang, { style: 'percent' }).format(1);\n } catch {\n return new Intl.NumberFormat('en', { style: 'percent' }).format(1);\n }\n}\n\n/** The chrome's zoom and fit keys as its tooltips name them (guide §5.8). */\nfunction viewKeys(platform: ShortcutPlatform, keyNames: ShortcutKeyNames) {\n if (platform === 'mac') {\n return { zoomIn: '⌘+', zoomOut: '⌘−', zoomToActual: '⌘0', fit: '⇧1' };\n }\n const { ctrl, shift, plus, minus } = keyNames;\n return {\n zoomIn: `${ctrl}+${plus}`,\n zoomOut: `${ctrl}+${minus}`,\n zoomToActual: `${ctrl}+0`,\n fit: `${shift}+1`,\n };\n}\n\nfunction editKeys(platform: ShortcutPlatform, keyNames: ShortcutKeyNames) {\n if (platform === 'mac') {\n return {\n undo: ['⌘Z'],\n redo: ['⌘⇧Z'],\n selectAll: ['⌘A'],\n copy: ['⌘C'],\n cut: ['⌘X'],\n paste: ['⌘V'],\n duplicate: ['⌘D'],\n remove: ['⌫'],\n coarseMove: ARROWS.map((arrow) => `⇧${arrow}`),\n moveCanvas: ARROWS.map((arrow) => `⌘${arrow}`),\n lassoDrag: ['⇧ Drag'],\n };\n }\n const { ctrl, shift } = keyNames;\n return {\n undo: [`${ctrl}+Z`],\n redo: [`${ctrl}+${shift}+Z`, `${ctrl}+Y`],\n selectAll: [`${ctrl}+A`],\n copy: [`${ctrl}+C`],\n cut: [`${ctrl}+X`],\n paste: [`${ctrl}+V`],\n duplicate: [`${ctrl}+D`],\n remove: ['Del', 'Backspace'],\n coarseMove: ARROWS.map((arrow) => `${shift}+${arrow}`),\n moveCanvas: ARROWS.map((arrow) => `${ctrl}+${arrow}`),\n lassoDrag: [`${shift}+Drag`],\n };\n}\n\nfunction fileGroup(chrome: ShortcutsChrome): ShortcutGroup {\n const { platform, messages } = chrome;\n return {\n title: 'File',\n rows: [\n {\n action: messages.openFile ?? 'Open…',\n keys: [commandKeyLabel('O', platform, messages.keyNames)],\n },\n { action: JSON_EXPORT_LABEL, keys: [commandKeyLabel('S', platform, messages.keyNames)] },\n ],\n };\n}\n\n/**\n * Every shortcut of the diagram, grouped as guide §5.4 asks (View, Edit, the notation's tools),\n * after the web app's File keys where it binds them.\n */\nexport function diagramShortcuts(\n chrome: ShortcutsChrome,\n options: DiagramShortcutOptions = {},\n): ShortcutGroup[] {\n const { platform, messages } = chrome;\n const view = viewKeys(platform, messages.keyNames);\n const edit = editKeys(platform, messages.keyNames);\n return [\n ...(options.fileKeys ? [fileGroup(chrome)] : []),\n {\n title: 'View',\n rows: [\n { action: messages.zoomIn, keys: [view.zoomIn] },\n { action: messages.zoomOut, keys: [view.zoomOut] },\n {\n action: messages.zoomToActual(percentOfActualSize(chrome.lang)),\n keys: [view.zoomToActual],\n },\n { action: messages.fit, keys: [view.fit] },\n { action: 'Move the canvas', keys: edit.moveCanvas },\n ],\n },\n {\n title: 'Edit',\n rows: [\n { action: 'Undo', keys: edit.undo },\n { action: 'Redo', keys: edit.redo },\n { action: 'Select all', keys: edit.selectAll },\n { action: 'Copy', keys: edit.copy },\n { action: 'Cut', keys: edit.cut },\n { action: 'Paste', keys: edit.paste },\n { action: 'Duplicate', keys: edit.duplicate },\n { action: 'Delete', keys: edit.remove },\n { action: 'Edit label', keys: ['E', 'Double-click'] },\n { action: 'Move selection', keys: ARROWS },\n { action: 'Move selection in large steps', keys: edit.coarseMove },\n ],\n },\n {\n title: 'Tools',\n rows: [\n { action: 'Lasso', keys: ['L'] },\n { action: 'Lasso by dragging', keys: edit.lassoDrag },\n { action: 'Hand', keys: ['H'] },\n { action: 'Hand while held', keys: ['Space'] },\n { action: 'Create or remove space', keys: ['S'] },\n { action: 'Connect', keys: ['C'] },\n ],\n },\n ];\n}\n","import { lucideIcon } from '../draw/lucide.js';\nimport {\n diagramShortcuts,\n type DiagramShortcutOptions,\n type ShortcutGroup,\n type ShortcutsChrome,\n} from './shortcuts.js';\n\nconst DIALOG_CLASS = 'vc-shortcuts';\nconst TITLE_ID = 'vc-shortcuts-title';\n\n/** What the dialog needs of the chrome around the diagram; a `@miragon/modeler-shell` handle fits. */\nexport interface ShortcutsDialogChrome extends ShortcutsChrome {\n /** Where the dialog lives (the shell root), so it shares the chrome's mode and fonts. */\n readonly root: HTMLElement;\n readonly messages: ShortcutsChrome['messages'] & { readonly close: string };\n /** The control the focus returns to once the dialog closes. */\n readonly menu: { readonly trigger: HTMLElement };\n}\n\nexport interface ShortcutsDialog {\n open(): void;\n isOpen(): boolean;\n close(): void;\n destroy(): void;\n}\n\nfunction element<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n className: string,\n text?: string,\n): HTMLElementTagNameMap[K] {\n const created = document.createElement(tag);\n created.className = className;\n if (text !== undefined) created.textContent = text;\n return created;\n}\n\nfunction shortcutTable(group: ShortcutGroup, index: number): HTMLElement {\n const section = element('section', `${DIALOG_CLASS}-group`);\n const headingId = `${TITLE_ID}-group-${index}`;\n const heading = element('h4', `${DIALOG_CLASS}-group-title`, group.title);\n heading.id = headingId;\n const table = element('table', `${DIALOG_CLASS}-table`);\n table.setAttribute('aria-labelledby', headingId);\n const body = table.createTBody();\n for (const row of group.rows) {\n const line = body.insertRow();\n const action = element('th', `${DIALOG_CLASS}-action`, row.action);\n action.scope = 'row';\n const keys = element('td', `${DIALOG_CLASS}-keys`);\n for (const key of row.keys) keys.append(element('kbd', `${DIALOG_CLASS}-key`, key));\n line.append(action, keys);\n }\n section.append(heading, table);\n return section;\n}\n\nfunction dialogContent(\n chrome: ShortcutsDialogChrome,\n options: DiagramShortcutOptions,\n onClose: () => void,\n): HTMLElement {\n const panel = element('div', `${DIALOG_CLASS}-panel`);\n const header = element('header', `${DIALOG_CLASS}-header`);\n const title = element('h3', `${DIALOG_CLASS}-title`, 'Keyboard shortcuts');\n title.id = TITLE_ID;\n const close = element('button', `${DIALOG_CLASS}-close`);\n close.type = 'button';\n close.setAttribute('aria-label', chrome.messages.close);\n close.innerHTML = lucideIcon('x');\n close.addEventListener('click', onClose);\n header.append(title, close);\n\n const body = element('div', `${DIALOG_CLASS}-body`);\n body.append(...diagramShortcuts(chrome, options).map(shortcutTable));\n panel.append(header, body);\n return panel;\n}\n\n/**\n * The \"Keyboard shortcuts…\" dialog of the Help group (guide §5.4, §8), a native modal <dialog>\n * inside the chrome's root: the browser keeps the focus inside it, closes it on Escape and puts it\n * in the top layer. Built on the first open and kept (closed) afterwards; the host calls\n * `destroy()` with the diagram's teardown, since the chrome removes only what it added itself.\n */\nexport function createShortcutsDialog(\n chrome: ShortcutsDialogChrome,\n options: DiagramShortcutOptions = {},\n): ShortcutsDialog {\n let dialog: HTMLDialogElement | undefined;\n\n function build(): HTMLDialogElement {\n const created = element('dialog', DIALOG_CLASS);\n created.setAttribute('aria-labelledby', TITLE_ID);\n created.append(dialogContent(chrome, options, () => created.close()));\n // A click on the backdrop targets the <dialog> itself; the panel covers all of its own box.\n created.addEventListener('click', (event) => {\n if (event.target === created) created.close();\n });\n created.addEventListener('close', () => {\n if (!chrome.menu.trigger.hidden) chrome.menu.trigger.focus({ preventScroll: true });\n });\n chrome.root.append(created);\n return created;\n }\n\n return {\n open() {\n dialog ??= build();\n if (!dialog.open) dialog.showModal();\n },\n close() {\n dialog?.close();\n },\n isOpen: () => dialog?.open === true,\n destroy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