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 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 | 109x 5x 2x 2x 104x 6x 5x 5x 5x 5x 5x 5x 5x 1x 5x 56x 56x 56x 51x 56x 56x 56x 56x 93x 89x 33x 25x 21x 9x 8x 4x 56x 56x 99x 99x 99x 34x 34x 31x 31x 29x 2x 3x 3x 1x 2x 34x 34x 31x 31x 29x 2x 3x 3x 1x 2x 3x 3x 3x 56x 56x 5x 51x 51x 56x 58x 2x 2x 56x 57x 1x 1x 56x 114x 58x 58x 58x 117x 58x 58x 64x 64x 64x 64x 58x 45x 6x 5x 5x 5x 5x 5x 56x 5x 5x 4x 4x 9x 7x 14x 9x 2x 5x 4x 56x 2x 56x 56x 1x 2x 56x 1x 2x 1x 5x 5x 9x 4x 5x 1x 2x 2x 2x 5x 1x 2x 2x 1x 1x 2x 59x 59x 59x 59x 59x 59x 59x 23x 59x 87x 87x 71x 87x 59x 31x 31x 31x 25x 46x 23x 23x 23x 23x 31x 3x 59x 55x 55x 55x 28x 89x 31x 55x 28x 28x 28x 28x 28x 28x 28x 28x 55x 4x 3x 2x 1x 2x 1x 56x 56x 56x 56x 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 1x 2x 2x 2x 1x 1x 1x 1x 1x 2x 1x 1x 2x 2x 2x 1x 56x | <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">
<!-- min-zoom must stay low enough that fitView() can always shrink an
arbitrarily wide state graph (states are laid out 320px apart) down
to the pane's width — a higher floor clamps the zoom before that,
leaving states outside the visible canvas (AC-9). -->
<VueFlow
:id="flowId"
v-model:nodes="nodes"
v-model:edges="edges"
:default-zoom="1"
:min-zoom="0.1"
: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="btn btn-sm btn-secondary 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="btn btn-sm btn-danger node-delete-btn"
:title="t('workflow.deleteState')"
@click.stop="removeStateByName(nodeProps.data.stateId)"
>
<font-awesome-icon icon="fa-solid fa-times" />
</button>
<div
class="node-label"
@dblclick="emit('open-state-panel', nodeProps.data.stateId)"
>
{{ nodeProps.data.label }}
<font-awesome-icon
v-if="nodeProps.data.timer"
icon="fa-solid fa-clock"
class="ms-1 state-timer-icon"
:title="t('workflow.timer.label')"
data-testid="state-timer-badge"
/>
</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="btn btn-sm btn-secondary 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="btn btn-sm btn-danger node-delete-btn"
:title="t('workflow.deleteTransition')"
@click.stop="removeTransition(nodeProps.data.transitionIndex)"
>
<font-awesome-icon icon="fa-solid fa-times" />
</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" />
{{ t('workflow.permission') }}
</div>
<div
v-if="nodeProps.data.automatic"
class="transition-permission transition-automatic"
data-testid="transition-automatic-badge"
>
<font-awesome-icon icon="fa-solid fa-bolt" class="me-1" />
{{ t('workflow.triggerAutomatic') }}
</div>
<div
v-if="nodeProps.data.emails?.length"
class="transition-permission"
:title="nodeProps.data.emails.join('\n')"
data-testid="transition-emails-badge"
>
<font-awesome-icon icon="fa-solid fa-envelope" class="me-1" />
{{ t('workflow.emailActions.badge') }} ({{ nodeProps.data.emails.length }})
</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>
<!-- Fallback status picker, shown before a state is actually removed -->
<div
v-if="pendingStateRemoval"
class="modal fade show d-block"
role="dialog"
aria-modal="true"
tabindex="-1"
style="background-color: rgba(0, 0, 0, 0.5)"
@click.self="cancelStateRemoval"
>
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-danger text-white">
<h5 class="modal-title">
<font-awesome-icon icon="fa-solid fa-triangle-exclamation" class="me-2" />
{{ t('workflow.deleteStateConfirmTitle') }}
</h5>
<button
type="button"
class="btn-close btn-close-white"
:aria-label="t('common.close')"
@click="cancelStateRemoval"
></button>
</div>
<div class="modal-body">
<p>
{{
t('workflow.deleteStateConfirmMessage').replace('{state}', pendingStateRemovalLabel)
}}
</p>
<label class="form-label small text-muted" for="workflow-fallback-state">
{{ t('workflow.fallbackState') }}
</label>
<select
id="workflow-fallback-state"
v-model="pendingStateRemoval.fallbackStateId"
class="form-select"
>
<option v-for="state in fallbackStateOptions" :key="state.id" :value="state.id">
{{ getStateLabel(state) }}
</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" @click="cancelStateRemoval">
<font-awesome-icon icon="fa-solid fa-xmark" class="me-2" />
{{ t('common.cancel') }}
</button>
<button type="button" class="btn btn-danger" @click="confirmStateRemoval">
<font-awesome-icon icon="fa-solid fa-triangle-exclamation" class="me-2" />
{{ t('workflow.deleteState') }}
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
// @implements UC-WORKFLOW-001.1, UC-WORKFLOW-007.1, UC-WORKFLOW-009.1
import { computed, ref, watch, nextTick, onMounted, onBeforeUnmount } 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 { EmailTemplate, WorkflowDefinition } from '@/schemas/entity-schema'
import { describeEmailAction } from '@/utils/emailTemplates'
import type { ConditionField } from '@/utils/workflowConditions'
const { t } = useUILanguage()
const { resolvedTheme } = useTheme()
const backgroundPatternColor = computed(() =>
resolvedTheme.value === 'dark' ? '#5a6470' : '#a5adb8'
)
interface Props {
modelValue?: WorkflowDefinition
defaultLanguage?: string
enabledLanguages?: string[]
currentLanguage?: string
/** the entity's email templates and fields: summaries of the transitions' emails */
emailTemplates?: EmailTemplate[]
fields?: ConditionField[]
}
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
/**
* emitted right after a state is actually removed (i.e. once a fallback has
* been confirmed) — the caller uses this to record a migration so existing
* items in the removed state get moved to the fallback on save
*/
(e: 'state-removed', payload: { removedStateId: string; fallbackStateId: string }): void
}
const props = withDefaults(defineProps<Props>(), {
modelValue: undefined,
defaultLanguage: 'en',
enabledLanguages: () => ['en', 'fr'],
currentLanguage: 'en',
emailTemplates: () => [],
fields: () => []
})
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] || ''
}
function translate(value: string | Record<string, string> | undefined): string {
if (!value) return ''
if (typeof value === 'string') return value
return (
value[props.currentLanguage] || value[props.defaultLanguage] || Object.values(value)[0] || ''
)
}
// 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 (and renamed templates or fields) to update displayed labels
watch(
() => [props.currentLanguage, props.emailTemplates, props.fields],
() => {
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]
})
scheduleFitView()
}
// fitView() only produces correct bounds once every node's dimensions have
// been measured. VueFlow measures newly-mounted nodes asynchronously (via
// ResizeObserver, after layout/paint), so a plain nextTick() can fire before
// that measurement completes. `onNodesInitialized` only fires on a false→true
// transition, which a burst of rapid addState() calls can miss entirely (a
// node added while a previous one is still unmeasured never causes a fresh
// transition), silently dropping the fitView call. Polling each frame instead
// — and letting a newer call cancel any still-pending older one via the token
// — coalesces a click burst into exactly one fitView, run once every node
// added during the burst has been measured.
let fitViewToken = 0
function scheduleFitView() {
const instance = vueFlowInstance.value
if (!instance) return
const token = ++fitViewToken
const tryFit = () => {
if (token !== fitViewToken) return
const allMeasured =
instance.nodes.length > 0 &&
instance.nodes.every(
(n) => n.handleBounds !== undefined && n.dimensions.width > 0 && n.dimensions.height > 0
)
if (allMeasured) {
instance.fitView({ padding: 0.2, duration: 200 })
} else {
requestAnimationFrame(tryFit)
}
}
requestAnimationFrame(tryFit)
}
// Cancel any in-flight polling loop so it doesn't touch a torn-down VueFlow
// instance after this component unmounts (e.g. the sidebar was closed right
// after clicking "Add State").
onBeforeUnmount(() => {
fitViewToken++
})
// A state is never deleted immediately: the editor must first choose a
// fallback status, since any item currently in the removed state has to be
// migrated somewhere (see entities/update.js's workflowStateMigrations).
const pendingStateRemoval = ref<{ stateId: string; fallbackStateId: string } | null>(null)
const fallbackStateOptions = computed(() => {
Iif (!props.modelValue || !pendingStateRemoval.value) return []
return props.modelValue.states.filter((s) => s.id !== pendingStateRemoval.value!.stateId)
})
const pendingStateRemovalLabel = computed(() => {
Iif (!props.modelValue || !pendingStateRemoval.value) return ''
const state = props.modelValue.states.find((s) => s.id === pendingStateRemoval.value!.stateId)
return state ? getStateLabel(state) : pendingStateRemoval.value.stateId
})
function removeStateByName(stateId: string) {
Iif (!props.modelValue) return
// Prevent deleting the start state
if (stateId === props.modelValue.startStateId) return
const remainingStates = props.modelValue.states.filter((s) => s.id !== stateId)
const defaultFallback = props.modelValue.startStateId || remainingStates[0]?.id || ''
pendingStateRemoval.value = { stateId, fallbackStateId: defaultFallback }
}
function cancelStateRemoval() {
pendingStateRemoval.value = null
}
function confirmStateRemoval() {
Iif (!props.modelValue || !pendingStateRemoval.value) return
const { stateId, fallbackStateId } = pendingStateRemoval.value
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)
})
emit('state-removed', { removedStateId: stateId, fallbackStateId })
pendingStateRemoval.value = null
}
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,
timer: !!state.timer
}
}
})
// 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,
automatic: !!transition.auto,
emails: (transition.actions ?? []).map((action) =>
describeEmailAction(action, props.emailTemplates, {
t,
translate,
fields: props.fields
})
),
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<boolean>(false)
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 = false
editingTransitionIndex.value = null
}
function cancelEditingNode() {
editingNodeId.value = null
editingNodeLabel.value = ''
editingNodePermission.value = false
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 newTransition: any = {
from: t.from,
to: t.to,
label: { en: label || '' }
}
if (editingNodePermission.value) {
newTransition.requiresPermission = true
}
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,
pendingStateRemoval,
fallbackStateOptions,
cancelStateRemoval,
confirmStateRemoval
})
</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);
}
.state-timer-icon {
font-size: 10px;
color: var(--bs-warning-text-emphasis, #997404);
}
.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: -12px;
right: 0px;
color: white;
border: 1px 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: 3px;
}
.node-edit-btn {
position: absolute;
top: -12px;
right: 26px;
color: white;
border: 1px solid var(--bw-border);
font-size: 13px;
line-height: 1;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.2s;
padding: 3px;
}
.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,
.transition-automatic .fa-bolt {
font-size: 9px;
}
.transition-automatic {
color: var(--bs-warning-text-emphasis, #997404);
}
.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>
|