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 | 108x 141x 141x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 40x 40x 108x 30x 30x 30x 30x 30x 30x 4x 4x 4x 4x 4x 6x 6x 4x 108x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 3x 4x 108x 260x 260x 260x 47x 47x 47x 47x 47x 47x 213x 213x 230x 79x 134x 176x 30x 30x 108x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 4x 4x 4x 108x 108x 108x 108x 108x 108x 1080x 1080x 1080x 1080x 1080x 1080x 1077x 1077x 1077x 1077x 1077x 1077x 1077x 1080x 1080x 1074x 1074x 1074x 1080x 1x 108x 108x 3x 3x 3x 3x 3x 3x 3x 108x 108x 341x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 8x 8x 8x 16x 16x 16x 108x 108x 108x 434x 434x 434x 434x 434x 459x 459x 459x 459x 26x 26x 433x 433x 433x 434x 459x 459x 417x 417x 417x 417x 417x 417x 417x 417x 417x 16x 16x 417x 417x 417x 26x 6x 6x 459x 459x 42x 42x 42x 42x 42x 42x 42x 6x 6x 6x 42x 42x 42x 6x 459x 16x 16x 16x 433x 433x 433x 433x 433x 433x 433x 433x 433x 433x 433x 6x 434x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 469x 469x 469x 469x 469x 23x 23x 23x 23x 23x 23x 23x 23x 23x 469x 108x 108x 108x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 50x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 4x 4x 4x 108x 108x 26x 26x 26x 26x 26x 26x 38x 38x 30x 38x 38x 26x 26x 26x 26x 108x 108x 24x 24x 24x 24x 24x 52x 52x 52x 48x 48x 48x 48x 48x 48x 48x 4x 4x 4x 52x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 108x 108x 112x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 108x 108x 108x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 64x 64x 64x 38x 38x 38x 4x 38x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 2x 2x 2x 2x 2x 4x 4x 38x 38x 108x 108x 18x 18x 18x 18x 18x 108x 108x 108x 108x 20x 20x 20x 20x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 3x 3x 1x 2x 2x 2x 2x 108x 108x 108x 564x 564x 564x 293x 293x 108x 4x 4x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 122x 122x 122x 122x 108x 108x 108x 108x 96x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 96x 11x 11x 11x 11x 11x 11x 11x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 19x 19x 19x 19x 19x 19x 19x 19x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 131x 131x 178x 133x 152x 152x 152x 178x 138x 138x 178x 108x 108x 108x 108x 108x 108x 108x 108x 131x 131x 179x 179x 179x 179x 131x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 411x 411x 179x 179x 179x 179x 179x 179x 156x 156x 108x 108x 108x 156x 108x 108x 108x 108x 108x 108x 137x 137x 138x 138x 138x 138x 129x 129x 129x 138x 121x 121x 138x 138x 137x 137x 137x 137x 137x 137x 138x 138x 138x 138x 138x 138x 138x 138x 138x 137x 137x 137x 124x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x 505x 505x 505x 152x 505x 108x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 108x 152x 152x 152x 128x 152x 152x 152x 152x 152x 152x 152x 152x | import { html, TemplateResult } from 'lit-html';
import { Action, NamedObject, FlowPosition } from '../store/flow-definition';
import { FlowIssue, zustand } from '../store/AppState';
import { CustomEventType } from '../interfaces';
import { tokenize, TokenType } from '../excellent/tokenizer';
import { TOKEN_COLORS } from '../excellent/token-styles';
import { messageParser, sessionParser } from '../excellent/helpers';
import { FormData, ValidationResult, NodeConfig, ActionConfig } from './types';
import {
categoriesToLocalizationFormData,
localizationFormDataToCategories
} from './nodes/shared';
/**
* Wraps a validation check into the standard `validate` signature. The check
* populates an `errors` object; the wrapper computes `valid` and returns the
* ValidationResult. Eliminates the `const errors = {}; ...; return {valid, errors}`
* boilerplate that appears in every node and action config.
*/
export function validateWith(
check: (formData: FormData, errors: { [key: string]: string }) => void
): (formData: FormData) => ValidationResult {
return (formData: FormData) => {
const errors: { [key: string]: string } = {};
check(formData, errors);
return { valid: Object.keys(errors).length === 0, errors };
};
}
function makeTextToLocalizationFormData(fields: readonly string[]) {
return (
action: { uuid: string },
localization: Record<string, any>
): FormData => {
const formData: FormData = { uuid: action.uuid };
fields.forEach((field) => {
const value = localization[field];
formData[field] = Array.isArray(value) ? value[0] || '' : '';
});
return formData;
};
}
function makeTextFromLocalizationFormData(fields: readonly string[]) {
return (
formData: FormData,
action: Record<string, any>
): Record<string, any> => {
const localization: Record<string, any> = {};
fields.forEach((field) => {
const value = formData[field];
if (value && value.trim() !== '' && value !== action[field]) {
localization[field] = [value];
}
});
return localization;
};
}
type ToLocalizationFn = (
nodeOrAction: any,
localization: Record<string, any>
) => FormData;
type FromLocalizationFn = (
formData: FormData,
nodeOrAction: any
) => Record<string, any>;
/**
* Returns the `toLocalizationFormData` impl for a node or action config. Uses
* the explicit impl if the config provides one; otherwise infers from the
* `localizable` shape: `'categories'` → category helper, `string[]` → text
* factory. Returns undefined if the config isn't localizable.
*/
export function resolveToLocalizationFormData(
config: NodeConfig | ActionConfig
): ToLocalizationFn | undefined {
if (config.toLocalizationFormData) {
return config.toLocalizationFormData as ToLocalizationFn;
}
if (config.localizable === 'categories') {
return categoriesToLocalizationFormData;
}
if (Array.isArray(config.localizable)) {
return makeTextToLocalizationFormData(config.localizable);
}
return undefined;
}
/**
* Mirror of resolveToLocalizationFormData for `fromLocalizationFormData`.
*/
export function resolveFromLocalizationFormData(
config: NodeConfig | ActionConfig
): FromLocalizationFn | undefined {
if (config.fromLocalizationFormData) {
return config.fromLocalizationFormData as FromLocalizationFn;
}
if (config.localizable === 'categories') {
return localizationFormDataToCategories;
}
if (Array.isArray(config.localizable)) {
return makeTextFromLocalizationFormData(config.localizable);
}
return undefined;
}
const intlLanguageNames = new Intl.DisplayNames(['en'], { type: 'language' });
export function getLanguageDisplayName(code: string): string {
if (code === 'und') return 'Unknown';
// Prefer names from the RapidPro languages endpoint, which supplies
// ISO 639-3 codes (e.g. prd, pst) that Intl.DisplayNames doesn't cover.
const storeName = zustand.getState().languageNames?.[code];
if (storeName) {
return storeName;
}
try {
return intlLanguageNames.of(code) || code;
} catch {
return code;
}
}
const IS_MAC =
typeof navigator !== 'undefined' &&
/Mac|iPod|iPhone|iPad/.test(navigator.platform);
/**
* Returns true if the mouse event is a right-click or equivalent:
* - button !== 0 (actual right-click or middle-click on any platform)
* - ctrl+click on macOS (emulates right-click / context menu)
*/
export function isRightClick(event: MouseEvent): boolean {
if (event.button !== 0) return true;
if (IS_MAC && event.ctrlKey) return true;
return false;
}
export function formatIssueMessage(issue: FlowIssue): string {
if (issue.dependency) {
const name = issue.dependency.name || issue.dependency.key;
return `Cannot find a ${issue.dependency.type} for ${name}`;
}
return issue.description;
}
const GRID_SIZE = 20;
export function snapToGrid(value: number): number {
const snapped = Math.round(value / GRID_SIZE) * GRID_SIZE;
return Math.max(snapped, 0);
}
const MONO =
"font-family:SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;font-size:0.95em";
const TOKEN_STYLES: Record<string, string> = {
[TokenType.ExpressionPrefix]: `color:${TOKEN_COLORS.expression};font-weight:600;${MONO}`,
[TokenType.Identifier]: `color:${TOKEN_COLORS.expression};${MONO}`,
[TokenType.FunctionName]: `color:${TOKEN_COLORS.fn};font-weight:900;${MONO}`,
[TokenType.StringLiteral]: `color:${TOKEN_COLORS.string};${MONO}`,
[TokenType.NumberLiteral]: `color:${TOKEN_COLORS.number};${MONO}`,
[TokenType.Keyword]: `color:${TOKEN_COLORS.keyword};${MONO}`,
[TokenType.Operator]: `color:${TOKEN_COLORS.operator};${MONO}`,
[TokenType.ContextRef]: `color:${TOKEN_COLORS.expression};${MONO}`,
[TokenType.Separator]: `color:${TOKEN_COLORS.operator};${MONO}`,
[TokenType.Arrow]: `color:${TOKEN_COLORS.operator};${MONO}`,
[TokenType.Bracket]: `color:${TOKEN_COLORS.operator};${MONO}`,
[TokenType.Paren]: `color:${TOKEN_COLORS.paren};${MONO}`,
[TokenType.Whitespace]: MONO
};
const LLM_ICON_MAP: [RegExp, string][] = [
[/claude|anthropic/i, 'anthropic'],
[/gpt|openai|o1|o3|o4/i, 'openai'],
[/gemini|google/i, 'gemini'],
[/azure|microsoft/i, 'azure'],
[/deepseek/i, 'deepseek']
];
export const getLlmIcon = (name: string): string | null => {
if (!name) return null;
for (const [pattern, icon] of LLM_ICON_MAP) {
if (pattern.test(name)) return icon;
}
return null;
};
/**
* Tokenizes text containing Excellent expressions and returns highlighted
* lit-html templates with inline styles, suitable for rendering on the canvas.
*/
export const renderHighlightedText = (
text: string,
session = false
): TemplateResult => {
const parser = session ? sessionParser : messageParser;
const tokens = tokenize(text || '', parser);
// Group consecutive expression tokens so we can wrap them in a single
// span with hyphens:none (plain text keeps hyphens:auto from container).
const groups: { isExpr: boolean; tokens: typeof tokens }[] = [];
for (const token of tokens) {
const isExpr = !!TOKEN_STYLES[token.type];
const last = groups[groups.length - 1];
if (last && last.isExpr === isExpr) {
last.tokens.push(token);
} else {
groups.push({ isExpr, tokens: [token] });
}
}
const renderToken = (token: (typeof tokens)[0]) => {
const style = TOKEN_STYLES[token.type];
if (!style) {
const parts = token.text.split('\n');
return html`${parts.map(
(part, i) => html`${i > 0 ? html`<br />` : null}${part}`
)}`;
}
const parts = token.text.split('\n');
return html`${parts.map(
(part, i) =>
html`${i > 0 ? html`<br />` : null}${part
? html`<span style="${style}">${part}</span>`
: null}`
)}`;
};
return html`${groups.map((group) => {
const content = html`${group.tokens.map(renderToken)}`;
return group.isExpr
? html`<span style="hyphens:none">${content}</span>`
: content;
})}`;
};
/**
* Renders content clamped to a maximum number of lines with ellipsis.
* Hovering shows the full text in a tooltip.
*/
export const renderClamped = (
content: TemplateResult | string,
titleText: string,
maxLines: number = 3
) => {
return html`<div
style="display: -webkit-box; -webkit-line-clamp: ${maxLines}; -webkit-box-orient: vertical; overflow: hidden; word-wrap: break-word; overflow-wrap: break-word; hyphens: auto;"
title="${titleText}"
>
${content}
</div>`;
};
/**
* Renders a single line item with optional icon.
* Content can be plain text or a TemplateResult (e.g. highlighted text).
*/
export const renderLineItem = (
name: string,
icon?: string,
content?: TemplateResult
) => {
return html`<div style="display:flex;align-items:center;">
${icon
? html`<temba-icon name=${icon} style="margin-right:0.5em"></temba-icon>`
: null}
<div
style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 250px;"
title="${name}"
>
${content || name}
</div>
</div>`;
};
/**
* Renders a list of named objects with optional icon, showing up to 3 items
* with a "+X more" indicator if there are more items
*/
export const renderNamedObjects = (assets: NamedObject[], icon?: string) => {
return renderStringList(
assets.map((asset) => asset.name),
icon
);
};
/**
* Renders a list of strings with optional icon, showing up to 3 items
* with a "+X more" indicator if there are more items.
* When session is provided, expression strings (starting with @) are highlighted.
*/
export const renderStringList = (
items: string[],
icon?: string,
session?: boolean
) => {
const itemElements = [];
const maxDisplay = 3;
// Show up to 3 items, or all 4 if exactly 4 items
const displayCount =
items.length === 4 ? 4 : Math.min(maxDisplay, items.length);
for (let i = 0; i < displayCount; i++) {
const item = items[i];
const highlighted =
session !== undefined && item.startsWith('@')
? renderHighlightedText(item, session)
: undefined;
itemElements.push(renderLineItem(item, icon, highlighted));
}
// Add "+X more" if there are more than 3 items (and not exactly 4)
if (items.length > maxDisplay && items.length !== 4) {
const remainingCount = items.length - maxDisplay;
itemElements.push(
html`<div style="display:flex;align-items:center;margin-top:0.2em;">
${icon
? html`<div style="margin-right:0.4em; width: 1em;"></div>` // spacing placeholder
: null}
<div style="font-size:0.8em">+${remainingCount} more</div>
</div>`
);
}
return itemElements;
};
export interface MixedListItem {
name: string;
icon: string;
content?: TemplateResult;
uuid?: string;
eventType?: CustomEventType;
}
/**
* Renders a mixed list of items, each with its own icon, showing up to 3 items
* with a "+X more" indicator if there are more items.
* Items with uuid and eventType are rendered as clickable links.
*/
export const renderMixedList = (items: MixedListItem[]) => {
const itemElements = [];
const maxDisplay = 3;
const displayCount =
items.length === 4 ? 4 : Math.min(maxDisplay, items.length);
for (let i = 0; i < displayCount; i++) {
const item = items[i];
if (item.uuid && item.eventType) {
itemElements.push(
renderLinkedObject(
{ uuid: item.uuid, name: item.name },
item.eventType,
item.icon
)
);
} else {
itemElements.push(renderLineItem(item.name, item.icon, item.content));
}
}
if (items.length > maxDisplay && items.length !== 4) {
const remainingCount = items.length - maxDisplay;
itemElements.push(
html`<div style="display:flex;align-items:center;margin-top:0.2em;">
<div style="margin-right:0.4em; width: 1em;"></div>
<div style="font-size:0.8em">+${remainingCount} more</div>
</div>`
);
}
return itemElements;
};
/**
* Renders a named object as a clickable link that fires a custom event
*/
const renderLinkedObject = (
obj: NamedObject,
eventType: CustomEventType,
icon?: string
) => {
const handleClick = (e: MouseEvent) => {
e.stopPropagation();
e.preventDefault();
const target = e.currentTarget as HTMLElement;
const editor = target.closest('temba-flow-editor') as any;
if (editor) {
editor.fireCustomEvent(eventType, {
uuid: obj.uuid,
name: obj.name,
metaKey: e.metaKey,
ctrlKey: e.ctrlKey
});
}
};
return html`<div style="display:flex;align-items:center;max-width:100%;">
${icon
? html`<temba-icon name=${icon} style="margin-right:0.5em"></temba-icon>`
: null}
<div
class="linked-name"
@click=${handleClick}
style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 250px; text-decoration: underline; cursor: pointer;"
>
${obj.name}
</div>
</div>`;
};
/**
* Renders a list of linked objects, showing up to 3 items
* with a "+X more" indicator if there are more items
*/
const renderLinkedObjects = (
objects: NamedObject[],
eventType: CustomEventType,
icon?: string
) => {
const itemElements = [];
const maxDisplay = 3;
const displayCount =
objects.length === 4 ? 4 : Math.min(maxDisplay, objects.length);
for (let i = 0; i < displayCount; i++) {
itemElements.push(renderLinkedObject(objects[i], eventType, icon));
}
if (objects.length > maxDisplay && objects.length !== 4) {
const remainingCount = objects.length - maxDisplay;
itemElements.push(
html`<div style="display:flex;align-items:center;margin-top:0.2em;">
${icon
? html`<div style="margin-right:0.4em; width: 1em;"></div>`
: null}
<div style="font-size:0.8em">+${remainingCount} more</div>
</div>`
);
}
return itemElements;
};
/**
* Renders a list of flows as clickable links, showing up to 3 items
* with a "+X more" indicator if there are more items
*/
export const renderFlowLinks = (flows: NamedObject[], icon?: string) => {
return renderLinkedObjects(flows, CustomEventType.FlowClicked, icon);
};
/**
* Renders a list of groups as clickable links, showing up to 3 items
* with a "+X more" indicator if there are more items
*/
export const renderGroupLinks = (groups: NamedObject[], icon?: string) => {
return renderLinkedObjects(groups, CustomEventType.GroupClicked, icon);
};
/**
* Renders a list of contacts as clickable links, showing up to 3 items
* with a "+X more" indicator if there are more items
*/
export const renderContactLinks = (contacts: NamedObject[], icon?: string) => {
return renderLinkedObjects(contacts, CustomEventType.ContactClicked, icon);
};
export interface Scheme {
scheme: string;
name: string;
path: string;
excludeFromSplit?: boolean;
}
export const SCHEMES: Scheme[] = [
{
scheme: 'tel',
name: 'SMS',
path: 'Phone Number'
},
{
scheme: 'whatsapp',
name: 'WhatsApp',
path: 'WhatsApp Number'
},
{
scheme: 'facebook',
name: 'Facebook',
path: 'Facebook ID'
},
{
scheme: 'instagram',
name: 'Instagram',
path: 'Instagram ID'
},
{
scheme: 'twitterid',
name: 'Twitter',
path: 'Twitter ID',
excludeFromSplit: true
},
{
scheme: 'telegram',
name: 'Telegram',
path: 'Telegram ID'
},
{
scheme: 'viber',
name: 'Viber',
path: 'Viber ID'
},
{
scheme: 'line',
name: 'Line',
path: 'Line ID'
},
{
scheme: 'wechat',
name: 'WeChat',
path: 'WeChat ID'
},
{
scheme: 'fcm',
name: 'Firebase',
path: 'Firebase ID'
},
{
scheme: 'jiochat',
name: 'JioChat',
path: 'JioChat ID'
},
{
scheme: 'freshchat',
name: 'Freshchat',
path: 'Freshchat ID'
},
{
scheme: 'mailto',
name: 'Email',
path: 'Email Address',
excludeFromSplit: true
},
{
scheme: 'twitter',
name: 'Twitter',
path: 'Twitter Handle',
excludeFromSplit: true
},
{
scheme: 'vk',
name: 'VK',
path: 'VK ID'
},
{
scheme: 'discord',
name: 'Discord',
path: 'Discord ID'
},
{
scheme: 'webchat',
name: 'Webchat',
path: 'Webchat ID',
excludeFromSplit: true
},
{
scheme: 'rocketchat',
name: 'RocketChat',
path: 'RocketChat ID'
},
{
scheme: 'ext',
name: 'External',
path: 'External ID'
}
];
/**
* Represents the bounding box of a node on the canvas
*/
export interface NodeBounds {
uuid: string;
left: number;
top: number;
right: number;
bottom: number;
width: number;
height: number;
}
/**
* Minimum vertical spacing between nodes (in pixels)
*/
const MIN_NODE_SPACING = 30;
/**
* Small buffer to avoid floating point precision issues in overlap detection (in pixels)
* This prevents false positives when nodes are exactly adjacent (e.g., bottom of one node
* at exactly the same position as top of another)
*/
const OVERLAP_BUFFER = 10;
/**
* Gets the bounding box for a node from the DOM
*
* @param nodeUuid - The UUID of the node
* @param position - The current position of the node
* @param element - Optional pre-fetched DOM element (recommended for performance when checking multiple nodes)
* @returns NodeBounds object or null if element not found
*
* Note: When element is not provided, performs a DOM query which may impact performance
* during bulk collision detection. Consider fetching elements beforehand when possible.
*/
export const getNodeBounds = (
nodeUuid: string,
position: FlowPosition,
element?: HTMLElement
): NodeBounds | null => {
// If element is provided, use it; otherwise try to find it in DOM
const nodeElement =
element || (document.querySelector(`[id="${nodeUuid}"]`) as HTMLElement);
if (!nodeElement) {
return null;
}
// Use offsetWidth/offsetHeight instead of getBoundingClientRect() so
// dimensions are in CSS-layout space and unaffected by ancestor transforms (zoom).
const width = nodeElement.offsetWidth;
const height = nodeElement.offsetHeight;
return {
uuid: nodeUuid,
left: position.left,
top: position.top,
right: position.left + width,
bottom: position.top + height,
width,
height
};
};
/**
* Checks if two node bounding boxes overlap
*/
export const nodesOverlap = (
bounds1: NodeBounds,
bounds2: NodeBounds
): boolean => {
// Use a small buffer to avoid floating point precision issues
const buffer = OVERLAP_BUFFER;
return !(
bounds1.right <= bounds2.left - buffer ||
bounds1.left >= bounds2.right + buffer ||
bounds1.bottom <= bounds2.top - buffer ||
bounds1.top >= bounds2.bottom + buffer
);
};
/**
* Detects all collisions between a node and other nodes
*/
export const detectCollisions = (
targetBounds: NodeBounds,
allBounds: NodeBounds[]
): NodeBounds[] => {
return allBounds.filter(
(bounds) =>
bounds.uuid !== targetBounds.uuid && nodesOverlap(targetBounds, bounds)
);
};
type Direction = 'down' | 'up' | 'right' | 'left';
const DIRECTIONS: Direction[] = ['down', 'up', 'right', 'left'];
/**
* Creates a new NodeBounds at a different position
*/
const makeBoundsAt = (
original: NodeBounds,
left: number,
top: number
): NodeBounds => ({
...original,
left,
top,
right: left + original.width,
bottom: top + original.height
});
/**
* Computes the minimum position needed to clear all fixed nodes in a given direction.
* Returns null if the direction is not viable (e.g., would require negative coordinates
* and still overlap).
*/
const computeDirectionalClearance = (
collider: NodeBounds,
fixedNodes: NodeBounds[],
direction: Direction
): { left: number; top: number } | null => {
switch (direction) {
case 'down': {
const maxBottom = Math.max(...fixedNodes.map((f) => f.bottom));
const newTop = snapToGrid(maxBottom + MIN_NODE_SPACING);
return { left: collider.left, top: newTop };
}
case 'up': {
const minTop = Math.min(...fixedNodes.map((f) => f.top));
const newTop = snapToGrid(minTop - collider.height - MIN_NODE_SPACING);
if (newTop < 0) return { left: collider.left, top: 0 };
return { left: collider.left, top: newTop };
}
case 'right': {
const maxRight = Math.max(...fixedNodes.map((f) => f.right));
const newLeft = snapToGrid(maxRight + MIN_NODE_SPACING);
return { left: newLeft, top: collider.top };
}
case 'left': {
const minLeft = Math.min(...fixedNodes.map((f) => f.left));
const newLeft = snapToGrid(minLeft - collider.width - MIN_NODE_SPACING);
if (newLeft < 0) return { left: 0, top: collider.top };
return { left: newLeft, top: collider.top };
}
}
};
/**
* Calculates new positions to resolve all collisions using multi-directional reflow.
*
* Sacred nodes (the ones just dropped/created) keep their positions. All other
* colliding nodes are moved in whichever direction requires the least displacement
* and causes the fewest cascading collisions.
*/
export const calculateReflowPositions = (
sacredNodeUuids: string[],
allBounds: NodeBounds[]
): Map<string, FlowPosition> => {
const newPositions = new Map<string, FlowPosition>();
const sacredSet = new Set(sacredNodeUuids);
// Mutable map of current bounds, updated as collisions are resolved
const currentBounds = new Map<string, NodeBounds>();
for (const b of allBounds) {
currentBounds.set(b.uuid, { ...b });
}
// A sacred node yields to an existing node at the top of the canvas when
// the sacred wasn't dropped above it. The existing node keeps its top
// position and the sacred node moves below instead.
for (const sacredUuid of [...sacredSet]) {
const sacred = currentBounds.get(sacredUuid);
if (!sacred) continue;
for (const [uuid, bounds] of currentBounds) {
if (uuid === sacredUuid || sacredSet.has(uuid)) continue;
if (!nodesOverlap(sacred, bounds)) continue;
if (sacred.top > bounds.top && bounds.top < MIN_NODE_SPACING) {
sacredSet.delete(sacredUuid);
sacredSet.add(uuid);
break;
}
}
}
// Seed the queue with non-sacred nodes that overlap any sacred node
const queue: string[] = [];
const inQueue = new Set<string>();
for (const sacredUuid of sacredSet) {
const sacred = currentBounds.get(sacredUuid);
if (!sacred) continue;
for (const [uuid, bounds] of currentBounds) {
if (sacredSet.has(uuid) || inQueue.has(uuid)) continue;
if (nodesOverlap(sacred, bounds)) {
queue.push(uuid);
inQueue.add(uuid);
}
}
}
const resolved = new Set<string>();
let iterations = 0;
const maxIterations = 200;
while (queue.length > 0 && iterations < maxIterations) {
iterations++;
const uuid = queue.shift()!;
if (resolved.has(uuid)) continue;
const collider = currentBounds.get(uuid)!;
// Find all fixed nodes (sacred + already-resolved) that overlap this node
const fixedOverlaps: NodeBounds[] = [];
for (const [otherUuid, otherBounds] of currentBounds) {
if (otherUuid === uuid) continue;
if (sacredSet.has(otherUuid) || resolved.has(otherUuid)) {
if (nodesOverlap(collider, otherBounds)) {
fixedOverlaps.push(otherBounds);
}
}
}
if (fixedOverlaps.length === 0) continue;
// Determine direction constraints and axis bias from sacred node overlaps
const sacredOverlaps = fixedOverlaps.filter((f) => sacredSet.has(f.uuid));
const allowedDirections: Direction[] = [...DIRECTIONS];
let axisBias: 'vertical' | 'horizontal' | null = null;
if (sacredOverlaps.length > 0) {
// Rule 1: don't move a lower node above the sacred node
// Rule 2: don't move a right-of node to the left of the sacred node
for (const sacred of sacredOverlaps) {
if (collider.top > sacred.top) {
const idx = allowedDirections.indexOf('up');
if (idx !== -1) allowedDirections.splice(idx, 1);
}
if (collider.left > sacred.left) {
const idx = allowedDirections.indexOf('left');
if (idx !== -1) allowedDirections.splice(idx, 1);
}
}
// Rule 3: bias direction based on overlap shape
let totalOverlapWidth = 0;
let totalOverlapHeight = 0;
for (const sacred of sacredOverlaps) {
totalOverlapWidth +=
Math.min(collider.right, sacred.right) -
Math.max(collider.left, sacred.left);
totalOverlapHeight +=
Math.min(collider.bottom, sacred.bottom) -
Math.max(collider.top, sacred.top);
}
if (totalOverlapWidth > totalOverlapHeight) {
axisBias = 'vertical'; // wide overlap = nodes stacked = prefer up/down
} else if (totalOverlapHeight > totalOverlapWidth) {
axisBias = 'horizontal'; // tall overlap = nodes side-by-side = prefer left/right
}
}
// Try each allowed direction, pick the one with least disruption
let bestPos: { left: number; top: number } | null = null;
let bestScore = Infinity;
for (const dir of allowedDirections) {
const candidate = computeDirectionalClearance(
collider,
fixedOverlaps,
dir
);
if (!candidate) continue;
const candidateBounds = makeBoundsAt(
collider,
candidate.left,
candidate.top
);
// Verify no overlap with any sacred or resolved node
let stillOverlaps = false;
let cascadeCount = 0;
for (const [otherUuid, otherBounds] of currentBounds) {
if (otherUuid === uuid) continue;
if (!nodesOverlap(candidateBounds, otherBounds)) continue;
if (sacredSet.has(otherUuid) || resolved.has(otherUuid)) {
stillOverlaps = true;
break;
}
cascadeCount++;
}
if (stillOverlaps) continue;
const distance =
Math.abs(candidate.left - collider.left) +
Math.abs(candidate.top - collider.top);
// When colliding with sacred nodes, use axis bias scoring;
// for cascading collisions (no sacred overlap), use original scoring
let score: number;
if (sacredOverlaps.length > 0) {
const isVerticalDir = dir === 'up' || dir === 'down';
const axisMatch =
axisBias === null ||
(axisBias === 'vertical' && isVerticalDir) ||
(axisBias === 'horizontal' && !isVerticalDir);
const axisPenalty = axisMatch ? 0 : 5000;
score = cascadeCount * 2000 + axisPenalty + distance;
} else {
score = cascadeCount * 10000 + distance;
}
if (score < bestScore) {
bestScore = score;
bestPos = candidate;
}
}
if (bestPos) {
newPositions.set(uuid, { left: bestPos.left, top: bestPos.top });
const newBounds = makeBoundsAt(collider, bestPos.left, bestPos.top);
currentBounds.set(uuid, newBounds);
resolved.add(uuid);
// Enqueue any new cascading collisions
for (const [otherUuid, otherBounds] of currentBounds) {
if (otherUuid === uuid) continue;
if (sacredSet.has(otherUuid) || resolved.has(otherUuid)) continue;
if (inQueue.has(otherUuid)) continue;
if (nodesOverlap(newBounds, otherBounds)) {
queue.push(otherUuid);
inQueue.add(otherUuid);
}
}
}
}
return newPositions;
};
/**
* Apply localization overrides to an action, falling back to the base value
* for any field that has no localized entry.
*
* @param action The base-language action.
* @param localization The per-field localization record for this action's UUID
* (i.e. `definition.localization[lang][action.uuid]`), or
* undefined if no localization exists.
* @returns A shallow copy with localized values merged in, or the original
* action if there is nothing to merge.
*/
export function localizeAction(
action: Action,
localization: Record<string, any> | undefined
): Action {
if (!localization) return action;
const localized = { ...action };
for (const field of Object.keys(localization)) {
const val = localization[field];
if (Array.isArray(val) && val.length > 0) {
if (Array.isArray((action as any)[field])) {
(localized as any)[field] = val;
} else {
(localized as any)[field] = val[0];
}
}
}
return localized;
}
|