@nyaruka/temba-components 0.156.7 → 0.156.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8796,7 +8796,7 @@ background: #ccc;
8796
8796
  ${this.renderUploader()}
8797
8797
  </div>
8798
8798
  </div>
8799
- </div>`}}t([mt({type:String,attribute:!1})],cu.prototype,"endpoint",void 0),t([mt({type:Boolean})],cu.prototype,"pendingDrop",void 0),t([mt({type:Boolean})],cu.prototype,"ignoreDrops",void 0),t([mt({type:String})],cu.prototype,"icon",void 0),t([mt({type:String})],cu.prototype,"accept",void 0),t([mt({type:Number})],cu.prototype,"max",void 0),t([mt({type:Array})],cu.prototype,"attachments",void 0),t([mt({type:Boolean,attribute:!1})],cu.prototype,"uploading",void 0);let hu="dev";try{hu="0.156.7"}catch(t){}const uu=hu,pu=new Intl.DisplayNames(["en"],{type:"language"});function mu(t){if("und"===t)return"Unknown";try{return pu.of(t)||t}catch(e){return t}}const gu="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform);function fu(t){return 0!==t.button||!(!gu||!t.ctrlKey)}function vu(t){if(t.dependency){const e=t.dependency.name||t.dependency.key;return`Cannot find a ${t.dependency.type} for ${e}`}return t.description}function bu(t){const e=20*Math.round(t/20);return Math.max(e,0)}const yu="font-family:SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;font-size:0.95em",xu={[Vd.ExpressionPrefix]:`color:${dc.expression};font-weight:600;${yu}`,[Vd.Identifier]:`color:${dc.expression};${yu}`,[Vd.FunctionName]:`color:${dc.fn};font-weight:900;${yu}`,[Vd.StringLiteral]:`color:${dc.string};${yu}`,[Vd.NumberLiteral]:`color:${dc.number};${yu}`,[Vd.Keyword]:`color:${dc.keyword};${yu}`,[Vd.Operator]:`color:${dc.operator};${yu}`,[Vd.ContextRef]:`color:${dc.expression};${yu}`,[Vd.Separator]:`color:${dc.operator};${yu}`,[Vd.Arrow]:`color:${dc.operator};${yu}`,[Vd.Bracket]:`color:${dc.operator};${yu}`,[Vd.Paren]:`color:${dc.paren};${yu}`,[Vd.Whitespace]:yu},wu=[[/claude|anthropic/i,"anthropic"],[/gpt|openai|o1|o3|o4/i,"openai"],[/gemini|google/i,"gemini"],[/azure|microsoft/i,"azure"],[/deepseek/i,"deepseek"]],_u=(t,e=!1)=>{const i=Qd(t||"",e?Nd:Rd),o=[];for(const t of i){const e=!!xu[t.type],i=o[o.length-1];i&&i.isExpr===e?i.tokens.push(t):o.push({isExpr:e,tokens:[t]})}const n=t=>{const e=xu[t.type];if(!e){const e=t.text.split("\n");return W`${e.map((t,e)=>W`${e>0?W`<br />`:null}${t}`)}`}const i=t.text.split("\n");return W`${i.map((t,i)=>W`${i>0?W`<br />`:null}${t?W`<span style="${e}">${t}</span>`:null}`)}`};return W`${o.map(t=>{const e=W`${t.tokens.map(n)}`;return t.isExpr?W`<span style="hyphens:none">${e}</span>`:e})}`},ku=(t,e,i=3)=>W`<div
8799
+ </div>`}}t([mt({type:String,attribute:!1})],cu.prototype,"endpoint",void 0),t([mt({type:Boolean})],cu.prototype,"pendingDrop",void 0),t([mt({type:Boolean})],cu.prototype,"ignoreDrops",void 0),t([mt({type:String})],cu.prototype,"icon",void 0),t([mt({type:String})],cu.prototype,"accept",void 0),t([mt({type:Number})],cu.prototype,"max",void 0),t([mt({type:Array})],cu.prototype,"attachments",void 0),t([mt({type:Boolean,attribute:!1})],cu.prototype,"uploading",void 0);let hu="dev";try{hu="0.156.8"}catch(t){}const uu=hu,pu=new Intl.DisplayNames(["en"],{type:"language"});function mu(t){if("und"===t)return"Unknown";try{return pu.of(t)||t}catch(e){return t}}const gu="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform);function fu(t){return 0!==t.button||!(!gu||!t.ctrlKey)}function vu(t){if(t.dependency){const e=t.dependency.name||t.dependency.key;return`Cannot find a ${t.dependency.type} for ${e}`}return t.description}function bu(t){const e=20*Math.round(t/20);return Math.max(e,0)}const yu="font-family:SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;font-size:0.95em",xu={[Vd.ExpressionPrefix]:`color:${dc.expression};font-weight:600;${yu}`,[Vd.Identifier]:`color:${dc.expression};${yu}`,[Vd.FunctionName]:`color:${dc.fn};font-weight:900;${yu}`,[Vd.StringLiteral]:`color:${dc.string};${yu}`,[Vd.NumberLiteral]:`color:${dc.number};${yu}`,[Vd.Keyword]:`color:${dc.keyword};${yu}`,[Vd.Operator]:`color:${dc.operator};${yu}`,[Vd.ContextRef]:`color:${dc.expression};${yu}`,[Vd.Separator]:`color:${dc.operator};${yu}`,[Vd.Arrow]:`color:${dc.operator};${yu}`,[Vd.Bracket]:`color:${dc.operator};${yu}`,[Vd.Paren]:`color:${dc.paren};${yu}`,[Vd.Whitespace]:yu},wu=[[/claude|anthropic/i,"anthropic"],[/gpt|openai|o1|o3|o4/i,"openai"],[/gemini|google/i,"gemini"],[/azure|microsoft/i,"azure"],[/deepseek/i,"deepseek"]],_u=(t,e=!1)=>{const i=Qd(t||"",e?Nd:Rd),o=[];for(const t of i){const e=!!xu[t.type],i=o[o.length-1];i&&i.isExpr===e?i.tokens.push(t):o.push({isExpr:e,tokens:[t]})}const n=t=>{const e=xu[t.type];if(!e){const e=t.text.split("\n");return W`${e.map((t,e)=>W`${e>0?W`<br />`:null}${t}`)}`}const i=t.text.split("\n");return W`${i.map((t,i)=>W`${i>0?W`<br />`:null}${t?W`<span style="${e}">${t}</span>`:null}`)}`};return W`${o.map(t=>{const e=W`${t.tokens.map(n)}`;return t.isExpr?W`<span style="hyphens:none">${e}</span>`:e})}`},ku=(t,e,i=3)=>W`<div
8800
8800
  style="display: -webkit-box; -webkit-line-clamp: ${i}; -webkit-box-orient: vertical; overflow: hidden; word-wrap: break-word; overflow-wrap: break-word; hyphens: auto;"
8801
8801
  title="${e}"
8802
8802
  >
@@ -8945,235 +8945,604 @@ background: #ccc;
8945
8945
  </div>
8946
8946
  `},form:{llm:{type:"select",label:"LLM",required:!0,options:[],endpoint:"/api/internal/llms.json",searchable:!0,valueKey:"uuid",nameKey:"name",placeholder:"Select an LLM..."},input:{type:"text",label:"Input",helpText:"The input the AI will process",required:!0,evaluated:!0,placeholder:"@input"},instructions:{type:"textarea",label:"Instructions",helpText:"Tell the AI what to do with the input. The result can be referenced as **`@locals._llm_output`**",required:!0,evaluated:!0,placeholder:"Enter instructions for the AI model...",minHeight:130}},layout:["llm","input","instructions"],toFormData:t=>{var e;const i=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_llm"===t.type);return{uuid:t.uuid,llm:(null==i?void 0:i.llm)?[i.llm]:[],input:(null==i?void 0:i.input)||"@input",instructions:(null==i?void 0:i.instructions)||""}},fromFormData:(t,e)=>{var i,o,n;const s=Array.isArray(t.llm)&&t.llm.length>0?t.llm[0]:null,r=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"call_llm"===t.type),a={type:"call_llm",uuid:(null==r?void 0:r.uuid)||Xt(),llm:s?{uuid:s.uuid||s.value,name:s.name}:{uuid:"",name:""},input:t.input||"@input",instructions:t.instructions||"",output_local:"_llm_output"},l=(null===(o=e.router)||void 0===o?void 0:o.categories)||[],d=e.exits||[],c=(null===(n=e.router)||void 0===n?void 0:n.cases)||[],{router:h,exits:u}=Me("@locals._llm_output",{type:"has_text",arguments:[]},l,d,c);return{uuid:e.uuid,actions:[a],router:h,exits:u}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},am={type:"split_by_llm_categorize",name:"Split by AI",group:ju.services,flowTypes:[],features:[qu],form:{llm:{type:"select",label:"LLM",helpText:"Select the LLM to use for categorization",required:!0,endpoint:"/api/internal/llms.json",valueKey:"uuid",nameKey:"name",placeholder:"Select an LLM..."},input:{type:"text",label:"Input",helpText:"The input to categorize (usually @input)",required:!0,evaluated:!0,placeholder:"@input"},categories:{type:"array",helpText:"Define the categories for classification",required:!0,sortable:!0,itemLabel:"Category",minItems:1,maxItems:10,isEmptyItem:t=>!t.name||""===t.name.trim(),itemConfig:{name:{type:"text",placeholder:"Category name",required:!0}}}},layout:["llm","input","categories"],validate:t=>{const e={};if(t.categories&&Array.isArray(t.categories)){const i=t.categories.filter(t=>(null==t?void 0:t.name)&&""!==t.name.trim()),o=[],n=new Map;if(i.forEach(t=>{const e=t.name.trim().toLowerCase();n.has(e)||n.set(e,[]),n.get(e).push(t.name.trim())}),n.forEach(t=>{t.length>1&&o.push(...t)}),o.length>0){const t=[...new Set(o)];e.categories=`Duplicate category names found: ${t.join(", ")}`}}return{valid:0===Object.keys(e).length,errors:e}},render:t=>{var e;const i=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_llm"===t.type);return W`
8947
8947
  <div class="body">Categorize with ${i.llm.name}</div>
8948
- `},toFormData:t=>{var e,i,o;const n=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_llm"===t.type),s=(null===(o=null===(i=t.router)||void 0===i?void 0:i.categories)||void 0===o?void 0:o.filter(t=>"Other"!==t.name&&"Failure"!==t.name).map(t=>({name:t.name})))||[];return{uuid:t.uuid,llm:(null==n?void 0:n.llm)?[n.llm]:[],input:(null==n?void 0:n.input)||"@input",categories:s}},fromFormData:(t,e)=>{var i,o,n;const s=Array.isArray(t.llm)&&t.llm.length>0?t.llm[0]:null,r=(t.categories||[]).filter(t=>{var e;return null===(e=null==t?void 0:t.name)||void 0===e?void 0:e.trim()}).map(t=>t.name.trim()),a=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"call_llm"===t.type),l={type:"call_llm",uuid:(null==a?void 0:a.uuid)||Xt(),llm:s?{uuid:s.uuid||s.value,name:s.name}:{uuid:"",name:""},instructions:'@(prompt("categorize", slice(node.categories, 0, -2)))',input:t.input||"@input",output_local:"_llm_output"},d=(null===(o=e.router)||void 0===o?void 0:o.categories)||[],c=e.exits||[],h=(null===(n=e.router)||void 0===n?void 0:n.cases)||[],{router:u,exits:p}=((t,e,i,o=[],n=[],s=[])=>{const r=[],a=[],l=[];e.forEach(t=>{const e=De({name:t,existingCategories:o,existingExits:n,existingCases:s,caseConfig:i(t)});r.push(e.category),a.push(e.exit),e.case&&l.push(e.case)});const d=De({name:"Other",existingCategories:o,existingExits:n});r.push(d.category),a.push(d.exit);const c=De({name:"Failure",existingCategories:o,existingExits:n,existingCases:s,caseConfig:{type:"has_only_text",arguments:["<ERROR>"]}});return r.push(c.category),a.push(c.exit),c.case&&l.push(c.case),{router:{type:"switch",categories:r,default_category_uuid:d.category.uuid,operand:t,cases:l},exits:a}})("@locals._llm_output",r,t=>({type:"has_only_text",arguments:[t]}),d,c,h);return{uuid:e.uuid,actions:[l],router:u,exits:p}},localizable:"categories",nonTranslatableCategories:["Failure"],toLocalizationFormData:Mp,fromLocalizationFormData:zp},lm={type:"wait_for_audio",name:"Make Recording",group:Hu.wait,flowTypes:[Bu],form:{result_name:{type:"text",label:"Result Name",required:!1,maxLength:64,placeholder:"(optional)",helpText:"The name to use to reference this result in the flow"}},layout:["result_name"],toFormData:t=>{var e;return{uuid:t.uuid,result_name:(null===(e=t.router)||void 0===e?void 0:e.result_name)||""}},fromFormData:(t,e)=>{var i;const o=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],n=e.exits||[];let s,r=o.find(t=>"All Responses"===t.name);if(r)s=n.find(t=>t.uuid===r.exit_uuid)||{uuid:r.exit_uuid,destination_uuid:null};else{const t=Xt();r={uuid:Xt(),name:"All Responses",exit_uuid:t},s={uuid:t,destination_uuid:null}}const a={type:"switch",operand:"@input",default_category_uuid:r.uuid,cases:[],categories:[r],wait:{type:"msg",hint:{type:"audio"}}};return t.result_name&&""!==t.result_name.trim()&&(a.result_name=t.result_name.trim()),{...e,router:a,exits:[s]}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},dm=["Answered","No Answer","Busy","Failed"],cm=[{type:"has_only_text",arguments:["answered"],categoryName:"Answered"},{type:"has_only_text",arguments:["no_answer"],categoryName:"No Answer"},{type:"has_only_text",arguments:["busy"],categoryName:"Busy"}],hm={type:"wait_for_dial",name:"Redirect Call",group:Hu.wait,flowTypes:[Bu],router:{type:"switch",defaultCategory:"Failed",rules:cm.map(t=>({type:t.type,arguments:t.arguments,categoryName:t.categoryName}))},form:{phone:{type:"text",label:"Phone Number",required:!0,evaluated:!0,placeholder:"Phone number or expression"},dial_limit_seconds:{type:"text",label:"Dial Limit (seconds)",required:!1,placeholder:"60"},call_limit_seconds:{type:"text",label:"Call Limit (seconds)",required:!1,placeholder:"7200"},result_name:Sp},layout:["phone",{type:"row",items:["dial_limit_seconds","call_limit_seconds"]},"result_name"],toFormData:t=>{var e,i;const o=null===(e=t.router)||void 0===e?void 0:e.wait;return{uuid:t.uuid,phone:(null==o?void 0:o.phone)||"",dial_limit_seconds:(null==o?void 0:o.dial_limit_seconds)?String(o.dial_limit_seconds):"",call_limit_seconds:(null==o?void 0:o.call_limit_seconds)?String(o.call_limit_seconds):"",result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o;const n=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],s=e.exits||[],r=(null===(o=e.router)||void 0===o?void 0:o.cases)||[],a=[],l=[],d=[];for(const t of dm){const e=n.find(e=>e.name===t);if(e){a.push(e);const t=s.find(t=>t.uuid===e.exit_uuid);l.push(t||{uuid:e.exit_uuid,destination_uuid:null})}else{const e=Xt();a.push({uuid:Xt(),name:t,exit_uuid:e}),l.push({uuid:e,destination_uuid:null})}}for(const t of cm){const e=a.find(e=>e.name===t.categoryName);if(!e)continue;const i=r.find(e=>{var i;return e.type===t.type&&(null===(i=e.arguments)||void 0===i?void 0:i[0])===t.arguments[0]});d.push({uuid:(null==i?void 0:i.uuid)||Xt(),type:t.type,arguments:t.arguments,category_uuid:e.uuid})}const c=a.find(t=>"Failed"===t.name),h=(t.phone||"").trim(),u=parseInt(t.dial_limit_seconds,10),p=parseInt(t.call_limit_seconds,10),m={type:"dial",phone:h};!isNaN(u)&&u>0&&(m.dial_limit_seconds=u),!isNaN(p)&&p>0&&(m.call_limit_seconds=p);const g={type:"switch",operand:'@(default(resume.dial.status, ""))',default_category_uuid:null==c?void 0:c.uuid,cases:d,categories:a,wait:m};return t.result_name&&""!==t.result_name.trim()&&(g.result_name=t.result_name.trim()),{...e,router:g,exits:l}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},um={type:"wait_for_digits",name:"Wait for Digits",group:Hu.wait,flowTypes:[Bu],dialogSize:"large",form:{rules:jp(Cp(xp.filter(t=>_p.has(t.type))),""),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:[{type:"text",text:"Rules match against all digits pressed by the caller followed by the # sign."},"rules",Tp],validate:t=>({valid:!0,errors:{}}),toFormData:(t,e)=>{var i,o,n;const s=Up(t);return{uuid:t.uuid,rules:s,result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||"",localizeRules:(null===(o=null==e?void 0:e.config)||void 0===o?void 0:o.localizeRules)||!1,localizeCategories:(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.localizeCategories)||!1}},toUIConfig:t=>{const e={};return e.localizeRules=!!t.localizeRules,e.localizeCategories=!!t.result_name&&!!t.localizeCategories,e},fromFormData:(t,e)=>{var i,o;const n=qp(t),s=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],r=e.exits||[],a=(null===(o=e.router)||void 0===o?void 0:o.cases)||[],{router:l,exits:d}=Oe("@input.text",n,kp,s,r,a),c={...l,wait:{type:"msg",hint:{type:"digits"}}};return t.result_name&&""!==t.result_name.trim()&&(c.result_name=t.result_name.trim()),{...e,router:c,exits:d}},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},pm=["1","2","3","4","5","6","7","8","9","0"];function mm(t){return`digit_${t}`}const gm={type:"wait_for_menu",name:"Wait for Menu",group:Hu.wait,flowTypes:[Bu],form:{...Object.fromEntries(pm.map(t=>[mm(t),{type:"text",required:!1,placeholder:"",flavor:"xsmall"}])),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:[{type:"row",items:["digit_1","digit_2","digit_3"],gap:"2rem",marginBottom:"0.5rem",inlineLabels:{digit_1:"1",digit_2:"2",digit_3:"3"}},{type:"row",items:["digit_4","digit_5","digit_6"],gap:"2rem",marginBottom:"0.5rem",inlineLabels:{digit_4:"4",digit_5:"5",digit_6:"6"}},{type:"row",items:["digit_7","digit_8","digit_9"],gap:"2rem",marginBottom:"0.5rem",inlineLabels:{digit_7:"7",digit_8:"8",digit_9:"9"}},{type:"row",items:[{type:"spacer"},"digit_0",{type:"spacer"}],gap:"2rem",inlineLabels:{digit_0:"0"}},Tp],toFormData:(t,e)=>{var i,o,n,s,r,a;const l={uuid:t.uuid,result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""};for(const t of pm)l[mm(t)]="";if((null===(o=t.router)||void 0===o?void 0:o.cases)&&(null===(n=t.router)||void 0===n?void 0:n.categories))for(const e of t.router.cases)if("has_number_eq"===e.type&&(null===(s=e.arguments)||void 0===s?void 0:s[0])){const i=e.arguments[0],o=t.router.categories.find(t=>t.uuid===e.category_uuid);o&&pm.includes(i)&&(l[mm(i)]=o.name)}return l.localizeRules=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.localizeRules)||!1,l.localizeCategories=(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.localizeCategories)||!1,l},toUIConfig:t=>{const e={};return e.localizeRules=!!t.localizeRules,e.localizeCategories=!!t.result_name&&!!t.localizeCategories,e},fromFormData:(t,e)=>{var i,o;const n=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],s=e.exits||[],r=(null===(o=e.router)||void 0===o?void 0:o.cases)||[],a=[],l=[],d=[];for(const e of pm){const i=(t[mm(e)]||"").trim();if(!i)continue;let o=a.find(t=>t.name===i);if(!o){const t=n.find(t=>t.name===i);if(t){o=t;const e=s.find(e=>e.uuid===t.exit_uuid);a.push(o),l.push(e||{uuid:t.exit_uuid,destination_uuid:null})}else{const t=Xt();o={uuid:Xt(),name:i,exit_uuid:t},a.push(o),l.push({uuid:t,destination_uuid:null})}}const c=r.find(t=>{var i;return"has_number_eq"===t.type&&(null===(i=t.arguments)||void 0===i?void 0:i[0])===e});d.push({uuid:(null==c?void 0:c.uuid)||Xt(),type:"has_number_eq",arguments:[e],category_uuid:o.uuid})}const c=n.find(t=>"Other"===t.name);let h;if(c){h=c;const t=s.find(t=>t.uuid===c.exit_uuid);l.push(t||{uuid:c.exit_uuid,destination_uuid:null})}else{const t=Xt();h={uuid:Xt(),name:"Other",exit_uuid:t},l.push({uuid:t,destination_uuid:null})}a.push(h);const u={type:"switch",operand:"@input.text",default_category_uuid:h.uuid,cases:d,categories:a,wait:{type:"msg",hint:{type:"digits",count:1}}};return t.result_name&&""!==t.result_name.trim()&&(u.result_name=t.result_name.trim()),{...e,router:u,exits:l}},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},fm=[{value:"60",name:"1 minute"},{value:"120",name:"2 minutes"},{value:"180",name:"3 minutes"},{value:"240",name:"4 minutes"},{value:"300",name:"5 minutes"},{value:"600",name:"10 minutes"},{value:"900",name:"15 minutes"},{value:"1800",name:"30 minutes"},{value:"3600",name:"1 hour"},{value:"7200",name:"2 hours"},{value:"10800",name:"3 hours"},{value:"21600",name:"6 hours"},{value:"43200",name:"12 hours"},{value:"64800",name:"18 hours"},{value:"86400",name:"1 day"},{value:"172800",name:"2 days"},{value:"259200",name:"3 days"},{value:"604800",name:"1 week"}],vm=(t,e=[],i=[],o=[])=>{const{router:n,exits:s}=Oe("@input.text",t,kp,e,i,o),r=e.find(t=>"No Response"===t.name||"Timeout"===t.name);if(r){const t=i.find(t=>t.uuid===r.exit_uuid);t&&(n.categories.push(r),s.push({uuid:t.uuid,destination_uuid:t.destination_uuid||null}))}return{router:n,exits:s}},bm={type:"wait_for_response",name:"Wait for Response",group:Hu.wait,flowTypes:[Nu],hideFromSplits:!0,dialogSize:"large",form:{rules:jp(Cp(wp()),"If the message from the contact..."),timeout_enabled:{type:"checkbox",label:t=>t.timeout_enabled?"Continue when there is no response for":"Continue when there is no response..",labelPadding:"4px 8px"},timeout_duration:{type:"select",placeholder:"5 minutes",multi:!1,maxWidth:"130px",flavor:"xsmall",options:fm,conditions:{visible:t=>!0===t.timeout_enabled}},result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:["rules",Tp],gutter:[{type:"row",items:["timeout_enabled","timeout_duration"],gap:"0.5rem"}],validate:t=>{const e={};return{valid:0===Object.keys(e).length,errors:e}},toFormData:(t,e)=>{var i,o,n,s,r,a;const l=Up(t),d=null===(n=null===(o=null===(i=t.router)||void 0===i?void 0:i.wait)||void 0===o?void 0:o.timeout)||void 0===n?void 0:n.seconds;let c=fm.find(t=>t.value===String(d));return c||(c={value:"300",name:"5 minutes"}),{uuid:t.uuid,rules:l,timeout_enabled:!!d,timeout_duration:c,result_name:(null===(s=t.router)||void 0===s?void 0:s.result_name)||"",localizeRules:(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.localizeRules)||!1,localizeCategories:(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.localizeCategories)||!1}},toUIConfig:t=>{const e={};return e.localizeRules=!!t.localizeRules,e.localizeCategories=!!t.result_name&&!!t.localizeCategories,e},fromFormData:(t,e)=>{var i,o,n,s,r,a,l,d;const c=qp(t);if(0===c.length){let o=(null===(i=e.router)||void 0===i?void 0:i.categories)||[];const n=[...e.exits||[]];if(t.timeout_enabled){let t=o.find(t=>"No Response"===t.name);if(!t){const e=Xt();t={uuid:Xt(),name:"No Response",exit_uuid:e},o=[...o,t],n.find(t=>t.uuid===e)||n.push({uuid:e,destination_uuid:null})}}else o=o.filter(t=>"No Response"!==t.name);const{router:s,exits:r}=vm([],o,n,[]),a={...s,cases:[]};t.result_name&&""!==t.result_name.trim()&&(a.result_name=t.result_name.trim());const l={type:"msg"};if(t.timeout_enabled){let e;e=t.timeout_duration?Array.isArray(t.timeout_duration)&&t.timeout_duration.length>0?parseInt(t.timeout_duration[0].value,10):"string"==typeof t.timeout_duration?parseInt(t.timeout_duration,10):t.timeout_duration&&"object"==typeof t.timeout_duration&&t.timeout_duration.value?parseInt(t.timeout_duration.value,10):300:300,(isNaN(e)||e<=0)&&(e=300);const i=a.categories.find(t=>"No Response"===t.name);i&&(l.timeout={seconds:e,category_uuid:i.uuid})}return a.wait=l,{...e,router:a,exits:r}}const h=(null===(o=e.router)||void 0===o?void 0:o.categories)||[],u=e.exits||[],p=(null===(n=e.router)||void 0===n?void 0:n.cases)||[],{router:m,exits:g}=vm(c,h,u,p),f={...m};t.result_name&&""!==t.result_name.trim()&&(f.result_name=t.result_name.trim());const v={type:"msg"};try{if(t.timeout_enabled){let i;if(t.timeout_duration)try{i=parseInt(t.timeout_duration[0].value,10)}catch(t){i=300}const o=null===(r=null===(s=e.router)||void 0===s?void 0:s.categories)||void 0===r?void 0:r.find(t=>"No Response"===t.name),n=o||{uuid:Xt(),name:"No Response",exit_uuid:Xt()};if(v.timeout={seconds:i,category_uuid:n.uuid},!(null===(a=m.categories)||void 0===a?void 0:a.some(t=>"No Response"===t.name))&&(m.categories=m.categories||[],m.categories.push(n),!g.some(t=>t.uuid===n.exit_uuid))){const t={uuid:n.exit_uuid,destination_uuid:(null==o?void 0:o.exit_uuid)&&(null===(d=null===(l=e.exits)||void 0===l?void 0:l.find(t=>t.uuid===o.exit_uuid))||void 0===d?void 0:d.destination_uuid)||null};g.push(t)}}else if(m.categories){const t=m.categories.findIndex(t=>"No Response"===t.name);if(-1!==t){const e=m.categories[t];m.categories.splice(t,1);const i=g.findIndex(t=>t.uuid===e.exit_uuid);-1!==i&&g.splice(i,1)}}}catch(t){console.error("Error processing timeout configuration:",t)}return f.wait=v,{...e,router:f,exits:g}},localizable:"categories",nonTranslatableCategories:["Timeout"],toLocalizationFormData:Mp,fromLocalizationFormData:zp},ym=xm({say_msg:mp,play_audio:gp,set_contact_field:Ku,send_broadcast:Ju,set_run_result:tp,send_msg:ip,send_email:op,start_session:np,set_contact_name:sp,add_contact_groups:rp,remove_contact_groups:ap,set_contact_channel:Gu,set_contact_language:Xu,set_contact_status:Qu,add_contact_urn:Yu,add_input_labels:Zu,request_optin:lp,enter_flow:vp});function xm(t){const e={...t};return Object.values(t).forEach(t=>{t.aliases&&t.aliases.forEach(i=>{e[i]=t})}),e}const wm=xm({execute_actions:{type:"execute_actions"},split_by_contact_field:Wp,split_by_expression:Vp,split_by_groups:Zp,split_by_llm:rm,split_by_llm_categorize:am,split_by_random:Yp,split_by_run_result:Xp,split_by_scheme:Qp,split_by_subflow:Jp,split_by_ticket:tm,split_by_webhook:nm,split_by_resthook:sm,wait_for_menu:gm,wait_for_digits:um,wait_for_audio:lm,wait_for_dial:hm,wait_for_response:bm,split_by_airtime:Ip,terminal:{type:"terminal"}}),_m=60,km=20;function Cm(t,e,i,o){if(0===t.length)return{};const n=new Set(t.map(t=>t.uuid)),s=new Map,r=new Map;for(const e of t){const t=new Set,i=[];for(const o of e.exits)if(o.destination_uuid&&n.has(o.destination_uuid)&&!t.has(o.destination_uuid)){t.add(o.destination_uuid),i.push(o.destination_uuid);const n=r.get(o.destination_uuid)||[];n.push(e.uuid),r.set(o.destination_uuid,n)}s.set(e.uuid,i)}const a=function(t,e){const i=new Set,o=new Set,n=new Set;function s(t){o.add(t),n.add(t);for(const r of e.get(t)||[])o.has(r)?i.add(`${t}->${r}`):n.has(r)||s(r);o.delete(t)}return s(t),i}(i,s),l=function(t,e,i,o,n){const s=new Map;s.set(t,0);const r=new Map;for(const t of e)r.set(t.uuid,0);for(const[t,e]of i)for(const i of e)n.has(`${t}->${i}`)||r.set(i,(r.get(i)||0)+1);const a=[];for(const[t,e]of r)0===e&&(a.push(t),s.has(t)||s.set(t,0));for(;a.length>0;){const t=a.shift(),e=s.get(t);for(const o of i.get(t)||[]){if(n.has(`${t}->${o}`))continue;const i=e+1;(!s.has(o)||i>s.get(o))&&s.set(o,i);const l=r.get(o)-1;r.set(o,l),0===l&&a.push(o)}}const l=e.filter(t=>!s.has(t.uuid));if(l.length>0){let t=Math.max(...Array.from(s.values()),-1)+2;for(const e of l)s.set(e.uuid,t),t++}return s}(i,t,s,0,a),d=new Map;for(const[t,e]of l){const i=d.get(e)||[];i.push(t),d.set(e,i)}const c=Array.from(d.keys()).sort((t,e)=>t-e);!function(t,e,i,o){const n=new Map;for(const s of t){const r=e.get(s);if(s===t[0]){r.forEach((t,e)=>n.set(t,e));continue}const a=r.map(t=>{const e=(i.get(t)||[]).filter(t=>{const e=o.get(t);return void 0!==e&&e<s});if(0===e.length)return{uuid:t,value:1/0};const r=e.reduce((t,e)=>{var i;return t+(null!==(i=n.get(e))&&void 0!==i?i:0)},0);return{uuid:t,value:r/e.length}});a.sort((t,e)=>t.value-e.value);const l=a.map(t=>t.uuid);e.set(s,l),l.forEach((t,e)=>n.set(t,e))}}(c,d,r,l);const h=new Map;for(const e of t)h.set(e.uuid,o(e.uuid));return function(t,e,i,o,n,s){var r,a,l,d;const c={};let h=0;for(const u of t){const p=Sm(e.get(u),i);for(const e of p){const p=bu(h);if(u===t[0]){let t=0;for(const o of e){const e=o===s?p:p+40;c[o]={left:bu(t),top:e},t+=((null===(r=i.get(o))||void 0===r?void 0:r.width)||200)+_m}}else{let t=0;for(const o of e)t+=(null===(a=i.get(o))||void 0===a?void 0:a.width)||200;t+=_m*(e.length-1);const s=[];for(const t of e){const e=(o.get(t)||[]).filter(t=>{const e=n.get(t);return void 0!==e&&e<u});for(const t of e){const e=c[t];if(e){const o=(null===(l=i.get(t))||void 0===l?void 0:l.width)||200;s.push(e.left+o/2)}}}let r;if(s.length>0){const e=(Math.min(...s)+Math.max(...s))/2;r=Math.max(0,e-t/2)}else r=0;let h=r;for(const t of e){const e=(null===(d=i.get(t))||void 0===d?void 0:d.width)||200;c[t]={left:bu(h),top:p},h=bu(h)+e+_m}}const m=Math.max(...e.map(t=>{var e;return(null===(e=i.get(t))||void 0===e?void 0:e.height)||100}));h=p+m+80}}const u=c[s];if(u){const t=u.left,e=u.top;for(const i of Object.keys(c))c[i]={left:bu(Math.max(0,c[i].left-t)),top:bu(Math.max(0,c[i].top-e))}}return c}(c,d,h,r,l,i)}function Sm(t,e){var i;const o=[];let n=[],s=0;for(const r of t){const t=(null===(i=e.get(r))||void 0===i?void 0:i.width)||200,a=n.length>0?_m+t:t;n.length>0&&s+a>1200?(o.push(n),n=[r],s=t):(n.push(r),s+=a)}return n.length>0&&o.push(n),o}function Am(t,e,i,o,n){for(const s of n)if(t<s.left+s.width+km&&t+i+km>s.left&&e<s.top+s.height+km&&e+o+km>s.top)return!0;return!1}function Em(t){if("touches"in t){const e=t.touches[0]||t.changedTouches[0];return{clientX:e.clientX,clientY:e.clientY}}return{clientX:t.clientX,clientY:t.clientY}}function $m(t,e,i,o,n=20,s=10,r=5,a="top",l=0){const d=r;if("top"===a){const r=e+n,a=o-s;let c=`M ${t} ${e}`;if(t===i)c+=` L ${i} ${a}`;else{const o=i>t?1:-1,n=Math.max(e+d,Math.min(r,a-d)),s=Math.max(e+d,Math.min(n+l,a-d-3)),h=Math.min(d,s-e);h>=1?(c+=` L ${t} ${s-h}`,c+=` Q ${t} ${s}, ${t+o*h} ${s}`):c+=` L ${t} ${s}`;const u=3,p=Math.min(d,Math.max(0,a-s-u));p>=1?(c+=` L ${i-o*p} ${s}`,c+=` Q ${i} ${s}, ${i} ${s+p}`):c+=` L ${i} ${s}`,c+=` L ${i} ${a}`}return c+=` L ${i} ${o}`,c}if("left"===a||"right"===a){const r=e+(o<e?0:n),l="left"===a?-1:1,c=i+l*s,h=c>t?1:-1,u=3,p=h===l?r+2*d:Math.max(r+2*d,o);let m=`M ${t} ${e} L ${t} ${r}`;p-r>d&&(m+=` L ${t} ${p-d}`,m+=` Q ${t} ${p}, ${t+h*d} ${p}`);const g=Math.abs(p-o);if(g<1)m+=` L ${c} ${o}`,m+=` L ${i} ${o}`;else{const t=o<p?-1:1,e=Math.min(d,Math.max(0,Math.floor((g-u)/2)),Math.max(0,s-u));e>=1?(m+=` L ${c-h*e} ${p}`,m+=` Q ${c} ${p}, ${c} ${p+t*e}`,m+=` L ${c} ${o-t*e}`,m+=` Q ${c} ${o}, ${c-l*e} ${o}`):(m+=` L ${c} ${p}`,m+=` L ${c} ${o}`),m+=` L ${i} ${o}`}return m}return`M ${t} ${e} L ${i} ${o}`}class Tm{constructor(t,e){this.connections=new Map,this.sources=new Map,this.pendingConnections=[],this.connectionWait=null,this.connectionListeners=new Map,this.dragState=null,this.retryCount=0,this.maxRetries=3,this.activityData=null,this.overlays=new Map,this.hoveredActivityKey=null,this.recentContactsPopup=null,this.recentContactsCache={},this.pendingFetches={},this.hideContactsTimeout=null,this.showContactsTimeout=null,this.connectionDragging=!1,this.zoom=1,this.canvas=t,this.editor=e}setContainer(t){this.canvas=t}notifyListeners(t,e){(this.connectionListeners.get(t)||[]).forEach(t=>t(e))}on(t,e){this.connectionListeners.has(t)||this.connectionListeners.set(t,[]),this.connectionListeners.get(t).push(e)}off(t,e){if(!this.connectionListeners.has(t))return;const i=this.connectionListeners.get(t),o=i.indexOf(e);-1!==o&&i.splice(o,1)}makeSource(t){const e=document.getElementById(t);if(!e)return;this.sources.has(t)&&this.sources.get(t)();let i=null;const o=o=>{if("button"in o&&fu(o))return;if(this.connections.has(t))return;const n="touches"in o;n&&o.preventDefault();const{clientX:s,clientY:r}=Em(o),a=e.closest("temba-flow-node"),l=(null==a?void 0:a.getAttribute("uuid"))||"",d=e=>{const{clientX:i,clientY:o}=Em(e),n=i-s,a=o-r;Math.sqrt(n*n+a*a)>5&&(h(),this.startDrag(t,l,null,e))},c=()=>{h()},h=()=>{document.removeEventListener("mousemove",d),document.removeEventListener("mouseup",c),document.removeEventListener("touchmove",d),document.removeEventListener("touchend",c),document.removeEventListener("touchcancel",c),i=null};document.addEventListener("mousemove",d),document.addEventListener("mouseup",c),document.addEventListener("touchmove",d,{passive:!1}),document.addEventListener("touchend",c),document.addEventListener("touchcancel",c),i={startX:s,startY:r,onMove:d,onUp:c,isTouch:n}};e.addEventListener("mousedown",o),e.addEventListener("touchstart",o,{passive:!1}),this.sources.set(t,()=>{e.removeEventListener("mousedown",o),e.removeEventListener("touchstart",o),i&&(document.removeEventListener("mousemove",i.onMove),document.removeEventListener("mouseup",i.onUp),document.removeEventListener("touchmove",i.onMove),document.removeEventListener("touchend",i.onUp),document.removeEventListener("touchcancel",i.onUp),i=null)})}makeTarget(t){}connectIds(t,e,i){this.pendingConnections.push({scope:t,fromId:e,toId:i}),this.processPendingConnections()}processPendingConnections(){this.connectionWait&&(cancelAnimationFrame(this.connectionWait),this.connectionWait=null),this.connectionWait=requestAnimationFrame(()=>{const t=[],e=new Set;if(this.pendingConnections.forEach(i=>{const{scope:o,fromId:n,toId:s}=i;this.removeConnectionSVG(n),this.createConnectionSVG(n,o,s)?e.add(s):t.push(i)}),this.pendingConnections=[],e.size>0){const t=new Set;this.connections.forEach(i=>{e.has(i.toId)&&t.add(i.scope)}),this.connections.forEach((i,o)=>{(e.has(i.toId)||t.has(i.scope))&&this.updateConnectionSVG(o)})}t.length>0&&this.retryCount<this.maxRetries?(this.retryCount++,this.pendingConnections=t,this.processPendingConnections()):this.retryCount=0})}toCanvas(t){return t/this.zoom}determineTargetFace(t,e,i,o){return o-e>30?"top":t<i?"left":"right"}getConnectionEndpoints(t,e,i){const o=document.getElementById(t),n=document.getElementById(e);if(!o||!n)return null;const s=this.canvas.getBoundingClientRect(),r=o.getBoundingClientRect(),a=n.getBoundingClientRect();if(0===r.width||0===a.width)return null;const l=this.toCanvas(r.left+r.width/2-s.left),d=this.toCanvas(r.bottom-s.top),c=this.toCanvas(a.left+a.width/2-s.left),h=this.toCanvas(a.top-s.top),u=this.determineTargetFace(l,d,c,h),p=new Map;this.connections.forEach(t=>{if(t.toId===e){const e=document.getElementById(t.fromId);if(e){const i=e.getBoundingClientRect(),o=this.toCanvas(i.left+i.width/2-s.left),n=this.toCanvas(i.bottom-s.top),r=this.determineTargetFace(o,n,c,h);p.has(r)||p.set(r,[]);const a="top"===r?o:n;p.get(r).push({fromId:t.fromId,sortPos:a})}}}),p.has(u)||p.set(u,[]);const m=p.get(u);if(!m.find(e=>e.fromId===t)){const e="top"===u?l:d;m.push({fromId:t,sortPos:e})}m.sort((t,e)=>t.sortPos-e.sortPos);const g=m.findIndex(e=>e.fromId===t),f=m.length,v=this.toCanvas(a.left-s.left),b=h,y=this.toCanvas(a.width),x=this.toCanvas(a.height);let w,_;if("top"===u){w=1===f?v+y/2:v+.2*y+.6*y*(g+.5)/f,_=b}else if("left"===u){w=v;_=1===f?b+x/2:b+.2*x+.6*x*(g+.5)/f}else{w=v+y;_=1===f?b+x/2:b+.2*x+.6*x*(g+.5)/f}let k=0;if("top"===u&&i){const o=8,n=50,r=[];if(this.connections.forEach(t=>{if(t.scope===i&&t.toId!==e){const e=document.getElementById(t.fromId),i=document.getElementById(t.toId);if(e&&i){const o=e.getBoundingClientRect(),n=i.getBoundingClientRect(),a=this.toCanvas(o.left+o.width/2-s.left),l=this.toCanvas(o.bottom-s.top),d=this.toCanvas(n.left+n.width/2-s.left),c=this.toCanvas(n.top-s.top);if("top"===this.determineTargetFace(a,l,d,c)){const e=this.toCanvas(n.left-s.left),i=this.toCanvas(n.width);r.push({fromId:t.fromId,targetX:e+i/2})}}}}),r.length>0){r.push({fromId:t,targetX:w}),r.sort((t,e)=>t.targetX-e.targetX);const e=r.findIndex(e=>e.fromId===t),i=r.length;k=(e-(i-1)/2)*((i-1)*o>n?n/(i-1):o)}}return{sourceX:l,sourceY:d,targetX:w,targetY:_,targetFace:u,jogYOffset:k}}createSVGElement(){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.classList.add("plumb-connector"),t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.pointerEvents="none",t.style.overflow="visible";const e=document.createElementNS("http://www.w3.org/2000/svg","path");e.setAttribute("fill","none"),e.setAttribute("stroke","var(--color-connectors)"),e.setAttribute("stroke-width","3"),e.style.pointerEvents="stroke";const i=document.createElementNS("http://www.w3.org/2000/svg","polygon");i.setAttribute("fill","var(--color-connectors)"),i.classList.add("plumb-arrow"),i.style.pointerEvents="fill",i.style.cursor="pointer";const o=document.createElementNS("http://www.w3.org/2000/svg","circle");o.setAttribute("r","18"),o.setAttribute("fill","transparent"),o.style.pointerEvents="fill",o.style.cursor="pointer",t.appendChild(e),t.appendChild(o),t.appendChild(i);const n=()=>t.classList.add("hover"),s=()=>t.classList.remove("hover");return e.addEventListener("mouseenter",n),e.addEventListener("mouseleave",s),i.addEventListener("mouseenter",n),i.addEventListener("mouseleave",s),o.addEventListener("mouseenter",n),o.addEventListener("mouseleave",s),{svgEl:t,pathEl:e,arrowEl:i,hitAreaEl:o}}updateSVGPath(t,e,i,o,n,s,r="top",a=0,l){const d=6.5,c=13;let h=n,u=s;"top"===r?u=s-c:"left"===r?h=n-c:"right"===r&&(h=n+c);const p=$m(i,o,h,u,30,8,5,r,a);if(t.setAttribute("d",p),"top"===r?e.setAttribute("points",`${n},${s} ${n-d},${s-c} ${n+d},${s-c}`):"left"===r?e.setAttribute("points",`${n},${s} ${n-c},${s-d} ${n-c},${s+d}`):e.setAttribute("points",`${n},${s} ${n+c},${s-d} ${n+c},${s+d}`),l){const t=6.5;let e=n,i=s;"top"===r?i=s-t:e="left"===r?n-t:n+t,l.setAttribute("cx",String(e)),l.setAttribute("cy",String(i))}}createConnectionSVG(t,e,i){const o=this.getConnectionEndpoints(t,i,e);if(!o)return!1;const{svgEl:n,pathEl:s,arrowEl:r,hitAreaEl:a}=this.createSVGElement();this.updateSVGPath(s,r,o.sourceX,o.sourceY,o.targetX,o.targetY,o.targetFace,o.jogYOffset,a),this.canvas.appendChild(n),this.connections.set(t,{scope:e,fromId:t,toId:i,svgEl:n,pathEl:s,arrowEl:r,hitAreaEl:a});const l=o=>{if("button"in o&&fu(o))return;o.stopPropagation(),"touches"in o&&o.preventDefault();const{clientX:n,clientY:s}=Em(o),r=o=>{const{clientX:l,clientY:d}=Em(o),c=l-n,h=d-s;Math.sqrt(c*c+h*h)>5&&(document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",a),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",a),document.removeEventListener("touchcancel",a),this.startDrag(t,e,i,o))},a=()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",a),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",a),document.removeEventListener("touchcancel",a)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",a),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",a),document.addEventListener("touchcancel",a)};r.addEventListener("mousedown",l),r.addEventListener("touchstart",l,{passive:!1}),a.addEventListener("mousedown",l),a.addEventListener("touchstart",l,{passive:!1}),s.addEventListener("mousedown",l),s.addEventListener("touchstart",l,{passive:!1});const d=document.getElementById(t);if(d&&d.classList.add("connected"),this.activityData){const e=`${t}:${i}`,o=this.activityData.segments[e];if(o&&o>0){const i=this.createOverlayElement(o,e);this.canvas.appendChild(i),this.overlays.set(t,i),this.updateOverlayPosition(t)}}return!0}updateConnectionSVG(t){const e=this.connections.get(t);if(!e)return;const i=this.getConnectionEndpoints(e.fromId,e.toId,e.scope);i&&(this.updateSVGPath(e.pathEl,e.arrowEl,i.sourceX,i.sourceY,i.targetX,i.targetY,i.targetFace,i.jogYOffset,e.hitAreaEl),this.updateOverlayPosition(t))}removeConnectionSVG(t){const e=this.connections.get(t);if(!e)return;const i=this.overlays.get(t);i&&(i.remove(),this.overlays.delete(t)),e.svgEl.remove(),this.connections.delete(t)}repaintEverything(){this.connections.forEach((t,e)=>{this.updateConnectionSVG(e)})}revalidate(t){const e=[],i=new Set;this.connections.forEach((o,n)=>{(t.includes(o.fromId)||t.includes(o.toId)||t.includes(o.scope))&&(e.push(n),i.add(o.toId))});const o=new Set(e);this.connections.forEach((t,e)=>{i.has(t.toId)&&o.add(e)}),o.forEach(t=>{this.updateConnectionSVG(t)})}forgetNode(t){var e;const i=[];this.connections.forEach((e,o)=>{e.scope!==t&&e.toId!==t||i.push(o)}),i.forEach(t=>this.removeConnectionSVG(t));const o=null===(e=document.getElementById(t))||void 0===e?void 0:e.querySelectorAll(".exit");o&&o.forEach(t=>{const e=t.id;this.sources.has(e)&&(this.sources.get(e)(),this.sources.delete(e))})}removeNodeConnections(t,e){var i;(e||Array.from((null===(i=document.getElementById(t))||void 0===i?void 0:i.querySelectorAll(".exit"))||[]).map(t=>t.id)).forEach(t=>this.removeConnectionSVG(t))}removeExitConnection(t){return!!this.connections.has(t)&&(this.removeConnectionSVG(t),!0)}removeAllEndpoints(t){var e;const i=null===(e=document.getElementById(t))||void 0===e?void 0:e.querySelectorAll(".exit");i&&i.forEach(t=>{const e=t.id;this.sources.has(e)&&(this.sources.get(e)(),this.sources.delete(e))})}setConnectionRemovingState(t,e){const i=this.connections.get(t);return!!i&&(e?i.svgEl.classList.add("removing"):i.svgEl.classList.remove("removing"),!0)}setActivityData(t){this.activityData=t,this.clearRecentContactsCache(),this.updateActivityOverlays()}updateActivityOverlays(){if(!this.activityData)return this.overlays.forEach(t=>t.remove()),void this.overlays.clear();const t=new Set;this.connections.forEach((e,i)=>{const o=`${e.fromId}:${e.toId}`,n=this.activityData.segments[o];if(n&&n>0){t.add(i);let e=this.overlays.get(i);e?(e.textContent=n.toLocaleString(),e.setAttribute("data-activity-key",o)):(e=this.createOverlayElement(n,o),this.canvas.appendChild(e),this.overlays.set(i,e)),this.updateOverlayPosition(i)}}),this.overlays.forEach((e,i)=>{t.has(i)||(e.remove(),this.overlays.delete(i))})}createOverlayElement(t,e){const i=document.createElement("div");return i.className="activity-overlay",i.textContent=t.toLocaleString(),i.setAttribute("data-activity-key",e),i.addEventListener("mouseenter",()=>{const t=this.getFlowUuid();t&&(this.fetchRecentContacts(e,t),this.showContactsTimeout=window.setTimeout(()=>{this.showRecentContacts(e,t)},500))}),i.addEventListener("mouseleave",()=>{this.showContactsTimeout&&(clearTimeout(this.showContactsTimeout),this.showContactsTimeout=null),this.hoveredActivityKey=null,this.hideRecentContacts()}),i}updateOverlayPosition(t){const e=this.overlays.get(t),i=this.connections.get(t);if(!e||!i)return;const o=this.getConnectionEndpoints(i.fromId,i.toId,i.scope);o&&(e.style.position="absolute",e.style.left=`${o.sourceX}px`,e.style.top=`${o.sourceY+15}px`,e.style.transform="translate(-50%, -50%)")}getFlowUuid(){var t,e;return(null===(e=null===(t=this.editor)||void 0===t?void 0:t.definition)||void 0===e?void 0:e.uuid)||null}async fetchRecentContacts(t,e){if(this.recentContactsCache[t]||this.pendingFetches[t])return;const i=new AbortController;this.pendingFetches[t]=i;try{const[o,n]=t.split(":"),s=`/flow/recent_contacts/${e}/${o}/${n}/`,r=await fetch(s,{signal:i.signal});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);const a=await r.json();this.recentContactsCache[t]=Array.isArray(a)?a:a.results||[]}catch(t){"AbortError"!==t.name&&console.error("Failed to fetch recent contacts:",t)}finally{delete this.pendingFetches[t]}}async showRecentContacts(t,e){const i=this.findOverlayForActivityKey(t);i&&(this.hideContactsTimeout&&(clearTimeout(this.hideContactsTimeout),this.hideContactsTimeout=null),this.hoveredActivityKey=t,this.recentContactsPopup||(this.recentContactsPopup=document.createElement("div"),this.recentContactsPopup.className="recent-contacts-popup",this.recentContactsPopup.style.position="absolute",this.recentContactsPopup.style.zIndex="1015",this.recentContactsPopup.style.display="none",document.body.appendChild(this.recentContactsPopup),this.recentContactsPopup.onmouseenter=()=>{this.hideContactsTimeout&&(clearTimeout(this.hideContactsTimeout),this.hideContactsTimeout=null)},this.recentContactsPopup.onmouseleave=()=>{this.hoveredActivityKey=null,this.hideRecentContacts()},this.recentContactsPopup.onclick=t=>{const e=t.target;if(e.classList.contains("contact-name")){this.hideRecentContacts(!1);const i=e.getAttribute("data-uuid");i&&this.editor.fireCustomEvent("temba-contact-clicked",{uuid:i,metaKey:t.metaKey,ctrlKey:t.ctrlKey})}}),this.recentContactsCache[t]?(this.renderRecentContactsPopup(this.recentContactsCache[t]),this.positionPopup(i)):(this.recentContactsPopup.innerHTML='<div class="no-contacts-message">Loading...</div>',this.positionPopup(i),await this.fetchRecentContacts(t,e),this.hoveredActivityKey===t&&(this.renderRecentContactsPopup(this.recentContactsCache[t]||[]),this.positionPopup(i))))}findOverlayForActivityKey(t){for(const[,e]of this.overlays)if(e.getAttribute("data-activity-key")===t)return e;return null}positionPopup(t){if(!this.recentContactsPopup)return;const e=t.getBoundingClientRect();this.recentContactsPopup.style.left=`${e.left+window.scrollX}px`,this.recentContactsPopup.style.top=`${e.bottom+window.scrollY+5}px`,this.recentContactsPopup.style.display="",this.recentContactsPopup.classList.remove("show"),this.recentContactsPopup.offsetWidth,this.recentContactsPopup.classList.add("show")}renderRecentContactsPopup(t){if(!this.recentContactsPopup)return;if(0===t.length)return void(this.recentContactsPopup.innerHTML='<div class="no-contacts-message">No Recent Contacts</div>');let e='<div class="popup-title">Recent Contacts</div>';t.forEach(t=>{if(e+='<div class="contact-row">',e+=`<div class="contact-name" data-uuid="${t.contact.uuid}">${t.contact.name}</div>`,t.operand&&(e+=`<div class="contact-operand">${t.operand}</div>`),t.time){const i=new Date(t.time),o=Date.now()-i.getTime(),n=Math.floor(o/6e4),s=Math.floor(o/36e5),r=Math.floor(o/864e5);let a="";a=n<1?"just now":n<60?`${n}m ago`:s<24?`${s}h ago`:`${r}d ago`,e+=`<div class="contact-time">${a}</div>`}e+="</div>"}),this.recentContactsPopup.innerHTML=e}hideRecentContacts(t=!0){t?this.hideContactsTimeout=window.setTimeout(()=>{!this.hoveredActivityKey&&this.recentContactsPopup&&(this.recentContactsPopup.classList.remove("show"),this.recentContactsPopup.style.display="none",this.hoveredActivityKey=null)},200):this.recentContactsPopup&&(this.recentContactsPopup.classList.remove("show"),this.recentContactsPopup.style.display="none",this.hoveredActivityKey=null)}clearRecentContactsCache(){this.recentContactsCache={},Object.values(this.pendingFetches).forEach(t=>t.abort()),this.pendingFetches={}}startDrag(t,e,i,o){const n=this.connections.get(t);if(n){n.svgEl.style.display="none";const e=this.overlays.get(t);e&&(e.style.display="none")}const{svgEl:s,pathEl:r,arrowEl:a,hitAreaEl:l}=this.createSVGElement();s.classList.add("dragging"),r.style.pointerEvents="none",a.style.pointerEvents="none",l.style.pointerEvents="none",this.canvas.appendChild(s);const d=document.getElementById(t);if(!d)return void s.remove();const c=this.canvas.getBoundingClientRect(),h=d.getBoundingClientRect(),u=this.toCanvas(h.left+h.width/2-c.left),p=this.toCanvas(h.bottom-c.top),m=6.5,g=(t,e)=>{const i=e<p;let o,n="top";i&&(n=t<u?"left":"right"),o=i?e+1+13:e-1;const s=$m(u,p,t,o,30,i?0:8,5,n);if(r.setAttribute("d",s),i){const i=e+1;a.setAttribute("points",`${t},${i} ${t-m},${o} ${t+m},${o}`)}else{const e=o+13;a.setAttribute("points",`${t},${e} ${t-m},${o} ${t+m},${o}`)}},{clientX:f,clientY:v}=Em(o),b=this.toCanvas(f-c.left),y=this.toCanvas(v-c.top);g(b,y),this.connectionDragging=!0;const x=t=>{"touches"in t&&t.preventDefault();const e=this.canvas.getBoundingClientRect(),{clientX:i,clientY:o}=Em(t),n=this.toCanvas(i-e.left),s=this.toCanvas(o-e.top);g(n,s)},w=o=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",w),document.removeEventListener("touchmove",x),document.removeEventListener("touchend",w),document.removeEventListener("touchcancel",w),s.remove(),this.removeConnectionSVG(t),this.connectionDragging=!1,this.dragState=null,this.notifyListeners("connection:abort",{source:d,sourceId:t,target:{id:i},data:{nodeId:e}})};document.addEventListener("mousemove",x),document.addEventListener("mouseup",w),document.addEventListener("touchmove",x,{passive:!1}),document.addEventListener("touchend",w),document.addEventListener("touchcancel",w),this.dragState={sourceId:t,scope:e,originalTargetId:i,svgEl:s,pathEl:r,arrowEl:a,onMove:x,onUp:w},this.notifyListeners("connection:drag",{sourceId:t,sourceX:u,sourceY:p,data:{nodeId:e},target:{id:i}})}reset(){this.connectionWait&&(cancelAnimationFrame(this.connectionWait),this.connectionWait=null),this.pendingConnections=[],this.connections.forEach(t=>t.svgEl.remove()),this.connections.clear(),this.overlays.forEach(t=>t.remove()),this.overlays.clear(),this.hideRecentContacts(!1),this.recentContactsPopup&&(this.recentContactsPopup.remove(),this.recentContactsPopup=null),this.recentContactsCache={},Object.values(this.pendingFetches).forEach(t=>t.abort()),this.pendingFetches={},this.sources.forEach(t=>t()),this.sources.clear(),this.dragState&&(document.removeEventListener("mousemove",this.dragState.onMove),document.removeEventListener("mouseup",this.dragState.onUp),this.dragState.svgEl.remove(),this.dragState=null,this.connectionDragging=!1)}}const Dm=new Set(["Other","No Response"]);function Mm(t,e){if(!t||!(null==e?void 0:e.length))return[];const i=wm[t],o=null==i?void 0:i.nonTranslatableCategories;if(!o)return[...e];if("all"===o)return e.filter(t=>Dm.has(t.name));const n=new Set(o);return e.filter(t=>!n.has(t.name)||Dm.has(t.name))}class zm extends Be{createRenderRoot(){return this}static get styles(){return a`
8949
-
8950
- .node {
8951
- background-color: #fff;
8952
- box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
8953
- min-width: 200px;
8954
- border-radius: var(--curvature);
8955
- color: #333;
8956
- user-select: none;
8948
+ `},toFormData:t=>{var e,i,o;const n=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_llm"===t.type),s=(null===(o=null===(i=t.router)||void 0===i?void 0:i.categories)||void 0===o?void 0:o.filter(t=>"Other"!==t.name&&"Failure"!==t.name).map(t=>({name:t.name})))||[];return{uuid:t.uuid,llm:(null==n?void 0:n.llm)?[n.llm]:[],input:(null==n?void 0:n.input)||"@input",categories:s}},fromFormData:(t,e)=>{var i,o,n;const s=Array.isArray(t.llm)&&t.llm.length>0?t.llm[0]:null,r=(t.categories||[]).filter(t=>{var e;return null===(e=null==t?void 0:t.name)||void 0===e?void 0:e.trim()}).map(t=>t.name.trim()),a=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"call_llm"===t.type),l={type:"call_llm",uuid:(null==a?void 0:a.uuid)||Xt(),llm:s?{uuid:s.uuid||s.value,name:s.name}:{uuid:"",name:""},instructions:'@(prompt("categorize", slice(node.categories, 0, -2)))',input:t.input||"@input",output_local:"_llm_output"},d=(null===(o=e.router)||void 0===o?void 0:o.categories)||[],c=e.exits||[],h=(null===(n=e.router)||void 0===n?void 0:n.cases)||[],{router:u,exits:p}=((t,e,i,o=[],n=[],s=[])=>{const r=[],a=[],l=[];e.forEach(t=>{const e=De({name:t,existingCategories:o,existingExits:n,existingCases:s,caseConfig:i(t)});r.push(e.category),a.push(e.exit),e.case&&l.push(e.case)});const d=De({name:"Other",existingCategories:o,existingExits:n});r.push(d.category),a.push(d.exit);const c=De({name:"Failure",existingCategories:o,existingExits:n,existingCases:s,caseConfig:{type:"has_only_text",arguments:["<ERROR>"]}});return r.push(c.category),a.push(c.exit),c.case&&l.push(c.case),{router:{type:"switch",categories:r,default_category_uuid:d.category.uuid,operand:t,cases:l},exits:a}})("@locals._llm_output",r,t=>({type:"has_only_text",arguments:[t]}),d,c,h);return{uuid:e.uuid,actions:[l],router:u,exits:p}},localizable:"categories",nonTranslatableCategories:["Failure"],toLocalizationFormData:Mp,fromLocalizationFormData:zp},lm={type:"wait_for_audio",name:"Make Recording",group:Hu.wait,flowTypes:[Bu],form:{result_name:{type:"text",label:"Result Name",required:!1,maxLength:64,placeholder:"(optional)",helpText:"The name to use to reference this result in the flow"}},layout:["result_name"],toFormData:t=>{var e;return{uuid:t.uuid,result_name:(null===(e=t.router)||void 0===e?void 0:e.result_name)||""}},fromFormData:(t,e)=>{var i;const o=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],n=e.exits||[];let s,r=o.find(t=>"All Responses"===t.name);if(r)s=n.find(t=>t.uuid===r.exit_uuid)||{uuid:r.exit_uuid,destination_uuid:null};else{const t=Xt();r={uuid:Xt(),name:"All Responses",exit_uuid:t},s={uuid:t,destination_uuid:null}}const a={type:"switch",operand:"@input",default_category_uuid:r.uuid,cases:[],categories:[r],wait:{type:"msg",hint:{type:"audio"}}};return t.result_name&&""!==t.result_name.trim()&&(a.result_name=t.result_name.trim()),{...e,router:a,exits:[s]}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},dm=["Answered","No Answer","Busy","Failed"],cm=[{type:"has_only_text",arguments:["answered"],categoryName:"Answered"},{type:"has_only_text",arguments:["no_answer"],categoryName:"No Answer"},{type:"has_only_text",arguments:["busy"],categoryName:"Busy"}],hm={type:"wait_for_dial",name:"Redirect Call",group:Hu.wait,flowTypes:[Bu],router:{type:"switch",defaultCategory:"Failed",rules:cm.map(t=>({type:t.type,arguments:t.arguments,categoryName:t.categoryName}))},form:{phone:{type:"text",label:"Phone Number",required:!0,evaluated:!0,placeholder:"Phone number or expression"},dial_limit_seconds:{type:"text",label:"Dial Limit (seconds)",required:!1,placeholder:"60"},call_limit_seconds:{type:"text",label:"Call Limit (seconds)",required:!1,placeholder:"7200"},result_name:Sp},layout:["phone",{type:"row",items:["dial_limit_seconds","call_limit_seconds"]},"result_name"],toFormData:t=>{var e,i;const o=null===(e=t.router)||void 0===e?void 0:e.wait;return{uuid:t.uuid,phone:(null==o?void 0:o.phone)||"",dial_limit_seconds:(null==o?void 0:o.dial_limit_seconds)?String(o.dial_limit_seconds):"",call_limit_seconds:(null==o?void 0:o.call_limit_seconds)?String(o.call_limit_seconds):"",result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o;const n=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],s=e.exits||[],r=(null===(o=e.router)||void 0===o?void 0:o.cases)||[],a=[],l=[],d=[];for(const t of dm){const e=n.find(e=>e.name===t);if(e){a.push(e);const t=s.find(t=>t.uuid===e.exit_uuid);l.push(t||{uuid:e.exit_uuid,destination_uuid:null})}else{const e=Xt();a.push({uuid:Xt(),name:t,exit_uuid:e}),l.push({uuid:e,destination_uuid:null})}}for(const t of cm){const e=a.find(e=>e.name===t.categoryName);if(!e)continue;const i=r.find(e=>{var i;return e.type===t.type&&(null===(i=e.arguments)||void 0===i?void 0:i[0])===t.arguments[0]});d.push({uuid:(null==i?void 0:i.uuid)||Xt(),type:t.type,arguments:t.arguments,category_uuid:e.uuid})}const c=a.find(t=>"Failed"===t.name),h=(t.phone||"").trim(),u=parseInt(t.dial_limit_seconds,10),p=parseInt(t.call_limit_seconds,10),m={type:"dial",phone:h};!isNaN(u)&&u>0&&(m.dial_limit_seconds=u),!isNaN(p)&&p>0&&(m.call_limit_seconds=p);const g={type:"switch",operand:'@(default(resume.dial.status, ""))',default_category_uuid:null==c?void 0:c.uuid,cases:d,categories:a,wait:m};return t.result_name&&""!==t.result_name.trim()&&(g.result_name=t.result_name.trim()),{...e,router:g,exits:l}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},um={type:"wait_for_digits",name:"Wait for Digits",group:Hu.wait,flowTypes:[Bu],dialogSize:"large",form:{rules:jp(Cp(xp.filter(t=>_p.has(t.type))),""),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:[{type:"text",text:"Rules match against all digits pressed by the caller followed by the # sign."},"rules",Tp],validate:t=>({valid:!0,errors:{}}),toFormData:(t,e)=>{var i,o,n;const s=Up(t);return{uuid:t.uuid,rules:s,result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||"",localizeRules:(null===(o=null==e?void 0:e.config)||void 0===o?void 0:o.localizeRules)||!1,localizeCategories:(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.localizeCategories)||!1}},toUIConfig:t=>{const e={};return e.localizeRules=!!t.localizeRules,e.localizeCategories=!!t.result_name&&!!t.localizeCategories,e},fromFormData:(t,e)=>{var i,o;const n=qp(t),s=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],r=e.exits||[],a=(null===(o=e.router)||void 0===o?void 0:o.cases)||[],{router:l,exits:d}=Oe("@input.text",n,kp,s,r,a),c={...l,wait:{type:"msg",hint:{type:"digits"}}};return t.result_name&&""!==t.result_name.trim()&&(c.result_name=t.result_name.trim()),{...e,router:c,exits:d}},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},pm=["1","2","3","4","5","6","7","8","9","0"];function mm(t){return`digit_${t}`}const gm={type:"wait_for_menu",name:"Wait for Menu",group:Hu.wait,flowTypes:[Bu],form:{...Object.fromEntries(pm.map(t=>[mm(t),{type:"text",required:!1,placeholder:"",flavor:"xsmall"}])),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:[{type:"row",items:["digit_1","digit_2","digit_3"],gap:"2rem",marginBottom:"0.5rem",inlineLabels:{digit_1:"1",digit_2:"2",digit_3:"3"}},{type:"row",items:["digit_4","digit_5","digit_6"],gap:"2rem",marginBottom:"0.5rem",inlineLabels:{digit_4:"4",digit_5:"5",digit_6:"6"}},{type:"row",items:["digit_7","digit_8","digit_9"],gap:"2rem",marginBottom:"0.5rem",inlineLabels:{digit_7:"7",digit_8:"8",digit_9:"9"}},{type:"row",items:[{type:"spacer"},"digit_0",{type:"spacer"}],gap:"2rem",inlineLabels:{digit_0:"0"}},Tp],toFormData:(t,e)=>{var i,o,n,s,r,a;const l={uuid:t.uuid,result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""};for(const t of pm)l[mm(t)]="";if((null===(o=t.router)||void 0===o?void 0:o.cases)&&(null===(n=t.router)||void 0===n?void 0:n.categories))for(const e of t.router.cases)if("has_number_eq"===e.type&&(null===(s=e.arguments)||void 0===s?void 0:s[0])){const i=e.arguments[0],o=t.router.categories.find(t=>t.uuid===e.category_uuid);o&&pm.includes(i)&&(l[mm(i)]=o.name)}return l.localizeRules=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.localizeRules)||!1,l.localizeCategories=(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.localizeCategories)||!1,l},toUIConfig:t=>{const e={};return e.localizeRules=!!t.localizeRules,e.localizeCategories=!!t.result_name&&!!t.localizeCategories,e},fromFormData:(t,e)=>{var i,o;const n=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],s=e.exits||[],r=(null===(o=e.router)||void 0===o?void 0:o.cases)||[],a=[],l=[],d=[];for(const e of pm){const i=(t[mm(e)]||"").trim();if(!i)continue;let o=a.find(t=>t.name===i);if(!o){const t=n.find(t=>t.name===i);if(t){o=t;const e=s.find(e=>e.uuid===t.exit_uuid);a.push(o),l.push(e||{uuid:t.exit_uuid,destination_uuid:null})}else{const t=Xt();o={uuid:Xt(),name:i,exit_uuid:t},a.push(o),l.push({uuid:t,destination_uuid:null})}}const c=r.find(t=>{var i;return"has_number_eq"===t.type&&(null===(i=t.arguments)||void 0===i?void 0:i[0])===e});d.push({uuid:(null==c?void 0:c.uuid)||Xt(),type:"has_number_eq",arguments:[e],category_uuid:o.uuid})}const c=n.find(t=>"Other"===t.name);let h;if(c){h=c;const t=s.find(t=>t.uuid===c.exit_uuid);l.push(t||{uuid:c.exit_uuid,destination_uuid:null})}else{const t=Xt();h={uuid:Xt(),name:"Other",exit_uuid:t},l.push({uuid:t,destination_uuid:null})}a.push(h);const u={type:"switch",operand:"@input.text",default_category_uuid:h.uuid,cases:d,categories:a,wait:{type:"msg",hint:{type:"digits",count:1}}};return t.result_name&&""!==t.result_name.trim()&&(u.result_name=t.result_name.trim()),{...e,router:u,exits:l}},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},fm=[{value:"60",name:"1 minute"},{value:"120",name:"2 minutes"},{value:"180",name:"3 minutes"},{value:"240",name:"4 minutes"},{value:"300",name:"5 minutes"},{value:"600",name:"10 minutes"},{value:"900",name:"15 minutes"},{value:"1800",name:"30 minutes"},{value:"3600",name:"1 hour"},{value:"7200",name:"2 hours"},{value:"10800",name:"3 hours"},{value:"21600",name:"6 hours"},{value:"43200",name:"12 hours"},{value:"64800",name:"18 hours"},{value:"86400",name:"1 day"},{value:"172800",name:"2 days"},{value:"259200",name:"3 days"},{value:"604800",name:"1 week"}],vm=(t,e=[],i=[],o=[])=>{const{router:n,exits:s}=Oe("@input.text",t,kp,e,i,o),r=e.find(t=>"No Response"===t.name||"Timeout"===t.name);if(r){const t=i.find(t=>t.uuid===r.exit_uuid);t&&(n.categories.push(r),s.push({uuid:t.uuid,destination_uuid:t.destination_uuid||null}))}return{router:n,exits:s}},bm={type:"wait_for_response",name:"Wait for Response",group:Hu.wait,flowTypes:[Nu],hideFromSplits:!0,dialogSize:"large",form:{rules:jp(Cp(wp()),"If the message from the contact..."),timeout_enabled:{type:"checkbox",label:t=>t.timeout_enabled?"Continue when there is no response for":"Continue when there is no response..",labelPadding:"4px 8px"},timeout_duration:{type:"select",placeholder:"5 minutes",multi:!1,maxWidth:"130px",flavor:"xsmall",options:fm,conditions:{visible:t=>!0===t.timeout_enabled}},result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:["rules",Tp],gutter:[{type:"row",items:["timeout_enabled","timeout_duration"],gap:"0.5rem"}],validate:t=>{const e={};return{valid:0===Object.keys(e).length,errors:e}},toFormData:(t,e)=>{var i,o,n,s,r,a;const l=Up(t),d=null===(n=null===(o=null===(i=t.router)||void 0===i?void 0:i.wait)||void 0===o?void 0:o.timeout)||void 0===n?void 0:n.seconds;let c=fm.find(t=>t.value===String(d));return c||(c={value:"300",name:"5 minutes"}),{uuid:t.uuid,rules:l,timeout_enabled:!!d,timeout_duration:c,result_name:(null===(s=t.router)||void 0===s?void 0:s.result_name)||"",localizeRules:(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.localizeRules)||!1,localizeCategories:(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.localizeCategories)||!1}},toUIConfig:t=>{const e={};return e.localizeRules=!!t.localizeRules,e.localizeCategories=!!t.result_name&&!!t.localizeCategories,e},fromFormData:(t,e)=>{var i,o,n,s,r,a,l,d;const c=qp(t);if(0===c.length){let o=(null===(i=e.router)||void 0===i?void 0:i.categories)||[];const n=[...e.exits||[]];if(t.timeout_enabled){let t=o.find(t=>"No Response"===t.name);if(!t){const e=Xt();t={uuid:Xt(),name:"No Response",exit_uuid:e},o=[...o,t],n.find(t=>t.uuid===e)||n.push({uuid:e,destination_uuid:null})}}else o=o.filter(t=>"No Response"!==t.name);const{router:s,exits:r}=vm([],o,n,[]),a={...s,cases:[]};t.result_name&&""!==t.result_name.trim()&&(a.result_name=t.result_name.trim());const l={type:"msg"};if(t.timeout_enabled){let e;e=t.timeout_duration?Array.isArray(t.timeout_duration)&&t.timeout_duration.length>0?parseInt(t.timeout_duration[0].value,10):"string"==typeof t.timeout_duration?parseInt(t.timeout_duration,10):t.timeout_duration&&"object"==typeof t.timeout_duration&&t.timeout_duration.value?parseInt(t.timeout_duration.value,10):300:300,(isNaN(e)||e<=0)&&(e=300);const i=a.categories.find(t=>"No Response"===t.name);i&&(l.timeout={seconds:e,category_uuid:i.uuid})}return a.wait=l,{...e,router:a,exits:r}}const h=(null===(o=e.router)||void 0===o?void 0:o.categories)||[],u=e.exits||[],p=(null===(n=e.router)||void 0===n?void 0:n.cases)||[],{router:m,exits:g}=vm(c,h,u,p),f={...m};t.result_name&&""!==t.result_name.trim()&&(f.result_name=t.result_name.trim());const v={type:"msg"};try{if(t.timeout_enabled){let i;if(t.timeout_duration)try{i=parseInt(t.timeout_duration[0].value,10)}catch(t){i=300}const o=null===(r=null===(s=e.router)||void 0===s?void 0:s.categories)||void 0===r?void 0:r.find(t=>"No Response"===t.name),n=o||{uuid:Xt(),name:"No Response",exit_uuid:Xt()};if(v.timeout={seconds:i,category_uuid:n.uuid},!(null===(a=m.categories)||void 0===a?void 0:a.some(t=>"No Response"===t.name))&&(m.categories=m.categories||[],m.categories.push(n),!g.some(t=>t.uuid===n.exit_uuid))){const t={uuid:n.exit_uuid,destination_uuid:(null==o?void 0:o.exit_uuid)&&(null===(d=null===(l=e.exits)||void 0===l?void 0:l.find(t=>t.uuid===o.exit_uuid))||void 0===d?void 0:d.destination_uuid)||null};g.push(t)}}else if(m.categories){const t=m.categories.findIndex(t=>"No Response"===t.name);if(-1!==t){const e=m.categories[t];m.categories.splice(t,1);const i=g.findIndex(t=>t.uuid===e.exit_uuid);-1!==i&&g.splice(i,1)}}}catch(t){console.error("Error processing timeout configuration:",t)}return f.wait=v,{...e,router:f,exits:g}},localizable:"categories",nonTranslatableCategories:["Timeout"],toLocalizationFormData:Mp,fromLocalizationFormData:zp},ym=xm({say_msg:mp,play_audio:gp,set_contact_field:Ku,send_broadcast:Ju,set_run_result:tp,send_msg:ip,send_email:op,start_session:np,set_contact_name:sp,add_contact_groups:rp,remove_contact_groups:ap,set_contact_channel:Gu,set_contact_language:Xu,set_contact_status:Qu,add_contact_urn:Yu,add_input_labels:Zu,request_optin:lp,enter_flow:vp});function xm(t){const e={...t};return Object.values(t).forEach(t=>{t.aliases&&t.aliases.forEach(i=>{e[i]=t})}),e}const wm=xm({execute_actions:{type:"execute_actions"},split_by_contact_field:Wp,split_by_expression:Vp,split_by_groups:Zp,split_by_llm:rm,split_by_llm_categorize:am,split_by_random:Yp,split_by_run_result:Xp,split_by_scheme:Qp,split_by_subflow:Jp,split_by_ticket:tm,split_by_webhook:nm,split_by_resthook:sm,wait_for_menu:gm,wait_for_digits:um,wait_for_audio:lm,wait_for_dial:hm,wait_for_response:bm,split_by_airtime:Ip,terminal:{type:"terminal"}}),_m=new Set(["Other","No Response"]);function km(t,e){if(!t||!(null==e?void 0:e.length))return[];const i=wm[t],o=null==i?void 0:i.nonTranslatableCategories;if(!o)return[...e];if("all"===o)return e.filter(t=>_m.has(t.name));const n=new Set(o);return e.filter(t=>!n.has(t.name)||_m.has(t.name))}const Cm="__primary_language__";class Sm extends Be{constructor(){super(...arguments),this.messageView=!1,this.zoom=1,this.zoomInitialized=!1,this.zoomFitted=!1,this.revisionsActive=!1,this.isSaving=!1,this.searchDisabled=!1,this.languageOptions=[],this.currentLanguageName="",this.isBaseLanguage=!0,this.languagePercent=0,this.showLocalizationTools=!1,this.showLanguageOptions=!1}static get styles(){return a`
8949
+ :host {
8950
+ display: block;
8957
8951
  }
8958
8952
 
8959
- .shift-held > temba-flow-node,
8960
- .shift-held > temba-flow-node * {
8961
- cursor: copy !important;
8953
+ .editor-toolbar {
8954
+ --toolbar-control-height: 28px;
8955
+ --toolbar-translation-control-height: 28px;
8956
+ display: flex;
8957
+ align-items: center;
8958
+ padding: 6px 12px;
8959
+ background: #fff;
8960
+ border-bottom: 1px solid #e8e8e8;
8961
+ flex-shrink: 0;
8962
+ gap: 8px;
8962
8963
  }
8963
8964
 
8964
- .shift-held > temba-flow-node .exit,
8965
- .shift-held > temba-flow-node .exit *,
8966
- .shift-held > temba-flow-node .linked-name,
8967
- .shift-held > temba-flow-node .linked-name *,
8968
- .shift-held > temba-flow-node .remove-button,
8969
- .shift-held > temba-flow-node .remove-button * {
8970
- cursor: pointer !important;
8965
+ .toolbar-left {
8966
+ display: flex;
8967
+ align-items: center;
8968
+ gap: 2px;
8971
8969
  }
8972
8970
 
8973
- temba-flow-node.drag-copy .node {
8974
- outline: 3px dashed var(--color-primary, #3b82f6);
8975
- outline-offset: 2px;
8976
- opacity: 0.7;
8971
+ .toolbar-right {
8972
+ display: flex;
8973
+ align-items: center;
8974
+ gap: 2px;
8975
+ margin-left: auto;
8977
8976
  }
8978
8977
 
8979
- /* Flow start indicator */
8980
- temba-flow-node.flow-start .node::before {
8981
- content: 'FLOW START';
8982
- position: absolute;
8983
- top: -16px;
8984
- left: 50%;
8985
- transform: translateX(-50%);
8986
- font-size: 10px;
8987
- font-weight: 600;
8988
- letter-spacing: 0.5px;
8989
- color: var(--color-primary-dark, #3b82f6);
8990
- opacity: 0.7;
8991
- z-index: 10;
8992
- white-space: nowrap;
8978
+ .toolbar-btn {
8979
+ width: var(--toolbar-control-height);
8980
+ height: var(--toolbar-control-height);
8981
+ border: none;
8982
+ background: transparent;
8983
+ border-radius: var(--curvature);
8984
+ cursor: pointer;
8985
+ display: flex;
8986
+ align-items: center;
8987
+ justify-content: center;
8988
+ padding: 0;
8989
+ color: #888;
8990
+ font-size: 16px;
8991
+ line-height: 1;
8992
+ outline: none;
8993
8993
  }
8994
8994
 
8995
- /* Cap width for execute_actions nodes */
8996
- .node.execute-actions {
8997
- max-width: 200px;
8995
+ .toolbar-btn:focus {
8996
+ outline: none;
8998
8997
  }
8999
8998
 
9000
- .node .action:last-child {
9001
- border-bottom-left-radius: var(--curvature);
9002
- border-bottom-right-radius: var(--curvature);
8999
+ .toolbar-btn:focus-visible {
9000
+ outline: 2px solid #0064c8;
9001
+ outline-offset: 2px;
9003
9002
  }
9004
9003
 
9005
- .node .action:first-child {
9006
- border-top-left-radius: var(--curvature);
9007
- border-top-right-radius: var(--curvature);
9004
+ .toolbar-btn:hover {
9005
+ background: rgba(0, 0, 0, 0.06);
9006
+ color: #555;
9008
9007
  }
9009
9008
 
9010
- .node.dragging {
9011
- box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);
9012
- transform: scale(1.02);
9013
- z-index: 1000;
9009
+ .toolbar-btn:disabled {
9010
+ opacity: 0.3;
9011
+ cursor: default;
9012
+ background: transparent;
9014
9013
  }
9015
9014
 
9016
- .action {
9017
- position: relative;
9015
+ .toolbar-btn.active {
9016
+ background: rgba(0, 100, 200, 0.1);
9017
+ color: #0064c8;
9018
9018
  }
9019
9019
 
9020
-
9021
- .action .cn-title:hover .remove-button,
9022
- .router:hover .remove-button {
9023
- visibility: visible;
9024
- opacity: 0.7;
9020
+ .toolbar-btn.active:hover {
9021
+ background: rgba(0, 100, 200, 0.15);
9025
9022
  }
9026
9023
 
9027
- .action.removing .cn-title,
9028
- .router .cn-title.removing {
9029
- background-color: var(--color-error, #dc3545) !important;
9024
+ .toolbar-tip {
9025
+ display: flex;
9026
+ align-items: center;
9030
9027
  }
9031
9028
 
9032
- .action.removing .cn-title .name,
9033
- .router .cn-title.removing .name {
9034
- color: white;
9029
+ .toolbar-divider {
9030
+ width: 1px;
9031
+ height: 16px;
9032
+ background: #e0e0e0;
9033
+ margin: 0 4px;
9035
9034
  }
9036
9035
 
9037
- .remove-button {
9038
- background: transparent;
9039
- color: white;
9040
- visibility: hidden;
9041
- cursor: pointer;
9042
- font-size: 1em;
9043
- font-weight: 600;
9044
- line-height: 1;
9045
- z-index: 10;
9046
- transition: all 100ms ease-in-out;
9047
- align-self: center;
9048
- margin-right: 0.3em;
9049
- border: 0px solid red;
9050
- width: 1em;
9051
- pointer-events: auto; /* Ensure remove button can receive events */
9036
+ .toolbar-group {
9037
+ display: flex;
9038
+ align-items: center;
9039
+ gap: 4px;
9040
+ height: var(--toolbar-control-height);
9041
+ box-sizing: border-box;
9042
+ padding: 0 3px;
9043
+ border: 1px solid #d7dce2;
9044
+ border-radius: calc(var(--curvature) + 2px);
9045
+ background: #f7f9fb;
9052
9046
  }
9053
9047
 
9054
- .remove-button:hover {
9055
- visibility: visible;
9056
- opacity: 1;
9048
+ .toolbar-group-divider {
9049
+ width: 1px;
9050
+ height: 18px;
9051
+ background: #d7dce2;
9052
+ margin: 0 2px;
9057
9053
  }
9058
9054
 
9059
- .read-only-hidden {
9060
- visibility: hidden !important;
9061
- pointer-events: none !important;
9055
+ .toolbar-language {
9056
+ position: relative;
9057
+ display: flex;
9058
+ align-items: center;
9062
9059
  }
9063
9060
 
9064
- /* Issue indicators - hatched red title bar */
9065
- .action-content.has-issues .cn-title,
9066
- .node.has-issues > .router .cn-title {
9067
- background: repeating-linear-gradient(120deg, tomato, tomato 6px, #ff7056 0, #ff7056 18px) !important;
9061
+ .toolbar-language-group {
9062
+ display: flex;
9063
+ align-items: center;
9064
+ gap: 6px;
9065
+ margin-left: 2px;
9068
9066
  }
9069
9067
 
9070
- /* Disable links on actions/nodes with issues */
9071
- .action-content.has-issues .linked-name div,
9072
- .node.has-issues > .router .linked-name div {
9073
- text-decoration: none !important;
9074
- cursor: default !important;
9075
- pointer-events: none;
9068
+ .toolbar-zoom-group {
9069
+ gap: 2px;
9076
9070
  }
9077
9071
 
9078
- .action.sortable {
9072
+ .language-pill {
9079
9073
  display: flex;
9080
- align-items: stretch;
9074
+ align-items: center;
9075
+ gap: 6px;
9076
+ background: #e9eef4;
9077
+ color: #0064c8;
9078
+ height: var(--toolbar-translation-control-height);
9079
+ padding: 0 8px;
9080
+ border-radius: var(--curvature);
9081
+ box-sizing: border-box;
9082
+ font-size: 13px;
9083
+ font-weight: 400;
9084
+ white-space: nowrap;
9085
+ cursor: pointer;
9086
+ --icon-color: #0064c8;
9087
+ --icon-size: 16px;
9088
+ border: none;
9089
+ outline: none;
9081
9090
  }
9082
9091
 
9083
- .action .action-content {
9084
- flex-grow: 1;
9085
- display: flex;
9086
- flex-direction: column;
9087
- min-width: 0; /* Allow flex item to shrink below its content size */
9088
- overflow: hidden;
9092
+ .language-pill:hover {
9093
+ filter: brightness(1.04);
9094
+ }
9095
+
9096
+ .language-pill.primary {
9089
9097
  background: #fff;
9098
+ border: 1px solid #d7dce2;
9090
9099
  }
9091
9100
 
9092
- .action .body {
9093
- padding: 0.75em;
9094
- word-wrap: break-word;
9095
- overflow-wrap: break-word;
9096
- hyphens: auto;
9097
- white-space: normal;
9098
- overflow: hidden;
9101
+ .language-pill.complete {
9102
+ background: #d4f5e0;
9103
+ color: #1a7f37;
9104
+ --icon-color: #1a7f37;
9099
9105
  }
9100
9106
 
9101
- .node.execute-actions temba-sortable-list .action:last-child .body {
9102
- padding-bottom: 1.5em;
9107
+ .language-pill-caret {
9108
+ margin-left: 1px;
9109
+ --icon-color: currentColor;
9110
+ --icon-size: 12px;
9103
9111
  }
9104
9112
 
9105
- /* Localization indicators */
9106
- .action.localizable:not(.has-localization) .action-content {
9107
- background: #fff8dc !important; /* Light yellow background for localizable but not yet localized */
9113
+ .language-percent {
9114
+ display: inline-block;
9115
+ font-size: 12px;
9116
+ font-weight: 700;
9117
+ line-height: 1;
9118
+ color: #0064c8;
9119
+ white-space: nowrap;
9108
9120
  }
9109
9121
 
9110
- .non-localizable {
9111
- opacity: 0.25;
9112
- pointer-events: none;
9122
+ .language-pill.complete .language-percent {
9123
+ color: #1a7f37;
9113
9124
  }
9114
9125
 
9115
- .action.non-localizable .action-content {
9116
- cursor: not-allowed;
9117
- }
9126
+ .toolbar-zoom-level {
9127
+ font-size: 12px;
9128
+ min-width: 40px;
9129
+ text-align: center;
9130
+ color: #555;
9131
+ font-weight: 500;
9132
+ }
9118
9133
 
9119
- .action .drag-handle {
9120
- visibility: hidden;
9121
- transition: all 200ms ease-in-out;
9122
- cursor: move;
9123
- background: rgba(0, 0, 0, 0.02);
9124
- width: 1em;
9125
- padding: 0.25em;
9126
- border: 0px solid red;
9127
- pointer-events: auto; /* Ensure drag handle can receive events */
9128
- }
9129
- .title-spacer {
9130
- width: 1.8em;
9134
+ .toolbar-translation {
9135
+ display: flex;
9136
+ align-items: center;
9137
+ gap: 4px;
9131
9138
  }
9132
9139
 
9133
- .action:hover .drag-handle {
9134
- visibility: visible;
9135
- opacity: 0.7;
9140
+ .toolbar-btn.language-tool {
9141
+ width: var(--toolbar-translation-control-height);
9142
+ height: var(--toolbar-translation-control-height);
9136
9143
  }
9144
+ `}fireToolbarAction(t,e={}){this.fireCustomEvent(Io.ButtonClicked,{action:t,...e})}handleLanguageIconClick(){this.showLanguageOptions?this.showLanguageOptions=!1:(this.showLanguageOptions=!0,requestAnimationFrame(()=>{const t=()=>{this.showLanguageOptions=!1,document.removeEventListener("click",t)};document.addEventListener("click",t,{once:!0})}))}handleLanguageOptionSelected(t){var e;if(!this.showLanguageOptions)return;const i=null===(e=t.detail)||void 0===e?void 0:e.selected;(null==i?void 0:i.value)===Cm?this.fireToolbarAction("language-change",{isPrimary:!0}):(null==i?void 0:i.value)&&this.fireToolbarAction("language-change",{languageCode:i.value}),this.showLanguageOptions=!1}isMacPlatform(){return"undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)}getSearchShortcutLabel(){return this.isMacPlatform()?"⌘F":"Ctrl+F"}renderTip(t,e){return W`
9145
+ <temba-tip
9146
+ class="toolbar-tip"
9147
+ .text=${"string"==typeof t?t:""}
9148
+ .content=${"string"==typeof t?null:t}
9149
+ position="top"
9150
+ >
9151
+ ${e}
9152
+ </temba-tip>
9153
+ `}renderShortcutLabel(t,e){return W`<span style="display:inline-flex; align-items:center; gap:8px;">
9154
+ <span>${t}</span>
9155
+ <kbd>${e}</kbd>
9156
+ </span>`}renderLanguageOption(t,e){var i;if(t.value===Cm){return W`
9157
+ <div
9158
+ style="display:flex; align-items:center; justify-content:space-between; gap:8px; background:${e?"#e1e8ef":"#edf1f5"}; color:#2f3f52; border-radius:4px; padding:6px 10px;"
9159
+ >
9160
+ <span>${t.name}</span>
9161
+ <span
9162
+ style="display:inline-flex; align-items:center; border-radius:999px; background:rgba(47, 63, 82, 0.12); color:#2f3f52; font-size:10px; font-weight:700; line-height:1; padding:3px 7px;"
9163
+ >Original</span
9164
+ >
9165
+ </div>
9166
+ `}const o=100===t.percent,n=o?"#d4f5e0":"",s=o?"#c0edce":"",r=o?"color:#1a7f37;":"color:#5f6b7a;";return W`
9167
+ <div
9168
+ style="display:flex; align-items:center; justify-content:space-between; gap:8px; padding:6px 10px; ${n?`background:${n};`:""} ${o?"border-radius:4px;":""}"
9169
+ @mouseenter=${o?t=>{t.currentTarget.style.background=s}:null}
9170
+ @mouseleave=${o?t=>{t.currentTarget.style.background=n}:null}
9171
+ >
9172
+ <span style="${o?"color:#1a7f37;":""}"
9173
+ >${t.name}</span
9174
+ >
9175
+ <span style="font-size:11px; font-weight:600; ${r}"
9176
+ >${null!==(i=t.percent)&&void 0!==i?i:0}%</span
9177
+ >
9178
+ </div>
9179
+ `}render(){var t;const e=this.languageOptions.length>1,i=this.messageView?"Search table":"Search flow";return W`
9180
+ <div class="editor-toolbar">
9181
+ <div class="toolbar-left">
9182
+ ${this.renderTip("Flow View",W`
9183
+ <button
9184
+ class="toolbar-btn ${this.messageView?"":"active"}"
9185
+ @click=${()=>this.fireToolbarAction("view-change",{view:"flow"})}
9186
+ aria-label="Flow View"
9187
+ >
9188
+ <temba-icon name="flow" size="1"></temba-icon>
9189
+ </button>
9190
+ `)}
9191
+ ${this.renderTip("Table View",W`
9192
+ <button
9193
+ class="toolbar-btn ${this.messageView?"active":""}"
9194
+ @click=${()=>this.fireToolbarAction("view-change",{view:"table"})}
9195
+ aria-label="Table View"
9196
+ >
9197
+ <temba-icon name=${ko.quick_replies} size="1"></temba-icon>
9198
+ </button>
9199
+ `)}
9200
+ ${e?W`
9201
+ <div class="toolbar-divider"></div>
9202
+ <div class="toolbar-language-group">
9203
+ <div class="toolbar-language">
9204
+ ${this.renderTip("Change language",W`
9205
+ <button
9206
+ class="language-pill ${this.isBaseLanguage?"primary":100===this.languagePercent?"complete":""}"
9207
+ id="language-btn"
9208
+ @click=${this.handleLanguageIconClick}
9209
+ aria-label="Change language"
9210
+ >
9211
+ <temba-icon name=${ko.language}></temba-icon>
9212
+ <span>${this.currentLanguageName}</span>
9213
+ ${this.isBaseLanguage?"":W`<span class="language-percent"
9214
+ >${this.languagePercent}%</span
9215
+ >`}
9216
+ <temba-icon
9217
+ class="language-pill-caret"
9218
+ name=${this.showLanguageOptions?ko.arrow_up:ko.arrow_down}
9219
+ ></temba-icon>
9220
+ </button>
9221
+ `)}
9222
+ <temba-options
9223
+ .anchorTo=${null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("#language-btn")}
9224
+ .options=${this.languageOptions}
9225
+ .renderOption=${this.renderLanguageOption}
9226
+ ?visible=${this.showLanguageOptions}
9227
+ @temba-selection=${this.handleLanguageOptionSelected}
9228
+ style="--temba-options-option-margin:4px; --temba-options-option-padding:0; --temba-options-option-radius:4px;"
9229
+ min-width="230"
9230
+ ></temba-options>
9231
+ </div>
9232
+ ${this.showLocalizationTools?this.renderTranslationTools():""}
9233
+ </div>
9234
+ `:""}
9235
+ </div>
9236
+ <div class="toolbar-right">
9237
+ ${this.messageView?"":W`
9238
+ ${this.renderTip("Zoom to fit",W`
9239
+ <button
9240
+ class="toolbar-btn"
9241
+ @click=${()=>this.fireToolbarAction("zoom-to-fit")}
9242
+ ?disabled=${!this.zoomInitialized||this.zoomFitted}
9243
+ aria-label="Zoom to fit"
9244
+ >
9245
+ <temba-icon
9246
+ name=${ko.zoom_fit}
9247
+ size="1"
9248
+ ></temba-icon>
9249
+ </button>
9250
+ `)}
9251
+ <div class="toolbar-divider"></div>
9252
+ ${this.renderTip("Zoom out",W`
9253
+ <button
9254
+ class="toolbar-btn"
9255
+ @click=${()=>this.fireToolbarAction("zoom-out")}
9256
+ ?disabled=${!this.zoomInitialized||this.zoom<=.3}
9257
+ aria-label="Zoom out"
9258
+ >
9259
+
9260
+ </button>
9261
+ `)}
9262
+ <span class="toolbar-zoom-level"
9263
+ >${this.zoomInitialized?`${Math.round(100*this.zoom)}%`:""}</span
9264
+ >
9265
+ ${this.renderTip("Zoom in",W`
9266
+ <button
9267
+ class="toolbar-btn"
9268
+ @click=${()=>this.fireToolbarAction("zoom-in")}
9269
+ ?disabled=${!this.zoomInitialized||this.zoom>=1}
9270
+ aria-label="Zoom in"
9271
+ >
9272
+ +
9273
+ </button>
9274
+ `)}
9275
+ <div class="toolbar-divider"></div>
9276
+ ${this.renderTip("Zoom to 100%",W`
9277
+ <button
9278
+ class="toolbar-btn"
9279
+ @click=${()=>this.fireToolbarAction("zoom-to-full")}
9280
+ ?disabled=${!this.zoomInitialized||this.zoom>=1}
9281
+ aria-label="Zoom to 100%"
9282
+ >
9283
+ <temba-icon
9284
+ name=${ko.zoom_in}
9285
+ size="1"
9286
+ ></temba-icon>
9287
+ </button>
9288
+ `)}
9289
+ <div class="toolbar-divider"></div>
9290
+ `}
9291
+ ${this.renderTip("Revisions",W`
9292
+ <button
9293
+ class="toolbar-btn ${this.revisionsActive?"active":""}"
9294
+ @click=${()=>this.fireToolbarAction("revisions")}
9295
+ aria-label="Revisions"
9296
+ >
9297
+ <temba-icon
9298
+ name=${this.isSaving?"progress_spinner":"revisions"}
9299
+ size="1"
9300
+ ?spin=${this.isSaving}
9301
+ ></temba-icon>
9302
+ </button>
9303
+ `)}
9304
+ <div class="toolbar-divider"></div>
9305
+ ${this.renderTip(this.renderShortcutLabel(i,this.getSearchShortcutLabel()),W`
9306
+ <button
9307
+ class="toolbar-btn"
9308
+ @click=${()=>this.fireToolbarAction("search")}
9309
+ ?disabled=${this.searchDisabled}
9310
+ aria-label=${i}
9311
+ >
9312
+ <temba-icon name=${ko.search} size="1"></temba-icon>
9313
+ </button>
9314
+ `)}
9315
+ </div>
9316
+ </div>
9317
+ `}renderTranslationTools(){return W``}}t([mt({type:Boolean,attribute:"message-view"})],Sm.prototype,"messageView",void 0),t([mt({type:Number})],Sm.prototype,"zoom",void 0),t([mt({type:Boolean,attribute:"zoom-initialized"})],Sm.prototype,"zoomInitialized",void 0),t([mt({type:Boolean,attribute:"zoom-fitted"})],Sm.prototype,"zoomFitted",void 0),t([mt({type:Boolean,attribute:"revisions-active"})],Sm.prototype,"revisionsActive",void 0),t([mt({type:Boolean,attribute:"is-saving"})],Sm.prototype,"isSaving",void 0),t([mt({type:Boolean,attribute:"search-disabled"})],Sm.prototype,"searchDisabled",void 0),t([mt({type:Array})],Sm.prototype,"languageOptions",void 0),t([mt({type:String,attribute:"current-language-name"})],Sm.prototype,"currentLanguageName",void 0),t([mt({type:Boolean,attribute:"is-base-language"})],Sm.prototype,"isBaseLanguage",void 0),t([mt({type:Number,attribute:"language-percent"})],Sm.prototype,"languagePercent",void 0),t([mt({type:Boolean,attribute:"show-localization-tools"})],Sm.prototype,"showLocalizationTools",void 0),t([gt()],Sm.prototype,"showLanguageOptions",void 0);const Am=60,Em=20;function $m(t,e,i,o){if(0===t.length)return{};const n=new Set(t.map(t=>t.uuid)),s=new Map,r=new Map;for(const e of t){const t=new Set,i=[];for(const o of e.exits)if(o.destination_uuid&&n.has(o.destination_uuid)&&!t.has(o.destination_uuid)){t.add(o.destination_uuid),i.push(o.destination_uuid);const n=r.get(o.destination_uuid)||[];n.push(e.uuid),r.set(o.destination_uuid,n)}s.set(e.uuid,i)}const a=function(t,e){const i=new Set,o=new Set,n=new Set;function s(t){o.add(t),n.add(t);for(const r of e.get(t)||[])o.has(r)?i.add(`${t}->${r}`):n.has(r)||s(r);o.delete(t)}return s(t),i}(i,s),l=function(t,e,i,o,n){const s=new Map;s.set(t,0);const r=new Map;for(const t of e)r.set(t.uuid,0);for(const[t,e]of i)for(const i of e)n.has(`${t}->${i}`)||r.set(i,(r.get(i)||0)+1);const a=[];for(const[t,e]of r)0===e&&(a.push(t),s.has(t)||s.set(t,0));for(;a.length>0;){const t=a.shift(),e=s.get(t);for(const o of i.get(t)||[]){if(n.has(`${t}->${o}`))continue;const i=e+1;(!s.has(o)||i>s.get(o))&&s.set(o,i);const l=r.get(o)-1;r.set(o,l),0===l&&a.push(o)}}const l=e.filter(t=>!s.has(t.uuid));if(l.length>0){let t=Math.max(...Array.from(s.values()),-1)+2;for(const e of l)s.set(e.uuid,t),t++}return s}(i,t,s,0,a),d=new Map;for(const[t,e]of l){const i=d.get(e)||[];i.push(t),d.set(e,i)}const c=Array.from(d.keys()).sort((t,e)=>t-e);!function(t,e,i,o){const n=new Map;for(const s of t){const r=e.get(s);if(s===t[0]){r.forEach((t,e)=>n.set(t,e));continue}const a=r.map(t=>{const e=(i.get(t)||[]).filter(t=>{const e=o.get(t);return void 0!==e&&e<s});if(0===e.length)return{uuid:t,value:1/0};const r=e.reduce((t,e)=>{var i;return t+(null!==(i=n.get(e))&&void 0!==i?i:0)},0);return{uuid:t,value:r/e.length}});a.sort((t,e)=>t.value-e.value);const l=a.map(t=>t.uuid);e.set(s,l),l.forEach((t,e)=>n.set(t,e))}}(c,d,r,l);const h=new Map;for(const e of t)h.set(e.uuid,o(e.uuid));return function(t,e,i,o,n,s){var r,a,l,d;const c={};let h=0;for(const u of t){const p=Tm(e.get(u),i);for(const e of p){const p=bu(h);if(u===t[0]){let t=0;for(const o of e){const e=o===s?p:p+40;c[o]={left:bu(t),top:e},t+=((null===(r=i.get(o))||void 0===r?void 0:r.width)||200)+Am}}else{let t=0;for(const o of e)t+=(null===(a=i.get(o))||void 0===a?void 0:a.width)||200;t+=Am*(e.length-1);const s=[];for(const t of e){const e=(o.get(t)||[]).filter(t=>{const e=n.get(t);return void 0!==e&&e<u});for(const t of e){const e=c[t];if(e){const o=(null===(l=i.get(t))||void 0===l?void 0:l.width)||200;s.push(e.left+o/2)}}}let r;if(s.length>0){const e=(Math.min(...s)+Math.max(...s))/2;r=Math.max(0,e-t/2)}else r=0;let h=r;for(const t of e){const e=(null===(d=i.get(t))||void 0===d?void 0:d.width)||200;c[t]={left:bu(h),top:p},h=bu(h)+e+Am}}const m=Math.max(...e.map(t=>{var e;return(null===(e=i.get(t))||void 0===e?void 0:e.height)||100}));h=p+m+80}}const u=c[s];if(u){const t=u.left,e=u.top;for(const i of Object.keys(c))c[i]={left:bu(Math.max(0,c[i].left-t)),top:bu(Math.max(0,c[i].top-e))}}return c}(c,d,h,r,l,i)}function Tm(t,e){var i;const o=[];let n=[],s=0;for(const r of t){const t=(null===(i=e.get(r))||void 0===i?void 0:i.width)||200,a=n.length>0?Am+t:t;n.length>0&&s+a>1200?(o.push(n),n=[r],s=t):(n.push(r),s+=a)}return n.length>0&&o.push(n),o}function Dm(t,e,i,o,n){for(const s of n)if(t<s.left+s.width+Em&&t+i+Em>s.left&&e<s.top+s.height+Em&&e+o+Em>s.top)return!0;return!1}function Mm(t){if("touches"in t){const e=t.touches[0]||t.changedTouches[0];return{clientX:e.clientX,clientY:e.clientY}}return{clientX:t.clientX,clientY:t.clientY}}function zm(t,e,i,o,n=20,s=10,r=5,a="top",l=0){const d=r;if("top"===a){const r=e+n,a=o-s;let c=`M ${t} ${e}`;if(t===i)c+=` L ${i} ${a}`;else{const o=i>t?1:-1,n=Math.max(e+d,Math.min(r,a-d)),s=Math.max(e+d,Math.min(n+l,a-d-3)),h=Math.min(d,s-e);h>=1?(c+=` L ${t} ${s-h}`,c+=` Q ${t} ${s}, ${t+o*h} ${s}`):c+=` L ${t} ${s}`;const u=3,p=Math.min(d,Math.max(0,a-s-u));p>=1?(c+=` L ${i-o*p} ${s}`,c+=` Q ${i} ${s}, ${i} ${s+p}`):c+=` L ${i} ${s}`,c+=` L ${i} ${a}`}return c+=` L ${i} ${o}`,c}if("left"===a||"right"===a){const r=e+(o<e?0:n),l="left"===a?-1:1,c=i+l*s,h=c>t?1:-1,u=3,p=h===l?r+2*d:Math.max(r+2*d,o);let m=`M ${t} ${e} L ${t} ${r}`;p-r>d&&(m+=` L ${t} ${p-d}`,m+=` Q ${t} ${p}, ${t+h*d} ${p}`);const g=Math.abs(p-o);if(g<1)m+=` L ${c} ${o}`,m+=` L ${i} ${o}`;else{const t=o<p?-1:1,e=Math.min(d,Math.max(0,Math.floor((g-u)/2)),Math.max(0,s-u));e>=1?(m+=` L ${c-h*e} ${p}`,m+=` Q ${c} ${p}, ${c} ${p+t*e}`,m+=` L ${c} ${o-t*e}`,m+=` Q ${c} ${o}, ${c-l*e} ${o}`):(m+=` L ${c} ${p}`,m+=` L ${c} ${o}`),m+=` L ${i} ${o}`}return m}return`M ${t} ${e} L ${i} ${o}`}class Im{constructor(t,e){this.connections=new Map,this.sources=new Map,this.pendingConnections=[],this.connectionWait=null,this.connectionListeners=new Map,this.dragState=null,this.retryCount=0,this.maxRetries=3,this.activityData=null,this.overlays=new Map,this.hoveredActivityKey=null,this.recentContactsPopup=null,this.recentContactsCache={},this.pendingFetches={},this.hideContactsTimeout=null,this.showContactsTimeout=null,this.connectionDragging=!1,this.zoom=1,this.canvas=t,this.editor=e}setContainer(t){this.canvas=t}notifyListeners(t,e){(this.connectionListeners.get(t)||[]).forEach(t=>t(e))}on(t,e){this.connectionListeners.has(t)||this.connectionListeners.set(t,[]),this.connectionListeners.get(t).push(e)}off(t,e){if(!this.connectionListeners.has(t))return;const i=this.connectionListeners.get(t),o=i.indexOf(e);-1!==o&&i.splice(o,1)}makeSource(t){const e=document.getElementById(t);if(!e)return;this.sources.has(t)&&this.sources.get(t)();let i=null;const o=o=>{if("button"in o&&fu(o))return;if(this.connections.has(t))return;const n="touches"in o;n&&o.preventDefault();const{clientX:s,clientY:r}=Mm(o),a=e.closest("temba-flow-node"),l=(null==a?void 0:a.getAttribute("uuid"))||"",d=e=>{const{clientX:i,clientY:o}=Mm(e),n=i-s,a=o-r;Math.sqrt(n*n+a*a)>5&&(h(),this.startDrag(t,l,null,e))},c=()=>{h()},h=()=>{document.removeEventListener("mousemove",d),document.removeEventListener("mouseup",c),document.removeEventListener("touchmove",d),document.removeEventListener("touchend",c),document.removeEventListener("touchcancel",c),i=null};document.addEventListener("mousemove",d),document.addEventListener("mouseup",c),document.addEventListener("touchmove",d,{passive:!1}),document.addEventListener("touchend",c),document.addEventListener("touchcancel",c),i={startX:s,startY:r,onMove:d,onUp:c,isTouch:n}};e.addEventListener("mousedown",o),e.addEventListener("touchstart",o,{passive:!1}),this.sources.set(t,()=>{e.removeEventListener("mousedown",o),e.removeEventListener("touchstart",o),i&&(document.removeEventListener("mousemove",i.onMove),document.removeEventListener("mouseup",i.onUp),document.removeEventListener("touchmove",i.onMove),document.removeEventListener("touchend",i.onUp),document.removeEventListener("touchcancel",i.onUp),i=null)})}makeTarget(t){}connectIds(t,e,i){this.pendingConnections.push({scope:t,fromId:e,toId:i}),this.processPendingConnections()}processPendingConnections(){this.connectionWait&&(cancelAnimationFrame(this.connectionWait),this.connectionWait=null),this.connectionWait=requestAnimationFrame(()=>{const t=[],e=new Set;if(this.pendingConnections.forEach(i=>{const{scope:o,fromId:n,toId:s}=i;this.removeConnectionSVG(n),this.createConnectionSVG(n,o,s)?e.add(s):t.push(i)}),this.pendingConnections=[],e.size>0){const t=new Set;this.connections.forEach(i=>{e.has(i.toId)&&t.add(i.scope)}),this.connections.forEach((i,o)=>{(e.has(i.toId)||t.has(i.scope))&&this.updateConnectionSVG(o)})}t.length>0&&this.retryCount<this.maxRetries?(this.retryCount++,this.pendingConnections=t,this.processPendingConnections()):this.retryCount=0})}toCanvas(t){return t/this.zoom}determineTargetFace(t,e,i,o){return o-e>30?"top":t<i?"left":"right"}getConnectionEndpoints(t,e,i){const o=document.getElementById(t),n=document.getElementById(e);if(!o||!n)return null;const s=this.canvas.getBoundingClientRect(),r=o.getBoundingClientRect(),a=n.getBoundingClientRect();if(0===r.width||0===a.width)return null;const l=this.toCanvas(r.left+r.width/2-s.left),d=this.toCanvas(r.bottom-s.top),c=this.toCanvas(a.left+a.width/2-s.left),h=this.toCanvas(a.top-s.top),u=this.determineTargetFace(l,d,c,h),p=new Map;this.connections.forEach(t=>{if(t.toId===e){const e=document.getElementById(t.fromId);if(e){const i=e.getBoundingClientRect(),o=this.toCanvas(i.left+i.width/2-s.left),n=this.toCanvas(i.bottom-s.top),r=this.determineTargetFace(o,n,c,h);p.has(r)||p.set(r,[]);const a="top"===r?o:n;p.get(r).push({fromId:t.fromId,sortPos:a})}}}),p.has(u)||p.set(u,[]);const m=p.get(u);if(!m.find(e=>e.fromId===t)){const e="top"===u?l:d;m.push({fromId:t,sortPos:e})}m.sort((t,e)=>t.sortPos-e.sortPos);const g=m.findIndex(e=>e.fromId===t),f=m.length,v=this.toCanvas(a.left-s.left),b=h,y=this.toCanvas(a.width),x=this.toCanvas(a.height);let w,_;if("top"===u){w=1===f?v+y/2:v+.2*y+.6*y*(g+.5)/f,_=b}else if("left"===u){w=v;_=1===f?b+x/2:b+.2*x+.6*x*(g+.5)/f}else{w=v+y;_=1===f?b+x/2:b+.2*x+.6*x*(g+.5)/f}let k=0;if("top"===u&&i){const o=8,n=50,r=[];if(this.connections.forEach(t=>{if(t.scope===i&&t.toId!==e){const e=document.getElementById(t.fromId),i=document.getElementById(t.toId);if(e&&i){const o=e.getBoundingClientRect(),n=i.getBoundingClientRect(),a=this.toCanvas(o.left+o.width/2-s.left),l=this.toCanvas(o.bottom-s.top),d=this.toCanvas(n.left+n.width/2-s.left),c=this.toCanvas(n.top-s.top);if("top"===this.determineTargetFace(a,l,d,c)){const e=this.toCanvas(n.left-s.left),i=this.toCanvas(n.width);r.push({fromId:t.fromId,targetX:e+i/2})}}}}),r.length>0){r.push({fromId:t,targetX:w}),r.sort((t,e)=>t.targetX-e.targetX);const e=r.findIndex(e=>e.fromId===t),i=r.length;k=(e-(i-1)/2)*((i-1)*o>n?n/(i-1):o)}}return{sourceX:l,sourceY:d,targetX:w,targetY:_,targetFace:u,jogYOffset:k}}createSVGElement(){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.classList.add("plumb-connector"),t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.pointerEvents="none",t.style.overflow="visible";const e=document.createElementNS("http://www.w3.org/2000/svg","path");e.setAttribute("fill","none"),e.setAttribute("stroke","var(--color-connectors)"),e.setAttribute("stroke-width","3"),e.style.pointerEvents="stroke";const i=document.createElementNS("http://www.w3.org/2000/svg","polygon");i.setAttribute("fill","var(--color-connectors)"),i.classList.add("plumb-arrow"),i.style.pointerEvents="fill",i.style.cursor="pointer";const o=document.createElementNS("http://www.w3.org/2000/svg","circle");o.setAttribute("r","18"),o.setAttribute("fill","transparent"),o.style.pointerEvents="fill",o.style.cursor="pointer",t.appendChild(e),t.appendChild(o),t.appendChild(i);const n=()=>t.classList.add("hover"),s=()=>t.classList.remove("hover");return e.addEventListener("mouseenter",n),e.addEventListener("mouseleave",s),i.addEventListener("mouseenter",n),i.addEventListener("mouseleave",s),o.addEventListener("mouseenter",n),o.addEventListener("mouseleave",s),{svgEl:t,pathEl:e,arrowEl:i,hitAreaEl:o}}updateSVGPath(t,e,i,o,n,s,r="top",a=0,l){const d=6.5,c=13;let h=n,u=s;"top"===r?u=s-c:"left"===r?h=n-c:"right"===r&&(h=n+c);const p=zm(i,o,h,u,30,8,5,r,a);if(t.setAttribute("d",p),"top"===r?e.setAttribute("points",`${n},${s} ${n-d},${s-c} ${n+d},${s-c}`):"left"===r?e.setAttribute("points",`${n},${s} ${n-c},${s-d} ${n-c},${s+d}`):e.setAttribute("points",`${n},${s} ${n+c},${s-d} ${n+c},${s+d}`),l){const t=6.5;let e=n,i=s;"top"===r?i=s-t:e="left"===r?n-t:n+t,l.setAttribute("cx",String(e)),l.setAttribute("cy",String(i))}}createConnectionSVG(t,e,i){const o=this.getConnectionEndpoints(t,i,e);if(!o)return!1;const{svgEl:n,pathEl:s,arrowEl:r,hitAreaEl:a}=this.createSVGElement();this.updateSVGPath(s,r,o.sourceX,o.sourceY,o.targetX,o.targetY,o.targetFace,o.jogYOffset,a),this.canvas.appendChild(n),this.connections.set(t,{scope:e,fromId:t,toId:i,svgEl:n,pathEl:s,arrowEl:r,hitAreaEl:a});const l=o=>{if("button"in o&&fu(o))return;o.stopPropagation(),"touches"in o&&o.preventDefault();const{clientX:n,clientY:s}=Mm(o),r=o=>{const{clientX:l,clientY:d}=Mm(o),c=l-n,h=d-s;Math.sqrt(c*c+h*h)>5&&(document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",a),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",a),document.removeEventListener("touchcancel",a),this.startDrag(t,e,i,o))},a=()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",a),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",a),document.removeEventListener("touchcancel",a)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",a),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",a),document.addEventListener("touchcancel",a)};r.addEventListener("mousedown",l),r.addEventListener("touchstart",l,{passive:!1}),a.addEventListener("mousedown",l),a.addEventListener("touchstart",l,{passive:!1}),s.addEventListener("mousedown",l),s.addEventListener("touchstart",l,{passive:!1});const d=document.getElementById(t);if(d&&d.classList.add("connected"),this.activityData){const e=`${t}:${i}`,o=this.activityData.segments[e];if(o&&o>0){const i=this.createOverlayElement(o,e);this.canvas.appendChild(i),this.overlays.set(t,i),this.updateOverlayPosition(t)}}return!0}updateConnectionSVG(t){const e=this.connections.get(t);if(!e)return;const i=this.getConnectionEndpoints(e.fromId,e.toId,e.scope);i&&(this.updateSVGPath(e.pathEl,e.arrowEl,i.sourceX,i.sourceY,i.targetX,i.targetY,i.targetFace,i.jogYOffset,e.hitAreaEl),this.updateOverlayPosition(t))}removeConnectionSVG(t){const e=this.connections.get(t);if(!e)return;const i=this.overlays.get(t);i&&(i.remove(),this.overlays.delete(t)),e.svgEl.remove(),this.connections.delete(t)}repaintEverything(){this.connections.forEach((t,e)=>{this.updateConnectionSVG(e)})}revalidate(t){const e=[],i=new Set;this.connections.forEach((o,n)=>{(t.includes(o.fromId)||t.includes(o.toId)||t.includes(o.scope))&&(e.push(n),i.add(o.toId))});const o=new Set(e);this.connections.forEach((t,e)=>{i.has(t.toId)&&o.add(e)}),o.forEach(t=>{this.updateConnectionSVG(t)})}forgetNode(t){var e;const i=[];this.connections.forEach((e,o)=>{e.scope!==t&&e.toId!==t||i.push(o)}),i.forEach(t=>this.removeConnectionSVG(t));const o=null===(e=document.getElementById(t))||void 0===e?void 0:e.querySelectorAll(".exit");o&&o.forEach(t=>{const e=t.id;this.sources.has(e)&&(this.sources.get(e)(),this.sources.delete(e))})}removeNodeConnections(t,e){var i;(e||Array.from((null===(i=document.getElementById(t))||void 0===i?void 0:i.querySelectorAll(".exit"))||[]).map(t=>t.id)).forEach(t=>this.removeConnectionSVG(t))}removeExitConnection(t){return!!this.connections.has(t)&&(this.removeConnectionSVG(t),!0)}removeAllEndpoints(t){var e;const i=null===(e=document.getElementById(t))||void 0===e?void 0:e.querySelectorAll(".exit");i&&i.forEach(t=>{const e=t.id;this.sources.has(e)&&(this.sources.get(e)(),this.sources.delete(e))})}setConnectionRemovingState(t,e){const i=this.connections.get(t);return!!i&&(e?i.svgEl.classList.add("removing"):i.svgEl.classList.remove("removing"),!0)}setActivityData(t){this.activityData=t,this.clearRecentContactsCache(),this.updateActivityOverlays()}updateActivityOverlays(){if(!this.activityData)return this.overlays.forEach(t=>t.remove()),void this.overlays.clear();const t=new Set;this.connections.forEach((e,i)=>{const o=`${e.fromId}:${e.toId}`,n=this.activityData.segments[o];if(n&&n>0){t.add(i);let e=this.overlays.get(i);e?(e.textContent=n.toLocaleString(),e.setAttribute("data-activity-key",o)):(e=this.createOverlayElement(n,o),this.canvas.appendChild(e),this.overlays.set(i,e)),this.updateOverlayPosition(i)}}),this.overlays.forEach((e,i)=>{t.has(i)||(e.remove(),this.overlays.delete(i))})}createOverlayElement(t,e){const i=document.createElement("div");return i.className="activity-overlay",i.textContent=t.toLocaleString(),i.setAttribute("data-activity-key",e),i.addEventListener("mouseenter",()=>{const t=this.getFlowUuid();t&&(this.fetchRecentContacts(e,t),this.showContactsTimeout=window.setTimeout(()=>{this.showRecentContacts(e,t)},500))}),i.addEventListener("mouseleave",()=>{this.showContactsTimeout&&(clearTimeout(this.showContactsTimeout),this.showContactsTimeout=null),this.hoveredActivityKey=null,this.hideRecentContacts()}),i}updateOverlayPosition(t){const e=this.overlays.get(t),i=this.connections.get(t);if(!e||!i)return;const o=this.getConnectionEndpoints(i.fromId,i.toId,i.scope);o&&(e.style.position="absolute",e.style.left=`${o.sourceX}px`,e.style.top=`${o.sourceY+15}px`,e.style.transform="translate(-50%, -50%)")}getFlowUuid(){var t,e;return(null===(e=null===(t=this.editor)||void 0===t?void 0:t.definition)||void 0===e?void 0:e.uuid)||null}async fetchRecentContacts(t,e){if(this.recentContactsCache[t]||this.pendingFetches[t])return;const i=new AbortController;this.pendingFetches[t]=i;try{const[o,n]=t.split(":"),s=`/flow/recent_contacts/${e}/${o}/${n}/`,r=await fetch(s,{signal:i.signal});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);const a=await r.json();this.recentContactsCache[t]=Array.isArray(a)?a:a.results||[]}catch(t){"AbortError"!==t.name&&console.error("Failed to fetch recent contacts:",t)}finally{delete this.pendingFetches[t]}}async showRecentContacts(t,e){const i=this.findOverlayForActivityKey(t);i&&(this.hideContactsTimeout&&(clearTimeout(this.hideContactsTimeout),this.hideContactsTimeout=null),this.hoveredActivityKey=t,this.recentContactsPopup||(this.recentContactsPopup=document.createElement("div"),this.recentContactsPopup.className="recent-contacts-popup",this.recentContactsPopup.style.position="absolute",this.recentContactsPopup.style.zIndex="1015",this.recentContactsPopup.style.display="none",document.body.appendChild(this.recentContactsPopup),this.recentContactsPopup.onmouseenter=()=>{this.hideContactsTimeout&&(clearTimeout(this.hideContactsTimeout),this.hideContactsTimeout=null)},this.recentContactsPopup.onmouseleave=()=>{this.hoveredActivityKey=null,this.hideRecentContacts()},this.recentContactsPopup.onclick=t=>{const e=t.target;if(e.classList.contains("contact-name")){this.hideRecentContacts(!1);const i=e.getAttribute("data-uuid");i&&this.editor.fireCustomEvent("temba-contact-clicked",{uuid:i,metaKey:t.metaKey,ctrlKey:t.ctrlKey})}}),this.recentContactsCache[t]?(this.renderRecentContactsPopup(this.recentContactsCache[t]),this.positionPopup(i)):(this.recentContactsPopup.innerHTML='<div class="no-contacts-message">Loading...</div>',this.positionPopup(i),await this.fetchRecentContacts(t,e),this.hoveredActivityKey===t&&(this.renderRecentContactsPopup(this.recentContactsCache[t]||[]),this.positionPopup(i))))}findOverlayForActivityKey(t){for(const[,e]of this.overlays)if(e.getAttribute("data-activity-key")===t)return e;return null}positionPopup(t){if(!this.recentContactsPopup)return;const e=t.getBoundingClientRect();this.recentContactsPopup.style.left=`${e.left+window.scrollX}px`,this.recentContactsPopup.style.top=`${e.bottom+window.scrollY+5}px`,this.recentContactsPopup.style.display="",this.recentContactsPopup.classList.remove("show"),this.recentContactsPopup.offsetWidth,this.recentContactsPopup.classList.add("show")}renderRecentContactsPopup(t){if(!this.recentContactsPopup)return;if(0===t.length)return void(this.recentContactsPopup.innerHTML='<div class="no-contacts-message">No Recent Contacts</div>');let e='<div class="popup-title">Recent Contacts</div>';t.forEach(t=>{if(e+='<div class="contact-row">',e+=`<div class="contact-name" data-uuid="${t.contact.uuid}">${t.contact.name}</div>`,t.operand&&(e+=`<div class="contact-operand">${t.operand}</div>`),t.time){const i=new Date(t.time),o=Date.now()-i.getTime(),n=Math.floor(o/6e4),s=Math.floor(o/36e5),r=Math.floor(o/864e5);let a="";a=n<1?"just now":n<60?`${n}m ago`:s<24?`${s}h ago`:`${r}d ago`,e+=`<div class="contact-time">${a}</div>`}e+="</div>"}),this.recentContactsPopup.innerHTML=e}hideRecentContacts(t=!0){t?this.hideContactsTimeout=window.setTimeout(()=>{!this.hoveredActivityKey&&this.recentContactsPopup&&(this.recentContactsPopup.classList.remove("show"),this.recentContactsPopup.style.display="none",this.hoveredActivityKey=null)},200):this.recentContactsPopup&&(this.recentContactsPopup.classList.remove("show"),this.recentContactsPopup.style.display="none",this.hoveredActivityKey=null)}clearRecentContactsCache(){this.recentContactsCache={},Object.values(this.pendingFetches).forEach(t=>t.abort()),this.pendingFetches={}}startDrag(t,e,i,o){const n=this.connections.get(t);if(n){n.svgEl.style.display="none";const e=this.overlays.get(t);e&&(e.style.display="none")}const{svgEl:s,pathEl:r,arrowEl:a,hitAreaEl:l}=this.createSVGElement();s.classList.add("dragging"),r.style.pointerEvents="none",a.style.pointerEvents="none",l.style.pointerEvents="none",this.canvas.appendChild(s);const d=document.getElementById(t);if(!d)return void s.remove();const c=this.canvas.getBoundingClientRect(),h=d.getBoundingClientRect(),u=this.toCanvas(h.left+h.width/2-c.left),p=this.toCanvas(h.bottom-c.top),m=6.5,g=(t,e)=>{const i=e<p;let o,n="top";i&&(n=t<u?"left":"right"),o=i?e+1+13:e-1;const s=zm(u,p,t,o,30,i?0:8,5,n);if(r.setAttribute("d",s),i){const i=e+1;a.setAttribute("points",`${t},${i} ${t-m},${o} ${t+m},${o}`)}else{const e=o+13;a.setAttribute("points",`${t},${e} ${t-m},${o} ${t+m},${o}`)}},{clientX:f,clientY:v}=Mm(o),b=this.toCanvas(f-c.left),y=this.toCanvas(v-c.top);g(b,y),this.connectionDragging=!0;const x=t=>{"touches"in t&&t.preventDefault();const e=this.canvas.getBoundingClientRect(),{clientX:i,clientY:o}=Mm(t),n=this.toCanvas(i-e.left),s=this.toCanvas(o-e.top);g(n,s)},w=o=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",w),document.removeEventListener("touchmove",x),document.removeEventListener("touchend",w),document.removeEventListener("touchcancel",w),s.remove(),this.removeConnectionSVG(t),this.connectionDragging=!1,this.dragState=null,this.notifyListeners("connection:abort",{source:d,sourceId:t,target:{id:i},data:{nodeId:e}})};document.addEventListener("mousemove",x),document.addEventListener("mouseup",w),document.addEventListener("touchmove",x,{passive:!1}),document.addEventListener("touchend",w),document.addEventListener("touchcancel",w),this.dragState={sourceId:t,scope:e,originalTargetId:i,svgEl:s,pathEl:r,arrowEl:a,onMove:x,onUp:w},this.notifyListeners("connection:drag",{sourceId:t,sourceX:u,sourceY:p,data:{nodeId:e},target:{id:i}})}reset(){this.connectionWait&&(cancelAnimationFrame(this.connectionWait),this.connectionWait=null),this.pendingConnections=[],this.connections.forEach(t=>t.svgEl.remove()),this.connections.clear(),this.overlays.forEach(t=>t.remove()),this.overlays.clear(),this.hideRecentContacts(!1),this.recentContactsPopup&&(this.recentContactsPopup.remove(),this.recentContactsPopup=null),this.recentContactsCache={},Object.values(this.pendingFetches).forEach(t=>t.abort()),this.pendingFetches={},this.sources.forEach(t=>t()),this.sources.clear(),this.dragState&&(document.removeEventListener("mousemove",this.dragState.onMove),document.removeEventListener("mouseup",this.dragState.onUp),this.dragState.svgEl.remove(),this.dragState=null,this.connectionDragging=!1)}}class Lm extends Be{createRenderRoot(){return this}static get styles(){return a`
9137
9318
 
9138
- .action .drag-handle:hover {
9139
- visibility: visible;
9140
- opacity: 1;
9319
+ .node {
9320
+ background-color: #fff;
9321
+ box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
9322
+ min-width: 200px;
9323
+ border-radius: var(--curvature);
9324
+ color: #333;
9325
+ user-select: none;
9141
9326
  }
9142
9327
 
9143
- strong {
9144
- font-weight: 500;
9328
+ .shift-held > temba-flow-node,
9329
+ .shift-held > temba-flow-node * {
9330
+ cursor: copy !important;
9145
9331
  }
9146
9332
 
9147
- .action .cn-title,
9148
- .router .cn-title {
9149
- display: flex;
9150
- color: #fff;
9151
- text-align: center;
9152
- font-size: 1em;
9153
- font-weight: 500;
9333
+ .shift-held > temba-flow-node .exit,
9334
+ .shift-held > temba-flow-node .exit *,
9335
+ .shift-held > temba-flow-node .linked-name,
9336
+ .shift-held > temba-flow-node .linked-name *,
9337
+ .shift-held > temba-flow-node .remove-button,
9338
+ .shift-held > temba-flow-node .remove-button * {
9339
+ cursor: pointer !important;
9154
9340
  }
9155
9341
 
9156
- .cn-title .name {
9157
- padding: 0.3em 0;
9158
-
9342
+ temba-flow-node.drag-copy .node {
9343
+ outline: 3px dashed var(--color-primary, #3b82f6);
9344
+ outline-offset: 2px;
9345
+ opacity: 0.7;
9159
9346
  }
9160
9347
 
9161
- .router .cn-title {
9162
-
9348
+ /* Flow start indicator */
9349
+ temba-flow-node.flow-start .node::before {
9350
+ content: 'FLOW START';
9351
+ position: absolute;
9352
+ top: -16px;
9353
+ left: 50%;
9354
+ transform: translateX(-50%);
9355
+ font-size: 10px;
9356
+ font-weight: 600;
9357
+ letter-spacing: 0.5px;
9358
+ color: var(--color-primary-dark, #3b82f6);
9359
+ opacity: 0.7;
9360
+ z-index: 10;
9361
+ white-space: nowrap;
9163
9362
  }
9164
9363
 
9165
- .cn-title .name {
9166
- flex-grow: 1;
9364
+ /* Cap width for execute_actions nodes */
9365
+ .node.execute-actions {
9366
+ max-width: 200px;
9167
9367
  }
9168
9368
 
9169
- .quick-replies {
9170
- margin-top: 0.5em;
9171
- display: flex;
9172
- flex-wrap: wrap;
9369
+ .node .action:last-child {
9370
+ border-bottom-left-radius: var(--curvature);
9371
+ border-bottom-right-radius: var(--curvature);
9173
9372
  }
9174
9373
 
9175
- .quick-reply {
9176
- background: white;
9374
+ .node .action:first-child {
9375
+ border-top-left-radius: var(--curvature);
9376
+ border-top-right-radius: var(--curvature);
9377
+ }
9378
+
9379
+ .node.dragging {
9380
+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);
9381
+ transform: scale(1.02);
9382
+ z-index: 1000;
9383
+ }
9384
+
9385
+ .action {
9386
+ position: relative;
9387
+ }
9388
+
9389
+
9390
+ .action .cn-title:hover .remove-button,
9391
+ .router:hover .remove-button {
9392
+ visibility: visible;
9393
+ opacity: 0.7;
9394
+ }
9395
+
9396
+ .action.removing .cn-title,
9397
+ .router .cn-title.removing {
9398
+ background-color: var(--color-error, #dc3545) !important;
9399
+ }
9400
+
9401
+ .action.removing .cn-title .name,
9402
+ .router .cn-title.removing .name {
9403
+ color: white;
9404
+ }
9405
+
9406
+ .remove-button {
9407
+ background: transparent;
9408
+ color: white;
9409
+ visibility: hidden;
9410
+ cursor: pointer;
9411
+ font-size: 1em;
9412
+ font-weight: 600;
9413
+ line-height: 1;
9414
+ z-index: 10;
9415
+ transition: all 100ms ease-in-out;
9416
+ align-self: center;
9417
+ margin-right: 0.3em;
9418
+ border: 0px solid red;
9419
+ width: 1em;
9420
+ pointer-events: auto; /* Ensure remove button can receive events */
9421
+ }
9422
+
9423
+ .remove-button:hover {
9424
+ visibility: visible;
9425
+ opacity: 1;
9426
+ }
9427
+
9428
+ .read-only-hidden {
9429
+ visibility: hidden !important;
9430
+ pointer-events: none !important;
9431
+ }
9432
+
9433
+ /* Issue indicators - hatched red title bar */
9434
+ .action-content.has-issues .cn-title,
9435
+ .node.has-issues > .router .cn-title {
9436
+ background: repeating-linear-gradient(120deg, tomato, tomato 6px, #ff7056 0, #ff7056 18px) !important;
9437
+ }
9438
+
9439
+ /* Disable links on actions/nodes with issues */
9440
+ .action-content.has-issues .linked-name div,
9441
+ .node.has-issues > .router .linked-name div {
9442
+ text-decoration: none !important;
9443
+ cursor: default !important;
9444
+ pointer-events: none;
9445
+ }
9446
+
9447
+ .action.sortable {
9448
+ display: flex;
9449
+ align-items: stretch;
9450
+ }
9451
+
9452
+ .action .action-content {
9453
+ flex-grow: 1;
9454
+ display: flex;
9455
+ flex-direction: column;
9456
+ min-width: 0; /* Allow flex item to shrink below its content size */
9457
+ overflow: hidden;
9458
+ background: #fff;
9459
+ }
9460
+
9461
+ .action .body {
9462
+ padding: 0.75em;
9463
+ word-wrap: break-word;
9464
+ overflow-wrap: break-word;
9465
+ hyphens: auto;
9466
+ white-space: normal;
9467
+ overflow: hidden;
9468
+ }
9469
+
9470
+ .node.execute-actions temba-sortable-list .action:last-child .body {
9471
+ padding-bottom: 1.5em;
9472
+ }
9473
+
9474
+ /* Localization indicators */
9475
+ .action.localizable:not(.has-localization) .action-content {
9476
+ background: #fff8dc !important; /* Light yellow background for localizable but not yet localized */
9477
+ }
9478
+
9479
+ .non-localizable {
9480
+ opacity: 0.25;
9481
+ pointer-events: none;
9482
+ }
9483
+
9484
+ .action.non-localizable .action-content {
9485
+ cursor: not-allowed;
9486
+ }
9487
+
9488
+ .action .drag-handle {
9489
+ visibility: hidden;
9490
+ transition: all 200ms ease-in-out;
9491
+ cursor: move;
9492
+ background: rgba(0, 0, 0, 0.02);
9493
+ width: 1em;
9494
+ padding: 0.25em;
9495
+ border: 0px solid red;
9496
+ pointer-events: auto; /* Ensure drag handle can receive events */
9497
+ }
9498
+ .title-spacer {
9499
+ width: 1.8em;
9500
+ }
9501
+
9502
+ .action:hover .drag-handle {
9503
+ visibility: visible;
9504
+ opacity: 0.7;
9505
+ }
9506
+
9507
+ .action .drag-handle:hover {
9508
+ visibility: visible;
9509
+ opacity: 1;
9510
+ }
9511
+
9512
+ strong {
9513
+ font-weight: 500;
9514
+ }
9515
+
9516
+ .action .cn-title,
9517
+ .router .cn-title {
9518
+ display: flex;
9519
+ color: #fff;
9520
+ text-align: center;
9521
+ font-size: 1em;
9522
+ font-weight: 500;
9523
+ }
9524
+
9525
+ .cn-title .name {
9526
+ padding: 0.3em 0;
9527
+
9528
+ }
9529
+
9530
+ .router .cn-title {
9531
+
9532
+ }
9533
+
9534
+ .cn-title .name {
9535
+ flex-grow: 1;
9536
+ }
9537
+
9538
+ .quick-replies {
9539
+ margin-top: 0.5em;
9540
+ display: flex;
9541
+ flex-wrap: wrap;
9542
+ }
9543
+
9544
+ .quick-reply {
9545
+ background: white;
9177
9546
  border: 1px solid var(--color-quick-reply, rgb(60, 146, 221));
9178
9547
  border-radius: 18px;
9179
9548
  padding: 4px 8px;
@@ -9498,7 +9867,7 @@ background: #ccc;
9498
9867
  ${ku(W`Save as
9499
9868
  <span class="result-name">${t.result_name}</span>`,`Save as ${t.result_name}`)}
9500
9869
  </div>`:null}
9501
- </div>`}renderCategories(t){var e,i;if(!t.router||!t.router.categories)return null;const o=wm[null===(e=this.ui)||void 0===e?void 0:e.type],n="categories"===(null==o?void 0:o.localizable),s=new Set(Mm(null===(i=this.ui)||void 0===i?void 0:i.type,t.router.categories).map(t=>t.uuid));return W`<div class="categories">
9870
+ </div>`}renderCategories(t){var e,i;if(!t.router||!t.router.categories)return null;const o=wm[null===(e=this.ui)||void 0===e?void 0:e.type],n="categories"===(null==o?void 0:o.localizable),s=new Set(km(null===(i=this.ui)||void 0===i?void 0:i.type,t.router.categories).map(t=>t.uuid));return W`<div class="categories">
9502
9871
  ${Vc(t.router.categories,t=>t.uuid,e=>{var i,o,r,a;const l=t.exits.find(t=>t.uuid==e.exit_uuid);let d=e.name,c=!1;if(this.isTranslating&&"eng"!==this.languageCode&&n&&s.has(e.uuid)){const t=null===(o=null===(i=this.flowDefinition)||void 0===i?void 0:i.localization)||void 0===o?void 0:o[this.languageCode];if(t&&t[e.uuid]){const i=t[e.uuid];i.name&&i.name[0]&&(d=i.name[0],c=!0)}}const h=!!(null===(a=null===(r=this.ui)||void 0===r?void 0:r.config)||void 0===a?void 0:a.localizeCategories),u=this.isTranslating&&"eng"!==this.languageCode&&n&&s.has(e.uuid)&&h&&!c;return W`<div
9503
9872
  class=${re({category:!0,localizable:u})}
9504
9873
  @mousedown=${t=>this.handleNodeMouseDown(t)}
@@ -9516,7 +9885,7 @@ background: #ccc;
9516
9885
  class=${re({exit:!0,connected:!!t.destination_uuid,removing:this.exitRemovingState.has(t.uuid),"read-only":this.isReadOnly()})}
9517
9886
  @click=${e=>this.handleExitClick(e,t)}
9518
9887
  ></div>
9519
- </div>`}isReadOnly(){return this.viewingRevision||this.isTranslating}render(){var t,e,i,o,n,s,r,a,l;if(!this.node||!this.ui)return W`<div class="node">Loading...</div>`;const d=wm[this.ui.type],c="categories"===(null==d?void 0:d.localizable)&&(h=this.ui.type,u=null===(t=this.node.router)||void 0===t?void 0:t.categories,Mm(h,u).length>0);var h,u;const p=(this.node.actions||[]).some(t=>{var e;const i=ym[t.type];return!!(null===(e=null==i?void 0:i.localizable)||void 0===e?void 0:e.length)}),m=!!(null===(i=null===(e=this.ui)||void 0===e?void 0:e.config)||void 0===i?void 0:i.localizeCategories),g=!!(null===(n=null===(o=this.ui)||void 0===o?void 0:o.config)||void 0===n?void 0:n.localizeRules),f=p||c&&m||g,v=this.isTranslating&&!f,b=(null===(s=this.activity)||void 0===s?void 0:s.nodes)&&this.activity.nodes[this.node.uuid]||0,y=(null===(r=this.issuesByNode)||void 0===r?void 0:r.has(this.node.uuid))||(null===(a=this.node.actions)||void 0===a?void 0:a.some(t=>{var e;return null===(e=this.issuesByAction)||void 0===e?void 0:e.has(t.uuid)}));return W`
9888
+ </div>`}isReadOnly(){return this.viewingRevision||this.isTranslating}render(){var t,e,i,o,n,s,r,a,l;if(!this.node||!this.ui)return W`<div class="node">Loading...</div>`;const d=wm[this.ui.type],c="categories"===(null==d?void 0:d.localizable)&&(h=this.ui.type,u=null===(t=this.node.router)||void 0===t?void 0:t.categories,km(h,u).length>0);var h,u;const p=(this.node.actions||[]).some(t=>{var e;const i=ym[t.type];return!!(null===(e=null==i?void 0:i.localizable)||void 0===e?void 0:e.length)}),m=!!(null===(i=null===(e=this.ui)||void 0===e?void 0:e.config)||void 0===i?void 0:i.localizeCategories),g=!!(null===(n=null===(o=this.ui)||void 0===o?void 0:o.config)||void 0===n?void 0:n.localizeRules),f=p||c&&m||g,v=this.isTranslating&&!f,b=(null===(s=this.activity)||void 0===s?void 0:s.nodes)&&this.activity.nodes[this.node.uuid]||0,y=(null===(r=this.issuesByNode)||void 0===r?void 0:r.has(this.node.uuid))||(null===(a=this.node.actions)||void 0===a?void 0:a.some(t=>{var e;return null===(e=this.issuesByAction)||void 0===e?void 0:e.has(t.uuid)}));return W`
9520
9889
  <div
9521
9890
  id="${this.node.uuid}"
9522
9891
  class=${re({node:!0,"execute-actions":"execute_actions"===this.ui.type,"non-localizable":v,"has-issues":y})}
@@ -9565,10 +9934,10 @@ background: #ccc;
9565
9934
  <temba-icon name="add"></temba-icon>
9566
9935
  </div>`}
9567
9936
  </div>
9568
- `}}t([mt({type:Object})],zm.prototype,"plumber",void 0),t([mt({type:Object})],zm.prototype,"node",void 0),t([mt({type:Object})],zm.prototype,"ui",void 0),t([Ad(Sd,t=>t.isTranslating)],zm.prototype,"isTranslating",void 0),t([Ad(Sd,t=>t.languageCode)],zm.prototype,"languageCode",void 0),t([Ad(Sd,t=>t.viewingRevision)],zm.prototype,"viewingRevision",void 0),t([Ad(Sd,t=>t.flowDefinition)],zm.prototype,"flowDefinition",void 0),t([Ad(Sd,t=>t.getCurrentActivity())],zm.prototype,"activity",void 0),t([Ad(Sd,t=>t.issuesByNode)],zm.prototype,"issuesByNode",void 0),t([Ad(Sd,t=>t.issuesByAction)],zm.prototype,"issuesByAction",void 0);class Im{constructor(t){this.editor=t,this.isMouseDown=!1,this.shiftDragCopy=!1,this.currentDragIsCopy=!1,this.dragStartPos={x:0,y:0},this.originalDragItem=null,this.originalSelectedItems=null,this.dragHintTimer=null,this.autoScrollAnimationId=null,this.autoScrollDeltaX=0,this.autoScrollDeltaY=0,this.lastPointerPos=null,this.activeDragIsTouch=!1,this.isTouchDevice=!1,this.isTwoFingerPanning=!1,this.twoFingerDidPan=!1,this.twoFingerStartMidX=0,this.twoFingerStartMidY=0,this.twoFingerOnCanvas=!1,this.lastPanX=0,this.lastPanY=0,this.canvasMouseDown=!1,this.boundMouseMove=this.handleMouseMove.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundGlobalMouseDown=this.handleGlobalMouseDown.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this),this.boundWindowBlur=this.handleWindowBlur.bind(this),this.boundTouchMove=this.handleTouchMove.bind(this),this.boundTouchEnd=this.handleTouchEnd.bind(this),this.boundTouchCancel=this.handleTouchCancel.bind(this),this.boundCanvasTouchStart=this.handleCanvasTouchStart.bind(this)}setupListeners(){document.addEventListener("mousemove",this.boundMouseMove),document.addEventListener("mouseup",this.boundMouseUp),document.addEventListener("mousedown",this.boundGlobalMouseDown),document.addEventListener("keydown",this.boundKeyDown),document.addEventListener("keyup",this.boundKeyUp),window.addEventListener("blur",this.boundWindowBlur),document.addEventListener("touchmove",this.boundTouchMove,{passive:!1}),document.addEventListener("touchend",this.boundTouchEnd),document.addEventListener("touchcancel",this.boundTouchCancel);const t=this.editor.querySelector("#canvas");null==t||t.addEventListener("touchstart",this.boundCanvasTouchStart,{passive:!1})}teardownListeners(){document.removeEventListener("mousemove",this.boundMouseMove),document.removeEventListener("mouseup",this.boundMouseUp),document.removeEventListener("mousedown",this.boundGlobalMouseDown),document.removeEventListener("keydown",this.boundKeyDown),document.removeEventListener("keyup",this.boundKeyUp),window.removeEventListener("blur",this.boundWindowBlur),document.removeEventListener("touchmove",this.boundTouchMove),document.removeEventListener("touchend",this.boundTouchEnd),document.removeEventListener("touchcancel",this.boundTouchCancel);const t=this.editor.querySelector("#canvas");null==t||t.removeEventListener("touchstart",this.boundCanvasTouchStart),this.stopAutoScroll(),this.hideDragHint()}getPosition(t,e){var i,o,n;return"node"===e?null===(i=this.editor.definition._ui.nodes[t])||void 0===i?void 0:i.position:null===(n=null===(o=this.editor.definition._ui.stickies)||void 0===o?void 0:o[t])||void 0===n?void 0:n.position}handleMouseDown(t){if(fu(t))return;if(this.editor.isReadOnly())return;this.blurActiveContentEditable();const e=t.currentTarget,i=t.target;if(i.classList.contains("exit")||i.closest(".exit")||i.closest(".linked-name"))return;const o=e.getAttribute("uuid"),n="TEMBA-FLOW-NODE"===e.tagName?"node":"sticky",s=this.getPosition(o,n);s&&(this.editor.selectedItems.has(o)||t.ctrlKey||t.metaKey?this.editor.selectedItems.has(o)||this.editor.selectedItems.add(o):this.editor.selectedItems.clear(),this.isMouseDown=!0,this.activeDragIsTouch=!1,this.shiftDragCopy=t.shiftKey,this.dragStartPos={x:t.clientX,y:t.clientY},this.editor.currentDragItem={uuid:o,position:s,element:e,type:n},t.preventDefault(),t.stopPropagation())}markTouchDevice(){var t,e;this.isTouchDevice||(this.isTouchDevice=!0,null===(t=this.editor.querySelector("#canvas"))||void 0===t||t.classList.add("touch-device"),null===(e=this.editor.querySelector("#editor"))||void 0===e||e.classList.add("touch-device"))}handleItemTouchStart(t){if(this.markTouchDevice(),this.editor.isReadOnly())return;this.blurActiveContentEditable();const e=t.touches[0];if(!e)return;const i=t.currentTarget,o=t.target;if(o.classList.contains("exit")||o.closest(".exit")||o.closest(".linked-name"))return;const n=i.getAttribute("uuid"),s="TEMBA-FLOW-NODE"===i.tagName?"node":"sticky",r=this.getPosition(n,s);r&&(this.editor.selectedItems.has(n)||this.editor.selectedItems.clear(),this.isMouseDown=!0,this.activeDragIsTouch=!0,this.dragStartPos={x:e.clientX,y:e.clientY},this.editor.currentDragItem={uuid:n,position:r,element:i,type:s},t.stopPropagation())}handleGlobalMouseDown(t){var e;if(fu(t))return;const i=null===(e=this.editor.querySelector("#grid"))||void 0===e?void 0:e.getBoundingClientRect();if(!i)return;if(!(t.clientX>=i.left&&t.clientX<=i.right&&t.clientY>=i.top&&t.clientY<=i.bottom))return;t.target.closest(".draggable")||this.handleCanvasMouseDown(t)}blurActiveContentEditable(){var t;let e=document.activeElement;for(;null===(t=null==e?void 0:e.shadowRoot)||void 0===t?void 0:t.activeElement;)e=e.shadowRoot.activeElement;e instanceof HTMLElement&&"true"===e.getAttribute("contenteditable")&&e.blur()}handleCanvasMouseDown(t){var e;if(this.editor.isReadOnly())return;this.blurActiveContentEditable();const i=t.target;if("canvas"===i.id||"grid"===i.id){this.canvasMouseDown=!0,this.dragStartPos={x:t.clientX,y:t.clientY};const i=null===(e=this.editor.querySelector("#canvas"))||void 0===e?void 0:e.getBoundingClientRect();if(i){this.editor.selectedItems.clear();const e=(t.clientX-i.left)/this.editor.zoom,o=(t.clientY-i.top)/this.editor.zoom;this.editor.selectionBox={startX:e,startY:o,endX:e,endY:o}}t.preventDefault()}}showDragHint(){if(this.editor.isReadOnly())return;const t=this.editor.querySelector("#drag-hint");t&&(this.dragHintTimer=setTimeout(()=>{t.classList.add("visible"),this.dragHintTimer=null},600))}hideDragHint(){this.dragHintTimer&&(clearTimeout(this.dragHintTimer),this.dragHintTimer=null);const t=this.editor.querySelector("#drag-hint");t&&t.classList.remove("visible")}handleKeyDown(t){var e;"Shift"===t.key&&(null===(e=this.editor.querySelector("#canvas"))||void 0===e||e.classList.add("shift-held"),this.editor.isDragging&&!this.currentDragIsCopy&&(this.hideDragHint(),this.performShiftDragCopy(),requestAnimationFrame(()=>{this.markCopyElements(),this.updateDragPositions()}))),this.editor.handleKeyDown(t)}handleKeyUp(t){var e;"Shift"===t.key&&(null===(e=this.editor.querySelector("#canvas"))||void 0===e||e.classList.remove("shift-held"),this.editor.isDragging&&this.currentDragIsCopy&&(this.revertShiftDragCopy(),requestAnimationFrame(()=>this.updateDragPositions()))),this.editor.handleKeyUp(t)}handleWindowBlur(){var t;null===(t=this.editor.querySelector("#canvas"))||void 0===t||t.classList.remove("shift-held"),this.editor.isDragging&&this.currentDragIsCopy&&(this.revertShiftDragCopy(),requestAnimationFrame(()=>this.updateDragPositions())),this.editor.handleWindowBlur()}updateSelectionBox(t){var e;if(!this.editor.selectionBox||!this.canvasMouseDown)return;const i=null===(e=this.editor.querySelector("#canvas"))||void 0===e?void 0:e.getBoundingClientRect();if(!i)return;const o=(t.clientX-i.left)/this.editor.zoom,n=(t.clientY-i.top)/this.editor.zoom;this.editor.selectionBox={...this.editor.selectionBox,endX:o,endY:n},this.updateSelectedItemsFromBox()}updateSelectedItemsFromBox(){var t,e,i;if(!this.editor.selectionBox)return;const o=new Set,n=Math.min(this.editor.selectionBox.startX,this.editor.selectionBox.endX),s=Math.min(this.editor.selectionBox.startY,this.editor.selectionBox.endY),r=Math.max(this.editor.selectionBox.startX,this.editor.selectionBox.endX),a=Math.max(this.editor.selectionBox.startY,this.editor.selectionBox.endY);null===(t=this.editor.definition)||void 0===t||t.nodes.forEach(t=>{var e,i,l;const d=this.editor.querySelector(`[id="${t.uuid}"]`);if(d){const c=null===(i=null===(e=this.editor.definition._ui)||void 0===e?void 0:e.nodes[t.uuid])||void 0===i?void 0:i.position;if(c){if(null===(l=this.editor.querySelector("#canvas"))||void 0===l?void 0:l.getBoundingClientRect()){const e=c.left,i=c.top,l=e+d.offsetWidth,h=i+d.offsetHeight;n<l&&r>e&&s<h&&a>i&&o.add(t.uuid)}}}});const l=(null===(i=null===(e=this.editor.definition)||void 0===e?void 0:e._ui)||void 0===i?void 0:i.stickies)||{};Object.entries(l).forEach(([t,e])=>{if(e.position){const i=this.editor.querySelector(`temba-sticky-note[uuid="${t}"]`);if(i){const l=i.clientWidth,d=i.clientHeight,c=e.position.left,h=e.position.top;n<c+l&&r>c&&s<h+d&&a>h&&o.add(t)}}}),this.editor.selectedItems=o}renderSelectionBox(){if(!this.editor.selectionBox||!this.editor.isSelecting)return"";const t=Math.min(this.editor.selectionBox.startX,this.editor.selectionBox.endX),e=Math.min(this.editor.selectionBox.startY,this.editor.selectionBox.endY),i=Math.abs(this.editor.selectionBox.endX-this.editor.selectionBox.startX),o=Math.abs(this.editor.selectionBox.endY-this.editor.selectionBox.startY);return W`<div
9937
+ `}}t([mt({type:Object})],Lm.prototype,"plumber",void 0),t([mt({type:Object})],Lm.prototype,"node",void 0),t([mt({type:Object})],Lm.prototype,"ui",void 0),t([Ad(Sd,t=>t.isTranslating)],Lm.prototype,"isTranslating",void 0),t([Ad(Sd,t=>t.languageCode)],Lm.prototype,"languageCode",void 0),t([Ad(Sd,t=>t.viewingRevision)],Lm.prototype,"viewingRevision",void 0),t([Ad(Sd,t=>t.flowDefinition)],Lm.prototype,"flowDefinition",void 0),t([Ad(Sd,t=>t.getCurrentActivity())],Lm.prototype,"activity",void 0),t([Ad(Sd,t=>t.issuesByNode)],Lm.prototype,"issuesByNode",void 0),t([Ad(Sd,t=>t.issuesByAction)],Lm.prototype,"issuesByAction",void 0);class Om{constructor(t){this.editor=t,this.isMouseDown=!1,this.shiftDragCopy=!1,this.currentDragIsCopy=!1,this.dragStartPos={x:0,y:0},this.originalDragItem=null,this.originalSelectedItems=null,this.dragHintTimer=null,this.autoScrollAnimationId=null,this.autoScrollDeltaX=0,this.autoScrollDeltaY=0,this.lastPointerPos=null,this.activeDragIsTouch=!1,this.isTouchDevice=!1,this.isTwoFingerPanning=!1,this.twoFingerDidPan=!1,this.twoFingerStartMidX=0,this.twoFingerStartMidY=0,this.twoFingerOnCanvas=!1,this.lastPanX=0,this.lastPanY=0,this.canvasMouseDown=!1,this.boundMouseMove=this.handleMouseMove.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundGlobalMouseDown=this.handleGlobalMouseDown.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this),this.boundWindowBlur=this.handleWindowBlur.bind(this),this.boundTouchMove=this.handleTouchMove.bind(this),this.boundTouchEnd=this.handleTouchEnd.bind(this),this.boundTouchCancel=this.handleTouchCancel.bind(this),this.boundCanvasTouchStart=this.handleCanvasTouchStart.bind(this)}setupListeners(){document.addEventListener("mousemove",this.boundMouseMove),document.addEventListener("mouseup",this.boundMouseUp),document.addEventListener("mousedown",this.boundGlobalMouseDown),document.addEventListener("keydown",this.boundKeyDown),document.addEventListener("keyup",this.boundKeyUp),window.addEventListener("blur",this.boundWindowBlur),document.addEventListener("touchmove",this.boundTouchMove,{passive:!1}),document.addEventListener("touchend",this.boundTouchEnd),document.addEventListener("touchcancel",this.boundTouchCancel);const t=this.editor.querySelector("#canvas");null==t||t.addEventListener("touchstart",this.boundCanvasTouchStart,{passive:!1})}teardownListeners(){document.removeEventListener("mousemove",this.boundMouseMove),document.removeEventListener("mouseup",this.boundMouseUp),document.removeEventListener("mousedown",this.boundGlobalMouseDown),document.removeEventListener("keydown",this.boundKeyDown),document.removeEventListener("keyup",this.boundKeyUp),window.removeEventListener("blur",this.boundWindowBlur),document.removeEventListener("touchmove",this.boundTouchMove),document.removeEventListener("touchend",this.boundTouchEnd),document.removeEventListener("touchcancel",this.boundTouchCancel);const t=this.editor.querySelector("#canvas");null==t||t.removeEventListener("touchstart",this.boundCanvasTouchStart),this.stopAutoScroll(),this.hideDragHint()}getPosition(t,e){var i,o,n;return"node"===e?null===(i=this.editor.definition._ui.nodes[t])||void 0===i?void 0:i.position:null===(n=null===(o=this.editor.definition._ui.stickies)||void 0===o?void 0:o[t])||void 0===n?void 0:n.position}handleMouseDown(t){if(fu(t))return;if(this.editor.isReadOnly())return;this.blurActiveContentEditable();const e=t.currentTarget,i=t.target;if(i.classList.contains("exit")||i.closest(".exit")||i.closest(".linked-name"))return;const o=e.getAttribute("uuid"),n="TEMBA-FLOW-NODE"===e.tagName?"node":"sticky",s=this.getPosition(o,n);s&&(this.editor.selectedItems.has(o)||t.ctrlKey||t.metaKey?this.editor.selectedItems.has(o)||this.editor.selectedItems.add(o):this.editor.selectedItems.clear(),this.isMouseDown=!0,this.activeDragIsTouch=!1,this.shiftDragCopy=t.shiftKey,this.dragStartPos={x:t.clientX,y:t.clientY},this.editor.currentDragItem={uuid:o,position:s,element:e,type:n},t.preventDefault(),t.stopPropagation())}markTouchDevice(){var t,e;this.isTouchDevice||(this.isTouchDevice=!0,null===(t=this.editor.querySelector("#canvas"))||void 0===t||t.classList.add("touch-device"),null===(e=this.editor.querySelector("#editor"))||void 0===e||e.classList.add("touch-device"))}handleItemTouchStart(t){if(this.markTouchDevice(),this.editor.isReadOnly())return;this.blurActiveContentEditable();const e=t.touches[0];if(!e)return;const i=t.currentTarget,o=t.target;if(o.classList.contains("exit")||o.closest(".exit")||o.closest(".linked-name"))return;const n=i.getAttribute("uuid"),s="TEMBA-FLOW-NODE"===i.tagName?"node":"sticky",r=this.getPosition(n,s);r&&(this.editor.selectedItems.has(n)||this.editor.selectedItems.clear(),this.isMouseDown=!0,this.activeDragIsTouch=!0,this.dragStartPos={x:e.clientX,y:e.clientY},this.editor.currentDragItem={uuid:n,position:r,element:i,type:s},t.stopPropagation())}handleGlobalMouseDown(t){var e;if(fu(t))return;const i=null===(e=this.editor.querySelector("#grid"))||void 0===e?void 0:e.getBoundingClientRect();if(!i)return;if(!(t.clientX>=i.left&&t.clientX<=i.right&&t.clientY>=i.top&&t.clientY<=i.bottom))return;t.target.closest(".draggable")||this.handleCanvasMouseDown(t)}blurActiveContentEditable(){var t;let e=document.activeElement;for(;null===(t=null==e?void 0:e.shadowRoot)||void 0===t?void 0:t.activeElement;)e=e.shadowRoot.activeElement;e instanceof HTMLElement&&"true"===e.getAttribute("contenteditable")&&e.blur()}handleCanvasMouseDown(t){var e;if(this.editor.isReadOnly())return;this.blurActiveContentEditable();const i=t.target;if("canvas"===i.id||"grid"===i.id){this.canvasMouseDown=!0,this.dragStartPos={x:t.clientX,y:t.clientY};const i=null===(e=this.editor.querySelector("#canvas"))||void 0===e?void 0:e.getBoundingClientRect();if(i){this.editor.selectedItems.clear();const e=(t.clientX-i.left)/this.editor.zoom,o=(t.clientY-i.top)/this.editor.zoom;this.editor.selectionBox={startX:e,startY:o,endX:e,endY:o}}t.preventDefault()}}showDragHint(){if(this.editor.isReadOnly())return;const t=this.editor.querySelector("#drag-hint");t&&(this.dragHintTimer=setTimeout(()=>{t.classList.add("visible"),this.dragHintTimer=null},600))}hideDragHint(){this.dragHintTimer&&(clearTimeout(this.dragHintTimer),this.dragHintTimer=null);const t=this.editor.querySelector("#drag-hint");t&&t.classList.remove("visible")}handleKeyDown(t){var e;"Shift"===t.key&&(null===(e=this.editor.querySelector("#canvas"))||void 0===e||e.classList.add("shift-held"),this.editor.isDragging&&!this.currentDragIsCopy&&(this.hideDragHint(),this.performShiftDragCopy(),requestAnimationFrame(()=>{this.markCopyElements(),this.updateDragPositions()}))),this.editor.handleKeyDown(t)}handleKeyUp(t){var e;"Shift"===t.key&&(null===(e=this.editor.querySelector("#canvas"))||void 0===e||e.classList.remove("shift-held"),this.editor.isDragging&&this.currentDragIsCopy&&(this.revertShiftDragCopy(),requestAnimationFrame(()=>this.updateDragPositions()))),this.editor.handleKeyUp(t)}handleWindowBlur(){var t;null===(t=this.editor.querySelector("#canvas"))||void 0===t||t.classList.remove("shift-held"),this.editor.isDragging&&this.currentDragIsCopy&&(this.revertShiftDragCopy(),requestAnimationFrame(()=>this.updateDragPositions())),this.editor.handleWindowBlur()}updateSelectionBox(t){var e;if(!this.editor.selectionBox||!this.canvasMouseDown)return;const i=null===(e=this.editor.querySelector("#canvas"))||void 0===e?void 0:e.getBoundingClientRect();if(!i)return;const o=(t.clientX-i.left)/this.editor.zoom,n=(t.clientY-i.top)/this.editor.zoom;this.editor.selectionBox={...this.editor.selectionBox,endX:o,endY:n},this.updateSelectedItemsFromBox()}updateSelectedItemsFromBox(){var t,e,i;if(!this.editor.selectionBox)return;const o=new Set,n=Math.min(this.editor.selectionBox.startX,this.editor.selectionBox.endX),s=Math.min(this.editor.selectionBox.startY,this.editor.selectionBox.endY),r=Math.max(this.editor.selectionBox.startX,this.editor.selectionBox.endX),a=Math.max(this.editor.selectionBox.startY,this.editor.selectionBox.endY);null===(t=this.editor.definition)||void 0===t||t.nodes.forEach(t=>{var e,i,l;const d=this.editor.querySelector(`[id="${t.uuid}"]`);if(d){const c=null===(i=null===(e=this.editor.definition._ui)||void 0===e?void 0:e.nodes[t.uuid])||void 0===i?void 0:i.position;if(c){if(null===(l=this.editor.querySelector("#canvas"))||void 0===l?void 0:l.getBoundingClientRect()){const e=c.left,i=c.top,l=e+d.offsetWidth,h=i+d.offsetHeight;n<l&&r>e&&s<h&&a>i&&o.add(t.uuid)}}}});const l=(null===(i=null===(e=this.editor.definition)||void 0===e?void 0:e._ui)||void 0===i?void 0:i.stickies)||{};Object.entries(l).forEach(([t,e])=>{if(e.position){const i=this.editor.querySelector(`temba-sticky-note[uuid="${t}"]`);if(i){const l=i.clientWidth,d=i.clientHeight,c=e.position.left,h=e.position.top;n<c+l&&r>c&&s<h+d&&a>h&&o.add(t)}}}),this.editor.selectedItems=o}renderSelectionBox(){if(!this.editor.selectionBox||!this.editor.isSelecting)return"";const t=Math.min(this.editor.selectionBox.startX,this.editor.selectionBox.endX),e=Math.min(this.editor.selectionBox.startY,this.editor.selectionBox.endY),i=Math.abs(this.editor.selectionBox.endX-this.editor.selectionBox.startX),o=Math.abs(this.editor.selectionBox.endY-this.editor.selectionBox.startY);return W`<div
9569
9938
  class="selection-box"
9570
9939
  style="left: ${t}px; top: ${e}px; width: ${i}px; height: ${o}px;"
9571
- ></div>`}handleCanvasTouchStart(t){var e;this.markTouchDevice();const i=t.touches[0];if(!i)return;const o=t.target;if(o.closest(".draggable"))return;if("canvas"!==o.id&&"grid"!==o.id)return;if(t.touches.length>=2)return this.canvasMouseDown=!1,this.editor.isSelecting=!1,this.editor.selectionBox=null,this.isTwoFingerPanning=!0,this.twoFingerOnCanvas=!0,this.twoFingerDidPan=!1,this.twoFingerStartMidX=(t.touches[0].clientX+t.touches[1].clientX)/2,this.twoFingerStartMidY=(t.touches[0].clientY+t.touches[1].clientY)/2,this.lastPanX=this.twoFingerStartMidX,void(this.lastPanY=this.twoFingerStartMidY);if(this.editor.isReadOnly())return;this.canvasMouseDown=!0,this.dragStartPos={x:i.clientX,y:i.clientY};const n=null===(e=this.editor.querySelector("#canvas"))||void 0===e?void 0:e.getBoundingClientRect();if(n){this.editor.selectedItems.clear();const t=(i.clientX-n.left)/this.editor.zoom,e=(i.clientY-n.top)/this.editor.zoom;this.editor.selectionBox={startX:t,startY:e,endX:t,endY:e}}t.preventDefault()}handleMouseMove(t){if(this.canvasMouseDown&&!this.isMouseDown)return this.editor.isSelecting=!0,this.updateSelectionBox(t),void this.editor.requestUpdate();if(this.editor.plumber.connectionDragging){this.activeDragIsTouch=!1,this.lastPointerPos={clientX:t.clientX,clientY:t.clientY},this.startAutoScroll();const e=document.querySelector("temba-flow-node:hover");if(document.querySelectorAll("temba-flow-node").forEach(t=>{t.classList.remove("connection-target-valid","connection-target-invalid")}),e)this.editor.targetId=e.getAttribute("uuid"),this.editor.isValidTarget=this.editor.targetId!==this.editor.dragFromNodeId,this.editor.isValidTarget?e.classList.add("connection-target-valid"):e.classList.add("connection-target-invalid"),this.editor.connectionPlaceholder=null;else{this.editor.targetId=null,this.editor.isValidTarget=!0;const e=this.editor.querySelector("#canvas");if(e){const i=e.getBoundingClientRect(),o=(t.clientX-i.left)/this.editor.zoom,n=(t.clientY-i.top)/this.editor.zoom,s=200,r=64,a=13,l=1,d=null!=this.editor.connectionSourceY&&n<this.editor.connectionSourceY;let c;c=d?n+l-r:n-l+a,this.editor.connectionPlaceholder={position:{left:o-s/2,top:c},visible:!0,dragUp:d}}}this.editor.requestUpdate()}if(!this.isMouseDown||!this.editor.currentDragItem)return;this.lastPointerPos={clientX:t.clientX,clientY:t.clientY};const e=t.clientX-this.dragStartPos.x+this.autoScrollDeltaX,i=t.clientY-this.dragStartPos.y+this.autoScrollDeltaY,o=Math.sqrt(e*e+i*i);!this.editor.isDragging&&o>5&&(this.editor.isDragging=!0,this.startAutoScroll(),this.originalDragItem={...this.editor.currentDragItem},this.originalSelectedItems=new Set(this.editor.selectedItems),this.shiftDragCopy||t.shiftKey?(this.performShiftDragCopy(),this.shiftDragCopy=!1):this.showDragHint()),this.editor.isDragging&&this.updateDragPositions()}performShiftDragCopy(){var t,e,i,o,n;if(!this.originalDragItem)return;const s=(null===(t=this.originalSelectedItems)||void 0===t?void 0:t.has(this.originalDragItem.uuid))&&(null!==(i=null===(e=this.originalSelectedItems)||void 0===e?void 0:e.size)&&void 0!==i?i:0)>1?Array.from(this.originalSelectedItems):[this.originalDragItem.uuid];if(0===s.length)return;const r=$d().getState().duplicateNodes(s);for(const t of s){const e=r[t];e&&!this.editor.copiedItemUuids.includes(e)&&this.editor.copiedItemUuids.push(e)}this.currentDragIsCopy=!0;for(const t of s){const e=this.editor.querySelector(`[uuid="${t}"]`),i="TEMBA-FLOW-NODE"===(null==e?void 0:e.tagName)?"node":"sticky",o=this.getPosition(t,i);e&&o&&(e.style.left=`${o.left}px`,e.style.top=`${o.top}px`)}this.editor.plumber.revalidate(s);for(const t of s){const e=this.editor.querySelector(`[uuid="${t}"]`);e&&(e.offsetHeight,e.classList.remove("dragging"))}const a=r[this.originalDragItem.uuid];if(a&&(this.editor.currentDragItem={...this.originalDragItem,uuid:a}),(null!==(n=null===(o=this.originalSelectedItems)||void 0===o?void 0:o.size)&&void 0!==n?n:0)>1){const t=new Set;for(const e of this.originalSelectedItems){const i=r[e];t.add(i||e)}this.editor.selectedItems=t}}markCopyElements(){for(const t of this.editor.copiedItemUuids){const e=this.editor.querySelector(`[uuid="${t}"]`);null==e||e.classList.add("drag-copy")}}revertShiftDragCopy(){if(this.originalDragItem){if(this.editor.copiedItemUuids.length>0){const t=this.editor.copiedItemUuids.filter(t=>this.editor.definition.nodes.some(e=>e.uuid===t)),e=this.editor.copiedItemUuids.filter(t=>{var e,i;return null===(i=null===(e=this.editor.definition._ui)||void 0===e?void 0:e.stickies)||void 0===i?void 0:i[t]});t.length>0&&$d().getState().removeNodes(t),e.length>0&&$d().getState().removeStickyNotes(e),this.editor.copiedItemUuids=[]}this.currentDragIsCopy=!1,$d().getState().setDirtyDate(null),this.editor.currentDragItem={...this.originalDragItem},this.originalSelectedItems&&(this.editor.selectedItems=new Set(this.originalSelectedItems))}}updateDragPositions(){if(!this.editor.currentDragItem||!this.lastPointerPos)return;const t=(this.lastPointerPos.clientX-this.dragStartPos.x+this.autoScrollDeltaX)/this.editor.zoom,e=(this.lastPointerPos.clientY-this.dragStartPos.y+this.autoScrollDeltaY)/this.editor.zoom,i=this.editor.selectedItems.has(this.editor.currentDragItem.uuid)&&this.editor.selectedItems.size>1?Array.from(this.editor.selectedItems):[this.editor.currentDragItem.uuid];i.forEach(i=>{const o=this.editor.querySelector(`[uuid="${i}"]`);if(o){const n="TEMBA-FLOW-NODE"===o.tagName?"node":"sticky",s=this.getPosition(i,n);s&&(o.style.left=`${s.left+t}px`,o.style.top=`${s.top+e}px`,o.classList.add("dragging"),this.currentDragIsCopy&&o.classList.add("drag-copy"))}}),this.editor.plumber.revalidate(i)}startAutoScroll(){if(null!==this.autoScrollAnimationId)return;const t=this.editor.querySelector("#editor");if(!t)return;const e=()=>{var i,o,n;if(!this.editor.isDragging&&!(null===(i=this.editor.plumber)||void 0===i?void 0:i.connectionDragging)||!this.lastPointerPos)return void(this.autoScrollAnimationId=null);const s=t.getBoundingClientRect(),r=this.lastPointerPos.clientX,a=this.lastPointerPos.clientY,l=this.activeDragIsTouch?40:150;let d=0,c=0;const h=r-s.left;if(h<l){const t=h<0;d=-Math.min(1,1-h/l)*(15*(t?5:1))}const u=s.right-r;if(u<l){const t=u<0;d=Math.min(1,1-u/l)*(15*(t?5:1))}const p=a-s.top;if(p<l){const t=p<0;c=-Math.min(1,1-p/l)*(15*(t?5:1))}const m=s.bottom-a;if(m<l){const t=m<0;c=Math.min(1,1-m/l)*(15*(t?5:1))}if(0!==d||0!==c){const e=t.scrollLeft,i=t.scrollTop;if(d>0||c>0){const e=(t.scrollLeft+t.clientWidth+d)/this.editor.zoom,i=(t.scrollTop+t.clientHeight+c)/this.editor.zoom;null===(n=null===(o=$d())||void 0===o?void 0:o.getState())||void 0===n||n.expandCanvas(e,i)}t.scrollLeft+=d,t.scrollTop+=c;const s=t.scrollLeft-e,r=t.scrollTop-i;this.autoScrollDeltaX+=s,this.autoScrollDeltaY+=r,0===s&&0===r||this.updateDragPositions()}this.autoScrollAnimationId=requestAnimationFrame(e)};this.autoScrollAnimationId=requestAnimationFrame(e)}stopAutoScroll(){null!==this.autoScrollAnimationId&&(cancelAnimationFrame(this.autoScrollAnimationId),this.autoScrollAnimationId=null)}handleMouseUp(t){if(this.canvasMouseDown&&this.editor.isSelecting)return this.editor.isSelecting=!1,this.editor.selectionBox=null,this.canvasMouseDown=!1,void this.editor.requestUpdate();if(!this.canvasMouseDown||this.editor.isSelecting){if(this.isMouseDown&&this.editor.currentDragItem){if(this.stopAutoScroll(),this.editor.isDragging){const e=(t.clientX-this.dragStartPos.x+this.autoScrollDeltaX)/this.editor.zoom,i=(t.clientY-this.dragStartPos.y+this.autoScrollDeltaY)/this.editor.zoom,o=this.editor.selectedItems.has(this.editor.currentDragItem.uuid)&&this.editor.selectedItems.size>1?Array.from(this.editor.selectedItems):[this.editor.currentDragItem.uuid],n={};o.forEach(t=>{const o=this.editor.definition.nodes.find(e=>e.uuid===t)?"node":"sticky",s=this.getPosition(t,o);if(s){const o=s.left+e,r=s.top+i,a=bu(o),l=bu(r),d={left:a,top:l};n[t]=d;const c=this.editor.querySelector(`[uuid="${t}"]`);c&&(c.classList.remove("dragging","drag-copy"),c.style.left=`${a}px`,c.style.top=`${l}px`)}}),Object.keys(n).length>0&&(this.currentDragIsCopy&&(this.editor.pendingTimer.pending=!0,this.editor.capturePositionsOnce()),$d().getState().updateCanvasPositions(n),setTimeout(()=>{this.editor.checkCollisionsAndReflow(o),this.editor.plumber.repaintEverything()},0)),this.currentDragIsCopy&&this.editor.pendingTimer.start(),this.editor.selectedItems.clear()}this.hideDragHint(),this.editor.isDragging=!1,this.isMouseDown=!1,this.shiftDragCopy=!1,this.currentDragIsCopy=!1,this.editor.currentDragItem=null,this.originalDragItem=null,this.originalSelectedItems=null,this.canvasMouseDown=!1,this.autoScrollDeltaX=0,this.autoScrollDeltaY=0,this.lastPointerPos=null}}else this.canvasMouseDown=!1}handleTouchMove(t){var e;if(t.touches.length>=2){t.preventDefault();const e=(t.touches[0].clientX+t.touches[1].clientX)/2,i=(t.touches[0].clientY+t.touches[1].clientY)/2;if(this.isTwoFingerPanning){const t=this.lastPanX-e,o=this.lastPanY-i;(Math.abs(t)>2||Math.abs(o)>2)&&(this.twoFingerDidPan=!0);const n=this.editor.querySelector("#editor");n&&n.scrollBy(t,o)}return this.canvasMouseDown=!1,this.editor.isSelecting=!1,this.editor.selectionBox=null,this.isTwoFingerPanning=!0,this.lastPanX=e,void(this.lastPanY=i)}const i=t.touches[0];if(!i)return;if(this.canvasMouseDown&&!this.isMouseDown){t.preventDefault(),this.editor.isSelecting=!0;const o=null===(e=this.editor.querySelector("#canvas"))||void 0===e?void 0:e.getBoundingClientRect();return o&&this.editor.selectionBox&&(this.editor.selectionBox={...this.editor.selectionBox,endX:(i.clientX-o.left)/this.editor.zoom,endY:(i.clientY-o.top)/this.editor.zoom},this.updateSelectedItemsFromBox()),void this.editor.requestUpdate()}if(this.editor.plumber.connectionDragging){t.preventDefault();const e=this.editor.findTargetNodeAt(i.clientX,i.clientY);if(document.querySelectorAll("temba-flow-node").forEach(t=>{t.classList.remove("connection-target-valid","connection-target-invalid")}),e)this.editor.targetId=e.getAttribute("uuid"),this.editor.isValidTarget=this.editor.targetId!==this.editor.dragFromNodeId,this.editor.isValidTarget?e.classList.add("connection-target-valid"):e.classList.add("connection-target-invalid"),this.editor.connectionPlaceholder=null;else{this.editor.targetId=null,this.editor.isValidTarget=!0;const t=this.editor.querySelector("#canvas");if(t){const e=t.getBoundingClientRect(),o=(i.clientX-e.left)/this.editor.zoom,n=(i.clientY-e.top)/this.editor.zoom,s=200,r=64,a=13,l=1,d=null!=this.editor.connectionSourceY&&n<this.editor.connectionSourceY;let c;c=d?n+l-r:n-l+a,this.editor.connectionPlaceholder={position:{left:o-s/2,top:c},visible:!0,dragUp:d}}}return void this.editor.requestUpdate()}if(!this.isMouseDown||!this.editor.currentDragItem)return;this.lastPointerPos={clientX:i.clientX,clientY:i.clientY};const o=i.clientX-this.dragStartPos.x+this.autoScrollDeltaX,n=i.clientY-this.dragStartPos.y+this.autoScrollDeltaY,s=Math.sqrt(o*o+n*n);!this.editor.isDragging&&s>5&&(this.editor.isDragging=!0,this.startAutoScroll()),this.editor.isDragging&&(t.preventDefault(),this.updateDragPositions())}handleTouchEnd(t){if(this.isTwoFingerPanning){if(0===t.touches.length){const t=this.twoFingerDidPan,e=this.twoFingerOnCanvas,i=this.twoFingerStartMidX,o=this.twoFingerStartMidY;this.isTwoFingerPanning=!1,this.twoFingerOnCanvas=!1,this.twoFingerDidPan=!1,!t&&e&&this.editor.showContextMenuAt(i,o)}return}const e=t.changedTouches[0];if(this.canvasMouseDown&&this.editor.isSelecting)return this.editor.isSelecting=!1,this.editor.selectionBox=null,this.canvasMouseDown=!1,void this.editor.requestUpdate();if(!this.canvasMouseDown||this.editor.isSelecting){if(this.editor.plumber.connectionDragging){if(e){const t=this.editor.findTargetNodeAt(e.clientX,e.clientY);t&&(this.editor.targetId=t.getAttribute("uuid"),this.editor.isValidTarget=this.editor.targetId!==this.editor.dragFromNodeId)}}else if(this.isMouseDown&&this.editor.currentDragItem){if(this.stopAutoScroll(),this.editor.isDragging&&e){const t=(e.clientX-this.dragStartPos.x+this.autoScrollDeltaX)/this.editor.zoom,i=(e.clientY-this.dragStartPos.y+this.autoScrollDeltaY)/this.editor.zoom,o=this.editor.selectedItems.has(this.editor.currentDragItem.uuid)&&this.editor.selectedItems.size>1?Array.from(this.editor.selectedItems):[this.editor.currentDragItem.uuid],n={};o.forEach(e=>{const o=this.editor.definition.nodes.find(t=>t.uuid===e)?"node":"sticky",s=this.getPosition(e,o);if(s){const o=s.left+t,r=s.top+i,a=bu(o),l=bu(r);n[e]={left:a,top:l};const d=this.editor.querySelector(`[uuid="${e}"]`);d&&(d.classList.remove("dragging"),d.style.left=`${a}px`,d.style.top=`${l}px`)}}),Object.keys(n).length>0&&($d().getState().updateCanvasPositions(n),setTimeout(()=>{this.editor.checkCollisionsAndReflow(o),this.editor.plumber.repaintEverything()},0)),this.editor.selectedItems.clear()}this.editor.isDragging=!1,this.isMouseDown=!1,this.editor.currentDragItem=null,this.canvasMouseDown=!1,this.autoScrollDeltaX=0,this.autoScrollDeltaY=0,this.lastPointerPos=null}}else this.canvasMouseDown=!1}handleTouchCancel(){if(this.isTwoFingerPanning=!1,this.editor.isSelecting=!1,this.editor.selectionBox=null,this.canvasMouseDown=!1,this.editor.isDragging&&this.editor.currentDragItem){(this.editor.selectedItems.has(this.editor.currentDragItem.uuid)&&this.editor.selectedItems.size>1?Array.from(this.editor.selectedItems):[this.editor.currentDragItem.uuid]).forEach(t=>{const e=this.editor.querySelector(`[uuid="${t}"]`);e&&e.classList.remove("dragging")})}this.stopAutoScroll(),this.editor.isDragging=!1,this.isMouseDown=!1,this.editor.currentDragItem=null,this.autoScrollDeltaX=0,this.autoScrollDeltaY=0,this.lastPointerPos=null,document.querySelectorAll("temba-flow-node").forEach(t=>{t.classList.remove("connection-target-valid","connection-target-invalid")}),this.editor.connectionPlaceholder=null,this.editor.requestUpdate()}}class Lm extends Be{constructor(){super(...arguments),this.color="#6B7280",this.order=0,this.top=100,this.hidden=!1,this.saving=!1,this.active=!1}static get styles(){return a`
9940
+ ></div>`}handleCanvasTouchStart(t){var e;this.markTouchDevice();const i=t.touches[0];if(!i)return;const o=t.target;if(o.closest(".draggable"))return;if("canvas"!==o.id&&"grid"!==o.id)return;if(t.touches.length>=2)return this.canvasMouseDown=!1,this.editor.isSelecting=!1,this.editor.selectionBox=null,this.isTwoFingerPanning=!0,this.twoFingerOnCanvas=!0,this.twoFingerDidPan=!1,this.twoFingerStartMidX=(t.touches[0].clientX+t.touches[1].clientX)/2,this.twoFingerStartMidY=(t.touches[0].clientY+t.touches[1].clientY)/2,this.lastPanX=this.twoFingerStartMidX,void(this.lastPanY=this.twoFingerStartMidY);if(this.editor.isReadOnly())return;this.canvasMouseDown=!0,this.dragStartPos={x:i.clientX,y:i.clientY};const n=null===(e=this.editor.querySelector("#canvas"))||void 0===e?void 0:e.getBoundingClientRect();if(n){this.editor.selectedItems.clear();const t=(i.clientX-n.left)/this.editor.zoom,e=(i.clientY-n.top)/this.editor.zoom;this.editor.selectionBox={startX:t,startY:e,endX:t,endY:e}}t.preventDefault()}handleMouseMove(t){if(this.canvasMouseDown&&!this.isMouseDown)return this.editor.isSelecting=!0,this.updateSelectionBox(t),void this.editor.requestUpdate();if(this.editor.plumber.connectionDragging){this.activeDragIsTouch=!1,this.lastPointerPos={clientX:t.clientX,clientY:t.clientY},this.startAutoScroll();const e=document.querySelector("temba-flow-node:hover");if(document.querySelectorAll("temba-flow-node").forEach(t=>{t.classList.remove("connection-target-valid","connection-target-invalid")}),e)this.editor.targetId=e.getAttribute("uuid"),this.editor.isValidTarget=this.editor.targetId!==this.editor.dragFromNodeId,this.editor.isValidTarget?e.classList.add("connection-target-valid"):e.classList.add("connection-target-invalid"),this.editor.connectionPlaceholder=null;else{this.editor.targetId=null,this.editor.isValidTarget=!0;const e=this.editor.querySelector("#canvas");if(e){const i=e.getBoundingClientRect(),o=(t.clientX-i.left)/this.editor.zoom,n=(t.clientY-i.top)/this.editor.zoom,s=200,r=64,a=13,l=1,d=null!=this.editor.connectionSourceY&&n<this.editor.connectionSourceY;let c;c=d?n+l-r:n-l+a,this.editor.connectionPlaceholder={position:{left:o-s/2,top:c},visible:!0,dragUp:d}}}this.editor.requestUpdate()}if(!this.isMouseDown||!this.editor.currentDragItem)return;this.lastPointerPos={clientX:t.clientX,clientY:t.clientY};const e=t.clientX-this.dragStartPos.x+this.autoScrollDeltaX,i=t.clientY-this.dragStartPos.y+this.autoScrollDeltaY,o=Math.sqrt(e*e+i*i);!this.editor.isDragging&&o>5&&(this.editor.isDragging=!0,this.startAutoScroll(),this.originalDragItem={...this.editor.currentDragItem},this.originalSelectedItems=new Set(this.editor.selectedItems),this.shiftDragCopy||t.shiftKey?(this.performShiftDragCopy(),this.shiftDragCopy=!1):this.showDragHint()),this.editor.isDragging&&this.updateDragPositions()}performShiftDragCopy(){var t,e,i,o,n;if(!this.originalDragItem)return;const s=(null===(t=this.originalSelectedItems)||void 0===t?void 0:t.has(this.originalDragItem.uuid))&&(null!==(i=null===(e=this.originalSelectedItems)||void 0===e?void 0:e.size)&&void 0!==i?i:0)>1?Array.from(this.originalSelectedItems):[this.originalDragItem.uuid];if(0===s.length)return;const r=$d().getState().duplicateNodes(s);for(const t of s){const e=r[t];e&&!this.editor.copiedItemUuids.includes(e)&&this.editor.copiedItemUuids.push(e)}this.currentDragIsCopy=!0;for(const t of s){const e=this.editor.querySelector(`[uuid="${t}"]`),i="TEMBA-FLOW-NODE"===(null==e?void 0:e.tagName)?"node":"sticky",o=this.getPosition(t,i);e&&o&&(e.style.left=`${o.left}px`,e.style.top=`${o.top}px`)}this.editor.plumber.revalidate(s);for(const t of s){const e=this.editor.querySelector(`[uuid="${t}"]`);e&&(e.offsetHeight,e.classList.remove("dragging"))}const a=r[this.originalDragItem.uuid];if(a&&(this.editor.currentDragItem={...this.originalDragItem,uuid:a}),(null!==(n=null===(o=this.originalSelectedItems)||void 0===o?void 0:o.size)&&void 0!==n?n:0)>1){const t=new Set;for(const e of this.originalSelectedItems){const i=r[e];t.add(i||e)}this.editor.selectedItems=t}}markCopyElements(){for(const t of this.editor.copiedItemUuids){const e=this.editor.querySelector(`[uuid="${t}"]`);null==e||e.classList.add("drag-copy")}}revertShiftDragCopy(){if(this.originalDragItem){if(this.editor.copiedItemUuids.length>0){const t=this.editor.copiedItemUuids.filter(t=>this.editor.definition.nodes.some(e=>e.uuid===t)),e=this.editor.copiedItemUuids.filter(t=>{var e,i;return null===(i=null===(e=this.editor.definition._ui)||void 0===e?void 0:e.stickies)||void 0===i?void 0:i[t]});t.length>0&&$d().getState().removeNodes(t),e.length>0&&$d().getState().removeStickyNotes(e),this.editor.copiedItemUuids=[]}this.currentDragIsCopy=!1,$d().getState().setDirtyDate(null),this.editor.currentDragItem={...this.originalDragItem},this.originalSelectedItems&&(this.editor.selectedItems=new Set(this.originalSelectedItems))}}updateDragPositions(){if(!this.editor.currentDragItem||!this.lastPointerPos)return;const t=(this.lastPointerPos.clientX-this.dragStartPos.x+this.autoScrollDeltaX)/this.editor.zoom,e=(this.lastPointerPos.clientY-this.dragStartPos.y+this.autoScrollDeltaY)/this.editor.zoom,i=this.editor.selectedItems.has(this.editor.currentDragItem.uuid)&&this.editor.selectedItems.size>1?Array.from(this.editor.selectedItems):[this.editor.currentDragItem.uuid];i.forEach(i=>{const o=this.editor.querySelector(`[uuid="${i}"]`);if(o){const n="TEMBA-FLOW-NODE"===o.tagName?"node":"sticky",s=this.getPosition(i,n);s&&(o.style.left=`${s.left+t}px`,o.style.top=`${s.top+e}px`,o.classList.add("dragging"),this.currentDragIsCopy&&o.classList.add("drag-copy"))}}),this.editor.plumber.revalidate(i)}startAutoScroll(){if(null!==this.autoScrollAnimationId)return;const t=this.editor.querySelector("#editor");if(!t)return;const e=()=>{var i,o,n;if(!this.editor.isDragging&&!(null===(i=this.editor.plumber)||void 0===i?void 0:i.connectionDragging)||!this.lastPointerPos)return void(this.autoScrollAnimationId=null);const s=t.getBoundingClientRect(),r=this.lastPointerPos.clientX,a=this.lastPointerPos.clientY,l=this.activeDragIsTouch?40:150;let d=0,c=0;const h=r-s.left;if(h<l){const t=h<0;d=-Math.min(1,1-h/l)*(15*(t?5:1))}const u=s.right-r;if(u<l){const t=u<0;d=Math.min(1,1-u/l)*(15*(t?5:1))}const p=a-s.top;if(p<l){const t=p<0;c=-Math.min(1,1-p/l)*(15*(t?5:1))}const m=s.bottom-a;if(m<l){const t=m<0;c=Math.min(1,1-m/l)*(15*(t?5:1))}if(0!==d||0!==c){const e=t.scrollLeft,i=t.scrollTop;if(d>0||c>0){const e=(t.scrollLeft+t.clientWidth+d)/this.editor.zoom,i=(t.scrollTop+t.clientHeight+c)/this.editor.zoom;null===(n=null===(o=$d())||void 0===o?void 0:o.getState())||void 0===n||n.expandCanvas(e,i)}t.scrollLeft+=d,t.scrollTop+=c;const s=t.scrollLeft-e,r=t.scrollTop-i;this.autoScrollDeltaX+=s,this.autoScrollDeltaY+=r,0===s&&0===r||this.updateDragPositions()}this.autoScrollAnimationId=requestAnimationFrame(e)};this.autoScrollAnimationId=requestAnimationFrame(e)}stopAutoScroll(){null!==this.autoScrollAnimationId&&(cancelAnimationFrame(this.autoScrollAnimationId),this.autoScrollAnimationId=null)}handleMouseUp(t){if(this.canvasMouseDown&&this.editor.isSelecting)return this.editor.isSelecting=!1,this.editor.selectionBox=null,this.canvasMouseDown=!1,void this.editor.requestUpdate();if(!this.canvasMouseDown||this.editor.isSelecting){if(this.isMouseDown&&this.editor.currentDragItem){if(this.stopAutoScroll(),this.editor.isDragging){const e=(t.clientX-this.dragStartPos.x+this.autoScrollDeltaX)/this.editor.zoom,i=(t.clientY-this.dragStartPos.y+this.autoScrollDeltaY)/this.editor.zoom,o=this.editor.selectedItems.has(this.editor.currentDragItem.uuid)&&this.editor.selectedItems.size>1?Array.from(this.editor.selectedItems):[this.editor.currentDragItem.uuid],n={};o.forEach(t=>{const o=this.editor.definition.nodes.find(e=>e.uuid===t)?"node":"sticky",s=this.getPosition(t,o);if(s){const o=s.left+e,r=s.top+i,a=bu(o),l=bu(r),d={left:a,top:l};n[t]=d;const c=this.editor.querySelector(`[uuid="${t}"]`);c&&(c.classList.remove("dragging","drag-copy"),c.style.left=`${a}px`,c.style.top=`${l}px`)}}),Object.keys(n).length>0&&(this.currentDragIsCopy&&(this.editor.pendingTimer.pending=!0,this.editor.capturePositionsOnce()),$d().getState().updateCanvasPositions(n),setTimeout(()=>{this.editor.checkCollisionsAndReflow(o),this.editor.plumber.repaintEverything()},0)),this.currentDragIsCopy&&this.editor.pendingTimer.start(),this.editor.selectedItems.clear()}this.hideDragHint(),this.editor.isDragging=!1,this.isMouseDown=!1,this.shiftDragCopy=!1,this.currentDragIsCopy=!1,this.editor.currentDragItem=null,this.originalDragItem=null,this.originalSelectedItems=null,this.canvasMouseDown=!1,this.autoScrollDeltaX=0,this.autoScrollDeltaY=0,this.lastPointerPos=null}}else this.canvasMouseDown=!1}handleTouchMove(t){var e;if(t.touches.length>=2){t.preventDefault();const e=(t.touches[0].clientX+t.touches[1].clientX)/2,i=(t.touches[0].clientY+t.touches[1].clientY)/2;if(this.isTwoFingerPanning){const t=this.lastPanX-e,o=this.lastPanY-i;(Math.abs(t)>2||Math.abs(o)>2)&&(this.twoFingerDidPan=!0);const n=this.editor.querySelector("#editor");n&&n.scrollBy(t,o)}return this.canvasMouseDown=!1,this.editor.isSelecting=!1,this.editor.selectionBox=null,this.isTwoFingerPanning=!0,this.lastPanX=e,void(this.lastPanY=i)}const i=t.touches[0];if(!i)return;if(this.canvasMouseDown&&!this.isMouseDown){t.preventDefault(),this.editor.isSelecting=!0;const o=null===(e=this.editor.querySelector("#canvas"))||void 0===e?void 0:e.getBoundingClientRect();return o&&this.editor.selectionBox&&(this.editor.selectionBox={...this.editor.selectionBox,endX:(i.clientX-o.left)/this.editor.zoom,endY:(i.clientY-o.top)/this.editor.zoom},this.updateSelectedItemsFromBox()),void this.editor.requestUpdate()}if(this.editor.plumber.connectionDragging){t.preventDefault();const e=this.editor.findTargetNodeAt(i.clientX,i.clientY);if(document.querySelectorAll("temba-flow-node").forEach(t=>{t.classList.remove("connection-target-valid","connection-target-invalid")}),e)this.editor.targetId=e.getAttribute("uuid"),this.editor.isValidTarget=this.editor.targetId!==this.editor.dragFromNodeId,this.editor.isValidTarget?e.classList.add("connection-target-valid"):e.classList.add("connection-target-invalid"),this.editor.connectionPlaceholder=null;else{this.editor.targetId=null,this.editor.isValidTarget=!0;const t=this.editor.querySelector("#canvas");if(t){const e=t.getBoundingClientRect(),o=(i.clientX-e.left)/this.editor.zoom,n=(i.clientY-e.top)/this.editor.zoom,s=200,r=64,a=13,l=1,d=null!=this.editor.connectionSourceY&&n<this.editor.connectionSourceY;let c;c=d?n+l-r:n-l+a,this.editor.connectionPlaceholder={position:{left:o-s/2,top:c},visible:!0,dragUp:d}}}return void this.editor.requestUpdate()}if(!this.isMouseDown||!this.editor.currentDragItem)return;this.lastPointerPos={clientX:i.clientX,clientY:i.clientY};const o=i.clientX-this.dragStartPos.x+this.autoScrollDeltaX,n=i.clientY-this.dragStartPos.y+this.autoScrollDeltaY,s=Math.sqrt(o*o+n*n);!this.editor.isDragging&&s>5&&(this.editor.isDragging=!0,this.startAutoScroll()),this.editor.isDragging&&(t.preventDefault(),this.updateDragPositions())}handleTouchEnd(t){if(this.isTwoFingerPanning){if(0===t.touches.length){const t=this.twoFingerDidPan,e=this.twoFingerOnCanvas,i=this.twoFingerStartMidX,o=this.twoFingerStartMidY;this.isTwoFingerPanning=!1,this.twoFingerOnCanvas=!1,this.twoFingerDidPan=!1,!t&&e&&this.editor.showContextMenuAt(i,o)}return}const e=t.changedTouches[0];if(this.canvasMouseDown&&this.editor.isSelecting)return this.editor.isSelecting=!1,this.editor.selectionBox=null,this.canvasMouseDown=!1,void this.editor.requestUpdate();if(!this.canvasMouseDown||this.editor.isSelecting){if(this.editor.plumber.connectionDragging){if(e){const t=this.editor.findTargetNodeAt(e.clientX,e.clientY);t&&(this.editor.targetId=t.getAttribute("uuid"),this.editor.isValidTarget=this.editor.targetId!==this.editor.dragFromNodeId)}}else if(this.isMouseDown&&this.editor.currentDragItem){if(this.stopAutoScroll(),this.editor.isDragging&&e){const t=(e.clientX-this.dragStartPos.x+this.autoScrollDeltaX)/this.editor.zoom,i=(e.clientY-this.dragStartPos.y+this.autoScrollDeltaY)/this.editor.zoom,o=this.editor.selectedItems.has(this.editor.currentDragItem.uuid)&&this.editor.selectedItems.size>1?Array.from(this.editor.selectedItems):[this.editor.currentDragItem.uuid],n={};o.forEach(e=>{const o=this.editor.definition.nodes.find(t=>t.uuid===e)?"node":"sticky",s=this.getPosition(e,o);if(s){const o=s.left+t,r=s.top+i,a=bu(o),l=bu(r);n[e]={left:a,top:l};const d=this.editor.querySelector(`[uuid="${e}"]`);d&&(d.classList.remove("dragging"),d.style.left=`${a}px`,d.style.top=`${l}px`)}}),Object.keys(n).length>0&&($d().getState().updateCanvasPositions(n),setTimeout(()=>{this.editor.checkCollisionsAndReflow(o),this.editor.plumber.repaintEverything()},0)),this.editor.selectedItems.clear()}this.editor.isDragging=!1,this.isMouseDown=!1,this.editor.currentDragItem=null,this.canvasMouseDown=!1,this.autoScrollDeltaX=0,this.autoScrollDeltaY=0,this.lastPointerPos=null}}else this.canvasMouseDown=!1}handleTouchCancel(){if(this.isTwoFingerPanning=!1,this.editor.isSelecting=!1,this.editor.selectionBox=null,this.canvasMouseDown=!1,this.editor.isDragging&&this.editor.currentDragItem){(this.editor.selectedItems.has(this.editor.currentDragItem.uuid)&&this.editor.selectedItems.size>1?Array.from(this.editor.selectedItems):[this.editor.currentDragItem.uuid]).forEach(t=>{const e=this.editor.querySelector(`[uuid="${t}"]`);e&&e.classList.remove("dragging")})}this.stopAutoScroll(),this.editor.isDragging=!1,this.isMouseDown=!1,this.editor.currentDragItem=null,this.autoScrollDeltaX=0,this.autoScrollDeltaY=0,this.lastPointerPos=null,document.querySelectorAll("temba-flow-node").forEach(t=>{t.classList.remove("connection-target-valid","connection-target-invalid")}),this.editor.connectionPlaceholder=null,this.editor.requestUpdate()}}class Pm extends Be{constructor(){super(...arguments),this.color="#6B7280",this.order=0,this.top=100,this.hidden=!1,this.saving=!1,this.active=!1}static get styles(){return a`
9572
9941
  .tab.hidden {
9573
9942
  transform: translateX(calc(100% + var(--floating-tab-clip, 0px)));
9574
9943
  }
@@ -9656,14 +10025,14 @@ background: #ccc;
9656
10025
  margin-left: 12px;
9657
10026
  opacity: 1;
9658
10027
  }
9659
- `}connectedCallback(){super.connectedCallback(),Lm.allTabs.push(this),Lm.updateAllPositions()}disconnectedCallback(){super.disconnectedCallback();const t=Lm.allTabs.indexOf(this);t>-1&&Lm.allTabs.splice(t,1),Lm.updateAllPositions()}static updateAllPositions(){const t=[...Lm.allTabs].sort((t,e)=>t.order-e.order);t.forEach((t,e)=>{t.top=Lm.START_TOP+e*(Lm.TAB_HEIGHT+Lm.TAB_GAP)})}updated(t){super.updated(t),t.has("hidden")&&this.classList.toggle("hidden",this.hidden),t.has("active")&&Lm.allTabs.forEach(t=>{t!==this&&t.requestUpdate()})}handleClick(){this.fireCustomEvent(Io.ButtonClicked,{action:"toggle"})}static showAllTabs(){Lm.allTabs.forEach(t=>{t.hidden=!1})}static hideAllTabs(){Lm.allTabs.forEach(t=>{t.hidden=!0})}render(){const t=`\n background-color: ${this.color};\n top: ${this.top}px;\n `,e=Lm.allTabs.some(t=>t.active),i=re({tab:!0,hidden:this.hidden,saving:this.saving,active:this.active,subdued:e}),o=this.saving?"progress_spinner":this.icon;return W`
10028
+ `}connectedCallback(){super.connectedCallback(),Pm.allTabs.push(this),Pm.updateAllPositions()}disconnectedCallback(){super.disconnectedCallback();const t=Pm.allTabs.indexOf(this);t>-1&&Pm.allTabs.splice(t,1),Pm.updateAllPositions()}static updateAllPositions(){const t=[...Pm.allTabs].sort((t,e)=>t.order-e.order);t.forEach((t,e)=>{t.top=Pm.START_TOP+e*(Pm.TAB_HEIGHT+Pm.TAB_GAP)})}updated(t){super.updated(t),t.has("hidden")&&this.classList.toggle("hidden",this.hidden),t.has("active")&&Pm.allTabs.forEach(t=>{t!==this&&t.requestUpdate()})}handleClick(){this.fireCustomEvent(Io.ButtonClicked,{action:"toggle"})}static showAllTabs(){Pm.allTabs.forEach(t=>{t.hidden=!1})}static hideAllTabs(){Pm.allTabs.forEach(t=>{t.hidden=!0})}render(){const t=`\n background-color: ${this.color};\n top: ${this.top}px;\n `,e=Pm.allTabs.some(t=>t.active),i=re({tab:!0,hidden:this.hidden,saving:this.saving,active:this.active,subdued:e}),o=this.saving?"progress_spinner":this.icon;return W`
9660
10029
  <div class="${i}" style="${t}" @click=${this.handleClick}>
9661
10030
  <div class="icon-container">
9662
10031
  ${o?W`<temba-icon size="1.5" name="${o}"></temba-icon>`:""}
9663
10032
  </div>
9664
10033
  <div class="label">${this.label}</div>
9665
10034
  </div>
9666
- `}}Lm.TAB_HEIGHT=50,Lm.TAB_GAP=4,Lm.START_TOP=165,Lm.allTabs=[],t([mt({type:String})],Lm.prototype,"icon",void 0),t([mt({type:String})],Lm.prototype,"label",void 0),t([mt({type:String})],Lm.prototype,"color",void 0),t([mt({type:Number})],Lm.prototype,"order",void 0),t([gt()],Lm.prototype,"top",void 0),t([mt({type:Boolean})],Lm.prototype,"hidden",void 0),t([mt({type:Boolean})],Lm.prototype,"saving",void 0),t([mt({type:Boolean})],Lm.prototype,"active",void 0);class Om{constructor(t){this.editor=t,this.zoomInitialized=!1,this.zoomFitted=!1,this.loupeEl=null,this.loupeContentEl=null,this.loupeRAF=null,this.hiddenTitles=[],this.loupeKeyHeld=!1,this.loupeMouseIsDown=!1,this.loupeLastMouse=null,this.loupeCloneTime=0,this.loupeClone=null,this.loupeCursorCanvas={x:0,y:0},this.boundLoupeMouseMove=this.handleLoupeMouseMove.bind(this),this.boundLoupeMouseDown=this.handleLoupeMouseDown.bind(this),this.boundLoupeMouseUp=this.handleLoupeMouseUp.bind(this),this.boundLoupeKeyDown=this.handleLoupeKeyDown.bind(this),this.boundLoupeKeyUp=this.handleLoupeKeyUp.bind(this)}setZoom(t,e){const i=Math.max(.3,Math.min(1,Math.round(100*t)/100));if(i===this.editor.zoom)return;const o=this.editor.querySelector("#editor"),n=this.editor.zoom;if(this.editor.zoom=i,this.editor.plumber.zoom=i,this.zoomFitted=!1,this.editor.requestUpdate(),this.editor.saveFlowSetting("zoom",i),o&&e){const t=o.getBoundingClientRect(),s=e.clientX-t.left,r=e.clientY-t.top,a=(o.scrollLeft+s)/n,l=(o.scrollTop+r)/n;requestAnimationFrame(()=>{o.scrollLeft=a*i-s,o.scrollTop=l*i-r,this.editor.plumber.repaintEverything()})}else requestAnimationFrame(()=>this.editor.plumber.repaintEverything())}zoomIn(){this.setZoom(this.editor.zoom+.05)}zoomOut(){this.setZoom(this.editor.zoom-.05)}zoomToFit(){var t;if(!this.editor.definition||0===this.editor.definition.nodes.length)return;const e=this.editor.querySelector("#editor");if(!e)return;let i=1/0,o=1/0,n=-1/0,s=-1/0;this.editor.definition.nodes.forEach(t=>{var e;const r=null===(e=this.editor.definition._ui)||void 0===e?void 0:e.nodes[t.uuid];if(!(null==r?void 0:r.position))return;const a=this.editor.querySelector(`[id="${t.uuid}"]`);if(!a)return;const l=a.offsetWidth,d=a.offsetHeight;i=Math.min(i,r.position.left),o=Math.min(o,r.position.top),n=Math.max(n,r.position.left+l),s=Math.max(s,r.position.top+d)});const r=(null===(t=this.editor.definition._ui)||void 0===t?void 0:t.stickies)||{};if(Object.entries(r).forEach(([t,e])=>{if(!e.position)return;const r=this.editor.querySelector(`temba-sticky-note[uuid="${t}"]`);if(!r)return;const a=r.offsetWidth,l=r.offsetHeight;i=Math.min(i,e.position.left),o=Math.min(o,e.position.top),n=Math.max(n,e.position.left+a),s=Math.max(s,e.position.top+l)}),i===1/0)return;const a=n-i,l=s-o,d=(e.clientWidth-80)/a,c=(e.clientHeight-80)/l;let h=Math.min(d,c,1);h=Math.max(h,.3),h=Math.round(20*h)/20,this.editor.zoom=h,this.editor.plumber.zoom=h,this.zoomFitted=!0,this.editor.requestUpdate(),this.editor.saveFlowSetting("zoom",h);const u=(i+n)/2+40,p=(o+s)/2+40;requestAnimationFrame(()=>{e.scrollLeft=u*h-e.clientWidth/2,e.scrollTop=p*h-e.clientHeight/2,this.editor.plumber.repaintEverything()})}zoomToFull(){this.setZoom(1)}handleWheel(t){if(!t.ctrlKey&&!t.metaKey)return;t.preventDefault();const e=t.deltaY>0?-.05:.05;this.setZoom(this.editor.zoom+e,{clientX:t.clientX,clientY:t.clientY})}restoreInitialZoomFromSettings(){if(this.zoomInitialized||!this.editor.definition)return;const t=this.editor.getFlowSetting("zoom");if("number"==typeof t&&Number.isFinite(t)){const e=Math.max(.3,Math.min(1,Math.round(100*t)/100));this.editor.zoom=e,this.editor.plumber&&(this.editor.plumber.zoom=e)}this.zoomInitialized=!0,this.editor.requestUpdate()}updateZoomControlPositioning(){requestAnimationFrame(()=>{const t=this.editor.querySelector("#editor");if(t){const e=Math.max(t.offsetWidth-t.clientWidth,0);document.documentElement.style.setProperty("--floating-tab-clip",`${e}px`)}const e=this.editor.querySelector(".editor-toolbar");if(e){const t=e.getBoundingClientRect();Lm.START_TOP=t.bottom+20,Lm.updateAllPositions()}})}initLoupe(){document.addEventListener("mousemove",this.boundLoupeMouseMove),document.addEventListener("keydown",this.boundLoupeKeyDown),document.addEventListener("keyup",this.boundLoupeKeyUp),document.addEventListener("mouseup",this.boundLoupeMouseUp);const t=this.editor.querySelector("#editor");t&&t.addEventListener("mousedown",this.boundLoupeMouseDown,!0)}teardownLoupe(){document.removeEventListener("mousemove",this.boundLoupeMouseMove),document.removeEventListener("keydown",this.boundLoupeKeyDown),document.removeEventListener("keyup",this.boundLoupeKeyUp),document.removeEventListener("mouseup",this.boundLoupeMouseUp);const t=this.editor.querySelector("#editor");t&&t.removeEventListener("mousedown",this.boundLoupeMouseDown,!0),this.hideLoupe()}setLoupeElements(t,e){this.loupeEl=t,this.loupeContentEl=e}isDialogOrMenuOpen(){var t;if(this.editor.editingNode||this.editor.editingAction)return!0;if(null===(t=this.editor.deleteDialog)||void 0===t?void 0:t.open)return!0;const e=this.editor.querySelector("temba-canvas-menu");return!!(null==e?void 0:e.open)}get isZoomFitted(){return this.zoomFitted}get isZoomInitialized(){return this.zoomInitialized}handleLoupeKeyDown(t){"a"===t.key.toLowerCase()&&t.metaKey&&t.ctrlKey&&(t.preventDefault(),this.loupeKeyHeld=!0,this.loupeLastMouse&&this.handleLoupeMouseMove(this.loupeLastMouse))}handleLoupeKeyUp(t){this.loupeKeyHeld&&("a"!==t.key&&"Meta"!==t.key&&"Control"!==t.key||(this.loupeKeyHeld=!1,this.hideLoupe()))}handleLoupeMouseDown(){this.loupeMouseIsDown=!0,this.hideLoupe()}handleLoupeMouseUp(){this.loupeMouseIsDown=!1}handleLoupeMouseMove(t){var e;if(this.loupeLastMouse={clientX:t.clientX,clientY:t.clientY},!this.loupeKeyHeld||this.loupeMouseIsDown||this.editor.isDragging||this.editor.isSelecting||(null===(e=this.editor.plumber)||void 0===e?void 0:e.connectionDragging)||this.isDialogOrMenuOpen())return void this.hideLoupe();const i=this.editor.querySelector("#editor");if(!i)return;const o=i.getBoundingClientRect();t.clientX<o.left||t.clientX>o.right||t.clientY<o.top||t.clientY>o.bottom?this.hideLoupe():(this.loupeRAF&&cancelAnimationFrame(this.loupeRAF),this.loupeRAF=requestAnimationFrame(()=>{this.updateLoupe(t.clientX,t.clientY)}))}hideLoupe(){this.loupeEl&&this.loupeEl.classList.remove("visible"),this.restoreTitles(),this.loupeClone&&(this.loupeClone.remove(),this.loupeClone=null),this.loupeRAF&&(cancelAnimationFrame(this.loupeRAF),this.loupeRAF=null)}suppressTitles(){this.hiddenTitles=[];const t=this.editor.querySelector("#canvas");if(t){for(const e of t.querySelectorAll("[title]"))this.hiddenTitles.push({el:e,title:e.getAttribute("title")}),e.removeAttribute("title");for(const e of t.querySelectorAll("temba-canvas-node, temba-sticky-note"))if(e.shadowRoot)for(const t of e.shadowRoot.querySelectorAll("[title]"))this.hiddenTitles.push({el:t,title:t.getAttribute("title")}),t.removeAttribute("title")}}restoreTitles(){for(const{el:t,title:e}of this.hiddenTitles)t.setAttribute("title",e);this.hiddenTitles=[]}rebuildLoupeClone(t,e,i,o){const n=this.loupeContentEl;if(!n)return;this.loupeClone&&this.loupeClone.remove();const s=document.createElement("div");s.className="loupe-clone",s.style.width=`${t.scrollWidth}px`,s.style.height=`${t.scrollHeight}px`;const r=50,a=t.querySelectorAll("[data-node-uuid]");for(const t of a){const n=t,a=parseFloat(n.style.left)||0,l=parseFloat(n.style.top)||0,d=n.offsetWidth,c=n.offsetHeight;if(a+d<e-o-r||a>e+o+r||l+c<i-o-r||l>i+o+r)continue;const h=document.createElement("div");h.className=n.className,h.style.cssText=n.style.cssText,h.innerHTML=n.innerHTML,s.appendChild(h)}const l=t.querySelectorAll("svg.plumb-connector");for(const t of l)s.appendChild(t.cloneNode(!0));const d=t.querySelectorAll(".activity-overlay");for(const t of d)s.appendChild(t.cloneNode(!0));const c=t.querySelectorAll("temba-sticky-note");for(const t of c){const n=t,a=n.offsetWidth,l=n.offsetHeight,d=parseFloat(n.style.left)||0,c=parseFloat(n.style.top)||0;if(d+a<e-o-r||d>e+o+r||c+l<i-o-r||c>i+o+r)continue;if(!n.shadowRoot)continue;const h=document.createElement("div");h.className=n.className,h.style.cssText=n.style.cssText,h.classList.add("loupe-sticky");const u=n.shadowRoot.adoptedStyleSheets;let p="";for(const t of u)for(const e of t.cssRules){const t=e.cssText;if(t.startsWith(":host"))p+=t.replace(/:host/g,".loupe-sticky")+"\n";else{const e=t.indexOf("{");if(-1!==e){p+=`.loupe-sticky ${t.substring(0,e).trim()} ${t.substring(e)}\n`}}}h.innerHTML=`<style>${p}</style>`+n.shadowRoot.innerHTML,s.appendChild(h)}n.appendChild(s),this.loupeClone=s}updateLoupe(t,e){const i=this.loupeEl,o=this.loupeContentEl;if(!i||!o||!this.editor.definition)return;const n=this.editor.querySelector("#canvas");if(!n)return;const s=n.getBoundingClientRect(),r=(t-s.left)/this.editor.zoom,a=(e-s.top)/this.editor.zoom,l=Om.LOUPE_DIAMETER/2,d=Math.min(1.5,2.5*this.editor.zoom),c=l/d;i.style.left=`${t}px`,i.style.top=`${e}px`,i.classList.add("visible"),0===this.hiddenTitles.length&&this.suppressTitles();const h=20*d;o.style.backgroundSize=`${h}px ${h}px`,o.style.backgroundPosition=`${l-r*d}px ${l-a*d}px`;const u=performance.now(),p=r-this.loupeCursorCanvas.x,m=a-this.loupeCursorCanvas.y,g=Math.abs(p)>.5*c||Math.abs(m)>.5*c;(!this.loupeClone||u-this.loupeCloneTime>Om.LOUPE_CLONE_INTERVAL&&g)&&(this.rebuildLoupeClone(n,r,a,c),this.loupeCloneTime=u,this.loupeCursorCanvas={x:r,y:a}),this.loupeClone&&(this.loupeClone.style.transform=`translate(${l-r*d}px, ${l-a*d}px) scale(${d})`)}}Om.LOUPE_DIAMETER=280,Om.LOUPE_CLONE_INTERVAL=200;const Pm=[];class Rm{constructor(t,e,i,o){this.label=t,this.delay=e,this.host=i,this.onExpire=o,this.unsaved=!1,this.pending=!1,this.resetCount=0,this.timer=null}start(t=!0){this.clearTimer(),this.resetCount++,this.unsaved=!0,this.timer=setTimeout(()=>{this.timer=null,this.unsaved&&(this.unsaved=!1,this.host.requestUpdate(),this.onExpire())},this.delay),t&&this.host.requestUpdate()}dismiss(){this.unsaved=!1,this.clearTimer(),this.host.requestUpdate()}clearTimer(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)}}class Nm extends Be{createRenderRoot(){return this}get dragging(){return this.isDragging}capturePositionsOnce(){var t,e;if(this.pendingPositions)return;const i={};for(const e of this.definition.nodes){const o=null===(t=this.definition._ui)||void 0===t?void 0:t.nodes[e.uuid];(null==o?void 0:o.position)&&(i[e.uuid]={...o.position})}const o=(null===(e=this.definition._ui)||void 0===e?void 0:e.stickies)||{};for(const[t,e]of Object.entries(o))e.position&&(i[t]={...e.position});this.pendingPositions=i}static get styles(){return a`
10035
+ `}}Pm.TAB_HEIGHT=50,Pm.TAB_GAP=4,Pm.START_TOP=165,Pm.allTabs=[],t([mt({type:String})],Pm.prototype,"icon",void 0),t([mt({type:String})],Pm.prototype,"label",void 0),t([mt({type:String})],Pm.prototype,"color",void 0),t([mt({type:Number})],Pm.prototype,"order",void 0),t([gt()],Pm.prototype,"top",void 0),t([mt({type:Boolean})],Pm.prototype,"hidden",void 0),t([mt({type:Boolean})],Pm.prototype,"saving",void 0),t([mt({type:Boolean})],Pm.prototype,"active",void 0);class Rm{constructor(t){this.editor=t,this.zoomInitialized=!1,this.zoomFitted=!1,this.loupeEl=null,this.loupeContentEl=null,this.loupeRAF=null,this.hiddenTitles=[],this.loupeKeyHeld=!1,this.loupeMouseIsDown=!1,this.loupeLastMouse=null,this.loupeCloneTime=0,this.loupeClone=null,this.loupeCursorCanvas={x:0,y:0},this.boundLoupeMouseMove=this.handleLoupeMouseMove.bind(this),this.boundLoupeMouseDown=this.handleLoupeMouseDown.bind(this),this.boundLoupeMouseUp=this.handleLoupeMouseUp.bind(this),this.boundLoupeKeyDown=this.handleLoupeKeyDown.bind(this),this.boundLoupeKeyUp=this.handleLoupeKeyUp.bind(this)}setZoom(t,e){const i=Math.max(.3,Math.min(1,Math.round(100*t)/100));if(i===this.editor.zoom)return;const o=this.editor.querySelector("#editor"),n=this.editor.zoom;if(this.editor.zoom=i,this.editor.plumber.zoom=i,this.zoomFitted=!1,this.editor.requestUpdate(),this.editor.saveFlowSetting("zoom",i),o&&e){const t=o.getBoundingClientRect(),s=e.clientX-t.left,r=e.clientY-t.top,a=(o.scrollLeft+s)/n,l=(o.scrollTop+r)/n;requestAnimationFrame(()=>{o.scrollLeft=a*i-s,o.scrollTop=l*i-r,this.editor.plumber.repaintEverything()})}else requestAnimationFrame(()=>this.editor.plumber.repaintEverything())}zoomIn(){this.setZoom(this.editor.zoom+.05)}zoomOut(){this.setZoom(this.editor.zoom-.05)}zoomToFit(){var t;if(!this.editor.definition||0===this.editor.definition.nodes.length)return;const e=this.editor.querySelector("#editor");if(!e)return;let i=1/0,o=1/0,n=-1/0,s=-1/0;this.editor.definition.nodes.forEach(t=>{var e;const r=null===(e=this.editor.definition._ui)||void 0===e?void 0:e.nodes[t.uuid];if(!(null==r?void 0:r.position))return;const a=this.editor.querySelector(`[id="${t.uuid}"]`);if(!a)return;const l=a.offsetWidth,d=a.offsetHeight;i=Math.min(i,r.position.left),o=Math.min(o,r.position.top),n=Math.max(n,r.position.left+l),s=Math.max(s,r.position.top+d)});const r=(null===(t=this.editor.definition._ui)||void 0===t?void 0:t.stickies)||{};if(Object.entries(r).forEach(([t,e])=>{if(!e.position)return;const r=this.editor.querySelector(`temba-sticky-note[uuid="${t}"]`);if(!r)return;const a=r.offsetWidth,l=r.offsetHeight;i=Math.min(i,e.position.left),o=Math.min(o,e.position.top),n=Math.max(n,e.position.left+a),s=Math.max(s,e.position.top+l)}),i===1/0)return;const a=n-i,l=s-o,d=(e.clientWidth-80)/a,c=(e.clientHeight-80)/l;let h=Math.min(d,c,1);h=Math.max(h,.3),h=Math.round(20*h)/20,this.editor.zoom=h,this.editor.plumber.zoom=h,this.zoomFitted=!0,this.editor.requestUpdate(),this.editor.saveFlowSetting("zoom",h);const u=(i+n)/2+40,p=(o+s)/2+40;requestAnimationFrame(()=>{e.scrollLeft=u*h-e.clientWidth/2,e.scrollTop=p*h-e.clientHeight/2,this.editor.plumber.repaintEverything()})}zoomToFull(){this.setZoom(1)}handleWheel(t){if(!t.ctrlKey&&!t.metaKey)return;t.preventDefault();const e=t.deltaY>0?-.05:.05;this.setZoom(this.editor.zoom+e,{clientX:t.clientX,clientY:t.clientY})}restoreInitialZoomFromSettings(){if(this.zoomInitialized||!this.editor.definition)return;const t=this.editor.getFlowSetting("zoom");if("number"==typeof t&&Number.isFinite(t)){const e=Math.max(.3,Math.min(1,Math.round(100*t)/100));this.editor.zoom=e,this.editor.plumber&&(this.editor.plumber.zoom=e)}this.zoomInitialized=!0,this.editor.requestUpdate()}updateZoomControlPositioning(){requestAnimationFrame(()=>{const t=this.editor.querySelector("#editor");if(t){const e=Math.max(t.offsetWidth-t.clientWidth,0);document.documentElement.style.setProperty("--floating-tab-clip",`${e}px`)}const e=this.editor.querySelector(".editor-toolbar");if(e){const t=e.getBoundingClientRect();Pm.START_TOP=t.bottom+20,Pm.updateAllPositions()}})}initLoupe(){document.addEventListener("mousemove",this.boundLoupeMouseMove),document.addEventListener("keydown",this.boundLoupeKeyDown),document.addEventListener("keyup",this.boundLoupeKeyUp),document.addEventListener("mouseup",this.boundLoupeMouseUp);const t=this.editor.querySelector("#editor");t&&t.addEventListener("mousedown",this.boundLoupeMouseDown,!0)}teardownLoupe(){document.removeEventListener("mousemove",this.boundLoupeMouseMove),document.removeEventListener("keydown",this.boundLoupeKeyDown),document.removeEventListener("keyup",this.boundLoupeKeyUp),document.removeEventListener("mouseup",this.boundLoupeMouseUp);const t=this.editor.querySelector("#editor");t&&t.removeEventListener("mousedown",this.boundLoupeMouseDown,!0),this.hideLoupe()}setLoupeElements(t,e){this.loupeEl=t,this.loupeContentEl=e}isDialogOrMenuOpen(){var t;if(this.editor.editingNode||this.editor.editingAction)return!0;if(null===(t=this.editor.deleteDialog)||void 0===t?void 0:t.open)return!0;const e=this.editor.querySelector("temba-canvas-menu");return!!(null==e?void 0:e.open)}get isZoomFitted(){return this.zoomFitted}get isZoomInitialized(){return this.zoomInitialized}handleLoupeKeyDown(t){"a"===t.key.toLowerCase()&&t.metaKey&&t.ctrlKey&&(t.preventDefault(),this.loupeKeyHeld=!0,this.loupeLastMouse&&this.handleLoupeMouseMove(this.loupeLastMouse))}handleLoupeKeyUp(t){this.loupeKeyHeld&&("a"!==t.key&&"Meta"!==t.key&&"Control"!==t.key||(this.loupeKeyHeld=!1,this.hideLoupe()))}handleLoupeMouseDown(){this.loupeMouseIsDown=!0,this.hideLoupe()}handleLoupeMouseUp(){this.loupeMouseIsDown=!1}handleLoupeMouseMove(t){var e;if(this.loupeLastMouse={clientX:t.clientX,clientY:t.clientY},!this.loupeKeyHeld||this.loupeMouseIsDown||this.editor.isDragging||this.editor.isSelecting||(null===(e=this.editor.plumber)||void 0===e?void 0:e.connectionDragging)||this.isDialogOrMenuOpen())return void this.hideLoupe();const i=this.editor.querySelector("#editor");if(!i)return;const o=i.getBoundingClientRect();t.clientX<o.left||t.clientX>o.right||t.clientY<o.top||t.clientY>o.bottom?this.hideLoupe():(this.loupeRAF&&cancelAnimationFrame(this.loupeRAF),this.loupeRAF=requestAnimationFrame(()=>{this.updateLoupe(t.clientX,t.clientY)}))}hideLoupe(){this.loupeEl&&this.loupeEl.classList.remove("visible"),this.restoreTitles(),this.loupeClone&&(this.loupeClone.remove(),this.loupeClone=null),this.loupeRAF&&(cancelAnimationFrame(this.loupeRAF),this.loupeRAF=null)}suppressTitles(){this.hiddenTitles=[];const t=this.editor.querySelector("#canvas");if(t){for(const e of t.querySelectorAll("[title]"))this.hiddenTitles.push({el:e,title:e.getAttribute("title")}),e.removeAttribute("title");for(const e of t.querySelectorAll("temba-canvas-node, temba-sticky-note"))if(e.shadowRoot)for(const t of e.shadowRoot.querySelectorAll("[title]"))this.hiddenTitles.push({el:t,title:t.getAttribute("title")}),t.removeAttribute("title")}}restoreTitles(){for(const{el:t,title:e}of this.hiddenTitles)t.setAttribute("title",e);this.hiddenTitles=[]}rebuildLoupeClone(t,e,i,o){const n=this.loupeContentEl;if(!n)return;this.loupeClone&&this.loupeClone.remove();const s=document.createElement("div");s.className="loupe-clone",s.style.width=`${t.scrollWidth}px`,s.style.height=`${t.scrollHeight}px`;const r=50,a=t.querySelectorAll("[data-node-uuid]");for(const t of a){const n=t,a=parseFloat(n.style.left)||0,l=parseFloat(n.style.top)||0,d=n.offsetWidth,c=n.offsetHeight;if(a+d<e-o-r||a>e+o+r||l+c<i-o-r||l>i+o+r)continue;const h=document.createElement("div");h.className=n.className,h.style.cssText=n.style.cssText,h.innerHTML=n.innerHTML,s.appendChild(h)}const l=t.querySelectorAll("svg.plumb-connector");for(const t of l)s.appendChild(t.cloneNode(!0));const d=t.querySelectorAll(".activity-overlay");for(const t of d)s.appendChild(t.cloneNode(!0));const c=t.querySelectorAll("temba-sticky-note");for(const t of c){const n=t,a=n.offsetWidth,l=n.offsetHeight,d=parseFloat(n.style.left)||0,c=parseFloat(n.style.top)||0;if(d+a<e-o-r||d>e+o+r||c+l<i-o-r||c>i+o+r)continue;if(!n.shadowRoot)continue;const h=document.createElement("div");h.className=n.className,h.style.cssText=n.style.cssText,h.classList.add("loupe-sticky");const u=n.shadowRoot.adoptedStyleSheets;let p="";for(const t of u)for(const e of t.cssRules){const t=e.cssText;if(t.startsWith(":host"))p+=t.replace(/:host/g,".loupe-sticky")+"\n";else{const e=t.indexOf("{");if(-1!==e){p+=`.loupe-sticky ${t.substring(0,e).trim()} ${t.substring(e)}\n`}}}h.innerHTML=`<style>${p}</style>`+n.shadowRoot.innerHTML,s.appendChild(h)}n.appendChild(s),this.loupeClone=s}updateLoupe(t,e){const i=this.loupeEl,o=this.loupeContentEl;if(!i||!o||!this.editor.definition)return;const n=this.editor.querySelector("#canvas");if(!n)return;const s=n.getBoundingClientRect(),r=(t-s.left)/this.editor.zoom,a=(e-s.top)/this.editor.zoom,l=Rm.LOUPE_DIAMETER/2,d=Math.min(1.5,2.5*this.editor.zoom),c=l/d;i.style.left=`${t}px`,i.style.top=`${e}px`,i.classList.add("visible"),0===this.hiddenTitles.length&&this.suppressTitles();const h=20*d;o.style.backgroundSize=`${h}px ${h}px`,o.style.backgroundPosition=`${l-r*d}px ${l-a*d}px`;const u=performance.now(),p=r-this.loupeCursorCanvas.x,m=a-this.loupeCursorCanvas.y,g=Math.abs(p)>.5*c||Math.abs(m)>.5*c;(!this.loupeClone||u-this.loupeCloneTime>Rm.LOUPE_CLONE_INTERVAL&&g)&&(this.rebuildLoupeClone(n,r,a,c),this.loupeCloneTime=u,this.loupeCursorCanvas={x:r,y:a}),this.loupeClone&&(this.loupeClone.style.transform=`translate(${l-r*d}px, ${l-a*d}px) scale(${d})`)}}Rm.LOUPE_DIAMETER=280,Rm.LOUPE_CLONE_INTERVAL=200;const Nm=[];class Bm{constructor(t,e,i,o){this.label=t,this.delay=e,this.host=i,this.onExpire=o,this.unsaved=!1,this.pending=!1,this.resetCount=0,this.timer=null}start(t=!0){this.clearTimer(),this.resetCount++,this.unsaved=!0,this.timer=setTimeout(()=>{this.timer=null,this.unsaved&&(this.unsaved=!1,this.host.requestUpdate(),this.onExpire())},this.delay),t&&this.host.requestUpdate()}dismiss(){this.unsaved=!1,this.clearTimer(),this.host.requestUpdate()}clearTimer(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)}}class Fm extends Be{createRenderRoot(){return this}get dragging(){return this.isDragging}capturePositionsOnce(){var t,e;if(this.pendingPositions)return;const i={};for(const e of this.definition.nodes){const o=null===(t=this.definition._ui)||void 0===t?void 0:t.nodes[e.uuid];(null==o?void 0:o.position)&&(i[e.uuid]={...o.position})}const o=(null===(e=this.definition._ui)||void 0===e?void 0:e.stickies)||{};for(const[t,e]of Object.entries(o))e.position&&(i[t]={...e.position});this.pendingPositions=i}static get styles(){return a`
9667
10036
  #editor-container {
9668
10037
  position: relative;
9669
10038
  flex: 1;
@@ -10470,7 +10839,7 @@ background: #ccc;
10470
10839
  animation-timing-function: linear;
10471
10840
  animation-fill-mode: forwards;
10472
10841
  }
10473
- `}constructor(){super(),this.saveTimer=null,this.flowType="message",this.features=[],this.activityTimer=null,this.activityInterval=100,this.isDragging=!1,this.currentDragItem=null,this.selectedItems=new Set,this.isSelecting=!1,this.selectionBox=null,this.targetId=null,this.sourceId=null,this.dragFromNodeId=null,this.originalConnectionTargetId=null,this.isValidTarget=!0,this.connectionSourceX=null,this.connectionSourceY=null,this.issuesWindowHidden=!0,this.revisionsWindowHidden=!0,this.viewingRevision=!1,this.isSaving=!1,this.saveError=null,this.zoom=1,this._suppressDirtySave=!1,this.savePromise=null,this.pendingTimer=new Rm("Unsaved Changes",5e3,this,()=>{this.pendingPositions=null,this.copiedItemUuids=[],this.saveChanges()}),this.pendingPositions=null,this.copiedItemUuids=[],this.deleteDialog=null,this.dirtyAdapter={dirtyMessage:"Your flow is still saving. If you leave now, your latest changes may be lost.",markClean:()=>{}},this.boundBeforeUnload=t=>{t.preventDefault()},this.editingNode=null,this.editingNodeUI=null,this.editingAction=null,this.dialogOrigin=null,this.showMessageTable=!1,this.isCreatingNewNode=!1,this.pendingNodePosition=null,this.canvasDropPreview=null,this.addActionToNodeUuid=null,this.actionDragTargetNodeUuid=null,this.previousActionDragTargetNodeUuid=null,this.isActionExternalDrag=!1,this.actionDragIsCopy=!1,this.actionDragLastDetail=null,this.connectionPlaceholder=null,this.pendingCanvasConnection=null,this.boundCanvasContextMenu=this.handleCanvasContextMenu.bind(this),this.boundWheel=t=>this.zoomManager.handleWheel(t),this.boundWindowResize=()=>this.zoomManager.updateZoomControlPositioning(),this.flushSave=async()=>{const t=this.definition?{...this.definition}:null;this.pendingTimer.unsaved&&(this.pendingPositions=null,this.copiedItemUuids=[],this.pendingTimer.dismiss()),null!==this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.savePromise&&await this.savePromise,t&&this.dirtyDate&&await this.saveChanges(t)},this.editForceBase=!1,this.dragManager=new Im(this),this.zoomManager=new Om(this)}firstUpdated(t){var e,i,o;super.firstUpdated(t),this.plumber=new Tm(this.querySelector("#canvas"),this),this.plumber.zoom=this.zoom,this.setupGlobalEventListeners(),null===(e=$d())||void 0===e||e.getState().setFlushSave(this.flushSave),Sd.getState().setFeatures(this.features),navigator.maxTouchPoints>0&&(null===(i=this.querySelector("#canvas"))||void 0===i||i.classList.add("touch-device"),null===(o=this.querySelector("#editor"))||void 0===o||o.classList.add("touch-device")),this.zoomManager.updateZoomControlPositioning(),this.zoomManager.setLoupeElements(this.querySelector("#loupe"),this.querySelector("#loupe-content")),this.zoomManager.initLoupe(),t.has("flow")&&this.flow&&setTimeout(()=>{this.isConnected&&this.flow&&$d().getState().fetchRevision(`/flow/revisions/${this.flow}`)},0),this.plumber.on("connection:drag",t=>{this.dragFromNodeId=t.data.nodeId,this.sourceId=t.sourceId,this.connectionSourceX=t.sourceX,this.connectionSourceY=t.sourceY,this.originalConnectionTargetId=t.target.id}),this.plumber.on("connection:abort",t=>{this.makeConnection(t)}),this.plumber.on("connection:detach",t=>{this.makeConnection(t)})}makeConnection(t){if(this.sourceId&&this.targetId&&this.isValidTarget)t.target.id===this.targetId?this.plumber.connectIds(this.dragFromNodeId,this.sourceId,this.targetId):$d().getState().updateConnection(this.dragFromNodeId,this.sourceId,this.targetId);else if(this.connectionPlaceholder&&this.connectionPlaceholder.visible&&this.sourceId){const t={left:bu(this.connectionPlaceholder.position.left),top:bu(this.connectionPlaceholder.position.top)},e=!!this.connectionPlaceholder.dragUp;this.connectionPlaceholder.position=t,this.pendingCanvasConnection={fromNodeId:this.dragFromNodeId,exitId:this.sourceId,position:t};const i=this.querySelector("#canvas");if(i){const o=i.getBoundingClientRect(),n=o.left+t.left*this.zoom-40,s=e?o.top+t.top*this.zoom+74:o.top+t.top*this.zoom+80,r=this.querySelector("temba-canvas-menu");r&&r.show(n,s,{x:t.left,y:t.top},!1,!1,"message"===this.flowType)}return void this.requestUpdate()}document.querySelectorAll("temba-flow-node").forEach(t=>{t.classList.remove("connection-target-valid","connection-target-invalid")}),this.pendingCanvasConnection||(this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null),this.targetId=null,this.isValidTarget=!0}willUpdate(t){var e;super.willUpdate(t),t.has("definition")&&((null===(e=this.definition)||void 0===e?void 0:e.type)&&(this.flowType=this.getFlowTypeFromDefinition(this.definition.type)),this.zoomManager.restoreInitialZoomFromSettings()),t.has("dirtyDate")&&this.dirtyDate&&(this.pendingTimer.pending?(this.pendingTimer.pending=!1,this._suppressDirtySave=!0):this.pendingTimer.unsaved?(this.pendingTimer.start(!1),this._suppressDirtySave=!0):this.isSaving=!0)}setSimulatorTabHidden(t){var e;const i=document.querySelector("temba-simulator"),o=null===(e=null==i?void 0:i.shadowRoot)||void 0===e?void 0:e.querySelector("#phone-tab");o&&(o.hidden=t)}updated(t){var e;if(super.updated(t),t.has("features")&&Sd.getState().setFeatures(this.features),t.has("revisionsWindowHidden")&&this.setSimulatorTabHidden(!this.revisionsWindowHidden),t.has("canvasSize")&&this.zoomManager.updateZoomControlPositioning(),t.has("showMessageTable")&&!this.showMessageTable&&this.plumber&&requestAnimationFrame(()=>{const t=this.querySelector("#canvas");t&&(this.plumber.setContainer(t),this.plumber.repaintEverything(),t.addEventListener("contextmenu",this.boundCanvasContextMenu))}),t.has("showMessageTable")&&this.zoomManager.updateZoomControlPositioning(),t.has("definition")&&(setTimeout(()=>this.updateCanvasSize(),0),(null===(e=this.definition)||void 0===e?void 0:e.uuid)&&this.startActivityFetching()),t.has("simulatorActive")&&(this.simulatorActive?(this.closeFloatingWindows(),this.stopActivityFetching()):(this.activityInterval=100,this.startActivityFetching())),t.has("activityData")&&this.plumber&&this.plumber.setActivityData(this.activityData),t.has("dirtyDate")&&this.dirtyDate&&(this._suppressDirtySave?this._suppressDirtySave=!1:this.debouncedSave()),t.has("isSaving")){const t=document.querySelector("temba-store");this.isSaving?(window.addEventListener("beforeunload",this.boundBeforeUnload),(null==t?void 0:t.markDirty)&&t.markDirty(this.dirtyAdapter)):(window.removeEventListener("beforeunload",this.boundBeforeUnload),(null==t?void 0:t.markClean)&&t.markClean(this.dirtyAdapter))}t.has("saveError")&&this.saveError&&(this.showSaveErrorDialog(this.saveError),setTimeout(()=>{this.saveError=null},0))}getFlowTypeFromDefinition(t){return"voice"===t?"voice":"messaging_background"===t||"messaging_offline"===t?"background":"message"}debouncedSave(){null!==this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{if(this.pendingTimer.unsaved)return void(this.saveTimer=null);(new Date).getTime()-this.dirtyDate.getTime()>=2e3?(this.saveChanges(),this.saveTimer=null):this.debouncedSave()},2e3)}definitionForSave(t){return{...t,_ui:{...t._ui,editor:uu}}}saveChanges(t){const e=this.definitionForSave(t||this.definition);this.isSaving=!0;const i=$d().postJSON(`/flow/revisions/${this.flow}/`,e).then(t=>{var e;if(t.status<200||t.status>=300)this.saveError=this.extractErrorMessage(t);else{if(t.json){const i=$d().getState();t.json.info&&i.setFlowInfo(t.json.info),void 0!==(null===(e=t.json.revision)||void 0===e?void 0:e.revision)&&i.setRevision(t.json.revision.revision)}$d().getState().setDirtyDate(null)}}).catch(t=>{console.error("Failed to save flow:",t),t instanceof Response?this.saveError=`Server error (${t.status}). Your changes have not been saved.`:this.saveError="Unable to reach the server. Please check your connection and try again."}).finally(()=>{this.isSaving=!1,this.savePromise=null});return this.savePromise=i,i}extractErrorMessage(t){if(t.json){if("string"==typeof t.json.detail)return t.json.detail;if("string"==typeof t.json.error)return t.json.error;if("string"==typeof t.json.description)return t.json.description}return`Save failed with status ${t.status}.`}showSaveErrorDialog(t){const e=document.createElement("temba-dialog");e.header="Save Failed",e.primaryButtonName="",e.cancelButtonName="Dismiss";const i=document.createElement("div");i.style.cssText="padding: 20px; font-size: 14px; line-height: 1.5;",i.textContent=t,e.appendChild(i),document.body.appendChild(e),e.open=!0,e.addEventListener("temba-dialog-hidden",()=>{document.body.removeChild(e)})}startActivityFetching(){this.simulatorActive||this.fetchActivityData()}stopActivityFetching(){null!==this.activityTimer&&(clearTimeout(this.activityTimer),this.activityTimer=null)}fetchActivityData(){var t;if(!(null===(t=this.definition)||void 0===t?void 0:t.uuid))return;if(this.simulatorActive)return;const e=`/flow/activity/${this.definition.uuid}/`,i=$d();if(!i)return;i.getState().fetchActivity(e).then(()=>{this.isConnected&&(this.activityInterval=Math.min(3e5,this.activityInterval+100),null!==this.activityTimer&&clearTimeout(this.activityTimer),this.activityTimer=window.setTimeout(()=>{this.fetchActivityData()},this.activityInterval))})}handleLanguageChange(t){Sd.getState().setLanguageCode(t)}disconnectedCallback(){var t;super.disconnectedCallback(),this.zoomManager.teardownLoupe(),null===(t=$d())||void 0===t||t.getState().setFlushSave(null),this.dragManager.teardownListeners(),window.removeEventListener("beforeunload",this.boundBeforeUnload);const e=document.querySelector("temba-store");(null==e?void 0:e.markClean)&&e.markClean(this.dirtyAdapter),null!==this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),null!==this.activityTimer&&(clearTimeout(this.activityTimer),this.activityTimer=null),this.pendingTimer.clearTimer(),window.removeEventListener("resize",this.boundWindowResize);const i=this.querySelector("#canvas");i&&i.removeEventListener("contextmenu",this.boundCanvasContextMenu);const o=this.querySelector("#editor");o&&o.removeEventListener("wheel",this.boundWheel),this.savePromise?this.savePromise.then(()=>Sd.getState().clearFlowData()):Sd.getState().clearFlowData()}setupGlobalEventListeners(){this.dragManager.setupListeners(),window.addEventListener("resize",this.boundWindowResize);const t=this.querySelector("#canvas");t&&t.addEventListener("contextmenu",this.boundCanvasContextMenu);const e=this.querySelector("#editor");e&&e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.addEventListener(Io.ActionEditRequested,this.handleActionEditRequested.bind(this)),this.addEventListener(Io.AddActionRequested,this.handleAddActionRequested.bind(this)),this.addEventListener(Io.NodeEditRequested,this.handleNodeEditRequested.bind(this)),this.addEventListener(Io.NodeDeleted,this.handleNodeDeleted.bind(this)),this.addEventListener(Io.StickyNoteDeleted,t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.uuid;i&&$d().getState().removeStickyNotes([i])}),this.addEventListener(Io.Selection,t=>{const e=t.target;"TEMBA-CANVAS-MENU"===e.tagName?this.handleCanvasMenuSelection(t):"TEMBA-NODE-TYPE-SELECTOR"===e.tagName&&this.handleNodeTypeSelection(t)}),this.addEventListener(Io.Canceled,t=>{const e=t.target;"TEMBA-CANVAS-MENU"===e.tagName?this.handleCanvasMenuClosed():"TEMBA-NODE-TYPE-SELECTOR"===e.tagName&&this.handleNodeTypeSelectorClosed()}),this.addEventListener(Io.DragExternal,this.handleActionDragExternal.bind(this)),this.addEventListener(Io.DragInternal,this.handleActionDragInternal.bind(this)),this.addEventListener(Io.DragStop,t=>{t.detail.isExternal&&this.handleActionDropExternal(t)}),this.addEventListener(Io.SizeChanged,t=>{const{uuid:e}=t.detail;e&&requestAnimationFrame(()=>{this.checkCollisionsAndReflow([e])})})}openFlowSearch(){if(this.viewingRevision)return;if(this.zoomManager.isDialogOrMenuOpen())return;const t=this.querySelector("temba-flow-search");t&&(t.definition=this.definition,t.languageCode=this.languageCode||"",t.scope=this.showMessageTable?"table":"flow",t.includeCategories=!1,t.show())}closeFlowSearch(){const t=this.querySelector("temba-flow-search");(null==t?void 0:t.open)&&t.hide()}handleKeyDown(t){var e,i;if("Shift"===t.key&&this.isActionExternalDrag&&!this.actionDragIsCopy&&(this.actionDragIsCopy=!0,this.showActionOriginal(!0),(null===(e=this.actionDragLastDetail)||void 0===e?void 0:e.isLastAction)&&this.reprocessActionDrag(),this.requestUpdate()),(t.metaKey||t.ctrlKey)&&"f"===t.key)return t.preventDefault(),void this.openFlowSearch();const o=this.querySelector("temba-flow-search");if(!(null==o?void 0:o.open)){if("Delete"===t.key||"Backspace"===t.key){if(null===(i=this.deleteDialog)||void 0===i?void 0:i.open)return this.deleteSelectedItems(),void(this.deleteDialog.open=!1);this.selectedItems.size>0&&this.showDeleteConfirmation()}"Escape"===t.key&&(this.selectedItems.clear(),this.requestUpdate())}}handleKeyUp(t){var e;"Shift"===t.key&&this.isActionExternalDrag&&this.actionDragIsCopy&&(this.actionDragIsCopy=!1,this.showActionOriginal(!1),(null===(e=this.actionDragLastDetail)||void 0===e?void 0:e.isLastAction)&&this.reprocessActionDrag(),this.requestUpdate())}handleWindowBlur(){var t;this.isActionExternalDrag&&this.actionDragIsCopy&&(this.actionDragIsCopy=!1,this.showActionOriginal(!1),(null===(t=this.actionDragLastDetail)||void 0===t?void 0:t.isLastAction)&&this.reprocessActionDrag(),this.requestUpdate())}getFlowSettings(){try{return JSON.parse(ye("flow-settings")||"{}")}catch(t){return{}}}saveFlowSetting(t,e){if(!this.flow)return;const i=this.getFlowSettings();delete i[this.flow],i[this.flow]={...i[this.flow]||{},[t]:e};const o=Object.keys(i);if(o.length>Nm.MAX_FLOW_SETTINGS)for(const t of o.slice(0,o.length-Nm.MAX_FLOW_SETTINGS))delete i[t];be("flow-settings",JSON.stringify(i))}getFlowSetting(t){var e;if(this.flow)return null===(e=this.getFlowSettings()[this.flow])||void 0===e?void 0:e[t]}showDeleteConfirmation(){var t;const e=this.selectedItems.size,i=1===e?"item":"items";if(null===(t=this.deleteDialog)||void 0===t?void 0:t.open)return;const o=document.createElement("temba-dialog");o.header="Delete Items",o.primaryButtonName="Delete",o.cancelButtonName="Cancel",o.destructive=!0,o.innerHTML=`<div style="padding: 20px;">Are you sure you want to delete ${e} ${i}?</div>`,o.addEventListener("temba-button-clicked",t=>{"Delete"===t.detail.button.name&&(this.deleteSelectedItems(),o.open=!1)}),document.body.appendChild(o),o.open=!0,this.deleteDialog=o,o.addEventListener("temba-dialog-hidden",()=>{document.body.removeChild(o),this.deleteDialog=null})}performReflow(){var t,e;if(!this.definition||0===this.definition.nodes.length)return;this.capturePositionsOnce();const i=(null===(t=this.definition._ui)||void 0===t?void 0:t.stickies)||{},o={};for(const t of this.definition.nodes){const i=null===(e=this.definition._ui)||void 0===e?void 0:e.nodes[t.uuid];(null==i?void 0:i.position)&&(o[t.uuid]={...i.position})}const n=this.definition.nodes[0].uuid,s=new Map,r=Cm(this.definition.nodes,this.definition._ui.nodes,n,t=>{const e=this.querySelector(`[id="${t}"]`);if(e){const i={width:e.offsetWidth,height:e.offsetHeight};return s.set(t,i),i}const i={width:200,height:100};return s.set(t,i),i});if(Object.keys(i).length>0){const t=new Map;for(const e of Object.keys(i)){const o=this.querySelector(`temba-sticky-note[uuid="${e}"]`);if(o)t.set(e,{width:o.offsetWidth,height:o.offsetHeight});else{const o=i[e];t.set(e,{width:o.width||200,height:o.height||100})}}const e=function(t,e,i,o,n,s){const r={},a=Object.keys(i);if(0===a.length)return r;const l=new Map,d=new Map;for(const[i,o]of Object.entries(t)){if(!o.position)continue;const t=o.position.left,n=o.position.top;let s=a[0],r=1/0;for(const i of a){const o=e[i];if(!o)continue;const a=t-o.left,l=n-o.top,d=a*a+l*l;d<r&&(r=d,s=i)}l.set(i,s);const c=e[s],h=!!c&&t<c.left,u=d.get(s)||[];u.push({uuid:i,wasLeft:h}),d.set(s,u)}const c=[];for(const t of a){const e=i[t],n=o.get(t)||{width:200,height:100};c.push({left:e.left,top:e.top,width:n.width,height:n.height})}for(const[t,e]of d){const a=i[t];if(!a)continue;const l=o.get(t)||{width:200};for(const{uuid:i,wasLeft:o}of e){const e=n.get(i)||{width:182,height:100};let d;d=t===s&&o||!o?a.left+l.width+km:a.left-e.width-km;let h=a.top;d=bu(Math.max(0,d)),h=bu(Math.max(0,h));let u=50;for(;u-- >0&&Am(d,h,e.width,e.height,c);)h=bu(h+km);r[i]={left:d,top:h},c.push({left:d,top:h,width:e.width,height:e.height})}}return r}(i,o,r,s,t,n);Object.assign(r,e)}null!==this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.pendingTimer.pending=!0,$d().getState().updateCanvasPositions(r),this.updateCanvasSize(),requestAnimationFrame(()=>{this.plumber.repaintEverything()});const a=this.querySelector("#editor");a&&a.scrollTo({left:0,top:0,behavior:"smooth"}),this.pendingTimer.start()}handlePendingDiscard(){this.pendingTimer.dismiss();if(this.copiedItemUuids.length>0||this.pendingPositions){if(null!==this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.copiedItemUuids.length>0){const t=this.copiedItemUuids.filter(t=>this.definition.nodes.some(e=>e.uuid===t)),e=this.copiedItemUuids.filter(t=>{var e,i;return null===(i=null===(e=this.definition._ui)||void 0===e?void 0:e.stickies)||void 0===i?void 0:i[t]});this.pendingTimer.pending=!0,t.length>0&&$d().getState().removeNodes(t),e.length>0&&(this.pendingTimer.pending=!0,$d().getState().removeStickyNotes(e)),this.copiedItemUuids=[]}this.pendingPositions&&(this.pendingTimer.pending=!0,$d().getState().updateCanvasPositions(this.pendingPositions),this.pendingPositions=null),setTimeout(()=>{$d().getState().setDirtyDate(null),this.isSaving=!1},0),requestAnimationFrame(()=>{this.plumber.repaintEverything()})}}renderPendingCard(){if(!this.pendingTimer.unsaved)return"";const t=`pc-${this.pendingTimer.resetCount}`;return W`<div class="reflow-card">
10842
+ `}constructor(){super(),this.saveTimer=null,this.flowType="message",this.features=[],this.activityTimer=null,this.activityInterval=100,this.isDragging=!1,this.currentDragItem=null,this.selectedItems=new Set,this.isSelecting=!1,this.selectionBox=null,this.targetId=null,this.sourceId=null,this.dragFromNodeId=null,this.originalConnectionTargetId=null,this.isValidTarget=!0,this.connectionSourceX=null,this.connectionSourceY=null,this.issuesWindowHidden=!0,this.revisionsWindowHidden=!0,this.viewingRevision=!1,this.isSaving=!1,this.saveError=null,this.zoom=1,this._suppressDirtySave=!1,this.savePromise=null,this.pendingTimer=new Bm("Unsaved Changes",5e3,this,()=>{this.pendingPositions=null,this.copiedItemUuids=[],this.saveChanges()}),this.pendingPositions=null,this.copiedItemUuids=[],this.deleteDialog=null,this.dirtyAdapter={dirtyMessage:"Your flow is still saving. If you leave now, your latest changes may be lost.",markClean:()=>{}},this.boundBeforeUnload=t=>{t.preventDefault()},this.editingNode=null,this.editingNodeUI=null,this.editingAction=null,this.dialogOrigin=null,this.showMessageTable=!1,this.isCreatingNewNode=!1,this.pendingNodePosition=null,this.canvasDropPreview=null,this.addActionToNodeUuid=null,this.actionDragTargetNodeUuid=null,this.previousActionDragTargetNodeUuid=null,this.isActionExternalDrag=!1,this.actionDragIsCopy=!1,this.actionDragLastDetail=null,this.connectionPlaceholder=null,this.pendingCanvasConnection=null,this.boundCanvasContextMenu=this.handleCanvasContextMenu.bind(this),this.boundWheel=t=>this.zoomManager.handleWheel(t),this.boundWindowResize=()=>this.zoomManager.updateZoomControlPositioning(),this.flushSave=async()=>{const t=this.definition?{...this.definition}:null;this.pendingTimer.unsaved&&(this.pendingPositions=null,this.copiedItemUuids=[],this.pendingTimer.dismiss()),null!==this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.savePromise&&await this.savePromise,t&&this.dirtyDate&&await this.saveChanges(t)},this.editForceBase=!1,this.dragManager=new Om(this),this.zoomManager=new Rm(this)}firstUpdated(t){var e,i,o;super.firstUpdated(t),this.plumber=new Im(this.querySelector("#canvas"),this),this.plumber.zoom=this.zoom,this.setupGlobalEventListeners(),null===(e=$d())||void 0===e||e.getState().setFlushSave(this.flushSave),Sd.getState().setFeatures(this.features),navigator.maxTouchPoints>0&&(null===(i=this.querySelector("#canvas"))||void 0===i||i.classList.add("touch-device"),null===(o=this.querySelector("#editor"))||void 0===o||o.classList.add("touch-device")),this.zoomManager.updateZoomControlPositioning(),this.zoomManager.setLoupeElements(this.querySelector("#loupe"),this.querySelector("#loupe-content")),this.zoomManager.initLoupe(),t.has("flow")&&this.flow&&setTimeout(()=>{this.isConnected&&this.flow&&$d().getState().fetchRevision(`/flow/revisions/${this.flow}`)},0),this.plumber.on("connection:drag",t=>{this.dragFromNodeId=t.data.nodeId,this.sourceId=t.sourceId,this.connectionSourceX=t.sourceX,this.connectionSourceY=t.sourceY,this.originalConnectionTargetId=t.target.id}),this.plumber.on("connection:abort",t=>{this.makeConnection(t)}),this.plumber.on("connection:detach",t=>{this.makeConnection(t)})}makeConnection(t){if(this.sourceId&&this.targetId&&this.isValidTarget)t.target.id===this.targetId?this.plumber.connectIds(this.dragFromNodeId,this.sourceId,this.targetId):$d().getState().updateConnection(this.dragFromNodeId,this.sourceId,this.targetId);else if(this.connectionPlaceholder&&this.connectionPlaceholder.visible&&this.sourceId){const t={left:bu(this.connectionPlaceholder.position.left),top:bu(this.connectionPlaceholder.position.top)},e=!!this.connectionPlaceholder.dragUp;this.connectionPlaceholder.position=t,this.pendingCanvasConnection={fromNodeId:this.dragFromNodeId,exitId:this.sourceId,position:t};const i=this.querySelector("#canvas");if(i){const o=i.getBoundingClientRect(),n=o.left+t.left*this.zoom-40,s=e?o.top+t.top*this.zoom+74:o.top+t.top*this.zoom+80,r=this.querySelector("temba-canvas-menu");r&&r.show(n,s,{x:t.left,y:t.top},!1,!1,"message"===this.flowType)}return void this.requestUpdate()}document.querySelectorAll("temba-flow-node").forEach(t=>{t.classList.remove("connection-target-valid","connection-target-invalid")}),this.pendingCanvasConnection||(this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null),this.targetId=null,this.isValidTarget=!0}willUpdate(t){var e;super.willUpdate(t),t.has("definition")&&((null===(e=this.definition)||void 0===e?void 0:e.type)&&(this.flowType=this.getFlowTypeFromDefinition(this.definition.type)),this.zoomManager.restoreInitialZoomFromSettings()),t.has("dirtyDate")&&this.dirtyDate&&(this.pendingTimer.pending?(this.pendingTimer.pending=!1,this._suppressDirtySave=!0):this.pendingTimer.unsaved?(this.pendingTimer.start(!1),this._suppressDirtySave=!0):this.isSaving=!0)}setSimulatorTabHidden(t){var e;const i=document.querySelector("temba-simulator"),o=null===(e=null==i?void 0:i.shadowRoot)||void 0===e?void 0:e.querySelector("#phone-tab");o&&(o.hidden=t)}updated(t){var e;if(super.updated(t),t.has("features")&&Sd.getState().setFeatures(this.features),t.has("revisionsWindowHidden")&&this.setSimulatorTabHidden(!this.revisionsWindowHidden),t.has("canvasSize")&&this.zoomManager.updateZoomControlPositioning(),t.has("showMessageTable")&&!this.showMessageTable&&this.plumber&&requestAnimationFrame(()=>{const t=this.querySelector("#canvas");t&&(this.plumber.setContainer(t),this.plumber.repaintEverything(),t.addEventListener("contextmenu",this.boundCanvasContextMenu))}),t.has("showMessageTable")&&this.zoomManager.updateZoomControlPositioning(),t.has("definition")&&(setTimeout(()=>this.updateCanvasSize(),0),(null===(e=this.definition)||void 0===e?void 0:e.uuid)&&this.startActivityFetching()),t.has("simulatorActive")&&(this.simulatorActive?(this.closeFloatingWindows(),this.stopActivityFetching()):(this.activityInterval=100,this.startActivityFetching())),t.has("activityData")&&this.plumber&&this.plumber.setActivityData(this.activityData),t.has("dirtyDate")&&this.dirtyDate&&(this._suppressDirtySave?this._suppressDirtySave=!1:this.debouncedSave()),t.has("isSaving")){const t=document.querySelector("temba-store");this.isSaving?(window.addEventListener("beforeunload",this.boundBeforeUnload),(null==t?void 0:t.markDirty)&&t.markDirty(this.dirtyAdapter)):(window.removeEventListener("beforeunload",this.boundBeforeUnload),(null==t?void 0:t.markClean)&&t.markClean(this.dirtyAdapter))}t.has("saveError")&&this.saveError&&(this.showSaveErrorDialog(this.saveError),setTimeout(()=>{this.saveError=null},0))}getFlowTypeFromDefinition(t){return"voice"===t?"voice":"messaging_background"===t||"messaging_offline"===t?"background":"message"}debouncedSave(){null!==this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{if(this.pendingTimer.unsaved)return void(this.saveTimer=null);(new Date).getTime()-this.dirtyDate.getTime()>=2e3?(this.saveChanges(),this.saveTimer=null):this.debouncedSave()},2e3)}definitionForSave(t){return{...t,_ui:{...t._ui,editor:uu}}}saveChanges(t){const e=this.definitionForSave(t||this.definition);this.isSaving=!0;const i=$d().postJSON(`/flow/revisions/${this.flow}/`,e).then(t=>{var e;if(t.status<200||t.status>=300)this.saveError=this.extractErrorMessage(t);else{if(t.json){const i=$d().getState();t.json.info&&i.setFlowInfo(t.json.info),void 0!==(null===(e=t.json.revision)||void 0===e?void 0:e.revision)&&i.setRevision(t.json.revision.revision)}$d().getState().setDirtyDate(null)}}).catch(t=>{console.error("Failed to save flow:",t),t instanceof Response?this.saveError=`Server error (${t.status}). Your changes have not been saved.`:this.saveError="Unable to reach the server. Please check your connection and try again."}).finally(()=>{this.isSaving=!1,this.savePromise=null});return this.savePromise=i,i}extractErrorMessage(t){if(t.json){if("string"==typeof t.json.detail)return t.json.detail;if("string"==typeof t.json.error)return t.json.error;if("string"==typeof t.json.description)return t.json.description}return`Save failed with status ${t.status}.`}showSaveErrorDialog(t){const e=document.createElement("temba-dialog");e.header="Save Failed",e.primaryButtonName="",e.cancelButtonName="Dismiss";const i=document.createElement("div");i.style.cssText="padding: 20px; font-size: 14px; line-height: 1.5;",i.textContent=t,e.appendChild(i),document.body.appendChild(e),e.open=!0,e.addEventListener("temba-dialog-hidden",()=>{document.body.removeChild(e)})}startActivityFetching(){this.simulatorActive||this.fetchActivityData()}stopActivityFetching(){null!==this.activityTimer&&(clearTimeout(this.activityTimer),this.activityTimer=null)}fetchActivityData(){var t;if(!(null===(t=this.definition)||void 0===t?void 0:t.uuid))return;if(this.simulatorActive)return;const e=`/flow/activity/${this.definition.uuid}/`,i=$d();if(!i)return;i.getState().fetchActivity(e).then(()=>{this.isConnected&&(this.activityInterval=Math.min(3e5,this.activityInterval+100),null!==this.activityTimer&&clearTimeout(this.activityTimer),this.activityTimer=window.setTimeout(()=>{this.fetchActivityData()},this.activityInterval))})}handleLanguageChange(t){Sd.getState().setLanguageCode(t)}getAvailableLanguages(){var t,e,i;return(null===(t=this.workspace)||void 0===t?void 0:t.languages)&&this.workspace.languages.length>0?this.workspace.languages.map(t=>({code:t,name:mu(t)})).filter(t=>t.code&&t.name):(null===(i=null===(e=this.definition)||void 0===e?void 0:e._ui)||void 0===i?void 0:i.languages)&&this.definition._ui.languages.length>0?this.definition._ui.languages.map(t=>({code:"string"==typeof t?t:t.iso||t.code,name:"string"==typeof t?t:t.name})):[]}getLocalizationLanguages(){if(!this.definition)return[];const t=this.definition.language;return this.getAvailableLanguages().filter(e=>e.code!==t)}getLocalizationProgress(t){if(!this.definition||!t||t===this.definition.language)return{total:0,localized:0};const e=this.buildTranslationBundles(t);return this.getTranslationCounts(e)}getLanguageLocalization(t){var e;return(null===(e=this.definition)||void 0===e?void 0:e.localization)&&this.definition.localization[t]||{}}buildTranslationBundles(t=this.languageCode){if(!this.definition||!t||t===this.definition.language)return[];const e=this.getLanguageLocalization(t),i=[];return this.definition.nodes.forEach(t=>{var o,n,s,r,a,l,d,c,h;null===(o=t.actions)||void 0===o||o.forEach(o=>{const n=ym[o.type];if(!(null==n?void 0:n.localizable)||0===n.localizable.length)return;const s="send_msg"===o.type?n.localizable.filter(t=>"text"===t):n.localizable,r=this.findTranslations("property",o.uuid,s,o,e);r.length>0&&i.push({nodeUuid:t.uuid,actionUuid:o.uuid,translations:r})});const u=null===(s=null===(n=this.definition._ui)||void 0===n?void 0:n.nodes)||void 0===s?void 0:s[t.uuid],p=null==u?void 0:u.type;if(!p)return;if((null===(r=null==u?void 0:u.config)||void 0===r?void 0:r.localizeRules)&&(null===(l=null===(a=t.router)||void 0===a?void 0:a.cases)||void 0===l?void 0:l.length)){const o=t.router.cases.filter(t=>{var e;return(null===(e=t.arguments)||void 0===e?void 0:e.length)>0&&t.arguments.some(t=>t)}).flatMap(t=>this.findTranslations("property",t.uuid,["arguments"],t,e));o.length>0&&i.push({nodeUuid:t.uuid,translations:o})}const m=wm[p];if((null===(d=null==u?void 0:u.config)||void 0===d?void 0:d.localizeCategories)&&"categories"===(null==m?void 0:m.localizable)&&(null===(h=null===(c=t.router)||void 0===c?void 0:c.categories)||void 0===h?void 0:h.length)){const o=km(p,t.router.categories).flatMap(t=>this.findTranslations("category",t.uuid,["name"],t,e));o.length>0&&i.push({nodeUuid:t.uuid,translations:o})}}),i}findTranslations(t,e,i,o,n){const s=[];return i.forEach(i=>{if("quick_replies"===i)return;const r=i.split(".");let a=o,l=[];for(;r.length>0&&a;){a.uuid&&(l=n[a.uuid]);const t=r.shift();if(!t)break;l&&(l=l[t]),a=a[t]}if(!a)return;const d=this.formatTranslationValue(a);if(!d)return;const c=l?this.formatTranslationValue(l):null;s.push({uuid:e,type:t,attribute:i,from:d,to:c})}),s}formatTranslationValue(t){if(null==t)return null;if(Array.isArray(t)){const e=t.map(t=>this.formatTranslationValue(t)).filter(t=>!!t);return e.length>0?e.join(", "):null}if("object"==typeof t)return"name"in t&&t.name?String(t.name):"arguments"in t&&Array.isArray(t.arguments)?t.arguments.join(" "):null;if("number"==typeof t)return t.toString();if("string"==typeof t){const e=t.trim();return e.length>0?e:null}return null}getTranslationCounts(t){return t.reduce((t,e)=>(e.translations.forEach(e=>{t.total+=1,e.to&&e.to.trim().length>0&&(t.localized+=1)}),t),{total:0,localized:0})}hasAnyNodeWithLocalizeCategories(){var t,e;return!!(null===(e=null===(t=this.definition)||void 0===t?void 0:t._ui)||void 0===e?void 0:e.nodes)&&Object.values(this.definition._ui.nodes).some(t=>{var e;return null===(e=null==t?void 0:t.config)||void 0===e?void 0:e.localizeCategories})}disconnectedCallback(){var t;super.disconnectedCallback(),this.zoomManager.teardownLoupe(),null===(t=$d())||void 0===t||t.getState().setFlushSave(null),this.dragManager.teardownListeners(),window.removeEventListener("beforeunload",this.boundBeforeUnload);const e=document.querySelector("temba-store");(null==e?void 0:e.markClean)&&e.markClean(this.dirtyAdapter),null!==this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),null!==this.activityTimer&&(clearTimeout(this.activityTimer),this.activityTimer=null),this.pendingTimer.clearTimer(),window.removeEventListener("resize",this.boundWindowResize);const i=this.querySelector("#canvas");i&&i.removeEventListener("contextmenu",this.boundCanvasContextMenu);const o=this.querySelector("#editor");o&&o.removeEventListener("wheel",this.boundWheel),this.savePromise?this.savePromise.then(()=>Sd.getState().clearFlowData()):Sd.getState().clearFlowData()}setupGlobalEventListeners(){this.dragManager.setupListeners(),window.addEventListener("resize",this.boundWindowResize);const t=this.querySelector("#canvas");t&&t.addEventListener("contextmenu",this.boundCanvasContextMenu);const e=this.querySelector("#editor");e&&e.addEventListener("wheel",this.boundWheel,{passive:!1}),this.addEventListener(Io.ActionEditRequested,this.handleActionEditRequested.bind(this)),this.addEventListener(Io.AddActionRequested,this.handleAddActionRequested.bind(this)),this.addEventListener(Io.NodeEditRequested,this.handleNodeEditRequested.bind(this)),this.addEventListener(Io.NodeDeleted,this.handleNodeDeleted.bind(this)),this.addEventListener(Io.StickyNoteDeleted,t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.uuid;i&&$d().getState().removeStickyNotes([i])}),this.addEventListener(Io.Selection,t=>{const e=t.target;"TEMBA-CANVAS-MENU"===e.tagName?this.handleCanvasMenuSelection(t):"TEMBA-NODE-TYPE-SELECTOR"===e.tagName&&this.handleNodeTypeSelection(t)}),this.addEventListener(Io.Canceled,t=>{const e=t.target;"TEMBA-CANVAS-MENU"===e.tagName?this.handleCanvasMenuClosed():"TEMBA-NODE-TYPE-SELECTOR"===e.tagName&&this.handleNodeTypeSelectorClosed()}),this.addEventListener(Io.DragExternal,this.handleActionDragExternal.bind(this)),this.addEventListener(Io.DragInternal,this.handleActionDragInternal.bind(this)),this.addEventListener(Io.DragStop,t=>{t.detail.isExternal&&this.handleActionDropExternal(t)}),this.addEventListener(Io.SizeChanged,t=>{const{uuid:e}=t.detail;e&&requestAnimationFrame(()=>{this.checkCollisionsAndReflow([e])})})}openFlowSearch(){if(this.viewingRevision)return;if(this.zoomManager.isDialogOrMenuOpen())return;const t=this.querySelector("temba-flow-search");t&&(t.definition=this.definition,t.languageCode=this.languageCode||"",t.scope=this.showMessageTable?"table":"flow",t.includeCategories=this.isTranslating&&this.hasAnyNodeWithLocalizeCategories(),t.show())}closeFlowSearch(){const t=this.querySelector("temba-flow-search");(null==t?void 0:t.open)&&t.hide()}handleKeyDown(t){var e,i;if("Shift"===t.key&&this.isActionExternalDrag&&!this.actionDragIsCopy&&(this.actionDragIsCopy=!0,this.showActionOriginal(!0),(null===(e=this.actionDragLastDetail)||void 0===e?void 0:e.isLastAction)&&this.reprocessActionDrag(),this.requestUpdate()),(t.metaKey||t.ctrlKey)&&"f"===t.key)return t.preventDefault(),void this.openFlowSearch();const o=this.querySelector("temba-flow-search");if(!(null==o?void 0:o.open)){if("Delete"===t.key||"Backspace"===t.key){if(null===(i=this.deleteDialog)||void 0===i?void 0:i.open)return this.deleteSelectedItems(),void(this.deleteDialog.open=!1);this.selectedItems.size>0&&this.showDeleteConfirmation()}"Escape"===t.key&&(this.selectedItems.clear(),this.requestUpdate())}}handleKeyUp(t){var e;"Shift"===t.key&&this.isActionExternalDrag&&this.actionDragIsCopy&&(this.actionDragIsCopy=!1,this.showActionOriginal(!1),(null===(e=this.actionDragLastDetail)||void 0===e?void 0:e.isLastAction)&&this.reprocessActionDrag(),this.requestUpdate())}handleWindowBlur(){var t;this.isActionExternalDrag&&this.actionDragIsCopy&&(this.actionDragIsCopy=!1,this.showActionOriginal(!1),(null===(t=this.actionDragLastDetail)||void 0===t?void 0:t.isLastAction)&&this.reprocessActionDrag(),this.requestUpdate())}getFlowSettings(){try{return JSON.parse(ye("flow-settings")||"{}")}catch(t){return{}}}saveFlowSetting(t,e){if(!this.flow)return;const i=this.getFlowSettings();delete i[this.flow],i[this.flow]={...i[this.flow]||{},[t]:e};const o=Object.keys(i);if(o.length>Fm.MAX_FLOW_SETTINGS)for(const t of o.slice(0,o.length-Fm.MAX_FLOW_SETTINGS))delete i[t];be("flow-settings",JSON.stringify(i))}getFlowSetting(t){var e;if(this.flow)return null===(e=this.getFlowSettings()[this.flow])||void 0===e?void 0:e[t]}showDeleteConfirmation(){var t;const e=this.selectedItems.size,i=1===e?"item":"items";if(null===(t=this.deleteDialog)||void 0===t?void 0:t.open)return;const o=document.createElement("temba-dialog");o.header="Delete Items",o.primaryButtonName="Delete",o.cancelButtonName="Cancel",o.destructive=!0,o.innerHTML=`<div style="padding: 20px;">Are you sure you want to delete ${e} ${i}?</div>`,o.addEventListener("temba-button-clicked",t=>{"Delete"===t.detail.button.name&&(this.deleteSelectedItems(),o.open=!1)}),document.body.appendChild(o),o.open=!0,this.deleteDialog=o,o.addEventListener("temba-dialog-hidden",()=>{document.body.removeChild(o),this.deleteDialog=null})}performReflow(){var t,e;if(!this.definition||0===this.definition.nodes.length)return;this.capturePositionsOnce();const i=(null===(t=this.definition._ui)||void 0===t?void 0:t.stickies)||{},o={};for(const t of this.definition.nodes){const i=null===(e=this.definition._ui)||void 0===e?void 0:e.nodes[t.uuid];(null==i?void 0:i.position)&&(o[t.uuid]={...i.position})}const n=this.definition.nodes[0].uuid,s=new Map,r=$m(this.definition.nodes,this.definition._ui.nodes,n,t=>{const e=this.querySelector(`[id="${t}"]`);if(e){const i={width:e.offsetWidth,height:e.offsetHeight};return s.set(t,i),i}const i={width:200,height:100};return s.set(t,i),i});if(Object.keys(i).length>0){const t=new Map;for(const e of Object.keys(i)){const o=this.querySelector(`temba-sticky-note[uuid="${e}"]`);if(o)t.set(e,{width:o.offsetWidth,height:o.offsetHeight});else{const o=i[e];t.set(e,{width:o.width||200,height:o.height||100})}}const e=function(t,e,i,o,n,s){const r={},a=Object.keys(i);if(0===a.length)return r;const l=new Map,d=new Map;for(const[i,o]of Object.entries(t)){if(!o.position)continue;const t=o.position.left,n=o.position.top;let s=a[0],r=1/0;for(const i of a){const o=e[i];if(!o)continue;const a=t-o.left,l=n-o.top,d=a*a+l*l;d<r&&(r=d,s=i)}l.set(i,s);const c=e[s],h=!!c&&t<c.left,u=d.get(s)||[];u.push({uuid:i,wasLeft:h}),d.set(s,u)}const c=[];for(const t of a){const e=i[t],n=o.get(t)||{width:200,height:100};c.push({left:e.left,top:e.top,width:n.width,height:n.height})}for(const[t,e]of d){const a=i[t];if(!a)continue;const l=o.get(t)||{width:200};for(const{uuid:i,wasLeft:o}of e){const e=n.get(i)||{width:182,height:100};let d;d=t===s&&o||!o?a.left+l.width+Em:a.left-e.width-Em;let h=a.top;d=bu(Math.max(0,d)),h=bu(Math.max(0,h));let u=50;for(;u-- >0&&Dm(d,h,e.width,e.height,c);)h=bu(h+Em);r[i]={left:d,top:h},c.push({left:d,top:h,width:e.width,height:e.height})}}return r}(i,o,r,s,t,n);Object.assign(r,e)}null!==this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.pendingTimer.pending=!0,$d().getState().updateCanvasPositions(r),this.updateCanvasSize(),requestAnimationFrame(()=>{this.plumber.repaintEverything()});const a=this.querySelector("#editor");a&&a.scrollTo({left:0,top:0,behavior:"smooth"}),this.pendingTimer.start()}handlePendingDiscard(){this.pendingTimer.dismiss();if(this.copiedItemUuids.length>0||this.pendingPositions){if(null!==this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.copiedItemUuids.length>0){const t=this.copiedItemUuids.filter(t=>this.definition.nodes.some(e=>e.uuid===t)),e=this.copiedItemUuids.filter(t=>{var e,i;return null===(i=null===(e=this.definition._ui)||void 0===e?void 0:e.stickies)||void 0===i?void 0:i[t]});this.pendingTimer.pending=!0,t.length>0&&$d().getState().removeNodes(t),e.length>0&&(this.pendingTimer.pending=!0,$d().getState().removeStickyNotes(e)),this.copiedItemUuids=[]}this.pendingPositions&&(this.pendingTimer.pending=!0,$d().getState().updateCanvasPositions(this.pendingPositions),this.pendingPositions=null),setTimeout(()=>{$d().getState().setDirtyDate(null),this.isSaving=!1},0),requestAnimationFrame(()=>{this.plumber.repaintEverything()})}}renderPendingCard(){if(!this.pendingTimer.unsaved)return"";const t=`pc-${this.pendingTimer.resetCount}`;return W`<div class="reflow-card">
10474
10843
  <div class="reflow-top">
10475
10844
  <span class="reflow-label">${this.pendingTimer.label}</span>
10476
10845
  <button class="reflow-discard" @click=${this.handlePendingDiscard}>
@@ -10519,7 +10888,7 @@ background: #ccc;
10519
10888
  </div>
10520
10889
  </div>
10521
10890
  </div>
10522
- </div>`:""}renderConnectionPlaceholder(){if(!this.connectionPlaceholder||!this.connectionPlaceholder.visible)return"";const{position:t,dragUp:e}=this.connectionPlaceholder;let i=null;if(this.sourceId&&this.dragFromNodeId&&this.pendingCanvasConnection&&null!=this.connectionSourceX&&null!=this.connectionSourceY){const o=this.connectionSourceX,n=this.connectionSourceY,s=t.left+100,r=e?t.top+64:t.top,a=$m(o,n,s,r,20,e?0:10,5,e?s<o?"left":"right":"top"),l=6.5,d=13;let c;c=e?`${s},${r-d} ${s-l},${r} ${s+l},${r}`:`${s},${r} ${s-l},${r-d} ${s+l},${r-d}`,i=W`
10891
+ </div>`:""}renderConnectionPlaceholder(){if(!this.connectionPlaceholder||!this.connectionPlaceholder.visible)return"";const{position:t,dragUp:e}=this.connectionPlaceholder;let i=null;if(this.sourceId&&this.dragFromNodeId&&this.pendingCanvasConnection&&null!=this.connectionSourceX&&null!=this.connectionSourceY){const o=this.connectionSourceX,n=this.connectionSourceY,s=t.left+100,r=e?t.top+64:t.top,a=zm(o,n,s,r,20,e?0:10,5,e?s<o?"left":"right":"top"),l=6.5,d=13;let c;c=e?`${s},${r-d} ${s-l},${r} ${s+l},${r}`:`${s},${r} ${s-l},${r-d} ${s+l},${r-d}`,i=W`
10523
10892
  <svg
10524
10893
  style="position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 9999;"
10525
10894
  >
@@ -10550,7 +10919,7 @@ background: #ccc;
10550
10919
  </div>
10551
10920
  </div>
10552
10921
  </div>
10553
- </div>`}checkCollisionsAndReflow(t=[]){var e,i;if(!this.definition)return;const o=[];for(const t of this.definition.nodes){const i=null===(e=this.definition._ui)||void 0===e?void 0:e.nodes[t.uuid];if(!(null==i?void 0:i.position))continue;const n=zu(t.uuid,i.position);n&&o.push(n)}const n=(null===(i=this.definition._ui)||void 0===i?void 0:i.stickies)||{};for(const[t,e]of Object.entries(n)){if(!e.position)continue;const i=this.querySelector(`temba-sticky-note[uuid="${t}"]`);if(!i)continue;const n=zu(t,e.position,i);n&&o.push(n)}const s=((t,e)=>{const i=new Map,o=new Set(t),n=new Map;for(const t of e)n.set(t.uuid,{...t});for(const t of[...o]){const e=n.get(t);if(e)for(const[i,s]of n)if(i!==t&&!o.has(i)&&Iu(e,s)&&e.top>s.top&&s.top<30){o.delete(t),o.add(i);break}}const s=[],r=new Set;for(const t of o){const e=n.get(t);if(e)for(const[t,i]of n)o.has(t)||r.has(t)||Iu(e,i)&&(s.push(t),r.add(t))}const a=new Set;let l=0;for(;s.length>0&&l<200;){l++;const t=s.shift();if(a.has(t))continue;const e=n.get(t),d=[];for(const[i,s]of n)i!==t&&(o.has(i)||a.has(i))&&Iu(e,s)&&d.push(s);if(0===d.length)continue;const c=d.filter(t=>o.has(t.uuid)),h=[...Lu];let u=null;if(c.length>0){for(const t of c){if(e.top>t.top){const t=h.indexOf("up");-1!==t&&h.splice(t,1)}if(e.left>t.left){const t=h.indexOf("left");-1!==t&&h.splice(t,1)}}let t=0,i=0;for(const o of c)t+=Math.min(e.right,o.right)-Math.max(e.left,o.left),i+=Math.min(e.bottom,o.bottom)-Math.max(e.top,o.top);t>i?u="vertical":i>t&&(u="horizontal")}let p=null,m=1/0;for(const i of h){const s=Pu(e,d,i);if(!s)continue;const r=Ou(e,s.left,s.top);let l=!1,h=0;for(const[e,i]of n)if(e!==t&&Iu(r,i)){if(o.has(e)||a.has(e)){l=!0;break}h++}if(l)continue;const g=Math.abs(s.left-e.left)+Math.abs(s.top-e.top);let f;if(c.length>0){const t="up"===i||"down"===i;f=2e3*h+(null===u||"vertical"===u&&t||"horizontal"===u&&!t?0:5e3)+g}else f=1e4*h+g;f<m&&(m=f,p=s)}if(p){i.set(t,{left:p.left,top:p.top});const l=Ou(e,p.left,p.top);n.set(t,l),a.add(t);for(const[e,i]of n)e!==t&&(o.has(e)||a.has(e)||r.has(e)||Iu(l,i)&&(s.push(e),r.add(e)))}}return i})(t,o);if(s.size>0){const t={};for(const[e,i]of s.entries())t[e]=i;$d().getState().updateCanvasPositions(t)}}findTargetNodeAt(t,e){var i;const o=document.elementFromPoint(t,e);return null!==(i=null==o?void 0:o.closest("temba-flow-node"))&&void 0!==i?i:null}updateCanvasSize(){var t;if(!this.definition)return;const e=$d();if(!e)return;let i=0,o=0;this.definition.nodes.forEach(t=>{const e=this.definition._ui.nodes[t.uuid];if(e&&e.position){const n=this.querySelector(`[id="${t.uuid}"]`);n&&(i=Math.max(i,e.position.left+n.offsetWidth),o=Math.max(o,e.position.top+n.offsetHeight))}});const n=(null===(t=this.definition._ui)||void 0===t?void 0:t.stickies)||{};Object.entries(n).forEach(([t,e])=>{if(e.position){const n=this.querySelector(`temba-sticky-note[uuid="${t}"]`);if(n){const t=n.clientWidth,s=n.clientHeight;i=Math.max(i,e.position.left+t),o=Math.max(o,e.position.top+s)}else i=Math.max(i,e.position.left+(e.width||200)),o=Math.max(o,e.position.top+(e.height||100))}}),e.getState().expandCanvas(i,o)}handleCanvasContextMenu(t){if(this.isReadOnly())return void t.preventDefault();"canvas"===t.target.id&&(t.preventDefault(),t.stopPropagation(),this.dragManager.blurActiveContentEditable(),this.showContextMenuAt(t.clientX,t.clientY))}showContextMenuAt(t,e){if(this.isReadOnly())return;const i=this.querySelector("#canvas");if(!i)return;const o=i.getBoundingClientRect(),n=(t-o.left)/this.zoom-10,s=(e-o.top)/this.zoom-10,r=bu(n),a=bu(s),l=this.querySelector("temba-canvas-menu");if(l){const i=this.definition&&this.definition.nodes.length>0;l.show(t,e,{x:r,y:a},!0,i,"message"===this.flowType)}}handleEmptyFlowClick(t){const e=this.querySelector("#editor");if(!e)return;e.scrollTo({left:0,top:0,behavior:"smooth"});const i=this.querySelector("temba-canvas-menu");if(i){const e=t.currentTarget.getBoundingClientRect(),o=265,n=e.left+e.width/2-o/2,s=e.bottom+8;i.show(n,s,{x:0,y:0},!1,!1,"message"===this.flowType)}}handleCanvasMenuSelection(t){const e=t.detail,i=$d();if("reflow"!==e.action){if("sticky"===e.action){const t=i.getState().createStickyNote({left:e.position.x,top:e.position.y});requestAnimationFrame(()=>{this.checkCollisionsAndReflow([t])}),this.pendingCanvasConnection=null,this.connectionPlaceholder=null,this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null}else if("send_msg"===e.action||"wait_for_response"===e.action)this.handleNodeTypeSelection(new CustomEvent(Io.Selection,{detail:{nodeType:e.action,position:e.position}}));else if("other"===e.action){const t=this.querySelector("temba-node-type-selector");t&&t.show("all",e.position)}}else this.performReflow()}cleanUpConnection(){this.isCreatingNewNode&&(this.isCreatingNewNode=!1,this.pendingNodePosition=null),this.originalConnectionTargetId&&(this.plumber.connectIds(this.dragFromNodeId,this.sourceId,this.originalConnectionTargetId),this.originalConnectionTargetId=null),this.pendingCanvasConnection&&(this.pendingCanvasConnection=null,this.connectionPlaceholder=null,this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null,this.originalConnectionTargetId=null)}handleCanvasMenuClosed(){this.cleanUpConnection()}handleNodeTypeSelectorClosed(){this.addActionToNodeUuid=null,this.cleanUpConnection()}handleNodeTypeSelection(t){const e=t.detail;if(this.pendingCanvasConnection,this.addActionToNodeUuid){const t=this.definition.nodes.find(t=>t.uuid===this.addActionToNodeUuid),i=this.definition._ui.nodes[this.addActionToNodeUuid];if(t&&i){const o=Xt();return this.editingAction={uuid:o,type:e.nodeType},this.editingNode=t,this.editingNodeUI=i,this.isCreatingNewNode=!1,void(this.addActionToNodeUuid=null)}this.addActionToNodeUuid=null}const i=Xt(),o=e.nodeType in ym,n=o?"execute_actions":e.nodeType,s=wm[n],r=(null==s?void 0:s.form)&&Object.keys(s.form).some(t=>{var e;return["rules","categories","cases"].includes(t)||"array"===(null===(e=s.form[t])||void 0===e?void 0:e.type)}),a={uuid:i,actions:[],exits:r?[]:[{uuid:Xt(),destination_uuid:null}]};r&&(a.router={type:"switch",categories:[],cases:[],operand:"@input.text",default_category_uuid:void 0});const l={position:this.pendingCanvasConnection?this.pendingCanvasConnection.position:{left:e.position.x,top:e.position.y},type:n,config:{}};if(this.isCreatingNewNode=!0,this.pendingNodePosition=this.pendingCanvasConnection?this.pendingCanvasConnection.position:{left:e.position.x,top:e.position.y},this.editingNode=a,this.editingNodeUI=l,o){const t=Xt();this.editingAction={uuid:t,type:e.nodeType}}}handleActionEditRequested(t){this.editingAction=t.detail.action,this.editForceBase=!!t.detail.forceBase,this.dialogOrigin=null!=t.detail.originX?{x:t.detail.originX,y:t.detail.originY}:null;const e=t.detail.nodeUuid,i=this.definition.nodes.find(t=>t.uuid===e);i&&(this.editingNode=i,this.editingNodeUI=this.definition._ui.nodes[e])}handleAddActionRequested(t){const e=t.detail.nodeUuid,i=this.definition.nodes.find(t=>t.uuid===e);if(!i)return;const o=this.definition._ui.nodes[e];if(!o)return;const n=this.querySelector("temba-node-type-selector");n&&(n.show("action-no-branching",{x:o.position.left,y:o.position.top}),this.addActionToNodeUuid=e)}handleNodeEditRequested(t){this.editForceBase=!!t.detail.forceBase,this.editingAction=null,this.editingNode=t.detail.node,this.editingNodeUI=t.detail.nodeUI,this.dialogOrigin=null!=t.detail.originX?{x:t.detail.originX,y:t.detail.originY}:null}handleNodeDeleted(t){const e=t.detail.uuid;e&&this.deleteNodes([e])}handleActionSaved(t){var e,i;if(this.editingNode&&this.editingAction){let o;o=this.editingNode.actions.findIndex(t=>t.uuid===this.editingAction.uuid)>=0?this.editingNode.actions.map(e=>e.uuid===this.editingAction.uuid?t:e):[...this.editingNode.actions,t];const n={...this.editingNode,actions:o};if(this.isCreatingNewNode){const t=$d(),i={position:this.pendingNodePosition||{left:0,top:0},type:null===(e=this.editingNodeUI)||void 0===e?void 0:e.type,config:{}};t.getState().addNode(n,i),this.pendingCanvasConnection&&(t.getState().updateConnection(this.pendingCanvasConnection.fromNodeId,this.pendingCanvasConnection.exitId,n.uuid),this.pendingCanvasConnection=null,this.connectionPlaceholder=null,this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null),this.isCreatingNewNode=!1,this.pendingNodePosition=null,requestAnimationFrame(()=>{this.checkCollisionsAndReflow([n.uuid])})}else{const t=this.editingNode.uuid;null===(i=$d())||void 0===i||i.getState().updateNode(t,n),requestAnimationFrame(()=>{this.checkCollisionsAndReflow([t])})}}this.closeNodeEditor()}closeNodeEditor(){this.editingNode=null,this.editingNodeUI=null,this.editingAction=null,this.dialogOrigin=null,this.editForceBase=!1}handleActionEditCanceled(){this.cleanUpConnection(),this.closeNodeEditor()}handleNodeSaved(t,e){var i,o,n;if(this.editingNode)if(this.isCreatingNewNode){const o=$d(),n={position:this.pendingNodePosition||{left:0,top:0},type:null===(i=this.editingNodeUI)||void 0===i?void 0:i.type,config:e||{}};o.getState().addNode(t,n),this.pendingCanvasConnection&&(o.getState().updateConnection(this.pendingCanvasConnection.fromNodeId,this.pendingCanvasConnection.exitId,t.uuid),this.pendingCanvasConnection=null,this.connectionPlaceholder=null,this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null),this.isCreatingNewNode=!1,this.pendingNodePosition=null,requestAnimationFrame(()=>{this.checkCollisionsAndReflow([t.uuid])})}else{if(this.plumber){const e=this.editingNode.exits||[],i=t.exits||[];e.filter(t=>!i.find(e=>e.uuid===t.uuid)).forEach(t=>{this.plumber.removeExitConnection(t.uuid)})}this.plumber.revalidate([t.uuid]),null===(o=$d())||void 0===o||o.getState().updateNode(this.editingNode.uuid,t),e&&(null===(n=$d())||void 0===n||n.getState().updateNodeUIConfig(t.uuid,e));const i=t.uuid;requestAnimationFrame(()=>{this.checkCollisionsAndReflow([i])})}this.closeNodeEditor()}handleNodeEditCanceled(){this.cleanUpConnection(),this.closeNodeEditor()}getNodeAtPosition(t,e){const i=this.querySelectorAll("temba-flow-node");for(const o of Array.from(i)){const i=o.getBoundingClientRect();if(t>=i.left&&t<=i.right&&e>=i.top&&e<=i.bottom)return o.getAttribute("data-node-uuid")}return null}calculateCanvasDropPosition(t,e,i=!0){const o=this.querySelector("#canvas");if(!o)return{left:0,top:0};const n=o.getBoundingClientRect(),s=(t-n.left)/this.zoom-20,r=(e-n.top)/this.zoom-20;return i?{left:bu(s),top:bu(r)}:{left:s,top:r}}handleActionDragExternal(t){var e,i,o;const{action:n,nodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,actionHeight:d=60,isLastAction:c=!1}=t.detail,h=!this.isActionExternalDrag;if(this.isActionExternalDrag=!0,this.actionDragLastDetail={action:n,nodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,actionHeight:d,isLastAction:c},h){null!==(i=null===(e=this.querySelector("#canvas"))||void 0===e?void 0:e.classList.contains("shift-held"))&&void 0!==i&&i?(this.actionDragIsCopy=!0,this.showActionOriginal(!0)):null===(o=this.querySelector("#drag-hint"))||void 0===o||o.classList.add("visible")}const u=this.getNodeAtPosition(a,l);if(u&&u!==s){const t=this.definition._ui.nodes[u],e=this.definition.nodes.find(t=>t.uuid===u);if("execute_actions"===(null==t?void 0:t.type)&&e){if(this.previousActionDragTargetNodeUuid&&this.previousActionDragTargetNodeUuid!==u){const t=this.querySelector(`temba-flow-node[data-node-uuid="${this.previousActionDragTargetNodeUuid}"]`);t&&t.dispatchEvent(new CustomEvent("action-drag-leave",{detail:{},bubbles:!1}))}this.actionDragTargetNodeUuid=u,this.previousActionDragTargetNodeUuid=u,this.canvasDropPreview=null;const t=this.querySelector(`temba-flow-node[data-node-uuid="${s}"]`);t&&t.dispatchEvent(new CustomEvent("action-show-ghost",{detail:{},bubbles:!1}));const e=this.querySelector(`temba-flow-node[data-node-uuid="${u}"]`);return e&&e.dispatchEvent(new CustomEvent("action-drag-over",{detail:{action:n,sourceNodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,actionHeight:d},bubbles:!1})),void this.requestUpdate()}}if(this.previousActionDragTargetNodeUuid){const t=this.querySelector(`temba-flow-node[data-node-uuid="${this.previousActionDragTargetNodeUuid}"]`);t&&t.dispatchEvent(new CustomEvent("action-drag-leave",{detail:{},bubbles:!1})),this.previousActionDragTargetNodeUuid=null}this.actionDragTargetNodeUuid=null;const p=this.querySelector(`temba-flow-node[data-node-uuid="${s}"]`);if(!c||this.actionDragIsCopy){p&&p.dispatchEvent(new CustomEvent("action-hide-ghost",{detail:{},bubbles:!1}));const t=this.calculateCanvasDropPosition(a,l,!1);this.canvasDropPreview={action:n,nodeUuid:s,actionIndex:r,position:t,actionHeight:d}}else p&&p.dispatchEvent(new CustomEvent("action-show-ghost",{detail:{},bubbles:!1})),this.canvasDropPreview=null;this.requestUpdate()}handleActionDragInternal(t){var e;if(this.previousActionDragTargetNodeUuid){const t=this.querySelector(`temba-flow-node[data-node-uuid="${this.previousActionDragTargetNodeUuid}"]`);t&&t.dispatchEvent(new CustomEvent("action-drag-leave",{detail:{},bubbles:!1})),this.previousActionDragTargetNodeUuid=null}this.canvasDropPreview=null,this.actionDragTargetNodeUuid=null,this.isActionExternalDrag=!1,this.actionDragIsCopy=!1,null===(e=this.querySelector("#drag-hint"))||void 0===e||e.classList.remove("visible"),this.actionDragLastDetail=null}showActionOriginal(t){if(!this.actionDragLastDetail)return;const e=this.querySelector(`temba-flow-node[data-node-uuid="${this.actionDragLastDetail.nodeUuid}"]`);e&&e.dispatchEvent(new CustomEvent(t?"action-show-original":"action-hide-original",{detail:{},bubbles:!1}))}reprocessActionDrag(){if(!this.actionDragLastDetail)return;const{action:t,nodeUuid:e,actionIndex:i,mouseX:o,mouseY:n,actionHeight:s}=this.actionDragLastDetail,r=this.querySelector(`temba-flow-node[data-node-uuid="${e}"]`);if(!this.actionDragTargetNodeUuid)if(this.actionDragIsCopy){r&&r.dispatchEvent(new CustomEvent("action-hide-ghost",{detail:{},bubbles:!1}));const a=this.calculateCanvasDropPosition(o,n,!1);this.canvasDropPreview={action:t,nodeUuid:e,actionIndex:i,position:a,actionHeight:s}}else r&&r.dispatchEvent(new CustomEvent("action-show-ghost",{detail:{},bubbles:!1})),this.canvasDropPreview=null}handleActionDropExternal(t){var e,i,o;const{action:n,nodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,isLastAction:d=!1}=t.detail,c=this.actionDragIsCopy;this.isActionExternalDrag=!1,this.actionDragIsCopy=!1,this.actionDragLastDetail=null,this.previousActionDragTargetNodeUuid=null,null===(e=this.querySelector("#drag-hint"))||void 0===e||e.classList.remove("visible");const h=this.actionDragTargetNodeUuid;if(h&&h!==s){const t=this.querySelector(`temba-flow-node[data-node-uuid="${h}"]`);return t&&t.dispatchEvent(new CustomEvent("action-drop",{detail:{action:n,sourceNodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,isCopy:c},bubbles:!1})),this.canvasDropPreview=null,void(this.actionDragTargetNodeUuid=null)}if(d&&!c)return this.canvasDropPreview=null,void(this.actionDragTargetNodeUuid=null);const u=this.calculateCanvasDropPosition(a,l,!0);if(!c){const t=this.definition.nodes.find(t=>t.uuid===s);if(!t)return;const e=t.actions.filter((t,e)=>e!==r);if(0===e.length)this.deleteNodes([s]);else{const o={...t,actions:e};null===(i=$d())||void 0===i||i.getState().updateNode(s,o)}}const p=c?{...n,uuid:Xt()}:n,m={uuid:Xt(),actions:[p],exits:[{uuid:Xt(),destination_uuid:null}]},g={position:u,type:"execute_actions",config:{}};null===(o=$d())||void 0===o||o.getState().addNode(m,g),c&&this.copyActionLocalizations(n.uuid,p.uuid),this.canvasDropPreview=null,this.actionDragTargetNodeUuid=null,requestAnimationFrame(()=>{this.checkCollisionsAndReflow([m.uuid])})}copyActionLocalizations(t,e){var i,o,n;const s=null===(i=this.definition)||void 0===i?void 0:i.localization;if(!s)return;const r=null===(o=$d())||void 0===o?void 0:o.getState();if(r)for(const i of Object.keys(s)){const o=null===(n=s[i])||void 0===n?void 0:n[t];o&&r.updateLocalization(i,e,JSON.parse(JSON.stringify(o)))}}closeOpenWindows(){var t;if(this.issuesWindowHidden||(this.issuesWindowHidden=!0),this.revisionsWindowHidden||(null===(t=this.getRevisionsWindow())||void 0===t||t.close(),this.revisionsWindowHidden=!0),this.simulatorActive){const t=document.querySelector("temba-simulator");null==t||t.handleClose()}}closeFloatingWindows(){var t;this.issuesWindowHidden||(this.issuesWindowHidden=!0),this.revisionsWindowHidden||(null===(t=this.getRevisionsWindow())||void 0===t||t.close(),this.revisionsWindowHidden=!0)}getRevisionsWindow(){return this.querySelector("temba-revisions-window")}handleIssuesTabClick(){this.issuesWindowHidden?(this.closeOpenWindows(),this.issuesWindowHidden=!1):this.issuesWindowHidden=!0}handleIssueSelected(t){var e;const{issue:i}=t.detail;this.issuesWindowHidden=!0,this.focusNode(i.node_uuid);const o=this.definition.nodes.find(t=>t.uuid===i.node_uuid);if(o)if(i.action_uuid){const t=null===(e=o.actions)||void 0===e?void 0:e.find(t=>t.uuid===i.action_uuid);t&&(this.editingAction=t,this.editingNode=o,this.editingNodeUI=this.definition._ui.nodes[i.node_uuid])}else this.editingNode=o,this.editingNodeUI=this.definition._ui.nodes[i.node_uuid]}handleRevisionViewed(){var t;this.viewingRevision=!0,this.closeFlowSearch(),null===(t=this.plumber)||void 0===t||t.reset()}handleRevisionCancelled(){var t;this.viewingRevision=!1,null===(t=this.plumber)||void 0===t||t.reset()}handleRevisionsClosed(){this.viewingRevision=!1,this.revisionsWindowHidden=!0}async handleRevisionReverted(t){var e;const{definition:i,languageCode:o}=t.detail;this.viewingRevision=!1,this.revisionsWindowHidden=!0,null===(e=this.plumber)||void 0===e||e.reset(),await this.saveChanges(i),$d().getState().fetchRevision(`/flow/revisions/${this.flow}`).finally(()=>{o&&this.handleLanguageChange(o)})}renderToolbarElement(){var t,e;return W`
10922
+ </div>`}checkCollisionsAndReflow(t=[]){var e,i;if(!this.definition)return;const o=[];for(const t of this.definition.nodes){const i=null===(e=this.definition._ui)||void 0===e?void 0:e.nodes[t.uuid];if(!(null==i?void 0:i.position))continue;const n=zu(t.uuid,i.position);n&&o.push(n)}const n=(null===(i=this.definition._ui)||void 0===i?void 0:i.stickies)||{};for(const[t,e]of Object.entries(n)){if(!e.position)continue;const i=this.querySelector(`temba-sticky-note[uuid="${t}"]`);if(!i)continue;const n=zu(t,e.position,i);n&&o.push(n)}const s=((t,e)=>{const i=new Map,o=new Set(t),n=new Map;for(const t of e)n.set(t.uuid,{...t});for(const t of[...o]){const e=n.get(t);if(e)for(const[i,s]of n)if(i!==t&&!o.has(i)&&Iu(e,s)&&e.top>s.top&&s.top<30){o.delete(t),o.add(i);break}}const s=[],r=new Set;for(const t of o){const e=n.get(t);if(e)for(const[t,i]of n)o.has(t)||r.has(t)||Iu(e,i)&&(s.push(t),r.add(t))}const a=new Set;let l=0;for(;s.length>0&&l<200;){l++;const t=s.shift();if(a.has(t))continue;const e=n.get(t),d=[];for(const[i,s]of n)i!==t&&(o.has(i)||a.has(i))&&Iu(e,s)&&d.push(s);if(0===d.length)continue;const c=d.filter(t=>o.has(t.uuid)),h=[...Lu];let u=null;if(c.length>0){for(const t of c){if(e.top>t.top){const t=h.indexOf("up");-1!==t&&h.splice(t,1)}if(e.left>t.left){const t=h.indexOf("left");-1!==t&&h.splice(t,1)}}let t=0,i=0;for(const o of c)t+=Math.min(e.right,o.right)-Math.max(e.left,o.left),i+=Math.min(e.bottom,o.bottom)-Math.max(e.top,o.top);t>i?u="vertical":i>t&&(u="horizontal")}let p=null,m=1/0;for(const i of h){const s=Pu(e,d,i);if(!s)continue;const r=Ou(e,s.left,s.top);let l=!1,h=0;for(const[e,i]of n)if(e!==t&&Iu(r,i)){if(o.has(e)||a.has(e)){l=!0;break}h++}if(l)continue;const g=Math.abs(s.left-e.left)+Math.abs(s.top-e.top);let f;if(c.length>0){const t="up"===i||"down"===i;f=2e3*h+(null===u||"vertical"===u&&t||"horizontal"===u&&!t?0:5e3)+g}else f=1e4*h+g;f<m&&(m=f,p=s)}if(p){i.set(t,{left:p.left,top:p.top});const l=Ou(e,p.left,p.top);n.set(t,l),a.add(t);for(const[e,i]of n)e!==t&&(o.has(e)||a.has(e)||r.has(e)||Iu(l,i)&&(s.push(e),r.add(e)))}}return i})(t,o);if(s.size>0){const t={};for(const[e,i]of s.entries())t[e]=i;$d().getState().updateCanvasPositions(t)}}findTargetNodeAt(t,e){var i;const o=document.elementFromPoint(t,e);return null!==(i=null==o?void 0:o.closest("temba-flow-node"))&&void 0!==i?i:null}updateCanvasSize(){var t;if(!this.definition)return;const e=$d();if(!e)return;let i=0,o=0;this.definition.nodes.forEach(t=>{const e=this.definition._ui.nodes[t.uuid];if(e&&e.position){const n=this.querySelector(`[id="${t.uuid}"]`);n&&(i=Math.max(i,e.position.left+n.offsetWidth),o=Math.max(o,e.position.top+n.offsetHeight))}});const n=(null===(t=this.definition._ui)||void 0===t?void 0:t.stickies)||{};Object.entries(n).forEach(([t,e])=>{if(e.position){const n=this.querySelector(`temba-sticky-note[uuid="${t}"]`);if(n){const t=n.clientWidth,s=n.clientHeight;i=Math.max(i,e.position.left+t),o=Math.max(o,e.position.top+s)}else i=Math.max(i,e.position.left+(e.width||200)),o=Math.max(o,e.position.top+(e.height||100))}}),e.getState().expandCanvas(i,o)}handleCanvasContextMenu(t){if(this.isReadOnly())return void t.preventDefault();"canvas"===t.target.id&&(t.preventDefault(),t.stopPropagation(),this.dragManager.blurActiveContentEditable(),this.showContextMenuAt(t.clientX,t.clientY))}showContextMenuAt(t,e){if(this.isReadOnly())return;const i=this.querySelector("#canvas");if(!i)return;const o=i.getBoundingClientRect(),n=(t-o.left)/this.zoom-10,s=(e-o.top)/this.zoom-10,r=bu(n),a=bu(s),l=this.querySelector("temba-canvas-menu");if(l){const i=this.definition&&this.definition.nodes.length>0;l.show(t,e,{x:r,y:a},!0,i,"message"===this.flowType)}}handleEmptyFlowClick(t){const e=this.querySelector("#editor");if(!e)return;e.scrollTo({left:0,top:0,behavior:"smooth"});const i=this.querySelector("temba-canvas-menu");if(i){const e=t.currentTarget.getBoundingClientRect(),o=265,n=e.left+e.width/2-o/2,s=e.bottom+8;i.show(n,s,{x:0,y:0},!1,!1,"message"===this.flowType)}}handleCanvasMenuSelection(t){const e=t.detail,i=$d();if("reflow"!==e.action){if("sticky"===e.action){const t=i.getState().createStickyNote({left:e.position.x,top:e.position.y});requestAnimationFrame(()=>{this.checkCollisionsAndReflow([t])}),this.pendingCanvasConnection=null,this.connectionPlaceholder=null,this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null}else if("send_msg"===e.action||"wait_for_response"===e.action)this.handleNodeTypeSelection(new CustomEvent(Io.Selection,{detail:{nodeType:e.action,position:e.position}}));else if("other"===e.action){const t=this.querySelector("temba-node-type-selector");t&&t.show("all",e.position)}}else this.performReflow()}cleanUpConnection(){this.isCreatingNewNode&&(this.isCreatingNewNode=!1,this.pendingNodePosition=null),this.originalConnectionTargetId&&(this.plumber.connectIds(this.dragFromNodeId,this.sourceId,this.originalConnectionTargetId),this.originalConnectionTargetId=null),this.pendingCanvasConnection&&(this.pendingCanvasConnection=null,this.connectionPlaceholder=null,this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null,this.originalConnectionTargetId=null)}handleCanvasMenuClosed(){this.cleanUpConnection()}handleNodeTypeSelectorClosed(){this.addActionToNodeUuid=null,this.cleanUpConnection()}handleNodeTypeSelection(t){const e=t.detail;if(this.pendingCanvasConnection,this.addActionToNodeUuid){const t=this.definition.nodes.find(t=>t.uuid===this.addActionToNodeUuid),i=this.definition._ui.nodes[this.addActionToNodeUuid];if(t&&i){const o=Xt();return this.editingAction={uuid:o,type:e.nodeType},this.editingNode=t,this.editingNodeUI=i,this.isCreatingNewNode=!1,void(this.addActionToNodeUuid=null)}this.addActionToNodeUuid=null}const i=Xt(),o=e.nodeType in ym,n=o?"execute_actions":e.nodeType,s=wm[n],r=(null==s?void 0:s.form)&&Object.keys(s.form).some(t=>{var e;return["rules","categories","cases"].includes(t)||"array"===(null===(e=s.form[t])||void 0===e?void 0:e.type)}),a={uuid:i,actions:[],exits:r?[]:[{uuid:Xt(),destination_uuid:null}]};r&&(a.router={type:"switch",categories:[],cases:[],operand:"@input.text",default_category_uuid:void 0});const l={position:this.pendingCanvasConnection?this.pendingCanvasConnection.position:{left:e.position.x,top:e.position.y},type:n,config:{}};if(this.isCreatingNewNode=!0,this.pendingNodePosition=this.pendingCanvasConnection?this.pendingCanvasConnection.position:{left:e.position.x,top:e.position.y},this.editingNode=a,this.editingNodeUI=l,o){const t=Xt();this.editingAction={uuid:t,type:e.nodeType}}}handleActionEditRequested(t){this.editingAction=t.detail.action,this.editForceBase=!!t.detail.forceBase,this.dialogOrigin=null!=t.detail.originX?{x:t.detail.originX,y:t.detail.originY}:null;const e=t.detail.nodeUuid,i=this.definition.nodes.find(t=>t.uuid===e);i&&(this.editingNode=i,this.editingNodeUI=this.definition._ui.nodes[e])}handleAddActionRequested(t){const e=t.detail.nodeUuid,i=this.definition.nodes.find(t=>t.uuid===e);if(!i)return;const o=this.definition._ui.nodes[e];if(!o)return;const n=this.querySelector("temba-node-type-selector");n&&(n.show("action-no-branching",{x:o.position.left,y:o.position.top}),this.addActionToNodeUuid=e)}handleNodeEditRequested(t){this.editForceBase=!!t.detail.forceBase,this.editingAction=null,this.editingNode=t.detail.node,this.editingNodeUI=t.detail.nodeUI,this.dialogOrigin=null!=t.detail.originX?{x:t.detail.originX,y:t.detail.originY}:null}handleNodeDeleted(t){const e=t.detail.uuid;e&&this.deleteNodes([e])}handleActionSaved(t){var e,i;if(this.editingNode&&this.editingAction){let o;o=this.editingNode.actions.findIndex(t=>t.uuid===this.editingAction.uuid)>=0?this.editingNode.actions.map(e=>e.uuid===this.editingAction.uuid?t:e):[...this.editingNode.actions,t];const n={...this.editingNode,actions:o};if(this.isCreatingNewNode){const t=$d(),i={position:this.pendingNodePosition||{left:0,top:0},type:null===(e=this.editingNodeUI)||void 0===e?void 0:e.type,config:{}};t.getState().addNode(n,i),this.pendingCanvasConnection&&(t.getState().updateConnection(this.pendingCanvasConnection.fromNodeId,this.pendingCanvasConnection.exitId,n.uuid),this.pendingCanvasConnection=null,this.connectionPlaceholder=null,this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null),this.isCreatingNewNode=!1,this.pendingNodePosition=null,requestAnimationFrame(()=>{this.checkCollisionsAndReflow([n.uuid])})}else{const t=this.editingNode.uuid;null===(i=$d())||void 0===i||i.getState().updateNode(t,n),requestAnimationFrame(()=>{this.checkCollisionsAndReflow([t])})}}this.closeNodeEditor()}closeNodeEditor(){this.editingNode=null,this.editingNodeUI=null,this.editingAction=null,this.dialogOrigin=null,this.editForceBase=!1}handleActionEditCanceled(){this.cleanUpConnection(),this.closeNodeEditor()}handleNodeSaved(t,e){var i,o,n;if(this.editingNode)if(this.isCreatingNewNode){const o=$d(),n={position:this.pendingNodePosition||{left:0,top:0},type:null===(i=this.editingNodeUI)||void 0===i?void 0:i.type,config:e||{}};o.getState().addNode(t,n),this.pendingCanvasConnection&&(o.getState().updateConnection(this.pendingCanvasConnection.fromNodeId,this.pendingCanvasConnection.exitId,t.uuid),this.pendingCanvasConnection=null,this.connectionPlaceholder=null,this.sourceId=null,this.connectionSourceX=null,this.connectionSourceY=null,this.dragFromNodeId=null),this.isCreatingNewNode=!1,this.pendingNodePosition=null,requestAnimationFrame(()=>{this.checkCollisionsAndReflow([t.uuid])})}else{if(this.plumber){const e=this.editingNode.exits||[],i=t.exits||[];e.filter(t=>!i.find(e=>e.uuid===t.uuid)).forEach(t=>{this.plumber.removeExitConnection(t.uuid)})}this.plumber.revalidate([t.uuid]),null===(o=$d())||void 0===o||o.getState().updateNode(this.editingNode.uuid,t),e&&(null===(n=$d())||void 0===n||n.getState().updateNodeUIConfig(t.uuid,e));const i=t.uuid;requestAnimationFrame(()=>{this.checkCollisionsAndReflow([i])})}this.closeNodeEditor()}handleNodeEditCanceled(){this.cleanUpConnection(),this.closeNodeEditor()}getNodeAtPosition(t,e){const i=this.querySelectorAll("temba-flow-node");for(const o of Array.from(i)){const i=o.getBoundingClientRect();if(t>=i.left&&t<=i.right&&e>=i.top&&e<=i.bottom)return o.getAttribute("data-node-uuid")}return null}calculateCanvasDropPosition(t,e,i=!0){const o=this.querySelector("#canvas");if(!o)return{left:0,top:0};const n=o.getBoundingClientRect(),s=(t-n.left)/this.zoom-20,r=(e-n.top)/this.zoom-20;return i?{left:bu(s),top:bu(r)}:{left:s,top:r}}handleActionDragExternal(t){var e,i,o;const{action:n,nodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,actionHeight:d=60,isLastAction:c=!1}=t.detail,h=!this.isActionExternalDrag;if(this.isActionExternalDrag=!0,this.actionDragLastDetail={action:n,nodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,actionHeight:d,isLastAction:c},h){null!==(i=null===(e=this.querySelector("#canvas"))||void 0===e?void 0:e.classList.contains("shift-held"))&&void 0!==i&&i?(this.actionDragIsCopy=!0,this.showActionOriginal(!0)):null===(o=this.querySelector("#drag-hint"))||void 0===o||o.classList.add("visible")}const u=this.getNodeAtPosition(a,l);if(u&&u!==s){const t=this.definition._ui.nodes[u],e=this.definition.nodes.find(t=>t.uuid===u);if("execute_actions"===(null==t?void 0:t.type)&&e){if(this.previousActionDragTargetNodeUuid&&this.previousActionDragTargetNodeUuid!==u){const t=this.querySelector(`temba-flow-node[data-node-uuid="${this.previousActionDragTargetNodeUuid}"]`);t&&t.dispatchEvent(new CustomEvent("action-drag-leave",{detail:{},bubbles:!1}))}this.actionDragTargetNodeUuid=u,this.previousActionDragTargetNodeUuid=u,this.canvasDropPreview=null;const t=this.querySelector(`temba-flow-node[data-node-uuid="${s}"]`);t&&t.dispatchEvent(new CustomEvent("action-show-ghost",{detail:{},bubbles:!1}));const e=this.querySelector(`temba-flow-node[data-node-uuid="${u}"]`);return e&&e.dispatchEvent(new CustomEvent("action-drag-over",{detail:{action:n,sourceNodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,actionHeight:d},bubbles:!1})),void this.requestUpdate()}}if(this.previousActionDragTargetNodeUuid){const t=this.querySelector(`temba-flow-node[data-node-uuid="${this.previousActionDragTargetNodeUuid}"]`);t&&t.dispatchEvent(new CustomEvent("action-drag-leave",{detail:{},bubbles:!1})),this.previousActionDragTargetNodeUuid=null}this.actionDragTargetNodeUuid=null;const p=this.querySelector(`temba-flow-node[data-node-uuid="${s}"]`);if(!c||this.actionDragIsCopy){p&&p.dispatchEvent(new CustomEvent("action-hide-ghost",{detail:{},bubbles:!1}));const t=this.calculateCanvasDropPosition(a,l,!1);this.canvasDropPreview={action:n,nodeUuid:s,actionIndex:r,position:t,actionHeight:d}}else p&&p.dispatchEvent(new CustomEvent("action-show-ghost",{detail:{},bubbles:!1})),this.canvasDropPreview=null;this.requestUpdate()}handleActionDragInternal(t){var e;if(this.previousActionDragTargetNodeUuid){const t=this.querySelector(`temba-flow-node[data-node-uuid="${this.previousActionDragTargetNodeUuid}"]`);t&&t.dispatchEvent(new CustomEvent("action-drag-leave",{detail:{},bubbles:!1})),this.previousActionDragTargetNodeUuid=null}this.canvasDropPreview=null,this.actionDragTargetNodeUuid=null,this.isActionExternalDrag=!1,this.actionDragIsCopy=!1,null===(e=this.querySelector("#drag-hint"))||void 0===e||e.classList.remove("visible"),this.actionDragLastDetail=null}showActionOriginal(t){if(!this.actionDragLastDetail)return;const e=this.querySelector(`temba-flow-node[data-node-uuid="${this.actionDragLastDetail.nodeUuid}"]`);e&&e.dispatchEvent(new CustomEvent(t?"action-show-original":"action-hide-original",{detail:{},bubbles:!1}))}reprocessActionDrag(){if(!this.actionDragLastDetail)return;const{action:t,nodeUuid:e,actionIndex:i,mouseX:o,mouseY:n,actionHeight:s}=this.actionDragLastDetail,r=this.querySelector(`temba-flow-node[data-node-uuid="${e}"]`);if(!this.actionDragTargetNodeUuid)if(this.actionDragIsCopy){r&&r.dispatchEvent(new CustomEvent("action-hide-ghost",{detail:{},bubbles:!1}));const a=this.calculateCanvasDropPosition(o,n,!1);this.canvasDropPreview={action:t,nodeUuid:e,actionIndex:i,position:a,actionHeight:s}}else r&&r.dispatchEvent(new CustomEvent("action-show-ghost",{detail:{},bubbles:!1})),this.canvasDropPreview=null}handleActionDropExternal(t){var e,i,o;const{action:n,nodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,isLastAction:d=!1}=t.detail,c=this.actionDragIsCopy;this.isActionExternalDrag=!1,this.actionDragIsCopy=!1,this.actionDragLastDetail=null,this.previousActionDragTargetNodeUuid=null,null===(e=this.querySelector("#drag-hint"))||void 0===e||e.classList.remove("visible");const h=this.actionDragTargetNodeUuid;if(h&&h!==s){const t=this.querySelector(`temba-flow-node[data-node-uuid="${h}"]`);return t&&t.dispatchEvent(new CustomEvent("action-drop",{detail:{action:n,sourceNodeUuid:s,actionIndex:r,mouseX:a,mouseY:l,isCopy:c},bubbles:!1})),this.canvasDropPreview=null,void(this.actionDragTargetNodeUuid=null)}if(d&&!c)return this.canvasDropPreview=null,void(this.actionDragTargetNodeUuid=null);const u=this.calculateCanvasDropPosition(a,l,!0);if(!c){const t=this.definition.nodes.find(t=>t.uuid===s);if(!t)return;const e=t.actions.filter((t,e)=>e!==r);if(0===e.length)this.deleteNodes([s]);else{const o={...t,actions:e};null===(i=$d())||void 0===i||i.getState().updateNode(s,o)}}const p=c?{...n,uuid:Xt()}:n,m={uuid:Xt(),actions:[p],exits:[{uuid:Xt(),destination_uuid:null}]},g={position:u,type:"execute_actions",config:{}};null===(o=$d())||void 0===o||o.getState().addNode(m,g),c&&this.copyActionLocalizations(n.uuid,p.uuid),this.canvasDropPreview=null,this.actionDragTargetNodeUuid=null,requestAnimationFrame(()=>{this.checkCollisionsAndReflow([m.uuid])})}copyActionLocalizations(t,e){var i,o,n;const s=null===(i=this.definition)||void 0===i?void 0:i.localization;if(!s)return;const r=null===(o=$d())||void 0===o?void 0:o.getState();if(r)for(const i of Object.keys(s)){const o=null===(n=s[i])||void 0===n?void 0:n[t];o&&r.updateLocalization(i,e,JSON.parse(JSON.stringify(o)))}}closeOpenWindows(){var t;if(this.issuesWindowHidden||(this.issuesWindowHidden=!0),this.revisionsWindowHidden||(null===(t=this.getRevisionsWindow())||void 0===t||t.close(),this.revisionsWindowHidden=!0),this.simulatorActive){const t=document.querySelector("temba-simulator");null==t||t.handleClose()}}closeFloatingWindows(){var t;this.issuesWindowHidden||(this.issuesWindowHidden=!0),this.revisionsWindowHidden||(null===(t=this.getRevisionsWindow())||void 0===t||t.close(),this.revisionsWindowHidden=!0)}getRevisionsWindow(){return this.querySelector("temba-revisions-window")}handleIssuesTabClick(){this.issuesWindowHidden?(this.closeOpenWindows(),this.issuesWindowHidden=!1):this.issuesWindowHidden=!0}handleIssueSelected(t){var e;const{issue:i}=t.detail;this.issuesWindowHidden=!0,this.focusNode(i.node_uuid);const o=this.definition.nodes.find(t=>t.uuid===i.node_uuid);if(o)if(i.action_uuid){const t=null===(e=o.actions)||void 0===e?void 0:e.find(t=>t.uuid===i.action_uuid);t&&(this.editingAction=t,this.editingNode=o,this.editingNodeUI=this.definition._ui.nodes[i.node_uuid])}else this.editingNode=o,this.editingNodeUI=this.definition._ui.nodes[i.node_uuid]}handleRevisionViewed(){var t;this.viewingRevision=!0,this.closeFlowSearch(),null===(t=this.plumber)||void 0===t||t.reset()}handleRevisionCancelled(){var t;this.viewingRevision=!1,null===(t=this.plumber)||void 0===t||t.reset()}handleRevisionsClosed(){this.viewingRevision=!1,this.revisionsWindowHidden=!0}async handleRevisionReverted(t){var e;const{definition:i,languageCode:o}=t.detail;this.viewingRevision=!1,this.revisionsWindowHidden=!0,null===(e=this.plumber)||void 0===e||e.reset(),await this.saveChanges(i),$d().getState().fetchRevision(`/flow/revisions/${this.flow}`).finally(()=>{o&&this.handleLanguageChange(o)})}renderToolbarElement(){var t,e,i,o;const n=this.getLocalizationLanguages(),s=this.getAvailableLanguages(),r=null===(t=this.definition)||void 0===t?void 0:t.language,a=(null===(e=s.find(t=>t.code===r))||void 0===e?void 0:e.name)||r||"Primary language",l=!this.languageCode||this.languageCode===r||!n.some(t=>t.code===this.languageCode),d=l?null:n.find(t=>t.code===this.languageCode),c=d||{name:a},h=this.getLocalizationProgress(l?"":this.languageCode),u=Math.round(h.localized/Math.max(h.total,1)*100),p=[{name:a,value:Cm},...n.map(t=>{const e=this.getLocalizationProgress(t.code),i=Math.round(e.localized/Math.max(e.total,1)*100);return{name:t.name,value:t.code,percent:i}})];return W`
10554
10923
  <temba-editor-toolbar
10555
10924
  ?message-view=${this.showMessageTable}
10556
10925
  .zoom=${this.zoom}
@@ -10558,12 +10927,17 @@ background: #ccc;
10558
10927
  ?zoom-fitted=${this.zoomManager.isZoomFitted}
10559
10928
  ?revisions-active=${!this.revisionsWindowHidden}
10560
10929
  ?is-saving=${this.isSaving}
10561
- ?search-disabled=${null!==(e=null===(t=this.getRevisionsWindow())||void 0===t?void 0:t.isViewingRevision)&&void 0!==e&&e}
10930
+ ?search-disabled=${null!==(o=null===(i=this.getRevisionsWindow())||void 0===i?void 0:i.isViewingRevision)&&void 0!==o&&o}
10931
+ .languageOptions=${p}
10932
+ current-language-name=${c.name}
10933
+ ?is-base-language=${l}
10934
+ .languagePercent=${u}
10935
+ ?show-localization-tools=${Boolean(d)}
10562
10936
  @temba-button-clicked=${this.handleToolbarAction}
10563
10937
  ></temba-editor-toolbar>
10564
- `}handleToolbarAction(t){var e;const i=t.detail;switch(i.action){case"view-change":this.showMessageTable="table"===i.view;break;case"zoom-in":this.zoomManager.zoomIn();break;case"zoom-out":this.zoomManager.zoomOut();break;case"zoom-to-fit":this.zoomManager.zoomToFit();break;case"zoom-to-full":this.zoomManager.zoomToFull();break;case"revisions":this.revisionsWindowHidden?(this.closeOpenWindows(),this.revisionsWindowHidden=!1):(null===(e=this.getRevisionsWindow())||void 0===e||e.close(),this.revisionsWindowHidden=!0);break;case"search":this.openFlowSearch()}}focusNode(t){const e=this.querySelector(`temba-flow-node[uuid="${t}"]`);if(!e)return;const i=this.querySelector("#editor");if(!i)return;const o=i.getBoundingClientRect(),n=o.width/2,s=o.height/2,r=e.offsetLeft+e.offsetWidth/2,a=e.offsetTop+e.offsetHeight/2,l=r*this.zoom-n,d=a*this.zoom-s;i.scrollTo({left:Math.max(0,l),top:Math.max(0,d),behavior:"smooth"})}handleSearchResultSelected(t){var e,i,o;const n=t.detail;if(n.stickyField)return void this.focusCanvasElement(`temba-sticky-note[uuid="${n.nodeUuid}"]`,n.stickyField);const s=this.definition.nodes.find(t=>t.uuid===n.nodeUuid);if(!s)return;const r=null===(e=this.definition._ui)||void 0===e?void 0:e.nodes[n.nodeUuid];if(this.showMessageTable){const t=this.querySelector("temba-message-table");null===(i=null==t?void 0:t.focusSearchResult)||void 0===i||i.call(t,n.nodeUuid,(null===(o=n.action)||void 0===o?void 0:o.uuid)||null)}else this.focusNode(n.nodeUuid);setTimeout(()=>{n.action?(this.editingAction=n.action,this.editingNode=s,this.editingNodeUI=r,this.dialogOrigin=null):(this.editingNode=s,this.editingNodeUI=r,this.dialogOrigin=null)},200)}focusCanvasElement(t,e){const i=this.querySelector(t);if(!i)return;const o=this.querySelector("#editor");if(!o)return;const n=o.getBoundingClientRect(),s=i.offsetLeft+i.offsetWidth/2,r=i.offsetTop+i.offsetHeight/2,a=s*this.zoom-n.width/2,l=r*this.zoom-n.height/2;o.scrollTo({left:Math.max(0,a),top:Math.max(0,l),behavior:"smooth"}),e&&setTimeout(()=>{var t;const o=null===(t=i.shadowRoot)||void 0===t?void 0:t.querySelector(`.sticky-${e}`);o&&o.focus()},300)}isReadOnly(){return this.viewingRevision||this.isTranslating}render(){var t,e,i;const o=W`<style>
10565
- ${r(Nm.styles.cssText)}
10566
- ${r(zm.styles.cssText)}
10938
+ `}handleToolbarAction(t){var e,i;const o=t.detail;switch(o.action){case"view-change":this.showMessageTable="table"===o.view;break;case"zoom-in":this.zoomManager.zoomIn();break;case"zoom-out":this.zoomManager.zoomOut();break;case"zoom-to-fit":this.zoomManager.zoomToFit();break;case"zoom-to-full":this.zoomManager.zoomToFull();break;case"revisions":this.revisionsWindowHidden?(this.closeOpenWindows(),this.revisionsWindowHidden=!1):(null===(e=this.getRevisionsWindow())||void 0===e||e.close(),this.revisionsWindowHidden=!0);break;case"search":this.openFlowSearch();break;case"language-change":o.isPrimary?this.handleLanguageChange((null===(i=this.definition)||void 0===i?void 0:i.language)||""):o.languageCode&&this.handleLanguageChange(o.languageCode)}}focusNode(t){const e=this.querySelector(`temba-flow-node[uuid="${t}"]`);if(!e)return;const i=this.querySelector("#editor");if(!i)return;const o=i.getBoundingClientRect(),n=o.width/2,s=o.height/2,r=e.offsetLeft+e.offsetWidth/2,a=e.offsetTop+e.offsetHeight/2,l=r*this.zoom-n,d=a*this.zoom-s;i.scrollTo({left:Math.max(0,l),top:Math.max(0,d),behavior:"smooth"})}handleSearchResultSelected(t){var e,i,o;const n=t.detail;if(n.stickyField)return void this.focusCanvasElement(`temba-sticky-note[uuid="${n.nodeUuid}"]`,n.stickyField);const s=this.definition.nodes.find(t=>t.uuid===n.nodeUuid);if(!s)return;const r=null===(e=this.definition._ui)||void 0===e?void 0:e.nodes[n.nodeUuid];if(this.showMessageTable){const t=this.querySelector("temba-message-table");null===(i=null==t?void 0:t.focusSearchResult)||void 0===i||i.call(t,n.nodeUuid,(null===(o=n.action)||void 0===o?void 0:o.uuid)||null)}else this.focusNode(n.nodeUuid);setTimeout(()=>{n.action?(this.editingAction=n.action,this.editingNode=s,this.editingNodeUI=r,this.dialogOrigin=null):(this.editingNode=s,this.editingNodeUI=r,this.dialogOrigin=null)},200)}focusCanvasElement(t,e){const i=this.querySelector(t);if(!i)return;const o=this.querySelector("#editor");if(!o)return;const n=o.getBoundingClientRect(),s=i.offsetLeft+i.offsetWidth/2,r=i.offsetTop+i.offsetHeight/2,a=s*this.zoom-n.width/2,l=r*this.zoom-n.height/2;o.scrollTo({left:Math.max(0,a),top:Math.max(0,l),behavior:"smooth"}),e&&setTimeout(()=>{var t;const o=null===(t=i.shadowRoot)||void 0===t?void 0:t.querySelector(`.sticky-${e}`);o&&o.focus()},300)}isReadOnly(){return this.viewingRevision||this.isTranslating}render(){var t,e,i;const o=W`<style>
10939
+ ${r(Fm.styles.cssText)}
10940
+ ${r(Lm.styles.cssText)}
10567
10941
  </style>`,n=(null===(e=null===(t=this.definition)||void 0===t?void 0:t._ui)||void 0===e?void 0:e.stickies)||{},s=this.definition&&this.definition.nodes.length>0&&this.definition.nodes.some(t=>{var e;return!(null===(e=this.definition._ui)||void 0===e?void 0:e.nodes[t.uuid])});return W`${o}
10568
10942
  <temba-issues-window
10569
10943
  .issues=${this.flowIssues}
@@ -10676,7 +11050,7 @@ background: #ccc;
10676
11050
  ></temba-node-type-selector>`}
10677
11051
  <temba-flow-search
10678
11052
  .scope=${this.showMessageTable?"table":"flow"}
10679
- .includeCategories=${!1}
11053
+ .includeCategories=${this.isTranslating&&this.hasAnyNodeWithLocalizeCategories()}
10680
11054
  @temba-search-result-selected=${this.handleSearchResultSelected}
10681
11055
  ></temba-flow-search>
10682
11056
  ${!this.showMessageTable&&(null===(i=this.flowIssues)||void 0===i?void 0:i.length)?W`
@@ -10689,376 +11063,7 @@ background: #ccc;
10689
11063
  .active=${!this.issuesWindowHidden}
10690
11064
  @temba-button-clicked=${()=>this.handleIssuesTabClick()}
10691
11065
  ></temba-floating-tab>
10692
- `:""} `}}Nm.MAX_FLOW_SETTINGS=50,t([mt({type:String})],Nm.prototype,"flow",void 0),t([mt({type:String})],Nm.prototype,"version",void 0),t([mt({type:String})],Nm.prototype,"flowType",void 0),t([mt({type:Array})],Nm.prototype,"features",void 0),t([Ad(Sd,t=>t.flowDefinition)],Nm.prototype,"definition",void 0),t([Ad(Sd,t=>t.simulatorActive)],Nm.prototype,"simulatorActive",void 0),t([Ad(Sd,t=>t.canvasSize)],Nm.prototype,"canvasSize",void 0),t([Ad(Sd,t=>t.dirtyDate)],Nm.prototype,"dirtyDate",void 0),t([Ad(Sd,t=>t.languageCode)],Nm.prototype,"languageCode",void 0),t([Ad(Sd,t=>t.isTranslating)],Nm.prototype,"isTranslating",void 0),t([Ad(Sd,t=>t.workspace)],Nm.prototype,"workspace",void 0),t([Ad(Sd,t=>t.getCurrentActivity())],Nm.prototype,"activityData",void 0),t([Ad(Sd,t=>{var e,i;return null!==(i=null===(e=t.flowInfo)||void 0===e?void 0:e.issues)&&void 0!==i?i:Pm})],Nm.prototype,"flowIssues",void 0),t([gt()],Nm.prototype,"isDragging",void 0),t([gt()],Nm.prototype,"currentDragItem",void 0),t([gt()],Nm.prototype,"selectedItems",void 0),t([gt()],Nm.prototype,"isSelecting",void 0),t([gt()],Nm.prototype,"selectionBox",void 0),t([gt()],Nm.prototype,"targetId",void 0),t([gt()],Nm.prototype,"sourceId",void 0),t([gt()],Nm.prototype,"dragFromNodeId",void 0),t([gt()],Nm.prototype,"originalConnectionTargetId",void 0),t([gt()],Nm.prototype,"isValidTarget",void 0),t([gt()],Nm.prototype,"issuesWindowHidden",void 0),t([gt()],Nm.prototype,"revisionsWindowHidden",void 0),t([gt()],Nm.prototype,"viewingRevision",void 0),t([gt()],Nm.prototype,"isSaving",void 0),t([gt()],Nm.prototype,"saveError",void 0),t([gt()],Nm.prototype,"zoom",void 0),t([gt()],Nm.prototype,"editingNode",void 0),t([gt()],Nm.prototype,"editingNodeUI",void 0),t([gt()],Nm.prototype,"editingAction",void 0),t([mt({type:Boolean,reflect:!0,attribute:"message-view"})],Nm.prototype,"showMessageTable",void 0),t([gt()],Nm.prototype,"isCreatingNewNode",void 0),t([gt()],Nm.prototype,"pendingNodePosition",void 0),t([gt()],Nm.prototype,"canvasDropPreview",void 0),t([gt()],Nm.prototype,"addActionToNodeUuid",void 0),t([gt()],Nm.prototype,"actionDragTargetNodeUuid",void 0),t([gt()],Nm.prototype,"connectionPlaceholder",void 0);const Bm="__primary_language__";class Fm extends Be{constructor(){super(...arguments),this.messageView=!1,this.zoom=1,this.zoomInitialized=!1,this.zoomFitted=!1,this.revisionsActive=!1,this.isSaving=!1,this.searchDisabled=!1,this.languageOptions=[],this.currentLanguageName="",this.isBaseLanguage=!0,this.languagePercent=0,this.showLocalizationTools=!1,this.showLanguageOptions=!1}static get styles(){return a`
10693
- :host {
10694
- display: block;
10695
- }
10696
-
10697
- .editor-toolbar {
10698
- --toolbar-control-height: 28px;
10699
- --toolbar-translation-control-height: 28px;
10700
- display: flex;
10701
- align-items: center;
10702
- padding: 6px 12px;
10703
- background: #fff;
10704
- border-bottom: 1px solid #e8e8e8;
10705
- flex-shrink: 0;
10706
- gap: 8px;
10707
- }
10708
-
10709
- .toolbar-left {
10710
- display: flex;
10711
- align-items: center;
10712
- gap: 2px;
10713
- }
10714
-
10715
- .toolbar-right {
10716
- display: flex;
10717
- align-items: center;
10718
- gap: 2px;
10719
- margin-left: auto;
10720
- }
10721
-
10722
- .toolbar-btn {
10723
- width: var(--toolbar-control-height);
10724
- height: var(--toolbar-control-height);
10725
- border: none;
10726
- background: transparent;
10727
- border-radius: var(--curvature);
10728
- cursor: pointer;
10729
- display: flex;
10730
- align-items: center;
10731
- justify-content: center;
10732
- padding: 0;
10733
- color: #888;
10734
- font-size: 16px;
10735
- line-height: 1;
10736
- outline: none;
10737
- }
10738
-
10739
- .toolbar-btn:focus {
10740
- outline: none;
10741
- }
10742
-
10743
- .toolbar-btn:focus-visible {
10744
- outline: 2px solid #0064c8;
10745
- outline-offset: 2px;
10746
- }
10747
-
10748
- .toolbar-btn:hover {
10749
- background: rgba(0, 0, 0, 0.06);
10750
- color: #555;
10751
- }
10752
-
10753
- .toolbar-btn:disabled {
10754
- opacity: 0.3;
10755
- cursor: default;
10756
- background: transparent;
10757
- }
10758
-
10759
- .toolbar-btn.active {
10760
- background: rgba(0, 100, 200, 0.1);
10761
- color: #0064c8;
10762
- }
10763
-
10764
- .toolbar-btn.active:hover {
10765
- background: rgba(0, 100, 200, 0.15);
10766
- }
10767
-
10768
- .toolbar-tip {
10769
- display: flex;
10770
- align-items: center;
10771
- }
10772
-
10773
- .toolbar-divider {
10774
- width: 1px;
10775
- height: 16px;
10776
- background: #e0e0e0;
10777
- margin: 0 4px;
10778
- }
10779
-
10780
- .toolbar-group {
10781
- display: flex;
10782
- align-items: center;
10783
- gap: 4px;
10784
- height: var(--toolbar-control-height);
10785
- box-sizing: border-box;
10786
- padding: 0 3px;
10787
- border: 1px solid #d7dce2;
10788
- border-radius: calc(var(--curvature) + 2px);
10789
- background: #f7f9fb;
10790
- }
10791
-
10792
- .toolbar-group-divider {
10793
- width: 1px;
10794
- height: 18px;
10795
- background: #d7dce2;
10796
- margin: 0 2px;
10797
- }
10798
-
10799
- .toolbar-language {
10800
- position: relative;
10801
- display: flex;
10802
- align-items: center;
10803
- }
10804
-
10805
- .toolbar-language-group {
10806
- display: flex;
10807
- align-items: center;
10808
- gap: 6px;
10809
- margin-left: 2px;
10810
- }
10811
-
10812
- .toolbar-zoom-group {
10813
- gap: 2px;
10814
- }
10815
-
10816
- .language-pill {
10817
- display: flex;
10818
- align-items: center;
10819
- gap: 6px;
10820
- background: #e9eef4;
10821
- color: #0064c8;
10822
- height: var(--toolbar-translation-control-height);
10823
- padding: 0 8px;
10824
- border-radius: var(--curvature);
10825
- box-sizing: border-box;
10826
- font-size: 13px;
10827
- font-weight: 400;
10828
- white-space: nowrap;
10829
- cursor: pointer;
10830
- --icon-color: #0064c8;
10831
- --icon-size: 16px;
10832
- border: none;
10833
- outline: none;
10834
- }
10835
-
10836
- .language-pill:hover {
10837
- filter: brightness(1.04);
10838
- }
10839
-
10840
- .language-pill.primary {
10841
- background: #fff;
10842
- border: 1px solid #d7dce2;
10843
- }
10844
-
10845
- .language-pill.complete {
10846
- background: #d4f5e0;
10847
- color: #1a7f37;
10848
- --icon-color: #1a7f37;
10849
- }
10850
-
10851
- .language-pill-caret {
10852
- margin-left: 1px;
10853
- --icon-color: currentColor;
10854
- --icon-size: 12px;
10855
- }
10856
-
10857
- .language-percent {
10858
- display: inline-block;
10859
- font-size: 12px;
10860
- font-weight: 700;
10861
- line-height: 1;
10862
- color: #0064c8;
10863
- white-space: nowrap;
10864
- }
10865
-
10866
- .language-pill.complete .language-percent {
10867
- color: #1a7f37;
10868
- }
10869
-
10870
- .toolbar-zoom-level {
10871
- font-size: 12px;
10872
- min-width: 40px;
10873
- text-align: center;
10874
- color: #555;
10875
- font-weight: 500;
10876
- }
10877
-
10878
- .toolbar-translation {
10879
- display: flex;
10880
- align-items: center;
10881
- gap: 4px;
10882
- }
10883
-
10884
- .toolbar-btn.language-tool {
10885
- width: var(--toolbar-translation-control-height);
10886
- height: var(--toolbar-translation-control-height);
10887
- }
10888
- `}fireToolbarAction(t,e={}){this.fireCustomEvent(Io.ButtonClicked,{action:t,...e})}handleLanguageIconClick(){this.showLanguageOptions?this.showLanguageOptions=!1:(this.showLanguageOptions=!0,requestAnimationFrame(()=>{const t=()=>{this.showLanguageOptions=!1,document.removeEventListener("click",t)};document.addEventListener("click",t,{once:!0})}))}handleLanguageOptionSelected(t){var e;if(!this.showLanguageOptions)return;const i=null===(e=t.detail)||void 0===e?void 0:e.selected;(null==i?void 0:i.value)===Bm?this.fireToolbarAction("language-change",{isPrimary:!0}):(null==i?void 0:i.value)&&this.fireToolbarAction("language-change",{languageCode:i.value}),this.showLanguageOptions=!1}isMacPlatform(){return"undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)}getSearchShortcutLabel(){return this.isMacPlatform()?"⌘F":"Ctrl+F"}renderTip(t,e){return W`
10889
- <temba-tip
10890
- class="toolbar-tip"
10891
- .text=${"string"==typeof t?t:""}
10892
- .content=${"string"==typeof t?null:t}
10893
- position="top"
10894
- >
10895
- ${e}
10896
- </temba-tip>
10897
- `}renderShortcutLabel(t,e){return W`<span style="display:inline-flex; align-items:center; gap:8px;">
10898
- <span>${t}</span>
10899
- <kbd>${e}</kbd>
10900
- </span>`}renderLanguageOption(t,e){var i;if(t.value===Bm){return W`
10901
- <div
10902
- style="display:flex; align-items:center; justify-content:space-between; gap:8px; background:${e?"#e1e8ef":"#edf1f5"}; color:#2f3f52; border-radius:4px; padding:6px 10px;"
10903
- >
10904
- <span>${t.name}</span>
10905
- <span
10906
- style="display:inline-flex; align-items:center; border-radius:999px; background:rgba(47, 63, 82, 0.12); color:#2f3f52; font-size:10px; font-weight:700; line-height:1; padding:3px 7px;"
10907
- >Original</span
10908
- >
10909
- </div>
10910
- `}const o=100===t.percent,n=o?"#d4f5e0":"",s=o?"#c0edce":"",r=o?"color:#1a7f37;":"color:#5f6b7a;";return W`
10911
- <div
10912
- style="display:flex; align-items:center; justify-content:space-between; gap:8px; padding:6px 10px; ${n?`background:${n};`:""} ${o?"border-radius:4px;":""}"
10913
- @mouseenter=${o?t=>{t.currentTarget.style.background=s}:null}
10914
- @mouseleave=${o?t=>{t.currentTarget.style.background=n}:null}
10915
- >
10916
- <span style="${o?"color:#1a7f37;":""}"
10917
- >${t.name}</span
10918
- >
10919
- <span style="font-size:11px; font-weight:600; ${r}"
10920
- >${null!==(i=t.percent)&&void 0!==i?i:0}%</span
10921
- >
10922
- </div>
10923
- `}render(){var t;const e=this.languageOptions.length>1,i=this.messageView?"Search table":"Search flow";return W`
10924
- <div class="editor-toolbar">
10925
- <div class="toolbar-left">
10926
- ${this.renderTip("Flow View",W`
10927
- <button
10928
- class="toolbar-btn ${this.messageView?"":"active"}"
10929
- @click=${()=>this.fireToolbarAction("view-change",{view:"flow"})}
10930
- aria-label="Flow View"
10931
- >
10932
- <temba-icon name="flow" size="1"></temba-icon>
10933
- </button>
10934
- `)}
10935
- ${this.renderTip("Table View",W`
10936
- <button
10937
- class="toolbar-btn ${this.messageView?"active":""}"
10938
- @click=${()=>this.fireToolbarAction("view-change",{view:"table"})}
10939
- aria-label="Table View"
10940
- >
10941
- <temba-icon name=${ko.quick_replies} size="1"></temba-icon>
10942
- </button>
10943
- `)}
10944
- ${e?W`
10945
- <div class="toolbar-divider"></div>
10946
- <div class="toolbar-language-group">
10947
- <div class="toolbar-language">
10948
- ${this.renderTip("Change language",W`
10949
- <button
10950
- class="language-pill ${this.isBaseLanguage?"primary":100===this.languagePercent?"complete":""}"
10951
- id="language-btn"
10952
- @click=${this.handleLanguageIconClick}
10953
- aria-label="Change language"
10954
- >
10955
- <temba-icon name=${ko.language}></temba-icon>
10956
- <span>${this.currentLanguageName}</span>
10957
- ${this.isBaseLanguage?"":W`<span class="language-percent"
10958
- >${this.languagePercent}%</span
10959
- >`}
10960
- <temba-icon
10961
- class="language-pill-caret"
10962
- name=${this.showLanguageOptions?ko.arrow_up:ko.arrow_down}
10963
- ></temba-icon>
10964
- </button>
10965
- `)}
10966
- <temba-options
10967
- .anchorTo=${null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("#language-btn")}
10968
- .options=${this.languageOptions}
10969
- .renderOption=${this.renderLanguageOption}
10970
- ?visible=${this.showLanguageOptions}
10971
- @temba-selection=${this.handleLanguageOptionSelected}
10972
- style="--temba-options-option-margin:4px; --temba-options-option-padding:0; --temba-options-option-radius:4px;"
10973
- min-width="230"
10974
- ></temba-options>
10975
- </div>
10976
- ${this.showLocalizationTools?this.renderTranslationTools():""}
10977
- </div>
10978
- `:""}
10979
- </div>
10980
- <div class="toolbar-right">
10981
- ${this.messageView?"":W`
10982
- ${this.renderTip("Zoom to fit",W`
10983
- <button
10984
- class="toolbar-btn"
10985
- @click=${()=>this.fireToolbarAction("zoom-to-fit")}
10986
- ?disabled=${!this.zoomInitialized||this.zoomFitted}
10987
- aria-label="Zoom to fit"
10988
- >
10989
- <temba-icon
10990
- name=${ko.zoom_fit}
10991
- size="1"
10992
- ></temba-icon>
10993
- </button>
10994
- `)}
10995
- <div class="toolbar-divider"></div>
10996
- ${this.renderTip("Zoom out",W`
10997
- <button
10998
- class="toolbar-btn"
10999
- @click=${()=>this.fireToolbarAction("zoom-out")}
11000
- ?disabled=${!this.zoomInitialized||this.zoom<=.3}
11001
- aria-label="Zoom out"
11002
- >
11003
-
11004
- </button>
11005
- `)}
11006
- <span class="toolbar-zoom-level"
11007
- >${this.zoomInitialized?`${Math.round(100*this.zoom)}%`:""}</span
11008
- >
11009
- ${this.renderTip("Zoom in",W`
11010
- <button
11011
- class="toolbar-btn"
11012
- @click=${()=>this.fireToolbarAction("zoom-in")}
11013
- ?disabled=${!this.zoomInitialized||this.zoom>=1}
11014
- aria-label="Zoom in"
11015
- >
11016
- +
11017
- </button>
11018
- `)}
11019
- <div class="toolbar-divider"></div>
11020
- ${this.renderTip("Zoom to 100%",W`
11021
- <button
11022
- class="toolbar-btn"
11023
- @click=${()=>this.fireToolbarAction("zoom-to-full")}
11024
- ?disabled=${!this.zoomInitialized||this.zoom>=1}
11025
- aria-label="Zoom to 100%"
11026
- >
11027
- <temba-icon
11028
- name=${ko.zoom_in}
11029
- size="1"
11030
- ></temba-icon>
11031
- </button>
11032
- `)}
11033
- <div class="toolbar-divider"></div>
11034
- `}
11035
- ${this.renderTip("Revisions",W`
11036
- <button
11037
- class="toolbar-btn ${this.revisionsActive?"active":""}"
11038
- @click=${()=>this.fireToolbarAction("revisions")}
11039
- aria-label="Revisions"
11040
- >
11041
- <temba-icon
11042
- name=${this.isSaving?"progress_spinner":"revisions"}
11043
- size="1"
11044
- ?spin=${this.isSaving}
11045
- ></temba-icon>
11046
- </button>
11047
- `)}
11048
- <div class="toolbar-divider"></div>
11049
- ${this.renderTip(this.renderShortcutLabel(i,this.getSearchShortcutLabel()),W`
11050
- <button
11051
- class="toolbar-btn"
11052
- @click=${()=>this.fireToolbarAction("search")}
11053
- ?disabled=${this.searchDisabled}
11054
- aria-label=${i}
11055
- >
11056
- <temba-icon name=${ko.search} size="1"></temba-icon>
11057
- </button>
11058
- `)}
11059
- </div>
11060
- </div>
11061
- `}renderTranslationTools(){return W``}}t([mt({type:Boolean,attribute:"message-view"})],Fm.prototype,"messageView",void 0),t([mt({type:Number})],Fm.prototype,"zoom",void 0),t([mt({type:Boolean,attribute:"zoom-initialized"})],Fm.prototype,"zoomInitialized",void 0),t([mt({type:Boolean,attribute:"zoom-fitted"})],Fm.prototype,"zoomFitted",void 0),t([mt({type:Boolean,attribute:"revisions-active"})],Fm.prototype,"revisionsActive",void 0),t([mt({type:Boolean,attribute:"is-saving"})],Fm.prototype,"isSaving",void 0),t([mt({type:Boolean,attribute:"search-disabled"})],Fm.prototype,"searchDisabled",void 0),t([mt({type:Array})],Fm.prototype,"languageOptions",void 0),t([mt({type:String,attribute:"current-language-name"})],Fm.prototype,"currentLanguageName",void 0),t([mt({type:Boolean,attribute:"is-base-language"})],Fm.prototype,"isBaseLanguage",void 0),t([mt({type:Number,attribute:"language-percent"})],Fm.prototype,"languagePercent",void 0),t([mt({type:Boolean,attribute:"show-localization-tools"})],Fm.prototype,"showLocalizationTools",void 0),t([gt()],Fm.prototype,"showLanguageOptions",void 0);class qm extends Be{constructor(){super(...arguments),this.dragging=!1,this.selected=!1,this.colorPickerExpanded=!1,this.removing=!1,this.isTouchDevice=navigator.maxTouchPoints>0&&/iPad|iPhone|Macintosh/.test(navigator.userAgent),this.editingField=null,this.removalTimeout=null,this.resizing=!1,this.resizeStartX=0,this.resizeStartY=0,this.resizeStartWidth=0,this.resizeStartHeight=0,this.resizeZoom=1,this.boundResizeMove=this.handleResizeMove.bind(this),this.boundResizeEnd=this.handleResizeEnd.bind(this),this.boundResizeTouchMove=this.handleResizeTouchMove.bind(this),this.boundResizeTouchEnd=this.handleResizeTouchEnd.bind(this)}static get styles(){return a`
11066
+ `:""} `}}Fm.MAX_FLOW_SETTINGS=50,t([mt({type:String})],Fm.prototype,"flow",void 0),t([mt({type:String})],Fm.prototype,"version",void 0),t([mt({type:String})],Fm.prototype,"flowType",void 0),t([mt({type:Array})],Fm.prototype,"features",void 0),t([Ad(Sd,t=>t.flowDefinition)],Fm.prototype,"definition",void 0),t([Ad(Sd,t=>t.simulatorActive)],Fm.prototype,"simulatorActive",void 0),t([Ad(Sd,t=>t.canvasSize)],Fm.prototype,"canvasSize",void 0),t([Ad(Sd,t=>t.dirtyDate)],Fm.prototype,"dirtyDate",void 0),t([Ad(Sd,t=>t.languageCode)],Fm.prototype,"languageCode",void 0),t([Ad(Sd,t=>t.isTranslating)],Fm.prototype,"isTranslating",void 0),t([Ad(Sd,t=>t.workspace)],Fm.prototype,"workspace",void 0),t([Ad(Sd,t=>t.getCurrentActivity())],Fm.prototype,"activityData",void 0),t([Ad(Sd,t=>{var e,i;return null!==(i=null===(e=t.flowInfo)||void 0===e?void 0:e.issues)&&void 0!==i?i:Nm})],Fm.prototype,"flowIssues",void 0),t([gt()],Fm.prototype,"isDragging",void 0),t([gt()],Fm.prototype,"currentDragItem",void 0),t([gt()],Fm.prototype,"selectedItems",void 0),t([gt()],Fm.prototype,"isSelecting",void 0),t([gt()],Fm.prototype,"selectionBox",void 0),t([gt()],Fm.prototype,"targetId",void 0),t([gt()],Fm.prototype,"sourceId",void 0),t([gt()],Fm.prototype,"dragFromNodeId",void 0),t([gt()],Fm.prototype,"originalConnectionTargetId",void 0),t([gt()],Fm.prototype,"isValidTarget",void 0),t([gt()],Fm.prototype,"issuesWindowHidden",void 0),t([gt()],Fm.prototype,"revisionsWindowHidden",void 0),t([gt()],Fm.prototype,"viewingRevision",void 0),t([gt()],Fm.prototype,"isSaving",void 0),t([gt()],Fm.prototype,"saveError",void 0),t([gt()],Fm.prototype,"zoom",void 0),t([gt()],Fm.prototype,"editingNode",void 0),t([gt()],Fm.prototype,"editingNodeUI",void 0),t([gt()],Fm.prototype,"editingAction",void 0),t([mt({type:Boolean,reflect:!0,attribute:"message-view"})],Fm.prototype,"showMessageTable",void 0),t([gt()],Fm.prototype,"isCreatingNewNode",void 0),t([gt()],Fm.prototype,"pendingNodePosition",void 0),t([gt()],Fm.prototype,"canvasDropPreview",void 0),t([gt()],Fm.prototype,"addActionToNodeUuid",void 0),t([gt()],Fm.prototype,"actionDragTargetNodeUuid",void 0),t([gt()],Fm.prototype,"connectionPlaceholder",void 0);class qm extends Be{constructor(){super(...arguments),this.dragging=!1,this.selected=!1,this.colorPickerExpanded=!1,this.removing=!1,this.isTouchDevice=navigator.maxTouchPoints>0&&/iPad|iPhone|Macintosh/.test(navigator.userAgent),this.editingField=null,this.removalTimeout=null,this.resizing=!1,this.resizeStartX=0,this.resizeStartY=0,this.resizeStartWidth=0,this.resizeStartHeight=0,this.resizeZoom=1,this.boundResizeMove=this.handleResizeMove.bind(this),this.boundResizeEnd=this.handleResizeEnd.bind(this),this.boundResizeTouchMove=this.handleResizeTouchMove.bind(this),this.boundResizeTouchEnd=this.handleResizeTouchEnd.bind(this)}static get styles(){return a`
11062
11067
  :host {
11063
11068
  --sticky-color: #fef08a;
11064
11069
  --sticky-border-color: #facc15;
@@ -13073,7 +13078,7 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
13073
13078
  color: #b8a060;
13074
13079
  margin-right: 4px;
13075
13080
  }
13076
- `}get isTranslating(){return!this.forceBase&&this._isTranslating}connectedCallback(){super.connectedCallback(),this.initializeFormData(),document.addEventListener("keydown",this.boundHandleEscape)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("keydown",this.boundHandleEscape)}handleEscapeKey(t){"Escape"===t.key&&this.isOpen&&this.handleCancel()}willUpdate(t){super.willUpdate(t),(t.has("node")||t.has("action")||t.has("nodeUI"))&&(!this.action||this.node&&this.nodeUI?this.node&&this.nodeUI?(this.isOpen=!0,this.initializeFormData(),this.errors={}):this.action||this.node&&this.nodeUI||(this.isOpen=!1):(this.isOpen=!0,this.initializeFormData(),this.errors={}))}updated(t){super.updated(t),(t.has("node")||t.has("action")||t.has("nodeUI"))&&(!this.action||this.node&&this.nodeUI?this.node&&this.nodeUI&&this.resolveFormData():this.resolveFormData())}initializeFormData(){var t,e,i,o,n,s,r,a,l,d,c,h,u;this.groupCollapseState={};const p=this.getNodeConfig();if(p&&"execute_actions"!==p.type&&"terminal"!==p.type||!this.action){if(this.node){const t=this.getNodeConfig();if(this.isTranslating&&"categories"===(null==t?void 0:t.localizable)&&t.toLocalizationFormData){const e=(null===(n=null===(o=this.flowDefinition)||void 0===o?void 0:o.localization)||void 0===n?void 0:n[this.languageCode])||{};this.formData=t.toLocalizationFormData(this.node,e);const i=new Set(Mm(null===(s=this.nodeUI)||void 0===s?void 0:s.type,null===(r=this.node.router)||void 0===r?void 0:r.categories).map(t=>t.uuid));this.formData.categories&&"object"==typeof this.formData.categories&&!Array.isArray(this.formData.categories)&&(this.formData={...this.formData,categories:Object.fromEntries(Object.entries(this.formData.categories).filter(([t])=>i.has(t)))});const l=(null===(a=this.nodeUI)||void 0===a?void 0:a.config)||{},d=l.localizeCategories||this.formData.categories&&Object.values(this.formData.categories).some(t=>t.localizedName),c=l.localizeRules||this.formData.rules&&Object.values(this.formData.rules).some(t=>{var e;return null===(e=t.localizedArguments)||void 0===e?void 0:e.some(t=>t)});d||delete this.formData.categories,c||delete this.formData.rules}else(null==t?void 0:t.toFormData)?this.formData=t.toFormData(this.node,this.nodeUI):this.formData={...this.node};if("wait_for_response"===(null===(l=this.nodeUI)||void 0===l?void 0:l.type)&&!this.formData.result_name&&(null===(d=this.flowInfo)||void 0===d?void 0:d.results)&&!(null===(u=null===(h=null===(c=this.flowDefinition)||void 0===c?void 0:c._ui)||void 0===h?void 0:h.nodes)||void 0===u?void 0:u[this.node.uuid])){const t=new Set(this.flowInfo.results.map(t=>t.name));let e="Result",i=2;for(;t.has(e);)e=`Result ${i}`,i++;this.formData.result_name=e,this.formData._isNew=!0}this.processFormDataForEditing(),this.originalFormData=JSON.parse(JSON.stringify(this.formData))}}else{const o=ym[this.action.type];if(this.isTranslating&&(null==o?void 0:o.localizable)&&o.toLocalizationFormData){const n=(null===(i=null===(e=null===(t=this.flowDefinition)||void 0===t?void 0:t.localization)||void 0===e?void 0:e[this.languageCode])||void 0===i?void 0:i[this.action.uuid])||{};this.formData=o.toLocalizationFormData(this.action,n)}else(null==o?void 0:o.toFormData)?this.formData=o.toFormData(this.action):this.formData={...this.action};this.processFormDataForEditing(),this.originalFormData=JSON.parse(JSON.stringify(this.formData))}Object.keys(this.formData).forEach(t=>{const e=this.formData[t];Array.isArray(e)?this.formData[t]=[...e]:e&&"object"==typeof e&&(this.formData[t]={...e})})}async resolveFormData(){const t=this.getConfig();if(null==t?void 0:t.resolveFormData)try{const e=await t.resolveFormData(this.formData);if(e&&e!==this.formData){this.formData=e,this.processFormDataForEditing();const i=t.form;i&&Object.entries(i).forEach(([t,e])=>{if(e.dependsOn&&e.computeValue){const i=e.computeValue(this.formData,this.formData[t],this.originalFormData);this.formData={...this.formData,[t]:i}}}),this.requestUpdate()}}catch(t){}}processFormDataForEditing(){const t={...this.formData};Object.keys(t).forEach(e=>{const i=t[e];if(i&&"object"==typeof i&&!Array.isArray(i)){this.isKeyValueField(e)&&(t[e]=Object.entries(i).map(([t,e])=>({key:t,value:e})))}});const e=this.getConfig();(null==e?void 0:e.form)&&this.processSelectFields(t,e.form),this.formData=t}processSelectFields(t,e){Object.entries(e).forEach(([e,i])=>{const o=t[e];"select"===i.type&&o&&(t[e]=this.convertToSelectArray(o)),"array"===i.type&&Array.isArray(o)&&i.itemConfig&&o.forEach(t=>{this.processSelectFields(t,i.itemConfig)})})}convertToSelectArray(t){return Array.isArray(t)?t.map(t=>"string"==typeof t?{name:t,value:t}:t):"string"==typeof t?[{name:t,value:t}]:[t]}isKeyValueField(t){var e;const i=this.getConfig(),o=null==i?void 0:i.form;return"key-value"===(null===(e=null==o?void 0:o[t])||void 0===e?void 0:e.type)}getConfig(){if(this.node&&this.nodeUI){const t=this.getNodeConfig();if(("execute_actions"===this.nodeUI.type||"terminal"===this.nodeUI.type)&&this.action)return ym[this.action.type]||null;if(t)return t}return this.action&&ym[this.action.type]||null}getNodeConfig(){return this.nodeUI&&this.nodeUI.type?wm[this.nodeUI.type]:null}getHeaderColor(){var t,e;const i=this.getConfig();return(null==i?void 0:i.group)?(null===(t=Wu[i.group])||void 0===t?void 0:t.color)||(null===(e=Vu[i.group])||void 0===e?void 0:e.color):"#aaaaaa"}handleDialogButtonClick(t){const e=t.detail.button;"Save"===e.name?this.handleSave():"Cancel"===e.name&&this.handleCancel()}handleSave(){var t,e,i,o,n,s;const r=this.processFormDataForSave();if(!this.isTranslating){const t=this.validateForm();if(!t.valid)return this.errors=t.errors,void this.expandGroupsWithErrors(t.errors)}if(this.isTranslating){if(this.action){const t=ym[this.action.type];if((null==t?void 0:t.localizable)&&t.fromLocalizationFormData){const e=t.fromLocalizationFormData(r,this.action);return this.updateLocalization(this.languageCode,this.action.uuid,e),void this.fireCustomEvent(Io.NodeEditCancelled,{})}}if(this.node){const a=this.getNodeConfig();if("categories"===(null==a?void 0:a.localizable)&&a.fromLocalizationFormData){const l=a.fromLocalizationFormData(r,this.node),d=(null===(e=null===(t=this.flowDefinition)||void 0===t?void 0:t.localization)||void 0===e?void 0:e[this.languageCode])||{};Mm(null===(i=this.nodeUI)||void 0===i?void 0:i.type,null===(n=null===(o=this.node)||void 0===o?void 0:o.router)||void 0===n?void 0:n.categories).forEach(t=>{const e=t.uuid,i=l[e];i?this.updateLocalization(this.languageCode,e,i):d[e]&&this.updateLocalization(this.languageCode,e,{})});return((null===(s=this.node.router)||void 0===s?void 0:s.cases)||[]).forEach(t=>{const e=l[t.uuid];e?this.updateLocalization(this.languageCode,t.uuid,e):d[t.uuid]&&this.updateLocalization(this.languageCode,t.uuid,{})}),void this.fireCustomEvent(Io.NodeEditCancelled,{})}}}if(this.node&&this.node.router){const t=this.formDataToNode(r);this.updateFlowInfoResult(t);const e=this.getNodeConfig(),i=(null==e?void 0:e.toUIConfig)?e.toUIConfig(r):void 0;this.fireCustomEvent(Io.NodeSaved,{node:t,uiConfig:i})}else if(this.action){const t=this.formDataToAction(r);this.fireCustomEvent(Io.ActionSaved,{action:t})}else if(this.node){const t=this.formDataToNode(r),e=this.getNodeConfig(),i=(null==e?void 0:e.toUIConfig)?e.toUIConfig(r):void 0;this.fireCustomEvent(Io.NodeSaved,{node:t,uiConfig:i})}}updateFlowInfoResult(t){var e,i,o;if(!(null===(e=this.flowInfo)||void 0===e?void 0:e.results))return;const n=Sd.getState(),s=this.flowInfo.results.filter(e=>!e.node_uuids.includes(t.uuid)),r=null===(i=t.router)||void 0===i?void 0:i.result_name;if(r){const e=((null===(o=t.router)||void 0===o?void 0:o.categories)||[]).map(t=>t.name);s.push({key:r.toLowerCase().replace(/\s+/g,"_"),name:r,categories:e,node_uuids:[t.uuid]})}n.setFlowInfo({...this.flowInfo,results:s})}updateLocalization(t,e,i){Sd.getState().updateLocalization(t,e,i)}processFormDataForSave(){const t={...this.formData};return Object.keys(t).forEach(e=>{const i=t[e];if(Array.isArray(i)&&i.length>0&&"object"==typeof i[0]&&"key"in i[0]&&"value"in i[0]){const o={};i.forEach(({key:t,value:e})=>{""===t.trim()&&""===e.trim()||(o[t]=e)}),t[e]=o}else if(Array.isArray(i)&&0===i.length){this.isKeyValueField(e)&&(t[e]={})}}),t}handleCancel(){this.fireCustomEvent(Io.NodeEditCancelled,{})}validateForm(){const t={},e=this.getConfig();if(e&&(e.form&&Object.entries(e.form).forEach(([e,i])=>{const o=this.formData[e];if("select"===i.type&&i.allowCreate){let i=this.formData[e];i=Array.isArray(i)?i.find(t=>t.arbitrary):null,i&&i.arbitrary&&(t[e]='There was an error creating "'+i.name+'"')}!this.isTranslating&&i.required&&(!o||Array.isArray(o)&&0===o.length)&&(t[e]=`${i.label||e} is required.`),"string"==typeof o&&i.minLength&&o.length<i.minLength&&(t[e]=`${i.label||e} must be at least ${i.minLength} characters`),"string"==typeof o&&i.maxLength&&o.length>i.maxLength&&(t[e]=`${i.label||e} must be no more than ${i.maxLength} characters`)}),this.validateCategoryNames(t),e.validate)){let i;e.sanitize&&e.sanitize(this.formData),i=this.action?e.validate({...this.action,...this.formData}):e.validate(this.formData),Object.assign(t,i.errors)}return this.validateKeyValueUniqueness(t),{valid:0===Object.keys(t).length,errors:t}}validateKeyValueUniqueness(t){Object.entries(this.formData).forEach(([e,i])=>{if(Array.isArray(i)&&i.length>0&&"object"==typeof i[0]&&"key"in i[0]&&"value"in i[0]){let o=!1;i.forEach(({key:t,value:e})=>{""===t.trim()&&""!==e.trim()&&(o=!0)});const n=i.filter(({key:t})=>""!==t.trim()).map(({key:t})=>t.trim()),s=new Set(n);n.length!==s.size&&(o=!0),o&&(t[e]="Please resolve validation errors to continue")}})}validateCategoryNames(t){const e=["other","failure","success","all responses","no response"];Object.entries(this.formData).forEach(([i,o])=>{if(Array.isArray(o)&&"categories"===i){const n=o.filter(t=>(null==t?void 0:t.name)&&""!==t.name.trim()).filter(t=>{const i=t.name.trim().toLowerCase();return e.includes(i)}).map(t=>t.name.trim());n.length>0&&(t[i]=`Reserved category names cannot be used: ${n.join(", ")}`)}})}formDataToNode(t=this.formData){var e;if(!this.node)throw new Error("No node to update");let i={...this.node};const o=this.getNodeConfig(),n=void 0!==(null==o?void 0:o.fromFormData);if(!n&&this.node.actions&&this.node.actions.length>0&&(i.actions=this.node.actions.map(e=>{if(this.action&&e.uuid===this.action.uuid){const i=ym[e.type];return(null==i?void 0:i.fromFormData)?i.fromFormData(t):{...e,...t}}return e})),n)i=o.fromFormData(t,i);else if(this.node.router){if(i.router={...this.node.router},void 0!==t.result_name&&(i.router.result_name=t.result_name),null===(e=null==o?void 0:o.router)||void 0===e?void 0:e.rules){const t=i.router.categories||[],e=i.exits||[],n=[],s=[],r=new Map;if(o.router.rules.forEach(t=>{r.has(t.categoryName)||r.set(t.categoryName,[]),r.get(t.categoryName).push(t)}),r.forEach((i,o)=>{const r=t.find(t=>t.name===o);if(r){n.push(r);const t=e.find(t=>t.uuid===r.exit_uuid);t&&s.push(t)}else{const t=Xt(),e=Xt();n.push({uuid:t,name:o,exit_uuid:e}),s.push({uuid:e,destination_uuid:null})}}),o.router.defaultCategory){if(!n.find(t=>t.name===o.router.defaultCategory)){const i=t.find(t=>t.name===o.router.defaultCategory);if(i){n.push(i);const t=e.find(t=>t.uuid===i.exit_uuid);t&&s.push(t)}else{const t=Xt(),e=Xt();n.push({uuid:t,name:o.router.defaultCategory,exit_uuid:e}),s.push({uuid:e,destination_uuid:null})}}}i.router.categories=n,i.exits=s}}else Object.keys(t).forEach(e=>{"uuid"!==e&&"actions"!==e&&"exits"!==e&&"router"!==e&&(i[e]=t[e])});return i}formDataToAction(t=this.formData){if(!this.action)throw new Error("No action to update");const e=ym[this.action.type];return(null==e?void 0:e.fromFormData)?e.fromFormData(t):{...this.action,...t}}handleFormFieldChange(t,e){const i=e.target;let o;if(o="TEMBA-CHECKBOX"===i.tagName?i.checked:void 0!==i.values?i.values:i.value,this.formData={...this.formData,[t]:o},this.errors[t]){const e={...this.errors};delete e[t],this.errors=e}this.updateComputedFields(t),this.updateGroupCollapseStates(),this.requestUpdate()}updateGroupCollapseStates(){const t=this.getConfig();(null==t?void 0:t.layout)&&this.updateGroupCollapseStatesRecursive(t.layout)}updateGroupCollapseStatesRecursive(t){t.forEach(t=>{if("object"==typeof t&&"group"===t.type){const{label:e,collapsed:i,collapsible:o}=t;if(o&&"function"==typeof i)if(t.reveal&&!1===this.groupCollapseState[e]);else{const t=i(this.formData);this.groupCollapseState[e]!==t&&(this.groupCollapseState={...this.groupCollapseState,[e]:t})}this.updateGroupCollapseStatesRecursive(t.items)}else"object"==typeof t&&"row"===t.type?this.updateGroupCollapseStatesRecursive(t.items):"object"==typeof t&&"accordion"===t.type&&t.sections.forEach(t=>{this.updateGroupCollapseStatesRecursive(t.items)})})}updateComputedFields(t){const e=this.getConfig();(null==e?void 0:e.form)&&Object.entries(e.form).forEach(([e,i])=>{var o;if((null===(o=i.dependsOn)||void 0===o?void 0:o.includes(t))&&i.computeValue){const t=this.formData[e],o=i.computeValue(this.formData,t,this.originalFormData);this.formData={...this.formData,[e]:o}}})}isFieldVisible(t,e){var i;if(null===(i=e.conditions)||void 0===i?void 0:i.visible)try{return e.conditions.visible(this.formData)}catch(e){return console.error(`Error checking visibility for ${t}:`,e),!0}return!0}renderNewField(t,e,i){if(!this.isFieldVisible(t,e))return W``;const o=this.errors[t]?[this.errors[t]]:[],n=e.maxWidth?`max-width: ${e.maxWidth};`:"",s=this.isTranslating&&this.action&&t in this.action?this.renderOriginalValue(t,this.action[t]):W``,r=this.renderFieldContent(t,e,i,o),a=W` ${s} ${r} `;return n?W`<div style="${n}">${a}</div>`:a}renderOptionalField(t,e,i){const o=i&&""!==i.toString().trim(),n=this.revealedOptionalFields.has(t);return o||n?this.renderNewField(t,e,i):W`
13081
+ `}get isTranslating(){return!this.forceBase&&this._isTranslating}connectedCallback(){super.connectedCallback(),this.initializeFormData(),document.addEventListener("keydown",this.boundHandleEscape)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("keydown",this.boundHandleEscape)}handleEscapeKey(t){"Escape"===t.key&&this.isOpen&&this.handleCancel()}willUpdate(t){super.willUpdate(t),(t.has("node")||t.has("action")||t.has("nodeUI"))&&(!this.action||this.node&&this.nodeUI?this.node&&this.nodeUI?(this.isOpen=!0,this.initializeFormData(),this.errors={}):this.action||this.node&&this.nodeUI||(this.isOpen=!1):(this.isOpen=!0,this.initializeFormData(),this.errors={}))}updated(t){super.updated(t),(t.has("node")||t.has("action")||t.has("nodeUI"))&&(!this.action||this.node&&this.nodeUI?this.node&&this.nodeUI&&this.resolveFormData():this.resolveFormData())}initializeFormData(){var t,e,i,o,n,s,r,a,l,d,c,h,u;this.groupCollapseState={};const p=this.getNodeConfig();if(p&&"execute_actions"!==p.type&&"terminal"!==p.type||!this.action){if(this.node){const t=this.getNodeConfig();if(this.isTranslating&&"categories"===(null==t?void 0:t.localizable)&&t.toLocalizationFormData){const e=(null===(n=null===(o=this.flowDefinition)||void 0===o?void 0:o.localization)||void 0===n?void 0:n[this.languageCode])||{};this.formData=t.toLocalizationFormData(this.node,e);const i=new Set(km(null===(s=this.nodeUI)||void 0===s?void 0:s.type,null===(r=this.node.router)||void 0===r?void 0:r.categories).map(t=>t.uuid));this.formData.categories&&"object"==typeof this.formData.categories&&!Array.isArray(this.formData.categories)&&(this.formData={...this.formData,categories:Object.fromEntries(Object.entries(this.formData.categories).filter(([t])=>i.has(t)))});const l=(null===(a=this.nodeUI)||void 0===a?void 0:a.config)||{},d=l.localizeCategories||this.formData.categories&&Object.values(this.formData.categories).some(t=>t.localizedName),c=l.localizeRules||this.formData.rules&&Object.values(this.formData.rules).some(t=>{var e;return null===(e=t.localizedArguments)||void 0===e?void 0:e.some(t=>t)});d||delete this.formData.categories,c||delete this.formData.rules}else(null==t?void 0:t.toFormData)?this.formData=t.toFormData(this.node,this.nodeUI):this.formData={...this.node};if("wait_for_response"===(null===(l=this.nodeUI)||void 0===l?void 0:l.type)&&!this.formData.result_name&&(null===(d=this.flowInfo)||void 0===d?void 0:d.results)&&!(null===(u=null===(h=null===(c=this.flowDefinition)||void 0===c?void 0:c._ui)||void 0===h?void 0:h.nodes)||void 0===u?void 0:u[this.node.uuid])){const t=new Set(this.flowInfo.results.map(t=>t.name));let e="Result",i=2;for(;t.has(e);)e=`Result ${i}`,i++;this.formData.result_name=e,this.formData._isNew=!0}this.processFormDataForEditing(),this.originalFormData=JSON.parse(JSON.stringify(this.formData))}}else{const o=ym[this.action.type];if(this.isTranslating&&(null==o?void 0:o.localizable)&&o.toLocalizationFormData){const n=(null===(i=null===(e=null===(t=this.flowDefinition)||void 0===t?void 0:t.localization)||void 0===e?void 0:e[this.languageCode])||void 0===i?void 0:i[this.action.uuid])||{};this.formData=o.toLocalizationFormData(this.action,n)}else(null==o?void 0:o.toFormData)?this.formData=o.toFormData(this.action):this.formData={...this.action};this.processFormDataForEditing(),this.originalFormData=JSON.parse(JSON.stringify(this.formData))}Object.keys(this.formData).forEach(t=>{const e=this.formData[t];Array.isArray(e)?this.formData[t]=[...e]:e&&"object"==typeof e&&(this.formData[t]={...e})})}async resolveFormData(){const t=this.getConfig();if(null==t?void 0:t.resolveFormData)try{const e=await t.resolveFormData(this.formData);if(e&&e!==this.formData){this.formData=e,this.processFormDataForEditing();const i=t.form;i&&Object.entries(i).forEach(([t,e])=>{if(e.dependsOn&&e.computeValue){const i=e.computeValue(this.formData,this.formData[t],this.originalFormData);this.formData={...this.formData,[t]:i}}}),this.requestUpdate()}}catch(t){}}processFormDataForEditing(){const t={...this.formData};Object.keys(t).forEach(e=>{const i=t[e];if(i&&"object"==typeof i&&!Array.isArray(i)){this.isKeyValueField(e)&&(t[e]=Object.entries(i).map(([t,e])=>({key:t,value:e})))}});const e=this.getConfig();(null==e?void 0:e.form)&&this.processSelectFields(t,e.form),this.formData=t}processSelectFields(t,e){Object.entries(e).forEach(([e,i])=>{const o=t[e];"select"===i.type&&o&&(t[e]=this.convertToSelectArray(o)),"array"===i.type&&Array.isArray(o)&&i.itemConfig&&o.forEach(t=>{this.processSelectFields(t,i.itemConfig)})})}convertToSelectArray(t){return Array.isArray(t)?t.map(t=>"string"==typeof t?{name:t,value:t}:t):"string"==typeof t?[{name:t,value:t}]:[t]}isKeyValueField(t){var e;const i=this.getConfig(),o=null==i?void 0:i.form;return"key-value"===(null===(e=null==o?void 0:o[t])||void 0===e?void 0:e.type)}getConfig(){if(this.node&&this.nodeUI){const t=this.getNodeConfig();if(("execute_actions"===this.nodeUI.type||"terminal"===this.nodeUI.type)&&this.action)return ym[this.action.type]||null;if(t)return t}return this.action&&ym[this.action.type]||null}getNodeConfig(){return this.nodeUI&&this.nodeUI.type?wm[this.nodeUI.type]:null}getHeaderColor(){var t,e;const i=this.getConfig();return(null==i?void 0:i.group)?(null===(t=Wu[i.group])||void 0===t?void 0:t.color)||(null===(e=Vu[i.group])||void 0===e?void 0:e.color):"#aaaaaa"}handleDialogButtonClick(t){const e=t.detail.button;"Save"===e.name?this.handleSave():"Cancel"===e.name&&this.handleCancel()}handleSave(){var t,e,i,o,n,s;const r=this.processFormDataForSave();if(!this.isTranslating){const t=this.validateForm();if(!t.valid)return this.errors=t.errors,void this.expandGroupsWithErrors(t.errors)}if(this.isTranslating){if(this.action){const t=ym[this.action.type];if((null==t?void 0:t.localizable)&&t.fromLocalizationFormData){const e=t.fromLocalizationFormData(r,this.action);return this.updateLocalization(this.languageCode,this.action.uuid,e),void this.fireCustomEvent(Io.NodeEditCancelled,{})}}if(this.node){const a=this.getNodeConfig();if("categories"===(null==a?void 0:a.localizable)&&a.fromLocalizationFormData){const l=a.fromLocalizationFormData(r,this.node),d=(null===(e=null===(t=this.flowDefinition)||void 0===t?void 0:t.localization)||void 0===e?void 0:e[this.languageCode])||{};km(null===(i=this.nodeUI)||void 0===i?void 0:i.type,null===(n=null===(o=this.node)||void 0===o?void 0:o.router)||void 0===n?void 0:n.categories).forEach(t=>{const e=t.uuid,i=l[e];i?this.updateLocalization(this.languageCode,e,i):d[e]&&this.updateLocalization(this.languageCode,e,{})});return((null===(s=this.node.router)||void 0===s?void 0:s.cases)||[]).forEach(t=>{const e=l[t.uuid];e?this.updateLocalization(this.languageCode,t.uuid,e):d[t.uuid]&&this.updateLocalization(this.languageCode,t.uuid,{})}),void this.fireCustomEvent(Io.NodeEditCancelled,{})}}}if(this.node&&this.node.router){const t=this.formDataToNode(r);this.updateFlowInfoResult(t);const e=this.getNodeConfig(),i=(null==e?void 0:e.toUIConfig)?e.toUIConfig(r):void 0;this.fireCustomEvent(Io.NodeSaved,{node:t,uiConfig:i})}else if(this.action){const t=this.formDataToAction(r);this.fireCustomEvent(Io.ActionSaved,{action:t})}else if(this.node){const t=this.formDataToNode(r),e=this.getNodeConfig(),i=(null==e?void 0:e.toUIConfig)?e.toUIConfig(r):void 0;this.fireCustomEvent(Io.NodeSaved,{node:t,uiConfig:i})}}updateFlowInfoResult(t){var e,i,o;if(!(null===(e=this.flowInfo)||void 0===e?void 0:e.results))return;const n=Sd.getState(),s=this.flowInfo.results.filter(e=>!e.node_uuids.includes(t.uuid)),r=null===(i=t.router)||void 0===i?void 0:i.result_name;if(r){const e=((null===(o=t.router)||void 0===o?void 0:o.categories)||[]).map(t=>t.name);s.push({key:r.toLowerCase().replace(/\s+/g,"_"),name:r,categories:e,node_uuids:[t.uuid]})}n.setFlowInfo({...this.flowInfo,results:s})}updateLocalization(t,e,i){Sd.getState().updateLocalization(t,e,i)}processFormDataForSave(){const t={...this.formData};return Object.keys(t).forEach(e=>{const i=t[e];if(Array.isArray(i)&&i.length>0&&"object"==typeof i[0]&&"key"in i[0]&&"value"in i[0]){const o={};i.forEach(({key:t,value:e})=>{""===t.trim()&&""===e.trim()||(o[t]=e)}),t[e]=o}else if(Array.isArray(i)&&0===i.length){this.isKeyValueField(e)&&(t[e]={})}}),t}handleCancel(){this.fireCustomEvent(Io.NodeEditCancelled,{})}validateForm(){const t={},e=this.getConfig();if(e&&(e.form&&Object.entries(e.form).forEach(([e,i])=>{const o=this.formData[e];if("select"===i.type&&i.allowCreate){let i=this.formData[e];i=Array.isArray(i)?i.find(t=>t.arbitrary):null,i&&i.arbitrary&&(t[e]='There was an error creating "'+i.name+'"')}!this.isTranslating&&i.required&&(!o||Array.isArray(o)&&0===o.length)&&(t[e]=`${i.label||e} is required.`),"string"==typeof o&&i.minLength&&o.length<i.minLength&&(t[e]=`${i.label||e} must be at least ${i.minLength} characters`),"string"==typeof o&&i.maxLength&&o.length>i.maxLength&&(t[e]=`${i.label||e} must be no more than ${i.maxLength} characters`)}),this.validateCategoryNames(t),e.validate)){let i;e.sanitize&&e.sanitize(this.formData),i=this.action?e.validate({...this.action,...this.formData}):e.validate(this.formData),Object.assign(t,i.errors)}return this.validateKeyValueUniqueness(t),{valid:0===Object.keys(t).length,errors:t}}validateKeyValueUniqueness(t){Object.entries(this.formData).forEach(([e,i])=>{if(Array.isArray(i)&&i.length>0&&"object"==typeof i[0]&&"key"in i[0]&&"value"in i[0]){let o=!1;i.forEach(({key:t,value:e})=>{""===t.trim()&&""!==e.trim()&&(o=!0)});const n=i.filter(({key:t})=>""!==t.trim()).map(({key:t})=>t.trim()),s=new Set(n);n.length!==s.size&&(o=!0),o&&(t[e]="Please resolve validation errors to continue")}})}validateCategoryNames(t){const e=["other","failure","success","all responses","no response"];Object.entries(this.formData).forEach(([i,o])=>{if(Array.isArray(o)&&"categories"===i){const n=o.filter(t=>(null==t?void 0:t.name)&&""!==t.name.trim()).filter(t=>{const i=t.name.trim().toLowerCase();return e.includes(i)}).map(t=>t.name.trim());n.length>0&&(t[i]=`Reserved category names cannot be used: ${n.join(", ")}`)}})}formDataToNode(t=this.formData){var e;if(!this.node)throw new Error("No node to update");let i={...this.node};const o=this.getNodeConfig(),n=void 0!==(null==o?void 0:o.fromFormData);if(!n&&this.node.actions&&this.node.actions.length>0&&(i.actions=this.node.actions.map(e=>{if(this.action&&e.uuid===this.action.uuid){const i=ym[e.type];return(null==i?void 0:i.fromFormData)?i.fromFormData(t):{...e,...t}}return e})),n)i=o.fromFormData(t,i);else if(this.node.router){if(i.router={...this.node.router},void 0!==t.result_name&&(i.router.result_name=t.result_name),null===(e=null==o?void 0:o.router)||void 0===e?void 0:e.rules){const t=i.router.categories||[],e=i.exits||[],n=[],s=[],r=new Map;if(o.router.rules.forEach(t=>{r.has(t.categoryName)||r.set(t.categoryName,[]),r.get(t.categoryName).push(t)}),r.forEach((i,o)=>{const r=t.find(t=>t.name===o);if(r){n.push(r);const t=e.find(t=>t.uuid===r.exit_uuid);t&&s.push(t)}else{const t=Xt(),e=Xt();n.push({uuid:t,name:o,exit_uuid:e}),s.push({uuid:e,destination_uuid:null})}}),o.router.defaultCategory){if(!n.find(t=>t.name===o.router.defaultCategory)){const i=t.find(t=>t.name===o.router.defaultCategory);if(i){n.push(i);const t=e.find(t=>t.uuid===i.exit_uuid);t&&s.push(t)}else{const t=Xt(),e=Xt();n.push({uuid:t,name:o.router.defaultCategory,exit_uuid:e}),s.push({uuid:e,destination_uuid:null})}}}i.router.categories=n,i.exits=s}}else Object.keys(t).forEach(e=>{"uuid"!==e&&"actions"!==e&&"exits"!==e&&"router"!==e&&(i[e]=t[e])});return i}formDataToAction(t=this.formData){if(!this.action)throw new Error("No action to update");const e=ym[this.action.type];return(null==e?void 0:e.fromFormData)?e.fromFormData(t):{...this.action,...t}}handleFormFieldChange(t,e){const i=e.target;let o;if(o="TEMBA-CHECKBOX"===i.tagName?i.checked:void 0!==i.values?i.values:i.value,this.formData={...this.formData,[t]:o},this.errors[t]){const e={...this.errors};delete e[t],this.errors=e}this.updateComputedFields(t),this.updateGroupCollapseStates(),this.requestUpdate()}updateGroupCollapseStates(){const t=this.getConfig();(null==t?void 0:t.layout)&&this.updateGroupCollapseStatesRecursive(t.layout)}updateGroupCollapseStatesRecursive(t){t.forEach(t=>{if("object"==typeof t&&"group"===t.type){const{label:e,collapsed:i,collapsible:o}=t;if(o&&"function"==typeof i)if(t.reveal&&!1===this.groupCollapseState[e]);else{const t=i(this.formData);this.groupCollapseState[e]!==t&&(this.groupCollapseState={...this.groupCollapseState,[e]:t})}this.updateGroupCollapseStatesRecursive(t.items)}else"object"==typeof t&&"row"===t.type?this.updateGroupCollapseStatesRecursive(t.items):"object"==typeof t&&"accordion"===t.type&&t.sections.forEach(t=>{this.updateGroupCollapseStatesRecursive(t.items)})})}updateComputedFields(t){const e=this.getConfig();(null==e?void 0:e.form)&&Object.entries(e.form).forEach(([e,i])=>{var o;if((null===(o=i.dependsOn)||void 0===o?void 0:o.includes(t))&&i.computeValue){const t=this.formData[e],o=i.computeValue(this.formData,t,this.originalFormData);this.formData={...this.formData,[e]:o}}})}isFieldVisible(t,e){var i;if(null===(i=e.conditions)||void 0===i?void 0:i.visible)try{return e.conditions.visible(this.formData)}catch(e){return console.error(`Error checking visibility for ${t}:`,e),!0}return!0}renderNewField(t,e,i){if(!this.isFieldVisible(t,e))return W``;const o=this.errors[t]?[this.errors[t]]:[],n=e.maxWidth?`max-width: ${e.maxWidth};`:"",s=this.isTranslating&&this.action&&t in this.action?this.renderOriginalValue(t,this.action[t]):W``,r=this.renderFieldContent(t,e,i,o),a=W` ${s} ${r} `;return n?W`<div style="${n}">${a}</div>`:a}renderOptionalField(t,e,i){const o=i&&""!==i.toString().trim(),n=this.revealedOptionalFields.has(t);return o||n?this.renderNewField(t,e,i):W`
13077
13082
  <div class="optional-field-link">
13078
13083
  <a
13079
13084
  @click="${e=>{e.preventDefault(),this.revealOptionalField(t)}}"
@@ -15070,7 +15075,7 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
15070
15075
  .active=${this.isVisible}
15071
15076
  @temba-button-clicked=${this.handleTabClick}
15072
15077
  ></temba-floating-tab>
15073
- `}}t([Ad(Sd,t=>t.flowDefinition)],Rk.prototype,"definition",void 0),t([Ad(Sd,t=>t.viewingRevision)],Rk.prototype,"viewingRevision",void 0),t([mt({type:String})],Rk.prototype,"flow",void 0),t([mt({type:String})],Rk.prototype,"endpoint",void 0),t([mt({type:Number})],Rk.prototype,"animationTime",void 0),t([ke("simulator","small",{validate:t=>t in Pk})],Rk.prototype,"size",void 0),t([mt({type:Array})],Rk.prototype,"events",void 0),t([mt({type:Object})],Rk.prototype,"session",void 0),t([mt({type:Object})],Rk.prototype,"context",void 0),t([mt({type:Object})],Rk.prototype,"contact",void 0),t([mt({type:Boolean})],Rk.prototype,"sprinting",void 0),t([mt({type:String})],Rk.prototype,"inputValue",void 0),t([ke("simulator",!0)],Rk.prototype,"following",void 0),t([ke("simulator",!1)],Rk.prototype,"contextExplorerOpen",void 0),t([mt({type:Object})],Rk.prototype,"expandedPaths",void 0),t([mt({type:String})],Rk.prototype,"copiedExpression",void 0),t([mt({type:String})],Rk.prototype,"toastMessage",void 0),t([mt({type:Boolean})],Rk.prototype,"showAllKeys",void 0),t([mt({type:Array})],Rk.prototype,"currentQuickReplies",void 0),t([mt({type:Boolean})],Rk.prototype,"isVisible",void 0),t([mt({type:Boolean})],Rk.prototype,"attachmentMenuOpen",void 0),t([mt({type:Boolean})],Rk.prototype,"webhookDetailsOpen",void 0),t([mt({attribute:!1})],Rk.prototype,"webhookDetailsEvent",void 0);const Nk={yellow:{border:"#facc15",fill:"#fcd94d",text:"#713f12"},blue:{border:"#3b82f6",fill:"#6ca1f8",text:"#fff"},pink:{border:"#ec4899",fill:"#f17ab7",text:"#fff"},green:{border:"#10b981",fill:"#48ca9d",text:"#fff"},gray:{border:"#6b7280",fill:"#8f949f",text:"#fff"}};function Bk(t){var e,i,o,n,s,r,a,l,d,c,h;const u=[];switch(t.type){case"send_msg":{const i=t;i.text&&u.push(i.text),i.quick_replies&&u.push(...i.quick_replies),(null===(e=i.template)||void 0===e?void 0:e.name)&&u.push(i.template.name);break}case"send_email":{const e=t;e.subject&&u.push(e.subject),e.body&&u.push(e.body),e.addresses&&u.push(...e.addresses);break}case"send_broadcast":{const e=t;e.text&&u.push(e.text),e.groups&&u.push(...e.groups.map(t=>t.name)),e.contacts&&u.push(...e.contacts.map(t=>t.name)),(null===(i=e.template)||void 0===i?void 0:i.name)&&u.push(e.template.name);break}case"say_msg":{const e=t;e.text&&u.push(e.text);break}case"play_audio":{const e=t;e.audio_url&&u.push(e.audio_url);break}case"set_contact_name":{const e=t;e.name&&u.push(e.name);break}case"set_contact_field":{const e=t;(null===(o=e.field)||void 0===o?void 0:o.name)&&u.push(e.field.name),e.value&&u.push(e.value);break}case"set_contact_language":{const e=t;e.language&&u.push(e.language);break}case"set_contact_status":{const e=t;e.status&&u.push(e.status);break}case"set_contact_channel":{const e=t;(null===(n=e.channel)||void 0===n?void 0:n.name)&&u.push(e.channel.name);break}case"add_contact_urn":{const e=t;e.path&&u.push(e.path);break}case"add_contact_groups":{const e=t;e.groups&&u.push(...e.groups.map(t=>t.name));break}case"remove_contact_groups":{const e=t;e.groups&&u.push(...e.groups.map(t=>t.name));break}case"add_input_labels":{const e=t;e.labels&&u.push(...e.labels.map(t=>t.name));break}case"set_run_result":{const e=t;e.name&&u.push(e.name),e.value&&u.push(e.value),e.category&&u.push(e.category);break}case"enter_flow":{const e=t;(null===(s=e.flow)||void 0===s?void 0:s.name)&&u.push(e.flow.name);break}case"start_session":{const e=t;(null===(r=e.flow)||void 0===r?void 0:r.name)&&u.push(e.flow.name),e.groups&&u.push(...e.groups.map(t=>t.name)),e.contacts&&u.push(...e.contacts.map(t=>t.name));break}case"request_optin":{const e=t;(null===(a=e.optin)||void 0===a?void 0:a.name)&&u.push(e.optin.name);break}case"call_webhook":{const e=t;e.url&&u.push(e.url),e.body&&u.push(e.body);break}case"call_resthook":{const e=t;e.resthook&&u.push(e.resthook);break}case"call_llm":{const e=t;(null===(l=e.llm)||void 0===l?void 0:l.name)&&u.push(e.llm.name),e.instructions&&u.push(e.instructions),e.input&&u.push(e.input);break}case"call_classifier":{const e=t;(null===(d=e.classifier)||void 0===d?void 0:d.name)&&u.push(e.classifier.name),e.input&&u.push(e.input);break}case"open_ticket":{const e=t;(null===(c=e.topic)||void 0===c?void 0:c.name)&&u.push(e.topic.name),e.subject&&u.push(e.subject),e.body&&u.push(e.body),(null===(h=e.assignee)||void 0===h?void 0:h.name)&&u.push(e.assignee.name);break}}return u}function Fk(t){const e=[],i=ym[t.type];if(!(null==i?void 0:i.localizable))return e;const o=t;for(const t of i.localizable){const i=o[t];if("string"==typeof i&&i.trim())e.push(i);else if(Array.isArray(i))for(const t of i)"string"==typeof t&&t.trim()&&e.push(t)}return e}function qk(t,e,i){var o,n,s,r,a,l;const d=[];if((null===(o=t.router)||void 0===o?void 0:o.operand)&&d.push(t.router.operand),(null===(n=t.router)||void 0===n?void 0:n.result_name)&&d.push(t.router.result_name),null===(s=t.router)||void 0===s?void 0:s.categories)for(const e of t.router.categories)e.name&&"Other"!==e.name&&"All Responses"!==e.name&&d.push(Hk(e.uuid,e.name,i));if(null===(r=t.router)||void 0===r?void 0:r.cases)for(const e of t.router.cases)if(e.arguments)for(const t of e.arguments)t&&d.push(t);return(null===(l=null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.operand)||void 0===l?void 0:l.name)&&d.push(e.config.operand.name),d}function Uk(t,e){var i,o,n;return(null==t?void 0:t.group)?(null===(i=Wu[t.group])||void 0===i?void 0:i.color)||"#aaaaaa":(null==e?void 0:e.group)&&((null===(o=Wu[e.group])||void 0===o?void 0:o.color)||(null===(n=Vu[e.group])||void 0===n?void 0:n.color))||"#aaaaaa"}function jk(t,e){return(null==t?void 0:t.name)?t.name:(null==e?void 0:e.name)?e.name:"Unknown"}function Hk(t,e,i){const o=null==i?void 0:i[t];return(null==o?void 0:o.name)&&Array.isArray(o.name)&&o.name[0]?o.name[0]:e}class Wk extends dt{constructor(){super(...arguments),this.open=!1,this.definition=null,this.languageCode="",this.scope="flow",this.includeCategories=!1,this.searchQuery="",this.results=[],this.highlightedIndex=0}show(){this.open=!0,this.searchQuery="",this.results=[],this.highlightedIndex=0,this.updateComplete.then(()=>{var t,e;null===(t=this.inputEl)||void 0===t||t.focus(),null===(e=this.inputEl)||void 0===e||e.select()})}hide(){this.open=!1,this.searchQuery="",this.results=[]}handleInput(t){const e=t.target;this.searchQuery=e.value,this.performSearch(),this.highlightedIndex=0}handleKeyDown(t){return"Escape"===t.key?(t.preventDefault(),void this.hide()):"ArrowDown"===t.key||t.ctrlKey&&"n"===t.key?(t.preventDefault(),void(this.results.length>0&&(this.highlightedIndex=(this.highlightedIndex+1)%this.results.length))):"ArrowUp"===t.key||t.ctrlKey&&"p"===t.key?(t.preventDefault(),void(this.results.length>0&&(this.highlightedIndex=(this.highlightedIndex-1+this.results.length)%this.results.length))):"Enter"===t.key?(t.preventDefault(),void(this.results.length>0&&this.selectResult(this.results[this.highlightedIndex]))):void 0}handleBackdropClick(){this.hide()}selectResult(t){this.hide(),this.dispatchEvent(new CustomEvent("temba-search-result-selected",{detail:t,bubbles:!0,composed:!0}))}performSearch(){var t;if(!this.definition||!this.searchQuery.trim())return void(this.results=[]);const e=this.searchQuery.toLowerCase(),i=this.languageCode&&this.languageCode!==this.definition.language?null===(t=this.definition.localization)||void 0===t?void 0:t[this.languageCode]:void 0;"table"!==this.scope?this.results=this.performFlowSearch(e,i):this.results=this.performTableSearch(e,i)}performFlowSearch(t,e){var i,o;const n=[];for(const o of this.definition.nodes){const s=null===(i=this.definition._ui)||void 0===i?void 0:i.nodes[o.uuid],r=(null==s?void 0:s.type)||"execute_actions";if("execute_actions"===r){if(o.actions)for(const i of o.actions){const s=ym[i.type],r=Bk(Ru(i,null==e?void 0:e[i.uuid]));for(const e of r){const r=e.toLowerCase().indexOf(t);if(-1!==r){n.push({nodeUuid:o.uuid,action:i,typeName:jk(s,void 0),color:Uk(s,void 0),fullText:e,matchStart:r,matchLength:t.length});break}}}}else{const i=wm[r],a=qk(o,s,e);if(o.actions)for(const t of o.actions){const i=Ru(t,null==e?void 0:e[t.uuid]);a.push(...Bk(i))}for(const e of a){const s=e.toLowerCase().indexOf(t);if(-1!==s){n.push({nodeUuid:o.uuid,action:null,typeName:jk(void 0,i),color:Uk(void 0,i),fullText:e,matchStart:s,matchLength:t.length});break}}}}const s=(null===(o=this.definition._ui)||void 0===o?void 0:o.stickies)||{};for(const[e,i]of Object.entries(s)){const o=[];i.title&&o.push({text:i.title,field:"title"}),i.body&&o.push({text:i.body,field:"body"});for(const{text:s,field:r}of o){const o=s.toLowerCase().indexOf(t);if(-1!==o){const a=Nk[i.color]||Nk.yellow;n.push({nodeUuid:e,action:null,typeName:"Sticky Note",color:a.fill,borderColor:a.border,textColor:a.text,fullText:s,matchStart:o,matchLength:t.length,stickyField:r});break}}}return n}performTableSearch(t,e){var i,o,n,s;const r=[];for(const a of this.definition.nodes){const l=null===(i=this.definition._ui)||void 0===i?void 0:i.nodes[a.uuid],d=(null==l?void 0:l.type)||"execute_actions";if(a.actions)for(const i of a.actions){const o=ym[i.type];if("send_msg"!==i.type&&(!(null==o?void 0:o.localizable)||0===o.localizable.length))continue;const n=Fk(i),s=Fk(Ru(i,null==e?void 0:e[i.uuid])),l=[],d=new Set;for(const t of[...n,...s])d.has(t)||(d.add(t),l.push(t));let c=!1;for(const e of l){const n=e.toLowerCase().indexOf(t);if(-1!==n){r.push({nodeUuid:a.uuid,action:i,typeName:jk(o,void 0),color:Uk(o,void 0),fullText:e,matchStart:n,matchLength:t.length}),c=!0;break}}}if(this.includeCategories&&(null===(n=null===(o=a.router)||void 0===o?void 0:o.categories)||void 0===n?void 0:n.length)&&"categories"===(null===(s=wm[d])||void 0===s?void 0:s.localizable)){const i=Mm(d,a.router.categories);if(!i.length)continue;const o=wm[d],n=i.map(t=>Hk(t.uuid,t.name,e));for(const e of n){const i=e.toLowerCase().indexOf(t);if(-1!==i){r.push({nodeUuid:a.uuid,action:null,typeName:jk(void 0,o),color:Uk(void 0,o),fullText:e,matchStart:i,matchLength:t.length});break}}}}return r}renderMatchText(t){const{matchStart:e,matchLength:i}=t,o=e+i,n=t.fullText.replace(/\n/g," "),s=n.length-o<30?50:20,r=Math.max(0,e-s),a=r>0?"…":"",l=n.slice(r,e),d=n.slice(e,o),c=n.slice(o);return W`${a}${l}<mark>${d}</mark>${c}`}updated(t){var e;if(t.has("highlightedIndex")){const t=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".result-item.highlighted");null==t||t.scrollIntoView({block:"nearest"})}}render(){const t="table"===this.scope?"Search this table":"Search this flow";return W`
15078
+ `}}t([Ad(Sd,t=>t.flowDefinition)],Rk.prototype,"definition",void 0),t([Ad(Sd,t=>t.viewingRevision)],Rk.prototype,"viewingRevision",void 0),t([mt({type:String})],Rk.prototype,"flow",void 0),t([mt({type:String})],Rk.prototype,"endpoint",void 0),t([mt({type:Number})],Rk.prototype,"animationTime",void 0),t([ke("simulator","small",{validate:t=>t in Pk})],Rk.prototype,"size",void 0),t([mt({type:Array})],Rk.prototype,"events",void 0),t([mt({type:Object})],Rk.prototype,"session",void 0),t([mt({type:Object})],Rk.prototype,"context",void 0),t([mt({type:Object})],Rk.prototype,"contact",void 0),t([mt({type:Boolean})],Rk.prototype,"sprinting",void 0),t([mt({type:String})],Rk.prototype,"inputValue",void 0),t([ke("simulator",!0)],Rk.prototype,"following",void 0),t([ke("simulator",!1)],Rk.prototype,"contextExplorerOpen",void 0),t([mt({type:Object})],Rk.prototype,"expandedPaths",void 0),t([mt({type:String})],Rk.prototype,"copiedExpression",void 0),t([mt({type:String})],Rk.prototype,"toastMessage",void 0),t([mt({type:Boolean})],Rk.prototype,"showAllKeys",void 0),t([mt({type:Array})],Rk.prototype,"currentQuickReplies",void 0),t([mt({type:Boolean})],Rk.prototype,"isVisible",void 0),t([mt({type:Boolean})],Rk.prototype,"attachmentMenuOpen",void 0),t([mt({type:Boolean})],Rk.prototype,"webhookDetailsOpen",void 0),t([mt({attribute:!1})],Rk.prototype,"webhookDetailsEvent",void 0);const Nk={yellow:{border:"#facc15",fill:"#fcd94d",text:"#713f12"},blue:{border:"#3b82f6",fill:"#6ca1f8",text:"#fff"},pink:{border:"#ec4899",fill:"#f17ab7",text:"#fff"},green:{border:"#10b981",fill:"#48ca9d",text:"#fff"},gray:{border:"#6b7280",fill:"#8f949f",text:"#fff"}};function Bk(t){var e,i,o,n,s,r,a,l,d,c,h;const u=[];switch(t.type){case"send_msg":{const i=t;i.text&&u.push(i.text),i.quick_replies&&u.push(...i.quick_replies),(null===(e=i.template)||void 0===e?void 0:e.name)&&u.push(i.template.name);break}case"send_email":{const e=t;e.subject&&u.push(e.subject),e.body&&u.push(e.body),e.addresses&&u.push(...e.addresses);break}case"send_broadcast":{const e=t;e.text&&u.push(e.text),e.groups&&u.push(...e.groups.map(t=>t.name)),e.contacts&&u.push(...e.contacts.map(t=>t.name)),(null===(i=e.template)||void 0===i?void 0:i.name)&&u.push(e.template.name);break}case"say_msg":{const e=t;e.text&&u.push(e.text);break}case"play_audio":{const e=t;e.audio_url&&u.push(e.audio_url);break}case"set_contact_name":{const e=t;e.name&&u.push(e.name);break}case"set_contact_field":{const e=t;(null===(o=e.field)||void 0===o?void 0:o.name)&&u.push(e.field.name),e.value&&u.push(e.value);break}case"set_contact_language":{const e=t;e.language&&u.push(e.language);break}case"set_contact_status":{const e=t;e.status&&u.push(e.status);break}case"set_contact_channel":{const e=t;(null===(n=e.channel)||void 0===n?void 0:n.name)&&u.push(e.channel.name);break}case"add_contact_urn":{const e=t;e.path&&u.push(e.path);break}case"add_contact_groups":{const e=t;e.groups&&u.push(...e.groups.map(t=>t.name));break}case"remove_contact_groups":{const e=t;e.groups&&u.push(...e.groups.map(t=>t.name));break}case"add_input_labels":{const e=t;e.labels&&u.push(...e.labels.map(t=>t.name));break}case"set_run_result":{const e=t;e.name&&u.push(e.name),e.value&&u.push(e.value),e.category&&u.push(e.category);break}case"enter_flow":{const e=t;(null===(s=e.flow)||void 0===s?void 0:s.name)&&u.push(e.flow.name);break}case"start_session":{const e=t;(null===(r=e.flow)||void 0===r?void 0:r.name)&&u.push(e.flow.name),e.groups&&u.push(...e.groups.map(t=>t.name)),e.contacts&&u.push(...e.contacts.map(t=>t.name));break}case"request_optin":{const e=t;(null===(a=e.optin)||void 0===a?void 0:a.name)&&u.push(e.optin.name);break}case"call_webhook":{const e=t;e.url&&u.push(e.url),e.body&&u.push(e.body);break}case"call_resthook":{const e=t;e.resthook&&u.push(e.resthook);break}case"call_llm":{const e=t;(null===(l=e.llm)||void 0===l?void 0:l.name)&&u.push(e.llm.name),e.instructions&&u.push(e.instructions),e.input&&u.push(e.input);break}case"call_classifier":{const e=t;(null===(d=e.classifier)||void 0===d?void 0:d.name)&&u.push(e.classifier.name),e.input&&u.push(e.input);break}case"open_ticket":{const e=t;(null===(c=e.topic)||void 0===c?void 0:c.name)&&u.push(e.topic.name),e.subject&&u.push(e.subject),e.body&&u.push(e.body),(null===(h=e.assignee)||void 0===h?void 0:h.name)&&u.push(e.assignee.name);break}}return u}function Fk(t){const e=[],i=ym[t.type];if(!(null==i?void 0:i.localizable))return e;const o=t;for(const t of i.localizable){const i=o[t];if("string"==typeof i&&i.trim())e.push(i);else if(Array.isArray(i))for(const t of i)"string"==typeof t&&t.trim()&&e.push(t)}return e}function qk(t,e,i){var o,n,s,r,a,l;const d=[];if((null===(o=t.router)||void 0===o?void 0:o.operand)&&d.push(t.router.operand),(null===(n=t.router)||void 0===n?void 0:n.result_name)&&d.push(t.router.result_name),null===(s=t.router)||void 0===s?void 0:s.categories)for(const e of t.router.categories)e.name&&"Other"!==e.name&&"All Responses"!==e.name&&d.push(Hk(e.uuid,e.name,i));if(null===(r=t.router)||void 0===r?void 0:r.cases)for(const e of t.router.cases)if(e.arguments)for(const t of e.arguments)t&&d.push(t);return(null===(l=null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.operand)||void 0===l?void 0:l.name)&&d.push(e.config.operand.name),d}function Uk(t,e){var i,o,n;return(null==t?void 0:t.group)?(null===(i=Wu[t.group])||void 0===i?void 0:i.color)||"#aaaaaa":(null==e?void 0:e.group)&&((null===(o=Wu[e.group])||void 0===o?void 0:o.color)||(null===(n=Vu[e.group])||void 0===n?void 0:n.color))||"#aaaaaa"}function jk(t,e){return(null==t?void 0:t.name)?t.name:(null==e?void 0:e.name)?e.name:"Unknown"}function Hk(t,e,i){const o=null==i?void 0:i[t];return(null==o?void 0:o.name)&&Array.isArray(o.name)&&o.name[0]?o.name[0]:e}class Wk extends dt{constructor(){super(...arguments),this.open=!1,this.definition=null,this.languageCode="",this.scope="flow",this.includeCategories=!1,this.searchQuery="",this.results=[],this.highlightedIndex=0}show(){this.open=!0,this.searchQuery="",this.results=[],this.highlightedIndex=0,this.updateComplete.then(()=>{var t,e;null===(t=this.inputEl)||void 0===t||t.focus(),null===(e=this.inputEl)||void 0===e||e.select()})}hide(){this.open=!1,this.searchQuery="",this.results=[]}handleInput(t){const e=t.target;this.searchQuery=e.value,this.performSearch(),this.highlightedIndex=0}handleKeyDown(t){return"Escape"===t.key?(t.preventDefault(),void this.hide()):"ArrowDown"===t.key||t.ctrlKey&&"n"===t.key?(t.preventDefault(),void(this.results.length>0&&(this.highlightedIndex=(this.highlightedIndex+1)%this.results.length))):"ArrowUp"===t.key||t.ctrlKey&&"p"===t.key?(t.preventDefault(),void(this.results.length>0&&(this.highlightedIndex=(this.highlightedIndex-1+this.results.length)%this.results.length))):"Enter"===t.key?(t.preventDefault(),void(this.results.length>0&&this.selectResult(this.results[this.highlightedIndex]))):void 0}handleBackdropClick(){this.hide()}selectResult(t){this.hide(),this.dispatchEvent(new CustomEvent("temba-search-result-selected",{detail:t,bubbles:!0,composed:!0}))}performSearch(){var t;if(!this.definition||!this.searchQuery.trim())return void(this.results=[]);const e=this.searchQuery.toLowerCase(),i=this.languageCode&&this.languageCode!==this.definition.language?null===(t=this.definition.localization)||void 0===t?void 0:t[this.languageCode]:void 0;"table"!==this.scope?this.results=this.performFlowSearch(e,i):this.results=this.performTableSearch(e,i)}performFlowSearch(t,e){var i,o;const n=[];for(const o of this.definition.nodes){const s=null===(i=this.definition._ui)||void 0===i?void 0:i.nodes[o.uuid],r=(null==s?void 0:s.type)||"execute_actions";if("execute_actions"===r){if(o.actions)for(const i of o.actions){const s=ym[i.type],r=Bk(Ru(i,null==e?void 0:e[i.uuid]));for(const e of r){const r=e.toLowerCase().indexOf(t);if(-1!==r){n.push({nodeUuid:o.uuid,action:i,typeName:jk(s,void 0),color:Uk(s,void 0),fullText:e,matchStart:r,matchLength:t.length});break}}}}else{const i=wm[r],a=qk(o,s,e);if(o.actions)for(const t of o.actions){const i=Ru(t,null==e?void 0:e[t.uuid]);a.push(...Bk(i))}for(const e of a){const s=e.toLowerCase().indexOf(t);if(-1!==s){n.push({nodeUuid:o.uuid,action:null,typeName:jk(void 0,i),color:Uk(void 0,i),fullText:e,matchStart:s,matchLength:t.length});break}}}}const s=(null===(o=this.definition._ui)||void 0===o?void 0:o.stickies)||{};for(const[e,i]of Object.entries(s)){const o=[];i.title&&o.push({text:i.title,field:"title"}),i.body&&o.push({text:i.body,field:"body"});for(const{text:s,field:r}of o){const o=s.toLowerCase().indexOf(t);if(-1!==o){const a=Nk[i.color]||Nk.yellow;n.push({nodeUuid:e,action:null,typeName:"Sticky Note",color:a.fill,borderColor:a.border,textColor:a.text,fullText:s,matchStart:o,matchLength:t.length,stickyField:r});break}}}return n}performTableSearch(t,e){var i,o,n,s;const r=[];for(const a of this.definition.nodes){const l=null===(i=this.definition._ui)||void 0===i?void 0:i.nodes[a.uuid],d=(null==l?void 0:l.type)||"execute_actions";if(a.actions)for(const i of a.actions){const o=ym[i.type];if("send_msg"!==i.type&&(!(null==o?void 0:o.localizable)||0===o.localizable.length))continue;const n=Fk(i),s=Fk(Ru(i,null==e?void 0:e[i.uuid])),l=[],d=new Set;for(const t of[...n,...s])d.has(t)||(d.add(t),l.push(t));let c=!1;for(const e of l){const n=e.toLowerCase().indexOf(t);if(-1!==n){r.push({nodeUuid:a.uuid,action:i,typeName:jk(o,void 0),color:Uk(o,void 0),fullText:e,matchStart:n,matchLength:t.length}),c=!0;break}}}if(this.includeCategories&&(null===(n=null===(o=a.router)||void 0===o?void 0:o.categories)||void 0===n?void 0:n.length)&&"categories"===(null===(s=wm[d])||void 0===s?void 0:s.localizable)){const i=km(d,a.router.categories);if(!i.length)continue;const o=wm[d],n=i.map(t=>Hk(t.uuid,t.name,e));for(const e of n){const i=e.toLowerCase().indexOf(t);if(-1!==i){r.push({nodeUuid:a.uuid,action:null,typeName:jk(void 0,o),color:Uk(void 0,o),fullText:e,matchStart:i,matchLength:t.length});break}}}}return r}renderMatchText(t){const{matchStart:e,matchLength:i}=t,o=e+i,n=t.fullText.replace(/\n/g," "),s=n.length-o<30?50:20,r=Math.max(0,e-s),a=r>0?"…":"",l=n.slice(r,e),d=n.slice(e,o),c=n.slice(o);return W`${a}${l}<mark>${d}</mark>${c}`}updated(t){var e;if(t.has("highlightedIndex")){const t=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".result-item.highlighted");null==t||t.scrollIntoView({block:"nearest"})}}render(){const t="table"===this.scope?"Search this table":"Search this flow";return W`
15074
15079
  <div class="backdrop" @click=${this.handleBackdropClick}></div>
15075
15080
  <div
15076
15081
  class="search-container"
@@ -15729,7 +15734,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15729
15734
  padding: 60px 20px;
15730
15735
  text-align: center;
15731
15736
  }
15732
- `}getEntries(){var t,e,i,o,n,s,r,a,l,d,c,h,u;if(!(null===(t=this.definition)||void 0===t?void 0:t.nodes))return[];const p=[];let m=0;for(const t of this.definition.nodes){m++;for(const e of t.actions||[]){const i=ym[e.type];("send_msg"===e.type||(null==i?void 0:i.localizable)&&i.localizable.length>0)&&p.push({kind:"message",node:t,action:e,nodeIndex:m})}if(!this.isTranslating)continue;const g=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e._ui)||void 0===i?void 0:i.nodes)||void 0===o?void 0:o[t.uuid],f=null==g?void 0:g.type,v=(null===(s=null===(n=this.definition)||void 0===n?void 0:n.localization)||void 0===s?void 0:s[this.languageCode])||{};let b=[];if(null===(a=null===(r=t.router)||void 0===r?void 0:r.cases)||void 0===a?void 0:a.length){const e=null===(l=null==g?void 0:g.config)||void 0===l?void 0:l.localizeRules;b=t.router.cases.filter(t=>{var e;return(null===(e=t.arguments)||void 0===e?void 0:e.length)>0&&t.arguments.some(t=>t)}).filter(t=>{var i,o;return e||(null===(o=null===(i=v[t.uuid])||void 0===i?void 0:i.arguments)||void 0===o?void 0:o.some(t=>t))}).map(t=>({uuid:t.uuid,type:t.type,arguments:[...t.arguments]}))}let y=[];if(f&&"categories"===(null===(d=wm[f])||void 0===d?void 0:d.localizable)&&(null===(h=null===(c=t.router)||void 0===c?void 0:c.categories)||void 0===h?void 0:h.length)){const e=null===(u=null==g?void 0:g.config)||void 0===u?void 0:u.localizeCategories,i=Mm(f,t.router.categories);y=e?i:i.filter(t=>{var e,i;return null===(i=null===(e=v[t.uuid])||void 0===e?void 0:e.name)||void 0===i?void 0:i.some(t=>t)})}(b.length>0||y.length>0)&&p.push({kind:"localization-group",node:t,rules:b,categories:y,nodeIndex:m})}return p}focusSearchResult(t,e){const i=Array.from(this.renderRoot.querySelectorAll("tr[data-node-uuid]"));if(!i.length)return;let o=e?i.find(i=>i.dataset.nodeUuid===t&&i.dataset.actionUuid===e):i.find(e=>e.dataset.nodeUuid===t&&"category-group"===e.dataset.entryKind);o||(o=i.find(e=>e.dataset.nodeUuid===t)),null==o||o.scrollIntoView({behavior:"smooth",block:"center"})}getTranslatedText(t){var e,i,o;if(!this.isTranslating||!this.languageCode)return null;const n=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t];return(null==n?void 0:n.text)&&Array.isArray(n.text)&&n.text[0]||null}getTranslatedQuickReplies(t){var e,i,o;if(!this.isTranslating||!this.languageCode)return[];const n=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t];return Array.isArray(null==n?void 0:n.quick_replies)?n.quick_replies.map(t=>"string"==typeof t?t.trim():"").filter(t=>t.length>0):[]}stripLeadingLineBreaks(t){return t.replace(/^(?:\r?\n)+/,"")}getTranslatedCategoryName(t){var e,i,o;if(!this.isTranslating||!this.languageCode)return null;const n=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t];return(null==n?void 0:n.name)?Array.isArray(n.name)?n.name[0]||null:"string"==typeof n.name?n.name:null:null}getTranslatedField(t,e){var i,o,n;if(!this.isTranslating||!this.languageCode)return null;const s=null===(n=null===(o=null===(i=this.definition)||void 0===i?void 0:i.localization)||void 0===o?void 0:o[this.languageCode])||void 0===n?void 0:n[t];return(null==s?void 0:s[e])&&Array.isArray(s[e])&&s[e][0]||null}getTranslatedArrayField(t,e){var i,o,n;if(!this.isTranslating||!this.languageCode)return[];const s=null===(n=null===(o=null===(i=this.definition)||void 0===i?void 0:i.localization)||void 0===o?void 0:o[this.languageCode])||void 0===n?void 0:n[t];return Array.isArray(null==s?void 0:s[e])?s[e]:[]}hasAnyTranslation(t){var e,i,o;const n=ym[t.action.type];if(!(null==n?void 0:n.localizable))return!1;const s=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t.action.uuid];return!!s&&n.localizable.some(t=>{const e=s[t];return!!Array.isArray(e)&&e.some(t=>"string"==typeof t&&t.trim())})}usesPairedRows(t){const e=ym[t.type];if(!(null==e?void 0:e.localizable))return!1;return e.localizable.filter(t=>{var i;const o=null===(i=e.form)||void 0===i?void 0:i[t];return o&&("text"===o.type||"textarea"===o.type)}).length>1}getPairedFields(t){const e=ym[t.type];return(null==e?void 0:e.localizable)&&e.form?e.localizable.filter(t=>{var i;const o=null===(i=e.form)||void 0===i?void 0:i[t];return o&&("text"===o.type||"textarea"===o.type)}).map(i=>{const o=e.form[i];return{key:i,label:"string"==typeof o.label?o.label:i,original:t[i]||"",translated:this.getTranslatedField(t.uuid,i)}}):[]}renderAttachments(t){return t&&0!==t.length?W`<div class="attachments">
15737
+ `}getEntries(){var t,e,i,o,n,s,r,a,l,d,c,h,u;if(!(null===(t=this.definition)||void 0===t?void 0:t.nodes))return[];const p=[];let m=0;for(const t of this.definition.nodes){m++;for(const e of t.actions||[]){const i=ym[e.type];("send_msg"===e.type||(null==i?void 0:i.localizable)&&i.localizable.length>0)&&p.push({kind:"message",node:t,action:e,nodeIndex:m})}if(!this.isTranslating)continue;const g=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e._ui)||void 0===i?void 0:i.nodes)||void 0===o?void 0:o[t.uuid],f=null==g?void 0:g.type,v=(null===(s=null===(n=this.definition)||void 0===n?void 0:n.localization)||void 0===s?void 0:s[this.languageCode])||{};let b=[];if(null===(a=null===(r=t.router)||void 0===r?void 0:r.cases)||void 0===a?void 0:a.length){const e=null===(l=null==g?void 0:g.config)||void 0===l?void 0:l.localizeRules;b=t.router.cases.filter(t=>{var e;return(null===(e=t.arguments)||void 0===e?void 0:e.length)>0&&t.arguments.some(t=>t)}).filter(t=>{var i,o;return e||(null===(o=null===(i=v[t.uuid])||void 0===i?void 0:i.arguments)||void 0===o?void 0:o.some(t=>t))}).map(t=>({uuid:t.uuid,type:t.type,arguments:[...t.arguments]}))}let y=[];if(f&&"categories"===(null===(d=wm[f])||void 0===d?void 0:d.localizable)&&(null===(h=null===(c=t.router)||void 0===c?void 0:c.categories)||void 0===h?void 0:h.length)){const e=null===(u=null==g?void 0:g.config)||void 0===u?void 0:u.localizeCategories,i=km(f,t.router.categories);y=e?i:i.filter(t=>{var e,i;return null===(i=null===(e=v[t.uuid])||void 0===e?void 0:e.name)||void 0===i?void 0:i.some(t=>t)})}(b.length>0||y.length>0)&&p.push({kind:"localization-group",node:t,rules:b,categories:y,nodeIndex:m})}return p}focusSearchResult(t,e){const i=Array.from(this.renderRoot.querySelectorAll("tr[data-node-uuid]"));if(!i.length)return;let o=e?i.find(i=>i.dataset.nodeUuid===t&&i.dataset.actionUuid===e):i.find(e=>e.dataset.nodeUuid===t&&"category-group"===e.dataset.entryKind);o||(o=i.find(e=>e.dataset.nodeUuid===t)),null==o||o.scrollIntoView({behavior:"smooth",block:"center"})}getTranslatedText(t){var e,i,o;if(!this.isTranslating||!this.languageCode)return null;const n=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t];return(null==n?void 0:n.text)&&Array.isArray(n.text)&&n.text[0]||null}getTranslatedQuickReplies(t){var e,i,o;if(!this.isTranslating||!this.languageCode)return[];const n=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t];return Array.isArray(null==n?void 0:n.quick_replies)?n.quick_replies.map(t=>"string"==typeof t?t.trim():"").filter(t=>t.length>0):[]}stripLeadingLineBreaks(t){return t.replace(/^(?:\r?\n)+/,"")}getTranslatedCategoryName(t){var e,i,o;if(!this.isTranslating||!this.languageCode)return null;const n=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t];return(null==n?void 0:n.name)?Array.isArray(n.name)?n.name[0]||null:"string"==typeof n.name?n.name:null:null}getTranslatedField(t,e){var i,o,n;if(!this.isTranslating||!this.languageCode)return null;const s=null===(n=null===(o=null===(i=this.definition)||void 0===i?void 0:i.localization)||void 0===o?void 0:o[this.languageCode])||void 0===n?void 0:n[t];return(null==s?void 0:s[e])&&Array.isArray(s[e])&&s[e][0]||null}getTranslatedArrayField(t,e){var i,o,n;if(!this.isTranslating||!this.languageCode)return[];const s=null===(n=null===(o=null===(i=this.definition)||void 0===i?void 0:i.localization)||void 0===o?void 0:o[this.languageCode])||void 0===n?void 0:n[t];return Array.isArray(null==s?void 0:s[e])?s[e]:[]}hasAnyTranslation(t){var e,i,o;const n=ym[t.action.type];if(!(null==n?void 0:n.localizable))return!1;const s=null===(o=null===(i=null===(e=this.definition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t.action.uuid];return!!s&&n.localizable.some(t=>{const e=s[t];return!!Array.isArray(e)&&e.some(t=>"string"==typeof t&&t.trim())})}usesPairedRows(t){const e=ym[t.type];if(!(null==e?void 0:e.localizable))return!1;return e.localizable.filter(t=>{var i;const o=null===(i=e.form)||void 0===i?void 0:i[t];return o&&("text"===o.type||"textarea"===o.type)}).length>1}getPairedFields(t){const e=ym[t.type];return(null==e?void 0:e.localizable)&&e.form?e.localizable.filter(t=>{var i;const o=null===(i=e.form)||void 0===i?void 0:i[t];return o&&("text"===o.type||"textarea"===o.type)}).map(i=>{const o=e.form[i];return{key:i,label:"string"==typeof o.label?o.label:i,original:t[i]||"",translated:this.getTranslatedField(t.uuid,i)}}):[]}renderAttachments(t){return t&&0!==t.length?W`<div class="attachments">
15733
15738
  ${t.map(t=>{const e=t.indexOf(":");if(e<0)return W``;const i=t.substring(0,e).split("/")[0],o=Yk.ATTACHMENT_ICONS[i]||ko.attachment;return W`<div class="attachment-icon">
15734
15739
  <temba-icon name="${o}"></temba-icon>
15735
15740
  </div>`})}
@@ -15945,7 +15950,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15945
15950
  </div>`}}renderHeader(){return W`<div class="header">
15946
15951
  <temba-icon name="notification"></temba-icon>
15947
15952
  <div class="title">Notifications</div>
15948
- </div>`}scrollToTop(){window.setTimeout(()=>{this.shadowRoot.querySelector("temba-options").scrollToTop()},1e3)}}),Kk("temba-list",rh),Kk("temba-sortable-list",Md),Kk("temba-run-list",Oh),Kk("temba-flow-details",Ph),Kk("temba-label",kh),Kk("temba-menu",bh),Kk("temba-contact-search",hh),Kk("temba-icon",uh),Kk("temba-dropdown",xh),Kk("temba-tabs",wh),Kk("temba-tab",_h),Kk("temba-contact-badges",Dh),Kk("temba-contact-pending",zh),Kk("temba-slider",Ih),Kk("temba-content-menu",Hh),Kk("temba-compose",Zh),Kk("temba-color-picker",Kh),Kk("temba-resizer",Gh),Kk("temba-thumbnail",tu),Kk("temba-webchat",ou),Kk("temba-image-picker",su),Kk("temba-mask",ru),Kk("temba-user",Sl),Kk("temba-template-editor",au),Kk("temba-toast",lu),Kk("temba-chat",Qc),Kk("temba-media-picker",cu),Kk("temba-flow-editor",Nm),Kk("temba-editor-toolbar",Fm),Kk("temba-message-table",Yk),Kk("temba-node-editor",_k),Kk("temba-flow-node",zm),Kk("temba-sticky-note",qm),Kk("temba-canvas-menu",Um),Kk("temba-node-type-selector",jm),Kk("temba-contact-notepad",Hm),Kk("temba-progress",Wm),Kk("temba-start-progress",Vm),Kk("temba-shortcuts",Zm),Kk("temba-popup-select",Ym),Kk("temba-user-select",Km),Kk("temba-workspace-select",Gm),Kk("temba-chart",dk),Kk("temba-key-value-editor",Ck),Kk("temba-array-editor",Sk),Kk("temba-message-editor",Ak),Kk("temba-rich-edit",Ek),Kk("temba-accordion",Dk),Kk("temba-accordion-section",Mk),Kk("temba-expression-highlight",$k),Kk("temba-floating-tab",Lm),Kk("temba-floating-window",Tk),Kk("temba-simulator",Rk),Kk("temba-flow-search",Wk),Kk("temba-issues-window",Vk),Kk("temba-revisions-window",Zk);class Gk extends dt{static get styles(){return a`
15953
+ </div>`}scrollToTop(){window.setTimeout(()=>{this.shadowRoot.querySelector("temba-options").scrollToTop()},1e3)}}),Kk("temba-list",rh),Kk("temba-sortable-list",Md),Kk("temba-run-list",Oh),Kk("temba-flow-details",Ph),Kk("temba-label",kh),Kk("temba-menu",bh),Kk("temba-contact-search",hh),Kk("temba-icon",uh),Kk("temba-dropdown",xh),Kk("temba-tabs",wh),Kk("temba-tab",_h),Kk("temba-contact-badges",Dh),Kk("temba-contact-pending",zh),Kk("temba-slider",Ih),Kk("temba-content-menu",Hh),Kk("temba-compose",Zh),Kk("temba-color-picker",Kh),Kk("temba-resizer",Gh),Kk("temba-thumbnail",tu),Kk("temba-webchat",ou),Kk("temba-image-picker",su),Kk("temba-mask",ru),Kk("temba-user",Sl),Kk("temba-template-editor",au),Kk("temba-toast",lu),Kk("temba-chat",Qc),Kk("temba-media-picker",cu),Kk("temba-flow-editor",Fm),Kk("temba-editor-toolbar",Sm),Kk("temba-message-table",Yk),Kk("temba-node-editor",_k),Kk("temba-flow-node",Lm),Kk("temba-sticky-note",qm),Kk("temba-canvas-menu",Um),Kk("temba-node-type-selector",jm),Kk("temba-contact-notepad",Hm),Kk("temba-progress",Wm),Kk("temba-start-progress",Vm),Kk("temba-shortcuts",Zm),Kk("temba-popup-select",Ym),Kk("temba-user-select",Km),Kk("temba-workspace-select",Gm),Kk("temba-chart",dk),Kk("temba-key-value-editor",Ck),Kk("temba-array-editor",Sk),Kk("temba-message-editor",Ak),Kk("temba-rich-edit",Ek),Kk("temba-accordion",Dk),Kk("temba-accordion-section",Mk),Kk("temba-expression-highlight",$k),Kk("temba-floating-tab",Pm),Kk("temba-floating-window",Tk),Kk("temba-simulator",Rk),Kk("temba-flow-search",Wk),Kk("temba-issues-window",Vk),Kk("temba-revisions-window",Zk);class Gk extends dt{static get styles(){return a`
15949
15954
  :host {
15950
15955
  line-height: normal;
15951
15956
  }