All files / src/components WorkflowEditor.vue

81.01% Statements 192/237
63.54% Branches 122/192
63.01% Functions 46/73
86.05% Lines 179/208

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991  87x 3x       3x                           82x                                                                                                 3x                                                                                                             3x                                                                 46x                         46x           46x     46x       63x 59x       21x 19x 18x       4x 4x     4x   4x 4x 4x           46x 46x     46x 46x 46x 46x       69x 69x 69x                     24x   24x   4x 4x   2x   2x     20x 20x   18x   2x                       24x   24x   4x 4x   2x   2x     20x 20x   18x   2x           1x   1x 1x         46x 46x 5x                                 41x 41x         46x 46x                 46x 46x               46x 87x   41x   41x 41x 71x       41x 41x 35x 35x 35x 35x     41x 34x                   2x 1x 1x 1x       1x             1x     1x   2x 1x         1x 1x   2x                           1x 1x 1x 1x         5x     5x 2x 2x 2x   2x 2x       2x           2x             2x     2x             3x 3x   3x 3x 1x 1x     2x     4x 4x 4x       2x 2x 2x       1x 1x 1x   1x 1x 1x 1x 1x             2x 2x   2x   1x       1x         2x     2x 1x       1x 1x 1x           44x   44x 44x 44x 44x     44x     44x 59x 59x 53x 53x           59x                 44x 18x   18x   18x   18x 35x 17x 17x                 18x                             44x         42x   42x   42x 18x 57x 19x 37x   18x     18x               18x               18x                 18x             18x                   18x             18x                     42x         4x     3x     2x 1x     2x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
<template>
  <div class="workflow-editor" @keydown.enter="onKeyDownEnter">
    <div class="border rounded p-3 bg-light">
      <!-- Workflow Editor -->
      <div v-if="modelValue" class="workflow-content">
        <!-- Visual Workflow Editor -->
        <div class="workflow-canvas border rounded bg-white position-relative">
          <VueFlow
            v-model:nodes="nodes"
            v-model:edges="edges"
            :default-zoom="1"
            :min-zoom="0.5"
            :max-zoom="2"
            :zoom-on-double-click="false"
            :edges-updatable="false"
            @edges-change="onEdgesChange"
            @connect="onConnect"
            @node-double-click="onNodeDoubleClick"
            @init="onVueFlowInit"
          >
            <Background pattern-color="#aaa" :gap="16" />
            <Controls />
            <MiniMap />
 
            <template #node-workflow="nodeProps">
              <!-- State Node -->
              <div v-if="!nodeProps.data.isTransition" class="workflow-node">
                <!-- Connection handles with all positions -->
                <Handle id="left" type="target" :position="Position.Left" />
                <Handle id="right" type="target" :position="Position.Right" />
                <Handle id="top" type="target" :position="Position.Top" />
                <Handle id="bottom" type="target" :position="Position.Bottom" />
                <Handle id="left" type="source" :position="Position.Left" />
                <Handle id="right" type="source" :position="Position.Right" />
                <Handle id="top" type="source" :position="Position.Top" />
                <Handle id="bottom" type="source" :position="Position.Bottom" />
 
                <button
                  type="button"
                  class="node-delete-btn"
                  title="Delete state"
                  @click.stop="removeStateByName(nodeProps.data.stateId)"
                >
                  ×
                </button>
                <div v-if="editingNodeId === nodeProps.id" class="node-edit-container">
                  <input
                    ref="nodeEditInput"
                    v-model="editingNodeLabel"
                    type="text"
                    class="node-edit-input"
                    @mousedown.stop
                    @click.stop
                    @dblclick.stop
                    @blur="finishEditingNode"
                    @keydown.enter.prevent="finishEditingNode"
                    @keydown.esc="cancelEditingNode"
                  />
                </div>
                <div
                  v-else
                  class="node-label"
                  @dblclick="startEditingNode(nodeProps.id, nodeProps.data.label)"
                >
                  {{ nodeProps.data.label }}
                </div>
              </div>
 
              <!-- Transition Node -->
              <div v-else class="transition-node">
                <!-- Connection handles with all positions -->
                <Handle id="left" type="target" :position="Position.Left" />
                <Handle id="right" type="target" :position="Position.Right" />
                <Handle id="top" type="target" :position="Position.Top" />
                <Handle id="bottom" type="target" :position="Position.Bottom" />
                <Handle id="left" type="source" :position="Position.Left" />
                <Handle id="right" type="source" :position="Position.Right" />
                <Handle id="top" type="source" :position="Position.Top" />
                <Handle id="bottom" type="source" :position="Position.Bottom" />
 
                <button
                  type="button"
                  class="node-delete-btn"
                  :title="t('workflow.deleteTransition')"
                  @click.stop="removeTransition(nodeProps.data.transitionIndex)"
                >
                  ×
                </button>
                <div
                  v-if="editingNodeId === nodeProps.id"
                  class="node-edit-container"
                  @focusout="onNodeEditFocusOut"
                >
                  <input
                    ref="nodeEditInput"
                    v-model="editingNodeLabel"
                    type="text"
                    class="transition-edit-input"
                    :placeholder="t('workflow.label')"
                    @mousedown.stop
                    @click.stop
                    @dblclick.stop
                    @keydown.enter.prevent="finishEditingNode"
                    @keydown.esc="cancelEditingNode"
                  />
                  <input
                    v-model="editingNodePermission"
                    type="text"
                    class="transition-permission-input"
                    :placeholder="t('workflow.permissionOptional')"
                    @mousedown.stop
                    @click.stop
                    @dblclick.stop
                    @keydown.enter.prevent="finishEditingNode"
                    @keydown.esc="cancelEditingNode"
                  />
                </div>
                <div
                  v-else
                  class="transition-info"
                  @dblclick="
                    startEditingTransitionNode(nodeProps.id, nodeProps.data.transitionIndex)
                  "
                >
                  <div class="transition-label">
                    {{ nodeProps.data.label || t('common.doubleClickToEdit') }}
                  </div>
                  <div v-if="nodeProps.data.permission" class="transition-permission">
                    <font-awesome-icon icon="fa-solid fa-lock" class="me-1" />
                    {{ nodeProps.data.permission }}
                  </div>
                </div>
              </div>
            </template>
          </VueFlow>
 
          <!-- Add State Button in Canvas -->
          <button type="button" class="btn btn-success btn-sm add-state-btn" @click="addState">
            <font-awesome-icon icon="fa-solid fa-plus" />
            {{ t('workflow.addState') }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
 
<script setup lang="ts">
import { ref, watch, nextTick, onMounted } from 'vue'
import { VueFlow, Handle, Position } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls'
import { MiniMap } from '@vue-flow/minimap'
import { useUILanguage } from '@/composables/useUILanguage'
import type { Node, Edge, Connection, VueFlowStore } from '@vue-flow/core'
import type { WorkflowDefinition } from '@/schemas/entity-schema'
 
const { t } = useUILanguage()
 
interface Props {
  modelValue?: WorkflowDefinition
  defaultLanguage?: string
  enabledLanguages?: string[]
  currentLanguage?: string
}
 
interface Emits {
  (e: 'update:modelValue', value: WorkflowDefinition | undefined): void
}
 
const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
  defaultLanguage: 'en',
  enabledLanguages: () => ['en', 'fr'],
  currentLanguage: 'en'
})
const emit = defineEmits<Emits>()
 
// VueFlow instance
const vueFlowInstance = ref<VueFlowStore | null>(null)
 
// Helper functions for multilingual labels
function getStateLabel(state: { id: string; label: Record<string, string> | string }): string {
  if (typeof state.label === 'string') return state.label
  return state.label[props.currentLanguage] || state.label[props.defaultLanguage] || state.id
}
 
function getTransitionLabel(transition: { label?: Record<string, string> | string }): string {
  if (!transition.label) return ''
  if (typeof transition.label === 'string') return transition.label
  return transition.label[props.currentLanguage] || transition.label[props.defaultLanguage] || ''
}
 
function updateStateLabel(stateId: string, newLabel: string) {
  Iif (!props.modelValue) return
  emit('update:modelValue', {
    ...props.modelValue,
    states: props.modelValue.states.map((s) => {
      Iif (s.id !== stateId) return s
      const label =
        typeof s.label === 'string' ? { [props.defaultLanguage]: s.label } : { ...s.label }
      label[props.currentLanguage] = newLabel
      return { ...s, label }
    })
  })
}
 
// VueFlow state
const nodes = ref<Node[]>([])
const edges = ref<Edge[]>([])
 
// Node editing state
const editingNodeId = ref<string | null>(null)
const editingNodeLabel = ref('')
const editingNodePermission = ref('')
const nodeEditInput = ref<HTMLInputElement | null>(null)
 
// Determine if a connection between two nodes is more horizontal or vertical
function isConnectionHorizontal(fromX: number, fromY: number, toX: number, toY: number): boolean {
  const dx = Math.abs(toX - fromX)
  const dy = Math.abs(toY - fromY)
  return dx >= dy
}
 
// Get the handle position where an edge should EXIT from a node (source handle)
function getSourceHandle(
  fromX: number,
  fromY: number,
  toX: number,
  toY: number,
  isStateNode: boolean = false
): string {
  const horizontal = isConnectionHorizontal(fromX, fromY, toX, toY)
 
  if (horizontal) {
    // Use horizontal handles
    const dx = toX - fromX
    if (isStateNode) {
      // For state nodes, only exit from right
      return 'right'
    }
    return dx > 0 ? 'right' : 'left'
  } else {
    // Use vertical handles
    const dy = toY - fromY
    if (isStateNode) {
      // For state nodes, only exit from bottom
      return 'bottom'
    }
    return dy > 0 ? 'bottom' : 'top'
  }
}
 
// Get the handle position where an edge should ENTER a node (target handle)
function getTargetHandle(
  fromX: number,
  fromY: number,
  toX: number,
  toY: number,
  isStateNode: boolean = false
): string {
  const horizontal = isConnectionHorizontal(fromX, fromY, toX, toY)
 
  if (horizontal) {
    // Use horizontal handles
    const dx = toX - fromX
    if (isStateNode) {
      // For state nodes, only enter from left
      return 'left'
    }
    return dx > 0 ? 'left' : 'right'
  } else {
    // Use vertical handles
    const dy = toY - fromY
    if (isStateNode) {
      // For state nodes, only enter from top
      return 'top'
    }
    return dy > 0 ? 'top' : 'bottom'
  }
}
 
// VueFlow initialization
function onVueFlowInit(instance: VueFlowStore) {
  vueFlowInstance.value = instance
  // Fit view on init
  nextTick(() => {
    instance.fitView({ padding: 0.2, duration: 200 })
  })
}
 
// Initialize workflow if not provided
onMounted(() => {
  if (!props.modelValue) {
    emit('update:modelValue', {
      states: [
        { id: 'draft', label: { en: 'Draft', fr: 'Brouillon' } },
        { id: 'review', label: { en: 'Review', fr: 'Révision' } },
        { id: 'approved', label: { en: 'Approved', fr: 'Approuvé' } }
      ],
      transitions: [
        {
          from: 'draft',
          to: 'review',
          label: { en: 'Submit for review', fr: 'Soumettre pour révision' }
        },
        { from: 'review', to: 'approved', label: { en: 'Approve', fr: 'Approuver' } },
        { from: 'review', to: 'draft', label: { en: 'Reject', fr: 'Rejeter' } }
      ]
    })
  } else {
    updateNodesFromStates()
    updateEdgesFromTransitions()
  }
})
 
// Watch for external changes to modelValue
watch(
  () => props.modelValue,
  () => {
    updateNodesFromStates()
    updateEdgesFromTransitions()
  },
  { deep: true }
)
 
// Watch for language changes to update displayed labels
watch(
  () => props.currentLanguage,
  () => {
    updateNodesFromStates()
    updateEdgesFromTransitions()
  }
)
 
// Watch for node position changes and save them
watch(
  () => nodes.value,
  (newNodes) => {
    Iif (!props.modelValue) return
 
    const positions: Record<string, { x: number; y: number }> = {}
    newNodes.forEach((node) => {
      positions[node.id] = { x: node.position.x, y: node.position.y }
    })
 
    // Only update if positions actually changed
    const currentPositions = props.modelValue.positions || {}
    const hasChanges = Object.keys(positions).some((id) => {
      const current = currentPositions[id]
      const newPos = positions[id]
      Iif (!newPos) return false
      return !current || current.x !== newPos.x || current.y !== newPos.y
    })
 
    if (hasChanges) {
      emit('update:modelValue', {
        ...props.modelValue,
        positions
      })
    }
  },
  { deep: true }
)
 
function addState() {
  if (!props.modelValue) return
  const stateNum = props.modelValue.states.length + 1
  const newStateId = `state_${stateNum}`
  const newState = {
    id: newStateId,
    label: { [props.currentLanguage]: `State ${stateNum}` }
  }
  emit('update:modelValue', {
    ...props.modelValue,
    states: [...props.modelValue.states, newState]
  })
}
 
function removeStateByName(stateId: string) {
  Iif (!props.modelValue) return
 
  // Remove transitions that reference this state and the state itself
  emit('update:modelValue', {
    ...props.modelValue,
    states: props.modelValue.states.filter((s) => s.id !== stateId),
    transitions: props.modelValue.transitions.filter((t) => t.from !== stateId && t.to !== stateId)
  })
}
 
function removeTransition(index: number) {
  Iif (!props.modelValue) return
  emit('update:modelValue', {
    ...props.modelValue,
    transitions: props.modelValue.transitions.filter((_, i) => i !== index)
  })
}
 
// Node editing functions
function onNodeDoubleClick(event: any) {
  const nodeId = event.node.id
  const state = props.modelValue?.states.find((s) => s.id === nodeId)
  if (state) {
    startEditingNode(nodeId, getStateLabel(state))
  }
}
 
function startEditingNode(nodeId: string, label: string) {
  editingNodeId.value = nodeId
  editingNodeLabel.value = label
  nextTick(() => {
    nodeEditInput.value?.focus()
  })
}
 
function finishEditingNode() {
  Iif (!props.modelValue || !editingNodeId.value) return
 
  // Check if it's a transition node
  if (editingNodeId.value.startsWith('t')) {
    const transitionIndex = parseInt(editingNodeId.value.substring(1))
    const transition = props.modelValue.transitions[transitionIndex]
    Iif (!transition) return
 
    const newLabel = editingNodeLabel.value.trim()
    const newPermission = editingNodePermission.value.trim()
 
    // Update the label for the current language
    let updatedLabel: Record<string, string> | string
    Iif (typeof transition.label === 'string' || !transition.label) {
      updatedLabel = {
        [props.defaultLanguage]: transition.label || '',
        [props.currentLanguage]: newLabel
      }
    } else {
      updatedLabel = {
        ...transition.label,
        [props.currentLanguage]: newLabel
      }
    }
 
    // Update both label and permission
    emit('update:modelValue', {
      ...props.modelValue,
      transitions: props.modelValue.transitions.map((t, i) =>
        i === transitionIndex
          ? { ...t, label: updatedLabel, requiresPermission: newPermission || undefined }
          : t
      )
    })
  } else {
    // It's a state node
    const state = props.modelValue.states.find((s) => s.id === editingNodeId.value)
    Iif (!state) return
 
    const newLabel = editingNodeLabel.value.trim()
    if (!newLabel) {
      cancelEditingNode()
      return
    }
 
    updateStateLabel(state.id, newLabel)
  }
 
  editingNodeId.value = null
  editingNodeLabel.value = ''
  editingNodePermission.value = ''
}
 
function cancelEditingNode() {
  editingNodeId.value = null
  editingNodeLabel.value = ''
  editingNodePermission.value = ''
}
 
function startEditingTransitionNode(nodeId: string, transitionIndex: number) {
  Iif (!props.modelValue) return
  const transition = props.modelValue.transitions[transitionIndex]
  Iif (!transition) return
 
  editingNodeId.value = nodeId
  editingNodeLabel.value = getTransitionLabel(transition)
  editingNodePermission.value = transition.requiresPermission || ''
  nextTick(() => {
    nodeEditInput.value?.focus()
  })
}
 
// Handle focus out from node edit container
function onNodeEditFocusOut(event: FocusEvent) {
  // Check if the new focus target is still within the edit container
  const currentTarget = event.currentTarget as HTMLElement
  const relatedTarget = event.relatedTarget as HTMLElement
 
  if (relatedTarget && currentTarget.contains(relatedTarget)) {
    // Focus is moving to another element within the container, don't close
    return
  }
 
  // Focus is leaving the container, finish editing
  finishEditingNode()
}
 
// Prevent Enter from submitting the form
function onKeyDownEnter(event: KeyboardEvent) {
  const target = event.target as HTMLElement
 
  // If editing a node, let it finish editing
  if (editingNodeId.value) {
    return
  }
 
  // For all other inputs, prevent default to avoid form submission
  Eif (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
    event.preventDefault()
    event.stopPropagation()
  }
}
 
// Update VueFlow nodes from states and transitions
function updateNodesFromStates() {
  Iif (!props.modelValue) return
 
  const stateCount = props.modelValue.states.length
  const radius = 150
  const centerX = 300
  const centerY = 200
 
  // Keep existing positions for nodes that already exist
  const existingPositions = new Map(nodes.value.map((n) => [n.id, n.position]))
 
  // Create state nodes
  const stateNodes = props.modelValue.states.map((state, index) => {
    let position = props.modelValue!.positions?.[state.id] || existingPositions.get(state.id)
    if (!position) {
      const angle = (index / stateCount) * 2 * Math.PI - Math.PI / 2
      position = {
        x: centerX + radius * Math.cos(angle),
        y: centerY + radius * Math.sin(angle)
      }
    }
 
    return {
      id: state.id,
      type: 'workflow',
      position,
      data: { label: getStateLabel(state), stateId: state.id, isTransition: false }
    }
  })
 
  // Create transition nodes (one for each transition)
  const transitionNodes = props.modelValue.transitions.map((transition, index) => {
    const transitionId = `t${index}`
    let position =
      props.modelValue!.positions?.[transitionId] || existingPositions.get(transitionId)
 
    if (!position) {
      // Calculate default position between from and to states
      const fromNode = stateNodes.find((n) => n.id === transition.from)
      const toNode = stateNodes.find((n) => n.id === transition.to)
      if (fromNode && toNode) {
        position = {
          x: (fromNode.position.x + toNode.position.x) / 2,
          y: (fromNode.position.y + toNode.position.y) / 2
        }
      } else E{
        position = { x: centerX, y: centerY }
      }
    }
 
    return {
      id: transitionId,
      type: 'workflow',
      position,
      data: {
        label: getTransitionLabel(transition),
        permission: transition.requiresPermission,
        transitionIndex: index,
        isTransition: true,
        from: transition.from,
        to: transition.to
      }
    }
  })
 
  nodes.value = [...stateNodes, ...transitionNodes]
}
 
// Update VueFlow edges from transitions
function updateEdgesFromTransitions() {
  Iif (!props.modelValue) return
 
  const newEdges: Edge[] = []
 
  props.modelValue.transitions.forEach((transition, index) => {
    const transitionId = `t${index}`
    const transitionNode = nodes.value.find((n) => n.id === transitionId)
    const fromNode = nodes.value.find((n) => n.id === transition.from)
    const toNode = nodes.value.find((n) => n.id === transition.to)
 
    Iif (!transitionNode || !fromNode || !toNode) return
 
    // Determine orientation based on the FROM and TO state positions (not the transition node)
    const isHorizontal = isConnectionHorizontal(
      fromNode.position.x,
      fromNode.position.y,
      toNode.position.x,
      toNode.position.y
    )
 
    // Get handle positions for transition node based on state-to-state orientation
    const transitionTargetHandle = isHorizontal
      ? fromNode.position.x < toNode.position.x
        ? 'left'
        : 'right'
      : fromNode.position.y < toNode.position.y
        ? 'top'
        : 'bottom'
 
    const transitionSourceHandle = isHorizontal
      ? fromNode.position.x < toNode.position.x
        ? 'right'
        : 'left'
      : fromNode.position.y < toNode.position.y
        ? 'bottom'
        : 'top'
 
    // Edge from source state to transition node
    const sourceHandle = getSourceHandle(
      fromNode.position.x,
      fromNode.position.y,
      toNode.position.x,
      toNode.position.y,
      true
    )
    newEdges.push({
      id: `e${index}-from`,
      source: transition.from,
      sourceHandle,
      target: transitionId,
      targetHandle: transitionTargetHandle,
      style: { strokeWidth: 2 }
    })
 
    // Edge from transition node to target state
    const targetHandle = getTargetHandle(
      fromNode.position.x,
      fromNode.position.y,
      toNode.position.x,
      toNode.position.y,
      true
    )
    newEdges.push({
      id: `e${index}-to`,
      source: transitionId,
      sourceHandle: transitionSourceHandle,
      target: transition.to,
      targetHandle,
      markerEnd: 'arrowclosed',
      style: { strokeWidth: 2 }
    })
  })
 
  edges.value = newEdges
}
 
// Handle edge changes from VueFlow (when user draws connection)
function onConnect(connection: Connection) {
  if (!props.modelValue || !connection.source || !connection.target) return
 
  // Check if source or target is a transition node - don't allow those connections
  if (connection.source.startsWith('t') || connection.target.startsWith('t')) return
 
  // Add transition
  const existingTransition = props.modelValue.transitions.find(
    (t) => t.from === connection.source && t.to === connection.target
  )
 
  if (!existingTransition) {
    emit('update:modelValue', {
      ...props.modelValue,
      transitions: [
        ...props.modelValue.transitions,
        {
          from: connection.source,
          to: connection.target,
          label: { [props.currentLanguage]: '' }
        }
      ]
    })
  }
}
 
function onEdgesChange(changes: any[]) {
  if (!props.modelValue) return
 
  // Handle edge removal
  changes.forEach((change) => {
    if (change.type === 'remove') {
      const edgeId = change.id
      const edgeIndex = props.modelValue!.transitions.findIndex(
        (_, i) => `e${i}-${_.from}-${_.to}` === edgeId
      )
      if (edgeIndex !== -1) {
        emit('update:modelValue', {
          ...props.modelValue!,
          transitions: props.modelValue!.transitions.filter((_, i) => i !== edgeIndex)
        })
      }
    }
  })
}
</script>
 
<style>
/* Import VueFlow base styles globally without scoping */
@import '@vue-flow/core/dist/style.css';
@import '@vue-flow/core/dist/theme-default.css';
@import '@vue-flow/controls/dist/style.css';
@import '@vue-flow/minimap/dist/style.css';
</style>
 
<style scoped>
.workflow-canvas {
  height: 500px;
  overflow: hidden;
}
 
.workflow-node {
  padding: 12px 20px;
  border-radius: 8px;
  background: rgb(255, 255, 255);
  border: 2px solid #0d6efd;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-weight: 500;
  min-width: 120px;
  text-align: center;
  position: relative;
  cursor: pointer;
}
 
.workflow-node:hover {
  border-color: #0a58ca;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
 
/* Hide handles by default on state nodes */
.workflow-node :deep(.vue-flow__handle) {
  opacity: 0;
  width: 12px;
  height: 12px;
  background: #0d6efd;
  border: 2px solid white;
  transition: opacity 0.2s;
}
 
/* Show handles on hover */
.workflow-node:hover :deep(.vue-flow__handle) {
  opacity: 1;
}
 
.node-delete-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #dc3545;
  color: white;
  border: 2px solid white;
  font-size: 14px;
  line-height: 1;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  padding: 0 0 3px 0;
}
 
.workflow-node:hover .node-delete-btn {
  opacity: 1;
}
 
.node-delete-btn:hover {
  background: #bb2d3b;
}
 
.node-label {
  font-size: 14px;
  color: #0d6efd;
  padding: 4px;
  user-select: none;
}
 
.node-edit-container {
  padding: 0;
}
 
.node-edit-input {
  width: 100%;
  border: 1px solid #0d6efd;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 14px;
  color: #0d6efd;
  text-align: center;
  outline: none;
  background: #f8f9fa;
}
 
.node-edit-input:focus {
  border-color: #0a58ca;
  background: rgb(255, 255, 255);
}
 
.transition-node {
  padding: 8px 12px;
  border-radius: 20px;
  background: #f8f9fa;
  border: 2px solid #6c757d;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  font-weight: 400;
  min-width: 80px;
  text-align: center;
  position: relative;
  cursor: pointer;
  font-size: 12px;
}
 
/* Hide handles on transition nodes */
.transition-node :deep(.vue-flow__handle) {
  opacity: 0;
  pointer-events: all;
}
 
.transition-node:hover {
  border-color: #495057;
  box-shadow: 0 3px 9px rgba(0, 0, 0, 0.15);
  background: #e9ecef;
}
 
.transition-node:hover .node-delete-btn {
  opacity: 1;
}
 
.transition-info {
  width: 100%;
}
 
.transition-label {
  font-size: 12px;
  color: #495057;
  padding: 2px;
  user-select: none;
  font-style: italic;
}
 
.transition-permission {
  font-size: 10px;
  color: #6c757d;
  padding: 2px;
  margin-top: 2px;
  user-select: none;
  font-weight: normal;
}
 
.transition-permission .fa-lock {
  font-size: 9px;
}
 
.transition-edit-input,
.transition-permission-input {
  width: 100%;
  border: 1px solid #6c757d;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 12px;
  color: #495057;
  text-align: center;
  outline: none;
  background: white;
}
 
.transition-permission-input {
  font-size: 10px;
  margin-top: 4px;
}
 
.transition-edit-input:focus,
.transition-permission-input:focus {
  border-color: #495057;
}
 
.add-state-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
 
.add-state-btn:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
 
.state-input {
  width: 100px;
  outline: none;
  font-size: 13px;
}
 
.state-input::placeholder {
  color: rgba(255, 255, 255, 0.7);
}
 
.btn-close-sm {
  width: 0.5em;
  height: 0.5em;
  font-size: 10px;
}
 
.edge-edit-container {
  min-width: 120px;
  position: relative;
  z-index: 1000;
  pointer-events: all;
}
 
.edge-edit-input {
  width: 100%;
  border: 1px solid #0d6efd;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  text-align: center;
  outline: none;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
 
.edge-edit-input:focus {
  border-color: #0a58ca;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25);
}
 
.edge-label-text {
  font-size: 12px;
  color: #6c757d;
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 3px;
  background: white;
  white-space: nowrap;
}
 
.edge-label-text:hover {
  color: #0d6efd;
  background: #f8f9fa;
}
 
.edge-label-button {
  font-size: 12px;
  color: #6c757d;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  background: white;
  border: 1px solid #dee2e6;
  white-space: nowrap;
  font-weight: normal;
  transition: all 0.2s;
  user-select: none;
  position: relative;
  z-index: 1000;
  pointer-events: all;
}
 
.edge-label-button:hover {
  color: #0d6efd;
  background: #f8f9fa;
  border-color: #0d6efd;
}
 
.edge-label-button:active {
  background: #e9ecef;
}
</style>