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 | 141x 138x 138x 138x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 1588x 58x 58x 141x 20x 20x 20x 20x 338x 20x 20x 20x 20x 338x 20x 20x 20x 20x 1x 18x 18x 20x 18x 18x 18x 18x 18x 18x 18x 5x 5x 5x 18x 20x 16x 16x 141x 141x 25x 25x 25x 25x 25x 25x 25x 2x 141x 32x 32x 32x 32x 32x 4x 4x 4x 4x 4x 4x 6x 6x 141x 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 6x 6x 6x 3x 4x 141x 298x 298x 73x 73x 73x 73x 73x 73x 73x 225x 225x 260x 87x 138x 202x 32x 106x 141x 6x 6x 6x 2x 2x 2x 2x 2x 2x 6x 4x 4x 4x 141x 141x 141x 7x 7x 7x 7x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 8x 8x 8x 8x 141x 141x 141x 141x 534x 534x 534x 534x 559x 559x 559x 559x 28x 559x 559x 533x 533x 559x 559x 534x 559x 517x 517x 18x 18x 517x 517x 517x 517x 517x 517x 517x 543x 543x 18x 18x 543x 517x 42x 6x 6x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 6x 6x 6x 6x 42x 559x 18x 534x 533x 18x 533x 533x 533x 533x 533x 533x 533x 533x 533x 6x 533x 534x 141x 141x 141x 141x 141x 141x 141x 141x 141x 534x 534x 534x 534x 534x 24x 24x 24x 24x 24x 24x 24x 24x 24x 534x 141x 141x 141x 50x 50x 50x 50x 50x 6x 6x 50x 50x 50x 50x 50x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 4x 4x 8x 8x 141x 26x 26x 26x 26x 26x 26x 26x 38x 38x 30x 30x 38x 38x 38x 38x 38x 26x 26x 26x 26x 141x 141x 24x 24x 24x 24x 24x 52x 52x 52x 48x 48x 48x 48x 48x 48x 48x 48x 48x 4x 4x 4x 24x 24x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 24x 141x 114x 114x 114x 1x 1x 1x 114x 114x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 114x 114x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 66x 66x 66x 66x 40x 40x 40x 40x 40x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 4x 4x 4x 4x 40x 40x 141x 141x 141x 19x 19x 19x 19x 19x 19x 141x 141x 21x 21x 21x 21x 21x 21x 21x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 3x 3x 3x 2x 2x 2x 2x 2x 141x 564x 564x 373x 373x 141x 141x 4x 8x 8x 141x 141x 122x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 96x 96x 33x 33x 33x 33x 33x 33x 33x 96x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 96x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 96x 19x 19x 19x 19x 19x 19x 19x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 206x 141x 141x 141x 164x 164x 164x 164x 164x 164x 211x 211x 211x 211x 141x 141x 141x 141x 211x 141x 141x 141x 141x 164x 164x 164x 163x 163x 164x 212x 212x 212x 212x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x 444x 444x 444x 212x 212x 189x 141x 141x 141x 189x 189x 189x 189x 141x 141x 141x 141x 170x 170x 171x 171x 171x 162x 162x 162x 162x 171x 171x 171x 171x 171x 154x 154x 154x 170x 170x 170x 171x 171x 171x 171x 171x 171x 171x 171x 171x 170x 170x 170x 170x 170x 170x 170x 144x 170x 141x 141x 141x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 484x 538x 224x 224x 538x 185x 236x 191x 191x 191x 236x 185x 185x 185x 185x 185x 185x 184x 184x 184x 184x 184x 184x 184x 184x 184x 184x 184x 184x 184x 185x 185x 185x 175x 175x 185x 185x 185x 236x 146x 236x 236x 173x 173x 173x 173x 236x 141x | import { html, TemplateResult } from 'lit-html';
import { iconToPillType } from '../styles/pillVariants';
import { Action, NamedObject, FlowPosition } from '../store/flow-definition';
import { FlowIssue } 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 };
};
}
/**
* Validates a mixed recipients list (contacts, groups and expressions) against
* the engine's limits: at most 100 of each kind and expressions at most 1000
* characters. Returns an error message or null if the list is valid. The type
* predicates mirror how fromFormData partitions the list into the action's
* contacts / groups / legacy_vars.
*/
export function validateRecipients(recipients: any[]): string | null {
const contacts = recipients.filter(
(r: any) => r.type === 'contact' || (!r.type && !r.expression && r.id)
);
const groups = recipients.filter((r: any) => r.type === 'group');
const expressions = recipients.filter(
(r: any) => r.type === 'expression' || r.expression
);
if (contacts.length > 100) {
return 'You can only add up to 100 contacts';
}
if (groups.length > 100) {
return 'You can only add up to 100 groups';
}
if (expressions.length > 100) {
return 'You can only add up to 100 expressions';
}
const tooLong = expressions.some((e: any) => {
const value = e.value || e.name || e.id || '';
return typeof value === 'string' && value.length > 1000;
});
if (tooLong) {
return 'Expressions must be no more than 1000 characters';
}
return null;
}
/**
* Validates template variables against the engine's limit of 10000 characters
* per variable. Returns an error message or null if they're valid.
*/
export function validateTemplateVariables(variables: any[]): string | null {
const tooLong = variables.some(
(v: any) => typeof v === 'string' && v.length > 10000
);
if (tooLong) {
return 'Template variables must be no more than 10000 characters';
}
return null;
}
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 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>`;
};
/**
* Inline margin for stacked pills — the previous implementation used
* `class="mr-1 mb-1"` (Tailwind utility classes), but this package
* doesn't ship Tailwind, so the classes resolved to no-ops in any host
* page that didn't already include it. Inline style is predictable
* across hosts.
*/
const PILL_MARGIN_STYLE = 'margin: 0 4px 4px 0;';
/**
* 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
) => {
const pillType = iconToPillType(icon);
return html`<temba-label
icon=${icon || ''}
type=${pillType || 'neutral'}
style=${PILL_MARGIN_STYLE}
title="${name}"
>${content || name}</temba-label
>`;
};
/**
* 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`<temba-label type="neutral" style=${PILL_MARGIN_STYLE}
>+${remainingCount} more</temba-label
>`
);
}
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`<temba-label type="neutral" style=${PILL_MARGIN_STYLE}
>+${remainingCount} more</temba-label
>`
);
}
return itemElements;
};
/**
* Renders a named object as a clickable DS pill 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
});
}
};
const pillType = iconToPillType(icon);
return html`<temba-label
class="linked-pill"
icon=${icon || ''}
type=${pillType || 'neutral'}
clickable
style=${PILL_MARGIN_STYLE}
title="${obj.name}"
@click=${handleClick}
>${obj.name}</temba-label
>`;
};
/**
* 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`<temba-label type="neutral" style=${PILL_MARGIN_STYLE}
>+${remainingCount} more</temba-label
>`
);
}
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;
}
|