@miragon/team-topologies-renderer 0.11.2 → 0.12.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/README.md +24 -6
- package/dist/TtBaseViewer.d.ts +9 -2
- package/dist/TtBaseViewer.d.ts.map +1 -1
- package/dist/collaborative/CollaborativeTeamTopologies.d.ts +15 -11
- package/dist/collaborative/CollaborativeTeamTopologies.d.ts.map +1 -1
- package/dist/collaborative/index.d.ts +1 -1
- package/dist/collaborative/index.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +136 -108
- package/dist/index.js.map +1 -1
- package/dist/label-editing/TtLabelEditing.d.ts +2 -2
- package/dist/label-editing/TtLabelEditing.d.ts.map +1 -1
- package/dist/palette/TtPaletteProvider.d.ts +8 -2
- package/dist/palette/TtPaletteProvider.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["SVG_NAMESPACE","svgAttr","svgCreate","Diagram","CroppingConnectionDocking","BaseRenderer","SelectionModule","ZoomScrollModule","MoveCanvasModule","LassoToolModule","ModelingModule","MoveModule","OutlineModule","ResizeModule","BaseLayouter","RulesModule","RuleProvider","CommandInterceptor","PaletteModule","CreateModule","ConnectModule","ConnectionPreviewModule","ContextPadModule","CopyPasteModule","CopyPaste","SHAPE_KINDS","kindOf","el","isTtElement","kind","isTtTeam","isTtInteraction","isTtFlow","isTtAnnotation","isTtAssociation","MIRAGON","CD_TOKENS","MARGIN","SVG_NAMESPACE$1","INTERACTION_CHROME_SELECTOR","TRANSIENT_CLASSES","CANVAS_ONLY_ATTRIBUTES","saveSVG","source","canvas","minX","minY","maxX","maxY","elementRegistry","s","x","y","width","height","clone","name","node","viewport","sheet","ROOT_ID","DIAGRAM_ROOT_ID","CANVAS_KEYBOARD_FOCUS_CLASS","sizeToCss","value","TtBaseViewer","options","container","modules","canvasContainer","diagram","svg","ownerDocument","lastKeyWasTab","onKeyDown","event","onPointerDown","priority","callback","problems","documentIdProblems","doc","path","message","eventBus","importer","labelEditing","warnings","root","current","partial","target","TtElementFactory","elementFactory","ttForeign","foreignFields","knownFields","TEAM_NODE_FIELDS","shape","INTERACTION_FIELDS","FLOW_FIELDS","annotation","ANNOTATION_FIELDS","associationId","getMid","spec","TEAM_TYPE_SPECS","type","newId","label","INTERACTION_MODE_SPECS","mode","FLOW_SPEC","ANNOTATION_SPEC","text","ttModelModule","TT_RENDER_PRIORITY","INK","INK_MUTED","STROKE_MUTED","FONT","LABEL_INSET","ANNOTATION_PADDING","LINE_HEIGHT","MIN_TEXT_CONTRAST","parseHexColour","colour","match","hex","digit","channel","offset","blendOver","mix","index","opacity","backdrop","relativeLuminance","red","green","blue","linear","contrastRatio","lighter","darker","first","second","b","a","readableTextColour","fillRgb","fill","ink","paper","background","inkContrast","shapeTextColour","element","flowHeadWidth","labelLayout","wrapLabel","maxChars","maxWidth","fontSize","paragraphs","lines","paragraph","words","word","candidate","TeamTopologiesRenderer","visuals","rect","attr","create","append","line","waypointsPath","connection","team","w","h","sw","dash","dashArray","outline","i","iw","ih","c","octagon","attrs","rx","common","glyph","pts","skew","head","shaft","top","bot","p","arrow","arm","bracket","layout","box","lineHeight","centred","startY","ln","t","idx","waypoints","point","ttDrawModule","TtImporter","factory","connectionDocking","existing","foreign","DOCUMENT_FIELDS","flow","interaction","association","elements","connections","shapes","TtExporter","meta","nodes","interactions","flows","annotations","geom","position","size","withForeignFields","attachedTo","attachedElementId","DOCUMENT_VERSION","NARROW_LAYOUT_MAX_WIDTH","TOP_INSET","TOP_INSET_NARROW","PADDING","SIDE_PADDING_NARROW","MAX_FIT_ZOOM","TtViewport","bounds","viewportWidth","viewportHeight","narrow","topInset","sidePadding","contentWidth","contentHeight","scale","freeHeight","slack","SVG_NAMESPACE","GEIST_UNICODE_RANGES","geistFontFaceCss","fonts","subset","embedSvgStyles","parsed","defs","style","css","ioModule","Viewer","NavigatedViewer","setOrDelete","obj","key","UpdatePropertiesHandler","context","old","properties","oldProperties","UNTITLED","UpdateTitleHandler","UPDATE_PROPERTIES","UPDATE_TITLE","ANNOTATION_GAP","TtModeling","commandStack","modeling","associations","TtLayouter","hints","ttModelingModule","isAttachable","TtRules","ttRulesModule","TtFlatModelBehavior","TtAssociationBehavior","previous","other","ttBehaviorsModule","ICON_PENCIL","ICON_TRASH","ICON_LINK","ICON_MESSAGE_SQUARE_PLUS","ICON_SQUARE_DASHED_MOUSE_POINTER","ICON_MENU","ICON_MINUS","ICON_PLUS","ICON_MAXIMIZE","ICON_DOWNLOAD","ICON_X","ICON_STROKE_WIDTH","ICON_SIZE","SVG_ELEMENTS","SVG_ATTRIBUTES","escapeAttribute","positiveNumberOr","number","fallback","iconMarkup","strokeWidth","icon","tag","attributes","allowed","attribute","PALETTE_TOOL_ICON","inner","teamIconSvg","flowIconSvg","annotationIconSvg","lassoIconSvg","interactionIconSvg","GROUP_TOOLS","GROUP_TEAMS","GROUP_MODES","GROUP_GUIDES","KEYBOARD_CREATE_OFFSET","entryHtml","draggable","isKeyboardClick","centreOf","TtPaletteProvider","config","lassoTool","selection","injector","palette","entries","ALL_TEAM_SPECS","ALL_INTERACTION_SPECS","\"flow\"","\"annotation\"","start","newShape","viewbox","centre","place","taken","elementCentre","created","ttPaletteModule","READ_ONLY_CHANGED_EVENT","LOCK_PRIORITY","EDIT_RULES","TtReadOnly","bus","readOnly","ttReadOnlyModule","ENTRY_SELECTOR","cpHtml","focusable","title","editTitle","TtContextPadProvider","contextPad","ttModeling","connect","keyboardEvent","startConnect","appendAnnotation","action","activate","ttContextPadModule","EDITING_MARKER","MIN_EDITOR_WIDTH","editorName","TtLabelEditing","edit","left","boxHeight","editor","resumed","fitToContent","done","cleanup","onKey","onBlur","commit","changed","snapshot","ttLabelEditingModule","NUDGE_STEP","NUDGE_STEP_FAST","ARROW_DIRECTIONS","MODAL_SELECTOR","isTypingTarget","isNode","isCanvasScope","isShape","TtKeyboard","undoRedoKeys","dragging","handleReadingKey","cmd","sel","copyPaste","handleEditingKey","undo","redo","rules","direction","step","ttKeyboardModule","pasteIdPrefix","ttKind","TtCopyPaste","clipboard","mouse","prefix","TT_PROPS","ttCopyPasteModule","prop","tier","isOrdered","TtZOrder","ordered","wrapper","layer","ttZOrderModule","Modeler","TEAM_TOPOLOGIES_NOTATION","createCollaborativeModeler","collaborative","diagramOptions","createCollaborativeViewer","parseDocumentText","result","parseDocument","contentListeners","importsRunning","destroyed","lastExport","MODELER_API_VERSION","editable","listener","exportText","serializeDocument","elementInfo","id","elementIds","host","document","fitOnImport","warning","state","isViewState","isFiniteNumber"],"sources":["../src/model/di-types.ts","../src/theme/palette.ts","../src/io/saveSvg.ts","../src/io/types.ts","../src/TtBaseViewer.ts","../src/model/TtElementFactory.ts","../src/model/index.ts","../src/draw/styles.ts","../src/draw/label-layout.ts","../src/draw/TeamTopologiesRenderer.ts","../src/draw/index.ts","../src/io/TtImporter.ts","../src/io/TtExporter.ts","../src/io/TtViewport.ts","../src/io/fontEmbedding.ts","../src/io/index.ts","../src/Viewer.ts","../src/NavigatedViewer.ts","../src/modeling/cmd/UpdatePropertiesHandler.ts","../src/modeling/cmd/UpdateTitleHandler.ts","../src/modeling/TtModeling.ts","../src/modeling/TtLayouter.ts","../src/modeling/index.ts","../src/rules/TtRules.ts","../src/rules/index.ts","../src/behaviors/TtFlatModelBehavior.ts","../src/behaviors/TtAssociationBehavior.ts","../src/behaviors/index.ts","../src/draw/icons.ts","../src/draw/palette-icons.ts","../src/palette/TtPaletteProvider.ts","../src/palette/index.ts","../src/read-only/TtReadOnly.ts","../src/read-only/index.ts","../src/context-pad/TtContextPadProvider.ts","../src/context-pad/index.ts","../src/label-editing/TtLabelEditing.ts","../src/label-editing/index.ts","../src/keyboard/TtKeyboard.ts","../src/keyboard/index.ts","../src/copy-paste/TtCopyPaste.ts","../src/copy-paste/TtCopyPasteProps.ts","../src/copy-paste/index.ts","../src/zorder/TtZOrder.ts","../src/zorder/index.ts","../src/Modeler.ts","../src/collaborative/CollaborativeTeamTopologies.ts"],"sourcesContent":["/**\n * diagram-js runtime model for the Team Topologies notation. Every element is a\n * placed, resizable SHAPE discriminated by `ttKind`:\n * - `team` — one of the four team types (label inside the box)\n * - `interaction` — a mode glyph (parallelogram / triangle / circle), 50%\n * transparent, overlaid on the boundary between teams\n * - `flow` — the \"flow of change\" arrow guide\n * - `annotation` — a free-text note (BPMN-style open bracket)\n *\n * The only connection is the `association`: the dashed connector from an\n * annotation to the element it is attached to.\n *\n * These runtime properties are the source of truth while editing; the exporter\n * rebuilds the canonical `TtDocument` from them.\n */\n\nimport type { Connection, Shape } from \"diagram-js/lib/model/Types\";\nimport type {\n ForeignFields,\n InteractionMode,\n TeamType,\n} from \"@miragon/team-topologies-schema-model\";\n\nexport type TtKind = \"team\" | \"interaction\" | \"flow\" | \"annotation\";\n\n/** What every Team Topologies shape carries beyond its geometry. */\ninterface TtShape extends Shape {\n /** Fields of the document element the modeler does not know, written back on export. */\n ttForeign?: ForeignFields;\n}\n\nexport interface TtTeam extends TtShape {\n ttKind: \"team\";\n teamType: TeamType;\n /** Display name (separate from diagram-js `label`). */\n ttLabel?: string;\n description?: string;\n fill?: string;\n stroke?: string;\n}\n\nexport interface TtInteraction extends TtShape {\n ttKind: \"interaction\";\n mode: InteractionMode;\n ttLabel?: string;\n fill?: string;\n stroke?: string;\n}\n\nexport interface TtFlow extends TtShape {\n ttKind: \"flow\";\n ttLabel?: string;\n}\n\nexport interface TtAnnotation extends TtShape {\n ttKind: \"annotation\";\n /** The annotation text (may contain line breaks). */\n ttLabel?: string;\n}\n\nexport interface TtAssociation extends Connection {\n ttKind: \"association\";\n}\n\nexport type TtElement = TtTeam | TtInteraction | TtFlow | TtAnnotation;\n\nconst SHAPE_KINDS: ReadonlySet<string> = new Set<TtKind>([\n \"team\",\n \"interaction\",\n \"flow\",\n \"annotation\",\n]);\n\nfunction kindOf(el: unknown): string | undefined {\n return typeof el === \"object\" && el !== null\n ? ((el as { ttKind?: unknown }).ttKind as string | undefined)\n : undefined;\n}\n\nexport function isTtElement(el: unknown): el is TtElement {\n const kind = kindOf(el);\n return kind !== undefined && SHAPE_KINDS.has(kind);\n}\n\nexport function isTtTeam(el: unknown): el is TtTeam {\n return kindOf(el) === \"team\";\n}\n\nexport function isTtInteraction(el: unknown): el is TtInteraction {\n return kindOf(el) === \"interaction\";\n}\n\nexport function isTtFlow(el: unknown): el is TtFlow {\n return kindOf(el) === \"flow\";\n}\n\nexport function isTtAnnotation(el: unknown): el is TtAnnotation {\n return kindOf(el) === \"annotation\";\n}\n\nexport function isTtAssociation(el: unknown): el is TtAssociation {\n return kindOf(el) === \"association\";\n}\n","/**\n * Miragon design tokens — the single source of truth for every non-notation colour in the renderer.\n *\n * Values mirror the Miragon corporate identity: the `miragon-brand:modeler-tool-design` skill in\n * `Miragon/corporate-identity`, whose vendored `cd-tokens.generated.css` (next to this file) defines\n * the `--cd-*` custom properties, generated from `brand/tokens.json`. Re-copy that CSS from the skill\n * to update; never fork the hex values by hand. `packages/renderer/src/theme/theme.sync.test.ts`\n * fails if this mirror drifts from the vendored CSS.\n *\n * Pure data — no DOM, no imports — so it stays inside the P1 DOM-free discipline and can be consumed\n * by the SVG-drawing constants in `draw/styles.ts`.\n *\n * Brand rule: blue leads (`blau` — surfaces, buttons, links, selection), green accents (`gruen` — key\n * visual, highlights; a fill, never body text on white). The four Team Topologies team-type and\n * interaction colours are the official notation and live in `schema-model/notation.ts` — they are NOT\n * part of this brand ramp.\n */\n\n/** Raw Miragon brand ramp + UI neutrals + functional layer — exact `--cd-*` values. */\nexport const MIRAGON = {\n /** Primary: surfaces, buttons, links, selection, backgrounds. */\n blau: \"#335DE5\",\n /** Deeper blue for links / accent text on white (WCAG AA, ~5.5:1). */\n blauLink: \"#2B50D4\",\n /** Lightened blue for accents on dark surfaces (unused here — the canvas is light-only). */\n blauHell: \"#6B8AFF\",\n /** Accent: key visual, highlights, the brand gradient. Bright — a fill, never text on white. */\n gruen: \"#00E676\",\n /** Calm neutral surface (warm off-white) — the paper surround. */\n grau: \"#F9F7F7\",\n /** Text on light; not pure black. */\n schwarz: \"#1D1D1D\",\n weiss: \"#FFFFFF\",\n /** Dividers and decorative borders; no contrast requirement. */\n linie: \"#E6E2E2\",\n /** Non-text elements that need ≥ 3:1 (input borders, structural strokes and connectors). */\n kontur: \"#8F8A8A\",\n /** Secondary text, ≥ 4.5:1 on `weiss` and on `grau`. */\n textLeise: \"#6B6666\",\n /**\n * Functional / status layer. `success` and `warning` are fills, borders, icons and dots only —\n * never text or thin strokes on light (1.67:1 / 1.83:1). `danger` and `info` also carry text\n * (AA on white). Each `-soft` is an opaque tint for notice boxes and badges.\n */\n success: \"#00E676\",\n successSoft: \"#DAFBEB\",\n warning: \"#FFB000\",\n warningSoft: \"#FFF1D2\",\n danger: \"#CD1839\",\n dangerSoft: \"#FBEEF0\",\n info: \"#335DE5\",\n infoSoft: \"#EEF1FD\",\n /** Each `-hell` is the status colour for dark surfaces (unused here — the canvas is light-only). */\n successHell: \"#00E676\",\n warningHell: \"#FFB000\",\n dangerHell: \"#FB6D73\",\n infoHell: \"#6B8AFF\",\n /** Signature brand gradient — brand moments only. Use verbatim. */\n gradientBrand: \"linear-gradient(120deg, #335DE5 30%, #00E676)\",\n} as const;\n\n/**\n * Every `--cd-*` token this repo depends on, mapped to the value it MUST hold. The drift test parses\n * `cd-tokens.generated.css` and asserts each entry matches, so re-copying the vendored CSS with a\n * changed value fails CI until this mirror (and `MIRAGON`) is updated too. `--cd-gradient-format`\n * stays unmirrored: nothing here uses the format-tile gradient.\n */\nexport const CD_TOKENS: Record<string, string> = {\n \"--cd-blau\": MIRAGON.blau,\n \"--cd-gruen\": MIRAGON.gruen,\n \"--cd-grau\": MIRAGON.grau,\n \"--cd-schwarz\": MIRAGON.schwarz,\n \"--cd-weiss\": MIRAGON.weiss,\n \"--cd-blau-link\": MIRAGON.blauLink,\n \"--cd-blau-hell\": MIRAGON.blauHell,\n \"--cd-linie\": MIRAGON.linie,\n \"--cd-kontur\": MIRAGON.kontur,\n \"--cd-text-leise\": MIRAGON.textLeise,\n \"--cd-success\": MIRAGON.success,\n \"--cd-success-soft\": MIRAGON.successSoft,\n \"--cd-warning\": MIRAGON.warning,\n \"--cd-warning-soft\": MIRAGON.warningSoft,\n \"--cd-danger\": MIRAGON.danger,\n \"--cd-danger-soft\": MIRAGON.dangerSoft,\n \"--cd-info\": MIRAGON.info,\n \"--cd-info-soft\": MIRAGON.infoSoft,\n \"--cd-success-hell\": MIRAGON.successHell,\n \"--cd-warning-hell\": MIRAGON.warningHell,\n \"--cd-danger-hell\": MIRAGON.dangerHell,\n \"--cd-info-hell\": MIRAGON.infoHell,\n \"--cd-gradient-brand\": MIRAGON.gradientBrand,\n};\n","/**\n * Serialises the current canvas into a standalone SVG (snapshot / export),\n * fitted to the content bounds and independent of the current zoom / scroll.\n * Interaction chrome (selection outlines, resize handles, hover state) is left\n * out, and a white sheet sits behind the diagram, so an export always looks the\n * same as the light canvas, whatever was selected and wherever it is viewed.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type ElementRegistry from \"diagram-js/lib/core/ElementRegistry\";\nimport { isTtElement } from \"../model/di-types.js\";\nimport { MIRAGON } from \"../theme/palette.js\";\n\nconst MARGIN = 40;\nconst SVG_NAMESPACE = \"http://www.w3.org/2000/svg\";\n\nconst INTERACTION_CHROME_SELECTOR = [\n \".djs-outline\",\n \".djs-resizer\",\n \".djs-selection-outline\",\n \".djs-lasso-overlay\",\n \".djs-dragger\",\n \".djs-bendpoint\",\n \".djs-segment-dragger\",\n].join(\", \");\n\nconst TRANSIENT_CLASSES = [\"selected\", \"hover\"];\n\nconst CANVAS_ONLY_ATTRIBUTES = [\"class\", \"tabindex\", \"role\", \"aria-roledescription\", \"aria-label\"];\n\nexport function saveSVG(canvas: Canvas, elementRegistry: ElementRegistry): { svg: string } {\n const container = canvas.getContainer();\n const source = container.querySelector(\":scope > svg\");\n if (!source) throw new Error(\"No SVG found in the canvas container.\");\n\n // Content bounds from the team shapes (interactions sit between them).\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const el of elementRegistry.getAll()) {\n if (!isTtElement(el)) continue;\n const s = el as unknown as { x: number; y: number; width: number; height: number };\n minX = Math.min(minX, s.x);\n minY = Math.min(minY, s.y);\n maxX = Math.max(maxX, s.x + s.width);\n maxY = Math.max(maxY, s.y + s.height);\n }\n if (!Number.isFinite(minX)) {\n minX = 0;\n minY = 0;\n maxX = 100;\n maxY = 100;\n }\n\n const x = minX - MARGIN;\n const y = minY - MARGIN;\n const width = maxX - minX + MARGIN * 2;\n const height = maxY - minY + MARGIN * 2;\n\n const clone = source.cloneNode(true) as SVGSVGElement;\n for (const name of CANVAS_ONLY_ATTRIBUTES) clone.removeAttribute(name);\n for (const node of clone.querySelectorAll(INTERACTION_CHROME_SELECTOR)) node.remove();\n for (const node of clone.querySelectorAll(TRANSIENT_CLASSES.map((name) => `.${name}`).join())) {\n node.classList.remove(...TRANSIENT_CLASSES);\n }\n\n clone.setAttribute(\"xmlns\", SVG_NAMESPACE);\n clone.setAttribute(\"viewBox\", `${x} ${y} ${width} ${height}`);\n clone.setAttribute(\"width\", String(Math.round(width)));\n clone.setAttribute(\"height\", String(Math.round(height)));\n\n // Neutralise pan/zoom: let the viewBox (above) drive the geometry.\n const viewport = clone.querySelector<SVGGElement>(\".viewport\");\n if (viewport) viewport.removeAttribute(\"transform\");\n\n const sheet = clone.ownerDocument.createElementNS(SVG_NAMESPACE, \"rect\");\n sheet.setAttribute(\"class\", \"tt-export-paper\");\n sheet.setAttribute(\"x\", String(x));\n sheet.setAttribute(\"y\", String(y));\n sheet.setAttribute(\"width\", String(width));\n sheet.setAttribute(\"height\", String(height));\n sheet.setAttribute(\"fill\", MIRAGON.weiss);\n clone.insertBefore(sheet, clone.firstChild);\n\n const svg = new XMLSerializer().serializeToString(clone);\n return { svg: '<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n' + svg };\n}\n","import { DIAGRAM_ROOT_ID, type ForeignFields } from \"@miragon/team-topologies-schema-model\";\n\n/** ID of the diagram-js root element holding the Team Topologies diagram. */\nexport const ROOT_ID = DIAGRAM_ROOT_ID;\n\nexport interface ImportWarning {\n readonly message: string;\n readonly elementId?: string;\n}\n\n/** Diagram-level metadata stashed on the root element. */\nexport interface RootBusinessObject {\n title: string;\n /** Document fields the modeler does not know, written back on export. */\n foreign?: ForeignFields;\n}\n","/**\n * Shared lifecycle & DI bootstrap for every Team Topologies viewer. Subclasses\n * only override `_getModules()`. The renderer\n * is framework-agnostic — mount it into any element (e.g. a VS Code webview).\n */\n\nimport Diagram from \"diagram-js/lib/Diagram\";\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 CommandStack from \"diagram-js/lib/command/CommandStack\";\nimport type { Root } from \"diagram-js/lib/model/Types\";\nimport { documentIdProblems, type TtDocument } from \"@miragon/team-topologies-schema-model\";\nimport { saveSVG } from \"./io/saveSvg.js\";\nimport type TtImporter from \"./io/TtImporter.js\";\nimport type TtExporter from \"./io/TtExporter.js\";\nimport type TtViewport from \"./io/TtViewport.js\";\nimport { ROOT_ID, type ImportWarning, type RootBusinessObject } from \"./io/types.js\";\nimport type TtLabelEditing from \"./label-editing/TtLabelEditing.js\";\nimport type { Point } from \"./palette/TtPaletteProvider.js\";\n\n/**\n * Set on the canvas SVG while it holds focus that arrived by Tab. Mouse users never see a frame\n * around the whole viewport, which a plain `:focus-visible` ring would show after any shortcut.\n */\nconst CANVAS_KEYBOARD_FOCUS_CLASS = \"tt-canvas-keyboard-focus\";\n\nexport interface TtViewerOptions {\n /** Host element. When absent, a detached <div> is created (attach later). */\n container?: HTMLElement;\n width?: number | string;\n height?: number | string;\n /** Appended to the module list (extension point). */\n additionalModules?: ModuleDeclaration[];\n /**\n * Bind Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z and Cmd/Ctrl+Y to the canvas history (default true). Pass\n * false when the host owns the history (the VS Code document), so the keys reach it.\n */\n undoRedoKeys?: boolean | undefined;\n /**\n * Where Enter or Space on a creating palette entry places the element (guide §5.5): the centre\n * of the part of the canvas no chrome covers, in diagram coordinates. Without it, the centre of\n * the visible canvas.\n */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\nexport interface ImportOptions {\n /** Fit the diagram into view after the import (default true); hosts with own chrome fit it. */\n fit?: boolean | undefined;\n}\n\nexport type EventCallback<T = unknown> = (event: T) => void;\n\ntype RootWithMeta = Root & { businessObject?: RootBusinessObject };\n\nfunction sizeToCss(value: number | string): string {\n return typeof value === \"number\" ? `${value}px` : value;\n}\n\nexport abstract class TtBaseViewer {\n protected abstract _getModules(): ModuleDeclaration[];\n\n private _diagram: Diagram | undefined;\n private readonly _container: HTMLElement;\n private readonly _options: TtViewerOptions;\n\n constructor(options: TtViewerOptions = {}) {\n this._options = options;\n this._container = this._createContainer(options);\n }\n\n private _createContainer(options: TtViewerOptions): HTMLElement {\n const container = options.container ?? document.createElement(\"div\");\n container.classList.add(\"tt-djs-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 ttKeyboard: { undoRedoKeys: this._options.undoRedoKeys ?? true },\n ttPalette: { freeRectCenter: this._options.freeRectCenter },\n });\n this._describeCanvas(this._diagram);\n }\n return this._diagram;\n }\n\n /**\n * Names the canvas. Its role stays the host's to give: the modeler shell makes it an\n * `application`, so screen readers pass the single-key commands through.\n */\n private _describeCanvas(diagram: Diagram): void {\n const canvasContainer = diagram.get<Canvas>(\"canvas\").getContainer();\n const svg = canvasContainer.querySelector<SVGSVGElement>(\":scope > svg\");\n if (!svg) return;\n svg.setAttribute(\"aria-label\", \"Team Topologies diagram\");\n\n const ownerDocument = canvasContainer.ownerDocument;\n let lastKeyWasTab = false;\n const onKeyDown = (event: KeyboardEvent) => {\n lastKeyWasTab = event.key === \"Tab\";\n };\n const onPointerDown = () => {\n lastKeyWasTab = false;\n svg.classList.remove(CANVAS_KEYBOARD_FOCUS_CLASS);\n };\n const onFocusIn = () => svg.classList.toggle(CANVAS_KEYBOARD_FOCUS_CLASS, lastKeyWasTab);\n const onFocusOut = () => svg.classList.remove(CANVAS_KEYBOARD_FOCUS_CLASS);\n ownerDocument.addEventListener(\"keydown\", onKeyDown, true);\n ownerDocument.addEventListener(\"pointerdown\", onPointerDown, true);\n svg.addEventListener(\"focusin\", onFocusIn);\n svg.addEventListener(\"focusout\", onFocusOut);\n diagram.get<EventBus>(\"eventBus\").on(\"diagram.destroy\", () => {\n ownerDocument.removeEventListener(\"keydown\", onKeyDown, true);\n ownerDocument.removeEventListener(\"pointerdown\", onPointerDown, true);\n });\n }\n\n /** Resolve a diagram-js service from the didi injector. */\n get<T>(name: string): T {\n return this._ensureDiagram().get<T>(name);\n }\n\n on<T = unknown>(event: string, callback: EventCallback<T>, priority = 1000): void {\n this.get<EventBus>(\"eventBus\").on(event, priority, callback as EventCallback);\n }\n\n off(event: string, callback: EventCallback): void {\n this.get<EventBus>(\"eventBus\").off(event, callback);\n }\n\n /**\n * Load a document into the canvas (replaces existing content) and, unless `fit: false`, fit it\n * into view. Clears the undo history without a change event: its commands point at the replaced\n * elements and would bring them back, and an import is no edit.\n *\n * Throws, before anything changes, for a document whose ids would collide on the canvas (see\n * `documentIdProblems`), so a rejected document leaves the previous one in place.\n */\n importDocument(doc: TtDocument, options: ImportOptions = {}): { warnings: ImportWarning[] } {\n const problems = documentIdProblems(doc);\n if (problems.length > 0) {\n throw new Error(\n problems.map(({ path, message }) => `${path.join(\".\")}: ${message}`).join(\"; \"),\n );\n }\n const diagram = this._ensureDiagram();\n const eventBus = diagram.get<EventBus>(\"eventBus\");\n const importer = diagram.get<TtImporter>(\"ttImporter\");\n const labelEditing = diagram.get<TtLabelEditing>(\"ttLabelEditing\", false);\n eventBus.fire(\"import.parse.start\", { document: doc });\n labelEditing?.suspend();\n diagram.get<CommandStack>(\"commandStack\", false)?.clear(false);\n importer.clear();\n const warnings = importer.import(doc);\n if (options.fit !== false) this._fit();\n eventBus.fire(\"import.done\", { warnings });\n labelEditing?.resumeAfterImport();\n return { warnings };\n }\n\n /**\n * Fit the whole diagram into the viewport, keeping the strip under the floating palette free\n * (88px at the top, 120px when the container is 760px wide or narrower).\n *\n * @deprecated Host chrome fits the diagram (the modeler shell's viewport, with the insets of the\n * chrome that is open); kept for hosts without it.\n */\n fitToView(): void {\n this._fit();\n }\n\n private _fit(): void {\n const viewport = this._ensureDiagram().get<TtViewport>(\"ttViewport\", false);\n if (viewport) viewport.fit();\n else this.get<Canvas>(\"canvas\").zoom(\"fit-viewport\");\n }\n\n /** Current canvas state as a canonical document. */\n exportDocument(): TtDocument {\n return this.get<TtExporter>(\"ttExporter\").export();\n }\n\n /**\n * Update diagram-level metadata (the title) on the root, outside the undo history.\n *\n * @deprecated Rename through `ttModeling.setTitle(title)`: one undo step that hosts see as a\n * change like any other.\n */\n setMeta(partial: Partial<RootBusinessObject>): void {\n const canvas = this.get<Canvas>(\"canvas\");\n let root: RootWithMeta | undefined;\n try {\n root = canvas.getRootElement() as RootWithMeta;\n } catch {\n return;\n }\n if (!root || root.id !== ROOT_ID) return;\n const current = root.businessObject ?? { title: \"Untitled team topology\" };\n root.businessObject = { ...current, ...partial };\n }\n\n /** Read diagram-level metadata (the title) from the root. */\n getMeta(): RootBusinessObject | undefined {\n try {\n const root = this.get<Canvas>(\"canvas\").getRootElement() as RootWithMeta;\n return root.businessObject;\n } catch {\n return undefined;\n }\n }\n\n /** Standalone, self-contained SVG snapshot. */\n saveSVG(): { svg: string } {\n return saveSVG(this.get<Canvas>(\"canvas\"), this.get<ElementRegistry>(\"elementRegistry\"));\n }\n\n /** Attach the container into `target`. */\n attachTo(target: Element): void {\n target.appendChild(this._container);\n this.get<Canvas>(\"canvas\").resized();\n }\n\n /** Detach the container from the DOM, preserving state. */\n detach(): void {\n this._container.remove();\n }\n\n clear(): void {\n this._ensureDiagram().clear();\n }\n\n destroy(): void {\n if (this._diagram) {\n this._diagram.destroy();\n this._diagram = undefined;\n }\n this._container.remove();\n }\n\n get container(): HTMLElement {\n return this._container;\n }\n}\n","/**\n * Creates diagram-js runtime elements carrying Team Topologies markers, from\n * canonical document elements (import) or from scratch (palette drag-to-create).\n * Teams, interaction glyphs, the flow arrow and annotations are shapes; the\n * annotation connector is the only connection.\n */\n\nimport type ElementFactory from \"diagram-js/lib/core/ElementFactory\";\nimport { getMid } from \"diagram-js/lib/layout/LayoutUtil\";\nimport {\n ANNOTATION_FIELDS,\n ANNOTATION_SPEC,\n FLOW_FIELDS,\n FLOW_SPEC,\n INTERACTION_FIELDS,\n INTERACTION_MODE_SPECS,\n TEAM_NODE_FIELDS,\n TEAM_TYPE_SPECS,\n associationId,\n foreignFields,\n newId,\n} from \"@miragon/team-topologies-schema-model\";\nimport type {\n FlowShape,\n InteractionMode,\n InteractionShape,\n TeamNode,\n TeamType,\n TextAnnotation,\n} from \"@miragon/team-topologies-schema-model\";\nimport type {\n TtAnnotation,\n TtAssociation,\n TtElement,\n TtFlow,\n TtInteraction,\n TtTeam,\n} from \"./di-types.js\";\n\nexport default class TtElementFactory {\n static $inject = [\"elementFactory\"];\n\n constructor(private readonly elementFactory: ElementFactory) {}\n\n /** A field the modeler does not know rides along on the shape, so the export writes it back. */\n private foreign(source: object, knownFields: readonly string[]): { ttForeign?: object } {\n const ttForeign = foreignFields(source, knownFields);\n return ttForeign ? { ttForeign } : {};\n }\n\n // --- from canonical document elements (import) -------------------------\n\n createTeam(node: TeamNode): TtTeam {\n return this.elementFactory.createShape({\n id: node.id,\n x: node.position.x,\n y: node.position.y,\n width: node.size.width,\n height: node.size.height,\n ttKind: \"team\",\n teamType: node.type,\n ttLabel: node.label,\n ...(node.description ? { description: node.description } : {}),\n ...(node.fill ? { fill: node.fill } : {}),\n ...(node.stroke ? { stroke: node.stroke } : {}),\n ...this.foreign(node, TEAM_NODE_FIELDS),\n } as Partial<TtTeam>) as unknown as TtTeam;\n }\n\n createInteraction(shape: InteractionShape): TtInteraction {\n return this.elementFactory.createShape({\n id: shape.id,\n x: shape.position.x,\n y: shape.position.y,\n width: shape.size.width,\n height: shape.size.height,\n ttKind: \"interaction\",\n mode: shape.mode,\n ...(shape.label ? { ttLabel: shape.label } : {}),\n ...(shape.fill ? { fill: shape.fill } : {}),\n ...(shape.stroke ? { stroke: shape.stroke } : {}),\n ...this.foreign(shape, INTERACTION_FIELDS),\n } as Partial<TtInteraction>) as unknown as TtInteraction;\n }\n\n createFlow(shape: FlowShape): TtFlow {\n return this.elementFactory.createShape({\n id: shape.id,\n x: shape.position.x,\n y: shape.position.y,\n width: shape.size.width,\n height: shape.size.height,\n ttKind: \"flow\",\n ...(shape.label ? { ttLabel: shape.label } : {}),\n ...this.foreign(shape, FLOW_FIELDS),\n } as Partial<TtFlow>) as unknown as TtFlow;\n }\n\n createAnnotation(annotation: TextAnnotation): TtAnnotation {\n return this.elementFactory.createShape({\n id: annotation.id,\n x: annotation.position.x,\n y: annotation.position.y,\n width: annotation.size.width,\n height: annotation.size.height,\n ttKind: \"annotation\",\n ...(annotation.text ? { ttLabel: annotation.text } : {}),\n ...this.foreign(annotation, ANNOTATION_FIELDS),\n } as Partial<TtAnnotation>) as unknown as TtAnnotation;\n }\n\n /**\n * The connector of an imported, attached annotation. Its id is derived from\n * the annotation (connectors aren't stored in the document), so re-importing\n * the same document yields the same id.\n */\n createAssociation(annotation: TtAnnotation, target: TtElement): TtAssociation {\n return this.elementFactory.createConnection({\n id: associationId(annotation.id),\n ttKind: \"association\",\n source: annotation,\n target,\n waypoints: [getMid(annotation), getMid(target)],\n } as Partial<TtAssociation>) as unknown as TtAssociation;\n }\n\n // --- fresh, not-yet-placed shapes (palette / context-pad create) -------\n //\n // These set an explicit model-style id (`team_…`/`int_…`/`flow_…`, matching\n // the model package's factory). We must NOT fall back to diagram-js' own\n // auto-id: its counter starts at `shape_12` and is not advanced past ids that\n // come in via import, so a re-imported `shape_N` (an element created in a\n // previous session, then autosaved) collides with the next palette create —\n // the first placement after a reload then throws \"element already exists\".\n\n createNewTeam(type: TeamType, label?: string): TtTeam {\n const spec = TEAM_TYPE_SPECS[type];\n return this.elementFactory.createShape({\n id: newId(\"team\"),\n width: spec.defaultSize.width,\n height: spec.defaultSize.height,\n ttKind: \"team\",\n teamType: type,\n ttLabel: label ?? spec.label,\n } as Partial<TtTeam>) as unknown as TtTeam;\n }\n\n createNewInteraction(mode: InteractionMode): TtInteraction {\n const spec = INTERACTION_MODE_SPECS[mode];\n return this.elementFactory.createShape({\n id: newId(\"int\"),\n width: spec.defaultSize.width,\n height: spec.defaultSize.height,\n ttKind: \"interaction\",\n mode,\n } as Partial<TtInteraction>) as unknown as TtInteraction;\n }\n\n createNewFlow(): TtFlow {\n return this.elementFactory.createShape({\n id: newId(\"flow\"),\n width: FLOW_SPEC.defaultSize.width,\n height: FLOW_SPEC.defaultSize.height,\n ttKind: \"flow\",\n ttLabel: FLOW_SPEC.label,\n } as Partial<TtFlow>) as unknown as TtFlow;\n }\n\n createNewAnnotation(text?: string): TtAnnotation {\n return this.elementFactory.createShape({\n id: newId(\"ann\"),\n width: ANNOTATION_SPEC.defaultSize.width,\n height: ANNOTATION_SPEC.defaultSize.height,\n ttKind: \"annotation\",\n ...(text ? { ttLabel: text } : {}),\n } as Partial<TtAnnotation>) as unknown as TtAnnotation;\n }\n\n /** A not-yet-connected association; modeling sets its ends and waypoints. */\n createNewAssociation(): TtAssociation {\n return this.elementFactory.createConnection({\n id: newId(\"assoc\"),\n ttKind: \"association\",\n } as Partial<TtAssociation>) as unknown as TtAssociation;\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtElementFactory from \"./TtElementFactory.js\";\n\n/** Element factory with Team Topologies defaults. */\nexport const ttModelModule: ModuleDeclaration = {\n ttElementFactory: [\"type\", TtElementFactory],\n};\n\nexport { default as TtElementFactory } from \"./TtElementFactory.js\";\nexport * from \"./di-types.js\";\n","/**\n * Shared rendering constants (typography, accent, priorities) — Miragon corporate identity.\n * Colours are derived from the single source of truth in `theme/palette.ts` (`MIRAGON`), which\n * mirrors the vendored `--cd-*` brand tokens.\n */\n\nimport { MIRAGON } from \"../theme/index.js\";\n\n/** BaseRenderer default priority is 1000; 1500 wins the render.shape/connection event. */\nexport const TT_RENDER_PRIORITY = 1500;\n\nexport const INK = MIRAGON.schwarz;\n/** Secondary canvas text (e.g. the flow-of-change label), ≥ 4.5:1 on the paper surround. */\nexport const INK_MUTED = MIRAGON.textLeise;\n/** Structural strokes that recede (annotation bracket, association connector), ≥ 3:1. */\nexport const STROKE_MUTED = MIRAGON.kontur;\n\nexport const FONT = {\n /**\n * Set directly as the `font-family` attribute on every SVG <text> (canvas\n * labels and therefore the SVG export too) — not inherited from a CSS\n * container. Prefers the self-hosted Miragon typeface Geist (registered as\n * 'Geist Variable' by @fontsource-variable/geist, with 'Geist' as a fallback\n * name), and falls back to a system sans when the host hasn't loaded it (e.g.\n * an exported SVG opened standalone).\n */\n family:\n \"'Geist Variable', 'Geist', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif\",\n label: 13.5,\n small: 11,\n annotation: 12,\n} as const;\n","/**\n * Where and how each element's text is laid out. Shared by the SVG renderer and\n * the inline label editor, so the editor sits exactly on top of the rendered\n * label and uses the same typography.\n */\n\nimport { INTERACTION_MODE_SPECS, TEAM_TYPE_SPECS } from \"@miragon/team-topologies-schema-model\";\nimport {\n isTtAnnotation,\n isTtFlow,\n isTtInteraction,\n type TtElement,\n type TtInteraction,\n type TtTeam,\n} from \"../model/di-types.js\";\nimport { MIRAGON } from \"../theme/index.js\";\nimport { FONT, INK, INK_MUTED } from \"./styles.js\";\n\n/** Horizontal padding between a shape's outline and its centred label. */\nconst LABEL_INSET = 10;\nconst ANNOTATION_PADDING = { left: 10, right: 6, top: 6, bottom: 6 };\nexport const LINE_HEIGHT = 1.2;\n\nexport interface LabelBox {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface LabelLayout {\n /** The area the text is laid out in, relative to the element's top-left corner. */\n box: LabelBox;\n /** `center`: centred both ways (shape labels). `left-top`: flows from the top-left (annotations). */\n align: \"center\" | \"left-top\";\n fontSize: number;\n fontWeight: string;\n letterSpacing?: string;\n fill: string;\n}\n\n/** WCAG AA for body text. */\nconst MIN_TEXT_CONTRAST = 4.5;\n\ntype Rgb = readonly [number, number, number];\n\nfunction parseHexColour(colour: unknown): Rgb | undefined {\n if (typeof colour !== \"string\") return undefined;\n const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(colour.trim());\n if (!match) return undefined;\n const hex =\n match[1].length === 3 ? [...match[1]].map((digit) => digit + digit).join(\"\") : match[1];\n const channel = (offset: number) => parseInt(hex.slice(offset, offset + 2), 16);\n return [channel(0), channel(2), channel(4)];\n}\n\nfunction blendOver(colour: Rgb, backdrop: Rgb, opacity: number): Rgb {\n const mix = (index: 0 | 1 | 2) =>\n Math.round(colour[index] * opacity + backdrop[index] * (1 - opacity));\n return [mix(0), mix(1), mix(2)];\n}\n\nfunction relativeLuminance([red, green, blue]: Rgb): number {\n const linear = (channel: number) => {\n const value = channel / 255;\n return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;\n };\n return 0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue);\n}\n\nfunction contrastRatio(first: Rgb, second: Rgb): number {\n const [lighter, darker] = [relativeLuminance(first), relativeLuminance(second)].sort(\n (a, b) => b - a,\n );\n return (lighter + 0.05) / (darker + 0.05);\n}\n\n/**\n * Label colour for text on a shape filled with `fill` at `opacity` over the white sheet:\n * schwarz while it stays readable (every official notation fill), weiss on dark custom fills.\n */\nexport function readableTextColour(fill: string, opacity = 1): string {\n const fillRgb = parseHexColour(fill);\n const ink = parseHexColour(INK);\n const paper = parseHexColour(MIRAGON.weiss);\n if (!fillRgb || !ink || !paper) return INK;\n const background = blendOver(fillRgb, paper, opacity);\n const inkContrast = contrastRatio(ink, background);\n if (inkContrast >= MIN_TEXT_CONTRAST) return INK;\n return contrastRatio(paper, background) > inkContrast ? MIRAGON.weiss : INK;\n}\n\nfunction shapeTextColour(element: TtTeam | TtInteraction): string {\n if (isTtInteraction(element)) {\n const spec = INTERACTION_MODE_SPECS[element.mode] ?? INTERACTION_MODE_SPECS.collaboration;\n return readableTextColour(element.fill ?? spec.fill, spec.opacity);\n }\n const spec = TEAM_TYPE_SPECS[element.teamType] ?? TEAM_TYPE_SPECS[\"stream-aligned\"];\n return readableTextColour(element.fill ?? spec.fill);\n}\n\n/** Width of the flow arrow's head; the label stays on the shaft. */\nexport function flowHeadWidth(width: number, height: number): number {\n return Math.min(width * 0.16, height * 1.1);\n}\n\nexport function labelLayout(element: TtElement): LabelLayout {\n const width = Math.max(element.width, 1);\n const height = Math.max(element.height, 1);\n\n if (isTtAnnotation(element)) {\n return {\n box: {\n x: ANNOTATION_PADDING.left,\n y: ANNOTATION_PADDING.top,\n width: Math.max(width - ANNOTATION_PADDING.left - ANNOTATION_PADDING.right, 1),\n height: Math.max(height - ANNOTATION_PADDING.top - ANNOTATION_PADDING.bottom, 1),\n },\n align: \"left-top\",\n fontSize: FONT.annotation,\n fontWeight: \"400\",\n fill: INK,\n };\n }\n\n if (isTtFlow(element)) {\n const shaftWidth = width - flowHeadWidth(width, height);\n return {\n box: { x: LABEL_INSET, y: 0, width: shaftWidth - 2 * LABEL_INSET, height },\n align: \"center\",\n fontSize: FONT.small,\n fontWeight: \"600\",\n letterSpacing: \"0.06em\",\n fill: INK_MUTED,\n };\n }\n\n return {\n box: { x: LABEL_INSET, y: 0, width: width - 2 * LABEL_INSET, height },\n align: \"center\",\n fontSize: isTtInteraction(element) ? FONT.small : FONT.label,\n fontWeight: \"600\",\n fill: shapeTextColour(element),\n };\n}\n\n/**\n * Greedy word-wrap into lines that roughly fit `maxWidth` at the font size.\n * Explicit line breaks are kept. Character-count based (not measured), so the\n * result is identical on every platform and exported SVGs stay stable.\n */\nexport function wrapLabel(text: string, maxWidth: number, fontSize: number): string[] {\n const maxChars = Math.max(4, Math.floor(maxWidth / (fontSize * 0.58)));\n const paragraphs = text.split(/\\r?\\n/);\n const lines: string[] = [];\n for (const paragraph of paragraphs) {\n const words = paragraph.split(/\\s+/).filter(Boolean);\n let current = \"\";\n for (const word of words) {\n const candidate = current ? `${current} ${word}` : word;\n if (candidate.length > maxChars && current) {\n lines.push(current);\n current = word;\n } else {\n current = candidate;\n }\n }\n lines.push(current);\n }\n while (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n while (lines.length > 0 && lines[0] === \"\") lines.shift();\n return lines;\n}\n","/**\n * SVG rendering of the Team Topologies notation (BaseRenderer subclass):\n * - teams: SOLID resizable boxes (label wrapped inside), distinguished by shape\n * as well as colour;\n * - interactions: DASHED, 50%-transparent glyphs (collaboration = parallelogram,\n * x-as-a-service = triangle, facilitating = circle) laid over team boundaries;\n * - flow: a dashed \"flow of change\" arrow;\n * - annotations: a BPMN-style open bracket with free text, and the dashed\n * association connecting an annotation to the element it is attached to.\n *\n * Colours/shapes come from the single notation source (`@miragon/team-topologies-schema-model`).\n */\n\nimport BaseRenderer from \"diagram-js/lib/draw/BaseRenderer\";\nimport { append as svgAppend, create as svgCreate, attr as svgAttr } from \"tiny-svg\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type { ConnectionLike, ElementLike, ShapeLike } from \"diagram-js/lib/model/Types\";\nimport {\n FLOW_SPEC,\n INTERACTION_MODE_SPECS,\n TEAM_TYPE_SPECS,\n dashArray,\n} from \"@miragon/team-topologies-schema-model\";\nimport { MIRAGON } from \"../theme/index.js\";\nimport { FONT, STROKE_MUTED, TT_RENDER_PRIORITY } from \"./styles.js\";\nimport {\n LINE_HEIGHT,\n flowHeadWidth,\n labelLayout,\n wrapLabel,\n type LabelLayout,\n} from \"./label-layout.js\";\nimport {\n isTtAnnotation,\n isTtAssociation,\n isTtElement,\n isTtFlow,\n isTtInteraction,\n isTtTeam,\n type TtAnnotation,\n type TtFlow,\n type TtInteraction,\n type TtTeam,\n} from \"../model/di-types.js\";\n\ntype Attrs = Record<string, string | number>;\n\nexport default class TeamTopologiesRenderer extends BaseRenderer {\n static $inject = [\"eventBus\"];\n\n constructor(eventBus: EventBus) {\n super(eventBus, TT_RENDER_PRIORITY);\n }\n\n override canRender(element: ElementLike): boolean {\n return isTtElement(element) || isTtAssociation(element);\n }\n\n override drawShape(visuals: SVGElement, element: ShapeLike): SVGElement {\n if (isTtTeam(element)) return this.drawTeam(visuals, element);\n if (isTtInteraction(element)) return this.drawInteraction(visuals, element);\n if (isTtFlow(element)) return this.drawFlow(visuals, element);\n if (isTtAnnotation(element)) return this.drawAnnotation(visuals, element);\n const rect = svgAttr(svgCreate(\"rect\"), {\n width: element.width,\n height: element.height,\n fill: MIRAGON.linie,\n });\n svgAppend(visuals, rect);\n return rect;\n }\n\n override drawConnection(visuals: SVGElement, connection: ConnectionLike): SVGElement {\n const line = svgAttr(svgCreate(\"path\"), {\n d: waypointsPath(connection.waypoints),\n fill: \"none\",\n stroke: STROKE_MUTED,\n \"stroke-width\": 1.5,\n \"stroke-dasharray\": \"4 4\",\n \"stroke-linecap\": \"round\",\n });\n svgAppend(visuals, line);\n return line;\n }\n\n override getShapePath(shape: ShapeLike): string {\n const { x, y, width, height } = shape;\n return `M${x},${y}l${width},0l0,${height}l${-width},0z`;\n }\n\n override getConnectionPath(connection: ConnectionLike): string {\n return waypointsPath(connection.waypoints);\n }\n\n // --- teams ---------------------------------------------------------------\n\n private drawTeam(visuals: SVGElement, team: TtTeam): SVGElement {\n const spec = TEAM_TYPE_SPECS[team.teamType] ?? TEAM_TYPE_SPECS[\"stream-aligned\"];\n const w = Math.max(team.width, 1);\n const h = Math.max(team.height, 1);\n const sw = spec.strokeWidth;\n const dash = dashArray(spec.strokeStyle, sw);\n const outline = this.teamOutline(spec.shape, w, h, sw, {\n fill: team.fill ?? spec.fill,\n stroke: team.stroke ?? spec.stroke,\n \"stroke-width\": sw,\n ...(dash ? { \"stroke-dasharray\": dash } : {}),\n \"stroke-linejoin\": \"round\",\n });\n svgAppend(visuals, outline);\n this.appendLabel(visuals, team.ttLabel ?? \"\", labelLayout(team));\n return outline;\n }\n\n private teamOutline(kind: string, w: number, h: number, sw: number, attrs: Attrs): SVGElement {\n const i = sw / 2;\n const iw = w - sw;\n const ih = h - sw;\n if (kind === \"octagon\") {\n const c = Math.min(iw, ih) * 0.29;\n return svgAttr(svgCreate(\"polygon\"), { points: octagon(i, iw, ih, c), ...attrs });\n }\n const rx = kind === \"rect\" ? 4 : Math.min(20, ih / 2, iw / 2);\n return svgAttr(svgCreate(\"rect\"), { x: i, y: i, width: iw, height: ih, rx, ry: rx, ...attrs });\n }\n\n // --- interactions --------------------------------------------------------\n\n private drawInteraction(visuals: SVGElement, el: TtInteraction): SVGElement {\n const spec = INTERACTION_MODE_SPECS[el.mode] ?? INTERACTION_MODE_SPECS.collaboration;\n const w = Math.max(el.width, 1);\n const h = Math.max(el.height, 1);\n const sw = 2;\n const i = sw / 2;\n const common: Attrs = {\n fill: el.fill ?? spec.fill,\n \"fill-opacity\": spec.opacity,\n stroke: el.stroke ?? spec.stroke,\n \"stroke-width\": sw,\n \"stroke-dasharray\": dashArray(spec.strokeStyle, sw) || \"6 4\",\n \"stroke-linejoin\": \"round\",\n };\n\n let glyph: SVGElement;\n if (spec.shape === \"circle\") {\n glyph = svgAttr(svgCreate(\"ellipse\"), {\n cx: w / 2,\n cy: h / 2,\n rx: (w - sw) / 2,\n ry: (h - sw) / 2,\n ...common,\n });\n } else if (spec.shape === \"triangle\") {\n // Point up — the tip indicates the direction the service is provided.\n const pts = `${w / 2},${i} ${w - i},${h - i} ${i},${h - i}`;\n glyph = svgAttr(svgCreate(\"polygon\"), { points: pts, ...common });\n } else {\n const skew = Math.min(w * 0.26, h * 0.85);\n const pts = `${i + skew},${i} ${w - i},${i} ${w - i - skew},${h - i} ${i},${h - i}`;\n glyph = svgAttr(svgCreate(\"polygon\"), { points: pts, ...common });\n }\n svgAppend(visuals, glyph);\n this.appendLabel(visuals, el.ttLabel ?? \"\", labelLayout(el));\n return glyph;\n }\n\n // --- flow of change ------------------------------------------------------\n\n private drawFlow(visuals: SVGElement, el: TtFlow): SVGElement {\n const w = Math.max(el.width, 1);\n const h = Math.max(el.height, 1);\n const sw = FLOW_SPEC.strokeWidth;\n const i = sw / 2;\n const head = flowHeadWidth(w, h);\n const shaft = h * 0.5;\n const top = (h - shaft) / 2;\n const bot = top + shaft;\n const pts = [\n [i, top],\n [w - head, top],\n [w - head, i],\n [w - i, h / 2],\n [w - head, h - i],\n [w - head, bot],\n [i, bot],\n ]\n .map((p) => p.join(\",\"))\n .join(\" \");\n const arrow = svgAttr(svgCreate(\"polygon\"), {\n points: pts,\n fill: \"none\",\n stroke: FLOW_SPEC.stroke,\n \"stroke-width\": sw,\n \"stroke-dasharray\": dashArray(FLOW_SPEC.strokeStyle, sw) || \"6 4\",\n \"stroke-linejoin\": \"round\",\n });\n svgAppend(visuals, arrow);\n this.appendLabel(visuals, el.ttLabel ?? \"\", labelLayout(el));\n return arrow;\n }\n\n // --- annotations ---------------------------------------------------------\n\n private drawAnnotation(visuals: SVGElement, el: TtAnnotation): SVGElement {\n const w = Math.max(el.width, 1);\n const h = Math.max(el.height, 1);\n const sw = 1.5;\n const i = sw / 2;\n const arm = Math.min(14, w / 2);\n const bracket = svgAttr(svgCreate(\"path\"), {\n d: `M${arm},${i} L${i},${i} L${i},${h - i} L${arm},${h - i}`,\n fill: \"none\",\n stroke: STROKE_MUTED,\n \"stroke-width\": sw,\n \"stroke-linejoin\": \"round\",\n });\n svgAppend(visuals, bracket);\n this.appendLabel(visuals, el.ttLabel ?? \"\", labelLayout(el));\n return bracket;\n }\n\n // --- shared label rendering (wrapped, no halo) ---------------------------\n\n private appendLabel(visuals: SVGElement, text: string, layout: LabelLayout): void {\n const { box, fontSize } = layout;\n const lines = wrapLabel(text, box.width, fontSize);\n const lineHeight = fontSize * LINE_HEIGHT;\n const centred = layout.align === \"center\";\n const x = centred ? box.x + box.width / 2 : box.x;\n const startY = centred\n ? box.y + box.height / 2 - ((lines.length - 1) * lineHeight) / 2\n : box.y + lineHeight / 2;\n lines.forEach((ln, idx) => {\n if (!ln) return;\n const t = svgAttr(svgCreate(\"text\"), {\n x,\n y: startY + idx * lineHeight,\n \"font-family\": FONT.family,\n \"font-size\": fontSize,\n fill: layout.fill,\n \"text-anchor\": centred ? \"middle\" : \"start\",\n \"dominant-baseline\": \"central\",\n \"font-weight\": layout.fontWeight,\n ...(layout.letterSpacing ? { \"letter-spacing\": layout.letterSpacing } : {}),\n });\n t.textContent = ln;\n svgAppend(visuals, t);\n });\n }\n}\n\n// --- helpers ---------------------------------------------------------------\n\nfunction octagon(i: number, w: number, h: number, c: number): string {\n return [\n [i + c, i],\n [i + w - c, i],\n [i + w, i + c],\n [i + w, i + h - c],\n [i + w - c, i + h],\n [i + c, i + h],\n [i, i + h - c],\n [i, i + c],\n ]\n .map((p) => p.join(\",\"))\n .join(\" \");\n}\n\nfunction waypointsPath(waypoints: ReadonlyArray<{ x: number; y: number }>): string {\n return waypoints.map((point, idx) => `${idx === 0 ? \"M\" : \"L\"}${point.x},${point.y}`).join(\" \");\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport CroppingConnectionDocking from \"diagram-js/lib/layout/CroppingConnectionDocking\";\nimport TeamTopologiesRenderer from \"./TeamTopologiesRenderer.js\";\n\n/**\n * SVG rendering of all Team Topologies element types (BaseRenderer, priority\n * 1500), plus the docking that crops annotation connectors to the outlines of\n * the shapes they join.\n */\nexport const ttDrawModule: ModuleDeclaration = {\n __init__: [\"ttRenderer\"],\n ttRenderer: [\"type\", TeamTopologiesRenderer],\n connectionDocking: [\"type\", CroppingConnectionDocking],\n};\n\nexport { default as TeamTopologiesRenderer } from \"./TeamTopologiesRenderer.js\";\n","/**\n * Bridges the canonical `TtDocument` into the diagram-js canvas. Stacking order\n * (back → front) is flows, teams, interactions, annotations, so the translucent\n * interaction glyphs read on top of the team boxes they overlay. Attached\n * annotations get their association connector last, once both ends exist.\n */\n\nimport 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 ConnectionDocking from \"diagram-js/lib/layout/ConnectionDocking\";\nimport type { Root } from \"diagram-js/lib/model/Types\";\nimport {\n DOCUMENT_FIELDS,\n foreignFields,\n type TtDocument,\n} from \"@miragon/team-topologies-schema-model\";\nimport { isTtAnnotation, isTtElement, type TtAnnotation } from \"../model/di-types.js\";\nimport type TtElementFactory from \"../model/TtElementFactory.js\";\nimport { ROOT_ID, type ImportWarning, type RootBusinessObject } from \"./types.js\";\n\ntype RootWithMeta = Root & { businessObject?: RootBusinessObject };\n\nexport default class TtImporter {\n static $inject = [\n \"canvas\",\n \"elementFactory\",\n \"ttElementFactory\",\n \"eventBus\",\n \"elementRegistry\",\n \"connectionDocking\",\n ];\n\n constructor(\n private readonly canvas: Canvas,\n private readonly elementFactory: ElementFactory,\n private readonly factory: TtElementFactory,\n private readonly eventBus: EventBus,\n private readonly elementRegistry: ElementRegistry,\n private readonly connectionDocking: ConnectionDocking,\n ) {}\n\n import(doc: TtDocument): ImportWarning[] {\n const warnings: ImportWarning[] = [];\n this.eventBus.fire(\"import.render.start\", { document: doc });\n\n let existing: RootWithMeta | undefined;\n try {\n existing = this.canvas.getRootElement() as RootWithMeta;\n } catch {\n existing = undefined;\n }\n let root: RootWithMeta;\n if (existing && existing.id === ROOT_ID) {\n root = existing;\n } else {\n root = this.elementFactory.createRoot({ id: ROOT_ID }) as RootWithMeta;\n this.canvas.setRootElement(root);\n }\n const foreign = foreignFields(doc, DOCUMENT_FIELDS);\n root.businessObject = { title: doc.title, ...(foreign ? { foreign } : {}) };\n\n // Back → front: flows, teams, interactions, annotations.\n for (const flow of doc.flows) {\n this.canvas.addShape(this.factory.createFlow(flow), root);\n }\n for (const node of doc.nodes) {\n this.canvas.addShape(this.factory.createTeam(node), root);\n }\n for (const interaction of doc.interactions) {\n this.canvas.addShape(this.factory.createInteraction(interaction), root);\n }\n for (const annotation of doc.annotations) {\n this.canvas.addShape(this.factory.createAnnotation(annotation), root);\n }\n for (const annotation of doc.annotations) {\n if (!annotation.attachedTo) continue;\n const source = this.elementRegistry.get(annotation.id) as TtAnnotation;\n const target = this.elementRegistry.get(annotation.attachedTo);\n if (!isTtElement(target) || isTtAnnotation(target)) {\n warnings.push({\n message: `Annotation \"${annotation.id}\" is attached to unknown element \"${annotation.attachedTo}\"; its connector was dropped.`,\n elementId: annotation.id,\n });\n continue;\n }\n const association = this.factory.createAssociation(source, target);\n association.waypoints = this.connectionDocking.getCroppedWaypoints(association);\n this.canvas.addConnection(association, root);\n }\n\n this.eventBus.fire(\"import.render.done\", { warnings });\n return warnings;\n }\n\n /**\n * Removes every element (for re-import). Roots stay: besides the diagram's own root, diagram-js\n * creates an implicit one when something asks for a root before the first import.\n */\n clear(): void {\n const elements = this.elementRegistry.getAll().filter((el) => Boolean(el.parent));\n const connections = elements.filter((el) => \"waypoints\" in el);\n const shapes = elements.filter((el) => !(\"waypoints\" in el));\n for (const connection of connections) this.canvas.removeConnection(connection.id);\n for (const shape of shapes) {\n try {\n this.canvas.removeShape(shape.id);\n } catch {\n // already removed — ignore\n }\n }\n }\n}\n","/**\n * Rebuilds a canonical `TtDocument` from the diagram-js runtime model. Position\n * and size truth are the live `x/y/width/height`; editable fields (label, type,\n * mode, colours) are read from the runtime properties. An annotation's\n * `attachedTo` comes from its association connection.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type ElementRegistry from \"diagram-js/lib/core/ElementRegistry\";\nimport type { Root } from \"diagram-js/lib/model/Types\";\nimport {\n ANNOTATION_FIELDS,\n DOCUMENT_FIELDS,\n DOCUMENT_VERSION,\n FLOW_FIELDS,\n INTERACTION_FIELDS,\n TEAM_NODE_FIELDS,\n withForeignFields,\n} from \"@miragon/team-topologies-schema-model\";\nimport type {\n FlowShape,\n InteractionShape,\n TeamNode,\n TextAnnotation,\n TtDocument,\n} from \"@miragon/team-topologies-schema-model\";\nimport {\n isTtAnnotation,\n isTtAssociation,\n isTtFlow,\n isTtInteraction,\n isTtTeam,\n type TtAnnotation,\n} from \"../model/di-types.js\";\nimport { ROOT_ID, type RootBusinessObject } from \"./types.js\";\n\nexport default class TtExporter {\n static $inject = [\"elementRegistry\", \"canvas\"];\n\n constructor(\n private readonly elementRegistry: ElementRegistry,\n private readonly canvas: Canvas,\n ) {}\n\n export(): TtDocument {\n let meta: RootBusinessObject | undefined;\n try {\n const root = this.canvas.getRootElement() as Root & {\n businessObject?: RootBusinessObject;\n };\n meta = root.businessObject;\n } catch {\n meta = undefined;\n }\n\n const nodes: TeamNode[] = [];\n const interactions: InteractionShape[] = [];\n const flows: FlowShape[] = [];\n const annotations: TextAnnotation[] = [];\n\n for (const el of this.elementRegistry.getAll()) {\n if (el.id === ROOT_ID) continue;\n const geom = el as unknown as { x: number; y: number; width: number; height: number };\n const position = { x: geom.x, y: geom.y };\n const size = { width: geom.width, height: geom.height };\n\n if (isTtTeam(el)) {\n nodes.push(\n withForeignFields(\n {\n id: el.id,\n type: el.teamType,\n label: el.ttLabel ?? \"\",\n position,\n size,\n ...(el.description ? { description: el.description } : {}),\n ...(el.fill ? { fill: el.fill } : {}),\n ...(el.stroke ? { stroke: el.stroke } : {}),\n },\n el.ttForeign,\n TEAM_NODE_FIELDS,\n ),\n );\n } else if (isTtInteraction(el)) {\n interactions.push(\n withForeignFields(\n {\n id: el.id,\n mode: el.mode,\n position,\n size,\n ...(el.ttLabel ? { label: el.ttLabel } : {}),\n ...(el.fill ? { fill: el.fill } : {}),\n ...(el.stroke ? { stroke: el.stroke } : {}),\n },\n el.ttForeign,\n INTERACTION_FIELDS,\n ),\n );\n } else if (isTtFlow(el)) {\n flows.push(\n withForeignFields(\n {\n id: el.id,\n position,\n size,\n ...(el.ttLabel ? { label: el.ttLabel } : {}),\n },\n el.ttForeign,\n FLOW_FIELDS,\n ),\n );\n } else if (isTtAnnotation(el)) {\n const attachedTo = attachedElementId(el);\n annotations.push(\n withForeignFields(\n {\n id: el.id,\n text: el.ttLabel ?? \"\",\n position,\n size,\n ...(attachedTo ? { attachedTo } : {}),\n },\n el.ttForeign,\n ANNOTATION_FIELDS,\n ),\n );\n }\n }\n\n return withForeignFields(\n {\n version: DOCUMENT_VERSION,\n title: meta?.title ?? \"Untitled team topology\",\n nodes,\n interactions,\n flows,\n annotations,\n },\n meta?.foreign,\n DOCUMENT_FIELDS,\n );\n }\n}\n\nfunction attachedElementId(annotation: TtAnnotation): string | undefined {\n const connections = [...annotation.outgoing, ...annotation.incoming];\n const association = connections.find(isTtAssociation);\n if (!association) return undefined;\n const other = association.source === annotation ? association.target : association.source;\n return other?.id;\n}\n","/**\n * Fits the diagram into the visible canvas. Unlike diagram-js `fit-viewport`, it keeps the\n * strip under the floating palette free, so no element starts hidden behind it.\n *\n * @deprecated Host chrome fits the diagram (the modeler shell's viewport, with the insets of the\n * chrome that is open and never above 100 %); kept for hosts without it.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type ElementRegistry from \"diagram-js/lib/core/ElementRegistry\";\n\n/** Up to this container width the palette sits on its own row below the host's top chrome. */\nconst NARROW_LAYOUT_MAX_WIDTH = 760;\n\nconst TOP_INSET = 88;\nconst TOP_INSET_NARROW = 120;\nconst PADDING = 56;\nconst SIDE_PADDING_NARROW = 24;\n/** Guide §5.9: a fit never zooms past 100 %, as the shell's fit does. */\nconst MAX_FIT_ZOOM = 1;\n\ninterface Bounds {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n}\n\nexport default class TtViewport {\n static $inject = [\"canvas\", \"elementRegistry\"];\n\n constructor(\n private readonly canvas: Canvas,\n private readonly elementRegistry: ElementRegistry,\n ) {}\n\n /** Fit every element into view, zooming in no further than 100 %. */\n fit(): void {\n const bounds = this.contentBounds();\n if (!bounds) return;\n\n const rect = this.canvas.getContainer().getBoundingClientRect();\n const viewportWidth = rect.width;\n const viewportHeight = rect.height;\n if (!viewportWidth || !viewportHeight) {\n this.canvas.zoom(\"fit-viewport\");\n return;\n }\n\n const narrow = viewportWidth <= NARROW_LAYOUT_MAX_WIDTH;\n const topInset = narrow ? TOP_INSET_NARROW : TOP_INSET;\n const sidePadding = narrow ? SIDE_PADDING_NARROW : PADDING;\n const contentWidth = Math.max(bounds.maxX - bounds.minX, 1);\n const contentHeight = Math.max(bounds.maxY - bounds.minY, 1);\n const scale = Math.min(\n (viewportWidth - 2 * sidePadding) / contentWidth,\n (viewportHeight - topInset - PADDING) / contentHeight,\n MAX_FIT_ZOOM,\n );\n if (!(scale > 0)) {\n this.canvas.zoom(\"fit-viewport\");\n return;\n }\n this.canvas.viewbox({\n x: bounds.minX + contentWidth / 2 - viewportWidth / 2 / scale,\n y: this.viewboxTop(bounds, contentHeight, scale, viewportHeight, topInset, narrow),\n width: viewportWidth / scale,\n height: viewportHeight / scale,\n });\n }\n\n /**\n * On a narrow (portrait) canvas the content is centred in the free band below the palette: the\n * band is tall, and a diagram pinned to its top would slide under the top chrome on the first\n * zoom step around the viewport centre. Wider hosts keep it at the top, because their lower left\n * corner tends to hold an overlay of their own, such as a legend.\n */\n private viewboxTop(\n bounds: Bounds,\n contentHeight: number,\n scale: number,\n viewportHeight: number,\n topInset: number,\n narrow: boolean,\n ): number {\n if (!narrow) return bounds.minY - topInset / scale;\n const freeHeight = viewportHeight - topInset - PADDING;\n const slack = Math.max(0, freeHeight - contentHeight * scale);\n return bounds.minY - (topInset + slack / 2) / scale;\n }\n\n private contentBounds(): Bounds | undefined {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const element of this.elementRegistry.getAll()) {\n const shape = element as { x?: unknown; y?: unknown; width?: unknown; height?: unknown };\n if (\n typeof shape.x !== \"number\" ||\n typeof shape.y !== \"number\" ||\n typeof shape.width !== \"number\" ||\n typeof shape.height !== \"number\"\n ) {\n continue;\n }\n minX = Math.min(minX, shape.x);\n minY = Math.min(minY, shape.y);\n maxX = Math.max(maxX, shape.x + shape.width);\n maxY = Math.max(maxY, shape.y + shape.height);\n }\n return Number.isFinite(minX) ? { minX, minY, maxX, maxY } : undefined;\n }\n}\n","/**\n * Geist inside an exported SVG. An SVG drawn as an image (the usual way to rasterise it into a PNG)\n * is an isolated document: it can't use the host page's @font-face rules, so its labels would fall\n * back to a system font. The host passes the font files as data URLs, because it owns them (for\n * example from `@fontsource-variable/geist`); the library ships no font.\n */\n\nconst SVG_NAMESPACE = \"http://www.w3.org/2000/svg\";\n\n/** The latin subsets of `@fontsource-variable/geist`, with the unicode ranges it publishes. */\nexport const GEIST_UNICODE_RANGES = {\n latin:\n \"U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD\",\n latinExt:\n \"U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF\",\n} as const;\n\n/** A `data:` URL of each latin Geist variable-weight WOFF2 file. */\nexport type GeistFontDataUrls = Record<keyof typeof GEIST_UNICODE_RANGES, string>;\n\n/** @font-face rules for the family the canvas labels ask for ('Geist Variable'). */\nexport function geistFontFaceCss(fonts: GeistFontDataUrls): string {\n return (Object.keys(GEIST_UNICODE_RANGES) as (keyof GeistFontDataUrls)[])\n .map((subset) => {\n const dataUrl = fonts[subset].replace(/^data:[^;,]*/, \"data:font/woff2\");\n return (\n `@font-face{font-family:'Geist Variable';font-style:normal;font-weight:100 900;` +\n `font-display:block;src:url(${dataUrl}) format('woff2');` +\n `unicode-range:${GEIST_UNICODE_RANGES[subset]};}`\n );\n })\n .join(\"\");\n}\n\n/** Puts `css` into a <style> at the top of a standalone SVG; returns the SVG unchanged if unparsable. */\nexport function embedSvgStyles(svg: string, css: string): string {\n const parsed = new DOMParser().parseFromString(svg, \"image/svg+xml\");\n const root = parsed.documentElement;\n if (root.namespaceURI !== SVG_NAMESPACE || parsed.querySelector(\"parsererror\")) return svg;\n const defs = parsed.createElementNS(SVG_NAMESPACE, \"defs\");\n const style = parsed.createElementNS(SVG_NAMESPACE, \"style\");\n style.textContent = css;\n defs.appendChild(style);\n root.insertBefore(defs, root.firstChild);\n return new XMLSerializer().serializeToString(parsed);\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtImporter from \"./TtImporter.js\";\nimport TtExporter from \"./TtExporter.js\";\nimport TtViewport from \"./TtViewport.js\";\n\n/** Document <-> diagram-js bridge (import / export) and the palette-aware fit. */\nexport const ioModule: ModuleDeclaration = {\n ttImporter: [\"type\", TtImporter],\n ttExporter: [\"type\", TtExporter],\n ttViewport: [\"type\", TtViewport],\n};\n\nexport { default as TtImporter } from \"./TtImporter.js\";\nexport { default as TtExporter } from \"./TtExporter.js\";\nexport { default as TtViewport } from \"./TtViewport.js\";\nexport { saveSVG } from \"./saveSvg.js\";\nexport { GEIST_UNICODE_RANGES, embedSvgStyles, geistFontFaceCss } from \"./fontEmbedding.js\";\nexport type { GeistFontDataUrls } from \"./fontEmbedding.js\";\nexport { ROOT_ID } from \"./types.js\";\nexport type { ImportWarning, RootBusinessObject } from \"./types.js\";\n","import type { ModuleDeclaration } from \"didi\";\nimport { TtBaseViewer } from \"./TtBaseViewer.js\";\nimport { ttModelModule } from \"./model/index.js\";\nimport { ttDrawModule } from \"./draw/index.js\";\nimport { ioModule } from \"./io/index.js\";\n\n/** Read-only renderer: draws a Team Topologies diagram with no interaction. */\nexport class Viewer extends TtBaseViewer {\n protected _getModules(): ModuleDeclaration[] {\n return [ttModelModule, ttDrawModule, 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/** Read-only + navigation: zoom (scroll), pan (drag), selection. */\nexport class NavigatedViewer extends Viewer {\n protected override _getModules(): ModuleDeclaration[] {\n return [...super._getModules(), SelectionModule, ZoomScrollModule, MoveCanvasModule];\n }\n}\n","/**\n * Generic, undo-able command that sets arbitrary Team Topologies properties\n * (ttLabel, teamType, mode, fill, stroke, description). Returns the changed\n * element so the CommandStack fires `elements.changed` → re-render.\n */\n\nimport type { ElementLike } from \"diagram-js/lib/core/Types\";\nimport type CommandHandler from \"diagram-js/lib/command/CommandHandler\";\n\nexport interface UpdatePropertiesContext {\n element: ElementLike & Record<string, unknown>;\n properties: Record<string, unknown>;\n /** set internally by the handler (for revert). */\n oldProperties?: Record<string, unknown>;\n}\n\nfunction setOrDelete(obj: Record<string, unknown>, key: string, value: unknown): void {\n if (value === undefined) delete obj[key];\n else obj[key] = value;\n}\n\nexport default class UpdatePropertiesHandler implements CommandHandler {\n execute(context: UpdatePropertiesContext): ElementLike[] {\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): ElementLike[] {\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)) setOrDelete(target, key, oldProperties[key]);\n }\n return [element];\n }\n}\n","/**\n * Renames the diagram as one undoable command. The title lives on the root element, so a host that\n * listens to the command stack sees the rename like any other change, and undo reverts it.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type CommandHandler from \"diagram-js/lib/command/CommandHandler\";\nimport type { ElementLike } from \"diagram-js/lib/core/Types\";\nimport type { Root } from \"diagram-js/lib/model/Types\";\nimport type { RootBusinessObject } from \"../../io/types.js\";\n\ntype RootWithMeta = Root & { businessObject?: RootBusinessObject };\n\nexport interface UpdateTitleContext {\n title: string;\n /** set internally by the handler (for revert). */\n oldTitle?: string;\n}\n\nconst UNTITLED = \"Untitled team topology\";\n\nexport default class UpdateTitleHandler implements CommandHandler {\n static $inject = [\"canvas\"];\n\n constructor(private readonly canvas: Canvas) {}\n\n execute(context: UpdateTitleContext): ElementLike[] {\n const root = this.canvas.getRootElement() as RootWithMeta;\n const current = root.businessObject ?? { title: UNTITLED };\n context.oldTitle = current.title;\n root.businessObject = { ...current, title: context.title };\n return [root];\n }\n\n revert(context: UpdateTitleContext): ElementLike[] {\n const root = this.canvas.getRootElement() as RootWithMeta;\n const current = root.businessObject ?? { title: UNTITLED };\n root.businessObject = { ...current, title: context.oldTitle ?? UNTITLED };\n return [root];\n }\n}\n","/**\n * High-level Team Topologies mutations that go through the command stack\n * (undo/redo). Registers the generic property command handler.\n */\n\nimport type CommandStack from \"diagram-js/lib/command/CommandStack\";\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type { Element, Root } from \"diagram-js/lib/model/Types\";\nimport type { InteractionMode, TeamType } from \"@miragon/team-topologies-schema-model\";\nimport {\n isTtAssociation,\n type TtAnnotation,\n type TtElement,\n type TtInteraction,\n type TtTeam,\n} from \"../model/di-types.js\";\nimport type TtElementFactory from \"../model/TtElementFactory.js\";\nimport UpdatePropertiesHandler from \"./cmd/UpdatePropertiesHandler.js\";\nimport UpdateTitleHandler from \"./cmd/UpdateTitleHandler.js\";\n\nconst UPDATE_PROPERTIES = \"element.updateProperties\";\nconst UPDATE_TITLE = \"tt.title.update\";\n\n/** Gap between an element and an annotation appended to it. */\nconst ANNOTATION_GAP = 40;\n\nexport default class TtModeling {\n static $inject = [\"commandStack\", \"modeling\", \"ttElementFactory\", \"canvas\"];\n\n constructor(\n private readonly commandStack: CommandStack,\n private readonly modeling: Modeling,\n private readonly factory: TtElementFactory,\n private readonly canvas: Canvas,\n ) {\n commandStack.registerHandler(UPDATE_PROPERTIES, UpdatePropertiesHandler);\n commandStack.registerHandler(UPDATE_TITLE, UpdateTitleHandler);\n }\n\n /** Renames the diagram, as one undo step. */\n setTitle(title: string): void {\n this.commandStack.execute(UPDATE_TITLE, { title });\n }\n\n updateProperties(element: TtElement, properties: Record<string, unknown>): void {\n this.commandStack.execute(UPDATE_PROPERTIES, { element, properties });\n }\n\n /** Rename / relabel any element. */\n updateLabel(element: TtElement, label: string): void {\n this.updateProperties(element, { ttLabel: label || undefined });\n }\n\n setTeamType(team: TtTeam, teamType: TeamType): void {\n this.updateProperties(team, { teamType });\n }\n\n setInteractionMode(interaction: TtInteraction, mode: InteractionMode): void {\n this.updateProperties(interaction, { mode });\n }\n\n /** Set or clear per-element colour overrides (`undefined` reverts to default). */\n setColors(\n element: TtTeam | TtInteraction,\n fill: string | undefined,\n stroke: string | undefined,\n ): void {\n this.updateProperties(element, { fill, stroke });\n }\n\n setDescription(team: TtTeam, description: string | undefined): void {\n this.updateProperties(team, { description });\n }\n\n /** Places a new annotation to the upper right of `element`, attached to it, as one undo step. */\n appendAnnotation(element: TtElement): TtAnnotation {\n const annotation = this.factory.createNewAnnotation();\n const position = {\n x: element.x + element.width + ANNOTATION_GAP + annotation.width / 2,\n y: element.y - ANNOTATION_GAP / 4,\n };\n return this.modeling.appendShape(\n element as Element,\n annotation as Element,\n position,\n this.canvas.getRootElement() as Root,\n { connection: this.factory.createNewAssociation(), connectionTarget: element },\n ) as unknown as TtAnnotation;\n }\n\n /** Removes the annotation's connector; the annotation itself stays. */\n detachAnnotation(annotation: TtAnnotation): void {\n const associations = [...annotation.incoming, ...annotation.outgoing].filter(isTtAssociation);\n if (associations.length > 0) this.modeling.removeElements(associations);\n }\n}\n","/**\n * Lays every annotation connector out as a straight line between the centres of\n * the annotation and its element (the association behaviour then crops it to\n * both outlines). The anchor hints from move / resize / connect are ignored on\n * purpose, so the connector never drifts off-centre.\n */\n\nimport BaseLayouter, { type LayoutConnectionHints } from \"diagram-js/lib/layout/BaseLayouter\";\nimport { getMid } from \"diagram-js/lib/layout/LayoutUtil\";\nimport type { Connection } from \"diagram-js/lib/model/Types\";\nimport type { Point } from \"diagram-js/lib/util/Types\";\n\nexport default class TtLayouter extends BaseLayouter {\n override layoutConnection(connection: Connection, hints: LayoutConnectionHints = {}): Point[] {\n const source = hints.source ?? connection.source;\n const target = hints.target ?? connection.target;\n if (!source || !target) return super.layoutConnection(connection, hints);\n return [getMid(source), getMid(target)];\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport ModelingModule from \"diagram-js/lib/features/modeling\";\nimport TtModeling from \"./TtModeling.js\";\nimport TtLayouter from \"./TtLayouter.js\";\n\n/**\n * High-level Team Topologies mutations + registration of the command handlers.\n * Depends on the diagram-js modeling module so our `layouter` replaces its\n * default one.\n */\nexport const ttModelingModule: ModuleDeclaration = {\n __depends__: [ModelingModule],\n __init__: [\"ttModeling\"],\n ttModeling: [\"type\", TtModeling],\n layouter: [\"type\", TtLayouter],\n};\n\nexport { default as TtModeling } from \"./TtModeling.js\";\nexport { default as TtLayouter } from \"./TtLayouter.js\";\n","/**\n * Allowed editing operations. Every Team Topologies element is a free, placed\n * shape — movable, creatable and resizable. The only connection is an\n * annotation's connector to a team, interaction or flow (the official notation\n * models interactions as overlapping shapes, not lines).\n */\n\nimport RuleProvider from \"diagram-js/lib/features/rules/RuleProvider\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport { isTtAnnotation, isTtElement } from \"../model/di-types.js\";\n\ninterface MoveContext {\n target?: { parent?: unknown } | null;\n}\n\ninterface ConnectContext {\n source?: unknown;\n target?: unknown;\n}\n\nfunction isAttachable(element: unknown): boolean {\n return isTtElement(element) && !isTtAnnotation(element);\n}\n\nexport default class TtRules extends RuleProvider {\n static override $inject = [\"eventBus\"];\n\n constructor(eventBus: EventBus) {\n super(eventBus);\n }\n\n override init(): void {\n this.addRule([\"shape.move\", \"elements.move\"], (context: MoveContext) =>\n context.target && context.target.parent ? null : true,\n );\n this.addRule(\"shape.create\", () => true);\n this.addRule(\"shape.resize\", () => true);\n this.addRule(\"element.copy\", () => true);\n this.addRule(\"connection.create\", ({ source, target }: ConnectContext) =>\n (isTtAnnotation(source) && isAttachable(target)) ||\n (isTtAnnotation(target) && isAttachable(source))\n ? { ttKind: \"association\" }\n : false,\n );\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport RulesModule from \"diagram-js/lib/features/rules\";\nimport TtRules from \"./TtRules.js\";\n\n/** Team Topologies editing rules (connect, move, create, resize). */\nexport const ttRulesModule: ModuleDeclaration = {\n __depends__: [RulesModule],\n __init__: [\"ttRules\"],\n ttRules: [\"type\", TtRules],\n};\n\nexport { default as TtRules } from \"./TtRules.js\";\n","/**\n * Keeps the diagram flat: Team Topologies shapes overlap but never nest.\n *\n * diagram-js parents a newly created shape to whatever element it is dropped on\n * (`context.parent` defaults to the drop target). Interaction glyphs are meant\n * to be placed *over* the teams they relate to, so the natural workflow would\n * otherwise nest the interaction inside a team — gluing it so it moves along\n * with the team. Force every created shape onto the diagram root instead.\n *\n * Re-parenting on *move* is prevented separately in TtRules.\n */\n\nimport CommandInterceptor from \"diagram-js/lib/command/CommandInterceptor\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\n\nexport default class TtFlatModelBehavior extends CommandInterceptor {\n static override $inject = [\"eventBus\", \"canvas\"];\n\n constructor(eventBus: EventBus, canvas: Canvas) {\n super(eventBus);\n\n this.preExecute(\n [\"shape.create\", \"elements.create\"],\n (context: { parent?: unknown }) => {\n context.parent = canvas.getRootElement();\n },\n true,\n );\n }\n}\n","/**\n * Keeps annotation connectors tidy while editing:\n * - crops every laid-out connector to the outlines of the two shapes it joins\n * (the layouter only knows their centres);\n * - an annotation is attached to at most one element (the document stores a\n * single `attachedTo`), so connecting it again replaces the old connector.\n */\n\nimport 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 ConnectionDocking from \"diagram-js/lib/layout/ConnectionDocking\";\nimport type { Connection } from \"diagram-js/lib/model/Types\";\nimport { isTtAnnotation, isTtAssociation } from \"../model/di-types.js\";\n\ninterface ConnectionContext {\n connection: Connection;\n cropped?: boolean;\n}\n\nexport default class TtAssociationBehavior extends CommandInterceptor {\n static override $inject = [\"eventBus\", \"connectionDocking\", \"modeling\"];\n\n constructor(eventBus: EventBus, connectionDocking: ConnectionDocking, modeling: Modeling) {\n super(eventBus);\n\n this.executed(\n [\"connection.layout\", \"connection.create\"],\n (context: ConnectionContext) => {\n if (context.cropped || !isTtAssociation(context.connection)) return;\n context.connection.waypoints = connectionDocking.getCroppedWaypoints(context.connection);\n context.cropped = true;\n },\n true,\n );\n\n this.reverted(\n \"connection.layout\",\n (context: ConnectionContext) => {\n delete context.cropped;\n },\n true,\n );\n\n this.postExecuted(\n \"connection.create\",\n (context: ConnectionContext) => {\n const connection = context.connection;\n if (!isTtAssociation(connection)) return;\n const annotation = isTtAnnotation(connection.source)\n ? connection.source\n : connection.target;\n if (!isTtAnnotation(annotation)) return;\n const previous = [...annotation.incoming, ...annotation.outgoing].filter(\n (other) => other !== connection && isTtAssociation(other),\n );\n if (previous.length > 0) modeling.removeElements(previous);\n },\n true,\n );\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtFlatModelBehavior from \"./TtFlatModelBehavior.js\";\nimport TtAssociationBehavior from \"./TtAssociationBehavior.js\";\n\n/**\n * Editing behaviors that keep the Team Topologies model flat (no nesting) and\n * annotation connectors cropped and one per annotation.\n */\nexport const ttBehaviorsModule: ModuleDeclaration = {\n __init__: [\"ttFlatModelBehavior\", \"ttAssociationBehavior\"],\n ttFlatModelBehavior: [\"type\", TtFlatModelBehavior],\n ttAssociationBehavior: [\"type\", TtAssociationBehavior],\n};\n\nexport { default as TtFlatModelBehavior } from \"./TtFlatModelBehavior.js\";\nexport { default as TtAssociationBehavior } from \"./TtAssociationBehavior.js\";\n","/**\n * Functional icons for the canvas chrome (context pad, palette tools), returned as inline SVG\n * markup.\n *\n * Lucide icons (ISC licence, © Lucide Icons and Contributors), copied unchanged from\n * lucide-static 1.59.0 and inlined so the published renderer has no icon runtime dependency.\n */\n\n/** One Lucide icon: its SVG child elements on the 24 × 24 grid. */\nexport type IconNode = ReadonlyArray<readonly [string, Readonly<Record<string, string>>]>;\n\nexport interface IconMarkupOptions {\n /** Rendered width and height in px; the viewBox stays on the 24 × 24 grid. */\n size?: number;\n strokeWidth?: number;\n className?: string;\n}\n\nexport const ICON_PENCIL: IconNode = [\n [\n \"path\",\n {\n d: \"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z\",\n },\n ],\n [\"path\", { d: \"m15 5 4 4\" }],\n];\n\nexport const ICON_TRASH: IconNode = [\n [\"path\", { d: \"M10 11v6\" }],\n [\"path\", { d: \"M14 11v6\" }],\n [\"path\", { d: \"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6\" }],\n [\"path\", { d: \"M3 6h18\" }],\n [\"path\", { d: \"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\" }],\n];\n\nexport const ICON_LINK: IconNode = [\n [\"path\", { d: \"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71\" }],\n [\"path\", { d: \"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71\" }],\n];\n\nexport const ICON_MESSAGE_SQUARE_PLUS: IconNode = [\n [\n \"path\",\n {\n d: \"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z\",\n },\n ],\n [\"path\", { d: \"M12 8v6\" }],\n [\"path\", { d: \"M9 11h6\" }],\n];\n\nexport const ICON_SQUARE_DASHED_MOUSE_POINTER: IconNode = [\n [\n \"path\",\n {\n 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 },\n ],\n [\"path\", { d: \"M5 3a2 2 0 0 0-2 2\" }],\n [\"path\", { d: \"M19 3a2 2 0 0 1 2 2\" }],\n [\"path\", { d: \"M5 21a2 2 0 0 1-2-2\" }],\n [\"path\", { d: \"M9 3h1\" }],\n [\"path\", { d: \"M9 21h2\" }],\n [\"path\", { d: \"M14 3h1\" }],\n [\"path\", { d: \"M3 9v1\" }],\n [\"path\", { d: \"M21 9v2\" }],\n [\"path\", { d: \"M3 14v1\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_MENU: IconNode = [\n [\"path\", { d: \"M4 5h16\" }],\n [\"path\", { d: \"M4 12h16\" }],\n [\"path\", { d: \"M4 19h16\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_MINUS: IconNode = [[\"path\", { d: \"M5 12h14\" }]];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_PLUS: IconNode = [\n [\"path\", { d: \"M5 12h14\" }],\n [\"path\", { d: \"M12 5v14\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_MAXIMIZE: IconNode = [\n [\"path\", { d: \"M8 3H5a2 2 0 0 0-2 2v3\" }],\n [\"path\", { d: \"M21 8V5a2 2 0 0 0-2-2h-3\" }],\n [\"path\", { d: \"M3 16v3a2 2 0 0 0 2 2h3\" }],\n [\"path\", { d: \"M16 21h3a2 2 0 0 0 2-2v-3\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_DOWNLOAD: IconNode = [\n [\"path\", { d: \"M12 15V3\" }],\n [\"path\", { d: \"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" }],\n [\"path\", { d: \"m7 10 5 5 5-5\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_X: IconNode = [\n [\"path\", { d: \"M18 6 6 18\" }],\n [\"path\", { d: \"m6 6 12 12\" }],\n];\n\nconst ICON_STROKE_WIDTH = 2.5;\nconst ICON_SIZE = 16;\n\n/**\n * The SVG elements and attributes Lucide icon nodes are made of. The markup is assigned to\n * innerHTML by hosts, so anything else a caller passes in (a <script>, an onload) is dropped.\n */\nconst SVG_ELEMENTS = [\"path\", \"circle\", \"ellipse\", \"line\", \"polyline\", \"polygon\", \"rect\"] as const;\nconst SVG_ATTRIBUTES = [\n \"d\",\n \"cx\",\n \"cy\",\n \"r\",\n \"rx\",\n \"ry\",\n \"x\",\n \"y\",\n \"x1\",\n \"y1\",\n \"x2\",\n \"y2\",\n \"width\",\n \"height\",\n \"points\",\n] as const;\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction positiveNumberOr(value: unknown, fallback: number): number {\n const number = Number(value);\n return Number.isFinite(number) && number > 0 ? number : fallback;\n}\n\n/** Decorative (`aria-hidden`) inline SVG for a Lucide icon; the control around it carries the name. */\nexport function iconMarkup(icon: IconNode, options: IconMarkupOptions = {}): string {\n const size = positiveNumberOr(options.size, ICON_SIZE);\n const strokeWidth = positiveNumberOr(options.strokeWidth, ICON_STROKE_WIDTH);\n const classAttribute = options.className ? ` class=\"${escapeAttribute(options.className)}\"` : \"\";\n const children = icon\n .map(([tag, attributes]) => {\n const element = SVG_ELEMENTS.find((allowed) => allowed === tag);\n if (!element) return \"\";\n const attributeList = Object.entries(attributes)\n .flatMap(([name, value]) => {\n const attribute = SVG_ATTRIBUTES.find((allowed) => allowed === name);\n return attribute ? [`${attribute}=\"${escapeAttribute(String(value))}\"`] : [];\n })\n .join(\" \");\n return `<${element} ${attributeList}/>`;\n })\n .join(\"\");\n return (\n `<svg${classAttribute} xmlns=\"http://www.w3.org/2000/svg\" width=\"${size}\" height=\"${size}\" viewBox=\"0 0 24 24\"` +\n ` fill=\"none\" stroke=\"currentColor\" stroke-width=\"${strokeWidth}\" stroke-linecap=\"round\"` +\n ` stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">${children}</svg>`\n );\n}\n","/**\n * Tiny inline-SVG glyphs for the palette entries — the same shapes the canvas\n * draws (so the palette is a faithful preview of each team type / interaction\n * mode). Returned as HTML strings for diagram-js palette `html`.\n */\n\nimport {\n FLOW_SPEC,\n INTERACTION_MODE_SPECS,\n TEAM_TYPE_SPECS,\n dashArray,\n} from \"@miragon/team-topologies-schema-model\";\nimport type { InteractionMode, TeamType } from \"@miragon/team-topologies-schema-model\";\nimport { ICON_SQUARE_DASHED_MOUSE_POINTER, iconMarkup } from \"./icons.js\";\n\n/**\n * The lasso is a tool, not notation: a Lucide icon at the guide's tool size (§5.14, 20px with a\n * stroke of 2, which renders as heavy as the 16px chrome icons).\n */\nconst PALETTE_TOOL_ICON = { size: 20, strokeWidth: 2 } as const;\n\nfunction svg(inner: string): string {\n return `<svg class=\"tt-palette-svg\" width=\"24\" height=\"24\" viewBox=\"0 0 26 26\" aria-hidden=\"true\">${inner}</svg>`;\n}\n\nexport function teamIconSvg(type: TeamType): string {\n const s = TEAM_TYPE_SPECS[type];\n const dash = dashArray(s.strokeStyle, 1.5);\n const common =\n `fill=\"${s.fill}\" stroke=\"${s.stroke}\" stroke-width=\"1.5\"` +\n (dash ? ` stroke-dasharray=\"${dash}\"` : \"\");\n switch (s.shape) {\n case \"octagon\":\n return svg(`<polygon points=\"8,3 18,3 23,8 23,18 18,23 8,23 3,18 3,8\" ${common}/>`);\n case \"rounded-rect-vertical\":\n return svg(`<rect x=\"8\" y=\"3\" width=\"10\" height=\"20\" rx=\"4\" ${common}/>`);\n case \"rect\":\n return svg(`<rect x=\"3\" y=\"7\" width=\"20\" height=\"12\" rx=\"1.5\" ${common}/>`);\n default:\n return svg(`<rect x=\"3\" y=\"8\" width=\"20\" height=\"10\" rx=\"5\" ${common}/>`);\n }\n}\n\nexport function flowIconSvg(): string {\n const dash = dashArray(FLOW_SPEC.strokeStyle, 1.5);\n return svg(\n `<g fill=\"none\" stroke=\"${FLOW_SPEC.stroke}\" stroke-width=\"1.5\" stroke-linejoin=\"round\"` +\n (dash ? ` stroke-dasharray=\"${dash}\"` : \"\") +\n `><polygon points=\"3,9 16,9 16,5 23,13 16,21 16,17 3,17\"/></g>`,\n );\n}\n\nexport function annotationIconSvg(): string {\n return svg(\n `<g fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\">` +\n `<path d=\"M10 4H5v18h5\"/><path d=\"M13 9h9M13 13h9M13 17h6\"/></g>`,\n );\n}\n\n/** The lasso (multi-select) tool: Lucide square-dashed-mouse-pointer. */\nexport function lassoIconSvg(): string {\n return iconMarkup(ICON_SQUARE_DASHED_MOUSE_POINTER, {\n ...PALETTE_TOOL_ICON,\n className: \"tt-palette-svg\",\n });\n}\n\nexport function interactionIconSvg(mode: InteractionMode): string {\n const s = INTERACTION_MODE_SPECS[mode];\n const dash = dashArray(s.strokeStyle, 1.5);\n const common =\n `fill=\"${s.fill}\" fill-opacity=\"${s.opacity}\" stroke=\"${s.stroke}\" stroke-width=\"1.5\"` +\n (dash ? ` stroke-dasharray=\"${dash}\"` : \"\");\n switch (s.shape) {\n case \"circle\":\n return svg(`<circle cx=\"13\" cy=\"13\" r=\"9\" ${common}/>`);\n case \"triangle\":\n return svg(`<polygon points=\"5,6 22,13 5,20\" ${common}/>`);\n default:\n return svg(`<polygon points=\"9,6 23,6 17,20 3,20\" ${common}/>`);\n }\n}\n","/**\n * The tool palette: the lasso (multi-select) tool, then drag-to-create entries for the four team\n * types, the three interaction-mode glyphs (placed over team boundaries), the flow-of-change arrow\n * and the text annotation.\n *\n * A host's chrome (the modeler shell) lays the palette out, gives it its toolbar semantics and\n * triggers an entry from the keyboard with a click whose `detail` is 0. Such a click on a creating\n * entry places the element in the centre of the free part of the canvas (guide §5.5), 24px further\n * diagonally while that spot is taken, selects it and opens its label editor: diagram-js's create\n * tool follows the pointer and never ends without one.\n */\n\nimport 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 Create from \"diagram-js/lib/features/create/Create\";\nimport type LassoTool from \"diagram-js/lib/features/lasso-tool/LassoTool\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type Selection from \"diagram-js/lib/features/selection/Selection\";\nimport type {\n PaletteEntries,\n PaletteEntry,\n default as PaletteProvider,\n} from \"diagram-js/lib/features/palette/PaletteProvider\";\nimport type { Root, Shape } from \"diagram-js/lib/model/Types\";\nimport type { Injector } from \"didi\";\nimport {\n ALL_INTERACTION_SPECS,\n ALL_TEAM_SPECS,\n ANNOTATION_SPEC,\n FLOW_SPEC,\n} from \"@miragon/team-topologies-schema-model\";\nimport {\n annotationIconSvg,\n flowIconSvg,\n interactionIconSvg,\n lassoIconSvg,\n teamIconSvg,\n} from \"../draw/palette-icons.js\";\nimport type { TtLabelEditing } from \"../label-editing/index.js\";\nimport { isTtElement, type TtElement } from \"../model/di-types.js\";\nimport type TtElementFactory from \"../model/TtElementFactory.js\";\nimport type { TtReadOnly } from \"../read-only/index.js\";\n\n/** diagram-js highlights the active tool only inside a group named exactly `tools`. */\nconst GROUP_TOOLS = \"tools\";\nconst GROUP_TEAMS = \"tt-1-teams\";\nconst GROUP_MODES = \"tt-2-modes\";\nconst GROUP_GUIDES = \"tt-3-guides\";\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\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface TtPaletteConfig {\n /**\n * The centre of the part of the canvas no chrome covers, in diagram coordinates (the modeler\n * shell's `viewport.freeRectCenter()`). Without it, the centre of the visible canvas.\n */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\nfunction entryHtml(icon: string, draggable = true): string {\n return `<div class=\"entry tt-palette-entry\" draggable=\"${draggable}\">${icon}</div>`;\n}\n\n/** A click the chrome synthesises for Enter or Space on a palette entry (no pointer, detail 0). */\nfunction isKeyboardClick(event: Event): boolean {\n return event.type === \"click\" && (event as MouseEvent).detail === 0;\n}\n\nfunction centreOf(element: TtElement): Point {\n return { x: element.x + element.width / 2, y: element.y + element.height / 2 };\n}\n\nexport default class TtPaletteProvider implements PaletteProvider {\n static $inject = [\n \"config.ttPalette\",\n \"palette\",\n \"create\",\n \"ttElementFactory\",\n \"lassoTool\",\n \"canvas\",\n \"modeling\",\n \"selection\",\n \"elementRegistry\",\n \"injector\",\n ];\n\n private readonly readOnly: TtReadOnly | undefined;\n private readonly labelEditing: TtLabelEditing | undefined;\n\n constructor(\n private readonly config: TtPaletteConfig | undefined,\n palette: Palette,\n private readonly create: Create,\n private readonly factory: TtElementFactory,\n private readonly lassoTool: LassoTool,\n private readonly canvas: Canvas,\n private readonly modeling: Modeling,\n private readonly selection: Selection,\n private readonly elementRegistry: ElementRegistry,\n injector: Injector,\n ) {\n this.readOnly = injector.get<TtReadOnly>(\"ttReadOnly\", false);\n this.labelEditing = injector.get<TtLabelEditing>(\"ttLabelEditing\", false);\n palette.registerProvider(this);\n }\n\n getPaletteEntries(): PaletteEntries {\n const entries: PaletteEntries = {};\n\n entries[\"lasso-tool\"] = {\n group: GROUP_TOOLS,\n title: \"Select several elements\",\n html: entryHtml(lassoIconSvg(), false),\n action: {\n click: (event: Event) => this.lassoTool.activateSelection(event as MouseEvent),\n },\n };\n\n for (const spec of ALL_TEAM_SPECS) {\n entries[`team.${spec.type}`] = this.createEntry(\n GROUP_TEAMS,\n `${spec.label} team`,\n teamIconSvg(spec.type),\n () => this.factory.createNewTeam(spec.type, spec.label) as unknown as Shape,\n );\n }\n\n for (const spec of ALL_INTERACTION_SPECS) {\n entries[`mode.${spec.mode}`] = this.createEntry(\n GROUP_MODES,\n `${spec.label} interaction`,\n interactionIconSvg(spec.mode),\n () => this.factory.createNewInteraction(spec.mode) as unknown as Shape,\n );\n }\n\n entries[\"flow\"] = this.createEntry(\n GROUP_GUIDES,\n FLOW_SPEC.label,\n flowIconSvg(),\n () => this.factory.createNewFlow() as unknown as Shape,\n );\n\n entries[\"annotation\"] = this.createEntry(\n GROUP_GUIDES,\n ANNOTATION_SPEC.label,\n annotationIconSvg(),\n () => this.factory.createNewAnnotation() as unknown as Shape,\n );\n\n return entries;\n }\n\n private createEntry(\n group: string,\n title: string,\n icon: string,\n newShape: () => Shape,\n ): PaletteEntry {\n const start = (event: Event) => {\n if (isKeyboardClick(event)) this.placeInFreeRect(newShape());\n else this.create.start(event as MouseEvent, newShape());\n };\n return {\n group,\n title,\n html: entryHtml(icon),\n action: { dragstart: start, click: start },\n };\n }\n\n /** The centre of the free rectangle, stepped diagonally past elements already centred there. */\n private freePlace(): Point {\n const viewbox = this.canvas.viewbox();\n const centre = this.config?.freeRectCenter?.() ?? {\n x: viewbox.x + viewbox.width / 2,\n y: viewbox.y + viewbox.height / 2,\n };\n const place = { x: Math.round(centre.x), y: Math.round(centre.y) };\n const taken = () =>\n this.elementRegistry.filter(isTtElement).some((element) => {\n const elementCentre = centreOf(element as unknown as TtElement);\n return Math.abs(elementCentre.x - place.x) < 1 && Math.abs(elementCentre.y - place.y) < 1;\n });\n while (taken()) {\n place.x += KEYBOARD_CREATE_OFFSET;\n place.y += KEYBOARD_CREATE_OFFSET;\n }\n return place;\n }\n\n private placeInFreeRect(shape: Shape): void {\n if (this.readOnly?.isReadOnly()) return;\n const created = this.modeling.createShape(\n shape,\n this.freePlace(),\n this.canvas.getRootElement() as Root,\n );\n this.selection.select(created);\n this.canvas.focus();\n if (isTtElement(created)) this.labelEditing?.activate(created);\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport PaletteModule from \"diagram-js/lib/features/palette\";\nimport CreateModule from \"diagram-js/lib/features/create\";\nimport LassoToolModule from \"diagram-js/lib/features/lasso-tool\";\nimport TtPaletteProvider from \"./TtPaletteProvider.js\";\n\n/** Tool palette (lasso, drag-to-create teams, interactions, flows and annotations). */\nexport const ttPaletteModule: ModuleDeclaration = {\n __depends__: [PaletteModule, CreateModule, LassoToolModule],\n __init__: [\"ttPaletteProvider\"],\n ttPaletteProvider: [\"type\", TtPaletteProvider],\n};\n\nexport { default as TtPaletteProvider } from \"./TtPaletteProvider.js\";\n","/**\n * Locks every edit on the canvas while the document behind it cannot be saved from the canvas (an\n * invalid file in an IDE host, guide §13.5): otherwise a change on the canvas would overwrite the\n * text the user is fixing. The rules veto move, resize, create, connect and delete; the keyboard,\n * the context pad and the label editor ask `isReadOnly()`, because rules alone do not stop a\n * context pad from opening or a double-click from opening the label editor. Selection, zoom, pan,\n * copy and export stay.\n */\n\nimport RuleProvider from \"diagram-js/lib/features/rules/RuleProvider\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\n\n/** Fired with `{ readOnly }` whenever the lock changes. */\nexport const READ_ONLY_CHANGED_EVENT = \"tt.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];\n\nexport default class TtReadOnly extends RuleProvider {\n static override $inject = [\"eventBus\"];\n\n private readOnly = false;\n\n constructor(private readonly bus: EventBus) {\n super(bus);\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) return;\n this.readOnly = readOnly;\n this.bus.fire(READ_ONLY_CHANGED_EVENT, { readOnly });\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport RulesModule from \"diagram-js/lib/features/rules\";\nimport TtReadOnly from \"./TtReadOnly.js\";\n\n/** The canvas edit lock (an invalid file in an IDE host). */\nexport const ttReadOnlyModule: ModuleDeclaration = {\n __depends__: [RulesModule],\n __init__: [\"ttReadOnly\"],\n ttReadOnly: [\"type\", TtReadOnly],\n};\n\nexport { default as TtReadOnly, READ_ONLY_CHANGED_EVENT } from \"./TtReadOnly.js\";\n","/**\n * Context-pad actions. Teams, interactions and flows: rename, add an attached\n * annotation, delete. Annotations: edit text, connect to an element, delete. An\n * annotation connector: delete. A multi-selection: delete all.\n *\n * Entries are focusable buttons; Enter or Space runs their keyboard action.\n * Connecting has none, because it is a pointer gesture that needs a drop target,\n * so Tab skips it. \"Add annotation\" on the element attaches one by keyboard.\n *\n * Every entry changes the diagram, so under the read-only lock there is no context pad at all.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type ContextPad from \"diagram-js/lib/features/context-pad/ContextPad\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type Connect from \"diagram-js/lib/features/connect/Connect\";\nimport type Selection from \"diagram-js/lib/features/selection/Selection\";\nimport type {\n ContextPadEntries,\n ContextPadEntry,\n default as ContextPadProvider,\n} from \"diagram-js/lib/features/context-pad/ContextPadProvider\";\nimport type { Element } from \"diagram-js/lib/model/Types\";\nimport {\n isTtAnnotation,\n isTtAssociation,\n isTtElement,\n isTtFlow,\n isTtInteraction,\n type TtElement,\n} from \"../model/di-types.js\";\nimport type TtLabelEditing from \"../label-editing/TtLabelEditing.js\";\nimport type TtModeling from \"../modeling/TtModeling.js\";\nimport { READ_ONLY_CHANGED_EVENT, type TtReadOnly } from \"../read-only/index.js\";\nimport {\n ICON_LINK,\n ICON_MESSAGE_SQUARE_PLUS,\n ICON_PENCIL,\n ICON_TRASH,\n iconMarkup,\n type IconNode,\n} from \"../draw/icons.js\";\n\nconst ENTRY_SELECTOR = \".djs-context-pad .entry[data-action]\";\n\nfunction cpHtml(icon: IconNode, title: string, focusable = true): string {\n return `<div class=\"entry tt-cp-entry\" role=\"button\" tabindex=\"${focusable ? 0 : -1}\" aria-label=\"${title}\">${iconMarkup(icon)}</div>`;\n}\n\nfunction editTitle(element: TtElement): string {\n if (isTtAnnotation(element)) return \"Edit text\";\n if (isTtInteraction(element) || isTtFlow(element)) return \"Edit label\";\n return \"Rename\";\n}\n\nexport default class TtContextPadProvider implements ContextPadProvider {\n static $inject = [\n \"contextPad\",\n \"modeling\",\n \"ttModeling\",\n \"ttLabelEditing\",\n \"connect\",\n \"selection\",\n \"canvas\",\n \"eventBus\",\n \"injector\",\n ];\n\n private readonly readOnly: TtReadOnly | null;\n\n constructor(\n private readonly contextPad: ContextPad,\n private readonly modeling: Modeling,\n private readonly ttModeling: TtModeling,\n private readonly labelEditing: TtLabelEditing,\n private readonly connect: Connect,\n private readonly selection: Selection,\n private readonly canvas: Canvas,\n eventBus: EventBus,\n injector: { get<T>(name: string, strict?: boolean): T | null },\n ) {\n this.readOnly = injector.get<TtReadOnly>(\"ttReadOnly\", false);\n contextPad.registerProvider(this);\n eventBus.on(\"contextPad.open.allowed\", () => (this.readOnly?.isReadOnly() ? false : undefined));\n eventBus.on(READ_ONLY_CHANGED_EVENT, (event: { readOnly?: boolean }) => {\n if (event.readOnly) contextPad.close();\n });\n canvas\n .getContainer()\n .addEventListener(\"keydown\", (keyboardEvent) => this.onEntryKeyDown(keyboardEvent));\n }\n\n getContextPadEntries(element: Element): ContextPadEntries {\n if (this.readOnly?.isReadOnly()) return {};\n if (isTtAssociation(element))\n return { delete: this.deleteEntry([element], \"Delete connector\") };\n if (!isTtElement(element)) return {};\n\n if (isTtAnnotation(element)) {\n const startConnect = (event: Event) => this.connect.start(event as MouseEvent, element);\n return {\n \"edit-label\": this.editEntry(element),\n connect: {\n group: \"edit\",\n title: \"Attach to element\",\n html: cpHtml(ICON_LINK, \"Attach to element\", false),\n action: { click: startConnect, dragstart: startConnect },\n },\n delete: this.deleteEntry([element], \"Delete\"),\n };\n }\n\n const appendAnnotation = () => {\n const annotation = this.ttModeling.appendAnnotation(element);\n this.selection.select(annotation as unknown as Element);\n this.labelEditing.activate(annotation);\n };\n return {\n \"edit-label\": this.editEntry(element),\n \"append-annotation\": {\n group: \"edit\",\n title: \"Add annotation\",\n html: cpHtml(ICON_MESSAGE_SQUARE_PLUS, \"Add annotation\"),\n action: { click: appendAnnotation, keyboard: appendAnnotation },\n },\n delete: this.deleteEntry([element], \"Delete\"),\n };\n }\n\n getMultiElementContextPadEntries(elements: Element[]): ContextPadEntries {\n if (this.readOnly?.isReadOnly()) return {};\n return { delete: this.deleteEntry(elements, `Delete ${elements.length} elements`) };\n }\n\n private onEntryKeyDown(event: KeyboardEvent): void {\n if ((event.key !== \"Enter\" && event.key !== \" \") || event.repeat) return;\n const entry = (event.target as HTMLElement | null)?.closest?.(ENTRY_SELECTOR);\n const action = entry?.getAttribute(\"data-action\");\n if (!action) return;\n event.preventDefault();\n event.stopPropagation();\n this.contextPad.triggerEntry(action, \"keyboard\", event);\n }\n\n private editEntry(element: TtElement): ContextPadEntry {\n const title = editTitle(element);\n const activate = () => this.labelEditing.activate(element);\n return {\n group: \"edit\",\n title,\n html: cpHtml(ICON_PENCIL, title),\n action: { click: activate, keyboard: activate },\n };\n }\n\n private deleteEntry(elements: Element[], title: string): ContextPadEntry {\n return {\n group: \"edit\",\n title,\n html: cpHtml(ICON_TRASH, title),\n action: {\n click: () => this.modeling.removeElements([...elements]),\n keyboard: () => {\n this.modeling.removeElements([...elements]);\n this.canvas.focus();\n },\n },\n };\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport ConnectModule from \"diagram-js/lib/features/connect\";\nimport ConnectionPreviewModule from \"diagram-js/lib/features/connection-preview\";\nimport ContextPadModule from \"diagram-js/lib/features/context-pad\";\nimport TtContextPadProvider from \"./TtContextPadProvider.js\";\n\n/** Per-element context actions (rename, annotate, attach, delete). */\nexport const ttContextPadModule: ModuleDeclaration = {\n __depends__: [ContextPadModule, ConnectModule, ConnectionPreviewModule],\n __init__: [\"ttContextPadProvider\"],\n ttContextPadProvider: [\"type\", TtContextPadProvider],\n};\n\nexport { default as TtContextPadProvider } from \"./TtContextPadProvider.js\";\n","/**\n * In-place label editing: a borderless, transparent <textarea> laid exactly over\n * the element's label area, in the label's own font, size, alignment and\n * wrapping, scaled with the zoom. The rendered label is hidden meanwhile, so the\n * text never shows twice. Enter (or clicking elsewhere) commits through\n * `ttModeling.updateLabel` — one undo step; Shift+Enter inserts a line break;\n * Escape discards. Double-click any element to edit its label.\n *\n * An import replaces every element, so an edit open while one runs is taken down without a commit\n * and reopened, with what was typed, on the element with the same id (hosts re-import remote\n * states while the user types). Under the read-only lock no editor opens.\n */\n\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 {\n isTtAnnotation,\n isTtElement,\n isTtFlow,\n isTtInteraction,\n type TtElement,\n} from \"../model/di-types.js\";\nimport type TtModeling from \"../modeling/TtModeling.js\";\nimport { READ_ONLY_CHANGED_EVENT, type TtReadOnly } from \"../read-only/index.js\";\nimport { LINE_HEIGHT, labelLayout } from \"../draw/label-layout.js\";\nimport { FONT } from \"../draw/styles.js\";\n\n/** Canvas marker that hides the rendered label while its editor is open. */\nconst EDITING_MARKER = \"tt-label-editing\";\n\n/** Narrow shapes (small interaction glyphs) still get an editor wide enough to type in. */\nconst MIN_EDITOR_WIDTH = 96;\n\nfunction editorName(element: TtElement): string {\n if (isTtAnnotation(element)) return \"Annotation text\";\n if (isTtInteraction(element)) return \"Interaction label\";\n if (isTtFlow(element)) return \"Flow label\";\n return \"Team name\";\n}\n\ninterface ActiveEdit {\n commit: () => void;\n cleanup: () => void;\n /** The element and what was typed so far, to reopen the edit after an import. */\n snapshot: () => SuspendedEdit;\n}\n\ninterface SuspendedEdit {\n elementId: string;\n value: string;\n selectionStart: number;\n selectionEnd: number;\n}\n\nexport default class TtLabelEditing {\n static $inject = [\"eventBus\", \"canvas\", \"ttModeling\", \"elementRegistry\", \"injector\"];\n\n private active: ActiveEdit | null = null;\n private suspended: SuspendedEdit | null = null;\n private resumeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly readOnly: TtReadOnly | null;\n\n constructor(\n eventBus: EventBus,\n private readonly canvas: Canvas,\n private readonly modeling: TtModeling,\n private readonly elementRegistry: ElementRegistry,\n injector: { get<T>(name: string, strict?: boolean): T | null },\n ) {\n this.readOnly = injector.get<TtReadOnly>(\"ttReadOnly\", false);\n eventBus.on(\"element.dblclick\", (event: { element?: unknown }) => {\n if (isTtElement(event.element)) this.activate(event.element);\n });\n // Any click/drag/pan outside the editor commits (only Escape discards).\n eventBus.on([\"element.mousedown\", \"drag.init\", \"canvas.viewbox.changing\"], () =>\n this.active?.commit(),\n );\n // An import that bypasses suspend() still must not apply a pending edit to a removed element.\n eventBus.on(\"import.render.start\", () => this.cancel());\n eventBus.on(READ_ONLY_CHANGED_EVENT, (event: { readOnly?: boolean }) => {\n if (event.readOnly) this.cancel();\n });\n // Before the canvas tears down: a field still open would blur, commit onto the destroyed\n // diagram and queue a focus on it.\n eventBus.on(\"diagram.destroy\", () => {\n clearTimeout(this.resumeTimer);\n this.suspended = null;\n this.cancel();\n });\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 go, so a commit would land on a removed shape. `resumeAfterImport` brings\n * the editor back with the typed text.\n */\n suspend(): void {\n clearTimeout(this.resumeTimer);\n if (!this.active) return;\n this.suspended = this.active.snapshot();\n this.active.cleanup();\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, after the host restored its viewbox around the import (a\n * viewbox change commits an open editor).\n */\n resumeAfterImport(): void {\n clearTimeout(this.resumeTimer);\n if (!this.suspended) return;\n this.resumeTimer = setTimeout(() => {\n const edit = this.suspended;\n this.suspended = null;\n if (!edit || this.active) return;\n const element = this.elementRegistry.get(edit.elementId);\n if (!isTtElement(element)) return;\n this.activate(element, edit);\n }, 0);\n }\n\n /** The edit open right now (its element and the uncommitted text), for hosts and tests. */\n openEdit(): { elementId: string; value: string } | undefined {\n if (!this.active) return undefined;\n const { elementId, value } = this.active.snapshot();\n return { elementId, value };\n }\n\n activate(element: TtElement, resumed?: SuspendedEdit): void {\n this.active?.commit();\n if (this.readOnly?.isReadOnly()) return;\n\n const layout = labelLayout(element);\n const centred = layout.align === \"center\";\n const scale = this.canvas.zoom();\n const viewbox = this.canvas.viewbox();\n\n const width = centred ? Math.max(layout.box.width, MIN_EDITOR_WIDTH) : layout.box.width;\n const left = element.x + layout.box.x + (layout.box.width - width) / 2;\n const top = (element.y + layout.box.y - viewbox.y) * scale;\n const boxHeight = layout.box.height * scale;\n\n const editor = document.createElement(\"textarea\");\n editor.className = \"tt-label-editor\";\n editor.value = resumed ? resumed.value : (element.ttLabel ?? \"\");\n editor.rows = 1;\n editor.setAttribute(\"aria-label\", editorName(element));\n Object.assign(editor.style, {\n left: `${(left - viewbox.x) * scale}px`,\n width: `${width * scale}px`,\n fontFamily: FONT.family,\n fontSize: `${layout.fontSize * scale}px`,\n fontWeight: layout.fontWeight,\n letterSpacing: layout.letterSpacing ?? \"normal\",\n lineHeight: String(LINE_HEIGHT),\n color: layout.fill,\n textAlign: centred ? \"center\" : \"left\",\n });\n\n // Grow with the text; centred labels stay vertically centred like the rendered ones.\n const fitToContent = () => {\n editor.style.height = \"0px\";\n const contentHeight = editor.scrollHeight;\n editor.style.height = `${centred ? contentHeight : Math.max(contentHeight, boxHeight)}px`;\n editor.style.top = `${centred ? top + (boxHeight - contentHeight) / 2 : top}px`;\n };\n\n this.canvas.getContainer().appendChild(editor);\n this.canvas.addMarker(element, EDITING_MARKER);\n fitToContent();\n editor.focus();\n if (resumed) editor.setSelectionRange(resumed.selectionStart, resumed.selectionEnd);\n else editor.select();\n\n let done = false;\n const cleanup = () => {\n if (done) return;\n done = true;\n editor.removeEventListener(\"keydown\", onKey);\n editor.removeEventListener(\"input\", fitToContent);\n editor.removeEventListener(\"blur\", onBlur);\n editor.remove();\n if (this.elementRegistry.get(element.id) === element) {\n this.canvas.removeMarker(element, EDITING_MARKER);\n }\n this.active = null;\n // Removing the focused field drops the focus to the page; the canvas takes it back.\n this.canvas.restoreFocus();\n };\n const commit = () => {\n if (done) return;\n const value = editor.value.trim();\n const changed = value !== (element.ttLabel ?? \"\");\n cleanup();\n if (changed) this.modeling.updateLabel(element, value);\n };\n // Removing the focused editor would drop focus to the page; keep keyboard users on the canvas.\n const onKey = (e: KeyboardEvent) => {\n if (e.key === \"Enter\" && !e.shiftKey && !e.isComposing) {\n e.preventDefault();\n commit();\n this.canvas.focus();\n } else if (e.key === \"Escape\") {\n e.preventDefault();\n cleanup();\n this.canvas.focus();\n }\n };\n const onBlur = () => commit();\n editor.addEventListener(\"keydown\", onKey);\n editor.addEventListener(\"input\", fitToContent);\n editor.addEventListener(\"blur\", onBlur);\n\n const snapshot = (): SuspendedEdit => ({\n elementId: element.id,\n value: editor.value,\n selectionStart: editor.selectionStart,\n selectionEnd: editor.selectionEnd,\n });\n this.active = { commit, cleanup, snapshot };\n }\n\n cancel(): void {\n this.active?.cleanup();\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtLabelEditing from \"./TtLabelEditing.js\";\n\n/** In-place label editing (double-click any element to edit its label or text). */\nexport const ttLabelEditingModule: ModuleDeclaration = {\n __init__: [\"ttLabelEditing\"],\n ttLabelEditing: [\"type\", TtLabelEditing],\n};\n\nexport { default as TtLabelEditing } from \"./TtLabelEditing.js\";\n","/**\n * Keyboard shortcuts of the canvas: undo / redo / select all / delete-selection / copy / paste /\n * nudge the selection with the arrow keys / clear the selection (Escape).\n *\n * Bound to the document so they work right after a click on the canvas, but they only act when the\n * key press targets the page itself or the canvas (diagram-js focuses its SVG on mouse-down). Key\n * presses in host chrome, open dialogs, form fields and the inline label editor stay with those\n * controls, a key a closer listener already handled (`defaultPrevented`) is left alone, and an\n * `inert` canvas takes no keys at all.\n *\n * Zoom and fit keys are the host chrome's (guide §5.8: only Cmd/Ctrl + `+` `-` `0` and Shift+1,\n * each acting exactly once), so the canvas binds none. A host that owns the history (the VS Code\n * document) turns the undo and redo keys off with `undoRedoKeys: false`, so they reach it.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type ElementRegistry from \"diagram-js/lib/core/ElementRegistry\";\nimport type CommandStack from \"diagram-js/lib/command/CommandStack\";\nimport type Selection from \"diagram-js/lib/features/selection/Selection\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type CopyPaste from \"diagram-js/lib/features/copy-paste/CopyPaste\";\nimport type Dragging from \"diagram-js/lib/features/dragging/Dragging\";\nimport type Rules from \"diagram-js/lib/features/rules/Rules\";\nimport type { Injector } from \"didi\";\nimport type { Element, Shape } from \"diagram-js/lib/model/Types\";\nimport type TtReadOnly from \"../read-only/TtReadOnly.js\";\n\nconst NUDGE_STEP = 1;\nconst NUDGE_STEP_FAST = 10;\n\nconst ARROW_DIRECTIONS: Record<string, { x: number; y: number }> = {\n ArrowLeft: { x: -1, y: 0 },\n ArrowRight: { x: 1, y: 0 },\n ArrowUp: { x: 0, y: -1 },\n ArrowDown: { x: 0, y: 1 },\n};\n\nconst MODAL_SELECTOR = '[aria-modal=\"true\"], dialog[open]';\n\nexport interface TtKeyboardConfig {\n /**\n * Bind Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z and Cmd/Ctrl+Y to the canvas command stack (default true).\n * A host that owns the history (the VS Code document) passes false so the keys reach it.\n */\n undoRedoKeys?: boolean | undefined;\n}\n\nfunction isTypingTarget(target: EventTarget | null): boolean {\n const el = target as HTMLElement | null;\n if (!el) return false;\n return (\n el.tagName === \"INPUT\" ||\n el.tagName === \"TEXTAREA\" ||\n el.tagName === \"SELECT\" ||\n el.isContentEditable\n );\n}\n\nfunction isNode(target: EventTarget | null): target is Node {\n return typeof (target as Node | null)?.nodeType === \"number\";\n}\n\nfunction isCanvasScope(target: EventTarget | null, canvasContainer: HTMLElement): boolean {\n // A host marks the canvas inert while something else fronts it, e.g. a start screen.\n if (canvasContainer.closest(\"[inert]\")) return false;\n if (!isNode(target)) return true;\n if (target.nodeType === Node.DOCUMENT_NODE) return true;\n const ownerDocument = target.ownerDocument;\n if (target === ownerDocument?.body || target === ownerDocument?.documentElement) return true;\n return canvasContainer.contains(target);\n}\n\nfunction isShape(element: Element): element is Shape {\n return !(\"waypoints\" in element);\n}\n\nexport default class TtKeyboard {\n static $inject = [\n \"config.ttKeyboard\",\n \"eventBus\",\n \"canvas\",\n \"elementRegistry\",\n \"commandStack\",\n \"selection\",\n \"modeling\",\n \"copyPaste\",\n \"rules\",\n \"injector\",\n ];\n\n constructor(\n config: TtKeyboardConfig | undefined,\n eventBus: EventBus,\n canvas: Canvas,\n elementRegistry: ElementRegistry,\n commandStack: CommandStack,\n selection: Selection,\n modeling: Modeling,\n copyPaste: CopyPaste,\n rules: Rules,\n injector: Injector,\n ) {\n const container = canvas.getContainer();\n const doc = container.ownerDocument ?? document;\n const undoRedoKeys = config?.undoRedoKeys ?? true;\n const dragging = injector.get<Dragging>(\"dragging\", false);\n const readOnly = injector.get<TtReadOnly>(\"ttReadOnly\", false);\n\n /** Keys that only read the diagram; they stay under the read-only lock. */\n const handleReadingKey = (e: KeyboardEvent, cmd: boolean, key: string): boolean => {\n if (cmd && key === \"a\" && !e.shiftKey) {\n e.preventDefault();\n selection.select(elementRegistry.filter((element) => Boolean(element.parent)));\n } else if (cmd && key === \"c\" && !e.shiftKey) {\n const sel = selection.get() as Element[];\n if (!sel.length) return true;\n e.preventDefault();\n copyPaste.copy(sel);\n } else if (!cmd && key === \"escape\") {\n if (dragging?.context() || !selection.get().length) return true;\n e.preventDefault();\n selection.select(null);\n } else {\n return false;\n }\n return true;\n };\n\n const handleEditingKey = (e: KeyboardEvent, cmd: boolean, key: string): void => {\n const undo = cmd && key === \"z\" && !e.shiftKey;\n const redo = (cmd && key === \"z\" && e.shiftKey) || (cmd && key === \"y\" && !e.shiftKey);\n if (undo || redo) {\n if (!undoRedoKeys) return;\n e.preventDefault();\n if (undo && commandStack.canUndo()) commandStack.undo();\n if (redo && commandStack.canRedo()) commandStack.redo();\n } else if (key === \"delete\" || key === \"backspace\") {\n const sel = selection.get() as Element[];\n if (sel.length) {\n e.preventDefault();\n modeling.removeElements([...sel]);\n }\n } else if (cmd && key === \"v\" && !e.shiftKey) {\n e.preventDefault();\n copyPaste.paste();\n } else if (!cmd && Object.hasOwn(ARROW_DIRECTIONS, e.key)) {\n const shapes = (selection.get() as Element[]).filter(isShape);\n if (!shapes.length || !rules.allowed(\"elements.move\", { shapes })) return;\n e.preventDefault();\n const direction = ARROW_DIRECTIONS[e.key]!;\n const step = e.shiftKey ? NUDGE_STEP_FAST : NUDGE_STEP;\n modeling.moveElements(shapes, { x: direction.x * step, y: direction.y * step });\n }\n };\n\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.altKey || e.isComposing || isTypingTarget(e.target)) return;\n if (!isCanvasScope(e.target, container) || doc.querySelector(MODAL_SELECTOR)) return;\n const cmd = e.ctrlKey || e.metaKey;\n const key = e.key.toLowerCase();\n if (handleReadingKey(e, cmd, key)) return;\n if (readOnly?.isReadOnly()) return;\n handleEditingKey(e, cmd, key);\n };\n\n doc.addEventListener(\"keydown\", onKeyDown);\n eventBus.on(\"diagram.destroy\", () => doc.removeEventListener(\"keydown\", onKeyDown));\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtKeyboard from \"./TtKeyboard.js\";\n\n/** Canvas shortcuts: history, selection, clipboard and nudging (see TtKeyboard). */\nexport const ttKeyboardModule: ModuleDeclaration = {\n __init__: [\"ttKeyboard\"],\n ttKeyboard: [\"type\", TtKeyboard],\n};\n\nexport { default as TtKeyboard } from \"./TtKeyboard.js\";\nexport type { TtKeyboardConfig } from \"./TtKeyboard.js\";\n","/**\n * Copy-paste for Team Topologies shapes, built on the stock diagram-js\n * CopyPaste feature. Only the id handling differs: the stock `createShape`\n * drops the descriptor id and lets diagram-js auto-assign a `shape_N` id, which\n * is the very collision hazard `TtElementFactory` avoids (its counter is not\n * advanced past ids that arrive via import). So we mint a fresh, scheme-correct\n * `team_/int_/flow_/ann_/assoc_` id instead — the custom `tt*` props are already\n * on the descriptor (added by `TtCopyPasteProps`) and pass straight through.\n * Annotation connectors are pasted only together with both of their ends.\n */\n\nimport CopyPaste from \"diagram-js/lib/features/copy-paste/CopyPaste.js\";\nimport { newId } from \"@miragon/team-topologies-schema-model\";\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type Create from \"diagram-js/lib/features/create/Create\";\nimport type Clipboard from \"diagram-js/lib/features/clipboard/Clipboard\";\nimport type ElementFactory from \"diagram-js/lib/core/ElementFactory\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type Mouse from \"diagram-js/lib/features/mouse/Mouse\";\nimport type Rules from \"diagram-js/lib/features/rules/Rules\";\nimport type { Connection, Shape } from \"diagram-js/lib/model/Types\";\n\n/** Maps a `ttKind` to the id prefix the model package's factory uses. */\nfunction pasteIdPrefix(ttKind: unknown): string | undefined {\n switch (ttKind) {\n case \"team\":\n return \"team\";\n case \"interaction\":\n return \"int\";\n case \"flow\":\n return \"flow\";\n case \"annotation\":\n return \"ann\";\n case \"association\":\n return \"assoc\";\n default:\n return undefined;\n }\n}\n\nexport default class TtCopyPaste extends CopyPaste {\n static override $inject = [\n \"canvas\",\n \"create\",\n \"clipboard\",\n \"elementFactory\",\n \"eventBus\",\n \"modeling\",\n \"mouse\",\n \"rules\",\n ];\n\n constructor(\n canvas: Canvas,\n create: Create,\n clipboard: Clipboard,\n private readonly elementFactory: ElementFactory,\n eventBus: EventBus,\n modeling: Modeling,\n mouse: Mouse,\n rules: Rules,\n ) {\n super(canvas, create, clipboard, elementFactory, eventBus, modeling, mouse, rules);\n }\n\n override createConnection(attrs: Record<string, unknown>): Connection {\n const prefix = pasteIdPrefix(attrs.ttKind);\n if (!prefix) {\n return super.createConnection(attrs);\n }\n return this.elementFactory.createConnection({ ...attrs, id: newId(prefix) }) as Connection;\n }\n\n override createShape(attrs: Record<string, unknown>): Shape {\n const prefix = pasteIdPrefix(attrs.ttKind);\n if (!prefix) {\n return super.createShape(attrs);\n }\n // Keep the id (unlike stock `createShape`, which strips it): a fresh\n // model-style id avoids \"element already exists\" on the next create.\n return this.elementFactory.createShape({ ...attrs, id: newId(prefix) }) as Shape;\n }\n}\n","/**\n * Carries the Team Topologies props across a copy-paste. diagram-js stores each\n * copied element as a plain descriptor whose built-in listener only records\n * geometry (`id/x/y/width/height/…`). Our domain data lives as flat attributes\n * on the shape (not a moddle businessObject), so without this the pasted copy\n * would lose its type, label, description, colours and the fields of other tools. This listener copies\n * those fields onto the descriptor; they then flow through to the new shape.\n */\n\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport { isTtAssociation, isTtElement } from \"../model/di-types.js\";\n\n/** Flat props that define a Team Topologies shape, beyond geometry. */\nconst TT_PROPS = [\n \"ttKind\",\n \"teamType\",\n \"mode\",\n \"ttLabel\",\n \"description\",\n \"fill\",\n \"stroke\",\n \"ttForeign\",\n] as const;\n\nexport default class TtCopyPasteProps {\n static $inject = [\"eventBus\"];\n\n constructor(eventBus: EventBus) {\n eventBus.on(\n \"copyPaste.copyElement\",\n (event: { descriptor: Record<string, unknown>; element: unknown }) => {\n const { descriptor, element } = event;\n if (!isTtElement(element) && !isTtAssociation(element)) return;\n const source = element as Record<string, unknown>;\n for (const prop of TT_PROPS) {\n if (source[prop] !== undefined) descriptor[prop] = structuredClone(source[prop]);\n }\n },\n );\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport CopyPasteModule from \"diagram-js/lib/features/copy-paste\";\nimport TtCopyPaste from \"./TtCopyPaste.js\";\nimport TtCopyPasteProps from \"./TtCopyPasteProps.js\";\n\n/**\n * Copy-paste of Team Topologies shapes: the stock diagram-js feature (clipboard,\n * cursor-follow placement) with `copyPaste` overridden to mint model-style ids\n * and a listener that preserves the flat `tt*` props across the round-trip.\n */\nexport const ttCopyPasteModule: ModuleDeclaration = {\n __depends__: [CopyPasteModule],\n __init__: [\"ttCopyPasteProps\"],\n copyPaste: [\"type\", TtCopyPaste],\n ttCopyPasteProps: [\"type\", TtCopyPasteProps],\n};\n\nexport { default as TtCopyPaste } from \"./TtCopyPaste.js\";\n","/**\n * Enforces a fixed stacking order regardless of creation order, by reordering\n * the element graphics within the canvas layer. Back → front:\n *\n * flow < stream-aligned / platform < complicated-subsystem < enabling\n * < interactions < annotations < annotation connectors\n *\n * So interaction glyphs always read on top of teams; enabling teams sit above the\n * complicated-subsystem teams, which in turn sit above the stream-aligned /\n * platform base teams they overlap. Annotation connectors come last so no shape\n * they cross on the way to their element hides them.\n */\n\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 {\n isTtAnnotation,\n isTtAssociation,\n isTtElement,\n isTtFlow,\n isTtInteraction,\n isTtTeam,\n type TtAssociation,\n type TtElement,\n} from \"../model/di-types.js\";\n\n/** Lower = further back. */\nfunction tier(el: TtElement | TtAssociation): number {\n if (isTtFlow(el)) return 0;\n if (isTtTeam(el)) {\n if (el.teamType === \"enabling\") return 3;\n if (el.teamType === \"complicated-subsystem\") return 2;\n return 1; // stream-aligned, platform\n }\n if (isTtInteraction(el)) return 4;\n if (isTtAnnotation(el)) return 5;\n if (isTtAssociation(el)) return 6;\n return 1;\n}\n\nfunction isOrdered(el: unknown): el is TtElement | TtAssociation {\n return isTtElement(el) || isTtAssociation(el);\n}\n\nexport default class TtZOrder {\n static $inject = [\"eventBus\", \"canvas\", \"elementRegistry\"];\n\n private importing = false;\n\n constructor(\n eventBus: EventBus,\n private readonly canvas: Canvas,\n private readonly elementRegistry: ElementRegistry,\n ) {\n eventBus.on(\"import.render.start\", () => {\n this.importing = true;\n });\n eventBus.on(\"import.render.done\", () => {\n this.importing = false;\n this.reorder();\n });\n // Covers create + team-type changes (and harmlessly re-runs on move/resize).\n eventBus.on(\"commandStack.changed\", () => {\n if (!this.importing) this.reorder();\n });\n }\n\n /** Re-append each element's graphics group in ascending tier order (back → front). */\n reorder(): void {\n const ordered = this.elementRegistry\n .getAll()\n .filter(isOrdered)\n .sort((a, b) => tier(a) - tier(b));\n for (const el of ordered) {\n const gfx = this.canvas.getGraphics(el) as SVGElement | undefined;\n const wrapper = gfx?.parentNode as (Node & ChildNode) | null;\n const layer = wrapper?.parentNode as (Node & { appendChild(n: Node): Node }) | null;\n if (wrapper && layer) layer.appendChild(wrapper);\n }\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtZOrder from \"./TtZOrder.js\";\n\n/** Keeps the fixed stacking order (interactions on top, base teams at the back). */\nexport const ttZOrderModule: ModuleDeclaration = {\n __init__: [\"ttZOrder\"],\n ttZOrder: [\"type\", TtZOrder],\n};\n\nexport { default as TtZOrder } from \"./TtZOrder.js\";\n","import type { ModuleDeclaration } from \"didi\";\nimport type CommandStack from \"diagram-js/lib/command/CommandStack\";\n\nimport LassoToolModule from \"diagram-js/lib/features/lasso-tool\";\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 ResizeModule from \"diagram-js/lib/features/resize\";\n\nimport { NavigatedViewer } from \"./NavigatedViewer.js\";\nimport { ttModelingModule } from \"./modeling/index.js\";\nimport { ttRulesModule } from \"./rules/index.js\";\nimport { ttBehaviorsModule } from \"./behaviors/index.js\";\nimport { ttPaletteModule } from \"./palette/index.js\";\nimport { ttContextPadModule } from \"./context-pad/index.js\";\nimport { ttLabelEditingModule } from \"./label-editing/index.js\";\nimport { ttKeyboardModule } from \"./keyboard/index.js\";\nimport { ttCopyPasteModule } from \"./copy-paste/index.js\";\nimport { ttZOrderModule } from \"./zorder/index.js\";\nimport { ttReadOnlyModule } from \"./read-only/index.js\";\n\n/**\n * Full Team Topologies editor: palette/create, multi-selection (lasso, select\n * all) and group move, resize, annotations with connectors, context pad,\n * in-place label editing, undo/redo, and the edit lock for a document the\n * canvas cannot save (`ttReadOnly`).\n */\nexport class Modeler extends NavigatedViewer {\n protected override _getModules(): ModuleDeclaration[] {\n return [\n ...super._getModules(),\n // diagram-js stock\n ModelingModule,\n LassoToolModule,\n MoveModule,\n OutlineModule,\n ResizeModule,\n // Team Topologies editor\n ttReadOnlyModule,\n ttModelingModule,\n ttRulesModule,\n ttBehaviorsModule,\n ttPaletteModule,\n ttContextPadModule,\n ttLabelEditingModule,\n ttKeyboardModule,\n ttCopyPasteModule,\n ttZOrderModule,\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","/**\n * The Team Topologies modeler behind the collaborative-modeler contract of `@miragon/modeler-api`\n * (the laws L1 to L7 in its README): hosts such as designIQ, the VS Code webview and the web app\n * import and export the document as text, observe changes and anchor on element ids without\n * knowing the renderer.\n */\n\nimport {\n MODELER_API_VERSION,\n type CollaborativeModeler,\n type ElementInfo,\n type ElementsSurface,\n type ImportResult,\n type ModelerMeta,\n} from \"@miragon/modeler-api\";\nimport {\n parseDocument,\n serializeDocument,\n type TtDocument,\n} from \"@miragon/team-topologies-schema-model\";\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 { Modeler } from \"../Modeler.js\";\nimport { NavigatedViewer } from \"../NavigatedViewer.js\";\nimport { isTtElement, type TtElement } from \"../model/di-types.js\";\nimport type { Point } from \"../palette/TtPaletteProvider.js\";\n\n/** Stable notation id in `meta.notation` of the collaborative-modeler contract. */\nexport const TEAM_TOPOLOGIES_NOTATION = \"team-topologies\";\n\nexport interface CollaborativeTeamTopologiesOptions {\n /** Appended to the renderer's own modules (e.g. a host's chrome module). */\n additionalModules?: ModuleDeclaration[] | undefined;\n /** See `TtViewerOptions.undoRedoKeys` (default true). */\n undoRedoKeys?: boolean | undefined;\n /** See `TtViewerOptions.freeRectCenter`. */\n freeRectCenter?: (() => Point | undefined) | undefined;\n /**\n * Fit the diagram into view after every import (default true, contract law L5). A host whose\n * chrome fits the diagram itself (the modeler shell's viewport) passes false.\n */\n fitOnImport?: boolean | undefined;\n}\n\n/** The contract surface plus the wrapped diagram for host-specific wiring. */\nexport interface CollaborativeTeamTopologiesModeler extends CollaborativeModeler {\n readonly elements: ElementsSurface;\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: CollaborativeTeamTopologiesOptions = {},\n): CollaborativeTeamTopologiesModeler {\n return collaborative(\n new Modeler({\n ...diagramOptions(options),\n undoRedoKeys: options.undoRedoKeys ?? true,\n freeRectCenter: options.freeRectCenter,\n }),\n true,\n options.fitOnImport ?? true,\n );\n}\n\n/** The read-only mount (`meta.editable: false`): imports, exports and reveals, never edits. */\nexport function createCollaborativeViewer(\n options: Pick<CollaborativeTeamTopologiesOptions, \"additionalModules\" | \"fitOnImport\"> = {},\n): CollaborativeTeamTopologiesModeler {\n return collaborative(\n new NavigatedViewer(diagramOptions(options)),\n false,\n options.fitOnImport ?? true,\n );\n}\n\nfunction diagramOptions(options: Pick<CollaborativeTeamTopologiesOptions, \"additionalModules\">) {\n return { width: \"100%\", height: \"100%\", additionalModules: options.additionalModules ?? [] };\n}\n\n/**\n * The document text as the contract reads it: blank text is a new, empty diagram (a file just\n * created in an editor), anything else must be a valid document.\n */\nexport function parseDocumentText(text: string): TtDocument {\n const result = parseDocument(text.trim() === \"\" ? {} : JSON.parse(text));\n if (!result.ok) throw new Error(result.error);\n return result.document;\n}\n\nfunction collaborative(\n diagram: Modeler | NavigatedViewer,\n editable: boolean,\n fitOnImport: boolean,\n): CollaborativeTeamTopologiesModeler {\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 importsRunning = 0;\n let destroyed = false;\n let lastExport = \"\";\n\n const meta: ModelerMeta = {\n notation: TEAM_TOPOLOGIES_NOTATION,\n apiVersion: MODELER_API_VERSION,\n editable,\n };\n\n if (editable) {\n eventBus.on(\"commandStack.changed\", () => {\n if (importsRunning > 0) return;\n for (const listener of [...contentListeners]) listener();\n });\n }\n\n const exportText = (): string => serializeDocument(diagram.exportDocument());\n\n const elements: ElementsSurface = {\n list: () =>\n destroyed ? [] : (elementRegistry.getAll() as unknown[]).filter(isTtElement).map(elementInfo),\n reveal(id) {\n if (destroyed) return false;\n const element = elementRegistry.get(id);\n if (!isTtElement(element)) return false;\n selection.select(element);\n canvas.scrollToElement(element);\n return true;\n },\n selection: () => (destroyed ? [] : elementIds(selection.get())),\n onSelection(callback) {\n const listener = (event: unknown) =>\n callback(elementIds((event as { newSelection?: unknown[] }).newSelection ?? []));\n eventBus.on(\"selection.changed\", listener);\n return () => eventBus.off(\"selection.changed\", listener);\n },\n };\n\n return {\n meta,\n elements,\n diagram,\n attachTo(host) {\n diagram.attachTo(host);\n },\n async importText(text): Promise<ImportResult> {\n if (destroyed) throw new Error(\"The modeler was destroyed.\");\n const document = parseDocumentText(text);\n importsRunning += 1;\n try {\n const { warnings } = diagram.importDocument(document, { fit: fitOnImport });\n return { warnings: warnings.map((warning) => warning.message) };\n } finally {\n importsRunning -= 1;\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 exportText();\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 = exportText();\n } catch {\n lastExport = \"\";\n }\n destroyed = true;\n contentListeners.clear();\n diagram.destroy();\n },\n };\n}\n\n/** Connectors are not addressable: their ids derive from the annotation and are never stored. */\nfunction elementIds(elements: readonly unknown[]): string[] {\n return elements.filter(isTtElement).map((element) => element.id);\n}\n\n/** A team's, interaction's or flow's label; an annotation's text. */\nfunction elementInfo(element: TtElement): ElementInfo {\n const name = element.ttLabel;\n return name ? { id: element.id, name } : { 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,IAAMyB,qBAAmC,IAAI,IAAY;CACvD;CACA;CACA;CACA;AACF,CAAC;AAED,SAASC,EAAO,GAAiC;CAC/C,OAAO,OAAOC,KAAO,YAAYA,IAC3BA,EAA4B,SAC9B,KAAA;AACN;AAEA,SAAgBC,EAAY,GAA8B;CACxD,IAAMC,IAAOH,EAAOC,CAAE;CACtB,OAAOE,MAAS,KAAA,KAAaJ,GAAY,IAAII,CAAI;AACnD;AAEA,SAAgBC,EAAS,GAA2B;CAClD,OAAOJ,EAAOC,CAAE,MAAM;AACxB;AAEA,SAAgBI,EAAgB,GAAkC;CAChE,OAAOL,EAAOC,CAAE,MAAM;AACxB;AAEA,SAAgBK,EAAS,GAA2B;CAClD,OAAON,EAAOC,CAAE,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R,IAAI,IACJ;QAAI;KACF,IAAaT,EAAW;IAC1B,QAAQ;KACN,IAAa;IACf;IAGA,AAFA,IAAY,IACZP,EAAiB,MAAM,GACvB3X,EAAQ,QAAQ;GAHhB;EAIF;CACF;AACF;AAGA,SAASsY,GAAW,GAAwC;CAC1D,OAAO3O,EAAS,OAAOrM,CAAW,CAAC,CAAC,KAAK,MAAYiI,EAAQ,EAAE;AACjE;AAGA,SAAS6S,GAAY,GAAiC;CACpD,IAAMlZ,IAAOqG,EAAQ;CACrB,OAAOrG,IAAO;EAAE,IAAIqG,EAAQ;EAAI;CAAK,IAAI,EAAE,IAAIA,EAAQ,GAAG;AAC5D;AAEA,SAASqT,GAAY,GAAoC;CACvD,IAAI,OAAOD,KAAU,aAAYA,GAAgB,OAAO;CACxD,IAAM,EAAE,MAAG,MAAG,UAAO,cAAWA;CAChC,OACEE,EAAeha,CAAC,KAChBga,EAAe/Z,CAAC,KAChB+Z,EAAe9Z,CAAK,KACpB8Z,EAAe7Z,CAAM,KACrBD,IAAQ,KACRC,IAAS;AAEb;AAEA,SAAS6Z,EAAe,GAAiC;CACvD,OAAO,OAAOnZ,KAAU,YAAY,OAAO,SAASA,CAAK;AAC3D"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["SVG_NAMESPACE","svgAttr","svgCreate","Diagram","CroppingConnectionDocking","BaseRenderer","SelectionModule","ZoomScrollModule","MoveCanvasModule","LassoToolModule","ModelingModule","MoveModule","OutlineModule","ResizeModule","BaseLayouter","RulesModule","RuleProvider","CommandInterceptor","PaletteModule","CreateModule","ConnectModule","ConnectionPreviewModule","ContextPadModule","CopyPasteModule","CopyPaste","SHAPE_KINDS","kindOf","el","isTtElement","kind","isTtTeam","isTtInteraction","isTtFlow","isTtAnnotation","isTtAssociation","MIRAGON","CD_TOKENS","MARGIN","SVG_NAMESPACE$1","INTERACTION_CHROME_SELECTOR","TRANSIENT_CLASSES","CANVAS_ONLY_ATTRIBUTES","saveSVG","source","canvas","minX","minY","maxX","maxY","elementRegistry","s","x","y","width","height","clone","name","node","viewport","sheet","ROOT_ID","DIAGRAM_ROOT_ID","CANVAS_KEYBOARD_FOCUS_CLASS","sizeToCss","value","TtBaseViewer","options","container","modules","canvasContainer","diagram","svg","ownerDocument","lastKeyWasTab","onKeyDown","event","onPointerDown","priority","callback","problems","documentIdProblems","doc","path","message","eventBus","importer","labelEditing","warnings","root","current","partial","target","TtElementFactory","elementFactory","ttForeign","foreignFields","knownFields","TEAM_NODE_FIELDS","shape","INTERACTION_FIELDS","FLOW_FIELDS","annotation","ANNOTATION_FIELDS","associationId","getMid","spec","TEAM_TYPE_SPECS","type","newId","label","INTERACTION_MODE_SPECS","mode","FLOW_SPEC","ANNOTATION_SPEC","text","ttModelModule","TT_RENDER_PRIORITY","INK","INK_MUTED","STROKE_MUTED","FONT","LABEL_INSET","ANNOTATION_PADDING","LINE_HEIGHT","MIN_TEXT_CONTRAST","parseHexColour","colour","match","hex","digit","channel","offset","blendOver","mix","index","opacity","backdrop","relativeLuminance","red","green","blue","linear","contrastRatio","lighter","darker","first","second","b","a","readableTextColour","fillRgb","fill","ink","paper","background","inkContrast","shapeTextColour","element","flowHeadWidth","labelLayout","wrapLabel","maxChars","maxWidth","fontSize","paragraphs","lines","paragraph","words","word","candidate","TeamTopologiesRenderer","visuals","rect","attr","create","append","line","waypointsPath","connection","team","w","h","sw","dash","dashArray","outline","i","iw","ih","c","octagon","attrs","rx","common","glyph","pts","skew","head","shaft","top","bot","p","arrow","arm","bracket","layout","box","lineHeight","centred","startY","ln","t","idx","waypoints","point","ttDrawModule","TtImporter","factory","connectionDocking","existing","foreign","DOCUMENT_FIELDS","flow","interaction","association","elements","connections","shapes","TtExporter","meta","nodes","interactions","flows","annotations","geom","position","size","withForeignFields","attachedTo","attachedElementId","DOCUMENT_VERSION","NARROW_LAYOUT_MAX_WIDTH","TOP_INSET","TOP_INSET_NARROW","PADDING","SIDE_PADDING_NARROW","MAX_FIT_ZOOM","TtViewport","bounds","viewportWidth","viewportHeight","narrow","topInset","sidePadding","contentWidth","contentHeight","scale","freeHeight","slack","SVG_NAMESPACE","GEIST_UNICODE_RANGES","geistFontFaceCss","fonts","subset","embedSvgStyles","parsed","defs","style","css","ioModule","Viewer","NavigatedViewer","setOrDelete","obj","key","UpdatePropertiesHandler","context","old","properties","oldProperties","UNTITLED","UpdateTitleHandler","UPDATE_PROPERTIES","UPDATE_TITLE","ANNOTATION_GAP","TtModeling","commandStack","modeling","associations","TtLayouter","hints","ttModelingModule","isAttachable","TtRules","ttRulesModule","TtFlatModelBehavior","TtAssociationBehavior","previous","other","ttBehaviorsModule","ICON_PENCIL","ICON_TRASH","ICON_LINK","ICON_MESSAGE_SQUARE_PLUS","ICON_SQUARE_DASHED_MOUSE_POINTER","ICON_MENU","ICON_MINUS","ICON_PLUS","ICON_MAXIMIZE","ICON_DOWNLOAD","ICON_X","ICON_STROKE_WIDTH","ICON_SIZE","SVG_ELEMENTS","SVG_ATTRIBUTES","escapeAttribute","positiveNumberOr","number","fallback","iconMarkup","strokeWidth","icon","tag","attributes","allowed","attribute","PALETTE_TOOL_ICON","inner","teamIconSvg","flowIconSvg","annotationIconSvg","lassoIconSvg","interactionIconSvg","GROUP_TOOLS","GROUP_TEAMS","GROUP_MODES","GROUP_GUIDES","KEYBOARD_CREATE_OFFSET","entryHtml","draggable","isKeyboardClick","centreOf","centreInside","freeWidth","outer","insets","TtPaletteProvider","config","lassoTool","selection","injector","palette","entries","ALL_TEAM_SPECS","ALL_INTERACTION_SPECS","\"flow\"","\"annotation\"","start","newShape","viewbox","centre","place","taken","elementCentre","freeArea","created","ttPaletteModule","READ_ONLY_CHANGED_EVENT","LOCK_PRIORITY","EDIT_RULES","TtReadOnly","bus","readOnly","ttReadOnlyModule","ENTRY_SELECTOR","cpHtml","focusable","title","editTitle","TtContextPadProvider","contextPad","ttModeling","connect","keyboardEvent","startConnect","appendAnnotation","action","activate","ttContextPadModule","EDITING_MARKER","MIN_EDITOR_WIDTH","editorName","TtLabelEditing","edit","left","editor","resumed","boxHeight","fitToContent","done","cleanup","onKey","onBlur","commit","changed","snapshot","ttLabelEditingModule","NUDGE_STEP","NUDGE_STEP_FAST","ARROW_DIRECTIONS","MODAL_SELECTOR","isTypingTarget","isNode","isCanvasScope","isShape","TtKeyboard","undoRedoKeys","dragging","handleReadingKey","cmd","sel","copyPaste","handleEditingKey","undo","redo","rules","direction","step","ttKeyboardModule","pasteIdPrefix","ttKind","TtCopyPaste","clipboard","mouse","prefix","TT_PROPS","ttCopyPasteModule","prop","tier","isOrdered","TtZOrder","ordered","wrapper","layer","ttZOrderModule","Modeler","TEAM_TOPOLOGIES_NOTATION","createCollaborativeModeler","collaborative","diagramOptions","createCollaborativeViewer","parseDocumentText","result","parseDocument","contentListeners","importsRunning","destroyed","lastExport","MODELER_API_VERSION","editable","listener","exportText","serializeDocument","elementInfo","id","elementIds","host","document","fitOnImport","warning","state","isViewState","isFiniteNumber"],"sources":["../src/model/di-types.ts","../src/theme/palette.ts","../src/io/saveSvg.ts","../src/io/types.ts","../src/TtBaseViewer.ts","../src/model/TtElementFactory.ts","../src/model/index.ts","../src/draw/styles.ts","../src/draw/label-layout.ts","../src/draw/TeamTopologiesRenderer.ts","../src/draw/index.ts","../src/io/TtImporter.ts","../src/io/TtExporter.ts","../src/io/TtViewport.ts","../src/io/fontEmbedding.ts","../src/io/index.ts","../src/Viewer.ts","../src/NavigatedViewer.ts","../src/modeling/cmd/UpdatePropertiesHandler.ts","../src/modeling/cmd/UpdateTitleHandler.ts","../src/modeling/TtModeling.ts","../src/modeling/TtLayouter.ts","../src/modeling/index.ts","../src/rules/TtRules.ts","../src/rules/index.ts","../src/behaviors/TtFlatModelBehavior.ts","../src/behaviors/TtAssociationBehavior.ts","../src/behaviors/index.ts","../src/draw/icons.ts","../src/draw/palette-icons.ts","../src/palette/TtPaletteProvider.ts","../src/palette/index.ts","../src/read-only/TtReadOnly.ts","../src/read-only/index.ts","../src/context-pad/TtContextPadProvider.ts","../src/context-pad/index.ts","../src/label-editing/TtLabelEditing.ts","../src/label-editing/index.ts","../src/keyboard/TtKeyboard.ts","../src/keyboard/index.ts","../src/copy-paste/TtCopyPaste.ts","../src/copy-paste/TtCopyPasteProps.ts","../src/copy-paste/index.ts","../src/zorder/TtZOrder.ts","../src/zorder/index.ts","../src/Modeler.ts","../src/collaborative/CollaborativeTeamTopologies.ts"],"sourcesContent":["/**\n * diagram-js runtime model for the Team Topologies notation. Every element is a\n * placed, resizable SHAPE discriminated by `ttKind`:\n * - `team` — one of the four team types (label inside the box)\n * - `interaction` — a mode glyph (parallelogram / triangle / circle), 50%\n * transparent, overlaid on the boundary between teams\n * - `flow` — the \"flow of change\" arrow guide\n * - `annotation` — a free-text note (BPMN-style open bracket)\n *\n * The only connection is the `association`: the dashed connector from an\n * annotation to the element it is attached to.\n *\n * These runtime properties are the source of truth while editing; the exporter\n * rebuilds the canonical `TtDocument` from them.\n */\n\nimport type { Connection, Shape } from \"diagram-js/lib/model/Types\";\nimport type {\n ForeignFields,\n InteractionMode,\n TeamType,\n} from \"@miragon/team-topologies-schema-model\";\n\nexport type TtKind = \"team\" | \"interaction\" | \"flow\" | \"annotation\";\n\n/** What every Team Topologies shape carries beyond its geometry. */\ninterface TtShape extends Shape {\n /** Fields of the document element the modeler does not know, written back on export. */\n ttForeign?: ForeignFields;\n}\n\nexport interface TtTeam extends TtShape {\n ttKind: \"team\";\n teamType: TeamType;\n /** Display name (separate from diagram-js `label`). */\n ttLabel?: string;\n description?: string;\n fill?: string;\n stroke?: string;\n}\n\nexport interface TtInteraction extends TtShape {\n ttKind: \"interaction\";\n mode: InteractionMode;\n ttLabel?: string;\n fill?: string;\n stroke?: string;\n}\n\nexport interface TtFlow extends TtShape {\n ttKind: \"flow\";\n ttLabel?: string;\n}\n\nexport interface TtAnnotation extends TtShape {\n ttKind: \"annotation\";\n /** The annotation text (may contain line breaks). */\n ttLabel?: string;\n}\n\nexport interface TtAssociation extends Connection {\n ttKind: \"association\";\n}\n\nexport type TtElement = TtTeam | TtInteraction | TtFlow | TtAnnotation;\n\nconst SHAPE_KINDS: ReadonlySet<string> = new Set<TtKind>([\n \"team\",\n \"interaction\",\n \"flow\",\n \"annotation\",\n]);\n\nfunction kindOf(el: unknown): string | undefined {\n return typeof el === \"object\" && el !== null\n ? ((el as { ttKind?: unknown }).ttKind as string | undefined)\n : undefined;\n}\n\nexport function isTtElement(el: unknown): el is TtElement {\n const kind = kindOf(el);\n return kind !== undefined && SHAPE_KINDS.has(kind);\n}\n\nexport function isTtTeam(el: unknown): el is TtTeam {\n return kindOf(el) === \"team\";\n}\n\nexport function isTtInteraction(el: unknown): el is TtInteraction {\n return kindOf(el) === \"interaction\";\n}\n\nexport function isTtFlow(el: unknown): el is TtFlow {\n return kindOf(el) === \"flow\";\n}\n\nexport function isTtAnnotation(el: unknown): el is TtAnnotation {\n return kindOf(el) === \"annotation\";\n}\n\nexport function isTtAssociation(el: unknown): el is TtAssociation {\n return kindOf(el) === \"association\";\n}\n","/**\n * Miragon design tokens — the single source of truth for every non-notation colour in the renderer.\n *\n * Values mirror the Miragon corporate identity: the `miragon-brand:modeler-tool-design` skill in\n * `Miragon/corporate-identity`, whose vendored `cd-tokens.generated.css` (next to this file) defines\n * the `--cd-*` custom properties, generated from `brand/tokens.json`. Re-copy that CSS from the skill\n * to update; never fork the hex values by hand. `packages/renderer/src/theme/theme.sync.test.ts`\n * fails if this mirror drifts from the vendored CSS.\n *\n * Pure data — no DOM, no imports — so it stays inside the P1 DOM-free discipline and can be consumed\n * by the SVG-drawing constants in `draw/styles.ts`.\n *\n * Brand rule: blue leads (`blau` — surfaces, buttons, links, selection), green accents (`gruen` — key\n * visual, highlights; a fill, never body text on white). The four Team Topologies team-type and\n * interaction colours are the official notation and live in `schema-model/notation.ts` — they are NOT\n * part of this brand ramp.\n */\n\n/** Raw Miragon brand ramp + UI neutrals + functional layer — exact `--cd-*` values. */\nexport const MIRAGON = {\n /** Primary: surfaces, buttons, links, selection, backgrounds. */\n blau: \"#335DE5\",\n /** Deeper blue for links / accent text on white (WCAG AA, ~5.5:1). */\n blauLink: \"#2B50D4\",\n /** Lightened blue for accents on dark surfaces (unused here — the canvas is light-only). */\n blauHell: \"#6B8AFF\",\n /** Accent: key visual, highlights, the brand gradient. Bright — a fill, never text on white. */\n gruen: \"#00E676\",\n /** Calm neutral surface (warm off-white) — the paper surround. */\n grau: \"#F9F7F7\",\n /** Text on light; not pure black. */\n schwarz: \"#1D1D1D\",\n weiss: \"#FFFFFF\",\n /** Dividers and decorative borders; no contrast requirement. */\n linie: \"#E6E2E2\",\n /** Non-text elements that need ≥ 3:1 (input borders, structural strokes and connectors). */\n kontur: \"#8F8A8A\",\n /** Secondary text, ≥ 4.5:1 on `weiss` and on `grau`. */\n textLeise: \"#6B6666\",\n /**\n * Functional / status layer. `success` and `warning` are fills, borders, icons and dots only —\n * never text or thin strokes on light (1.67:1 / 1.83:1). `danger` and `info` also carry text\n * (AA on white). Each `-soft` is an opaque tint for notice boxes and badges.\n */\n success: \"#00E676\",\n successSoft: \"#DAFBEB\",\n warning: \"#FFB000\",\n warningSoft: \"#FFF1D2\",\n danger: \"#CD1839\",\n dangerSoft: \"#FBEEF0\",\n info: \"#335DE5\",\n infoSoft: \"#EEF1FD\",\n /** Each `-hell` is the status colour for dark surfaces (unused here — the canvas is light-only). */\n successHell: \"#00E676\",\n warningHell: \"#FFB000\",\n dangerHell: \"#FB6D73\",\n infoHell: \"#6B8AFF\",\n /** Signature brand gradient — brand moments only. Use verbatim. */\n gradientBrand: \"linear-gradient(120deg, #335DE5 30%, #00E676)\",\n} as const;\n\n/**\n * Every `--cd-*` token this repo depends on, mapped to the value it MUST hold. The drift test parses\n * `cd-tokens.generated.css` and asserts each entry matches, so re-copying the vendored CSS with a\n * changed value fails CI until this mirror (and `MIRAGON`) is updated too. `--cd-gradient-format`\n * stays unmirrored: nothing here uses the format-tile gradient.\n */\nexport const CD_TOKENS: Record<string, string> = {\n \"--cd-blau\": MIRAGON.blau,\n \"--cd-gruen\": MIRAGON.gruen,\n \"--cd-grau\": MIRAGON.grau,\n \"--cd-schwarz\": MIRAGON.schwarz,\n \"--cd-weiss\": MIRAGON.weiss,\n \"--cd-blau-link\": MIRAGON.blauLink,\n \"--cd-blau-hell\": MIRAGON.blauHell,\n \"--cd-linie\": MIRAGON.linie,\n \"--cd-kontur\": MIRAGON.kontur,\n \"--cd-text-leise\": MIRAGON.textLeise,\n \"--cd-success\": MIRAGON.success,\n \"--cd-success-soft\": MIRAGON.successSoft,\n \"--cd-warning\": MIRAGON.warning,\n \"--cd-warning-soft\": MIRAGON.warningSoft,\n \"--cd-danger\": MIRAGON.danger,\n \"--cd-danger-soft\": MIRAGON.dangerSoft,\n \"--cd-info\": MIRAGON.info,\n \"--cd-info-soft\": MIRAGON.infoSoft,\n \"--cd-success-hell\": MIRAGON.successHell,\n \"--cd-warning-hell\": MIRAGON.warningHell,\n \"--cd-danger-hell\": MIRAGON.dangerHell,\n \"--cd-info-hell\": MIRAGON.infoHell,\n \"--cd-gradient-brand\": MIRAGON.gradientBrand,\n};\n","/**\n * Serialises the current canvas into a standalone SVG (snapshot / export),\n * fitted to the content bounds and independent of the current zoom / scroll.\n * Interaction chrome (selection outlines, resize handles, hover state) is left\n * out, and a white sheet sits behind the diagram, so an export always looks the\n * same as the light canvas, whatever was selected and wherever it is viewed.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type ElementRegistry from \"diagram-js/lib/core/ElementRegistry\";\nimport { isTtElement } from \"../model/di-types.js\";\nimport { MIRAGON } from \"../theme/palette.js\";\n\nconst MARGIN = 40;\nconst SVG_NAMESPACE = \"http://www.w3.org/2000/svg\";\n\nconst INTERACTION_CHROME_SELECTOR = [\n \".djs-outline\",\n \".djs-resizer\",\n \".djs-selection-outline\",\n \".djs-lasso-overlay\",\n \".djs-dragger\",\n \".djs-bendpoint\",\n \".djs-segment-dragger\",\n].join(\", \");\n\nconst TRANSIENT_CLASSES = [\"selected\", \"hover\"];\n\nconst CANVAS_ONLY_ATTRIBUTES = [\"class\", \"tabindex\", \"role\", \"aria-roledescription\", \"aria-label\"];\n\nexport function saveSVG(canvas: Canvas, elementRegistry: ElementRegistry): { svg: string } {\n const container = canvas.getContainer();\n const source = container.querySelector(\":scope > svg\");\n if (!source) throw new Error(\"No SVG found in the canvas container.\");\n\n // Content bounds from the team shapes (interactions sit between them).\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const el of elementRegistry.getAll()) {\n if (!isTtElement(el)) continue;\n const s = el as unknown as { x: number; y: number; width: number; height: number };\n minX = Math.min(minX, s.x);\n minY = Math.min(minY, s.y);\n maxX = Math.max(maxX, s.x + s.width);\n maxY = Math.max(maxY, s.y + s.height);\n }\n if (!Number.isFinite(minX)) {\n minX = 0;\n minY = 0;\n maxX = 100;\n maxY = 100;\n }\n\n const x = minX - MARGIN;\n const y = minY - MARGIN;\n const width = maxX - minX + MARGIN * 2;\n const height = maxY - minY + MARGIN * 2;\n\n const clone = source.cloneNode(true) as SVGSVGElement;\n for (const name of CANVAS_ONLY_ATTRIBUTES) clone.removeAttribute(name);\n for (const node of clone.querySelectorAll(INTERACTION_CHROME_SELECTOR)) node.remove();\n for (const node of clone.querySelectorAll(TRANSIENT_CLASSES.map((name) => `.${name}`).join())) {\n node.classList.remove(...TRANSIENT_CLASSES);\n }\n\n clone.setAttribute(\"xmlns\", SVG_NAMESPACE);\n clone.setAttribute(\"viewBox\", `${x} ${y} ${width} ${height}`);\n clone.setAttribute(\"width\", String(Math.round(width)));\n clone.setAttribute(\"height\", String(Math.round(height)));\n\n // Neutralise pan/zoom: let the viewBox (above) drive the geometry.\n const viewport = clone.querySelector<SVGGElement>(\".viewport\");\n if (viewport) viewport.removeAttribute(\"transform\");\n\n const sheet = clone.ownerDocument.createElementNS(SVG_NAMESPACE, \"rect\");\n sheet.setAttribute(\"class\", \"tt-export-paper\");\n sheet.setAttribute(\"x\", String(x));\n sheet.setAttribute(\"y\", String(y));\n sheet.setAttribute(\"width\", String(width));\n sheet.setAttribute(\"height\", String(height));\n sheet.setAttribute(\"fill\", MIRAGON.weiss);\n clone.insertBefore(sheet, clone.firstChild);\n\n const svg = new XMLSerializer().serializeToString(clone);\n return { svg: '<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n' + svg };\n}\n","import { DIAGRAM_ROOT_ID, type ForeignFields } from \"@miragon/team-topologies-schema-model\";\n\n/** ID of the diagram-js root element holding the Team Topologies diagram. */\nexport const ROOT_ID = DIAGRAM_ROOT_ID;\n\nexport interface ImportWarning {\n readonly message: string;\n readonly elementId?: string;\n}\n\n/** Diagram-level metadata stashed on the root element. */\nexport interface RootBusinessObject {\n title: string;\n /** Document fields the modeler does not know, written back on export. */\n foreign?: ForeignFields;\n}\n","/**\n * Shared lifecycle & DI bootstrap for every Team Topologies viewer. Subclasses\n * only override `_getModules()`. The renderer\n * is framework-agnostic — mount it into any element (e.g. a VS Code webview).\n */\n\nimport Diagram from \"diagram-js/lib/Diagram\";\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 CommandStack from \"diagram-js/lib/command/CommandStack\";\nimport type { Root } from \"diagram-js/lib/model/Types\";\nimport type { FreeArea } from \"@miragon/modeler-api\";\nimport { documentIdProblems, type TtDocument } from \"@miragon/team-topologies-schema-model\";\nimport { saveSVG } from \"./io/saveSvg.js\";\nimport type TtImporter from \"./io/TtImporter.js\";\nimport type TtExporter from \"./io/TtExporter.js\";\nimport type TtViewport from \"./io/TtViewport.js\";\nimport { ROOT_ID, type ImportWarning, type RootBusinessObject } from \"./io/types.js\";\nimport type TtLabelEditing from \"./label-editing/TtLabelEditing.js\";\nimport type { Point } from \"./palette/TtPaletteProvider.js\";\n\n/**\n * Set on the canvas SVG while it holds focus that arrived by Tab. Mouse users never see a frame\n * around the whole viewport, which a plain `:focus-visible` ring would show after any shortcut.\n */\nconst CANVAS_KEYBOARD_FOCUS_CLASS = \"tt-canvas-keyboard-focus\";\n\nexport interface TtViewerOptions {\n /** Host element. When absent, a detached <div> is created (attach later). */\n container?: HTMLElement;\n width?: number | string;\n height?: number | string;\n /** Appended to the module list (extension point). */\n additionalModules?: ModuleDeclaration[];\n /**\n * Bind Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z and Cmd/Ctrl+Y to the canvas history (default true). Pass\n * false when the host owns the history (the VS Code document), so the keys reach it.\n */\n undoRedoKeys?: boolean | undefined;\n /**\n * Where Enter or Space on a creating palette entry places the element (guide §5.5): the centre\n * of the part of the canvas no chrome covers, given as its insets in px from the container's\n * edges (`{ insets }`) or as that centre in diagram coordinates (`{ center }`). Without it, the\n * centre of the visible canvas.\n */\n freeArea?: FreeArea | undefined;\n /**\n * @deprecated Since 0.12, the `@miragon/modeler-api` 1.2 name is `freeArea: { center }`; given\n * both, `freeArea` wins. Accepted for one more minor release.\n */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\nexport interface ImportOptions {\n /** Fit the diagram into view after the import (default true); hosts with own chrome fit it. */\n fit?: boolean | undefined;\n}\n\nexport type EventCallback<T = unknown> = (event: T) => void;\n\ntype RootWithMeta = Root & { businessObject?: RootBusinessObject };\n\nfunction sizeToCss(value: number | string): string {\n return typeof value === \"number\" ? `${value}px` : value;\n}\n\nexport abstract class TtBaseViewer {\n protected abstract _getModules(): ModuleDeclaration[];\n\n private _diagram: Diagram | undefined;\n private readonly _container: HTMLElement;\n private readonly _options: TtViewerOptions;\n\n constructor(options: TtViewerOptions = {}) {\n this._options = options;\n this._container = this._createContainer(options);\n }\n\n private _createContainer(options: TtViewerOptions): HTMLElement {\n const container = options.container ?? document.createElement(\"div\");\n container.classList.add(\"tt-djs-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 ttKeyboard: { undoRedoKeys: this._options.undoRedoKeys ?? true },\n ttPalette: {\n freeArea: this._options.freeArea,\n freeRectCenter: this._options.freeRectCenter,\n },\n });\n this._describeCanvas(this._diagram);\n }\n return this._diagram;\n }\n\n /**\n * Names the canvas. Its role stays the host's to give: the modeler shell makes it an\n * `application`, so screen readers pass the single-key commands through.\n */\n private _describeCanvas(diagram: Diagram): void {\n const canvasContainer = diagram.get<Canvas>(\"canvas\").getContainer();\n const svg = canvasContainer.querySelector<SVGSVGElement>(\":scope > svg\");\n if (!svg) return;\n svg.setAttribute(\"aria-label\", \"Team Topologies diagram\");\n\n const ownerDocument = canvasContainer.ownerDocument;\n let lastKeyWasTab = false;\n const onKeyDown = (event: KeyboardEvent) => {\n lastKeyWasTab = event.key === \"Tab\";\n };\n const onPointerDown = () => {\n lastKeyWasTab = false;\n svg.classList.remove(CANVAS_KEYBOARD_FOCUS_CLASS);\n };\n const onFocusIn = () => svg.classList.toggle(CANVAS_KEYBOARD_FOCUS_CLASS, lastKeyWasTab);\n const onFocusOut = () => svg.classList.remove(CANVAS_KEYBOARD_FOCUS_CLASS);\n ownerDocument.addEventListener(\"keydown\", onKeyDown, true);\n ownerDocument.addEventListener(\"pointerdown\", onPointerDown, true);\n svg.addEventListener(\"focusin\", onFocusIn);\n svg.addEventListener(\"focusout\", onFocusOut);\n diagram.get<EventBus>(\"eventBus\").on(\"diagram.destroy\", () => {\n ownerDocument.removeEventListener(\"keydown\", onKeyDown, true);\n ownerDocument.removeEventListener(\"pointerdown\", onPointerDown, true);\n });\n }\n\n /** Resolve a diagram-js service from the didi injector. */\n get<T>(name: string): T {\n return this._ensureDiagram().get<T>(name);\n }\n\n on<T = unknown>(event: string, callback: EventCallback<T>, priority = 1000): void {\n this.get<EventBus>(\"eventBus\").on(event, priority, callback as EventCallback);\n }\n\n off(event: string, callback: EventCallback): void {\n this.get<EventBus>(\"eventBus\").off(event, callback);\n }\n\n /**\n * Load a document into the canvas (replaces existing content) and, unless `fit: false`, fit it\n * into view. Clears the undo history without a change event: its commands point at the replaced\n * elements and would bring them back, and an import is no edit.\n *\n * Throws, before anything changes, for a document whose ids would collide on the canvas (see\n * `documentIdProblems`), so a rejected document leaves the previous one in place.\n */\n importDocument(doc: TtDocument, options: ImportOptions = {}): { warnings: ImportWarning[] } {\n const problems = documentIdProblems(doc);\n if (problems.length > 0) {\n throw new Error(\n problems.map(({ path, message }) => `${path.join(\".\")}: ${message}`).join(\"; \"),\n );\n }\n const diagram = this._ensureDiagram();\n const eventBus = diagram.get<EventBus>(\"eventBus\");\n const importer = diagram.get<TtImporter>(\"ttImporter\");\n const labelEditing = diagram.get<TtLabelEditing>(\"ttLabelEditing\", false);\n eventBus.fire(\"import.parse.start\", { document: doc });\n labelEditing?.suspend();\n diagram.get<CommandStack>(\"commandStack\", false)?.clear(false);\n importer.clear();\n const warnings = importer.import(doc);\n if (options.fit !== false) this._fit();\n eventBus.fire(\"import.done\", { warnings });\n labelEditing?.resumeAfterImport();\n return { warnings };\n }\n\n /**\n * Fit the whole diagram into the viewport, keeping the strip under the floating palette free\n * (88px at the top, 120px when the container is 760px wide or narrower).\n *\n * @deprecated Host chrome fits the diagram (the modeler shell's viewport, with the insets of the\n * chrome that is open); kept for hosts without it.\n */\n fitToView(): void {\n this._fit();\n }\n\n private _fit(): void {\n const viewport = this._ensureDiagram().get<TtViewport>(\"ttViewport\", false);\n if (viewport) viewport.fit();\n else this.get<Canvas>(\"canvas\").zoom(\"fit-viewport\");\n }\n\n /** Current canvas state as a canonical document. */\n exportDocument(): TtDocument {\n return this.get<TtExporter>(\"ttExporter\").export();\n }\n\n /**\n * Update diagram-level metadata (the title) on the root, outside the undo history.\n *\n * @deprecated Rename through `ttModeling.setTitle(title)`: one undo step that hosts see as a\n * change like any other.\n */\n setMeta(partial: Partial<RootBusinessObject>): void {\n const canvas = this.get<Canvas>(\"canvas\");\n let root: RootWithMeta | undefined;\n try {\n root = canvas.getRootElement() as RootWithMeta;\n } catch {\n return;\n }\n if (!root || root.id !== ROOT_ID) return;\n const current = root.businessObject ?? { title: \"Untitled team topology\" };\n root.businessObject = { ...current, ...partial };\n }\n\n /** Read diagram-level metadata (the title) from the root. */\n getMeta(): RootBusinessObject | undefined {\n try {\n const root = this.get<Canvas>(\"canvas\").getRootElement() as RootWithMeta;\n return root.businessObject;\n } catch {\n return undefined;\n }\n }\n\n /** Standalone, self-contained SVG snapshot. */\n saveSVG(): { svg: string } {\n return saveSVG(this.get<Canvas>(\"canvas\"), this.get<ElementRegistry>(\"elementRegistry\"));\n }\n\n /** Attach the container into `target`. */\n attachTo(target: Element): void {\n target.appendChild(this._container);\n this.get<Canvas>(\"canvas\").resized();\n }\n\n /** Detach the container from the DOM, preserving state. */\n detach(): void {\n this._container.remove();\n }\n\n clear(): void {\n this._ensureDiagram().clear();\n }\n\n destroy(): void {\n if (this._diagram) {\n this._diagram.destroy();\n this._diagram = undefined;\n }\n this._container.remove();\n }\n\n get container(): HTMLElement {\n return this._container;\n }\n}\n","/**\n * Creates diagram-js runtime elements carrying Team Topologies markers, from\n * canonical document elements (import) or from scratch (palette drag-to-create).\n * Teams, interaction glyphs, the flow arrow and annotations are shapes; the\n * annotation connector is the only connection.\n */\n\nimport type ElementFactory from \"diagram-js/lib/core/ElementFactory\";\nimport { getMid } from \"diagram-js/lib/layout/LayoutUtil\";\nimport {\n ANNOTATION_FIELDS,\n ANNOTATION_SPEC,\n FLOW_FIELDS,\n FLOW_SPEC,\n INTERACTION_FIELDS,\n INTERACTION_MODE_SPECS,\n TEAM_NODE_FIELDS,\n TEAM_TYPE_SPECS,\n associationId,\n foreignFields,\n newId,\n} from \"@miragon/team-topologies-schema-model\";\nimport type {\n FlowShape,\n InteractionMode,\n InteractionShape,\n TeamNode,\n TeamType,\n TextAnnotation,\n} from \"@miragon/team-topologies-schema-model\";\nimport type {\n TtAnnotation,\n TtAssociation,\n TtElement,\n TtFlow,\n TtInteraction,\n TtTeam,\n} from \"./di-types.js\";\n\nexport default class TtElementFactory {\n static $inject = [\"elementFactory\"];\n\n constructor(private readonly elementFactory: ElementFactory) {}\n\n /** A field the modeler does not know rides along on the shape, so the export writes it back. */\n private foreign(source: object, knownFields: readonly string[]): { ttForeign?: object } {\n const ttForeign = foreignFields(source, knownFields);\n return ttForeign ? { ttForeign } : {};\n }\n\n // --- from canonical document elements (import) -------------------------\n\n createTeam(node: TeamNode): TtTeam {\n return this.elementFactory.createShape({\n id: node.id,\n x: node.position.x,\n y: node.position.y,\n width: node.size.width,\n height: node.size.height,\n ttKind: \"team\",\n teamType: node.type,\n ttLabel: node.label,\n ...(node.description ? { description: node.description } : {}),\n ...(node.fill ? { fill: node.fill } : {}),\n ...(node.stroke ? { stroke: node.stroke } : {}),\n ...this.foreign(node, TEAM_NODE_FIELDS),\n } as Partial<TtTeam>) as unknown as TtTeam;\n }\n\n createInteraction(shape: InteractionShape): TtInteraction {\n return this.elementFactory.createShape({\n id: shape.id,\n x: shape.position.x,\n y: shape.position.y,\n width: shape.size.width,\n height: shape.size.height,\n ttKind: \"interaction\",\n mode: shape.mode,\n ...(shape.label ? { ttLabel: shape.label } : {}),\n ...(shape.fill ? { fill: shape.fill } : {}),\n ...(shape.stroke ? { stroke: shape.stroke } : {}),\n ...this.foreign(shape, INTERACTION_FIELDS),\n } as Partial<TtInteraction>) as unknown as TtInteraction;\n }\n\n createFlow(shape: FlowShape): TtFlow {\n return this.elementFactory.createShape({\n id: shape.id,\n x: shape.position.x,\n y: shape.position.y,\n width: shape.size.width,\n height: shape.size.height,\n ttKind: \"flow\",\n ...(shape.label ? { ttLabel: shape.label } : {}),\n ...this.foreign(shape, FLOW_FIELDS),\n } as Partial<TtFlow>) as unknown as TtFlow;\n }\n\n createAnnotation(annotation: TextAnnotation): TtAnnotation {\n return this.elementFactory.createShape({\n id: annotation.id,\n x: annotation.position.x,\n y: annotation.position.y,\n width: annotation.size.width,\n height: annotation.size.height,\n ttKind: \"annotation\",\n ...(annotation.text ? { ttLabel: annotation.text } : {}),\n ...this.foreign(annotation, ANNOTATION_FIELDS),\n } as Partial<TtAnnotation>) as unknown as TtAnnotation;\n }\n\n /**\n * The connector of an imported, attached annotation. Its id is derived from\n * the annotation (connectors aren't stored in the document), so re-importing\n * the same document yields the same id.\n */\n createAssociation(annotation: TtAnnotation, target: TtElement): TtAssociation {\n return this.elementFactory.createConnection({\n id: associationId(annotation.id),\n ttKind: \"association\",\n source: annotation,\n target,\n waypoints: [getMid(annotation), getMid(target)],\n } as Partial<TtAssociation>) as unknown as TtAssociation;\n }\n\n // --- fresh, not-yet-placed shapes (palette / context-pad create) -------\n //\n // These set an explicit model-style id (`team_…`/`int_…`/`flow_…`, matching\n // the model package's factory). We must NOT fall back to diagram-js' own\n // auto-id: its counter starts at `shape_12` and is not advanced past ids that\n // come in via import, so a re-imported `shape_N` (an element created in a\n // previous session, then autosaved) collides with the next palette create —\n // the first placement after a reload then throws \"element already exists\".\n\n createNewTeam(type: TeamType, label?: string): TtTeam {\n const spec = TEAM_TYPE_SPECS[type];\n return this.elementFactory.createShape({\n id: newId(\"team\"),\n width: spec.defaultSize.width,\n height: spec.defaultSize.height,\n ttKind: \"team\",\n teamType: type,\n ttLabel: label ?? spec.label,\n } as Partial<TtTeam>) as unknown as TtTeam;\n }\n\n createNewInteraction(mode: InteractionMode): TtInteraction {\n const spec = INTERACTION_MODE_SPECS[mode];\n return this.elementFactory.createShape({\n id: newId(\"int\"),\n width: spec.defaultSize.width,\n height: spec.defaultSize.height,\n ttKind: \"interaction\",\n mode,\n } as Partial<TtInteraction>) as unknown as TtInteraction;\n }\n\n createNewFlow(): TtFlow {\n return this.elementFactory.createShape({\n id: newId(\"flow\"),\n width: FLOW_SPEC.defaultSize.width,\n height: FLOW_SPEC.defaultSize.height,\n ttKind: \"flow\",\n ttLabel: FLOW_SPEC.label,\n } as Partial<TtFlow>) as unknown as TtFlow;\n }\n\n createNewAnnotation(text?: string): TtAnnotation {\n return this.elementFactory.createShape({\n id: newId(\"ann\"),\n width: ANNOTATION_SPEC.defaultSize.width,\n height: ANNOTATION_SPEC.defaultSize.height,\n ttKind: \"annotation\",\n ...(text ? { ttLabel: text } : {}),\n } as Partial<TtAnnotation>) as unknown as TtAnnotation;\n }\n\n /** A not-yet-connected association; modeling sets its ends and waypoints. */\n createNewAssociation(): TtAssociation {\n return this.elementFactory.createConnection({\n id: newId(\"assoc\"),\n ttKind: \"association\",\n } as Partial<TtAssociation>) as unknown as TtAssociation;\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtElementFactory from \"./TtElementFactory.js\";\n\n/** Element factory with Team Topologies defaults. */\nexport const ttModelModule: ModuleDeclaration = {\n ttElementFactory: [\"type\", TtElementFactory],\n};\n\nexport { default as TtElementFactory } from \"./TtElementFactory.js\";\nexport * from \"./di-types.js\";\n","/**\n * Shared rendering constants (typography, accent, priorities) — Miragon corporate identity.\n * Colours are derived from the single source of truth in `theme/palette.ts` (`MIRAGON`), which\n * mirrors the vendored `--cd-*` brand tokens.\n */\n\nimport { MIRAGON } from \"../theme/index.js\";\n\n/** BaseRenderer default priority is 1000; 1500 wins the render.shape/connection event. */\nexport const TT_RENDER_PRIORITY = 1500;\n\nexport const INK = MIRAGON.schwarz;\n/** Secondary canvas text (e.g. the flow-of-change label), ≥ 4.5:1 on the paper surround. */\nexport const INK_MUTED = MIRAGON.textLeise;\n/** Structural strokes that recede (annotation bracket, association connector), ≥ 3:1. */\nexport const STROKE_MUTED = MIRAGON.kontur;\n\nexport const FONT = {\n /**\n * Set directly as the `font-family` attribute on every SVG <text> (canvas\n * labels and therefore the SVG export too) — not inherited from a CSS\n * container. Prefers the self-hosted Miragon typeface Geist (registered as\n * 'Geist Variable' by @fontsource-variable/geist, with 'Geist' as a fallback\n * name), and falls back to a system sans when the host hasn't loaded it (e.g.\n * an exported SVG opened standalone).\n */\n family:\n \"'Geist Variable', 'Geist', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif\",\n label: 13.5,\n small: 11,\n annotation: 12,\n} as const;\n","/**\n * Where and how each element's text is laid out. Shared by the SVG renderer and\n * the inline label editor, so the editor sits exactly on top of the rendered\n * label and uses the same typography.\n */\n\nimport { INTERACTION_MODE_SPECS, TEAM_TYPE_SPECS } from \"@miragon/team-topologies-schema-model\";\nimport {\n isTtAnnotation,\n isTtFlow,\n isTtInteraction,\n type TtElement,\n type TtInteraction,\n type TtTeam,\n} from \"../model/di-types.js\";\nimport { MIRAGON } from \"../theme/index.js\";\nimport { FONT, INK, INK_MUTED } from \"./styles.js\";\n\n/** Horizontal padding between a shape's outline and its centred label. */\nconst LABEL_INSET = 10;\nconst ANNOTATION_PADDING = { left: 10, right: 6, top: 6, bottom: 6 };\nexport const LINE_HEIGHT = 1.2;\n\nexport interface LabelBox {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface LabelLayout {\n /** The area the text is laid out in, relative to the element's top-left corner. */\n box: LabelBox;\n /** `center`: centred both ways (shape labels). `left-top`: flows from the top-left (annotations). */\n align: \"center\" | \"left-top\";\n fontSize: number;\n fontWeight: string;\n letterSpacing?: string;\n fill: string;\n}\n\n/** WCAG AA for body text. */\nconst MIN_TEXT_CONTRAST = 4.5;\n\ntype Rgb = readonly [number, number, number];\n\nfunction parseHexColour(colour: unknown): Rgb | undefined {\n if (typeof colour !== \"string\") return undefined;\n const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(colour.trim());\n if (!match) return undefined;\n const hex =\n match[1].length === 3 ? [...match[1]].map((digit) => digit + digit).join(\"\") : match[1];\n const channel = (offset: number) => parseInt(hex.slice(offset, offset + 2), 16);\n return [channel(0), channel(2), channel(4)];\n}\n\nfunction blendOver(colour: Rgb, backdrop: Rgb, opacity: number): Rgb {\n const mix = (index: 0 | 1 | 2) =>\n Math.round(colour[index] * opacity + backdrop[index] * (1 - opacity));\n return [mix(0), mix(1), mix(2)];\n}\n\nfunction relativeLuminance([red, green, blue]: Rgb): number {\n const linear = (channel: number) => {\n const value = channel / 255;\n return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;\n };\n return 0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue);\n}\n\nfunction contrastRatio(first: Rgb, second: Rgb): number {\n const [lighter, darker] = [relativeLuminance(first), relativeLuminance(second)].sort(\n (a, b) => b - a,\n );\n return (lighter + 0.05) / (darker + 0.05);\n}\n\n/**\n * Label colour for text on a shape filled with `fill` at `opacity` over the white sheet:\n * schwarz while it stays readable (every official notation fill), weiss on dark custom fills.\n */\nexport function readableTextColour(fill: string, opacity = 1): string {\n const fillRgb = parseHexColour(fill);\n const ink = parseHexColour(INK);\n const paper = parseHexColour(MIRAGON.weiss);\n if (!fillRgb || !ink || !paper) return INK;\n const background = blendOver(fillRgb, paper, opacity);\n const inkContrast = contrastRatio(ink, background);\n if (inkContrast >= MIN_TEXT_CONTRAST) return INK;\n return contrastRatio(paper, background) > inkContrast ? MIRAGON.weiss : INK;\n}\n\nfunction shapeTextColour(element: TtTeam | TtInteraction): string {\n if (isTtInteraction(element)) {\n const spec = INTERACTION_MODE_SPECS[element.mode] ?? INTERACTION_MODE_SPECS.collaboration;\n return readableTextColour(element.fill ?? spec.fill, spec.opacity);\n }\n const spec = TEAM_TYPE_SPECS[element.teamType] ?? TEAM_TYPE_SPECS[\"stream-aligned\"];\n return readableTextColour(element.fill ?? spec.fill);\n}\n\n/** Width of the flow arrow's head; the label stays on the shaft. */\nexport function flowHeadWidth(width: number, height: number): number {\n return Math.min(width * 0.16, height * 1.1);\n}\n\nexport function labelLayout(element: TtElement): LabelLayout {\n const width = Math.max(element.width, 1);\n const height = Math.max(element.height, 1);\n\n if (isTtAnnotation(element)) {\n return {\n box: {\n x: ANNOTATION_PADDING.left,\n y: ANNOTATION_PADDING.top,\n width: Math.max(width - ANNOTATION_PADDING.left - ANNOTATION_PADDING.right, 1),\n height: Math.max(height - ANNOTATION_PADDING.top - ANNOTATION_PADDING.bottom, 1),\n },\n align: \"left-top\",\n fontSize: FONT.annotation,\n fontWeight: \"400\",\n fill: INK,\n };\n }\n\n if (isTtFlow(element)) {\n const shaftWidth = width - flowHeadWidth(width, height);\n return {\n box: { x: LABEL_INSET, y: 0, width: shaftWidth - 2 * LABEL_INSET, height },\n align: \"center\",\n fontSize: FONT.small,\n fontWeight: \"600\",\n letterSpacing: \"0.06em\",\n fill: INK_MUTED,\n };\n }\n\n return {\n box: { x: LABEL_INSET, y: 0, width: width - 2 * LABEL_INSET, height },\n align: \"center\",\n fontSize: isTtInteraction(element) ? FONT.small : FONT.label,\n fontWeight: \"600\",\n fill: shapeTextColour(element),\n };\n}\n\n/**\n * Greedy word-wrap into lines that roughly fit `maxWidth` at the font size.\n * Explicit line breaks are kept. Character-count based (not measured), so the\n * result is identical on every platform and exported SVGs stay stable.\n */\nexport function wrapLabel(text: string, maxWidth: number, fontSize: number): string[] {\n const maxChars = Math.max(4, Math.floor(maxWidth / (fontSize * 0.58)));\n const paragraphs = text.split(/\\r?\\n/);\n const lines: string[] = [];\n for (const paragraph of paragraphs) {\n const words = paragraph.split(/\\s+/).filter(Boolean);\n let current = \"\";\n for (const word of words) {\n const candidate = current ? `${current} ${word}` : word;\n if (candidate.length > maxChars && current) {\n lines.push(current);\n current = word;\n } else {\n current = candidate;\n }\n }\n lines.push(current);\n }\n while (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n while (lines.length > 0 && lines[0] === \"\") lines.shift();\n return lines;\n}\n","/**\n * SVG rendering of the Team Topologies notation (BaseRenderer subclass):\n * - teams: SOLID resizable boxes (label wrapped inside), distinguished by shape\n * as well as colour;\n * - interactions: DASHED, 50%-transparent glyphs (collaboration = parallelogram,\n * x-as-a-service = triangle, facilitating = circle) laid over team boundaries;\n * - flow: a dashed \"flow of change\" arrow;\n * - annotations: a BPMN-style open bracket with free text, and the dashed\n * association connecting an annotation to the element it is attached to.\n *\n * Colours/shapes come from the single notation source (`@miragon/team-topologies-schema-model`).\n */\n\nimport BaseRenderer from \"diagram-js/lib/draw/BaseRenderer\";\nimport { append as svgAppend, create as svgCreate, attr as svgAttr } from \"tiny-svg\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type { ConnectionLike, ElementLike, ShapeLike } from \"diagram-js/lib/model/Types\";\nimport {\n FLOW_SPEC,\n INTERACTION_MODE_SPECS,\n TEAM_TYPE_SPECS,\n dashArray,\n} from \"@miragon/team-topologies-schema-model\";\nimport { MIRAGON } from \"../theme/index.js\";\nimport { FONT, STROKE_MUTED, TT_RENDER_PRIORITY } from \"./styles.js\";\nimport {\n LINE_HEIGHT,\n flowHeadWidth,\n labelLayout,\n wrapLabel,\n type LabelLayout,\n} from \"./label-layout.js\";\nimport {\n isTtAnnotation,\n isTtAssociation,\n isTtElement,\n isTtFlow,\n isTtInteraction,\n isTtTeam,\n type TtAnnotation,\n type TtFlow,\n type TtInteraction,\n type TtTeam,\n} from \"../model/di-types.js\";\n\ntype Attrs = Record<string, string | number>;\n\nexport default class TeamTopologiesRenderer extends BaseRenderer {\n static $inject = [\"eventBus\"];\n\n constructor(eventBus: EventBus) {\n super(eventBus, TT_RENDER_PRIORITY);\n }\n\n override canRender(element: ElementLike): boolean {\n return isTtElement(element) || isTtAssociation(element);\n }\n\n override drawShape(visuals: SVGElement, element: ShapeLike): SVGElement {\n if (isTtTeam(element)) return this.drawTeam(visuals, element);\n if (isTtInteraction(element)) return this.drawInteraction(visuals, element);\n if (isTtFlow(element)) return this.drawFlow(visuals, element);\n if (isTtAnnotation(element)) return this.drawAnnotation(visuals, element);\n const rect = svgAttr(svgCreate(\"rect\"), {\n width: element.width,\n height: element.height,\n fill: MIRAGON.linie,\n });\n svgAppend(visuals, rect);\n return rect;\n }\n\n override drawConnection(visuals: SVGElement, connection: ConnectionLike): SVGElement {\n const line = svgAttr(svgCreate(\"path\"), {\n d: waypointsPath(connection.waypoints),\n fill: \"none\",\n stroke: STROKE_MUTED,\n \"stroke-width\": 1.5,\n \"stroke-dasharray\": \"4 4\",\n \"stroke-linecap\": \"round\",\n });\n svgAppend(visuals, line);\n return line;\n }\n\n override getShapePath(shape: ShapeLike): string {\n const { x, y, width, height } = shape;\n return `M${x},${y}l${width},0l0,${height}l${-width},0z`;\n }\n\n override getConnectionPath(connection: ConnectionLike): string {\n return waypointsPath(connection.waypoints);\n }\n\n // --- teams ---------------------------------------------------------------\n\n private drawTeam(visuals: SVGElement, team: TtTeam): SVGElement {\n const spec = TEAM_TYPE_SPECS[team.teamType] ?? TEAM_TYPE_SPECS[\"stream-aligned\"];\n const w = Math.max(team.width, 1);\n const h = Math.max(team.height, 1);\n const sw = spec.strokeWidth;\n const dash = dashArray(spec.strokeStyle, sw);\n const outline = this.teamOutline(spec.shape, w, h, sw, {\n fill: team.fill ?? spec.fill,\n stroke: team.stroke ?? spec.stroke,\n \"stroke-width\": sw,\n ...(dash ? { \"stroke-dasharray\": dash } : {}),\n \"stroke-linejoin\": \"round\",\n });\n svgAppend(visuals, outline);\n this.appendLabel(visuals, team.ttLabel ?? \"\", labelLayout(team));\n return outline;\n }\n\n private teamOutline(kind: string, w: number, h: number, sw: number, attrs: Attrs): SVGElement {\n const i = sw / 2;\n const iw = w - sw;\n const ih = h - sw;\n if (kind === \"octagon\") {\n const c = Math.min(iw, ih) * 0.29;\n return svgAttr(svgCreate(\"polygon\"), { points: octagon(i, iw, ih, c), ...attrs });\n }\n const rx = kind === \"rect\" ? 4 : Math.min(20, ih / 2, iw / 2);\n return svgAttr(svgCreate(\"rect\"), { x: i, y: i, width: iw, height: ih, rx, ry: rx, ...attrs });\n }\n\n // --- interactions --------------------------------------------------------\n\n private drawInteraction(visuals: SVGElement, el: TtInteraction): SVGElement {\n const spec = INTERACTION_MODE_SPECS[el.mode] ?? INTERACTION_MODE_SPECS.collaboration;\n const w = Math.max(el.width, 1);\n const h = Math.max(el.height, 1);\n const sw = 2;\n const i = sw / 2;\n const common: Attrs = {\n fill: el.fill ?? spec.fill,\n \"fill-opacity\": spec.opacity,\n stroke: el.stroke ?? spec.stroke,\n \"stroke-width\": sw,\n \"stroke-dasharray\": dashArray(spec.strokeStyle, sw) || \"6 4\",\n \"stroke-linejoin\": \"round\",\n };\n\n let glyph: SVGElement;\n if (spec.shape === \"circle\") {\n glyph = svgAttr(svgCreate(\"ellipse\"), {\n cx: w / 2,\n cy: h / 2,\n rx: (w - sw) / 2,\n ry: (h - sw) / 2,\n ...common,\n });\n } else if (spec.shape === \"triangle\") {\n // Point up — the tip indicates the direction the service is provided.\n const pts = `${w / 2},${i} ${w - i},${h - i} ${i},${h - i}`;\n glyph = svgAttr(svgCreate(\"polygon\"), { points: pts, ...common });\n } else {\n const skew = Math.min(w * 0.26, h * 0.85);\n const pts = `${i + skew},${i} ${w - i},${i} ${w - i - skew},${h - i} ${i},${h - i}`;\n glyph = svgAttr(svgCreate(\"polygon\"), { points: pts, ...common });\n }\n svgAppend(visuals, glyph);\n this.appendLabel(visuals, el.ttLabel ?? \"\", labelLayout(el));\n return glyph;\n }\n\n // --- flow of change ------------------------------------------------------\n\n private drawFlow(visuals: SVGElement, el: TtFlow): SVGElement {\n const w = Math.max(el.width, 1);\n const h = Math.max(el.height, 1);\n const sw = FLOW_SPEC.strokeWidth;\n const i = sw / 2;\n const head = flowHeadWidth(w, h);\n const shaft = h * 0.5;\n const top = (h - shaft) / 2;\n const bot = top + shaft;\n const pts = [\n [i, top],\n [w - head, top],\n [w - head, i],\n [w - i, h / 2],\n [w - head, h - i],\n [w - head, bot],\n [i, bot],\n ]\n .map((p) => p.join(\",\"))\n .join(\" \");\n const arrow = svgAttr(svgCreate(\"polygon\"), {\n points: pts,\n fill: \"none\",\n stroke: FLOW_SPEC.stroke,\n \"stroke-width\": sw,\n \"stroke-dasharray\": dashArray(FLOW_SPEC.strokeStyle, sw) || \"6 4\",\n \"stroke-linejoin\": \"round\",\n });\n svgAppend(visuals, arrow);\n this.appendLabel(visuals, el.ttLabel ?? \"\", labelLayout(el));\n return arrow;\n }\n\n // --- annotations ---------------------------------------------------------\n\n private drawAnnotation(visuals: SVGElement, el: TtAnnotation): SVGElement {\n const w = Math.max(el.width, 1);\n const h = Math.max(el.height, 1);\n const sw = 1.5;\n const i = sw / 2;\n const arm = Math.min(14, w / 2);\n const bracket = svgAttr(svgCreate(\"path\"), {\n d: `M${arm},${i} L${i},${i} L${i},${h - i} L${arm},${h - i}`,\n fill: \"none\",\n stroke: STROKE_MUTED,\n \"stroke-width\": sw,\n \"stroke-linejoin\": \"round\",\n });\n svgAppend(visuals, bracket);\n this.appendLabel(visuals, el.ttLabel ?? \"\", labelLayout(el));\n return bracket;\n }\n\n // --- shared label rendering (wrapped, no halo) ---------------------------\n\n private appendLabel(visuals: SVGElement, text: string, layout: LabelLayout): void {\n const { box, fontSize } = layout;\n const lines = wrapLabel(text, box.width, fontSize);\n const lineHeight = fontSize * LINE_HEIGHT;\n const centred = layout.align === \"center\";\n const x = centred ? box.x + box.width / 2 : box.x;\n const startY = centred\n ? box.y + box.height / 2 - ((lines.length - 1) * lineHeight) / 2\n : box.y + lineHeight / 2;\n lines.forEach((ln, idx) => {\n if (!ln) return;\n const t = svgAttr(svgCreate(\"text\"), {\n x,\n y: startY + idx * lineHeight,\n \"font-family\": FONT.family,\n \"font-size\": fontSize,\n fill: layout.fill,\n \"text-anchor\": centred ? \"middle\" : \"start\",\n \"dominant-baseline\": \"central\",\n \"font-weight\": layout.fontWeight,\n ...(layout.letterSpacing ? { \"letter-spacing\": layout.letterSpacing } : {}),\n });\n t.textContent = ln;\n svgAppend(visuals, t);\n });\n }\n}\n\n// --- helpers ---------------------------------------------------------------\n\nfunction octagon(i: number, w: number, h: number, c: number): string {\n return [\n [i + c, i],\n [i + w - c, i],\n [i + w, i + c],\n [i + w, i + h - c],\n [i + w - c, i + h],\n [i + c, i + h],\n [i, i + h - c],\n [i, i + c],\n ]\n .map((p) => p.join(\",\"))\n .join(\" \");\n}\n\nfunction waypointsPath(waypoints: ReadonlyArray<{ x: number; y: number }>): string {\n return waypoints.map((point, idx) => `${idx === 0 ? \"M\" : \"L\"}${point.x},${point.y}`).join(\" \");\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport CroppingConnectionDocking from \"diagram-js/lib/layout/CroppingConnectionDocking\";\nimport TeamTopologiesRenderer from \"./TeamTopologiesRenderer.js\";\n\n/**\n * SVG rendering of all Team Topologies element types (BaseRenderer, priority\n * 1500), plus the docking that crops annotation connectors to the outlines of\n * the shapes they join.\n */\nexport const ttDrawModule: ModuleDeclaration = {\n __init__: [\"ttRenderer\"],\n ttRenderer: [\"type\", TeamTopologiesRenderer],\n connectionDocking: [\"type\", CroppingConnectionDocking],\n};\n\nexport { default as TeamTopologiesRenderer } from \"./TeamTopologiesRenderer.js\";\n","/**\n * Bridges the canonical `TtDocument` into the diagram-js canvas. Stacking order\n * (back → front) is flows, teams, interactions, annotations, so the translucent\n * interaction glyphs read on top of the team boxes they overlay. Attached\n * annotations get their association connector last, once both ends exist.\n */\n\nimport 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 ConnectionDocking from \"diagram-js/lib/layout/ConnectionDocking\";\nimport type { Root } from \"diagram-js/lib/model/Types\";\nimport {\n DOCUMENT_FIELDS,\n foreignFields,\n type TtDocument,\n} from \"@miragon/team-topologies-schema-model\";\nimport { isTtAnnotation, isTtElement, type TtAnnotation } from \"../model/di-types.js\";\nimport type TtElementFactory from \"../model/TtElementFactory.js\";\nimport { ROOT_ID, type ImportWarning, type RootBusinessObject } from \"./types.js\";\n\ntype RootWithMeta = Root & { businessObject?: RootBusinessObject };\n\nexport default class TtImporter {\n static $inject = [\n \"canvas\",\n \"elementFactory\",\n \"ttElementFactory\",\n \"eventBus\",\n \"elementRegistry\",\n \"connectionDocking\",\n ];\n\n constructor(\n private readonly canvas: Canvas,\n private readonly elementFactory: ElementFactory,\n private readonly factory: TtElementFactory,\n private readonly eventBus: EventBus,\n private readonly elementRegistry: ElementRegistry,\n private readonly connectionDocking: ConnectionDocking,\n ) {}\n\n import(doc: TtDocument): ImportWarning[] {\n const warnings: ImportWarning[] = [];\n this.eventBus.fire(\"import.render.start\", { document: doc });\n\n let existing: RootWithMeta | undefined;\n try {\n existing = this.canvas.getRootElement() as RootWithMeta;\n } catch {\n existing = undefined;\n }\n let root: RootWithMeta;\n if (existing && existing.id === ROOT_ID) {\n root = existing;\n } else {\n root = this.elementFactory.createRoot({ id: ROOT_ID }) as RootWithMeta;\n this.canvas.setRootElement(root);\n }\n const foreign = foreignFields(doc, DOCUMENT_FIELDS);\n root.businessObject = { title: doc.title, ...(foreign ? { foreign } : {}) };\n\n // Back → front: flows, teams, interactions, annotations.\n for (const flow of doc.flows) {\n this.canvas.addShape(this.factory.createFlow(flow), root);\n }\n for (const node of doc.nodes) {\n this.canvas.addShape(this.factory.createTeam(node), root);\n }\n for (const interaction of doc.interactions) {\n this.canvas.addShape(this.factory.createInteraction(interaction), root);\n }\n for (const annotation of doc.annotations) {\n this.canvas.addShape(this.factory.createAnnotation(annotation), root);\n }\n for (const annotation of doc.annotations) {\n if (!annotation.attachedTo) continue;\n const source = this.elementRegistry.get(annotation.id) as TtAnnotation;\n const target = this.elementRegistry.get(annotation.attachedTo);\n if (!isTtElement(target) || isTtAnnotation(target)) {\n warnings.push({\n message: `Annotation \"${annotation.id}\" is attached to unknown element \"${annotation.attachedTo}\"; its connector was dropped.`,\n elementId: annotation.id,\n });\n continue;\n }\n const association = this.factory.createAssociation(source, target);\n association.waypoints = this.connectionDocking.getCroppedWaypoints(association);\n this.canvas.addConnection(association, root);\n }\n\n this.eventBus.fire(\"import.render.done\", { warnings });\n return warnings;\n }\n\n /**\n * Removes every element (for re-import). Roots stay: besides the diagram's own root, diagram-js\n * creates an implicit one when something asks for a root before the first import.\n */\n clear(): void {\n const elements = this.elementRegistry.getAll().filter((el) => Boolean(el.parent));\n const connections = elements.filter((el) => \"waypoints\" in el);\n const shapes = elements.filter((el) => !(\"waypoints\" in el));\n for (const connection of connections) this.canvas.removeConnection(connection.id);\n for (const shape of shapes) {\n try {\n this.canvas.removeShape(shape.id);\n } catch {\n // already removed — ignore\n }\n }\n }\n}\n","/**\n * Rebuilds a canonical `TtDocument` from the diagram-js runtime model. Position\n * and size truth are the live `x/y/width/height`; editable fields (label, type,\n * mode, colours) are read from the runtime properties. An annotation's\n * `attachedTo` comes from its association connection.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type ElementRegistry from \"diagram-js/lib/core/ElementRegistry\";\nimport type { Root } from \"diagram-js/lib/model/Types\";\nimport {\n ANNOTATION_FIELDS,\n DOCUMENT_FIELDS,\n DOCUMENT_VERSION,\n FLOW_FIELDS,\n INTERACTION_FIELDS,\n TEAM_NODE_FIELDS,\n withForeignFields,\n} from \"@miragon/team-topologies-schema-model\";\nimport type {\n FlowShape,\n InteractionShape,\n TeamNode,\n TextAnnotation,\n TtDocument,\n} from \"@miragon/team-topologies-schema-model\";\nimport {\n isTtAnnotation,\n isTtAssociation,\n isTtFlow,\n isTtInteraction,\n isTtTeam,\n type TtAnnotation,\n} from \"../model/di-types.js\";\nimport { ROOT_ID, type RootBusinessObject } from \"./types.js\";\n\nexport default class TtExporter {\n static $inject = [\"elementRegistry\", \"canvas\"];\n\n constructor(\n private readonly elementRegistry: ElementRegistry,\n private readonly canvas: Canvas,\n ) {}\n\n export(): TtDocument {\n let meta: RootBusinessObject | undefined;\n try {\n const root = this.canvas.getRootElement() as Root & {\n businessObject?: RootBusinessObject;\n };\n meta = root.businessObject;\n } catch {\n meta = undefined;\n }\n\n const nodes: TeamNode[] = [];\n const interactions: InteractionShape[] = [];\n const flows: FlowShape[] = [];\n const annotations: TextAnnotation[] = [];\n\n for (const el of this.elementRegistry.getAll()) {\n if (el.id === ROOT_ID) continue;\n const geom = el as unknown as { x: number; y: number; width: number; height: number };\n const position = { x: geom.x, y: geom.y };\n const size = { width: geom.width, height: geom.height };\n\n if (isTtTeam(el)) {\n nodes.push(\n withForeignFields(\n {\n id: el.id,\n type: el.teamType,\n label: el.ttLabel ?? \"\",\n position,\n size,\n ...(el.description ? { description: el.description } : {}),\n ...(el.fill ? { fill: el.fill } : {}),\n ...(el.stroke ? { stroke: el.stroke } : {}),\n },\n el.ttForeign,\n TEAM_NODE_FIELDS,\n ),\n );\n } else if (isTtInteraction(el)) {\n interactions.push(\n withForeignFields(\n {\n id: el.id,\n mode: el.mode,\n position,\n size,\n ...(el.ttLabel ? { label: el.ttLabel } : {}),\n ...(el.fill ? { fill: el.fill } : {}),\n ...(el.stroke ? { stroke: el.stroke } : {}),\n },\n el.ttForeign,\n INTERACTION_FIELDS,\n ),\n );\n } else if (isTtFlow(el)) {\n flows.push(\n withForeignFields(\n {\n id: el.id,\n position,\n size,\n ...(el.ttLabel ? { label: el.ttLabel } : {}),\n },\n el.ttForeign,\n FLOW_FIELDS,\n ),\n );\n } else if (isTtAnnotation(el)) {\n const attachedTo = attachedElementId(el);\n annotations.push(\n withForeignFields(\n {\n id: el.id,\n text: el.ttLabel ?? \"\",\n position,\n size,\n ...(attachedTo ? { attachedTo } : {}),\n },\n el.ttForeign,\n ANNOTATION_FIELDS,\n ),\n );\n }\n }\n\n return withForeignFields(\n {\n version: DOCUMENT_VERSION,\n title: meta?.title ?? \"Untitled team topology\",\n nodes,\n interactions,\n flows,\n annotations,\n },\n meta?.foreign,\n DOCUMENT_FIELDS,\n );\n }\n}\n\nfunction attachedElementId(annotation: TtAnnotation): string | undefined {\n const connections = [...annotation.outgoing, ...annotation.incoming];\n const association = connections.find(isTtAssociation);\n if (!association) return undefined;\n const other = association.source === annotation ? association.target : association.source;\n return other?.id;\n}\n","/**\n * Fits the diagram into the visible canvas. Unlike diagram-js `fit-viewport`, it keeps the\n * strip under the floating palette free, so no element starts hidden behind it.\n *\n * @deprecated Host chrome fits the diagram (the modeler shell's viewport, with the insets of the\n * chrome that is open and never above 100 %); kept for hosts without it.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type ElementRegistry from \"diagram-js/lib/core/ElementRegistry\";\n\n/** Up to this container width the palette sits on its own row below the host's top chrome. */\nconst NARROW_LAYOUT_MAX_WIDTH = 760;\n\nconst TOP_INSET = 88;\nconst TOP_INSET_NARROW = 120;\nconst PADDING = 56;\nconst SIDE_PADDING_NARROW = 24;\n/** Guide §5.9: a fit never zooms past 100 %, as the shell's fit does. */\nconst MAX_FIT_ZOOM = 1;\n\ninterface Bounds {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n}\n\nexport default class TtViewport {\n static $inject = [\"canvas\", \"elementRegistry\"];\n\n constructor(\n private readonly canvas: Canvas,\n private readonly elementRegistry: ElementRegistry,\n ) {}\n\n /** Fit every element into view, zooming in no further than 100 %. */\n fit(): void {\n const bounds = this.contentBounds();\n if (!bounds) return;\n\n const rect = this.canvas.getContainer().getBoundingClientRect();\n const viewportWidth = rect.width;\n const viewportHeight = rect.height;\n if (!viewportWidth || !viewportHeight) {\n this.canvas.zoom(\"fit-viewport\");\n return;\n }\n\n const narrow = viewportWidth <= NARROW_LAYOUT_MAX_WIDTH;\n const topInset = narrow ? TOP_INSET_NARROW : TOP_INSET;\n const sidePadding = narrow ? SIDE_PADDING_NARROW : PADDING;\n const contentWidth = Math.max(bounds.maxX - bounds.minX, 1);\n const contentHeight = Math.max(bounds.maxY - bounds.minY, 1);\n const scale = Math.min(\n (viewportWidth - 2 * sidePadding) / contentWidth,\n (viewportHeight - topInset - PADDING) / contentHeight,\n MAX_FIT_ZOOM,\n );\n if (!(scale > 0)) {\n this.canvas.zoom(\"fit-viewport\");\n return;\n }\n this.canvas.viewbox({\n x: bounds.minX + contentWidth / 2 - viewportWidth / 2 / scale,\n y: this.viewboxTop(bounds, contentHeight, scale, viewportHeight, topInset, narrow),\n width: viewportWidth / scale,\n height: viewportHeight / scale,\n });\n }\n\n /**\n * On a narrow (portrait) canvas the content is centred in the free band below the palette: the\n * band is tall, and a diagram pinned to its top would slide under the top chrome on the first\n * zoom step around the viewport centre. Wider hosts keep it at the top, because their lower left\n * corner tends to hold an overlay of their own, such as a legend.\n */\n private viewboxTop(\n bounds: Bounds,\n contentHeight: number,\n scale: number,\n viewportHeight: number,\n topInset: number,\n narrow: boolean,\n ): number {\n if (!narrow) return bounds.minY - topInset / scale;\n const freeHeight = viewportHeight - topInset - PADDING;\n const slack = Math.max(0, freeHeight - contentHeight * scale);\n return bounds.minY - (topInset + slack / 2) / scale;\n }\n\n private contentBounds(): Bounds | undefined {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const element of this.elementRegistry.getAll()) {\n const shape = element as { x?: unknown; y?: unknown; width?: unknown; height?: unknown };\n if (\n typeof shape.x !== \"number\" ||\n typeof shape.y !== \"number\" ||\n typeof shape.width !== \"number\" ||\n typeof shape.height !== \"number\"\n ) {\n continue;\n }\n minX = Math.min(minX, shape.x);\n minY = Math.min(minY, shape.y);\n maxX = Math.max(maxX, shape.x + shape.width);\n maxY = Math.max(maxY, shape.y + shape.height);\n }\n return Number.isFinite(minX) ? { minX, minY, maxX, maxY } : undefined;\n }\n}\n","/**\n * Geist inside an exported SVG. An SVG drawn as an image (the usual way to rasterise it into a PNG)\n * is an isolated document: it can't use the host page's @font-face rules, so its labels would fall\n * back to a system font. The host passes the font files as data URLs, because it owns them (for\n * example from `@fontsource-variable/geist`); the library ships no font.\n */\n\nconst SVG_NAMESPACE = \"http://www.w3.org/2000/svg\";\n\n/** The latin subsets of `@fontsource-variable/geist`, with the unicode ranges it publishes. */\nexport const GEIST_UNICODE_RANGES = {\n latin:\n \"U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD\",\n latinExt:\n \"U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF\",\n} as const;\n\n/** A `data:` URL of each latin Geist variable-weight WOFF2 file. */\nexport type GeistFontDataUrls = Record<keyof typeof GEIST_UNICODE_RANGES, string>;\n\n/** @font-face rules for the family the canvas labels ask for ('Geist Variable'). */\nexport function geistFontFaceCss(fonts: GeistFontDataUrls): string {\n return (Object.keys(GEIST_UNICODE_RANGES) as (keyof GeistFontDataUrls)[])\n .map((subset) => {\n const dataUrl = fonts[subset].replace(/^data:[^;,]*/, \"data:font/woff2\");\n return (\n `@font-face{font-family:'Geist Variable';font-style:normal;font-weight:100 900;` +\n `font-display:block;src:url(${dataUrl}) format('woff2');` +\n `unicode-range:${GEIST_UNICODE_RANGES[subset]};}`\n );\n })\n .join(\"\");\n}\n\n/** Puts `css` into a <style> at the top of a standalone SVG; returns the SVG unchanged if unparsable. */\nexport function embedSvgStyles(svg: string, css: string): string {\n const parsed = new DOMParser().parseFromString(svg, \"image/svg+xml\");\n const root = parsed.documentElement;\n if (root.namespaceURI !== SVG_NAMESPACE || parsed.querySelector(\"parsererror\")) return svg;\n const defs = parsed.createElementNS(SVG_NAMESPACE, \"defs\");\n const style = parsed.createElementNS(SVG_NAMESPACE, \"style\");\n style.textContent = css;\n defs.appendChild(style);\n root.insertBefore(defs, root.firstChild);\n return new XMLSerializer().serializeToString(parsed);\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtImporter from \"./TtImporter.js\";\nimport TtExporter from \"./TtExporter.js\";\nimport TtViewport from \"./TtViewport.js\";\n\n/** Document <-> diagram-js bridge (import / export) and the palette-aware fit. */\nexport const ioModule: ModuleDeclaration = {\n ttImporter: [\"type\", TtImporter],\n ttExporter: [\"type\", TtExporter],\n ttViewport: [\"type\", TtViewport],\n};\n\nexport { default as TtImporter } from \"./TtImporter.js\";\nexport { default as TtExporter } from \"./TtExporter.js\";\nexport { default as TtViewport } from \"./TtViewport.js\";\nexport { saveSVG } from \"./saveSvg.js\";\nexport { GEIST_UNICODE_RANGES, embedSvgStyles, geistFontFaceCss } from \"./fontEmbedding.js\";\nexport type { GeistFontDataUrls } from \"./fontEmbedding.js\";\nexport { ROOT_ID } from \"./types.js\";\nexport type { ImportWarning, RootBusinessObject } from \"./types.js\";\n","import type { ModuleDeclaration } from \"didi\";\nimport { TtBaseViewer } from \"./TtBaseViewer.js\";\nimport { ttModelModule } from \"./model/index.js\";\nimport { ttDrawModule } from \"./draw/index.js\";\nimport { ioModule } from \"./io/index.js\";\n\n/** Read-only renderer: draws a Team Topologies diagram with no interaction. */\nexport class Viewer extends TtBaseViewer {\n protected _getModules(): ModuleDeclaration[] {\n return [ttModelModule, ttDrawModule, 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/** Read-only + navigation: zoom (scroll), pan (drag), selection. */\nexport class NavigatedViewer extends Viewer {\n protected override _getModules(): ModuleDeclaration[] {\n return [...super._getModules(), SelectionModule, ZoomScrollModule, MoveCanvasModule];\n }\n}\n","/**\n * Generic, undo-able command that sets arbitrary Team Topologies properties\n * (ttLabel, teamType, mode, fill, stroke, description). Returns the changed\n * element so the CommandStack fires `elements.changed` → re-render.\n */\n\nimport type { ElementLike } from \"diagram-js/lib/core/Types\";\nimport type CommandHandler from \"diagram-js/lib/command/CommandHandler\";\n\nexport interface UpdatePropertiesContext {\n element: ElementLike & Record<string, unknown>;\n properties: Record<string, unknown>;\n /** set internally by the handler (for revert). */\n oldProperties?: Record<string, unknown>;\n}\n\nfunction setOrDelete(obj: Record<string, unknown>, key: string, value: unknown): void {\n if (value === undefined) delete obj[key];\n else obj[key] = value;\n}\n\nexport default class UpdatePropertiesHandler implements CommandHandler {\n execute(context: UpdatePropertiesContext): ElementLike[] {\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): ElementLike[] {\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)) setOrDelete(target, key, oldProperties[key]);\n }\n return [element];\n }\n}\n","/**\n * Renames the diagram as one undoable command. The title lives on the root element, so a host that\n * listens to the command stack sees the rename like any other change, and undo reverts it.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type CommandHandler from \"diagram-js/lib/command/CommandHandler\";\nimport type { ElementLike } from \"diagram-js/lib/core/Types\";\nimport type { Root } from \"diagram-js/lib/model/Types\";\nimport type { RootBusinessObject } from \"../../io/types.js\";\n\ntype RootWithMeta = Root & { businessObject?: RootBusinessObject };\n\nexport interface UpdateTitleContext {\n title: string;\n /** set internally by the handler (for revert). */\n oldTitle?: string;\n}\n\nconst UNTITLED = \"Untitled team topology\";\n\nexport default class UpdateTitleHandler implements CommandHandler {\n static $inject = [\"canvas\"];\n\n constructor(private readonly canvas: Canvas) {}\n\n execute(context: UpdateTitleContext): ElementLike[] {\n const root = this.canvas.getRootElement() as RootWithMeta;\n const current = root.businessObject ?? { title: UNTITLED };\n context.oldTitle = current.title;\n root.businessObject = { ...current, title: context.title };\n return [root];\n }\n\n revert(context: UpdateTitleContext): ElementLike[] {\n const root = this.canvas.getRootElement() as RootWithMeta;\n const current = root.businessObject ?? { title: UNTITLED };\n root.businessObject = { ...current, title: context.oldTitle ?? UNTITLED };\n return [root];\n }\n}\n","/**\n * High-level Team Topologies mutations that go through the command stack\n * (undo/redo). Registers the generic property command handler.\n */\n\nimport type CommandStack from \"diagram-js/lib/command/CommandStack\";\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type { Element, Root } from \"diagram-js/lib/model/Types\";\nimport type { InteractionMode, TeamType } from \"@miragon/team-topologies-schema-model\";\nimport {\n isTtAssociation,\n type TtAnnotation,\n type TtElement,\n type TtInteraction,\n type TtTeam,\n} from \"../model/di-types.js\";\nimport type TtElementFactory from \"../model/TtElementFactory.js\";\nimport UpdatePropertiesHandler from \"./cmd/UpdatePropertiesHandler.js\";\nimport UpdateTitleHandler from \"./cmd/UpdateTitleHandler.js\";\n\nconst UPDATE_PROPERTIES = \"element.updateProperties\";\nconst UPDATE_TITLE = \"tt.title.update\";\n\n/** Gap between an element and an annotation appended to it. */\nconst ANNOTATION_GAP = 40;\n\nexport default class TtModeling {\n static $inject = [\"commandStack\", \"modeling\", \"ttElementFactory\", \"canvas\"];\n\n constructor(\n private readonly commandStack: CommandStack,\n private readonly modeling: Modeling,\n private readonly factory: TtElementFactory,\n private readonly canvas: Canvas,\n ) {\n commandStack.registerHandler(UPDATE_PROPERTIES, UpdatePropertiesHandler);\n commandStack.registerHandler(UPDATE_TITLE, UpdateTitleHandler);\n }\n\n /** Renames the diagram, as one undo step. */\n setTitle(title: string): void {\n this.commandStack.execute(UPDATE_TITLE, { title });\n }\n\n updateProperties(element: TtElement, properties: Record<string, unknown>): void {\n this.commandStack.execute(UPDATE_PROPERTIES, { element, properties });\n }\n\n /** Rename / relabel any element. */\n updateLabel(element: TtElement, label: string): void {\n this.updateProperties(element, { ttLabel: label || undefined });\n }\n\n setTeamType(team: TtTeam, teamType: TeamType): void {\n this.updateProperties(team, { teamType });\n }\n\n setInteractionMode(interaction: TtInteraction, mode: InteractionMode): void {\n this.updateProperties(interaction, { mode });\n }\n\n /** Set or clear per-element colour overrides (`undefined` reverts to default). */\n setColors(\n element: TtTeam | TtInteraction,\n fill: string | undefined,\n stroke: string | undefined,\n ): void {\n this.updateProperties(element, { fill, stroke });\n }\n\n setDescription(team: TtTeam, description: string | undefined): void {\n this.updateProperties(team, { description });\n }\n\n /** Places a new annotation to the upper right of `element`, attached to it, as one undo step. */\n appendAnnotation(element: TtElement): TtAnnotation {\n const annotation = this.factory.createNewAnnotation();\n const position = {\n x: element.x + element.width + ANNOTATION_GAP + annotation.width / 2,\n y: element.y - ANNOTATION_GAP / 4,\n };\n return this.modeling.appendShape(\n element as Element,\n annotation as Element,\n position,\n this.canvas.getRootElement() as Root,\n { connection: this.factory.createNewAssociation(), connectionTarget: element },\n ) as unknown as TtAnnotation;\n }\n\n /** Removes the annotation's connector; the annotation itself stays. */\n detachAnnotation(annotation: TtAnnotation): void {\n const associations = [...annotation.incoming, ...annotation.outgoing].filter(isTtAssociation);\n if (associations.length > 0) this.modeling.removeElements(associations);\n }\n}\n","/**\n * Lays every annotation connector out as a straight line between the centres of\n * the annotation and its element (the association behaviour then crops it to\n * both outlines). The anchor hints from move / resize / connect are ignored on\n * purpose, so the connector never drifts off-centre.\n */\n\nimport BaseLayouter, { type LayoutConnectionHints } from \"diagram-js/lib/layout/BaseLayouter\";\nimport { getMid } from \"diagram-js/lib/layout/LayoutUtil\";\nimport type { Connection } from \"diagram-js/lib/model/Types\";\nimport type { Point } from \"diagram-js/lib/util/Types\";\n\nexport default class TtLayouter extends BaseLayouter {\n override layoutConnection(connection: Connection, hints: LayoutConnectionHints = {}): Point[] {\n const source = hints.source ?? connection.source;\n const target = hints.target ?? connection.target;\n if (!source || !target) return super.layoutConnection(connection, hints);\n return [getMid(source), getMid(target)];\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport ModelingModule from \"diagram-js/lib/features/modeling\";\nimport TtModeling from \"./TtModeling.js\";\nimport TtLayouter from \"./TtLayouter.js\";\n\n/**\n * High-level Team Topologies mutations + registration of the command handlers.\n * Depends on the diagram-js modeling module so our `layouter` replaces its\n * default one.\n */\nexport const ttModelingModule: ModuleDeclaration = {\n __depends__: [ModelingModule],\n __init__: [\"ttModeling\"],\n ttModeling: [\"type\", TtModeling],\n layouter: [\"type\", TtLayouter],\n};\n\nexport { default as TtModeling } from \"./TtModeling.js\";\nexport { default as TtLayouter } from \"./TtLayouter.js\";\n","/**\n * Allowed editing operations. Every Team Topologies element is a free, placed\n * shape — movable, creatable and resizable. The only connection is an\n * annotation's connector to a team, interaction or flow (the official notation\n * models interactions as overlapping shapes, not lines).\n */\n\nimport RuleProvider from \"diagram-js/lib/features/rules/RuleProvider\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport { isTtAnnotation, isTtElement } from \"../model/di-types.js\";\n\ninterface MoveContext {\n target?: { parent?: unknown } | null;\n}\n\ninterface ConnectContext {\n source?: unknown;\n target?: unknown;\n}\n\nfunction isAttachable(element: unknown): boolean {\n return isTtElement(element) && !isTtAnnotation(element);\n}\n\nexport default class TtRules extends RuleProvider {\n static override $inject = [\"eventBus\"];\n\n constructor(eventBus: EventBus) {\n super(eventBus);\n }\n\n override init(): void {\n this.addRule([\"shape.move\", \"elements.move\"], (context: MoveContext) =>\n context.target && context.target.parent ? null : true,\n );\n this.addRule(\"shape.create\", () => true);\n this.addRule(\"shape.resize\", () => true);\n this.addRule(\"element.copy\", () => true);\n this.addRule(\"connection.create\", ({ source, target }: ConnectContext) =>\n (isTtAnnotation(source) && isAttachable(target)) ||\n (isTtAnnotation(target) && isAttachable(source))\n ? { ttKind: \"association\" }\n : false,\n );\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport RulesModule from \"diagram-js/lib/features/rules\";\nimport TtRules from \"./TtRules.js\";\n\n/** Team Topologies editing rules (connect, move, create, resize). */\nexport const ttRulesModule: ModuleDeclaration = {\n __depends__: [RulesModule],\n __init__: [\"ttRules\"],\n ttRules: [\"type\", TtRules],\n};\n\nexport { default as TtRules } from \"./TtRules.js\";\n","/**\n * Keeps the diagram flat: Team Topologies shapes overlap but never nest.\n *\n * diagram-js parents a newly created shape to whatever element it is dropped on\n * (`context.parent` defaults to the drop target). Interaction glyphs are meant\n * to be placed *over* the teams they relate to, so the natural workflow would\n * otherwise nest the interaction inside a team — gluing it so it moves along\n * with the team. Force every created shape onto the diagram root instead.\n *\n * Re-parenting on *move* is prevented separately in TtRules.\n */\n\nimport CommandInterceptor from \"diagram-js/lib/command/CommandInterceptor\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\n\nexport default class TtFlatModelBehavior extends CommandInterceptor {\n static override $inject = [\"eventBus\", \"canvas\"];\n\n constructor(eventBus: EventBus, canvas: Canvas) {\n super(eventBus);\n\n this.preExecute(\n [\"shape.create\", \"elements.create\"],\n (context: { parent?: unknown }) => {\n context.parent = canvas.getRootElement();\n },\n true,\n );\n }\n}\n","/**\n * Keeps annotation connectors tidy while editing:\n * - crops every laid-out connector to the outlines of the two shapes it joins\n * (the layouter only knows their centres);\n * - an annotation is attached to at most one element (the document stores a\n * single `attachedTo`), so connecting it again replaces the old connector.\n */\n\nimport 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 ConnectionDocking from \"diagram-js/lib/layout/ConnectionDocking\";\nimport type { Connection } from \"diagram-js/lib/model/Types\";\nimport { isTtAnnotation, isTtAssociation } from \"../model/di-types.js\";\n\ninterface ConnectionContext {\n connection: Connection;\n cropped?: boolean;\n}\n\nexport default class TtAssociationBehavior extends CommandInterceptor {\n static override $inject = [\"eventBus\", \"connectionDocking\", \"modeling\"];\n\n constructor(eventBus: EventBus, connectionDocking: ConnectionDocking, modeling: Modeling) {\n super(eventBus);\n\n this.executed(\n [\"connection.layout\", \"connection.create\"],\n (context: ConnectionContext) => {\n if (context.cropped || !isTtAssociation(context.connection)) return;\n context.connection.waypoints = connectionDocking.getCroppedWaypoints(context.connection);\n context.cropped = true;\n },\n true,\n );\n\n this.reverted(\n \"connection.layout\",\n (context: ConnectionContext) => {\n delete context.cropped;\n },\n true,\n );\n\n this.postExecuted(\n \"connection.create\",\n (context: ConnectionContext) => {\n const connection = context.connection;\n if (!isTtAssociation(connection)) return;\n const annotation = isTtAnnotation(connection.source)\n ? connection.source\n : connection.target;\n if (!isTtAnnotation(annotation)) return;\n const previous = [...annotation.incoming, ...annotation.outgoing].filter(\n (other) => other !== connection && isTtAssociation(other),\n );\n if (previous.length > 0) modeling.removeElements(previous);\n },\n true,\n );\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtFlatModelBehavior from \"./TtFlatModelBehavior.js\";\nimport TtAssociationBehavior from \"./TtAssociationBehavior.js\";\n\n/**\n * Editing behaviors that keep the Team Topologies model flat (no nesting) and\n * annotation connectors cropped and one per annotation.\n */\nexport const ttBehaviorsModule: ModuleDeclaration = {\n __init__: [\"ttFlatModelBehavior\", \"ttAssociationBehavior\"],\n ttFlatModelBehavior: [\"type\", TtFlatModelBehavior],\n ttAssociationBehavior: [\"type\", TtAssociationBehavior],\n};\n\nexport { default as TtFlatModelBehavior } from \"./TtFlatModelBehavior.js\";\nexport { default as TtAssociationBehavior } from \"./TtAssociationBehavior.js\";\n","/**\n * Functional icons for the canvas chrome (context pad, palette tools), returned as inline SVG\n * markup.\n *\n * Lucide icons (ISC licence, © Lucide Icons and Contributors), copied unchanged from\n * lucide-static 1.59.0 and inlined so the published renderer has no icon runtime dependency.\n */\n\n/** One Lucide icon: its SVG child elements on the 24 × 24 grid. */\nexport type IconNode = ReadonlyArray<readonly [string, Readonly<Record<string, string>>]>;\n\nexport interface IconMarkupOptions {\n /** Rendered width and height in px; the viewBox stays on the 24 × 24 grid. */\n size?: number;\n strokeWidth?: number;\n className?: string;\n}\n\nexport const ICON_PENCIL: IconNode = [\n [\n \"path\",\n {\n d: \"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z\",\n },\n ],\n [\"path\", { d: \"m15 5 4 4\" }],\n];\n\nexport const ICON_TRASH: IconNode = [\n [\"path\", { d: \"M10 11v6\" }],\n [\"path\", { d: \"M14 11v6\" }],\n [\"path\", { d: \"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6\" }],\n [\"path\", { d: \"M3 6h18\" }],\n [\"path\", { d: \"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\" }],\n];\n\nexport const ICON_LINK: IconNode = [\n [\"path\", { d: \"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71\" }],\n [\"path\", { d: \"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71\" }],\n];\n\nexport const ICON_MESSAGE_SQUARE_PLUS: IconNode = [\n [\n \"path\",\n {\n d: \"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z\",\n },\n ],\n [\"path\", { d: \"M12 8v6\" }],\n [\"path\", { d: \"M9 11h6\" }],\n];\n\nexport const ICON_SQUARE_DASHED_MOUSE_POINTER: IconNode = [\n [\n \"path\",\n {\n 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 },\n ],\n [\"path\", { d: \"M5 3a2 2 0 0 0-2 2\" }],\n [\"path\", { d: \"M19 3a2 2 0 0 1 2 2\" }],\n [\"path\", { d: \"M5 21a2 2 0 0 1-2-2\" }],\n [\"path\", { d: \"M9 3h1\" }],\n [\"path\", { d: \"M9 21h2\" }],\n [\"path\", { d: \"M14 3h1\" }],\n [\"path\", { d: \"M3 9v1\" }],\n [\"path\", { d: \"M21 9v2\" }],\n [\"path\", { d: \"M3 14v1\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_MENU: IconNode = [\n [\"path\", { d: \"M4 5h16\" }],\n [\"path\", { d: \"M4 12h16\" }],\n [\"path\", { d: \"M4 19h16\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_MINUS: IconNode = [[\"path\", { d: \"M5 12h14\" }]];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_PLUS: IconNode = [\n [\"path\", { d: \"M5 12h14\" }],\n [\"path\", { d: \"M12 5v14\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_MAXIMIZE: IconNode = [\n [\"path\", { d: \"M8 3H5a2 2 0 0 0-2 2v3\" }],\n [\"path\", { d: \"M21 8V5a2 2 0 0 0-2-2h-3\" }],\n [\"path\", { d: \"M3 16v3a2 2 0 0 0 2 2h3\" }],\n [\"path\", { d: \"M16 21h3a2 2 0 0 0 2-2v-3\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_DOWNLOAD: IconNode = [\n [\"path\", { d: \"M12 15V3\" }],\n [\"path\", { d: \"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" }],\n [\"path\", { d: \"m7 10 5 5 5-5\" }],\n];\n\n/**\n * @deprecated Host chrome only (menu, zoom panel, dialogs); hosts take their chrome and its icons\n * from `@miragon/modeler-shell`. Kept for existing consumers, removed in a later release.\n */\nexport const ICON_X: IconNode = [\n [\"path\", { d: \"M18 6 6 18\" }],\n [\"path\", { d: \"m6 6 12 12\" }],\n];\n\nconst ICON_STROKE_WIDTH = 2.5;\nconst ICON_SIZE = 16;\n\n/**\n * The SVG elements and attributes Lucide icon nodes are made of. The markup is assigned to\n * innerHTML by hosts, so anything else a caller passes in (a <script>, an onload) is dropped.\n */\nconst SVG_ELEMENTS = [\"path\", \"circle\", \"ellipse\", \"line\", \"polyline\", \"polygon\", \"rect\"] as const;\nconst SVG_ATTRIBUTES = [\n \"d\",\n \"cx\",\n \"cy\",\n \"r\",\n \"rx\",\n \"ry\",\n \"x\",\n \"y\",\n \"x1\",\n \"y1\",\n \"x2\",\n \"y2\",\n \"width\",\n \"height\",\n \"points\",\n] as const;\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction positiveNumberOr(value: unknown, fallback: number): number {\n const number = Number(value);\n return Number.isFinite(number) && number > 0 ? number : fallback;\n}\n\n/** Decorative (`aria-hidden`) inline SVG for a Lucide icon; the control around it carries the name. */\nexport function iconMarkup(icon: IconNode, options: IconMarkupOptions = {}): string {\n const size = positiveNumberOr(options.size, ICON_SIZE);\n const strokeWidth = positiveNumberOr(options.strokeWidth, ICON_STROKE_WIDTH);\n const classAttribute = options.className ? ` class=\"${escapeAttribute(options.className)}\"` : \"\";\n const children = icon\n .map(([tag, attributes]) => {\n const element = SVG_ELEMENTS.find((allowed) => allowed === tag);\n if (!element) return \"\";\n const attributeList = Object.entries(attributes)\n .flatMap(([name, value]) => {\n const attribute = SVG_ATTRIBUTES.find((allowed) => allowed === name);\n return attribute ? [`${attribute}=\"${escapeAttribute(String(value))}\"`] : [];\n })\n .join(\" \");\n return `<${element} ${attributeList}/>`;\n })\n .join(\"\");\n return (\n `<svg${classAttribute} xmlns=\"http://www.w3.org/2000/svg\" width=\"${size}\" height=\"${size}\" viewBox=\"0 0 24 24\"` +\n ` fill=\"none\" stroke=\"currentColor\" stroke-width=\"${strokeWidth}\" stroke-linecap=\"round\"` +\n ` stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">${children}</svg>`\n );\n}\n","/**\n * Tiny inline-SVG glyphs for the palette entries — the same shapes the canvas\n * draws (so the palette is a faithful preview of each team type / interaction\n * mode). Returned as HTML strings for diagram-js palette `html`.\n */\n\nimport {\n FLOW_SPEC,\n INTERACTION_MODE_SPECS,\n TEAM_TYPE_SPECS,\n dashArray,\n} from \"@miragon/team-topologies-schema-model\";\nimport type { InteractionMode, TeamType } from \"@miragon/team-topologies-schema-model\";\nimport { ICON_SQUARE_DASHED_MOUSE_POINTER, iconMarkup } from \"./icons.js\";\n\n/**\n * The lasso is a tool, not notation: a Lucide icon at the guide's tool size (§5.14, 20px with a\n * stroke of 2, which renders as heavy as the 16px chrome icons).\n */\nconst PALETTE_TOOL_ICON = { size: 20, strokeWidth: 2 } as const;\n\nfunction svg(inner: string): string {\n return `<svg class=\"tt-palette-svg\" width=\"24\" height=\"24\" viewBox=\"0 0 26 26\" aria-hidden=\"true\">${inner}</svg>`;\n}\n\nexport function teamIconSvg(type: TeamType): string {\n const s = TEAM_TYPE_SPECS[type];\n const dash = dashArray(s.strokeStyle, 1.5);\n const common =\n `fill=\"${s.fill}\" stroke=\"${s.stroke}\" stroke-width=\"1.5\"` +\n (dash ? ` stroke-dasharray=\"${dash}\"` : \"\");\n switch (s.shape) {\n case \"octagon\":\n return svg(`<polygon points=\"8,3 18,3 23,8 23,18 18,23 8,23 3,18 3,8\" ${common}/>`);\n case \"rounded-rect-vertical\":\n return svg(`<rect x=\"8\" y=\"3\" width=\"10\" height=\"20\" rx=\"4\" ${common}/>`);\n case \"rect\":\n return svg(`<rect x=\"3\" y=\"7\" width=\"20\" height=\"12\" rx=\"1.5\" ${common}/>`);\n default:\n return svg(`<rect x=\"3\" y=\"8\" width=\"20\" height=\"10\" rx=\"5\" ${common}/>`);\n }\n}\n\nexport function flowIconSvg(): string {\n const dash = dashArray(FLOW_SPEC.strokeStyle, 1.5);\n return svg(\n `<g fill=\"none\" stroke=\"${FLOW_SPEC.stroke}\" stroke-width=\"1.5\" stroke-linejoin=\"round\"` +\n (dash ? ` stroke-dasharray=\"${dash}\"` : \"\") +\n `><polygon points=\"3,9 16,9 16,5 23,13 16,21 16,17 3,17\"/></g>`,\n );\n}\n\nexport function annotationIconSvg(): string {\n return svg(\n `<g fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\">` +\n `<path d=\"M10 4H5v18h5\"/><path d=\"M13 9h9M13 13h9M13 17h6\"/></g>`,\n );\n}\n\n/** The lasso (multi-select) tool: Lucide square-dashed-mouse-pointer. */\nexport function lassoIconSvg(): string {\n return iconMarkup(ICON_SQUARE_DASHED_MOUSE_POINTER, {\n ...PALETTE_TOOL_ICON,\n className: \"tt-palette-svg\",\n });\n}\n\nexport function interactionIconSvg(mode: InteractionMode): string {\n const s = INTERACTION_MODE_SPECS[mode];\n const dash = dashArray(s.strokeStyle, 1.5);\n const common =\n `fill=\"${s.fill}\" fill-opacity=\"${s.opacity}\" stroke=\"${s.stroke}\" stroke-width=\"1.5\"` +\n (dash ? ` stroke-dasharray=\"${dash}\"` : \"\");\n switch (s.shape) {\n case \"circle\":\n return svg(`<circle cx=\"13\" cy=\"13\" r=\"9\" ${common}/>`);\n case \"triangle\":\n return svg(`<polygon points=\"5,6 22,13 5,20\" ${common}/>`);\n default:\n return svg(`<polygon points=\"9,6 23,6 17,20 3,20\" ${common}/>`);\n }\n}\n","/**\n * The tool palette: the lasso (multi-select) tool, then drag-to-create entries for the four team\n * types, the three interaction-mode glyphs (placed over team boundaries), the flow-of-change arrow\n * and the text annotation.\n *\n * A host's chrome (the modeler shell) lays the palette out, gives it its toolbar semantics and\n * triggers an entry from the keyboard with a click whose `detail` is 0. Such a click on a creating\n * entry places the element in the centre of the free part of the canvas (guide §5.5), 24px further\n * diagonally while that spot is taken, selects it and opens its label editor: diagram-js's create\n * tool follows the pointer and never ends without one.\n */\n\nimport 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 Create from \"diagram-js/lib/features/create/Create\";\nimport type LassoTool from \"diagram-js/lib/features/lasso-tool/LassoTool\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type Selection from \"diagram-js/lib/features/selection/Selection\";\nimport type {\n PaletteEntries,\n PaletteEntry,\n default as PaletteProvider,\n} from \"diagram-js/lib/features/palette/PaletteProvider\";\nimport type { Root, Shape } from \"diagram-js/lib/model/Types\";\nimport type { Injector } from \"didi\";\nimport type { FreeArea, FreeAreaInsets } from \"@miragon/modeler-api\";\nimport {\n ALL_INTERACTION_SPECS,\n ALL_TEAM_SPECS,\n ANNOTATION_SPEC,\n FLOW_SPEC,\n} from \"@miragon/team-topologies-schema-model\";\nimport {\n annotationIconSvg,\n flowIconSvg,\n interactionIconSvg,\n lassoIconSvg,\n teamIconSvg,\n} from \"../draw/palette-icons.js\";\nimport type { TtLabelEditing } from \"../label-editing/index.js\";\nimport { isTtElement, type TtElement } from \"../model/di-types.js\";\nimport type TtElementFactory from \"../model/TtElementFactory.js\";\nimport type { TtReadOnly } from \"../read-only/index.js\";\n\n/** diagram-js highlights the active tool only inside a group named exactly `tools`. */\nconst GROUP_TOOLS = \"tools\";\nconst GROUP_TEAMS = \"tt-1-teams\";\nconst GROUP_MODES = \"tt-2-modes\";\nconst GROUP_GUIDES = \"tt-3-guides\";\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\nexport interface Point {\n x: number;\n y: number;\n}\n\nexport interface TtPaletteConfig {\n /**\n * The part of the canvas no chrome covers (contract option of `@miragon/modeler-api` 1.2): its\n * insets in px from the container's edges (the modeler shell's `shell.fitInsets()`) or its centre\n * in diagram coordinates (the shell's `viewport.freeRectCenter()`). Without it, the centre of\n * the visible canvas.\n */\n freeArea?: FreeArea | undefined;\n /** @deprecated Pass `freeArea: { center }`; given both, `freeArea` wins. */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\nfunction entryHtml(icon: string, draggable = true): string {\n return `<div class=\"entry tt-palette-entry\" draggable=\"${draggable}\">${icon}</div>`;\n}\n\n/** A click the chrome synthesises for Enter or Space on a palette entry (no pointer, detail 0). */\nfunction isKeyboardClick(event: Event): boolean {\n return event.type === \"click\" && (event as MouseEvent).detail === 0;\n}\n\nfunction centreOf(element: TtElement): Point {\n return { x: element.x + element.width / 2, y: element.y + element.height / 2 };\n}\n\n/** The centre of the container minus `insets`, in diagram coordinates, the way a fit finds it. */\nfunction centreInside(canvas: Canvas, insets: FreeAreaInsets): Point | undefined {\n const { x, y, scale, outer } = canvas.viewbox();\n const freeWidth = outer.width - insets.left - insets.right;\n const freeHeight = outer.height - insets.top - insets.bottom;\n if (!(scale > 0) || !(freeWidth > 0) || !(freeHeight > 0)) return undefined;\n return {\n x: x + (insets.left + freeWidth / 2) / scale,\n y: y + (insets.top + freeHeight / 2) / scale,\n };\n}\n\nexport default class TtPaletteProvider implements PaletteProvider {\n static $inject = [\n \"config.ttPalette\",\n \"palette\",\n \"create\",\n \"ttElementFactory\",\n \"lassoTool\",\n \"canvas\",\n \"modeling\",\n \"selection\",\n \"elementRegistry\",\n \"injector\",\n ];\n\n private readonly readOnly: TtReadOnly | undefined;\n private readonly labelEditing: TtLabelEditing | undefined;\n\n constructor(\n private readonly config: TtPaletteConfig | undefined,\n palette: Palette,\n private readonly create: Create,\n private readonly factory: TtElementFactory,\n private readonly lassoTool: LassoTool,\n private readonly canvas: Canvas,\n private readonly modeling: Modeling,\n private readonly selection: Selection,\n private readonly elementRegistry: ElementRegistry,\n injector: Injector,\n ) {\n this.readOnly = injector.get<TtReadOnly>(\"ttReadOnly\", false);\n this.labelEditing = injector.get<TtLabelEditing>(\"ttLabelEditing\", false);\n palette.registerProvider(this);\n }\n\n getPaletteEntries(): PaletteEntries {\n const entries: PaletteEntries = {};\n\n entries[\"lasso-tool\"] = {\n group: GROUP_TOOLS,\n title: \"Select several elements\",\n html: entryHtml(lassoIconSvg(), false),\n action: {\n click: (event: Event) => this.lassoTool.activateSelection(event as MouseEvent),\n },\n };\n\n for (const spec of ALL_TEAM_SPECS) {\n entries[`team.${spec.type}`] = this.createEntry(\n GROUP_TEAMS,\n `${spec.label} team`,\n teamIconSvg(spec.type),\n () => this.factory.createNewTeam(spec.type, spec.label) as unknown as Shape,\n );\n }\n\n for (const spec of ALL_INTERACTION_SPECS) {\n entries[`mode.${spec.mode}`] = this.createEntry(\n GROUP_MODES,\n `${spec.label} interaction`,\n interactionIconSvg(spec.mode),\n () => this.factory.createNewInteraction(spec.mode) as unknown as Shape,\n );\n }\n\n entries[\"flow\"] = this.createEntry(\n GROUP_GUIDES,\n FLOW_SPEC.label,\n flowIconSvg(),\n () => this.factory.createNewFlow() as unknown as Shape,\n );\n\n entries[\"annotation\"] = this.createEntry(\n GROUP_GUIDES,\n ANNOTATION_SPEC.label,\n annotationIconSvg(),\n () => this.factory.createNewAnnotation() as unknown as Shape,\n );\n\n return entries;\n }\n\n private createEntry(\n group: string,\n title: string,\n icon: string,\n newShape: () => Shape,\n ): PaletteEntry {\n const start = (event: Event) => {\n if (isKeyboardClick(event)) this.placeInFreeRect(newShape());\n else this.create.start(event as MouseEvent, newShape());\n };\n return {\n group,\n title,\n html: entryHtml(icon),\n action: { dragstart: start, click: start },\n };\n }\n\n /** The centre of the free rectangle, stepped diagonally past elements already centred there. */\n private freePlace(): Point {\n const viewbox = this.canvas.viewbox();\n const centre = this.freeAreaCentre() ?? {\n x: viewbox.x + viewbox.width / 2,\n y: viewbox.y + viewbox.height / 2,\n };\n const place = { x: Math.round(centre.x), y: Math.round(centre.y) };\n const taken = () =>\n this.elementRegistry.filter(isTtElement).some((element) => {\n const elementCentre = centreOf(element as unknown as TtElement);\n return Math.abs(elementCentre.x - place.x) < 1 && Math.abs(elementCentre.y - place.y) < 1;\n });\n while (taken()) {\n place.x += KEYBOARD_CREATE_OFFSET;\n place.y += KEYBOARD_CREATE_OFFSET;\n }\n return place;\n }\n\n private freeAreaCentre(): Point | undefined {\n const freeArea = this.config?.freeArea;\n if (freeArea?.center) return freeArea.center();\n if (freeArea?.insets) return centreInside(this.canvas, freeArea.insets());\n return this.config?.freeRectCenter?.();\n }\n\n private placeInFreeRect(shape: Shape): void {\n if (this.readOnly?.isReadOnly()) return;\n const created = this.modeling.createShape(\n shape,\n this.freePlace(),\n this.canvas.getRootElement() as Root,\n );\n this.selection.select(created);\n this.canvas.focus();\n if (isTtElement(created)) this.labelEditing?.activate(created);\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport PaletteModule from \"diagram-js/lib/features/palette\";\nimport CreateModule from \"diagram-js/lib/features/create\";\nimport LassoToolModule from \"diagram-js/lib/features/lasso-tool\";\nimport TtPaletteProvider from \"./TtPaletteProvider.js\";\n\n/** Tool palette (lasso, drag-to-create teams, interactions, flows and annotations). */\nexport const ttPaletteModule: ModuleDeclaration = {\n __depends__: [PaletteModule, CreateModule, LassoToolModule],\n __init__: [\"ttPaletteProvider\"],\n ttPaletteProvider: [\"type\", TtPaletteProvider],\n};\n\nexport { default as TtPaletteProvider } from \"./TtPaletteProvider.js\";\n","/**\n * Locks every edit on the canvas while the document behind it cannot be saved from the canvas (an\n * invalid file in an IDE host, guide §13.5): otherwise a change on the canvas would overwrite the\n * text the user is fixing. The rules veto move, resize, create, connect and delete; the keyboard,\n * the context pad and the label editor ask `isReadOnly()`, because rules alone do not stop a\n * context pad from opening or a double-click from opening the label editor. Selection, zoom, pan,\n * copy and export stay.\n */\n\nimport RuleProvider from \"diagram-js/lib/features/rules/RuleProvider\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\n\n/** Fired with `{ readOnly }` whenever the lock changes. */\nexport const READ_ONLY_CHANGED_EVENT = \"tt.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];\n\nexport default class TtReadOnly extends RuleProvider {\n static override $inject = [\"eventBus\"];\n\n private readOnly = false;\n\n constructor(private readonly bus: EventBus) {\n super(bus);\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) return;\n this.readOnly = readOnly;\n this.bus.fire(READ_ONLY_CHANGED_EVENT, { readOnly });\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport RulesModule from \"diagram-js/lib/features/rules\";\nimport TtReadOnly from \"./TtReadOnly.js\";\n\n/** The canvas edit lock (an invalid file in an IDE host). */\nexport const ttReadOnlyModule: ModuleDeclaration = {\n __depends__: [RulesModule],\n __init__: [\"ttReadOnly\"],\n ttReadOnly: [\"type\", TtReadOnly],\n};\n\nexport { default as TtReadOnly, READ_ONLY_CHANGED_EVENT } from \"./TtReadOnly.js\";\n","/**\n * Context-pad actions. Teams, interactions and flows: rename, add an attached\n * annotation, delete. Annotations: edit text, connect to an element, delete. An\n * annotation connector: delete. A multi-selection: delete all.\n *\n * Entries are focusable buttons; Enter or Space runs their keyboard action.\n * Connecting has none, because it is a pointer gesture that needs a drop target,\n * so Tab skips it. \"Add annotation\" on the element attaches one by keyboard.\n *\n * Every entry changes the diagram, so under the read-only lock there is no context pad at all.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type ContextPad from \"diagram-js/lib/features/context-pad/ContextPad\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type Connect from \"diagram-js/lib/features/connect/Connect\";\nimport type Selection from \"diagram-js/lib/features/selection/Selection\";\nimport type {\n ContextPadEntries,\n ContextPadEntry,\n default as ContextPadProvider,\n} from \"diagram-js/lib/features/context-pad/ContextPadProvider\";\nimport type { Element } from \"diagram-js/lib/model/Types\";\nimport {\n isTtAnnotation,\n isTtAssociation,\n isTtElement,\n isTtFlow,\n isTtInteraction,\n type TtElement,\n} from \"../model/di-types.js\";\nimport type TtLabelEditing from \"../label-editing/TtLabelEditing.js\";\nimport type TtModeling from \"../modeling/TtModeling.js\";\nimport { READ_ONLY_CHANGED_EVENT, type TtReadOnly } from \"../read-only/index.js\";\nimport {\n ICON_LINK,\n ICON_MESSAGE_SQUARE_PLUS,\n ICON_PENCIL,\n ICON_TRASH,\n iconMarkup,\n type IconNode,\n} from \"../draw/icons.js\";\n\nconst ENTRY_SELECTOR = \".djs-context-pad .entry[data-action]\";\n\nfunction cpHtml(icon: IconNode, title: string, focusable = true): string {\n return `<div class=\"entry tt-cp-entry\" role=\"button\" tabindex=\"${focusable ? 0 : -1}\" aria-label=\"${title}\">${iconMarkup(icon)}</div>`;\n}\n\nfunction editTitle(element: TtElement): string {\n if (isTtAnnotation(element)) return \"Edit text\";\n if (isTtInteraction(element) || isTtFlow(element)) return \"Edit label\";\n return \"Rename\";\n}\n\nexport default class TtContextPadProvider implements ContextPadProvider {\n static $inject = [\n \"contextPad\",\n \"modeling\",\n \"ttModeling\",\n \"ttLabelEditing\",\n \"connect\",\n \"selection\",\n \"canvas\",\n \"eventBus\",\n \"injector\",\n ];\n\n private readonly readOnly: TtReadOnly | null;\n\n constructor(\n private readonly contextPad: ContextPad,\n private readonly modeling: Modeling,\n private readonly ttModeling: TtModeling,\n private readonly labelEditing: TtLabelEditing,\n private readonly connect: Connect,\n private readonly selection: Selection,\n private readonly canvas: Canvas,\n eventBus: EventBus,\n injector: { get<T>(name: string, strict?: boolean): T | null },\n ) {\n this.readOnly = injector.get<TtReadOnly>(\"ttReadOnly\", false);\n contextPad.registerProvider(this);\n eventBus.on(\"contextPad.open.allowed\", () => (this.readOnly?.isReadOnly() ? false : undefined));\n eventBus.on(READ_ONLY_CHANGED_EVENT, (event: { readOnly?: boolean }) => {\n if (event.readOnly) contextPad.close();\n });\n canvas\n .getContainer()\n .addEventListener(\"keydown\", (keyboardEvent) => this.onEntryKeyDown(keyboardEvent));\n }\n\n getContextPadEntries(element: Element): ContextPadEntries {\n if (this.readOnly?.isReadOnly()) return {};\n if (isTtAssociation(element))\n return { delete: this.deleteEntry([element], \"Delete connector\") };\n if (!isTtElement(element)) return {};\n\n if (isTtAnnotation(element)) {\n const startConnect = (event: Event) => this.connect.start(event as MouseEvent, element);\n return {\n \"edit-label\": this.editEntry(element),\n connect: {\n group: \"edit\",\n title: \"Attach to element\",\n html: cpHtml(ICON_LINK, \"Attach to element\", false),\n action: { click: startConnect, dragstart: startConnect },\n },\n delete: this.deleteEntry([element], \"Delete\"),\n };\n }\n\n const appendAnnotation = () => {\n const annotation = this.ttModeling.appendAnnotation(element);\n this.selection.select(annotation as unknown as Element);\n this.labelEditing.activate(annotation);\n };\n return {\n \"edit-label\": this.editEntry(element),\n \"append-annotation\": {\n group: \"edit\",\n title: \"Add annotation\",\n html: cpHtml(ICON_MESSAGE_SQUARE_PLUS, \"Add annotation\"),\n action: { click: appendAnnotation, keyboard: appendAnnotation },\n },\n delete: this.deleteEntry([element], \"Delete\"),\n };\n }\n\n getMultiElementContextPadEntries(elements: Element[]): ContextPadEntries {\n if (this.readOnly?.isReadOnly()) return {};\n return { delete: this.deleteEntry(elements, `Delete ${elements.length} elements`) };\n }\n\n private onEntryKeyDown(event: KeyboardEvent): void {\n if ((event.key !== \"Enter\" && event.key !== \" \") || event.repeat) return;\n const entry = (event.target as HTMLElement | null)?.closest?.(ENTRY_SELECTOR);\n const action = entry?.getAttribute(\"data-action\");\n if (!action) return;\n event.preventDefault();\n event.stopPropagation();\n this.contextPad.triggerEntry(action, \"keyboard\", event);\n }\n\n private editEntry(element: TtElement): ContextPadEntry {\n const title = editTitle(element);\n const activate = () => this.labelEditing.activate(element);\n return {\n group: \"edit\",\n title,\n html: cpHtml(ICON_PENCIL, title),\n action: { click: activate, keyboard: activate },\n };\n }\n\n private deleteEntry(elements: Element[], title: string): ContextPadEntry {\n return {\n group: \"edit\",\n title,\n html: cpHtml(ICON_TRASH, title),\n action: {\n click: () => this.modeling.removeElements([...elements]),\n keyboard: () => {\n this.modeling.removeElements([...elements]);\n this.canvas.focus();\n },\n },\n };\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport ConnectModule from \"diagram-js/lib/features/connect\";\nimport ConnectionPreviewModule from \"diagram-js/lib/features/connection-preview\";\nimport ContextPadModule from \"diagram-js/lib/features/context-pad\";\nimport TtContextPadProvider from \"./TtContextPadProvider.js\";\n\n/** Per-element context actions (rename, annotate, attach, delete). */\nexport const ttContextPadModule: ModuleDeclaration = {\n __depends__: [ContextPadModule, ConnectModule, ConnectionPreviewModule],\n __init__: [\"ttContextPadProvider\"],\n ttContextPadProvider: [\"type\", TtContextPadProvider],\n};\n\nexport { default as TtContextPadProvider } from \"./TtContextPadProvider.js\";\n","/**\n * In-place label editing: a borderless, transparent <textarea> laid exactly over\n * the element's label area, in the label's own font, size, alignment and\n * wrapping, scaled with the zoom. The rendered label is hidden meanwhile, so the\n * text never shows twice. Enter (or clicking elsewhere) commits through\n * `ttModeling.updateLabel` — one undo step; Shift+Enter inserts a line break;\n * Escape discards. Double-click any element to edit its label.\n *\n * A change of the view (a host's `setViewState` or fit, a wheel zoom or scroll) never commits: the\n * editor stays open with what was typed and follows its element, because a host may change the\n * view while the user types, and only the user's own gestures end an edit (law L5 of the\n * `@miragon/modeler-api` contract).\n *\n * An import replaces every element, so an edit open while one runs is taken down without a commit\n * and reopened, with what was typed, on the element with the same id (hosts re-import remote\n * states while the user types). Under the read-only lock no editor opens.\n */\n\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 {\n isTtAnnotation,\n isTtElement,\n isTtFlow,\n isTtInteraction,\n type TtElement,\n} from \"../model/di-types.js\";\nimport type TtModeling from \"../modeling/TtModeling.js\";\nimport { READ_ONLY_CHANGED_EVENT, type TtReadOnly } from \"../read-only/index.js\";\nimport { LINE_HEIGHT, labelLayout } from \"../draw/label-layout.js\";\nimport { FONT } from \"../draw/styles.js\";\n\n/** Canvas marker that hides the rendered label while its editor is open. */\nconst EDITING_MARKER = \"tt-label-editing\";\n\n/** Narrow shapes (small interaction glyphs) still get an editor wide enough to type in. */\nconst MIN_EDITOR_WIDTH = 96;\n\nfunction editorName(element: TtElement): string {\n if (isTtAnnotation(element)) return \"Annotation text\";\n if (isTtInteraction(element)) return \"Interaction label\";\n if (isTtFlow(element)) return \"Flow label\";\n return \"Team name\";\n}\n\ninterface ActiveEdit {\n commit: () => void;\n cleanup: () => void;\n /** Lays the editor over its element again, after the view changed. */\n place: () => void;\n /** The element and what was typed so far, to reopen the edit after an import. */\n snapshot: () => SuspendedEdit;\n}\n\ninterface SuspendedEdit {\n elementId: string;\n value: string;\n selectionStart: number;\n selectionEnd: number;\n}\n\nexport default class TtLabelEditing {\n static $inject = [\"eventBus\", \"canvas\", \"ttModeling\", \"elementRegistry\", \"injector\"];\n\n private active: ActiveEdit | null = null;\n private suspended: SuspendedEdit | null = null;\n private resumeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly readOnly: TtReadOnly | null;\n\n constructor(\n eventBus: EventBus,\n private readonly canvas: Canvas,\n private readonly modeling: TtModeling,\n private readonly elementRegistry: ElementRegistry,\n injector: { get<T>(name: string, strict?: boolean): T | null },\n ) {\n this.readOnly = injector.get<TtReadOnly>(\"ttReadOnly\", false);\n eventBus.on(\"element.dblclick\", (event: { element?: unknown }) => {\n if (isTtElement(event.element)) this.activate(event.element);\n });\n // Any click or drag outside the editor commits (only Escape discards); a pan starts with one.\n eventBus.on([\"element.mousedown\", \"drag.init\"], () => this.active?.commit());\n eventBus.on(\"canvas.viewbox.changed\", () => this.active?.place());\n // An import that bypasses suspend() still must not apply a pending edit to a removed element.\n eventBus.on(\"import.render.start\", () => this.cancel());\n eventBus.on(READ_ONLY_CHANGED_EVENT, (event: { readOnly?: boolean }) => {\n if (event.readOnly) this.cancel();\n });\n // Before the canvas tears down: a field still open would blur, commit onto the destroyed\n // diagram and queue a focus on it.\n eventBus.on(\"diagram.destroy\", () => {\n clearTimeout(this.resumeTimer);\n this.suspended = null;\n this.cancel();\n });\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 go, so a commit would land on a removed shape. `resumeAfterImport` brings\n * the editor back with the typed text.\n */\n suspend(): void {\n clearTimeout(this.resumeTimer);\n if (!this.active) return;\n this.suspended = this.active.snapshot();\n this.active.cleanup();\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 host's own work around the import (restoring its view,\n * moving the focus) is done before the editor takes the focus back.\n */\n resumeAfterImport(): void {\n clearTimeout(this.resumeTimer);\n if (!this.suspended) return;\n this.resumeTimer = setTimeout(() => {\n const edit = this.suspended;\n this.suspended = null;\n if (!edit || this.active) return;\n const element = this.elementRegistry.get(edit.elementId);\n if (!isTtElement(element)) return;\n this.activate(element, edit);\n }, 0);\n }\n\n /** The edit open right now (its element and the uncommitted text), for hosts and tests. */\n openEdit(): { elementId: string; value: string } | undefined {\n if (!this.active) return undefined;\n const { elementId, value } = this.active.snapshot();\n return { elementId, value };\n }\n\n activate(element: TtElement, resumed?: SuspendedEdit): void {\n this.active?.commit();\n if (this.readOnly?.isReadOnly()) return;\n\n const layout = labelLayout(element);\n const centred = layout.align === \"center\";\n const width = centred ? Math.max(layout.box.width, MIN_EDITOR_WIDTH) : layout.box.width;\n const left = element.x + layout.box.x + (layout.box.width - width) / 2;\n\n const editor = document.createElement(\"textarea\");\n editor.className = \"tt-label-editor\";\n editor.value = resumed ? resumed.value : (element.ttLabel ?? \"\");\n editor.rows = 1;\n editor.setAttribute(\"aria-label\", editorName(element));\n Object.assign(editor.style, {\n fontFamily: FONT.family,\n fontWeight: layout.fontWeight,\n letterSpacing: layout.letterSpacing ?? \"normal\",\n lineHeight: String(LINE_HEIGHT),\n color: layout.fill,\n textAlign: centred ? \"center\" : \"left\",\n });\n\n let top = 0;\n let boxHeight = 0;\n // Grow with the text; centred labels stay vertically centred like the rendered ones.\n const fitToContent = () => {\n editor.style.height = \"0px\";\n const contentHeight = editor.scrollHeight;\n editor.style.height = `${centred ? contentHeight : Math.max(contentHeight, boxHeight)}px`;\n editor.style.top = `${centred ? top + (boxHeight - contentHeight) / 2 : top}px`;\n };\n const place = () => {\n const scale = this.canvas.zoom();\n const viewbox = this.canvas.viewbox();\n top = (element.y + layout.box.y - viewbox.y) * scale;\n boxHeight = layout.box.height * scale;\n Object.assign(editor.style, {\n left: `${(left - viewbox.x) * scale}px`,\n width: `${width * scale}px`,\n fontSize: `${layout.fontSize * scale}px`,\n });\n fitToContent();\n };\n\n this.canvas.getContainer().appendChild(editor);\n this.canvas.addMarker(element, EDITING_MARKER);\n place();\n editor.focus();\n if (resumed) editor.setSelectionRange(resumed.selectionStart, resumed.selectionEnd);\n else editor.select();\n\n let done = false;\n const cleanup = () => {\n if (done) return;\n done = true;\n editor.removeEventListener(\"keydown\", onKey);\n editor.removeEventListener(\"input\", fitToContent);\n editor.removeEventListener(\"blur\", onBlur);\n editor.remove();\n if (this.elementRegistry.get(element.id) === element) {\n this.canvas.removeMarker(element, EDITING_MARKER);\n }\n this.active = null;\n // Removing the focused field drops the focus to the page; the canvas takes it back.\n this.canvas.restoreFocus();\n };\n const commit = () => {\n if (done) return;\n const value = editor.value.trim();\n const changed = value !== (element.ttLabel ?? \"\");\n cleanup();\n if (changed) this.modeling.updateLabel(element, value);\n };\n // Removing the focused editor would drop focus to the page; keep keyboard users on the canvas.\n const onKey = (e: KeyboardEvent) => {\n if (e.key === \"Enter\" && !e.shiftKey && !e.isComposing) {\n e.preventDefault();\n commit();\n this.canvas.focus();\n } else if (e.key === \"Escape\") {\n e.preventDefault();\n cleanup();\n this.canvas.focus();\n }\n };\n const onBlur = () => commit();\n editor.addEventListener(\"keydown\", onKey);\n editor.addEventListener(\"input\", fitToContent);\n editor.addEventListener(\"blur\", onBlur);\n\n const snapshot = (): SuspendedEdit => ({\n elementId: element.id,\n value: editor.value,\n selectionStart: editor.selectionStart,\n selectionEnd: editor.selectionEnd,\n });\n this.active = { commit, cleanup, place, snapshot };\n }\n\n cancel(): void {\n this.active?.cleanup();\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtLabelEditing from \"./TtLabelEditing.js\";\n\n/** In-place label editing (double-click any element to edit its label or text). */\nexport const ttLabelEditingModule: ModuleDeclaration = {\n __init__: [\"ttLabelEditing\"],\n ttLabelEditing: [\"type\", TtLabelEditing],\n};\n\nexport { default as TtLabelEditing } from \"./TtLabelEditing.js\";\n","/**\n * Keyboard shortcuts of the canvas: undo / redo / select all / delete-selection / copy / paste /\n * nudge the selection with the arrow keys / clear the selection (Escape).\n *\n * Bound to the document so they work right after a click on the canvas, but they only act when the\n * key press targets the page itself or the canvas (diagram-js focuses its SVG on mouse-down). Key\n * presses in host chrome, open dialogs, form fields and the inline label editor stay with those\n * controls, a key a closer listener already handled (`defaultPrevented`) is left alone, and an\n * `inert` canvas takes no keys at all.\n *\n * Zoom and fit keys are the host chrome's (guide §5.8: only Cmd/Ctrl + `+` `-` `0` and Shift+1,\n * each acting exactly once), so the canvas binds none. A host that owns the history (the VS Code\n * document) turns the undo and redo keys off with `undoRedoKeys: false`, so they reach it.\n */\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type ElementRegistry from \"diagram-js/lib/core/ElementRegistry\";\nimport type CommandStack from \"diagram-js/lib/command/CommandStack\";\nimport type Selection from \"diagram-js/lib/features/selection/Selection\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type CopyPaste from \"diagram-js/lib/features/copy-paste/CopyPaste\";\nimport type Dragging from \"diagram-js/lib/features/dragging/Dragging\";\nimport type Rules from \"diagram-js/lib/features/rules/Rules\";\nimport type { Injector } from \"didi\";\nimport type { Element, Shape } from \"diagram-js/lib/model/Types\";\nimport type TtReadOnly from \"../read-only/TtReadOnly.js\";\n\nconst NUDGE_STEP = 1;\nconst NUDGE_STEP_FAST = 10;\n\nconst ARROW_DIRECTIONS: Record<string, { x: number; y: number }> = {\n ArrowLeft: { x: -1, y: 0 },\n ArrowRight: { x: 1, y: 0 },\n ArrowUp: { x: 0, y: -1 },\n ArrowDown: { x: 0, y: 1 },\n};\n\nconst MODAL_SELECTOR = '[aria-modal=\"true\"], dialog[open]';\n\nexport interface TtKeyboardConfig {\n /**\n * Bind Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z and Cmd/Ctrl+Y to the canvas command stack (default true).\n * A host that owns the history (the VS Code document) passes false so the keys reach it.\n */\n undoRedoKeys?: boolean | undefined;\n}\n\nfunction isTypingTarget(target: EventTarget | null): boolean {\n const el = target as HTMLElement | null;\n if (!el) return false;\n return (\n el.tagName === \"INPUT\" ||\n el.tagName === \"TEXTAREA\" ||\n el.tagName === \"SELECT\" ||\n el.isContentEditable\n );\n}\n\nfunction isNode(target: EventTarget | null): target is Node {\n return typeof (target as Node | null)?.nodeType === \"number\";\n}\n\nfunction isCanvasScope(target: EventTarget | null, canvasContainer: HTMLElement): boolean {\n // A host marks the canvas inert while something else fronts it, e.g. a start screen.\n if (canvasContainer.closest(\"[inert]\")) return false;\n if (!isNode(target)) return true;\n if (target.nodeType === Node.DOCUMENT_NODE) return true;\n const ownerDocument = target.ownerDocument;\n if (target === ownerDocument?.body || target === ownerDocument?.documentElement) return true;\n return canvasContainer.contains(target);\n}\n\nfunction isShape(element: Element): element is Shape {\n return !(\"waypoints\" in element);\n}\n\nexport default class TtKeyboard {\n static $inject = [\n \"config.ttKeyboard\",\n \"eventBus\",\n \"canvas\",\n \"elementRegistry\",\n \"commandStack\",\n \"selection\",\n \"modeling\",\n \"copyPaste\",\n \"rules\",\n \"injector\",\n ];\n\n constructor(\n config: TtKeyboardConfig | undefined,\n eventBus: EventBus,\n canvas: Canvas,\n elementRegistry: ElementRegistry,\n commandStack: CommandStack,\n selection: Selection,\n modeling: Modeling,\n copyPaste: CopyPaste,\n rules: Rules,\n injector: Injector,\n ) {\n const container = canvas.getContainer();\n const doc = container.ownerDocument ?? document;\n const undoRedoKeys = config?.undoRedoKeys ?? true;\n const dragging = injector.get<Dragging>(\"dragging\", false);\n const readOnly = injector.get<TtReadOnly>(\"ttReadOnly\", false);\n\n /** Keys that only read the diagram; they stay under the read-only lock. */\n const handleReadingKey = (e: KeyboardEvent, cmd: boolean, key: string): boolean => {\n if (cmd && key === \"a\" && !e.shiftKey) {\n e.preventDefault();\n selection.select(elementRegistry.filter((element) => Boolean(element.parent)));\n } else if (cmd && key === \"c\" && !e.shiftKey) {\n const sel = selection.get() as Element[];\n if (!sel.length) return true;\n e.preventDefault();\n copyPaste.copy(sel);\n } else if (!cmd && key === \"escape\") {\n if (dragging?.context() || !selection.get().length) return true;\n e.preventDefault();\n selection.select(null);\n } else {\n return false;\n }\n return true;\n };\n\n const handleEditingKey = (e: KeyboardEvent, cmd: boolean, key: string): void => {\n const undo = cmd && key === \"z\" && !e.shiftKey;\n const redo = (cmd && key === \"z\" && e.shiftKey) || (cmd && key === \"y\" && !e.shiftKey);\n if (undo || redo) {\n if (!undoRedoKeys) return;\n e.preventDefault();\n if (undo && commandStack.canUndo()) commandStack.undo();\n if (redo && commandStack.canRedo()) commandStack.redo();\n } else if (key === \"delete\" || key === \"backspace\") {\n const sel = selection.get() as Element[];\n if (sel.length) {\n e.preventDefault();\n modeling.removeElements([...sel]);\n }\n } else if (cmd && key === \"v\" && !e.shiftKey) {\n e.preventDefault();\n copyPaste.paste();\n } else if (!cmd && Object.hasOwn(ARROW_DIRECTIONS, e.key)) {\n const shapes = (selection.get() as Element[]).filter(isShape);\n if (!shapes.length || !rules.allowed(\"elements.move\", { shapes })) return;\n e.preventDefault();\n const direction = ARROW_DIRECTIONS[e.key]!;\n const step = e.shiftKey ? NUDGE_STEP_FAST : NUDGE_STEP;\n modeling.moveElements(shapes, { x: direction.x * step, y: direction.y * step });\n }\n };\n\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.altKey || e.isComposing || isTypingTarget(e.target)) return;\n if (!isCanvasScope(e.target, container) || doc.querySelector(MODAL_SELECTOR)) return;\n const cmd = e.ctrlKey || e.metaKey;\n const key = e.key.toLowerCase();\n if (handleReadingKey(e, cmd, key)) return;\n if (readOnly?.isReadOnly()) return;\n handleEditingKey(e, cmd, key);\n };\n\n doc.addEventListener(\"keydown\", onKeyDown);\n eventBus.on(\"diagram.destroy\", () => doc.removeEventListener(\"keydown\", onKeyDown));\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtKeyboard from \"./TtKeyboard.js\";\n\n/** Canvas shortcuts: history, selection, clipboard and nudging (see TtKeyboard). */\nexport const ttKeyboardModule: ModuleDeclaration = {\n __init__: [\"ttKeyboard\"],\n ttKeyboard: [\"type\", TtKeyboard],\n};\n\nexport { default as TtKeyboard } from \"./TtKeyboard.js\";\nexport type { TtKeyboardConfig } from \"./TtKeyboard.js\";\n","/**\n * Copy-paste for Team Topologies shapes, built on the stock diagram-js\n * CopyPaste feature. Only the id handling differs: the stock `createShape`\n * drops the descriptor id and lets diagram-js auto-assign a `shape_N` id, which\n * is the very collision hazard `TtElementFactory` avoids (its counter is not\n * advanced past ids that arrive via import). So we mint a fresh, scheme-correct\n * `team_/int_/flow_/ann_/assoc_` id instead — the custom `tt*` props are already\n * on the descriptor (added by `TtCopyPasteProps`) and pass straight through.\n * Annotation connectors are pasted only together with both of their ends.\n */\n\nimport CopyPaste from \"diagram-js/lib/features/copy-paste/CopyPaste.js\";\nimport { newId } from \"@miragon/team-topologies-schema-model\";\n\nimport type Canvas from \"diagram-js/lib/core/Canvas\";\nimport type Create from \"diagram-js/lib/features/create/Create\";\nimport type Clipboard from \"diagram-js/lib/features/clipboard/Clipboard\";\nimport type ElementFactory from \"diagram-js/lib/core/ElementFactory\";\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport type Modeling from \"diagram-js/lib/features/modeling/Modeling\";\nimport type Mouse from \"diagram-js/lib/features/mouse/Mouse\";\nimport type Rules from \"diagram-js/lib/features/rules/Rules\";\nimport type { Connection, Shape } from \"diagram-js/lib/model/Types\";\n\n/** Maps a `ttKind` to the id prefix the model package's factory uses. */\nfunction pasteIdPrefix(ttKind: unknown): string | undefined {\n switch (ttKind) {\n case \"team\":\n return \"team\";\n case \"interaction\":\n return \"int\";\n case \"flow\":\n return \"flow\";\n case \"annotation\":\n return \"ann\";\n case \"association\":\n return \"assoc\";\n default:\n return undefined;\n }\n}\n\nexport default class TtCopyPaste extends CopyPaste {\n static override $inject = [\n \"canvas\",\n \"create\",\n \"clipboard\",\n \"elementFactory\",\n \"eventBus\",\n \"modeling\",\n \"mouse\",\n \"rules\",\n ];\n\n constructor(\n canvas: Canvas,\n create: Create,\n clipboard: Clipboard,\n private readonly elementFactory: ElementFactory,\n eventBus: EventBus,\n modeling: Modeling,\n mouse: Mouse,\n rules: Rules,\n ) {\n super(canvas, create, clipboard, elementFactory, eventBus, modeling, mouse, rules);\n }\n\n override createConnection(attrs: Record<string, unknown>): Connection {\n const prefix = pasteIdPrefix(attrs.ttKind);\n if (!prefix) {\n return super.createConnection(attrs);\n }\n return this.elementFactory.createConnection({ ...attrs, id: newId(prefix) }) as Connection;\n }\n\n override createShape(attrs: Record<string, unknown>): Shape {\n const prefix = pasteIdPrefix(attrs.ttKind);\n if (!prefix) {\n return super.createShape(attrs);\n }\n // Keep the id (unlike stock `createShape`, which strips it): a fresh\n // model-style id avoids \"element already exists\" on the next create.\n return this.elementFactory.createShape({ ...attrs, id: newId(prefix) }) as Shape;\n }\n}\n","/**\n * Carries the Team Topologies props across a copy-paste. diagram-js stores each\n * copied element as a plain descriptor whose built-in listener only records\n * geometry (`id/x/y/width/height/…`). Our domain data lives as flat attributes\n * on the shape (not a moddle businessObject), so without this the pasted copy\n * would lose its type, label, description, colours and the fields of other tools. This listener copies\n * those fields onto the descriptor; they then flow through to the new shape.\n */\n\nimport type EventBus from \"diagram-js/lib/core/EventBus\";\nimport { isTtAssociation, isTtElement } from \"../model/di-types.js\";\n\n/** Flat props that define a Team Topologies shape, beyond geometry. */\nconst TT_PROPS = [\n \"ttKind\",\n \"teamType\",\n \"mode\",\n \"ttLabel\",\n \"description\",\n \"fill\",\n \"stroke\",\n \"ttForeign\",\n] as const;\n\nexport default class TtCopyPasteProps {\n static $inject = [\"eventBus\"];\n\n constructor(eventBus: EventBus) {\n eventBus.on(\n \"copyPaste.copyElement\",\n (event: { descriptor: Record<string, unknown>; element: unknown }) => {\n const { descriptor, element } = event;\n if (!isTtElement(element) && !isTtAssociation(element)) return;\n const source = element as Record<string, unknown>;\n for (const prop of TT_PROPS) {\n if (source[prop] !== undefined) descriptor[prop] = structuredClone(source[prop]);\n }\n },\n );\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport CopyPasteModule from \"diagram-js/lib/features/copy-paste\";\nimport TtCopyPaste from \"./TtCopyPaste.js\";\nimport TtCopyPasteProps from \"./TtCopyPasteProps.js\";\n\n/**\n * Copy-paste of Team Topologies shapes: the stock diagram-js feature (clipboard,\n * cursor-follow placement) with `copyPaste` overridden to mint model-style ids\n * and a listener that preserves the flat `tt*` props across the round-trip.\n */\nexport const ttCopyPasteModule: ModuleDeclaration = {\n __depends__: [CopyPasteModule],\n __init__: [\"ttCopyPasteProps\"],\n copyPaste: [\"type\", TtCopyPaste],\n ttCopyPasteProps: [\"type\", TtCopyPasteProps],\n};\n\nexport { default as TtCopyPaste } from \"./TtCopyPaste.js\";\n","/**\n * Enforces a fixed stacking order regardless of creation order, by reordering\n * the element graphics within the canvas layer. Back → front:\n *\n * flow < stream-aligned / platform < complicated-subsystem < enabling\n * < interactions < annotations < annotation connectors\n *\n * So interaction glyphs always read on top of teams; enabling teams sit above the\n * complicated-subsystem teams, which in turn sit above the stream-aligned /\n * platform base teams they overlap. Annotation connectors come last so no shape\n * they cross on the way to their element hides them.\n */\n\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 {\n isTtAnnotation,\n isTtAssociation,\n isTtElement,\n isTtFlow,\n isTtInteraction,\n isTtTeam,\n type TtAssociation,\n type TtElement,\n} from \"../model/di-types.js\";\n\n/** Lower = further back. */\nfunction tier(el: TtElement | TtAssociation): number {\n if (isTtFlow(el)) return 0;\n if (isTtTeam(el)) {\n if (el.teamType === \"enabling\") return 3;\n if (el.teamType === \"complicated-subsystem\") return 2;\n return 1; // stream-aligned, platform\n }\n if (isTtInteraction(el)) return 4;\n if (isTtAnnotation(el)) return 5;\n if (isTtAssociation(el)) return 6;\n return 1;\n}\n\nfunction isOrdered(el: unknown): el is TtElement | TtAssociation {\n return isTtElement(el) || isTtAssociation(el);\n}\n\nexport default class TtZOrder {\n static $inject = [\"eventBus\", \"canvas\", \"elementRegistry\"];\n\n private importing = false;\n\n constructor(\n eventBus: EventBus,\n private readonly canvas: Canvas,\n private readonly elementRegistry: ElementRegistry,\n ) {\n eventBus.on(\"import.render.start\", () => {\n this.importing = true;\n });\n eventBus.on(\"import.render.done\", () => {\n this.importing = false;\n this.reorder();\n });\n // Covers create + team-type changes (and harmlessly re-runs on move/resize).\n eventBus.on(\"commandStack.changed\", () => {\n if (!this.importing) this.reorder();\n });\n }\n\n /** Re-append each element's graphics group in ascending tier order (back → front). */\n reorder(): void {\n const ordered = this.elementRegistry\n .getAll()\n .filter(isOrdered)\n .sort((a, b) => tier(a) - tier(b));\n for (const el of ordered) {\n const gfx = this.canvas.getGraphics(el) as SVGElement | undefined;\n const wrapper = gfx?.parentNode as (Node & ChildNode) | null;\n const layer = wrapper?.parentNode as (Node & { appendChild(n: Node): Node }) | null;\n if (wrapper && layer) layer.appendChild(wrapper);\n }\n }\n}\n","import type { ModuleDeclaration } from \"didi\";\nimport TtZOrder from \"./TtZOrder.js\";\n\n/** Keeps the fixed stacking order (interactions on top, base teams at the back). */\nexport const ttZOrderModule: ModuleDeclaration = {\n __init__: [\"ttZOrder\"],\n ttZOrder: [\"type\", TtZOrder],\n};\n\nexport { default as TtZOrder } from \"./TtZOrder.js\";\n","import type { ModuleDeclaration } from \"didi\";\nimport type CommandStack from \"diagram-js/lib/command/CommandStack\";\n\nimport LassoToolModule from \"diagram-js/lib/features/lasso-tool\";\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 ResizeModule from \"diagram-js/lib/features/resize\";\n\nimport { NavigatedViewer } from \"./NavigatedViewer.js\";\nimport { ttModelingModule } from \"./modeling/index.js\";\nimport { ttRulesModule } from \"./rules/index.js\";\nimport { ttBehaviorsModule } from \"./behaviors/index.js\";\nimport { ttPaletteModule } from \"./palette/index.js\";\nimport { ttContextPadModule } from \"./context-pad/index.js\";\nimport { ttLabelEditingModule } from \"./label-editing/index.js\";\nimport { ttKeyboardModule } from \"./keyboard/index.js\";\nimport { ttCopyPasteModule } from \"./copy-paste/index.js\";\nimport { ttZOrderModule } from \"./zorder/index.js\";\nimport { ttReadOnlyModule } from \"./read-only/index.js\";\n\n/**\n * Full Team Topologies editor: palette/create, multi-selection (lasso, select\n * all) and group move, resize, annotations with connectors, context pad,\n * in-place label editing, undo/redo, and the edit lock for a document the\n * canvas cannot save (`ttReadOnly`).\n */\nexport class Modeler extends NavigatedViewer {\n protected override _getModules(): ModuleDeclaration[] {\n return [\n ...super._getModules(),\n // diagram-js stock\n ModelingModule,\n LassoToolModule,\n MoveModule,\n OutlineModule,\n ResizeModule,\n // Team Topologies editor\n ttReadOnlyModule,\n ttModelingModule,\n ttRulesModule,\n ttBehaviorsModule,\n ttPaletteModule,\n ttContextPadModule,\n ttLabelEditingModule,\n ttKeyboardModule,\n ttCopyPasteModule,\n ttZOrderModule,\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","/**\n * The Team Topologies modeler behind the collaborative-modeler contract of `@miragon/modeler-api`\n * (the laws L1 to L7 in its README): hosts such as designIQ, the VS Code webview and the web app\n * import and export the document as text, observe changes and anchor on element ids without\n * knowing the renderer.\n */\n\nimport {\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 {\n parseDocument,\n serializeDocument,\n type TtDocument,\n} from \"@miragon/team-topologies-schema-model\";\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 { Modeler } from \"../Modeler.js\";\nimport { NavigatedViewer } from \"../NavigatedViewer.js\";\nimport { isTtElement, type TtElement } from \"../model/di-types.js\";\nimport type { Point } from \"../palette/TtPaletteProvider.js\";\n\n/** Stable notation id in `meta.notation` of the collaborative-modeler contract. */\nexport const TEAM_TOPOLOGIES_NOTATION = \"team-topologies\";\n\n/**\n * The contract's factory options (`freeArea`, `fitOnImport`, `undoRedoKeys`; the viewer ignores\n * `freeArea` and `undoRedoKeys`) plus the renderer's own.\n */\nexport interface CollaborativeTeamTopologiesOptions extends CollaborativeModelerOptions {\n /** Appended to the renderer's own modules (e.g. a host's chrome module). */\n additionalModules?: ModuleDeclaration[] | undefined;\n /**\n * @deprecated Since 0.12, the contract's name is `freeArea: { center }`; given both, `freeArea`\n * wins. Accepted for one more minor release.\n */\n freeRectCenter?: (() => Point | undefined) | undefined;\n}\n\n/** The elements surface with the optional `bounds` of contract 1.2, which this renderer has. */\nexport interface TtElementsSurface extends ElementsSurface {\n bounds(id: string): ElementBounds | undefined;\n}\n\n/** The contract surface plus the wrapped diagram for host-specific wiring. */\nexport interface CollaborativeTeamTopologiesModeler extends CollaborativeModeler {\n readonly elements: TtElementsSurface;\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: CollaborativeTeamTopologiesOptions = {},\n): CollaborativeTeamTopologiesModeler {\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 options.fitOnImport ?? true,\n );\n}\n\n/** The read-only mount (`meta.editable: false`): imports, exports and reveals, never edits. */\nexport function createCollaborativeViewer(\n options: CollaborativeTeamTopologiesOptions = {},\n): CollaborativeTeamTopologiesModeler {\n return collaborative(\n new NavigatedViewer(diagramOptions(options)),\n false,\n options.fitOnImport ?? true,\n );\n}\n\nfunction diagramOptions(options: Pick<CollaborativeTeamTopologiesOptions, \"additionalModules\">) {\n return { width: \"100%\", height: \"100%\", additionalModules: options.additionalModules ?? [] };\n}\n\n/**\n * The document text as the contract reads it: blank text is a new, empty diagram (a file just\n * created in an editor), anything else must be a valid document.\n */\nexport function parseDocumentText(text: string): TtDocument {\n const result = parseDocument(text.trim() === \"\" ? {} : JSON.parse(text));\n if (!result.ok) throw new Error(result.error);\n return result.document;\n}\n\nfunction collaborative(\n diagram: Modeler | NavigatedViewer,\n editable: boolean,\n fitOnImport: boolean,\n): CollaborativeTeamTopologiesModeler {\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 importsRunning = 0;\n let destroyed = false;\n let lastExport = \"\";\n\n const meta: ModelerMeta = {\n notation: TEAM_TOPOLOGIES_NOTATION,\n apiVersion: MODELER_API_VERSION,\n editable,\n };\n\n if (editable) {\n eventBus.on(\"commandStack.changed\", () => {\n if (importsRunning > 0) return;\n for (const listener of [...contentListeners]) listener();\n });\n }\n\n const exportText = (): string => serializeDocument(diagram.exportDocument());\n\n const elements: TtElementsSurface = {\n list: () =>\n destroyed ? [] : (elementRegistry.getAll() as unknown[]).filter(isTtElement).map(elementInfo),\n reveal(id) {\n if (destroyed) return false;\n const element = elementRegistry.get(id);\n if (!isTtElement(element)) return false;\n selection.select(element);\n canvas.scrollToElement(element);\n return true;\n },\n selection: () => (destroyed ? [] : elementIds(selection.get())),\n onSelection(callback) {\n const listener = (event: unknown) =>\n callback(elementIds((event as { newSelection?: unknown[] }).newSelection ?? []));\n eventBus.on(\"selection.changed\", listener);\n return () => eventBus.off(\"selection.changed\", listener);\n },\n bounds(id) {\n if (destroyed) return undefined;\n const element = elementRegistry.get(id);\n if (!isTtElement(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 diagram.attachTo(host);\n },\n async importText(text): Promise<ImportResult> {\n if (destroyed) throw new Error(\"The modeler was destroyed.\");\n const document = parseDocumentText(text);\n importsRunning += 1;\n try {\n const { warnings } = diagram.importDocument(document, { fit: fitOnImport });\n return { warnings: warnings.map((warning) => warning.message) };\n } finally {\n importsRunning -= 1;\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 exportText();\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 = exportText();\n } catch {\n lastExport = \"\";\n }\n destroyed = true;\n contentListeners.clear();\n diagram.destroy();\n },\n };\n}\n\n/** Connectors are not addressable: their ids derive from the annotation and are never stored. */\nfunction elementIds(elements: readonly unknown[]): string[] {\n return elements.filter(isTtElement).map((element) => element.id);\n}\n\n/** A team's, interaction's or flow's label; an annotation's text. */\nfunction elementInfo(element: TtElement): ElementInfo {\n const name = element.ttLabel;\n return name ? { id: element.id, name } : { 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,IAAMyB,qBAAmC,IAAI,IAAY;CACvD;CACA;CACA;CACA;AACF,CAAC;AAED,SAASC,EAAO,GAAiC;CAC/C,OAAO,OAAOC,KAAO,YAAYA,IAC3BA,EAA4B,SAC9B,KAAA;AACN;AAEA,SAAgBC,EAAY,GAA8B;CACxD,IAAMC,IAAOH,EAAOC,CAAE;CAC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