All files / temba-components/src/flow Editor.ts

43.99% Statements 509/1157
45.65% Branches 21/46
37.83% Functions 14/37
43.99% Lines 509/1157

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 115859x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x       59x 59x                       59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x                                                     11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 59x 59x 11x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 11x 11x 11x 11x       11x 11x           11x 11x 11x 11x 11x 11x 11x 11x 11x 59x 1x                             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 59x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 59x                                     59x                             59x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 59x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 59x                         59x                                                                                   59x                                                           59x                                                         59x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 59x                                                                     59x         59x                                     59x                                   59x                                                                                                                                                                             59x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 59x     1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x           1x                                                                                   59x                                                                                                                                             59x 11x 11x 11x 11x 11x 11x 11x                                 11x   11x 11x 11x 11x 11x                                                       11x 11x 11x 11x 59x                                                 59x                                         59x                                                         59x         59x 59x                                                                                 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 48x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 48x 48x 48x 48x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 58x 59x 59x 58x 58x 58x 58x  
import { html, TemplateResult } from 'lit-html';
import { css, PropertyValueMap, unsafeCSS } from 'lit';
import { property, state } from 'lit/decorators.js';
import {
  FlowDefinition,
  FlowPosition,
  Action,
  Node,
  NodeUI
} from '../store/flow-definition';
import { getStore } from '../store/Store';
import { AppState, fromStore, zustand } from '../store/AppState';
import { RapidElement } from '../RapidElement';
import { repeat } from 'lit-html/directives/repeat.js';
import { CustomEventType } from '../interfaces';
 
import { Plumber } from './Plumber';
import { CanvasNode } from './CanvasNode';
import { Dialog } from '../layout/Dialog';
import { Connection } from '@jsplumb/browser-ui';
 
export function snapToGrid(value: number): number {
  const snapped = Math.round(value / 20) * 20;
  return Math.max(snapped, 0);
}
 
export function findNodeForExit(
  definition: FlowDefinition,
  exitUuid: string
): string | null {
  for (const node of definition.nodes) {
    const exit = node.exits.find((e) => e.uuid === exitUuid);
    if (exit) {
      return node.uuid;
    }
  }
  return null;
}
 
const SAVE_QUIET_TIME = 500;
 
export interface DraggableItem {
  uuid: string;
  position: FlowPosition;
  element: HTMLElement;
  type: 'node' | 'sticky';
}
 
export interface SelectionBox {
  startX: number;
  startY: number;
  endX: number;
  endY: number;
}
 
const DRAG_THRESHOLD = 5;
 
export class Editor extends RapidElement {
  // unfortunately, jsplumb requires that we be in light DOM
  createRenderRoot() {
    return this;
  }
 
  // this is the master plumber
  private plumber: Plumber;
 
  // timer for debounced saving
  private saveTimer: number | null = null;
 
  @property({ type: String })
  public flow: string;
 
  @property({ type: String })
  public version: string;
 
  @fromStore(zustand, (state: AppState) => state.flowDefinition)
  private definition!: FlowDefinition;
 
  @fromStore(zustand, (state: AppState) => state.canvasSize)
  private canvasSize!: { width: number; height: number };
 
  @fromStore(zustand, (state: AppState) => state.dirtyDate)
  private dirtyDate!: Date;
 
  // Drag state
  @state()
  private isDragging = false;
  private isMouseDown = false;
  private dragStartPos = { x: 0, y: 0 };

  // Public getter for drag state
  public get dragging(): boolean {
    return this.isDragging;
  }

  @state()
  private currentDragItem: DraggableItem | null = null;
  private startPos = { left: 0, top: 0 };

  // Selection state
  @state()
  private selectedItems: Set<string> = new Set();

  @state()
  private isSelecting = false;

  @state()
  private selectionBox: SelectionBox | null = null;

  @state()
  private targetId: string | null = null;

  @state()
  private sourceId: string | null = null;
 
  @state()
  private dragFromNodeId: string | null = null;
 
  @state()
  private isValidTarget = true;
 
  // NodeEditor state - handles both node and action editing
  @state()
  private editingNode: Node | null = null;
 
  @state()
  private editingNodeUI: NodeUI | null = null;
 
  @state()
  private editingAction: Action | null = null;
 
  private canvasMouseDown = false;
 
  // Bound event handlers to maintain proper 'this' context
  private boundMouseMove = this.handleMouseMove.bind(this);
  private boundMouseUp = this.handleMouseUp.bind(this);
  private boundGlobalMouseDown = this.handleGlobalMouseDown.bind(this);
  private boundKeyDown = this.handleKeyDown.bind(this);
  private boundCanvasDoubleClick = this.handleCanvasDoubleClick.bind(this);
 
  static get styles() {
    return css`
      #editor {
        overflow: scroll;
        flex: 1;
      }
 
      #grid {
        position: relative;
        background-color: #f9f9f9;
        background-image: radial-gradient(
          circle,
          rgba(61, 177, 255, 0.3) 1px,
          transparent 1px
        );
        background-size: 20px 20px;
        background-position: 10px 10px;
        box-shadow: inset -5px 0 10px rgba(0, 0, 0, 0.05);
        border-top: 1px solid #e0e0e0;
        width: 100%;
        display: flex;
      }
 
      #canvas {
        position: relative;
        padding: 0px;
        flex-grow: 1;
        margin: 20px;
      }
 
      #canvas > .draggable {
        position: absolute;
        z-index: 100;
      }
 
      #canvas > .dragging {
        z-index: 99999 !important;
      }
 
      body .jtk-endpoint {
        width: initial;
        height: initial;
      }
 
      .jtk-endpoint {
        z-index: 600;
        opacity: 0;
      }
 
      .plumb-source {
        z-index: 600;
        cursor: pointer;
        opacity: 0;
      }
 
      .plumb-source.connected {
        border-radius: 50%;
        pointer-events: none;
      }
 
      .plumb-source circle {
        fill: purple;
      }
 
      .plumb-target {
        z-index: 600;
        opacity: 0;
        cursor: pointer;
        fill: transparent;
      }
 
      body svg.jtk-connector.plumb-connector path {
        stroke: var(--color-connectors) !important;
        stroke-width: 3px;
      }
 
      body .plumb-connector {
        z-index: 10 !important;
      }
 
      body .plumb-connector .plumb-arrow {
        fill: var(--color-connectors);
        stroke: var(--color-connectors);
        stroke-width: 0px !important;
        margin-top: 6px;
        z-index: 10;
      }
 
      body svg.jtk-connector.jtk-hover path {
        stroke: var(--color-success) !important;
        stroke-width: 3px;
      }
 
      body .plumb-connector.jtk-hover .plumb-arrow {
        fill: var(--color-success) !important;
        stroke-width: 0px;
        z-index: 10;
      }
 
      /* Connection dragging feedback */
      body svg.jtk-connector.jtk-dragging {
        z-index: 99999 !important;
      }
 
      .katavorio-drag-no-select svg.jtk-connector path,
      .katavorio-drag-no-select svg.jtk-endpoint path {
        pointer-events: none !important;
        border: 1px solid purple;
      }
 
      /* Connection target feedback */
      temba-flow-node.connection-target-valid {
        outline: 3px solid var(--color-success, #22c55e) !important;
        outline-offset: 2px;
        border-radius: var(--curvature);
      }
 
      temba-flow-node.connection-target-invalid {
        outline: 3px solid var(--color-error, #ef4444) !important;
        outline-offset: 2px;
        border-radius: var(--curvature);
      }
 
      /* Selection box styles */
      .selection-box {
        position: absolute;
        border: 2px dashed #6298f0ff;
        background-color: rgba(59, 130, 246, 0.1);
        z-index: 9999;
        pointer-events: none;
      }
 
      /* Selected item styles */
      .draggable.selected {
        outline: 3px solid #6298f0ff;
        outline-offset: 0px;
        border-radius: var(--curvature);
      }
 
      .jtk-floating-endpoint {
        pointer-events: none;
      }
    `;
  }
 
  constructor() {
    super();
  }
 
  protected firstUpdated(
    changes: PropertyValueMap<any> | Map<PropertyKey, unknown>
  ): void {
    super.firstUpdated(changes);
    this.plumber = new Plumber(this.querySelector('#canvas'));
    this.setupGlobalEventListeners();
    if (changes.has('flow')) {
      getStore().getState().fetchRevision(`/flow/revisions/${this.flow}`);
    }

    this.plumber.on('connection:drag', (info: Connection) => {
      this.dragFromNodeId = document
        .getElementById(info.sourceId)
        .closest('.node').id;
      this.sourceId = info.sourceId;
    });

    this.plumber.on('connection:abort', () => {
      this.makeConnection();
    });
 
    this.plumber.on('connection:detach', () => {
      this.makeConnection();
    });
  }
 
  private makeConnection() {
    if (this.sourceId && this.targetId && this.isValidTarget) {
      this.plumber.connectIds(
        this.dragFromNodeId,
        this.sourceId,
        this.targetId
      );
      getStore()
        .getState()
        .updateConnection(this.dragFromNodeId, this.sourceId, this.targetId);

      setTimeout(() => {
        this.plumber.repaintEverything();
      }, 100);
    }

    // Clean up visual feedback
    document.querySelectorAll('temba-flow-node').forEach((node) => {
      node.classList.remove(
        'connection-target-valid',
        'connection-target-invalid'
      );
    });
 
    this.sourceId = null;
    this.targetId = null;
    this.dragFromNodeId = null;
    this.isValidTarget = true;
  }
 
  protected updated(
    changes: PropertyValueMap<any> | Map<PropertyKey, unknown>
  ): void {
    super.updated(changes);
    if (changes.has('canvasSize')) {
      // console.log('Setting canvas size', this.canvasSize);
    }
 
    if (changes.has('definition')) {
      this.updateCanvasSize();
    }
 
    if (changes.has('dirtyDate')) {
      if (this.dirtyDate) {
        this.debouncedSave();
      }
    }
  }
 
  private debouncedSave(): void {
    // Clear any existing timer
    if (this.saveTimer !== null) {
      clearTimeout(this.saveTimer);
    }

    this.saveTimer = window.setTimeout(() => {
      const now = new Date();
      const timeSinceLastChange = now.getTime() - this.dirtyDate.getTime();

      if (timeSinceLastChange >= SAVE_QUIET_TIME) {
        this.saveChanges();
        this.saveTimer = null;
      } else {
        this.debouncedSave();
      }
    }, SAVE_QUIET_TIME);
  }

  private saveChanges(): void {
    // post the flow definition to the server
    getStore()
      .postJSON(`/flow/revisions/${this.flow}`, this.definition)
      .then((response) => {
        // Update flow info with the response data
        if (response.json && response.json.info) {
          getStore().getState().setFlowInfo(response.json.info);
        }
      })
      .catch((error) => {
        console.error('Failed to save flow:', error);
      });

    getStore().getState().setDirtyDate(null);
  }

  disconnectedCallback(): void {
    super.disconnectedCallback();
    if (this.saveTimer !== null) {
      clearTimeout(this.saveTimer);
      this.saveTimer = null;
    }
    document.removeEventListener('mousemove', this.boundMouseMove);
    document.removeEventListener('mouseup', this.boundMouseUp);
    document.removeEventListener('mousedown', this.boundGlobalMouseDown);
    document.removeEventListener('keydown', this.boundKeyDown);
 
    const canvas = this.querySelector('#canvas');
    if (canvas) {
      canvas.removeEventListener('dblclick', this.boundCanvasDoubleClick);
    }
  }
 
  private setupGlobalEventListeners(): void {
    document.addEventListener('mousemove', this.boundMouseMove);
    document.addEventListener('mouseup', this.boundMouseUp);
    document.addEventListener('mousedown', this.boundGlobalMouseDown);
    document.addEventListener('keydown', this.boundKeyDown);
 
    const canvas = this.querySelector('#canvas');
    if (canvas) {
      canvas.addEventListener('dblclick', this.boundCanvasDoubleClick);
    }
 
    // Listen for action edit requests from flow nodes
    this.addEventListener(
      CustomEventType.ActionEditRequested,
      this.handleActionEditRequested.bind(this)
    );
 
    // Listen for node edit requests from flow nodes
    this.addEventListener(
      CustomEventType.NodeEditRequested,
      this.handleNodeEditRequested.bind(this)
    );
  }
 
  private getPosition(uuid: string, type: 'node' | 'sticky'): FlowPosition {
    if (type === 'node') {
      return this.definition._ui.nodes[uuid]?.position;
    } else {
      return this.definition._ui.stickies?.[uuid]?.position;
    }
  }

  private handleMouseDown(event: MouseEvent): void {
    // ignore right clicks
    if (event.button !== 0) return;

    const element = event.currentTarget as HTMLElement;
    // Only start dragging if clicking on the element itself, not on exits or other interactive elements
    const target = event.target as HTMLElement;
    if (target.classList.contains('exit') || target.closest('.exit')) {
      return;
    }

    const uuid = element.getAttribute('uuid');
    const type = element.tagName === 'TEMBA-FLOW-NODE' ? 'node' : 'sticky';

    const position = this.getPosition(uuid, type);
    if (!position) return;

    // If clicking on a non-selected item, clear selection unless Ctrl/Cmd is held
    if (!this.selectedItems.has(uuid) && !event.ctrlKey && !event.metaKey) {
      this.selectedItems.clear();
      // Don't add single items to selection - single clicks just clear existing selection
    } else if (!this.selectedItems.has(uuid)) {
      // Add this item to selection only if Ctrl/Cmd is held
      this.selectedItems.add(uuid);
    }

    // Always set up drag state regardless of selection status
    // This allows single nodes to be dragged without being selected
    this.isMouseDown = true;
    this.dragStartPos = { x: event.clientX, y: event.clientY };
    this.startPos = { left: position.left, top: position.top };
    this.currentDragItem = {
      uuid,
      position,
      element,
      type
    };

    event.preventDefault();
    event.stopPropagation();
  }

  private handleGlobalMouseDown(event: MouseEvent): void {
    // ignore right clicks
    if (event.button !== 0) return;

    // Check if the click is within our canvas
    const canvasRect = this.querySelector('#grid')?.getBoundingClientRect();

    if (!canvasRect) return;

    const isWithinCanvas =
      event.clientX >= canvasRect.left &&
      event.clientX <= canvasRect.right &&
      event.clientY >= canvasRect.top &&
      event.clientY <= canvasRect.bottom;

    if (!isWithinCanvas) return;

    // Check if we clicked on a draggable item (node or sticky)
    const target = event.target as HTMLElement;
    const clickedOnDraggable = target.closest('.draggable');

    if (clickedOnDraggable) {
      // This is handled by the individual item mousedown handlers
      return;
    }

    // We clicked on empty canvas space, start selection
    this.handleCanvasMouseDown(event);
  }

  private handleCanvasMouseDown(event: MouseEvent): void {
    const target = event.target as HTMLElement;
    if (target.id === 'canvas' || target.id === 'grid') {
      // Ignore clicks on exits

      // Start selection box
      this.canvasMouseDown = true;
      this.dragStartPos = { x: event.clientX, y: event.clientY };

      const canvasRect = this.querySelector('#canvas')?.getBoundingClientRect();
      if (canvasRect) {
        // Clear current selection
        this.selectedItems.clear();

        const relativeX = event.clientX - canvasRect.left;
        const relativeY = event.clientY - canvasRect.top;

        this.selectionBox = {
          startX: relativeX,
          startY: relativeY,
          endX: relativeX,
          endY: relativeY
        };
      }

      event.preventDefault();
    }
  }

  private handleKeyDown(event: KeyboardEvent): void {
    if (event.key === 'Delete' || event.key === 'Backspace') {
      if (this.selectedItems.size > 0) {
        this.showDeleteConfirmation();
      }
    }
    if (event.key === 'Escape') {
      this.selectedItems.clear();
      this.requestUpdate();
    }
  }
 
  private showDeleteConfirmation(): void {
    const itemCount = this.selectedItems.size;
    const itemType = itemCount === 1 ? 'item' : 'items';
 
    // Create and show confirmation dialog
    const dialog = document.createElement('temba-dialog') as Dialog;
    dialog.header = 'Delete Items';
    dialog.primaryButtonName = 'Delete';
    dialog.cancelButtonName = 'Cancel';
    dialog.destructive = true;
    dialog.innerHTML = `<div style="padding: 20px;">Are you sure you want to delete ${itemCount} ${itemType}?</div>`;

    dialog.addEventListener('temba-button-clicked', (event: any) => {
      if (event.detail.button.name === 'Delete') {
        this.deleteSelectedItems();
        dialog.open = false;
      }
    });

    // Add to document and show
    document.body.appendChild(dialog);
    dialog.open = true;

    // Clean up dialog when closed
    dialog.addEventListener('temba-dialog-hidden', () => {
      document.body.removeChild(dialog);
    });
  }

  private deleteNodes(uuids: string[]): void {
    // Clean up jsPlumb connections for nodes before removing them
    uuids.forEach((uuid) => {
      this.plumber.removeNodeConnections(uuid);
    });

    // Now remove them from the definition
    if (uuids.length > 0 && this.plumber) {
      getStore().getState().removeNodes(uuids);
    }
  }

  private deleteSelectedItems(): void {
    const nodes = Array.from(this.selectedItems).filter((uuid) =>
      this.definition.nodes.some((node) => node.uuid === uuid)
    );
    this.deleteNodes(Array.from(nodes));

    const stickies = Array.from(this.selectedItems).filter(
      (uuid) => this.definition._ui?.stickies?.[uuid]
    );

    getStore().getState().removeStickyNotes(stickies);

    // Clear selection
    this.selectedItems.clear();
  }

  private updateSelectionBox(event: MouseEvent): void {
    if (!this.selectionBox || !this.canvasMouseDown) return;

    const canvasRect = this.querySelector('#canvas')?.getBoundingClientRect();
    if (!canvasRect) return;

    const relativeX = event.clientX - canvasRect.left;
    const relativeY = event.clientY - canvasRect.top;

    this.selectionBox = {
      ...this.selectionBox,
      endX: relativeX,
      endY: relativeY
    };

    // Update selected items based on selection box
    this.updateSelectedItemsFromBox();
  }

  private updateSelectedItemsFromBox(): void {
    if (!this.selectionBox) return;

    const newSelection = new Set<string>();

    const boxLeft = Math.min(this.selectionBox.startX, this.selectionBox.endX);
    const boxTop = Math.min(this.selectionBox.startY, this.selectionBox.endY);
    const boxRight = Math.max(this.selectionBox.startX, this.selectionBox.endX);
    const boxBottom = Math.max(
      this.selectionBox.startY,
      this.selectionBox.endY
    );

    // Check nodes
    this.definition?.nodes.forEach((node) => {
      const nodeElement = this.querySelector(`[id="${node.uuid}"]`);
      if (nodeElement) {
        const position = this.definition._ui?.nodes[node.uuid]?.position;
        if (position) {
          const rect = nodeElement.getBoundingClientRect();
          const canvasRect =
            this.querySelector('#canvas')?.getBoundingClientRect();

          if (canvasRect) {
            const nodeLeft = position.left;
            const nodeTop = position.top;
            const nodeRight = nodeLeft + rect.width;
            const nodeBottom = nodeTop + rect.height;

            // Check if selection box intersects with node
            if (
              boxLeft < nodeRight &&
              boxRight > nodeLeft &&
              boxTop < nodeBottom &&
              boxBottom > nodeTop
            ) {
              newSelection.add(node.uuid);
            }
          }
        }
      }
    });

    // Check sticky notes
    const stickies = this.definition?._ui?.stickies || {};
    Object.entries(stickies).forEach(([uuid, sticky]) => {
      if (sticky.position) {
        const stickyElement = this.querySelector(
          `temba-sticky-note[uuid="${uuid}"]`
        ) as HTMLElement;

        if (stickyElement) {
          // Use clientWidth/clientHeight instead of getBoundingClientRect() to get element dimensions
          // This avoids the coordinate system mismatch between viewport and canvas coordinates
          const width = stickyElement.clientWidth;
          const height = stickyElement.clientHeight;

          // Use the canvas coordinates from the sticky's position
          const stickyLeft = sticky.position.left;
          const stickyTop = sticky.position.top;
          const stickyRight = stickyLeft + width;
          const stickyBottom = stickyTop + height;

          // Check if selection box intersects with sticky
          if (
            boxLeft < stickyRight &&
            boxRight > stickyLeft &&
            boxTop < stickyBottom &&
            boxBottom > stickyTop
          ) {
            newSelection.add(uuid);
          }
        }
      }
    });

    this.selectedItems = newSelection;
  }

  private renderSelectionBox(): TemplateResult | string {
    if (!this.selectionBox || !this.isSelecting) return '';

    const left = Math.min(this.selectionBox.startX, this.selectionBox.endX);
    const top = Math.min(this.selectionBox.startY, this.selectionBox.endY);
    const width = Math.abs(this.selectionBox.endX - this.selectionBox.startX);
    const height = Math.abs(this.selectionBox.endY - this.selectionBox.startY);

    return html`<div
      class="selection-box"
      style="left: ${left}px; top: ${top}px; width: ${width}px; height: ${height}px;"
    ></div>`;
  }

  private handleMouseMove(event: MouseEvent): void {
    // Handle selection box drawing
    if (this.canvasMouseDown && !this.isMouseDown) {
      this.isSelecting = true;
      this.updateSelectionBox(event);
      this.requestUpdate(); // Force re-render
      return;
    }
 
    if (this.plumber.connectionDragging) {
      const targetNode = document.querySelector('temba-flow-node:hover');
 
      // Clear previous target styles
      document.querySelectorAll('temba-flow-node').forEach((node) => {
        node.classList.remove(
          'connection-target-valid',
          'connection-target-invalid'
        );
      });
 
      if (targetNode) {
        this.targetId = targetNode.getAttribute('uuid');
        // Check if target is different from source node (prevent self-targeting)
        this.isValidTarget = this.targetId !== this.dragFromNodeId;

        // Apply visual feedback based on validity
        if (this.isValidTarget) {
          targetNode.classList.add('connection-target-valid');
        } else {
          targetNode.classList.add('connection-target-invalid');
        }
      } else {
        this.targetId = null;
        this.isValidTarget = true;
      }
    }
 
    // Handle item dragging
    if (!this.isMouseDown || !this.currentDragItem) return;
 
    const deltaX = event.clientX - this.dragStartPos.x;
    const deltaY = event.clientY - this.dragStartPos.y;
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
 
    // Only start dragging if we've moved beyond the threshold
    if (!this.isDragging && distance > DRAG_THRESHOLD) {
      this.isDragging = true;
    }
 
    // If we're actually dragging, update positions
    if (this.isDragging) {
      // Determine what items to move
      const itemsToMove =
        this.selectedItems.has(this.currentDragItem.uuid) &&
        this.selectedItems.size > 1
          ? Array.from(this.selectedItems)
          : [this.currentDragItem.uuid];

      itemsToMove.forEach((uuid) => {
        const element = this.querySelector(`[uuid="${uuid}"]`) as HTMLElement;
        if (element) {
          const type =
            element.tagName === 'TEMBA-FLOW-NODE' ? 'node' : 'sticky';
          const position = this.getPosition(uuid, type);

          if (position) {
            const newLeft = position.left + deltaX;
            const newTop = position.top + deltaY;

            // Update the visual position during drag
            element.style.left = `${newLeft}px`;
            element.style.top = `${newTop}px`;

            // Add dragging class to ensure highest z-index
            element.classList.add('dragging');
          }
        }
      });

      this.plumber.revalidate(itemsToMove);
    }
  }

  private handleMouseUp(event: MouseEvent): void {
    // Handle selection box completion
    if (this.canvasMouseDown && this.isSelecting) {
      this.isSelecting = false;
      this.selectionBox = null;
      this.canvasMouseDown = false;
      this.requestUpdate();
      return;
    }

    // Handle canvas click (clear selection)
    if (this.canvasMouseDown && !this.isSelecting) {
      this.canvasMouseDown = false;
      return;
    }

    // Handle item drag completion
    if (!this.isMouseDown || !this.currentDragItem) return;

    // If we were actually dragging, handle the drag end
    if (this.isDragging) {
      const deltaX = event.clientX - this.dragStartPos.x;
      const deltaY = event.clientY - this.dragStartPos.y;

      // Determine what items were moved
      const itemsToMove =
        this.selectedItems.has(this.currentDragItem.uuid) &&
        this.selectedItems.size > 1
          ? Array.from(this.selectedItems)
          : [this.currentDragItem.uuid];

      // Update positions for all moved items
      const newPositions: { [uuid: string]: FlowPosition } = {};

      itemsToMove.forEach((uuid) => {
        const type = this.definition.nodes.find((node) => node.uuid === uuid)
          ? 'node'
          : 'sticky';
        const position = this.getPosition(uuid, type);

        if (position) {
          const newLeft = position.left + deltaX;
          const newTop = position.top + deltaY;

          // Snap to 20px grid for final position
          const snappedLeft = snapToGrid(newLeft);
          const snappedTop = snapToGrid(newTop);

          const newPosition = { left: snappedLeft, top: snappedTop };
          newPositions[uuid] = newPosition;

          // Remove dragging class
          const element = this.querySelector(`[uuid="${uuid}"]`) as HTMLElement;
          if (element) {
            element.classList.remove('dragging');
            element.style.left = `${snappedLeft}px`;
            element.style.top = `${snappedTop}px`;
          }
        }
      });

      if (Object.keys(newPositions).length > 0) {
        getStore().getState().updateCanvasPositions(newPositions);

        setTimeout(() => {
          this.plumber.repaintEverything();
        }, 0);
      }

      this.selectedItems.clear();
    }

    // Reset all drag state
    this.isDragging = false;
    this.isMouseDown = false;
    this.currentDragItem = null;
    this.canvasMouseDown = false;
  }

  private updateCanvasSize(): void {
    if (!this.definition) return;

    const store = getStore();
    if (!store) return;

    // Calculate required canvas size based on all elements
    let maxWidth = 0;
    let maxHeight = 0;

    // Check node positions
    this.definition.nodes.forEach((node) => {
      const ui = this.definition._ui.nodes[node.uuid];
      if (ui && ui.position) {
        const nodeElement = this.querySelector(`[id="${node.uuid}"]`);
        if (nodeElement) {
          const rect = nodeElement.getBoundingClientRect();
          maxWidth = Math.max(maxWidth, ui.position.left + rect.width);
          maxHeight = Math.max(maxHeight, ui.position.top + rect.height);
        }
      }
    });
 
    // Check sticky note positions
    const stickies = this.definition._ui?.stickies || {};
    Object.entries(stickies).forEach(([uuid, sticky]) => {
      if (sticky.position) {
        const stickyElement = this.querySelector(
          `temba-sticky-note[uuid="${uuid}"]`
        ) as HTMLElement;
        if (stickyElement) {
          // Use clientWidth/clientHeight instead of getBoundingClientRect() to get element dimensions
          // This avoids the coordinate system mismatch between viewport and canvas coordinates
          const width = stickyElement.clientWidth;
          const height = stickyElement.clientHeight;

          // Both sticky.position and width/height are now in the same coordinate system
          maxWidth = Math.max(maxWidth, sticky.position.left + width);
          maxHeight = Math.max(maxHeight, sticky.position.top + height);
        } else {
          // Fallback to default sizes if element not found
          maxWidth = Math.max(maxWidth, sticky.position.left + 200);
          maxHeight = Math.max(maxHeight, sticky.position.top + 100);
        }
      }
    });
 
    // Update canvas size in store
    store.getState().expandCanvas(maxWidth, maxHeight);
  }

  private handleCanvasDoubleClick(event: MouseEvent): void {
    // Check if we double-clicked on empty canvas space
    const target = event.target as HTMLElement;
    if (target.id !== 'canvas') {
      return;
    }

    // Get canvas position
    const canvas = this.querySelector('#canvas');
    if (!canvas) {
      return;
    }

    const canvasRect = canvas.getBoundingClientRect();
    const relativeX = event.clientX - canvasRect.left - 10;
    const relativeY = event.clientY - canvasRect.top - 10;

    // Snap position to grid
    const snappedLeft = snapToGrid(relativeX);
    const snappedTop = snapToGrid(relativeY);

    // Create new sticky note
    const store = getStore();
    store.getState().createStickyNote({
      left: snappedLeft,
      top: snappedTop
    });
 
    event.preventDefault();
    event.stopPropagation();
  }

  private handleActionEditRequested(event: CustomEvent): void {
    // For action editing, we set the action and find the corresponding node
    this.editingAction = event.detail.action;

    // Find the node that contains this action
    const nodeUuid = event.detail.nodeUuid;
    const node = this.definition.nodes.find((n) => n.uuid === nodeUuid);

    if (node) {
      this.editingNode = node;
      this.editingNodeUI = this.definition._ui.nodes[nodeUuid];
    }
  }
  private handleNodeEditRequested(event: CustomEvent): void {
    this.editingNode = event.detail.node;
    this.editingNodeUI = event.detail.nodeUI;
  }

  private handleActionSaved(updatedAction: Action): void {
    if (this.editingNode && this.editingAction) {
      // Update the specific action in the node
      const updatedActions = this.editingNode.actions.map((action) =>
        action.uuid === this.editingAction.uuid ? updatedAction : action
      );
      const updatedNode = { ...this.editingNode, actions: updatedActions };

      // Update the node in the store
      getStore()?.getState().updateNode(this.editingNode.uuid, updatedNode);

      // Repaint jsplumb connections in case node size changed
      if (this.plumber) {
        // Use requestAnimationFrame to ensure DOM has been updated first
        requestAnimationFrame(() => {
          this.plumber.repaintEverything();
        });
      }
    }
    this.closeNodeEditor();
  }

  private closeNodeEditor(): void {
    this.editingNode = null;
    this.editingNodeUI = null;
    this.editingAction = null;
  }

  private handleActionEditCanceled(): void {
    this.closeNodeEditor();
  }

  private handleNodeSaved(updatedNode: Node): void {
    if (this.editingNode) {
      // Clean up jsPlumb connections for removed exits before updating the node
      if (this.plumber) {
        const oldExits = this.editingNode.exits || [];
        const newExits = updatedNode.exits || [];

        // Find exits that were removed
        const removedExits = oldExits.filter(
          (oldExit) =>
            !newExits.find((newExit) => newExit.uuid === oldExit.uuid)
        );

        // Remove jsPlumb connections for removed exits
        removedExits.forEach((exit) => {
          this.plumber.removeExitConnection(exit.uuid);
        });
      }

      this.plumber.revalidate([updatedNode.uuid]);

      // Update the node in the store
      getStore()?.getState().updateNode(this.editingNode.uuid, updatedNode);

      // Repaint jsplumb connections in case node size changed
      if (this.plumber) {
        // Use requestAnimationFrame to ensure DOM has been updated first
        requestAnimationFrame(() => {
          this.plumber.repaintEverything();
        });
      }
    }
    this.closeNodeEditor();
  }

  private handleNodeEditCanceled(): void {
    this.closeNodeEditor();
  }

  public render(): TemplateResult {
    // we have to embed our own style since we are in light DOM
    const style = html`<style>
      ${unsafeCSS(Editor.styles.cssText)}
      ${unsafeCSS(CanvasNode.styles.cssText)}
    </style>`;

    const stickies = this.definition?._ui?.stickies || {};

    return html`${style}
      <div id="editor">
        <div
          id="grid"
          style="min-width:100%;width:${this.canvasSize.width}px; height:${this
            .canvasSize.height}px"
        >
          <div id="canvas">
            ${this.definition
              ? repeat(
                  this.definition.nodes,
                  (node) => node.uuid,
                  (node) => {
                    const position = this.definition._ui?.nodes[node.uuid]
                      ?.position || {
                      left: 0,
                      top: 0
                    };

                    const dragging =
                      this.isDragging &&
                      this.currentDragItem?.uuid === node.uuid;
 
                    const selected = this.selectedItems.has(node.uuid);
 
                    return html`<temba-flow-node
                      class="draggable ${dragging ? 'dragging' : ''} ${selected
                        ? 'selected'
                        : ''}"
                      @mousedown=${this.handleMouseDown.bind(this)}
                      uuid=${node.uuid}
                      style="left:${position.left}px; top:${position.top}px"
                      .plumber=${this.plumber}
                      .node=${node}
                      .ui=${this.definition._ui.nodes[node.uuid]}
                      @temba-node-deleted=${(event) => {
                        this.deleteNodes([event.detail.uuid]);
                      }}
                    ></temba-flow-node>`;
                  }
                )
              : html`<temba-loading></temba-loading>`}
            ${repeat(
              Object.entries(stickies),
              ([uuid]) => uuid,
              ([uuid, sticky]) => {
                const position = sticky.position || { left: 0, top: 0 };
                const dragging =
                  this.isDragging && this.currentDragItem?.uuid === uuid;
                const selected = this.selectedItems.has(uuid);
                return html`<temba-sticky-note
                  class="draggable ${dragging ? 'dragging' : ''} ${selected
                    ? 'selected'
                    : ''}"
                  @mousedown=${this.handleMouseDown.bind(this)}
                  style="left:${position.left}px; top:${position.top}px; z-index: ${1000 +
                  position.top}"
                  uuid=${uuid}
                  .data=${sticky}
                  .dragging=${dragging}
                  .selected=${selected}
                ></temba-sticky-note>`;
              }
            )}
            ${this.renderSelectionBox()}
          </div>
        </div>
      </div>
 
      ${this.editingNode || this.editingAction
        ? html`<temba-node-editor
            .node=${this.editingNode}
            .nodeUI=${this.editingNodeUI}
            .action=${this.editingAction}
            @temba-node-saved=${(e: CustomEvent) =>
              this.handleNodeSaved(e.detail.node)}
            @temba-action-saved=${(e: CustomEvent) =>
              this.handleActionSaved(e.detail.action)}
            @temba-node-edit-cancelled=${this.handleNodeEditCanceled}
          ></temba-node-editor>`
        : ''} `;
  }
}