All files / src/components WorkflowEditor.vue

82.15% Statements 198/241
71.02% Branches 125/176
72.88% Functions 43/59
86.11% Lines 186/216

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 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042  87x         3x                             82x                                                                                             3x                                                             3x                                                                   46x 46x   46x 41x                                   46x           46x     46x     46x       63x 59x       20x 18x 17x       46x 46x       69x 69x 69x                     24x   24x   21x 21x   19x   2x     3x 3x   1x   2x                       24x   24x   21x 21x   19x   2x     3x 3x   1x   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 1x   2x 1x         1x 1x   2x                                 44x   44x 44x 44x     44x     44x 44x 6x       44x 59x 59x 53x           59x                           44x 18x   18x   18x   18x 35x 17x 17x   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                                                                     46x 46x 46x 46x     4x 4x 4x 4x   4x 1x 3x 3x   4x 4x       4x   4x       1x 1x 1x 1x       5x 5x 5x 5x       5x 5x   5x 3x 1x 1x   2x 2x 2x     2x   5x     2x 2x   2x 2x         2x 1x   2x     2x 2x       1x 1x 1x 1x           1x           2x 1x 1x           2x 2x 2x 1x       46x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
<template>
  <div class="workflow-editor">
    <div>
      <!-- Workflow Editor -->
      <div v-if="modelValue" class="workflow-content">
        <!-- Visual Workflow Editor -->
        <div class="workflow-canvas border rounded position-relative">
          <VueFlow
            :id="flowId"
            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="backgroundPatternColor" :gap="16" />
            <Controls />
 
            <template #node-workflow="nodeProps">
              <!-- State Node -->
              <div
                v-if="!nodeProps.data.isTransition"
                class="workflow-node"
                :class="{ 'workflow-node--start': nodeProps.data.isStart }"
              >
                <!-- 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
                  v-if="!nodeProps.data.isStart"
                  type="button"
                  class="node-edit-btn"
                  :title="t('common.edit')"
                  @click.stop="emit('open-state-panel', nodeProps.data.stateId)"
                >
                  <font-awesome-icon icon="fa-solid fa-pen" />
                </button>
                <button
                  v-if="!nodeProps.data.isStart"
                  type="button"
                  class="node-delete-btn"
                  :title="t('workflow.deleteState')"
                  @click.stop="removeStateByName(nodeProps.data.stateId)"
                >
                  ×
                </button>
                <div
                  class="node-label"
                  @dblclick="emit('open-state-panel', nodeProps.data.stateId)"
                >
                  {{ 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-edit-btn"
                  :title="t('common.edit')"
                  @click.stop="emit('open-transition-panel', nodeProps.data.transitionIndex)"
                >
                  <font-awesome-icon icon="fa-solid fa-pen" />
                </button>
                <button
                  type="button"
                  class="node-delete-btn"
                  :title="t('workflow.deleteTransition')"
                  @click.stop="removeTransition(nodeProps.data.transitionIndex)"
                >
                  ×
                </button>
                <div
                  class="transition-info"
                  @dblclick="emit('open-transition-panel', 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">
// @implements UC-WORKFLOW-001.1
import { computed, 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 { useUILanguage } from '@/composables/useUILanguage'
import { useTheme } from '@/composables/useTheme'
import type { Node, Edge, Connection, VueFlowStore } from '@vue-flow/core'
import type { WorkflowDefinition } from '@/schemas/entity-schema'
 
const { t } = useUILanguage()
const { resolvedTheme } = useTheme()
 
const backgroundPatternColor = computed(() =>
  resolvedTheme.value === 'dark' ? '#5a6470' : '#a5adb8'
)
 
interface Props {
  modelValue?: WorkflowDefinition
  defaultLanguage?: string
  enabledLanguages?: string[]
  currentLanguage?: string
}
 
interface Emits {
  (e: 'update:modelValue', value: WorkflowDefinition | undefined): void
  /** emitted when user double-clicks a state node; payload = state id */
  (e: 'open-state-panel', stateId: string): void
  /** emitted when user double-clicks a transition node; payload = transition index */
  (e: 'open-transition-panel', transitionIndex: number): void
}
 
const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
  defaultLanguage: 'en',
  enabledLanguages: () => ['en', 'fr'],
  currentLanguage: 'en'
})
const emit = defineEmits<Emits>()
 
// Unique id per instance so VueFlow stores don't collide when multiple editors coexist
const flowId = `workflow-editor-${Math.random().toString(36).slice(2, 9)}`
 
// 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] || ''
}
 
// VueFlow state
const nodes = ref<Node[]>([])
const edges = ref<Edge[]>([])
 
// 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' } }
      ],
      startStateId: 'draft'
    })
  } 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
 
  // Prevent deleting the start state
  Iif (stateId === props.modelValue.startStateId) return
  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
  if (nodeId.startsWith('t')) {
    const transitionIndex = parseInt(nodeId.substring(1))
    emit('open-transition-panel', transitionIndex)
  } else {
    emit('open-state-panel', nodeId)
  }
}
 
// Update VueFlow nodes from states and transitions
function updateNodesFromStates() {
  Iif (!props.modelValue) return
 
  const SPACING_X = 320
  const STATE_Y = 150
  const BACK_TRANSITION_Y_OFFSET = -100
  // Offset so transition node handles (vertical center) align with state node handles.
  // .workflow-node height ≈ 50px (center at +25), .transition-node height ≈ 35px (center at +17).
  const TRANSITION_Y_ALIGN = 8 // STATE_Y + 25 - 17
 
  // Keep existing positions for nodes that already exist
  const existingPositions = new Map<string, { x: number; y: number }>()
  for (const n of nodes.value) {
    existingPositions.set(n.id, n.position)
  }
 
  // Create state nodes — horizontal layout: equally spaced along X
  const stateNodes = props.modelValue.states.map((state, index) => {
    let position = props.modelValue!.positions?.[state.id] || existingPositions.get(state.id)
    if (!position) {
      position = {
        x: 50 + index * SPACING_X,
        y: STATE_Y
      }
    }
 
    return {
      id: state.id,
      type: 'workflow',
      position,
      data: {
        label: getStateLabel(state),
        stateId: state.id,
        isTransition: false,
        isStart: state.id === props.modelValue?.startStateId
      }
    }
  })
 
  // 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) {
        const midX = (fromNode.position.x + toNode.position.x) / 2
        // Back-transitions (going left) are placed above the main line
        const isBackward = fromNode.position.x > toNode.position.x
        position = {
          x: midX,
          y: isBackward
            ? STATE_Y + BACK_TRANSITION_Y_OFFSET + TRANSITION_Y_ALIGN
            : STATE_Y + TRANSITION_Y_ALIGN
        }
      } else E{
        position = { x: 50, y: STATE_Y + TRANSITION_Y_ALIGN }
      }
    }
 
    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)
        })
      }
    }
  })
}
 
// --- Node editing logic for tests ---
const editingNodeId = ref<string | null>(null)
const editingNodeLabel = ref<string>('')
const editingNodePermission = ref<string>('')
const editingTransitionIndex = ref<number | null>(null)
 
function updateStateLabel(stateId: string, label: string | Record<string, string>) {
  Iif (!props.modelValue) return
  const states = props.modelValue.states.map((s) => {
    Iif (s.id !== stateId) return s
    let newLabel: Record<string, string> = {}
    // Toujours convertir en multilingue, en préservant les anciennes valeurs
    if (typeof s.label === 'string') {
      newLabel = { [props.defaultLanguage]: s.label }
    } else Eif (typeof s.label === 'object' && s.label !== null) {
      newLabel = { ...s.label }
    }
    if (typeof label === 'string') {
      newLabel[props.currentLanguage] = label
    } else E{
      newLabel = { ...newLabel, ...label }
    }
    return { ...s, label: newLabel }
  })
  emit('update:modelValue', { ...props.modelValue, states })
}
 
function startEditingNode(nodeId: string, label: string) {
  editingNodeId.value = nodeId
  editingNodeLabel.value = label
  editingNodePermission.value = ''
  editingTransitionIndex.value = null
}
 
function cancelEditingNode() {
  editingNodeId.value = null
  editingNodeLabel.value = ''
  editingNodePermission.value = ''
  editingTransitionIndex.value = null
}
 
function finishEditingNode() {
  Iif (!editingNodeId.value || !props.modelValue) return
  const label = editingNodeLabel.value?.trim()
  // State node
  if (!editingNodeId.value.startsWith('t')) {
    if (!label) {
      editingNodeId.value = null
      return
    }
    updateStateLabel(editingNodeId.value, label)
    cancelEditingNode()
    return
  }
  // Transition node — derive index from node ID (e.g. 't0') if not explicitly set
  const idx = editingTransitionIndex.value ?? parseInt(editingNodeId.value.substring(1))
  let transitions
  Iif (isNaN(idx) || idx < 0) {
    transitions = [...props.modelValue.transitions]
  } else {
    transitions = props.modelValue.transitions.map((t, i) => {
      Iif (i !== idx) return t
      // Only keep from/to, always set label and requiresPermission from editingNode* refs
      const perm = editingNodePermission.value?.trim()
      const newTransition: any = {
        from: t.from,
        to: t.to,
        label: { en: label || '' }
      }
      if (perm) {
        newTransition.requiresPermission = perm
      }
      return newTransition
    })
  }
  emit('update:modelValue', { ...props.modelValue, transitions })
  cancelEditingNode()
}
 
function startEditingTransitionNode(nodeId: string, index: number) {
  editingNodeId.value = nodeId
  editingTransitionIndex.value = index
  const t = props.modelValue?.transitions[index]
  editingNodeLabel.value =
    t && t.label
      ? typeof t.label === 'string'
        ? t.label
        : t.label[props.currentLanguage] || ''
      : ''
  editingNodePermission.value = t?.requiresPermission || ''
}
 
// Keyboard and focus event handlers for test access
function onKeyDownEnter(event: KeyboardEvent) {
  // Prevent form submit on Enter if not editing a node
  if (!editingNodeId.value) {
    event.preventDefault?.()
    event.stopPropagation?.()
  }
}
 
function onNodeEditFocusOut(event: FocusEvent) {
  // Only finish editing if focus leaves the edit container
  const container = event.currentTarget as HTMLElement
  const related = event.relatedTarget as HTMLElement | null
  if (!container.contains(related)) {
    finishEditingNode()
  }
}
 
defineExpose({
  updateStateLabel,
  startEditingNode,
  cancelEditingNode,
  finishEditingNode,
  startEditingTransitionNode,
  editingNodeId,
  editingNodeLabel,
  editingNodePermission,
  editingTransitionIndex,
  onKeyDownEnter,
  onNodeEditFocusOut
})
</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;
  background: var(--bw-surface);
  border-color: var(--bw-border) !important;
}
 
:deep(.vue-flow__pane),
:deep(.vue-flow__viewport) {
  background: var(--bw-surface);
}
 
:deep(.vue-flow__background) {
  background: var(--bw-surface);
}
 
/* Controls panel: always bottom-left, horizontal layout */
:deep(.vue-flow__controls) {
  display: flex;
  flex-direction: row;
}
 
/* Reorient button separators for horizontal layout */
:deep(.vue-flow__controls-button) {
  border-bottom: none;
  border-right: 1px solid var(--bw-border);
  background: var(--bw-surface-muted);
  color: var(--bw-text);
}
 
:deep(.vue-flow__controls-button:last-child) {
  border-right: none;
}
 
.workflow-node {
  padding: 12px 20px;
  border-radius: 8px;
  background: var(--bw-surface);
  border: 2px solid #615581;
  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: #4d4267;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
 
.workflow-node--start {
  border-color: #198754;
  box-shadow: 0 2px 8px rgba(25, 135, 84, 0.2);
}
 
.workflow-node--start:hover {
  border-color: #157347;
  box-shadow: 0 4px 12px rgba(25, 135, 84, 0.3);
}
 
.workflow-node--start .node-label {
  color: #198754;
}
 
.workflow-node--start :deep(.vue-flow__handle) {
  background: #198754;
}
 
.set-start-btn {
  margin-top: 6px;
  width: 100%;
  font-size: 11px;
  padding: 3px 8px;
  border: 1px solid #198754;
  border-radius: 4px;
  color: #198754;
  background: #f6fff9;
  cursor: pointer;
  transition: all 0.15s;
}
 
.set-start-btn:hover {
  background: #198754;
  color: white;
}
 
/* Hide handles by default on state nodes */
.workflow-node :deep(.vue-flow__handle) {
  opacity: 0;
  width: 12px;
  height: 12px;
  background: #615581;
  border: 2px solid var(--bw-surface);
  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 var(--bw-surface);
  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;
}
 
.node-edit-btn {
  position: absolute;
  top: -8px;
  right: 16px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #615581;
  color: white;
  border: 2px solid var(--bw-surface);
  font-size: 13px;
  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;
}
 
.workflow-node:hover .node-edit-btn {
  opacity: 1;
}
 
.node-delete-btn:hover {
  background: #bb2d3b;
}
 
.node-label {
  font-size: 14px;
  color: var(--bw-text);
  padding: 4px;
  user-select: none;
  cursor: pointer;
}
 
.transition-node {
  padding: 8px 12px;
  border-radius: 20px;
  background: var(--bw-surface-muted);
  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: color-mix(in srgb, var(--bw-surface-muted) 78%, var(--bw-text) 22%);
}
 
.transition-node:hover .node-delete-btn {
  opacity: 1;
}
 
.transition-node:hover .node-edit-btn {
  opacity: 1;
}
 
.transition-info {
  width: 100%;
  cursor: pointer;
}
 
.transition-label {
  font-size: 12px;
  color: var(--bw-text);
  padding: 2px;
  user-select: none;
  font-style: italic;
}
 
.transition-permission {
  font-size: 10px;
  color: var(--bw-text-muted);
  padding: 2px;
  margin-top: 2px;
  user-select: none;
  font-weight: normal;
}
 
.transition-permission .fa-lock {
  font-size: 9px;
}
 
.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 #615581;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  text-align: center;
  outline: none;
  background: var(--bw-surface);
  color: var(--bw-text);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
 
.edge-edit-input:focus {
  border-color: #4d4267;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25);
}
 
.edge-label-text {
  font-size: 12px;
  color: var(--bw-text-muted);
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 3px;
  background: var(--bw-surface);
  white-space: nowrap;
}
 
.edge-label-text:hover {
  color: #615581;
  background: var(--bw-surface-muted);
}
 
.edge-label-button {
  font-size: 12px;
  color: var(--bw-text-muted);
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  background: var(--bw-surface);
  border: 1px solid var(--bw-border);
  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: #615581;
  background: var(--bw-surface-muted);
  border-color: #615581;
}
 
.edge-label-button:active {
  background: color-mix(in srgb, var(--bw-surface-muted) 78%, var(--bw-text) 22%);
}
</style>