@nyaruka/temba-components 0.156.8 → 0.156.9

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.
@@ -613,7 +613,140 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
613
613
  -webkit-box-orient: vertical;
614
614
  overflow: hidden;
615
615
  }
616
- `,t([mt({type:Number})],Sl.prototype,"scale",void 0),t([mt({type:Boolean})],Sl.prototype,"showName",void 0),t([mt({type:Boolean})],Sl.prototype,"system",void 0),t([mt({type:String,attribute:!1})],Sl.prototype,"bgimage",void 0),t([mt({type:String,attribute:!1})],Sl.prototype,"bgcolor",void 0),t([mt({type:String,attribute:!1})],Sl.prototype,"initials",void 0),t([mt({type:String})],Sl.prototype,"name",void 0),t([mt({type:String})],Sl.prototype,"email",void 0),t([mt({type:String})],Sl.prototype,"uuid",void 0),t([mt({type:String})],Sl.prototype,"avatar",void 0);const Al=t=>{let e;const i=new Set,o=(t,o)=>{const n="function"==typeof t?t(e):t;if(!Object.is(n,e)){const t=e;e=(null!=o?o:"object"!=typeof n||null===n)?n:Object.assign({},e,n),i.forEach(i=>i(e,t))}},n=()=>e,s={setState:o,getState:n,getInitialState:()=>r,subscribe:t=>(i.add(t),()=>i.delete(t))},r=e=t(o,n,s);return s};var El=Symbol.for("immer-nothing"),$l=Symbol.for("immer-draftable"),Tl=Symbol.for("immer-state"),Dl=[function(t){return`The plugin for '${t}' has not been loaded into Immer. To enable the plugin, import and call \`enable${t}()\` when initializing your application.`},function(t){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${t}'`},"This object has been frozen and should not be mutated",function(t){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+t},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(t){return`'current' expects a draft, got: ${t}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(t){return`'original' expects a draft, got: ${t}`}];function Ml(t,...e){{const i=Dl[t],o="function"==typeof i?i.apply(null,e):i;throw new Error(`[Immer] ${o}`)}}var zl=Object.getPrototypeOf;function Il(t){return!!t&&!!t[Tl]}function Ll(t){return!!t&&(Rl(t)||Array.isArray(t)||!!t[$l]||!!t.constructor?.[$l]||Ul(t)||jl(t))}var Ol=Object.prototype.constructor.toString(),Pl=new WeakMap;function Rl(t){if(!t||"object"!=typeof t)return!1;const e=Object.getPrototypeOf(t);if(null===e||e===Object.prototype)return!0;const i=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;if(i===Object)return!0;if("function"!=typeof i)return!1;let o=Pl.get(i);return void 0===o&&(o=Function.toString.call(i),Pl.set(i,o)),o===Ol}function Nl(t,e,i=!0){if(0===Bl(t)){(i?Reflect.ownKeys(t):Object.keys(t)).forEach(i=>{e(i,t[i],t)})}else t.forEach((i,o)=>e(o,i,t))}function Bl(t){const e=t[Tl];return e?e.type_:Array.isArray(t)?1:Ul(t)?2:jl(t)?3:0}function Fl(t,e){return 2===Bl(t)?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function ql(t,e,i){const o=Bl(t);2===o?t.set(e,i):3===o?t.add(i):t[e]=i}function Ul(t){return t instanceof Map}function jl(t){return t instanceof Set}function Hl(t){return t.copy_||t.base_}function Wl(t,e){if(Ul(t))return new Map(t);if(jl(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);const i=Rl(t);if(!0===e||"class_only"===e&&!i){const e=Object.getOwnPropertyDescriptors(t);delete e[Tl];let i=Reflect.ownKeys(e);for(let o=0;o<i.length;o++){const n=i[o],s=e[n];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(e[n]={configurable:!0,writable:!0,enumerable:s.enumerable,value:t[n]})}return Object.create(zl(t),e)}{const e=zl(t);if(null!==e&&i)return{...t};const o=Object.create(e);return Object.assign(o,t)}}function Vl(t,e=!1){return Yl(t)||Il(t)||!Ll(t)||(Bl(t)>1&&Object.defineProperties(t,{set:Zl,add:Zl,clear:Zl,delete:Zl}),Object.freeze(t),e&&Object.values(t).forEach(t=>Vl(t,!0))),t}var Zl={value:function(){Ml(2)}};function Yl(t){return null===t||"object"!=typeof t||Object.isFrozen(t)}var Kl,Gl={};function Xl(t){const e=Gl[t];return e||Ml(0,t),e}function Ql(){return Kl}function Jl(t,e){e&&(Xl("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function td(t){ed(t),t.drafts_.forEach(od),t.drafts_=null}function ed(t){t===Kl&&(Kl=t.parent_)}function id(t){return Kl={drafts_:[],parent_:Kl,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function od(t){const e=t[Tl];0===e.type_||1===e.type_?e.revoke_():e.revoked_=!0}function nd(t,e){e.unfinalizedDrafts_=e.drafts_.length;const i=e.drafts_[0];return void 0!==t&&t!==i?(i[Tl].modified_&&(td(e),Ml(4)),Ll(t)&&(t=sd(e,t),e.parent_||ad(e,t)),e.patches_&&Xl("Patches").generateReplacementPatches_(i[Tl].base_,t,e.patches_,e.inversePatches_)):t=sd(e,i,[]),td(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==El?t:void 0}function sd(t,e,i){if(Yl(e))return e;const o=t.immer_.shouldUseStrictIteration(),n=e[Tl];if(!n)return Nl(e,(o,s)=>rd(t,n,e,o,s,i),o),e;if(n.scope_!==t)return e;if(!n.modified_)return ad(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const e=n.copy_;let s=e,r=!1;3===n.type_&&(s=new Set(e),e.clear(),r=!0),Nl(s,(o,s)=>rd(t,n,e,o,s,i,r),o),ad(t,e,!1),i&&t.patches_&&Xl("Patches").generatePatches_(n,i,t.patches_,t.inversePatches_)}return n.copy_}function rd(t,e,i,o,n,s,r){if(null==n)return;if("object"!=typeof n&&!r)return;const a=Yl(n);if(!a||r){if(n===i&&Ml(5),Il(n)){const r=sd(t,n,s&&e&&3!==e.type_&&!Fl(e.assigned_,o)?s.concat(o):void 0);if(ql(i,o,r),!Il(r))return;t.canAutoFreeze_=!1}else r&&i.add(n);if(Ll(n)&&!a){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;if(e&&e.base_&&e.base_[o]===n&&a)return;sd(t,n),e&&e.scope_.parent_||"symbol"==typeof o||!(Ul(i)?i.has(o):Object.prototype.propertyIsEnumerable.call(i,o))||ad(t,n)}}}function ad(t,e,i=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&Vl(e,i)}var ld={get(t,e){if(e===Tl)return t;const i=Hl(t);if(!Fl(i,e))return function(t,e,i){const o=hd(e,i);return o?"value"in o?o.value:o.get?.call(t.draft_):void 0}(t,i,e);const o=i[e];return t.finalized_||!Ll(o)?o:o===cd(t.base_,e)?(pd(t),t.copy_[e]=md(o,t)):o},has:(t,e)=>e in Hl(t),ownKeys:t=>Reflect.ownKeys(Hl(t)),set(t,e,i){const o=hd(Hl(t),e);if(o?.set)return o.set.call(t.draft_,i),!0;if(!t.modified_){const o=cd(Hl(t),e),n=o?.[Tl];if(n&&n.base_===i)return t.copy_[e]=i,t.assigned_[e]=!1,!0;if(function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}(i,o)&&(void 0!==i||Fl(t.base_,e)))return!0;pd(t),ud(t)}return t.copy_[e]===i&&(void 0!==i||e in t.copy_)||Number.isNaN(i)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=i,t.assigned_[e]=!0),!0},deleteProperty:(t,e)=>(void 0!==cd(t.base_,e)||e in t.base_?(t.assigned_[e]=!1,pd(t),ud(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0),getOwnPropertyDescriptor(t,e){const i=Hl(t),o=Reflect.getOwnPropertyDescriptor(i,e);return o?{writable:!0,configurable:1!==t.type_||"length"!==e,enumerable:o.enumerable,value:i[e]}:o},defineProperty(){Ml(11)},getPrototypeOf:t=>zl(t.base_),setPrototypeOf(){Ml(12)}},dd={};function cd(t,e){const i=t[Tl];return(i?Hl(i):t)[e]}function hd(t,e){if(!(e in t))return;let i=zl(t);for(;i;){const t=Object.getOwnPropertyDescriptor(i,e);if(t)return t;i=zl(i)}}function ud(t){t.modified_||(t.modified_=!0,t.parent_&&ud(t.parent_))}function pd(t){t.copy_||(t.copy_=Wl(t.base_,t.scope_.immer_.useStrictShallowCopy_))}Nl(ld,(t,e)=>{dd[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}}),dd.deleteProperty=function(t,e){return isNaN(parseInt(e))&&Ml(13),dd.set.call(this,t,e,void 0)},dd.set=function(t,e,i){return"length"!==e&&isNaN(parseInt(e))&&Ml(14),ld.set.call(this,t[0],e,i,t[0])};function md(t,e){const i=Ul(t)?Xl("MapSet").proxyMap_(t,e):jl(t)?Xl("MapSet").proxySet_(t,e):function(t,e){const i=Array.isArray(t),o={type_:i?1:0,scope_:e?e.scope_:Ql(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1};let n=o,s=ld;i&&(n=[o],s=dd);const{revoke:r,proxy:a}=Proxy.revocable(n,s);return o.draft_=a,o.revoke_=r,a}(t,e);return(e?e.scope_:Ql()).drafts_.push(i),i}function gd(t){if(!Ll(t)||Yl(t))return t;const e=t[Tl];let i,o=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,i=Wl(t,e.scope_.immer_.useStrictShallowCopy_),o=e.scope_.immer_.shouldUseStrictIteration()}else i=Wl(t,!0);return Nl(i,(t,e)=>{ql(i,t,gd(e))},o),e&&(e.finalized_=!1),i}var fd=new class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,e,i)=>{if("function"==typeof t&&"function"!=typeof e){const i=e;e=t;const o=this;return function(t=i,...n){return o.produce(t,t=>e.call(this,t,...n))}}let o;if("function"!=typeof e&&Ml(6),void 0!==i&&"function"!=typeof i&&Ml(7),Ll(t)){const n=id(this),s=md(t,void 0);let r=!0;try{o=e(s),r=!1}finally{r?td(n):ed(n)}return Jl(n,i),nd(o,n)}if(!t||"object"!=typeof t){if(o=e(t),void 0===o&&(o=t),o===El&&(o=void 0),this.autoFreeze_&&Vl(o,!0),i){const e=[],n=[];Xl("Patches").generateReplacementPatches_(t,o,e,n),i(e,n)}return o}Ml(1,t)},this.produceWithPatches=(t,e)=>{if("function"==typeof t)return(e,...i)=>this.produceWithPatches(e,e=>t(e,...i));let i,o;const n=this.produce(t,e,(t,e)=>{i=t,o=e});return[n,i,o]},"boolean"==typeof t?.autoFreeze&&this.setAutoFreeze(t.autoFreeze),"boolean"==typeof t?.useStrictShallowCopy&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),"boolean"==typeof t?.useStrictIteration&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(t){Ll(t)||Ml(8),Il(t)&&(t=function(t){Il(t)||Ml(10,t);return gd(t)}(t));const e=id(this),i=md(t,void 0);return i[Tl].isManual_=!0,ed(e),i}finishDraft(t,e){const i=t&&t[Tl];i&&i.isManual_||Ml(9);const{scope_:o}=i;return Jl(o,e),nd(void 0,o)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}setUseStrictIteration(t){this.useStrictIteration_=t}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(t,e){let i;for(i=e.length-1;i>=0;i--){const o=e[i];if(0===o.path.length&&"replace"===o.op){t=o.value;break}}i>-1&&(e=e.slice(i+1));const o=Xl("Patches").applyPatches_;return Il(t)?o(t,e):this.produce(t,t=>o(t,e))}},vd=fd.produce;const bd=t=>(e,i,o)=>(o.setState=(t,i,...o)=>{const n="function"==typeof t?vd(t):t;return e(n,i,...o)},t(o.setState,i,o)),yd=t=>(e,i,o)=>{const n=o.subscribe;o.subscribe=(t,e,i)=>{let s=t;if(e){const n=(null==i?void 0:i.equalityFn)||Object.is;let r=t(o.getState());s=i=>{const o=t(i);if(!n(r,o)){const t=r;e(r=o,t)}},(null==i?void 0:i.fireImmediately)&&e(r,r)}return n(s)};return t(e,i,o)},xd="14.3";function wd(t){var e,i;if((null==t?void 0:t.nodes)&&(null===(e=null==t?void 0:t._ui)||void 0===e?void 0:e.nodes))for(const e of t.nodes){const o=t._ui.nodes[e.uuid];if(!o)continue;const n=null===(i=e.actions)||void 0===i?void 0:i.some(t=>!0===t.terminal);"execute_actions"===o.type&&n?o.type="terminal":"terminal"!==o.type||n||(o.type="execute_actions")}}function _d(t){var e,i,o;if((null==t?void 0:t.nodes)&&(null===(e=null==t?void 0:t._ui)||void 0===e?void 0:e.nodes))for(const e of t.nodes){const n=t._ui.nodes[e.uuid];if(!n||"wait_for_response"!==n.type)continue;const s=null===(o=null===(i=e.router)||void 0===i?void 0:i.wait)||void 0===o?void 0:o.hint;s&&("digits"===s.type&&1===s.count?n.type="wait_for_menu":"digits"===s.type?n.type="wait_for_digits":"audio"===s.type&&(n.type="wait_for_audio"))}}function kd(t,e){t.sort((t,i)=>{var o,n;const s=null===(o=e[t.uuid])||void 0===o?void 0:o.position,r=null===(n=e[i.uuid])||void 0===n?void 0:n.position;return s&&r?s.top!==r.top?s.top-r.top:s.left-r.left:0})}function Cd(t=[]){const e=new Map,i=new Map;for(const o of t)if(o.action_uuid){const t=i.get(o.action_uuid)||[];t.push(o),i.set(o.action_uuid,t)}else{const t=e.get(o.node_uuid)||[];t.push(o),e.set(o.node_uuid,t)}return{byNode:e,byAction:i}}const Sd=Al(yd(bd((t,e)=>({features:[],languageNames:{},canvasSize:{width:0,height:0},languageCode:"",workspace:null,flowDefinition:null,flowInfo:null,issuesByNode:new Map,issuesByAction:new Map,isTranslating:!1,viewingRevision:!1,dirtyDate:null,activity:null,simulatorActivity:null,activityEndpoint:null,simulatorActive:!1,flushSave:null,setFlushSave:e=>{t({flushSave:e})},setDirtyDate:e=>{t(t=>{t.dirtyDate=e})},fetchRevision:async(e,i=null)=>{var o;const n=!!i&&"latest"!==i;i||(i="latest");const s=await fetch(`${e}/${i}/?version=${xd}`);if(!s.ok)throw new Error("Network response was not ok");const r=await s.json();wd(r.definition),_d(r.definition);const a=Cd(null===(o=r.info)||void 0===o?void 0:o.issues),l=r.definition.language;t({flowInfo:r.info,flowDefinition:r.definition,viewingRevision:n,issuesByNode:a.byNode,issuesByAction:a.byAction,languageCode:l,isTranslating:!1})},fetchWorkspace:async e=>{const i=await fetch(e);if(!i.ok)throw new Error("Network response was not ok");const o=await i.json();t({workspace:o})},fetchAllLanguages:async e=>{const i=(await le(e)).reduce(function(t,e){return t[e.value]=e.name,t},{});t({languageNames:i})},setActivityEndpoint:e=>{t({activityEndpoint:e})},fetchActivity:async e=>{try{const i=await fetch(e);if(!i.ok)return;const o=await i.json();t({activity:o})}catch(t){console.error("Failed to fetch activity:",t)}},updateActivity:e=>{t({activity:e})},updateSimulatorActivity:e=>{t({simulatorActivity:e})},setSimulatorActive:e=>{t({simulatorActive:e})},getCurrentActivity:()=>{const t=e();return t.simulatorActive?t.simulatorActivity:t.activity},getFlowResults:()=>e().flowInfo.results,getResultByKey:t=>e().flowInfo.results.find(e=>e.key===t),getLanguage:()=>{const t=e(),i=t.languageCode;return{name:t.languageNames[i],code:i}},setFeatures:e=>{t({features:e})},clearFlowData:()=>{t({flowDefinition:null,flowInfo:null,issuesByNode:new Map,issuesByAction:new Map,activity:null,simulatorActivity:null,simulatorActive:!1,dirtyDate:null,viewingRevision:!1})},setFlowContents:e=>{t(t=>{var i,o,n,s;const r=e.definition.language;t.flowDefinition={...e.definition,nodes:[...e.definition.nodes||[]]},t.flowInfo=e.info;const a=Cd(null===(i=e.info)||void 0===i?void 0:i.issues);t.issuesByNode=a.byNode,t.issuesByAction=a.byAction,t.languageCode=r,t.isTranslating=!1,t.viewingRevision=!1,wd(t.flowDefinition),_d(t.flowDefinition),(null===(o=t.flowDefinition)||void 0===o?void 0:o.nodes)&&(null===(s=null===(n=t.flowDefinition)||void 0===n?void 0:n._ui)||void 0===s?void 0:s.nodes)&&kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes)})},setFlowInfo:e=>{t(t=>{t.flowInfo=e;const i=Cd(null==e?void 0:e.issues);t.issuesByNode=i.byNode,t.issuesByAction=i.byAction})},setRevision:e=>{t(t=>{t.flowDefinition.revision=e})},setLanguageCode:e=>{t(t=>{t.languageCode=e,t.isTranslating=t.flowDefinition.language!==e})},expandCanvas:(e,i)=>{t(t=>{const o=Math.max(t.canvasSize.width,e+800),n=Math.max(t.canvasSize.height,i+800);t.canvasSize.width=o,t.canvasSize.height=n})},updateCanvasPositions:e=>{t(t=>{for(const i in e)t.flowDefinition._ui.nodes[i]?t.flowDefinition._ui.nodes[i].position=e[i]:t.flowDefinition._ui.stickies[i]&&(t.flowDefinition._ui.stickies[i].position=e[i]);kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes),t.dirtyDate=new Date})},removeNodes:e=>{t(t=>{for(const i of e)delete t.flowDefinition._ui.nodes[i];t.flowDefinition=vd(t.flowDefinition,t=>{e.forEach(i=>{const o=t.nodes.find(t=>t.uuid===i);if(!o||!o.exits.length)return;const n=o.exits.map(t=>t.destination_uuid).filter(t=>t);if(n.length===o.exits.length&&n.every(t=>t===n[0])){const o=n[0];if(e.includes(o))return;t.nodes.forEach(t=>{t.exits.forEach(t=>{t.destination_uuid===i&&(t.destination_uuid=o)})})}}),t.nodes=t.nodes.filter(t=>!e.includes(t.uuid)),t.nodes.forEach(t=>{t.exits.forEach(t=>{e.includes(t.destination_uuid)&&(t.destination_uuid=null)})}),kd(t.nodes,t._ui.nodes)}),t.dirtyDate=new Date})},removeStickyNotes:e=>{t(t=>{var i;if(null===(i=t.flowDefinition._ui)||void 0===i?void 0:i.stickies)for(const i of e)delete t.flowDefinition._ui.stickies[i];t.dirtyDate=new Date})},updateNode:(e,i)=>{t(t=>{var o;const n=null===(o=t.flowDefinition)||void 0===o?void 0:o.nodes.find(t=>t.uuid===e);n&&(n.actions=i.actions,n.uuid=i.uuid,n.exits=i.exits,n.router=i.router),t.dirtyDate=new Date})},updateNodeUIConfig:(e,i)=>{t(t=>{if(t.flowDefinition._ui.nodes[e]){void 0!==i.type&&(t.flowDefinition._ui.nodes[e].type=i.type),t.flowDefinition._ui.nodes[e].config||(t.flowDefinition._ui.nodes[e].config={});const{type:o,...n}=i;Object.assign(t.flowDefinition._ui.nodes[e].config,n)}t.dirtyDate=new Date})},updateConnection:(e,i,o)=>{t(t=>{const n=t.flowDefinition.nodes.find(t=>t.uuid===e),s=null==n?void 0:n.exits.find(t=>t.uuid===i);s&&(s.destination_uuid=o,t.dirtyDate=new Date)})},updateStickyNote:(e,i)=>{t(t=>{t.flowDefinition._ui.stickies||(t.flowDefinition._ui.stickies={}),t.flowDefinition._ui.stickies[e]=i,t.dirtyDate=new Date})},createStickyNote:e=>{const i=Xt();return t(t=>{t.flowDefinition._ui.stickies||(t.flowDefinition._ui.stickies={});const o={position:e,title:"",body:"",color:"yellow"};t.flowDefinition._ui.stickies[i]=o,t.dirtyDate=new Date}),i},createNode:(e,i)=>{const o=Xt(),n=Xt();return t(t=>{const s={uuid:o,actions:[],exits:[{uuid:n,destination_uuid:null}]};t.flowDefinition.nodes.push(s),t.flowDefinition._ui.nodes||(t.flowDefinition._ui.nodes={}),t.flowDefinition._ui.nodes[o]={position:i,type:e,config:{}},kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes),t.dirtyDate=new Date}),o},addNode:(e,i)=>{t(t=>{t.flowDefinition.nodes.push(e),t.flowDefinition._ui.nodes||(t.flowDefinition._ui.nodes={}),t.flowDefinition._ui.nodes[e.uuid]=i,kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes),t.dirtyDate=new Date})},duplicateNodes:i=>{var o,n;const s=e(),r=new Set(i),a={},l=s.flowDefinition._ui.stickies||{};for(const t of i){if(l[t]){a[t]=Xt();continue}const e=s.flowDefinition.nodes.find(e=>e.uuid===t);if(e){a[t]=Xt();for(const t of e.actions)a[t.uuid]=Xt();for(const t of e.exits)a[t.uuid]=Xt();if(e.router){for(const t of e.router.categories)a[t.uuid]=Xt();for(const t of e.router.cases||[])a[t.uuid]=Xt()}}}const d=[],c=[];for(const t of i){if(l[t]){const e=JSON.parse(JSON.stringify(l[t]));c.push({uuid:a[t],sticky:e});continue}const e=s.flowDefinition.nodes.find(e=>e.uuid===t),i=s.flowDefinition._ui.nodes[t];if(!e||!i)continue;const h=JSON.parse(JSON.stringify(e));h.uuid=a[t];for(const t of h.actions)t.uuid=a[t.uuid];for(const t of h.exits)t.uuid=a[t.uuid],t.destination_uuid&&r.has(t.destination_uuid)?t.destination_uuid=a[t.destination_uuid]:t.destination_uuid=null;if(h.router){for(const t of h.router.categories)t.uuid=a[t.uuid],t.exit_uuid=a[t.exit_uuid];if(h.router.cases)for(const t of h.router.cases)t.uuid=a[t.uuid],t.category_uuid=a[t.category_uuid];h.router.default_category_uuid&&(h.router.default_category_uuid=a[h.router.default_category_uuid]),(null===(n=null===(o=h.router.wait)||void 0===o?void 0:o.timeout)||void 0===n?void 0:n.category_uuid)&&(h.router.wait.timeout.category_uuid=a[h.router.wait.timeout.category_uuid])}const u=JSON.parse(JSON.stringify(i));d.push({node:h,ui:u})}const h={},u=s.flowDefinition.localization;if(u)for(const t of Object.keys(u)){const e=u[t];for(const i of Object.keys(a))e[i]&&(h[t]||(h[t]={}),h[t][a[i]]=JSON.parse(JSON.stringify(e[i])))}return t(t=>{for(const{node:e,ui:i}of d)t.flowDefinition.nodes.push(e),t.flowDefinition._ui.nodes[e.uuid]=i;t.flowDefinition._ui.stickies||(t.flowDefinition._ui.stickies={});for(const{uuid:e,sticky:i}of c)t.flowDefinition._ui.stickies[e]=i;for(const e of Object.keys(h)){t.flowDefinition.localization[e]||(t.flowDefinition.localization[e]={});for(const[i,o]of Object.entries(h[e]))t.flowDefinition.localization[e][i]=o}kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes)}),a},updateLocalization:(e,i,o)=>{t(t=>{t.flowDefinition.localization||(t.flowDefinition.localization={}),t.flowDefinition.localization[e]||(t.flowDefinition.localization[e]={}),Object.keys(o).length>0?t.flowDefinition.localization[e][i]=o:delete t.flowDefinition.localization[e][i],0===Object.keys(t.flowDefinition.localization[e]).length&&delete t.flowDefinition.localization[e],0===Object.keys(t.flowDefinition.localization).length&&delete t.flowDefinition.localization,t.dirtyDate=new Date})},setTranslationFilters:e=>{t(t=>{var i;if(!(null===(i=t.flowDefinition)||void 0===i?void 0:i._ui))return;const o=t.flowDefinition._ui.translation_filters||{categories:!1},n=!!e.categories;o.categories!==n&&(t.flowDefinition._ui.translation_filters={...o,categories:n},t.dirtyDate=new Date)})},markAutoTranslated:(e,i,o)=>{t(t=>{var n;if(!(null===(n=t.flowDefinition)||void 0===n?void 0:n._ui))return;t.flowDefinition._ui.auto_translations||(t.flowDefinition._ui.auto_translations={}),t.flowDefinition._ui.auto_translations[e]||(t.flowDefinition._ui.auto_translations[e]={});const s=t.flowDefinition._ui.auto_translations[e][i]||[],r=Array.from(new Set([...s,...o||[]]));t.flowDefinition._ui.auto_translations[e][i]=r,t.dirtyDate=new Date})}}))));function Ad(t,e){return(i,o)=>{mt()(i,o);const n="connectedCallback",s="disconnectedCallback",r=i[n],a=i[s];i[n]=function(){var i;null!==(i=this._zustandUnsubscribe)&&void 0!==i||(this._zustandUnsubscribe={}),this[o]=e(t.getState()),this._zustandUnsubscribe[o]=t.subscribe(e,t=>{this[o]=t}),r&&r.call(this)},i[s]=function(){var t,e;null===(e=null===(t=this._zustandUnsubscribe)||void 0===t?void 0:t[o])||void 0===e||e.call(t),a&&a.call(this)}}}const{setLocale:Ed}=(t=>(function(t){if(nl)throw new Error("lit-localize can only be configured once");ol=t,nl=!0}((t,e)=>cl(fl,t,e)),vl=pl=t.sourceLocale,ml=new Set(t.targetLocales),ml.add(t.sourceLocale),gl=t.loadLocale,{getLocale:xl,setLocale:wl}))({sourceLocale:"en",targetLocales:_l,loadLocale:t=>import(`./locales/${t}.js`)}),$d=()=>document.querySelector("temba-store");class Td extends Be{constructor(){super(...arguments),this.settings={},this.ttl=6e4,this.max=20,this.ready=!1,this.loader=!1,this.keyedAssets={},this.locale=[...navigator.languages],this.fields={},this.groups={},this.shortcuts=[],this.languages={},this.featuredFields=[],this.dirtyElements=[],this.pendingResolves={},this.fetching={}}static get styles(){return a`
616
+ `,t([mt({type:Number})],Sl.prototype,"scale",void 0),t([mt({type:Boolean})],Sl.prototype,"showName",void 0),t([mt({type:Boolean})],Sl.prototype,"system",void 0),t([mt({type:String,attribute:!1})],Sl.prototype,"bgimage",void 0),t([mt({type:String,attribute:!1})],Sl.prototype,"bgcolor",void 0),t([mt({type:String,attribute:!1})],Sl.prototype,"initials",void 0),t([mt({type:String})],Sl.prototype,"name",void 0),t([mt({type:String})],Sl.prototype,"email",void 0),t([mt({type:String})],Sl.prototype,"uuid",void 0),t([mt({type:String})],Sl.prototype,"avatar",void 0);const Al=t=>{let e;const i=new Set,o=(t,o)=>{const n="function"==typeof t?t(e):t;if(!Object.is(n,e)){const t=e;e=(null!=o?o:"object"!=typeof n||null===n)?n:Object.assign({},e,n),i.forEach(i=>i(e,t))}},n=()=>e,s={setState:o,getState:n,getInitialState:()=>r,subscribe:t=>(i.add(t),()=>i.delete(t))},r=e=t(o,n,s);return s};var El=Symbol.for("immer-nothing"),$l=Symbol.for("immer-draftable"),Tl=Symbol.for("immer-state"),Dl=[function(t){return`The plugin for '${t}' has not been loaded into Immer. To enable the plugin, import and call \`enable${t}()\` when initializing your application.`},function(t){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${t}'`},"This object has been frozen and should not be mutated",function(t){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+t},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(t){return`'current' expects a draft, got: ${t}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(t){return`'original' expects a draft, got: ${t}`}];function Ml(t,...e){{const i=Dl[t],o="function"==typeof i?i.apply(null,e):i;throw new Error(`[Immer] ${o}`)}}var zl=Object.getPrototypeOf;function Il(t){return!!t&&!!t[Tl]}function Ll(t){return!!t&&(Rl(t)||Array.isArray(t)||!!t[$l]||!!t.constructor?.[$l]||Ul(t)||jl(t))}var Ol=Object.prototype.constructor.toString(),Pl=new WeakMap;function Rl(t){if(!t||"object"!=typeof t)return!1;const e=Object.getPrototypeOf(t);if(null===e||e===Object.prototype)return!0;const i=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;if(i===Object)return!0;if("function"!=typeof i)return!1;let o=Pl.get(i);return void 0===o&&(o=Function.toString.call(i),Pl.set(i,o)),o===Ol}function Nl(t,e,i=!0){if(0===Bl(t)){(i?Reflect.ownKeys(t):Object.keys(t)).forEach(i=>{e(i,t[i],t)})}else t.forEach((i,o)=>e(o,i,t))}function Bl(t){const e=t[Tl];return e?e.type_:Array.isArray(t)?1:Ul(t)?2:jl(t)?3:0}function Fl(t,e){return 2===Bl(t)?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function ql(t,e,i){const o=Bl(t);2===o?t.set(e,i):3===o?t.add(i):t[e]=i}function Ul(t){return t instanceof Map}function jl(t){return t instanceof Set}function Hl(t){return t.copy_||t.base_}function Wl(t,e){if(Ul(t))return new Map(t);if(jl(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);const i=Rl(t);if(!0===e||"class_only"===e&&!i){const e=Object.getOwnPropertyDescriptors(t);delete e[Tl];let i=Reflect.ownKeys(e);for(let o=0;o<i.length;o++){const n=i[o],s=e[n];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(e[n]={configurable:!0,writable:!0,enumerable:s.enumerable,value:t[n]})}return Object.create(zl(t),e)}{const e=zl(t);if(null!==e&&i)return{...t};const o=Object.create(e);return Object.assign(o,t)}}function Vl(t,e=!1){return Yl(t)||Il(t)||!Ll(t)||(Bl(t)>1&&Object.defineProperties(t,{set:Zl,add:Zl,clear:Zl,delete:Zl}),Object.freeze(t),e&&Object.values(t).forEach(t=>Vl(t,!0))),t}var Zl={value:function(){Ml(2)}};function Yl(t){return null===t||"object"!=typeof t||Object.isFrozen(t)}var Kl,Gl={};function Xl(t){const e=Gl[t];return e||Ml(0,t),e}function Ql(){return Kl}function Jl(t,e){e&&(Xl("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function td(t){ed(t),t.drafts_.forEach(od),t.drafts_=null}function ed(t){t===Kl&&(Kl=t.parent_)}function id(t){return Kl={drafts_:[],parent_:Kl,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function od(t){const e=t[Tl];0===e.type_||1===e.type_?e.revoke_():e.revoked_=!0}function nd(t,e){e.unfinalizedDrafts_=e.drafts_.length;const i=e.drafts_[0];return void 0!==t&&t!==i?(i[Tl].modified_&&(td(e),Ml(4)),Ll(t)&&(t=sd(e,t),e.parent_||ad(e,t)),e.patches_&&Xl("Patches").generateReplacementPatches_(i[Tl].base_,t,e.patches_,e.inversePatches_)):t=sd(e,i,[]),td(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==El?t:void 0}function sd(t,e,i){if(Yl(e))return e;const o=t.immer_.shouldUseStrictIteration(),n=e[Tl];if(!n)return Nl(e,(o,s)=>rd(t,n,e,o,s,i),o),e;if(n.scope_!==t)return e;if(!n.modified_)return ad(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const e=n.copy_;let s=e,r=!1;3===n.type_&&(s=new Set(e),e.clear(),r=!0),Nl(s,(o,s)=>rd(t,n,e,o,s,i,r),o),ad(t,e,!1),i&&t.patches_&&Xl("Patches").generatePatches_(n,i,t.patches_,t.inversePatches_)}return n.copy_}function rd(t,e,i,o,n,s,r){if(null==n)return;if("object"!=typeof n&&!r)return;const a=Yl(n);if(!a||r){if(n===i&&Ml(5),Il(n)){const r=sd(t,n,s&&e&&3!==e.type_&&!Fl(e.assigned_,o)?s.concat(o):void 0);if(ql(i,o,r),!Il(r))return;t.canAutoFreeze_=!1}else r&&i.add(n);if(Ll(n)&&!a){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;if(e&&e.base_&&e.base_[o]===n&&a)return;sd(t,n),e&&e.scope_.parent_||"symbol"==typeof o||!(Ul(i)?i.has(o):Object.prototype.propertyIsEnumerable.call(i,o))||ad(t,n)}}}function ad(t,e,i=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&Vl(e,i)}var ld={get(t,e){if(e===Tl)return t;const i=Hl(t);if(!Fl(i,e))return function(t,e,i){const o=hd(e,i);return o?"value"in o?o.value:o.get?.call(t.draft_):void 0}(t,i,e);const o=i[e];return t.finalized_||!Ll(o)?o:o===cd(t.base_,e)?(pd(t),t.copy_[e]=md(o,t)):o},has:(t,e)=>e in Hl(t),ownKeys:t=>Reflect.ownKeys(Hl(t)),set(t,e,i){const o=hd(Hl(t),e);if(o?.set)return o.set.call(t.draft_,i),!0;if(!t.modified_){const o=cd(Hl(t),e),n=o?.[Tl];if(n&&n.base_===i)return t.copy_[e]=i,t.assigned_[e]=!1,!0;if(function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}(i,o)&&(void 0!==i||Fl(t.base_,e)))return!0;pd(t),ud(t)}return t.copy_[e]===i&&(void 0!==i||e in t.copy_)||Number.isNaN(i)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=i,t.assigned_[e]=!0),!0},deleteProperty:(t,e)=>(void 0!==cd(t.base_,e)||e in t.base_?(t.assigned_[e]=!1,pd(t),ud(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0),getOwnPropertyDescriptor(t,e){const i=Hl(t),o=Reflect.getOwnPropertyDescriptor(i,e);return o?{writable:!0,configurable:1!==t.type_||"length"!==e,enumerable:o.enumerable,value:i[e]}:o},defineProperty(){Ml(11)},getPrototypeOf:t=>zl(t.base_),setPrototypeOf(){Ml(12)}},dd={};function cd(t,e){const i=t[Tl];return(i?Hl(i):t)[e]}function hd(t,e){if(!(e in t))return;let i=zl(t);for(;i;){const t=Object.getOwnPropertyDescriptor(i,e);if(t)return t;i=zl(i)}}function ud(t){t.modified_||(t.modified_=!0,t.parent_&&ud(t.parent_))}function pd(t){t.copy_||(t.copy_=Wl(t.base_,t.scope_.immer_.useStrictShallowCopy_))}Nl(ld,(t,e)=>{dd[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}}),dd.deleteProperty=function(t,e){return isNaN(parseInt(e))&&Ml(13),dd.set.call(this,t,e,void 0)},dd.set=function(t,e,i){return"length"!==e&&isNaN(parseInt(e))&&Ml(14),ld.set.call(this,t[0],e,i,t[0])};function md(t,e){const i=Ul(t)?Xl("MapSet").proxyMap_(t,e):jl(t)?Xl("MapSet").proxySet_(t,e):function(t,e){const i=Array.isArray(t),o={type_:i?1:0,scope_:e?e.scope_:Ql(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1};let n=o,s=ld;i&&(n=[o],s=dd);const{revoke:r,proxy:a}=Proxy.revocable(n,s);return o.draft_=a,o.revoke_=r,a}(t,e);return(e?e.scope_:Ql()).drafts_.push(i),i}function gd(t){if(!Ll(t)||Yl(t))return t;const e=t[Tl];let i,o=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,i=Wl(t,e.scope_.immer_.useStrictShallowCopy_),o=e.scope_.immer_.shouldUseStrictIteration()}else i=Wl(t,!0);return Nl(i,(t,e)=>{ql(i,t,gd(e))},o),e&&(e.finalized_=!1),i}var fd=new class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,e,i)=>{if("function"==typeof t&&"function"!=typeof e){const i=e;e=t;const o=this;return function(t=i,...n){return o.produce(t,t=>e.call(this,t,...n))}}let o;if("function"!=typeof e&&Ml(6),void 0!==i&&"function"!=typeof i&&Ml(7),Ll(t)){const n=id(this),s=md(t,void 0);let r=!0;try{o=e(s),r=!1}finally{r?td(n):ed(n)}return Jl(n,i),nd(o,n)}if(!t||"object"!=typeof t){if(o=e(t),void 0===o&&(o=t),o===El&&(o=void 0),this.autoFreeze_&&Vl(o,!0),i){const e=[],n=[];Xl("Patches").generateReplacementPatches_(t,o,e,n),i(e,n)}return o}Ml(1,t)},this.produceWithPatches=(t,e)=>{if("function"==typeof t)return(e,...i)=>this.produceWithPatches(e,e=>t(e,...i));let i,o;const n=this.produce(t,e,(t,e)=>{i=t,o=e});return[n,i,o]},"boolean"==typeof t?.autoFreeze&&this.setAutoFreeze(t.autoFreeze),"boolean"==typeof t?.useStrictShallowCopy&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),"boolean"==typeof t?.useStrictIteration&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(t){Ll(t)||Ml(8),Il(t)&&(t=function(t){Il(t)||Ml(10,t);return gd(t)}(t));const e=id(this),i=md(t,void 0);return i[Tl].isManual_=!0,ed(e),i}finishDraft(t,e){const i=t&&t[Tl];i&&i.isManual_||Ml(9);const{scope_:o}=i;return Jl(o,e),nd(void 0,o)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}setUseStrictIteration(t){this.useStrictIteration_=t}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(t,e){let i;for(i=e.length-1;i>=0;i--){const o=e[i];if(0===o.path.length&&"replace"===o.op){t=o.value;break}}i>-1&&(e=e.slice(i+1));const o=Xl("Patches").applyPatches_;return Il(t)?o(t,e):this.produce(t,t=>o(t,e))}},vd=fd.produce;const bd=t=>(e,i,o)=>(o.setState=(t,i,...o)=>{const n="function"==typeof t?vd(t):t;return e(n,i,...o)},t(o.setState,i,o)),yd=t=>(e,i,o)=>{const n=o.subscribe;o.subscribe=(t,e,i)=>{let s=t;if(e){const n=(null==i?void 0:i.equalityFn)||Object.is;let r=t(o.getState());s=i=>{const o=t(i);if(!n(r,o)){const t=r;e(r=o,t)}},(null==i?void 0:i.fireImmediately)&&e(r,r)}return n(s)};return t(e,i,o)},xd="14.3";function wd(t){var e,i;if((null==t?void 0:t.nodes)&&(null===(e=null==t?void 0:t._ui)||void 0===e?void 0:e.nodes))for(const e of t.nodes){const o=t._ui.nodes[e.uuid];if(!o)continue;const n=null===(i=e.actions)||void 0===i?void 0:i.some(t=>!0===t.terminal);"execute_actions"===o.type&&n?o.type="terminal":"terminal"!==o.type||n||(o.type="execute_actions")}}function _d(t){var e,i,o;if((null==t?void 0:t.nodes)&&(null===(e=null==t?void 0:t._ui)||void 0===e?void 0:e.nodes))for(const e of t.nodes){const n=t._ui.nodes[e.uuid];if(!n||"wait_for_response"!==n.type)continue;const s=null===(o=null===(i=e.router)||void 0===i?void 0:i.wait)||void 0===o?void 0:o.hint;s&&("digits"===s.type&&1===s.count?n.type="wait_for_menu":"digits"===s.type?n.type="wait_for_digits":"audio"===s.type&&(n.type="wait_for_audio"))}}function kd(t,e){t.sort((t,i)=>{var o,n;const s=null===(o=e[t.uuid])||void 0===o?void 0:o.position,r=null===(n=e[i.uuid])||void 0===n?void 0:n.position;return s&&r?s.top!==r.top?s.top-r.top:s.left-r.left:0})}function Cd(t=[]){const e=new Map,i=new Map;for(const o of t)if(o.action_uuid){const t=i.get(o.action_uuid)||[];t.push(o),i.set(o.action_uuid,t)}else{const t=e.get(o.node_uuid)||[];t.push(o),e.set(o.node_uuid,t)}return{byNode:e,byAction:i}}const Sd=Al(yd(bd((t,e)=>({features:[],languageNames:{},canvasSize:{width:0,height:0},languageCode:"",workspace:null,flowDefinition:null,flowInfo:null,issuesByNode:new Map,issuesByAction:new Map,isTranslating:!1,viewingRevision:!1,dirtyDate:null,activity:null,simulatorActivity:null,activityEndpoint:null,simulatorActive:!1,flushSave:null,setFlushSave:e=>{t({flushSave:e})},setDirtyDate:e=>{t(t=>{t.dirtyDate=e})},fetchRevision:async(e,i=null)=>{var o;const n=!!i&&"latest"!==i;i||(i="latest");const s=await fetch(`${e}/${i}/?version=${xd}`);if(!s.ok)throw new Error("Network response was not ok");const r=await s.json();wd(r.definition),_d(r.definition);const a=Cd(null===(o=r.info)||void 0===o?void 0:o.issues),l=r.definition.language;t({flowInfo:r.info,flowDefinition:r.definition,viewingRevision:n,issuesByNode:a.byNode,issuesByAction:a.byAction,languageCode:l,isTranslating:!1})},fetchWorkspace:async e=>{const i=await fetch(e);if(!i.ok)throw new Error("Network response was not ok");const o=await i.json();t({workspace:o})},fetchAllLanguages:async e=>{const i=(await le(e)).reduce(function(t,e){return t[e.value]=e.name,t},{});t({languageNames:i})},setActivityEndpoint:e=>{t({activityEndpoint:e})},fetchActivity:async e=>{try{const i=await fetch(e);if(!i.ok)return;const o=await i.json();t({activity:o})}catch(t){console.error("Failed to fetch activity:",t)}},updateActivity:e=>{t({activity:e})},updateSimulatorActivity:e=>{t({simulatorActivity:e})},setSimulatorActive:e=>{t({simulatorActive:e})},getCurrentActivity:()=>{const t=e();return t.simulatorActive?t.simulatorActivity:t.activity},getFlowResults:()=>e().flowInfo.results,getResultByKey:t=>e().flowInfo.results.find(e=>e.key===t),getLanguage:()=>{const t=e(),i=t.languageCode;return{name:t.languageNames[i],code:i}},setFeatures:e=>{t({features:e})},clearFlowData:()=>{t({flowDefinition:null,flowInfo:null,issuesByNode:new Map,issuesByAction:new Map,activity:null,simulatorActivity:null,simulatorActive:!1,dirtyDate:null,viewingRevision:!1})},setFlowContents:e=>{t(t=>{var i,o,n,s;const r=e.definition.language;t.flowDefinition={...e.definition,nodes:[...e.definition.nodes||[]]},t.flowInfo=e.info;const a=Cd(null===(i=e.info)||void 0===i?void 0:i.issues);t.issuesByNode=a.byNode,t.issuesByAction=a.byAction,t.languageCode=r,t.isTranslating=!1,t.viewingRevision=!1,wd(t.flowDefinition),_d(t.flowDefinition),(null===(o=t.flowDefinition)||void 0===o?void 0:o.nodes)&&(null===(s=null===(n=t.flowDefinition)||void 0===n?void 0:n._ui)||void 0===s?void 0:s.nodes)&&kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes)})},setFlowInfo:e=>{t(t=>{t.flowInfo=e;const i=Cd(null==e?void 0:e.issues);t.issuesByNode=i.byNode,t.issuesByAction=i.byAction})},setRevision:e=>{t(t=>{t.flowDefinition.revision=e})},setLanguageCode:e=>{t(t=>{t.languageCode=e,t.isTranslating=t.flowDefinition.language!==e})},expandCanvas:(e,i)=>{t(t=>{const o=Math.max(t.canvasSize.width,e+800),n=Math.max(t.canvasSize.height,i+800);t.canvasSize.width=o,t.canvasSize.height=n})},updateCanvasPositions:e=>{t(t=>{for(const i in e)t.flowDefinition._ui.nodes[i]?t.flowDefinition._ui.nodes[i].position=e[i]:t.flowDefinition._ui.stickies[i]&&(t.flowDefinition._ui.stickies[i].position=e[i]);kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes),t.dirtyDate=new Date})},removeNodes:e=>{t(t=>{for(const i of e)delete t.flowDefinition._ui.nodes[i];t.flowDefinition=vd(t.flowDefinition,t=>{e.forEach(i=>{const o=t.nodes.find(t=>t.uuid===i);if(!o||!o.exits.length)return;const n=o.exits.map(t=>t.destination_uuid).filter(t=>t);if(n.length===o.exits.length&&n.every(t=>t===n[0])){const o=n[0];if(e.includes(o))return;t.nodes.forEach(t=>{t.exits.forEach(t=>{t.destination_uuid===i&&(t.destination_uuid=o)})})}}),t.nodes=t.nodes.filter(t=>!e.includes(t.uuid)),t.nodes.forEach(t=>{t.exits.forEach(t=>{e.includes(t.destination_uuid)&&(t.destination_uuid=null)})}),kd(t.nodes,t._ui.nodes)}),t.dirtyDate=new Date})},removeStickyNotes:e=>{t(t=>{var i;if(null===(i=t.flowDefinition._ui)||void 0===i?void 0:i.stickies)for(const i of e)delete t.flowDefinition._ui.stickies[i];t.dirtyDate=new Date})},updateNode:(e,i)=>{t(t=>{var o;const n=null===(o=t.flowDefinition)||void 0===o?void 0:o.nodes.find(t=>t.uuid===e);n&&(n.actions=i.actions,n.uuid=i.uuid,n.exits=i.exits,n.router=i.router),t.dirtyDate=new Date})},updateNodeUIConfig:(e,i)=>{t(t=>{if(t.flowDefinition._ui.nodes[e]){void 0!==i.type&&(t.flowDefinition._ui.nodes[e].type=i.type),t.flowDefinition._ui.nodes[e].config||(t.flowDefinition._ui.nodes[e].config={});const{type:o,...n}=i;Object.assign(t.flowDefinition._ui.nodes[e].config,n)}t.dirtyDate=new Date})},updateConnection:(e,i,o)=>{t(t=>{const n=t.flowDefinition.nodes.find(t=>t.uuid===e),s=null==n?void 0:n.exits.find(t=>t.uuid===i);s&&(s.destination_uuid=o,t.dirtyDate=new Date)})},updateStickyNote:(e,i)=>{t(t=>{t.flowDefinition._ui.stickies||(t.flowDefinition._ui.stickies={}),t.flowDefinition._ui.stickies[e]=i,t.dirtyDate=new Date})},createStickyNote:e=>{const i=Xt();return t(t=>{t.flowDefinition._ui.stickies||(t.flowDefinition._ui.stickies={});const o={position:e,title:"",body:"",color:"yellow"};t.flowDefinition._ui.stickies[i]=o,t.dirtyDate=new Date}),i},createNode:(e,i)=>{const o=Xt(),n=Xt();return t(t=>{const s={uuid:o,actions:[],exits:[{uuid:n,destination_uuid:null}]};t.flowDefinition.nodes.push(s),t.flowDefinition._ui.nodes||(t.flowDefinition._ui.nodes={}),t.flowDefinition._ui.nodes[o]={position:i,type:e,config:{}},kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes),t.dirtyDate=new Date}),o},addNode:(e,i)=>{t(t=>{t.flowDefinition.nodes.push(e),t.flowDefinition._ui.nodes||(t.flowDefinition._ui.nodes={}),t.flowDefinition._ui.nodes[e.uuid]=i,kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes),t.dirtyDate=new Date})},duplicateNodes:i=>{var o,n;const s=e(),r=new Set(i),a={},l=s.flowDefinition._ui.stickies||{};for(const t of i){if(l[t]){a[t]=Xt();continue}const e=s.flowDefinition.nodes.find(e=>e.uuid===t);if(e){a[t]=Xt();for(const t of e.actions)a[t.uuid]=Xt();for(const t of e.exits)a[t.uuid]=Xt();if(e.router){for(const t of e.router.categories)a[t.uuid]=Xt();for(const t of e.router.cases||[])a[t.uuid]=Xt()}}}const d=[],c=[];for(const t of i){if(l[t]){const e=JSON.parse(JSON.stringify(l[t]));c.push({uuid:a[t],sticky:e});continue}const e=s.flowDefinition.nodes.find(e=>e.uuid===t),i=s.flowDefinition._ui.nodes[t];if(!e||!i)continue;const h=JSON.parse(JSON.stringify(e));h.uuid=a[t];for(const t of h.actions)t.uuid=a[t.uuid];for(const t of h.exits)t.uuid=a[t.uuid],t.destination_uuid&&r.has(t.destination_uuid)?t.destination_uuid=a[t.destination_uuid]:t.destination_uuid=null;if(h.router){for(const t of h.router.categories)t.uuid=a[t.uuid],t.exit_uuid=a[t.exit_uuid];if(h.router.cases)for(const t of h.router.cases)t.uuid=a[t.uuid],t.category_uuid=a[t.category_uuid];h.router.default_category_uuid&&(h.router.default_category_uuid=a[h.router.default_category_uuid]),(null===(n=null===(o=h.router.wait)||void 0===o?void 0:o.timeout)||void 0===n?void 0:n.category_uuid)&&(h.router.wait.timeout.category_uuid=a[h.router.wait.timeout.category_uuid])}const u=JSON.parse(JSON.stringify(i));d.push({node:h,ui:u})}const h={},u=s.flowDefinition.localization;if(u)for(const t of Object.keys(u)){const e=u[t];for(const i of Object.keys(a))e[i]&&(h[t]||(h[t]={}),h[t][a[i]]=JSON.parse(JSON.stringify(e[i])))}return t(t=>{for(const{node:e,ui:i}of d)t.flowDefinition.nodes.push(e),t.flowDefinition._ui.nodes[e.uuid]=i;t.flowDefinition._ui.stickies||(t.flowDefinition._ui.stickies={});for(const{uuid:e,sticky:i}of c)t.flowDefinition._ui.stickies[e]=i;for(const e of Object.keys(h)){t.flowDefinition.localization[e]||(t.flowDefinition.localization[e]={});for(const[i,o]of Object.entries(h[e]))t.flowDefinition.localization[e][i]=o}kd(t.flowDefinition.nodes,t.flowDefinition._ui.nodes)}),a},updateLocalization:(e,i,o)=>{t(t=>{t.flowDefinition.localization||(t.flowDefinition.localization={}),t.flowDefinition.localization[e]||(t.flowDefinition.localization[e]={}),Object.keys(o).length>0?t.flowDefinition.localization[e][i]=o:delete t.flowDefinition.localization[e][i],0===Object.keys(t.flowDefinition.localization[e]).length&&delete t.flowDefinition.localization[e],0===Object.keys(t.flowDefinition.localization).length&&delete t.flowDefinition.localization,t.dirtyDate=new Date})},setTranslationFilters:e=>{t(t=>{var i;if(!(null===(i=t.flowDefinition)||void 0===i?void 0:i._ui))return;const o=t.flowDefinition._ui.translation_filters||{categories:!1},n=!!e.categories;o.categories!==n&&(t.flowDefinition._ui.translation_filters={...o,categories:n},t.dirtyDate=new Date)})},markAutoTranslated:(e,i,o)=>{t(t=>{var n;if(!(null===(n=t.flowDefinition)||void 0===n?void 0:n._ui))return;t.flowDefinition._ui.auto_translations||(t.flowDefinition._ui.auto_translations={}),t.flowDefinition._ui.auto_translations[e]||(t.flowDefinition._ui.auto_translations[e]={});const s=t.flowDefinition._ui.auto_translations[e][i]||[],r=Array.from(new Set([...s,...o||[]]));t.flowDefinition._ui.auto_translations[e][i]=r,t.dirtyDate=new Date})}}))));function Ad(t,e){return(i,o)=>{mt()(i,o);const n="connectedCallback",s="disconnectedCallback",r=i[n],a=i[s];i[n]=function(){var i;null!==(i=this._zustandUnsubscribe)&&void 0!==i||(this._zustandUnsubscribe={}),this[o]=e(t.getState()),this._zustandUnsubscribe[o]=t.subscribe(e,t=>{this[o]=t}),r&&r.call(this)},i[s]=function(){var t,e;null===(e=null===(t=this._zustandUnsubscribe)||void 0===t?void 0:t[o])||void 0===e||e.call(t),a&&a.call(this)}}}var Ed;!function(t){t.Text="text",t.ExpressionPrefix="prefix",t.Identifier="identifier",t.Paren="paren",t.Operator="operator",t.FunctionName="fn",t.StringLiteral="string",t.NumberLiteral="number",t.Keyword="keyword",t.ContextRef="context-ref",t.Separator="separator",t.Whitespace="ws",t.Arrow="arrow",t.Bracket="bracket",t.EscapedAt="escaped-at"}(Ed||(Ed={}));const $d=new Set(["true","false","null"]),Td=new Set(["+","-","*","/","^","&","=","<",">"]),Dd=t=>t>="0"&&t<="9",Md=t=>t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t;function zd(t,e,i){const o=[];let n=0,s=i;const r=(e=0)=>t[n+e],a=(i,n)=>{const s=t.substring(i,n),r=e+i;if($d.has(s.toLowerCase()))return void o.push({type:Ed.Keyword,text:s,start:r});let a=n;for(;a<t.length&&" "===t[a];)a++;a<t.length&&"("===t[a]?o.push({type:Ed.FunctionName,text:s,start:r}):o.push({type:Ed.ContextRef,text:s,start:r})};for(;n<t.length;){const i=t[n];if('"'===i){const i=n;for(n++;n<t.length;)if("\\"===t[n]&&n+1<t.length&&'"'===t[n+1])n+=2;else{if('"'===t[n]){n++;break}n++}o.push({type:Ed.StringLiteral,text:t.substring(i,n),start:e+i});continue}if(Dd(i)||"."===i&&r(1)&&Dd(r(1))){const i=n;for(;n<t.length&&Dd(t[n]);)n++;if(n<t.length&&"."===t[n]&&n+1<t.length&&Dd(t[n+1]))for(n++;n<t.length&&Dd(t[n]);)n++;o.push({type:Ed.NumberLiteral,text:t.substring(i,n),start:e+i});continue}if(Md(i)&&!Dd(i)){const e=n;for(;n<t.length&&(Md(t[n])||"."===t[n])&&("."!==t[n]||!(n+1>=t.length)&&Md(t[n+1]));)n++;a(e,n);continue}if("("!==i)if(")"!==i)if("["!==i&&"]"!==i)if("="!==i||">"!==r(1))if("!"===i&&"="===r(1)||"<"===i&&"="===r(1)||">"===i&&"="===r(1))o.push({type:Ed.Operator,text:i+r(1),start:e+n}),n+=2;else if(Td.has(i))o.push({type:Ed.Operator,text:i,start:e+n}),n++;else if(","!==i){if(" "===i||"\t"===i||"\n"===i||"\r"===i){const i=n;for(;n<t.length&&(" "===t[n]||"\t"===t[n]||"\n"===t[n]||"\r"===t[n]);)n++;o.push({type:Ed.Whitespace,text:t.substring(i,n),start:e+i});continue}o.push({type:Ed.Text,text:i,start:e+n}),n++}else o.push({type:Ed.Separator,text:",",start:e+n}),n++;else o.push({type:Ed.Arrow,text:"=>",start:e+n}),n+=2;else o.push({type:Ed.Bracket,text:i,start:e+n}),n++;else s--,o.push({type:Ed.Paren,text:")",start:e+n,depth:Math.max(0,s),balanced:!0}),n++;else o.push({type:Ed.Paren,text:"(",start:e+n,depth:s,balanced:!0}),s++,n++}return o}function Id(t,e){if(!t)return[];const i=e.findExpressions(t),o=[];let n=0;for(const e of i){if(e.start>n){const i=t.substring(n,e.start);let s=0;for(;s<i.length;){const t=i.indexOf("@@",s);if(-1===t){s<i.length&&o.push({type:Ed.Text,text:i.substring(s),start:n+s});break}t>s&&o.push({type:Ed.Text,text:i.substring(s,t),start:n+s}),o.push({type:Ed.EscapedAt,text:"@@",start:n+t}),s=t+2}}const i=e.text;if(o.push({type:Ed.ExpressionPrefix,text:"@",start:e.start}),i.length>1&&"("===i[1]){o.push({type:Ed.Paren,text:"(",start:e.start+1,depth:0,balanced:e.closed});const t=e.closed&&")"===i[i.length-1],n=t?i.length-1:i.length,s=i.substring(2,n);if(s.length>0){const t=zd(s,e.start+2,1);o.push(...t)}t&&o.push({type:Ed.Paren,text:")",start:e.start+i.length-1,depth:0,balanced:!0}),e.closed||Ld(o,e.start)}else o.push({type:Ed.Identifier,text:i.substring(1),start:e.start+1});n=e.end}if(n<t.length){const e=t.substring(n);let i=0;for(;i<e.length;){const t=e.indexOf("@@",i);if(-1===t){i<e.length&&o.push({type:Ed.Text,text:e.substring(i),start:n+i});break}t>i&&o.push({type:Ed.Text,text:e.substring(i,t),start:n+i}),o.push({type:Ed.EscapedAt,text:"@@",start:n+t}),i=t+2}}return o}function Ld(t,e){for(const i of t)i.type===Ed.Paren&&i.start>=e&&"("===i.text&&0===i.depth&&(i.balanced=!1)}const Od={expression:"#0086e0",fn:"#0086e0",string:"#06a810",number:"#c25ceb",keyword:"#1750eb",operator:"#666",paren:"#999",parenUnmatched:"#ff0011"},Pd={[Ed.Text]:"tok-text",[Ed.ExpressionPrefix]:"tok-prefix",[Ed.Identifier]:"tok-id",[Ed.FunctionName]:"tok-fn",[Ed.StringLiteral]:"tok-str",[Ed.NumberLiteral]:"tok-num",[Ed.Keyword]:"tok-kw",[Ed.Operator]:"tok-op",[Ed.ContextRef]:"tok-ctx",[Ed.Separator]:"tok-sep",[Ed.Whitespace]:"tok-ws",[Ed.Arrow]:"tok-arrow",[Ed.Bracket]:"tok-bracket",[Ed.EscapedAt]:"tok-text",[Ed.Paren]:"tok-paren"},Rd=new Set([Ed.ExpressionPrefix,Ed.Identifier,Ed.FunctionName,Ed.StringLiteral,Ed.NumberLiteral,Ed.Keyword,Ed.Operator,Ed.ContextRef,Ed.Separator,Ed.Whitespace,Ed.Arrow,Ed.Bracket,Ed.Paren]);function Nd(t){return t.type===Ed.Paren&&!1===t.balanced?"tok-paren-unmatched":Pd[t.type]||"tok-text"}const Bd=t=>r(Od[t]),Fd=a`
617
+ .tok-text {
618
+ color: inherit;
619
+ }
620
+
621
+ .tok-prefix {
622
+ color: var(--expression-color, ${Bd("expression")});
623
+ font-weight: 600;
624
+ }
625
+
626
+ .tok-id {
627
+ color: var(--expression-color, ${Bd("expression")});
628
+ }
629
+
630
+ .tok-fn {
631
+ color: var(--expression-fn-color, ${Bd("fn")});
632
+ font-weight: 900;
633
+ }
634
+
635
+ .tok-str {
636
+ color: var(--expression-string-color, ${Bd("string")});
637
+ }
638
+
639
+ .tok-num {
640
+ color: var(--expression-number-color, ${Bd("number")});
641
+ }
642
+
643
+ .tok-kw {
644
+ color: var(--expression-keyword-color, ${Bd("keyword")});
645
+ }
646
+
647
+ .tok-op {
648
+ color: var(--expression-operator-color, ${Bd("operator")});
649
+ }
650
+
651
+ .tok-ctx {
652
+ color: var(--expression-color, ${Bd("expression")});
653
+ }
654
+
655
+ .tok-sep {
656
+ color: var(--expression-operator-color, ${Bd("operator")});
657
+ }
658
+
659
+ .tok-arrow {
660
+ color: var(--expression-operator-color, ${Bd("operator")});
661
+ }
662
+
663
+ .tok-bracket {
664
+ color: var(--expression-operator-color, ${Bd("operator")});
665
+ }
666
+
667
+ .tok-ws {
668
+ /* whitespace tokens — no special color */
669
+ }
670
+
671
+ .tok-newline {
672
+ /* Newline chars rendered via white-space: pre-wrap on parent */
673
+ }
674
+
675
+ .tok-paren {
676
+ color: ${Bd("paren")};
677
+ }
678
+
679
+ .tok-paren-unmatched {
680
+ color: var(--expression-paren-unmatched-color, ${Bd("parenUnmatched")});
681
+ font-weight: 900;
682
+ }
683
+
684
+ .tok-fn-invalid {
685
+ text-decoration: wavy underline ${Bd("parenUnmatched")};
686
+ text-underline-offset: 3px;
687
+ }
688
+
689
+ .tok-mono {
690
+ font-family: var(
691
+ --expression-font-family,
692
+ 'SFMono-Regular',
693
+ 'Consolas',
694
+ 'Liberation Mono',
695
+ 'Menlo',
696
+ monospace
697
+ );
698
+ font-size: 0.95em;
699
+ }
700
+ `,qd=(t,e)=>0===t.indexOf(e,0),Ud=(t,e,i)=>{const o=t.substring(1);if("("===o[0])return!0;{const t=o.split(".")[0].toLowerCase();if(!i)return e.indexOf(t)>=0;for(const i of e)if(qd(i,t))return!0;return!1}},jd=t=>t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t,Hd=t=>{let e=0;for(const i of t)'"'===i&&e++;return e%2!=0};class Wd{constructor(t,e){this.expressionPrefix=t,this.allowedTopLevels=e}expressionContext(t){const e=this.findExpressions(t);if(0===e.length)return null;const i=e[e.length-1];return i.end<t.length||i.closed?null:i.text.substring(1)}autoCompleteContext(t){if(Hd(t))return null;const e=[];let i="",o=!1,n=!1,s="";for(let r=t.length-1;r>=0;r--){const a=t[r];if(" "===a&&(o=!0),","===a&&(o=!0,"("!==e[e.length-1]&&e.push("(")),")"!==a||n||(o=!0,e.push("("),e.push("(")),'"'===a&&(n=!n),o&&("("!==a||n||("("===e[e.length-1]&&e.pop(),0===e.length&&(o=!1))),"("===a&&""===i&&(s="#"),!(o||n||"("===a&&""===i)){if(!jd(a)&&"."!==a)break;i=a+i}}return i.match(/[A-Za-z][\w]*(\.[\w]+)*/)?s+i:null}functionContext(t){let e=Hd(t)?4:6,i="",o="("===t[-1]?0:1;for(let n=t.length-1;n>=0;n--){const s=t[n];if("@"===s)return"";if(6===e)0!==o||!jd(s)&&"."!==s?'"'===s?e=4:"("===s?o--:")"===s&&o++:(e=2,i=s+i);else if(2===e){if(!jd(s)&&"."!==s)return i;i=s+i}else 4===e&&'"'===s&&(e=6)}return""}getContactFields(t){const e={},i=/((parent|child\.)*contact\.)*fields\.([a-z0-9_]+)/g,o=this.findExpressions(t);for(const t of o){let o;for(;o=i.exec(t.text);)e[o[3]]=!0}return Object.keys(e)}findExpressions(t){const e=[];let i=0,o=null,n=0;for(let s=0;s<t.length;s++){const r=t[s],a=s<t.length-1?t[s+1]:0,l=s<t.length-2?t[s+2]:0;if(0===i?r!==this.expressionPrefix||!jd(a)&&"("!==a?r===this.expressionPrefix&&a===this.expressionPrefix&&(i=5):(i=1,o={start:s,end:null,text:r,closed:!1}):1===i?(jd(r)?i=2:"("===r&&(i=3,n+=1),o.text+=r):2===i?o.text+=r:3===i?("("===r?n+=1:")"===r?n-=1:'"'===r&&(i=4),o.text+=r,0===n&&(o.end=s+1)):4===i?('"'===r&&(i=3),o.text+=r):5===i&&(i=0),2===i&&(!jd(a)&&"."!==a||"."===a&&!jd(l))&&(o.end=s+1),null!=o&&(null!=o.end||0===a)){const t=0===a;Ud(o.text,this.allowedTopLevels,t)&&(o.closed="("===o.text[1]&&0===n,o.end=s+1,e.push(o)),o=null,i=0}}return e}}const Vd=new Wd("@",["contact","fields","globals","urns"]),Zd=new Wd("@",["contact","fields","globals","locals","urns","results","input","run","child","parent","node","webhook","ticket","trigger","resume"]),Yd=(t,e)=>{if(t.signature){const i=t.signature.indexOf("("),o=t.signature.substr(0,i),n=t.signature.substr(i);return W`
701
+ <div style="${e?"font-weight: 400":""}">
702
+ <div style="display:inline-block;margin-right: 5px">ƒ</div>
703
+ <div style="display:inline-block">${o}</div>
704
+ ${e?W`
705
+ <div
706
+ style="display:inline-block; font-weight: 300; font-size: 85%"
707
+ >
708
+ ${n}
709
+ </div>
710
+ <div class="detail">${wo(t.summary)}</div>
711
+ `:null}
712
+ </div>
713
+ `}return W`
714
+ <div>
715
+ <div style="${e?"font-weight: 400":""}">${t.name}</div>
716
+ ${e?W` <div style="font-size: 85%">${t.summary}</div> `:null}
717
+ </div>
718
+ `},Kd=(t,e)=>e?t.filter(t=>!!t.signature&&0===t.signature.indexOf((e||"").toLowerCase())):t,Gd=(t,e,i,o)=>{const n=(e||"").split(".");let s=i?t.root:t.root_no_session;if(!s)return[];let r="",a="";for(;n.length>0;)if(a=n.shift(),a){const e=s.find(t=>t.key===a);if(!e){s=s.filter(t=>t.key.startsWith(a.toLowerCase()));break}{const i=t.types.find(t=>t.name===e.type);if(i&&i.properties)s=i.properties,r+=a+".";else{if(!i||!i.property_template){s=s.filter(t=>t.key.startsWith(a.toLowerCase()));break}{r+=a+".";const t=i.property_template,e=o.getCompletions(i.name);s=e?e.map(e=>({key:t.key.replace("{key}",e),help:t.help.replace("{key}",e),type:t.type})):[]}}}}return s.map(t=>({name:"__default__"===t.key?r.substr(0,r.length-1):r+t.key,summary:t.help}))},Xd=(t,e)=>{if(t.isContentEditable)return Qd(t,e);const{offsetLeft:i,offsetTop:o}=t,n=document.createElement("div"),s=getComputedStyle(t);for(const t of s)n.style[t]=s[t];n.style.position="relative";const r="INPUT"===t.tagName?t.value.replace(/ /g,"."):t.value,a=r.substr(0,e);n.textContent=a,"TEXTAREA"===t.tagName&&(n.style.height="auto"),"INPUT"===t.tagName&&(n.style.width="auto");const l=document.createElement("span");l.textContent=r.substr(e)||".",n.appendChild(l),document.body.appendChild(n);const{offsetLeft:d,offsetTop:c}=l;return document.body.removeChild(n),{left:i+d,top:o+c}},Qd=(t,e)=>{const i=t.getRootNode(),o=i.getSelection?i.getSelection():window.getSelection(),n=o&&o.rangeCount>0?o.getRangeAt(0).cloneRange():null,s=((t,e)=>{let i=e;const o=t=>{if(t.nodeType===Node.TEXT_NODE)return i<=t.textContent.length?{node:t,offset:i}:(i-=t.textContent.length,null);if("BR"===t.nodeName)return null;for(const e of t.childNodes){const t=o(e);if(t)return t}return null};return o(t)})(t,e);if(!s){const e=t.getBoundingClientRect();return{left:e.left,top:e.top}}const r=document.createRange();r.setStart(s.node,s.offset),r.collapse(!0);const a=r.getBoundingClientRect();return n&&o&&(o.removeAllRanges(),o.addRange(n)),{left:a.left-t.getBoundingClientRect().left+t.offsetLeft,top:a.top-t.getBoundingClientRect().top+t.offsetTop}},Jd=(t,e,i)=>{let o="";o=i.signature?i.signature.substr(0,i.signature.indexOf("(")+1):i.name;const n=t.length;if(e){const t=e.value,i=e.selectionStart-n,s=t.substr(0,i),r=t.substr(i+n),a=s.length+o.length;e.value=s+o+r,e.setSelectionRange(a,a);const l=Xd(e,a);l.left>e.width&&(e.scrollLeft=l.left),e.dispatchEvent(new Event("input"))}},tc=(t,e)=>{var i;const o={currentFunction:null,options:[],anchorPosition:null,query:null};if(!t)return;const n=Ec();if(!n)return o;const s=t.selectionStart,r=t.value,a=r[s];if(a&&/[\w.]/.test(a))return o;const l=r.substring(0,s),d=e?Zd:Vd,c=d.findExpressions(l).find(t=>t.start<=s&&(t.end>s||t.end===s&&!t.closed));if(c){const s=c.text.indexOf("(")>-1;if(s){const t=d.functionContext(c.text);if(t){const e=Kd(n.getFunctions(),t);e.length>0&&(o.currentFunction=e[0])}}for(let r=c.text.length;r>=0;r--){const a=c.text[r];if("@"===a||"("===a||" "===a||","===a||")"===a||0===r){"("!==a&&" "!==a&&","!==a&&")"!==a&&"@"!==a||r++;const l=Xd(t,c.start+r);if(o.anchorPosition={left:l.left-2-t.scrollLeft,top:l.top-t.scrollTop},o.query=c.text.substr(r,c.text.length-r),o.options=[...Gd(n.getCompletionSchema(),o.query,e,n),...s?Kd(n.getFunctions(),o.query):[]],1===o.options.length){const t=o.options[0];(t.name||(null===(i=t.signature)||void 0===i?void 0:i.substring(0,t.signature.indexOf("(")))||"").toLowerCase()===o.query.toLowerCase()&&(o.options=[])}return o}}}else o.options=[],o.query="";return o},ec=new Intl.DisplayNames(["en"],{type:"language"});function ic(t){if("und"===t)return"Unknown";try{return ec.of(t)||t}catch(e){return t}}const oc="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform);function nc(t){return 0!==t.button||!(!oc||!t.ctrlKey)}function sc(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 rc(t){const e=20*Math.round(t/20);return Math.max(e,0)}const ac="font-family:SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;font-size:0.95em",lc={[Ed.ExpressionPrefix]:`color:${Od.expression};font-weight:600;${ac}`,[Ed.Identifier]:`color:${Od.expression};${ac}`,[Ed.FunctionName]:`color:${Od.fn};font-weight:900;${ac}`,[Ed.StringLiteral]:`color:${Od.string};${ac}`,[Ed.NumberLiteral]:`color:${Od.number};${ac}`,[Ed.Keyword]:`color:${Od.keyword};${ac}`,[Ed.Operator]:`color:${Od.operator};${ac}`,[Ed.ContextRef]:`color:${Od.expression};${ac}`,[Ed.Separator]:`color:${Od.operator};${ac}`,[Ed.Arrow]:`color:${Od.operator};${ac}`,[Ed.Bracket]:`color:${Od.operator};${ac}`,[Ed.Paren]:`color:${Od.paren};${ac}`,[Ed.Whitespace]:ac},dc=[[/claude|anthropic/i,"anthropic"],[/gpt|openai|o1|o3|o4/i,"openai"],[/gemini|google/i,"gemini"],[/azure|microsoft/i,"azure"],[/deepseek/i,"deepseek"]],cc=(t,e=!1)=>{const i=Id(t||"",e?Zd:Vd),o=[];for(const t of i){const e=!!lc[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=lc[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})}`},hc=(t,e,i=3)=>W`<div
719
+ style="display: -webkit-box; -webkit-line-clamp: ${i}; -webkit-box-orient: vertical; overflow: hidden; word-wrap: break-word; overflow-wrap: break-word; hyphens: auto;"
720
+ title="${e}"
721
+ >
722
+ ${t}
723
+ </div>`,uc=(t,e,i)=>W`<div style="display:flex;align-items:center;">
724
+ ${e?W`<temba-icon name=${e} style="margin-right:0.5em"></temba-icon>`:null}
725
+ <div
726
+ style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 250px;"
727
+ title="${t}"
728
+ >
729
+ ${i||t}
730
+ </div>
731
+ </div>`,pc=(t,e,i)=>{const o=[],n=4===t.length?4:Math.min(3,t.length);for(let s=0;s<n;s++){const n=t[s],r=void 0!==i&&n.startsWith("@")?cc(n,i):void 0;o.push(uc(n,e,r))}if(t.length>3&&4!==t.length){const i=t.length-3;o.push(W`<div style="display:flex;align-items:center;margin-top:0.2em;">
732
+ ${e?W`<div style="margin-right:0.4em; width: 1em;"></div>`:null}
733
+ <div style="font-size:0.8em">+${i} more</div>
734
+ </div>`)}return o},mc=t=>{const e=[],i=4===t.length?4:Math.min(3,t.length);for(let o=0;o<i;o++){const i=t[o];i.uuid&&i.eventType?e.push(gc({uuid:i.uuid,name:i.name},i.eventType,i.icon)):e.push(uc(i.name,i.icon,i.content))}if(t.length>3&&4!==t.length){const i=t.length-3;e.push(W`<div style="display:flex;align-items:center;margin-top:0.2em;">
735
+ <div style="margin-right:0.4em; width: 1em;"></div>
736
+ <div style="font-size:0.8em">+${i} more</div>
737
+ </div>`)}return e},gc=(t,e,i)=>W`<div style="display:flex;align-items:center;max-width:100%;">
738
+ ${i?W`<temba-icon name=${i} style="margin-right:0.5em"></temba-icon>`:null}
739
+ <div
740
+ class="linked-name"
741
+ @click=${i=>{i.stopPropagation(),i.preventDefault();const o=i.currentTarget.closest("temba-flow-editor");o&&o.fireCustomEvent(e,{uuid:t.uuid,name:t.name,metaKey:i.metaKey,ctrlKey:i.ctrlKey})}}
742
+ style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 250px; text-decoration: underline; cursor: pointer;"
743
+ >
744
+ ${t.name}
745
+ </div>
746
+ </div>`,fc=(t,e,i)=>{const o=[],n=4===t.length?4:Math.min(3,t.length);for(let s=0;s<n;s++)o.push(gc(t[s],e,i));if(t.length>3&&4!==t.length){const e=t.length-3;o.push(W`<div style="display:flex;align-items:center;margin-top:0.2em;">
747
+ ${i?W`<div style="margin-right:0.4em; width: 1em;"></div>`:null}
748
+ <div style="font-size:0.8em">+${e} more</div>
749
+ </div>`)}return o},vc=(t,e)=>fc(t,Io.FlowClicked,e),bc=(t,e)=>fc(t,Io.GroupClicked,e),yc=[{scheme:"tel",name:"SMS",path:"Phone Number"},{scheme:"whatsapp",name:"WhatsApp",path:"WhatsApp Number"},{scheme:"facebook",name:"Facebook",path:"Facebook ID"},{scheme:"instagram",name:"Instagram",path:"Instagram ID"},{scheme:"twitterid",name:"Twitter",path:"Twitter ID",excludeFromSplit:!0},{scheme:"telegram",name:"Telegram",path:"Telegram ID"},{scheme:"viber",name:"Viber",path:"Viber ID"},{scheme:"line",name:"Line",path:"Line ID"},{scheme:"wechat",name:"WeChat",path:"WeChat ID"},{scheme:"fcm",name:"Firebase",path:"Firebase ID"},{scheme:"jiochat",name:"JioChat",path:"JioChat ID"},{scheme:"freshchat",name:"Freshchat",path:"Freshchat ID"},{scheme:"mailto",name:"Email",path:"Email Address",excludeFromSplit:!0},{scheme:"twitter",name:"Twitter",path:"Twitter Handle",excludeFromSplit:!0},{scheme:"vk",name:"VK",path:"VK ID"},{scheme:"discord",name:"Discord",path:"Discord ID"},{scheme:"webchat",name:"Webchat",path:"Webchat ID",excludeFromSplit:!0},{scheme:"rocketchat",name:"RocketChat",path:"RocketChat ID"},{scheme:"ext",name:"External",path:"External ID"}],xc=(t,e,i)=>{const o=i||document.querySelector(`[id="${t}"]`);if(!o)return null;const n=o.offsetWidth,s=o.offsetHeight;return{uuid:t,left:e.left,top:e.top,right:e.left+n,bottom:e.top+s,width:n,height:s}},wc=(t,e)=>!(t.right<=e.left-10||t.left>=e.right+10||t.bottom<=e.top-10||t.top>=e.bottom+10),_c=["down","up","right","left"],kc=(t,e,i)=>({...t,left:e,top:i,right:e+t.width,bottom:i+t.height}),Cc=(t,e,i)=>{switch(i){case"down":{const i=Math.max(...e.map(t=>t.bottom)),o=rc(i+30);return{left:t.left,top:o}}case"up":{const i=Math.min(...e.map(t=>t.top)),o=rc(i-t.height-30);return o<0?{left:t.left,top:0}:{left:t.left,top:o}}case"right":{const i=Math.max(...e.map(t=>t.right));return{left:rc(i+30),top:t.top}}case"left":{const i=Math.min(...e.map(t=>t.left)),o=rc(i-t.width-30);return o<0?{left:0,top:t.top}:{left:o,top:t.top}}}};function Sc(t,e){if(!e)return t;const i={...t};for(const o of Object.keys(e)){const n=e[o];Array.isArray(n)&&n.length>0&&(Array.isArray(t[o])?i[o]=n:i[o]=n[0])}return i}const{setLocale:Ac}=(t=>(function(t){if(nl)throw new Error("lit-localize can only be configured once");ol=t,nl=!0}((t,e)=>cl(fl,t,e)),vl=pl=t.sourceLocale,ml=new Set(t.targetLocales),ml.add(t.sourceLocale),gl=t.loadLocale,{getLocale:xl,setLocale:wl}))({sourceLocale:"en",targetLocales:_l,loadLocale:t=>import(`./locales/${t}.js`)}),Ec=()=>document.querySelector("temba-store");class $c extends Be{constructor(){super(...arguments),this.settings={},this.ttl=6e4,this.max=20,this.ready=!1,this.loader=!1,this.keyedAssets={},this.locale=[...navigator.languages],this.fields={},this.groups={},this.shortcuts=[],this.languages={},this.featuredFields=[],this.dirtyElements=[],this.pendingResolves={},this.fetching={}}static get styles(){return a`
617
750
  :host {
618
751
  position: fixed;
619
752
  z-index: 1000;
@@ -624,7 +757,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
624
757
  width: 100%;
625
758
  top: 0.5em;
626
759
  }
627
- `}markDirty(t){this.dirtyElements.includes(t)||this.dirtyElements.push(t)}cleanAll(){this.dirtyElements.forEach(t=>t.markClean()),this.dirtyElements=[]}markClean(t){this.dirtyElements=this.dirtyElements.filter(e=>e!==t)}getDirtyMessage(){if(this.dirtyElements.length>0)return this.dirtyElements[0].dirtyMessage||"You have unsaved changes, are you sure you want to continue?"}getLocale(){return this.locale[0]}clearCache(){this.cache=Po(this.max,this.ttl)}reset(){const t=this.getState();this.ready=!1,this.clearCache(),this.settings=JSON.parse(ye("settings")||"{}");const e=[];this.completionEndpoint&&e.push(se(this.completionEndpoint).then(t=>{this.schema=t.json.context,this.fnOptions=t.json.functions})),this.fieldsEndpoint&&e.push(this.refreshFields()),this.globalsEndpoint&&e.push(ce(this.globalsEndpoint).then(t=>{this.keyedAssets.globals=t.map(t=>t.key)})),this.languagesEndpoint&&(t.fetchAllLanguages(this.languagesEndpoint),e.push(ce(this.languagesEndpoint).then(t=>{this.languages=t.reduce(function(t,e){return t[e.value]=e.name,t},{})}))),this.groupsEndpoint&&e.push(ce(this.groupsEndpoint).then(t=>{t.forEach(t=>{this.groups[t.uuid]=t})})),this.workspaceEndpoint&&(t.fetchWorkspace(this.workspaceEndpoint),e.push(se(this.workspaceEndpoint).then(t=>{this.workspace=t.json;const e=t.headers.get("content-language");e&&(this.locale=[e,...this.locale])}))),this.shortcutsEndpoint&&e.push(this.refreshShortcuts()),this.initialHttpComplete=Promise.all(e),this.initialHttpComplete.then(()=>{this.ready=!0})}getShortcuts(){return this.shortcuts||[]}firstUpdated(){this.reset()}getLanguageCode(){return this.locale.length>0?this.locale[0].split("-")[0]:"en"}async refreshGlobals(){return ce(this.globalsEndpoint).then(t=>{this.keyedAssets.globals=t.map(t=>t.key)})}async refreshShortcuts(){return ce(this.shortcutsEndpoint).then(t=>{this.shortcuts=t})}async refreshFields(){return ce(this.fieldsEndpoint).then(t=>{this.keyedAssets.fields=[],this.featuredFields=[],t.forEach(t=>{this.keyedAssets.fields.push(t.key),this.fields[t.key]=t,t.featured&&this.featuredFields.push(t)}),this.featuredFields.sort((t,e)=>e.priority-t.priority),this.keyedAssets.fields.sort(),this.fireCustomEvent(Io.StoreUpdated,{url:this.fieldsEndpoint,data:this.keyedAssets.fields})})}shiftAndRound(t,e,i){const o=Math.round(t.shiftTo(e).get(e));return 1==o?`1 ${i}`:`${o} ${e}`}getCountdown(t){const e=t.diff(Ja.now()).rescale();return e.months>0?"> 1 month":e.days>1?`~ ${this.shiftAndRound(e,"days","day")}`:e.hours>0?`~ ${this.shiftAndRound(e,"hours","hour")}`:`~ ${this.shiftAndRound(e,"minutes","minute")}`}getShortDuration(t,e=null){const i=e||Ja.now();return t.setLocale(this.locale[0]).toRelative({base:i,style:"long"})}getShortDurationFromIso(t,e=null){const i=Ja.fromISO(t),o=e?Ja.fromISO(e):Ja.now();return this.getShortDuration(i,o)}setKeyedAssets(t,e){this.keyedAssets[t]=e}updated(t){if(super.updated(t),t.has("ready")&&this.ready){const t=this.getLanguageCode(),e=_l.find(e=>e===t);e&&Ed(e)}}getCompletionSchema(){return this.schema}getFunctions(){return this.fnOptions}getKeyedAssets(){return this.keyedAssets}getFieldKeys(){return this.keyedAssets.fields||[]}getContactField(t){return this.fields[t]}getFeaturedFields(){return this.featuredFields}getLanguageName(t){return this.languages[t]}isDynamicGroup(t){const e=this.groups[t];return!(e&&!e.query)}getWorkspace(){return this.workspace}formatDate(t){return Ja.fromISO(t).setLocale(this.getLocale()).toLocaleString(Ja.DATETIME_SHORT)}postJSON(t,e=""){return ue(t,e)}postForm(t,e,i={}){return((t,e,i={})=>{const o=new FormData;return Object.keys(e).forEach(t=>{o.append(t,e[t])}),pe(t,o,i)})(t,e,i)}postUrl(t,e="",i={},o=null){return he(t,e,i,o)}getUrl(t,e){return!(e=e||{}).force&&this.cache.has(t)?new Promise(e=>{e(this.cache.get(t))}):se(t,e.controller,e.headers||{}).then(i=>new Promise((o,n)=>{i.status>=200&&i.status<=300?(e.skipCache||this.cache.set(t,i),o(i)):n("Status: "+i.status)}))}getResults(t,e){e=e||{};const i="results_"+t,o=this.cache.get(i);return!e.force&&o?new Promise(t=>{t(o)}):new Promise(e=>{const o=this.pendingResolves[t]||[];o.push(e),this.pendingResolves[t]=o,o.length<=1&&le(t).then(e=>{this.cache.set(i,e);const o=this.pendingResolves[t]||[];for(;o.length>0;){o.pop()(e)}})})}updateCache(t,e){this.cache.set(t,e),this.fireCustomEvent(Io.StoreUpdated,{url:t,data:e})}removeFromCache(t){this.cache.delete(t)}resolveUsers(t,e){return new Promise(i=>{const o=new Set;t.forEach(t=>{e.forEach(e=>{const i=e.split(".");let n=t;for(let t=0;t<i.length&&(n=n[i[t]],n);t++);n&&n.uuid&&o.add(n.uuid)})});const n=[];o.forEach(t=>{n.push(this.getUrl(`/api/v2/users.json?uuid=${encodeURIComponent(t)}`,{force:!0}))}),Promise.all(n).then(o=>{o.forEach(i=>{if(i&&i.json){const o=i.json.results;if(o&&1===o.length){const i=o[0];t.forEach(t=>{e.forEach(e=>{const o=e.split(".");let n=t,s=n;for(let t=0;t<o.length&&(s=n,n=n[o[t]],n);t++);if(n&&n.email===i.email){const t=s[o[o.length-1]];t.avatar=i.avatar,t.name=Cl(i),t.uuid=i.uuid,s[o[o.length-1]].avatar=i.avatar}})})}}}),i()})})}makeRequest(t,e){const i=this.fetching[t],o=(new Date).getTime();if(i)return void setTimeout(()=>{this.makeRequest(t,e)},500);let n=this.cache.get(t);n&&!e.force?(n=e.prepareData?e.prepareData(n):n,this.fireCustomEvent(Io.StoreUpdated,{url:t,data:n})):(e=e||{},this.fetching[t]=o,le(t).then(i=>{i?(this.cache.set(t,i),delete this.fetching[t],i=e.prepareData?e.prepareData(i):i,this.fireCustomEvent(Io.StoreUpdated,{url:t,data:i})):delete this.fetching[t]}))}get(t,e=null){return this.settings[t]||e}set(t,e){this.settings[t]=e}render(){if(!this.ready&&this.loader)return W`<temba-loading size="10" units="8"></temba-loading>`}getCompletions(t){const e=this.getState().flowInfo;return"results"===t?e.results.map(t=>t.key):"locals"===t?e.locals:this.keyedAssets[t]||[]}getApp(){return Sd}getState(){return Sd.getState()}}t([mt({type:Number})],Td.prototype,"ttl",void 0),t([mt({type:Number})],Td.prototype,"max",void 0),t([mt({type:Boolean})],Td.prototype,"ready",void 0),t([mt({type:Boolean})],Td.prototype,"loader",void 0),t([mt({type:String,attribute:"completion"})],Td.prototype,"completionEndpoint",void 0),t([mt({type:String,attribute:"fields"})],Td.prototype,"fieldsEndpoint",void 0),t([mt({type:String,attribute:"groups"})],Td.prototype,"groupsEndpoint",void 0),t([mt({type:String,attribute:"globals"})],Td.prototype,"globalsEndpoint",void 0),t([mt({type:String,attribute:"languages"})],Td.prototype,"languagesEndpoint",void 0),t([mt({type:String,attribute:"workspace"})],Td.prototype,"workspaceEndpoint",void 0),t([mt({type:String,attribute:"shortcuts"})],Td.prototype,"shortcutsEndpoint",void 0),t([mt({type:Object,attribute:!1})],Td.prototype,"schema",void 0),t([mt({type:Object,attribute:!1})],Td.prototype,"fnOptions",void 0),t([mt({type:Object,attribute:!1})],Td.prototype,"keyedAssets",void 0);class Dd extends Be{constructor(){super(...arguments),this.marginHorizontal=0,this.marginVertical=7,this.scrollPct=75,this.cursorIndex=-1,this.internalFocusDisabled=!1,this.nameKey="name",this.loading=!1,this.hideShadow=!1,this.getName=function(t){return t[this.nameKey||"name"]},this.renderInputOption=function(){return null},this.scrollHeight=0,this.triggerScroll=!1,this.showEmptyMessage=!1,this.scrollParent=null,this.setCursor=fe(function(t){this.internalFocusDisabled||t!==this.cursorIndex&&(this.cursorIndex=t)},50)}static get styles(){return a`
760
+ `}markDirty(t){this.dirtyElements.includes(t)||this.dirtyElements.push(t)}cleanAll(){this.dirtyElements.forEach(t=>t.markClean()),this.dirtyElements=[]}markClean(t){this.dirtyElements=this.dirtyElements.filter(e=>e!==t)}getDirtyMessage(){if(this.dirtyElements.length>0)return this.dirtyElements[0].dirtyMessage||"You have unsaved changes, are you sure you want to continue?"}getLocale(){return this.locale[0]}clearCache(){this.cache=Po(this.max,this.ttl)}reset(){const t=this.getState();this.ready=!1,this.clearCache(),this.settings=JSON.parse(ye("settings")||"{}");const e=[];this.completionEndpoint&&e.push(se(this.completionEndpoint).then(t=>{this.schema=t.json.context,this.fnOptions=t.json.functions})),this.fieldsEndpoint&&e.push(this.refreshFields()),this.globalsEndpoint&&e.push(ce(this.globalsEndpoint).then(t=>{this.keyedAssets.globals=t.map(t=>t.key)})),this.languagesEndpoint&&(t.fetchAllLanguages(this.languagesEndpoint),e.push(ce(this.languagesEndpoint).then(t=>{this.languages=t.reduce(function(t,e){return t[e.value]=e.name,t},{})}))),this.groupsEndpoint&&e.push(ce(this.groupsEndpoint).then(t=>{t.forEach(t=>{this.groups[t.uuid]=t})})),this.workspaceEndpoint&&(t.fetchWorkspace(this.workspaceEndpoint),e.push(se(this.workspaceEndpoint).then(t=>{this.workspace=t.json;const e=t.headers.get("content-language");e&&(this.locale=[e,...this.locale])}))),this.shortcutsEndpoint&&e.push(this.refreshShortcuts()),this.initialHttpComplete=Promise.all(e),this.initialHttpComplete.then(()=>{this.ready=!0})}getShortcuts(){return this.shortcuts||[]}firstUpdated(){this.reset()}getLanguageCode(){return this.locale.length>0?this.locale[0].split("-")[0]:"en"}async refreshGlobals(){return ce(this.globalsEndpoint).then(t=>{this.keyedAssets.globals=t.map(t=>t.key)})}async refreshShortcuts(){return ce(this.shortcutsEndpoint).then(t=>{this.shortcuts=t})}async refreshFields(){return ce(this.fieldsEndpoint).then(t=>{this.keyedAssets.fields=[],this.featuredFields=[],t.forEach(t=>{this.keyedAssets.fields.push(t.key),this.fields[t.key]=t,t.featured&&this.featuredFields.push(t)}),this.featuredFields.sort((t,e)=>e.priority-t.priority),this.keyedAssets.fields.sort(),this.fireCustomEvent(Io.StoreUpdated,{url:this.fieldsEndpoint,data:this.keyedAssets.fields})})}shiftAndRound(t,e,i){const o=Math.round(t.shiftTo(e).get(e));return 1==o?`1 ${i}`:`${o} ${e}`}getCountdown(t){const e=t.diff(Ja.now()).rescale();return e.months>0?"> 1 month":e.days>1?`~ ${this.shiftAndRound(e,"days","day")}`:e.hours>0?`~ ${this.shiftAndRound(e,"hours","hour")}`:`~ ${this.shiftAndRound(e,"minutes","minute")}`}getShortDuration(t,e=null){const i=e||Ja.now();return t.setLocale(this.locale[0]).toRelative({base:i,style:"long"})}getShortDurationFromIso(t,e=null){const i=Ja.fromISO(t),o=e?Ja.fromISO(e):Ja.now();return this.getShortDuration(i,o)}setKeyedAssets(t,e){this.keyedAssets[t]=e}updated(t){if(super.updated(t),t.has("ready")&&this.ready){const t=this.getLanguageCode(),e=_l.find(e=>e===t);e&&Ac(e)}}getCompletionSchema(){return this.schema}getFunctions(){return this.fnOptions}getKeyedAssets(){return this.keyedAssets}getFieldKeys(){return this.keyedAssets.fields||[]}getContactField(t){return this.fields[t]}getFeaturedFields(){return this.featuredFields}getLanguageName(t){const e=this.languages[t];return e&&"und"!==e&&"und"!==t?e:ic(t)}isDynamicGroup(t){const e=this.groups[t];return!(e&&!e.query)}getWorkspace(){return this.workspace}formatDate(t){return Ja.fromISO(t).setLocale(this.getLocale()).toLocaleString(Ja.DATETIME_SHORT)}postJSON(t,e=""){return ue(t,e)}postForm(t,e,i={}){return((t,e,i={})=>{const o=new FormData;return Object.keys(e).forEach(t=>{o.append(t,e[t])}),pe(t,o,i)})(t,e,i)}postUrl(t,e="",i={},o=null){return he(t,e,i,o)}getUrl(t,e){return!(e=e||{}).force&&this.cache.has(t)?new Promise(e=>{e(this.cache.get(t))}):se(t,e.controller,e.headers||{}).then(i=>new Promise((o,n)=>{i.status>=200&&i.status<=300?(e.skipCache||this.cache.set(t,i),o(i)):n("Status: "+i.status)}))}getResults(t,e){e=e||{};const i="results_"+t,o=this.cache.get(i);return!e.force&&o?new Promise(t=>{t(o)}):new Promise(e=>{const o=this.pendingResolves[t]||[];o.push(e),this.pendingResolves[t]=o,o.length<=1&&le(t).then(e=>{this.cache.set(i,e);const o=this.pendingResolves[t]||[];for(;o.length>0;){o.pop()(e)}})})}updateCache(t,e){this.cache.set(t,e),this.fireCustomEvent(Io.StoreUpdated,{url:t,data:e})}removeFromCache(t){this.cache.delete(t)}resolveUsers(t,e){return new Promise(i=>{const o=new Set;t.forEach(t=>{e.forEach(e=>{const i=e.split(".");let n=t;for(let t=0;t<i.length&&(n=n[i[t]],n);t++);n&&n.uuid&&o.add(n.uuid)})});const n=[];o.forEach(t=>{n.push(this.getUrl(`/api/v2/users.json?uuid=${encodeURIComponent(t)}`,{force:!0}))}),Promise.all(n).then(o=>{o.forEach(i=>{if(i&&i.json){const o=i.json.results;if(o&&1===o.length){const i=o[0];t.forEach(t=>{e.forEach(e=>{const o=e.split(".");let n=t,s=n;for(let t=0;t<o.length&&(s=n,n=n[o[t]],n);t++);if(n&&n.email===i.email){const t=s[o[o.length-1]];t.avatar=i.avatar,t.name=Cl(i),t.uuid=i.uuid,s[o[o.length-1]].avatar=i.avatar}})})}}}),i()})})}makeRequest(t,e){const i=this.fetching[t],o=(new Date).getTime();if(i)return void setTimeout(()=>{this.makeRequest(t,e)},500);let n=this.cache.get(t);n&&!e.force?(n=e.prepareData?e.prepareData(n):n,this.fireCustomEvent(Io.StoreUpdated,{url:t,data:n})):(e=e||{},this.fetching[t]=o,le(t).then(i=>{i?(this.cache.set(t,i),delete this.fetching[t],i=e.prepareData?e.prepareData(i):i,this.fireCustomEvent(Io.StoreUpdated,{url:t,data:i})):delete this.fetching[t]}))}get(t,e=null){return this.settings[t]||e}set(t,e){this.settings[t]=e}render(){if(!this.ready&&this.loader)return W`<temba-loading size="10" units="8"></temba-loading>`}getCompletions(t){const e=this.getState().flowInfo;return"results"===t?e.results.map(t=>t.key):"locals"===t?e.locals:this.keyedAssets[t]||[]}getApp(){return Sd}getState(){return Sd.getState()}}t([mt({type:Number})],$c.prototype,"ttl",void 0),t([mt({type:Number})],$c.prototype,"max",void 0),t([mt({type:Boolean})],$c.prototype,"ready",void 0),t([mt({type:Boolean})],$c.prototype,"loader",void 0),t([mt({type:String,attribute:"completion"})],$c.prototype,"completionEndpoint",void 0),t([mt({type:String,attribute:"fields"})],$c.prototype,"fieldsEndpoint",void 0),t([mt({type:String,attribute:"groups"})],$c.prototype,"groupsEndpoint",void 0),t([mt({type:String,attribute:"globals"})],$c.prototype,"globalsEndpoint",void 0),t([mt({type:String,attribute:"languages"})],$c.prototype,"languagesEndpoint",void 0),t([mt({type:String,attribute:"workspace"})],$c.prototype,"workspaceEndpoint",void 0),t([mt({type:String,attribute:"shortcuts"})],$c.prototype,"shortcutsEndpoint",void 0),t([mt({type:Object,attribute:!1})],$c.prototype,"schema",void 0),t([mt({type:Object,attribute:!1})],$c.prototype,"fnOptions",void 0),t([mt({type:Object,attribute:!1})],$c.prototype,"keyedAssets",void 0);class Tc extends Be{constructor(){super(...arguments),this.marginHorizontal=0,this.marginVertical=7,this.scrollPct=75,this.cursorIndex=-1,this.internalFocusDisabled=!1,this.nameKey="name",this.loading=!1,this.hideShadow=!1,this.getName=function(t){return t[this.nameKey||"name"]},this.renderInputOption=function(){return null},this.scrollHeight=0,this.triggerScroll=!1,this.showEmptyMessage=!1,this.scrollParent=null,this.setCursor=fe(function(t){this.internalFocusDisabled||t!==this.cursorIndex&&(this.cursorIndex=t)},50)}static get styles(){return a`
628
761
  :host {
629
762
  --transition-speed: 0;
630
763
  }
@@ -840,7 +973,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
840
973
  <temba-loading></temba-loading>
841
974
  </div>
842
975
  </div>
843
- `}}t([mt({type:Number})],Dd.prototype,"top",void 0),t([mt({type:Number})],Dd.prototype,"left",void 0),t([mt({type:Number})],Dd.prototype,"width",void 0),t([mt({type:Number,attribute:"min-width"})],Dd.prototype,"minWidth",void 0),t([mt({type:Number,attribute:"static-width"})],Dd.prototype,"staticWidth",void 0),t([mt({type:Boolean,attribute:"anchor-right"})],Dd.prototype,"anchorRight",void 0),t([mt({type:Number})],Dd.prototype,"marginHorizontal",void 0),t([mt({type:Number})],Dd.prototype,"marginVertical",void 0),t([mt({type:Object})],Dd.prototype,"anchorTo",void 0),t([mt({type:Boolean})],Dd.prototype,"visible",void 0),t([mt({type:Boolean})],Dd.prototype,"block",void 0),t([mt({type:Boolean})],Dd.prototype,"cursorHover",void 0),t([mt({type:Boolean})],Dd.prototype,"cursorSelection",void 0),t([mt({type:Number})],Dd.prototype,"scrollPct",void 0),t([mt({type:Number})],Dd.prototype,"cursorIndex",void 0),t([mt({type:Boolean})],Dd.prototype,"internalFocusDisabled",void 0),t([mt({type:Array})],Dd.prototype,"options",void 0),t([mt({type:Array})],Dd.prototype,"tempOptions",void 0),t([mt({type:Boolean})],Dd.prototype,"poppedTop",void 0),t([mt({type:Boolean})],Dd.prototype,"spaceSelect",void 0),t([mt({type:String})],Dd.prototype,"nameKey",void 0),t([mt({type:Boolean})],Dd.prototype,"loading",void 0),t([mt({type:Boolean})],Dd.prototype,"collapsed",void 0),t([mt({type:Boolean})],Dd.prototype,"hideShadow",void 0),t([mt({attribute:!1})],Dd.prototype,"getName",void 0),t([mt({attribute:!1})],Dd.prototype,"renderInputOption",void 0),t([mt({attribute:!1})],Dd.prototype,"renderOption",void 0),t([mt({attribute:!1})],Dd.prototype,"renderOptionName",void 0),t([mt({attribute:!1})],Dd.prototype,"renderOptionDetail",void 0),t([mt({type:Number})],Dd.prototype,"scrollHeight",void 0),t([mt({type:Boolean})],Dd.prototype,"triggerScroll",void 0),t([mt({type:Boolean})],Dd.prototype,"showEmptyMessage",void 0);class Md extends Be{static get styles(){return a`
976
+ `}}t([mt({type:Number})],Tc.prototype,"top",void 0),t([mt({type:Number})],Tc.prototype,"left",void 0),t([mt({type:Number})],Tc.prototype,"width",void 0),t([mt({type:Number,attribute:"min-width"})],Tc.prototype,"minWidth",void 0),t([mt({type:Number,attribute:"static-width"})],Tc.prototype,"staticWidth",void 0),t([mt({type:Boolean,attribute:"anchor-right"})],Tc.prototype,"anchorRight",void 0),t([mt({type:Number})],Tc.prototype,"marginHorizontal",void 0),t([mt({type:Number})],Tc.prototype,"marginVertical",void 0),t([mt({type:Object})],Tc.prototype,"anchorTo",void 0),t([mt({type:Boolean})],Tc.prototype,"visible",void 0),t([mt({type:Boolean})],Tc.prototype,"block",void 0),t([mt({type:Boolean})],Tc.prototype,"cursorHover",void 0),t([mt({type:Boolean})],Tc.prototype,"cursorSelection",void 0),t([mt({type:Number})],Tc.prototype,"scrollPct",void 0),t([mt({type:Number})],Tc.prototype,"cursorIndex",void 0),t([mt({type:Boolean})],Tc.prototype,"internalFocusDisabled",void 0),t([mt({type:Array})],Tc.prototype,"options",void 0),t([mt({type:Array})],Tc.prototype,"tempOptions",void 0),t([mt({type:Boolean})],Tc.prototype,"poppedTop",void 0),t([mt({type:Boolean})],Tc.prototype,"spaceSelect",void 0),t([mt({type:String})],Tc.prototype,"nameKey",void 0),t([mt({type:Boolean})],Tc.prototype,"loading",void 0),t([mt({type:Boolean})],Tc.prototype,"collapsed",void 0),t([mt({type:Boolean})],Tc.prototype,"hideShadow",void 0),t([mt({attribute:!1})],Tc.prototype,"getName",void 0),t([mt({attribute:!1})],Tc.prototype,"renderInputOption",void 0),t([mt({attribute:!1})],Tc.prototype,"renderOption",void 0),t([mt({attribute:!1})],Tc.prototype,"renderOptionName",void 0),t([mt({attribute:!1})],Tc.prototype,"renderOptionDetail",void 0),t([mt({type:Number})],Tc.prototype,"scrollHeight",void 0),t([mt({type:Boolean})],Tc.prototype,"triggerScroll",void 0),t([mt({type:Boolean})],Tc.prototype,"showEmptyMessage",void 0);class Dc extends Be{static get styles(){return a`
844
977
  :host {
845
978
  margin: auto;
846
979
  }
@@ -886,109 +1019,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
886
1019
  @touchstart=${this.handleTouchStart}
887
1020
  ></slot>
888
1021
  </div>
889
- `}}t([mt({type:String})],Md.prototype,"draggingId",void 0),t([mt({type:Boolean})],Md.prototype,"horizontal",void 0),t([mt({type:String})],Md.prototype,"dropTargetId",void 0),t([mt({type:String})],Md.prototype,"dragHandle",void 0),t([mt({type:String})],Md.prototype,"gap",void 0),t([mt({type:Boolean})],Md.prototype,"externalDrag",void 0),t([mt({attribute:!1})],Md.prototype,"prepareGhost",void 0);const zd=(t,e)=>0===t.indexOf(e,0),Id=(t,e,i)=>{const o=t.substring(1);if("("===o[0])return!0;{const t=o.split(".")[0].toLowerCase();if(!i)return e.indexOf(t)>=0;for(const i of e)if(zd(i,t))return!0;return!1}},Ld=t=>t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t,Od=t=>{let e=0;for(const i of t)'"'===i&&e++;return e%2!=0};class Pd{constructor(t,e){this.expressionPrefix=t,this.allowedTopLevels=e}expressionContext(t){const e=this.findExpressions(t);if(0===e.length)return null;const i=e[e.length-1];return i.end<t.length||i.closed?null:i.text.substring(1)}autoCompleteContext(t){if(Od(t))return null;const e=[];let i="",o=!1,n=!1,s="";for(let r=t.length-1;r>=0;r--){const a=t[r];if(" "===a&&(o=!0),","===a&&(o=!0,"("!==e[e.length-1]&&e.push("(")),")"!==a||n||(o=!0,e.push("("),e.push("(")),'"'===a&&(n=!n),o&&("("!==a||n||("("===e[e.length-1]&&e.pop(),0===e.length&&(o=!1))),"("===a&&""===i&&(s="#"),!(o||n||"("===a&&""===i)){if(!Ld(a)&&"."!==a)break;i=a+i}}return i.match(/[A-Za-z][\w]*(\.[\w]+)*/)?s+i:null}functionContext(t){let e=Od(t)?4:6,i="",o="("===t[-1]?0:1;for(let n=t.length-1;n>=0;n--){const s=t[n];if("@"===s)return"";if(6===e)0!==o||!Ld(s)&&"."!==s?'"'===s?e=4:"("===s?o--:")"===s&&o++:(e=2,i=s+i);else if(2===e){if(!Ld(s)&&"."!==s)return i;i=s+i}else 4===e&&'"'===s&&(e=6)}return""}getContactFields(t){const e={},i=/((parent|child\.)*contact\.)*fields\.([a-z0-9_]+)/g,o=this.findExpressions(t);for(const t of o){let o;for(;o=i.exec(t.text);)e[o[3]]=!0}return Object.keys(e)}findExpressions(t){const e=[];let i=0,o=null,n=0;for(let s=0;s<t.length;s++){const r=t[s],a=s<t.length-1?t[s+1]:0,l=s<t.length-2?t[s+2]:0;if(0===i?r!==this.expressionPrefix||!Ld(a)&&"("!==a?r===this.expressionPrefix&&a===this.expressionPrefix&&(i=5):(i=1,o={start:s,end:null,text:r,closed:!1}):1===i?(Ld(r)?i=2:"("===r&&(i=3,n+=1),o.text+=r):2===i?o.text+=r:3===i?("("===r?n+=1:")"===r?n-=1:'"'===r&&(i=4),o.text+=r,0===n&&(o.end=s+1)):4===i?('"'===r&&(i=3),o.text+=r):5===i&&(i=0),2===i&&(!Ld(a)&&"."!==a||"."===a&&!Ld(l))&&(o.end=s+1),null!=o&&(null!=o.end||0===a)){const t=0===a;Id(o.text,this.allowedTopLevels,t)&&(o.closed="("===o.text[1]&&0===n,o.end=s+1,e.push(o)),o=null,i=0}}return e}}const Rd=new Pd("@",["contact","fields","globals","urns"]),Nd=new Pd("@",["contact","fields","globals","locals","urns","results","input","run","child","parent","node","webhook","ticket","trigger","resume"]),Bd=(t,e)=>{if(t.signature){const i=t.signature.indexOf("("),o=t.signature.substr(0,i),n=t.signature.substr(i);return W`
890
- <div style="${e?"font-weight: 400":""}">
891
- <div style="display:inline-block;margin-right: 5px">ƒ</div>
892
- <div style="display:inline-block">${o}</div>
893
- ${e?W`
894
- <div
895
- style="display:inline-block; font-weight: 300; font-size: 85%"
896
- >
897
- ${n}
898
- </div>
899
- <div class="detail">${wo(t.summary)}</div>
900
- `:null}
901
- </div>
902
- `}return W`
903
- <div>
904
- <div style="${e?"font-weight: 400":""}">${t.name}</div>
905
- ${e?W` <div style="font-size: 85%">${t.summary}</div> `:null}
906
- </div>
907
- `},Fd=(t,e)=>e?t.filter(t=>!!t.signature&&0===t.signature.indexOf((e||"").toLowerCase())):t,qd=(t,e,i,o)=>{const n=(e||"").split(".");let s=i?t.root:t.root_no_session;if(!s)return[];let r="",a="";for(;n.length>0;)if(a=n.shift(),a){const e=s.find(t=>t.key===a);if(!e){s=s.filter(t=>t.key.startsWith(a.toLowerCase()));break}{const i=t.types.find(t=>t.name===e.type);if(i&&i.properties)s=i.properties,r+=a+".";else{if(!i||!i.property_template){s=s.filter(t=>t.key.startsWith(a.toLowerCase()));break}{r+=a+".";const t=i.property_template,e=o.getCompletions(i.name);s=e?e.map(e=>({key:t.key.replace("{key}",e),help:t.help.replace("{key}",e),type:t.type})):[]}}}}return s.map(t=>({name:"__default__"===t.key?r.substr(0,r.length-1):r+t.key,summary:t.help}))},Ud=(t,e)=>{if(t.isContentEditable)return jd(t,e);const{offsetLeft:i,offsetTop:o}=t,n=document.createElement("div"),s=getComputedStyle(t);for(const t of s)n.style[t]=s[t];n.style.position="relative";const r="INPUT"===t.tagName?t.value.replace(/ /g,"."):t.value,a=r.substr(0,e);n.textContent=a,"TEXTAREA"===t.tagName&&(n.style.height="auto"),"INPUT"===t.tagName&&(n.style.width="auto");const l=document.createElement("span");l.textContent=r.substr(e)||".",n.appendChild(l),document.body.appendChild(n);const{offsetLeft:d,offsetTop:c}=l;return document.body.removeChild(n),{left:i+d,top:o+c}},jd=(t,e)=>{const i=t.getRootNode(),o=i.getSelection?i.getSelection():window.getSelection(),n=o&&o.rangeCount>0?o.getRangeAt(0).cloneRange():null,s=((t,e)=>{let i=e;const o=t=>{if(t.nodeType===Node.TEXT_NODE)return i<=t.textContent.length?{node:t,offset:i}:(i-=t.textContent.length,null);if("BR"===t.nodeName)return null;for(const e of t.childNodes){const t=o(e);if(t)return t}return null};return o(t)})(t,e);if(!s){const e=t.getBoundingClientRect();return{left:e.left,top:e.top}}const r=document.createRange();r.setStart(s.node,s.offset),r.collapse(!0);const a=r.getBoundingClientRect();return n&&o&&(o.removeAllRanges(),o.addRange(n)),{left:a.left-t.getBoundingClientRect().left+t.offsetLeft,top:a.top-t.getBoundingClientRect().top+t.offsetTop}},Hd=(t,e,i)=>{let o="";o=i.signature?i.signature.substr(0,i.signature.indexOf("(")+1):i.name;const n=t.length;if(e){const t=e.value,i=e.selectionStart-n,s=t.substr(0,i),r=t.substr(i+n),a=s.length+o.length;e.value=s+o+r,e.setSelectionRange(a,a);const l=Ud(e,a);l.left>e.width&&(e.scrollLeft=l.left),e.dispatchEvent(new Event("input"))}},Wd=(t,e)=>{var i;const o={currentFunction:null,options:[],anchorPosition:null,query:null};if(!t)return;const n=$d();if(!n)return o;const s=t.selectionStart,r=t.value,a=r[s];if(a&&/[\w.]/.test(a))return o;const l=r.substring(0,s),d=e?Nd:Rd,c=d.findExpressions(l).find(t=>t.start<=s&&(t.end>s||t.end===s&&!t.closed));if(c){const s=c.text.indexOf("(")>-1;if(s){const t=d.functionContext(c.text);if(t){const e=Fd(n.getFunctions(),t);e.length>0&&(o.currentFunction=e[0])}}for(let r=c.text.length;r>=0;r--){const a=c.text[r];if("@"===a||"("===a||" "===a||","===a||")"===a||0===r){"("!==a&&" "!==a&&","!==a&&")"!==a&&"@"!==a||r++;const l=Ud(t,c.start+r);if(o.anchorPosition={left:l.left-2-t.scrollLeft,top:l.top-t.scrollTop},o.query=c.text.substr(r,c.text.length-r),o.options=[...qd(n.getCompletionSchema(),o.query,e,n),...s?Fd(n.getFunctions(),o.query):[]],1===o.options.length){const t=o.options[0];(t.name||(null===(i=t.signature)||void 0===i?void 0:i.substring(0,t.signature.indexOf("(")))||"").toLowerCase()===o.query.toLowerCase()&&(o.options=[])}return o}}}else o.options=[],o.query="";return o};var Vd;!function(t){t.Text="text",t.ExpressionPrefix="prefix",t.Identifier="identifier",t.Paren="paren",t.Operator="operator",t.FunctionName="fn",t.StringLiteral="string",t.NumberLiteral="number",t.Keyword="keyword",t.ContextRef="context-ref",t.Separator="separator",t.Whitespace="ws",t.Arrow="arrow",t.Bracket="bracket",t.EscapedAt="escaped-at"}(Vd||(Vd={}));const Zd=new Set(["true","false","null"]),Yd=new Set(["+","-","*","/","^","&","=","<",">"]),Kd=t=>t>="0"&&t<="9",Gd=t=>t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t;function Xd(t,e,i){const o=[];let n=0,s=i;const r=(e=0)=>t[n+e],a=(i,n)=>{const s=t.substring(i,n),r=e+i;if(Zd.has(s.toLowerCase()))return void o.push({type:Vd.Keyword,text:s,start:r});let a=n;for(;a<t.length&&" "===t[a];)a++;a<t.length&&"("===t[a]?o.push({type:Vd.FunctionName,text:s,start:r}):o.push({type:Vd.ContextRef,text:s,start:r})};for(;n<t.length;){const i=t[n];if('"'===i){const i=n;for(n++;n<t.length;)if("\\"===t[n]&&n+1<t.length&&'"'===t[n+1])n+=2;else{if('"'===t[n]){n++;break}n++}o.push({type:Vd.StringLiteral,text:t.substring(i,n),start:e+i});continue}if(Kd(i)||"."===i&&r(1)&&Kd(r(1))){const i=n;for(;n<t.length&&Kd(t[n]);)n++;if(n<t.length&&"."===t[n]&&n+1<t.length&&Kd(t[n+1]))for(n++;n<t.length&&Kd(t[n]);)n++;o.push({type:Vd.NumberLiteral,text:t.substring(i,n),start:e+i});continue}if(Gd(i)&&!Kd(i)){const e=n;for(;n<t.length&&(Gd(t[n])||"."===t[n])&&("."!==t[n]||!(n+1>=t.length)&&Gd(t[n+1]));)n++;a(e,n);continue}if("("!==i)if(")"!==i)if("["!==i&&"]"!==i)if("="!==i||">"!==r(1))if("!"===i&&"="===r(1)||"<"===i&&"="===r(1)||">"===i&&"="===r(1))o.push({type:Vd.Operator,text:i+r(1),start:e+n}),n+=2;else if(Yd.has(i))o.push({type:Vd.Operator,text:i,start:e+n}),n++;else if(","!==i){if(" "===i||"\t"===i||"\n"===i||"\r"===i){const i=n;for(;n<t.length&&(" "===t[n]||"\t"===t[n]||"\n"===t[n]||"\r"===t[n]);)n++;o.push({type:Vd.Whitespace,text:t.substring(i,n),start:e+i});continue}o.push({type:Vd.Text,text:i,start:e+n}),n++}else o.push({type:Vd.Separator,text:",",start:e+n}),n++;else o.push({type:Vd.Arrow,text:"=>",start:e+n}),n+=2;else o.push({type:Vd.Bracket,text:i,start:e+n}),n++;else s--,o.push({type:Vd.Paren,text:")",start:e+n,depth:Math.max(0,s),balanced:!0}),n++;else o.push({type:Vd.Paren,text:"(",start:e+n,depth:s,balanced:!0}),s++,n++}return o}function Qd(t,e){if(!t)return[];const i=e.findExpressions(t),o=[];let n=0;for(const e of i){if(e.start>n){const i=t.substring(n,e.start);let s=0;for(;s<i.length;){const t=i.indexOf("@@",s);if(-1===t){s<i.length&&o.push({type:Vd.Text,text:i.substring(s),start:n+s});break}t>s&&o.push({type:Vd.Text,text:i.substring(s,t),start:n+s}),o.push({type:Vd.EscapedAt,text:"@@",start:n+t}),s=t+2}}const i=e.text;if(o.push({type:Vd.ExpressionPrefix,text:"@",start:e.start}),i.length>1&&"("===i[1]){o.push({type:Vd.Paren,text:"(",start:e.start+1,depth:0,balanced:e.closed});const t=e.closed&&")"===i[i.length-1],n=t?i.length-1:i.length,s=i.substring(2,n);if(s.length>0){const t=Xd(s,e.start+2,1);o.push(...t)}t&&o.push({type:Vd.Paren,text:")",start:e.start+i.length-1,depth:0,balanced:!0}),e.closed||Jd(o,e.start)}else o.push({type:Vd.Identifier,text:i.substring(1),start:e.start+1});n=e.end}if(n<t.length){const e=t.substring(n);let i=0;for(;i<e.length;){const t=e.indexOf("@@",i);if(-1===t){i<e.length&&o.push({type:Vd.Text,text:e.substring(i),start:n+i});break}t>i&&o.push({type:Vd.Text,text:e.substring(i,t),start:n+i}),o.push({type:Vd.EscapedAt,text:"@@",start:n+t}),i=t+2}}return o}function Jd(t,e){for(const i of t)i.type===Vd.Paren&&i.start>=e&&"("===i.text&&0===i.depth&&(i.balanced=!1)}function tc(t){const e=t.getRootNode();return e.getSelection?e.getSelection():window.getSelection()}function ec(t){if(t.nodeType===Node.TEXT_NODE)return t.textContent.length;if("BR"===t.nodeName)return 0;let e=0;for(const i of Array.from(t.childNodes))e+=ec(i);return e}function ic(t,e,i){let o=0;const n=t=>{if(t===e){if(t.nodeType===Node.TEXT_NODE)o+=i;else for(let e=0;e<i&&e<t.childNodes.length;e++)o+=ec(t.childNodes[e]);return!0}if(t.nodeType===Node.TEXT_NODE)return o+=t.textContent.length,!1;if("BR"===t.nodeName)return!1;for(const e of Array.from(t.childNodes))if(n(e))return!0;return!1};return n(t),o}function oc(t,e){let i=e;const o=t=>{if(t.nodeType===Node.TEXT_NODE)return i<=t.textContent.length?{node:t,offset:i}:(i-=t.textContent.length,null);if("BR"===t.nodeName)return null;for(const e of Array.from(t.childNodes)){const t=o(e);if(t)return t}return null};return o(t)}function nc(t){let e="";for(const i of Array.from(t.childNodes))if(i.nodeType===Node.TEXT_NODE)e+=i.textContent;else if(i.nodeType===Node.ELEMENT_NODE){if("BR"===i.nodeName)continue;e+=nc(i)}return e}function sc(t){const e=tc(t);if(!e||0===e.rangeCount)return 0;const i=e.getRangeAt(0);return ic(t,i.startContainer,i.startOffset)}function rc(t){const e=tc(t);if(!e||0===e.rangeCount)return 0;const i=e.getRangeAt(0);return ic(t,i.endContainer,i.endOffset)}function ac(t,e){const i=oc(t,e);if(!i)return;const o=tc(t);if(!o)return;const n=document.createRange();n.setStart(i.node,i.offset),n.collapse(!0),o.removeAllRanges(),o.addRange(n)}function lc(t,e,i){const o=oc(t,e),n=oc(t,i);if(!o||!n)return;const s=tc(t);if(!s)return;const r=document.createRange();r.setStart(o.node,o.offset),r.setEnd(n.node,n.offset),s.removeAllRanges(),s.addRange(r)}const dc={expression:"#0086e0",fn:"#0086e0",string:"#06a810",number:"#c25ceb",keyword:"#1750eb",operator:"#666",paren:"#999",parenUnmatched:"#ff0011"},cc={[Vd.Text]:"tok-text",[Vd.ExpressionPrefix]:"tok-prefix",[Vd.Identifier]:"tok-id",[Vd.FunctionName]:"tok-fn",[Vd.StringLiteral]:"tok-str",[Vd.NumberLiteral]:"tok-num",[Vd.Keyword]:"tok-kw",[Vd.Operator]:"tok-op",[Vd.ContextRef]:"tok-ctx",[Vd.Separator]:"tok-sep",[Vd.Whitespace]:"tok-ws",[Vd.Arrow]:"tok-arrow",[Vd.Bracket]:"tok-bracket",[Vd.EscapedAt]:"tok-text",[Vd.Paren]:"tok-paren"},hc=new Set([Vd.ExpressionPrefix,Vd.Identifier,Vd.FunctionName,Vd.StringLiteral,Vd.NumberLiteral,Vd.Keyword,Vd.Operator,Vd.ContextRef,Vd.Separator,Vd.Whitespace,Vd.Arrow,Vd.Bracket,Vd.Paren]);function uc(t){return t.type===Vd.Paren&&!1===t.balanced?"tok-paren-unmatched":cc[t.type]||"tok-text"}const pc=t=>r(dc[t]),mc=a`
908
- .tok-text {
909
- color: inherit;
910
- }
911
-
912
- .tok-prefix {
913
- color: var(--expression-color, ${pc("expression")});
914
- font-weight: 600;
915
- }
916
-
917
- .tok-id {
918
- color: var(--expression-color, ${pc("expression")});
919
- }
920
-
921
- .tok-fn {
922
- color: var(--expression-fn-color, ${pc("fn")});
923
- font-weight: 900;
924
- }
925
-
926
- .tok-str {
927
- color: var(--expression-string-color, ${pc("string")});
928
- }
929
-
930
- .tok-num {
931
- color: var(--expression-number-color, ${pc("number")});
932
- }
933
-
934
- .tok-kw {
935
- color: var(--expression-keyword-color, ${pc("keyword")});
936
- }
937
-
938
- .tok-op {
939
- color: var(--expression-operator-color, ${pc("operator")});
940
- }
941
-
942
- .tok-ctx {
943
- color: var(--expression-color, ${pc("expression")});
944
- }
945
-
946
- .tok-sep {
947
- color: var(--expression-operator-color, ${pc("operator")});
948
- }
949
-
950
- .tok-arrow {
951
- color: var(--expression-operator-color, ${pc("operator")});
952
- }
953
-
954
- .tok-bracket {
955
- color: var(--expression-operator-color, ${pc("operator")});
956
- }
957
-
958
- .tok-ws {
959
- /* whitespace tokens — no special color */
960
- }
961
-
962
- .tok-newline {
963
- /* Newline chars rendered via white-space: pre-wrap on parent */
964
- }
965
-
966
- .tok-paren {
967
- color: ${pc("paren")};
968
- }
969
-
970
- .tok-paren-unmatched {
971
- color: var(--expression-paren-unmatched-color, ${pc("parenUnmatched")});
972
- font-weight: 900;
973
- }
974
-
975
- .tok-fn-invalid {
976
- text-decoration: wavy underline ${pc("parenUnmatched")};
977
- text-underline-offset: 3px;
978
- }
979
-
980
- .tok-mono {
981
- font-family: var(
982
- --expression-font-family,
983
- 'SFMono-Regular',
984
- 'Consolas',
985
- 'Liberation Mono',
986
- 'Menlo',
987
- monospace
988
- );
989
- font-size: 0.95em;
990
- }
991
- `;class gc extends _o{static get styles(){return a`
1022
+ `}}function Mc(t){const e=t.getRootNode();return e.getSelection?e.getSelection():window.getSelection()}function zc(t){if(t.nodeType===Node.TEXT_NODE)return t.textContent.length;if("BR"===t.nodeName)return 0;let e=0;for(const i of Array.from(t.childNodes))e+=zc(i);return e}function Ic(t,e,i){let o=0;const n=t=>{if(t===e){if(t.nodeType===Node.TEXT_NODE)o+=i;else for(let e=0;e<i&&e<t.childNodes.length;e++)o+=zc(t.childNodes[e]);return!0}if(t.nodeType===Node.TEXT_NODE)return o+=t.textContent.length,!1;if("BR"===t.nodeName)return!1;for(const e of Array.from(t.childNodes))if(n(e))return!0;return!1};return n(t),o}function Lc(t,e){let i=e;const o=t=>{if(t.nodeType===Node.TEXT_NODE)return i<=t.textContent.length?{node:t,offset:i}:(i-=t.textContent.length,null);if("BR"===t.nodeName)return null;for(const e of Array.from(t.childNodes)){const t=o(e);if(t)return t}return null};return o(t)}function Oc(t){let e="";for(const i of Array.from(t.childNodes))if(i.nodeType===Node.TEXT_NODE)e+=i.textContent;else if(i.nodeType===Node.ELEMENT_NODE){if("BR"===i.nodeName)continue;e+=Oc(i)}return e}function Pc(t){const e=Mc(t);if(!e||0===e.rangeCount)return 0;const i=e.getRangeAt(0);return Ic(t,i.startContainer,i.startOffset)}function Rc(t){const e=Mc(t);if(!e||0===e.rangeCount)return 0;const i=e.getRangeAt(0);return Ic(t,i.endContainer,i.endOffset)}function Nc(t,e){const i=Lc(t,e);if(!i)return;const o=Mc(t);if(!o)return;const n=document.createRange();n.setStart(i.node,i.offset),n.collapse(!0),o.removeAllRanges(),o.addRange(n)}function Bc(t,e,i){const o=Lc(t,e),n=Lc(t,i);if(!o||!n)return;const s=Mc(t);if(!s)return;const r=document.createRange();r.setStart(o.node,o.offset),r.setEnd(n.node,n.offset),s.removeAllRanges(),s.addRange(r)}t([mt({type:String})],Dc.prototype,"draggingId",void 0),t([mt({type:Boolean})],Dc.prototype,"horizontal",void 0),t([mt({type:String})],Dc.prototype,"dropTargetId",void 0),t([mt({type:String})],Dc.prototype,"dragHandle",void 0),t([mt({type:String})],Dc.prototype,"gap",void 0),t([mt({type:Boolean})],Dc.prototype,"externalDrag",void 0),t([mt({attribute:!1})],Dc.prototype,"prepareGhost",void 0);class Fc extends _o{static get styles(){return a`
992
1023
  ${super.styles}
993
1024
 
994
1025
  :host {
@@ -1281,7 +1312,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1281
1312
  content: '';
1282
1313
  }
1283
1314
 
1284
- ${mc}
1315
+ ${Fd}
1285
1316
 
1286
1317
  .placeholder {
1287
1318
  font-size: var(--temba-select-selected-font-size);
@@ -1363,7 +1394,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1363
1394
  padding: 4px 10px;
1364
1395
  border-radius: 2px;
1365
1396
  }
1366
- `}set values(t){this._values=Array.isArray(t)?t:[],this.requestUpdate("values")}get values(){return this._values||[]}constructor(){super(),this.hiddenInputs=[],this.inputStyle={},this.multi=!1,this.searchOnFocus=!1,this.placeholder="",this.name="",this.allowCreate=!1,this.nameKey="name",this.valueKey="value",this.maxItems=0,this.maxItemsText="Maximum items reached",this.queryParam=null,this.input="",this.visibleOptions=[],this.completionOptions=[],this.quietMillis=0,this.searchable=!1,this.cache=!0,this.cacheKey="",this.focused=!1,this.disabled=!1,this.attemptedOpen=!1,this.selectedIndex=-1,this.anchorPosition={left:0,top:0},this.tags=!1,this.emails=!1,this.flavor="default",this.infoText="",this._values=[],this.getName=t=>t[this.nameKey||"name"],this.isMatch=this.isMatchDefault,this.getValue=t=>t[this.valueKey||"value"]||t.id,this.sortFunction=null,this.renderOptionDetail=()=>W``,this.renderSelectedItem=this.renderSelectedItemDefault,this.createArbitraryOption=this.createArbitraryOptionDefault,this.getOptions=this.getOptionsDefault,this.prepareOptions=this.prepareOptionsDefault,this.isComplete=this.isCompleteDefault,this.staticOptions=[],this.allowAnchor=!0,this.alphaSort=(t,e)=>this.endpoint?this.getNameInternal(t).localeCompare(this.getNameInternal(e)):0,this.next=null,this.lruCache=Po(20,6e4),this.hintRepositionHandler=null,this.getNameInternal=t=>this.getName?this.getName(t):t[this.nameKey||"name"]||"",this.expressionInputPatchedElement=null,this.renderOptionDefault=this.renderOptionDefault.bind(this),this.renderSelectedItemDefault=this.renderSelectedItemDefault.bind(this),this.prepareOptionsDefault=this.prepareOptionsDefault.bind(this),this.isMatchDefault=this.isMatchDefault.bind(this),this.handleOrderChanged=this.handleOrderChanged.bind(this),this.createArbitraryOption=this.createArbitraryOptionDefault.bind(this)}prepareOptionsDefault(t){return t}isMatchDefault(t,e){return(this.getNameInternal(t)||"").toLowerCase().indexOf(e)>-1}handleSlotChange(){if(this.staticOptions&&0===this.staticOptions.length)for(const t of this.children)if("TEMBA-OPTION"===t.tagName){const e={};for(const i of t.attributes)e[i.name]=i.value;if(e){let t=!1;void 0!==e.selected&&(delete e.selected,t=!0);const i=this.value||this.getAttribute("value");if(i){this.getValue(e)==i&&(t=!0)}this.staticOptions.push(e),t&&(this.isMultiMode?this.addValue(e):this.setValues([e]))}}this.searchable&&0===this.staticOptions.length&&(this.quietMillis=200)}checkSelectedOption(){if(this.value&&0==this.values.length&&0==this.staticOptions.length&&this.endpoint){const t=this.value;this.resolving=!0,le(this.endpoint).then(e=>{if(e&&e.length>0){if(t){const i=e.find(e=>this.getValue(e)===t);if(i)return this.resolving=!1,this.fetching=!1,void this.setValues([i])}this.setValues([e[0]]),this.resolving=!1}})}else this.staticOptions.length>0&&(null!==this.getAttribute("multi")?this.addValue(this.staticOptions[0]):this.getAttribute("value")?this.setSelectedValue(this.getAttribute("value")):this.setValues([this.staticOptions[0]]))}firstUpdated(t){super.firstUpdated(t),this.anchorElement=this.shadowRoot.querySelector(".select-container"),this.anchorExpressions=this.shadowRoot.querySelector("#anchor"),this.shadowRoot.addEventListener("slotchange",this.handleSlotChange.bind(this))}willUpdate(t){if(t.has("createArbitraryOption")&&(this.createArbitraryOption||(this.createArbitraryOption=this.createArbitraryOptionDefault.bind(this))),0===this.values.length&&!this.placeholder&&this.staticOptions.length>0){const t=this._values;this._values=[this.staticOptions[0]],this.requestUpdate("values",t)}if(t.has("sorted")&&(this.sortFunction=this.sorted?this.alphaSort:null),t.has("value")&&this.value&&!this.values.length)if(this.staticOptions.length>0){const t=this.staticOptions.find(t=>this.getValue(t)===this.value);t&&(this._values=[t],this.requestUpdate("values"))}else this.checkSelectedOption();if(t.has("values"))if(0===this.values.length)this.value=null;else{this.getAttribute("name")&&!this.isMultiMode&&1===this.values.length&&(this.selection=this.values[0],this.value=this.serializeValue(this.values[0]))}super.willUpdate(t)}measureInputTextWidth(t){if(this.useExpressionInput)return t.scrollWidth;const e=document.createElement("span"),i=getComputedStyle(t);e.style.font=i.font,e.style.letterSpacing=i.letterSpacing,e.style.visibility="hidden",e.style.position="absolute",e.style.whiteSpace="pre",e.textContent=this.input,this.shadowRoot.appendChild(e);const o=e.offsetWidth;return e.remove(),o}addHintRepositionListeners(){this.hintRepositionHandler||(this.hintRepositionHandler=()=>this.updateEnterHintPosition(),window.addEventListener("scroll",this.hintRepositionHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.hintRepositionHandler))}removeHintRepositionListeners(){this.hintRepositionHandler&&(window.removeEventListener("scroll",this.hintRepositionHandler,{capture:!0}),window.removeEventListener("resize",this.hintRepositionHandler),this.hintRepositionHandler=null)}disconnectedCallback(){super.disconnectedCallback(),this.removeHintRepositionListeners()}updateEnterHintPosition(){const t=this.shadowRoot.querySelector(".enter-hint");if(!t)return void this.removeHintRepositionListeners();const e=this.shadowRoot.querySelector(".searchbox");if(!e)return;this.addHintRepositionListeners();const i=e.getBoundingClientRect(),o=this.measureInputTextWidth(e);t.style.left=`${i.left+o+4}px`,t.style.top=`${i.top+(i.height-t.offsetHeight)/2}px`}updateInputWrapperWidth(){if(!this.isMultiMode)return;const t=this.shadowRoot.querySelector(".input-wrapper");if(!t)return;const e=this.shadowRoot.querySelector(".searchbox");if(e)if(this.input){const i=this.measureInputTextWidth(e);t.style.minWidth=`${i+20}px`}else t.style.minWidth=""}updated(t){if(super.updated(t),(t.has("input")||t.has("focused"))&&(this.updateEnterHintPosition(),this.updateInputWrapperWidth()),this.expressions&&!this.anchorExpressions){const t=this.shadowRoot.querySelector("#anchor");t&&(this.anchorExpressions=t)}if(this.useExpressionInput){const e=this.shadowRoot.querySelector(".expression-input");if(e&&(this.patchEditableAsInput(e),t.has("input"))){nc(e)!==this.input&&this.renderExpressionHighlight(e,this.input)}}t.has("values")&&(this.updateInputs(),this.hasChanges(t.get("values"))&&this.fireEvent("change")),t.has("cacheKey")&&this.lruCache.clear(),t.has("input")&&!t.has("values")&&!t.has("options")&&this.focused&&(this.lastQuery&&window.clearTimeout(this.lastQuery),this.lastQuery=window.setTimeout(()=>{this.expressions&&this.input.indexOf("@")>-1&&(!this.emails&&!this.tags||this.input.trimStart().startsWith("@"))?this.fetchExpressions():(this.completionOptions.length>0&&(this.completionOptions=[]),this.emails||this.tags||this.fetchOptions(this.input))},this.quietMillis)),this.endpoint&&t.has("fetching")&&(this.fetching||this.isPastFetchThreshold()||this.fireCustomEvent(Io.FetchComplete)),(t.has("cursorIndex")||t.has("visibleOptions"))&&this.endpoint&&!this.fetching&&this.isPastFetchThreshold()&&(this.next?this.fetchOptions(null,null,this.next):this.fetchOptions(this.query,this.page+1))}hasChanges(t){if(void 0===t)return!1;let e;void 0!==t&&(e=(t||[]).map(t=>this.getValue(t)).join(","));return e!==(this.values||[]).map(t=>t.arbitrary||this.getValue(t)).join(",")}setSelectedValue(t){if(this.staticOptions.length>0){const e=this.staticOptions.find(e=>this.getValue(e)===t);e&&this.setValues([e])}else this.checkSelectedOption()}updateInputs(){for(let t=null;t=this.hiddenInputs.pop();)t.remove();if(0===this.values.length)this.value=null;else{const t=this.getAttribute("name");t&&(this.isMultiMode||1!==this.values.length?this.inputRoot.parentElement&&this.values.forEach(e=>{const i=document.createElement("input");i.setAttribute("type","hidden"),i.setAttribute("name",t),i.setAttribute("value",this.serializeValue(e)),this.hiddenInputs.push(i),this.inputRoot.parentElement.appendChild(i)}):(this.selection=this.values[0],this.value=this.serializeValue(this.values[0]),this.internals&&this.internals.setFormValue(this.value)))}}setSelectedOption(t){this.isMultiMode?this.addValue(t):this.setValues([t]),this.isMultiMode&&this.searchable||(this.blur(),this.focused=!1),this.visibleOptions=[],this.attemptedOpen=!1,this.input="",this.next=null,this.complete=!0,this.selectedIndex=-1}isPastFetchThreshold(){return(this.visibleOptions.length>0||this.next)&&!this.complete&&(this.cursorIndex||0)>this.visibleOptions.length-20}handleOptionSelection(t){if(this.isMultiMode&&this.maxItems>0&&this.values.length>=this.maxItems)return void(this.infoText=this.maxItemsText);this.infoText="";const e=t.detail.selected;e.arbitrary&&this.allowCreate&&this.endpoint?(this.resolving=!0,ue(this.endpoint,e).then(t=>{t.status>=200&&t.status<300?(this.setSelectedOption(t.json),this.lruCache=Po(20,6e4),this.errors=[]):(this.setSelectedOption(e),setTimeout(()=>{this.errors=['There was an error creating "'+this.getNameInternal(e)+'"']},0),this.blur()),this.resolving=!1})):(this.setSelectedOption(e),this.errors=[])}handleExpressionSelection(t){const e=t.detail.selected,i=t.detail.tabbed,o=this.shadowRoot.querySelector(".searchbox"),n=this.input;Hd(this.query,o,e),this.query="",this.completionOptions=[],this.input!==n&&(i||this.emails||this.tags?this.fetchExpressions():-1===this.input.indexOf("(")&&this.addInputAsValue())}getOptionsDefault(t){return t.json.results}isCompleteDefault(t,e){const i=e.json;return!i.more&&!i.next}handleRemoveSelection(t){if(this.removeValue(t),this.visibleOptions=[],this.errors=[],this.allowCreate){const t=this.values.find(t=>t.arbitrary);t&&setTimeout(()=>{this.errors=['There was an error creating "'+this.getNameInternal(t)+'"']},0)}}createArbitraryOptionDefault(t,e){return this.expressions&&t&&this.isValidExpression(t)?{name:t,value:t,expression:!0}:this.emails&&t&&this.isValidEmail(t)||this.tags&&t?{name:t,value:t}:null}isValidEmail(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}isDuplicateValue(t){const e=t.trim().toLowerCase();return this.values.some(t=>(t.value||t.name||"").toLowerCase()===e)}isAcceptableInput(t){if(!t||this.isDuplicateValue(t))return!1;return this.expressions&&t.trimStart().startsWith("@")?this.isValidExpression(t):this.emails?this.isValidEmail(t.trim()):this.tags?t.trim().length>0:!this.expressions}looksLikeExpression(t){return/^@[a-zA-Z_(]/.test(t.trim())}isValidExpression(t){if(!this.looksLikeExpression(t))return!1;const e=("session"===this.expressions?Nd:Rd).findExpressions(t.trim());return 0!==e.length&&e.every(t=>!t.text.startsWith("@(")||t.closed)}get useExpressionInput(){return!(!this.expressions||!this.searchable)}patchEditableAsInput(t){if(this.expressionInputPatchedElement===t)return;const e=this,i=t;Object.defineProperty(i,"value",{get:()=>nc(t),set(i){e.renderExpressionHighlight(t,i)},configurable:!0}),Object.defineProperty(i,"selectionStart",{get:()=>sc(t),configurable:!0}),Object.defineProperty(i,"selectionEnd",{get:()=>rc(t),configurable:!0}),i.setSelectionRange=(e,i)=>{lc(t,e,i)},this.expressionInputPatchedElement=t}renderExpressionHighlight(t,e){if(t.textContent="",e&&e.trimStart().startsWith("@")&&!this.isDuplicateValue(e)){const i=Qd(e,"session"===this.expressions?Nd:Rd);for(const e of i){const i=uc(e),o=hc.has(e.type);if(e.text.length>0){const n=document.createElement("span");n.textContent=e.text,n.className=o?`${i} tok-mono`:i,t.appendChild(n)}}}else if(e)if(e.trimStart().startsWith("@")){const i=document.createElement("span");i.textContent=e,i.className="tok-mono",t.appendChild(i)}else t.appendChild(document.createTextNode(e));e||t.appendChild(document.createTextNode(""))}get isMultiMode(){return this.multi||this.emails}open(){this.shadowRoot.querySelector(".select-container").click()}isOpen(){return this.visibleOptions.length>0||this.attemptedOpen&&this.focused}setOptions(t){this.staticOptions=t}setVisibleOptions(t){if(t=t.filter(t=>!!this.getNameInternal(t)&&(!this.shouldExclude||!this.shouldExclude(t))),this.input){if(this.searchable&&!this.queryParam){const e=this.input.trim().toLowerCase();t=t.filter(t=>this.isMatch(t,e))}const e=this.createArbitraryOption(this.input,t);if(e){e.arbitrary=!0;t.find(t=>this.getValue(t)===this.getValue(e))||(t.length>0&&t[0].arbitrary?t[0]=e:t.unshift(e))}}this.values.length>0&&(this.isMultiMode?t=t.filter(t=>!this.values.find(e=>this.getValue(e)===this.getValue(t))):(this.input?this.cursorIndex=0:this.cursorIndex=t.findIndex(t=>this.getValue(t)===this.getValue(this.values[0])),this.requestUpdate("cursorIndex"))),this.isMultiMode&&this.maxItems>0&&this.values.length>=this.maxItems&&(t=[],this.infoText=this.maxItemsText),this.sortFunction&&t.sort(this.sortFunction),this.visibleOptions=t,this.fireCustomEvent(Io.ContentChanged,{options:this.visibleOptions})}fetchExpressions(){const t=document.querySelector("temba-store");if(this.expressions&&t){const t=this.shadowRoot.querySelector(".searchbox"),e=Wd(t,"session"===this.expressions);return this.query=e.query,this.completionOptions=e.options,this.visibleOptions=[],this.anchorPosition=e.anchorPosition,void this.fireCustomEvent(Io.FetchComplete)}}fetchOptions(t,e=0,i=null){if(this.completionOptions=[],!this.fetching){this.fetching=!0;const o=[...this.staticOptions],n=(t||"").trim().toLowerCase();if(this.tags&&n&&(o.find(t=>this.getValue(t)&&this.getValue(t).toLowerCase()===n)||o.splice(0,0,{name:t,value:t})),this.emails&&n&&this.isValidEmail(n)&&!o.find(t=>this.getValue(t)&&this.getValue(t).toLowerCase()===n)&&o.splice(0,0,{name:t,value:t}),this.endpoint){let s=this.endpoint;i?s=i:(t&&this.queryParam&&(s.indexOf("?")>-1?s+="&":s+="?",s+=this.queryParam+"="+encodeURIComponent(t)),e&&(s.indexOf("?")>-1?s+="&":s+="?",s+="page="+e));const r=this.lruCache.get(s);if(this.cache&&!this.tags&&!this.emails&&r)return 0!==e||this.next?this.setVisibleOptions([...this.visibleOptions,...r.options]):(this.cursorIndex=0,this.setVisibleOptions([...o,...r.options])),this.complete=r.complete,this.next=r.next,void(this.fetching=!1);this.searchable&&!this.queryParam?le(s).then(t=>{t=this.prepareOptions(t),!this.cache||this.tags||this.emails||(this.lruCache.set(s,{options:t,complete:!0,next:null}),this.complete=!0,this.next=null,this.setVisibleOptions([...o,...t]),this.fetching=!1)}):se(s).then(i=>{let r=this.getOptions(i).filter(t=>this.isMatch(t,n));r=this.prepareOptions(r),this.next=null;const a=i.json;a.next&&(this.next=a.next),0!==e||this.next?(r.length>0&&this.setVisibleOptions([...this.visibleOptions,...r]),this.complete=this.isComplete(r,i)):(this.cursorIndex=0,this.setVisibleOptions([...o,...r]),this.query=t,this.complete=this.isComplete(this.visibleOptions,i)),!this.cache||this.tags||this.emails||this.lruCache.set(s,{options:r,complete:this.complete,next:this.next}),this.fetching=!1,this.page=e}).catch(t=>{this.fetching=!1,console.error(t)})}else this.fetching=!1,this.setVisibleOptions(o)}}handleFocus(){this.focused||0!==this.visibleOptions.length||(this.focused=!0)}handleBlur(){setTimeout(()=>{this.focused=!1,this.attemptedOpen=!1,this.visibleOptions.length>0&&(this.input="",this.next=null,this.complete=!0,this.visibleOptions=[],this.cursorIndex=0),(this.emails||this.tags)&&(this.input="",this.completionOptions=[]),this.isMultiMode&&this.maxItems>0&&this.values.length>=this.maxItems&&(this.infoText="")},0)}handleClick(){this.selectedIndex=-1,this.requestUpdate("input")}addInputAsValue(){const t=this.shadowRoot.querySelector(".searchbox"),e={name:t.value,value:t.value,expression:!0};this.isMultiMode?this.values.find(t=>t.expression&&t.value&&e.value&&t.value.toLowerCase().trim()==e.value.toLowerCase().trim())||this.addValue(e):this.setValues([e]),this.input="",this.isMultiMode||this.blur()}handleBeforeInput(t){"insertLineBreak"!==t.inputType&&"insertParagraph"!==t.inputType||(this.useExpressionInput&&t.preventDefault(),0===this.completionOptions.length&&(this.emails||this.tags||this.expressions)&&this.isAcceptableInput(this.input)&&(t.preventDefault(),this.addInputAsValue()))}handleKeyDown(t){if("Enter"===t.key&&this.useExpressionInput&&t.preventDefault(),","===t.key&&this.emails&&!this.looksLikeExpression(this.input))return t.preventDefault(),void(this.isAcceptableInput(this.input)&&this.addInputAsValue());if("Enter"===t.key&&0===this.completionOptions.length&&(this.emails||this.tags||this.expressions)&&this.isAcceptableInput(this.input))return t.preventDefault(),void this.addInputAsValue();if(("Enter"===t.key||"ArrowDown"===t.key||"n"===t.key&&t.ctrlKey)&&0===this.visibleOptions.length&&0===this.completionOptions.length&&!this.input)return this.attemptedOpen=!0,void this.requestUpdate("input");if(this.isMultiMode&&"Backspace"===t.key&&!this.input){if(this.visibleOptions.length>0)return void(this.visibleOptions=[]);-1===this.selectedIndex?(this.selectedIndex=this.values.length-1,this.visibleOptions=[]):(this.popValue(),this.selectedIndex=-1)}else this.selectedIndex=-1}getStaticOptions(){return this.staticOptions}handleInput(t){const e=t.currentTarget;if(this.useExpressionInput){const t=nc(e),i=sc(e);this.input=t,this.renderExpressionHighlight(e,t);try{lc(e,i,i)}catch(t){}}else this.input=e.value}handleCancel(){this.visibleOptions=[],this.attemptedOpen=!1}handleCursorChanged(t){this.cursorIndex=t.detail.index}getSearchboxElement(){return this.shadowRoot.querySelector(".searchbox")}isExpressionInputTarget(t){return t instanceof HTMLElement&&t.classList.contains("expression-input")}handleContainerClick(t){if(this.disabled)return t.stopPropagation(),void t.preventDefault();this.focused=!0;if("INPUT"!==t.target.tagName&&!this.isExpressionInputTarget(t.target)){const t=this.getSearchboxElement();if(t)return t.click(),void t.focus();this.isOpen()?(this.visibleOptions=[],this.attemptedOpen=!1):(this.attemptedOpen=!0,this.requestUpdate("input"),this.requestUpdate())}}getEventHandlers(){return[{event:Io.Canceled,method:this.handleCancel},{event:Io.CursorChanged,method:this.handleCursorChanged},{event:"blur",method:this.handleBlur},{event:"focus",method:this.handleFocus}]}handleArrowClick(t){this.disabled||this.isOpen()&&(t.preventDefault(),t.stopPropagation(),this.blur())}renderHighlightedName(t){const e=this.getNameInternal(t);if(this.expressions&&e.startsWith("@")){const t=Qd(e,"session"===this.expressions?Nd:Rd);return W`${t.map(t=>{const e=uc(t),i=hc.has(t.type);return W`<span class="${i?`${e} tok-mono`:e}"
1397
+ `}set values(t){this._values=Array.isArray(t)?t:[],this.requestUpdate("values")}get values(){return this._values||[]}constructor(){super(),this.hiddenInputs=[],this.inputStyle={},this.multi=!1,this.searchOnFocus=!1,this.placeholder="",this.name="",this.allowCreate=!1,this.nameKey="name",this.valueKey="value",this.maxItems=0,this.maxItemsText="Maximum items reached",this.queryParam=null,this.input="",this.visibleOptions=[],this.completionOptions=[],this.quietMillis=0,this.searchable=!1,this.cache=!0,this.cacheKey="",this.focused=!1,this.disabled=!1,this.attemptedOpen=!1,this.selectedIndex=-1,this.anchorPosition={left:0,top:0},this.tags=!1,this.emails=!1,this.flavor="default",this.infoText="",this._values=[],this.getName=t=>t[this.nameKey||"name"],this.isMatch=this.isMatchDefault,this.getValue=t=>t[this.valueKey||"value"]||t.id,this.sortFunction=null,this.renderOptionDetail=()=>W``,this.renderSelectedItem=this.renderSelectedItemDefault,this.createArbitraryOption=this.createArbitraryOptionDefault,this.getOptions=this.getOptionsDefault,this.prepareOptions=this.prepareOptionsDefault,this.isComplete=this.isCompleteDefault,this.staticOptions=[],this.allowAnchor=!0,this.alphaSort=(t,e)=>this.endpoint?this.getNameInternal(t).localeCompare(this.getNameInternal(e)):0,this.next=null,this.lruCache=Po(20,6e4),this.hintRepositionHandler=null,this.getNameInternal=t=>this.getName?this.getName(t):t[this.nameKey||"name"]||"",this.expressionInputPatchedElement=null,this.renderOptionDefault=this.renderOptionDefault.bind(this),this.renderSelectedItemDefault=this.renderSelectedItemDefault.bind(this),this.prepareOptionsDefault=this.prepareOptionsDefault.bind(this),this.isMatchDefault=this.isMatchDefault.bind(this),this.handleOrderChanged=this.handleOrderChanged.bind(this),this.createArbitraryOption=this.createArbitraryOptionDefault.bind(this)}prepareOptionsDefault(t){return t}isMatchDefault(t,e){return(this.getNameInternal(t)||"").toLowerCase().indexOf(e)>-1}handleSlotChange(){if(this.staticOptions&&0===this.staticOptions.length)for(const t of this.children)if("TEMBA-OPTION"===t.tagName){const e={};for(const i of t.attributes)e[i.name]=i.value;if(e){let t=!1;void 0!==e.selected&&(delete e.selected,t=!0);const i=this.value||this.getAttribute("value");if(i){this.getValue(e)==i&&(t=!0)}this.staticOptions.push(e),t&&(this.isMultiMode?this.addValue(e):this.setValues([e]))}}this.searchable&&0===this.staticOptions.length&&(this.quietMillis=200)}checkSelectedOption(){if(this.value&&0==this.values.length&&0==this.staticOptions.length&&this.endpoint){const t=this.value;this.resolving=!0,le(this.endpoint).then(e=>{if(e&&e.length>0){if(t){const i=e.find(e=>this.getValue(e)===t);if(i)return this.resolving=!1,this.fetching=!1,void this.setValues([i])}this.setValues([e[0]]),this.resolving=!1}})}else this.staticOptions.length>0&&(null!==this.getAttribute("multi")?this.addValue(this.staticOptions[0]):this.getAttribute("value")?this.setSelectedValue(this.getAttribute("value")):this.setValues([this.staticOptions[0]]))}firstUpdated(t){super.firstUpdated(t),this.anchorElement=this.shadowRoot.querySelector(".select-container"),this.anchorExpressions=this.shadowRoot.querySelector("#anchor"),this.shadowRoot.addEventListener("slotchange",this.handleSlotChange.bind(this))}willUpdate(t){if(t.has("createArbitraryOption")&&(this.createArbitraryOption||(this.createArbitraryOption=this.createArbitraryOptionDefault.bind(this))),0===this.values.length&&!this.placeholder&&this.staticOptions.length>0){const t=this._values;this._values=[this.staticOptions[0]],this.requestUpdate("values",t)}if(t.has("sorted")&&(this.sortFunction=this.sorted?this.alphaSort:null),t.has("value")&&this.value&&!this.values.length)if(this.staticOptions.length>0){const t=this.staticOptions.find(t=>this.getValue(t)===this.value);t&&(this._values=[t],this.requestUpdate("values"))}else this.checkSelectedOption();if(t.has("values"))if(0===this.values.length)this.value=null;else{this.getAttribute("name")&&!this.isMultiMode&&1===this.values.length&&(this.selection=this.values[0],this.value=this.serializeValue(this.values[0]))}super.willUpdate(t)}measureInputTextWidth(t){if(this.useExpressionInput)return t.scrollWidth;const e=document.createElement("span"),i=getComputedStyle(t);e.style.font=i.font,e.style.letterSpacing=i.letterSpacing,e.style.visibility="hidden",e.style.position="absolute",e.style.whiteSpace="pre",e.textContent=this.input,this.shadowRoot.appendChild(e);const o=e.offsetWidth;return e.remove(),o}addHintRepositionListeners(){this.hintRepositionHandler||(this.hintRepositionHandler=()=>this.updateEnterHintPosition(),window.addEventListener("scroll",this.hintRepositionHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.hintRepositionHandler))}removeHintRepositionListeners(){this.hintRepositionHandler&&(window.removeEventListener("scroll",this.hintRepositionHandler,{capture:!0}),window.removeEventListener("resize",this.hintRepositionHandler),this.hintRepositionHandler=null)}disconnectedCallback(){super.disconnectedCallback(),this.removeHintRepositionListeners()}updateEnterHintPosition(){const t=this.shadowRoot.querySelector(".enter-hint");if(!t)return void this.removeHintRepositionListeners();const e=this.shadowRoot.querySelector(".searchbox");if(!e)return;this.addHintRepositionListeners();const i=e.getBoundingClientRect(),o=this.measureInputTextWidth(e);t.style.left=`${i.left+o+4}px`,t.style.top=`${i.top+(i.height-t.offsetHeight)/2}px`}updateInputWrapperWidth(){if(!this.isMultiMode)return;const t=this.shadowRoot.querySelector(".input-wrapper");if(!t)return;const e=this.shadowRoot.querySelector(".searchbox");if(e)if(this.input){const i=this.measureInputTextWidth(e);t.style.minWidth=`${i+20}px`}else t.style.minWidth=""}updated(t){if(super.updated(t),(t.has("input")||t.has("focused"))&&(this.updateEnterHintPosition(),this.updateInputWrapperWidth()),this.expressions&&!this.anchorExpressions){const t=this.shadowRoot.querySelector("#anchor");t&&(this.anchorExpressions=t)}if(this.useExpressionInput){const e=this.shadowRoot.querySelector(".expression-input");if(e&&(this.patchEditableAsInput(e),t.has("input"))){Oc(e)!==this.input&&this.renderExpressionHighlight(e,this.input)}}t.has("values")&&(this.updateInputs(),this.hasChanges(t.get("values"))&&this.fireEvent("change")),t.has("cacheKey")&&this.lruCache.clear(),t.has("input")&&!t.has("values")&&!t.has("options")&&this.focused&&(this.lastQuery&&window.clearTimeout(this.lastQuery),this.lastQuery=window.setTimeout(()=>{this.expressions&&this.input.indexOf("@")>-1&&(!this.emails&&!this.tags||this.input.trimStart().startsWith("@"))?this.fetchExpressions():(this.completionOptions.length>0&&(this.completionOptions=[]),this.emails||this.tags||this.fetchOptions(this.input))},this.quietMillis)),this.endpoint&&t.has("fetching")&&(this.fetching||this.isPastFetchThreshold()||this.fireCustomEvent(Io.FetchComplete)),(t.has("cursorIndex")||t.has("visibleOptions"))&&this.endpoint&&!this.fetching&&this.isPastFetchThreshold()&&(this.next?this.fetchOptions(null,null,this.next):this.fetchOptions(this.query,this.page+1))}hasChanges(t){if(void 0===t)return!1;let e;void 0!==t&&(e=(t||[]).map(t=>this.getValue(t)).join(","));return e!==(this.values||[]).map(t=>t.arbitrary||this.getValue(t)).join(",")}setSelectedValue(t){if(this.staticOptions.length>0){const e=this.staticOptions.find(e=>this.getValue(e)===t);e&&this.setValues([e])}else this.checkSelectedOption()}updateInputs(){for(let t=null;t=this.hiddenInputs.pop();)t.remove();if(0===this.values.length)this.value=null;else{const t=this.getAttribute("name");t&&(this.isMultiMode||1!==this.values.length?this.inputRoot.parentElement&&this.values.forEach(e=>{const i=document.createElement("input");i.setAttribute("type","hidden"),i.setAttribute("name",t),i.setAttribute("value",this.serializeValue(e)),this.hiddenInputs.push(i),this.inputRoot.parentElement.appendChild(i)}):(this.selection=this.values[0],this.value=this.serializeValue(this.values[0]),this.internals&&this.internals.setFormValue(this.value)))}}setSelectedOption(t){this.isMultiMode?this.addValue(t):this.setValues([t]),this.isMultiMode&&this.searchable||(this.blur(),this.focused=!1),this.visibleOptions=[],this.attemptedOpen=!1,this.input="",this.next=null,this.complete=!0,this.selectedIndex=-1}isPastFetchThreshold(){return(this.visibleOptions.length>0||this.next)&&!this.complete&&(this.cursorIndex||0)>this.visibleOptions.length-20}handleOptionSelection(t){if(this.isMultiMode&&this.maxItems>0&&this.values.length>=this.maxItems)return void(this.infoText=this.maxItemsText);this.infoText="";const e=t.detail.selected;e.arbitrary&&this.allowCreate&&this.endpoint?(this.resolving=!0,ue(this.endpoint,e).then(t=>{t.status>=200&&t.status<300?(this.setSelectedOption(t.json),this.lruCache=Po(20,6e4),this.errors=[]):(this.setSelectedOption(e),setTimeout(()=>{this.errors=['There was an error creating "'+this.getNameInternal(e)+'"']},0),this.blur()),this.resolving=!1})):(this.setSelectedOption(e),this.errors=[])}handleExpressionSelection(t){const e=t.detail.selected,i=t.detail.tabbed,o=this.shadowRoot.querySelector(".searchbox"),n=this.input;Jd(this.query,o,e),this.query="",this.completionOptions=[],this.input!==n&&(i||this.emails||this.tags?this.fetchExpressions():-1===this.input.indexOf("(")&&this.addInputAsValue())}getOptionsDefault(t){return t.json.results}isCompleteDefault(t,e){const i=e.json;return!i.more&&!i.next}handleRemoveSelection(t){if(this.removeValue(t),this.visibleOptions=[],this.errors=[],this.allowCreate){const t=this.values.find(t=>t.arbitrary);t&&setTimeout(()=>{this.errors=['There was an error creating "'+this.getNameInternal(t)+'"']},0)}}createArbitraryOptionDefault(t,e){return this.expressions&&t&&this.isValidExpression(t)?{name:t,value:t,expression:!0}:this.emails&&t&&this.isValidEmail(t)||this.tags&&t?{name:t,value:t}:null}isValidEmail(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}isDuplicateValue(t){const e=t.trim().toLowerCase();return this.values.some(t=>(t.value||t.name||"").toLowerCase()===e)}isAcceptableInput(t){if(!t||this.isDuplicateValue(t))return!1;return this.expressions&&t.trimStart().startsWith("@")?this.isValidExpression(t):this.emails?this.isValidEmail(t.trim()):this.tags?t.trim().length>0:!this.expressions}looksLikeExpression(t){return/^@[a-zA-Z_(]/.test(t.trim())}isValidExpression(t){if(!this.looksLikeExpression(t))return!1;const e=("session"===this.expressions?Zd:Vd).findExpressions(t.trim());return 0!==e.length&&e.every(t=>!t.text.startsWith("@(")||t.closed)}get useExpressionInput(){return!(!this.expressions||!this.searchable)}patchEditableAsInput(t){if(this.expressionInputPatchedElement===t)return;const e=this,i=t;Object.defineProperty(i,"value",{get:()=>Oc(t),set(i){e.renderExpressionHighlight(t,i)},configurable:!0}),Object.defineProperty(i,"selectionStart",{get:()=>Pc(t),configurable:!0}),Object.defineProperty(i,"selectionEnd",{get:()=>Rc(t),configurable:!0}),i.setSelectionRange=(e,i)=>{Bc(t,e,i)},this.expressionInputPatchedElement=t}renderExpressionHighlight(t,e){if(t.textContent="",e&&e.trimStart().startsWith("@")&&!this.isDuplicateValue(e)){const i=Id(e,"session"===this.expressions?Zd:Vd);for(const e of i){const i=Nd(e),o=Rd.has(e.type);if(e.text.length>0){const n=document.createElement("span");n.textContent=e.text,n.className=o?`${i} tok-mono`:i,t.appendChild(n)}}}else if(e)if(e.trimStart().startsWith("@")){const i=document.createElement("span");i.textContent=e,i.className="tok-mono",t.appendChild(i)}else t.appendChild(document.createTextNode(e));e||t.appendChild(document.createTextNode(""))}get isMultiMode(){return this.multi||this.emails}open(){this.shadowRoot.querySelector(".select-container").click()}isOpen(){return this.visibleOptions.length>0||this.attemptedOpen&&this.focused}setOptions(t){this.staticOptions=t}setVisibleOptions(t){if(t=t.filter(t=>!!this.getNameInternal(t)&&(!this.shouldExclude||!this.shouldExclude(t))),this.input){if(this.searchable&&!this.queryParam){const e=this.input.trim().toLowerCase();t=t.filter(t=>this.isMatch(t,e))}const e=this.createArbitraryOption(this.input,t);if(e){e.arbitrary=!0;t.find(t=>this.getValue(t)===this.getValue(e))||(t.length>0&&t[0].arbitrary?t[0]=e:t.unshift(e))}}this.values.length>0&&(this.isMultiMode?t=t.filter(t=>!this.values.find(e=>this.getValue(e)===this.getValue(t))):(this.input?this.cursorIndex=0:this.cursorIndex=t.findIndex(t=>this.getValue(t)===this.getValue(this.values[0])),this.requestUpdate("cursorIndex"))),this.isMultiMode&&this.maxItems>0&&this.values.length>=this.maxItems&&(t=[],this.infoText=this.maxItemsText),this.sortFunction&&t.sort(this.sortFunction),this.visibleOptions=t,this.fireCustomEvent(Io.ContentChanged,{options:this.visibleOptions})}fetchExpressions(){const t=document.querySelector("temba-store");if(this.expressions&&t){const t=this.shadowRoot.querySelector(".searchbox"),e=tc(t,"session"===this.expressions);return this.query=e.query,this.completionOptions=e.options,this.visibleOptions=[],this.anchorPosition=e.anchorPosition,void this.fireCustomEvent(Io.FetchComplete)}}fetchOptions(t,e=0,i=null){if(this.completionOptions=[],!this.fetching){this.fetching=!0;const o=[...this.staticOptions],n=(t||"").trim().toLowerCase();if(this.tags&&n&&(o.find(t=>this.getValue(t)&&this.getValue(t).toLowerCase()===n)||o.splice(0,0,{name:t,value:t})),this.emails&&n&&this.isValidEmail(n)&&!o.find(t=>this.getValue(t)&&this.getValue(t).toLowerCase()===n)&&o.splice(0,0,{name:t,value:t}),this.endpoint){let s=this.endpoint;i?s=i:(t&&this.queryParam&&(s.indexOf("?")>-1?s+="&":s+="?",s+=this.queryParam+"="+encodeURIComponent(t)),e&&(s.indexOf("?")>-1?s+="&":s+="?",s+="page="+e));const r=this.lruCache.get(s);if(this.cache&&!this.tags&&!this.emails&&r)return 0!==e||this.next?this.setVisibleOptions([...this.visibleOptions,...r.options]):(this.cursorIndex=0,this.setVisibleOptions([...o,...r.options])),this.complete=r.complete,this.next=r.next,void(this.fetching=!1);this.searchable&&!this.queryParam?le(s).then(t=>{t=this.prepareOptions(t),!this.cache||this.tags||this.emails||(this.lruCache.set(s,{options:t,complete:!0,next:null}),this.complete=!0,this.next=null,this.setVisibleOptions([...o,...t]),this.fetching=!1)}):se(s).then(i=>{let r=this.getOptions(i).filter(t=>this.isMatch(t,n));r=this.prepareOptions(r),this.next=null;const a=i.json;a.next&&(this.next=a.next),0!==e||this.next?(r.length>0&&this.setVisibleOptions([...this.visibleOptions,...r]),this.complete=this.isComplete(r,i)):(this.cursorIndex=0,this.setVisibleOptions([...o,...r]),this.query=t,this.complete=this.isComplete(this.visibleOptions,i)),!this.cache||this.tags||this.emails||this.lruCache.set(s,{options:r,complete:this.complete,next:this.next}),this.fetching=!1,this.page=e}).catch(t=>{this.fetching=!1,console.error(t)})}else this.fetching=!1,this.setVisibleOptions(o)}}handleFocus(){this.focused||0!==this.visibleOptions.length||(this.focused=!0)}handleBlur(){setTimeout(()=>{this.focused=!1,this.attemptedOpen=!1,this.visibleOptions.length>0&&(this.input="",this.next=null,this.complete=!0,this.visibleOptions=[],this.cursorIndex=0),(this.emails||this.tags)&&(this.input="",this.completionOptions=[]),this.isMultiMode&&this.maxItems>0&&this.values.length>=this.maxItems&&(this.infoText="")},0)}handleClick(){this.selectedIndex=-1,this.requestUpdate("input")}addInputAsValue(){const t=this.shadowRoot.querySelector(".searchbox"),e={name:t.value,value:t.value,expression:!0};this.isMultiMode?this.values.find(t=>t.expression&&t.value&&e.value&&t.value.toLowerCase().trim()==e.value.toLowerCase().trim())||this.addValue(e):this.setValues([e]),this.input="",this.isMultiMode||this.blur()}handleBeforeInput(t){"insertLineBreak"!==t.inputType&&"insertParagraph"!==t.inputType||(this.useExpressionInput&&t.preventDefault(),0===this.completionOptions.length&&(this.emails||this.tags||this.expressions)&&this.isAcceptableInput(this.input)&&(t.preventDefault(),this.addInputAsValue()))}handleKeyDown(t){if("Enter"===t.key&&this.useExpressionInput&&t.preventDefault(),","===t.key&&this.emails&&!this.looksLikeExpression(this.input))return t.preventDefault(),void(this.isAcceptableInput(this.input)&&this.addInputAsValue());if("Enter"===t.key&&0===this.completionOptions.length&&(this.emails||this.tags||this.expressions)&&this.isAcceptableInput(this.input))return t.preventDefault(),void this.addInputAsValue();if(("Enter"===t.key||"ArrowDown"===t.key||"n"===t.key&&t.ctrlKey)&&0===this.visibleOptions.length&&0===this.completionOptions.length&&!this.input)return this.attemptedOpen=!0,void this.requestUpdate("input");if(this.isMultiMode&&"Backspace"===t.key&&!this.input){if(this.visibleOptions.length>0)return void(this.visibleOptions=[]);-1===this.selectedIndex?(this.selectedIndex=this.values.length-1,this.visibleOptions=[]):(this.popValue(),this.selectedIndex=-1)}else this.selectedIndex=-1}getStaticOptions(){return this.staticOptions}handleInput(t){const e=t.currentTarget;if(this.useExpressionInput){const t=Oc(e),i=Pc(e);this.input=t,this.renderExpressionHighlight(e,t);try{Bc(e,i,i)}catch(t){}}else this.input=e.value}handleCancel(){this.visibleOptions=[],this.attemptedOpen=!1}handleCursorChanged(t){this.cursorIndex=t.detail.index}getSearchboxElement(){return this.shadowRoot.querySelector(".searchbox")}isExpressionInputTarget(t){return t instanceof HTMLElement&&t.classList.contains("expression-input")}handleContainerClick(t){if(this.disabled)return t.stopPropagation(),void t.preventDefault();this.focused=!0;if("INPUT"!==t.target.tagName&&!this.isExpressionInputTarget(t.target)){const t=this.getSearchboxElement();if(t)return t.click(),void t.focus();this.isOpen()?(this.visibleOptions=[],this.attemptedOpen=!1):(this.attemptedOpen=!0,this.requestUpdate("input"),this.requestUpdate())}}getEventHandlers(){return[{event:Io.Canceled,method:this.handleCancel},{event:Io.CursorChanged,method:this.handleCursorChanged},{event:"blur",method:this.handleBlur},{event:"focus",method:this.handleFocus}]}handleArrowClick(t){this.disabled||this.isOpen()&&(t.preventDefault(),t.stopPropagation(),this.blur())}renderHighlightedName(t){const e=this.getNameInternal(t);if(this.expressions&&e.startsWith("@")){const t=Id(e,"session"===this.expressions?Zd:Vd);return W`${t.map(t=>{const e=Nd(t),i=Rd.has(t.type);return W`<span class="${i?`${e} tok-mono`:e}"
1367
1398
  >${t.text}</span
1368
1399
  >`})}`}return e}renderOptionDefault(t){if(!t)return null;const e=t.icon;return W`
1369
1400
  <div
@@ -1559,12 +1590,12 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1559
1590
  @temba-canceled=${()=>{}}
1560
1591
  .anchorTo=${this.allowAnchor?this.anchorExpressions:null}
1561
1592
  .options=${this.completionOptions}
1562
- .renderOption=${Bd}
1593
+ .renderOption=${Yd}
1563
1594
  ?visible=${this.completionOptions.length>0}
1564
1595
  >
1565
1596
  ${this.currentFunction?W`
1566
1597
  <div class="current-fn">
1567
- ${Bd(this.currentFunction,!0)}
1598
+ ${Yd(this.currentFunction,!0)}
1568
1599
  </div>
1569
1600
  `:null}
1570
1601
  ${this.completionOptions.length>0?W`<div class="footer">
@@ -1574,7 +1605,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1574
1605
  ${a?W`<div class="enter-hint">
1575
1606
  <span style="position:relative;top:3px">↵</span> ${ol("to add")}
1576
1607
  </div>`:null}
1577
- `}render(){return this.renderField()}}t([mt({type:Object})],gc.prototype,"inputStyle",void 0),t([mt({type:Boolean})],gc.prototype,"multi",void 0),t([mt({type:Boolean})],gc.prototype,"searchOnFocus",void 0),t([mt({type:String})],gc.prototype,"placeholder",void 0),t([mt()],gc.prototype,"name",void 0),t([mt()],gc.prototype,"endpoint",void 0),t([mt({type:Boolean})],gc.prototype,"allowCreate",void 0),t([mt({type:String})],gc.prototype,"nameKey",void 0),t([mt({type:String})],gc.prototype,"valueKey",void 0),t([mt({type:Number})],gc.prototype,"maxItems",void 0),t([mt({type:String})],gc.prototype,"maxItemsText",void 0),t([mt({attribute:!1})],gc.prototype,"currentFunction",void 0),t([mt({type:String})],gc.prototype,"queryParam",void 0),t([mt({type:String})],gc.prototype,"input",void 0),t([mt({type:Array})],gc.prototype,"visibleOptions",void 0),t([mt({type:Array})],gc.prototype,"completionOptions",void 0),t([mt({type:Number})],gc.prototype,"quietMillis",void 0),t([mt({type:Boolean})],gc.prototype,"fetching",void 0),t([mt({type:Boolean})],gc.prototype,"resolving",void 0),t([mt({type:Boolean})],gc.prototype,"searchable",void 0),t([mt({type:String})],gc.prototype,"expressions",void 0),t([mt({type:Boolean})],gc.prototype,"cache",void 0),t([mt({type:String})],gc.prototype,"cacheKey",void 0),t([mt({type:Boolean})],gc.prototype,"focused",void 0),t([mt({type:Boolean})],gc.prototype,"disabled",void 0),t([gt()],gc.prototype,"attemptedOpen",void 0),t([mt({attribute:!1})],gc.prototype,"selectedIndex",void 0),t([mt({type:Number})],gc.prototype,"cursorIndex",void 0),t([mt({type:Object})],gc.prototype,"anchorPosition",void 0),t([mt({type:Boolean})],gc.prototype,"tags",void 0),t([mt({type:Boolean})],gc.prototype,"emails",void 0),t([mt({type:Boolean,attribute:"space_select"})],gc.prototype,"spaceSelect",void 0),t([mt({type:Boolean})],gc.prototype,"jsonValue",void 0),t([mt({type:Boolean})],gc.prototype,"hideErrors",void 0),t([mt({type:Boolean})],gc.prototype,"clearable",void 0),t([mt({type:Boolean})],gc.prototype,"sorted",void 0),t([mt({type:String})],gc.prototype,"flavor",void 0),t([mt({type:String,attribute:"info_text"})],gc.prototype,"infoText",void 0),t([mt({type:Array})],gc.prototype,"values",null),t([mt({type:Object})],gc.prototype,"selection",void 0),t([mt({attribute:!1})],gc.prototype,"getName",void 0),t([mt({attribute:!1})],gc.prototype,"isMatch",void 0),t([mt({attribute:!1})],gc.prototype,"getValue",void 0),t([mt({type:Number,attribute:"option-width"})],gc.prototype,"optionWidth",void 0),t([mt({type:Number,attribute:"option-min-width"})],gc.prototype,"optionMinWidth",void 0),t([mt({type:Boolean,attribute:"anchor-right"})],gc.prototype,"anchorRight",void 0),t([mt({attribute:!1})],gc.prototype,"shouldExclude",void 0),t([mt({attribute:!1})],gc.prototype,"sortFunction",void 0),t([mt({attribute:!1})],gc.prototype,"renderOption",void 0),t([mt({attribute:!1})],gc.prototype,"renderOptionName",void 0),t([mt({attribute:!1})],gc.prototype,"renderOptionDetail",void 0),t([mt({attribute:!1})],gc.prototype,"renderSelectedItem",void 0),t([mt({attribute:!1})],gc.prototype,"createArbitraryOption",void 0),t([mt({attribute:!1})],gc.prototype,"getOptions",void 0),t([mt({attribute:!1})],gc.prototype,"prepareOptions",void 0),t([mt({attribute:!1})],gc.prototype,"isComplete",void 0),t([mt({type:Array,attribute:"options"})],gc.prototype,"staticOptions",void 0),t([mt({type:Boolean})],gc.prototype,"allowAnchor",void 0),t([mt({type:String})],gc.prototype,"draggingId",void 0);class fc extends _o{constructor(){super(...arguments),this.submitOnEnter=!1,this.anchorPosition={left:0,top:0},this.placeholder="",this.options=[],this.name="",this.autogrow=!1}static get styles(){return a`
1608
+ `}render(){return this.renderField()}}t([mt({type:Object})],Fc.prototype,"inputStyle",void 0),t([mt({type:Boolean})],Fc.prototype,"multi",void 0),t([mt({type:Boolean})],Fc.prototype,"searchOnFocus",void 0),t([mt({type:String})],Fc.prototype,"placeholder",void 0),t([mt()],Fc.prototype,"name",void 0),t([mt()],Fc.prototype,"endpoint",void 0),t([mt({type:Boolean})],Fc.prototype,"allowCreate",void 0),t([mt({type:String})],Fc.prototype,"nameKey",void 0),t([mt({type:String})],Fc.prototype,"valueKey",void 0),t([mt({type:Number})],Fc.prototype,"maxItems",void 0),t([mt({type:String})],Fc.prototype,"maxItemsText",void 0),t([mt({attribute:!1})],Fc.prototype,"currentFunction",void 0),t([mt({type:String})],Fc.prototype,"queryParam",void 0),t([mt({type:String})],Fc.prototype,"input",void 0),t([mt({type:Array})],Fc.prototype,"visibleOptions",void 0),t([mt({type:Array})],Fc.prototype,"completionOptions",void 0),t([mt({type:Number})],Fc.prototype,"quietMillis",void 0),t([mt({type:Boolean})],Fc.prototype,"fetching",void 0),t([mt({type:Boolean})],Fc.prototype,"resolving",void 0),t([mt({type:Boolean})],Fc.prototype,"searchable",void 0),t([mt({type:String})],Fc.prototype,"expressions",void 0),t([mt({type:Boolean})],Fc.prototype,"cache",void 0),t([mt({type:String})],Fc.prototype,"cacheKey",void 0),t([mt({type:Boolean})],Fc.prototype,"focused",void 0),t([mt({type:Boolean})],Fc.prototype,"disabled",void 0),t([gt()],Fc.prototype,"attemptedOpen",void 0),t([mt({attribute:!1})],Fc.prototype,"selectedIndex",void 0),t([mt({type:Number})],Fc.prototype,"cursorIndex",void 0),t([mt({type:Object})],Fc.prototype,"anchorPosition",void 0),t([mt({type:Boolean})],Fc.prototype,"tags",void 0),t([mt({type:Boolean})],Fc.prototype,"emails",void 0),t([mt({type:Boolean,attribute:"space_select"})],Fc.prototype,"spaceSelect",void 0),t([mt({type:Boolean})],Fc.prototype,"jsonValue",void 0),t([mt({type:Boolean})],Fc.prototype,"hideErrors",void 0),t([mt({type:Boolean})],Fc.prototype,"clearable",void 0),t([mt({type:Boolean})],Fc.prototype,"sorted",void 0),t([mt({type:String})],Fc.prototype,"flavor",void 0),t([mt({type:String,attribute:"info_text"})],Fc.prototype,"infoText",void 0),t([mt({type:Array})],Fc.prototype,"values",null),t([mt({type:Object})],Fc.prototype,"selection",void 0),t([mt({attribute:!1})],Fc.prototype,"getName",void 0),t([mt({attribute:!1})],Fc.prototype,"isMatch",void 0),t([mt({attribute:!1})],Fc.prototype,"getValue",void 0),t([mt({type:Number,attribute:"option-width"})],Fc.prototype,"optionWidth",void 0),t([mt({type:Number,attribute:"option-min-width"})],Fc.prototype,"optionMinWidth",void 0),t([mt({type:Boolean,attribute:"anchor-right"})],Fc.prototype,"anchorRight",void 0),t([mt({attribute:!1})],Fc.prototype,"shouldExclude",void 0),t([mt({attribute:!1})],Fc.prototype,"sortFunction",void 0),t([mt({attribute:!1})],Fc.prototype,"renderOption",void 0),t([mt({attribute:!1})],Fc.prototype,"renderOptionName",void 0),t([mt({attribute:!1})],Fc.prototype,"renderOptionDetail",void 0),t([mt({attribute:!1})],Fc.prototype,"renderSelectedItem",void 0),t([mt({attribute:!1})],Fc.prototype,"createArbitraryOption",void 0),t([mt({attribute:!1})],Fc.prototype,"getOptions",void 0),t([mt({attribute:!1})],Fc.prototype,"prepareOptions",void 0),t([mt({attribute:!1})],Fc.prototype,"isComplete",void 0),t([mt({type:Array,attribute:"options"})],Fc.prototype,"staticOptions",void 0),t([mt({type:Boolean})],Fc.prototype,"allowAnchor",void 0),t([mt({type:String})],Fc.prototype,"draggingId",void 0);class qc extends _o{constructor(){super(...arguments),this.submitOnEnter=!1,this.anchorPosition={left:0,top:0},this.placeholder="",this.options=[],this.name="",this.autogrow=!1}static get styles(){return a`
1578
1609
  ${super.styles}
1579
1610
  :host {
1580
1611
  display: block;
@@ -1629,7 +1660,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1629
1660
  padding: 1px 5px;
1630
1661
  border-radius: var(--curvature);
1631
1662
  }
1632
- `}firstUpdated(){this.textInputElement=this.shadowRoot.querySelector("temba-textinput"),this.anchorElement=this.shadowRoot.querySelector("#anchor"),this.hiddenElement=document.createElement("input"),this.hiddenElement.setAttribute("type","hidden"),this.hiddenElement.setAttribute("name",this.getAttribute("name")),this.hiddenElement.setAttribute("value",this.getAttribute("value")||""),this.appendChild(this.hiddenElement)}handleKeyUp(t){if(this.disableCompletion&&this.options&&this.options.length>0){if("ArrowUp"===t.key||"ArrowDown"===t.key)return;if(t.ctrlKey&&("n"===t.key||"p"===t.key))return;if("Enter"===t.key||"Escape"===t.key||"Tab"===t.key||t.key.startsWith("Control"))return t.stopPropagation(),void t.preventDefault();this.executeQuery(t.currentTarget)}}hasVisibleOptions(){return this.options.length>0}executeQuery(t){if(this.disableCompletion)return;if(!t.inputElement)return;const e=Wd(t.inputElement,this.session);this.query=e.query,this.options=e.options,this.anchorPosition=e.anchorPosition}handleClick(t){this.executeQuery(t.currentTarget)}updated(t){super.updated(t),t.has("value")&&this.hiddenElement.setAttribute("value",this.value)}handleInput(t){const e=t.currentTarget;this.executeQuery(e),this.value=e.inputElement.value,this.fireEvent("change")}handleOptionCanceled(){window.setTimeout(()=>{this.options=[],this.query=""},100)}handleOptionSelection(t){const e=t.detail.selected,i=t.detail.tabbed;Hd(this.query,this.textInputElement.inputElement,e),this.query="",this.options=[],i&&this.executeQuery(this.textInputElement)}getTextInput(){return this.textInputElement}click(){super.click();const t=this.shadowRoot.querySelector("temba-textinput");t&&t.click()}focus(){super.focus();const t=this.shadowRoot.querySelector("temba-textinput");t&&t.focus()}renderWidget(){const t=this.anchorPosition?{top:`${this.anchorPosition.top}px`,left:`${this.anchorPosition.left}px`}:{},e=this.options&&this.options.length>0;return W`
1663
+ `}firstUpdated(){this.textInputElement=this.shadowRoot.querySelector("temba-textinput"),this.anchorElement=this.shadowRoot.querySelector("#anchor"),this.hiddenElement=document.createElement("input"),this.hiddenElement.setAttribute("type","hidden"),this.hiddenElement.setAttribute("name",this.getAttribute("name")),this.hiddenElement.setAttribute("value",this.getAttribute("value")||""),this.appendChild(this.hiddenElement)}handleKeyUp(t){if(this.disableCompletion&&this.options&&this.options.length>0){if("ArrowUp"===t.key||"ArrowDown"===t.key)return;if(t.ctrlKey&&("n"===t.key||"p"===t.key))return;if("Enter"===t.key||"Escape"===t.key||"Tab"===t.key||t.key.startsWith("Control"))return t.stopPropagation(),void t.preventDefault();this.executeQuery(t.currentTarget)}}hasVisibleOptions(){return this.options.length>0}executeQuery(t){if(this.disableCompletion)return;if(!t.inputElement)return;const e=tc(t.inputElement,this.session);this.query=e.query,this.options=e.options,this.anchorPosition=e.anchorPosition}handleClick(t){this.executeQuery(t.currentTarget)}updated(t){super.updated(t),t.has("value")&&this.hiddenElement.setAttribute("value",this.value)}handleInput(t){const e=t.currentTarget;this.executeQuery(e),this.value=e.inputElement.value,this.fireEvent("change")}handleOptionCanceled(){window.setTimeout(()=>{this.options=[],this.query=""},100)}handleOptionSelection(t){const e=t.detail.selected,i=t.detail.tabbed;Jd(this.query,this.textInputElement.inputElement,e),this.query="",this.options=[],i&&this.executeQuery(this.textInputElement)}getTextInput(){return this.textInputElement}click(){super.click();const t=this.shadowRoot.querySelector("temba-textinput");t&&t.click()}focus(){super.focus();const t=this.shadowRoot.querySelector("temba-textinput");t&&t.focus()}renderWidget(){const t=this.anchorPosition?{top:`${this.anchorPosition.top}px`,left:`${this.anchorPosition.left}px`}:{},e=this.options&&this.options.length>0;return W`
1633
1664
  <div class="comp-container">
1634
1665
  <div id="anchor" style=${$o(t)}></div>
1635
1666
  <temba-textinput
@@ -1652,14 +1683,14 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1652
1683
  <temba-options
1653
1684
  @temba-selection=${this.handleOptionSelection}
1654
1685
  @temba-canceled=${this.handleOptionCanceled}
1655
- .renderOption=${Bd}
1686
+ .renderOption=${Yd}
1656
1687
  .anchorTo=${this.anchorElement}
1657
1688
  .options=${this.options}
1658
1689
  ?visible=${e}
1659
1690
  >
1660
1691
  ${this.currentFunction?W`
1661
1692
  <div class="current-fn">
1662
- ${Bd(this.currentFunction,!0)}
1693
+ ${Yd(this.currentFunction,!0)}
1663
1694
  </div>
1664
1695
  `:null}
1665
1696
  <div class="footer" style="${e?null:"display:none"}">
@@ -1667,7 +1698,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1667
1698
  </div>
1668
1699
  </temba-options>
1669
1700
  </div>
1670
- `}render(){return this.renderField()}}t([mt({type:Number})],fc.prototype,"maxLength",void 0),t([mt({type:Boolean})],fc.prototype,"session",void 0),t([mt({type:Boolean})],fc.prototype,"submitOnEnter",void 0),t([mt({type:Object})],fc.prototype,"anchorPosition",void 0),t([mt({attribute:!1})],fc.prototype,"currentFunction",void 0),t([mt({type:String})],fc.prototype,"placeholder",void 0),t([mt({type:Array})],fc.prototype,"options",void 0),t([mt({type:String})],fc.prototype,"name",void 0),t([mt({type:Boolean})],fc.prototype,"textarea",void 0),t([mt({type:Boolean})],fc.prototype,"gsm",void 0),t([mt({type:Boolean})],fc.prototype,"disableCompletion",void 0),t([mt({type:String})],fc.prototype,"counter",void 0),t([mt({type:Boolean})],fc.prototype,"autogrow",void 0),t([mt({type:Number})],fc.prototype,"minHeight",void 0);class vc extends Be{handleResize(){this.requestUpdate()}getEventHandlers(){return[{event:"resize",method:fe(this.handleResize,50),isWindow:!0}]}}var bc;!function(t){t.PRIMARY="primary",t.SECONDARY="secondary",t.DESTRUCTIVE="destructive"}(bc||(bc={}));class yc extends vc{static get widths(){return{small:"400px",medium:"600px",large:"655px",xlarge:"800px"}}static get styles(){return a`
1701
+ `}render(){return this.renderField()}}t([mt({type:Number})],qc.prototype,"maxLength",void 0),t([mt({type:Boolean})],qc.prototype,"session",void 0),t([mt({type:Boolean})],qc.prototype,"submitOnEnter",void 0),t([mt({type:Object})],qc.prototype,"anchorPosition",void 0),t([mt({attribute:!1})],qc.prototype,"currentFunction",void 0),t([mt({type:String})],qc.prototype,"placeholder",void 0),t([mt({type:Array})],qc.prototype,"options",void 0),t([mt({type:String})],qc.prototype,"name",void 0),t([mt({type:Boolean})],qc.prototype,"textarea",void 0),t([mt({type:Boolean})],qc.prototype,"gsm",void 0),t([mt({type:Boolean})],qc.prototype,"disableCompletion",void 0),t([mt({type:String})],qc.prototype,"counter",void 0),t([mt({type:Boolean})],qc.prototype,"autogrow",void 0),t([mt({type:Number})],qc.prototype,"minHeight",void 0);class Uc extends Be{handleResize(){this.requestUpdate()}getEventHandlers(){return[{event:"resize",method:fe(this.handleResize,50),isWindow:!0}]}}var jc;!function(t){t.PRIMARY="primary",t.SECONDARY="secondary",t.DESTRUCTIVE="destructive"}(jc||(jc={}));class Hc extends Uc{static get widths(){return{small:"400px",medium:"600px",large:"655px",xlarge:"800px"}}static get styles(){return a`
1671
1702
  :host {
1672
1703
  position: absolute;
1673
1704
  z-index: 10000;
@@ -1837,7 +1868,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1837
1868
  flex-grow: 1;
1838
1869
  text-align: right;
1839
1870
  }
1840
- `}constructor(){super(),this.size="medium",this.primaryButtonName="Ok",this.cancelButtonName="Cancel",this.width=null,this.submittingName="Saving",this.buttons=[],this.originX=null,this.originY=null,this.scrollOffset=0}updateButtons(){this.buttons=[],this.cancelButtonName&&this.buttons.push({name:this.cancelButtonName,type:bc.SECONDARY,closes:!0}),this.primaryButtonName&&this.buttons.push({name:this.primaryButtonName,type:bc.PRIMARY})}willUpdate(t){super.willUpdate(t),(t.has("cancelButtonName")||t.has("primaryButtonName"))&&this.updateButtons(),t.has("open")&&this.open&&null==this.originX&&null==this.originY&&(this.animationEnd=!0)}updated(t){if(super.updated(t),t.has("open")){const e=document.querySelector("body");if(this.open){if(null!=this.originX&&null!=this.originY){const t=this.originX,e=this.originY;this.originX=null,this.originY=null,requestAnimationFrame(()=>{var i;const o=null===(i=this.shadowRoot)||void 0===i?void 0:i.querySelector(".dialog-container");if(o){const i=o.getBoundingClientRect(),n=i.left+i.width/2,s=i.top+i.height/2,r=t-n,a=e-s;o.style.transition="none",o.style.transform=`translate(${r}px, ${a}px) scale(0.2)`,o.getBoundingClientRect(),o.style.transition="",this.animationEnd=!0,window.setTimeout(()=>{this.ready=!0,this.animationEnd=!1,o.style.transform=""},400)}})}else window.setTimeout(()=>{this.ready=!0,this.animationEnd=!1},400);this.scrollOffset=-document.documentElement.scrollTop,e.style.position="fixed",e.style.overflowY="scroll",e.style.top=this.scrollOffset+"px",e.style.width="100%",e.style.overflowY="hidden"}else e.style.position="",e.style.overflowY="",e.style.width="",e.style.marginRight="",e.style.paddingRight="0px",window.scrollTo(0,-1*parseInt(this.scrollOffset||"0"));this.open&&!t.get("open")?this.shadowRoot.querySelectorAll("temba-button").forEach(t=>{t&&(t.submitting=!1)}):window.setTimeout(()=>{this.ready=!1},400)}}focusFirstInput(){window.setTimeout(()=>{let t=this.querySelector('temba-textinput, temba-completion, input[type="text"], textarea');t&&(t=t.textInputElement||t.inputElement||t,t.readOnly||(t.focus(),t.click()))},100)}handleClick(t){const e=t.currentTarget;if(!e.disabled){let t={};e.index>=0&&e.index<this.buttons.length&&(t=this.buttons[e.index]),this.fireCustomEvent(Io.ButtonClicked,{button:e,detail:t}),(e.name===this.cancelButtonName||t&&t.closes)&&(this.open=!1)}}getDocumentHeight(){const t=document.body,e=document.documentElement;return Math.max(t.scrollHeight,t.offsetHeight,e.clientHeight,e.scrollHeight,e.offsetHeight)}clickCancel(){const t=this.getCancelButton();t&&t.click()}getCancelButton(){return this.shadowRoot.querySelector(`temba-button[name='${this.cancelButtonName}']`)}getPrimaryButton(){return this.shadowRoot.querySelector("temba-button[primary]")}handleKeyUp(t){"Escape"===t.key&&this.clickCancel()}handleClickMask(t){if(this.hideOnClick){const e=t.target.id;"dialog-mask"!==e&&"dialog-bg"!==e||(this.fireCustomEvent(Io.DialogHidden),this.clickCancel())}}show(){this.open=!0}hide(){this.open=!1}render(){const t={width:this.width};this.width||(t.width=yc.widths[this.size]),this.isMobile()&&(t.width="100%",t.height="100%",delete t.maxWidth);const e=this.header?W`
1871
+ `}constructor(){super(),this.size="medium",this.primaryButtonName="Ok",this.cancelButtonName="Cancel",this.width=null,this.submittingName="Saving",this.buttons=[],this.originX=null,this.originY=null,this.scrollOffset=0}updateButtons(){this.buttons=[],this.cancelButtonName&&this.buttons.push({name:this.cancelButtonName,type:jc.SECONDARY,closes:!0}),this.primaryButtonName&&this.buttons.push({name:this.primaryButtonName,type:jc.PRIMARY})}willUpdate(t){super.willUpdate(t),(t.has("cancelButtonName")||t.has("primaryButtonName"))&&this.updateButtons(),t.has("open")&&this.open&&null==this.originX&&null==this.originY&&(this.animationEnd=!0)}updated(t){if(super.updated(t),t.has("open")){const e=document.querySelector("body");if(this.open){if(null!=this.originX&&null!=this.originY){const t=this.originX,e=this.originY;this.originX=null,this.originY=null,requestAnimationFrame(()=>{var i;const o=null===(i=this.shadowRoot)||void 0===i?void 0:i.querySelector(".dialog-container");if(o){const i=o.getBoundingClientRect(),n=i.left+i.width/2,s=i.top+i.height/2,r=t-n,a=e-s;o.style.transition="none",o.style.transform=`translate(${r}px, ${a}px) scale(0.2)`,o.getBoundingClientRect(),o.style.transition="",this.animationEnd=!0,window.setTimeout(()=>{this.ready=!0,this.animationEnd=!1,o.style.transform=""},400)}})}else window.setTimeout(()=>{this.ready=!0,this.animationEnd=!1},400);this.scrollOffset=-document.documentElement.scrollTop,e.style.position="fixed",e.style.overflowY="scroll",e.style.top=this.scrollOffset+"px",e.style.width="100%",e.style.overflowY="hidden"}else e.style.position="",e.style.overflowY="",e.style.width="",e.style.marginRight="",e.style.paddingRight="0px",window.scrollTo(0,-1*parseInt(this.scrollOffset||"0"));this.open&&!t.get("open")?this.shadowRoot.querySelectorAll("temba-button").forEach(t=>{t&&(t.submitting=!1)}):window.setTimeout(()=>{this.ready=!1},400)}}focusFirstInput(){window.setTimeout(()=>{let t=this.querySelector('temba-textinput, temba-completion, input[type="text"], textarea');t&&(t=t.textInputElement||t.inputElement||t,t.readOnly||(t.focus(),t.click()))},100)}handleClick(t){const e=t.currentTarget;if(!e.disabled){let t={};e.index>=0&&e.index<this.buttons.length&&(t=this.buttons[e.index]),this.fireCustomEvent(Io.ButtonClicked,{button:e,detail:t}),(e.name===this.cancelButtonName||t&&t.closes)&&(this.open=!1)}}getDocumentHeight(){const t=document.body,e=document.documentElement;return Math.max(t.scrollHeight,t.offsetHeight,e.clientHeight,e.scrollHeight,e.offsetHeight)}clickCancel(){const t=this.getCancelButton();t&&t.click()}getCancelButton(){return this.shadowRoot.querySelector(`temba-button[name='${this.cancelButtonName}']`)}getPrimaryButton(){return this.shadowRoot.querySelector("temba-button[primary]")}handleKeyUp(t){"Escape"===t.key&&this.clickCancel()}handleClickMask(t){if(this.hideOnClick){const e=t.target.id;"dialog-mask"!==e&&"dialog-bg"!==e||(this.fireCustomEvent(Io.DialogHidden),this.clickCancel())}}show(){this.open=!0}hide(){this.open=!1}render(){const t={width:this.width};this.width||(t.width=Hc.widths[this.size]),this.isMobile()&&(t.width="100%",t.height="100%",delete t.maxWidth);const e=this.header?W`
1841
1872
  <div class="dialog-header">
1842
1873
  <div class="header-text">
1843
1874
  <div class="title">${this.header}</div>
@@ -1893,7 +1924,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1893
1924
  </div>
1894
1925
  </div>
1895
1926
  </div>
1896
- `}}t([mt({type:Boolean})],yc.prototype,"open",void 0),t([mt()],yc.prototype,"header",void 0),t([mt()],yc.prototype,"body",void 0),t([mt({type:Boolean})],yc.prototype,"submitting",void 0),t([mt({type:Boolean})],yc.prototype,"destructive",void 0),t([mt({type:Boolean})],yc.prototype,"disabled",void 0),t([mt({type:Boolean})],yc.prototype,"loading",void 0),t([mt({type:Boolean})],yc.prototype,"hideOnClick",void 0),t([mt({type:Boolean})],yc.prototype,"noFocus",void 0),t([mt()],yc.prototype,"size",void 0),t([mt({type:String})],yc.prototype,"primaryButtonName",void 0),t([mt({type:String})],yc.prototype,"cancelButtonName",void 0),t([mt({type:String})],yc.prototype,"width",void 0),t([mt()],yc.prototype,"submittingName",void 0),t([mt()],yc.prototype,"animationEnd",void 0),t([mt()],yc.prototype,"ready",void 0),t([mt({type:Array})],yc.prototype,"buttons",void 0),t([mt({attribute:!1})],yc.prototype,"onButtonClicked",void 0),t([mt({type:Number})],yc.prototype,"originX",void 0),t([mt({type:Number})],yc.prototype,"originY",void 0);class xc extends Be{constructor(){super(...arguments),this.header="",this.open=!1,this.fetching=!1,this.headers={},this.body=this.getLoading(),this.disabled=!1,this.buttons=[],this.wizardStep=0,this.wizardStepCount=0,this.suspendSubmit=!1,this.originX=null,this.originY=null}static get styles(){return a`
1927
+ `}}t([mt({type:Boolean})],Hc.prototype,"open",void 0),t([mt()],Hc.prototype,"header",void 0),t([mt()],Hc.prototype,"body",void 0),t([mt({type:Boolean})],Hc.prototype,"submitting",void 0),t([mt({type:Boolean})],Hc.prototype,"destructive",void 0),t([mt({type:Boolean})],Hc.prototype,"disabled",void 0),t([mt({type:Boolean})],Hc.prototype,"loading",void 0),t([mt({type:Boolean})],Hc.prototype,"hideOnClick",void 0),t([mt({type:Boolean})],Hc.prototype,"noFocus",void 0),t([mt()],Hc.prototype,"size",void 0),t([mt({type:String})],Hc.prototype,"primaryButtonName",void 0),t([mt({type:String})],Hc.prototype,"cancelButtonName",void 0),t([mt({type:String})],Hc.prototype,"width",void 0),t([mt()],Hc.prototype,"submittingName",void 0),t([mt()],Hc.prototype,"animationEnd",void 0),t([mt()],Hc.prototype,"ready",void 0),t([mt({type:Array})],Hc.prototype,"buttons",void 0),t([mt({attribute:!1})],Hc.prototype,"onButtonClicked",void 0),t([mt({type:Number})],Hc.prototype,"originX",void 0),t([mt({type:Number})],Hc.prototype,"originY",void 0);class Wc extends Be{constructor(){super(...arguments),this.header="",this.open=!1,this.fetching=!1,this.headers={},this.body=this.getLoading(),this.disabled=!1,this.buttons=[],this.wizardStep=0,this.wizardStepCount=0,this.suspendSubmit=!1,this.originX=null,this.originY=null}static get styles(){return a`
1897
1928
  fieldset {
1898
1929
  border: none;
1899
1930
  margin: 0;
@@ -1983,7 +2014,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1983
2014
  flex-direction: row;
1984
2015
  margin-left: 0.6em;
1985
2016
  }
1986
- `}handleSlotClicked(t){const e=t.currentTarget;if(e){const t=e.getBoundingClientRect();this.originX=t.left+t.width/2,this.originY=t.top}this.open=!0}willUpdate(t){super.willUpdate(t),t.has("open")&&(this.open?(this.fetching=!0,this.body=this.getLoading()):void 0!==t.get("open")&&(this.body="",this.originX=null,this.originY=null))}updated(t){if(super.updated(t),t.has("open"))if(this.open)this.fetchForm();else if(void 0!==t.get("open")){const t=this.shadowRoot.querySelector(".scripts");if(t)for(const e of Array.from(t.children))e.remove()}if(t.has("body")&&this.open&&this.body&&!this.fetching){this.shadowRoot.querySelector("temba-dialog").focusFirstInput()}}getLoading(){return W`<temba-loading units="6" size="8"></temba-loading>`}updatePrimaryButton(){const t=this.shadowRoot.querySelector("#wizard-form");t&&(this.wizardStep=parseInt(t.dataset.step),this.wizardStepCount=parseInt(t.dataset.steps)),this.noSubmit||this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("input[type='submit'],button[type='submit']");this.buttons=t?[{type:bc.SECONDARY,name:"Cancel",closes:!0},{type:bc.PRIMARY,name:t.value}]:[{type:bc.SECONDARY,name:"Ok",closes:!0}],this.submitting=!1})}setBody(t){const e=this.shadowRoot.querySelector(".scripts");for(const t of e.children)t.remove();const i=this.ownerDocument.createElement("div");i.innerHTML=t;const o=i.getElementsByTagName("script"),n=[];for(let t=o.length-1;t>=0;t--){const e=this.ownerDocument.createElement("script"),i=o[t].innerText;o[t].src&&-1===o[t].src.indexOf("web-dev-server")?(e.src=o[t].src,e.type="text/javascript",e.async=!0,e.onload=function(){},n.push(e)):i&&(e.appendChild(this.ownerDocument.createTextNode(i)),n.push(e)),o[t].remove()}const s=!!i.querySelector(".success-script");return s||(this.body=We(i.innerHTML)),this.updateComplete.then(()=>{for(const t of n)e.appendChild(t)}),!s}getHeaders(){const t=this.headers;return t["X-PJAX"]=1,t}fetchForm(){se(this.endpoint,null,this.getHeaders()).then(t=>{if(0==t.body.indexOf("<!DOCTYPE HTML>"))this.open=!1,document.location=t.url;else{const e=t.headers.get("X-Temba-Header-Bg"),i=t.headers.get("X-Temba-Header-Text");e?this.style.setProperty("--header-bg",e):this.style.removeProperty("--header-bg"),i?this.style.setProperty("--header-text",i):this.style.removeProperty("--header-text"),this.setBody(t.body),this.fetching=!1,this.updateComplete.then(()=>{this.updatePrimaryButton(),this.fireCustomEvent(Io.Loaded,{body:this.getBody()})})}}).catch(t=>{this.fetching=!1,this.open=!1,this.fireCustomEvent(Io.Error,{error:t})})}submit(t={}){this.submitting=!0;const e=this.shadowRoot.querySelector("form");let i=e?function(t){const e=[];for(let i=0;i<t.elements.length;i++){const o=t.elements[i];if(o.name&&!o.disabled&&"file"!==o.type&&"reset"!==o.type&&"submit"!==o.type&&"button"!==o.type)if("select-multiple"===o.type)for(let t=0;t<o.options.length;t++)o.options[t].selected&&o.options[t].value&&e.push(encodeURIComponent(o.name)+"="+encodeURIComponent(o.options[t].value));else if("checkbox"!==o.type&&"radio"!==o.type||o.checked){let t=o.value;!t&&o.checked&&(t="1"),t&&e.push(encodeURIComponent(o.name)+"="+encodeURIComponent(t))}}return e.join("&")}(e):"";t&&Object.keys(t).forEach(e=>{i+=(i.length>1?"&":"")+encodeURIComponent(e)+"="+encodeURIComponent(t[e])}),he(this.endpoint,i,this.getHeaders(),"application/x-www-form-urlencoded").then(t=>{window.setTimeout(()=>{let e=t.headers.get("X-Temba-Success");if(!e&&t.url&&-1===t.url.indexOf(this.endpoint)&&(e=t.url),e)"hide"===e?this.updateComplete.then(()=>{this.open=!1,this.fireCustomEvent(Io.Submitted)}):(this.fireCustomEvent(Io.Redirected,{url:e}),this.open=!1);else{if(0==t.body.indexOf("<!DOCTYPE HTML>"))return this.open=!1,void(document.location=t.url);this.setBody(t.body)&&this.updateComplete.then(()=>{this.updatePrimaryButton()})}},1e3)}).catch(t=>{console.error(t)})}handleDialogClick(t){const e=t.detail.button,i=t.detail.detail;e.disabled||e.submitting||(e.primary||e.destructive)&&(this.suspendSubmit||this.submit()),i.closes&&(this.open=!1,this.fetching=!1,this.cancelName=void 0)}handleDialogHidden(){this.open=!1,this.fetching=!1}isDestructive(){return this.endpoint&&(this.endpoint.indexOf("delete")>-1||this.endpoint.indexOf("interrupt")>-1)}handleGotoStep(t){const e=t.target.dataset.gotoStep;e&&this.submit({wizard_goto_step:e})}getBody(){return this.shadowRoot.querySelector(".modax-body")}render(){const t=[],e=this.shadowRoot.querySelector("#wizard-form");if(e){const i=(e.getAttribute("data-completed")||"").split(",").filter(t=>t.length>0);for(let e=0;e<this.wizardStepCount;e++)t.push(W`<div
2017
+ `}handleSlotClicked(t){const e=t.currentTarget;if(e){const t=e.getBoundingClientRect();this.originX=t.left+t.width/2,this.originY=t.top}this.open=!0}willUpdate(t){super.willUpdate(t),t.has("open")&&(this.open?(this.fetching=!0,this.body=this.getLoading()):void 0!==t.get("open")&&(this.body="",this.originX=null,this.originY=null))}updated(t){if(super.updated(t),t.has("open"))if(this.open)this.fetchForm();else if(void 0!==t.get("open")){const t=this.shadowRoot.querySelector(".scripts");if(t)for(const e of Array.from(t.children))e.remove()}if(t.has("body")&&this.open&&this.body&&!this.fetching){this.shadowRoot.querySelector("temba-dialog").focusFirstInput()}}getLoading(){return W`<temba-loading units="6" size="8"></temba-loading>`}updatePrimaryButton(){const t=this.shadowRoot.querySelector("#wizard-form");t&&(this.wizardStep=parseInt(t.dataset.step),this.wizardStepCount=parseInt(t.dataset.steps)),this.noSubmit||this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("input[type='submit'],button[type='submit']");this.buttons=t?[{type:jc.SECONDARY,name:"Cancel",closes:!0},{type:jc.PRIMARY,name:t.value}]:[{type:jc.SECONDARY,name:"Ok",closes:!0}],this.submitting=!1})}setBody(t){const e=this.shadowRoot.querySelector(".scripts");for(const t of e.children)t.remove();const i=this.ownerDocument.createElement("div");i.innerHTML=t;const o=i.getElementsByTagName("script"),n=[];for(let t=o.length-1;t>=0;t--){const e=this.ownerDocument.createElement("script"),i=o[t].innerText;o[t].src&&-1===o[t].src.indexOf("web-dev-server")?(e.src=o[t].src,e.type="text/javascript",e.async=!0,e.onload=function(){},n.push(e)):i&&(e.appendChild(this.ownerDocument.createTextNode(i)),n.push(e)),o[t].remove()}const s=!!i.querySelector(".success-script");return s||(this.body=We(i.innerHTML)),this.updateComplete.then(()=>{for(const t of n)e.appendChild(t)}),!s}getHeaders(){const t=this.headers;return t["X-PJAX"]=1,t}fetchForm(){se(this.endpoint,null,this.getHeaders()).then(t=>{if(0==t.body.indexOf("<!DOCTYPE HTML>"))this.open=!1,document.location=t.url;else{const e=t.headers.get("X-Temba-Header-Bg"),i=t.headers.get("X-Temba-Header-Text");e?this.style.setProperty("--header-bg",e):this.style.removeProperty("--header-bg"),i?this.style.setProperty("--header-text",i):this.style.removeProperty("--header-text"),this.setBody(t.body),this.fetching=!1,this.updateComplete.then(()=>{this.updatePrimaryButton(),this.fireCustomEvent(Io.Loaded,{body:this.getBody()})})}}).catch(t=>{this.fetching=!1,this.open=!1,this.fireCustomEvent(Io.Error,{error:t})})}submit(t={}){this.submitting=!0;const e=this.shadowRoot.querySelector("form");let i=e?function(t){const e=[];for(let i=0;i<t.elements.length;i++){const o=t.elements[i];if(o.name&&!o.disabled&&"file"!==o.type&&"reset"!==o.type&&"submit"!==o.type&&"button"!==o.type)if("select-multiple"===o.type)for(let t=0;t<o.options.length;t++)o.options[t].selected&&o.options[t].value&&e.push(encodeURIComponent(o.name)+"="+encodeURIComponent(o.options[t].value));else if("checkbox"!==o.type&&"radio"!==o.type||o.checked){let t=o.value;!t&&o.checked&&(t="1"),t&&e.push(encodeURIComponent(o.name)+"="+encodeURIComponent(t))}}return e.join("&")}(e):"";t&&Object.keys(t).forEach(e=>{i+=(i.length>1?"&":"")+encodeURIComponent(e)+"="+encodeURIComponent(t[e])}),he(this.endpoint,i,this.getHeaders(),"application/x-www-form-urlencoded").then(t=>{window.setTimeout(()=>{let e=t.headers.get("X-Temba-Success");if(!e&&t.url&&-1===t.url.indexOf(this.endpoint)&&(e=t.url),e)"hide"===e?this.updateComplete.then(()=>{this.open=!1,this.fireCustomEvent(Io.Submitted)}):(this.fireCustomEvent(Io.Redirected,{url:e}),this.open=!1);else{if(0==t.body.indexOf("<!DOCTYPE HTML>"))return this.open=!1,void(document.location=t.url);this.setBody(t.body)&&this.updateComplete.then(()=>{this.updatePrimaryButton()})}},1e3)}).catch(t=>{console.error(t)})}handleDialogClick(t){const e=t.detail.button,i=t.detail.detail;e.disabled||e.submitting||(e.primary||e.destructive)&&(this.suspendSubmit||this.submit()),i.closes&&(this.open=!1,this.fetching=!1,this.cancelName=void 0)}handleDialogHidden(){this.open=!1,this.fetching=!1}isDestructive(){return this.endpoint&&(this.endpoint.indexOf("delete")>-1||this.endpoint.indexOf("interrupt")>-1)}handleGotoStep(t){const e=t.target.dataset.gotoStep;e&&this.submit({wizard_goto_step:e})}getBody(){return this.shadowRoot.querySelector(".modax-body")}render(){const t=[],e=this.shadowRoot.querySelector("#wizard-form");if(e){const i=(e.getAttribute("data-completed")||"").split(",").filter(t=>t.length>0);for(let e=0;e<this.wizardStepCount;e++)t.push(W`<div
1987
2018
  data-goto-step=${i[e]}
1988
2019
  @click=${this.handleGotoStep.bind(this)}
1989
2020
  class="${re({"step-ball":!0,active:this.wizardStep-1===e,complete:e<i.length})}"
@@ -2016,7 +2047,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
2016
2047
  <div class="slot-wrapper" @click=${this.handleSlotClicked}>
2017
2048
  <slot></slot>
2018
2049
  </div>
2019
- `}}t([mt({type:String})],xc.prototype,"header",void 0),t([mt({type:String})],xc.prototype,"endpoint",void 0),t([mt({type:Boolean,reflect:!0})],xc.prototype,"open",void 0),t([mt({type:Boolean})],xc.prototype,"fetching",void 0),t([mt({type:Boolean})],xc.prototype,"submitting",void 0),t([mt({type:String})],xc.prototype,"primaryName",void 0),t([mt({type:String})],xc.prototype,"cancelName",void 0),t([mt({type:String})],xc.prototype,"onLoaded",void 0),t([mt({type:Boolean})],xc.prototype,"noSubmit",void 0),t([mt({type:Object})],xc.prototype,"headers",void 0),t([mt({type:String})],xc.prototype,"body",void 0),t([mt({type:Boolean})],xc.prototype,"disabled",void 0),t([mt({type:Array})],xc.prototype,"buttons",void 0),t([mt({type:Number})],xc.prototype,"wizardStep",void 0),t([mt({type:Number})],xc.prototype,"wizardStepCount",void 0),t([mt({type:Boolean})],xc.prototype,"suspendSubmit",void 0),t([mt({type:Number})],xc.prototype,"originX",void 0),t([mt({type:Number})],xc.prototype,"originY",void 0);class wc extends dt{constructor(){super(...arguments),this.v=1}static get styles(){return a`
2050
+ `}}t([mt({type:String})],Wc.prototype,"header",void 0),t([mt({type:String})],Wc.prototype,"endpoint",void 0),t([mt({type:Boolean,reflect:!0})],Wc.prototype,"open",void 0),t([mt({type:Boolean})],Wc.prototype,"fetching",void 0),t([mt({type:Boolean})],Wc.prototype,"submitting",void 0),t([mt({type:String})],Wc.prototype,"primaryName",void 0),t([mt({type:String})],Wc.prototype,"cancelName",void 0),t([mt({type:String})],Wc.prototype,"onLoaded",void 0),t([mt({type:Boolean})],Wc.prototype,"noSubmit",void 0),t([mt({type:Object})],Wc.prototype,"headers",void 0),t([mt({type:String})],Wc.prototype,"body",void 0),t([mt({type:Boolean})],Wc.prototype,"disabled",void 0),t([mt({type:Array})],Wc.prototype,"buttons",void 0),t([mt({type:Number})],Wc.prototype,"wizardStep",void 0),t([mt({type:Number})],Wc.prototype,"wizardStepCount",void 0),t([mt({type:Boolean})],Wc.prototype,"suspendSubmit",void 0),t([mt({type:Number})],Wc.prototype,"originX",void 0),t([mt({type:Number})],Wc.prototype,"originY",void 0);class Vc extends dt{constructor(){super(...arguments),this.v=1}static get styles(){return a`
2020
2051
  :host {
2021
2052
  display: flex;
2022
2053
  align-self: stretch;
@@ -2206,7 +2237,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
2206
2237
  <div class="button-name"><slot name="name">${t}</slot></div>
2207
2238
  </div>
2208
2239
  </div>
2209
- `}}t([mt({type:Boolean})],wc.prototype,"primary",void 0),t([mt({type:Boolean})],wc.prototype,"secondary",void 0),t([mt({type:Boolean})],wc.prototype,"attention",void 0),t([mt({type:Number})],wc.prototype,"v",void 0),t([mt({type:Boolean})],wc.prototype,"destructive",void 0),t([mt({type:Boolean})],wc.prototype,"light",void 0),t([mt()],wc.prototype,"name",void 0),t([mt({type:Boolean})],wc.prototype,"disabled",void 0),t([mt({type:Boolean})],wc.prototype,"submitting",void 0),t([mt({type:Boolean})],wc.prototype,"active",void 0),t([mt({type:Boolean})],wc.prototype,"small",void 0),t([mt({type:Boolean})],wc.prototype,"lined",void 0),t([mt({type:String})],wc.prototype,"href",void 0),t([mt({type:Number})],wc.prototype,"index",void 0),t([mt({type:String})],wc.prototype,"icon",void 0);class _c extends dt{constructor(){super(...arguments),this.color="var(--color-primary-dark)",this.size=5,this.units=5,this.direction="row"}static get styles(){return a`
2240
+ `}}t([mt({type:Boolean})],Vc.prototype,"primary",void 0),t([mt({type:Boolean})],Vc.prototype,"secondary",void 0),t([mt({type:Boolean})],Vc.prototype,"attention",void 0),t([mt({type:Number})],Vc.prototype,"v",void 0),t([mt({type:Boolean})],Vc.prototype,"destructive",void 0),t([mt({type:Boolean})],Vc.prototype,"light",void 0),t([mt()],Vc.prototype,"name",void 0),t([mt({type:Boolean})],Vc.prototype,"disabled",void 0),t([mt({type:Boolean})],Vc.prototype,"submitting",void 0),t([mt({type:Boolean})],Vc.prototype,"active",void 0),t([mt({type:Boolean})],Vc.prototype,"small",void 0),t([mt({type:Boolean})],Vc.prototype,"lined",void 0),t([mt({type:String})],Vc.prototype,"href",void 0),t([mt({type:Number})],Vc.prototype,"index",void 0),t([mt({type:String})],Vc.prototype,"icon",void 0);class Zc extends dt{constructor(){super(...arguments),this.color="var(--color-primary-dark)",this.size=5,this.units=5,this.direction="row"}static get styles(){return a`
2210
2241
  :host {
2211
2242
  display: block;
2212
2243
  }
@@ -2240,7 +2271,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
2240
2271
  <div class="loading-unit" style=${$o(i)}></div>
2241
2272
  `})}
2242
2273
  </div>
2243
- `;var e,i}}t([mt({type:String})],_c.prototype,"color",void 0),t([mt({type:Number})],_c.prototype,"size",void 0),t([mt({type:Number})],_c.prototype,"units",void 0),t([mt({type:Boolean})],_c.prototype,"square",void 0),t([mt({type:String})],_c.prototype,"direction",void 0);const kc=[10,12,13,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,161,163,164,165,167,191,196,197,198,199,201,209,214,216,220,223,224,228,229,230,232,233,236,241,242,246,248,249,252,915,916,920,923,926,928,931,934,936,937,8364],Cc=[12,91,92,93,94,123,124,125,126,8364];function Sc(t,e){const i=e.length;let o=0;for(;o<i;){if(t===e[o])return!0;o++}return!1}function Ac(t){return Sc(t.charCodeAt(0),kc)}function Ec(t){return Sc(t.charCodeAt(0),Cc)}function $c(t){return t>=55296&&t<=56319}function Tc(t){return t>=55296&&t<=56319}const Dc=function(t,e={}){const i=e&&e.characterset;e={summary:e&&e.summary};const o=void 0===i&&function(t){for(let e=0;e<t.length;e++)if(!Ac(t.charAt(e)))return!1;return!0}(t)||"GSM"===i;let n,s,r,a;o?(n=function(t,e){if(e=e||{summary:!1},""===t)return{parts:[{content:e.summary?void 0:"",length:0,bytes:0}],totalLength:0,totalBytes:0};const i=[];let o=0,n=0,s=0,r=0,a="";function l(){const t={content:e.summary?void 0:a,length:o,bytes:n};i.push(t),r+=o,o=0,s+=n,n=0,a=""}for(let i=0,s=t.length;i<s;i++){let s=t.charAt(i);Ac(s)?Ec(s)&&(152===n&&l(),n++):($c(s.charCodeAt(0))&&i++,s=" "),n++,o++,e.summary||(a+=s),153===n&&l()}return n>0&&l(),i[1]&&s<=160?{parts:[{content:e.summary?void 0:i[0].content+i[1].content,length:r,bytes:s}],totalLength:r,totalBytes:s}:{parts:i,totalLength:r,totalBytes:s}}(t,e),s=160,r=153,a=1):(n=function(t,e){if(e=e||{summary:!1},""===t)return{parts:[{content:e.summary?void 0:"",length:0,bytes:0}],totalLength:0,totalBytes:0};const i=[];let o=0,n=0,s=0,r=0,a=0;function l(l=void 0){const d={content:e.summary?void 0:l?t.substring(a,l+1):t.substring(a),length:o,bytes:n};i.push(d),a=l+1,r+=o,o=0,s+=n,n=0}for(let e=0,i=t.length;e<i;e++)Tc(t.charCodeAt(e))&&(132===n&&l(e-1),n+=2,e++),n+=2,o++,134===n&&l(e);return n>0&&l(),i[1]&&s<=140?{parts:[{content:e.summary?void 0:t,length:r,bytes:s}],totalLength:r,totalBytes:s}:{parts:i,totalLength:r,totalBytes:s}}(t,e),s=140,r=134,a=2);const l=function(t,e,i,o){return((1===t.length?e:i)-t[t.length-1].bytes)/o}(n.parts,s,r,a);return{characterSet:o?"GSM":"Unicode",parts:n.parts,bytes:n.totalBytes,length:n.totalLength,remainingInPart:l}},Mc={0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,"\n":10,"\f":12,"\r":13," ":32,"!":33,'"':34,"#":35,$:36,"%":37,"&":38,"'":39,"(":40,")":41,"*":42,"+":43,",":44,"-":45,".":46,"/":47,":":58,";":59,"<":60,"=":61,">":62,"?":63,"@":64,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,"[":91,"\\":92,"]":93,"^":94,_:95,a:97,b:98,c:99,d:100,e:101,f:102,g:103,h:104,i:105,j:106,k:107,l:108,m:109,n:110,o:111,p:112,q:113,r:114,s:115,t:116,u:117,v:118,w:119,x:120,y:121,z:122,"{":123,"|":124,"}":125,"~":126,"¡":161,"£":163,"¤":164,"¥":165,"§":167,"¿":191,"Ä":196,"Å":197,"Æ":198,"Ç":199,"É":201,"Ñ":209,"Ö":214,"Ø":216,"Ü":220,"ß":223,"à":224,"ä":228,"å":229,"æ":230,"è":232,"é":233,"ì":236,"ñ":241,"ò":242,"ö":246,"ø":248,"ù":249,"ü":252,"Γ":915,"Δ":916,"Θ":920,"Λ":923,"Ξ":926,"Π":928,"Σ":931,"Φ":934,"Ψ":936,"Ω":937,"€":8364},zc=t=>Mc.hasOwnProperty(t);class Ic extends Be{constructor(){super(...arguments),this.noExpressions=!1,this.extended=[]}static get styles(){return a`
2274
+ `;var e,i}}t([mt({type:String})],Zc.prototype,"color",void 0),t([mt({type:Number})],Zc.prototype,"size",void 0),t([mt({type:Number})],Zc.prototype,"units",void 0),t([mt({type:Boolean})],Zc.prototype,"square",void 0),t([mt({type:String})],Zc.prototype,"direction",void 0);const Yc=[10,12,13,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,161,163,164,165,167,191,196,197,198,199,201,209,214,216,220,223,224,228,229,230,232,233,236,241,242,246,248,249,252,915,916,920,923,926,928,931,934,936,937,8364],Kc=[12,91,92,93,94,123,124,125,126,8364];function Gc(t,e){const i=e.length;let o=0;for(;o<i;){if(t===e[o])return!0;o++}return!1}function Xc(t){return Gc(t.charCodeAt(0),Yc)}function Qc(t){return Gc(t.charCodeAt(0),Kc)}function Jc(t){return t>=55296&&t<=56319}function th(t){return t>=55296&&t<=56319}const eh=function(t,e={}){const i=e&&e.characterset;e={summary:e&&e.summary};const o=void 0===i&&function(t){for(let e=0;e<t.length;e++)if(!Xc(t.charAt(e)))return!1;return!0}(t)||"GSM"===i;let n,s,r,a;o?(n=function(t,e){if(e=e||{summary:!1},""===t)return{parts:[{content:e.summary?void 0:"",length:0,bytes:0}],totalLength:0,totalBytes:0};const i=[];let o=0,n=0,s=0,r=0,a="";function l(){const t={content:e.summary?void 0:a,length:o,bytes:n};i.push(t),r+=o,o=0,s+=n,n=0,a=""}for(let i=0,s=t.length;i<s;i++){let s=t.charAt(i);Xc(s)?Qc(s)&&(152===n&&l(),n++):(Jc(s.charCodeAt(0))&&i++,s=" "),n++,o++,e.summary||(a+=s),153===n&&l()}return n>0&&l(),i[1]&&s<=160?{parts:[{content:e.summary?void 0:i[0].content+i[1].content,length:r,bytes:s}],totalLength:r,totalBytes:s}:{parts:i,totalLength:r,totalBytes:s}}(t,e),s=160,r=153,a=1):(n=function(t,e){if(e=e||{summary:!1},""===t)return{parts:[{content:e.summary?void 0:"",length:0,bytes:0}],totalLength:0,totalBytes:0};const i=[];let o=0,n=0,s=0,r=0,a=0;function l(l=void 0){const d={content:e.summary?void 0:l?t.substring(a,l+1):t.substring(a),length:o,bytes:n};i.push(d),a=l+1,r+=o,o=0,s+=n,n=0}for(let e=0,i=t.length;e<i;e++)th(t.charCodeAt(e))&&(132===n&&l(e-1),n+=2,e++),n+=2,o++,134===n&&l(e);return n>0&&l(),i[1]&&s<=140?{parts:[{content:e.summary?void 0:t,length:r,bytes:s}],totalLength:r,totalBytes:s}:{parts:i,totalLength:r,totalBytes:s}}(t,e),s=140,r=134,a=2);const l=function(t,e,i,o){return((1===t.length?e:i)-t[t.length-1].bytes)/o}(n.parts,s,r,a);return{characterSet:o?"GSM":"Unicode",parts:n.parts,bytes:n.totalBytes,length:n.totalLength,remainingInPart:l}},ih={0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,"\n":10,"\f":12,"\r":13," ":32,"!":33,'"':34,"#":35,$:36,"%":37,"&":38,"'":39,"(":40,")":41,"*":42,"+":43,",":44,"-":45,".":46,"/":47,":":58,";":59,"<":60,"=":61,">":62,"?":63,"@":64,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,"[":91,"\\":92,"]":93,"^":94,_:95,a:97,b:98,c:99,d:100,e:101,f:102,g:103,h:104,i:105,j:106,k:107,l:108,m:109,n:110,o:111,p:112,q:113,r:114,s:115,t:116,u:117,v:118,w:119,x:120,y:121,z:122,"{":123,"|":124,"}":125,"~":126,"¡":161,"£":163,"¤":164,"¥":165,"§":167,"¿":191,"Ä":196,"Å":197,"Æ":198,"Ç":199,"É":201,"Ñ":209,"Ö":214,"Ø":216,"Ü":220,"ß":223,"à":224,"ä":228,"å":229,"æ":230,"è":232,"é":233,"ì":236,"ñ":241,"ò":242,"ö":246,"ø":248,"ù":249,"ü":252,"Γ":915,"Δ":916,"Θ":920,"Λ":923,"Ξ":926,"Π":928,"Σ":931,"Φ":934,"Ψ":936,"Ω":937,"€":8364},oh=t=>ih.hasOwnProperty(t);class nh extends Be{constructor(){super(...arguments),this.noExpressions=!1,this.extended=[]}static get styles(){return a`
2244
2275
  :host {
2245
2276
  overflow: visible;
2246
2277
  }
@@ -2340,7 +2371,7 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
2340
2371
  transform: scale(1);
2341
2372
  visibility: visible;
2342
2373
  }
2343
- `}willUpdate(t){super.willUpdate(t),t.has("text")&&this.updateSegments()}replaceExpressions(t){const e=Rd.findExpressions(t);if(0===e.length)return t;const i="x".repeat(10);let o="",n=0;for(const s of e)o+=t.substring(n,s.start)+i,n=s.end;return o+=t.substring(n),o}updateSegments(){const t=this.noExpressions?this.text:this.replaceExpressions(this.text),e=Dc(t);this.count=t.length,this.segments=e.parts.length,this.extended=(t=>{const e={};for(const i of t)zc(i)||(e[i]=!0);return Object.keys(e)})(t)}handleCounterMouseEnter(t){const e=t.currentTarget,i=e.querySelector(".summary");i&&(i.style.marginLeft=e.offsetWidth-i.offsetWidth+"px",i.style.marginTop="4px")}render(){const t=!this.noExpressions&&this.text&&this.text.indexOf("@")>-1;let e=W`.`;e=this.segments>1?W`and will use ${t?W`at least`:null}
2374
+ `}willUpdate(t){super.willUpdate(t),t.has("text")&&this.updateSegments()}replaceExpressions(t){const e=Vd.findExpressions(t);if(0===e.length)return t;const i="x".repeat(10);let o="",n=0;for(const s of e)o+=t.substring(n,s.start)+i,n=s.end;return o+=t.substring(n),o}updateSegments(){const t=this.noExpressions?this.text:this.replaceExpressions(this.text),e=eh(t);this.count=t.length,this.segments=e.parts.length,this.extended=(t=>{const e={};for(const i of t)oh(i)||(e[i]=!0);return Object.keys(e)})(t)}handleCounterMouseEnter(t){const e=t.currentTarget,i=e.querySelector(".summary");i&&(i.style.marginLeft=e.offsetWidth-i.offsetWidth+"px",i.style.marginTop="4px")}render(){const t=!this.noExpressions&&this.text&&this.text.indexOf("@")>-1;let e=W`.`;e=this.segments>1?W`and will use ${t?W`at least`:null}
2344
2375
  <b>${this.segments} messages</b> to send over SMS.`:W`and will use ${t?W`at least`:null} one
2345
2376
  message to send over SMS.`;let i=null;this.extended.length>0&&(this.segments>1||t)&&(i=this.extended.map(t=>W`<div class="extended-char">${t}</div>`),i=W`
2346
2377
  <div class="extended-warning">
@@ -2361,18 +2392,18 @@ class sl{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
2361
2392
  </div>`:null,n=this.segments>2||2===this.segments&&this.extended.length>0;return W`<div class="counter${n?" attention":""}" @mouseenter=${this.handleCounterMouseEnter}><div class="counts">${this.count}${this.segments>1||t?W`<div class="segments">
2362
2393
  &nbsp;/&nbsp;${this.segments}${t?W`+`:null}
2363
2394
  <div></div>
2364
- </div>`:null}</div> ${o}</div></div>`}}t([mt({type:String})],Ic.prototype,"text",void 0),t([mt({type:Boolean,attribute:"no-expressions"})],Ic.prototype,"noExpressions",void 0),t([mt({type:Number})],Ic.prototype,"count",void 0),t([mt({type:Number,attribute:!1})],Ic.prototype,"segments",void 0),t([mt({type:Object,attribute:!1})],Ic.prototype,"extended",void 0);class Lc extends Be{constructor(){super(...arguments),this.showLoading=!1,this.dirty=!1}markDirty(){this.dirty=!0,this.store.markDirty(this),this.fireCustomEvent(Io.DetailsChanged,{dirty:!0})}markClean(){this.dirty=!1,this.store.markClean(this),this.fireCustomEvent(Io.DetailsChanged,{dirty:!1})}handleStoreUpdated(t){this.storeUpdated(t)}storeUpdated(t){}connectedCallback(){super.connectedCallback(),this.store=document.querySelector("temba-store"),this.handleStoreUpdated=this.handleStoreUpdated.bind(this),this.store&&this.store.addEventListener(Io.StoreUpdated,this.handleStoreUpdated)}disconnectedCallback(){super.disconnectedCallback(),this.store&&(this.store.removeEventListener(Io.StoreUpdated,this.handleStoreUpdated),this.store.markClean(this))}render(){if(!this.store.ready&&this.showLoading)return W`<temba-loading></temba-loading>`}}t([mt({type:String})],Lc.prototype,"url",void 0),t([mt({type:Boolean})],Lc.prototype,"showLoading",void 0),t([mt({type:Boolean})],Lc.prototype,"dirty",void 0),t([mt({type:String})],Lc.prototype,"dirtyMessage",void 0);class Oc extends Lc{constructor(){super(...arguments),this.showLoading=!1}connectedCallback(){super.connectedCallback(),this.prepareData=this.prepareData.bind(this)}prepareData(t){return t}refresh(){this.store.makeRequest(this.url,{prepareData:this.prepareData,force:!0})}storeUpdated(t){if(t.detail.url===this.url){const e=this.data;this.data=t.detail.data,this.fireCustomEvent(Io.Refreshed,{data:t.detail.data,previous:e})}}willUpdate(t){super.willUpdate(t),t.has("url")&&!this.url&&(this.data=null)}updated(t){super.updated(t),t.has("url")&&this.url&&this.store.makeRequest(this.url,{prepareData:this.prepareData})}}t([mt({type:String})],Oc.prototype,"url",void 0),t([mt({type:Boolean})],Oc.prototype,"showLoading",void 0),t([mt({type:Object,attribute:!1})],Oc.prototype,"data",void 0);class Pc extends Oc{constructor(){super(...arguments),this.endpoint="/api/v2/contacts.json?uuid="}prepareData(t){return t&&t.length>0?((t=t[0]).groups.forEach(t=>{t.is_dynamic=this.store.isDynamicGroup(t.uuid)}),t.groups.sort((t,e)=>{if(!t.is_dynamic||!e.is_dynamic){if(t.is_dynamic)return-1;if(e.is_dynamic)return 1}return t.name.localeCompare(e.name)}),t):null}postChanges(t){return this.store.removeFromCache(`${this.endpoint}${this.contact}`),this.store.postJSON(`${this.endpoint}${this.contact}`,t).then(t=>{this.setContact(t.json)})}setContact(t){this.data=this.prepareData([t]),this.store.updateCache(`${this.endpoint}${this.contact}`,this.data)}willUpdate(t){super.willUpdate(t),(t.has("contact")||t.has("endpoint"))&&(this.contact?this.url=`${this.endpoint}${this.contact}`:this.url=null)}}t([mt({type:String})],Pc.prototype,"contact",void 0),t([mt({type:Object,attribute:!1})],Pc.prototype,"data",void 0),t([mt({type:String})],Pc.prototype,"endpoint",void 0);
2395
+ </div>`:null}</div> ${o}</div></div>`}}t([mt({type:String})],nh.prototype,"text",void 0),t([mt({type:Boolean,attribute:"no-expressions"})],nh.prototype,"noExpressions",void 0),t([mt({type:Number})],nh.prototype,"count",void 0),t([mt({type:Number,attribute:!1})],nh.prototype,"segments",void 0),t([mt({type:Object,attribute:!1})],nh.prototype,"extended",void 0);class sh extends Be{constructor(){super(...arguments),this.showLoading=!1,this.dirty=!1}markDirty(){this.dirty=!0,this.store.markDirty(this),this.fireCustomEvent(Io.DetailsChanged,{dirty:!0})}markClean(){this.dirty=!1,this.store.markClean(this),this.fireCustomEvent(Io.DetailsChanged,{dirty:!1})}handleStoreUpdated(t){this.storeUpdated(t)}storeUpdated(t){}connectedCallback(){super.connectedCallback(),this.store=document.querySelector("temba-store"),this.handleStoreUpdated=this.handleStoreUpdated.bind(this),this.store&&this.store.addEventListener(Io.StoreUpdated,this.handleStoreUpdated)}disconnectedCallback(){super.disconnectedCallback(),this.store&&(this.store.removeEventListener(Io.StoreUpdated,this.handleStoreUpdated),this.store.markClean(this))}render(){if(!this.store.ready&&this.showLoading)return W`<temba-loading></temba-loading>`}}t([mt({type:String})],sh.prototype,"url",void 0),t([mt({type:Boolean})],sh.prototype,"showLoading",void 0),t([mt({type:Boolean})],sh.prototype,"dirty",void 0),t([mt({type:String})],sh.prototype,"dirtyMessage",void 0);class rh extends sh{constructor(){super(...arguments),this.showLoading=!1}connectedCallback(){super.connectedCallback(),this.prepareData=this.prepareData.bind(this)}prepareData(t){return t}refresh(){this.store.makeRequest(this.url,{prepareData:this.prepareData,force:!0})}storeUpdated(t){if(t.detail.url===this.url){const e=this.data;this.data=t.detail.data,this.fireCustomEvent(Io.Refreshed,{data:t.detail.data,previous:e})}}willUpdate(t){super.willUpdate(t),t.has("url")&&!this.url&&(this.data=null)}updated(t){super.updated(t),t.has("url")&&this.url&&this.store.makeRequest(this.url,{prepareData:this.prepareData})}}t([mt({type:String})],rh.prototype,"url",void 0),t([mt({type:Boolean})],rh.prototype,"showLoading",void 0),t([mt({type:Object,attribute:!1})],rh.prototype,"data",void 0);class ah extends rh{constructor(){super(...arguments),this.endpoint="/api/v2/contacts.json?uuid="}prepareData(t){return t&&t.length>0?((t=t[0]).groups.forEach(t=>{t.is_dynamic=this.store.isDynamicGroup(t.uuid)}),t.groups.sort((t,e)=>{if(!t.is_dynamic||!e.is_dynamic){if(t.is_dynamic)return-1;if(e.is_dynamic)return 1}return t.name.localeCompare(e.name)}),t):null}postChanges(t){return this.store.removeFromCache(`${this.endpoint}${this.contact}`),this.store.postJSON(`${this.endpoint}${this.contact}`,t).then(t=>{this.setContact(t.json)})}setContact(t){this.data=this.prepareData([t]),this.store.updateCache(`${this.endpoint}${this.contact}`,this.data)}willUpdate(t){super.willUpdate(t),(t.has("contact")||t.has("endpoint"))&&(this.contact?this.url=`${this.endpoint}${this.contact}`:this.url=null)}}t([mt({type:String})],ah.prototype,"contact",void 0),t([mt({type:Object,attribute:!1})],ah.prototype,"data",void 0),t([mt({type:String})],ah.prototype,"endpoint",void 0);
2365
2396
  /**
2366
2397
  * @license
2367
2398
  * Copyright 2020 Google LLC
2368
2399
  * SPDX-License-Identifier: BSD-3-Clause
2369
2400
  */
2370
- const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t._$AA.parentNode,n=void 0===e?t._$AB:e._$AA;if(void 0===i){const e=o.insertBefore(Bc(),n),s=o.insertBefore(Bc(),n);i=new Rc(e,s,t,t.options)}else{const e=i._$AB.nextSibling,s=i._$AM,r=s!==t;if(r){let e;i._$AQ?.(t),i._$AM=t,void 0!==i._$AP&&(e=t._$AU)!==s._$AU&&i._$AP(e)}if(e!==n||r){let t=i._$AA;for(;t!==e;){const e=Nc(t).nextSibling;Nc(o).insertBefore(t,n),t=e}}}return i},qc=(t,e,i=t)=>(t._$AI(e,i),t),Uc={},jc=(t,e=Uc)=>t._$AH=e,Hc=t=>{t._$AR(),t._$AA.remove()},Wc=(t,e,i)=>{const o=new Map;for(let n=e;n<=i;n++)o.set(t[n],n);return o},Vc=Ue(class extends je{constructor(t){if(super(t),t.type!==qe)throw Error("repeat() can only be used in text expressions")}dt(t,e,i){let o;void 0===i?i=e:void 0!==e&&(o=e);const n=[],s=[];let r=0;for(const e of t)n[r]=o?o(e,r):r,s[r]=i(e,r),r++;return{values:s,keys:n}}render(t,e,i){return this.dt(t,e,i).values}update(t,[e,i,o]){const n=(t=>t._$AH)(t),{values:s,keys:r}=this.dt(e,i,o);if(!Array.isArray(n))return this.ut=r,s;const a=this.ut??=[],l=[];let d,c,h=0,u=n.length-1,p=0,m=s.length-1;for(;h<=u&&p<=m;)if(null===n[h])h++;else if(null===n[u])u--;else if(a[h]===r[p])l[p]=qc(n[h],s[p]),h++,p++;else if(a[u]===r[m])l[m]=qc(n[u],s[m]),u--,m--;else if(a[h]===r[m])l[m]=qc(n[h],s[m]),Fc(t,l[m+1],n[h]),h++,m--;else if(a[u]===r[p])l[p]=qc(n[u],s[p]),Fc(t,n[h],n[u]),u--,p++;else if(void 0===d&&(d=Wc(r,p,m),c=Wc(a,h,u)),d.has(a[h]))if(d.has(a[u])){const e=c.get(r[p]),i=void 0!==e?n[e]:null;if(null===i){const e=Fc(t,n[h]);qc(e,s[p]),l[p]=e}else l[p]=qc(i,s[p]),Fc(t,n[h],i),n[e]=null;p++}else Hc(n[u]),u--;else Hc(n[h]),h++;for(;p<=m;){const e=Fc(t,l[m+1]);qc(e,s[p]),l[p++]=e}for(;h<=u;){const t=n[h++];null!==t&&Hc(t)}return this.ut=r,jc(t,l),V}}),Zc=36e5;
2401
+ const{I:lh}=rt,dh=t=>t,ch=()=>document.createComment(""),hh=(t,e,i)=>{const o=t._$AA.parentNode,n=void 0===e?t._$AB:e._$AA;if(void 0===i){const e=o.insertBefore(ch(),n),s=o.insertBefore(ch(),n);i=new lh(e,s,t,t.options)}else{const e=i._$AB.nextSibling,s=i._$AM,r=s!==t;if(r){let e;i._$AQ?.(t),i._$AM=t,void 0!==i._$AP&&(e=t._$AU)!==s._$AU&&i._$AP(e)}if(e!==n||r){let t=i._$AA;for(;t!==e;){const e=dh(t).nextSibling;dh(o).insertBefore(t,n),t=e}}}return i},uh=(t,e,i=t)=>(t._$AI(e,i),t),ph={},mh=(t,e=ph)=>t._$AH=e,gh=t=>{t._$AR(),t._$AA.remove()},fh=(t,e,i)=>{const o=new Map;for(let n=e;n<=i;n++)o.set(t[n],n);return o},vh=Ue(class extends je{constructor(t){if(super(t),t.type!==qe)throw Error("repeat() can only be used in text expressions")}dt(t,e,i){let o;void 0===i?i=e:void 0!==e&&(o=e);const n=[],s=[];let r=0;for(const e of t)n[r]=o?o(e,r):r,s[r]=i(e,r),r++;return{values:s,keys:n}}render(t,e,i){return this.dt(t,e,i).values}update(t,[e,i,o]){const n=(t=>t._$AH)(t),{values:s,keys:r}=this.dt(e,i,o);if(!Array.isArray(n))return this.ut=r,s;const a=this.ut??=[],l=[];let d,c,h=0,u=n.length-1,p=0,m=s.length-1;for(;h<=u&&p<=m;)if(null===n[h])h++;else if(null===n[u])u--;else if(a[h]===r[p])l[p]=uh(n[h],s[p]),h++,p++;else if(a[u]===r[m])l[m]=uh(n[u],s[m]),u--,m--;else if(a[h]===r[m])l[m]=uh(n[h],s[m]),hh(t,l[m+1],n[h]),h++,m--;else if(a[u]===r[p])l[p]=uh(n[u],s[p]),hh(t,n[h],n[u]),u--,p++;else if(void 0===d&&(d=fh(r,p,m),c=fh(a,h,u)),d.has(a[h]))if(d.has(a[u])){const e=c.get(r[p]),i=void 0!==e?n[e]:null;if(null===i){const e=hh(t,n[h]);uh(e,s[p]),l[p]=e}else l[p]=uh(i,s[p]),hh(t,n[h],i),n[e]=null;p++}else gh(n[u]),u--;else gh(n[h]),h++;for(;p<=m;){const e=hh(t,l[m+1]);uh(e,s[p]),l[p++]=e}for(;h<=u;){const t=n[h++];null!==t&&gh(t)}return this.ut=r,mh(t,l),V}}),bh=36e5;
2371
2402
  /**
2372
2403
  * @license
2373
2404
  * Copyright 2017 Google LLC
2374
2405
  * SPDX-License-Identifier: BSD-3-Clause
2375
- */var Yc;!function(t){t.Inline="inline",t.Error="error",t.Collapse="collapse",t.Note="note"}(Yc||(Yc={}));const Kc={hour:"numeric",minute:"2-digit"},Gc={weekday:void 0,year:void 0,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"},Xc={weekday:void 0,year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"};class Qc extends Be{constructor(){super(...arguments),this.messageGroups=[],this.fetching=!1,this.hideTopScroll=!0,this.hideBottomScroll=!0,this.defaultAvatar=kl,this.agent=!1,this.avatars=!1,this.endOfHistory=!1,this.oldestEventDate=null,this.showNewMessageNotification=!1,this.showMessageLogsAfter=null,this.hasFooter=!1,this.showTimestamps=!0,this.searchHighlight=null,this.highlightMessageUuid=null,this.msgMap=new Map,this.metadataCache=new Map}static get styles(){return a`
2406
+ */var yh;!function(t){t.Inline="inline",t.Error="error",t.Collapse="collapse",t.Note="note"}(yh||(yh={}));const xh={hour:"numeric",minute:"2-digit"},wh={weekday:void 0,year:void 0,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"},_h={weekday:void 0,year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"};class kh extends Be{constructor(){super(...arguments),this.messageGroups=[],this.fetching=!1,this.hideTopScroll=!0,this.hideBottomScroll=!0,this.defaultAvatar=kl,this.agent=!1,this.avatars=!1,this.endOfHistory=!1,this.oldestEventDate=null,this.showNewMessageNotification=!1,this.showMessageLogsAfter=null,this.hasFooter=!1,this.showTimestamps=!0,this.searchHighlight=null,this.highlightMessageUuid=null,this.msgMap=new Map,this.metadataCache=new Map}static get styles(){return a`
2376
2407
  :host {
2377
2408
  display: flex;
2378
2409
  flex-direction: column;
@@ -2996,12 +3027,12 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
2996
3027
  .search-match .bubble {
2997
3028
  animation: search-pulse 1s ease-in-out 2;
2998
3029
  }
2999
- `}firstUpdated(t){super.firstUpdated(t);const e=this.shadowRoot.querySelector(".scroll"),i=e.scrollHeight>e.clientHeight;this.hideBottomScroll=!0,this.hideTopScroll=!i}addMessages(t,e=null,i=!1,o=!1){e||(e=new Date);const n=(new Date).getTime()-e.getTime();window.setTimeout(()=>{this.fetching=!1;const e=[];for(const i of t){if("msg_deleted"===i.type||"msg_status_changed"===i.type){const t=i.msg_uuid;t&&this.metadataCache.set(t,i);continue}this.addMessage(i)&&e.push(i.uuid)}if(0===e.length)return;const n=this.shadowRoot.querySelector(".scroll"),s=n.scrollTop,r=n.scrollHeight,a=n.scrollHeight-n.clientHeight>0&&Math.abs(n.scrollTop)>50,l=this.groupMessages(e);this.insertGroups(l,i),i&&a&&e.length>0&&!this.searchHighlight&&(this.showNewMessageNotification=!0),window.setTimeout(()=>{if(i&&(a||o)){const t=n.scrollHeight-r;n.scrollTop=s-t}else n.scrollTop=s;const t=n.scrollHeight-n.clientHeight,e=Math.abs(n.scrollTop);this.hideTopScroll=e>=t-1,this.hideBottomScroll=e<=1,this.fireCustomEvent(Io.FetchComplete)},100)},0===this.messageGroups.length?0:Math.max(0,250-n))}loadMessages(t){const e=[];for(const i of t){if("msg_deleted"===i.type||"msg_status_changed"===i.type){const t=i.msg_uuid;t&&this.metadataCache.set(t,i);continue}this.addMessage(i)&&e.push(i.uuid)}if(e.length>0){const t=this.groupMessages(e);this.insertGroups(t,!1)}}addMessage(t){const e=!this.messageExists(t);return this.msgMap.set(t.uuid,t),e}messageExists(t){return this.msgMap.has(t.uuid)}isSameGroup(t,e,i){var o,n;if(!t||!e)return{same:!0};const s="msg_created"===t.type||"msg_received"===t.type||"ivr_created"===t.type,r="msg_created"===e.type||"msg_received"===e.type||"ivr_created"===e.type,a=s&&r?t.type===e.type:s===r,l=i||e.created_on;return Math.abs(t.created_on.getTime()-l.getTime())>=Zc?{same:!1,reason:"time_elapsed"}:a?s&&r&&(null===(o=t._user)||void 0===o?void 0:o.name)!==(null===(n=e._user)||void 0===n?void 0:n.name)?{same:!1,reason:"new_author"}:{same:!0}:{same:!1,reason:"new_type"}}insertGroups(t,e=!1){e||t.reverse();for(const i of t){const t=this.messageGroups[e?0:this.messageGroups.length-1];if(t){const o=t.messages[t.messages.length-1],n=this.msgMap.get(o),s=this.msgMap.get(i.messages[0]),r=this.isSameGroup(n,s);r.same?e?t.messages.push(...i.messages):t.messages.unshift(...i.messages):e?this.messageGroups.splice(0,0,i):(r.reason&&(t.reason=r.reason),this.messageGroups.push(i))}else e?this.messageGroups.splice(0,0,i):this.messageGroups.push(i)}this.requestUpdate("messageGroups")}groupMessages(t){const e=[];let i=null,o=null,n=null;for(const s of t){const t=this.msgMap.get(s),r=this.isSameGroup(t,o,n);r.same&&i||(i={messages:[],reason:r.reason||"initial"},e.push(i),"time_elapsed"===r.reason&&(n=t.created_on)),i.messages.push(s),o=t}return e}handleScroll(t){const e=t.target,i=e.scrollHeight-e.clientHeight;if(i<=0)return;const o=Math.abs(e.scrollTop),n=o>=i-200;this.hideTopScroll=o>=i-1,this.hideBottomScroll=o<=1,o<=10&&(this.showNewMessageNotification=!1),n&&this.fireCustomEvent(Io.ScrollThreshold),o<=600&&i>0&&this.fireCustomEvent(Io.ScrollThresholdBottom)}scrollToBottom(){const t=this.shadowRoot.querySelector(".scroll");t&&(t.scrollTop=0,this.hideBottomScroll=!0,this.showNewMessageNotification=!1)}scrollToMessage(t,e=!0,i){this.highlightMessageUuid=t,window.setTimeout(()=>{const o=this.shadowRoot.querySelector(".scroll"),n=this.shadowRoot.querySelector(`.row[data-uuid="${t}"]`);if(o&&n){const t=o.getBoundingClientRect(),i=n.getBoundingClientRect(),s=i.top+i.height/2-(t.top+t.height/2);e?o.scrollBy({top:s,behavior:"smooth"}):o.scrollTop=o.scrollTop+s}i&&requestAnimationFrame(()=>i())},150)}highlightText(t,e){if(!e||!t)return t;const i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(${i})`,"gi"),n=t.split(o);return 1===n.length?t:W`${n.map((t,e)=>e%2==1?W`<mark>${t}</mark>`:t)}`}handleNewMessageClick(){this.scrollToBottom()}getReasonLabel(t){switch(t){case"new_author":return"👤 Different author";case"new_type":return"🔄 Message type changed";default:return""}}renderMessageGroup(t,e,i){var o,n,s,r;const a=new Date,l=t.messages,d=l[l.length-1],c=this.msgMap.get(d),h=this.agent?"msg_received"!==c.type:"msg_received"===c.type,u=null===(o=c._user)||void 0===o?void 0:o.name,p="msg_received"===c.type||"msg_created"===c.type||"ivr_created"===c.type,m=this.avatars&&(p&&this.agent||!h),g=!(null===(n=c._user)||void 0===n?void 0:n.uuid);this.getReasonLabel(t.reason);const f=l[0],v=this.msgMap.get(f);let b=!1,y=i;if(e>0)if(i){b=Math.abs(v.created_on.getTime()-i.getTime())>=Zc}else b="time_elapsed"===t.reason;let x=null;if(b){y=v.created_on;const t=a.getFullYear()!==v.created_on.getFullYear()?Xc:a.getDate()!==v.created_on.getDate()?Gc:Kc;x=W`<div class="time time-elapsed">
3030
+ `}firstUpdated(t){super.firstUpdated(t);const e=this.shadowRoot.querySelector(".scroll"),i=e.scrollHeight>e.clientHeight;this.hideBottomScroll=!0,this.hideTopScroll=!i}addMessages(t,e=null,i=!1,o=!1){e||(e=new Date);const n=(new Date).getTime()-e.getTime();window.setTimeout(()=>{this.fetching=!1;const e=[];for(const i of t){if("msg_deleted"===i.type||"msg_status_changed"===i.type){const t=i.msg_uuid;t&&this.metadataCache.set(t,i);continue}this.addMessage(i)&&e.push(i.uuid)}if(0===e.length)return;const n=this.shadowRoot.querySelector(".scroll"),s=n.scrollTop,r=n.scrollHeight,a=n.scrollHeight-n.clientHeight>0&&Math.abs(n.scrollTop)>50,l=this.groupMessages(e);this.insertGroups(l,i),i&&a&&e.length>0&&!this.searchHighlight&&(this.showNewMessageNotification=!0),window.setTimeout(()=>{if(i&&(a||o)){const t=n.scrollHeight-r;n.scrollTop=s-t}else n.scrollTop=s;const t=n.scrollHeight-n.clientHeight,e=Math.abs(n.scrollTop);this.hideTopScroll=e>=t-1,this.hideBottomScroll=e<=1,this.fireCustomEvent(Io.FetchComplete)},100)},0===this.messageGroups.length?0:Math.max(0,250-n))}loadMessages(t){const e=[];for(const i of t){if("msg_deleted"===i.type||"msg_status_changed"===i.type){const t=i.msg_uuid;t&&this.metadataCache.set(t,i);continue}this.addMessage(i)&&e.push(i.uuid)}if(e.length>0){const t=this.groupMessages(e);this.insertGroups(t,!1)}}addMessage(t){const e=!this.messageExists(t);return this.msgMap.set(t.uuid,t),e}messageExists(t){return this.msgMap.has(t.uuid)}isSameGroup(t,e,i){var o,n;if(!t||!e)return{same:!0};const s="msg_created"===t.type||"msg_received"===t.type||"ivr_created"===t.type,r="msg_created"===e.type||"msg_received"===e.type||"ivr_created"===e.type,a=s&&r?t.type===e.type:s===r,l=i||e.created_on;return Math.abs(t.created_on.getTime()-l.getTime())>=bh?{same:!1,reason:"time_elapsed"}:a?s&&r&&(null===(o=t._user)||void 0===o?void 0:o.name)!==(null===(n=e._user)||void 0===n?void 0:n.name)?{same:!1,reason:"new_author"}:{same:!0}:{same:!1,reason:"new_type"}}insertGroups(t,e=!1){e||t.reverse();for(const i of t){const t=this.messageGroups[e?0:this.messageGroups.length-1];if(t){const o=t.messages[t.messages.length-1],n=this.msgMap.get(o),s=this.msgMap.get(i.messages[0]),r=this.isSameGroup(n,s);r.same?e?t.messages.push(...i.messages):t.messages.unshift(...i.messages):e?this.messageGroups.splice(0,0,i):(r.reason&&(t.reason=r.reason),this.messageGroups.push(i))}else e?this.messageGroups.splice(0,0,i):this.messageGroups.push(i)}this.requestUpdate("messageGroups")}groupMessages(t){const e=[];let i=null,o=null,n=null;for(const s of t){const t=this.msgMap.get(s),r=this.isSameGroup(t,o,n);r.same&&i||(i={messages:[],reason:r.reason||"initial"},e.push(i),"time_elapsed"===r.reason&&(n=t.created_on)),i.messages.push(s),o=t}return e}handleScroll(t){const e=t.target,i=e.scrollHeight-e.clientHeight;if(i<=0)return;const o=Math.abs(e.scrollTop),n=o>=i-200;this.hideTopScroll=o>=i-1,this.hideBottomScroll=o<=1,o<=10&&(this.showNewMessageNotification=!1),n&&this.fireCustomEvent(Io.ScrollThreshold),o<=600&&i>0&&this.fireCustomEvent(Io.ScrollThresholdBottom)}scrollToBottom(){const t=this.shadowRoot.querySelector(".scroll");t&&(t.scrollTop=0,this.hideBottomScroll=!0,this.showNewMessageNotification=!1)}scrollToMessage(t,e=!0,i){this.highlightMessageUuid=t,window.setTimeout(()=>{const o=this.shadowRoot.querySelector(".scroll"),n=this.shadowRoot.querySelector(`.row[data-uuid="${t}"]`);if(o&&n){const t=o.getBoundingClientRect(),i=n.getBoundingClientRect(),s=i.top+i.height/2-(t.top+t.height/2);e?o.scrollBy({top:s,behavior:"smooth"}):o.scrollTop=o.scrollTop+s}i&&requestAnimationFrame(()=>i())},150)}highlightText(t,e){if(!e||!t)return t;const i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(${i})`,"gi"),n=t.split(o);return 1===n.length?t:W`${n.map((t,e)=>e%2==1?W`<mark>${t}</mark>`:t)}`}handleNewMessageClick(){this.scrollToBottom()}getReasonLabel(t){switch(t){case"new_author":return"👤 Different author";case"new_type":return"🔄 Message type changed";default:return""}}renderMessageGroup(t,e,i){var o,n,s,r;const a=new Date,l=t.messages,d=l[l.length-1],c=this.msgMap.get(d),h=this.agent?"msg_received"!==c.type:"msg_received"===c.type,u=null===(o=c._user)||void 0===o?void 0:o.name,p="msg_received"===c.type||"msg_created"===c.type||"ivr_created"===c.type,m=this.avatars&&(p&&this.agent||!h),g=!(null===(n=c._user)||void 0===n?void 0:n.uuid);this.getReasonLabel(t.reason);const f=l[0],v=this.msgMap.get(f);let b=!1,y=i;if(e>0)if(i){b=Math.abs(v.created_on.getTime()-i.getTime())>=bh}else b="time_elapsed"===t.reason;let x=null;if(b){y=v.created_on;const t=a.getFullYear()!==v.created_on.getFullYear()?_h:a.getDate()!==v.created_on.getDate()?wh:xh;x=W`<div class="time time-elapsed">
3000
3031
  ${v.created_on.toLocaleTimeString(void 0,t)}
3001
3032
  </div>`}const w=W`
3002
3033
  <div class="block ${h?"incoming":"outgoing"}">
3003
3034
  <div class="group-messages" style="flex-grow:1">
3004
- ${Vc(l,t=>t,(t,e)=>{var i,o;const n=this.msgMap.get(t),s=n,r=n._status?n._status.status:"",a=(null===(i=s.msg)||void 0===i?void 0:i.unsendable_reason)||(null===(o=s._status)||void 0===o?void 0:o.reason)&&("failed"===r||"errored"===r)?"error":"",d=s._deleted?"deleted":"",c=e===l.length-1?"latest":"",h=n._rendered?"is-event":"",p=this.highlightMessageUuid===n.uuid?"search-match":"";return W`<div
3035
+ ${vh(l,t=>t,(t,e)=>{var i,o;const n=this.msgMap.get(t),s=n,r=n._status?n._status.status:"",a=(null===(i=s.msg)||void 0===i?void 0:i.unsendable_reason)||(null===(o=s._status)||void 0===o?void 0:o.reason)&&("failed"===r||"errored"===r)?"error":"",d=s._deleted?"deleted":"",c=e===l.length-1?"latest":"",h=n._rendered?"is-event":"",p=this.highlightMessageUuid===n.uuid?"search-match":"";return W`<div
3005
3036
  class="row message ${r} ${a} ${d} ${c} ${h} ${p}"
3006
3037
  data-uuid=${n.uuid||Z}
3007
3038
  >
@@ -3072,7 +3103,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
3072
3103
  ></temba-loading>
3073
3104
 
3074
3105
  ${this.endOfHistory&&this.oldestEventDate?W`<div class="time first">
3075
- ${this.oldestEventDate.toLocaleTimeString(void 0,Gc)}
3106
+ ${this.oldestEventDate.toLocaleTimeString(void 0,wh)}
3076
3107
  </div>`:null}
3077
3108
  </div>
3078
3109
  ${this.hasFooter?null:W`<div
@@ -3083,9 +3114,9 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
3083
3114
  </div>`}
3084
3115
  <slot class="header" name="header"></slot>
3085
3116
  <slot class="footer" name="footer"></slot>
3086
- </div>`}}var Jc;t([mt({type:Array})],Qc.prototype,"messageGroups",void 0),t([mt({type:Boolean})],Qc.prototype,"fetching",void 0),t([mt({type:Boolean,attribute:!1})],Qc.prototype,"hideTopScroll",void 0),t([mt({type:Boolean,attribute:!1})],Qc.prototype,"hideBottomScroll",void 0),t([mt({type:String,attribute:"avatar"})],Qc.prototype,"defaultAvatar",void 0),t([mt({type:Boolean})],Qc.prototype,"agent",void 0),t([mt({type:Boolean})],Qc.prototype,"avatars",void 0),t([mt({type:Boolean,attribute:!1})],Qc.prototype,"endOfHistory",void 0),t([mt({type:Object,attribute:!1})],Qc.prototype,"oldestEventDate",void 0),t([mt({type:Boolean,attribute:!1})],Qc.prototype,"showNewMessageNotification",void 0),t([mt({type:Object})],Qc.prototype,"showMessageLogsAfter",void 0),t([mt({type:Boolean})],Qc.prototype,"hasFooter",void 0),t([mt({type:Boolean})],Qc.prototype,"showTimestamps",void 0),t([mt({type:String,attribute:!1})],Qc.prototype,"searchHighlight",void 0),t([mt({type:String,attribute:!1})],Qc.prototype,"highlightMessageUuid",void 0),function(t){t.AIRTIME_TRANSFERRED="airtime_transferred",t.BROADCAST_CREATED="broadcast_created",t.CALL_CREATED="call_created",t.CALL_MISSED="call_missed",t.CALL_RECEIVED="call_received",t.CHAT_STARTED="chat_started",t.CONTACT_FIELD_CHANGED="contact_field_changed",t.CONTACT_GROUPS_CHANGED="contact_groups_changed",t.CONTACT_LANGUAGE_CHANGED="contact_language_changed",t.CONTACT_NAME_CHANGED="contact_name_changed",t.CONTACT_STATUS_CHANGED="contact_status_changed",t.CONTACT_URNS_CHANGED="contact_urns_changed",t.EMAIL_CREATED="email_created",t.EMAIL_SENT="email_sent",t.ERROR="error",t.FAILURE="failure",t.FLOW_ENTERED="flow_entered",t.INPUT_LABELS_ADDED="input_labels_added",t.IVR_CREATED="ivr_created",t.MSG_CREATED="msg_created",t.MSG_RECEIVED="msg_received",t.OPTIN_REQUESTED="optin_requested",t.OPTIN_STARTED="optin_started",t.OPTIN_STOPPED="optin_stopped",t.RESTHOOK_CALLED="resthook_called",t.RUN_ENDED="run_ended",t.RUN_RESULT_CHANGED="run_result_changed",t.RUN_STARTED="run_started",t.SERVICE_CALLED="service_called",t.SESSION_TRIGGERED="session_triggered",t.TICKET_ASSIGNEE_CHANGED="ticket_assignee_changed",t.TICKET_CLOSED="ticket_closed",t.TICKET_NOTE_ADDED="ticket_note_added",t.TICKET_OPENED="ticket_opened",t.TICKET_REOPENED="ticket_reopened",t.TICKET_TOPIC_CHANGED="ticket_topic_changed",t.WARNING="warning",t.WEBHOOK_CALLED="webhook_called"}(Jc||(Jc={}));const th=(t,e,i)=>{if(1===i.length)return W`<div>${t} <strong>${i[0].name}</strong></div>`;{const t=i.map(t=>t.name);if(2===t.length)return W`<div>
3117
+ </div>`}}var Ch;t([mt({type:Array})],kh.prototype,"messageGroups",void 0),t([mt({type:Boolean})],kh.prototype,"fetching",void 0),t([mt({type:Boolean,attribute:!1})],kh.prototype,"hideTopScroll",void 0),t([mt({type:Boolean,attribute:!1})],kh.prototype,"hideBottomScroll",void 0),t([mt({type:String,attribute:"avatar"})],kh.prototype,"defaultAvatar",void 0),t([mt({type:Boolean})],kh.prototype,"agent",void 0),t([mt({type:Boolean})],kh.prototype,"avatars",void 0),t([mt({type:Boolean,attribute:!1})],kh.prototype,"endOfHistory",void 0),t([mt({type:Object,attribute:!1})],kh.prototype,"oldestEventDate",void 0),t([mt({type:Boolean,attribute:!1})],kh.prototype,"showNewMessageNotification",void 0),t([mt({type:Object})],kh.prototype,"showMessageLogsAfter",void 0),t([mt({type:Boolean})],kh.prototype,"hasFooter",void 0),t([mt({type:Boolean})],kh.prototype,"showTimestamps",void 0),t([mt({type:String,attribute:!1})],kh.prototype,"searchHighlight",void 0),t([mt({type:String,attribute:!1})],kh.prototype,"highlightMessageUuid",void 0),function(t){t.AIRTIME_TRANSFERRED="airtime_transferred",t.BROADCAST_CREATED="broadcast_created",t.CALL_CREATED="call_created",t.CALL_MISSED="call_missed",t.CALL_RECEIVED="call_received",t.CHAT_STARTED="chat_started",t.CONTACT_FIELD_CHANGED="contact_field_changed",t.CONTACT_GROUPS_CHANGED="contact_groups_changed",t.CONTACT_LANGUAGE_CHANGED="contact_language_changed",t.CONTACT_NAME_CHANGED="contact_name_changed",t.CONTACT_STATUS_CHANGED="contact_status_changed",t.CONTACT_URNS_CHANGED="contact_urns_changed",t.EMAIL_CREATED="email_created",t.EMAIL_SENT="email_sent",t.ERROR="error",t.FAILURE="failure",t.FLOW_ENTERED="flow_entered",t.INPUT_LABELS_ADDED="input_labels_added",t.IVR_CREATED="ivr_created",t.MSG_CREATED="msg_created",t.MSG_RECEIVED="msg_received",t.OPTIN_REQUESTED="optin_requested",t.OPTIN_STARTED="optin_started",t.OPTIN_STOPPED="optin_stopped",t.RESTHOOK_CALLED="resthook_called",t.RUN_ENDED="run_ended",t.RUN_RESULT_CHANGED="run_result_changed",t.RUN_STARTED="run_started",t.SERVICE_CALLED="service_called",t.SESSION_TRIGGERED="session_triggered",t.TICKET_ASSIGNEE_CHANGED="ticket_assignee_changed",t.TICKET_CLOSED="ticket_closed",t.TICKET_NOTE_ADDED="ticket_note_added",t.TICKET_OPENED="ticket_opened",t.TICKET_REOPENED="ticket_reopened",t.TICKET_TOPIC_CHANGED="ticket_topic_changed",t.WARNING="warning",t.WEBHOOK_CALLED="webhook_called"}(Ch||(Ch={}));const Sh=(t,e,i)=>{if(1===i.length)return W`<div>${t} <strong>${i[0].name}</strong></div>`;{const t=i.map(t=>t.name);if(2===t.length)return W`<div>
3087
3118
  ${e} <strong>${t[0]}</strong> and <strong>${t[1]}</strong>
3088
- </div>`;{const i=t.pop(),o=t.map((e,i)=>W`<strong>${e}</strong>${i<t.length-1?", ":""}`);return W`<div>${e} ${o}, and <strong>${i}</strong></div>`}}},eh=(t,e)=>{var i;const o=(null===(i=t.ticket)||void 0===i?void 0:i.uuid)||t.ticket_uuid,n=t.note?W`<div
3119
+ </div>`;{const i=t.pop(),o=t.map((e,i)=>W`<strong>${e}</strong>${i<t.length-1?", ":""}`);return W`<div>${e} ${o}, and <strong>${i}</strong></div>`}}},Ah=(t,e)=>{var i;const o=(null===(i=t.ticket)||void 0===i?void 0:i.uuid)||t.ticket_uuid,n=t.note?W`<div
3089
3120
  style="width:85%; background: #fffac3; padding: 1em;margin-bottom: 1em;margin-top:1em; border: 1px solid #ffe97f;border-radius: var(--curvature);line-height: 1.2em; word-break: break-word;"
3090
3121
  >
3091
3122
  <div style="color: #8e830fff; font-size: 1em;margin-bottom:0.25em; ">
@@ -3107,60 +3138,60 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
3107
3138
  </div>`;return W`<div style="${n?"margin-bottom: 1em;":""}">
3108
3139
  ${s}
3109
3140
  </div>
3110
- ${n}`},ih=(t,e)=>{let i=null;switch(t.type){case Jc.ERROR:case Jc.FAILURE:case Jc.WARNING:i=(t=>{if(t.text){let e="⚠️",i="#fff3cd",o="#856404";return"error"===t.type?(e="❗",i="#fee3e3",o="#c01829"):"failure"===t.type&&(e="💥",i="#fee3e3",o="#c01829"),W`<div
3141
+ ${n}`},Eh=(t,e)=>{let i=null;switch(t.type){case Ch.ERROR:case Ch.FAILURE:case Ch.WARNING:i=(t=>{if(t.text){let e="⚠️",i="#fff3cd",o="#856404";return"error"===t.type?(e="❗",i="#fee3e3",o="#c01829"):"failure"===t.type&&(e="💥",i="#fee3e3",o="#c01829"),W`<div
3111
3142
  style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: ${i}; color: ${o}; border-radius: 12px; margin: 4px 18px;"
3112
3143
  >
3113
3144
  <span style="font-size: 16px; line-height: 1.4;">${e}</span>
3114
3145
  <span style="flex: 1; line-height: 1.4;">${t.text}</span>
3115
- </div>`}return null})(t,e);break;case Jc.AIRTIME_TRANSFERRED:i=(t=>0===parseFloat(t.amount)?W`<div>Airtime transfer failed</div>`:W`<div>
3146
+ </div>`}return null})(t,e);break;case Ch.AIRTIME_TRANSFERRED:i=(t=>0===parseFloat(t.amount)?W`<div>Airtime transfer failed</div>`:W`<div>
3116
3147
  Transferred <strong>${t.amount}</strong> ${t.currency} of airtime
3117
- </div>`)(t);break;case Jc.CALL_CREATED:case Jc.CALL_MISSED:case Jc.CALL_RECEIVED:i=(t=>t.type===Jc.CALL_CREATED?W`<div>Call started</div>`:t.type===Jc.CALL_MISSED?W`<div>Call missed</div>`:t.type===Jc.CALL_RECEIVED?W`<div>Call answered</div>`:void 0)(t);break;case Jc.CHAT_STARTED:i=(t=>t.params?W`<div>Chat referral</div>`:W`<div>Chat started</div>`)(t);break;case Jc.CONTACT_FIELD_CHANGED:i=(t=>t.value?W`<div>
3148
+ </div>`)(t);break;case Ch.CALL_CREATED:case Ch.CALL_MISSED:case Ch.CALL_RECEIVED:i=(t=>t.type===Ch.CALL_CREATED?W`<div>Call started</div>`:t.type===Ch.CALL_MISSED?W`<div>Call missed</div>`:t.type===Ch.CALL_RECEIVED?W`<div>Call answered</div>`:void 0)(t);break;case Ch.CHAT_STARTED:i=(t=>t.params?W`<div>Chat referral</div>`:W`<div>Chat started</div>`)(t);break;case Ch.CONTACT_FIELD_CHANGED:i=(t=>t.value?W`<div>
3118
3149
  Updated <strong>${t.field.name}</strong> to
3119
3150
  <strong>${t.value.text}</strong>
3120
- </div>`:W`<div>Cleared <strong>${t.field.name}</strong></div>`)(t);break;case Jc.CONTACT_GROUPS_CHANGED:i=(t=>{const e=t;return e.groups_added?th("Added to group","Added to groups",e.groups_added):e.groups_removed?th("Removed from group","Removed from groups",e.groups_removed):void 0})(t);break;case Jc.CONTACT_LANGUAGE_CHANGED:i=(t=>W`<div>
3151
+ </div>`:W`<div>Cleared <strong>${t.field.name}</strong></div>`)(t);break;case Ch.CONTACT_GROUPS_CHANGED:i=(t=>{const e=t;return e.groups_added?Sh("Added to group","Added to groups",e.groups_added):e.groups_removed?Sh("Removed from group","Removed from groups",e.groups_removed):void 0})(t);break;case Ch.CONTACT_LANGUAGE_CHANGED:i=(t=>W`<div>
3121
3152
  Language updated to <strong>${t.language}</strong>
3122
- </div>`)(t);break;case Jc.CONTACT_NAME_CHANGED:i=(t=>W`<div>
3153
+ </div>`)(t);break;case Ch.CONTACT_NAME_CHANGED:i=(t=>W`<div>
3123
3154
  Updated <strong>name</strong> to <strong>${t.name}</strong>
3124
- </div>`)(t);break;case Jc.CONTACT_STATUS_CHANGED:i=(t=>W`<div>Status updated to <strong>${t.status}</strong></div>`)(t);break;case Jc.CONTACT_URNS_CHANGED:i=(t=>W`<div>
3155
+ </div>`)(t);break;case Ch.CONTACT_STATUS_CHANGED:i=(t=>W`<div>Status updated to <strong>${t.status}</strong></div>`)(t);break;case Ch.CONTACT_URNS_CHANGED:i=(t=>W`<div>
3125
3156
  Updated <strong>URNs</strong> to
3126
3157
  ${ve(t.urns,t=>W`<strong>${t.split(":")[1].split("?")[0]}</strong>`)}
3127
- </div>`)(t);break;case Jc.INPUT_LABELS_ADDED:i=(t=>{const e=t.labels||[];if(e.length>0){const t=e.map(t=>t.name);if(1===t.length)return W`<div>
3158
+ </div>`)(t);break;case Ch.INPUT_LABELS_ADDED:i=(t=>{const e=t.labels||[];if(e.length>0){const t=e.map(t=>t.name);if(1===t.length)return W`<div>
3128
3159
  Message labeled with <strong>${t[0]}</strong>
3129
3160
  </div>`;{const e=t.pop();return W`<div>
3130
3161
  Message labeled with
3131
3162
  ${t.map((e,i)=>W`<strong>${e}</strong>${i<t.length-1?", ":""}`)}
3132
3163
  and <strong>${e}</strong>
3133
- </div>`}}return null})(t);break;case Jc.RUN_RESULT_CHANGED:i=((t,e=!1)=>{const i=String(t.value),o=e?30:100;if(i.length>o){const e=i.substring(0,o)+"...";return W`<div>
3164
+ </div>`}}return null})(t);break;case Ch.RUN_RESULT_CHANGED:i=((t,e=!1)=>{const i=String(t.value),o=e?30:100;if(i.length>o){const e=i.substring(0,o)+"...";return W`<div>
3134
3165
  Set result <strong>${t.name}</strong> to "<span
3135
3166
  title="${i}"
3136
3167
  style="cursor: help; border-bottom: 1px dotted #999;"
3137
3168
  >${e}</span
3138
3169
  >"
3139
- </div>`}return W`<div>Set result <strong>${t.name}</strong> to "${i}"</div>`})(t,e);break;case Jc.OPTIN_REQUESTED:case Jc.OPTIN_STARTED:case Jc.OPTIN_STOPPED:i=(t=>t.type===Jc.OPTIN_REQUESTED?W`<div>
3170
+ </div>`}return W`<div>Set result <strong>${t.name}</strong> to "${i}"</div>`})(t,e);break;case Ch.OPTIN_REQUESTED:case Ch.OPTIN_STARTED:case Ch.OPTIN_STOPPED:i=(t=>t.type===Ch.OPTIN_REQUESTED?W`<div>
3140
3171
  Requested opt-in for <strong>${t.optin.name}</strong>
3141
- </div>`:t.type===Jc.OPTIN_STARTED?W`<div>Opted in to <strong>${t.optin.name}</strong></div>`:t.type===Jc.OPTIN_STOPPED?W`<div>Opted out of <strong>${t.optin.name}</strong></div>`:void 0)(t);break;case Jc.RUN_STARTED:case Jc.RUN_ENDED:case Jc.FLOW_ENTERED:i=(t=>{let e="Started";return t.type===Jc.RUN_ENDED&&(e="completed"===t.status?"Completed":"expired"===t.status?"Expired from":"Interrupted"),W`<div>
3172
+ </div>`:t.type===Ch.OPTIN_STARTED?W`<div>Opted in to <strong>${t.optin.name}</strong></div>`:t.type===Ch.OPTIN_STOPPED?W`<div>Opted out of <strong>${t.optin.name}</strong></div>`:void 0)(t);break;case Ch.RUN_STARTED:case Ch.RUN_ENDED:case Ch.FLOW_ENTERED:i=(t=>{let e="Started";return t.type===Ch.RUN_ENDED&&(e="completed"===t.status?"Completed":"expired"===t.status?"Expired from":"Interrupted"),W`<div>
3142
3173
  ${e}
3143
3174
  <a href="/flow/editor/${t.flow.uuid}/"
3144
3175
  ><strong>${t.flow.name}</strong></a
3145
3176
  >
3146
- </div>`})(t);break;case Jc.EMAIL_CREATED:case Jc.EMAIL_SENT:i=(t=>{const e=t.to||t.addresses||[],i=t.subject;if(e.length>0){const t=e.join(", ");return W`<div>
3177
+ </div>`})(t);break;case Ch.EMAIL_CREATED:case Ch.EMAIL_SENT:i=(t=>{const e=t.to||t.addresses||[],i=t.subject;if(e.length>0){const t=e.join(", ");return W`<div>
3147
3178
  Sent email to <strong>${t}</strong> with subject "${i}"
3148
- </div>`}return null})(t);break;case Jc.BROADCAST_CREATED:i=(t=>{const e=t.translations,i=t.base_language;return e&&e[i]?W`<div>
3179
+ </div>`}return null})(t);break;case Ch.BROADCAST_CREATED:i=(t=>{const e=t.translations,i=t.base_language;return e&&e[i]?W`<div>
3149
3180
  Sent broadcast: "${e[i].text}"
3150
- </div>`:W`<div>Sent broadcast</div>`})(t);break;case Jc.SESSION_TRIGGERED:i=(t=>{const e=t.flow;return e?W`<div>
3181
+ </div>`:W`<div>Sent broadcast</div>`})(t);break;case Ch.SESSION_TRIGGERED:i=(t=>{const e=t.flow;return e?W`<div>
3151
3182
  Started somebody else in <strong>${e.name}</strong>
3152
- </div>`:null})(t);break;case Jc.RESTHOOK_CALLED:i=(t=>W`<div>
3183
+ </div>`:null})(t);break;case Ch.RESTHOOK_CALLED:i=(t=>W`<div>
3153
3184
  Triggered flow event <strong>${t.resthook}</strong>
3154
- </div>`)(t);break;case Jc.WEBHOOK_CALLED:i=(t=>{const e=t.url&&t.url.length>50?t.url.slice(0,50)+"...":t.url;return W`<div>Called <strong>${e}</strong></div>`})(t);break;case Jc.SERVICE_CALLED:i=(t=>{const e=t.service;return"classifier"===e?W`<div>Called classifier</div>`:W`<div>Called <strong>${e}</strong></div>`})(t);break;case Jc.TICKET_ASSIGNEE_CHANGED:i=(t=>t._user?t.assignee?W`<div>
3185
+ </div>`)(t);break;case Ch.WEBHOOK_CALLED:i=(t=>{const e=t.url&&t.url.length>50?t.url.slice(0,50)+"...":t.url;return W`<div>Called <strong>${e}</strong></div>`})(t);break;case Ch.SERVICE_CALLED:i=(t=>{const e=t.service;return"classifier"===e?W`<div>Called classifier</div>`:W`<div>Called <strong>${e}</strong></div>`})(t);break;case Ch.TICKET_ASSIGNEE_CHANGED:i=(t=>t._user?t.assignee?W`<div>
3155
3186
  <strong>${t._user.name}</strong> assigned this ticket to
3156
3187
  <strong>${t.assignee.name}</strong>
3157
3188
  </div>`:W`<div>
3158
3189
  <strong>${t._user.name}</strong> unassigned this ticket
3159
3190
  </div>`:t.assignee?W`<div>
3160
3191
  This ticket was assigned to <strong>${t.assignee.name}</strong>
3161
- </div>`:W`<div>This ticket was unassigned</div>`)(t);break;case Jc.TICKET_CLOSED:i=eh(t,"closed");break;case Jc.TICKET_OPENED:i=eh(t,"opened");break;case Jc.TICKET_NOTE_ADDED:i=eh(t,"noted");break;case Jc.TICKET_REOPENED:i=eh(t,"reopened");break;case Jc.TICKET_TOPIC_CHANGED:i=W`<div>
3192
+ </div>`:W`<div>This ticket was unassigned</div>`)(t);break;case Ch.TICKET_CLOSED:i=Ah(t,"closed");break;case Ch.TICKET_OPENED:i=Ah(t,"opened");break;case Ch.TICKET_NOTE_ADDED:i=Ah(t,"noted");break;case Ch.TICKET_REOPENED:i=Ah(t,"reopened");break;case Ch.TICKET_TOPIC_CHANGED:i=W`<div>
3162
3193
  Topic changed to <strong>${t.topic.name}</strong>
3163
- </div>`;break;default:return null}if(null===i)return null;return W`<div style="font-size: ${e?"11px":"14px"}">${i}</div>`};class oh extends Pc{static get styles(){return a`
3194
+ </div>`;break;default:return null}if(null===i)return null;return W`<div style="font-size: ${e?"11px":"14px"}">${i}</div>`};class $h extends ah{static get styles(){return a`
3164
3195
  :host {
3165
3196
  flex-grow: 1;
3166
3197
  display: flex;
@@ -3520,7 +3551,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
3520
3551
  temba-button {
3521
3552
  --button-border: 1px solid #ddd;
3522
3553
  }
3523
- `}set showMessageLogsAfter(t){const e=this._showMessageLogsAfter;this._showMessageLogsAfter=t?new Date(t):null,this.requestUpdate("showMessageLogsAfter",e)}get showMessageLogsAfter(){return this._showMessageLogsAfter}constructor(){super(),this.contactsEndpoint="/api/v2/contacts.json",this.currentNote="",this.showDetails=!0,this.currentTicket=null,this.currentContact=null,this.agent="",this.blockFetching=!1,this.showInterrupt=!1,this.disableAssign=!1,this.disableReply=!1,this.showSearch=!1,this.avatar=kl,this._showMessageLogsAfter=null,this.searchMode=!1,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchFocused=!1,this.searchClosing=!1,this.searchNoResults=!1,this.ticket=null,this.beforeUUID=null,this.afterUUID=null,this.refreshId=null,this.polling=!1,this.pollingInterval=2e3,this.lastFetchTime=null,this.lastSearchedQuery="",this.blockFetchingNewer=!1,this.fetchingNewer=!1}willUpdate(t){if(super.willUpdate(t),t.has("data")&&(this.currentContact=this.data),t.has("currentContact")&&this.currentContact){const e=t.get("currentContact");this.currentContact.uuid!==(null==e?void 0:e.uuid)&&(this.blockFetching=!1,this.errorMessage=null)}}firstUpdated(t){super.firstUpdated(t)}connectedCallback(){super.connectedCallback(),this.chat=this.shadowRoot.querySelector("temba-chat")}disconnectedCallback(){super.disconnectedCallback(),this.refreshId&&clearInterval(this.refreshId)}updated(t){var e;super.updated(t),(t.has("data")||t.has("currentContact"))&&this.refreshId&&(clearTimeout(this.refreshId),this.refreshId=null),t.has("currentContact")&&this.currentContact&&(this.chat=this.shadowRoot.querySelector("temba-chat"),this.currentContact.uuid!==(null===(e=t.get("currentContact"))||void 0===e?void 0:e.uuid)?this.reset():setTimeout(()=>this.checkForNewMessages(),500),this.fetchPreviousMessages())}reset(){this.chat&&this.chat.reset(),this.ticket=null,this.beforeUUID=null,this.afterUUID=null,this.refreshId=null,this.polling=!1,this.pollingInterval=2e3,this.lastFetchTime=null;const t=this.shadowRoot.querySelector("temba-compose");t&&t.reset()}handleSearchToggle(){this.searchMode?this.handleSearchClose():(this.searchMode=!0,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchNoResults=!1,this.refreshId&&(clearTimeout(this.refreshId),this.refreshId=null),window.setTimeout(()=>{const t=this.shadowRoot.querySelector(".search-input");t&&t.focus()},50))}handleSearchClose(){this.searchClosing=!0,window.setTimeout(()=>{this.searchClosing=!1,this.searchMode=!1,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchNoResults=!1,this.lastSearchedQuery="";const t=this.chat;t&&(t.searchHighlight=null,t.highlightMessageUuid=null,t.reset(),this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null,this.fetchPreviousMessages())},150)}handleSearchInput(t){const e=t.target;this.searchQuery=e.value}handleSearchKeydown(t){if("Enter"===t.key){t.preventDefault();this.searchQuery.trim()!==this.lastSearchedQuery?this.executeSearch():t.shiftKey?this.handleSearchPrev():this.handleSearchNext()}else"Escape"===t.key&&(this.handleSearchClose(),t.preventDefault())}executeSearch(){const t=this.searchQuery.trim();if(!t||!this.currentContact||this.searchLoading)return;this.searchLoading=!0,this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1,this.lastSearchedQuery=t,this.chat&&(this.chat.searchHighlight=null,this.chat.highlightMessageUuid=null,this.chat.reset());const e=`/contact/chat_search/${this.currentContact.uuid}/?text=${encodeURIComponent(t)}`;se(e).then(t=>{this.searchLoading=!1,this.searchResults=t.json.results||[],this.searchResults.length>0?(this.searchNoResults=!1,this.searchIndex=0,this.navigateToResult(0)):(this.searchNoResults=!0,this.searchIndex=-1)}).catch(()=>{this.searchLoading=!1,this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1})}navigateToResult(t){var e,i;if(t<0||t>=this.searchResults.length)return;this.searchIndex=t;const o=this.searchResults[t];if(!this.chat)return;const n=this.getEndpoint();if(!n)return;this.chat.searchHighlight=this.searchQuery.trim();const s=nh(n,null===(e=this.currentTicket)||void 0===e?void 0:e.uuid,o.uuid,null),r=nh(n,null===(i=this.currentTicket)||void 0===i?void 0:i.uuid,null,o.uuid);this.chat.style.opacity="0",window.setTimeout(()=>{this.chat.style.visibility="hidden",this.chat.reset(),this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null;const t={...o,created_on:new Date(o.created_on)};let e=!1;Promise.all([s,r]).then(([i,n])=>{const s=this.createMessages(n);s.reverse();const r=this.createMessages(i);r.reverse();const a={events:[t],next:null},l=this.createMessages(a);if(l.reverse(),i.next)this.beforeUUID=i.next;else if(r.length>0){const t=i.events[i.events.length-1];this.beforeUUID=t.uuid}else{this.blockFetching=!0;const t=[...s,...l];if(t.length>0){const e=t[t.length-1];this.chat.setEndOfHistory(new Date(e.created_on))}}const d=[...r,...l,...s];this.chat.loadMessages(d),e=!0,this.chat.updateComplete.then(()=>{window.setTimeout(()=>{var t,e;if(!this.chat)return;this.chat.highlightMessageUuid=o.uuid;const i=null===(t=this.chat.shadowRoot)||void 0===t?void 0:t.querySelector(".scroll"),n=null===(e=this.chat.shadowRoot)||void 0===e?void 0:e.querySelector(`.row[data-uuid="${o.uuid}"]`);if(i&&n){const t=i.getBoundingClientRect(),e=n.getBoundingClientRect(),o=e.top+e.height/2-(t.top+t.height/2);i.scrollTop=i.scrollTop+o}else i&&(i.scrollTop=0);window.setTimeout(()=>{this.chat&&(this.chat.style.visibility="visible",this.chat.style.opacity="0",window.setTimeout(()=>{this.chat&&(this.chat.style.opacity="1")},16))},16)},16)})}).catch(()=>{this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null,this.fetchPreviousMessages()}).finally(()=>{!e&&this.chat&&(this.chat.style.visibility="visible",this.chat.style.opacity="1")})},120)}handleSearchPrev(){if(0===this.searchResults.length)return;const t=this.searchIndex<=0?this.searchResults.length-1:this.searchIndex-1;this.navigateToResult(t)}handleSearchNext(){if(0===this.searchResults.length)return;const t=this.searchIndex>=this.searchResults.length-1?0:this.searchIndex+1;this.navigateToResult(t)}handleInterrupt(){this.fireCustomEvent(Io.Interrupt,{contact:this.currentContact})}handleRetry(){this.shadowRoot.querySelector("temba-compose").triggerSend()}handleSend(t){this.errorMessage=null;const e=t.currentTarget,i=t.detail.langValues.und,o={contact:this.currentContact.uuid},n=i.text;n&&n.length>0&&(o.text=n);const s=i.attachments;if(s&&s.length>0){const t=s.map(t=>t.uuid);o.attachments=t}this.currentTicket&&(o.ticket=this.currentTicket.uuid);const r="Send failed, please try again.";ue(`/contact/chat/${this.currentContact.uuid}/`,o).then(t=>{if(t.status<400){const i=t.json.event;i.created_on=new Date(i.created_on),this.chat.addMessages([i],null,!0),this.pollingInterval=2e3,this.checkForNewMessages(),e.reset(),this.fireCustomEvent(Io.MessageSent,{msg:o,response:t})}else this.errorMessage=r}).catch(()=>{this.errorMessage=r})}getEndpoint(){return this.contact?`/contact/chat/${this.contact}/`:null}scheduleRefresh(t=!1){this.refreshId&&(clearTimeout(this.refreshId),this.refreshId=null),this.pollingInterval=t?2e3:Math.min(this.pollingInterval+1e3,15e3),this.refreshId=setTimeout(()=>{this.checkForNewMessages()},this.pollingInterval)}prerender(t){const e=ih(t,!1);e&&(t._rendered={html:e,type:Yc.Inline})}createMessages(t){if(t.events){const e=[];return t.events.forEach(t=>{(!this.afterUUID||t.uuid.toLowerCase()>this.afterUUID.toLowerCase())&&(this.afterUUID=t.uuid),t.created_on=new Date(t.created_on),"msg_created"===t.type||"msg_received"===t.type||"ivr_created"===t.type?e.push(t):(this.prerender(t),t._rendered&&e.push(t))}),e.filter(t=>!!t)}return[]}checkForNewMessages(){var t;if(this.polling||this.searchMode)return;const e=this.chat;if(this.currentContact&&this.afterUUID){this.polling=!0,this.lastFetchTime=Date.now();const i=this.getEndpoint();if(!i)return;const o=this.currentContact.uuid;nh(i,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,null,this.afterUUID).then(t=>{const i=this.createMessages(t);if(i.reverse(),o===this.currentContact.uuid){const t=i.length>0;e.addMessages(i,null,!0),this.polling=!1,this.scheduleRefresh(t)}else this.polling=!1})}}fetchPreviousMessages(){var t;const e=this.chat,i=this;if(e&&!e.fetching&&!i.blockFetching&&(e.fetching=!0,this.currentContact)){const o=this.getEndpoint();if(!o)return;if(!this.beforeUUID&&!this.afterUUID){const t=Jt();this.beforeUUID=t,this.afterUUID=t}nh(o,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,this.beforeUUID,null).then(t=>{const o=this.createMessages(t);if(o.reverse(),0===o.length)i.blockFetching=!0;else if(t.next)this.beforeUUID=t.next;else if(i.blockFetching=!0,t.events&&t.events.length>0){const i=t.events[t.events.length-1];e.setEndOfHistory(new Date(i.created_on))}e.addMessages(o),this.searchMode||this.scheduleRefresh()})}}fetchComplete(){this.chat&&(this.chat.fetching=!1),this.fetchingNewer=!1}fetchNewerMessages(){var t;if(!this.searchMode||!this.afterUUID||!this.chat||this.fetchingNewer||this.blockFetchingNewer)return;this.fetchingNewer=!0;const e=this.getEndpoint();e?nh(e,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,null,this.afterUUID).then(t=>{if(!this.chat)return void(this.fetchingNewer=!1);const e=this.createMessages(t);if(e.reverse(),0===e.length)return this.blockFetchingNewer=!0,void(this.fetchingNewer=!1);this.chat.addMessages(e,null,!0,!0)}).catch(()=>{this.fetchingNewer=!1}):this.fetchingNewer=!1}getTembaCompose(){return this.currentTicket?this.currentContact&&"active"!==this.currentContact.status||this.currentTicket.closed_on?null:!this.disableReply||this.currentTicket.assignee&&this.currentTicket.assignee.email===this.agent?this.getCompose():null:this.currentContact&&"active"!==this.currentContact.status?null:this.getCompose()}getCompose(){return W`<div class="border"></div>
3554
+ `}set showMessageLogsAfter(t){const e=this._showMessageLogsAfter;this._showMessageLogsAfter=t?new Date(t):null,this.requestUpdate("showMessageLogsAfter",e)}get showMessageLogsAfter(){return this._showMessageLogsAfter}constructor(){super(),this.contactsEndpoint="/api/v2/contacts.json",this.currentNote="",this.showDetails=!0,this.currentTicket=null,this.currentContact=null,this.agent="",this.blockFetching=!1,this.showInterrupt=!1,this.disableAssign=!1,this.disableReply=!1,this.showSearch=!1,this.avatar=kl,this._showMessageLogsAfter=null,this.searchMode=!1,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchFocused=!1,this.searchClosing=!1,this.searchNoResults=!1,this.ticket=null,this.beforeUUID=null,this.afterUUID=null,this.refreshId=null,this.polling=!1,this.pollingInterval=2e3,this.lastFetchTime=null,this.lastSearchedQuery="",this.blockFetchingNewer=!1,this.fetchingNewer=!1}willUpdate(t){if(super.willUpdate(t),t.has("data")&&(this.currentContact=this.data),t.has("currentContact")&&this.currentContact){const e=t.get("currentContact");this.currentContact.uuid!==(null==e?void 0:e.uuid)&&(this.blockFetching=!1,this.errorMessage=null)}}firstUpdated(t){super.firstUpdated(t)}connectedCallback(){super.connectedCallback(),this.chat=this.shadowRoot.querySelector("temba-chat")}disconnectedCallback(){super.disconnectedCallback(),this.refreshId&&clearInterval(this.refreshId)}updated(t){var e;super.updated(t),(t.has("data")||t.has("currentContact"))&&this.refreshId&&(clearTimeout(this.refreshId),this.refreshId=null),t.has("currentContact")&&this.currentContact&&(this.chat=this.shadowRoot.querySelector("temba-chat"),this.currentContact.uuid!==(null===(e=t.get("currentContact"))||void 0===e?void 0:e.uuid)?this.reset():setTimeout(()=>this.checkForNewMessages(),500),this.fetchPreviousMessages())}reset(){this.chat&&this.chat.reset(),this.ticket=null,this.beforeUUID=null,this.afterUUID=null,this.refreshId=null,this.polling=!1,this.pollingInterval=2e3,this.lastFetchTime=null;const t=this.shadowRoot.querySelector("temba-compose");t&&t.reset()}handleSearchToggle(){this.searchMode?this.handleSearchClose():(this.searchMode=!0,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchNoResults=!1,this.refreshId&&(clearTimeout(this.refreshId),this.refreshId=null),window.setTimeout(()=>{const t=this.shadowRoot.querySelector(".search-input");t&&t.focus()},50))}handleSearchClose(){this.searchClosing=!0,window.setTimeout(()=>{this.searchClosing=!1,this.searchMode=!1,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchNoResults=!1,this.lastSearchedQuery="";const t=this.chat;t&&(t.searchHighlight=null,t.highlightMessageUuid=null,t.reset(),this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null,this.fetchPreviousMessages())},150)}handleSearchInput(t){const e=t.target;this.searchQuery=e.value}handleSearchKeydown(t){if("Enter"===t.key){t.preventDefault();this.searchQuery.trim()!==this.lastSearchedQuery?this.executeSearch():t.shiftKey?this.handleSearchPrev():this.handleSearchNext()}else"Escape"===t.key&&(this.handleSearchClose(),t.preventDefault())}executeSearch(){const t=this.searchQuery.trim();if(!t||!this.currentContact||this.searchLoading)return;this.searchLoading=!0,this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1,this.lastSearchedQuery=t,this.chat&&(this.chat.searchHighlight=null,this.chat.highlightMessageUuid=null,this.chat.reset());const e=`/contact/chat_search/${this.currentContact.uuid}/?text=${encodeURIComponent(t)}`;se(e).then(t=>{this.searchLoading=!1,this.searchResults=t.json.results||[],this.searchResults.length>0?(this.searchNoResults=!1,this.searchIndex=0,this.navigateToResult(0)):(this.searchNoResults=!0,this.searchIndex=-1)}).catch(()=>{this.searchLoading=!1,this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1})}navigateToResult(t){var e,i;if(t<0||t>=this.searchResults.length)return;this.searchIndex=t;const o=this.searchResults[t];if(!this.chat)return;const n=this.getEndpoint();if(!n)return;this.chat.searchHighlight=this.searchQuery.trim();const s=Th(n,null===(e=this.currentTicket)||void 0===e?void 0:e.uuid,o.uuid,null),r=Th(n,null===(i=this.currentTicket)||void 0===i?void 0:i.uuid,null,o.uuid);this.chat.style.opacity="0",window.setTimeout(()=>{this.chat.style.visibility="hidden",this.chat.reset(),this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null;const t={...o,created_on:new Date(o.created_on)};let e=!1;Promise.all([s,r]).then(([i,n])=>{const s=this.createMessages(n);s.reverse();const r=this.createMessages(i);r.reverse();const a={events:[t],next:null},l=this.createMessages(a);if(l.reverse(),i.next)this.beforeUUID=i.next;else if(r.length>0){const t=i.events[i.events.length-1];this.beforeUUID=t.uuid}else{this.blockFetching=!0;const t=[...s,...l];if(t.length>0){const e=t[t.length-1];this.chat.setEndOfHistory(new Date(e.created_on))}}const d=[...r,...l,...s];this.chat.loadMessages(d),e=!0,this.chat.updateComplete.then(()=>{window.setTimeout(()=>{var t,e;if(!this.chat)return;this.chat.highlightMessageUuid=o.uuid;const i=null===(t=this.chat.shadowRoot)||void 0===t?void 0:t.querySelector(".scroll"),n=null===(e=this.chat.shadowRoot)||void 0===e?void 0:e.querySelector(`.row[data-uuid="${o.uuid}"]`);if(i&&n){const t=i.getBoundingClientRect(),e=n.getBoundingClientRect(),o=e.top+e.height/2-(t.top+t.height/2);i.scrollTop=i.scrollTop+o}else i&&(i.scrollTop=0);window.setTimeout(()=>{this.chat&&(this.chat.style.visibility="visible",this.chat.style.opacity="0",window.setTimeout(()=>{this.chat&&(this.chat.style.opacity="1")},16))},16)},16)})}).catch(()=>{this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null,this.fetchPreviousMessages()}).finally(()=>{!e&&this.chat&&(this.chat.style.visibility="visible",this.chat.style.opacity="1")})},120)}handleSearchPrev(){if(0===this.searchResults.length)return;const t=this.searchIndex<=0?this.searchResults.length-1:this.searchIndex-1;this.navigateToResult(t)}handleSearchNext(){if(0===this.searchResults.length)return;const t=this.searchIndex>=this.searchResults.length-1?0:this.searchIndex+1;this.navigateToResult(t)}handleInterrupt(){this.fireCustomEvent(Io.Interrupt,{contact:this.currentContact})}handleRetry(){this.shadowRoot.querySelector("temba-compose").triggerSend()}handleSend(t){this.errorMessage=null;const e=t.currentTarget,i=t.detail.langValues.und,o={contact:this.currentContact.uuid},n=i.text;n&&n.length>0&&(o.text=n);const s=i.attachments;if(s&&s.length>0){const t=s.map(t=>t.uuid);o.attachments=t}this.currentTicket&&(o.ticket=this.currentTicket.uuid);const r="Send failed, please try again.";ue(`/contact/chat/${this.currentContact.uuid}/`,o).then(t=>{if(t.status<400){const i=t.json.event;i.created_on=new Date(i.created_on),this.chat.addMessages([i],null,!0),this.pollingInterval=2e3,this.checkForNewMessages(),e.reset(),this.fireCustomEvent(Io.MessageSent,{msg:o,response:t})}else this.errorMessage=r}).catch(()=>{this.errorMessage=r})}getEndpoint(){return this.contact?`/contact/chat/${this.contact}/`:null}scheduleRefresh(t=!1){this.refreshId&&(clearTimeout(this.refreshId),this.refreshId=null),this.pollingInterval=t?2e3:Math.min(this.pollingInterval+1e3,15e3),this.refreshId=setTimeout(()=>{this.checkForNewMessages()},this.pollingInterval)}prerender(t){const e=Eh(t,!1);e&&(t._rendered={html:e,type:yh.Inline})}createMessages(t){if(t.events){const e=[];return t.events.forEach(t=>{(!this.afterUUID||t.uuid.toLowerCase()>this.afterUUID.toLowerCase())&&(this.afterUUID=t.uuid),t.created_on=new Date(t.created_on),"msg_created"===t.type||"msg_received"===t.type||"ivr_created"===t.type?e.push(t):(this.prerender(t),t._rendered&&e.push(t))}),e.filter(t=>!!t)}return[]}checkForNewMessages(){var t;if(this.polling||this.searchMode)return;const e=this.chat;if(this.currentContact&&this.afterUUID){this.polling=!0,this.lastFetchTime=Date.now();const i=this.getEndpoint();if(!i)return;const o=this.currentContact.uuid;Th(i,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,null,this.afterUUID).then(t=>{const i=this.createMessages(t);if(i.reverse(),o===this.currentContact.uuid){const t=i.length>0;e.addMessages(i,null,!0),this.polling=!1,this.scheduleRefresh(t)}else this.polling=!1})}}fetchPreviousMessages(){var t;const e=this.chat,i=this;if(e&&!e.fetching&&!i.blockFetching&&(e.fetching=!0,this.currentContact)){const o=this.getEndpoint();if(!o)return;if(!this.beforeUUID&&!this.afterUUID){const t=Jt();this.beforeUUID=t,this.afterUUID=t}Th(o,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,this.beforeUUID,null).then(t=>{const o=this.createMessages(t);if(o.reverse(),0===o.length)i.blockFetching=!0;else if(t.next)this.beforeUUID=t.next;else if(i.blockFetching=!0,t.events&&t.events.length>0){const i=t.events[t.events.length-1];e.setEndOfHistory(new Date(i.created_on))}e.addMessages(o),this.searchMode||this.scheduleRefresh()})}}fetchComplete(){this.chat&&(this.chat.fetching=!1),this.fetchingNewer=!1}fetchNewerMessages(){var t;if(!this.searchMode||!this.afterUUID||!this.chat||this.fetchingNewer||this.blockFetchingNewer)return;this.fetchingNewer=!0;const e=this.getEndpoint();e?Th(e,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,null,this.afterUUID).then(t=>{if(!this.chat)return void(this.fetchingNewer=!1);const e=this.createMessages(t);if(e.reverse(),0===e.length)return this.blockFetchingNewer=!0,void(this.fetchingNewer=!1);this.chat.addMessages(e,null,!0,!0)}).catch(()=>{this.fetchingNewer=!1}):this.fetchingNewer=!1}getTembaCompose(){return this.currentTicket?this.currentContact&&"active"!==this.currentContact.status||this.currentTicket.closed_on?null:!this.disableReply||this.currentTicket.assignee&&this.currentTicket.assignee.email===this.agent?this.getCompose():null:this.currentContact&&"active"!==this.currentContact.status?null:this.getCompose()}getCompose(){return W`<div class="border"></div>
3524
3555
  <div class="compose">
3525
3556
  <temba-compose
3526
3557
  attachments
@@ -3677,7 +3708,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
3677
3708
  </div>
3678
3709
  </div> `:null}
3679
3710
  ${this.getTembaCompose()}`:null}
3680
- </div>`}}t([mt({type:String,attribute:"ticket"})],oh.prototype,"ticketUUID",void 0),t([mt({type:String})],oh.prototype,"contactsEndpoint",void 0),t([mt({type:String})],oh.prototype,"currentNote",void 0),t([mt({type:Boolean})],oh.prototype,"showDetails",void 0),t([mt({type:Object})],oh.prototype,"currentTicket",void 0),t([mt({type:Object})],oh.prototype,"currentContact",void 0),t([mt({type:String})],oh.prototype,"agent",void 0),t([mt({type:Boolean})],oh.prototype,"blockFetching",void 0),t([mt({type:Boolean})],oh.prototype,"showInterrupt",void 0),t([mt({type:Boolean})],oh.prototype,"disableAssign",void 0),t([mt({type:Boolean})],oh.prototype,"disableReply",void 0),t([mt({type:Boolean})],oh.prototype,"showSearch",void 0),t([mt({type:String})],oh.prototype,"avatar",void 0),t([mt({type:String})],oh.prototype,"showMessageLogsAfter",null),t([mt({type:String})],oh.prototype,"errorMessage",void 0),t([mt({type:Boolean,attribute:!1})],oh.prototype,"searchMode",void 0),t([mt({type:String,attribute:!1})],oh.prototype,"searchQuery",void 0),t([mt({type:Array,attribute:!1})],oh.prototype,"searchResults",void 0),t([mt({type:Number,attribute:!1})],oh.prototype,"searchIndex",void 0),t([mt({type:Boolean,attribute:!1})],oh.prototype,"searchLoading",void 0),t([mt({type:Boolean,attribute:!1})],oh.prototype,"searchFocused",void 0),t([mt({type:Boolean,attribute:!1})],oh.prototype,"searchClosing",void 0),t([mt({type:Boolean,attribute:!1})],oh.prototype,"searchNoResults",void 0);const nh=(t,e=void 0,i=void 0,o=void 0)=>new Promise(n=>{const s={events:[],next:null},r=new AbortController;sh.push(r);const a=()=>{sh=sh.filter(t=>t!==r)};let l=t;const d=[];i&&d.push(`before=${i}`),o&&d.push(`after=${o}`),e&&d.push(`ticket=${e}`),d.length>0&&(l+=(l.includes("?")?"&":"?")+d.join("&")),se(l,r).then(t=>{a();const e=t.json;n(e||s)}).catch(()=>{a(),n(s)})});let sh=[];class rh extends Be{static get styles(){return a`
3711
+ </div>`}}t([mt({type:String,attribute:"ticket"})],$h.prototype,"ticketUUID",void 0),t([mt({type:String})],$h.prototype,"contactsEndpoint",void 0),t([mt({type:String})],$h.prototype,"currentNote",void 0),t([mt({type:Boolean})],$h.prototype,"showDetails",void 0),t([mt({type:Object})],$h.prototype,"currentTicket",void 0),t([mt({type:Object})],$h.prototype,"currentContact",void 0),t([mt({type:String})],$h.prototype,"agent",void 0),t([mt({type:Boolean})],$h.prototype,"blockFetching",void 0),t([mt({type:Boolean})],$h.prototype,"showInterrupt",void 0),t([mt({type:Boolean})],$h.prototype,"disableAssign",void 0),t([mt({type:Boolean})],$h.prototype,"disableReply",void 0),t([mt({type:Boolean})],$h.prototype,"showSearch",void 0),t([mt({type:String})],$h.prototype,"avatar",void 0),t([mt({type:String})],$h.prototype,"showMessageLogsAfter",null),t([mt({type:String})],$h.prototype,"errorMessage",void 0),t([mt({type:Boolean,attribute:!1})],$h.prototype,"searchMode",void 0),t([mt({type:String,attribute:!1})],$h.prototype,"searchQuery",void 0),t([mt({type:Array,attribute:!1})],$h.prototype,"searchResults",void 0),t([mt({type:Number,attribute:!1})],$h.prototype,"searchIndex",void 0),t([mt({type:Boolean,attribute:!1})],$h.prototype,"searchLoading",void 0),t([mt({type:Boolean,attribute:!1})],$h.prototype,"searchFocused",void 0),t([mt({type:Boolean,attribute:!1})],$h.prototype,"searchClosing",void 0),t([mt({type:Boolean,attribute:!1})],$h.prototype,"searchNoResults",void 0);const Th=(t,e=void 0,i=void 0,o=void 0)=>new Promise(n=>{const s={events:[],next:null},r=new AbortController;Dh.push(r);const a=()=>{Dh=Dh.filter(t=>t!==r)};let l=t;const d=[];i&&d.push(`before=${i}`),o&&d.push(`after=${o}`),e&&d.push(`ticket=${e}`),d.length>0&&(l+=(l.includes("?")?"&":"?")+d.join("&")),se(l,r).then(t=>{a();const e=t.json;n(e||s)}).catch(()=>{a(),n(s)})});let Dh=[];class Mh extends Be{static get styles(){return a`
3681
3712
  temba-options {
3682
3713
  display: block;
3683
3714
  width: 100%;
@@ -3704,7 +3735,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
3704
3735
  <slot></slot>
3705
3736
  </temba-options>
3706
3737
  ${this.renderFooter()}
3707
- `}}t([mt({type:Array,attribute:!1})],rh.prototype,"items",void 0),t([mt({type:Object,attribute:!1})],rh.prototype,"selected",void 0),t([mt({type:Number})],rh.prototype,"cursorIndex",void 0),t([mt({type:String})],rh.prototype,"endpoint",void 0),t([mt({type:String})],rh.prototype,"nextSelection",void 0),t([mt({type:Number})],rh.prototype,"tabIndex",void 0),t([mt({type:String})],rh.prototype,"valueKey",void 0),t([mt({type:String})],rh.prototype,"value",void 0),t([mt({type:Boolean})],rh.prototype,"loading",void 0),t([mt({type:Boolean})],rh.prototype,"collapsed",void 0),t([mt({type:Boolean})],rh.prototype,"hideShadow",void 0),t([mt({type:Boolean})],rh.prototype,"paused",void 0),t([mt({type:Boolean})],rh.prototype,"internalFocusDisabled",void 0),t([mt({attribute:!1})],rh.prototype,"getNextRefresh",void 0),t([mt({attribute:!1})],rh.prototype,"sanitizeOption",void 0),t([mt({attribute:!1})],rh.prototype,"renderOption",void 0),t([mt({attribute:!1})],rh.prototype,"renderOptionDetail",void 0),t([mt({attribute:!1,type:Object})],rh.prototype,"mostRecentItem",void 0),t([mt({type:String})],rh.prototype,"refreshKey",void 0);class ah extends rh{getRefreshEndpoint(){if(this.items.length>0){const t=this.items[0].ticket.last_activity_on,e=this.endpoint.includes("?")?"&":"?";return this.endpoint+e+"after="+1e3*new Date(t).getTime()}return this.endpoint}sanitizeResults(t){return new Promise(e=>{const i=t;this.store.resolveUsers(i,["ticket.assignee"]).then(()=>{e(i)})})}constructor(){super(),this.agent="",this.valueKey="ticket.uuid",this.renderOption=t=>W`
3738
+ `}}t([mt({type:Array,attribute:!1})],Mh.prototype,"items",void 0),t([mt({type:Object,attribute:!1})],Mh.prototype,"selected",void 0),t([mt({type:Number})],Mh.prototype,"cursorIndex",void 0),t([mt({type:String})],Mh.prototype,"endpoint",void 0),t([mt({type:String})],Mh.prototype,"nextSelection",void 0),t([mt({type:Number})],Mh.prototype,"tabIndex",void 0),t([mt({type:String})],Mh.prototype,"valueKey",void 0),t([mt({type:String})],Mh.prototype,"value",void 0),t([mt({type:Boolean})],Mh.prototype,"loading",void 0),t([mt({type:Boolean})],Mh.prototype,"collapsed",void 0),t([mt({type:Boolean})],Mh.prototype,"hideShadow",void 0),t([mt({type:Boolean})],Mh.prototype,"paused",void 0),t([mt({type:Boolean})],Mh.prototype,"internalFocusDisabled",void 0),t([mt({attribute:!1})],Mh.prototype,"getNextRefresh",void 0),t([mt({attribute:!1})],Mh.prototype,"sanitizeOption",void 0),t([mt({attribute:!1})],Mh.prototype,"renderOption",void 0),t([mt({attribute:!1})],Mh.prototype,"renderOptionDetail",void 0),t([mt({attribute:!1,type:Object})],Mh.prototype,"mostRecentItem",void 0),t([mt({type:String})],Mh.prototype,"refreshKey",void 0);class zh extends Mh{getRefreshEndpoint(){if(this.items.length>0){const t=this.items[0].ticket.last_activity_on,e=this.endpoint.includes("?")?"&":"?";return this.endpoint+e+"after="+1e3*new Date(t).getTime()}return this.endpoint}sanitizeResults(t){return new Promise(e=>{const i=t;this.store.resolveUsers(i,["ticket.assignee"]).then(()=>{e(i)})})}constructor(){super(),this.agent="",this.valueKey="ticket.uuid",this.renderOption=t=>W`
3708
3739
  <div
3709
3740
  style="align-items:center; margin-top: 0.1em; margin-bottom: 0.1em"
3710
3741
  >
@@ -3758,7 +3789,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
3758
3789
  ></temba-date>
3759
3790
  </div>
3760
3791
  </div>
3761
- `}}t([mt({type:String})],ah.prototype,"agent",void 0);const lh={active:"Active",blocked:"Blocked",stopped:"Stopped",archived:"Archived"},dh={tel:"Phone",whatsapp:"WhatsApp",fcm:"Firebase Cloud Messaging",twitter:"Twitter"};class ch extends dt{constructor(){super(...arguments),this.level="info"}static get styles(){return a`
3792
+ `}}t([mt({type:String})],zh.prototype,"agent",void 0);const Ih={active:"Active",blocked:"Blocked",stopped:"Stopped",archived:"Archived"},Lh={tel:"Phone",whatsapp:"WhatsApp",fcm:"Firebase Cloud Messaging",twitter:"Twitter"};class Oh extends dt{constructor(){super(...arguments),this.level="info"}static get styles(){return a`
3762
3793
  :host {
3763
3794
  display: block;
3764
3795
  }
@@ -3790,7 +3821,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
3790
3821
  }
3791
3822
  `}render(){return W`
3792
3823
  <div class="temba-alert temba-${this.level}"><slot></slot></div>
3793
- `}}t([mt({type:String})],ch.prototype,"level",void 0);class hh extends _o{constructor(){super(...arguments),this.placeholder="",this.name="",this.query="",this.inactiveThreshold=1e3,this.inactiveDays=90,this.recipients=[],this.advanced=!1,this.refreshKey="0",this.exclusions={},this.initialized=!1}static get styles(){return a`
3824
+ `}}t([mt({type:String})],Oh.prototype,"level",void 0);class Ph extends _o{constructor(){super(...arguments),this.placeholder="",this.name="",this.query="",this.inactiveThreshold=1e3,this.inactiveDays=90,this.recipients=[],this.advanced=!1,this.refreshKey="0",this.exclusions={},this.initialized=!1}static get styles(){return a`
3794
3825
  :host {
3795
3826
  color: var(--color-text);
3796
3827
  }
@@ -4134,7 +4165,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
4134
4165
  >`):""}
4135
4166
 
4136
4167
 
4137
- `}}t([mt({type:Boolean})],hh.prototype,"in_a_flow",void 0),t([mt({type:Boolean})],hh.prototype,"started_previously",void 0),t([mt({type:Boolean})],hh.prototype,"not_seen_since_days",void 0),t([mt({type:Boolean})],hh.prototype,"fetching",void 0),t([mt({type:Boolean})],hh.prototype,"expanded",void 0),t([mt({type:String})],hh.prototype,"endpoint",void 0),t([mt({type:String})],hh.prototype,"placeholder",void 0),t([mt({type:String})],hh.prototype,"name",void 0),t([mt({type:String})],hh.prototype,"query",void 0),t([mt({type:Number})],hh.prototype,"inactiveThreshold",void 0),t([mt({type:Number})],hh.prototype,"inactiveDays",void 0),t([mt({type:Object,attribute:!1})],hh.prototype,"summary",void 0),t([mt({type:Object,attribute:!1})],hh.prototype,"flow",void 0),t([mt({type:Array})],hh.prototype,"recipients",void 0),t([mt({type:Boolean})],hh.prototype,"advanced",void 0),t([mt({type:String})],hh.prototype,"refreshKey",void 0),t([mt({type:Object})],hh.prototype,"exclusions",void 0);class uh extends dt{static get styles(){return a`
4168
+ `}}t([mt({type:Boolean})],Ph.prototype,"in_a_flow",void 0),t([mt({type:Boolean})],Ph.prototype,"started_previously",void 0),t([mt({type:Boolean})],Ph.prototype,"not_seen_since_days",void 0),t([mt({type:Boolean})],Ph.prototype,"fetching",void 0),t([mt({type:Boolean})],Ph.prototype,"expanded",void 0),t([mt({type:String})],Ph.prototype,"endpoint",void 0),t([mt({type:String})],Ph.prototype,"placeholder",void 0),t([mt({type:String})],Ph.prototype,"name",void 0),t([mt({type:String})],Ph.prototype,"query",void 0),t([mt({type:Number})],Ph.prototype,"inactiveThreshold",void 0),t([mt({type:Number})],Ph.prototype,"inactiveDays",void 0),t([mt({type:Object,attribute:!1})],Ph.prototype,"summary",void 0),t([mt({type:Object,attribute:!1})],Ph.prototype,"flow",void 0),t([mt({type:Array})],Ph.prototype,"recipients",void 0),t([mt({type:Boolean})],Ph.prototype,"advanced",void 0),t([mt({type:String})],Ph.prototype,"refreshKey",void 0),t([mt({type:Object})],Ph.prototype,"exclusions",void 0);class Rh extends dt{static get styles(){return a`
4138
4169
  :host {
4139
4170
  align-items: center;
4140
4171
  align-self: center;
@@ -4245,7 +4276,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
4245
4276
  />
4246
4277
  </svg>
4247
4278
  </div>
4248
- `}}var ph;t([mt({type:String})],uh.prototype,"name",void 0),t([mt({type:String})],uh.prototype,"prefix",void 0),t([mt({type:String})],uh.prototype,"id",void 0),t([mt({type:Number})],uh.prototype,"size",void 0),t([mt({type:Boolean})],uh.prototype,"spin",void 0),t([mt({type:Boolean})],uh.prototype,"clickable",void 0),t([mt({type:Boolean})],uh.prototype,"circled",void 0),t([mt({type:String})],uh.prototype,"animateChange",void 0),t([mt({type:String})],uh.prototype,"animateClick",void 0),t([mt({type:Number})],uh.prototype,"animationDuration",void 0),t([mt({type:String})],uh.prototype,"src",void 0),t([mt({type:Number,attribute:!1})],uh.prototype,"steps",void 0),t([mt({type:Number,attribute:!1})],uh.prototype,"animationStep",void 0),t([mt({type:String})],uh.prototype,"easing",void 0),function(t){t.Group="group",t.Contact="contact"}(ph||(ph={}));const mh={color:"var(--color-text-dark)",padding:"0px 6px",fontSize:"12px"};class gh extends gc{constructor(){super(...arguments),this.valueKey="uuid",this.groups=!1,this.contacts=!1,this.placeholder="Select recipients",this.multi=!0,this.jsonValue=!0,this.searchable=!0,this.searchOnFocus=!0,this.queryParam="search"}willUpdate(t){if((t.has("groups")||t.has("contacts"))&&(this.groups||this.contacts)){let t="&types=";this.groups&&(t+="g"),this.contacts&&(t+="c"),this.endpoint=this.endpoint+t}super.willUpdate(t)}renderOptionDefault(t){return W`
4279
+ `}}var Nh;t([mt({type:String})],Rh.prototype,"name",void 0),t([mt({type:String})],Rh.prototype,"prefix",void 0),t([mt({type:String})],Rh.prototype,"id",void 0),t([mt({type:Number})],Rh.prototype,"size",void 0),t([mt({type:Boolean})],Rh.prototype,"spin",void 0),t([mt({type:Boolean})],Rh.prototype,"clickable",void 0),t([mt({type:Boolean})],Rh.prototype,"circled",void 0),t([mt({type:String})],Rh.prototype,"animateChange",void 0),t([mt({type:String})],Rh.prototype,"animateClick",void 0),t([mt({type:Number})],Rh.prototype,"animationDuration",void 0),t([mt({type:String})],Rh.prototype,"src",void 0),t([mt({type:Number,attribute:!1})],Rh.prototype,"steps",void 0),t([mt({type:Number,attribute:!1})],Rh.prototype,"animationStep",void 0),t([mt({type:String})],Rh.prototype,"easing",void 0),function(t){t.Group="group",t.Contact="contact"}(Nh||(Nh={}));const Bh={color:"var(--color-text-dark)",padding:"0px 6px",fontSize:"12px"};class Fh extends Fc{constructor(){super(...arguments),this.valueKey="uuid",this.groups=!1,this.contacts=!1,this.placeholder="Select recipients",this.multi=!0,this.jsonValue=!0,this.searchable=!0,this.searchOnFocus=!0,this.queryParam="search"}willUpdate(t){if((t.has("groups")||t.has("contacts"))&&(this.groups||this.contacts)){let t="&types=";this.groups&&(t+="g"),this.contacts&&(t+="c"),this.endpoint=this.endpoint+t}super.willUpdate(t)}renderOptionDefault(t){return W`
4249
4280
  <div style="display:flex;">
4250
4281
  <div style="margin-right: 8px">${this.getIcon(t)}</div>
4251
4282
  <div style="flex: 1">${t.name}</div>
@@ -4255,7 +4286,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
4255
4286
  ${this.getPostName(t)}
4256
4287
  </div>
4257
4288
  </div>
4258
- `}getPostName(t){const e={...mh};return t.urn&&t.type===ph.Contact&&t.urn!==t.name?W`<div style=${$o(e)}>${t.urn}</div>`:t.type===ph.Group?W`
4289
+ `}getPostName(t){const e={...Bh};return t.urn&&t.type===Nh.Contact&&t.urn!==t.name?W`<div style=${$o(e)}>${t.urn}</div>`:t.type===Nh.Group?W`
4259
4290
  <div style=${$o(e)}>${t.count.toLocaleString()}</div>
4260
4291
  `:null}renderSelectedItemDefault(t){return W`
4261
4292
  <div
@@ -4276,7 +4307,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
4276
4307
  ${this.getPostName(t)}
4277
4308
  </div>
4278
4309
  </div>
4279
- `}getIcon(t){return t.type===ph.Group?W`<temba-icon name="${ko.group}"></temba-icon>`:t.type===ph.Contact?W`<temba-icon name="${ko.contact}"></temba-icon>`:void 0}}t([mt({type:String})],gh.prototype,"valueKey",void 0),t([mt({type:Boolean})],gh.prototype,"groups",void 0),t([mt({type:Boolean})],gh.prototype,"contacts",void 0),t([mt({type:String})],gh.prototype,"placeholder",void 0),t([mt({type:Boolean})],gh.prototype,"multi",void 0),t([mt({type:Boolean})],gh.prototype,"jsonValue",void 0),t([mt({type:Boolean})],gh.prototype,"searchable",void 0),t([mt({type:Boolean})],gh.prototype,"searchOnFocus",void 0),t([mt({type:Boolean})],gh.prototype,"queryParam",void 0);class fh extends Be{constructor(){super(...arguments),this.content=null,this.visible=!1,this.position="auto",this.delay=350,this.hideDelay=40,this.showTimer=0,this.hideTimer=0}static get styles(){return a`
4310
+ `}getIcon(t){return t.type===Nh.Group?W`<temba-icon name="${ko.group}"></temba-icon>`:t.type===Nh.Contact?W`<temba-icon name="${ko.contact}"></temba-icon>`:void 0}}t([mt({type:String})],Fh.prototype,"valueKey",void 0),t([mt({type:Boolean})],Fh.prototype,"groups",void 0),t([mt({type:Boolean})],Fh.prototype,"contacts",void 0),t([mt({type:String})],Fh.prototype,"placeholder",void 0),t([mt({type:Boolean})],Fh.prototype,"multi",void 0),t([mt({type:Boolean})],Fh.prototype,"jsonValue",void 0),t([mt({type:Boolean})],Fh.prototype,"searchable",void 0),t([mt({type:Boolean})],Fh.prototype,"searchOnFocus",void 0),t([mt({type:Boolean})],Fh.prototype,"queryParam",void 0);class qh extends Be{constructor(){super(...arguments),this.content=null,this.visible=!1,this.position="auto",this.delay=350,this.hideDelay=40,this.showTimer=0,this.hideTimer=0}static get styles(){return a`
4280
4311
  .tip {
4281
4312
  transition: opacity 120ms cubic-bezier(0.2, 0, 0, 1);
4282
4313
  margin: 0px;
@@ -4359,7 +4390,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
4359
4390
  ${null!==(t=this.content)&&void 0!==t?t:this.text}
4360
4391
  <div class="arrow" style=${$o(i)}></div>
4361
4392
  </div>
4362
- `}}t([mt({type:String})],fh.prototype,"text",void 0),t([mt({attribute:!1})],fh.prototype,"content",void 0),t([mt({type:Boolean})],fh.prototype,"visible",void 0),t([mt({type:String})],fh.prototype,"position",void 0),t([mt({type:Boolean})],fh.prototype,"hideOnChange",void 0),t([mt({type:Number,attribute:!1})],fh.prototype,"width",void 0),t([mt({type:Boolean,attribute:!1})],fh.prototype,"poppedTop",void 0),t([mt({type:Number})],fh.prototype,"delay",void 0),t([mt({type:Number})],fh.prototype,"hideDelay",void 0);const vh=(t,e)=>{const i=t||[],o=i.findIndex(t=>t.id==e||t.vanity_id==e);if(o>-1){return{item:i[o],index:o}}return{item:null,index:-1}};class bh extends vc{static get styles(){return a`
4393
+ `}}t([mt({type:String})],qh.prototype,"text",void 0),t([mt({attribute:!1})],qh.prototype,"content",void 0),t([mt({type:Boolean})],qh.prototype,"visible",void 0),t([mt({type:String})],qh.prototype,"position",void 0),t([mt({type:Boolean})],qh.prototype,"hideOnChange",void 0),t([mt({type:Number,attribute:!1})],qh.prototype,"width",void 0),t([mt({type:Boolean,attribute:!1})],qh.prototype,"poppedTop",void 0),t([mt({type:Number})],qh.prototype,"delay",void 0),t([mt({type:Number})],qh.prototype,"hideDelay",void 0);const Uh=(t,e)=>{const i=t||[],o=i.findIndex(t=>t.id==e||t.vanity_id==e);if(o>-1){return{item:i[o],index:o}}return{item:null,index:-1}};class jh extends Uc{static get styles(){return a`
4363
4394
  :host {
4364
4395
  width: 100%;
4365
4396
  display: block;
@@ -5059,7 +5090,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5059
5090
  ${(t.items||[]).map(e=>(e.level=t.level+1,W`${this.renderMenuItem(e,t)}`))}
5060
5091
  </div>
5061
5092
  </temba-dropdown>
5062
- `:a},this.doRefresh=this.doRefresh.bind(this),this.addEventListener("blur",()=>{this.shadowRoot.querySelectorAll("temba-list, temba-notification-list").forEach(t=>{t.scrollToTop()})})}setBubble(t,e){const i=vh(this.root.items,t);return!(!i||!i.item)&&(i.item.bubble=e,this.requestUpdate("root"),!0)}getMenuItemState(t){let e={};return t&&(e=this.state[t],e||(e={},this.state[t]=e)),e}updated(t){t.has("endpoint")&&(this.root={level:-1,endpoint:this.endpoint},this.wait?this.fireCustomEvent(Io.Ready):this.loadItems(this.root)),t.has("root")&&this.value&&(this.setFocusedItem(this.value),this.value=null)}reset(){this.loadItems(this.root)}async doRefresh(){const t=[...this.selection];let e=this.root;for(;t.length>0;){this.loadItems(e),await this.httpComplete;const i=t.shift();e=(e.items||[]).find(t=>t.id==i)}this.loadItems(e),this.shadowRoot.querySelectorAll("temba-notification-list").forEach(t=>{t.refresh()})}loadItems(t,e=null){t&&t.endpoint&&(t.loading=!0,this.httpComplete=le(t.endpoint).then(i=>{if(i.forEach(e=>{if(!e.items){const i=(t.items||[]).find(t=>t.id==e.id);i&&i.items&&(e.items=i.items)}}),i.forEach(e=>{e.level=t.level+1,e.items&&e.items.forEach(e=>{e.level=t.level+2})}),t.items=i,t.loading=!1,this.submenu&&0==this.selection.length){const t=this.getMenuItemForSelection([this.submenu]);this.handleItemClicked(e,t)}this.wait||(this.fireCustomEvent(Io.Ready),this.wait=!0),this.requestUpdate("root"),this.scrollSelectedIntoView()}).catch(t=>{this.fireCustomEvent(Io.Error,{error:t})}))}handleItemClicked(t,e,i=null){var o,n;const s=document.querySelector("temba-store");if(s){if(s.getDirtyMessage())return void(null===(n=(o=s.getState()).flushSave)||void 0===n||n.call(o).then(()=>{s.cleanAll(),this.executeNavigation(t,e,i)}));s.cleanAll()}this.executeNavigation(t,e,i)}executeNavigation(t,e,i=null){if(i&&i.popup){const o=this.shadowRoot.querySelector("temba-dropdown");return o&&o.blur(),void(t&&this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i}))}if(e.popup)t&&this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i});else if("modax-button"!==e.type){if(t&&t.metaKey&&e.href)return t.preventDefault(),t.stopPropagation(),void window.open(e.href,"_blank");if(i&&i.inline&&this.handleItemClicked(null,i),this.collapsed&&!this.isMobile()&&(this.collapsed=!1),this.isMobile()&&(this.collapsed=!0),e.trigger||e.event)this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i});else{if(e.level>=this.selection.length?this.selection.push(e.vanity_id||e.id):this.selection.splice(e.level,this.selection.length-e.level,e.vanity_id||e.id),e.endpoint){if(this.loadItems(e,t),!e.href)return}else this.requestUpdate();e.href?this.dispatchEvent(new Event("change")):this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i})}}else this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i})}scrollSelectedIntoView(){window.setTimeout(()=>{this.shadowRoot.querySelectorAll(".selected").forEach(t=>{t.scrollIntoView({block:"end",behavior:"smooth"})})},0)}clickItem(t){const e=[...this.selection];e.splice(e.length-1,1,t);const i=this.getMenuItemForSelection(e);return!!i&&(this.handleItemClicked(null,i),this.scrollSelectedIntoView(),!0)}getMenuItem(){return this.getMenuItemForSelection([...this.selection])}getMenuItemForSelection(t){const e=[...t];let i=this.root.items,o=null;for(;e.length>0;){const t=e.splice(0,1)[0];if(!i)break;if(o=vh(i,t).item,!o)break;i=o.items}return o}getSelection(){return this.selection}handleExpand(){this.collapsed=!1}handleCollapse(){this.collapsed=!0}async setFocusedItem(t){const e=t.split("/").filter(t=>!!t);if(!this.root)return;if(e.length>0){if(!vh(this.root.items,e[0]).item)return}const i=[];let o=this.root;for(;e.length>0;){const t=e.shift();t&&(o.items||(this.loadItems(o),await this.httpComplete),o=vh(o.items,t).item,o?i.push(t):e.splice(0,e.length))}this.selection=i,this.refresh(),this.requestUpdate("root")}isSelected(t){if(t.level<this.selection.length){return this.selection[t.level]==(t.vanity_id||t.id)}return!1}isExpanded(t){return!!this.selection.find(e=>e===t.vanity_id||t.id)}render(){if(!this.root||!this.root.items)return null;let t=this.root.items||[];const e=[],i=this.isMobile()?ko.menu:ko.menu_collapse;e.push(W`<div class="level level-0 ${this.submenu?"hidden":""}">
5093
+ `:a},this.doRefresh=this.doRefresh.bind(this),this.addEventListener("blur",()=>{this.shadowRoot.querySelectorAll("temba-list, temba-notification-list").forEach(t=>{t.scrollToTop()})})}setBubble(t,e){const i=Uh(this.root.items,t);return!(!i||!i.item)&&(i.item.bubble=e,this.requestUpdate("root"),!0)}getMenuItemState(t){let e={};return t&&(e=this.state[t],e||(e={},this.state[t]=e)),e}updated(t){t.has("endpoint")&&(this.root={level:-1,endpoint:this.endpoint},this.wait?this.fireCustomEvent(Io.Ready):this.loadItems(this.root)),t.has("root")&&this.value&&(this.setFocusedItem(this.value),this.value=null)}reset(){this.loadItems(this.root)}async doRefresh(){const t=[...this.selection];let e=this.root;for(;t.length>0;){this.loadItems(e),await this.httpComplete;const i=t.shift();e=(e.items||[]).find(t=>t.id==i)}this.loadItems(e),this.shadowRoot.querySelectorAll("temba-notification-list").forEach(t=>{t.refresh()})}loadItems(t,e=null){t&&t.endpoint&&(t.loading=!0,this.httpComplete=le(t.endpoint).then(i=>{if(i.forEach(e=>{if(!e.items){const i=(t.items||[]).find(t=>t.id==e.id);i&&i.items&&(e.items=i.items)}}),i.forEach(e=>{e.level=t.level+1,e.items&&e.items.forEach(e=>{e.level=t.level+2})}),t.items=i,t.loading=!1,this.submenu&&0==this.selection.length){const t=this.getMenuItemForSelection([this.submenu]);this.handleItemClicked(e,t)}this.wait||(this.fireCustomEvent(Io.Ready),this.wait=!0),this.requestUpdate("root"),this.scrollSelectedIntoView()}).catch(t=>{this.fireCustomEvent(Io.Error,{error:t})}))}handleItemClicked(t,e,i=null){var o,n;const s=document.querySelector("temba-store");if(s){if(s.getDirtyMessage())return void(null===(n=(o=s.getState()).flushSave)||void 0===n||n.call(o).then(()=>{s.cleanAll(),this.executeNavigation(t,e,i)}));s.cleanAll()}this.executeNavigation(t,e,i)}executeNavigation(t,e,i=null){if(i&&i.popup){const o=this.shadowRoot.querySelector("temba-dropdown");return o&&o.blur(),void(t&&this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i}))}if(e.popup)t&&this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i});else if("modax-button"!==e.type){if(t&&t.metaKey&&e.href)return t.preventDefault(),t.stopPropagation(),void window.open(e.href,"_blank");if(i&&i.inline&&this.handleItemClicked(null,i),this.collapsed&&!this.isMobile()&&(this.collapsed=!1),this.isMobile()&&(this.collapsed=!0),e.trigger||e.event)this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i});else{if(e.level>=this.selection.length?this.selection.push(e.vanity_id||e.id):this.selection.splice(e.level,this.selection.length-e.level,e.vanity_id||e.id),e.endpoint){if(this.loadItems(e,t),!e.href)return}else this.requestUpdate();e.href?this.dispatchEvent(new Event("change")):this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i})}}else this.fireCustomEvent(Io.ButtonClicked,{item:e,selection:this.getSelection(),parent:i})}scrollSelectedIntoView(){window.setTimeout(()=>{this.shadowRoot.querySelectorAll(".selected").forEach(t=>{t.scrollIntoView({block:"end",behavior:"smooth"})})},0)}clickItem(t){const e=[...this.selection];e.splice(e.length-1,1,t);const i=this.getMenuItemForSelection(e);return!!i&&(this.handleItemClicked(null,i),this.scrollSelectedIntoView(),!0)}getMenuItem(){return this.getMenuItemForSelection([...this.selection])}getMenuItemForSelection(t){const e=[...t];let i=this.root.items,o=null;for(;e.length>0;){const t=e.splice(0,1)[0];if(!i)break;if(o=Uh(i,t).item,!o)break;i=o.items}return o}getSelection(){return this.selection}handleExpand(){this.collapsed=!1}handleCollapse(){this.collapsed=!0}async setFocusedItem(t){const e=t.split("/").filter(t=>!!t);if(!this.root)return;if(e.length>0){if(!Uh(this.root.items,e[0]).item)return}const i=[];let o=this.root;for(;e.length>0;){const t=e.shift();t&&(o.items||(this.loadItems(o),await this.httpComplete),o=Uh(o.items,t).item,o?i.push(t):e.splice(0,e.length))}this.selection=i,this.refresh(),this.requestUpdate("root")}isSelected(t){if(t.level<this.selection.length){return this.selection[t.level]==(t.vanity_id||t.id)}return!1}isExpanded(t){return!!this.selection.find(e=>e===t.vanity_id||t.id)}render(){if(!this.root||!this.root.items)return null;let t=this.root.items||[];const e=[],i=this.isMobile()?ko.menu:ko.menu_collapse;e.push(W`<div class="level level-0 ${this.submenu?"hidden":""}">
5063
5094
  <div class="top">
5064
5095
  <div class="expand-icon" @click=${this.handleExpand}>
5065
5096
  <temba-icon
@@ -5076,7 +5107,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5076
5107
  <div class="empty"></div>
5077
5108
  ${t.filter(t=>!!t.bottom).map(t=>this.renderMenuItem(t))}
5078
5109
  <div class="bottom"></div>
5079
- </div>`),this.selection.forEach((i,o)=>{const n=vh(t,i).item;let s=!1;if(n){t=n.items;const e=this.getMenuItemState(n.id);e.collapsed?s="collapsed"===e.collapsed:this.selection.length>n.level+2&&(s=!1)}else t=null;const r=this.isMobile()?ko.close:ko.menu_collapse;t&&t.length>0&&!n.inline&&e.push(W`<div
5110
+ </div>`),this.selection.forEach((i,o)=>{const n=Uh(t,i).item;let s=!1;if(n){t=n.items;const e=this.getMenuItemState(n.id);e.collapsed?s="collapsed"===e.collapsed:this.selection.length>n.level+2&&(s=!1)}else t=null;const r=this.isMobile()?ko.close:ko.menu_collapse;t&&t.length>0&&!n.inline&&e.push(W`<div
5080
5111
  class="${re({level:!0,["level-"+(o+1)]:!0,collapsed:s})}"
5081
5112
  >
5082
5113
  ${this.submenu?null:W`
@@ -5102,7 +5133,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5102
5133
  class="${re({root:!0,"fully-collapsed":this.collapsed,mobile:this.isMobile()})}"
5103
5134
  >
5104
5135
  ${e}
5105
- </div>`;return W`${o}`}}t([mt({type:Boolean})],bh.prototype,"wraps",void 0),t([mt({type:Boolean})],bh.prototype,"wait",void 0),t([mt({type:String})],bh.prototype,"endpoint",void 0),t([mt({type:String})],bh.prototype,"expanding",void 0),t([mt({type:String})],bh.prototype,"value",void 0),t([mt({type:String})],bh.prototype,"submenu",void 0),t([mt({type:Boolean})],bh.prototype,"collapsed",void 0),t([mt({type:Object})],bh.prototype,"pressedItem",void 0);class yh extends dt{static get styles(){return a`
5136
+ </div>`;return W`${o}`}}t([mt({type:Boolean})],jh.prototype,"wraps",void 0),t([mt({type:Boolean})],jh.prototype,"wait",void 0),t([mt({type:String})],jh.prototype,"endpoint",void 0),t([mt({type:String})],jh.prototype,"expanding",void 0),t([mt({type:String})],jh.prototype,"value",void 0),t([mt({type:String})],jh.prototype,"submenu",void 0),t([mt({type:Boolean})],jh.prototype,"collapsed",void 0),t([mt({type:Object})],jh.prototype,"pressedItem",void 0);class Hh extends dt{static get styles(){return a`
5106
5137
  :host {
5107
5138
  color: var(--color-link-primary);
5108
5139
  display: inline-block;
@@ -5112,7 +5143,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5112
5143
  cursor: pointer;
5113
5144
  text-decoration: underline;
5114
5145
  }
5115
- `}handleClick(t){window.goto(t)}render(){return W`<slot href="${this.href}" @click="${this.handleClick}"></slot>`}}t([mt({type:String})],yh.prototype,"href",void 0);class xh extends Be{static get styles(){return a`
5146
+ `}handleClick(t){window.goto(t)}render(){return W`<slot href="${this.href}" @click="${this.handleClick}"></slot>`}}t([mt({type:String})],Hh.prototype,"href",void 0);class Wh extends Be{static get styles(){return a`
5116
5147
  :host {
5117
5148
  }
5118
5149
 
@@ -5217,7 +5248,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5217
5248
  </div>
5218
5249
  </div>
5219
5250
  </div>
5220
- `}}t([mt({type:Boolean})],xh.prototype,"open",void 0),t([mt({type:Boolean})],xh.prototype,"dormant",void 0),t([mt({type:Number})],xh.prototype,"arrowSize",void 0),t([mt({type:Number})],xh.prototype,"margin",void 0),t([mt({type:Boolean})],xh.prototype,"mask",void 0);class wh extends Be{constructor(){super(...arguments),this.embedded=!1,this.collapses=!1,this.unselect=!1,this.focusedName=!1,this.index=-1,this.refresh="",this.options=[]}static get styles(){return a`
5251
+ `}}t([mt({type:Boolean})],Wh.prototype,"open",void 0),t([mt({type:Boolean})],Wh.prototype,"dormant",void 0),t([mt({type:Number})],Wh.prototype,"arrowSize",void 0),t([mt({type:Number})],Wh.prototype,"margin",void 0),t([mt({type:Boolean})],Wh.prototype,"mask",void 0);class Vh extends Be{constructor(){super(...arguments),this.embedded=!1,this.collapses=!1,this.unselect=!1,this.focusedName=!1,this.index=-1,this.refresh="",this.options=[]}static get styles(){return a`
5221
5252
  :host {
5222
5253
  display: flex;
5223
5254
  flex-direction: column;
@@ -5477,7 +5508,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5477
5508
  <slot></slot>
5478
5509
  <slot name="pane-bottom"></slot>
5479
5510
  </div>
5480
- `}}t([mt({type:Boolean})],wh.prototype,"embedded",void 0),t([mt({type:Boolean})],wh.prototype,"collapses",void 0),t([mt({type:Boolean})],wh.prototype,"unselect",void 0),t([mt({type:Boolean})],wh.prototype,"focusedName",void 0),t([mt({type:Number})],wh.prototype,"index",void 0),t([mt({type:String})],wh.prototype,"refresh",void 0),t([mt({type:Array,attribute:!1})],wh.prototype,"options",void 0);class _h extends Be{constructor(){super(...arguments),this.borderColor="var(--color-widget-border)",this.activityColor="var(--color-link-primary)",this.selected=!1,this.notify=!1,this.alert=!1,this.hidden=!1,this.hideEmpty=!1,this.activity=!1,this.count=0,this.checked=!1,this.dirty=!1}static get styles(){return a`
5511
+ `}}t([mt({type:Boolean})],Vh.prototype,"embedded",void 0),t([mt({type:Boolean})],Vh.prototype,"collapses",void 0),t([mt({type:Boolean})],Vh.prototype,"unselect",void 0),t([mt({type:Boolean})],Vh.prototype,"focusedName",void 0),t([mt({type:Number})],Vh.prototype,"index",void 0),t([mt({type:String})],Vh.prototype,"refresh",void 0),t([mt({type:Array,attribute:!1})],Vh.prototype,"options",void 0);class Zh extends Be{constructor(){super(...arguments),this.borderColor="var(--color-widget-border)",this.activityColor="var(--color-link-primary)",this.selected=!1,this.notify=!1,this.alert=!1,this.hidden=!1,this.hideEmpty=!1,this.activity=!1,this.count=0,this.checked=!1,this.dirty=!1}static get styles(){return a`
5481
5512
  :host {
5482
5513
  display: none;
5483
5514
  flex-direction: column;
@@ -5493,7 +5524,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5493
5524
  `}updated(t){super.updated(t),t.has("selected")&&this.classList.toggle("selected",this.selected)}hasBadge(){return this.count>0}handleDetailsChanged(t){"dirty"in t.detail&&(this.dirty=t.detail.dirty),"count"in t.detail&&(this.count=t.detail.count,this.hideEmpty&&(this.hidden=0===this.count))}render(){return W`<slot
5494
5525
  @temba-details-changed=${this.handleDetailsChanged}
5495
5526
  class="${re({selected:this.selected})}"
5496
- ></slot> `}}t([mt({type:String})],_h.prototype,"name",void 0),t([mt({type:String})],_h.prototype,"icon",void 0),t([mt({type:String})],_h.prototype,"selectionColor",void 0),t([mt({type:String})],_h.prototype,"selectionBackground",void 0),t([mt({type:String})],_h.prototype,"borderColor",void 0),t([mt({type:String})],_h.prototype,"activityColor",void 0),t([mt({type:Boolean})],_h.prototype,"selected",void 0),t([mt({type:Boolean})],_h.prototype,"notify",void 0),t([mt({type:Boolean})],_h.prototype,"alert",void 0),t([mt({type:Boolean})],_h.prototype,"hidden",void 0),t([mt({type:Boolean})],_h.prototype,"hideEmpty",void 0),t([mt({type:Boolean})],_h.prototype,"activity",void 0),t([mt({type:Number})],_h.prototype,"count",void 0),t([mt({type:Boolean})],_h.prototype,"checked",void 0),t([mt({type:Boolean})],_h.prototype,"dirty",void 0);let kh=class extends dt{static get styles(){return a`
5527
+ ></slot> `}}t([mt({type:String})],Zh.prototype,"name",void 0),t([mt({type:String})],Zh.prototype,"icon",void 0),t([mt({type:String})],Zh.prototype,"selectionColor",void 0),t([mt({type:String})],Zh.prototype,"selectionBackground",void 0),t([mt({type:String})],Zh.prototype,"borderColor",void 0),t([mt({type:String})],Zh.prototype,"activityColor",void 0),t([mt({type:Boolean})],Zh.prototype,"selected",void 0),t([mt({type:Boolean})],Zh.prototype,"notify",void 0),t([mt({type:Boolean})],Zh.prototype,"alert",void 0),t([mt({type:Boolean})],Zh.prototype,"hidden",void 0),t([mt({type:Boolean})],Zh.prototype,"hideEmpty",void 0),t([mt({type:Boolean})],Zh.prototype,"activity",void 0),t([mt({type:Number})],Zh.prototype,"count",void 0),t([mt({type:Boolean})],Zh.prototype,"checked",void 0),t([mt({type:Boolean})],Zh.prototype,"dirty",void 0);let Yh=class extends dt{static get styles(){return a`
5497
5528
  :host {
5498
5529
  display: inline-block;
5499
5530
  }
@@ -5577,7 +5608,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5577
5608
  <slot></slot>
5578
5609
  </div>
5579
5610
  </div>
5580
- `}};t([mt({type:Boolean})],kh.prototype,"clickable",void 0),t([mt({type:Boolean})],kh.prototype,"primary",void 0),t([mt({type:Boolean})],kh.prototype,"secondary",void 0),t([mt({type:Boolean})],kh.prototype,"tertiary",void 0),t([mt({type:Boolean})],kh.prototype,"danger",void 0),t([mt({type:Boolean})],kh.prototype,"dark",void 0),t([mt({type:Boolean})],kh.prototype,"shadow",void 0),t([mt({type:String})],kh.prototype,"icon",void 0),t([mt()],kh.prototype,"backgroundColor",void 0),t([mt()],kh.prototype,"textColor",void 0);class Ch extends Be{constructor(){super(...arguments),this.size=20}static get styles(){return a`
5611
+ `}};t([mt({type:Boolean})],Yh.prototype,"clickable",void 0),t([mt({type:Boolean})],Yh.prototype,"primary",void 0),t([mt({type:Boolean})],Yh.prototype,"secondary",void 0),t([mt({type:Boolean})],Yh.prototype,"tertiary",void 0),t([mt({type:Boolean})],Yh.prototype,"danger",void 0),t([mt({type:Boolean})],Yh.prototype,"dark",void 0),t([mt({type:Boolean})],Yh.prototype,"shadow",void 0),t([mt({type:String})],Yh.prototype,"icon",void 0),t([mt()],Yh.prototype,"backgroundColor",void 0),t([mt()],Yh.prototype,"textColor",void 0);class Kh extends Be{constructor(){super(...arguments),this.size=20}static get styles(){return a`
5581
5612
  :host {
5582
5613
  display: flex;
5583
5614
  align-items: center;
@@ -5602,7 +5633,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5602
5633
  ${this.name?this.name:this.urn?this.urn.split(":")[1]:""}
5603
5634
  </div>
5604
5635
  <slot></slot>
5605
- `}}t([mt({type:String})],Ch.prototype,"name",void 0),t([mt({type:String})],Ch.prototype,"urn",void 0),t([mt({type:Number,attribute:"icon-size"})],Ch.prototype,"size",void 0);class Sh extends Be{constructor(){super(...arguments),this.size=20}static get styles(){return a`
5636
+ `}}t([mt({type:String})],Kh.prototype,"name",void 0),t([mt({type:String})],Kh.prototype,"urn",void 0),t([mt({type:Number,attribute:"icon-size"})],Kh.prototype,"size",void 0);class Gh extends Be{constructor(){super(...arguments),this.size=20}static get styles(){return a`
5606
5637
  :host {
5607
5638
  display: flex;
5608
5639
  align-items: center;
@@ -5629,7 +5660,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5629
5660
  height="${this.size}em"
5630
5661
  src="${this.prefix||window.static_url||"/static/"}img/schemes/${t}.svg"
5631
5662
  />
5632
- `}}t([mt({type:String})],Sh.prototype,"urn",void 0),t([mt({type:String})],Sh.prototype,"scheme",void 0),t([mt({type:Number})],Sh.prototype,"size",void 0);class Ah extends Pc{constructor(){super(...arguments),this.disabled=!1}static get styles(){return a`
5663
+ `}}t([mt({type:String})],Gh.prototype,"urn",void 0),t([mt({type:String})],Gh.prototype,"scheme",void 0),t([mt({type:Number})],Gh.prototype,"size",void 0);class Xh extends ah{constructor(){super(...arguments),this.disabled=!1}static get styles(){return a`
5633
5664
  .field {
5634
5665
  display: flex;
5635
5666
  margin: 1em 0.3em;
@@ -5710,7 +5741,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5710
5741
  </div>
5711
5742
  </div>`:null}
5712
5743
  </div>
5713
- `}return super.render()}}var Eh;t([mt({type:Boolean})],Ah.prototype,"system",void 0),t([mt({type:Boolean})],Ah.prototype,"dirty",void 0),t([mt({type:Boolean})],Ah.prototype,"showAll",void 0),t([mt({type:String})],Ah.prototype,"timezone",void 0),t([mt({type:String})],Ah.prototype,"role",void 0),t([mt({type:Boolean})],Ah.prototype,"disabled",void 0),function(t){t.Success="success",t.Failure="failure",t.Saving="saving",t.Ready="ready"}(Eh||(Eh={}));class $h extends Be{constructor(){super(...arguments),this.icon=navigator.clipboard?ko.copy:"",this.iconClass="",this.status=Eh.Ready,this.disabled=!1,this.dirty=!1}static get styles(){return a`
5744
+ `}return super.render()}}var Qh;t([mt({type:Boolean})],Xh.prototype,"system",void 0),t([mt({type:Boolean})],Xh.prototype,"dirty",void 0),t([mt({type:Boolean})],Xh.prototype,"showAll",void 0),t([mt({type:String})],Xh.prototype,"timezone",void 0),t([mt({type:String})],Xh.prototype,"role",void 0),t([mt({type:Boolean})],Xh.prototype,"disabled",void 0),function(t){t.Success="success",t.Failure="failure",t.Saving="saving",t.Ready="ready"}(Qh||(Qh={}));class Jh extends Be{constructor(){super(...arguments),this.icon=navigator.clipboard?ko.copy:"",this.iconClass="",this.status=Qh.Ready,this.disabled=!1,this.dirty=!1}static get styles(){return a`
5714
5745
  :host {
5715
5746
  --transition-speed: 0ms;
5716
5747
  margin-bottom: 1em;
@@ -5972,7 +6003,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
5972
6003
 
5973
6004
  temba-option {
5974
6005
  }
5975
- `}connectedCallback(){super.connectedCallback(),this.handleInput=this.handleInput.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}handleIconClick(t){const e=t.target.getAttribute("icon-action"),i=this.shadowRoot.querySelector("temba-textinput");"copy"===e&&navigator.clipboard&&(this.iconClass="clicked",navigator.clipboard.writeText(i.getDisplayValue()).then(()=>{window.setTimeout(()=>{this.iconClass=""},300)})),"search"===e&&this.fireCustomEvent(Io.ButtonClicked,{key:this.key,value:this.value}),t.preventDefault(),t.stopPropagation()}handleResponse(t){200===t.status?(this.value=t.json.fields[this.key],this.status=Eh.Ready,this.dirty=!1):(this.status=Eh.Failure,this.dirty=!1)}handleSelectChange(t){const e=t.currentTarget;let i="";t.preventDefault(),t.stopPropagation(),e.values.length>0&&(i=e.values[0].path),i!==this.value&&(this.dirty=!0,this.status=Eh.Saving,this.value=i,this.fireEvent("change"))}handleSubmit(){const t=this.shadowRoot.querySelector("temba-textinput, temba-datepicker");t.value!==this.value&&(this.dirty=!0,this.status=Eh.Saving,this.value=t.value,this.fireEvent("change"))}handleChange(t){t.preventDefault(),t.stopPropagation()}handleDateChange(t){t.preventDefault(),t.stopPropagation(),this.dirty=!0}handleInput(t){const e=t.currentTarget;"Enter"===t.key?(e.blur(),this.handleSubmit()):e.value!==this.value&&(this.dirty=!0)}getInputType(t){return"numeric"===t?To.Number:To.Text}renderDateField(t){return W` <temba-datepicker
6006
+ `}connectedCallback(){super.connectedCallback(),this.handleInput=this.handleInput.bind(this),this.handleSubmit=this.handleSubmit.bind(this)}handleIconClick(t){const e=t.target.getAttribute("icon-action"),i=this.shadowRoot.querySelector("temba-textinput");"copy"===e&&navigator.clipboard&&(this.iconClass="clicked",navigator.clipboard.writeText(i.getDisplayValue()).then(()=>{window.setTimeout(()=>{this.iconClass=""},300)})),"search"===e&&this.fireCustomEvent(Io.ButtonClicked,{key:this.key,value:this.value}),t.preventDefault(),t.stopPropagation()}handleResponse(t){200===t.status?(this.value=t.json.fields[this.key],this.status=Qh.Ready,this.dirty=!1):(this.status=Qh.Failure,this.dirty=!1)}handleSelectChange(t){const e=t.currentTarget;let i="";t.preventDefault(),t.stopPropagation(),e.values.length>0&&(i=e.values[0].path),i!==this.value&&(this.dirty=!0,this.status=Qh.Saving,this.value=i,this.fireEvent("change"))}handleSubmit(){const t=this.shadowRoot.querySelector("temba-textinput, temba-datepicker");t.value!==this.value&&(this.dirty=!0,this.status=Qh.Saving,this.value=t.value,this.fireEvent("change"))}handleChange(t){t.preventDefault(),t.stopPropagation()}handleDateChange(t){t.preventDefault(),t.stopPropagation(),this.dirty=!0}handleInput(t){const e=t.currentTarget;"Enter"===t.key?(e.blur(),this.handleSubmit()):e.value!==this.value&&(this.dirty=!0)}getInputType(t){return"numeric"===t?To.Number:To.Text}renderDateField(t){return W` <temba-datepicker
5976
6007
  timezone=${this.timezone}
5977
6008
  value="${this.value?this.value:""}"
5978
6009
  @change=${this.handleDateChange}
@@ -6063,12 +6094,12 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6063
6094
  name="Save"
6064
6095
  small
6065
6096
  @click=${this.handleSubmit}
6066
- ></temba-button>`:W` ${this.status===Eh.Saving?W`<temba-icon
6097
+ ></temba-button>`:W` ${this.status===Qh.Saving?W`<temba-icon
6067
6098
  spin
6068
6099
  name="${ko.progress_spinner}"
6069
6100
  ></temba-icon>`:null}
6070
- ${this.status!==Eh.Success||this.dirty?null:W`<temba-icon name="${ko.success}"></temba-icon>`}
6071
- ${this.status===Eh.Failure?W`<temba-tip text="Failed to save changes, try again later."
6101
+ ${this.status!==Qh.Success||this.dirty?null:W`<temba-icon name="${ko.success}"></temba-icon>`}
6102
+ ${this.status===Qh.Failure?W`<temba-tip text="Failed to save changes, try again later."
6072
6103
  ><temba-icon name="${ko.alert_warning}"></temba-icon
6073
6104
  ></temba-tip>`:null}`}
6074
6105
  </div>`;return W`
@@ -6077,7 +6108,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6077
6108
  >
6078
6109
  ${"datetime"===this.type?this.renderDateField(t):"state"===this.type||"district"===this.type||"ward"===this.type?this.renderLocationField(this.type):this.renderTextField(t)}
6079
6110
  </div>
6080
- `}}t([mt({type:String})],$h.prototype,"key",void 0),t([mt({type:String})],$h.prototype,"value",void 0),t([mt({type:String})],$h.prototype,"name",void 0),t([mt({type:String})],$h.prototype,"type",void 0),t([mt({type:String})],$h.prototype,"timezone",void 0),t([mt({type:String})],$h.prototype,"icon",void 0),t([mt({type:String})],$h.prototype,"iconClass",void 0),t([mt({type:String})],$h.prototype,"status",void 0),t([mt({type:Boolean})],$h.prototype,"disabled",void 0),t([mt({type:Boolean})],$h.prototype,"dirty",void 0);const Th={stopped:{name:"Stopped"},blocked:{name:"Blocked"},archived:{name:"Archived"}};class Dh extends Pc{constructor(){super(...arguments),this.hasMore=!1,this.expanded=!1}static get styles(){return a`
6111
+ `}}t([mt({type:String})],Jh.prototype,"key",void 0),t([mt({type:String})],Jh.prototype,"value",void 0),t([mt({type:String})],Jh.prototype,"name",void 0),t([mt({type:String})],Jh.prototype,"type",void 0),t([mt({type:String})],Jh.prototype,"timezone",void 0),t([mt({type:String})],Jh.prototype,"icon",void 0),t([mt({type:String})],Jh.prototype,"iconClass",void 0),t([mt({type:String})],Jh.prototype,"status",void 0),t([mt({type:Boolean})],Jh.prototype,"disabled",void 0),t([mt({type:Boolean})],Jh.prototype,"dirty",void 0);const tu={stopped:{name:"Stopped"},blocked:{name:"Blocked"},archived:{name:"Archived"}};class eu extends ah{constructor(){super(...arguments),this.hasMore=!1,this.expanded=!1}static get styles(){return a`
6081
6112
  .wrapper {
6082
6113
  display: flex;
6083
6114
  flex-direction: column;
@@ -6146,7 +6177,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6146
6177
  .show-button temba-icon {
6147
6178
  border-radius: 9999px;
6148
6179
  }
6149
- `}handleResized(){if(this.shadowRoot){const t=this.shadowRoot.querySelector(".badges");t&&(this.hasMore=t.scrollHeight>t.clientHeight)}}updated(t){if(super.updated(t),t.has("data")&&!t.get("data")){const t=this.shadowRoot.querySelector(".badges");new ResizeObserver(ge(this.handleResized.bind(this),200)).observe(t)}}render(){if(this.data){const t=Th[this.data.status];return W`
6180
+ `}handleResized(){if(this.shadowRoot){const t=this.shadowRoot.querySelector(".badges");t&&(this.hasMore=t.scrollHeight>t.clientHeight)}}updated(t){if(super.updated(t),t.has("data")&&!t.get("data")){const t=this.shadowRoot.querySelector(".badges");new ResizeObserver(ge(this.handleResized.bind(this),200)).observe(t)}}render(){if(this.data){const t=tu[this.data.status];return W`
6150
6181
  <div
6151
6182
  class=${re({wrapper:!0,"has-more":this.hasMore,expanded:this.expanded})}
6152
6183
  >
@@ -6211,7 +6242,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6211
6242
  ></temba-icon>
6212
6243
  </div>
6213
6244
  </div>
6214
- `}return null}}t([mt({type:Boolean})],Dh.prototype,"hasMore",void 0),t([mt({type:Boolean})],Dh.prototype,"expanded",void 0);const Mh={[Mo.CampaignEvent]:ko.campaign,[Mo.ScheduledBroadcast]:ko.message,[Mo.ScheduledTrigger]:ko.trigger};class zh extends Oc{static get styles(){return a`
6245
+ `}return null}}t([mt({type:Boolean})],eu.prototype,"hasMore",void 0),t([mt({type:Boolean})],eu.prototype,"expanded",void 0);const iu={[Mo.CampaignEvent]:ko.campaign,[Mo.ScheduledBroadcast]:ko.message,[Mo.ScheduledTrigger]:ko.trigger};class ou extends rh{static get styles(){return a`
6215
6246
  :host {
6216
6247
  }
6217
6248
 
@@ -6341,7 +6372,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6341
6372
  <div class="name">${t.campaign.name}</div>
6342
6373
  </div>`:W`
6343
6374
  ${t.type===Mo.ScheduledTrigger?W`<temba-icon
6344
- name="${Mh[t.type]}"
6375
+ name="${iu[t.type]}"
6345
6376
  ></temba-icon>`:null}
6346
6377
  <div class="name">
6347
6378
  ${this.REPEAT_PERIOD[t.repeat_period]}
@@ -6363,7 +6394,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6363
6394
  </div>
6364
6395
  `}render(){if(this.data)return this.data.length>0?W`
6365
6396
  ${this.data.map(t=>this.renderEvent(t))}
6366
- `:W`<slot name="empty"></slot>`}}t([mt({type:String})],zh.prototype,"contact",void 0),t([mt({type:Object,attribute:!1})],zh.prototype,"data",void 0),t([mt({type:String})],zh.prototype,"lang_weekly",void 0),t([mt({type:String})],zh.prototype,"lang_daily",void 0),t([mt({type:String})],zh.prototype,"lang_once",void 0);class Ih extends _o{constructor(){super(...arguments),this.range=!1,this.min=0,this.max=100,this.circleX=0,this.grabbed=!1}static get styles(){return a`
6397
+ `:W`<slot name="empty"></slot>`}}t([mt({type:String})],ou.prototype,"contact",void 0),t([mt({type:Object,attribute:!1})],ou.prototype,"data",void 0),t([mt({type:String})],ou.prototype,"lang_weekly",void 0),t([mt({type:String})],ou.prototype,"lang_daily",void 0),t([mt({type:String})],ou.prototype,"lang_once",void 0);class nu extends _o{constructor(){super(...arguments),this.range=!1,this.min=0,this.max=100,this.circleX=0,this.grabbed=!1}static get styles(){return a`
6367
6398
  :host {
6368
6399
  display: block;
6369
6400
  }
@@ -6429,7 +6460,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6429
6460
  <div class="track" @mousedown=${this.handleTrackDown}></div>
6430
6461
  ${this.range?W`<div class="post">${this.max}</div>`:null}
6431
6462
  </div>
6432
- </div>`}}t([mt({type:Boolean})],Ih.prototype,"range",void 0),t([mt({type:Number})],Ih.prototype,"min",void 0),t([mt({type:Number})],Ih.prototype,"max",void 0);const Lh="rgb(223, 65, 159)";class Oh extends rh{static get styles(){return a`
6463
+ </div>`}}t([mt({type:Boolean})],nu.prototype,"range",void 0),t([mt({type:Number})],nu.prototype,"min",void 0),t([mt({type:Number})],nu.prototype,"max",void 0);const su="rgb(223, 65, 159)";class ru extends Mh{static get styles(){return a`
6433
6464
  :host {
6434
6465
  overflow-y: auto !important;
6435
6466
  --contact-name-font-size: 1em;
@@ -6451,10 +6482,10 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6451
6482
  style="--icon-color:#666;margin-left:0.5em"
6452
6483
  />`:"interrupted"==t.exit_type?e=W`<temba-icon
6453
6484
  name="x-octagon"
6454
- style="--icon-color:${Lh};margin-left:0.5em"
6485
+ style="--icon-color:${su};margin-left:0.5em"
6455
6486
  />`:"expired"==t.exit_type?e=W`<temba-icon
6456
6487
  name="clock"
6457
- style="--icon-color:${Lh};margin-left:0.5em"
6488
+ style="--icon-color:${su};margin-left:0.5em"
6458
6489
  />`:t.exit_type||(e=t.responded?W`<temba-icon
6459
6490
  name="activity"
6460
6491
  style="--icon-color:var(--color-primary-dark);margin-left:0.5em"
@@ -6608,7 +6639,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6608
6639
  </div>
6609
6640
  `:null}
6610
6641
  </div>
6611
- </div>`}constructor(){super(),this.responses=!0,this.allowDelete=!1,this.resultKeys={},this.reverseRefresh=!1,this.valueKey="uuid",this.hideShadow=!0,this.createRenderOption()}}t([mt({type:String})],Oh.prototype,"flow",void 0),t([mt({type:Object,attribute:!1})],Oh.prototype,"results",void 0),t([mt({type:Boolean})],Oh.prototype,"responses",void 0),t([mt({type:Object})],Oh.prototype,"resultPreview",void 0),t([mt({type:Object})],Oh.prototype,"selectedRun",void 0),t([mt({type:Boolean})],Oh.prototype,"allowDelete",void 0);class Ph extends Oc{constructor(){super(...arguments),this.endpoint="/api/v2/flows.json?uuid="}prepareData(t){return t&&t.length>0&&(t=t[0]),t}updated(t){super.updated(t),t.has("flow")&&(this.flow?this.url=`${this.endpoint}${this.flow}`:this.url=null)}render(){if(this.data)return W`<div></div>`}}t([mt({type:String})],Ph.prototype,"flow",void 0),t([mt({type:Object,attribute:!1})],Ph.prototype,"data",void 0),t([mt({type:String})],Ph.prototype,"endpoint",void 0);class Rh extends Pc{constructor(){super(...arguments),this.size=20}static get styles(){return a`
6642
+ </div>`}constructor(){super(),this.responses=!0,this.allowDelete=!1,this.resultKeys={},this.reverseRefresh=!1,this.valueKey="uuid",this.hideShadow=!0,this.createRenderOption()}}t([mt({type:String})],ru.prototype,"flow",void 0),t([mt({type:Object,attribute:!1})],ru.prototype,"results",void 0),t([mt({type:Boolean})],ru.prototype,"responses",void 0),t([mt({type:Object})],ru.prototype,"resultPreview",void 0),t([mt({type:Object})],ru.prototype,"selectedRun",void 0),t([mt({type:Boolean})],ru.prototype,"allowDelete",void 0);class au extends rh{constructor(){super(...arguments),this.endpoint="/api/v2/flows.json?uuid="}prepareData(t){return t&&t.length>0&&(t=t[0]),t}updated(t){super.updated(t),t.has("flow")&&(this.flow?this.url=`${this.endpoint}${this.flow}`:this.url=null)}render(){if(this.data)return W`<div></div>`}}t([mt({type:String})],au.prototype,"flow",void 0),t([mt({type:Object,attribute:!1})],au.prototype,"data",void 0),t([mt({type:String})],au.prototype,"endpoint",void 0);class lu extends ah{constructor(){super(...arguments),this.size=20}static get styles(){return a`
6612
6643
  :host {
6613
6644
  display: flex;
6614
6645
  }
@@ -6621,7 +6652,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6621
6652
  name=${this.data.name||this.data.ref}
6622
6653
  urn=${this.data.urns.length>0?this.data.urns[0]:null}
6623
6654
  ></temba-contact-name>
6624
- <slot></slot>`:super.render()}}t([mt({type:Number,attribute:"icon-size"})],Rh.prototype,"size",void 0);class Nh extends _o{static get styles(){return a`
6655
+ <slot></slot>`:super.render()}}t([mt({type:Number,attribute:"icon-size"})],lu.prototype,"size",void 0);class du extends _o{static get styles(){return a`
6625
6656
  ${super.styles}
6626
6657
  :host {
6627
6658
  display: block;
@@ -6756,7 +6787,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6756
6787
  `:null}
6757
6788
  <slot name="postfix"></slot>
6758
6789
  </div>
6759
- `}render(){return this.renderField()}}t([mt({type:String})],Nh.prototype,"timezone",void 0),t([mt({type:String})],Nh.prototype,"timezoneFriendly",void 0),t([mt({type:Object})],Nh.prototype,"datetime",void 0),t([mt({type:Boolean})],Nh.prototype,"time",void 0),t([mt({type:String})],Nh.prototype,"min",void 0),t([mt({type:String})],Nh.prototype,"max",void 0);const Bh={text:"Text",numeric:"Number",number:"Number",datetime:"Date & Time",state:"State",ward:"Ward",district:"District"},Fh=(t,e)=>{if(!e)return!0;return(t.label+t.key+Bh[t.value_type]).toLowerCase().toLowerCase().indexOf(e)>-1};class qh extends Oc{constructor(){super(...arguments),this.otherFieldKeys=[],this.query=""}static get styles(){return a`
6790
+ `}render(){return this.renderField()}}t([mt({type:String})],du.prototype,"timezone",void 0),t([mt({type:String})],du.prototype,"timezoneFriendly",void 0),t([mt({type:Object})],du.prototype,"datetime",void 0),t([mt({type:Boolean})],du.prototype,"time",void 0),t([mt({type:String})],du.prototype,"min",void 0),t([mt({type:String})],du.prototype,"max",void 0);const cu={text:"Text",numeric:"Number",number:"Number",datetime:"Date & Time",state:"State",ward:"Ward",district:"District"},hu=(t,e)=>{if(!e)return!0;return(t.label+t.key+cu[t.value_type]).toLowerCase().toLowerCase().indexOf(e)>-1};class uu extends rh{constructor(){super(...arguments),this.otherFieldKeys=[],this.query=""}static get styles(){return a`
6760
6791
  :host {
6761
6792
  display: flex;
6762
6793
  flex-grow: 1;
@@ -6849,7 +6880,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6849
6880
  border-color: #e6e6e6;
6850
6881
  background: #fcfcfc;
6851
6882
  }
6852
- `}connectedCallback(){var t;super.connectedCallback(),(null===(t=this.store)||void 0===t?void 0:t.fieldsEndpoint)&&(this.url=this.store.fieldsEndpoint)}willUpdate(t){super.willUpdate(t),(t.has("data")||t.has("query"))&&this.filterFields()}filterFields(){const t=this.store.getFieldKeys().filter(t=>{const e=this.store.getContactField(t);return!e.featured&&Fh(e,this.query)});t.sort((t,e)=>this.store.getContactField(t).label.localeCompare(this.store.getContactField(e).label));const e=[];this.store.getFeaturedFields().forEach(t=>{Fh(t,this.query)&&e.push(t)}),this.otherFieldKeys=t,this.featuredFields=e}handleOrderChanged(t){const[e,i]=t.detail.swap,o=this.featuredFields[e];this.featuredFields.splice(e,1),this.featuredFields.splice(i,0,o),this.requestUpdate();const n=t.currentTarget;setTimeout(()=>{ue(this.priorityEndpoint,n.getIds().reverse().reduce((t,e,i)=>(t[e]=i,t),{})).then(()=>{this.store.refreshFields()})},0)}handleFieldAction(t){const e=t.target,i=e.dataset.key,o=e.dataset.action;this.fireCustomEvent(Io.Selection,{key:i,action:o})}handleSearch(t){this.query=(t.target.value||"").trim()}hasUsages(t){return t.usages.campaign_events+t.usages.flows+t.usages.groups>0}renderField(t){return W`
6883
+ `}connectedCallback(){var t;super.connectedCallback(),(null===(t=this.store)||void 0===t?void 0:t.fieldsEndpoint)&&(this.url=this.store.fieldsEndpoint)}willUpdate(t){super.willUpdate(t),(t.has("data")||t.has("query"))&&this.filterFields()}filterFields(){const t=this.store.getFieldKeys().filter(t=>{const e=this.store.getContactField(t);return!e.featured&&hu(e,this.query)});t.sort((t,e)=>this.store.getContactField(t).label.localeCompare(this.store.getContactField(e).label));const e=[];this.store.getFeaturedFields().forEach(t=>{hu(t,this.query)&&e.push(t)}),this.otherFieldKeys=t,this.featuredFields=e}handleOrderChanged(t){const[e,i]=t.detail.swap,o=this.featuredFields[e];this.featuredFields.splice(e,1),this.featuredFields.splice(i,0,o),this.requestUpdate();const n=t.currentTarget;setTimeout(()=>{ue(this.priorityEndpoint,n.getIds().reverse().reduce((t,e,i)=>(t[e]=i,t),{})).then(()=>{this.store.refreshFields()})},0)}handleFieldAction(t){const e=t.target,i=e.dataset.key,o=e.dataset.action;this.fireCustomEvent(Io.Selection,{key:i,action:o})}handleSearch(t){this.query=(t.target.value||"").trim()}hasUsages(t){return t.usages.campaign_events+t.usages.flows+t.usages.groups>0}renderField(t){return W`
6853
6884
  <div
6854
6885
  class="field sortable"
6855
6886
  id="${t.key}"
@@ -6889,7 +6920,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6889
6920
  >
6890
6921
  @fields.${t.key}
6891
6922
  </div>
6892
- <div>${Bh[t.value_type]}</div>
6923
+ <div>${cu[t.value_type]}</div>
6893
6924
  <temba-icon
6894
6925
  style="pointer-events:none;color:#ccc;margin-left:0.3em;margin-right:-0.5em;opacity:0"
6895
6926
  name="delete_small"
@@ -6936,7 +6967,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6936
6967
  ${this.otherFieldKeys.map(t=>this.renderField(this.store.getContactField(t)))}
6937
6968
  </div>
6938
6969
  </div>
6939
- `:null}}t([mt({type:String,attribute:"priority-endpoint"})],qh.prototype,"priorityEndpoint",void 0),t([mt({type:Object,attribute:!1})],qh.prototype,"featuredFields",void 0),t([mt({type:Object,attribute:!1})],qh.prototype,"otherFieldKeys",void 0),t([mt({type:String})],qh.prototype,"query",void 0);const Uh={"X-Temba-Content-Menu":"1","X-Temba-Spa":"1"};var jh;!function(t){t.LINK="link",t.JS="js",t.URL_POST="url_post",t.MODAX="modax",t.DIVIDER="divider"}(jh||(jh={}));class Hh extends Be{constructor(){super(...arguments),this.buttons=[],this.items=[]}static get styles(){return a`
6970
+ `:null}}t([mt({type:String,attribute:"priority-endpoint"})],uu.prototype,"priorityEndpoint",void 0),t([mt({type:Object,attribute:!1})],uu.prototype,"featuredFields",void 0),t([mt({type:Object,attribute:!1})],uu.prototype,"otherFieldKeys",void 0),t([mt({type:String})],uu.prototype,"query",void 0);const pu={"X-Temba-Content-Menu":"1","X-Temba-Spa":"1"};var mu;!function(t){t.LINK="link",t.JS="js",t.URL_POST="url_post",t.MODAX="modax",t.DIVIDER="divider"}(mu||(mu={}));class gu extends Be{constructor(){super(...arguments),this.buttons=[],this.items=[]}static get styles(){return a`
6940
6971
  :host {
6941
6972
  tabindex: 0;
6942
6973
  z-index: 5000;
@@ -6992,7 +7023,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
6992
7023
  .item:hover {
6993
7024
  color: var(--color-link-primary);
6994
7025
  }
6995
- `}fetchContentMenu(){const t=this.endpoint;if(t){const e=this.legacy,i=Uh;e&&delete i["Temba-Spa"],se(t,null,i).then(t=>{const e=t.json.items;e?(this.buttons=e.filter(t=>t.as_button),this.items=e.filter(t=>!t.as_button)):(this.buttons=[],this.items=[]),this.fireCustomEvent(Io.Loaded,{buttons:this.buttons,items:this.items})}).catch(t=>{this.fireCustomEvent(Io.Loaded,{buttons:this.buttons,items:this.items}),console.error(t)})}}refresh(){this.fetchContentMenu()}updated(t){super.updated(t),(t.has("endpoint")||t.has("legacy"))&&this.fetchContentMenu()}getTopCenter(t){const e=t.getBoundingClientRect();return{x:e.left+e.width/2,y:e.top}}handleItemClicked(t,e){const i=e.currentTarget,o=i?this.getTopCenter(i):{x:e.clientX,y:e.clientY};this.fireCustomEvent(Io.Selection,{item:t,event:e,originX:o.x,originY:o.y})}render(){return W`
7026
+ `}fetchContentMenu(){const t=this.endpoint;if(t){const e=this.legacy,i=pu;e&&delete i["Temba-Spa"],se(t,null,i).then(t=>{const e=t.json.items;e?(this.buttons=e.filter(t=>t.as_button),this.items=e.filter(t=>!t.as_button)):(this.buttons=[],this.items=[]),this.fireCustomEvent(Io.Loaded,{buttons:this.buttons,items:this.items})}).catch(t=>{this.fireCustomEvent(Io.Loaded,{buttons:this.buttons,items:this.items}),console.error(t)})}}refresh(){this.fetchContentMenu()}updated(t){super.updated(t),(t.has("endpoint")||t.has("legacy"))&&this.fetchContentMenu()}getTopCenter(t){const e=t.getBoundingClientRect();return{x:e.left+e.width/2,y:e.top}}handleItemClicked(t,e){const i=e.currentTarget,o=i?this.getTopCenter(i):{x:e.clientX,y:e.clientY};this.fireCustomEvent(Io.Selection,{item:t,event:e,originX:o.x,originY:o.y})}render(){return W`
6996
7027
  <div class="container">
6997
7028
  ${this.buttons.map(t=>W`<temba-button
6998
7029
  class="${t.primary?"primary_button_item":"button_item"}"
@@ -7006,7 +7037,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7006
7037
  <temba-icon name="menu" size="1.5"></temba-icon>
7007
7038
  </div>
7008
7039
  <div slot="dropdown" class="dropdown">
7009
- ${this.items.map(t=>t.type===jh.DIVIDER?W` <div class="divider"></div>`:W` <div
7040
+ ${this.items.map(t=>t.type===mu.DIVIDER?W` <div class="divider"></div>`:W` <div
7010
7041
  class="item"
7011
7042
  name=${t.label}
7012
7043
  @click=${e=>this.handleItemClicked(t,e)}
@@ -7016,23 +7047,23 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7016
7047
  </div>
7017
7048
  </temba-dropdown>`:null}
7018
7049
  </div>
7019
- `}}t([mt({type:String})],Hh.prototype,"endpoint",void 0),t([mt({type:Number})],Hh.prototype,"legacy",void 0),t([mt({type:Array,attribute:!1})],Hh.prototype,"buttons",void 0),t([mt({type:Array,attribute:!1})],Hh.prototype,"items",void 0),t([mt({type:Boolean})],Hh.prototype,"arrowTopLeft",void 0);const Wh={date:Ja.DATE_SHORT,datetime:Ja.DATETIME_SHORT,time:Ja.TIME_SIMPLE,timedate:"timedate",duration:"duration",relative:"relative",countdown:"countdown",day:"LLL d"};class Vh extends Be{constructor(){super(...arguments),this.display="date"}static get styles(){return a`
7050
+ `}}t([mt({type:String})],gu.prototype,"endpoint",void 0),t([mt({type:Number})],gu.prototype,"legacy",void 0),t([mt({type:Array,attribute:!1})],gu.prototype,"buttons",void 0),t([mt({type:Array,attribute:!1})],gu.prototype,"items",void 0),t([mt({type:Boolean})],gu.prototype,"arrowTopLeft",void 0);const fu={date:Ja.DATE_SHORT,datetime:Ja.DATETIME_SHORT,time:Ja.TIME_SIMPLE,timedate:"timedate",duration:"duration",relative:"relative",countdown:"countdown",day:"LLL d"};class vu extends Be{constructor(){super(...arguments),this.display="date"}static get styles(){return a`
7020
7051
  .date {
7021
7052
  display: inline;
7022
7053
  }
7023
- `}connectedCallback(){super.connectedCallback(),this.store=document.querySelector("temba-store")}willUpdate(t){super.willUpdate(t),t.has("value")&&(this.datetime=Ja.fromISO(this.value))}render(){if(this.datetime&&this.store){this.datetime.setLocale(this.store.getLocale());let t="";if(this.display===Wh.timedate){const e=Math.abs(this.datetime.diffNow().milliseconds/1e3/60/60),i=this.datetime.get("day");t=e<24&&i==Ja.now().get("day")?this.datetime.toLocaleString(Wh.time):e<8760?this.datetime.toFormat(Wh.day):this.datetime.toLocaleString(Wh.date)}else if(this.display===Wh.relative){if(Math.abs(this.datetime.diffNow().milliseconds/1e3/60)<1)return W`<span
7054
+ `}connectedCallback(){super.connectedCallback(),this.store=document.querySelector("temba-store")}willUpdate(t){super.willUpdate(t),t.has("value")&&(this.datetime=Ja.fromISO(this.value))}render(){if(this.datetime&&this.store){this.datetime.setLocale(this.store.getLocale());let t="";if(this.display===fu.timedate){const e=Math.abs(this.datetime.diffNow().milliseconds/1e3/60/60),i=this.datetime.get("day");t=e<24&&i==Ja.now().get("day")?this.datetime.toLocaleString(fu.time):e<8760?this.datetime.toFormat(fu.day):this.datetime.toLocaleString(fu.date)}else if(this.display===fu.relative){if(Math.abs(this.datetime.diffNow().milliseconds/1e3/60)<1)return W`<span
7024
7055
  class="date"
7025
- title="${this.datetime.toLocaleString(Wh.datetime)}"
7056
+ title="${this.datetime.toLocaleString(fu.datetime)}"
7026
7057
  >just now</span
7027
- >`;t=this.store.getShortDuration(this.datetime)}else if(this.display===Wh.duration){if(Math.abs(this.datetime.diffNow().milliseconds/1e3/60)<1)return W`<span
7058
+ >`;t=this.store.getShortDuration(this.datetime)}else if(this.display===fu.duration){if(Math.abs(this.datetime.diffNow().milliseconds/1e3/60)<1)return W`<span
7028
7059
  class="date"
7029
- title="${this.datetime.toLocaleString(Wh.datetime)}"
7060
+ title="${this.datetime.toLocaleString(fu.datetime)}"
7030
7061
  >just now</span
7031
- >`;t=this.store.getShortDuration(this.datetime)}else t=this.display===Wh.countdown?this.store.getCountdown(this.datetime):this.display===Wh.day?this.datetime.toLocaleString(Wh.day):this.datetime.toLocaleString(Wh[this.display]);return W`<span
7062
+ >`;t=this.store.getShortDuration(this.datetime)}else t=this.display===fu.countdown?this.store.getCountdown(this.datetime):this.display===fu.day?this.datetime.toLocaleString(fu.day):this.datetime.toLocaleString(fu[this.display]);return W`<span
7032
7063
  class="date"
7033
- title="${this.datetime.toLocaleString(Wh.datetime)}"
7064
+ title="${this.datetime.toLocaleString(fu.datetime)}"
7034
7065
  >${t}</span
7035
- >`}}}t([mt({type:String})],Vh.prototype,"value",void 0),t([mt({type:String})],Vh.prototype,"display",void 0),t([mt({type:Object,attribute:!1})],Vh.prototype,"datetime",void 0);class Zh extends _o{static get styles(){return a`
7066
+ >`}}}t([mt({type:String})],vu.prototype,"value",void 0),t([mt({type:String})],vu.prototype,"display",void 0),t([mt({type:Object,attribute:!1})],vu.prototype,"datetime",void 0);class bu extends _o{static get styles(){return a`
7036
7067
  :host {
7037
7068
  border-top-right-radius: var(--curvature);
7038
7069
  border-top-left-radius: var(--curvature);
@@ -7135,7 +7166,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7135
7166
  background: rgba(0, 0, 0, 0.08);
7136
7167
  }
7137
7168
 
7138
- `}constructor(){super(),this.index=1,this.maxAttachments=3,this.maxLength=640,this.maxQuickReplies=10,this.templateSession=!1,this.minHeight=150,this.currentText="",this.initialText="",this.accept="",this.endpoint=te,this.languages=[],this.currentAttachments=[],this.currentQuickReplies=[],this.currentOptin=[],this.variables=[],this.optinEndpoint="/api/v2/optins.json",this.templateEndpoint="/api/internal/templates.json",this.empty=!0,this.langValues={},this.currentLanguage="und",this.hasPendingText=!1,this.showShortcuts=!1,this.shortcutFilter=null,this.shortcutViaIcon=!1,this.lastCaretPosition=0,this.handleHostKeyDown=t=>{if("Escape"===t.key&&this.showShortcuts)return t.preventDefault(),t.stopPropagation(),void(this.showShortcuts=!1);if("Enter"===t.key&&!t.shiftKey){if(this.showShortcuts)return;const e=this.getMessageEditor();if(e){const t=e.getRichEditor();if(t&&t.hasVisibleOptions())return}t.preventDefault(),t.stopPropagation(),this.triggerSend()}}}isBaseLanguage(){return"und"==this.currentLanguage||this.currentLanguage==this.languages[0].iso}willUpdate(t){var e,i;if(super.willUpdate(t),t.has("languages")&&this.languages.length>0&&(this.currentLanguage=this.languages[0].iso),t.has("value")&&(this.langValues=this.getDeserializedValue()||{},this.variables=(null===(e=this.langValues[this.currentLanguage])||void 0===e?void 0:e.variables)||[],this.template=(null===(i=this.langValues[this.currentLanguage])||void 0===i?void 0:i.template)||null),t.has("currentLanguage")&&this.langValues){let t={text:"",attachments:[],quick_replies:[]};this.currentLanguage in this.langValues&&(t=this.langValues[this.currentLanguage]),this.currentText=t.text||"",this.initialText=t.text||"",this.currentAttachments=t.attachments||[],this.currentQuickReplies=(t.quick_replies||[]).map(t=>({name:t,value:t})),this.currentOptin=t.optin?[t.optin]:[]}if(this.langValues&&(t.has("currentText")||t.has("currentAttachments")||t.has("currentQuickReplies")||t.has("currentOptin")||t.has("currentTemplate")||t.has("variables"))){this.checkIfEmpty();const t=this.currentText?this.currentText.trim():"";t||(this.currentAttachments||[]).length>0||this.currentQuickReplies.length>0||this.currentOptin.length>0||this.variables.length>0?this.langValues[this.currentLanguage]={text:t,attachments:this.currentAttachments,quick_replies:this.currentQuickReplies.map(t=>t.value),optin:this.currentOptin.length>0?this.currentOptin[0]:null,template:this.currentTemplate?this.currentTemplate.uuid:null,variables:this.variables,locale:this.locale}:delete this.langValues[this.currentLanguage],this.setValue(this.langValues)}}connectedCallback(){super.connectedCallback(),this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),this.addEventListener("keydown",this.handleHostKeyDown)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("keydown",this.handleHostKeyDown)}handleShortcutIconClick(){this.showShortcuts?this.showShortcuts=!1:(this.shortcutFilter="",this.shortcutViaIcon=!0,this.showShortcuts=!0,this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("temba-shortcuts");t&&(t.filter="",t.showSearch=!0,t.updateComplete.then(()=>{t.focusSearch()}))}))}firstUpdated(t){super.firstUpdated(t),this.setFocusOnEditor()}updated(t){if(super.updated(t),t.has("currentLanguage")&&this.langValues){this.setFocusOnEditor();const t=this.getMessageEditor();if(t){const e=t.getRichEditor();e&&(e.value=this.initialText)}}(this.langValues&&(t.has("currentText")||t.has("currentAttachments")||t.has("currentQuickReplies"))||t.has("currentOptin")||t.has("currentTemplate")||t.has("variables"))&&this.fireCustomEvent(Io.ContentChanged,this.langValues)}handleLoading(t){this.uploading=t.detail.loading}handleAttachmentsChanged(t){t.detail&&t.detail.attachments&&(this.currentAttachments=t.detail.attachments),this.requestUpdate()}setFocusOnEditor(){const t=this.getMessageEditor();t&&window.setTimeout(()=>{t.focus()},0)}reset(){const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){e.getTextInput().updateValue(""),e.fireEvent("change")}this.initialText="",this.currentText="",this.currentQuickReplies=[],this.currentAttachments=[],this.showShortcuts=!1}}handleQuickReplyChange(){this.requestUpdate("currentQuickReplies")}handleOptInChange(t){this.currentOptin=t.target.values,this.requestUpdate("currentOptin")}handleEditorChange(t){const e=t.target.getRichEditor();if(e&&(this.currentText=e.value||"",this.hasPendingText=this.currentText.length>0,this.lastCaretPosition=e.getCaretPosition(),this.shortcuts)){const t=this.currentText,i=e.getCaretPosition(),o=t.lastIndexOf("\n",i-1)+1,n=t.substring(o,i);n.startsWith("/")?(this.showShortcuts||(this.shortcutViaIcon=!1),this.shortcutFilter=n.substring(1),this.showShortcuts=!0,this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("temba-shortcuts");t&&(t.showSearch=!1,t.filter=this.shortcutFilter)})):this.showShortcuts=!1}}checkIfEmpty(){const t=0===this.currentText.trim().length,e=0===this.currentAttachments.length;this.attachments?this.empty=t&&e:this.empty=t}handleKeyDown(t){if("Backspace"===t.key&&this.shortcuts&&this.showShortcuts){const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){const t=e.getText(),i=e.getCaretPosition(),o=t.lastIndexOf("\n",i-1)+1;"/"===t.substring(o,i)&&(this.showShortcuts=!1)}}}}triggerSend(){this.checkIfEmpty(),this.empty||this.fireCustomEvent(Io.Submitted,{langValues:this.langValues})}handleLanguageChange(t){const e=t.target;this.currentLanguage=e.values[0].iso}getShortcutOverlayStyle(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".container");if(!e)return"";const i=e.getBoundingClientRect(),o=window.innerHeight-i.top,n=i.top-16;return`left: ${i.left}px; bottom: ${o}px; width: ${i.width}px; max-height: ${n}px;`}getMessageEditor(){return this.shadowRoot.querySelector("temba-message-editor")}handleShortcutSelection(t){this.activeShortcut=t.detail.selected;const e=this.getMessageEditor();if(!e)return;const i=e.getRichEditor();if(!i)return;const o=i.getText(),n=i.getCaretPosition()||this.lastCaretPosition,s=o.lastIndexOf("\n",n-1)+1;let r=o.indexOf("\n",s);-1===r&&(r=o.length);let a,l;if(o.substring(s,r).startsWith("/")){const t=o.substring(0,s),e=o.substring(r);a=t+this.activeShortcut.text+e,l=s+this.activeShortcut.text.length}else a=o.substring(0,n)+this.activeShortcut.text+o.substring(n),l=n+this.activeShortcut.text.length;i.getTextInput().updateValue(a),i.fireEvent("change");const d=i.inputElement;d&&(d.focus(),ac(d,l)),this.showShortcuts=!1}handleTemplateChanged(t){var e;this.currentTemplate=t.detail.template,this.locale=null===(e=t.detail.translation)||void 0===e?void 0:e.locale,this.requestUpdate()}handleTemplateVariablesChanged(t){this.variables=[...t.detail.variables]}render(){return this.renderField()}renderWidget(){const t=this.optIns&&this.isBaseLanguage(),e=this.templates&&this.isBaseLanguage(),i=this.quickReplies||t||e;return W`
7169
+ `}constructor(){super(),this.index=1,this.maxAttachments=3,this.maxLength=640,this.maxQuickReplies=10,this.templateSession=!1,this.minHeight=150,this.currentText="",this.initialText="",this.accept="",this.endpoint=te,this.languages=[],this.currentAttachments=[],this.currentQuickReplies=[],this.currentOptin=[],this.variables=[],this.optinEndpoint="/api/v2/optins.json",this.templateEndpoint="/api/internal/templates.json",this.empty=!0,this.langValues={},this.currentLanguage="und",this.hasPendingText=!1,this.showShortcuts=!1,this.shortcutFilter=null,this.shortcutViaIcon=!1,this.lastCaretPosition=0,this.handleHostKeyDown=t=>{if("Escape"===t.key&&this.showShortcuts)return t.preventDefault(),t.stopPropagation(),void(this.showShortcuts=!1);if("Enter"===t.key&&!t.shiftKey){if(this.showShortcuts)return;const e=this.getMessageEditor();if(e){const t=e.getRichEditor();if(t&&t.hasVisibleOptions())return}t.preventDefault(),t.stopPropagation(),this.triggerSend()}}}isBaseLanguage(){return"und"==this.currentLanguage||this.currentLanguage==this.languages[0].iso}willUpdate(t){var e,i;if(super.willUpdate(t),t.has("languages")&&this.languages.length>0&&(this.currentLanguage=this.languages[0].iso),t.has("value")&&(this.langValues=this.getDeserializedValue()||{},this.variables=(null===(e=this.langValues[this.currentLanguage])||void 0===e?void 0:e.variables)||[],this.template=(null===(i=this.langValues[this.currentLanguage])||void 0===i?void 0:i.template)||null),t.has("currentLanguage")&&this.langValues){let t={text:"",attachments:[],quick_replies:[]};this.currentLanguage in this.langValues&&(t=this.langValues[this.currentLanguage]),this.currentText=t.text||"",this.initialText=t.text||"",this.currentAttachments=t.attachments||[],this.currentQuickReplies=(t.quick_replies||[]).map(t=>({name:t,value:t})),this.currentOptin=t.optin?[t.optin]:[]}if(this.langValues&&(t.has("currentText")||t.has("currentAttachments")||t.has("currentQuickReplies")||t.has("currentOptin")||t.has("currentTemplate")||t.has("variables"))){this.checkIfEmpty();const t=this.currentText?this.currentText.trim():"";t||(this.currentAttachments||[]).length>0||this.currentQuickReplies.length>0||this.currentOptin.length>0||this.variables.length>0?this.langValues[this.currentLanguage]={text:t,attachments:this.currentAttachments,quick_replies:this.currentQuickReplies.map(t=>t.value),optin:this.currentOptin.length>0?this.currentOptin[0]:null,template:this.currentTemplate?this.currentTemplate.uuid:null,variables:this.variables,locale:this.locale}:delete this.langValues[this.currentLanguage],this.setValue(this.langValues)}}connectedCallback(){super.connectedCallback(),this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),this.addEventListener("keydown",this.handleHostKeyDown)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("keydown",this.handleHostKeyDown)}handleShortcutIconClick(){this.showShortcuts?this.showShortcuts=!1:(this.shortcutFilter="",this.shortcutViaIcon=!0,this.showShortcuts=!0,this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("temba-shortcuts");t&&(t.filter="",t.showSearch=!0,t.updateComplete.then(()=>{t.focusSearch()}))}))}firstUpdated(t){super.firstUpdated(t),this.setFocusOnEditor()}updated(t){if(super.updated(t),t.has("currentLanguage")&&this.langValues){this.setFocusOnEditor();const t=this.getMessageEditor();if(t){const e=t.getRichEditor();e&&(e.value=this.initialText)}}(this.langValues&&(t.has("currentText")||t.has("currentAttachments")||t.has("currentQuickReplies"))||t.has("currentOptin")||t.has("currentTemplate")||t.has("variables"))&&this.fireCustomEvent(Io.ContentChanged,this.langValues)}handleLoading(t){this.uploading=t.detail.loading}handleAttachmentsChanged(t){t.detail&&t.detail.attachments&&(this.currentAttachments=t.detail.attachments),this.requestUpdate()}setFocusOnEditor(){const t=this.getMessageEditor();t&&window.setTimeout(()=>{t.focus()},0)}reset(){const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){e.getTextInput().updateValue(""),e.fireEvent("change")}this.initialText="",this.currentText="",this.currentQuickReplies=[],this.currentAttachments=[],this.showShortcuts=!1}}handleQuickReplyChange(){this.requestUpdate("currentQuickReplies")}handleOptInChange(t){this.currentOptin=t.target.values,this.requestUpdate("currentOptin")}handleEditorChange(t){const e=t.target.getRichEditor();if(e&&(this.currentText=e.value||"",this.hasPendingText=this.currentText.length>0,this.lastCaretPosition=e.getCaretPosition(),this.shortcuts)){const t=this.currentText,i=e.getCaretPosition(),o=t.lastIndexOf("\n",i-1)+1,n=t.substring(o,i);n.startsWith("/")?(this.showShortcuts||(this.shortcutViaIcon=!1),this.shortcutFilter=n.substring(1),this.showShortcuts=!0,this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("temba-shortcuts");t&&(t.showSearch=!1,t.filter=this.shortcutFilter)})):this.showShortcuts=!1}}checkIfEmpty(){const t=0===this.currentText.trim().length,e=0===this.currentAttachments.length;this.attachments?this.empty=t&&e:this.empty=t}handleKeyDown(t){if("Backspace"===t.key&&this.shortcuts&&this.showShortcuts){const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){const t=e.getText(),i=e.getCaretPosition(),o=t.lastIndexOf("\n",i-1)+1;"/"===t.substring(o,i)&&(this.showShortcuts=!1)}}}}triggerSend(){this.checkIfEmpty(),this.empty||this.fireCustomEvent(Io.Submitted,{langValues:this.langValues})}handleLanguageChange(t){const e=t.target;this.currentLanguage=e.values[0].iso}getShortcutOverlayStyle(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".container");if(!e)return"";const i=e.getBoundingClientRect(),o=window.innerHeight-i.top,n=i.top-16;return`left: ${i.left}px; bottom: ${o}px; width: ${i.width}px; max-height: ${n}px;`}getMessageEditor(){return this.shadowRoot.querySelector("temba-message-editor")}handleShortcutSelection(t){this.activeShortcut=t.detail.selected;const e=this.getMessageEditor();if(!e)return;const i=e.getRichEditor();if(!i)return;const o=i.getText(),n=i.getCaretPosition()||this.lastCaretPosition,s=o.lastIndexOf("\n",n-1)+1;let r=o.indexOf("\n",s);-1===r&&(r=o.length);let a,l;if(o.substring(s,r).startsWith("/")){const t=o.substring(0,s),e=o.substring(r);a=t+this.activeShortcut.text+e,l=s+this.activeShortcut.text.length}else a=o.substring(0,n)+this.activeShortcut.text+o.substring(n),l=n+this.activeShortcut.text.length;i.getTextInput().updateValue(a),i.fireEvent("change");const d=i.inputElement;d&&(d.focus(),Nc(d,l)),this.showShortcuts=!1}handleTemplateChanged(t){var e;this.currentTemplate=t.detail.template,this.locale=null===(e=t.detail.translation)||void 0===e?void 0:e.locale,this.requestUpdate()}handleTemplateVariablesChanged(t){this.variables=[...t.detail.variables]}render(){return this.renderField()}renderWidget(){const t=this.optIns&&this.isBaseLanguage(),e=this.templates&&this.isBaseLanguage(),i=this.quickReplies||t||e;return W`
7139
7170
  <div>
7140
7171
  ${this.languages.length>1?W`<temba-select
7141
7172
  @change=${this.handleLanguageChange}
@@ -7239,7 +7270,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7239
7270
  </temba-accordion-section>`:null}
7240
7271
  </temba-accordion>`:null}
7241
7272
  </div>
7242
- `}}t([mt({type:Number})],Zh.prototype,"index",void 0),t([mt({type:Number})],Zh.prototype,"maxAttachments",void 0),t([mt({type:Number})],Zh.prototype,"maxLength",void 0),t([mt({type:Number})],Zh.prototype,"maxQuickReplies",void 0),t([mt({type:Boolean})],Zh.prototype,"completion",void 0),t([mt({type:Boolean})],Zh.prototype,"attachments",void 0),t([mt({type:Boolean})],Zh.prototype,"quickReplies",void 0),t([mt({type:Boolean})],Zh.prototype,"optIns",void 0),t([mt({type:Boolean})],Zh.prototype,"templates",void 0),t([mt({type:Boolean,attribute:"template-session"})],Zh.prototype,"templateSession",void 0),t([mt({type:String,attribute:"template-warning"})],Zh.prototype,"templateWarning",void 0),t([mt({type:Boolean})],Zh.prototype,"counter",void 0),t([mt({type:Boolean})],Zh.prototype,"autogrow",void 0),t([mt({type:Number,attribute:"min-height"})],Zh.prototype,"minHeight",void 0),t([mt({type:Boolean})],Zh.prototype,"shortcuts",void 0),t([mt({type:String})],Zh.prototype,"currentText",void 0),t([mt({type:String})],Zh.prototype,"initialText",void 0),t([mt({type:String})],Zh.prototype,"accept",void 0),t([mt({type:String,attribute:!1})],Zh.prototype,"endpoint",void 0),t([mt({type:Boolean,attribute:!1})],Zh.prototype,"uploading",void 0),t([mt({type:Array})],Zh.prototype,"languages",void 0),t([mt({type:Array})],Zh.prototype,"currentAttachments",void 0),t([mt({type:Array})],Zh.prototype,"currentQuickReplies",void 0),t([mt({type:Array})],Zh.prototype,"currentOptin",void 0),t([mt({type:Array})],Zh.prototype,"variables",void 0),t([mt({type:String})],Zh.prototype,"template",void 0),t([mt({type:Object})],Zh.prototype,"currentTemplate",void 0),t([mt({type:String})],Zh.prototype,"locale",void 0),t([mt({type:String})],Zh.prototype,"optinEndpoint",void 0),t([mt({type:String})],Zh.prototype,"templateEndpoint",void 0),t([mt({type:Boolean,attribute:!1})],Zh.prototype,"empty",void 0),t([mt({type:Boolean,attribute:"widget_only"})],Zh.prototype,"widgetOnly",void 0),t([mt({type:Array})],Zh.prototype,"errors",void 0),t([mt({type:Object})],Zh.prototype,"langValues",void 0),t([mt({type:String})],Zh.prototype,"currentLanguage",void 0),t([mt({type:Boolean})],Zh.prototype,"hasPendingText",void 0),t([mt({type:Object})],Zh.prototype,"activeShortcut",void 0),t([mt({type:Boolean,attribute:!1})],Zh.prototype,"showShortcuts",void 0);class Yh extends Be{constructor(){super(...arguments),this.animationTime=300,this.show=!1,this.zoom=!1,this.zoomPct=.9,this.scale=1,this.xTrans=0,this.yTrans=0}static get styles(){return a`
7273
+ `}}t([mt({type:Number})],bu.prototype,"index",void 0),t([mt({type:Number})],bu.prototype,"maxAttachments",void 0),t([mt({type:Number})],bu.prototype,"maxLength",void 0),t([mt({type:Number})],bu.prototype,"maxQuickReplies",void 0),t([mt({type:Boolean})],bu.prototype,"completion",void 0),t([mt({type:Boolean})],bu.prototype,"attachments",void 0),t([mt({type:Boolean})],bu.prototype,"quickReplies",void 0),t([mt({type:Boolean})],bu.prototype,"optIns",void 0),t([mt({type:Boolean})],bu.prototype,"templates",void 0),t([mt({type:Boolean,attribute:"template-session"})],bu.prototype,"templateSession",void 0),t([mt({type:String,attribute:"template-warning"})],bu.prototype,"templateWarning",void 0),t([mt({type:Boolean})],bu.prototype,"counter",void 0),t([mt({type:Boolean})],bu.prototype,"autogrow",void 0),t([mt({type:Number,attribute:"min-height"})],bu.prototype,"minHeight",void 0),t([mt({type:Boolean})],bu.prototype,"shortcuts",void 0),t([mt({type:String})],bu.prototype,"currentText",void 0),t([mt({type:String})],bu.prototype,"initialText",void 0),t([mt({type:String})],bu.prototype,"accept",void 0),t([mt({type:String,attribute:!1})],bu.prototype,"endpoint",void 0),t([mt({type:Boolean,attribute:!1})],bu.prototype,"uploading",void 0),t([mt({type:Array})],bu.prototype,"languages",void 0),t([mt({type:Array})],bu.prototype,"currentAttachments",void 0),t([mt({type:Array})],bu.prototype,"currentQuickReplies",void 0),t([mt({type:Array})],bu.prototype,"currentOptin",void 0),t([mt({type:Array})],bu.prototype,"variables",void 0),t([mt({type:String})],bu.prototype,"template",void 0),t([mt({type:Object})],bu.prototype,"currentTemplate",void 0),t([mt({type:String})],bu.prototype,"locale",void 0),t([mt({type:String})],bu.prototype,"optinEndpoint",void 0),t([mt({type:String})],bu.prototype,"templateEndpoint",void 0),t([mt({type:Boolean,attribute:!1})],bu.prototype,"empty",void 0),t([mt({type:Boolean,attribute:"widget_only"})],bu.prototype,"widgetOnly",void 0),t([mt({type:Array})],bu.prototype,"errors",void 0),t([mt({type:Object})],bu.prototype,"langValues",void 0),t([mt({type:String})],bu.prototype,"currentLanguage",void 0),t([mt({type:Boolean})],bu.prototype,"hasPendingText",void 0),t([mt({type:Object})],bu.prototype,"activeShortcut",void 0),t([mt({type:Boolean,attribute:!1})],bu.prototype,"showShortcuts",void 0);class yu extends Be{constructor(){super(...arguments),this.animationTime=300,this.show=!1,this.zoom=!1,this.zoomPct=.9,this.scale=1,this.xTrans=0,this.yTrans=0}static get styles(){return a`
7243
7274
  :host {
7244
7275
  z-index: 10000;
7245
7276
  position: absolute;
@@ -7295,7 +7326,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7295
7326
  ${this.show?W`${this.ele}`:null}
7296
7327
  </div>
7297
7328
  </div>
7298
- `}}t([mt({type:Number})],Yh.prototype,"animationTime",void 0),t([mt({type:Boolean})],Yh.prototype,"show",void 0),t([mt({type:Boolean})],Yh.prototype,"zoom",void 0),t([mt({type:Number})],Yh.prototype,"zoomPct",void 0);class Kh extends _o{constructor(){super(...arguments),this.expanded=!1,this.previewColor="#ffffff",this.labelColor="#ffffffee",this.selecting=!1,this.saturation=100,this.lightness=50,this.hex=""}static get styles(){return a`
7329
+ `}}t([mt({type:Number})],yu.prototype,"animationTime",void 0),t([mt({type:Boolean})],yu.prototype,"show",void 0),t([mt({type:Boolean})],yu.prototype,"zoom",void 0),t([mt({type:Number})],yu.prototype,"zoomPct",void 0);class xu extends _o{constructor(){super(...arguments),this.expanded=!1,this.previewColor="#ffffff",this.labelColor="#ffffffee",this.selecting=!1,this.saturation=100,this.lightness=50,this.hex=""}static get styles(){return a`
7299
7330
  ${super.styles}
7300
7331
 
7301
7332
  :host {
@@ -7429,7 +7460,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7429
7460
  ></temba-textinput>
7430
7461
  </div>
7431
7462
  </div>
7432
- `}}t([mt({type:Boolean})],Kh.prototype,"expanded",void 0),t([mt({type:String})],Kh.prototype,"previewColor",void 0),t([mt({type:String})],Kh.prototype,"labelColor",void 0),t([mt({type:Boolean})],Kh.prototype,"selecting",void 0),t([mt({type:Number})],Kh.prototype,"hue",void 0),t([mt({type:Number})],Kh.prototype,"saturation",void 0),t([mt({type:Number})],Kh.prototype,"lightness",void 0),t([mt({type:String})],Kh.prototype,"hex",void 0);class Gh extends vc{constructor(){super(),this.minWidth=200,this.maxWidth=2e3,this.resizing=!1,this.startResize=this.startResize.bind(this),this.resize=this.resize.bind(this),this.stopResize=this.stopResize.bind(this)}updated(t){super.updated(t),t.has("currentWidth")&&this.style.setProperty("--box-width",`${this.currentWidth}px`)}setWidth(t){const e=Math.min(Math.max(t,this.minWidth),this.maxWidth);this.currentWidth=e}startResize(t){this.initialX=t.x,this.boxWidth=this.offsetWidth,document.body.style.userSelect="none",this.resizing=!0,window.addEventListener("mousemove",this.resize),window.addEventListener("mouseup",this.stopResize),this.requestUpdate()}resize(t){const e=t.x-this.initialX;this.setWidth(this.boxWidth+e)}stopResize(){document.body.style.userSelect="initial",window.removeEventListener("mousemove",this.resize),window.removeEventListener("mouseup",this.stopResize),this.requestUpdate(),this.resizing=!1,this.fireCustomEvent(Io.Resized,{width:this.currentWidth})}render(){return W`
7463
+ `}}t([mt({type:Boolean})],xu.prototype,"expanded",void 0),t([mt({type:String})],xu.prototype,"previewColor",void 0),t([mt({type:String})],xu.prototype,"labelColor",void 0),t([mt({type:Boolean})],xu.prototype,"selecting",void 0),t([mt({type:Number})],xu.prototype,"hue",void 0),t([mt({type:Number})],xu.prototype,"saturation",void 0),t([mt({type:Number})],xu.prototype,"lightness",void 0),t([mt({type:String})],xu.prototype,"hex",void 0);class wu extends Uc{constructor(){super(),this.minWidth=200,this.maxWidth=2e3,this.resizing=!1,this.startResize=this.startResize.bind(this),this.resize=this.resize.bind(this),this.stopResize=this.stopResize.bind(this)}updated(t){super.updated(t),t.has("currentWidth")&&this.style.setProperty("--box-width",`${this.currentWidth}px`)}setWidth(t){const e=Math.min(Math.max(t,this.minWidth),this.maxWidth);this.currentWidth=e}startResize(t){this.initialX=t.x,this.boxWidth=this.offsetWidth,document.body.style.userSelect="none",this.resizing=!0,window.addEventListener("mousemove",this.resize),window.addEventListener("mouseup",this.stopResize),this.requestUpdate()}resize(t){const e=t.x-this.initialX;this.setWidth(this.boxWidth+e)}stopResize(){document.body.style.userSelect="initial",window.removeEventListener("mousemove",this.resize),window.removeEventListener("mouseup",this.stopResize),this.requestUpdate(),this.resizing=!1,this.fireCustomEvent(Io.Resized,{width:this.currentWidth})}render(){return W`
7433
7464
  <div
7434
7465
  class=${re({resizer:!0,resizing:this.resizing})}
7435
7466
  @mousedown="${this.startResize}"
@@ -7437,7 +7468,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7437
7468
  <div class=${re({"resizer-handle":!0})}></div>
7438
7469
  </div>
7439
7470
  <slot></slot>
7440
- `}}var Xh,Qh;Gh.styles=a`
7471
+ `}}var _u,ku;wu.styles=a`
7441
7472
  :host {
7442
7473
  display: block;
7443
7474
  position: relative;
@@ -7477,7 +7508,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7477
7508
  margin-right: var(--resizer-handle-size);
7478
7509
  background: red;
7479
7510
  }
7480
- `,t([mt({type:Number})],Gh.prototype,"minWidth",void 0),t([mt({type:Number})],Gh.prototype,"maxWidth",void 0),t([mt({type:Boolean})],Gh.prototype,"resizing",void 0),t([mt({type:Number})],Gh.prototype,"currentWidth",void 0),function(t){t.send="send-03",t.attachment="paperclip",t.attachment_audio="volume-min",t.attachment_document="file-06",t.attachment_image="image-01",t.attachment_location="marker-pin-01",t.attachment_video="video-recorder"}(Xh||(Xh={})),function(t){t.IMAGE="image",t.AUDIO="audio",t.VIDEO="video",t.DOCUMENT="document",t.LOCATION="location",t.OTHER="other"}(Qh||(Qh={}));const Jh={[Qh.IMAGE]:Xh.attachment_image,[Qh.AUDIO]:Xh.attachment_audio,[Qh.VIDEO]:Xh.attachment_video,[Qh.DOCUMENT]:Xh.attachment_document,[Qh.OTHER]:Xh.attachment};class tu extends Be{constructor(){super(...arguments),this.ratio=0,this.preview=!0,this.tileUrl="",this.audio=null,this.audioPlaying=!1,this.audioProgress=0,this.audioDuration=0}static get styles(){return a`
7511
+ `,t([mt({type:Number})],wu.prototype,"minWidth",void 0),t([mt({type:Number})],wu.prototype,"maxWidth",void 0),t([mt({type:Boolean})],wu.prototype,"resizing",void 0),t([mt({type:Number})],wu.prototype,"currentWidth",void 0),function(t){t.send="send-03",t.attachment="paperclip",t.attachment_audio="volume-min",t.attachment_document="file-06",t.attachment_image="image-01",t.attachment_location="marker-pin-01",t.attachment_video="video-recorder"}(_u||(_u={})),function(t){t.IMAGE="image",t.AUDIO="audio",t.VIDEO="video",t.DOCUMENT="document",t.LOCATION="location",t.OTHER="other"}(ku||(ku={}));const Cu={[ku.IMAGE]:_u.attachment_image,[ku.AUDIO]:_u.attachment_audio,[ku.VIDEO]:_u.attachment_video,[ku.DOCUMENT]:_u.attachment_document,[ku.OTHER]:_u.attachment};class Su extends Be{constructor(){super(...arguments),this.ratio=0,this.preview=!0,this.tileUrl="",this.audio=null,this.audioPlaying=!1,this.audioProgress=0,this.audioDuration=0}static get styles(){return a`
7481
7512
  :host {
7482
7513
  display: inline;
7483
7514
  }
@@ -7601,17 +7632,17 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7601
7632
  background: rgba(0, 0, 0, 0.6);
7602
7633
  cursor: pointer;
7603
7634
  }
7604
- `}handleAudioPlayClick(t){t.stopPropagation(),this.audio||(this.audio=new Audio(this.url),this.audio.addEventListener("timeupdate",()=>{this.audio.duration&&(this.audioProgress=this.audio.currentTime/this.audio.duration,this.audioDuration=this.audio.duration)}),this.audio.addEventListener("ended",()=>{this.audioPlaying=!1,this.audioProgress=0}),this.audio.addEventListener("error",()=>{this.audioPlaying=!1,this.audioProgress=0})),this.audioPlaying?(this.audio.pause(),this.audioPlaying=!1):(this.audio.play().catch(()=>{this.audioPlaying=!1}),this.audioPlaying=!0)}handleProgressClick(t){if(t.stopPropagation(),!this.audio||!this.audio.duration)return;const e=t.currentTarget.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.audio.currentTime=i*this.audio.duration}formatTime(t){const e=Math.floor(t);return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`}disconnectedCallback(){super.disconnectedCallback(),this.audio&&(this.audio.pause(),this.audio=null)}latLngToTile(t,e,i){const o=Math.pow(2,i),n=Math.floor((e+180)/360*o),s=t*Math.PI/180;return{x:n,y:Math.floor((1-Math.log(Math.tan(s)+1/Math.cos(s))/Math.PI)/2*o),z:i}}willUpdate(t){if(super.willUpdate(t),t.has("attachment")&&this.attachment){const t=this.attachment.indexOf(":");if(-1===t)this.url=this.attachment;else{const e=this.attachment.substring(0,t);if(this.url=this.attachment.substring(t+1),e.startsWith("image"))this.contentType=Qh.IMAGE;else if(e.startsWith("audio"))this.contentType=Qh.AUDIO;else if(e.startsWith("video"))this.contentType=Qh.VIDEO;else if(e.startsWith("application"))this.contentType=Qh.DOCUMENT;else if(e.startsWith("geo")){this.contentType=Qh.LOCATION;const t=this.url.match(/^([^,]+),([^,]+)/);if(t){this.latitude=parseFloat(t[1]),this.longitude=parseFloat(t[2]);const e=this.latLngToTile(this.latitude,this.longitude,13);this.tileUrl=`https://tile.openstreetmap.org/${e.z}/${e.x}/${e.y}.png`}}else this.contentType=Qh.OTHER}}if(t.has("latitude")||t.has("longitude"))if(void 0===this.latitude||void 0===this.longitude||isNaN(this.latitude)||isNaN(this.longitude))this.tileUrl="";else{const t=this.latLngToTile(this.latitude,this.longitude,13);this.tileUrl=`https://tile.openstreetmap.org/${t.z}/${t.x}/${t.y}.png`}}updated(t){if(super.updated(t),t.has("contentType")&&this.contentType===Qh.IMAGE){const t=this.shadowRoot.querySelector(".observe");t&&new ResizeObserver((e,i)=>{t.clientHeight>0&&t.clientWidth>0&&(this.ratio=t.clientHeight/t.clientWidth,this.preview=0===this.ratio||this.ratio>.25&&this.ratio<=1.5,i.disconnect())}).observe(t)}}handleThumbnailClicked(){if(this.contentType===Qh.IMAGE&&this.preview)window.setTimeout(()=>{document.querySelector("temba-lightbox").showElement(this)},100);else if(this.contentType===Qh.LOCATION){const t=`https://www.openstreetmap.org/?mlat=${this.latitude}&mlon=${this.longitude}#map=15/${this.latitude}/${this.longitude}`;window.open(t,"_blank")}else this.contentType===Qh.AUDIO||window.open(this.url,"_blank")}handleDownload(t){t.stopPropagation(),t.preventDefault(),window.open(this.url,"_blank")}render(){var t;return W`
7635
+ `}handleAudioPlayClick(t){t.stopPropagation(),this.audio||(this.audio=new Audio(this.url),this.audio.addEventListener("timeupdate",()=>{this.audio.duration&&(this.audioProgress=this.audio.currentTime/this.audio.duration,this.audioDuration=this.audio.duration)}),this.audio.addEventListener("ended",()=>{this.audioPlaying=!1,this.audioProgress=0}),this.audio.addEventListener("error",()=>{this.audioPlaying=!1,this.audioProgress=0})),this.audioPlaying?(this.audio.pause(),this.audioPlaying=!1):(this.audio.play().catch(()=>{this.audioPlaying=!1}),this.audioPlaying=!0)}handleProgressClick(t){if(t.stopPropagation(),!this.audio||!this.audio.duration)return;const e=t.currentTarget.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.audio.currentTime=i*this.audio.duration}formatTime(t){const e=Math.floor(t);return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,"0")}`}disconnectedCallback(){super.disconnectedCallback(),this.audio&&(this.audio.pause(),this.audio=null)}latLngToTile(t,e,i){const o=Math.pow(2,i),n=Math.floor((e+180)/360*o),s=t*Math.PI/180;return{x:n,y:Math.floor((1-Math.log(Math.tan(s)+1/Math.cos(s))/Math.PI)/2*o),z:i}}willUpdate(t){if(super.willUpdate(t),t.has("attachment")&&this.attachment){const t=this.attachment.indexOf(":");if(-1===t)this.url=this.attachment;else{const e=this.attachment.substring(0,t);if(this.url=this.attachment.substring(t+1),e.startsWith("image"))this.contentType=ku.IMAGE;else if(e.startsWith("audio"))this.contentType=ku.AUDIO;else if(e.startsWith("video"))this.contentType=ku.VIDEO;else if(e.startsWith("application"))this.contentType=ku.DOCUMENT;else if(e.startsWith("geo")){this.contentType=ku.LOCATION;const t=this.url.match(/^([^,]+),([^,]+)/);if(t){this.latitude=parseFloat(t[1]),this.longitude=parseFloat(t[2]);const e=this.latLngToTile(this.latitude,this.longitude,13);this.tileUrl=`https://tile.openstreetmap.org/${e.z}/${e.x}/${e.y}.png`}}else this.contentType=ku.OTHER}}if(t.has("latitude")||t.has("longitude"))if(void 0===this.latitude||void 0===this.longitude||isNaN(this.latitude)||isNaN(this.longitude))this.tileUrl="";else{const t=this.latLngToTile(this.latitude,this.longitude,13);this.tileUrl=`https://tile.openstreetmap.org/${t.z}/${t.x}/${t.y}.png`}}updated(t){if(super.updated(t),t.has("contentType")&&this.contentType===ku.IMAGE){const t=this.shadowRoot.querySelector(".observe");t&&new ResizeObserver((e,i)=>{t.clientHeight>0&&t.clientWidth>0&&(this.ratio=t.clientHeight/t.clientWidth,this.preview=0===this.ratio||this.ratio>.25&&this.ratio<=1.5,i.disconnect())}).observe(t)}}handleThumbnailClicked(){if(this.contentType===ku.IMAGE&&this.preview)window.setTimeout(()=>{document.querySelector("temba-lightbox").showElement(this)},100);else if(this.contentType===ku.LOCATION){const t=`https://www.openstreetmap.org/?mlat=${this.latitude}&mlon=${this.longitude}#map=15/${this.latitude}/${this.longitude}`;window.open(t,"_blank")}else this.contentType===ku.AUDIO||window.open(this.url,"_blank")}handleDownload(t){t.stopPropagation(),t.preventDefault(),window.open(this.url,"_blank")}render(){var t;return W`
7605
7636
  <div
7606
7637
  @click=${this.handleThumbnailClicked.bind(this)}
7607
7638
  class="${re({wrapper:!0,zoom:this.zoom})}"
7608
- style="${this.contentType===Qh.AUDIO?"cursor: default;":""}"
7639
+ style="${this.contentType===ku.AUDIO?"cursor: default;":""}"
7609
7640
  url=${this.url}
7610
7641
  >
7611
- ${this.contentType===Qh.IMAGE&&this.preview?W`<div class=""><div class="download" @click=${this.handleDownload.bind(this)}><temba-icon size="1" style="color:#fff;" name="download"></temba-icon></div><img
7642
+ ${this.contentType===ku.IMAGE&&this.preview?W`<div class=""><div class="download" @click=${this.handleDownload.bind(this)}><temba-icon size="1" style="color:#fff;" name="download"></temba-icon></div><img
7612
7643
  class="observe thumb ${this.contentType}"
7613
7644
  src="${this.url}"
7614
- ></img></div>`:this.contentType===Qh.AUDIO?W`<div class="audio-player">
7645
+ ></img></div>`:this.contentType===ku.AUDIO?W`<div class="audio-player">
7615
7646
  <div class="audio-play-btn" @click=${this.handleAudioPlayClick}>
7616
7647
  ${this.audioPlaying?W`<svg
7617
7648
  viewBox="0 0 24 24"
@@ -7643,7 +7674,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7643
7674
  ${this.audioDuration?this.formatTime(this.audioPlaying||this.audioProgress>0?(null===(t=this.audio)||void 0===t?void 0:t.currentTime)||0:this.audioDuration):""}
7644
7675
  </div>
7645
7676
  </div>`:W`
7646
- ${this.contentType===Qh.LOCATION?W`<img
7677
+ ${this.contentType===ku.LOCATION?W`<img
7647
7678
  style="height:125px;margin-bottom:-3px;border-radius:var(--curvature);"
7648
7679
  src="${this.tileUrl}"
7649
7680
  alt="Location preview"
@@ -7652,12 +7683,12 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7652
7683
  >
7653
7684
  <temba-icon
7654
7685
  size="1.5"
7655
- name="${Jh[this.contentType]}"
7686
+ name="${Cu[this.contentType]}"
7656
7687
  ></temba-icon>
7657
7688
  </div>`}
7658
7689
  `}
7659
7690
  </div>
7660
- `}}t([mt({type:String})],tu.prototype,"url",void 0),t([mt({type:String})],tu.prototype,"attachment",void 0),t([mt({type:Number})],tu.prototype,"ratio",void 0),t([mt({type:Boolean})],tu.prototype,"preview",void 0),t([mt({type:Boolean,attribute:!1})],tu.prototype,"zoom",void 0),t([mt({type:String,attribute:!0})],tu.prototype,"contentType",void 0),t([mt({type:Number,attribute:!1})],tu.prototype,"latitude",void 0),t([mt({type:Number,attribute:!1})],tu.prototype,"longitude",void 0),t([mt({type:String,attribute:!1})],tu.prototype,"tileUrl",void 0),t([gt()],tu.prototype,"audioPlaying",void 0),t([gt()],tu.prototype,"audioProgress",void 0),t([gt()],tu.prototype,"audioDuration",void 0);var eu;!function(t){t.DISCONNECTED="disconnected",t.CONNECTING="connecting",t.CONNECTED="connected"}(eu||(eu={}));const iu=function(t){const e=t.msg_in?"msg_created":"msg_received",i=t.msg_in||t.msg_out;return{uuid:i.id,type:e,created_on:new Date(i.time),_user:i.user,msg:{text:i.text,channel:void 0,quick_replies:[],urn:"",direction:"",type:"",attachments:i.attachments}}};class ou extends dt{static get styles(){return a`
7691
+ `}}t([mt({type:String})],Su.prototype,"url",void 0),t([mt({type:String})],Su.prototype,"attachment",void 0),t([mt({type:Number})],Su.prototype,"ratio",void 0),t([mt({type:Boolean})],Su.prototype,"preview",void 0),t([mt({type:Boolean,attribute:!1})],Su.prototype,"zoom",void 0),t([mt({type:String,attribute:!0})],Su.prototype,"contentType",void 0),t([mt({type:Number,attribute:!1})],Su.prototype,"latitude",void 0),t([mt({type:Number,attribute:!1})],Su.prototype,"longitude",void 0),t([mt({type:String,attribute:!1})],Su.prototype,"tileUrl",void 0),t([gt()],Su.prototype,"audioPlaying",void 0),t([gt()],Su.prototype,"audioProgress",void 0),t([gt()],Su.prototype,"audioDuration",void 0);var Au;!function(t){t.DISCONNECTED="disconnected",t.CONNECTING="connecting",t.CONNECTED="connected"}(Au||(Au={}));const Eu=function(t){const e=t.msg_in?"msg_created":"msg_received",i=t.msg_in||t.msg_out;return{uuid:i.id,type:e,created_on:new Date(i.time),_user:i.user,msg:{text:i.text,channel:void 0,quick_replies:[],urn:"",direction:"",type:"",attachments:i.attachments}}};class $u extends dt{static get styles(){return a`
7661
7692
  :host {
7662
7693
  display: flex;
7663
7694
  align-items: center;
@@ -7913,7 +7944,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7913
7944
  temba-loading.hidden {
7914
7945
  display: none;
7915
7946
  }
7916
- `}constructor(){super(),this.messageGroups=[],this.status=eu.DISCONNECTED,this.open=!1,this.hasPendingText=!1,this.blockHistoryFetching=!1,this.newMessageCount=0}willUpdate(t){super.willUpdate(t),t.has("open")&&this.open&&void 0!==t.get("open")&&this.status===eu.DISCONNECTED&&(this.status=eu.CONNECTING)}firstUpdated(t){if(super.firstUpdated(t),this.chat=this.shadowRoot.querySelector("temba-chat"),!document.querySelector("temba-lightbox")){const t=document.createElement("temba-lightbox");document.querySelector("body").appendChild(t)}}handleReconnect(){this.openSocket()}sendSockMessage(t){console.log("out",t),this.sock.send(JSON.stringify(t))}openSocket(){if(this.status!==eu.DISCONNECTED&&this.status!==eu.CONNECTING)return;if(this.sock&&this.sock.readyState<=WebSocket.OPEN)return;this.status=eu.CONNECTING;const t=this;let e=`wss://localhost.textit.com/wc/connect/${this.channel}/`;this.urn&&(e=`${e}?chat_id=${this.urn}`);const i=new WebSocket(e);this.sock=i,this.sock.onclose=function(){t.status=eu.DISCONNECTED},this.sock.onopen=function(){t.beforeTime=(new Date).toISOString(),t.status=eu.CONNECTED,t.urn=ye("temba-chat-urn");const e={type:"start_chat"};t.urn&&(e.chat_id=t.urn),t.sendSockMessage(e)},this.sock.onmessage=function(e){t.status=eu.CONNECTED;const i=JSON.parse(e.data);if(console.log("in",i),"chat_started"===i.type){const e=i;t.urn!==e.chat_id&&(t.messageGroups=[]),t.urn=e.chat_id,be("temba-chat-urn",e.chat_id),t.requestUpdate("messageGroups")}else if("chat_resumed"===i.type){const e=i;t.urn=e.chat_id,t.fetchPreviousMessages()}else if("chat_out"===i.type){const e=i;t.chat.addMessages([iu(e)],null,!0);const o={type:"ack_chat",msg_id:e.msg_out.id};t.sendSockMessage(o)}else"history"===i.type&&t.handleHistoryResponse(i)},this.sock.onerror=function(){t.status=eu.DISCONNECTED}}fetchPreviousMessages(){if(!this.blockHistoryFetching){this.fetchRequested=new Date,this.blockHistoryFetching=!0,this.chat.fetching=!0;const t={type:"get_history",before:this.beforeTime};this.fetchRequested=new Date,this.sendSockMessage(t)}}handleHistoryResponse(t){const e=t.history.reverse();if(e.length>0){const t=e[0];if(t.msg_in){const e=t.msg_in;this.beforeTime=e.time}else if(t.msg_out){const e=t.msg_out;this.beforeTime=e.time}}this.chat.addMessages(e.map(iu),this.fetchRequested)}fetchComplete(){this.blockHistoryFetching=!1}focusInput(){const t=this.shadowRoot.querySelector(".input");t&&t.focus()}updated(t){super.updated(t),this.open&&t.has("open")&&void 0!==t.get("open")&&this.status===eu.CONNECTING&&this.openSocket(),t.has("status")&&this.status===eu.CONNECTED&&this.focusInput()}openChat(){this.open=!0}handleKeyUp(t){this.hasPendingText&&"Enter"===t.key&&this.sendPendingMessage(),this.hasPendingText=t.target.value.length>0}sendPendingMessage(){if(this.status===eu.CONNECTED){const t=this.shadowRoot.querySelector(".input"),e=t.value;t.value="";const i={type:"send_msg",text:e};this.sendSockMessage(i);const o=new Date;this.chat.addMessages([{uuid:Jt(),type:"msg_received",msg:{text:e},created_on:o}],o,!0),this.hasPendingText=t.value.length>0}}handleClickInputPanel(t){t.preventDefault(),t.stopPropagation();this.shadowRoot.querySelector(".input").focus()}toggleChat(){this.open=!this.open}render(){return W`
7947
+ `}constructor(){super(),this.messageGroups=[],this.status=Au.DISCONNECTED,this.open=!1,this.hasPendingText=!1,this.blockHistoryFetching=!1,this.newMessageCount=0}willUpdate(t){super.willUpdate(t),t.has("open")&&this.open&&void 0!==t.get("open")&&this.status===Au.DISCONNECTED&&(this.status=Au.CONNECTING)}firstUpdated(t){if(super.firstUpdated(t),this.chat=this.shadowRoot.querySelector("temba-chat"),!document.querySelector("temba-lightbox")){const t=document.createElement("temba-lightbox");document.querySelector("body").appendChild(t)}}handleReconnect(){this.openSocket()}sendSockMessage(t){console.log("out",t),this.sock.send(JSON.stringify(t))}openSocket(){if(this.status!==Au.DISCONNECTED&&this.status!==Au.CONNECTING)return;if(this.sock&&this.sock.readyState<=WebSocket.OPEN)return;this.status=Au.CONNECTING;const t=this;let e=`wss://localhost.textit.com/wc/connect/${this.channel}/`;this.urn&&(e=`${e}?chat_id=${this.urn}`);const i=new WebSocket(e);this.sock=i,this.sock.onclose=function(){t.status=Au.DISCONNECTED},this.sock.onopen=function(){t.beforeTime=(new Date).toISOString(),t.status=Au.CONNECTED,t.urn=ye("temba-chat-urn");const e={type:"start_chat"};t.urn&&(e.chat_id=t.urn),t.sendSockMessage(e)},this.sock.onmessage=function(e){t.status=Au.CONNECTED;const i=JSON.parse(e.data);if(console.log("in",i),"chat_started"===i.type){const e=i;t.urn!==e.chat_id&&(t.messageGroups=[]),t.urn=e.chat_id,be("temba-chat-urn",e.chat_id),t.requestUpdate("messageGroups")}else if("chat_resumed"===i.type){const e=i;t.urn=e.chat_id,t.fetchPreviousMessages()}else if("chat_out"===i.type){const e=i;t.chat.addMessages([Eu(e)],null,!0);const o={type:"ack_chat",msg_id:e.msg_out.id};t.sendSockMessage(o)}else"history"===i.type&&t.handleHistoryResponse(i)},this.sock.onerror=function(){t.status=Au.DISCONNECTED}}fetchPreviousMessages(){if(!this.blockHistoryFetching){this.fetchRequested=new Date,this.blockHistoryFetching=!0,this.chat.fetching=!0;const t={type:"get_history",before:this.beforeTime};this.fetchRequested=new Date,this.sendSockMessage(t)}}handleHistoryResponse(t){const e=t.history.reverse();if(e.length>0){const t=e[0];if(t.msg_in){const e=t.msg_in;this.beforeTime=e.time}else if(t.msg_out){const e=t.msg_out;this.beforeTime=e.time}}this.chat.addMessages(e.map(Eu),this.fetchRequested)}fetchComplete(){this.blockHistoryFetching=!1}focusInput(){const t=this.shadowRoot.querySelector(".input");t&&t.focus()}updated(t){super.updated(t),this.open&&t.has("open")&&void 0!==t.get("open")&&this.status===Au.CONNECTING&&this.openSocket(),t.has("status")&&this.status===Au.CONNECTED&&this.focusInput()}openChat(){this.open=!0}handleKeyUp(t){this.hasPendingText&&"Enter"===t.key&&this.sendPendingMessage(),this.hasPendingText=t.target.value.length>0}sendPendingMessage(){if(this.status===Au.CONNECTED){const t=this.shadowRoot.querySelector(".input"),e=t.value;t.value="";const i={type:"send_msg",text:e};this.sendSockMessage(i);const o=new Date;this.chat.addMessages([{uuid:Jt(),type:"msg_received",msg:{text:e},created_on:o}],o,!0),this.hasPendingText=t.value.length>0}}handleClickInputPanel(t){t.preventDefault(),t.stopPropagation();this.shadowRoot.querySelector(".input").focus()}toggleChat(){this.open=!this.open}render(){return W`
7917
7948
  <div class="chat ${this.status} ${this.open?"open":""}">
7918
7949
  <div class="header">
7919
7950
  <slot name="header">${this.urn?this.urn:"Chat"}</slot>
@@ -7930,27 +7961,27 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7930
7961
  @temba-fetch-complete=${this.fetchComplete}
7931
7962
  ></temba-chat>
7932
7963
 
7933
- ${this.status===eu.DISCONNECTED?W`<div class="notice">
7964
+ ${this.status===Au.DISCONNECTED?W`<div class="notice">
7934
7965
  <div>This chat is not currently connected.</div>
7935
7966
  <div class="reconnect" @click=${this.handleReconnect}>
7936
7967
  Click here to reconnect
7937
7968
  <div></div>
7938
7969
  </div>
7939
7970
  </div>`:null}
7940
- ${this.status===eu.CONNECTING?W`<div class="notice">
7971
+ ${this.status===Au.CONNECTING?W`<div class="notice">
7941
7972
  <div>Connecting</div>
7942
7973
  <temba-icon name="progress_spinner" spin></temba-icon>
7943
7974
  </div>`:null}
7944
- ${this.status===eu.CONNECTED?W` <div class="border"></div>
7975
+ ${this.status===Au.CONNECTED?W` <div class="border"></div>
7945
7976
  <div
7946
7977
  class="row input-panel ${this.hasPendingText?"pending":""}"
7947
7978
  @click=${this.handleClickInputPanel}
7948
7979
  >
7949
7980
  <input
7950
- class="input ${this.status===eu.CONNECTED?"active":"inactive"}"
7981
+ class="input ${this.status===Au.CONNECTED?"active":"inactive"}"
7951
7982
  type="text"
7952
7983
  placeholder="Message.."
7953
- ?disabled=${this.status!==eu.CONNECTED}
7984
+ ?disabled=${this.status!==Au.CONNECTED}
7954
7985
  @keydown=${this.handleKeyUp}
7955
7986
  />
7956
7987
  <temba-icon
@@ -7970,7 +8001,7 @@ const{I:Rc}=rt,Nc=t=>t,Bc=()=>document.createComment(""),Fc=(t,e,i)=>{const o=t.
7970
8001
  style="background: center / contain no-repeat url(${this.activeUserAvatar||kl})"
7971
8002
  ></div>
7972
8003
  </div>
7973
- `}}t([mt({type:String})],ou.prototype,"channel",void 0),t([mt({type:String})],ou.prototype,"urn",void 0),t([mt({type:Array})],ou.prototype,"messageGroups",void 0),t([mt({type:String})],ou.prototype,"status",void 0),t([mt({type:Boolean})],ou.prototype,"open",void 0),t([mt({type:Boolean})],ou.prototype,"hasPendingText",void 0),t([mt({type:String})],ou.prototype,"host",void 0),t([mt({type:String})],ou.prototype,"activeUserAvatar",void 0),t([mt({type:Boolean,attribute:!1})],ou.prototype,"blockHistoryFetching",void 0);const nu=a`
8004
+ `}}t([mt({type:String})],$u.prototype,"channel",void 0),t([mt({type:String})],$u.prototype,"urn",void 0),t([mt({type:Array})],$u.prototype,"messageGroups",void 0),t([mt({type:String})],$u.prototype,"status",void 0),t([mt({type:Boolean})],$u.prototype,"open",void 0),t([mt({type:Boolean})],$u.prototype,"hasPendingText",void 0),t([mt({type:String})],$u.prototype,"host",void 0),t([mt({type:String})],$u.prototype,"activeUserAvatar",void 0),t([mt({type:Boolean,attribute:!1})],$u.prototype,"blockHistoryFetching",void 0);const Tu=a`
7974
8005
  .croppie-container {
7975
8006
  width: 100%;
7976
8007
  height: 100%;
@@ -8221,9 +8252,9 @@ background: #ccc;
8221
8252
  .cr-rotate-r i:before {
8222
8253
  content: '↻';
8223
8254
  }
8224
- `;class su extends _o{constructor(){super(...arguments),this.shape="square",this.showCroppie=!1,this.uploadReader=new FileReader}static get styles(){return a`
8255
+ `;class Du extends _o{constructor(){super(...arguments),this.shape="square",this.showCroppie=!1,this.uploadReader=new FileReader}static get styles(){return a`
8225
8256
  ${super.styles}
8226
- ${nu}
8257
+ ${Tu}
8227
8258
 
8228
8259
  .croppie {
8229
8260
  max-width: 400px;
@@ -8353,9 +8384,9 @@ background: #ccc;
8353
8384
  </div>
8354
8385
  </temba-mask>
8355
8386
  </div>
8356
- `}render(){return this.renderField()}}t([mt({type:String})],su.prototype,"tempImage",void 0),t([mt({type:String})],su.prototype,"url",void 0),t([mt({type:String})],su.prototype,"shape",void 0),t([mt({type:Boolean,attribute:!1})],su.prototype,"showCroppie",void 0);class ru extends dt{constructor(){super(...arguments),this.show=!1}render(){return W` <div class="mask ${this.show?"show":""}">
8387
+ `}render(){return this.renderField()}}t([mt({type:String})],Du.prototype,"tempImage",void 0),t([mt({type:String})],Du.prototype,"url",void 0),t([mt({type:String})],Du.prototype,"shape",void 0),t([mt({type:Boolean,attribute:!1})],Du.prototype,"showCroppie",void 0);class Mu extends dt{constructor(){super(...arguments),this.show=!1}render(){return W` <div class="mask ${this.show?"show":""}">
8357
8388
  <slot></slot>
8358
- </div>`}}ru.styles=a`
8389
+ </div>`}}Mu.styles=a`
8359
8390
  .mask {
8360
8391
  position: fixed;
8361
8392
  top: 0;
@@ -8372,7 +8403,7 @@ background: #ccc;
8372
8403
  .show {
8373
8404
  display: flex;
8374
8405
  }
8375
- `,t([mt({type:Boolean})],ru.prototype,"show",void 0);class au extends _o{constructor(){super(...arguments),this.session=!1,this.pickersLoading={},this.textInputAttachments={}}static get styles(){return a`
8406
+ `,t([mt({type:Boolean})],Mu.prototype,"show",void 0);class zu extends _o{constructor(){super(...arguments),this.session=!1,this.pickersLoading={},this.textInputAttachments={}}static get styles(){return a`
8376
8407
  .component {
8377
8408
  background: #fff;
8378
8409
  border: 1px solid var(--color-widget-border);
@@ -8582,8 +8613,8 @@ background: #ccc;
8582
8613
  ${this.templateWarning&&this.selectedTemplate?W`<temba-alert level="warning" style="margin-bottom: 0.5em; display: block;">${this.templateWarning}</temba-alert>`:null}
8583
8614
  ${t?W` <div class="template">${t}</div>`:null}
8584
8615
  </div>
8585
- `}}au.shadowRootOptions={...dt.shadowRootOptions,delegatesFocus:!0},t([mt({type:String})],au.prototype,"url",void 0),t([mt({type:String})],au.prototype,"template",void 0),t([mt({type:Object})],au.prototype,"selectedTemplate",void 0),t([mt({type:Array})],au.prototype,"variables",void 0),t([mt({type:Array})],au.prototype,"currentVariables",void 0),t([mt({type:Object,attribute:!1})],au.prototype,"translation",void 0),t([mt({type:Boolean})],au.prototype,"translating",void 0),t([mt({type:Boolean})],au.prototype,"session",void 0),t([mt({type:String,attribute:"template-warning"})],au.prototype,"templateWarning",void 0);class lu extends Be{constructor(){super(...arguments),this.messages=[],this.staleDuration=5e3,this.animationDuration=200,this.errorSticky=!1,this.warningSticky=!1,this.infoSticky=!1,this.messageId=0}checkForStaleMessages(){const t=new Date;this.messages.filter(t=>("error"!==t.level||!this.errorSticky)&&(("warning"!==t.level||!this.warningSticky)&&("info"!==t.level||!this.infoSticky))).forEach(e=>{t.getTime()-e.time.getTime()>this.staleDuration&&this.removeMessage(e)}),0===this.messages.length&&this.checker&&(window.clearInterval(this.checker),this.checker=0)}addMessages(t){t.forEach(t=>{this.addMessage(t.text,t.level)})}addMessage(t,e){const i={id:++this.messageId,text:t,level:e,time:new Date};this.messages.push(i),window.setTimeout(()=>{i.visible=!0,this.requestUpdate("messages")},100),this.requestUpdate("messages"),this.checker&&(window.clearInterval(this.checker),this.checker=0),this.checker=window.setInterval(this.checkForStaleMessages.bind(this),1e3)}info(t){this.addMessage(t,"info")}warning(t){this.addMessage(t,"warning")}error(t){this.addMessage(t,"error")}removeMessage(t){t.removeTime=new Date,window.setTimeout(()=>{this.messages=this.messages.filter(e=>e!==t),this.requestUpdate("messages")},this.animationDuration),this.requestUpdate("messages")}handleMessageClicked(t){const e=t.target,i=parseInt(e.getAttribute("message_id")),o=this.messages.find(t=>t.id===i);o&&this.removeMessage(o)}render(){return W`
8586
- ${Vc(this.messages,t=>t.id,t=>W`
8616
+ `}}zu.shadowRootOptions={...dt.shadowRootOptions,delegatesFocus:!0},t([mt({type:String})],zu.prototype,"url",void 0),t([mt({type:String})],zu.prototype,"template",void 0),t([mt({type:Object})],zu.prototype,"selectedTemplate",void 0),t([mt({type:Array})],zu.prototype,"variables",void 0),t([mt({type:Array})],zu.prototype,"currentVariables",void 0),t([mt({type:Object,attribute:!1})],zu.prototype,"translation",void 0),t([mt({type:Boolean})],zu.prototype,"translating",void 0),t([mt({type:Boolean})],zu.prototype,"session",void 0),t([mt({type:String,attribute:"template-warning"})],zu.prototype,"templateWarning",void 0);class Iu extends Be{constructor(){super(...arguments),this.messages=[],this.staleDuration=5e3,this.animationDuration=200,this.errorSticky=!1,this.warningSticky=!1,this.infoSticky=!1,this.messageId=0}checkForStaleMessages(){const t=new Date;this.messages.filter(t=>("error"!==t.level||!this.errorSticky)&&(("warning"!==t.level||!this.warningSticky)&&("info"!==t.level||!this.infoSticky))).forEach(e=>{t.getTime()-e.time.getTime()>this.staleDuration&&this.removeMessage(e)}),0===this.messages.length&&this.checker&&(window.clearInterval(this.checker),this.checker=0)}addMessages(t){t.forEach(t=>{this.addMessage(t.text,t.level)})}addMessage(t,e){const i={id:++this.messageId,text:t,level:e,time:new Date};this.messages.push(i),window.setTimeout(()=>{i.visible=!0,this.requestUpdate("messages")},100),this.requestUpdate("messages"),this.checker&&(window.clearInterval(this.checker),this.checker=0),this.checker=window.setInterval(this.checkForStaleMessages.bind(this),1e3)}info(t){this.addMessage(t,"info")}warning(t){this.addMessage(t,"warning")}error(t){this.addMessage(t,"error")}removeMessage(t){t.removeTime=new Date,window.setTimeout(()=>{this.messages=this.messages.filter(e=>e!==t),this.requestUpdate("messages")},this.animationDuration),this.requestUpdate("messages")}handleMessageClicked(t){const e=t.target,i=parseInt(e.getAttribute("message_id")),o=this.messages.find(t=>t.id===i);o&&this.removeMessage(o)}render(){return W`
8617
+ ${vh(this.messages,t=>t.id,t=>W`
8587
8618
  <div
8588
8619
  style="transition-duration: ${this.animationDuration}ms"
8589
8620
  class="message ${t.level} ${t.visible?"visible":""} ${t.removeTime?"removing":""}"
@@ -8597,7 +8628,7 @@ background: #ccc;
8597
8628
  ></temba-icon>
8598
8629
  </div>
8599
8630
  `)}
8600
- `}}lu.styles=a`
8631
+ `}}Iu.styles=a`
8601
8632
  :host {
8602
8633
  position: fixed;
8603
8634
  width: 400px;
@@ -8664,7 +8695,7 @@ background: #ccc;
8664
8695
 
8665
8696
  .info {
8666
8697
  }
8667
- `,t([mt({type:Array})],lu.prototype,"messages",void 0),t([mt({type:Number,attribute:"duration"})],lu.prototype,"staleDuration",void 0),t([mt({type:Number,attribute:"animation"})],lu.prototype,"animationDuration",void 0),t([mt({type:Boolean,attribute:"error-sticky"})],lu.prototype,"errorSticky",void 0),t([mt({type:Boolean,attribute:"warning-sticky"})],lu.prototype,"warningSticky",void 0),t([mt({type:Boolean,attribute:"info-sticky"})],lu.prototype,"infoSticky",void 0);const du=(t,e)=>{if(e){const i=e.split(",").map(t=>t.trim());return i.includes(t)||i.includes(t.split("/")[0]+"/*")}return!0};class cu extends Be{constructor(){super(...arguments),this.endpoint=te,this.ignoreDrops=!1,this.icon=ko.add,this.accept="",this.max=3,this.attachments=[]}static get styles(){return a`
8698
+ `,t([mt({type:Array})],Iu.prototype,"messages",void 0),t([mt({type:Number,attribute:"duration"})],Iu.prototype,"staleDuration",void 0),t([mt({type:Number,attribute:"animation"})],Iu.prototype,"animationDuration",void 0),t([mt({type:Boolean,attribute:"error-sticky"})],Iu.prototype,"errorSticky",void 0),t([mt({type:Boolean,attribute:"warning-sticky"})],Iu.prototype,"warningSticky",void 0),t([mt({type:Boolean,attribute:"info-sticky"})],Iu.prototype,"infoSticky",void 0);const Lu=(t,e)=>{if(e){const i=e.split(",").map(t=>t.trim());return i.includes(t)||i.includes(t.split("/")[0]+"/*")}return!0};class Ou extends Be{constructor(){super(...arguments),this.endpoint=te,this.ignoreDrops=!1,this.icon=ko.add,this.accept="",this.max=3,this.attachments=[]}static get styles(){return a`
8668
8699
  .drop-mask {
8669
8700
  border-radius: var(--curvature-widget);
8670
8701
  transition: opacity ease-in-out var(--transition-speed);
@@ -8758,7 +8789,7 @@ background: #ccc;
8758
8789
  background-color: rgba(0, 0, 0, 0.07);
8759
8790
  cursor: pointer;
8760
8791
  }
8761
- `}updated(t){super.updated(t),t.has("attachments")&&setTimeout(()=>{this.dispatchEvent(new Event("change"))},0),t.has("uploading")&&this.dispatchEvent(new CustomEvent(Io.Loading,{detail:{loading:this.uploading}}))}getAcceptableFiles(t){const e=t.dataTransfer;if(e){return[...e.files].filter(t=>du(t.type,this.accept))}}handleDragEnter(t){this.highlight(t)}handleDragOver(t){this.highlight(t)}handleDragLeave(t){this.unhighlight(t)}handleDrop(t){this.ignoreDrops||(this.unhighlight(t),this.canAcceptAttachments()&&this.uploadFiles(this.getAcceptableFiles(t)))}canAcceptAttachments(){return this.attachments.length<this.max}highlight(t){this.ignoreDrops||(t.preventDefault(),t.stopPropagation(),this.canAcceptAttachments()&&(this.pendingDrop=!0))}unhighlight(t){this.ignoreDrops||(t.preventDefault(),t.stopPropagation(),this.pendingDrop=!1)}addCurrentAttachment(t){this.attachments.push(t),this.requestUpdate("attachments")}removeCurrentAttachment(t){this.attachments=this.attachments.filter(e=>e!==t),this.requestUpdate("attachments")}handleRemoveFileClicked(t){const e=t.target,i=this.attachments.find(({url:t})=>t===e.id);i&&this.removeCurrentAttachment(i)}handleUploadFileInputChanged(t){const e=t.target.files;this.uploadFiles([...e])}uploadFiles(t){let e=[];e=t.filter(t=>{if(this.accept&&!du(t.type,this.accept))return!1;return-1===this.attachments.findIndex(e=>e.filename===t.name&&e.size===t.size)?t:void 0}),e.map(t=>{this.uploadFile(t)})}uploadFile(t){this.uploading=!0;const e=this.endpoint,i=new FormData;i.append("file",t),pe(e,i).then(t=>{if(this.attachments.length<this.max){const e=t.json;e&&this.addCurrentAttachment(e)}}).catch(t=>{let e="";e=400===t.status?t.json.file[0]:"Server failure",console.error(e)}).finally(()=>{this.uploading=!1})}renderUploader(){return this.uploading?W`<temba-loading units="3" size="12"></temba-loading>`:this.attachments.length<this.max?W`<input
8792
+ `}updated(t){super.updated(t),t.has("attachments")&&setTimeout(()=>{this.dispatchEvent(new Event("change"))},0),t.has("uploading")&&this.dispatchEvent(new CustomEvent(Io.Loading,{detail:{loading:this.uploading}}))}getAcceptableFiles(t){const e=t.dataTransfer;if(e){return[...e.files].filter(t=>Lu(t.type,this.accept))}}handleDragEnter(t){this.highlight(t)}handleDragOver(t){this.highlight(t)}handleDragLeave(t){this.unhighlight(t)}handleDrop(t){this.ignoreDrops||(this.unhighlight(t),this.canAcceptAttachments()&&this.uploadFiles(this.getAcceptableFiles(t)))}canAcceptAttachments(){return this.attachments.length<this.max}highlight(t){this.ignoreDrops||(t.preventDefault(),t.stopPropagation(),this.canAcceptAttachments()&&(this.pendingDrop=!0))}unhighlight(t){this.ignoreDrops||(t.preventDefault(),t.stopPropagation(),this.pendingDrop=!1)}addCurrentAttachment(t){this.attachments.push(t),this.requestUpdate("attachments")}removeCurrentAttachment(t){this.attachments=this.attachments.filter(e=>e!==t),this.requestUpdate("attachments")}handleRemoveFileClicked(t){const e=t.target,i=this.attachments.find(({url:t})=>t===e.id);i&&this.removeCurrentAttachment(i)}handleUploadFileInputChanged(t){const e=t.target.files;this.uploadFiles([...e])}uploadFiles(t){let e=[];e=t.filter(t=>{if(this.accept&&!Lu(t.type,this.accept))return!1;return-1===this.attachments.findIndex(e=>e.filename===t.name&&e.size===t.size)?t:void 0}),e.map(t=>{this.uploadFile(t)})}uploadFile(t){this.uploading=!0;const e=this.endpoint,i=new FormData;i.append("file",t),pe(e,i).then(t=>{if(this.attachments.length<this.max){const e=t.json;e&&this.addCurrentAttachment(e)}}).catch(t=>{let e="";e=400===t.status?t.json.file[0]:"Server failure",console.error(e)}).finally(()=>{this.uploading=!1})}renderUploader(){return this.uploading?W`<temba-loading units="3" size="12"></temba-loading>`:this.attachments.length<this.max?W`<input
8762
8793
  type="file"
8763
8794
  id="upload-input"
8764
8795
  ?multiple=${this.max>1}
@@ -8796,40 +8827,9 @@ background: #ccc;
8796
8827
  ${this.renderUploader()}
8797
8828
  </div>
8798
8829
  </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
- 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
- title="${e}"
8802
- >
8803
- ${t}
8804
- </div>`,Cu=(t,e,i)=>W`<div style="display:flex;align-items:center;">
8805
- ${e?W`<temba-icon name=${e} style="margin-right:0.5em"></temba-icon>`:null}
8806
- <div
8807
- style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 250px;"
8808
- title="${t}"
8809
- >
8810
- ${i||t}
8811
- </div>
8812
- </div>`,Su=(t,e,i)=>{const o=[],n=4===t.length?4:Math.min(3,t.length);for(let s=0;s<n;s++){const n=t[s],r=void 0!==i&&n.startsWith("@")?_u(n,i):void 0;o.push(Cu(n,e,r))}if(t.length>3&&4!==t.length){const i=t.length-3;o.push(W`<div style="display:flex;align-items:center;margin-top:0.2em;">
8813
- ${e?W`<div style="margin-right:0.4em; width: 1em;"></div>`:null}
8814
- <div style="font-size:0.8em">+${i} more</div>
8815
- </div>`)}return o},Au=t=>{const e=[],i=4===t.length?4:Math.min(3,t.length);for(let o=0;o<i;o++){const i=t[o];i.uuid&&i.eventType?e.push(Eu({uuid:i.uuid,name:i.name},i.eventType,i.icon)):e.push(Cu(i.name,i.icon,i.content))}if(t.length>3&&4!==t.length){const i=t.length-3;e.push(W`<div style="display:flex;align-items:center;margin-top:0.2em;">
8816
- <div style="margin-right:0.4em; width: 1em;"></div>
8817
- <div style="font-size:0.8em">+${i} more</div>
8818
- </div>`)}return e},Eu=(t,e,i)=>W`<div style="display:flex;align-items:center;max-width:100%;">
8819
- ${i?W`<temba-icon name=${i} style="margin-right:0.5em"></temba-icon>`:null}
8820
- <div
8821
- class="linked-name"
8822
- @click=${i=>{i.stopPropagation(),i.preventDefault();const o=i.currentTarget.closest("temba-flow-editor");o&&o.fireCustomEvent(e,{uuid:t.uuid,name:t.name,metaKey:i.metaKey,ctrlKey:i.ctrlKey})}}
8823
- style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 250px; text-decoration: underline; cursor: pointer;"
8824
- >
8825
- ${t.name}
8826
- </div>
8827
- </div>`,$u=(t,e,i)=>{const o=[],n=4===t.length?4:Math.min(3,t.length);for(let s=0;s<n;s++)o.push(Eu(t[s],e,i));if(t.length>3&&4!==t.length){const e=t.length-3;o.push(W`<div style="display:flex;align-items:center;margin-top:0.2em;">
8828
- ${i?W`<div style="margin-right:0.4em; width: 1em;"></div>`:null}
8829
- <div style="font-size:0.8em">+${e} more</div>
8830
- </div>`)}return o},Tu=(t,e)=>$u(t,Io.FlowClicked,e),Du=(t,e)=>$u(t,Io.GroupClicked,e),Mu=[{scheme:"tel",name:"SMS",path:"Phone Number"},{scheme:"whatsapp",name:"WhatsApp",path:"WhatsApp Number"},{scheme:"facebook",name:"Facebook",path:"Facebook ID"},{scheme:"instagram",name:"Instagram",path:"Instagram ID"},{scheme:"twitterid",name:"Twitter",path:"Twitter ID",excludeFromSplit:!0},{scheme:"telegram",name:"Telegram",path:"Telegram ID"},{scheme:"viber",name:"Viber",path:"Viber ID"},{scheme:"line",name:"Line",path:"Line ID"},{scheme:"wechat",name:"WeChat",path:"WeChat ID"},{scheme:"fcm",name:"Firebase",path:"Firebase ID"},{scheme:"jiochat",name:"JioChat",path:"JioChat ID"},{scheme:"freshchat",name:"Freshchat",path:"Freshchat ID"},{scheme:"mailto",name:"Email",path:"Email Address",excludeFromSplit:!0},{scheme:"twitter",name:"Twitter",path:"Twitter Handle",excludeFromSplit:!0},{scheme:"vk",name:"VK",path:"VK ID"},{scheme:"discord",name:"Discord",path:"Discord ID"},{scheme:"webchat",name:"Webchat",path:"Webchat ID",excludeFromSplit:!0},{scheme:"rocketchat",name:"RocketChat",path:"RocketChat ID"},{scheme:"ext",name:"External",path:"External ID"}],zu=(t,e,i)=>{const o=i||document.querySelector(`[id="${t}"]`);if(!o)return null;const n=o.offsetWidth,s=o.offsetHeight;return{uuid:t,left:e.left,top:e.top,right:e.left+n,bottom:e.top+s,width:n,height:s}},Iu=(t,e)=>!(t.right<=e.left-10||t.left>=e.right+10||t.bottom<=e.top-10||t.top>=e.bottom+10),Lu=["down","up","right","left"],Ou=(t,e,i)=>({...t,left:e,top:i,right:e+t.width,bottom:i+t.height}),Pu=(t,e,i)=>{switch(i){case"down":{const i=Math.max(...e.map(t=>t.bottom)),o=bu(i+30);return{left:t.left,top:o}}case"up":{const i=Math.min(...e.map(t=>t.top)),o=bu(i-t.height-30);return o<0?{left:t.left,top:0}:{left:t.left,top:o}}case"right":{const i=Math.max(...e.map(t=>t.right));return{left:bu(i+30),top:t.top}}case"left":{const i=Math.min(...e.map(t=>t.left)),o=bu(i-t.width-30);return o<0?{left:0,top:t.top}:{left:o,top:t.top}}}};function Ru(t,e){if(!e)return t;const i={...t};for(const o of Object.keys(e)){const n=e[o];Array.isArray(n)&&n.length>0&&(Array.isArray(t[o])?i[o]=n:i[o]=n[0])}return i}const Nu="message",Bu="voice",Fu="background",qu="ai",Uu="airtime",ju={send:"send",contacts:"contacts",save:"save",services:"services",broadcast:"broadcast",trigger:"trigger"},Hu={wait:"wait",split:"split"},Wu={[ju.send]:{color:"#3498db",title:"Send",description:"Actions that send messages or content to contacts"},[ju.contacts]:{color:"#01c1af",title:"Contact",description:"Actions that update contact information"},[ju.save]:{color:"#1a777c",title:"Save",description:"Actions that save or store data"},[ju.services]:{color:"#f79035ff",title:"Services",description:"Call external services and APIs"},[ju.broadcast]:{color:"#8e5ea7",title:"Other People",description:"Actions that apply to others instead of the contact"},[ju.trigger]:{color:"#df419f",title:"Trigger",description:"Actions that trigger other behavior"}},Vu={[Hu.wait]:{color:"#4d7dad",title:"Wait",description:"Wait for user and split on their response"},[Hu.split]:{color:"#aaaaaa",title:"Split",description:"Split the flow based on conditions"}},Zu={name:"Add Input Labels",group:ju.save,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{return W`<div>${i=e.labels,o="label",Su(i.map(t=>t.name),o)}</div>`;var i,o},toFormData:t=>({labels:t.labels||null,uuid:t.uuid}),form:{labels:{type:"select",label:"Labels",helpText:"Select labels to add to the input. Type a new label name to create it.",required:!0,options:[],multi:!0,searchable:!0,endpoint:"/api/v2/labels.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for labels or type to create new ones...",allowCreate:!0,createArbitraryOption:(t,e)=>!e.find(e=>e.name.toLowerCase().trim()===t.toLowerCase().trim())&&t.trim()?{name:t.trim(),arbitrary:!0}:null}},fromFormData:t=>({uuid:t.uuid,type:"add_input_labels",labels:(t.labels||[]).map(t=>({uuid:t.uuid,name:t.name}))})},Yu={name:"Add URN",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{const i=Mu.find(t=>t.scheme===e.scheme),o=(null==i?void 0:i.path)||e.scheme;return ku(W`Add ${o} ${_u(e.path,!0)}`,`Add ${o} ${e.path}`)},toFormData:t=>{const e=Mu.find(e=>e.scheme===t.scheme);return{uuid:t.uuid,scheme:e?[{name:e.path,value:t.scheme}]:null,path:t.path||""}},fromFormData:t=>{const e=Array.isArray(t.scheme)&&t.scheme.length>0?t.scheme[0].value:"tel";return{uuid:t.uuid,type:"add_contact_urn",scheme:e,path:t.path||""}},form:{scheme:{type:"select",label:"URN Type",helpText:"Select the type of URN to add to the contact",required:!0,searchable:!1,multi:!1,options:Mu.map(t=>({name:t.path,value:t.scheme}))},path:{type:"text",label:"URN Value",helpText:"Enter the URN value (e.g., phone number, Facebook ID, etc.)",required:!0,placeholder:"Enter the URN value...",evaluated:!0}},validate:t=>{const e={};return t.scheme&&0!==t.scheme.length||(e.scheme="URN type is required"),t.path&&""!==t.path.trim()||(e.path="URN value is required"),{valid:0===Object.keys(e).length,errors:e}}},Ku={name:"Update Field",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>e.value?ku(W`Set <strong>${e.field.name}</strong> to
8831
- ${_u(e.value,!0)}`,`Set ${e.field.name} to ${e.value}`):ku(W`Clear <strong>${e.field.name}</strong>`,`Clear ${e.field.name}`),form:{field:{type:"select",label:"Field",required:!0,searchable:!0,clearable:!1,placeholder:"Search for contact fields...",nameKey:"name",valueKey:"key",endpoint:"/api/v2/fields.json",helpText:"Select the contact field to update",allowCreate:!0,createArbitraryOption:t=>({key:t,name:t,type:"text"})},value:{type:"textarea",label:"Value",placeholder:"Enter field value...",evaluated:!0,helpText:"The new value for the contact field. You can use expressions like @contact.name"}},toFormData:t=>({uuid:t.uuid,field:t.field?[t.field]:null,value:t.value}),fromFormData:t=>{const e=t.field[0];return{uuid:t.uuid,type:"set_contact_field",field:{name:e.name,key:e.key},value:t.value}},sanitize:t=>{t.value&&"string"==typeof t.value&&(t.value=t.value.trim())}},Gu={name:"Update Channel",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>ku(W`Set to <strong>${e.channel.name}</strong>`,`Set to ${e.channel.name}`),form:{channel:{type:"select",label:"Channel",required:!0,searchable:!0,clearable:!1,endpoint:"/api/v2/channels.json",valueKey:"uuid",nameKey:"name",placeholder:"Select channel",helpText:"Select the channel to set for the contact"}},toFormData:t=>({uuid:t.uuid,channel:t.channel?[t.channel]:null}),fromFormData:t=>{var e;const i=null===(e=t.channel)||void 0===e?void 0:e[0];return{uuid:t.uuid,type:"set_contact_channel",channel:{uuid:i.uuid||i.value,name:i.name}}}},Xu={name:"Update Language",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{const i=mu(e.language);return ku(W`Set to <strong>${i}</strong>`,`Set to ${i}`)},form:{language:{type:"select",label:"Language",required:!0,searchable:!0,clearable:!1,valueKey:"value",nameKey:"name",helpText:"Select the language to set for the contact",getDynamicOptions:()=>{const t=$d(),e=null==t?void 0:t.getState().workspace;return(null==e?void 0:e.languages)&&Array.isArray(e.languages)?e.languages.map(t=>({value:t,name:mu(t)})):[]}}},toFormData:t=>t.language?{language:[{value:t.language,name:mu(t.language)}],uuid:t.uuid}:{language:null,uuid:t.uuid},fromFormData:t=>({uuid:t.uuid,type:"set_contact_language",language:t.language[0].value}),validate:t=>{const e={};return t.language||(e.language="Language is required"),{valid:0===Object.keys(e).length,errors:e}}},Qu={name:"Update Status",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>ku(W`Set to <strong>${Pe(e.status)}</strong>`,`Set to ${Pe(e.status)}`),toFormData:t=>({uuid:t.uuid,status:[{name:Pe(t.status||"active"),value:t.status||"active"}]}),fromFormData:t=>({status:t.status[0].value,type:"set_contact_status",uuid:t.uuid}),form:{status:{type:"select",label:"Status",required:!0,searchable:!1,clearable:!1,options:[{value:"active",name:"Active"},{value:"archived",name:"Archived"},{value:"stopped",name:"Stopped"},{value:"blocked",name:"Blocked"}],helpText:"Select the status to set for the contact"}}},Ju={name:"Send Broadcast",group:ju.broadcast,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{const i=[...(e.groups||[]).map(t=>({name:t.name,icon:ko.group,uuid:t.uuid,eventType:Io.GroupClicked})),...(e.contacts||[]).map(t=>({name:t.name,icon:ko.contacts,uuid:t.uuid,eventType:Io.ContactClicked})),...(e.legacy_vars||[]).map(t=>({name:t,icon:ko.contacts,content:_u(t,!0)}))];return W`<div>
8832
- <div>${Au(i)}</div>
8830
+ </div>`}}t([mt({type:String,attribute:!1})],Ou.prototype,"endpoint",void 0),t([mt({type:Boolean})],Ou.prototype,"pendingDrop",void 0),t([mt({type:Boolean})],Ou.prototype,"ignoreDrops",void 0),t([mt({type:String})],Ou.prototype,"icon",void 0),t([mt({type:String})],Ou.prototype,"accept",void 0),t([mt({type:Number})],Ou.prototype,"max",void 0),t([mt({type:Array})],Ou.prototype,"attachments",void 0),t([mt({type:Boolean,attribute:!1})],Ou.prototype,"uploading",void 0);let Pu="dev";try{Pu="0.156.9"}catch(t){}const Ru=Pu,Nu="message",Bu="voice",Fu="background",qu="ai",Uu="airtime",ju={send:"send",contacts:"contacts",save:"save",services:"services",broadcast:"broadcast",trigger:"trigger"},Hu={wait:"wait",split:"split"},Wu={[ju.send]:{color:"#3498db",title:"Send",description:"Actions that send messages or content to contacts"},[ju.contacts]:{color:"#01c1af",title:"Contact",description:"Actions that update contact information"},[ju.save]:{color:"#1a777c",title:"Save",description:"Actions that save or store data"},[ju.services]:{color:"#f79035ff",title:"Services",description:"Call external services and APIs"},[ju.broadcast]:{color:"#8e5ea7",title:"Other People",description:"Actions that apply to others instead of the contact"},[ju.trigger]:{color:"#df419f",title:"Trigger",description:"Actions that trigger other behavior"}},Vu={[Hu.wait]:{color:"#4d7dad",title:"Wait",description:"Wait for user and split on their response"},[Hu.split]:{color:"#aaaaaa",title:"Split",description:"Split the flow based on conditions"}},Zu={name:"Add Input Labels",group:ju.save,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{return W`<div>${i=e.labels,o="label",pc(i.map(t=>t.name),o)}</div>`;var i,o},toFormData:t=>({labels:t.labels||null,uuid:t.uuid}),form:{labels:{type:"select",label:"Labels",helpText:"Select labels to add to the input. Type a new label name to create it.",required:!0,options:[],multi:!0,searchable:!0,endpoint:"/api/v2/labels.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for labels or type to create new ones...",allowCreate:!0,createArbitraryOption:(t,e)=>!e.find(e=>e.name.toLowerCase().trim()===t.toLowerCase().trim())&&t.trim()?{name:t.trim(),arbitrary:!0}:null}},fromFormData:t=>({uuid:t.uuid,type:"add_input_labels",labels:(t.labels||[]).map(t=>({uuid:t.uuid,name:t.name}))})},Yu={name:"Add URN",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{const i=yc.find(t=>t.scheme===e.scheme),o=(null==i?void 0:i.path)||e.scheme;return hc(W`Add ${o} ${cc(e.path,!0)}`,`Add ${o} ${e.path}`)},toFormData:t=>{const e=yc.find(e=>e.scheme===t.scheme);return{uuid:t.uuid,scheme:e?[{name:e.path,value:t.scheme}]:null,path:t.path||""}},fromFormData:t=>{const e=Array.isArray(t.scheme)&&t.scheme.length>0?t.scheme[0].value:"tel";return{uuid:t.uuid,type:"add_contact_urn",scheme:e,path:t.path||""}},form:{scheme:{type:"select",label:"URN Type",helpText:"Select the type of URN to add to the contact",required:!0,searchable:!1,multi:!1,options:yc.map(t=>({name:t.path,value:t.scheme}))},path:{type:"text",label:"URN Value",helpText:"Enter the URN value (e.g., phone number, Facebook ID, etc.)",required:!0,placeholder:"Enter the URN value...",evaluated:!0}},validate:t=>{const e={};return t.scheme&&0!==t.scheme.length||(e.scheme="URN type is required"),t.path&&""!==t.path.trim()||(e.path="URN value is required"),{valid:0===Object.keys(e).length,errors:e}}},Ku={name:"Update Field",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>e.value?hc(W`Set <strong>${e.field.name}</strong> to
8831
+ ${cc(e.value,!0)}`,`Set ${e.field.name} to ${e.value}`):hc(W`Clear <strong>${e.field.name}</strong>`,`Clear ${e.field.name}`),form:{field:{type:"select",label:"Field",required:!0,searchable:!0,clearable:!1,placeholder:"Search for contact fields...",nameKey:"name",valueKey:"key",endpoint:"/api/v2/fields.json",helpText:"Select the contact field to update",allowCreate:!0,createArbitraryOption:t=>({key:t,name:t,type:"text"})},value:{type:"textarea",label:"Value",placeholder:"Enter field value...",evaluated:!0,helpText:"The new value for the contact field. You can use expressions like @contact.name"}},toFormData:t=>({uuid:t.uuid,field:t.field?[t.field]:null,value:t.value}),fromFormData:t=>{const e=t.field[0];return{uuid:t.uuid,type:"set_contact_field",field:{name:e.name,key:e.key},value:t.value}},sanitize:t=>{t.value&&"string"==typeof t.value&&(t.value=t.value.trim())}},Gu={name:"Update Channel",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>hc(W`Set to <strong>${e.channel.name}</strong>`,`Set to ${e.channel.name}`),form:{channel:{type:"select",label:"Channel",required:!0,searchable:!0,clearable:!1,endpoint:"/api/v2/channels.json",valueKey:"uuid",nameKey:"name",placeholder:"Select channel",helpText:"Select the channel to set for the contact"}},toFormData:t=>({uuid:t.uuid,channel:t.channel?[t.channel]:null}),fromFormData:t=>{var e;const i=null===(e=t.channel)||void 0===e?void 0:e[0];return{uuid:t.uuid,type:"set_contact_channel",channel:{uuid:i.uuid||i.value,name:i.name}}}},Xu={name:"Update Language",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{const i=ic(e.language);return hc(W`Set to <strong>${i}</strong>`,`Set to ${i}`)},form:{language:{type:"select",label:"Language",required:!0,searchable:!0,clearable:!1,valueKey:"value",nameKey:"name",helpText:"Select the language to set for the contact",getDynamicOptions:()=>{const t=Ec(),e=null==t?void 0:t.getState().workspace;return(null==e?void 0:e.languages)&&Array.isArray(e.languages)?e.languages.map(t=>({value:t,name:ic(t)})):[]}}},toFormData:t=>t.language?{language:[{value:t.language,name:ic(t.language)}],uuid:t.uuid}:{language:null,uuid:t.uuid},fromFormData:t=>({uuid:t.uuid,type:"set_contact_language",language:t.language[0].value}),validate:t=>{const e={};return t.language||(e.language="Language is required"),{valid:0===Object.keys(e).length,errors:e}}},Qu={name:"Update Status",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>hc(W`Set to <strong>${Pe(e.status)}</strong>`,`Set to ${Pe(e.status)}`),toFormData:t=>({uuid:t.uuid,status:[{name:Pe(t.status||"active"),value:t.status||"active"}]}),fromFormData:t=>({status:t.status[0].value,type:"set_contact_status",uuid:t.uuid}),form:{status:{type:"select",label:"Status",required:!0,searchable:!1,clearable:!1,options:[{value:"active",name:"Active"},{value:"archived",name:"Archived"},{value:"stopped",name:"Stopped"},{value:"blocked",name:"Blocked"}],helpText:"Select the status to set for the contact"}}},Ju={name:"Send Broadcast",group:ju.broadcast,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{const i=[...(e.groups||[]).map(t=>({name:t.name,icon:ko.group,uuid:t.uuid,eventType:Io.GroupClicked})),...(e.contacts||[]).map(t=>({name:t.name,icon:ko.contacts,uuid:t.uuid,eventType:Io.ContactClicked})),...(e.legacy_vars||[]).map(t=>({name:t,icon:ko.contacts,content:cc(t,!0)}))];return W`<div>
8832
+ <div>${mc(i)}</div>
8833
8833
  <div style="margin-top: 0.5em">
8834
8834
  ${e.template?W`<div
8835
8835
  style="border: 1px solid #7dc8bc;padding: 0.5em;margin-bottom: 0.5em;border-radius: 4px; display:flex;align-items: flex-start;background: #f0faf7;color: #128C7E;font-size: 0.85em;"
@@ -8840,10 +8840,10 @@ background: #ccc;
8840
8840
  ></temba-icon>
8841
8841
  <div style="margin-left:0.4em">${e.template.name}</div>
8842
8842
  </div>`:null}
8843
- ${ku(_u(e.text,!0),e.text)}
8843
+ ${hc(cc(e.text,!0),e.text)}
8844
8844
  </div>
8845
- </div>`},form:{recipients:{type:"select",label:"Recipients",helpText:"Select the contacts or groups to receive the broadcast",multi:!0,searchable:!0,endpoint:"/contact/omnibox/?types=gc",queryParam:"search",valueKey:"id",nameKey:"name",placeholder:"Search for contacts or groups...",required:!0,expressions:"session"},text:{type:"message-editor",label:"Message",helpText:"Enter the message to send with optional attachments. You can use expressions like @contact.name",required:!0,evaluated:!0,placeholder:"Type your message here...",maxLength:640,maxAttachments:10,accept:"",endpoint:"/api/v2/media.json",counter:"temba-charcount",gsm:!0,autogrow:!0},template:{type:"template-editor",endpoint:"/api/internal/templates.json"}},layout:["recipients","text",{type:"accordion",sections:[{label:"WhatsApp Template",collapsed:!0,localizable:!1,getValueCount:t=>!!t.template,items:["template"]}]}],toFormData:t=>({uuid:t.uuid,recipients:[...(t.contacts||[]).map(t=>({id:t.uuid,name:t.name,type:"contact"})),...(t.groups||[]).map(t=>({id:t.uuid,name:t.name,type:"group"})),...(t.legacy_vars||[]).map(t=>({id:t,name:t,type:"expression"}))],text:t.text||"",attachments:t.attachments||[],template:t.template||null,template_variables:t.template_variables||[]}),fromFormData:t=>{const e=t.recipients||[],i=e.filter(t=>"contact"===t.type||!t.type&&!t.expression&&t.id).map(t=>({uuid:t.id,name:t.name})),o=e.filter(t=>"group"===t.type).map(t=>({uuid:t.id,name:t.name})),n=e.filter(t=>"expression"===t.type||t.expression).map(t=>t.value||t.name||t.id),s={uuid:t.uuid,type:"send_broadcast",text:t.text||"",contacts:i,groups:o,attachments:t.attachments||[]};return n.length>0&&(s.legacy_vars=n),0===s.attachments.length&&delete s.attachments,t.template&&(s.template=t.template,s.template_variables=t.template_variables||[]),s},sanitize:t=>{t.text&&"string"==typeof t.text&&(t.text=t.text.trim())},localizable:["text","attachments"],toLocalizationFormData:(t,e)=>{const i={uuid:t.uuid};return e.text&&Array.isArray(e.text)?i.text=e.text[0]||"":i.text="",e.attachments&&Array.isArray(e.attachments)?i.attachments=e.attachments:i.attachments=[],i},fromLocalizationFormData:(t,e)=>{const i={};t.text&&""!==t.text.trim()&&t.text!==e.text&&(i.text=[t.text]);const o=(t.attachments||[]).filter(t=>t&&""!==t.trim());return o.length>0&&JSON.stringify(o)!==JSON.stringify(e.attachments||[])&&(i.attachments=o),i}},tp={name:"Save Flow Result",group:ju.save,flowTypes:[Bu,Nu,Fu],render:(t,e)=>ku(W`Set <strong>${e.name}</strong> to
8846
- ${_u(e.value,!0)}`,`Set ${e.name} to ${e.value}`),form:{name:{type:"select",label:"Result Name",helpText:"Select an existing result name or type a new one",required:!0,placeholder:"Select or enter result name...",createArbitraryOption:(t,e)=>!e.some(e=>e.value.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase())&&t.trim().length>0?{value:t,name:t}:null,searchable:!0,clearable:!1,getDynamicOptions:()=>{const t=$d();return t?t.getState().getFlowResults().map(t=>({value:t.name,name:t.name})):[]}},value:{type:"textarea",label:"Value",helpText:"The value to save for this result (can use expressions)",required:!1,evaluated:!0,placeholder:"Enter value..."},category:{type:"text",label:"Category",helpText:"Optional category for this result",required:!1,maxLength:36,placeholder:"Enter category..."}},layout:["name","value","category"],toFormData:t=>({uuid:t.uuid,name:t.name?[{name:t.name,value:t.name}]:null,value:t.value||"",category:t.category||""}),fromFormData:t=>{let e=t.name||"";return Array.isArray(e)&&e.length>0&&(e=e[0]),"object"==typeof e&&e.value&&(e=e.value),"object"==typeof e&&e.name&&(e=e.name),{uuid:t.uuid,type:"set_run_result",name:String(e),value:t.value||"",category:t.category||""}}},ep={image:"Image",audio:"Audio",video:"Video",application:"Document"},ip={name:"Send Message",group:ju.send,flowTypes:[Bu,Nu,Fu],hideFromActions:!0,render:(t,e)=>{var i;const o=Dc(e.text);return W`
8845
+ </div>`},form:{recipients:{type:"select",label:"Recipients",helpText:"Select the contacts or groups to receive the broadcast",multi:!0,searchable:!0,endpoint:"/contact/omnibox/?types=gc",queryParam:"search",valueKey:"id",nameKey:"name",placeholder:"Search for contacts or groups...",required:!0,expressions:"session"},text:{type:"message-editor",label:"Message",helpText:"Enter the message to send with optional attachments. You can use expressions like @contact.name",required:!0,evaluated:!0,placeholder:"Type your message here...",maxLength:640,maxAttachments:10,accept:"",endpoint:"/api/v2/media.json",counter:"temba-charcount",gsm:!0,autogrow:!0},template:{type:"template-editor",endpoint:"/api/internal/templates.json"}},layout:["recipients","text",{type:"accordion",sections:[{label:"WhatsApp Template",collapsed:!0,localizable:!1,getValueCount:t=>!!t.template,items:["template"]}]}],toFormData:t=>({uuid:t.uuid,recipients:[...(t.contacts||[]).map(t=>({id:t.uuid,name:t.name,type:"contact"})),...(t.groups||[]).map(t=>({id:t.uuid,name:t.name,type:"group"})),...(t.legacy_vars||[]).map(t=>({id:t,name:t,type:"expression"}))],text:t.text||"",attachments:t.attachments||[],template:t.template||null,template_variables:t.template_variables||[]}),fromFormData:t=>{const e=t.recipients||[],i=e.filter(t=>"contact"===t.type||!t.type&&!t.expression&&t.id).map(t=>({uuid:t.id,name:t.name})),o=e.filter(t=>"group"===t.type).map(t=>({uuid:t.id,name:t.name})),n=e.filter(t=>"expression"===t.type||t.expression).map(t=>t.value||t.name||t.id),s={uuid:t.uuid,type:"send_broadcast",text:t.text||"",contacts:i,groups:o,attachments:t.attachments||[]};return n.length>0&&(s.legacy_vars=n),0===s.attachments.length&&delete s.attachments,t.template&&(s.template=t.template,s.template_variables=t.template_variables||[]),s},sanitize:t=>{t.text&&"string"==typeof t.text&&(t.text=t.text.trim())},localizable:["text","attachments"],toLocalizationFormData:(t,e)=>{const i={uuid:t.uuid};return e.text&&Array.isArray(e.text)?i.text=e.text[0]||"":i.text="",e.attachments&&Array.isArray(e.attachments)?i.attachments=e.attachments:i.attachments=[],i},fromLocalizationFormData:(t,e)=>{const i={};t.text&&""!==t.text.trim()&&t.text!==e.text&&(i.text=[t.text]);const o=(t.attachments||[]).filter(t=>t&&""!==t.trim());return o.length>0&&JSON.stringify(o)!==JSON.stringify(e.attachments||[])&&(i.attachments=o),i}},tp={name:"Save Flow Result",group:ju.save,flowTypes:[Bu,Nu,Fu],render:(t,e)=>hc(W`Set <strong>${e.name}</strong> to
8846
+ ${cc(e.value,!0)}`,`Set ${e.name} to ${e.value}`),form:{name:{type:"select",label:"Result Name",helpText:"Select an existing result name or type a new one",required:!0,placeholder:"Select or enter result name...",createArbitraryOption:(t,e)=>!e.some(e=>e.value.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase())&&t.trim().length>0?{value:t,name:t}:null,searchable:!0,clearable:!1,getDynamicOptions:()=>{const t=Ec();return t?t.getState().getFlowResults().map(t=>({value:t.name,name:t.name})):[]}},value:{type:"textarea",label:"Value",helpText:"The value to save for this result (can use expressions)",required:!1,evaluated:!0,placeholder:"Enter value..."},category:{type:"text",label:"Category",helpText:"Optional category for this result",required:!1,maxLength:36,placeholder:"Enter category..."}},layout:["name","value","category"],toFormData:t=>({uuid:t.uuid,name:t.name?[{name:t.name,value:t.name}]:null,value:t.value||"",category:t.category||""}),fromFormData:t=>{let e=t.name||"";return Array.isArray(e)&&e.length>0&&(e=e[0]),"object"==typeof e&&e.value&&(e=e.value),"object"==typeof e&&e.name&&(e=e.name),{uuid:t.uuid,type:"set_run_result",name:String(e),value:t.value||"",category:t.category||""}}},ep={image:"Image",audio:"Audio",video:"Video",application:"Document"},ip={name:"Send Message",group:ju.send,flowTypes:[Bu,Nu,Fu],hideFromActions:!0,render:(t,e)=>{var i;const o=eh(e.text);return W`
8847
8847
  ${e.template?W`<div
8848
8848
  style="border: 1px solid #7dc8bc;padding: 0.5em;margin-bottom: 0.5em;border-radius: 4px; display:flex;align-items: flex-start;background: #f0faf7;color: #128C7E;font-size: 0.85em;"
8849
8849
  >
@@ -8853,7 +8853,7 @@ background: #ccc;
8853
8853
  ></temba-icon>
8854
8854
  <div style="margin-left:0.4em">${e.template.name}</div>
8855
8855
  </div>`:null}
8856
- ${ku(_u(e.text,!0),e.text,6)}
8856
+ ${hc(cc(e.text,!0),e.text,6)}
8857
8857
  ${o.parts.length>1?W`<div style="text-align: right;">
8858
8858
  <temba-charcount
8859
8859
  .text="${e.text}"
@@ -8864,18 +8864,18 @@ background: #ccc;
8864
8864
  ${(e.quick_replies||[]).map(t=>W`<div class="quick-reply">${t}</div>`)}
8865
8865
  </div>`:null}
8866
8866
  `},form:{text:{type:"message-editor",label:"Message",helpText:"Enter the message to send with optional attachments. You can use expressions like @contact.name",required:!0,evaluated:!0,placeholder:"Type your message here...",maxLength:1e4,maxAttachments:10,accept:"",endpoint:"/api/v2/media.json",counter:"temba-charcount",gsm:!0,autogrow:!0},quick_replies:{type:"select",options:[],multi:!0,tags:!0,searchable:!0,placeholder:"Add quick replies...",maxItems:10,evaluated:!0},template:{type:"template-editor",endpoint:"/api/internal/templates.json"},runtime_attachments:{type:"array",itemLabel:"Attachment",sortable:!0,maxItems:10,isEmptyItem:t=>!t.expression||""===t.expression.trim(),itemConfig:{type:{type:"select",width:"140px",options:[{value:"image",name:"Image"},{value:"audio",name:"Audio"},{value:"video",name:"Video"},{value:"application",name:"Document"}],required:!0,searchable:!1},expression:{type:"text",placeholder:"Expression (e.g. @contact.photo)",required:!0,evaluated:!0}}}},layout:["text",{type:"accordion",sections:[{label:"Quick Replies",collapsed:!0,getValueCount:t=>{var e;return(null===(e=t.quick_replies)||void 0===e?void 0:e.length)||0},items:["quick_replies"]},{label:"WhatsApp Template",collapsed:!0,localizable:!1,getValueCount:t=>!!t.template,items:["template"]},{label:"Runtime Attachments",collapsed:!0,getValueCount:t=>{var e;return(null===(e=t.runtime_attachments)||void 0===e?void 0:e.filter(t=>t&&t.expression&&""!==t.expression.trim()).length)||0},items:["runtime_attachments"]}]}],toFormData:t=>{const e=[],i=[];return t.attachments&&Array.isArray(t.attachments)&&t.attachments.forEach(t=>{if("string"==typeof t&&t.includes(":")){const o=t.indexOf(":"),n=t.substring(0,o),s=t.substring(o+1);n.includes("/")?i.push(t):e.push({type:{name:ep[n]||Pe(n),value:n},expression:s})}}),{uuid:t.uuid,text:t.text||"",attachments:i,runtime_attachments:e,quick_replies:(t.quick_replies||[]).map(t=>({name:t,value:t})),template:t.template||null,template_variables:t.template_variables||[]}},fromFormData:t=>{const e={uuid:t.uuid,type:"send_msg",text:t.text||"",attachments:[],quick_replies:(t.quick_replies||[]).map(t=>"string"==typeof t?t:t.value||t.name||t)},i=t.attachments||[],o=(t.runtime_attachments||[]).filter(t=>t&&t.type&&t.expression).map(t=>`${t.type[0].value}:${t.expression}`);return e.attachments=[...i,...o],0===e.quick_replies.length&&delete e.quick_replies,t.template&&(e.template=t.template,e.template_variables=t.template_variables||[]),e},sanitize:t=>{t.text&&"string"==typeof t.text&&(t.text=t.text.trim())},validate:t=>{const e={},i=t.attachments||[],o=(t.runtime_attachments||[]).filter(t=>t&&t.expression&&""!==t.expression.trim());return i.length+o.length>10&&(o.length>0&&(e.runtime_attachments="Each message can only have up to 10 attachments"),i.length>0&&(e.text="Each message can only have up to 10 total attachments")),{valid:0===Object.keys(e).length,errors:e}},localizable:["text","quick_replies","attachments"],toLocalizationFormData:(t,e)=>{const i={uuid:t.uuid};e.text&&Array.isArray(e.text)?i.text=e.text[0]||"":i.text="",e.attachments&&Array.isArray(e.attachments)&&(i.attachments=e.attachments),e.quick_replies&&Array.isArray(e.quick_replies)&&(i.quick_replies=e.quick_replies.map(t=>({name:t,value:t})));const o=[],n=[];return i.attachments&&Array.isArray(i.attachments)&&i.attachments.forEach(t=>{if("string"==typeof t&&t.includes(":")){const e=t.indexOf(":"),i=t.substring(0,e),s=t.substring(e+1);i.includes("/")?n.push(t):o.push({type:{name:ep[i]||Pe(i),value:i},expression:s})}}),i.attachments=n,i.runtime_attachments=o,i},fromLocalizationFormData:(t,e)=>{const i={};t.text&&""!==t.text.trim()&&t.text!==e.text&&(i.text=[t.text]);const o=(t.quick_replies||[]).map(t=>"string"==typeof t?t:t.value||t.name||t).filter(t=>t&&""!==t.trim());o.length>0&&JSON.stringify(o)!==JSON.stringify(e.quick_replies||[])&&(i.quick_replies=o);const n=[...(t.attachments||[]).filter(t=>t&&""!==t.trim()),...(t.runtime_attachments||[]).filter(t=>t&&t.type&&t.expression&&""!==t.expression.trim()).map(t=>`${t.type[0].value}:${t.expression}`)];return n.length>0&&JSON.stringify(n)!==JSON.stringify(e.attachments||[])&&(i.attachments=n),i}},op={name:"Send Email",group:ju.broadcast,flowTypes:[Bu,Nu,Fu],render:(t,e)=>W`<div>
8867
- <div>${Su(e.addresses,ko.email,!0)}</div>
8867
+ <div>${pc(e.addresses,ko.email,!0)}</div>
8868
8868
  <div style="margin-top: 0.5em">
8869
- ${ku(_u(e.subject,!0),e.subject)}
8869
+ ${hc(cc(e.subject,!0),e.subject)}
8870
8870
  </div>
8871
- </div>`,form:{addresses:{type:"select",label:"Recipients",multi:!0,searchable:!0,placeholder:"Enter email addresses...",emails:!0,expressions:"session"},subject:{type:"text",label:"Subject",required:!0,evaluated:!0,placeholder:"Enter email subject",maxLength:1e3},body:{type:"textarea",required:!0,evaluated:!0,maxLength:1e4,minHeight:175}},fromFormData:t=>({uuid:t.uuid,type:"send_email",addresses:t.addresses.map(t=>t.value),subject:t.subject,body:t.body}),localizable:["subject","body"],toLocalizationFormData:(t,e)=>{const i={uuid:t.uuid};return e.subject&&Array.isArray(e.subject)?i.subject=e.subject[0]||"":i.subject="",e.body&&Array.isArray(e.body)?i.body=e.body[0]||"":i.body="",i},fromLocalizationFormData:(t,e)=>{const i={};return t.subject&&""!==t.subject.trim()&&t.subject!==e.subject&&(i.subject=[t.subject]),t.body&&""!==t.body.trim()&&t.body!==e.body&&(i.body=[t.body]),i},validate:t=>{const e={};return t.addresses&&0!==t.addresses.length||(e.addresses="At least one recipient email address is required"),{valid:0===Object.keys(e).length,errors:e}}},np={name:"Start Flow",group:ju.broadcast,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{let i=W``;if(e.create_contact)i=W`Create a new contact`;else if(e.contact_query)i=W`${_u(e.contact_query,!0)}`;else{const t=[...(e.groups||[]).map(t=>({name:t.name,icon:ko.group,uuid:t.uuid,eventType:Io.GroupClicked})),...(e.contacts||[]).map(t=>({name:t.name,icon:ko.contacts,uuid:t.uuid,eventType:Io.ContactClicked})),...(e.legacy_vars||[]).map(t=>({name:t,icon:ko.contacts,content:_u(t,!0)}))];i=W`${Au(t)}`}return W`
8871
+ </div>`,form:{addresses:{type:"select",label:"Recipients",multi:!0,searchable:!0,placeholder:"Enter email addresses...",emails:!0,expressions:"session"},subject:{type:"text",label:"Subject",required:!0,evaluated:!0,placeholder:"Enter email subject",maxLength:1e3},body:{type:"textarea",required:!0,evaluated:!0,maxLength:1e4,minHeight:175}},fromFormData:t=>({uuid:t.uuid,type:"send_email",addresses:t.addresses.map(t=>t.value),subject:t.subject,body:t.body}),localizable:["subject","body"],toLocalizationFormData:(t,e)=>{const i={uuid:t.uuid};return e.subject&&Array.isArray(e.subject)?i.subject=e.subject[0]||"":i.subject="",e.body&&Array.isArray(e.body)?i.body=e.body[0]||"":i.body="",i},fromLocalizationFormData:(t,e)=>{const i={};return t.subject&&""!==t.subject.trim()&&t.subject!==e.subject&&(i.subject=[t.subject]),t.body&&""!==t.body.trim()&&t.body!==e.body&&(i.body=[t.body]),i},validate:t=>{const e={};return t.addresses&&0!==t.addresses.length||(e.addresses="At least one recipient email address is required"),{valid:0===Object.keys(e).length,errors:e}}},np={name:"Start Flow",group:ju.broadcast,flowTypes:[Bu,Nu,Fu],render:(t,e)=>{let i=W``;if(e.create_contact)i=W`Create a new contact`;else if(e.contact_query)i=W`${cc(e.contact_query,!0)}`;else{const t=[...(e.groups||[]).map(t=>({name:t.name,icon:ko.group,uuid:t.uuid,eventType:Io.GroupClicked})),...(e.contacts||[]).map(t=>({name:t.name,icon:ko.contacts,uuid:t.uuid,eventType:Io.ContactClicked})),...(e.legacy_vars||[]).map(t=>({name:t,icon:ko.contacts,content:cc(t,!0)}))];i=W`${mc(t)}`}return W`
8872
8872
  <div>
8873
8873
  <div>${i}</div>
8874
8874
  <div style="margin-top: 0.5em">
8875
- ${Tu([e.flow],"flow")}
8875
+ ${vc([e.flow],"flow")}
8876
8876
  </div>
8877
8877
  </div>
8878
- `},toFormData:t=>{var e;const i=t;let o="manual";t.create_contact?o="create":i.contact_query&&(o="query");const n=[{value:"manual",name:"Select recipients manually"},{value:"query",name:"Select a contact with a query"},{value:"create",name:"Create a new contact"}],s=n.find(t=>t.value===o)||n[0];return{flow:t.flow?[t.flow]:null,recipients:[...(t.contacts||[]).map(t=>({id:t.uuid,name:t.name,type:"contact"})),...(t.groups||[]).map(t=>({id:t.uuid,name:t.name,type:"group"})),...(t.legacy_vars||[]).map(t=>({id:t,name:t,type:"expression"}))],startType:[s],contactQuery:i.contact_query||"",skipContactsInFlow:(null===(e=i.exclusions)||void 0===e?void 0:e.in_a_flow)||!1,uuid:t.uuid}},form:{flow:{type:"select",label:"Flow",helpText:"Select the flow to start",required:!0,searchable:!0,endpoint:"/api/v2/flows.json",valueKey:"uuid",nameKey:"name",placeholder:"Select a flow..."},startType:{type:"select",label:"Start Type",helpText:"How should contacts be selected?",required:!0,options:[{value:"manual",name:"Select recipients manually"},{value:"query",name:"Select a contact with a query"},{value:"create",name:"Create a new contact"}]},recipients:{type:"select",label:"Recipients",helpText:"Select who should be started in the flow",multi:!0,searchable:!0,endpoint:"/contact/omnibox/?types=gc",queryParam:"search",valueKey:"id",nameKey:"name",placeholder:"Search for contacts or groups...",expressions:"session",conditions:{visible:t=>{var e,i;return"manual"===(null===(i=null===(e=t.startType)||void 0===e?void 0:e[0])||void 0===i?void 0:i.value)}}},contactQuery:{type:"text",evaluated:!0,label:"Contact Query",helpText:"Only one matching contact will be started",placeholder:"household_id = @fields.household_id",conditions:{visible:t=>{var e,i;return"query"===(null===(i=null===(e=t.startType)||void 0===e?void 0:e[0])||void 0===i?void 0:i.value)}}},skipContactsInFlow:{type:"checkbox",label:"Skip contacts currently in a flow",helpText:"Avoid interrupting a contact who is already in a flow"}},layout:["flow","startType","recipients","contactQuery","skipContactsInFlow"],validate:t=>{var e,i;const o={},n=null===(i=null===(e=t.startType)||void 0===e?void 0:e[0])||void 0===i?void 0:i.value;return"manual"!==n||t.recipients&&0!==t.recipients.length||(o.recipients="At least one contact or group must be selected"),"query"!==n||t.contactQuery&&t.contactQuery.trim()||(o.contactQuery="Contact query is required"),{valid:0===Object.keys(o).length,errors:o}},fromFormData:t=>{const e={uuid:t.uuid,type:"start_session",flow:{uuid:t.flow[0].uuid||t.flow[0].value,name:t.flow[0].name},groups:[],contacts:[]},i=t.startType[0].value;if("create"===i)e.create_contact=!0;else if("query"===i)e.contact_query=t.contactQuery||"";else{const i=t.recipients||[];e.contacts=i.filter(t=>"contact"===t.type||!t.type&&!t.expression&&t.id).map(t=>({uuid:t.id,name:t.name})),e.groups=i.filter(t=>"group"===t.type).map(t=>({uuid:t.id,name:t.name}));const o=i.filter(t=>"expression"===t.type||t.expression).map(t=>t.value||t.name||t.id);o.length>0&&(e.legacy_vars=o)}return t.skipContactsInFlow&&(e.exclusions={in_a_flow:!0}),e}},sp={name:"Update Name",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>ku(W`Set to ${_u(e.name,!0)}`,`Set to ${e.name}`),form:{name:{type:"text",label:"Name",placeholder:"Enter contact name...",required:!0,evaluated:!0,helpText:"The new name for the contact. You can use expressions like @contact.name"}},sanitize:t=>{t.name&&"string"==typeof t.name&&(t.name=t.name.trim())}},rp={name:"Add to Group",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>W`<div>${Du(e.groups,"group")}</div>`,toFormData:t=>({groups:t.groups||null,uuid:t.uuid}),form:{groups:{type:"select",label:"Groups",helpText:"Select the groups to add the contact to",required:!0,options:[],multi:!0,searchable:!0,endpoint:"/api/v2/groups.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for groups...",shouldExclude:t=>!!t.query,allowCreate:!0,createArbitraryOption:(t,e)=>!e.find(e=>e.name.toLowerCase().trim()===t.toLowerCase().trim())&&t.trim()?{name:t.trim(),arbitrary:!0}:null}},fromFormData:t=>({uuid:t.uuid,type:"add_contact_groups",groups:(t.groups||[]).map(t=>({uuid:t.uuid,name:t.name}))})},ap={name:"Remove from Group",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>e.all_groups?W`<div>Remove from all groups</div>`:W`<div>${Du(e.groups,"group")}</div>`,toFormData:t=>({uuid:t.uuid,all_groups:t.all_groups||!1,groups:t.groups||null}),form:{groups:{type:"select",label:"Groups",helpText:"Select the groups to remove the contact from",options:[],multi:!0,searchable:!0,endpoint:"/api/v2/groups.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for groups...",conditions:{visible:t=>!t.all_groups}},all_groups:{type:"checkbox",label:"Remove from All Groups",helpText:"Check this to remove the contact from all groups instead of specific ones"}},validate:t=>{const e={};return t.all_groups||t.groups&&0!==t.groups.length||(e.groups='At least one group must be selected or check "Remove from All Groups"'),{valid:0===Object.keys(e).length,errors:e}},fromFormData:t=>({uuid:t.uuid,type:"remove_contact_groups",groups:t.all_groups?[]:(t.groups||[]).map(t=>({uuid:t.uuid,name:t.name})),all_groups:t.all_groups||!1})},lp={name:"Request Opt-In",group:ju.send,flowTypes:[],render:(t,e)=>{var i;const o=(null===(i=e.optin)||void 0===i?void 0:i.name)||"Unknown opt-in";return ku(W`Request <strong>${o}</strong>`,`Request ${o}`)},toFormData:t=>({uuid:t.uuid,optin:t.optin?[t.optin]:null}),form:{optin:{type:"select",label:"Opt-In",required:!0,searchable:!0,endpoint:"/api/v2/optins.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for opt-ins or type to create one...",helpText:"Select an existing opt-in to request, or type a name to create a new one.",allowCreate:!0,createArbitraryOption:(t,e)=>!e.find(e=>e.name.toLowerCase().trim()===t.toLowerCase().trim())&&t.trim()?{name:t.trim(),arbitrary:!0}:null}},fromFormData:t=>{var e;const i=null===(e=t.optin)||void 0===e?void 0:e[0];return{uuid:t.uuid,type:"request_optin",optin:{uuid:i.uuid||i.value,name:i.name}}}},dp=W`<svg
8878
+ `},toFormData:t=>{var e;const i=t;let o="manual";t.create_contact?o="create":i.contact_query&&(o="query");const n=[{value:"manual",name:"Select recipients manually"},{value:"query",name:"Select a contact with a query"},{value:"create",name:"Create a new contact"}],s=n.find(t=>t.value===o)||n[0];return{flow:t.flow?[t.flow]:null,recipients:[...(t.contacts||[]).map(t=>({id:t.uuid,name:t.name,type:"contact"})),...(t.groups||[]).map(t=>({id:t.uuid,name:t.name,type:"group"})),...(t.legacy_vars||[]).map(t=>({id:t,name:t,type:"expression"}))],startType:[s],contactQuery:i.contact_query||"",skipContactsInFlow:(null===(e=i.exclusions)||void 0===e?void 0:e.in_a_flow)||!1,uuid:t.uuid}},form:{flow:{type:"select",label:"Flow",helpText:"Select the flow to start",required:!0,searchable:!0,endpoint:"/api/v2/flows.json",valueKey:"uuid",nameKey:"name",placeholder:"Select a flow..."},startType:{type:"select",label:"Start Type",helpText:"How should contacts be selected?",required:!0,options:[{value:"manual",name:"Select recipients manually"},{value:"query",name:"Select a contact with a query"},{value:"create",name:"Create a new contact"}]},recipients:{type:"select",label:"Recipients",helpText:"Select who should be started in the flow",multi:!0,searchable:!0,endpoint:"/contact/omnibox/?types=gc",queryParam:"search",valueKey:"id",nameKey:"name",placeholder:"Search for contacts or groups...",expressions:"session",conditions:{visible:t=>{var e,i;return"manual"===(null===(i=null===(e=t.startType)||void 0===e?void 0:e[0])||void 0===i?void 0:i.value)}}},contactQuery:{type:"text",evaluated:!0,label:"Contact Query",helpText:"Only one matching contact will be started",placeholder:"household_id = @fields.household_id",conditions:{visible:t=>{var e,i;return"query"===(null===(i=null===(e=t.startType)||void 0===e?void 0:e[0])||void 0===i?void 0:i.value)}}},skipContactsInFlow:{type:"checkbox",label:"Skip contacts currently in a flow",helpText:"Avoid interrupting a contact who is already in a flow"}},layout:["flow","startType","recipients","contactQuery","skipContactsInFlow"],validate:t=>{var e,i;const o={},n=null===(i=null===(e=t.startType)||void 0===e?void 0:e[0])||void 0===i?void 0:i.value;return"manual"!==n||t.recipients&&0!==t.recipients.length||(o.recipients="At least one contact or group must be selected"),"query"!==n||t.contactQuery&&t.contactQuery.trim()||(o.contactQuery="Contact query is required"),{valid:0===Object.keys(o).length,errors:o}},fromFormData:t=>{const e={uuid:t.uuid,type:"start_session",flow:{uuid:t.flow[0].uuid||t.flow[0].value,name:t.flow[0].name},groups:[],contacts:[]},i=t.startType[0].value;if("create"===i)e.create_contact=!0;else if("query"===i)e.contact_query=t.contactQuery||"";else{const i=t.recipients||[];e.contacts=i.filter(t=>"contact"===t.type||!t.type&&!t.expression&&t.id).map(t=>({uuid:t.id,name:t.name})),e.groups=i.filter(t=>"group"===t.type).map(t=>({uuid:t.id,name:t.name}));const o=i.filter(t=>"expression"===t.type||t.expression).map(t=>t.value||t.name||t.id);o.length>0&&(e.legacy_vars=o)}return t.skipContactsInFlow&&(e.exclusions={in_a_flow:!0}),e}},sp={name:"Update Name",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>hc(W`Set to ${cc(e.name,!0)}`,`Set to ${e.name}`),form:{name:{type:"text",label:"Name",placeholder:"Enter contact name...",required:!0,evaluated:!0,helpText:"The new name for the contact. You can use expressions like @contact.name"}},sanitize:t=>{t.name&&"string"==typeof t.name&&(t.name=t.name.trim())}},rp={name:"Add to Group",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>W`<div>${bc(e.groups,"group")}</div>`,toFormData:t=>({groups:t.groups||null,uuid:t.uuid}),form:{groups:{type:"select",label:"Groups",helpText:"Select the groups to add the contact to",required:!0,options:[],multi:!0,searchable:!0,endpoint:"/api/v2/groups.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for groups...",shouldExclude:t=>!!t.query,allowCreate:!0,createArbitraryOption:(t,e)=>!e.find(e=>e.name.toLowerCase().trim()===t.toLowerCase().trim())&&t.trim()?{name:t.trim(),arbitrary:!0}:null}},fromFormData:t=>({uuid:t.uuid,type:"add_contact_groups",groups:(t.groups||[]).map(t=>({uuid:t.uuid,name:t.name}))})},ap={name:"Remove from Group",group:ju.contacts,flowTypes:[Bu,Nu,Fu],render:(t,e)=>e.all_groups?W`<div>Remove from all groups</div>`:W`<div>${bc(e.groups,"group")}</div>`,toFormData:t=>({uuid:t.uuid,all_groups:t.all_groups||!1,groups:t.groups||null}),form:{groups:{type:"select",label:"Groups",helpText:"Select the groups to remove the contact from",options:[],multi:!0,searchable:!0,endpoint:"/api/v2/groups.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for groups...",conditions:{visible:t=>!t.all_groups}},all_groups:{type:"checkbox",label:"Remove from All Groups",helpText:"Check this to remove the contact from all groups instead of specific ones"}},validate:t=>{const e={};return t.all_groups||t.groups&&0!==t.groups.length||(e.groups='At least one group must be selected or check "Remove from All Groups"'),{valid:0===Object.keys(e).length,errors:e}},fromFormData:t=>({uuid:t.uuid,type:"remove_contact_groups",groups:t.all_groups?[]:(t.groups||[]).map(t=>({uuid:t.uuid,name:t.name})),all_groups:t.all_groups||!1})},lp={name:"Request Opt-In",group:ju.send,flowTypes:[],render:(t,e)=>{var i;const o=(null===(i=e.optin)||void 0===i?void 0:i.name)||"Unknown opt-in";return hc(W`Request <strong>${o}</strong>`,`Request ${o}`)},toFormData:t=>({uuid:t.uuid,optin:t.optin?[t.optin]:null}),form:{optin:{type:"select",label:"Opt-In",required:!0,searchable:!0,endpoint:"/api/v2/optins.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for opt-ins or type to create one...",helpText:"Select an existing opt-in to request, or type a name to create a new one.",allowCreate:!0,createArbitraryOption:(t,e)=>!e.find(e=>e.name.toLowerCase().trim()===t.toLowerCase().trim())&&t.trim()?{name:t.trim(),arbitrary:!0}:null}},fromFormData:t=>{var e;const i=null===(e=t.optin)||void 0===e?void 0:e[0];return{uuid:t.uuid,type:"request_optin",optin:{uuid:i.uuid||i.value,name:i.name}}}},dp=W`<svg
8879
8879
  viewBox="0 0 24 24"
8880
8880
  width="16"
8881
8881
  height="16"
@@ -8883,7 +8883,7 @@ background: #ccc;
8883
8883
  >
8884
8884
  <polygon points="6,3 20,12 6,21" />
8885
8885
  </svg>`;let cp=null,hp=null;function up(t){const e=t.querySelector(".audio-play-btn"),i=t.querySelector(".audio-progress");e&&(e.innerHTML='<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><polygon points="6,3 20,12 6,21"/></svg>'),i&&(i.style.width="0%")}function pp(t){t.stopPropagation(),t.preventDefault();const e=t.currentTarget.closest(".audio-player");if(!e)return;const i=e.dataset.url;if(!i)return;const o=e.querySelector(".audio-play-btn"),n=e.querySelector(".audio-progress");if(cp&&hp===e&&!cp.paused)return cp.pause(),void(o.innerHTML='<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><polygon points="6,3 20,12 6,21"/></svg>');cp&&(cp.pause(),cp.currentTime=0,hp&&up(hp),cp=null,hp=null);const s=new Audio(i);cp=s,hp=e,o.innerHTML='<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><rect x="5" y="3" width="4" height="18"/><rect x="15" y="3" width="4" height="18"/></svg>',s.addEventListener("timeupdate",()=>{if(s.duration&&n){const t=s.currentTime/s.duration*100;n.style.width=`${t}%`}}),s.addEventListener("ended",()=>{up(e),cp=null,hp=null}),s.addEventListener("error",()=>{up(e),cp=null,hp=null}),s.play().catch(()=>{up(e),cp=null,hp=null})}const mp={name:"Say Message",group:ju.send,flowTypes:[Bu],render:(t,e)=>{return W`
8886
- ${ku(_u(e.text||"",!0),e.text||"")}
8886
+ ${hc(cc(e.text||"",!0),e.text||"")}
8887
8887
  ${e.audio_url?W`<div style="margin-top: 0.5em;">
8888
8888
  ${i=e.audio_url,W`
8889
8889
  <div
@@ -8918,30 +8918,30 @@ background: #ccc;
8918
8918
  style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0;"
8919
8919
  title="${e.audio_url||""}"
8920
8920
  >
8921
- ${_u(e.audio_url||"",!0)}
8921
+ ${cc(e.audio_url||"",!0)}
8922
8922
  </div>
8923
8923
  </div>
8924
- `,form:{audio_url:{type:"text",label:"Recording URL",required:!0,evaluated:!0}},layout:["audio_url"],toFormData:t=>({uuid:t.uuid,audio_url:t.audio_url||""}),fromFormData:t=>({uuid:t.uuid,type:"play_audio",audio_url:(t.audio_url||"").trim()}),localizable:["audio_url"],toLocalizationFormData:(t,e)=>{const i={uuid:t.uuid};return e.audio_url&&Array.isArray(e.audio_url)?i.audio_url=e.audio_url[0]||"":i.audio_url="",i},fromLocalizationFormData:(t,e)=>{const i={};return t.audio_url&&""!==t.audio_url.trim()&&t.audio_url!==e.audio_url&&(i.audio_url=[t.audio_url]),i}};function fp(t){const e=Sd.getState().flowDefinition;return!!e&&("messaging_background"===e.type&&"message"===t.type)}const vp={name:"Enter a Flow",group:ju.trigger,hideFromActions:!0,flowTypes:[Bu,Nu,Fu],render:(t,e)=>W`${Tu([e.flow],"flow")}`,toFormData:t=>({uuid:t.uuid,flow:t.flow?[t.flow]:[]}),form:{flow:{type:"select",required:!0,placeholder:"Select a flow...",helpText:"The contact will enter this flow and not return",endpoint:"/api/v2/flows.json",valueKey:"uuid",nameKey:"name",shouldExclude:fp}},layout:["flow"],fromFormData:t=>{const e=t.flow[0];return{uuid:t.uuid,type:"enter_flow",terminal:!0,flow:{uuid:e.uuid||e.value,name:e.name}}}},bp={ARS:{code:"ARS",name:"Argentine Peso"},AUD:{code:"AUD",name:"Australian Dollar"},BIF:{code:"BIF",name:"Burundi Franc"},BRL:{code:"BRL",name:"Brazilian Real"},CAD:{code:"CAD",name:"Canadian Dollar"},CDF:{code:"CDF",name:"Congolese Franc"},CLP:{code:"CLP",name:"Chilean Peso"},COP:{code:"COP",name:"Colombian Peso"},DJF:{code:"DJF",name:"Djibouti Franc"},DOP:{code:"DOP",name:"Dominican Peso"},DZD:{code:"DZD",name:"Algerian Dinar"},EUR:{code:"EUR",name:"Euro"},GBP:{code:"GBP",name:"Pound Sterling"},GHS:{code:"GHS",name:"Ghana Cedi"},GNF:{code:"GNF",name:"Guinean Franc"},KES:{code:"KES",name:"Kenyan Shilling"},LBP:{code:"LBP",name:"Lebanese Pound"},LKR:{code:"LKR",name:"Sri Lanka Rupee"},LRD:{code:"LRD",name:"Liberian Dollar"},MWK:{code:"MWK",name:"Malawian Kwacha"},MXN:{code:"MXN",name:"Mexican Peso"},MZN:{code:"MZN",name:"Mozambican Metical"},NAD:{code:"NAD",name:"Namibian Dollar"},NGN:{code:"NGN",name:"Nigerian Naira"},PEN:{code:"PEN",name:"Peruvian Sol"},PHP:{code:"PHP",name:"Philippine Peso"},RWF:{code:"RWF",name:"Rwandan Franc"},SZL:{code:"SZL",name:"Swazi Lilangeni"},TZS:{code:"TZS",name:"Tanzanian Shilling"},UGX:{code:"UGX",name:"Ugandan Shilling"},USD:{code:"USD",name:"US Dollar"},XAF:{code:"XAF",name:"Central African CFA Franc"},XOF:{code:"XOF",name:"West African CFA Franc"},ZAR:{code:"ZAR",name:"South African Rand"},ZMW:{code:"ZMW",name:"Zambian Kwacha"}},yp=Object.values(bp).map(t=>({value:t.code,name:`${t.name} (${t.code})`})),xp=[{type:"has_any_word",name:"has any of the words",operands:1},{type:"has_all_words",name:"has all of the words",operands:1},{type:"has_phrase",name:"has the phrase",operands:1},{type:"has_only_phrase",name:"has only the phrase",operands:1},{type:"has_beginning",name:"starts with",operands:1},{type:"has_text",name:"has some text",operands:0,categoryName:"Has Text"},{type:"has_number",name:"has a number",operands:0,categoryName:"Has Number"},{type:"has_number_between",name:"has a number between",operands:2},{type:"has_number_lt",name:"has a number below",operands:1},{type:"has_number_lte",name:"has a number at or below",operands:1},{type:"has_number_eq",name:"has a number equal to",operands:1},{type:"has_number_gte",name:"has a number at or above",operands:1},{type:"has_number_gt",name:"has a number above",operands:1},{type:"has_date",name:"has a date",operands:0,categoryName:"Has Date"},{type:"has_date_lt",name:"has a date before",operands:1},{type:"has_date_eq",name:"has a date equal to",operands:1},{type:"has_date_gt",name:"has a date after",operands:1},{type:"has_time",name:"has a time",operands:0,categoryName:"Has Time"},{type:"has_phone",name:"has a phone number",operands:0,categoryName:"Has Phone"},{type:"has_email",name:"has an email",operands:0,categoryName:"Has Email"},{type:"has_state",name:"has state",operands:0,categoryName:"Has State",filter:"locations"},{type:"has_district",name:"has district",operands:1,categoryName:"Has District",filter:"locations"},{type:"has_ward",name:"has ward",operands:2,categoryName:"Has Ward",filter:"locations"},{type:"has_group",name:"is in the group",operands:1,visibility:"hidden"},{type:"has_category",name:"has the category",operands:0,visibility:"hidden"},{type:"has_error",name:"has an error",operands:0,categoryName:"Has Error",visibility:"hidden"},{type:"has_value",name:"is not empty",operands:0,categoryName:"Not Empty",visibility:"hidden"},{type:"has_pattern",name:"matches regex",operands:1}],wp=t=>xp.filter(e=>"hidden"!==e.visibility&&(!e.filter||!!t&&t.includes(e.filter))),_p=new Set(["has_beginning","has_number","has_number_between","has_number_lt","has_number_lte","has_number_eq","has_number_gte","has_number_gt","has_pattern"]),kp=t=>xp.find(e=>e.type===t),Cp=t=>t.map(t=>({value:t.type,name:t.name})),Sp={type:"text",required:!1,maxLength:64,placeholder:"(optional)",helpText:"The name to use to reference this result in the flow"},Ap={type:"checkbox",label:"Require rules to be localized",helpText:"Each language must specify its own rules for this node"},Ep={type:"checkbox",label:"Require categories to be localized",helpText:t=>{var e;const i=null===(e=t.result_name)||void 0===e?void 0:e.trim();if(i){return`Only enable if you plan to use @results.${i.toLowerCase().replace(/\s+/g,"_")}.category_localized`}return"Only enable if you plan to use category_localized in your expressions for this result"},conditions:{visible:t=>!!t.result_name}},$p={label:"Save Result",localizable:!1,items:["result_name"],collapsed:t=>!(t._isNew&&t.result_name),getValueCount:t=>!!t.result_name},Tp={type:"accordion",multi:!0,sections:[$p,{label:"Localization",localizable:!1,items:["localizeRules","localizeCategories"],collapsed:!0,getValueCount:t=>!(!t.localizeRules&&!t.localizeCategories)}]},Dp={type:"accordion",multi:!0,sections:[$p]};function Mp(t,e){var i,o;const n=(null===(i=t.router)||void 0===i?void 0:i.categories)||[],s={};n.forEach(t=>{const i=t.uuid,o=e[i];s[i]={originalName:t.name,localizedName:o&&o.name?Array.isArray(o.name)?o.name[0]||"":o.name:""}});const r=(null===(o=t.router)||void 0===o?void 0:o.cases)||[],a={};return r.forEach(t=>{var i,o;if(!(null===(i=t.arguments)||void 0===i?void 0:i.length)||!t.arguments.some(t=>t))return;const n=e[t.uuid],s=(null===(o=kp(t.type))||void 0===o?void 0:o.name)||t.type;a[t.uuid]={operatorName:s,originalArguments:[...t.arguments],localizedArguments:(null==n?void 0:n.arguments)?[...n.arguments]:t.arguments.map(()=>"")}}),{categories:s,rules:a}}function zp(t,e){const i={};return t.categories&&Object.keys(t.categories).forEach(e=>{var o,n;const s=t.categories[e],r=(null===(o=s.localizedName)||void 0===o?void 0:o.trim())||"",a=(null===(n=s.originalName)||void 0===n?void 0:n.trim())||"";r&&r!==a&&(i[e]={name:[r]})}),t.rules&&Object.keys(t.rules).forEach(e=>{const o=t.rules[e],n=o.localizedArguments||[],s=o.originalArguments||[],r=n.some((t,e)=>(null==t?void 0:t.trim())&&t.trim()!==(s[e]||""));r&&(i[e]={arguments:n.map(t=>(null==t?void 0:t.trim())||"")})}),i}const Ip={type:"split_by_airtime",name:"Send Airtime",group:ju.services,flowTypes:[Bu,Nu,Fu],features:[Uu],showAsAction:!0,form:{amounts:{type:"array",label:"Airtime Amounts",helpText:"Define the currencies and amounts to transfer",required:!0,itemLabel:"Amount",sortable:!1,minItems:1,maxItems:10,isEmptyItem:t=>!t.currency||!t.amount||""===t.amount.trim(),itemConfig:{currency:{type:"select",placeholder:"Select a currency",required:!0,options:yp,searchable:!0,multi:!1,width:"200px"},amount:{type:"text",placeholder:"Amount",required:!0}}},result_name:Sp},layout:["amounts","result_name"],validate:t=>{const e={};if(t.amounts&&Array.isArray(t.amounts)){const i=t.amounts.filter(t=>(null==t?void 0:t.currency)&&(null==t?void 0:t.amount)&&""!==t.amount.trim());if(0===i.length)return e.amounts="At least one currency and amount is required",{valid:!1,errors:e};const o=new Set,n=[];i.forEach(t=>{var e;const i=Array.isArray(t.currency)&&t.currency.length>0?t.currency[0].value:"string"==typeof t.currency?t.currency:null===(e=t.currency)||void 0===e?void 0:e.value;o.has(i)?n.push(i):o.add(i)}),n.length>0&&(e.amounts=`Duplicate currencies found: ${n.join(", ")}`);for(const t of i){const i=t.amount.trim();if(isNaN(Number(i))||Number(i)<=0)return e.amounts="All amounts must be valid positive numbers",{valid:!1,errors:e}}}else e.amounts="At least one currency and amount is required";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=>"transfer_airtime"===t.type);if(!i||!i.amounts)return W`<div class="body">Configure airtime transfer</div>`;const o=i.amounts,n=Object.keys(o);if(0===n.length)return W`<div class="body">Configure airtime transfer</div>`;const s=n[0],r=o[s],a=n.length-1;return W`
8924
+ `,form:{audio_url:{type:"text",label:"Recording URL",required:!0,evaluated:!0}},layout:["audio_url"],toFormData:t=>({uuid:t.uuid,audio_url:t.audio_url||""}),fromFormData:t=>({uuid:t.uuid,type:"play_audio",audio_url:(t.audio_url||"").trim()}),localizable:["audio_url"],toLocalizationFormData:(t,e)=>{const i={uuid:t.uuid};return e.audio_url&&Array.isArray(e.audio_url)?i.audio_url=e.audio_url[0]||"":i.audio_url="",i},fromLocalizationFormData:(t,e)=>{const i={};return t.audio_url&&""!==t.audio_url.trim()&&t.audio_url!==e.audio_url&&(i.audio_url=[t.audio_url]),i}};function fp(t){const e=Sd.getState().flowDefinition;return!!e&&("messaging_background"===e.type&&"message"===t.type)}const vp={name:"Enter a Flow",group:ju.trigger,hideFromActions:!0,flowTypes:[Bu,Nu,Fu],render:(t,e)=>W`${vc([e.flow],"flow")}`,toFormData:t=>({uuid:t.uuid,flow:t.flow?[t.flow]:[]}),form:{flow:{type:"select",required:!0,placeholder:"Select a flow...",helpText:"The contact will enter this flow and not return",endpoint:"/api/v2/flows.json",valueKey:"uuid",nameKey:"name",shouldExclude:fp}},layout:["flow"],fromFormData:t=>{const e=t.flow[0];return{uuid:t.uuid,type:"enter_flow",terminal:!0,flow:{uuid:e.uuid||e.value,name:e.name}}}},bp={ARS:{code:"ARS",name:"Argentine Peso"},AUD:{code:"AUD",name:"Australian Dollar"},BIF:{code:"BIF",name:"Burundi Franc"},BRL:{code:"BRL",name:"Brazilian Real"},CAD:{code:"CAD",name:"Canadian Dollar"},CDF:{code:"CDF",name:"Congolese Franc"},CLP:{code:"CLP",name:"Chilean Peso"},COP:{code:"COP",name:"Colombian Peso"},DJF:{code:"DJF",name:"Djibouti Franc"},DOP:{code:"DOP",name:"Dominican Peso"},DZD:{code:"DZD",name:"Algerian Dinar"},EUR:{code:"EUR",name:"Euro"},GBP:{code:"GBP",name:"Pound Sterling"},GHS:{code:"GHS",name:"Ghana Cedi"},GNF:{code:"GNF",name:"Guinean Franc"},KES:{code:"KES",name:"Kenyan Shilling"},LBP:{code:"LBP",name:"Lebanese Pound"},LKR:{code:"LKR",name:"Sri Lanka Rupee"},LRD:{code:"LRD",name:"Liberian Dollar"},MWK:{code:"MWK",name:"Malawian Kwacha"},MXN:{code:"MXN",name:"Mexican Peso"},MZN:{code:"MZN",name:"Mozambican Metical"},NAD:{code:"NAD",name:"Namibian Dollar"},NGN:{code:"NGN",name:"Nigerian Naira"},PEN:{code:"PEN",name:"Peruvian Sol"},PHP:{code:"PHP",name:"Philippine Peso"},RWF:{code:"RWF",name:"Rwandan Franc"},SZL:{code:"SZL",name:"Swazi Lilangeni"},TZS:{code:"TZS",name:"Tanzanian Shilling"},UGX:{code:"UGX",name:"Ugandan Shilling"},USD:{code:"USD",name:"US Dollar"},XAF:{code:"XAF",name:"Central African CFA Franc"},XOF:{code:"XOF",name:"West African CFA Franc"},ZAR:{code:"ZAR",name:"South African Rand"},ZMW:{code:"ZMW",name:"Zambian Kwacha"}},yp=Object.values(bp).map(t=>({value:t.code,name:`${t.name} (${t.code})`})),xp=[{type:"has_any_word",name:"has any of the words",operands:1},{type:"has_all_words",name:"has all of the words",operands:1},{type:"has_phrase",name:"has the phrase",operands:1},{type:"has_only_phrase",name:"has only the phrase",operands:1},{type:"has_beginning",name:"starts with",operands:1},{type:"has_text",name:"has some text",operands:0,categoryName:"Has Text"},{type:"has_number",name:"has a number",operands:0,categoryName:"Has Number"},{type:"has_number_between",name:"has a number between",operands:2},{type:"has_number_lt",name:"has a number below",operands:1},{type:"has_number_lte",name:"has a number at or below",operands:1},{type:"has_number_eq",name:"has a number equal to",operands:1},{type:"has_number_gte",name:"has a number at or above",operands:1},{type:"has_number_gt",name:"has a number above",operands:1},{type:"has_date",name:"has a date",operands:0,categoryName:"Has Date"},{type:"has_date_lt",name:"has a date before",operands:1},{type:"has_date_eq",name:"has a date equal to",operands:1},{type:"has_date_gt",name:"has a date after",operands:1},{type:"has_time",name:"has a time",operands:0,categoryName:"Has Time"},{type:"has_phone",name:"has a phone number",operands:0,categoryName:"Has Phone"},{type:"has_email",name:"has an email",operands:0,categoryName:"Has Email"},{type:"has_state",name:"has state",operands:0,categoryName:"Has State",filter:"locations"},{type:"has_district",name:"has district",operands:1,categoryName:"Has District",filter:"locations"},{type:"has_ward",name:"has ward",operands:2,categoryName:"Has Ward",filter:"locations"},{type:"has_group",name:"is in the group",operands:1,visibility:"hidden"},{type:"has_category",name:"has the category",operands:0,visibility:"hidden"},{type:"has_error",name:"has an error",operands:0,categoryName:"Has Error",visibility:"hidden"},{type:"has_value",name:"is not empty",operands:0,categoryName:"Not Empty",visibility:"hidden"},{type:"has_pattern",name:"matches regex",operands:1}],wp=t=>xp.filter(e=>"hidden"!==e.visibility&&(!e.filter||!!t&&t.includes(e.filter))),_p=new Set(["has_beginning","has_number","has_number_between","has_number_lt","has_number_lte","has_number_eq","has_number_gte","has_number_gt","has_pattern"]),kp=t=>xp.find(e=>e.type===t),Cp=t=>t.map(t=>({value:t.type,name:t.name})),Sp={type:"text",required:!1,maxLength:64,placeholder:"(optional)",helpText:"The name to use to reference this result in the flow"},Ap={type:"checkbox",label:"Require rules to be localized",helpText:"Each language must specify its own rules for this node"},Ep={type:"checkbox",label:"Require categories to be localized",helpText:t=>{var e;const i=null===(e=t.result_name)||void 0===e?void 0:e.trim();if(i){return`Only enable if you plan to use @results.${i.toLowerCase().replace(/\s+/g,"_")}.category_localized`}return"Only enable if you plan to use category_localized in your expressions for this result"},conditions:{visible:t=>!!t.result_name}},$p={label:"Save Result",localizable:!1,items:["result_name"],collapsed:t=>!(t._isNew&&t.result_name),getValueCount:t=>!!t.result_name},Tp={type:"accordion",multi:!0,sections:[$p,{label:"Localization",localizable:!1,items:["localizeRules","localizeCategories"],collapsed:!0,getValueCount:t=>!(!t.localizeRules&&!t.localizeCategories)}]},Dp={type:"accordion",multi:!0,sections:[$p]};function Mp(t,e){var i,o;const n=(null===(i=t.router)||void 0===i?void 0:i.categories)||[],s={};n.forEach(t=>{const i=t.uuid,o=e[i];s[i]={originalName:t.name,localizedName:o&&o.name?Array.isArray(o.name)?o.name[0]||"":o.name:""}});const r=(null===(o=t.router)||void 0===o?void 0:o.cases)||[],a={};return r.forEach(t=>{var i,o;if(!(null===(i=t.arguments)||void 0===i?void 0:i.length)||!t.arguments.some(t=>t))return;const n=e[t.uuid],s=(null===(o=kp(t.type))||void 0===o?void 0:o.name)||t.type;a[t.uuid]={operatorName:s,originalArguments:[...t.arguments],localizedArguments:(null==n?void 0:n.arguments)?[...n.arguments]:t.arguments.map(()=>"")}}),{categories:s,rules:a}}function zp(t,e){const i={};return t.categories&&Object.keys(t.categories).forEach(e=>{var o,n;const s=t.categories[e],r=(null===(o=s.localizedName)||void 0===o?void 0:o.trim())||"",a=(null===(n=s.originalName)||void 0===n?void 0:n.trim())||"";r&&r!==a&&(i[e]={name:[r]})}),t.rules&&Object.keys(t.rules).forEach(e=>{const o=t.rules[e],n=o.localizedArguments||[],s=o.originalArguments||[],r=n.some((t,e)=>(null==t?void 0:t.trim())&&t.trim()!==(s[e]||""));r&&(i[e]={arguments:n.map(t=>(null==t?void 0:t.trim())||"")})}),i}const Ip={type:"split_by_airtime",name:"Send Airtime",group:ju.services,flowTypes:[Bu,Nu,Fu],features:[Uu],showAsAction:!0,form:{amounts:{type:"array",label:"Airtime Amounts",helpText:"Define the currencies and amounts to transfer",required:!0,itemLabel:"Amount",sortable:!1,minItems:1,maxItems:10,isEmptyItem:t=>!t.currency||!t.amount||""===t.amount.trim(),itemConfig:{currency:{type:"select",placeholder:"Select a currency",required:!0,options:yp,searchable:!0,multi:!1,width:"200px"},amount:{type:"text",placeholder:"Amount",required:!0}}},result_name:Sp},layout:["amounts","result_name"],validate:t=>{const e={};if(t.amounts&&Array.isArray(t.amounts)){const i=t.amounts.filter(t=>(null==t?void 0:t.currency)&&(null==t?void 0:t.amount)&&""!==t.amount.trim());if(0===i.length)return e.amounts="At least one currency and amount is required",{valid:!1,errors:e};const o=new Set,n=[];i.forEach(t=>{var e;const i=Array.isArray(t.currency)&&t.currency.length>0?t.currency[0].value:"string"==typeof t.currency?t.currency:null===(e=t.currency)||void 0===e?void 0:e.value;o.has(i)?n.push(i):o.add(i)}),n.length>0&&(e.amounts=`Duplicate currencies found: ${n.join(", ")}`);for(const t of i){const i=t.amount.trim();if(isNaN(Number(i))||Number(i)<=0)return e.amounts="All amounts must be valid positive numbers",{valid:!1,errors:e}}}else e.amounts="At least one currency and amount is required";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=>"transfer_airtime"===t.type);if(!i||!i.amounts)return W`<div class="body">Configure airtime transfer</div>`;const o=i.amounts,n=Object.keys(o);if(0===n.length)return W`<div class="body">Configure airtime transfer</div>`;const s=n[0],r=o[s],a=n.length-1;return W`
8925
8925
  <div class="body">
8926
8926
  ${s}
8927
8927
  ${r}${a>0?W` <span style="color: #999;">+${a} more</span>`:""}
8928
8928
  </div>
8929
- `},toFormData:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"transfer_airtime"===t.type),n=[];return o&&o.amounts&&Object.entries(o.amounts).forEach(([t,e])=>{var i;n.push({currency:[{value:t,name:(null===(i=bp[t])||void 0===i?void 0:i.name)?`${bp[t].name} (${t})`:t}],amount:String(e)})}),{uuid:t.uuid,amounts:n,result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o,n;const s={};t.amounts&&Array.isArray(t.amounts)&&t.amounts.forEach(t=>{var e;if(!(null==t?void 0:t.currency)||!(null==t?void 0:t.amount)||""===t.amount.trim())return;let i;if(Array.isArray(t.currency)&&t.currency.length>0)i=t.currency[0].value;else if("string"==typeof t.currency)i=t.currency;else{if(!(null===(e=t.currency)||void 0===e?void 0:e.value))return;i=t.currency.value}const o=parseFloat(t.amount.trim());!isNaN(o)&&o>0&&(s[i]=o)});const r=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"transfer_airtime"===t.type),a={type:"transfer_airtime",uuid:(null==r?void 0:r.uuid)||Xt(),amounts:s},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._new_transfer",{type:"has_text",arguments:[]},l,d,c),p={...h};return t.result_name&&""!==t.result_name.trim()&&(p.result_name=t.result_name.trim()),{uuid:e.uuid,actions:[a],router:p,exits:u}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Lp=t=>{if("string"==typeof t)return t.trim();if(Array.isArray(t)&&t.length>0){const e=t[0];if(e&&"object"==typeof e&&e.value)return e.value.trim()}else if(t&&"object"==typeof t&&t.value)return t.value.trim();return""},Op=t=>{const e=Lp(t.operator);if(!e||!t.category||""===t.category.trim())return!0;const i=kp(e);return i&&1===i.operands?!t.value1||""===t.value1.trim():!(!i||2!==i.operands)&&(!t.value1||""===t.value1.trim()||!t.value2||""===t.value2.trim())},Pp=t=>{const e=Lp(t.operator),i=kp(e);return!i||i.operands>=1},Rp=t=>{const e=Lp(t.operator),i=kp(e);return!!i&&2===i.operands},Np=t=>{const e=Lp(t.operator);return"has_district"===e||"has_ward"===e?"State":""},Bp=t=>"has_ward"===Lp(t.operator)?"District":"",Fp=()=>({operator:{type:"select",required:!0,multi:!1,options:[],getDynamicOptions:()=>{const t=Sd.getState().features;return Cp(wp(t))},flavor:"xsmall",width:"220px"},value1:{type:"text",placeholder:Np,evaluated:!0,flavor:"xsmall",conditions:{visible:Pp}},value2:{type:"text",placeholder:Bp,evaluated:!0,flavor:"xsmall",conditions:{visible:Rp}},category:{type:"text",placeholder:"Category",required:!0,maxLength:36,maxWidth:"120px",flavor:"xsmall"}}),qp=t=>(t.rules||[]).filter(t=>{const e=Lp(null==t?void 0:t.operator);if(!e||!(null==t?void 0:t.category)||""===e||""===t.category.trim())return!1;const i=kp(e);return i&&1===i.operands?(null==t?void 0:t.value1)&&""!==t.value1.trim():!i||2!==i.operands||(null==t?void 0:t.value1)&&""!==t.value1.trim()&&(null==t?void 0:t.value2)&&""!==t.value2.trim()}).map(t=>{const e=Lp(t.operator),i=kp(e),o=t.value1?t.value1.trim():"",n=t.value2?t.value2.trim():"";let s="";return s=i&&1===i.operands?o:(i&&i.operands,""),{operator:e,value:s,value1:o,value2:n,category:t.category.trim()}}),Up=t=>{var e,i;const o=[];return(null===(e=t.router)||void 0===e?void 0:e.cases)&&(null===(i=t.router)||void 0===i?void 0:i.categories)&&t.router.cases.forEach(e=>{const i=t.router.categories.find(t=>t.uuid===e.category_uuid);if(i&&(n=i.name,!["No Response","Other","All Responses","Timeout"].includes(n))){const t=kp(e.type),n=t?t.name:e.type;let s="",r="";t&&0===t.operands?(s="",r=""):t&&1===t.operands?(s=e.arguments.join(" "),r=""):t&&2===t.operands?(s=e.arguments[0]||"",r=e.arguments[1]||""):(s=e.arguments.join(" "),r=""),o.push({operator:{value:e.type,name:n},value1:s,value2:r,category:i.name})}var n}),o};const jp=(t,e="Define rules to categorize responses")=>({type:"array",helpText:e,itemLabel:"Rule",minItems:0,maxItems:100,sortable:!0,maintainEmptyItem:!0,isEmptyItem:Op,onItemChange:(t,e,i,o)=>{const n=[...o],s={...n[t]};s[e]=i;const r=o[t]||{},a=Lp("operator"===e?r.operator:s.operator),l=Lp(s.operator),d=Le(a,kp,"value1"===e?r.value1:s.value1,"value2"===e?r.value2:s.value2),c=Le(l,kp,s.value1,s.value2);return(!s.category||""===s.category.trim()||s.category===d)&&c&&(s.category=c),n[t]=s,n},createEmptyItem:t=>{const e=Sd.getState().features,i=Cp(wp(e)),o=[...t].reverse().find(t=>{const e=Lp(t.operator),i=e?kp(e):void 0;return i&&i.operands>=1&&"locations"!==i.filter}),n=i.filter(t=>{const e=kp(t.value);return!e||"locations"!==e.filter}),s=o?Lp(o.operator):null,r=s?i.find(t=>t.value===s):n[0];return r?{operator:[{...r}]}:{}},itemConfig:{...Fp(),operator:{...Fp().operator,options:t}}}),Hp={name:{id:"name",name:"Name",type:"property"},language:{id:"language",name:"Language",type:"property"},status:{id:"status",name:"Status",type:"property"},channel:{id:"channel",name:"Channel",type:"property"}},Wp={type:"split_by_contact_field",name:"Split by Contact Field",group:Hu.split,flowTypes:[Bu,Nu,Fu],dialogSize:"large",form:{field:{type:"select",required:!0,searchable:!0,clearable:!1,endpoint:"/api/v2/fields.json",valueKey:"key",nameKey:"name",placeholder:"Select a field...",options:[...Object.values(Hp).map(t=>({value:t.id,name:t.name,type:t.type})),...Mu.filter(t=>!t.excludeFromSplit).map(t=>({value:t.scheme,name:t.path,type:"scheme"}))]},rules:jp(Cp(wp()),""),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:["field","rules",Tp],validate:t=>{const e={};return t.field&&0!==t.field.length||(e.field="A field is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:(t,e)=>{var i,o,n,s;const r={...(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.operand)||Hp.name};"field"===r.type?r.key||(r.key=r.id):r.value||(r.value=r.id);const a=Up(t);return{uuid:t.uuid,field:[r],rules:a,result_name:(null===(o=t.router)||void 0===o?void 0:o.result_name)||"",localizeRules:(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.localizeRules)||!1,localizeCategories:(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.localizeCategories)||!1}},fromFormData:(t,e)=>{var i,o,n;const s=null===(i=t.field)||void 0===i?void 0:i[0];if(!s)return e;const r=(t=>{if("scheme"===t.type)return`@(default(urn_parts(urns.${t.id||t.value}).path, ""))`;return"property"===t.type?`@contact.${t.id||t.value}`:`@fields.${t.key||t.id||t.value}`})(s),a=qp(t),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}=Oe(r,a,kp,l,d,c),p={...h};return t.result_name&&""!==t.result_name.trim()&&(p.result_name=t.result_name.trim()),{...e,router:p,exits:u}},toUIConfig:t=>{var e;const i=null===(e=t.field)||void 0===e?void 0:e[0];if(!i)return{};let o=i.id||i.value||i.key;"scheme"===i.type&&(o=i.value||i.id);let n=i.type;"property"!==n&&"scheme"!==n&&(n="field");const s={operand:{id:o,name:i.name||i.label,type:n}};return s.localizeRules=!!t.localizeRules,s.localizeCategories=!!t.result_name&&!!t.localizeCategories,s},renderTitle:(t,e)=>W`<div>Split by ${e.config.operand.name}</div>`,localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Vp={type:"split_by_expression",name:"Split by Expression",group:Hu.split,flowTypes:[Bu,Nu,Fu],dialogSize:"large",form:{operand:{type:"text",label:"Expression",helpText:"The expression to evaluate and split on",required:!0,evaluated:!0,placeholder:"@fields.age"},rules:jp(Cp(wp()),""),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:["operand","rules",Tp],validate:t=>{const e={};return t.operand&&""!==t.operand.trim()||(e.operand="Expression is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:(t,e)=>{var i,o,n,s;const r=Up(t);return{uuid:t.uuid,operand:(null===(i=t.router)||void 0===i?void 0:i.operand)||"@input.text",rules:r,result_name:(null===(o=t.router)||void 0===o?void 0:o.result_name)||"",localizeRules:(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.localizeRules)||!1,localizeCategories:(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.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;const s=qp(t),r=(null===(i=t.operand)||void 0===i?void 0:i.trim())||"@input.text",a=(null===(o=e.router)||void 0===o?void 0:o.categories)||[],l=e.exits||[],d=(null===(n=e.router)||void 0===n?void 0:n.cases)||[],{router:c,exits:h}=Oe(r,s,kp,a,l,d),u={...c};return t.result_name&&""!==t.result_name.trim()&&(u.result_name=t.result_name.trim()),{...e,router:u,exits:h}},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Zp={type:"split_by_groups",name:"Split by Group",group:Hu.split,flowTypes:[Bu,Nu,Fu],form:{groups:{type:"select",label:"Groups",helpText:"Select the groups to split contacts by. Contacts will be routed based on their group membership.",required:!0,options:[],multi:!0,searchable:!0,endpoint:"/api/v2/groups.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for groups...",allowCreate:!0,createArbitraryOption:(t,e)=>!e.find(e=>e.name.toLowerCase().trim()===t.toLowerCase().trim())&&t.trim()?{name:t.trim(),arbitrary:!0}:null},result_name:Sp},layout:["groups",Dp],validate:t=>{const e={};return t.groups&&Array.isArray(t.groups)&&0!==t.groups.length||(e.groups="At least one group is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:t=>{var e,i;const o=[];return(null===(e=t.router)||void 0===e?void 0:e.cases)&&t.router.cases.forEach(t=>{var e;"has_group"===t.type&&(null===(e=t.arguments)||void 0===e?void 0:e.length)>=2&&o.push({uuid:t.arguments[0],name:t.arguments[1]})}),{uuid:t.uuid,groups:o,result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o;const n=(t.groups||[]).filter(t=>(null==t?void 0:t.uuid)||(null==t?void 0:t.arbitrary)).map(t=>({uuid:t.uuid||Xt(),name:t.name})),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}=((t,e=[],i=[],o=[],n="")=>{const s=[],r=[],a=[];t.forEach(t=>{const n=e.find(e=>e.name===t.name),l=n?i.find(t=>t.uuid===n.exit_uuid):null,d=o.find(e=>{var i;return(null===(i=e.arguments)||void 0===i?void 0:i[0])===t.uuid}),c=(null==l?void 0:l.uuid)||Xt(),h=(null==n?void 0:n.uuid)||Xt(),u=(null==d?void 0:d.uuid)||Xt();s.push({uuid:h,name:t.name,exit_uuid:c}),r.push({uuid:c,destination_uuid:(null==l?void 0:l.destination_uuid)||null}),a.push({uuid:u,type:"has_group",arguments:[t.uuid,t.name],category_uuid:h})});const l=e.find(e=>"Other"===e.name&&!t.some(t=>t.name===e.name)),d=l?i.find(t=>t.uuid===l.exit_uuid):null,c=(null==d?void 0:d.uuid)||Xt(),h=(null==l?void 0:l.uuid)||Xt();return s.push({uuid:h,name:"Other",exit_uuid:c}),r.push({uuid:c,destination_uuid:(null==d?void 0:d.destination_uuid)||null}),{router:{type:"switch",cases:a,categories:s,default_category_uuid:h,operand:"@contact.groups",result_name:n},exits:r}})(n,s,r,a,t.result_name||"");return{uuid:e.uuid,actions:e.actions||[],router:l,exits:d}},router:{type:"switch",operand:"@contact.groups"},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Yp={type:"split_by_random",name:"Random Split",group:Hu.split,flowTypes:[Bu,Nu,Fu],form:{categories:{type:"array",helpText:"Define the buckets to randomly split contacts into",required:!0,itemLabel:"Bucket",sortable:!0,minItems:2,maxItems:10,isEmptyItem:t=>!t.name||""===t.name.trim(),itemConfig:{name:{type:"text",placeholder:"Bucket name",required:!0}}}},layout:["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());i.length<2&&(e.categories="At least 2 buckets are required for random split");const 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 bucket names found: ${t.join(", ")}`}}return{valid:0===Object.keys(e).length,errors:e}},toFormData:t=>{var e,i;const o=(null===(i=null===(e=t.router)||void 0===e?void 0:e.categories)||void 0===i?void 0:i.map(t=>({name:t.name})))||[];return{uuid:t.uuid,categories:o}},fromFormData:(t,e)=>{var i;const o=(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()),n=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],s=e.exits||[],{router:r,exits:a}=((t,e=[],i=[])=>{const o=[],n=[];return t.forEach(t=>{const s=e.find(e=>e.name===t),r=s?i.find(t=>t.uuid===s.exit_uuid):null,a=(null==r?void 0:r.uuid)||Xt(),l=(null==s?void 0:s.uuid)||Xt();o.push({uuid:l,name:t,exit_uuid:a}),n.push({uuid:a,destination_uuid:(null==r?void 0:r.destination_uuid)||null})}),{router:{type:"random",categories:o},exits:n}})(o,n,s);return{uuid:e.uuid,actions:e.actions||[],router:r,exits:a}},router:{type:"random"},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Kp=[{value:"0",name:"first result"},{value:"1",name:"second result"},{value:"2",name:"third result"},{value:"3",name:"fourth result"},{value:"4",name:"fifth result"},{value:"5",name:"sixth result"},{value:"6",name:"seventh result"},{value:"7",name:"eighth result"},{value:"8",name:"ninth result"},{value:"9",name:"tenth result"},{value:"10",name:"11th result"},{value:"11",name:"12th result"},{value:"12",name:"13th result"},{value:"13",name:"14th result"},{value:"14",name:"15th result"},{value:"15",name:"16th result"},{value:"16",name:"17th result"},{value:"17",name:"18th result"},{value:"18",name:"19th result"},{value:"19",name:"20th result"}],Gp=[{value:"",name:"Don't delimit result"},{value:" ",name:"Delimited by spaces"},{value:".",name:"Delimited by periods"},{value:"+",name:"Delimited by plusses"}],Xp={type:"split_by_run_result",name:"Split by Result",aliases:["split_by_run_result_delimited"],group:Hu.split,flowTypes:[Bu,Nu,Fu],dialogSize:"large",form:{result:{type:"select",required:!0,searchable:!1,clearable:!1,placeholder:"Select a result...",getDynamicOptions:()=>{const t=$d();return t?t.getState().getFlowResults().map(t=>({value:t.key,name:t.name})):[]},valueKey:"value",nameKey:"name"},delimit_by:{type:"select",required:!1,searchable:!1,clearable:!1,options:Gp,valueKey:"value",nameKey:"name",maxWidth:"180px"},delimit_index:{type:"select",required:!1,searchable:!1,clearable:!1,options:Kp,valueKey:"value",nameKey:"name",maxWidth:"140px",conditions:{visible:t=>{var e,i;const o=null===(i=null===(e=t.delimit_by)||void 0===e?void 0:e[0])||void 0===i?void 0:i.value;return void 0!==o&&""!==o}}},rules:jp(Cp(wp()),""),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:[{type:"row",label:"Flow Result",helpText:"Select a flow result and optionally delimit it to split on a specific part",items:["result","delimit_by","delimit_index"]},"rules",Tp],validate:t=>{const e={};return t.result&&0!==t.result.length||(e.result="A flow result is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:(t,e)=>{var i,o,n,s,r;const a=null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.operand,l=a?{...a,value:a.value||a.id}:null,d=Up(t),c=((null===(o=t.router)||void 0===o?void 0:o.operand)||"").match(/field\(results\.[\w]+,\s*(\d+),\s*"(.+?)"\)/),h=null!==c,u=h?parseInt(c[1],10):0,p=h?c[2]:"";return{uuid:t.uuid,result:l?[l]:[],delimit_by:h?[Gp.find(t=>t.value===p)]:[Gp[0]],delimit_index:h?[Kp.find(t=>t.value===String(u))]:[Kp[0]],rules:d,result_name:(null===(n=t.router)||void 0===n?void 0:n.result_name)||"",localizeRules:(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.localizeRules)||!1,localizeCategories:(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.localizeCategories)||!1}},fromFormData:(t,e)=>{var i,o,n,s,r,a,l,d;const c=null===(i=t.result)||void 0===i?void 0:i[0];if(!c)return e;let h;const u=c.value||c.id,p=null===(n=null===(o=t.delimit_by)||void 0===o?void 0:o[0])||void 0===n?void 0:n.value;if(void 0!==p&&""!==p){h=`@(field(results.${u}, ${null!==(a=null===(r=null===(s=t.delimit_index)||void 0===s?void 0:s[0])||void 0===r?void 0:r.value)&&void 0!==a?a:"0"}, "${p}"))`}else h=`@results.${u}`;const m=qp(t),g=(null===(l=e.router)||void 0===l?void 0:l.categories)||[],f=e.exits||[],v=(null===(d=e.router)||void 0===d?void 0:d.cases)||[],{router:b,exits:y}=Oe(h,m,kp,g,f,v),x={...b};return t.result_name&&""!==t.result_name.trim()&&(x.result_name=t.result_name.trim()),{...e,router:x,exits:y}},toUIConfig:t=>{var e,i,o,n,s,r;const a=null===(e=t.result)||void 0===e?void 0:e[0];if(!a)return{};const l={operand:{id:a.value,name:a.name,type:"result"}},d=null===(o=null===(i=t.delimit_by)||void 0===i?void 0:i[0])||void 0===o?void 0:o.value,c=void 0!==d&&""!==d;return c&&(l.index=parseInt(null!==(r=null===(s=null===(n=t.delimit_index)||void 0===n?void 0:n[0])||void 0===s?void 0:s.value)&&void 0!==r?r:"0",10),l.delimiter=d),l.type=c?"split_by_run_result_delimited":"split_by_run_result",l.localizeRules=!!t.localizeRules,l.localizeCategories=!!t.result_name&&!!t.localizeCategories,l},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Qp={type:"split_by_scheme",name:"Split by URN Type",group:Hu.split,flowTypes:[Bu,Nu,Fu],form:{schemes:{type:"select",label:"Channel Types",helpText:"The contact's URN is the address they used to reach you such as their phone number or a Facebook ID. Select which URN types to split by.",required:!0,options:Mu.map(t=>({value:t.scheme,name:t.name})),multi:!0,searchable:!0,placeholder:"Select the channels to split by..."},result_name:Sp},layout:["schemes",Dp],validate:t=>{const e={};return t.schemes&&Array.isArray(t.schemes)&&0!==t.schemes.length||(e.schemes="At least one channel type is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:t=>{var e,i;const o=[];return(null===(e=t.router)||void 0===e?void 0:e.cases)&&t.router.cases.forEach(t=>{var e;"has_only_phrase"===t.type&&(null===(e=t.arguments)||void 0===e?void 0:e.length)>0&&o.push(t.arguments[0])}),{uuid:t.uuid,schemes:o.map(t=>{const e=Mu.find(e=>e.scheme===t);return{value:t,name:(null==e?void 0:e.name)||t}}),result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o;const n=(t.schemes||[]).filter(t=>t).map(t=>"string"==typeof t?t:t.value),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}=((t,e=[],i=[],o=[],n="")=>{const s=[],r=[],a=[];t.forEach(t=>{const n=Mu.find(e=>e.scheme===t),l=(null==n?void 0:n.name)||t,d=e.find(t=>t.name===l),c=d?i.find(t=>t.uuid===d.exit_uuid):null,h=o.find(e=>{var i;return(null===(i=e.arguments)||void 0===i?void 0:i[0])===t}),u=(null==c?void 0:c.uuid)||Xt(),p=(null==d?void 0:d.uuid)||Xt(),m=(null==h?void 0:h.uuid)||Xt();s.push({uuid:p,name:l,exit_uuid:u}),r.push({uuid:u,destination_uuid:(null==c?void 0:c.destination_uuid)||null}),a.push({uuid:m,type:"has_only_phrase",arguments:[t],category_uuid:p})});const l=e.find(e=>{const i=t.some(t=>{const i=Mu.find(e=>e.scheme===t);return(null==i?void 0:i.name)===e.name});return"Other"===e.name&&!i}),d=l?i.find(t=>t.uuid===l.exit_uuid):null,c=(null==d?void 0:d.uuid)||Xt(),h=(null==l?void 0:l.uuid)||Xt();return s.push({uuid:h,name:"Other",exit_uuid:c}),r.push({uuid:c,destination_uuid:(null==d?void 0:d.destination_uuid)||null}),{router:{type:"switch",cases:a,categories:s,default_category_uuid:h,operand:"@(urn_parts(contact.urn).scheme)",result_name:n},exits:r}})(n,s,r,a,t.result_name||"");return{uuid:e.uuid,actions:e.actions||[],router:l,exits:d}},router:{type:"switch",operand:"@(urn_parts(contact.urn).scheme)"},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Jp={type:"split_by_subflow",name:"Enter a Flow",group:ju.trigger,flowTypes:[Bu,Nu,Fu],showAsAction:!0,form:{flow:{type:"select",required:!0,searchable:!0,placeholder:"Select a flow...",helpText:"Once the subflow is complete or expires, the contact will return here",endpoint:"/api/v2/flows.json",valueKey:"uuid",nameKey:"name",shouldExclude:fp},params:{type:"key-value",keyPlaceholder:"Parameter name",valuePlaceholder:"Value",minRows:0,readOnlyKeys:!0,dependsOn:["flow"],conditions:{visible:t=>{const e=t.params;return Array.isArray(e)?e.length>0:!(!e||"object"!=typeof e)&&Object.keys(e).length>0}},computeValue:(t,e)=>{var i;const o=Array.isArray(t.flow)&&t.flow.length>0?t.flow[0]:null;if(!(null===(i=null==o?void 0:o.parent_refs)||void 0===i?void 0:i.length))return[];const n={};return Array.isArray(e)?e.forEach(t=>{t.key&&(n[t.key]=t.value||"")}):e&&"object"==typeof e&&Object.entries(e).forEach(([t,e])=>{n[t]="string"==typeof e?e:""}),o.parent_refs.map(t=>({key:t,value:n[t]||""}))}}},layout:["flow",{type:"accordion",sections:[{label:"Parameters",collapsed:!1,getValueCount:t=>{const e=t.params;return Array.isArray(e)?e.filter(t=>t.value&&""!==t.value.trim()).length:e&&"object"==typeof e?Object.values(e).filter(t=>"string"==typeof t&&""!==t.trim()).length:0},items:["params"]}]}],resolveFormData:async t=>{var e;const i=Array.isArray(t.flow)&&t.flow.length>0?t.flow[0]:null;if(!(null==i?void 0:i.uuid))return t;if(i.parent_refs)return t;try{const o=await fetch(`/api/v2/flows.json?uuid=${i.uuid}`),n=null===(e=(await o.json()).results)||void 0===e?void 0:e[0];if(null==n?void 0:n.parent_refs){const e={...i,parent_refs:n.parent_refs};return{...t,flow:[e]}}}catch(t){}return t},render:t=>{var e;const i=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"enter_flow"===t.type);return W`
8929
+ `},toFormData:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"transfer_airtime"===t.type),n=[];return o&&o.amounts&&Object.entries(o.amounts).forEach(([t,e])=>{var i;n.push({currency:[{value:t,name:(null===(i=bp[t])||void 0===i?void 0:i.name)?`${bp[t].name} (${t})`:t}],amount:String(e)})}),{uuid:t.uuid,amounts:n,result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o,n;const s={};t.amounts&&Array.isArray(t.amounts)&&t.amounts.forEach(t=>{var e;if(!(null==t?void 0:t.currency)||!(null==t?void 0:t.amount)||""===t.amount.trim())return;let i;if(Array.isArray(t.currency)&&t.currency.length>0)i=t.currency[0].value;else if("string"==typeof t.currency)i=t.currency;else{if(!(null===(e=t.currency)||void 0===e?void 0:e.value))return;i=t.currency.value}const o=parseFloat(t.amount.trim());!isNaN(o)&&o>0&&(s[i]=o)});const r=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"transfer_airtime"===t.type),a={type:"transfer_airtime",uuid:(null==r?void 0:r.uuid)||Xt(),amounts:s},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._new_transfer",{type:"has_text",arguments:[]},l,d,c),p={...h};return t.result_name&&""!==t.result_name.trim()&&(p.result_name=t.result_name.trim()),{uuid:e.uuid,actions:[a],router:p,exits:u}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Lp=t=>{if("string"==typeof t)return t.trim();if(Array.isArray(t)&&t.length>0){const e=t[0];if(e&&"object"==typeof e&&e.value)return e.value.trim()}else if(t&&"object"==typeof t&&t.value)return t.value.trim();return""},Op=t=>{const e=Lp(t.operator);if(!e||!t.category||""===t.category.trim())return!0;const i=kp(e);return i&&1===i.operands?!t.value1||""===t.value1.trim():!(!i||2!==i.operands)&&(!t.value1||""===t.value1.trim()||!t.value2||""===t.value2.trim())},Pp=t=>{const e=Lp(t.operator),i=kp(e);return!i||i.operands>=1},Rp=t=>{const e=Lp(t.operator),i=kp(e);return!!i&&2===i.operands},Np=t=>{const e=Lp(t.operator);return"has_district"===e||"has_ward"===e?"State":""},Bp=t=>"has_ward"===Lp(t.operator)?"District":"",Fp=()=>({operator:{type:"select",required:!0,multi:!1,options:[],getDynamicOptions:()=>{const t=Sd.getState().features;return Cp(wp(t))},flavor:"xsmall",width:"220px"},value1:{type:"text",placeholder:Np,evaluated:!0,flavor:"xsmall",conditions:{visible:Pp}},value2:{type:"text",placeholder:Bp,evaluated:!0,flavor:"xsmall",conditions:{visible:Rp}},category:{type:"text",placeholder:"Category",required:!0,maxLength:36,maxWidth:"120px",flavor:"xsmall"}}),qp=t=>(t.rules||[]).filter(t=>{const e=Lp(null==t?void 0:t.operator);if(!e||!(null==t?void 0:t.category)||""===e||""===t.category.trim())return!1;const i=kp(e);return i&&1===i.operands?(null==t?void 0:t.value1)&&""!==t.value1.trim():!i||2!==i.operands||(null==t?void 0:t.value1)&&""!==t.value1.trim()&&(null==t?void 0:t.value2)&&""!==t.value2.trim()}).map(t=>{const e=Lp(t.operator),i=kp(e),o=t.value1?t.value1.trim():"",n=t.value2?t.value2.trim():"";let s="";return s=i&&1===i.operands?o:(i&&i.operands,""),{operator:e,value:s,value1:o,value2:n,category:t.category.trim()}}),Up=t=>{var e,i;const o=[];return(null===(e=t.router)||void 0===e?void 0:e.cases)&&(null===(i=t.router)||void 0===i?void 0:i.categories)&&t.router.cases.forEach(e=>{const i=t.router.categories.find(t=>t.uuid===e.category_uuid);if(i&&(n=i.name,!["No Response","Other","All Responses","Timeout"].includes(n))){const t=kp(e.type),n=t?t.name:e.type;let s="",r="";t&&0===t.operands?(s="",r=""):t&&1===t.operands?(s=e.arguments.join(" "),r=""):t&&2===t.operands?(s=e.arguments[0]||"",r=e.arguments[1]||""):(s=e.arguments.join(" "),r=""),o.push({operator:{value:e.type,name:n},value1:s,value2:r,category:i.name})}var n}),o};const jp=(t,e="Define rules to categorize responses")=>({type:"array",helpText:e,itemLabel:"Rule",minItems:0,maxItems:100,sortable:!0,maintainEmptyItem:!0,isEmptyItem:Op,onItemChange:(t,e,i,o)=>{const n=[...o],s={...n[t]};s[e]=i;const r=o[t]||{},a=Lp("operator"===e?r.operator:s.operator),l=Lp(s.operator),d=Le(a,kp,"value1"===e?r.value1:s.value1,"value2"===e?r.value2:s.value2),c=Le(l,kp,s.value1,s.value2);return(!s.category||""===s.category.trim()||s.category===d)&&c&&(s.category=c),n[t]=s,n},createEmptyItem:t=>{const e=Sd.getState().features,i=Cp(wp(e)),o=[...t].reverse().find(t=>{const e=Lp(t.operator),i=e?kp(e):void 0;return i&&i.operands>=1&&"locations"!==i.filter}),n=i.filter(t=>{const e=kp(t.value);return!e||"locations"!==e.filter}),s=o?Lp(o.operator):null,r=s?i.find(t=>t.value===s):n[0];return r?{operator:[{...r}]}:{}},itemConfig:{...Fp(),operator:{...Fp().operator,options:t}}}),Hp={name:{id:"name",name:"Name",type:"property"},language:{id:"language",name:"Language",type:"property"},status:{id:"status",name:"Status",type:"property"},channel:{id:"channel",name:"Channel",type:"property"}},Wp={type:"split_by_contact_field",name:"Split by Contact Field",group:Hu.split,flowTypes:[Bu,Nu,Fu],dialogSize:"large",form:{field:{type:"select",required:!0,searchable:!0,clearable:!1,endpoint:"/api/v2/fields.json",valueKey:"key",nameKey:"name",placeholder:"Select a field...",options:[...Object.values(Hp).map(t=>({value:t.id,name:t.name,type:t.type})),...yc.filter(t=>!t.excludeFromSplit).map(t=>({value:t.scheme,name:t.path,type:"scheme"}))]},rules:jp(Cp(wp()),""),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:["field","rules",Tp],validate:t=>{const e={};return t.field&&0!==t.field.length||(e.field="A field is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:(t,e)=>{var i,o,n,s;const r={...(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.operand)||Hp.name};"field"===r.type?r.key||(r.key=r.id):r.value||(r.value=r.id);const a=Up(t);return{uuid:t.uuid,field:[r],rules:a,result_name:(null===(o=t.router)||void 0===o?void 0:o.result_name)||"",localizeRules:(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.localizeRules)||!1,localizeCategories:(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.localizeCategories)||!1}},fromFormData:(t,e)=>{var i,o,n;const s=null===(i=t.field)||void 0===i?void 0:i[0];if(!s)return e;const r=(t=>{if("scheme"===t.type)return`@(default(urn_parts(urns.${t.id||t.value}).path, ""))`;return"property"===t.type?`@contact.${t.id||t.value}`:`@fields.${t.key||t.id||t.value}`})(s),a=qp(t),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}=Oe(r,a,kp,l,d,c),p={...h};return t.result_name&&""!==t.result_name.trim()&&(p.result_name=t.result_name.trim()),{...e,router:p,exits:u}},toUIConfig:t=>{var e;const i=null===(e=t.field)||void 0===e?void 0:e[0];if(!i)return{};let o=i.id||i.value||i.key;"scheme"===i.type&&(o=i.value||i.id);let n=i.type;"property"!==n&&"scheme"!==n&&(n="field");const s={operand:{id:o,name:i.name||i.label,type:n}};return s.localizeRules=!!t.localizeRules,s.localizeCategories=!!t.result_name&&!!t.localizeCategories,s},renderTitle:(t,e)=>W`<div>Split by ${e.config.operand.name}</div>`,localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Vp={type:"split_by_expression",name:"Split by Expression",group:Hu.split,flowTypes:[Bu,Nu,Fu],dialogSize:"large",form:{operand:{type:"text",label:"Expression",helpText:"The expression to evaluate and split on",required:!0,evaluated:!0,placeholder:"@fields.age"},rules:jp(Cp(wp()),""),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:["operand","rules",Tp],validate:t=>{const e={};return t.operand&&""!==t.operand.trim()||(e.operand="Expression is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:(t,e)=>{var i,o,n,s;const r=Up(t);return{uuid:t.uuid,operand:(null===(i=t.router)||void 0===i?void 0:i.operand)||"@input.text",rules:r,result_name:(null===(o=t.router)||void 0===o?void 0:o.result_name)||"",localizeRules:(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.localizeRules)||!1,localizeCategories:(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.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;const s=qp(t),r=(null===(i=t.operand)||void 0===i?void 0:i.trim())||"@input.text",a=(null===(o=e.router)||void 0===o?void 0:o.categories)||[],l=e.exits||[],d=(null===(n=e.router)||void 0===n?void 0:n.cases)||[],{router:c,exits:h}=Oe(r,s,kp,a,l,d),u={...c};return t.result_name&&""!==t.result_name.trim()&&(u.result_name=t.result_name.trim()),{...e,router:u,exits:h}},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Zp={type:"split_by_groups",name:"Split by Group",group:Hu.split,flowTypes:[Bu,Nu,Fu],form:{groups:{type:"select",label:"Groups",helpText:"Select the groups to split contacts by. Contacts will be routed based on their group membership.",required:!0,options:[],multi:!0,searchable:!0,endpoint:"/api/v2/groups.json",valueKey:"uuid",nameKey:"name",placeholder:"Search for groups...",allowCreate:!0,createArbitraryOption:(t,e)=>!e.find(e=>e.name.toLowerCase().trim()===t.toLowerCase().trim())&&t.trim()?{name:t.trim(),arbitrary:!0}:null},result_name:Sp},layout:["groups",Dp],validate:t=>{const e={};return t.groups&&Array.isArray(t.groups)&&0!==t.groups.length||(e.groups="At least one group is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:t=>{var e,i;const o=[];return(null===(e=t.router)||void 0===e?void 0:e.cases)&&t.router.cases.forEach(t=>{var e;"has_group"===t.type&&(null===(e=t.arguments)||void 0===e?void 0:e.length)>=2&&o.push({uuid:t.arguments[0],name:t.arguments[1]})}),{uuid:t.uuid,groups:o,result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o;const n=(t.groups||[]).filter(t=>(null==t?void 0:t.uuid)||(null==t?void 0:t.arbitrary)).map(t=>({uuid:t.uuid||Xt(),name:t.name})),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}=((t,e=[],i=[],o=[],n="")=>{const s=[],r=[],a=[];t.forEach(t=>{const n=e.find(e=>e.name===t.name),l=n?i.find(t=>t.uuid===n.exit_uuid):null,d=o.find(e=>{var i;return(null===(i=e.arguments)||void 0===i?void 0:i[0])===t.uuid}),c=(null==l?void 0:l.uuid)||Xt(),h=(null==n?void 0:n.uuid)||Xt(),u=(null==d?void 0:d.uuid)||Xt();s.push({uuid:h,name:t.name,exit_uuid:c}),r.push({uuid:c,destination_uuid:(null==l?void 0:l.destination_uuid)||null}),a.push({uuid:u,type:"has_group",arguments:[t.uuid,t.name],category_uuid:h})});const l=e.find(e=>"Other"===e.name&&!t.some(t=>t.name===e.name)),d=l?i.find(t=>t.uuid===l.exit_uuid):null,c=(null==d?void 0:d.uuid)||Xt(),h=(null==l?void 0:l.uuid)||Xt();return s.push({uuid:h,name:"Other",exit_uuid:c}),r.push({uuid:c,destination_uuid:(null==d?void 0:d.destination_uuid)||null}),{router:{type:"switch",cases:a,categories:s,default_category_uuid:h,operand:"@contact.groups",result_name:n},exits:r}})(n,s,r,a,t.result_name||"");return{uuid:e.uuid,actions:e.actions||[],router:l,exits:d}},router:{type:"switch",operand:"@contact.groups"},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Yp={type:"split_by_random",name:"Random Split",group:Hu.split,flowTypes:[Bu,Nu,Fu],form:{categories:{type:"array",helpText:"Define the buckets to randomly split contacts into",required:!0,itemLabel:"Bucket",sortable:!0,minItems:2,maxItems:10,isEmptyItem:t=>!t.name||""===t.name.trim(),itemConfig:{name:{type:"text",placeholder:"Bucket name",required:!0}}}},layout:["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());i.length<2&&(e.categories="At least 2 buckets are required for random split");const 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 bucket names found: ${t.join(", ")}`}}return{valid:0===Object.keys(e).length,errors:e}},toFormData:t=>{var e,i;const o=(null===(i=null===(e=t.router)||void 0===e?void 0:e.categories)||void 0===i?void 0:i.map(t=>({name:t.name})))||[];return{uuid:t.uuid,categories:o}},fromFormData:(t,e)=>{var i;const o=(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()),n=(null===(i=e.router)||void 0===i?void 0:i.categories)||[],s=e.exits||[],{router:r,exits:a}=((t,e=[],i=[])=>{const o=[],n=[];return t.forEach(t=>{const s=e.find(e=>e.name===t),r=s?i.find(t=>t.uuid===s.exit_uuid):null,a=(null==r?void 0:r.uuid)||Xt(),l=(null==s?void 0:s.uuid)||Xt();o.push({uuid:l,name:t,exit_uuid:a}),n.push({uuid:a,destination_uuid:(null==r?void 0:r.destination_uuid)||null})}),{router:{type:"random",categories:o},exits:n}})(o,n,s);return{uuid:e.uuid,actions:e.actions||[],router:r,exits:a}},router:{type:"random"},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Kp=[{value:"0",name:"first result"},{value:"1",name:"second result"},{value:"2",name:"third result"},{value:"3",name:"fourth result"},{value:"4",name:"fifth result"},{value:"5",name:"sixth result"},{value:"6",name:"seventh result"},{value:"7",name:"eighth result"},{value:"8",name:"ninth result"},{value:"9",name:"tenth result"},{value:"10",name:"11th result"},{value:"11",name:"12th result"},{value:"12",name:"13th result"},{value:"13",name:"14th result"},{value:"14",name:"15th result"},{value:"15",name:"16th result"},{value:"16",name:"17th result"},{value:"17",name:"18th result"},{value:"18",name:"19th result"},{value:"19",name:"20th result"}],Gp=[{value:"",name:"Don't delimit result"},{value:" ",name:"Delimited by spaces"},{value:".",name:"Delimited by periods"},{value:"+",name:"Delimited by plusses"}],Xp={type:"split_by_run_result",name:"Split by Result",aliases:["split_by_run_result_delimited"],group:Hu.split,flowTypes:[Bu,Nu,Fu],dialogSize:"large",form:{result:{type:"select",required:!0,searchable:!1,clearable:!1,placeholder:"Select a result...",getDynamicOptions:()=>{const t=Ec();return t?t.getState().getFlowResults().map(t=>({value:t.key,name:t.name})):[]},valueKey:"value",nameKey:"name"},delimit_by:{type:"select",required:!1,searchable:!1,clearable:!1,options:Gp,valueKey:"value",nameKey:"name",maxWidth:"180px"},delimit_index:{type:"select",required:!1,searchable:!1,clearable:!1,options:Kp,valueKey:"value",nameKey:"name",maxWidth:"140px",conditions:{visible:t=>{var e,i;const o=null===(i=null===(e=t.delimit_by)||void 0===e?void 0:e[0])||void 0===i?void 0:i.value;return void 0!==o&&""!==o}}},rules:jp(Cp(wp()),""),result_name:Sp,localizeRules:Ap,localizeCategories:Ep},layout:[{type:"row",label:"Flow Result",helpText:"Select a flow result and optionally delimit it to split on a specific part",items:["result","delimit_by","delimit_index"]},"rules",Tp],validate:t=>{const e={};return t.result&&0!==t.result.length||(e.result="A flow result is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:(t,e)=>{var i,o,n,s,r;const a=null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.operand,l=a?{...a,value:a.value||a.id}:null,d=Up(t),c=((null===(o=t.router)||void 0===o?void 0:o.operand)||"").match(/field\(results\.[\w]+,\s*(\d+),\s*"(.+?)"\)/),h=null!==c,u=h?parseInt(c[1],10):0,p=h?c[2]:"";return{uuid:t.uuid,result:l?[l]:[],delimit_by:h?[Gp.find(t=>t.value===p)]:[Gp[0]],delimit_index:h?[Kp.find(t=>t.value===String(u))]:[Kp[0]],rules:d,result_name:(null===(n=t.router)||void 0===n?void 0:n.result_name)||"",localizeRules:(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.localizeRules)||!1,localizeCategories:(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.localizeCategories)||!1}},fromFormData:(t,e)=>{var i,o,n,s,r,a,l,d;const c=null===(i=t.result)||void 0===i?void 0:i[0];if(!c)return e;let h;const u=c.value||c.id,p=null===(n=null===(o=t.delimit_by)||void 0===o?void 0:o[0])||void 0===n?void 0:n.value;if(void 0!==p&&""!==p){h=`@(field(results.${u}, ${null!==(a=null===(r=null===(s=t.delimit_index)||void 0===s?void 0:s[0])||void 0===r?void 0:r.value)&&void 0!==a?a:"0"}, "${p}"))`}else h=`@results.${u}`;const m=qp(t),g=(null===(l=e.router)||void 0===l?void 0:l.categories)||[],f=e.exits||[],v=(null===(d=e.router)||void 0===d?void 0:d.cases)||[],{router:b,exits:y}=Oe(h,m,kp,g,f,v),x={...b};return t.result_name&&""!==t.result_name.trim()&&(x.result_name=t.result_name.trim()),{...e,router:x,exits:y}},toUIConfig:t=>{var e,i,o,n,s,r;const a=null===(e=t.result)||void 0===e?void 0:e[0];if(!a)return{};const l={operand:{id:a.value,name:a.name,type:"result"}},d=null===(o=null===(i=t.delimit_by)||void 0===i?void 0:i[0])||void 0===o?void 0:o.value,c=void 0!==d&&""!==d;return c&&(l.index=parseInt(null!==(r=null===(s=null===(n=t.delimit_index)||void 0===n?void 0:n[0])||void 0===s?void 0:s.value)&&void 0!==r?r:"0",10),l.delimiter=d),l.type=c?"split_by_run_result_delimited":"split_by_run_result",l.localizeRules=!!t.localizeRules,l.localizeCategories=!!t.result_name&&!!t.localizeCategories,l},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Qp={type:"split_by_scheme",name:"Split by URN Type",group:Hu.split,flowTypes:[Bu,Nu,Fu],form:{schemes:{type:"select",label:"Channel Types",helpText:"The contact's URN is the address they used to reach you such as their phone number or a Facebook ID. Select which URN types to split by.",required:!0,options:yc.map(t=>({value:t.scheme,name:t.name})),multi:!0,searchable:!0,placeholder:"Select the channels to split by..."},result_name:Sp},layout:["schemes",Dp],validate:t=>{const e={};return t.schemes&&Array.isArray(t.schemes)&&0!==t.schemes.length||(e.schemes="At least one channel type is required"),{valid:0===Object.keys(e).length,errors:e}},toFormData:t=>{var e,i;const o=[];return(null===(e=t.router)||void 0===e?void 0:e.cases)&&t.router.cases.forEach(t=>{var e;"has_only_phrase"===t.type&&(null===(e=t.arguments)||void 0===e?void 0:e.length)>0&&o.push(t.arguments[0])}),{uuid:t.uuid,schemes:o.map(t=>{const e=yc.find(e=>e.scheme===t);return{value:t,name:(null==e?void 0:e.name)||t}}),result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o;const n=(t.schemes||[]).filter(t=>t).map(t=>"string"==typeof t?t:t.value),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}=((t,e=[],i=[],o=[],n="")=>{const s=[],r=[],a=[];t.forEach(t=>{const n=yc.find(e=>e.scheme===t),l=(null==n?void 0:n.name)||t,d=e.find(t=>t.name===l),c=d?i.find(t=>t.uuid===d.exit_uuid):null,h=o.find(e=>{var i;return(null===(i=e.arguments)||void 0===i?void 0:i[0])===t}),u=(null==c?void 0:c.uuid)||Xt(),p=(null==d?void 0:d.uuid)||Xt(),m=(null==h?void 0:h.uuid)||Xt();s.push({uuid:p,name:l,exit_uuid:u}),r.push({uuid:u,destination_uuid:(null==c?void 0:c.destination_uuid)||null}),a.push({uuid:m,type:"has_only_phrase",arguments:[t],category_uuid:p})});const l=e.find(e=>{const i=t.some(t=>{const i=yc.find(e=>e.scheme===t);return(null==i?void 0:i.name)===e.name});return"Other"===e.name&&!i}),d=l?i.find(t=>t.uuid===l.exit_uuid):null,c=(null==d?void 0:d.uuid)||Xt(),h=(null==l?void 0:l.uuid)||Xt();return s.push({uuid:h,name:"Other",exit_uuid:c}),r.push({uuid:c,destination_uuid:(null==d?void 0:d.destination_uuid)||null}),{router:{type:"switch",cases:a,categories:s,default_category_uuid:h,operand:"@(urn_parts(contact.urn).scheme)",result_name:n},exits:r}})(n,s,r,a,t.result_name||"");return{uuid:e.uuid,actions:e.actions||[],router:l,exits:d}},router:{type:"switch",operand:"@(urn_parts(contact.urn).scheme)"},localizable:"categories",toLocalizationFormData:Mp,fromLocalizationFormData:zp},Jp={type:"split_by_subflow",name:"Enter a Flow",group:ju.trigger,flowTypes:[Bu,Nu,Fu],showAsAction:!0,form:{flow:{type:"select",required:!0,searchable:!0,placeholder:"Select a flow...",helpText:"Once the subflow is complete or expires, the contact will return here",endpoint:"/api/v2/flows.json",valueKey:"uuid",nameKey:"name",shouldExclude:fp},params:{type:"key-value",keyPlaceholder:"Parameter name",valuePlaceholder:"Value",minRows:0,readOnlyKeys:!0,dependsOn:["flow"],conditions:{visible:t=>{const e=t.params;return Array.isArray(e)?e.length>0:!(!e||"object"!=typeof e)&&Object.keys(e).length>0}},computeValue:(t,e)=>{var i;const o=Array.isArray(t.flow)&&t.flow.length>0?t.flow[0]:null;if(!(null===(i=null==o?void 0:o.parent_refs)||void 0===i?void 0:i.length))return[];const n={};return Array.isArray(e)?e.forEach(t=>{t.key&&(n[t.key]=t.value||"")}):e&&"object"==typeof e&&Object.entries(e).forEach(([t,e])=>{n[t]="string"==typeof e?e:""}),o.parent_refs.map(t=>({key:t,value:n[t]||""}))}}},layout:["flow",{type:"accordion",sections:[{label:"Parameters",collapsed:!1,getValueCount:t=>{const e=t.params;return Array.isArray(e)?e.filter(t=>t.value&&""!==t.value.trim()).length:e&&"object"==typeof e?Object.values(e).filter(t=>"string"==typeof t&&""!==t.trim()).length:0},items:["params"]}]}],resolveFormData:async t=>{var e;const i=Array.isArray(t.flow)&&t.flow.length>0?t.flow[0]:null;if(!(null==i?void 0:i.uuid))return t;if(i.parent_refs)return t;try{const o=await fetch(`/api/v2/flows.json?uuid=${i.uuid}`),n=null===(e=(await o.json()).results)||void 0===e?void 0:e[0];if(null==n?void 0:n.parent_refs){const e={...i,parent_refs:n.parent_refs};return{...t,flow:[e]}}}catch(t){}return t},render:t=>{var e;const i=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"enter_flow"===t.type);return W`
8930
8930
  <div class="body">
8931
- ${(null==i?void 0:i.flow)?Tu([i.flow],"flow"):null}
8931
+ ${(null==i?void 0:i.flow)?vc([i.flow],"flow"):null}
8932
8932
  </div>
8933
8933
  `},toFormData:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"enter_flow"===t.type),n={};return null===(i=t.actions)||void 0===i||i.filter(t=>"set_run_result"===t.type).forEach(t=>{const e=t;n[e.name]=e.value}),{uuid:t.uuid,flow:(null==o?void 0:o.flow)?[{uuid:o.flow.uuid,name:o.flow.name}]:[],params:n}},fromFormData:(t,e)=>{var i,o,n;const s=Array.isArray(t.flow)&&t.flow.length>0?t.flow[0]:null,r=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"enter_flow"===t.type),a={type:"enter_flow",uuid:(null==r?void 0:r.uuid)||Xt(),flow:s?{uuid:s.uuid||s.value,name:s.name}:{uuid:"",name:""}},l=[],d=t.params||{};Object.entries(d).forEach(([t,e])=>{"string"==typeof e&&""!==e.trim()&&l.push({type:"set_run_result",uuid:Xt(),name:t,value:e,category:""})}),l.push(a);const c=(null===(o=e.router)||void 0===o?void 0:o.categories)||[],h=e.exits||[],u=(null===(n=e.router)||void 0===n?void 0:n.cases)||[],p=c.find(t=>"Complete"===t.name),m=p?h.find(t=>t.uuid===p.exit_uuid):null,g=p?u.find(t=>t.category_uuid===p.uuid):null,f=(null==p?void 0:p.uuid)||Xt(),v=(null==m?void 0:m.uuid)||Xt(),b=(null==g?void 0:g.uuid)||Xt(),y=c.find(t=>"Expired"===t.name),x=y?h.find(t=>t.uuid===y.exit_uuid):null,w=(null==y?void 0:y.uuid)||Xt(),_=(null==x?void 0:x.uuid)||Xt(),k=[{uuid:f,name:"Complete",exit_uuid:v},{uuid:w,name:"Expired",exit_uuid:_}],C=[{uuid:v,destination_uuid:(null==m?void 0:m.destination_uuid)||null},{uuid:_,destination_uuid:(null==x?void 0:x.destination_uuid)||null}],S={type:"switch",categories:k,default_category_uuid:w,operand:"@child.status",cases:[{uuid:b,type:"has_only_text",arguments:["completed"],category_uuid:f}]};return{uuid:e.uuid,actions:l,router:S,exits:C}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},tm={type:"split_by_ticket",name:"Open Ticket",group:ju.trigger,flowTypes:[Bu,Nu,Fu],showAsAction:!0,form:{topic:{type:"select",label:"Topic",required:!0,placeholder:"Select a topic",options:[],endpoint:"/api/v2/topics.json",valueKey:"uuid",nameKey:"name",maxWidth:"200px"},assignee:{type:"select",label:"Assignee",required:!1,placeholder:"Select an agent (optional)",endpoint:"/api/v2/users.json",valueKey:"uuid",getName:t=>t.name||[t.first_name,t.last_name].join(" "),clearable:!0},note:{type:"textarea",label:"Note",required:!1,placeholder:"Enter a note for the ticket (optional)",minHeight:100}},layout:[{type:"row",items:["topic","assignee"]},"note"],render:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"open_ticket"===t.type);return W`
8934
8934
  <div class="body">
8935
8935
  ${(null===(i=null==o?void 0:o.topic)||void 0===i?void 0:i.name)||"Configure ticket"}
8936
8936
  </div>
8937
8937
  `},toFormData:t=>{var e;const i=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"open_ticket"===t.type);return{uuid:t.uuid,topic:(null==i?void 0:i.topic)?[{uuid:i.topic.uuid,name:i.topic.name}]:[],assignee:(null==i?void 0:i.assignee)?[{uuid:i.assignee.uuid,name:i.assignee.name}]:[],note:(null==i?void 0:i.note)||""}},fromFormData:(t,e)=>{var i,o,n;const s=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"open_ticket"===t.type),r={type:"open_ticket",uuid:(null==s?void 0:s.uuid)||Xt(),topic:t.topic&&t.topic.length>0?{uuid:t.topic[0].uuid,name:t.topic[0].name}:void 0,assignee:t.assignee&&t.assignee.length>0?{uuid:t.assignee[0].uuid,name:t.assignee[0].name||[t.assignee[0].first_name,t.assignee[0].last_name].join(" ")}:void 0,note:t.note||""},a=(null===(o=e.router)||void 0===o?void 0:o.categories)||[],l=e.exits||[],d=(null===(n=e.router)||void 0===n?void 0:n.cases)||[],{router:c,exits:h}=Me("@locals._new_ticket",{type:"has_text",arguments:[]},a,l,d);return{uuid:e.uuid,actions:[r],router:c,exits:h}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},em=[{key:"Accept",value:"application/json"}],im=[{key:"Accept",value:"application/json"},{key:"Content-Type",value:"application/json"}];const om='@(json(object(\n "contact", object(\n "uuid", contact.uuid, \n "name", contact.name, \n "urn", contact.urn\n ),\n "flow", object(\n "uuid", run.flow.uuid, \n "name", run.flow.name\n ),\n "results", foreach_value(results, extract_object, "value", "category")\n)))',nm={type:"split_by_webhook",name:"Call Webhook",group:ju.services,flowTypes:[Bu,Nu,Fu],showAsAction:!0,form:{method:{type:"select",required:!0,options:["GET","POST","PUT","DELETE","HEAD","PATCH"],maxWidth:"120px",searchable:!1},url:{type:"text",required:!0,evaluated:!0,placeholder:"https://example.com/webhook"},headers:{type:"key-value",sortable:!0,keyPlaceholder:"Header name",valuePlaceholder:"Header value",minRows:0,dependsOn:["method"],computeValue:(t,e,i)=>{const o=Array.isArray(t.method)&&t.method.length>0?t.method[0].value||t.method[0].name:t.method;return function(t){if(!t||0===t.length)return!0;const e=t.filter(t=>""!==(t.key||t.name||"")||""!==(t.value||""));if(0===e.length)return!0;for(const t of[em,im])if(e.length===t.length&&e.every((e,i)=>(e.key||e.name)===t[i].key&&e.value===t[i].value))return!0;return!1}(e)?function(t){return"POST"===t||"PUT"===t||"PATCH"===t?im.map(t=>({...t})):em.map(t=>({...t}))}(o):e}},result_name:Sp,body:{type:"textarea",evaluated:!0,placeholder:"Request body content (JSON, XML, etc.)",minHeight:200,dependsOn:["method"],computeValue:(t,e,i)=>{if("POST"===(Array.isArray(t.method)&&t.method.length>0?t.method[0].value||t.method[0].name:t.method)){if(!e||""===e.trim())return om}else{const t=(null==i?void 0:i.body)||"";if(!t||""===t.trim()||!e||""===e.trim()||e.trim()===om.trim())return""}return e}}},layout:[{type:"row",items:["method","url"]},{type:"accordion",sections:[{label:"Headers",collapsed:!0,getValueCount:t=>{var e;return(null===(e=t.headers)||void 0===e?void 0:e.length)||0},items:["headers"]},{label:"Body",collapsed:!0,getValueCount:t=>!(!t.body||""===t.body.trim()||t.body===om),items:["body"]}]},"result_name"],render:t=>{var e;const i=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_webhook"===t.type),o=(null==i?void 0:i.url)||"Configure webhook";return W` <div class="body">
8938
- ${ku(_u(o,!0),o)}
8939
- </div>`},toFormData:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_webhook"===t.type);return{uuid:t.uuid,method:(null==o?void 0:o.method)||"GET",url:(null==o?void 0:o.url)||"",headers:(null==o?void 0:o.headers)||(n=(null==o?void 0:o.method)||"GET","POST"===n||"PUT"===n||"PATCH"===n?{Accept:"application/json","Content-Type":"application/json"}:{Accept:"application/json"}),body:(null==o?void 0:o.body)||"",result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""};var n},fromFormData:(t,e)=>{var i,o,n;const s=Array.isArray(t.method)&&t.method.length>0?t.method[0]:{value:"GET"},r=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"call_webhook"===t.type),a={type:"call_webhook",uuid:(null==r?void 0:r.uuid)||Xt(),method:s.value,url:t.url||"",headers:t.headers||[],body:t.body||""},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("@webhook.status",{type:"has_number_between",arguments:["200","299"]},l,d,c),p={...h};return t.result_name&&""!==t.result_name.trim()&&(p.result_name=t.result_name.trim()),{uuid:e.uuid,actions:[a],router:p,exits:u}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},sm={type:"split_by_resthook",name:"Call Resthook",group:ju.services,flowTypes:[Bu,Nu,Fu],showAsAction:!0,form:{resthook:{type:"select",label:"Resthook",required:!0,searchable:!0,clearable:!1,placeholder:"Select a resthook...",endpoint:"/api/v2/resthooks.json",valueKey:"resthook",nameKey:"resthook",helpText:"Select the resthook to call"},result_name:Sp},layout:["resthook","result_name"],validate:t=>{const e={};return t.resthook&&0!==t.resthook.length||(e.resthook="A resthook is required"),{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_resthook"===t.type),o=(null==i?void 0:i.resthook)||"Configure resthook";return W` <div class="body">${ku(o,o)}</div> `},toFormData:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_resthook"===t.type);return{uuid:t.uuid,resthook:(null==o?void 0:o.resthook)?[{resthook:o.resthook}]:[],result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o,n;const s=Array.isArray(t.resthook)&&t.resthook.length>0?t.resthook[0]:null;if(!s)return e;const r=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"call_resthook"===t.type),a={type:"call_resthook",uuid:(null==r?void 0:r.uuid)||Xt(),resthook:s.resthook},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("@webhook.json.status",{type:"has_text",arguments:[]},l,d,c),p={...h};return t.result_name&&""!==t.result_name.trim()&&(p.result_name=t.result_name.trim()),{uuid:e.uuid,actions:[a],router:p,exits:u}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},rm={type:"split_by_llm",name:"Call AI",group:ju.services,flowTypes:[Bu,Nu,Fu],showAsAction:!0,render:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_llm"===t.type),n=(null==o?void 0:o.instructions)||"Configure AI instructions",s=null===(i=null==o?void 0:o.llm)||void 0===i?void 0:i.name;return W`
8938
+ ${hc(cc(o,!0),o)}
8939
+ </div>`},toFormData:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_webhook"===t.type);return{uuid:t.uuid,method:(null==o?void 0:o.method)||"GET",url:(null==o?void 0:o.url)||"",headers:(null==o?void 0:o.headers)||(n=(null==o?void 0:o.method)||"GET","POST"===n||"PUT"===n||"PATCH"===n?{Accept:"application/json","Content-Type":"application/json"}:{Accept:"application/json"}),body:(null==o?void 0:o.body)||"",result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""};var n},fromFormData:(t,e)=>{var i,o,n;const s=Array.isArray(t.method)&&t.method.length>0?t.method[0]:{value:"GET"},r=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"call_webhook"===t.type),a={type:"call_webhook",uuid:(null==r?void 0:r.uuid)||Xt(),method:s.value,url:t.url||"",headers:t.headers||[],body:t.body||""},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("@webhook.status",{type:"has_number_between",arguments:["200","299"]},l,d,c),p={...h};return t.result_name&&""!==t.result_name.trim()&&(p.result_name=t.result_name.trim()),{uuid:e.uuid,actions:[a],router:p,exits:u}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},sm={type:"split_by_resthook",name:"Call Resthook",group:ju.services,flowTypes:[Bu,Nu,Fu],showAsAction:!0,form:{resthook:{type:"select",label:"Resthook",required:!0,searchable:!0,clearable:!1,placeholder:"Select a resthook...",endpoint:"/api/v2/resthooks.json",valueKey:"resthook",nameKey:"resthook",helpText:"Select the resthook to call"},result_name:Sp},layout:["resthook","result_name"],validate:t=>{const e={};return t.resthook&&0!==t.resthook.length||(e.resthook="A resthook is required"),{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_resthook"===t.type),o=(null==i?void 0:i.resthook)||"Configure resthook";return W` <div class="body">${hc(o,o)}</div> `},toFormData:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_resthook"===t.type);return{uuid:t.uuid,resthook:(null==o?void 0:o.resthook)?[{resthook:o.resthook}]:[],result_name:(null===(i=t.router)||void 0===i?void 0:i.result_name)||""}},fromFormData:(t,e)=>{var i,o,n;const s=Array.isArray(t.resthook)&&t.resthook.length>0?t.resthook[0]:null;if(!s)return e;const r=null===(i=e.actions)||void 0===i?void 0:i.find(t=>"call_resthook"===t.type),a={type:"call_resthook",uuid:(null==r?void 0:r.uuid)||Xt(),resthook:s.resthook},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("@webhook.json.status",{type:"has_text",arguments:[]},l,d,c),p={...h};return t.result_name&&""!==t.result_name.trim()&&(p.result_name=t.result_name.trim()),{uuid:e.uuid,actions:[a],router:p,exits:u}},localizable:"categories",nonTranslatableCategories:"all",toLocalizationFormData:Mp,fromLocalizationFormData:zp},rm={type:"split_by_llm",name:"Call AI",group:ju.services,flowTypes:[Bu,Nu,Fu],showAsAction:!0,render:t=>{var e,i;const o=null===(e=t.actions)||void 0===e?void 0:e.find(t=>"call_llm"===t.type),n=(null==o?void 0:o.instructions)||"Configure AI instructions",s=null===(i=null==o?void 0:o.llm)||void 0===i?void 0:i.name;return W`
8940
8940
  ${s?W`<div class="body" style="padding-bottom:0;">
8941
- ${Cu(s,(t=>{if(!t)return null;for(const[e,i]of wu)if(e.test(t))return i;return null})(s))}
8941
+ ${uc(s,(t=>{if(!t)return null;for(const[e,i]of dc)if(e.test(t))return i;return null})(s))}
8942
8942
  </div>`:null}
8943
8943
  <div class="body" style="margin-bottom:10px;">
8944
- ${ku(_u(n,!0),n)}
8944
+ ${hc(cc(n,!0),n)}
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>
@@ -9314,7 +9314,7 @@ background: #ccc;
9314
9314
  `)}
9315
9315
  </div>
9316
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`
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=rc(h);if(u===t[0]){let t=0;for(const o of e){const e=o===s?p:p+40;c[o]={left:rc(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:rc(h),top:p},h=rc(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:rc(Math.max(0,c[i].left-t)),top:rc(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&&nc(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&&nc(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`
9318
9318
 
9319
9319
  .node {
9320
9320
  background-color: #fff;
@@ -9796,7 +9796,7 @@ background: #ccc;
9796
9796
  .touch-device .add-action-button {
9797
9797
  opacity: 0.8 !important;
9798
9798
  }
9799
- }`}constructor(){super(),this.exitRemovalTimeouts=new Map,this.connectionTimeout=null,this.exitRemovingState=new Set,this.actionRemovalTimeouts=new Map,this.actionRemovingState=new Set,this.actionClickStartPos=null,this.pendingActionClick=null,this.nodeClickStartPos=null,this.pendingNodeClick=null,this.draggedActionHeight=0,this.resizeObserver=null,this.externalDragInfo=null,this.showLastActionPlaceholder=!1,this.lastActionPlaceholderHeight=60,this.handleActionOrderChanged=this.handleActionOrderChanged.bind(this),this.handleActionDragStart=this.handleActionDragStart.bind(this),this.handleActionDragExternal=this.handleActionDragExternal.bind(this),this.handleActionDragInternal=this.handleActionDragInternal.bind(this),this.handleActionDragStop=this.handleActionDragStop.bind(this),this.handleExternalActionDragOver=this.handleExternalActionDragOver.bind(this),this.handleExternalActionDrop=this.handleExternalActionDrop.bind(this),this.handleExternalActionDragLeave=this.handleExternalActionDragLeave.bind(this),this.handleActionShowGhost=this.handleActionShowGhost.bind(this),this.handleActionHideGhost=this.handleActionHideGhost.bind(this),this.handleActionShowOriginal=this.handleActionShowOriginal.bind(this),this.handleActionHideOriginal=this.handleActionHideOriginal.bind(this)}connectedCallback(){super.connectedCallback(),this.addEventListener("action-drag-over",this.handleExternalActionDragOver),this.addEventListener("action-drop",this.handleExternalActionDrop),this.addEventListener("action-drag-leave",this.handleExternalActionDragLeave),this.addEventListener("action-show-ghost",this.handleActionShowGhost),this.addEventListener("action-hide-ghost",this.handleActionHideGhost),this.addEventListener("action-show-original",this.handleActionShowOriginal),this.addEventListener("action-hide-original",this.handleActionHideOriginal),this.resizeObserver=new ResizeObserver(()=>{this.plumber&&this.node&&this.plumber.revalidate([this.node.uuid])}),this.resizeObserver.observe(this)}updated(t){var e;if(super.updated(t),t.get("ui")&&t.has("ui"))for(let t=25;t<=350;t+=25)setTimeout(()=>{this.plumber.revalidate([this.node.uuid])},t);if(t.has("node")){if(this.plumber){this.connectionTimeout&&clearTimeout(this.connectionTimeout);const t=this.node.exits.map(t=>t.uuid);this.plumber.removeNodeConnections(this.node.uuid,t),this.connectionTimeout=window.setTimeout(()=>{var t;if("terminal"!==(null===(t=this.ui)||void 0===t?void 0:t.type))for(const t of this.node.exits)this.plumber.makeSource(t.uuid),t.destination_uuid&&this.plumber.connectIds(this.node.uuid,t.uuid,t.destination_uuid);this.connectionTimeout=null,this.plumber.revalidate([this.node.uuid])},0)}const t=this.parentElement;if(t&&this.ui){const i=t.getBoundingClientRect();null===(e=$d())||void 0===e||e.getState().expandCanvas(this.ui.position.left+i.width,this.ui.position.top+i.height)}}}disconnectedCallback(){this.plumber&&this.node&&(this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.plumber.forgetNode(this.node.uuid)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),super.disconnectedCallback(),this.removeEventListener("action-drag-over",this.handleExternalActionDragOver),this.removeEventListener("action-drop",this.handleExternalActionDrop),this.removeEventListener("action-drag-leave",this.handleExternalActionDragLeave),this.removeEventListener("action-show-ghost",this.handleActionShowGhost),this.removeEventListener("action-hide-ghost",this.handleActionHideGhost),this.removeEventListener("action-show-original",this.handleActionShowOriginal),this.removeEventListener("action-hide-original",this.handleActionHideOriginal),this.exitRemovalTimeouts.forEach(t=>{clearTimeout(t)}),this.exitRemovalTimeouts.clear(),this.actionRemovalTimeouts.forEach(t=>{clearTimeout(t)}),this.actionRemovalTimeouts.clear(),this.exitRemovingState.clear(),this.actionRemovingState.clear(),this.plumber&&this.plumber.removeNodeConnections(this.node.uuid,this.node.exits.map(t=>t.uuid))}handleExitClick(t,e){t.preventDefault(),t.stopPropagation();const i=e.uuid;if(!e.destination_uuid)return;if(this.exitRemovingState.has(i))return void this.disconnectExit(e);this.exitRemovingState.add(i),this.requestUpdate(),this.plumber.setConnectionRemovingState(i,!0),this.exitRemovalTimeouts.has(i)&&clearTimeout(this.exitRemovalTimeouts.get(i));const o=window.setTimeout(()=>{this.exitRemovingState.delete(i),this.exitRemovalTimeouts.delete(i),this.plumber.setConnectionRemovingState(i,!1),this.requestUpdate()},1500);this.exitRemovalTimeouts.set(i,o)}disconnectExit(t){var e;const i=t.uuid;this.exitRemovingState.delete(i),this.plumber.setConnectionRemovingState(i,!1),this.exitRemovalTimeouts.has(i)&&(clearTimeout(this.exitRemovalTimeouts.get(i)),this.exitRemovalTimeouts.delete(i)),this.plumber.removeExitConnection(i);const o={...t,destination_uuid:null},n=this.node.exits.map(t=>t.uuid===i?o:t),s={...this.node,exits:n};null===(e=$d())||void 0===e||e.getState().updateNode(this.node.uuid,s),this.requestUpdate()}handleActionRemoveClick(t,e,i){t.preventDefault(),t.stopPropagation();const o=e.uuid;if(this.actionRemovingState.has(o))return void this.removeAction(e,i);this.actionRemovingState.add(o),this.requestUpdate(),this.actionRemovalTimeouts.has(o)&&clearTimeout(this.actionRemovalTimeouts.get(o));const n=window.setTimeout(()=>{this.actionRemovingState.delete(o),this.actionRemovalTimeouts.delete(o),this.requestUpdate()},1e3);this.actionRemovalTimeouts.set(o,n)}removeAction(t,e){var i;const o=t.uuid;this.actionRemovingState.delete(o),this.actionRemovalTimeouts.has(o)&&(clearTimeout(this.actionRemovalTimeouts.get(o)),this.actionRemovalTimeouts.delete(o));const n=this.node.actions.filter(t=>t.uuid!==o);if(0===n.length)this.fireCustomEvent(Io.NodeDeleted,{uuid:this.node.uuid});else{const t={...this.node,actions:n};null===(i=$d())||void 0===i||i.getState().updateNode(this.node.uuid,t),this.requestUpdate()}}handleNodeRemoveClick(t){t.preventDefault(),t.stopPropagation();const e=this.node.uuid;if(this.actionRemovingState.has(e))return void this.removeNode();this.actionRemovingState.add(e),this.requestUpdate(),this.actionRemovalTimeouts.has(e)&&clearTimeout(this.actionRemovalTimeouts.get(e));const i=window.setTimeout(()=>{this.actionRemovingState.delete(e),this.actionRemovalTimeouts.delete(e),this.requestUpdate()},1e3);this.actionRemovalTimeouts.set(e,i)}removeNode(){const t=this.node.uuid;this.actionRemovingState.delete(t),this.actionRemovalTimeouts.has(t)&&(clearTimeout(this.actionRemovalTimeouts.get(t)),this.actionRemovalTimeouts.delete(t)),this.fireCustomEvent(Io.NodeDeleted,{uuid:this.node.uuid})}handleActionOrderChanged(t){var e;const[i,o]=t.detail.swap;if(this.externalDragInfo)return;const n=[...this.node.actions],s=n.splice(i,1)[0];n.splice(o,0,s),this.node={...this.node,actions:n},null===(e=$d())||void 0===e||e.getState().updateNode(this.node.uuid,{...this.node,actions:n})}handleActionDragStart(t){const e=t.detail.id,i=this.querySelector(`#${e}`);this.draggedActionHeight=i?i.offsetHeight:60,1===this.node.actions.length&&(this.showLastActionPlaceholder=!0,this.lastActionPlaceholderHeight=this.draggedActionHeight,this.requestUpdate())}handleActionDragExternal(t){t.stopPropagation();const e=t.detail.id.split("-");if(e.length<2||isNaN(parseInt(e[1],10)))return;const i=parseInt(e[1],10),o=this.node.actions[i],n=1===this.node.actions.length;this.fireCustomEvent(Io.DragExternal,{action:o,nodeUuid:this.node.uuid,actionIndex:i,mouseX:t.detail.mouseX,mouseY:t.detail.mouseY,actionHeight:this.draggedActionHeight,isLastAction:n})}handleActionDragInternal(t){t.stopPropagation(),this.fireCustomEvent(Io.DragInternal,{})}handleActionDragStop(t){const e=t.detail.isExternal;if(this.showLastActionPlaceholder=!1,e){t.stopPropagation();const e=t.detail.id.split("-");if(e.length<2||isNaN(Number(e[1])))return;const i=parseInt(e[1],10),o=this.node.actions[i],n=1===this.node.actions.length;this.fireCustomEvent(Io.DragStop,{action:o,nodeUuid:this.node.uuid,actionIndex:i,isExternal:!0,isLastAction:n,mouseX:t.detail.mouseX,mouseY:t.detail.mouseY})}this.requestUpdate()}getTopCenter(t){const e=t.getBoundingClientRect();return{x:e.left+e.width/2,y:e.top}}isActiveLink(t,e){var i,o,n;return!!t.closest(".linked-name")&&(e?!(null===(i=this.issuesByAction)||void 0===i?void 0:i.has(e.uuid)):!((null===(o=this.issuesByNode)||void 0===o?void 0:o.has(this.node.uuid))||(null===(n=this.node.actions)||void 0===n?void 0:n.some(t=>{var e;return null===(e=this.issuesByAction)||void 0===e?void 0:e.has(t.uuid)}))))}handleActionMouseDown(t,e){if(fu(t))return;const i=t.target;i.closest(".remove-button")||i.closest(".drag-handle")||this.isActiveLink(i,e)||this.actionRemovingState.has(e.uuid)||(this.actionClickStartPos={x:t.clientX,y:t.clientY},this.pendingActionClick={action:e,event:t})}handleActionMouseUp(t,e){if(!this.pendingActionClick||this.pendingActionClick.action.uuid!==e.uuid)return this.actionClickStartPos=null,void(this.pendingActionClick=null);const i=t.target;if(i.closest(".remove-button")||i.closest(".drag-handle")||this.isActiveLink(i,e)||this.actionRemovingState.has(e.uuid))return this.actionClickStartPos=null,void(this.pendingActionClick=null);if(this.actionClickStartPos){const i=t.clientX-this.actionClickStartPos.x,o=t.clientY-this.actionClickStartPos.y,n=Math.sqrt(i*i+o*o),s=this.closest("temba-flow-editor"),r=null==s?void 0:s.dragging;if(n<=5&&(!s||!r)){const i=t.currentTarget,o=i?this.getTopCenter(i):{x:t.clientX,y:t.clientY};this.fireCustomEvent(Io.ActionEditRequested,{action:e,nodeUuid:this.node.uuid,originX:o.x,originY:o.y})}}this.actionClickStartPos=null,this.pendingActionClick=null}handleActionTouchStart(t,e){const i=t.target;if(i.closest(".remove-button")||i.closest(".drag-handle")||this.isActiveLink(i,e)||this.actionRemovingState.has(e.uuid))return;const o=t.touches[0];o&&(this.actionClickStartPos={x:o.clientX,y:o.clientY},this.pendingActionClick={action:e,event:t})}handleActionTouchEnd(t,e){if(!this.pendingActionClick||this.pendingActionClick.action.uuid!==e.uuid)return this.actionClickStartPos=null,void(this.pendingActionClick=null);const i=t.target;if(i.closest(".remove-button")||i.closest(".drag-handle")||this.isActiveLink(i,e)||this.actionRemovingState.has(e.uuid))return this.actionClickStartPos=null,void(this.pendingActionClick=null);const o=t.changedTouches[0];if(this.actionClickStartPos&&o){const i=o.clientX-this.actionClickStartPos.x,n=o.clientY-this.actionClickStartPos.y,s=Math.sqrt(i*i+n*n),r=this.closest("temba-flow-editor"),a=null==r?void 0:r.dragging;if(s<=5&&(!r||!a)){const i=t.currentTarget,n=i?this.getTopCenter(i):{x:o.clientX,y:o.clientY};this.fireCustomEvent(Io.ActionEditRequested,{action:e,nodeUuid:this.node.uuid,originX:n.x,originY:n.y})}}this.actionClickStartPos=null,this.pendingActionClick=null}handleActionClick(t,e){t.preventDefault(),t.stopPropagation();t.target.closest(".remove-button")||this.actionRemovingState.has(e.uuid)||this.fireCustomEvent(Io.ActionEditRequested,{action:e,nodeUuid:this.node.uuid})}handleNodeEditClick(t){t.preventDefault(),t.stopPropagation();t.target.closest(".remove-button")||this.actionRemovingState.has(this.node.uuid)||this.node.router&&(this.node.actions&&1===this.node.actions.length?this.fireCustomEvent(Io.ActionEditRequested,{action:this.node.actions[0],nodeUuid:this.node.uuid}):this.fireCustomEvent(Io.NodeEditRequested,{node:this.node,nodeUI:this.ui}))}handleNodeMouseDown(t){if(fu(t))return;const e=t.target;e.closest(".remove-button")||e.closest(".exit")||e.closest(".exit-wrapper")||e.closest(".drag-handle")||this.isActiveLink(e)||this.actionRemovingState.has(this.node.uuid)||(this.nodeClickStartPos={x:t.clientX,y:t.clientY},this.pendingNodeClick={event:t})}handleNodeMouseUp(t){if(!this.pendingNodeClick)return this.nodeClickStartPos=null,void(this.pendingNodeClick=null);const e=t.target;if(e.closest(".remove-button")||e.closest(".exit")||e.closest(".exit-wrapper")||e.closest(".drag-handle")||this.isActiveLink(e)||this.actionRemovingState.has(this.node.uuid))return this.nodeClickStartPos=null,void(this.pendingNodeClick=null);if(this.nodeClickStartPos){const e=t.clientX-this.nodeClickStartPos.x,i=t.clientY-this.nodeClickStartPos.y,o=Math.sqrt(e*e+i*i),n=this.closest("temba-flow-editor"),s=null==n?void 0:n.dragging;if(o<=5&&(!n||!s)&&this.node.router){const t=this.getTopCenter(this);this.node.actions&&1===this.node.actions.length?this.fireCustomEvent(Io.ActionEditRequested,{action:this.node.actions[0],nodeUuid:this.node.uuid,originX:t.x,originY:t.y}):this.fireCustomEvent(Io.NodeEditRequested,{node:this.node,nodeUI:this.ui,originX:t.x,originY:t.y})}}this.nodeClickStartPos=null,this.pendingNodeClick=null}handleNodeTouchStart(t){const e=t.target;if(e.closest(".remove-button")||e.closest(".exit")||e.closest(".exit-wrapper")||e.closest(".drag-handle")||this.isActiveLink(e)||this.actionRemovingState.has(this.node.uuid))return;const i=t.touches[0];i&&(this.nodeClickStartPos={x:i.clientX,y:i.clientY},this.pendingNodeClick={event:t})}handleNodeTouchEnd(t){if(!this.pendingNodeClick)return this.nodeClickStartPos=null,void(this.pendingNodeClick=null);const e=t.target;if(e.closest(".remove-button")||e.closest(".exit")||e.closest(".exit-wrapper")||e.closest(".drag-handle")||this.isActiveLink(e)||this.actionRemovingState.has(this.node.uuid))return this.nodeClickStartPos=null,void(this.pendingNodeClick=null);const i=t.changedTouches[0];if(this.nodeClickStartPos&&i){const t=i.clientX-this.nodeClickStartPos.x,e=i.clientY-this.nodeClickStartPos.y,o=Math.sqrt(t*t+e*e),n=this.closest("temba-flow-editor"),s=null==n?void 0:n.dragging;if(o<=5&&(!n||!s)&&this.node.router){const t=this.getTopCenter(this);this.node.actions&&1===this.node.actions.length?this.fireCustomEvent(Io.ActionEditRequested,{action:this.node.actions[0],nodeUuid:this.node.uuid,originX:t.x,originY:t.y}):this.fireCustomEvent(Io.NodeEditRequested,{node:this.node,nodeUI:this.ui,originX:t.x,originY:t.y})}}this.nodeClickStartPos=null,this.pendingNodeClick=null}handleAddActionClick(t){t.preventDefault(),t.stopPropagation(),this.fireCustomEvent(Io.AddActionRequested,{nodeUuid:this.node.uuid})}calculateDropIndex(t){var e,i;const o=this.querySelector("temba-sortable-list");if(!o||!this.node.actions)return null!==(i=null===(e=this.node.actions)||void 0===e?void 0:e.length)&&void 0!==i?i:0;const n=Array.from(o.querySelectorAll(".action.sortable:not(.drop-placeholder)"));if(0===n.length)return 0;for(let e=0;e<n.length;e++){const i=n[e].getBoundingClientRect();if(t<i.top+i.height/2)return e}return n.length}handleExternalActionDragOver(t){if("execute_actions"!==this.ui.type)return;const{action:e,sourceNodeUuid:i,actionIndex:o,mouseY:n,actionHeight:s}=t.detail;if(i===this.node.uuid)return;const r=this.calculateDropIndex(n);this.externalDragInfo={action:e,sourceNodeUuid:i,actionIndex:o,dropIndex:r,actionHeight:s||60},this.requestUpdate()}handleExternalActionDragLeave(t){this.externalDragInfo=null,this.requestUpdate()}handleActionShowGhost(t){if(this.querySelector("temba-sortable-list")){const t=document.querySelector(".ghost");t&&(t.style.display="block")}}handleActionHideGhost(t){if(this.querySelector("temba-sortable-list")){const t=document.querySelector(".ghost");t&&(t.style.display="none")}}handleActionShowOriginal(t){const e=this.querySelector("temba-sortable-list");null==e||e.setOriginalVisible(!0),this.showLastActionPlaceholder=!1,this.requestUpdate()}handleActionHideOriginal(t){const e=this.querySelector("temba-sortable-list");null==e||e.setOriginalVisible(!1),1===this.node.actions.length&&(this.showLastActionPlaceholder=!0),this.requestUpdate()}handleExternalActionDrop(t){var e,i,o,n,s,r,a;if("execute_actions"!==this.ui.type)return;const{action:l,sourceNodeUuid:d,actionIndex:c,isCopy:h}=t.detail;if(d===this.node.uuid)return;const u=null!==(n=null!==(i=null===(e=this.externalDragInfo)||void 0===e?void 0:e.dropIndex)&&void 0!==i?i:null===(o=this.node.actions)||void 0===o?void 0:o.length)&&void 0!==n?n:0;this.externalDragInfo=null;const p=$d();if(!p)return;const m=p.getState().flowDefinition;if(!m)return;const g=m.nodes.find(t=>t.uuid===d);if(!g)return;const f=h?{...l,uuid:Xt()}:l,v=[...this.node.actions];v.splice(u,0,f);const b={...this.node,actions:v};if(null===(s=$d())||void 0===s||s.getState().updateNode(this.node.uuid,b),h){const t=m.localization;if(t)for(const e of Object.keys(t)){const i=null===(r=t[e])||void 0===r?void 0:r[l.uuid];i&&p.getState().updateLocalization(e,f.uuid,JSON.parse(JSON.stringify(i)))}}if(!h){const t=g.actions.filter((t,e)=>e!==c);if(0===t.length)this.fireCustomEvent(Io.NodeDeleted,{uuid:d});else{const e={...g,actions:t};null===(a=$d())||void 0===a||a.getState().updateNode(d,e)}}this.requestUpdate(),this.fireCustomEvent(Io.SizeChanged,{uuid:this.node.uuid})}renderTitle(t,e,i,o=!1){var n,s,r,a,l;const d=t.group?null===(n=Wu[t.group])||void 0===n?void 0:n.color:"#aaaaaa",c="terminal"===(null===(s=this.ui)||void 0===s?void 0:s.type);return W`<div class="cn-title" style="background:${d}">
9799
+ }`}constructor(){super(),this.exitRemovalTimeouts=new Map,this.connectionTimeout=null,this.exitRemovingState=new Set,this.actionRemovalTimeouts=new Map,this.actionRemovingState=new Set,this.actionClickStartPos=null,this.pendingActionClick=null,this.nodeClickStartPos=null,this.pendingNodeClick=null,this.draggedActionHeight=0,this.resizeObserver=null,this.externalDragInfo=null,this.showLastActionPlaceholder=!1,this.lastActionPlaceholderHeight=60,this.handleActionOrderChanged=this.handleActionOrderChanged.bind(this),this.handleActionDragStart=this.handleActionDragStart.bind(this),this.handleActionDragExternal=this.handleActionDragExternal.bind(this),this.handleActionDragInternal=this.handleActionDragInternal.bind(this),this.handleActionDragStop=this.handleActionDragStop.bind(this),this.handleExternalActionDragOver=this.handleExternalActionDragOver.bind(this),this.handleExternalActionDrop=this.handleExternalActionDrop.bind(this),this.handleExternalActionDragLeave=this.handleExternalActionDragLeave.bind(this),this.handleActionShowGhost=this.handleActionShowGhost.bind(this),this.handleActionHideGhost=this.handleActionHideGhost.bind(this),this.handleActionShowOriginal=this.handleActionShowOriginal.bind(this),this.handleActionHideOriginal=this.handleActionHideOriginal.bind(this)}connectedCallback(){super.connectedCallback(),this.addEventListener("action-drag-over",this.handleExternalActionDragOver),this.addEventListener("action-drop",this.handleExternalActionDrop),this.addEventListener("action-drag-leave",this.handleExternalActionDragLeave),this.addEventListener("action-show-ghost",this.handleActionShowGhost),this.addEventListener("action-hide-ghost",this.handleActionHideGhost),this.addEventListener("action-show-original",this.handleActionShowOriginal),this.addEventListener("action-hide-original",this.handleActionHideOriginal),this.resizeObserver=new ResizeObserver(()=>{this.plumber&&this.node&&this.plumber.revalidate([this.node.uuid])}),this.resizeObserver.observe(this)}updated(t){var e;if(super.updated(t),t.get("ui")&&t.has("ui"))for(let t=25;t<=350;t+=25)setTimeout(()=>{this.plumber.revalidate([this.node.uuid])},t);if(t.has("node")){if(this.plumber){this.connectionTimeout&&clearTimeout(this.connectionTimeout);const t=this.node.exits.map(t=>t.uuid);this.plumber.removeNodeConnections(this.node.uuid,t),this.connectionTimeout=window.setTimeout(()=>{var t;if("terminal"!==(null===(t=this.ui)||void 0===t?void 0:t.type))for(const t of this.node.exits)this.plumber.makeSource(t.uuid),t.destination_uuid&&this.plumber.connectIds(this.node.uuid,t.uuid,t.destination_uuid);this.connectionTimeout=null,this.plumber.revalidate([this.node.uuid])},0)}const t=this.parentElement;if(t&&this.ui){const i=t.getBoundingClientRect();null===(e=Ec())||void 0===e||e.getState().expandCanvas(this.ui.position.left+i.width,this.ui.position.top+i.height)}}}disconnectedCallback(){this.plumber&&this.node&&(this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.plumber.forgetNode(this.node.uuid)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),super.disconnectedCallback(),this.removeEventListener("action-drag-over",this.handleExternalActionDragOver),this.removeEventListener("action-drop",this.handleExternalActionDrop),this.removeEventListener("action-drag-leave",this.handleExternalActionDragLeave),this.removeEventListener("action-show-ghost",this.handleActionShowGhost),this.removeEventListener("action-hide-ghost",this.handleActionHideGhost),this.removeEventListener("action-show-original",this.handleActionShowOriginal),this.removeEventListener("action-hide-original",this.handleActionHideOriginal),this.exitRemovalTimeouts.forEach(t=>{clearTimeout(t)}),this.exitRemovalTimeouts.clear(),this.actionRemovalTimeouts.forEach(t=>{clearTimeout(t)}),this.actionRemovalTimeouts.clear(),this.exitRemovingState.clear(),this.actionRemovingState.clear(),this.plumber&&this.plumber.removeNodeConnections(this.node.uuid,this.node.exits.map(t=>t.uuid))}handleExitClick(t,e){t.preventDefault(),t.stopPropagation();const i=e.uuid;if(!e.destination_uuid)return;if(this.exitRemovingState.has(i))return void this.disconnectExit(e);this.exitRemovingState.add(i),this.requestUpdate(),this.plumber.setConnectionRemovingState(i,!0),this.exitRemovalTimeouts.has(i)&&clearTimeout(this.exitRemovalTimeouts.get(i));const o=window.setTimeout(()=>{this.exitRemovingState.delete(i),this.exitRemovalTimeouts.delete(i),this.plumber.setConnectionRemovingState(i,!1),this.requestUpdate()},1500);this.exitRemovalTimeouts.set(i,o)}disconnectExit(t){var e;const i=t.uuid;this.exitRemovingState.delete(i),this.plumber.setConnectionRemovingState(i,!1),this.exitRemovalTimeouts.has(i)&&(clearTimeout(this.exitRemovalTimeouts.get(i)),this.exitRemovalTimeouts.delete(i)),this.plumber.removeExitConnection(i);const o={...t,destination_uuid:null},n=this.node.exits.map(t=>t.uuid===i?o:t),s={...this.node,exits:n};null===(e=Ec())||void 0===e||e.getState().updateNode(this.node.uuid,s),this.requestUpdate()}handleActionRemoveClick(t,e,i){t.preventDefault(),t.stopPropagation();const o=e.uuid;if(this.actionRemovingState.has(o))return void this.removeAction(e,i);this.actionRemovingState.add(o),this.requestUpdate(),this.actionRemovalTimeouts.has(o)&&clearTimeout(this.actionRemovalTimeouts.get(o));const n=window.setTimeout(()=>{this.actionRemovingState.delete(o),this.actionRemovalTimeouts.delete(o),this.requestUpdate()},1e3);this.actionRemovalTimeouts.set(o,n)}removeAction(t,e){var i;const o=t.uuid;this.actionRemovingState.delete(o),this.actionRemovalTimeouts.has(o)&&(clearTimeout(this.actionRemovalTimeouts.get(o)),this.actionRemovalTimeouts.delete(o));const n=this.node.actions.filter(t=>t.uuid!==o);if(0===n.length)this.fireCustomEvent(Io.NodeDeleted,{uuid:this.node.uuid});else{const t={...this.node,actions:n};null===(i=Ec())||void 0===i||i.getState().updateNode(this.node.uuid,t),this.requestUpdate()}}handleNodeRemoveClick(t){t.preventDefault(),t.stopPropagation();const e=this.node.uuid;if(this.actionRemovingState.has(e))return void this.removeNode();this.actionRemovingState.add(e),this.requestUpdate(),this.actionRemovalTimeouts.has(e)&&clearTimeout(this.actionRemovalTimeouts.get(e));const i=window.setTimeout(()=>{this.actionRemovingState.delete(e),this.actionRemovalTimeouts.delete(e),this.requestUpdate()},1e3);this.actionRemovalTimeouts.set(e,i)}removeNode(){const t=this.node.uuid;this.actionRemovingState.delete(t),this.actionRemovalTimeouts.has(t)&&(clearTimeout(this.actionRemovalTimeouts.get(t)),this.actionRemovalTimeouts.delete(t)),this.fireCustomEvent(Io.NodeDeleted,{uuid:this.node.uuid})}handleActionOrderChanged(t){var e;const[i,o]=t.detail.swap;if(this.externalDragInfo)return;const n=[...this.node.actions],s=n.splice(i,1)[0];n.splice(o,0,s),this.node={...this.node,actions:n},null===(e=Ec())||void 0===e||e.getState().updateNode(this.node.uuid,{...this.node,actions:n})}handleActionDragStart(t){const e=t.detail.id,i=this.querySelector(`#${e}`);this.draggedActionHeight=i?i.offsetHeight:60,1===this.node.actions.length&&(this.showLastActionPlaceholder=!0,this.lastActionPlaceholderHeight=this.draggedActionHeight,this.requestUpdate())}handleActionDragExternal(t){t.stopPropagation();const e=t.detail.id.split("-");if(e.length<2||isNaN(parseInt(e[1],10)))return;const i=parseInt(e[1],10),o=this.node.actions[i],n=1===this.node.actions.length;this.fireCustomEvent(Io.DragExternal,{action:o,nodeUuid:this.node.uuid,actionIndex:i,mouseX:t.detail.mouseX,mouseY:t.detail.mouseY,actionHeight:this.draggedActionHeight,isLastAction:n})}handleActionDragInternal(t){t.stopPropagation(),this.fireCustomEvent(Io.DragInternal,{})}handleActionDragStop(t){const e=t.detail.isExternal;if(this.showLastActionPlaceholder=!1,e){t.stopPropagation();const e=t.detail.id.split("-");if(e.length<2||isNaN(Number(e[1])))return;const i=parseInt(e[1],10),o=this.node.actions[i],n=1===this.node.actions.length;this.fireCustomEvent(Io.DragStop,{action:o,nodeUuid:this.node.uuid,actionIndex:i,isExternal:!0,isLastAction:n,mouseX:t.detail.mouseX,mouseY:t.detail.mouseY})}this.requestUpdate()}getTopCenter(t){const e=t.getBoundingClientRect();return{x:e.left+e.width/2,y:e.top}}isActiveLink(t,e){var i,o,n;return!!t.closest(".linked-name")&&(e?!(null===(i=this.issuesByAction)||void 0===i?void 0:i.has(e.uuid)):!((null===(o=this.issuesByNode)||void 0===o?void 0:o.has(this.node.uuid))||(null===(n=this.node.actions)||void 0===n?void 0:n.some(t=>{var e;return null===(e=this.issuesByAction)||void 0===e?void 0:e.has(t.uuid)}))))}handleActionMouseDown(t,e){if(nc(t))return;const i=t.target;i.closest(".remove-button")||i.closest(".drag-handle")||this.isActiveLink(i,e)||this.actionRemovingState.has(e.uuid)||(this.actionClickStartPos={x:t.clientX,y:t.clientY},this.pendingActionClick={action:e,event:t})}handleActionMouseUp(t,e){if(!this.pendingActionClick||this.pendingActionClick.action.uuid!==e.uuid)return this.actionClickStartPos=null,void(this.pendingActionClick=null);const i=t.target;if(i.closest(".remove-button")||i.closest(".drag-handle")||this.isActiveLink(i,e)||this.actionRemovingState.has(e.uuid))return this.actionClickStartPos=null,void(this.pendingActionClick=null);if(this.actionClickStartPos){const i=t.clientX-this.actionClickStartPos.x,o=t.clientY-this.actionClickStartPos.y,n=Math.sqrt(i*i+o*o),s=this.closest("temba-flow-editor"),r=null==s?void 0:s.dragging;if(n<=5&&(!s||!r)){const i=t.currentTarget,o=i?this.getTopCenter(i):{x:t.clientX,y:t.clientY};this.fireCustomEvent(Io.ActionEditRequested,{action:e,nodeUuid:this.node.uuid,originX:o.x,originY:o.y})}}this.actionClickStartPos=null,this.pendingActionClick=null}handleActionTouchStart(t,e){const i=t.target;if(i.closest(".remove-button")||i.closest(".drag-handle")||this.isActiveLink(i,e)||this.actionRemovingState.has(e.uuid))return;const o=t.touches[0];o&&(this.actionClickStartPos={x:o.clientX,y:o.clientY},this.pendingActionClick={action:e,event:t})}handleActionTouchEnd(t,e){if(!this.pendingActionClick||this.pendingActionClick.action.uuid!==e.uuid)return this.actionClickStartPos=null,void(this.pendingActionClick=null);const i=t.target;if(i.closest(".remove-button")||i.closest(".drag-handle")||this.isActiveLink(i,e)||this.actionRemovingState.has(e.uuid))return this.actionClickStartPos=null,void(this.pendingActionClick=null);const o=t.changedTouches[0];if(this.actionClickStartPos&&o){const i=o.clientX-this.actionClickStartPos.x,n=o.clientY-this.actionClickStartPos.y,s=Math.sqrt(i*i+n*n),r=this.closest("temba-flow-editor"),a=null==r?void 0:r.dragging;if(s<=5&&(!r||!a)){const i=t.currentTarget,n=i?this.getTopCenter(i):{x:o.clientX,y:o.clientY};this.fireCustomEvent(Io.ActionEditRequested,{action:e,nodeUuid:this.node.uuid,originX:n.x,originY:n.y})}}this.actionClickStartPos=null,this.pendingActionClick=null}handleActionClick(t,e){t.preventDefault(),t.stopPropagation();t.target.closest(".remove-button")||this.actionRemovingState.has(e.uuid)||this.fireCustomEvent(Io.ActionEditRequested,{action:e,nodeUuid:this.node.uuid})}handleNodeEditClick(t){t.preventDefault(),t.stopPropagation();t.target.closest(".remove-button")||this.actionRemovingState.has(this.node.uuid)||this.node.router&&(this.node.actions&&1===this.node.actions.length?this.fireCustomEvent(Io.ActionEditRequested,{action:this.node.actions[0],nodeUuid:this.node.uuid}):this.fireCustomEvent(Io.NodeEditRequested,{node:this.node,nodeUI:this.ui}))}handleNodeMouseDown(t){if(nc(t))return;const e=t.target;e.closest(".remove-button")||e.closest(".exit")||e.closest(".exit-wrapper")||e.closest(".drag-handle")||this.isActiveLink(e)||this.actionRemovingState.has(this.node.uuid)||(this.nodeClickStartPos={x:t.clientX,y:t.clientY},this.pendingNodeClick={event:t})}handleNodeMouseUp(t){if(!this.pendingNodeClick)return this.nodeClickStartPos=null,void(this.pendingNodeClick=null);const e=t.target;if(e.closest(".remove-button")||e.closest(".exit")||e.closest(".exit-wrapper")||e.closest(".drag-handle")||this.isActiveLink(e)||this.actionRemovingState.has(this.node.uuid))return this.nodeClickStartPos=null,void(this.pendingNodeClick=null);if(this.nodeClickStartPos){const e=t.clientX-this.nodeClickStartPos.x,i=t.clientY-this.nodeClickStartPos.y,o=Math.sqrt(e*e+i*i),n=this.closest("temba-flow-editor"),s=null==n?void 0:n.dragging;if(o<=5&&(!n||!s)&&this.node.router){const t=this.getTopCenter(this);this.node.actions&&1===this.node.actions.length?this.fireCustomEvent(Io.ActionEditRequested,{action:this.node.actions[0],nodeUuid:this.node.uuid,originX:t.x,originY:t.y}):this.fireCustomEvent(Io.NodeEditRequested,{node:this.node,nodeUI:this.ui,originX:t.x,originY:t.y})}}this.nodeClickStartPos=null,this.pendingNodeClick=null}handleNodeTouchStart(t){const e=t.target;if(e.closest(".remove-button")||e.closest(".exit")||e.closest(".exit-wrapper")||e.closest(".drag-handle")||this.isActiveLink(e)||this.actionRemovingState.has(this.node.uuid))return;const i=t.touches[0];i&&(this.nodeClickStartPos={x:i.clientX,y:i.clientY},this.pendingNodeClick={event:t})}handleNodeTouchEnd(t){if(!this.pendingNodeClick)return this.nodeClickStartPos=null,void(this.pendingNodeClick=null);const e=t.target;if(e.closest(".remove-button")||e.closest(".exit")||e.closest(".exit-wrapper")||e.closest(".drag-handle")||this.isActiveLink(e)||this.actionRemovingState.has(this.node.uuid))return this.nodeClickStartPos=null,void(this.pendingNodeClick=null);const i=t.changedTouches[0];if(this.nodeClickStartPos&&i){const t=i.clientX-this.nodeClickStartPos.x,e=i.clientY-this.nodeClickStartPos.y,o=Math.sqrt(t*t+e*e),n=this.closest("temba-flow-editor"),s=null==n?void 0:n.dragging;if(o<=5&&(!n||!s)&&this.node.router){const t=this.getTopCenter(this);this.node.actions&&1===this.node.actions.length?this.fireCustomEvent(Io.ActionEditRequested,{action:this.node.actions[0],nodeUuid:this.node.uuid,originX:t.x,originY:t.y}):this.fireCustomEvent(Io.NodeEditRequested,{node:this.node,nodeUI:this.ui,originX:t.x,originY:t.y})}}this.nodeClickStartPos=null,this.pendingNodeClick=null}handleAddActionClick(t){t.preventDefault(),t.stopPropagation(),this.fireCustomEvent(Io.AddActionRequested,{nodeUuid:this.node.uuid})}calculateDropIndex(t){var e,i;const o=this.querySelector("temba-sortable-list");if(!o||!this.node.actions)return null!==(i=null===(e=this.node.actions)||void 0===e?void 0:e.length)&&void 0!==i?i:0;const n=Array.from(o.querySelectorAll(".action.sortable:not(.drop-placeholder)"));if(0===n.length)return 0;for(let e=0;e<n.length;e++){const i=n[e].getBoundingClientRect();if(t<i.top+i.height/2)return e}return n.length}handleExternalActionDragOver(t){if("execute_actions"!==this.ui.type)return;const{action:e,sourceNodeUuid:i,actionIndex:o,mouseY:n,actionHeight:s}=t.detail;if(i===this.node.uuid)return;const r=this.calculateDropIndex(n);this.externalDragInfo={action:e,sourceNodeUuid:i,actionIndex:o,dropIndex:r,actionHeight:s||60},this.requestUpdate()}handleExternalActionDragLeave(t){this.externalDragInfo=null,this.requestUpdate()}handleActionShowGhost(t){if(this.querySelector("temba-sortable-list")){const t=document.querySelector(".ghost");t&&(t.style.display="block")}}handleActionHideGhost(t){if(this.querySelector("temba-sortable-list")){const t=document.querySelector(".ghost");t&&(t.style.display="none")}}handleActionShowOriginal(t){const e=this.querySelector("temba-sortable-list");null==e||e.setOriginalVisible(!0),this.showLastActionPlaceholder=!1,this.requestUpdate()}handleActionHideOriginal(t){const e=this.querySelector("temba-sortable-list");null==e||e.setOriginalVisible(!1),1===this.node.actions.length&&(this.showLastActionPlaceholder=!0),this.requestUpdate()}handleExternalActionDrop(t){var e,i,o,n,s,r,a;if("execute_actions"!==this.ui.type)return;const{action:l,sourceNodeUuid:d,actionIndex:c,isCopy:h}=t.detail;if(d===this.node.uuid)return;const u=null!==(n=null!==(i=null===(e=this.externalDragInfo)||void 0===e?void 0:e.dropIndex)&&void 0!==i?i:null===(o=this.node.actions)||void 0===o?void 0:o.length)&&void 0!==n?n:0;this.externalDragInfo=null;const p=Ec();if(!p)return;const m=p.getState().flowDefinition;if(!m)return;const g=m.nodes.find(t=>t.uuid===d);if(!g)return;const f=h?{...l,uuid:Xt()}:l,v=[...this.node.actions];v.splice(u,0,f);const b={...this.node,actions:v};if(null===(s=Ec())||void 0===s||s.getState().updateNode(this.node.uuid,b),h){const t=m.localization;if(t)for(const e of Object.keys(t)){const i=null===(r=t[e])||void 0===r?void 0:r[l.uuid];i&&p.getState().updateLocalization(e,f.uuid,JSON.parse(JSON.stringify(i)))}}if(!h){const t=g.actions.filter((t,e)=>e!==c);if(0===t.length)this.fireCustomEvent(Io.NodeDeleted,{uuid:d});else{const e={...g,actions:t};null===(a=Ec())||void 0===a||a.getState().updateNode(d,e)}}this.requestUpdate(),this.fireCustomEvent(Io.SizeChanged,{uuid:this.node.uuid})}renderTitle(t,e,i,o=!1){var n,s,r,a,l;const d=t.group?null===(n=Wu[t.group])||void 0===n?void 0:n.color:"#aaaaaa",c="terminal"===(null===(s=this.ui)||void 0===s?void 0:s.type);return W`<div class="cn-title" style="background:${d}">
9800
9800
  ${c?W`<div class="title-spacer"></div>`:"execute_actions"===(null===(r=this.ui)||void 0===r?void 0:r.type)||(null===(l=null===(a=this.node)||void 0===a?void 0:a.actions)||void 0===l?void 0:l.length)>1?W`<temba-icon
9801
9801
  class="drag-handle ${this.isReadOnly()?"read-only-hidden":""}"
9802
9802
  name="sort"
@@ -9829,7 +9829,7 @@ background: #ccc;
9829
9829
  </div>`}renderDropPlaceholder(){var t;const e=(null===(t=this.externalDragInfo)||void 0===t?void 0:t.actionHeight)||60;return W`<div
9830
9830
  class="action sortable drop-placeholder"
9831
9831
  style="height: ${e}px; background: #f3f4f6; border: 2px dashed #d1d5db; border-radius: var(--curvature);"
9832
- ></div>`}getLocalizedAction(t){var e,i,o;return this.isTranslating&&this.flowDefinition&&this.languageCode&&this.languageCode!==this.flowDefinition.language?Ru(t,null===(o=null===(i=null===(e=this.flowDefinition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t.uuid]):t}renderAction(t,e,i){var o,n,s,r;const a=ym[e.type],l=this.actionRemovingState.has(e.uuid),d=(null==a?void 0:a.localizable)&&a.localizable.length>0,c=this.isTranslating&&!d,h=this.isTranslating&&(null===(s=null===(n=null===(o=this.flowDefinition)||void 0===o?void 0:o.localization)||void 0===n?void 0:n[this.languageCode])||void 0===s?void 0:s[e.uuid]),u=this.getLocalizedAction(e);if(a){const o=null===(r=this.issuesByAction)||void 0===r?void 0:r.has(e.uuid),n=["action","sortable",e.type,l?"removing":"",d&&this.isTranslating?"localizable":"",h?"has-localization":"",c?"non-localizable":""].filter(Boolean).join(" ");return W`<div class="${n}" id="action-${i}">
9832
+ ></div>`}getLocalizedAction(t){var e,i,o;return this.isTranslating&&this.flowDefinition&&this.languageCode&&this.languageCode!==this.flowDefinition.language?Sc(t,null===(o=null===(i=null===(e=this.flowDefinition)||void 0===e?void 0:e.localization)||void 0===i?void 0:i[this.languageCode])||void 0===o?void 0:o[t.uuid]):t}renderAction(t,e,i){var o,n,s,r;const a=ym[e.type],l=this.actionRemovingState.has(e.uuid),d=(null==a?void 0:a.localizable)&&a.localizable.length>0,c=this.isTranslating&&!d,h=this.isTranslating&&(null===(s=null===(n=null===(o=this.flowDefinition)||void 0===o?void 0:o.localization)||void 0===n?void 0:n[this.languageCode])||void 0===s?void 0:s[e.uuid]),u=this.getLocalizedAction(e);if(a){const o=null===(r=this.issuesByAction)||void 0===r?void 0:r.has(e.uuid),n=["action","sortable",e.type,l?"removing":"",d&&this.isTranslating?"localizable":"",h?"has-localization":"",c?"non-localizable":""].filter(Boolean).join(" ");return W`<div class="${n}" id="action-${i}">
9833
9833
  <div
9834
9834
  class="action-content ${o?"has-issues":""}"
9835
9835
  @mousedown=${t=>!c&&this.handleActionMouseDown(t,e)}
@@ -9864,11 +9864,11 @@ background: #ccc;
9864
9864
  @touchend=${t=>this.handleNodeTouchEnd(t)}
9865
9865
  style="cursor: pointer;"
9866
9866
  >
9867
- ${ku(W`Save as
9867
+ ${hc(W`Save as
9868
9868
  <span class="result-name">${t.result_name}</span>`,`Save as ${t.result_name}`)}
9869
9869
  </div>`:null}
9870
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">
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
9871
+ ${vh(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
9872
9872
  class=${re({category:!0,localizable:u})}
9873
9873
  @mousedown=${t=>this.handleNodeMouseDown(t)}
9874
9874
  @mouseup=${t=>this.handleNodeMouseUp(t)}
@@ -9924,7 +9924,7 @@ background: #ccc;
9924
9924
  ${this.renderRouter(this.node.router,this.ui)}
9925
9925
  ${this.renderCategories(this.node)}
9926
9926
  </div>`:"terminal"===this.ui.type?"":W`<div class="action-exits">
9927
- ${Vc(this.node.exits,t=>t.uuid,t=>this.renderExit(t))}
9927
+ ${vh(this.node.exits,t=>t.uuid,t=>this.renderExit(t))}
9928
9928
  </div>`}
9929
9929
  ${"execute_actions"!==this.ui.type||this.isReadOnly()?"":W`<div
9930
9930
  class="add-action-button"
@@ -9934,10 +9934,10 @@ background: #ccc;
9934
9934
  <temba-icon name="add"></temba-icon>
9935
9935
  </div>`}
9936
9936
  </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
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(nc(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(nc(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
9938
9938
  class="selection-box"
9939
9939
  style="left: ${t}px; top: ${e}px; width: ${i}px; height: ${o}px;"
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`
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=Ec().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&&Ec().getState().removeNodes(t),e.length>0&&Ec().getState().removeStickyNotes(e),this.editor.copiedItemUuids=[]}this.currentDragIsCopy=!1,Ec().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=Ec())||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=rc(o),l=rc(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()),Ec().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=rc(o),l=rc(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&&(Ec().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`
9941
9941
  .tab.hidden {
9942
9942
  transform: translateX(calc(100% + var(--floating-tab-clip, 0px)));
9943
9943
  }
@@ -10839,7 +10839,7 @@ background: #ccc;
10839
10839
  animation-timing-function: linear;
10840
10840
  animation-fill-mode: forwards;
10841
10841
  }
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">
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=Ec())||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&&Ec().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):Ec().getState().updateConnection(this.dragFromNodeId,this.sourceId,this.targetId);else if(this.connectionPlaceholder&&this.connectionPlaceholder.visible&&this.sourceId){const t={left:rc(this.connectionPlaceholder.position.left),top:rc(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:Ru}}}saveChanges(t){const e=this.definitionForSave(t||this.definition);this.isSaving=!0;const i=Ec().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=Ec().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)}Ec().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=Ec();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:ic(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=>{const e="string"==typeof t?t:t.iso||t.code;return{code:e,name:ic(e)}}):[]}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=Ec())||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&&Ec().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=rc(Math.max(0,d)),h=rc(Math.max(0,h));let u=50;for(;u-- >0&&Dm(d,h,e.width,e.height,c);)h=rc(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,Ec().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&&Ec().getState().removeNodes(t),e.length>0&&(this.pendingTimer.pending=!0,Ec().getState().removeStickyNotes(e)),this.copiedItemUuids=[]}this.pendingPositions&&(this.pendingTimer.pending=!0,Ec().getState().updateCanvasPositions(this.pendingPositions),this.pendingPositions=null),setTimeout(()=>{Ec().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">
10843
10843
  <div class="reflow-top">
10844
10844
  <span class="reflow-label">${this.pendingTimer.label}</span>
10845
10845
  <button class="reflow-discard" @click=${this.handlePendingDiscard}>
@@ -10859,7 +10859,7 @@ background: #ccc;
10859
10859
  }
10860
10860
  }
10861
10861
  </style>
10862
- </div>`}deleteNodes(t){t.length>0&&$d().getState().removeNodes(t)}deleteSelectedItems(){const t=Array.from(this.selectedItems).filter(t=>this.definition.nodes.some(e=>e.uuid===t));this.deleteNodes(Array.from(t));const e=Array.from(this.selectedItems).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]});$d().getState().removeStickyNotes(e),this.selectedItems.clear()}renderCanvasDropPreview(){var t;if(!this.canvasDropPreview)return"";const{action:e,position:i}=this.canvasDropPreview,o=ym[e.type];return o?W`<div
10862
+ </div>`}deleteNodes(t){t.length>0&&Ec().getState().removeNodes(t)}deleteSelectedItems(){const t=Array.from(this.selectedItems).filter(t=>this.definition.nodes.some(e=>e.uuid===t));this.deleteNodes(Array.from(t));const e=Array.from(this.selectedItems).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]});Ec().getState().removeStickyNotes(e),this.selectedItems.clear()}renderCanvasDropPreview(){var t;if(!this.canvasDropPreview)return"";const{action:e,position:i}=this.canvasDropPreview,o=ym[e.type];return o?W`<div
10863
10863
  class="canvas-drop-preview"
10864
10864
  style="position: absolute; left: ${i.left}px; top: ${i.top}px; opacity: 0.6; pointer-events: none; z-index: 10000;"
10865
10865
  >
@@ -10919,7 +10919,7 @@ background: #ccc;
10919
10919
  </div>
10920
10920
  </div>
10921
10921
  </div>
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`
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=xc(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=xc(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)&&wc(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)||wc(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))&&wc(e,s)&&d.push(s);if(0===d.length)continue;const c=d.filter(t=>o.has(t.uuid)),h=[..._c];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=Cc(e,d,i);if(!s)continue;const r=kc(e,s.left,s.top);let l=!1,h=0;for(const[e,i]of n)if(e!==t&&wc(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=kc(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)||wc(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;Ec().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=Ec();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=rc(n),a=rc(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=Ec();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=Ec(),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=Ec())||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=Ec(),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=Ec())||void 0===o||o.getState().updateNode(this.editingNode.uuid,t),e&&(null===(n=Ec())||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:rc(s),top:rc(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=Ec())||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=Ec())||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=Ec())||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),Ec().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?ic(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`
10923
10923
  <temba-editor-toolbar
10924
10924
  ?message-view=${this.showMessageTable}
10925
10925
  .zoom=${this.zoom}
@@ -10994,7 +10994,7 @@ background: #ccc;
10994
10994
  id="canvas"
10995
10995
  class="${re({"viewing-revision":this.viewingRevision,"read-only-connections":this.viewingRevision||this.isTranslating})}"
10996
10996
  >
10997
- ${this.definition&&!s?Vc([...this.definition.nodes].sort((t,e)=>t.uuid.localeCompare(e.uuid)),t=>t.uuid,t=>{var e,i,o;const n=(null===(e=this.definition._ui)||void 0===e?void 0:e.nodes[t.uuid])||{position:{left:0,top:0},type:(null===(i=t.router)||void 0===i?void 0:i.wait)?"wait_for_response":"execute_actions"},s=n.position,r=this.isDragging&&(null===(o=this.currentDragItem)||void 0===o?void 0:o.uuid)===t.uuid,a=this.selectedItems.has(t.uuid),l=this.definition.nodes.length>0&&this.definition.nodes[0].uuid===t.uuid;return W`<temba-flow-node
10997
+ ${this.definition&&!s?vh([...this.definition.nodes].sort((t,e)=>t.uuid.localeCompare(e.uuid)),t=>t.uuid,t=>{var e,i,o;const n=(null===(e=this.definition._ui)||void 0===e?void 0:e.nodes[t.uuid])||{position:{left:0,top:0},type:(null===(i=t.router)||void 0===i?void 0:i.wait)?"wait_for_response":"execute_actions"},s=n.position,r=this.isDragging&&(null===(o=this.currentDragItem)||void 0===o?void 0:o.uuid)===t.uuid,a=this.selectedItems.has(t.uuid),l=this.definition.nodes.length>0&&this.definition.nodes[0].uuid===t.uuid;return W`<temba-flow-node
10998
10998
  class="draggable ${r?"dragging":""} ${a?"selected":""} ${l?"flow-start":""}"
10999
10999
  @mousedown=${t=>this.dragManager.handleMouseDown(t)}
11000
11000
  @touchstart=${t=>this.dragManager.handleItemTouchStart(t)}
@@ -11006,7 +11006,7 @@ background: #ccc;
11006
11006
  .ui=${n}
11007
11007
  @temba-node-deleted=${t=>{this.deleteNodes([t.detail.uuid])}}
11008
11008
  ></temba-flow-node>`}):s?"":W`<temba-loading></temba-loading>`}
11009
- ${Vc(Object.entries(n),([t])=>t,([t,e])=>{var i;const o=e.position||{left:0,top:0},n=this.isDragging&&(null===(i=this.currentDragItem)||void 0===i?void 0:i.uuid)===t,s=this.selectedItems.has(t);return W`<temba-sticky-note
11009
+ ${vh(Object.entries(n),([t])=>t,([t,e])=>{var i;const o=e.position||{left:0,top:0},n=this.isDragging&&(null===(i=this.currentDragItem)||void 0===i?void 0:i.uuid)===t,s=this.selectedItems.has(t);return W`<temba-sticky-note
11010
11010
  class="draggable ${n?"dragging":""} ${s?"selected":""}"
11011
11011
  @mousedown=${t=>this.dragManager.handleMouseDown(t)}
11012
11012
  @touchstart=${t=>this.dragManager.handleItemTouchStart(t)}
@@ -11428,7 +11428,7 @@ background: #ccc;
11428
11428
  .color-option.gray {
11429
11429
  background-color: #f3f4f6;
11430
11430
  }
11431
- `}updated(t){super.updated(t),(t.has("data")||t.has("uuid"))&&this.updateCanvasSize()}updateCanvasSize(){if(!this.data)return;const t=this.querySelector(".sticky-note");if(t){const e=t.getBoundingClientRect();$d().getState().expandCanvas(this.data.position.left+e.width,this.data.position.top+e.height)}}handleTitleBlur(t){this.handleContentBlurForTouch(t);const e=t.target.textContent||"";this.data&&e!==this.data.title&&($d().getState().updateStickyNote(this.uuid,{...this.data,title:e}),this.fireCustomEvent(Io.SizeChanged,{uuid:this.uuid})),this.requestUpdate()}handleBodyBlur(t){this.handleContentBlurForTouch(t);const e=t.target.innerText||"";this.data&&e!==this.data.body&&($d().getState().updateStickyNote(this.uuid,{...this.data,body:e}),this.fireCustomEvent(Io.SizeChanged,{uuid:this.uuid})),this.requestUpdate()}handleDragHandleTouchStart(t){t.preventDefault()}handleContentTap(t){if(!this.isTouchDevice)return;const e=t.target;(e.classList.contains("sticky-title")||e.classList.contains("sticky-body"))&&(e.setAttribute("contenteditable","true"),this.editingField=e,e.focus(),t.stopPropagation())}handleContentBlurForTouch(t){const e=t.target;this.isTouchDevice&&this.editingField===e&&(e.setAttribute("contenteditable","false"),this.editingField=null)}handleContentMouseDown(t){fu(t)?t.preventDefault():this.selected||t.stopPropagation()}handleTitleKeyDown(t){"Enter"===t.key&&(t.preventDefault(),t.target.blur()),"Escape"===t.key&&t.target.blur()}handleBodyKeyDown(t){"Enter"!==t.key||t.shiftKey||(t.preventDefault(),t.target.blur()),"Escape"===t.key&&t.target.blur()}handleColorPickerMouseEnter(){this.colorPickerExpanded=!0}handleColorPickerMouseLeave(){this.colorPickerExpanded=!1}handleColorPickerTap(t){t.stopPropagation(),t.preventDefault(),this.colorPickerExpanded=!this.colorPickerExpanded}handleColorOptionClick(t,e){t.stopPropagation(),t.preventDefault(),this.data&&e!==this.data.color&&$d().getState().updateStickyNote(this.uuid,{...this.data,color:e}),this.colorPickerExpanded=!1,this.requestUpdate()}handleRemoveClick(t){if(t.preventDefault(),t.stopPropagation(),this.removing)return this.resetRemovingState(),void this.fireCustomEvent(Io.StickyNoteDeleted,{uuid:this.uuid});const e=this.shadowRoot.querySelector(".sticky-title-container");e&&(e.style.minHeight=e.offsetHeight+"px",e.style.boxSizing="border-box"),this.removing=!0,null!==this.removalTimeout&&clearTimeout(this.removalTimeout),this.removalTimeout=window.setTimeout(()=>{this.resetRemovingState()},1e3)}resetRemovingState(){var t;this.removing=!1;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".sticky-title-container");e&&(e.style.minHeight="",e.style.boxSizing=""),null!==this.removalTimeout&&(clearTimeout(this.removalTimeout),this.removalTimeout=null)}disconnectedCallback(){super.disconnectedCallback(),this.resetRemovingState(),this.cleanupResize()}startResize(t,e){const i=this.shadowRoot.querySelector(".sticky-note");if(!i)return;this.resizeStartX=t,this.resizeStartY=e,this.resizeStartWidth=i.offsetWidth,this.resizeStartHeight=i.offsetHeight;const o=i.getBoundingClientRect();this.resizeZoom=o.width/i.offsetWidth,this.resizing=!0,i.classList.add("resizing"),document.body.style.userSelect="none"}applyResize(t,e){const i=this.shadowRoot.querySelector(".sticky-note");if(!i)return;const o=(t-this.resizeStartX)/this.resizeZoom,n=(e-this.resizeStartY)/this.resizeZoom,s=Math.max(this.resizeStartWidth+o,200),r=Math.max(this.resizeStartHeight+n,80);i.style.setProperty("--sticky-width",`${s}px`),i.style.minHeight=`${r}px`}finishResize(t,e){const i=this.shadowRoot.querySelector(".sticky-note");if(!i)return;const o=(t-this.resizeStartX)/this.resizeZoom,n=(e-this.resizeStartY)/this.resizeZoom;let s=Math.max(this.resizeStartWidth+o,200),r=Math.max(this.resizeStartHeight+n,80);s=Math.max(s,i.scrollWidth),r=Math.max(r,i.scrollHeight),this.cleanupResize(),$d().getState().updateStickyNote(this.uuid,{...this.data,width:Math.round(s),height:Math.round(r)}),this.updateCanvasSize(),this.fireCustomEvent(Io.SizeChanged,{uuid:this.uuid})}cleanupResize(){var t;if(!this.resizing)return;this.resizing=!1;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".sticky-note");e&&e.classList.remove("resizing"),document.body.style.userSelect="",document.removeEventListener("mousemove",this.boundResizeMove),document.removeEventListener("mouseup",this.boundResizeEnd),document.removeEventListener("touchmove",this.boundResizeTouchMove),document.removeEventListener("touchend",this.boundResizeTouchEnd)}handleResizeStart(t){t.preventDefault(),t.stopPropagation(),this.startResize(t.clientX,t.clientY),document.addEventListener("mousemove",this.boundResizeMove),document.addEventListener("mouseup",this.boundResizeEnd)}handleResizeMove(t){this.resizing&&this.applyResize(t.clientX,t.clientY)}handleResizeEnd(t){this.resizing&&this.finishResize(t.clientX,t.clientY)}handleResizeTouchStart(t){t.preventDefault(),t.stopPropagation();const e=t.touches[0];e&&(this.startResize(e.clientX,e.clientY),document.addEventListener("touchmove",this.boundResizeTouchMove,{passive:!1}),document.addEventListener("touchend",this.boundResizeTouchEnd))}handleResizeTouchMove(t){if(!this.resizing)return;t.preventDefault();const e=t.touches[0];e&&this.applyResize(e.clientX,e.clientY)}handleResizeTouchEnd(t){if(!this.resizing)return;const e=t.changedTouches[0];e&&this.finishResize(e.clientX,e.clientY)}render(){if(!this.data)return W`<div class="sticky-note" style="display: none;"></div>`;const t=this.data.width?`--sticky-width: ${this.data.width}px;`:"",e=this.data.height?`min-height: ${this.data.height}px;`:"",i=`left: ${this.data.position.left}px; top: ${this.data.position.top}px; ${t} ${e}`;return W`
11431
+ `}updated(t){super.updated(t),(t.has("data")||t.has("uuid"))&&this.updateCanvasSize()}updateCanvasSize(){if(!this.data)return;const t=this.querySelector(".sticky-note");if(t){const e=t.getBoundingClientRect();Ec().getState().expandCanvas(this.data.position.left+e.width,this.data.position.top+e.height)}}handleTitleBlur(t){this.handleContentBlurForTouch(t);const e=t.target.textContent||"";this.data&&e!==this.data.title&&(Ec().getState().updateStickyNote(this.uuid,{...this.data,title:e}),this.fireCustomEvent(Io.SizeChanged,{uuid:this.uuid})),this.requestUpdate()}handleBodyBlur(t){this.handleContentBlurForTouch(t);const e=t.target.innerText||"";this.data&&e!==this.data.body&&(Ec().getState().updateStickyNote(this.uuid,{...this.data,body:e}),this.fireCustomEvent(Io.SizeChanged,{uuid:this.uuid})),this.requestUpdate()}handleDragHandleTouchStart(t){t.preventDefault()}handleContentTap(t){if(!this.isTouchDevice)return;const e=t.target;(e.classList.contains("sticky-title")||e.classList.contains("sticky-body"))&&(e.setAttribute("contenteditable","true"),this.editingField=e,e.focus(),t.stopPropagation())}handleContentBlurForTouch(t){const e=t.target;this.isTouchDevice&&this.editingField===e&&(e.setAttribute("contenteditable","false"),this.editingField=null)}handleContentMouseDown(t){nc(t)?t.preventDefault():this.selected||t.stopPropagation()}handleTitleKeyDown(t){"Enter"===t.key&&(t.preventDefault(),t.target.blur()),"Escape"===t.key&&t.target.blur()}handleBodyKeyDown(t){"Enter"!==t.key||t.shiftKey||(t.preventDefault(),t.target.blur()),"Escape"===t.key&&t.target.blur()}handleColorPickerMouseEnter(){this.colorPickerExpanded=!0}handleColorPickerMouseLeave(){this.colorPickerExpanded=!1}handleColorPickerTap(t){t.stopPropagation(),t.preventDefault(),this.colorPickerExpanded=!this.colorPickerExpanded}handleColorOptionClick(t,e){t.stopPropagation(),t.preventDefault(),this.data&&e!==this.data.color&&Ec().getState().updateStickyNote(this.uuid,{...this.data,color:e}),this.colorPickerExpanded=!1,this.requestUpdate()}handleRemoveClick(t){if(t.preventDefault(),t.stopPropagation(),this.removing)return this.resetRemovingState(),void this.fireCustomEvent(Io.StickyNoteDeleted,{uuid:this.uuid});const e=this.shadowRoot.querySelector(".sticky-title-container");e&&(e.style.minHeight=e.offsetHeight+"px",e.style.boxSizing="border-box"),this.removing=!0,null!==this.removalTimeout&&clearTimeout(this.removalTimeout),this.removalTimeout=window.setTimeout(()=>{this.resetRemovingState()},1e3)}resetRemovingState(){var t;this.removing=!1;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".sticky-title-container");e&&(e.style.minHeight="",e.style.boxSizing=""),null!==this.removalTimeout&&(clearTimeout(this.removalTimeout),this.removalTimeout=null)}disconnectedCallback(){super.disconnectedCallback(),this.resetRemovingState(),this.cleanupResize()}startResize(t,e){const i=this.shadowRoot.querySelector(".sticky-note");if(!i)return;this.resizeStartX=t,this.resizeStartY=e,this.resizeStartWidth=i.offsetWidth,this.resizeStartHeight=i.offsetHeight;const o=i.getBoundingClientRect();this.resizeZoom=o.width/i.offsetWidth,this.resizing=!0,i.classList.add("resizing"),document.body.style.userSelect="none"}applyResize(t,e){const i=this.shadowRoot.querySelector(".sticky-note");if(!i)return;const o=(t-this.resizeStartX)/this.resizeZoom,n=(e-this.resizeStartY)/this.resizeZoom,s=Math.max(this.resizeStartWidth+o,200),r=Math.max(this.resizeStartHeight+n,80);i.style.setProperty("--sticky-width",`${s}px`),i.style.minHeight=`${r}px`}finishResize(t,e){const i=this.shadowRoot.querySelector(".sticky-note");if(!i)return;const o=(t-this.resizeStartX)/this.resizeZoom,n=(e-this.resizeStartY)/this.resizeZoom;let s=Math.max(this.resizeStartWidth+o,200),r=Math.max(this.resizeStartHeight+n,80);s=Math.max(s,i.scrollWidth),r=Math.max(r,i.scrollHeight),this.cleanupResize(),Ec().getState().updateStickyNote(this.uuid,{...this.data,width:Math.round(s),height:Math.round(r)}),this.updateCanvasSize(),this.fireCustomEvent(Io.SizeChanged,{uuid:this.uuid})}cleanupResize(){var t;if(!this.resizing)return;this.resizing=!1;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".sticky-note");e&&e.classList.remove("resizing"),document.body.style.userSelect="",document.removeEventListener("mousemove",this.boundResizeMove),document.removeEventListener("mouseup",this.boundResizeEnd),document.removeEventListener("touchmove",this.boundResizeTouchMove),document.removeEventListener("touchend",this.boundResizeTouchEnd)}handleResizeStart(t){t.preventDefault(),t.stopPropagation(),this.startResize(t.clientX,t.clientY),document.addEventListener("mousemove",this.boundResizeMove),document.addEventListener("mouseup",this.boundResizeEnd)}handleResizeMove(t){this.resizing&&this.applyResize(t.clientX,t.clientY)}handleResizeEnd(t){this.resizing&&this.finishResize(t.clientX,t.clientY)}handleResizeTouchStart(t){t.preventDefault(),t.stopPropagation();const e=t.touches[0];e&&(this.startResize(e.clientX,e.clientY),document.addEventListener("touchmove",this.boundResizeTouchMove,{passive:!1}),document.addEventListener("touchend",this.boundResizeTouchEnd))}handleResizeTouchMove(t){if(!this.resizing)return;t.preventDefault();const e=t.touches[0];e&&this.applyResize(e.clientX,e.clientY)}handleResizeTouchEnd(t){if(!this.resizing)return;const e=t.changedTouches[0];e&&this.finishResize(e.clientX,e.clientY)}render(){if(!this.data)return W`<div class="sticky-note" style="display: none;"></div>`;const t=this.data.width?`--sticky-width: ${this.data.width}px;`:"",e=this.data.height?`min-height: ${this.data.height}px;`:"",i=`left: ${this.data.position.left}px; top: ${this.data.position.top}px; ${t} ${e}`;return W`
11432
11432
  <div
11433
11433
  class="sticky-note ${this.data.color} ${this.dragging?"dragging":""} ${this.removing?"removing":""} ${this.selected?"selected":""}"
11434
11434
  style="${i}"
@@ -11833,7 +11833,7 @@ background: #ccc;
11833
11833
  ></temba-button>
11834
11834
  </div>
11835
11835
  </div>
11836
- `}}t([mt({type:Boolean,reflect:!0})],jm.prototype,"open",void 0),t([mt({type:String})],jm.prototype,"mode",void 0),t([mt({type:String})],jm.prototype,"flowType",void 0),t([mt({type:Array})],jm.prototype,"features",void 0),t([gt()],jm.prototype,"clickPosition",void 0),t([gt()],jm.prototype,"searchQuery",void 0),t([gt()],jm.prototype,"highlightedIndex",void 0);class Hm extends Pc{constructor(){super(...arguments),this.dirtyMessage="You have unsaved changes to the contact notepad. Are you sure you want to contiunue?"}static get styles(){return a`
11836
+ `}}t([mt({type:Boolean,reflect:!0})],jm.prototype,"open",void 0),t([mt({type:String})],jm.prototype,"mode",void 0),t([mt({type:String})],jm.prototype,"flowType",void 0),t([mt({type:Array})],jm.prototype,"features",void 0),t([gt()],jm.prototype,"clickPosition",void 0),t([gt()],jm.prototype,"searchQuery",void 0),t([gt()],jm.prototype,"highlightedIndex",void 0);class Hm extends ah{constructor(){super(...arguments),this.dirtyMessage="You have unsaved changes to the contact notepad. Are you sure you want to contiunue?"}static get styles(){return a`
11837
11837
  :host {
11838
11838
  height: 100%;
11839
11839
  display: flex;
@@ -12073,7 +12073,7 @@ background: #ccc;
12073
12073
  temba-icon[name='close']:hover {
12074
12074
  color: var(--color-primary-dark);
12075
12075
  }
12076
- `,t([mt({type:String})],Vm.prototype,"id",void 0),t([mt({type:Number})],Vm.prototype,"current",void 0),t([mt({type:Number})],Vm.prototype,"total",void 0),t([mt({type:Number})],Vm.prototype,"refreshes",void 0),t([mt({type:String})],Vm.prototype,"eta",void 0),t([mt({type:Boolean})],Vm.prototype,"complete",void 0),t([mt({type:Boolean})],Vm.prototype,"running",void 0),t([mt({type:String})],Vm.prototype,"message",void 0),t([mt({type:String})],Vm.prototype,"statusEndpoint",void 0),t([mt({type:String})],Vm.prototype,"interruptTitle",void 0),t([mt({type:String})],Vm.prototype,"interruptEndpoint",void 0);class Zm extends Lc{static get styles(){return a`
12076
+ `,t([mt({type:String})],Vm.prototype,"id",void 0),t([mt({type:Number})],Vm.prototype,"current",void 0),t([mt({type:Number})],Vm.prototype,"total",void 0),t([mt({type:Number})],Vm.prototype,"refreshes",void 0),t([mt({type:String})],Vm.prototype,"eta",void 0),t([mt({type:Boolean})],Vm.prototype,"complete",void 0),t([mt({type:Boolean})],Vm.prototype,"running",void 0),t([mt({type:String})],Vm.prototype,"message",void 0),t([mt({type:String})],Vm.prototype,"statusEndpoint",void 0),t([mt({type:String})],Vm.prototype,"interruptTitle",void 0),t([mt({type:String})],Vm.prototype,"interruptEndpoint",void 0);class Zm extends sh{static get styles(){return a`
12077
12077
  temba-options {
12078
12078
  display: block;
12079
12079
  width: 100%;
@@ -12193,7 +12193,7 @@ background: #ccc;
12193
12193
  --color-widget-border: transparent;
12194
12194
  --widget-box-shadow: none;
12195
12195
  }
12196
- `,t([mt({type:String})],Ym.prototype,"placeholder",void 0),t([mt({type:String})],Ym.prototype,"endpoint",void 0);class Km extends gc{static get styles(){return a`
12196
+ `,t([mt({type:String})],Ym.prototype,"placeholder",void 0),t([mt({type:String})],Ym.prototype,"endpoint",void 0);class Km extends Fc{static get styles(){return a`
12197
12197
  ${super.styles}
12198
12198
 
12199
12199
  :host {
@@ -12205,7 +12205,7 @@ background: #ccc;
12205
12205
  name=${t.name}
12206
12206
  avatar=${t.avatar}
12207
12207
  showname
12208
- ></temba-user>`:W``}}t([mt({type:String})],Km.prototype,"endpoint",void 0),t([mt({type:String})],Km.prototype,"nameKey",void 0),t([mt({type:String})],Km.prototype,"valueKey",void 0),t([mt({type:String})],Km.prototype,"placeholder",void 0),t([mt({type:Boolean})],Km.prototype,"sorted",void 0),t([mt({type:Object})],Km.prototype,"user",void 0);class Gm extends gc{static get styles(){return a`
12208
+ ></temba-user>`:W``}}t([mt({type:String})],Km.prototype,"endpoint",void 0),t([mt({type:String})],Km.prototype,"nameKey",void 0),t([mt({type:String})],Km.prototype,"valueKey",void 0),t([mt({type:String})],Km.prototype,"placeholder",void 0),t([mt({type:Boolean})],Km.prototype,"sorted",void 0),t([mt({type:Object})],Km.prototype,"user",void 0);class Gm extends Fc{static get styles(){return a`
12209
12209
  ${super.styles}
12210
12210
 
12211
12211
  :host {
@@ -12285,7 +12285,7 @@ var $_=function(){if("undefined"!=typeof window){if(window.devicePixelRatio)retu
12285
12285
  padding: 2em 1em 1.5em 1em;
12286
12286
  max-height: 50px;
12287
12287
  }
12288
- `}constructor(){super(),this.chartType="bar",this.horizontal=!1,this.header="",this.other=!1,this.datasets=[],this.maxSplits=2,this.xType="category",this.xMaxTicks=10,this.yType="count",this.xFormat="auto",this.maxChartHeight=250,this.hideOther=!1,this.splits=[],this.dataname="Counts",this.single=!1,this.legend=!1,this.config=!1,this.showAll=!1,this.requireWindow=!1,this.colorIndex=0,this.showConfig=!1,this.opacity=1,this.seriesBorderRadius=2,this.seriesBorderWidth=1,this.showPercent=!1}firstUpdated(t){super.firstUpdated(t);const e=this.shadowRoot.querySelector("#canvas-wrapper");this.canvas=document.createElement("canvas"),this.canvas.setAttribute("height","300px"),e.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d")}willUpdate(t){super.willUpdate(t),t.has("splitNames")&&(this.splits=this.splitNames.split(",").map(t=>t.trim())),(t.has("data")||t.has("splits"))&&this.calculateSplits()}updated(t){if(super.updated(t),t.has("datasets")&&this.updateChart(),t.has("horizontal")&&this.updateChart(),(t.has("url")||t.has("start")||t.has("end"))&&this.url&&(!this.requireWindow||this.start&&this.end)){const t=$d();let e=this.url;const i=new URLSearchParams;if(this.start&&i.append("since",this.start),this.end&&i.append("until",this.end),i.toString()){const t=this.url.includes("?")?"&":"?";e=`${this.url}${t}${i.toString()}`}t.getUrl(e,{skipCache:!0}).then(t=>{this.data=t.json.data})}if(t.has("chartType")&&"line"===this.chartType&&(this.seriesBorderWidth=Math.max(1,this.seriesBorderWidth)),t.has("showPercent")&&this.chart){const t=this.horizontal?this.chart.options.scales.x:this.chart.options.scales.y;t.ticks.display=!this.showPercent,t.grid.display=!this.showPercent,t.border.display=!this.showPercent,t.max=this.showPercent?this.getInflatedMax():void 0,this.chart.update()}}get colors(){const t=rk[this.palette]||rk["qualitative-set1"],e=Math.max(0,Math.min(1,this.opacity)),i=t.map(t=>Ee(t,.25)),o=t.map(t=>{if(t.startsWith("rgba"))return t.replace(/rgba\(([^,]+),([^,]+),([^,]+),([^)]+)\)/,(t,i,o,n)=>`rgba(${i},${o},${n},${e})`);if(t.startsWith("rgb("))return t.replace(/rgb\(([^,]+),([^,]+),([^,]+)\)/,(t,i,o,n)=>`rgba(${i},${o},${n},${e})`);if(t.startsWith("#")){let i=t.replace("#","");3===i.length&&(i=i.split("").map(t=>t+t).join(""));const o=parseInt(i,16);return`rgba(${o>>16&255},${o>>8&255},${255&o},${e})`}return t});return[o,i]}handleResize(){if(this.chart){const t=this.shadowRoot.querySelector("#canvas-wrapper");t&&t.clientHeight>this.maxChartHeight&&(this.canvas.style.height=`${this.maxChartHeight}px`,this.chart.resize())}}calculateSplits(){if(this.data){const t=[],e=[],[i,o]=this.colors;for(const n of this.data.datasets)if(this.showAll||void 0!==this.splits.find(t=>t===n.label)){const e=(t.length+this.colorIndex)%i.length,s=i[e],r=o[e];t.push({...n,backgroundColor:s,borderColor:r,borderWidth:this.seriesBorderWidth,borderRadius:this.seriesBorderRadius})}else for(let t=0;t<n.data.length;t++)void 0===e[t]?e[t]=n.data[t]:e[t]+=n.data[t];if(0===t.length){const n=this.colorIndex%i.length;t.push({label:this.single?this.dataname:`All ${this.dataname}`,data:e,backgroundColor:i[n],borderColor:o[n],borderWidth:this.seriesBorderWidth,borderRadius:this.seriesBorderRadius})}else this.hideOther||this.showAll||t.push({label:"Other",data:e,backgroundColor:ak,borderColor:Ee(ak,.05),borderWidth:1,borderRadius:this.seriesBorderRadius});this.datasets=t}}updateChart(){var t;if((null===(t=this.datasets)||void 0===t?void 0:t.length)>0){const t=this.datasets.reduce((t,e)=>t+e.data.reduce((t,e)=>t+(null!=e?e:0),0),0)||void 0,e=e=>{const i=t?e/t*100:0;return 0===i?"":`${Math.round(i)}%`};if(this.chart){this.chart.data.labels=this.data.labels,this.chart.data.datasets=this.datasets,this.showPercent&&(this.chart.options.scales.y.max=this.getInflatedMax());const t=this.chart.options.plugins.datalabels||{};t.display=this.showPercent,this.showPercent?t.formatter=e:delete t.formatter,this.chart.options.plugins.datalabels=t,this.horizontal?(this.chart.options.scales.x=this.getValueAxisConfig(),this.chart.options.scales.y=this.getCategoryAxisConfig()):(this.chart.options.scales.x=this.getCategoryAxisConfig(),this.chart.options.scales.y=this.getValueAxisConfig()),this.chart.update()}else{const t={type:this.chartType,data:{labels:this.data.labels,datasets:this.datasets},options:{...this.horizontal&&{indexAxis:"y"},maxBarThickness:80,plugins:{legend:{display:this.legend},tooltip:{callbacks:{label:t=>{const e=t.dataset.label||"",i=this.horizontal?t.parsed.x:t.parsed.y;return"duration"===this.yType?`${e}: ${lk(i)}`:`${e}: ${i}`}}},datalabels:{display:this.showPercent,anchor:"end",align:"end",offset:-3,clamp:!0,...this.showPercent&&{formatter:e},color:"#666",font:{weight:"600"}}},responsive:!0,aspectRatio:2,onResize:this.handleResize.bind(this),maintainAspectRatio:!1,animation:!1,animations:{x:{duration:0},y:{duration:0}},scales:this.horizontal?{x:this.getValueAxisConfig(),y:this.getCategoryAxisConfig()}:{y:this.getValueAxisConfig(),x:this.getCategoryAxisConfig()}}};this.chart=new Cx(this.ctx,t)}}}handleSplitsChanged(t){const e=t.target;this.splits=e.values.map(t=>t.value)}handleToggleConfig(){this.showConfig=!this.showConfig,this.showConfig||(this.splits=[])}getValueAxisConfig(){return{min:0,...this.showPercent&&{max:this.getInflatedMax()},stacked:!0,grid:{color:"rgba(0,0,0,0.04)",display:!this.showPercent,drawBorder:!this.showPercent},border:{display:!this.showPercent},ticks:{display:!this.showPercent,..."duration"===this.yType&&!this.showPercent&&{callback:t=>lk(t)}}}}getCategoryAxisConfig(){let t=this.xFormat;if("time"===this.xType&&"auto"===this.xFormat){const e=this.data.labels[0],i=this.data.labels[this.data.labels.length-1],o=Date.parse(e),n=Date.parse(i);t="MMM dd",Math.ceil((n-o)/864e5)>365&&(t="MMM yyyy")}return{max:"time"===this.xType?this.end:this.xMaxTicks,min:"time"===this.xType?this.start:0,type:this.xType,grid:{display:!1},stacked:!0,ticks:{maxTicksLimit:this.xMaxTicks},..."time"===this.xType&&{time:{unit:"day",tooltipFormat:"DDD",displayFormats:{day:t}}}}}render(){var t,e,i;return W`<div>
12288
+ `}constructor(){super(),this.chartType="bar",this.horizontal=!1,this.header="",this.other=!1,this.datasets=[],this.maxSplits=2,this.xType="category",this.xMaxTicks=10,this.yType="count",this.xFormat="auto",this.maxChartHeight=250,this.hideOther=!1,this.splits=[],this.dataname="Counts",this.single=!1,this.legend=!1,this.config=!1,this.showAll=!1,this.requireWindow=!1,this.colorIndex=0,this.showConfig=!1,this.opacity=1,this.seriesBorderRadius=2,this.seriesBorderWidth=1,this.showPercent=!1}firstUpdated(t){super.firstUpdated(t);const e=this.shadowRoot.querySelector("#canvas-wrapper");this.canvas=document.createElement("canvas"),this.canvas.setAttribute("height","300px"),e.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d")}willUpdate(t){super.willUpdate(t),t.has("splitNames")&&(this.splits=this.splitNames.split(",").map(t=>t.trim())),(t.has("data")||t.has("splits"))&&this.calculateSplits()}updated(t){if(super.updated(t),t.has("datasets")&&this.updateChart(),t.has("horizontal")&&this.updateChart(),(t.has("url")||t.has("start")||t.has("end"))&&this.url&&(!this.requireWindow||this.start&&this.end)){const t=Ec();let e=this.url;const i=new URLSearchParams;if(this.start&&i.append("since",this.start),this.end&&i.append("until",this.end),i.toString()){const t=this.url.includes("?")?"&":"?";e=`${this.url}${t}${i.toString()}`}t.getUrl(e,{skipCache:!0}).then(t=>{this.data=t.json.data})}if(t.has("chartType")&&"line"===this.chartType&&(this.seriesBorderWidth=Math.max(1,this.seriesBorderWidth)),t.has("showPercent")&&this.chart){const t=this.horizontal?this.chart.options.scales.x:this.chart.options.scales.y;t.ticks.display=!this.showPercent,t.grid.display=!this.showPercent,t.border.display=!this.showPercent,t.max=this.showPercent?this.getInflatedMax():void 0,this.chart.update()}}get colors(){const t=rk[this.palette]||rk["qualitative-set1"],e=Math.max(0,Math.min(1,this.opacity)),i=t.map(t=>Ee(t,.25)),o=t.map(t=>{if(t.startsWith("rgba"))return t.replace(/rgba\(([^,]+),([^,]+),([^,]+),([^)]+)\)/,(t,i,o,n)=>`rgba(${i},${o},${n},${e})`);if(t.startsWith("rgb("))return t.replace(/rgb\(([^,]+),([^,]+),([^,]+)\)/,(t,i,o,n)=>`rgba(${i},${o},${n},${e})`);if(t.startsWith("#")){let i=t.replace("#","");3===i.length&&(i=i.split("").map(t=>t+t).join(""));const o=parseInt(i,16);return`rgba(${o>>16&255},${o>>8&255},${255&o},${e})`}return t});return[o,i]}handleResize(){if(this.chart){const t=this.shadowRoot.querySelector("#canvas-wrapper");t&&t.clientHeight>this.maxChartHeight&&(this.canvas.style.height=`${this.maxChartHeight}px`,this.chart.resize())}}calculateSplits(){if(this.data){const t=[],e=[],[i,o]=this.colors;for(const n of this.data.datasets)if(this.showAll||void 0!==this.splits.find(t=>t===n.label)){const e=(t.length+this.colorIndex)%i.length,s=i[e],r=o[e];t.push({...n,backgroundColor:s,borderColor:r,borderWidth:this.seriesBorderWidth,borderRadius:this.seriesBorderRadius})}else for(let t=0;t<n.data.length;t++)void 0===e[t]?e[t]=n.data[t]:e[t]+=n.data[t];if(0===t.length){const n=this.colorIndex%i.length;t.push({label:this.single?this.dataname:`All ${this.dataname}`,data:e,backgroundColor:i[n],borderColor:o[n],borderWidth:this.seriesBorderWidth,borderRadius:this.seriesBorderRadius})}else this.hideOther||this.showAll||t.push({label:"Other",data:e,backgroundColor:ak,borderColor:Ee(ak,.05),borderWidth:1,borderRadius:this.seriesBorderRadius});this.datasets=t}}updateChart(){var t;if((null===(t=this.datasets)||void 0===t?void 0:t.length)>0){const t=this.datasets.reduce((t,e)=>t+e.data.reduce((t,e)=>t+(null!=e?e:0),0),0)||void 0,e=e=>{const i=t?e/t*100:0;return 0===i?"":`${Math.round(i)}%`};if(this.chart){this.chart.data.labels=this.data.labels,this.chart.data.datasets=this.datasets,this.showPercent&&(this.chart.options.scales.y.max=this.getInflatedMax());const t=this.chart.options.plugins.datalabels||{};t.display=this.showPercent,this.showPercent?t.formatter=e:delete t.formatter,this.chart.options.plugins.datalabels=t,this.horizontal?(this.chart.options.scales.x=this.getValueAxisConfig(),this.chart.options.scales.y=this.getCategoryAxisConfig()):(this.chart.options.scales.x=this.getCategoryAxisConfig(),this.chart.options.scales.y=this.getValueAxisConfig()),this.chart.update()}else{const t={type:this.chartType,data:{labels:this.data.labels,datasets:this.datasets},options:{...this.horizontal&&{indexAxis:"y"},maxBarThickness:80,plugins:{legend:{display:this.legend},tooltip:{callbacks:{label:t=>{const e=t.dataset.label||"",i=this.horizontal?t.parsed.x:t.parsed.y;return"duration"===this.yType?`${e}: ${lk(i)}`:`${e}: ${i}`}}},datalabels:{display:this.showPercent,anchor:"end",align:"end",offset:-3,clamp:!0,...this.showPercent&&{formatter:e},color:"#666",font:{weight:"600"}}},responsive:!0,aspectRatio:2,onResize:this.handleResize.bind(this),maintainAspectRatio:!1,animation:!1,animations:{x:{duration:0},y:{duration:0}},scales:this.horizontal?{x:this.getValueAxisConfig(),y:this.getCategoryAxisConfig()}:{y:this.getValueAxisConfig(),x:this.getCategoryAxisConfig()}}};this.chart=new Cx(this.ctx,t)}}}handleSplitsChanged(t){const e=t.target;this.splits=e.values.map(t=>t.value)}handleToggleConfig(){this.showConfig=!this.showConfig,this.showConfig||(this.splits=[])}getValueAxisConfig(){return{min:0,...this.showPercent&&{max:this.getInflatedMax()},stacked:!0,grid:{color:"rgba(0,0,0,0.04)",display:!this.showPercent,drawBorder:!this.showPercent},border:{display:!this.showPercent},ticks:{display:!this.showPercent,..."duration"===this.yType&&!this.showPercent&&{callback:t=>lk(t)}}}}getCategoryAxisConfig(){let t=this.xFormat;if("time"===this.xType&&"auto"===this.xFormat){const e=this.data.labels[0],i=this.data.labels[this.data.labels.length-1],o=Date.parse(e),n=Date.parse(i);t="MMM dd",Math.ceil((n-o)/864e5)>365&&(t="MMM yyyy")}return{max:"time"===this.xType?this.end:this.xMaxTicks,min:"time"===this.xType?this.start:0,type:this.xType,grid:{display:!1},stacked:!0,ticks:{maxTicksLimit:this.xMaxTicks},..."time"===this.xType&&{time:{unit:"day",tooltipFormat:"DDD",displayFormats:{day:t}}}}}render(){var t,e,i;return W`<div>
12289
12289
  ${this.header?W`<div class="chart-title">${this.header}</div>`:null}
12290
12290
  <div id="canvas-wrapper"></div>
12291
12291
  ${this.config&&this.data?W`
@@ -13252,10 +13252,10 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
13252
13252
  @click=${()=>this.handleIssueClick(t)}
13253
13253
  >
13254
13254
  <temba-icon name="alert_warning" size="1.2"></temba-icon>
13255
- <span class="issue-text">${vu(t)}</span>
13255
+ <span class="issue-text">${sc(t)}</span>
13256
13256
  </div>
13257
13257
  `)}
13258
- `}render(){var t,e,i,o,n,s;if(!this.isOpen)return W``;const r=this.isTranslating?"#505050":this.getHeaderColor(),a=(this.isTranslating,"#fff"),l=this.getConfig(),d=(null==l?void 0:l.dialogSize)||"medium",c=this.isTranslating?$d().getLanguageName(this.languageCode):"";let h=(null==l?void 0:l.name)||"Edit";return this.isTranslating&&(h=c?`${c} - ${h}`:h),W`
13258
+ `}render(){var t,e,i,o,n,s;if(!this.isOpen)return W``;const r=this.isTranslating?"#505050":this.getHeaderColor(),a=(this.isTranslating,"#fff"),l=this.getConfig(),d=(null==l?void 0:l.dialogSize)||"medium",c=this.isTranslating?Ec().getLanguageName(this.languageCode):"";let h=(null==l?void 0:l.name)||"Edit";return this.isTranslating&&(h=c?`${c} - ${h}`:h),W`
13259
13259
  <temba-dialog
13260
13260
  header="${h}"
13261
13261
  .open="${this.isOpen}"
@@ -13792,7 +13792,7 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
13792
13792
  }
13793
13793
 
13794
13794
  /* Token styles (shared) */
13795
- ${mc}
13795
+ ${Fd}
13796
13796
 
13797
13797
  /* Completion popup styles */
13798
13798
  temba-options {
@@ -13825,7 +13825,7 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
13825
13825
  padding: 1px 5px;
13826
13826
  border-radius: var(--curvature);
13827
13827
  }
13828
- `}firstUpdated(){this.editableDiv=this.shadowRoot.querySelector(".highlight-editor"),this.anchorElement=this.shadowRoot.querySelector("#anchor"),this.hiddenElement=document.createElement("input"),this.hiddenElement.setAttribute("type","hidden"),this.hiddenElement.setAttribute("name",this.getAttribute("name")||""),this.hiddenElement.setAttribute("value",this.getAttribute("value")||""),this.appendChild(this.hiddenElement),this.patchEditableAsInput(),this.value&&this.renderHighlightedContent(this.value)}updated(t){super.updated(t),t.has("value")&&(this.hiddenElement&&this.hiddenElement.setAttribute("value",this.value||""),this._skipRender?this._skipRender=!1:this.editableDiv&&this.renderHighlightedContent(this.value||""))}patchEditableAsInput(){const t=this.editableDiv,e=this;Object.defineProperty(t,"value",{get:()=>e.value||"",set(t){e._skipRender=!0,e.value=t,e.renderHighlightedContent(t)},configurable:!0}),Object.defineProperty(t,"selectionStart",{get:()=>sc(t),configurable:!0}),Object.defineProperty(t,"selectionEnd",{get:()=>rc(t),configurable:!0}),t.setSelectionRange=(e,i)=>{lc(t,e,i)}}renderHighlightedContent(t){var e;const i=this.editableDiv;if(!i)return;if(this.disableCompletion)return void(i.textContent=t||"");const o=Qd(t||"",this.session?Nd:Rd),n=new Set;try{const t=$d();if(t)for(const i of t.getFunctions()){const t=null===(e=i.signature)||void 0===e?void 0:e.substring(0,i.signature.indexOf("("));t&&n.add(t.toLowerCase())}}catch(t){}i.textContent="";for(const t of o){const e=uc(t),o=hc.has(t.type),s=t.type===Vd.FunctionName&&n.size>0&&!n.has(t.text.toLowerCase()),r=t.text.split("\n");for(let t=0;t<r.length;t++){if(t>0){const t=document.createElement("span");t.className="tok-newline",t.textContent="\n",i.appendChild(t)}if(r[t].length>0){const n=document.createElement("span");n.textContent=r[t];let a=o?`${e} tok-mono`:e;s&&(a+=" tok-fn-invalid"),n.className=a,o&&n.setAttribute("spellcheck","false"),i.appendChild(n)}}}t&&""!==t||i.appendChild(document.createTextNode(""))}handleInput(){if(this.disabled||this._composing)return;const t=nc(this.editableDiv),e=this.value||"";if(t===e)return;const i=sc(this.editableDiv);this.undoStack.push({value:e,caret:i}),this.redoStack=[],this.applyValue(t,Math.min(i,t.length))}handleCompositionStart(){this._composing=!0}handleCompositionEnd(){this._composing=!1,this.handleInput()}applyValue(t,e){this._skipRender=!0,this.value=t,this.renderHighlightedContent(t),ac(this.editableDiv,e),this.executeQuery(),this.fireEvent("input"),this.fireEvent("change")}performUndo(){if(this.undoStack.length>0){const t=sc(this.editableDiv);this.redoStack.push({value:this.value||"",caret:t});const e=this.undoStack.pop();this.applyValue(e.value,e.caret)}}performRedo(){if(this.redoStack.length>0){const t=sc(this.editableDiv);this.undoStack.push({value:this.value||"",caret:t});const e=this.redoStack.pop();this.applyValue(e.value,e.caret)}}handleBeforeInput(t){"historyUndo"===t.inputType?(t.preventDefault(),this.performUndo()):"historyRedo"===t.inputType&&(t.preventDefault(),this.performRedo())}handleKeydown(t){const e=t.metaKey||t.ctrlKey;if(e&&"z"===t.key&&!t.shiftKey)return t.preventDefault(),void this.performUndo();if(e&&("z"===t.key&&t.shiftKey||"y"===t.key))return t.preventDefault(),void this.performRedo();if("Enter"===t.key){if(this.hasVisibleOptions())return void t.preventDefault();if(this.submitOnEnter||!this.textarea){t.preventDefault();const e=this.closest("temba-modax");return void(e?e.submit():this.fireCustomEvent(Io.Submitted))}t.preventDefault();const e=sc(this.editableDiv),i=rc(this.editableDiv),o=this.value||"";this.undoStack.push({value:o,caret:e}),this.redoStack=[];const n=o.substring(0,e)+"\n"+o.substring(i);this.applyValue(n,e+1)}}handleKeyUp(t){if(!this.disableCompletion){if(this.options&&this.options.length>0){if("ArrowUp"===t.key||"ArrowDown"===t.key)return;if(t.ctrlKey&&("n"===t.key||"p"===t.key))return;if("Enter"===t.key||"Escape"===t.key||"Tab"===t.key||t.key.startsWith("Control"))return t.stopPropagation(),void t.preventDefault()}this.executeQuery()}}handlePaste(t){var e;t.preventDefault();const i=(null===(e=t.clipboardData)||void 0===e?void 0:e.getData("text/plain"))||"",o=sc(this.editableDiv),n=rc(this.editableDiv),s=this.value||"";this.undoStack.push({value:s,caret:o}),this.redoStack=[];const r=s.substring(0,o)+i+s.substring(n);this.applyValue(r,o+i.length)}handleClick(){this.executeQuery()}handleBlur(){this.handleOptionCanceled()}executeQuery(){if(this.disableCompletion)return;if(!this.editableDiv)return;const t=Wd(this.editableDiv,this.session);t&&(this.query=t.query,this.options=t.options,this.anchorPosition=t.anchorPosition,this.currentFunction=t.currentFunction)}handleOptionSelection(t){const e=t.detail.selected,i=t.detail.tabbed,o=this.value||"",n=sc(this.editableDiv);this.undoStack.push({value:o,caret:n}),this.redoStack=[],Hd(this.query,this.editableDiv,e),this.value=this.editableDiv.value,this.query="",this.options=[],this.fireEvent("input"),this.fireEvent("change"),i&&this.executeQuery()}handleOptionCanceled(){window.setTimeout(()=>{this.options=[],this.query=""},100)}getTextInput(){const t=this;return{get inputElement(){return t.editableDiv},get value(){return t.value},updateValue(e){t._skipRender=!0,t.value=e,t.renderHighlightedContent(e)}}}get inputElement(){return this.editableDiv}getText(){return this.value||""}getCaretPosition(){return this.editableDiv?sc(this.editableDiv):0}getCaretScreenPosition(){if(!this.editableDiv)return null;const t=this.editableDiv.getRootNode(),e=t.getSelection?t.getSelection():window.getSelection();if(!e||0===e.rangeCount)return null;const i=e.getRangeAt(0).cloneRange();i.collapse(!0);const o=i.getBoundingClientRect();return 0===o.top&&0===o.left?null:{top:o.bottom,left:o.left}}insertTextAt(t,e){const i=this.value||"",o=i.substring(0,e)+t+i.substring(e),n=e+t.length;return this.applyValue(o,n),n}hasVisibleOptions(){return this.options.length>0}focus(){super.focus(),this.editableDiv&&this.editableDiv.focus()}click(){super.click(),this.editableDiv&&this.editableDiv.click()}renderWidget(){const t=this.anchorPosition?{top:`${this.anchorPosition.top}px`,left:`${this.anchorPosition.left}px`}:{},e=this.options&&this.options.length>0;return W`
13828
+ `}firstUpdated(){this.editableDiv=this.shadowRoot.querySelector(".highlight-editor"),this.anchorElement=this.shadowRoot.querySelector("#anchor"),this.hiddenElement=document.createElement("input"),this.hiddenElement.setAttribute("type","hidden"),this.hiddenElement.setAttribute("name",this.getAttribute("name")||""),this.hiddenElement.setAttribute("value",this.getAttribute("value")||""),this.appendChild(this.hiddenElement),this.patchEditableAsInput(),this.value&&this.renderHighlightedContent(this.value)}updated(t){super.updated(t),t.has("value")&&(this.hiddenElement&&this.hiddenElement.setAttribute("value",this.value||""),this._skipRender?this._skipRender=!1:this.editableDiv&&this.renderHighlightedContent(this.value||""))}patchEditableAsInput(){const t=this.editableDiv,e=this;Object.defineProperty(t,"value",{get:()=>e.value||"",set(t){e._skipRender=!0,e.value=t,e.renderHighlightedContent(t)},configurable:!0}),Object.defineProperty(t,"selectionStart",{get:()=>Pc(t),configurable:!0}),Object.defineProperty(t,"selectionEnd",{get:()=>Rc(t),configurable:!0}),t.setSelectionRange=(e,i)=>{Bc(t,e,i)}}renderHighlightedContent(t){var e;const i=this.editableDiv;if(!i)return;if(this.disableCompletion)return void(i.textContent=t||"");const o=Id(t||"",this.session?Zd:Vd),n=new Set;try{const t=Ec();if(t)for(const i of t.getFunctions()){const t=null===(e=i.signature)||void 0===e?void 0:e.substring(0,i.signature.indexOf("("));t&&n.add(t.toLowerCase())}}catch(t){}i.textContent="";for(const t of o){const e=Nd(t),o=Rd.has(t.type),s=t.type===Ed.FunctionName&&n.size>0&&!n.has(t.text.toLowerCase()),r=t.text.split("\n");for(let t=0;t<r.length;t++){if(t>0){const t=document.createElement("span");t.className="tok-newline",t.textContent="\n",i.appendChild(t)}if(r[t].length>0){const n=document.createElement("span");n.textContent=r[t];let a=o?`${e} tok-mono`:e;s&&(a+=" tok-fn-invalid"),n.className=a,o&&n.setAttribute("spellcheck","false"),i.appendChild(n)}}}t&&""!==t||i.appendChild(document.createTextNode(""))}handleInput(){if(this.disabled||this._composing)return;const t=Oc(this.editableDiv),e=this.value||"";if(t===e)return;const i=Pc(this.editableDiv);this.undoStack.push({value:e,caret:i}),this.redoStack=[],this.applyValue(t,Math.min(i,t.length))}handleCompositionStart(){this._composing=!0}handleCompositionEnd(){this._composing=!1,this.handleInput()}applyValue(t,e){this._skipRender=!0,this.value=t,this.renderHighlightedContent(t),Nc(this.editableDiv,e),this.executeQuery(),this.fireEvent("input"),this.fireEvent("change")}performUndo(){if(this.undoStack.length>0){const t=Pc(this.editableDiv);this.redoStack.push({value:this.value||"",caret:t});const e=this.undoStack.pop();this.applyValue(e.value,e.caret)}}performRedo(){if(this.redoStack.length>0){const t=Pc(this.editableDiv);this.undoStack.push({value:this.value||"",caret:t});const e=this.redoStack.pop();this.applyValue(e.value,e.caret)}}handleBeforeInput(t){"historyUndo"===t.inputType?(t.preventDefault(),this.performUndo()):"historyRedo"===t.inputType&&(t.preventDefault(),this.performRedo())}handleKeydown(t){const e=t.metaKey||t.ctrlKey;if(e&&"z"===t.key&&!t.shiftKey)return t.preventDefault(),void this.performUndo();if(e&&("z"===t.key&&t.shiftKey||"y"===t.key))return t.preventDefault(),void this.performRedo();if("Enter"===t.key){if(this.hasVisibleOptions())return void t.preventDefault();if(this.submitOnEnter||!this.textarea){t.preventDefault();const e=this.closest("temba-modax");return void(e?e.submit():this.fireCustomEvent(Io.Submitted))}t.preventDefault();const e=Pc(this.editableDiv),i=Rc(this.editableDiv),o=this.value||"";this.undoStack.push({value:o,caret:e}),this.redoStack=[];const n=o.substring(0,e)+"\n"+o.substring(i);this.applyValue(n,e+1)}}handleKeyUp(t){if(!this.disableCompletion){if(this.options&&this.options.length>0){if("ArrowUp"===t.key||"ArrowDown"===t.key)return;if(t.ctrlKey&&("n"===t.key||"p"===t.key))return;if("Enter"===t.key||"Escape"===t.key||"Tab"===t.key||t.key.startsWith("Control"))return t.stopPropagation(),void t.preventDefault()}this.executeQuery()}}handlePaste(t){var e;t.preventDefault();const i=(null===(e=t.clipboardData)||void 0===e?void 0:e.getData("text/plain"))||"",o=Pc(this.editableDiv),n=Rc(this.editableDiv),s=this.value||"";this.undoStack.push({value:s,caret:o}),this.redoStack=[];const r=s.substring(0,o)+i+s.substring(n);this.applyValue(r,o+i.length)}handleClick(){this.executeQuery()}handleBlur(){this.handleOptionCanceled()}executeQuery(){if(this.disableCompletion)return;if(!this.editableDiv)return;const t=tc(this.editableDiv,this.session);t&&(this.query=t.query,this.options=t.options,this.anchorPosition=t.anchorPosition,this.currentFunction=t.currentFunction)}handleOptionSelection(t){const e=t.detail.selected,i=t.detail.tabbed,o=this.value||"",n=Pc(this.editableDiv);this.undoStack.push({value:o,caret:n}),this.redoStack=[],Jd(this.query,this.editableDiv,e),this.value=this.editableDiv.value,this.query="",this.options=[],this.fireEvent("input"),this.fireEvent("change"),i&&this.executeQuery()}handleOptionCanceled(){window.setTimeout(()=>{this.options=[],this.query=""},100)}getTextInput(){const t=this;return{get inputElement(){return t.editableDiv},get value(){return t.value},updateValue(e){t._skipRender=!0,t.value=e,t.renderHighlightedContent(e)}}}get inputElement(){return this.editableDiv}getText(){return this.value||""}getCaretPosition(){return this.editableDiv?Pc(this.editableDiv):0}getCaretScreenPosition(){if(!this.editableDiv)return null;const t=this.editableDiv.getRootNode(),e=t.getSelection?t.getSelection():window.getSelection();if(!e||0===e.rangeCount)return null;const i=e.getRangeAt(0).cloneRange();i.collapse(!0);const o=i.getBoundingClientRect();return 0===o.top&&0===o.left?null:{top:o.bottom,left:o.left}}insertTextAt(t,e){const i=this.value||"",o=i.substring(0,e)+t+i.substring(e),n=e+t.length;return this.applyValue(o,n),n}hasVisibleOptions(){return this.options.length>0}focus(){super.focus(),this.editableDiv&&this.editableDiv.focus()}click(){super.click(),this.editableDiv&&this.editableDiv.click()}renderWidget(){const t=this.anchorPosition?{top:`${this.anchorPosition.top}px`,left:`${this.anchorPosition.left}px`}:{},e=this.options&&this.options.length>0;return W`
13829
13829
  <div class="comp-container">
13830
13830
  <div id="anchor" style=${$o(t)}></div>
13831
13831
  <div
@@ -13851,14 +13851,14 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
13851
13851
  <temba-options
13852
13852
  @temba-selection=${this.handleOptionSelection}
13853
13853
  @temba-canceled=${this.handleOptionCanceled}
13854
- .renderOption=${Bd}
13854
+ .renderOption=${Yd}
13855
13855
  .anchorTo=${this.anchorElement}
13856
13856
  .options=${this.options}
13857
13857
  ?visible=${e}
13858
13858
  >
13859
13859
  ${this.currentFunction?W`
13860
13860
  <div class="current-fn">
13861
- ${Bd(this.currentFunction,!0)}
13861
+ ${Yd(this.currentFunction,!0)}
13862
13862
  </div>
13863
13863
  `:null}
13864
13864
  <div class="footer" style="${e?null:"display:none"}">
@@ -13866,11 +13866,11 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
13866
13866
  </div>
13867
13867
  </temba-options>
13868
13868
  </div>
13869
- `}render(){return this.renderField()}}t([mt({type:String})],Ek.prototype,"placeholder",void 0),t([mt({type:Boolean})],Ek.prototype,"textarea",void 0),t([mt({type:Boolean})],Ek.prototype,"autogrow",void 0),t([mt({type:Boolean})],Ek.prototype,"gsm",void 0),t([mt({type:String})],Ek.prototype,"counter",void 0),t([mt({type:Number})],Ek.prototype,"maxLength",void 0),t([mt({type:String})],Ek.prototype,"flavor",void 0),t([mt({type:Boolean})],Ek.prototype,"session",void 0),t([mt({type:Boolean})],Ek.prototype,"submitOnEnter",void 0),t([mt({type:Boolean})],Ek.prototype,"disableCompletion",void 0),t([mt({type:Number})],Ek.prototype,"minHeight",void 0),t([mt({type:Array})],Ek.prototype,"options",void 0),t([mt({type:Object})],Ek.prototype,"anchorPosition",void 0),t([mt({attribute:!1})],Ek.prototype,"currentFunction",void 0);class $k extends dt{constructor(){super(...arguments),this.text=""}static get styles(){return[mc,a`
13869
+ `}render(){return this.renderField()}}t([mt({type:String})],Ek.prototype,"placeholder",void 0),t([mt({type:Boolean})],Ek.prototype,"textarea",void 0),t([mt({type:Boolean})],Ek.prototype,"autogrow",void 0),t([mt({type:Boolean})],Ek.prototype,"gsm",void 0),t([mt({type:String})],Ek.prototype,"counter",void 0),t([mt({type:Number})],Ek.prototype,"maxLength",void 0),t([mt({type:String})],Ek.prototype,"flavor",void 0),t([mt({type:Boolean})],Ek.prototype,"session",void 0),t([mt({type:Boolean})],Ek.prototype,"submitOnEnter",void 0),t([mt({type:Boolean})],Ek.prototype,"disableCompletion",void 0),t([mt({type:Number})],Ek.prototype,"minHeight",void 0),t([mt({type:Array})],Ek.prototype,"options",void 0),t([mt({type:Object})],Ek.prototype,"anchorPosition",void 0),t([mt({attribute:!1})],Ek.prototype,"currentFunction",void 0);class $k extends dt{constructor(){super(...arguments),this.text=""}static get styles(){return[Fd,a`
13870
13870
  :host {
13871
13871
  display: inline;
13872
13872
  }
13873
- `]}connectedCallback(){super.connectedCallback(),this.text=this.textContent||"",this.observer=new MutationObserver(()=>{this.text=this.textContent||""}),this.observer.observe(this,{childList:!0,characterData:!0,subtree:!0})}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this.observer)||void 0===t||t.disconnect()}renderTokens(){return Qd(this.text,Nd).map(t=>{const e=uc(t),i=hc.has(t.type);return W`<span class="${i?`${e} tok-mono`:e}">${t.text}</span>`})}render(){return W`${this.renderTokens()}`}}t([mt({type:String})],$k.prototype,"text",void 0);class Tk extends Be{constructor(){super(...arguments),this.name="",this.header="",this.icon="",this.width=500,this.minHeight=200,this.maxHeight=800,this.top=100,this.left=-1,this.hidden=!0,this.dragging=!1,this.chromeless=!1,this.color="#6B7280",this.saving=!1,this.leftBoundaryMargin=0,this.rightBoundaryMargin=0,this.topBoundaryMargin=0,this.bottomBoundaryMargin=0,this.dragStartX=0,this.dragStartY=0,this.dragOffsetX=0,this.dragOffsetY=0,this.positionFromRight=!1,this.defaultTop=100,this.defaultLeft=-1,this.handleSlotMouseDown=t=>{t.target.closest(".drag-handle")&&(this.dragging=!0,this.dragStartX=t.clientX,this.dragStartY=t.clientY,this.dragOffsetX=this.left,this.dragOffsetY=this.top,document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),t.preventDefault())},this.handleMouseMove=t=>{var e;if(!this.dragging)return;const i=t.clientX-this.dragStartX,o=t.clientY-this.dragStartY;this.left=this.dragOffsetX+i,this.top=this.dragOffsetY+o;this.left=Math.max(20-this.leftBoundaryMargin,Math.min(this.left,window.innerWidth-this.width-20+this.rightBoundaryMargin));const n=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".window"),s=(null==n?void 0:n.offsetHeight)||this.maxHeight||window.innerHeight,r=Math.max(20-this.topBoundaryMargin,window.innerHeight-s-20+this.bottomBoundaryMargin);this.top=Math.max(20-this.topBoundaryMargin,Math.min(this.top,r))},this.handleMouseUp=()=>{this.dragging=!1,document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),this.positionFromRight=!1,this.savePosition()},this.handleResize=()=>{var t;if(this.hidden)return;const e=20,i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".window"),o=(null==i?void 0:i.offsetHeight)||this.maxHeight||window.innerHeight;if(this.positionFromRight)this.left=window.innerWidth-this.width-e+this.rightBoundaryMargin;else{const t=e-this.leftBoundaryMargin,i=window.innerWidth-this.width-e+this.rightBoundaryMargin;this.left<t?this.left=t:this.left>i&&(this.left=i)}const n=e-this.topBoundaryMargin,s=Math.max(e-this.topBoundaryMargin,window.innerHeight-o-e+this.bottomBoundaryMargin);this.top<n?this.top=n:this.top>s&&(this.top=s)}}static get styles(){return a`
13873
+ `]}connectedCallback(){super.connectedCallback(),this.text=this.textContent||"",this.observer=new MutationObserver(()=>{this.text=this.textContent||""}),this.observer.observe(this,{childList:!0,characterData:!0,subtree:!0})}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this.observer)||void 0===t||t.disconnect()}renderTokens(){return Id(this.text,Zd).map(t=>{const e=Nd(t),i=Rd.has(t.type);return W`<span class="${i?`${e} tok-mono`:e}">${t.text}</span>`})}render(){return W`${this.renderTokens()}`}}t([mt({type:String})],$k.prototype,"text",void 0);class Tk extends Be{constructor(){super(...arguments),this.name="",this.header="",this.icon="",this.width=500,this.minHeight=200,this.maxHeight=800,this.top=100,this.left=-1,this.hidden=!0,this.dragging=!1,this.chromeless=!1,this.color="#6B7280",this.saving=!1,this.leftBoundaryMargin=0,this.rightBoundaryMargin=0,this.topBoundaryMargin=0,this.bottomBoundaryMargin=0,this.dragStartX=0,this.dragStartY=0,this.dragOffsetX=0,this.dragOffsetY=0,this.positionFromRight=!1,this.defaultTop=100,this.defaultLeft=-1,this.handleSlotMouseDown=t=>{t.target.closest(".drag-handle")&&(this.dragging=!0,this.dragStartX=t.clientX,this.dragStartY=t.clientY,this.dragOffsetX=this.left,this.dragOffsetY=this.top,document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),t.preventDefault())},this.handleMouseMove=t=>{var e;if(!this.dragging)return;const i=t.clientX-this.dragStartX,o=t.clientY-this.dragStartY;this.left=this.dragOffsetX+i,this.top=this.dragOffsetY+o;this.left=Math.max(20-this.leftBoundaryMargin,Math.min(this.left,window.innerWidth-this.width-20+this.rightBoundaryMargin));const n=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".window"),s=(null==n?void 0:n.offsetHeight)||this.maxHeight||window.innerHeight,r=Math.max(20-this.topBoundaryMargin,window.innerHeight-s-20+this.bottomBoundaryMargin);this.top=Math.max(20-this.topBoundaryMargin,Math.min(this.top,r))},this.handleMouseUp=()=>{this.dragging=!1,document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),this.positionFromRight=!1,this.savePosition()},this.handleResize=()=>{var t;if(this.hidden)return;const e=20,i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".window"),o=(null==i?void 0:i.offsetHeight)||this.maxHeight||window.innerHeight;if(this.positionFromRight)this.left=window.innerWidth-this.width-e+this.rightBoundaryMargin;else{const t=e-this.leftBoundaryMargin,i=window.innerWidth-this.width-e+this.rightBoundaryMargin;this.left<t?this.left=t:this.left>i&&(this.left=i)}const n=e-this.topBoundaryMargin,s=Math.max(e-this.topBoundaryMargin,window.innerHeight-o-e+this.bottomBoundaryMargin);this.top<n?this.top=n:this.top>s&&(this.top=s)}}static get styles(){return a`
13874
13874
  .window.hidden {
13875
13875
  transform: translateX(100%);
13876
13876
  opacity: 0;
@@ -14815,7 +14815,7 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
14815
14815
  color: #6b7280;
14816
14816
  font-size: 13px;
14817
14817
  }
14818
- `}resetAttachmentIndices(){this.imageIndex=2,this.videoIndex=0,this.audioIndex=0,this.locationIndex=0}get sizeConfig(){return Pk[this.size]||Pk.medium}get windowWidth(){const t=this.sizeConfig;return t.contextWidth+t.phoneWidth+t.optionPaneWidth+t.optionPaneGap+t.contextOffset}get leftBoundaryMargin(){const t=this.sizeConfig;return t.contextWidth+t.contextOffset}get contextClosedLeft(){const t=this.sizeConfig;return t.contextWidth+t.contextOffset-t.phoneWidth}connectedCallback(){super.connectedCallback()}firstUpdated(t){super.firstUpdated(t),this.refreshChat(),this.setupCustomScrollbar()}refreshChat(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("temba-chat");return e!==this.chat&&(this.chat=e),this.chat&&this.events.length>0&&(this.chat.addMessages(this.events,null,!0),this.events=[]),this.chat}setupCustomScrollbar(){var t,e,i;const o=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("temba-chat"),n=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".custom-scrollbar-container"),s=null===(i=this.shadowRoot)||void 0===i?void 0:i.querySelector(".custom-scrollbar-content");o&&n&&s&&o.updateComplete.then(()=>{var t;const e=null===(t=o.shadowRoot)||void 0===t?void 0:t.querySelector(".scroll");if(!e)return;let i=!1;e.addEventListener("scroll",()=>{if(!i){i=!0;const t=n.scrollHeight-n.clientHeight-Math.abs(e.scrollTop);n.scrollTop=t,requestAnimationFrame(()=>i=!1)}}),n.addEventListener("scroll",()=>{if(!i){i=!0;const t=n.scrollHeight-n.clientHeight-n.scrollTop;e.scrollTop=-t,requestAnimationFrame(()=>i=!1)}});const r=()=>{const t=e.scrollHeight-e.clientHeight,i=n.clientHeight;if(t<=0)return void(s.style.height="100%");const o=t+i;s.style.height=`${o}px`,Math.abs(e.scrollTop)<5&&(n.scrollTop=n.scrollHeight)};new MutationObserver(r).observe(e,{childList:!0,subtree:!0,attributes:!0});new ResizeObserver(r).observe(e),r()})}willUpdate(t){super.willUpdate(t),t.has("flow")&&this.flow&&(this.endpoint=`/flow/simulate/${this.flow}/`)}updated(t){super.updated(t),(t.has("currentQuickReplies")||t.has("keyboardVisible")||t.has("attachmentMenuOpen"))&&this.updateBottomInputHeight(),t.has("attachmentMenuOpen")&&(this.attachmentMenuOpen?(this.boundClickOutsideHandler||(this.boundClickOutsideHandler=this.handleClickOutsideAttachmentMenu.bind(this)),setTimeout(()=>{document.addEventListener("click",this.boundClickOutsideHandler)},0)):this.boundClickOutsideHandler&&document.removeEventListener("click",this.boundClickOutsideHandler)),t.has("size")?requestAnimationFrame(()=>{var t,e;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById("phone-window");if(i){const t=this.previousWindowWidth||i.width,o=i.left+t,n=this.sizeConfig,s=this.windowWidth;this.previousWindowWidth=s,i.width=s,i.leftBoundaryMargin=this.leftBoundaryMargin,i.topBoundaryMargin=n.windowPadding,i.bottomBoundaryMargin=n.windowPadding;let r=o-s;const a=20,l=a-this.leftBoundaryMargin,d=window.innerWidth-s-a+i.rightBoundaryMargin;r=Math.max(l,Math.min(r,d)),i.left=r;const c=null===(e=i.shadowRoot)||void 0===e?void 0:e.querySelector(".window"),h=(null==c?void 0:c.offsetHeight)||n.phoneTotalHeight,u=Math.max(a-n.windowPadding,window.innerHeight-h-a+n.windowPadding);i.top=Math.max(a-n.windowPadding,Math.min(i.top,u))}}):this.previousWindowWidth||(this.previousWindowWidth=this.windowWidth)}disconnectedCallback(){super.disconnectedCallback(),this.boundClickOutsideHandler&&document.removeEventListener("click",this.boundClickOutsideHandler)}handleTabClick(){this.isVisible?this.handleClose():this.handleShow()}async handleShow(){var t,e;this.shadowRoot.getElementById("phone-window").show(),this.isVisible=!0,$d().getState().setSimulatorActive(!0),this.refreshChat(),this.session||(await(null===(e=(t=$d().getState()).flushSave)||void 0===e?void 0:e.call(t)),this.startFlow())}async startFlow(){const t=(new Date).toISOString(),e=Sd.getState().languageCode;e&&(this.contact={...this.contact,language:e}),this.contact={...this.contact,created_on:t};const i={contact:this.contact,trigger:{type:"manual",triggered_on:t,flow:{uuid:this.flow,name:"New Chat"},params:{}}};try{const t=await ue(this.endpoint,i);this.updateRunContext(t.json)}catch(e){console.error("Failed to start simulation:",e);const i={uuid:Jt(),type:"error",created_on:new Date(t),_rendered:{html:W`<p>Failed to start simulation</p>`,type:Yc.Error}};this.refreshChat(),this.chat?this.chat.addMessages([i],null,!0):this.events=[...this.events,i]}}updateRunContext(t,e){var i;const o=[];if(e&&(e.uuid||(e.uuid=Jt()),"string"==typeof e.created_on&&(e.created_on=new Date(e.created_on)),o.push(e)),t.session&&(this.session=t.session,t.contact&&(this.contact=t.contact)),t.context&&(this.context=t.context),this.currentQuickReplies=[],t.events&&t.events.length>0)for(const e of t.events){if("msg_received"===e.type)continue;if(("msg_created"===e.type||"ivr_created"===e.type)&&!e.msg)continue;const t={...e,uuid:e.uuid||Jt(),created_on:"string"==typeof e.created_on?new Date(e.created_on):e.created_on};this.prerenderEvent(t),"msg_created"===t.type&&(null===(i=t.msg)||void 0===i?void 0:i.quick_replies)&&(this.currentQuickReplies=t.msg.quick_replies);const n="msg_created"===t.type||"ivr_created"===t.type,s=t.msg;if(n){const t=s.text&&s.text.trim().length>0,e=s.attachments&&s.attachments.length>0;if(!t&&!e)continue}else if(!t._rendered)continue;o.push(t)}this.refreshChat(),this.chat?this.chat.addMessages(o,null,!0):this.events=[...this.events,...o],this.sprinting=!1,this.requestUpdate(),this.scrollToBottom(),this.updateActivity()}updateActivity(){if(!this.session)return;const t={},e={};for(const i of this.session.runs){if(i.path)for(let e=0;e<i.path.length-1;e++){const o=i.path[e],n=i.path[e+1];if(o.exit_uuid&&n.node_uuid){const e=o.exit_uuid+":"+n.node_uuid;t[e]=(t[e]||0)+1}}if(("active"===i.status||"waiting"===i.status)&&i.path&&i.path.length>0){const t=i.path[i.path.length-1];t&&t.node_uuid&&(e[t.node_uuid]=(e[t.node_uuid]||0)+1)}}$d().getState().updateSimulatorActivity({segments:t,nodes:e}),this.following&&this.fireFollowEvent()}fireFollowEvent(){var t;if(!this.session||!this.session.runs||0===this.session.runs.length)return;let e=this.session.runs.find(t=>"active"===t.status||"waiting"===t.status);if(e||(e=this.session.runs.find(t=>"completed"===t.status)),e&&e.path&&e.path.length>0){const i=e.path[e.path.length-1];i&&i.node_uuid&&this.fireCustomEvent(Io.FollowSimulation,{flowUuid:(null===(t=e.flow)||void 0===t?void 0:t.uuid)||this.flow,nodeUuid:i.node_uuid})}}scrollToBottom(){if(this.chat)return this.chat.scrollToBottom(),void setTimeout(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".message-input input");e&&e.focus()},50);setTimeout(()=>{var t,e;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".phone-screen");i&&(i.scrollTop=i.scrollHeight),this.previousEventCount=this.events.length;const o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".message-input input");o&&o.focus()},50)}prerenderEvent(t){if(t._rendered||t.type===Jc.MSG_CREATED||t.type===Jc.MSG_RECEIVED)return;if("error"===t.type||"failure"===t.type)return void(t._rendered={html:ih(t,!0),type:Yc.Error});if("warning"===t.type)return void(t._rendered={html:ih(t,!0),type:Yc.Note});const e=ih(t,!0);if(e){const i=t.type===Jc.WEBHOOK_CALLED&&this.hasWebhookDetails(t)?W`<div class="webhook-event">
14818
+ `}resetAttachmentIndices(){this.imageIndex=2,this.videoIndex=0,this.audioIndex=0,this.locationIndex=0}get sizeConfig(){return Pk[this.size]||Pk.medium}get windowWidth(){const t=this.sizeConfig;return t.contextWidth+t.phoneWidth+t.optionPaneWidth+t.optionPaneGap+t.contextOffset}get leftBoundaryMargin(){const t=this.sizeConfig;return t.contextWidth+t.contextOffset}get contextClosedLeft(){const t=this.sizeConfig;return t.contextWidth+t.contextOffset-t.phoneWidth}connectedCallback(){super.connectedCallback()}firstUpdated(t){super.firstUpdated(t),this.refreshChat(),this.setupCustomScrollbar()}refreshChat(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("temba-chat");return e!==this.chat&&(this.chat=e),this.chat&&this.events.length>0&&(this.chat.addMessages(this.events,null,!0),this.events=[]),this.chat}setupCustomScrollbar(){var t,e,i;const o=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("temba-chat"),n=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".custom-scrollbar-container"),s=null===(i=this.shadowRoot)||void 0===i?void 0:i.querySelector(".custom-scrollbar-content");o&&n&&s&&o.updateComplete.then(()=>{var t;const e=null===(t=o.shadowRoot)||void 0===t?void 0:t.querySelector(".scroll");if(!e)return;let i=!1;e.addEventListener("scroll",()=>{if(!i){i=!0;const t=n.scrollHeight-n.clientHeight-Math.abs(e.scrollTop);n.scrollTop=t,requestAnimationFrame(()=>i=!1)}}),n.addEventListener("scroll",()=>{if(!i){i=!0;const t=n.scrollHeight-n.clientHeight-n.scrollTop;e.scrollTop=-t,requestAnimationFrame(()=>i=!1)}});const r=()=>{const t=e.scrollHeight-e.clientHeight,i=n.clientHeight;if(t<=0)return void(s.style.height="100%");const o=t+i;s.style.height=`${o}px`,Math.abs(e.scrollTop)<5&&(n.scrollTop=n.scrollHeight)};new MutationObserver(r).observe(e,{childList:!0,subtree:!0,attributes:!0});new ResizeObserver(r).observe(e),r()})}willUpdate(t){super.willUpdate(t),t.has("flow")&&this.flow&&(this.endpoint=`/flow/simulate/${this.flow}/`)}updated(t){super.updated(t),(t.has("currentQuickReplies")||t.has("keyboardVisible")||t.has("attachmentMenuOpen"))&&this.updateBottomInputHeight(),t.has("attachmentMenuOpen")&&(this.attachmentMenuOpen?(this.boundClickOutsideHandler||(this.boundClickOutsideHandler=this.handleClickOutsideAttachmentMenu.bind(this)),setTimeout(()=>{document.addEventListener("click",this.boundClickOutsideHandler)},0)):this.boundClickOutsideHandler&&document.removeEventListener("click",this.boundClickOutsideHandler)),t.has("size")?requestAnimationFrame(()=>{var t,e;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById("phone-window");if(i){const t=this.previousWindowWidth||i.width,o=i.left+t,n=this.sizeConfig,s=this.windowWidth;this.previousWindowWidth=s,i.width=s,i.leftBoundaryMargin=this.leftBoundaryMargin,i.topBoundaryMargin=n.windowPadding,i.bottomBoundaryMargin=n.windowPadding;let r=o-s;const a=20,l=a-this.leftBoundaryMargin,d=window.innerWidth-s-a+i.rightBoundaryMargin;r=Math.max(l,Math.min(r,d)),i.left=r;const c=null===(e=i.shadowRoot)||void 0===e?void 0:e.querySelector(".window"),h=(null==c?void 0:c.offsetHeight)||n.phoneTotalHeight,u=Math.max(a-n.windowPadding,window.innerHeight-h-a+n.windowPadding);i.top=Math.max(a-n.windowPadding,Math.min(i.top,u))}}):this.previousWindowWidth||(this.previousWindowWidth=this.windowWidth)}disconnectedCallback(){super.disconnectedCallback(),this.boundClickOutsideHandler&&document.removeEventListener("click",this.boundClickOutsideHandler)}handleTabClick(){this.isVisible?this.handleClose():this.handleShow()}async handleShow(){var t,e;this.shadowRoot.getElementById("phone-window").show(),this.isVisible=!0,Ec().getState().setSimulatorActive(!0),this.refreshChat(),this.session||(await(null===(e=(t=Ec().getState()).flushSave)||void 0===e?void 0:e.call(t)),this.startFlow())}async startFlow(){const t=(new Date).toISOString(),e=Sd.getState().languageCode;e&&(this.contact={...this.contact,language:e}),this.contact={...this.contact,created_on:t};const i={contact:this.contact,trigger:{type:"manual",triggered_on:t,flow:{uuid:this.flow,name:"New Chat"},params:{}}};try{const t=await ue(this.endpoint,i);this.updateRunContext(t.json)}catch(e){console.error("Failed to start simulation:",e);const i={uuid:Jt(),type:"error",created_on:new Date(t),_rendered:{html:W`<p>Failed to start simulation</p>`,type:yh.Error}};this.refreshChat(),this.chat?this.chat.addMessages([i],null,!0):this.events=[...this.events,i]}}updateRunContext(t,e){var i;const o=[];if(e&&(e.uuid||(e.uuid=Jt()),"string"==typeof e.created_on&&(e.created_on=new Date(e.created_on)),o.push(e)),t.session&&(this.session=t.session,t.contact&&(this.contact=t.contact)),t.context&&(this.context=t.context),this.currentQuickReplies=[],t.events&&t.events.length>0)for(const e of t.events){if("msg_received"===e.type)continue;if(("msg_created"===e.type||"ivr_created"===e.type)&&!e.msg)continue;const t={...e,uuid:e.uuid||Jt(),created_on:"string"==typeof e.created_on?new Date(e.created_on):e.created_on};this.prerenderEvent(t),"msg_created"===t.type&&(null===(i=t.msg)||void 0===i?void 0:i.quick_replies)&&(this.currentQuickReplies=t.msg.quick_replies);const n="msg_created"===t.type||"ivr_created"===t.type,s=t.msg;if(n){const t=s.text&&s.text.trim().length>0,e=s.attachments&&s.attachments.length>0;if(!t&&!e)continue}else if(!t._rendered)continue;o.push(t)}this.refreshChat(),this.chat?this.chat.addMessages(o,null,!0):this.events=[...this.events,...o],this.sprinting=!1,this.requestUpdate(),this.scrollToBottom(),this.updateActivity()}updateActivity(){if(!this.session)return;const t={},e={};for(const i of this.session.runs){if(i.path)for(let e=0;e<i.path.length-1;e++){const o=i.path[e],n=i.path[e+1];if(o.exit_uuid&&n.node_uuid){const e=o.exit_uuid+":"+n.node_uuid;t[e]=(t[e]||0)+1}}if(("active"===i.status||"waiting"===i.status)&&i.path&&i.path.length>0){const t=i.path[i.path.length-1];t&&t.node_uuid&&(e[t.node_uuid]=(e[t.node_uuid]||0)+1)}}Ec().getState().updateSimulatorActivity({segments:t,nodes:e}),this.following&&this.fireFollowEvent()}fireFollowEvent(){var t;if(!this.session||!this.session.runs||0===this.session.runs.length)return;let e=this.session.runs.find(t=>"active"===t.status||"waiting"===t.status);if(e||(e=this.session.runs.find(t=>"completed"===t.status)),e&&e.path&&e.path.length>0){const i=e.path[e.path.length-1];i&&i.node_uuid&&this.fireCustomEvent(Io.FollowSimulation,{flowUuid:(null===(t=e.flow)||void 0===t?void 0:t.uuid)||this.flow,nodeUuid:i.node_uuid})}}scrollToBottom(){if(this.chat)return this.chat.scrollToBottom(),void setTimeout(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".message-input input");e&&e.focus()},50);setTimeout(()=>{var t,e;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".phone-screen");i&&(i.scrollTop=i.scrollHeight),this.previousEventCount=this.events.length;const o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".message-input input");o&&o.focus()},50)}prerenderEvent(t){if(t._rendered||t.type===Ch.MSG_CREATED||t.type===Ch.MSG_RECEIVED)return;if("error"===t.type||"failure"===t.type)return void(t._rendered={html:Eh(t,!0),type:yh.Error});if("warning"===t.type)return void(t._rendered={html:Eh(t,!0),type:yh.Note});const e=Eh(t,!0);if(e){const i=t.type===Ch.WEBHOOK_CALLED&&this.hasWebhookDetails(t)?W`<div class="webhook-event">
14819
14819
  <div class="webhook-event-text">
14820
14820
  Called
14821
14821
  <a
@@ -14827,7 +14827,7 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
14827
14827
  >${((t,e=50)=>t&&t.length>e?t.slice(0,e)+"…":t)(t.url)}</a
14828
14828
  >
14829
14829
  </div>
14830
- </div>`:e;t._rendered={html:i,type:Yc.Inline}}}handleClose(){this.shadowRoot.getElementById("phone-window").handleClose(),this.isVisible=!1,this.closeWebhookDetails(),$d().getState().setSimulatorActive(!1)}async handleReset(){var t,e,i;this.events=[],this.session=null,this.context=null,this.inputValue="",this.sprinting=!1,this.previousEventCount=0,this.currentQuickReplies=[],this.closeWebhookDetails(),this.refreshChat(),this.chat&&this.chat.reset(),$d().getState().updateSimulatorActivity({segments:{},nodes:{}});const o=Sd.getState().languageCode;this.contact={uuid:"fb3787ab-2eda-48a0-a2bc-e2ddadec1286",urns:["tel:+12065551212"],fields:{},groups:[],language:o||(null===(t=this.definition)||void 0===t?void 0:t.language)||"eng",status:"active",created_on:(new Date).toISOString()},await(null===(i=(e=$d().getState()).flushSave)||void 0===i?void 0:i.call(e)),this.startFlow()}handleToggleFollow(){this.following=!this.following}handleCycleSize(){const t=["small","medium","large"],e=(t.indexOf(this.size)+1)%t.length;this.size=t[e]}handleToggleContextExplorer(){this.contextExplorerOpen=!this.contextExplorerOpen,this.contextExplorerOpen&&requestAnimationFrame(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById("phone-window");if(e){const t=20-this.sizeConfig.contextOffset;e.left<t&&(e.left=t)}})}togglePath(t){this.expandedPaths.has(t)?this.expandedPaths.delete(t):this.expandedPaths.add(t),this.requestUpdate()}isExpandable(t){if(null===t||"object"!=typeof t)return!1;if(Array.isArray(t))return t.length>0;return Object.keys(t).filter(t=>"__default__"!==t).length>0}renderContextValue(t){return null==t?"":"boolean"==typeof t||"number"==typeof t||"string"==typeof t?W`<span class="context-value">${t}</span>`:Array.isArray(t)?W`<span class="context-value">[${t.length}]</span>`:""}buildExpression(t){return`@${t}`}async handleCopyExpression(t,e){e.stopPropagation();const i=this.buildExpression(t);try{await navigator.clipboard.writeText(i),this.copiedExpression=i,setTimeout(()=>{this.copiedExpression=""},2e3)}catch(t){console.error("Failed to copy expression:",t)}}handleToggleShowAllKeys(){this.showAllKeys=!this.showAllKeys,this.toastMessage=this.showAllKeys?"Showing all keys":"Filtering out keys without values",setTimeout(()=>{this.toastMessage=""},2e3)}renderContextTree(t,e=""){if(!t||"object"!=typeof t)return W``;let i=Array.isArray(t)?t.map((t,e)=>[String(e),t]):Object.entries(t).filter(([t])=>"__default__"!==t);return this.showAllKeys||(i=i.filter(([,t])=>!!this.isExpandable(t)||null!=t&&("boolean"==typeof t||"number"==typeof t||"string"==typeof t||Array.isArray(t)))),W`${i.map(([t,i])=>{const o=e?`${e}.${t}`:t,n=this.expandedPaths.has(o),s=this.isExpandable(i);let r=i;return s&&!Array.isArray(i)&&null!==i&&"object"==typeof i&&"__default__"in i&&(r=i.__default__),W`
14830
+ </div>`:e;t._rendered={html:i,type:yh.Inline}}}handleClose(){this.shadowRoot.getElementById("phone-window").handleClose(),this.isVisible=!1,this.closeWebhookDetails(),Ec().getState().setSimulatorActive(!1)}async handleReset(){var t,e,i;this.events=[],this.session=null,this.context=null,this.inputValue="",this.sprinting=!1,this.previousEventCount=0,this.currentQuickReplies=[],this.closeWebhookDetails(),this.refreshChat(),this.chat&&this.chat.reset(),Ec().getState().updateSimulatorActivity({segments:{},nodes:{}});const o=Sd.getState().languageCode;this.contact={uuid:"fb3787ab-2eda-48a0-a2bc-e2ddadec1286",urns:["tel:+12065551212"],fields:{},groups:[],language:o||(null===(t=this.definition)||void 0===t?void 0:t.language)||"eng",status:"active",created_on:(new Date).toISOString()},await(null===(i=(e=Ec().getState()).flushSave)||void 0===i?void 0:i.call(e)),this.startFlow()}handleToggleFollow(){this.following=!this.following}handleCycleSize(){const t=["small","medium","large"],e=(t.indexOf(this.size)+1)%t.length;this.size=t[e]}handleToggleContextExplorer(){this.contextExplorerOpen=!this.contextExplorerOpen,this.contextExplorerOpen&&requestAnimationFrame(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById("phone-window");if(e){const t=20-this.sizeConfig.contextOffset;e.left<t&&(e.left=t)}})}togglePath(t){this.expandedPaths.has(t)?this.expandedPaths.delete(t):this.expandedPaths.add(t),this.requestUpdate()}isExpandable(t){if(null===t||"object"!=typeof t)return!1;if(Array.isArray(t))return t.length>0;return Object.keys(t).filter(t=>"__default__"!==t).length>0}renderContextValue(t){return null==t?"":"boolean"==typeof t||"number"==typeof t||"string"==typeof t?W`<span class="context-value">${t}</span>`:Array.isArray(t)?W`<span class="context-value">[${t.length}]</span>`:""}buildExpression(t){return`@${t}`}async handleCopyExpression(t,e){e.stopPropagation();const i=this.buildExpression(t);try{await navigator.clipboard.writeText(i),this.copiedExpression=i,setTimeout(()=>{this.copiedExpression=""},2e3)}catch(t){console.error("Failed to copy expression:",t)}}handleToggleShowAllKeys(){this.showAllKeys=!this.showAllKeys,this.toastMessage=this.showAllKeys?"Showing all keys":"Filtering out keys without values",setTimeout(()=>{this.toastMessage=""},2e3)}renderContextTree(t,e=""){if(!t||"object"!=typeof t)return W``;let i=Array.isArray(t)?t.map((t,e)=>[String(e),t]):Object.entries(t).filter(([t])=>"__default__"!==t);return this.showAllKeys||(i=i.filter(([,t])=>!!this.isExpandable(t)||null!=t&&("boolean"==typeof t||"number"==typeof t||"string"==typeof t||Array.isArray(t)))),W`${i.map(([t,i])=>{const o=e?`${e}.${t}`:t,n=this.expandedPaths.has(o),s=this.isExpandable(i);let r=i;return s&&!Array.isArray(i)&&null!==i&&"object"==typeof i&&"__default__"in i&&(r=i.__default__),W`
14831
14831
  <div>
14832
14832
  <div
14833
14833
  class="context-item ${s?"context-item-expandable":""}"
@@ -14894,7 +14894,7 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
14894
14894
  `):n(t[0],!0)}`}
14895
14895
  </div>
14896
14896
  </temba-dialog>
14897
- `}async resume(t,e){if(!t&&!e||!this.session)return;this.sprinting=!0,this.inputValue="",this.currentQuickReplies=[],this.attachmentMenuOpen=!1;const i=(new Date).toISOString(),o={uuid:Jt(),type:"msg_received",created_on:i,msg:{uuid:Jt(),text:t||"",urn:this.contact.urns[0],direction:"in",type:"text",attachments:e?[e]:[],quick_replies:[],channel:{uuid:Jt(),name:"Simulator"}}},n={...o,created_on:new Date(i)};this.refreshChat(),this.chat?this.chat.addMessages([n],null,!0):this.events=[...this.events,n],this.requestUpdate(),this.scrollToBottom();const s={session:this.session,contact:this.contact,resume:{type:"msg",event:o,resumed_on:i}};try{const t=await ue(this.endpoint,s);await new Promise(t=>setTimeout(t,400)),this.updateRunContext(t.json,null)}catch(t){console.error("Failed to resume simulation:",t);const e={uuid:Jt(),type:"error",created_on:new Date(i),_rendered:{html:W`<p>Failed to send message</p>`,type:Yc.Error}};this.refreshChat(),this.chat?this.chat.addMessages([e],null,!0):this.events=[...this.events,e],this.sprinting=!1}}handleKeyUp(t){if("Enter"===t.key){const e=t.target.value.trim();e&&this.resume(e)}}handleInput(t){const e=t.target;this.inputValue=e.value}handleQuickReplyClick(t){!this.sprinting&&t&&this.resume(t)}handleToggleAttachmentMenu(){this.attachmentMenuOpen=!this.attachmentMenuOpen}handleClickOutsideAttachmentMenu(t){var e,i;if(!this.attachmentMenuOpen)return;const o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".attachment-menu"),n=null===(i=this.shadowRoot)||void 0===i?void 0:i.querySelector(".attachment-button");if(!o||!n)return;const s=o.contains(t.target),r=n.contains(t.target);s||r||(this.attachmentMenuOpen=!1)}handleSendAttachment(t){let e="";switch(t){case"image":e=`image/jpeg:${zk[this.imageIndex]}`,this.imageIndex=(this.imageIndex+1)%zk.length;break;case"video":e=`video/mp4:${Ik[this.videoIndex]}`,this.videoIndex=(this.videoIndex+1)%Ik.length;break;case"audio":e=`audio/mp3:${Lk[this.audioIndex]}`,this.audioIndex=(this.audioIndex+1)%Lk.length;break;case"location":e=Ok[this.locationIndex],this.locationIndex=(this.locationIndex+1)%Ok.length}e&&this.resume("",e)}updateBottomInputHeight(){requestAnimationFrame(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".bottom-input-container");if(e){const t=e.offsetHeight;this.style.setProperty("--bottom-input-height",`${t}px`)}})}render(){var t;if(this.viewingRevision||0===(null===(t=this.definition)||void 0===t?void 0:t.nodes.length))return W``;const e=this.sizeConfig,i=`\n --phone-width: ${e.phoneWidth}px;\n --phone-total-height: ${e.phoneTotalHeight}px;\n --context-width: ${e.contextWidth}px;\n --context-offset: ${e.contextOffset}px;\n --option-pane-width: ${e.optionPaneWidth}px;\n --option-pane-gap: ${e.optionPaneGap}px;\n --window-padding: ${e.windowPadding}px;\n --phone-screen-height: ${e.phoneScreenHeight}px;\n --context-height: ${e.contextHeight}px;\n --context-closed-left: ${this.contextClosedLeft}px;\n --cutout-height: ${e.cutoutHeight}px;\n --cutout-padding: ${e.cutoutPadding}px;\n --cutout-font-size: ${e.cutoutFontSize}px;\n --cutout-island-width: ${e.cutoutIslandWidth}px;\n --cutout-island-height: ${e.cutoutIslandHeight}px;\n --cutout-island-top: ${e.cutoutIslandTop}px;\n --animation-time: ${this.animationTime}ms;\n `;return W`
14897
+ `}async resume(t,e){if(!t&&!e||!this.session)return;this.sprinting=!0,this.inputValue="",this.currentQuickReplies=[],this.attachmentMenuOpen=!1;const i=(new Date).toISOString(),o={uuid:Jt(),type:"msg_received",created_on:i,msg:{uuid:Jt(),text:t||"",urn:this.contact.urns[0],direction:"in",type:"text",attachments:e?[e]:[],quick_replies:[],channel:{uuid:Jt(),name:"Simulator"}}},n={...o,created_on:new Date(i)};this.refreshChat(),this.chat?this.chat.addMessages([n],null,!0):this.events=[...this.events,n],this.requestUpdate(),this.scrollToBottom();const s={session:this.session,contact:this.contact,resume:{type:"msg",event:o,resumed_on:i}};try{const t=await ue(this.endpoint,s);await new Promise(t=>setTimeout(t,400)),this.updateRunContext(t.json,null)}catch(t){console.error("Failed to resume simulation:",t);const e={uuid:Jt(),type:"error",created_on:new Date(i),_rendered:{html:W`<p>Failed to send message</p>`,type:yh.Error}};this.refreshChat(),this.chat?this.chat.addMessages([e],null,!0):this.events=[...this.events,e],this.sprinting=!1}}handleKeyUp(t){if("Enter"===t.key){const e=t.target.value.trim();e&&this.resume(e)}}handleInput(t){const e=t.target;this.inputValue=e.value}handleQuickReplyClick(t){!this.sprinting&&t&&this.resume(t)}handleToggleAttachmentMenu(){this.attachmentMenuOpen=!this.attachmentMenuOpen}handleClickOutsideAttachmentMenu(t){var e,i;if(!this.attachmentMenuOpen)return;const o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".attachment-menu"),n=null===(i=this.shadowRoot)||void 0===i?void 0:i.querySelector(".attachment-button");if(!o||!n)return;const s=o.contains(t.target),r=n.contains(t.target);s||r||(this.attachmentMenuOpen=!1)}handleSendAttachment(t){let e="";switch(t){case"image":e=`image/jpeg:${zk[this.imageIndex]}`,this.imageIndex=(this.imageIndex+1)%zk.length;break;case"video":e=`video/mp4:${Ik[this.videoIndex]}`,this.videoIndex=(this.videoIndex+1)%Ik.length;break;case"audio":e=`audio/mp3:${Lk[this.audioIndex]}`,this.audioIndex=(this.audioIndex+1)%Lk.length;break;case"location":e=Ok[this.locationIndex],this.locationIndex=(this.locationIndex+1)%Ok.length}e&&this.resume("",e)}updateBottomInputHeight(){requestAnimationFrame(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".bottom-input-container");if(e){const t=e.offsetHeight;this.style.setProperty("--bottom-input-height",`${t}px`)}})}render(){var t;if(this.viewingRevision||0===(null===(t=this.definition)||void 0===t?void 0:t.nodes.length))return W``;const e=this.sizeConfig,i=`\n --phone-width: ${e.phoneWidth}px;\n --phone-total-height: ${e.phoneTotalHeight}px;\n --context-width: ${e.contextWidth}px;\n --context-offset: ${e.contextOffset}px;\n --option-pane-width: ${e.optionPaneWidth}px;\n --option-pane-gap: ${e.optionPaneGap}px;\n --window-padding: ${e.windowPadding}px;\n --phone-screen-height: ${e.phoneScreenHeight}px;\n --context-height: ${e.contextHeight}px;\n --context-closed-left: ${this.contextClosedLeft}px;\n --cutout-height: ${e.cutoutHeight}px;\n --cutout-padding: ${e.cutoutPadding}px;\n --cutout-font-size: ${e.cutoutFontSize}px;\n --cutout-island-width: ${e.cutoutIslandWidth}px;\n --cutout-island-height: ${e.cutoutIslandHeight}px;\n --cutout-island-top: ${e.cutoutIslandTop}px;\n --animation-time: ${this.animationTime}ms;\n `;return W`
14898
14898
  <temba-floating-window
14899
14899
  style="--transition-duration: ${this.animationTime}ms"
14900
14900
  id="phone-window"
@@ -15075,7 +15075,7 @@ const hk=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
15075
15075
  .active=${this.isVisible}
15076
15076
  @temba-button-clicked=${this.handleTabClick}
15077
15077
  ></temba-floating-tab>
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`
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(Sc(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=Sc(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(Sc(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`
15079
15079
  <div class="backdrop" @click=${this.handleBackdropClick}></div>
15080
15080
  <div
15081
15081
  class="search-container"
@@ -15340,7 +15340,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15340
15340
  @click=${()=>this.handleItemClick(t)}
15341
15341
  >
15342
15342
  <temba-icon name="alert_warning" size="1.2"></temba-icon>
15343
- <span>${vu(t)}</span>
15343
+ <span>${sc(t)}</span>
15344
15344
  </div>
15345
15345
  `)}
15346
15346
  </div>
@@ -15411,7 +15411,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15411
15411
  </div>
15412
15412
  </div>
15413
15413
  </temba-floating-window>
15414
- `}async fetchRevisions(){this.isLoading=!0;try{const t=await le(`/flow/revisions/${this.flow}/?version=${xd}`);this.revisions=t.slice(1)}catch(t){console.error("Error fetching revisions",t)}finally{this.isLoading=!1}}async handleRevisionClick(t){var e;if((null===(e=this.viewingRevision)||void 0===e?void 0:e.id)===t.id)return;const i=$d().getState();this.viewingRevision||(this.preRevertState={definition:i.flowDefinition,dirtyDate:i.dirtyDate},this.browseLanguageCode=i.languageCode),this.viewingRevision=t,this.isLoading=!0,this.fireCustomEvent(Io.RevisionViewed,{revision:t});try{await i.fetchRevision(`/flow/revisions/${this.flow}`,t.id.toString()),this.browseLanguageCode&&i.setLanguageCode(this.browseLanguageCode)}catch(t){console.error("Error fetching revision details",t),this.cancelRevisionView()}finally{this.isLoading=!1}}cancelRevisionView(){const t=$d().getState(),e=this.browseLanguageCode||t.languageCode;if(this.preRevertState){const i=t.flowInfo;t.setFlowContents({definition:this.preRevertState.definition,info:i}),this.preRevertState.dirtyDate&&t.setDirtyDate(this.preRevertState.dirtyDate),e&&t.setLanguageCode(e)}else t.fetchRevision(`/flow/revisions/${this.flow}`).finally(()=>{e&&t.setLanguageCode(e)});this.viewingRevision=null,this.preRevertState=null,this.browseLanguageCode=null,this.fireCustomEvent(Io.RevisionCancelled)}async handleRevertClick(){if(!this.viewingRevision||!this.preRevertState)return;const t=$d().getState(),e=this.browseLanguageCode||t.languageCode,i={...t.flowDefinition,revision:this.preRevertState.definition.revision};this.viewingRevision=null,this.preRevertState=null,this.browseLanguageCode=null,this.fireCustomEvent(Io.RevisionReverted,{definition:i,languageCode:e})}resetScroll(){var t,e;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("temba-floating-window"),o=null===(e=null==i?void 0:i.shadowRoot)||void 0===e?void 0:e.querySelector(".body");o&&(o.scrollTop=0)}}t([mt({type:String})],Zk.prototype,"flow",void 0),t([mt({type:Boolean})],Zk.prototype,"hidden",void 0),t([mt({type:Boolean})],Zk.prototype,"saving",void 0),t([gt()],Zk.prototype,"revisions",void 0),t([gt()],Zk.prototype,"viewingRevision",void 0),t([gt()],Zk.prototype,"isLoading",void 0);class Yk extends Be{static get styles(){return a`
15414
+ `}async fetchRevisions(){this.isLoading=!0;try{const t=await le(`/flow/revisions/${this.flow}/?version=${xd}`);this.revisions=t.slice(1)}catch(t){console.error("Error fetching revisions",t)}finally{this.isLoading=!1}}async handleRevisionClick(t){var e;if((null===(e=this.viewingRevision)||void 0===e?void 0:e.id)===t.id)return;const i=Ec().getState();this.viewingRevision||(this.preRevertState={definition:i.flowDefinition,dirtyDate:i.dirtyDate},this.browseLanguageCode=i.languageCode),this.viewingRevision=t,this.isLoading=!0,this.fireCustomEvent(Io.RevisionViewed,{revision:t});try{await i.fetchRevision(`/flow/revisions/${this.flow}`,t.id.toString()),this.browseLanguageCode&&i.setLanguageCode(this.browseLanguageCode)}catch(t){console.error("Error fetching revision details",t),this.cancelRevisionView()}finally{this.isLoading=!1}}cancelRevisionView(){const t=Ec().getState(),e=this.browseLanguageCode||t.languageCode;if(this.preRevertState){const i=t.flowInfo;t.setFlowContents({definition:this.preRevertState.definition,info:i}),this.preRevertState.dirtyDate&&t.setDirtyDate(this.preRevertState.dirtyDate),e&&t.setLanguageCode(e)}else t.fetchRevision(`/flow/revisions/${this.flow}`).finally(()=>{e&&t.setLanguageCode(e)});this.viewingRevision=null,this.preRevertState=null,this.browseLanguageCode=null,this.fireCustomEvent(Io.RevisionCancelled)}async handleRevertClick(){if(!this.viewingRevision||!this.preRevertState)return;const t=Ec().getState(),e=this.browseLanguageCode||t.languageCode,i={...t.flowDefinition,revision:this.preRevertState.definition.revision};this.viewingRevision=null,this.preRevertState=null,this.browseLanguageCode=null,this.fireCustomEvent(Io.RevisionReverted,{definition:i,languageCode:e})}resetScroll(){var t,e;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("temba-floating-window"),o=null===(e=null==i?void 0:i.shadowRoot)||void 0===e?void 0:e.querySelector(".body");o&&(o.scrollTop=0)}}t([mt({type:String})],Zk.prototype,"flow",void 0),t([mt({type:Boolean})],Zk.prototype,"hidden",void 0),t([mt({type:Boolean})],Zk.prototype,"saving",void 0),t([gt()],Zk.prototype,"revisions",void 0),t([gt()],Zk.prototype,"viewingRevision",void 0),t([gt()],Zk.prototype,"isLoading",void 0);class Yk extends Be{static get styles(){return a`
15415
15415
  :host {
15416
15416
  display: block;
15417
15417
  overflow: auto;
@@ -15738,7 +15738,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15738
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">
15739
15739
  <temba-icon name="${o}"></temba-icon>
15740
15740
  </div>`})}
15741
- </div>`:W``}renderOriginalContent(t){const e=t.action,i=ym[e.type],o=(null==i?void 0:i.localizable)||[],n=[];if(null==i?void 0:i.form)for(const t of o){const o=i.form[t];if(o&&("text"===o.type||"textarea"===o.type||"message-editor"===o.type)){const i=e[t]||"";i&&n.push(_u(this.stripLeadingLineBreaks(i),!0))}}const s=e.quick_replies||[];s.length>0&&n.push(W`<div class="quick-replies ${0===n.length?"standalone":""}">${s.map(t=>W`<div class="quick-reply">${t}</div>`)}</div>`);const r=e.attachments||[];return r.length>0&&n.push(this.renderAttachments(r)),0===n.length?W`<span style="color: #bbb; font-style: italic;">Empty</span>`:W`${n}`}renderTranslatedContent(t){const e=t.action,i=ym[e.type],o=(null==i?void 0:i.localizable)||[],n=[];if(null==i?void 0:i.form)for(const t of o){const o=i.form[t];if(o&&("text"===o.type||"textarea"===o.type||"message-editor"===o.type)){const i=this.getTranslatedField(e.uuid,t);"string"==typeof i&&n.push(_u(this.stripLeadingLineBreaks(i),!0))}}const s=this.getTranslatedQuickReplies(e.uuid);s.length>0&&n.push(W`<div class="quick-replies ${0===n.length?"standalone":""}">${s.map(t=>W`<div class="quick-reply">${t}</div>`)}</div>`);const r=this.getTranslatedArrayField(e.uuid,"attachments");return r.length>0&&n.push(this.renderAttachments(r)),0===n.length?W`No translation`:W`${n}`}handleBaseTextClick(t){this.fireCustomEvent(Io.ActionEditRequested,{action:t.action,nodeUuid:t.node.uuid,forceBase:!0})}handleTranslationClick(t){this.fireCustomEvent(Io.ActionEditRequested,{action:t.action,nodeUuid:t.node.uuid})}handleBaseGroupClick(t){var e,i,o;const n=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.node.uuid];n&&this.fireCustomEvent(Io.NodeEditRequested,{node:t.node,nodeUI:n,forceBase:!0})}handleGroupTranslationClick(t){var e,i,o;const n=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.node.uuid];n&&this.fireCustomEvent(Io.NodeEditRequested,{node:t.node,nodeUI:n})}getGroupTranslations(t){const e=t.rules.map(t=>{var e,i,o,n;const s=t.arguments.join(", "),r=(null===(e=kp(t.type))||void 0===e?void 0:e.name)||t.type,a=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.uuid];return{original:s,translated:Array.isArray(null==a?void 0:a.arguments)?a.arguments.join(", "):null,isRule:!0,operatorName:r}});return[...e,...t.categories.map(t=>({original:t.name,translated:this.getTranslatedCategoryName(t.uuid),isRule:!1}))]}getEntryRailColor(t){var e,i,o,n,s,r,a;if("message"===t.kind){const i=ym[t.action.type],o=null==i?void 0:i.group;return o&&(null===(e=Wu[o])||void 0===e?void 0:e.color)||"#cbd5e1"}const l=null===(s=null===(n=null===(o=null===(i=this.definition)||void 0===i?void 0:i._ui)||void 0===o?void 0:o.nodes)||void 0===n?void 0:n[t.node.uuid])||void 0===s?void 0:s.type;if(!l)return"#cbd5e1";const d=wm[l],c=null==d?void 0:d.group;return c&&((null===(r=Wu[c])||void 0===r?void 0:r.color)||(null===(a=Vu[c])||void 0===a?void 0:a.color))||"#cbd5e1"}renderPairedRows(t,e,i,o,n){return W`
15741
+ </div>`:W``}renderOriginalContent(t){const e=t.action,i=ym[e.type],o=(null==i?void 0:i.localizable)||[],n=[];if(null==i?void 0:i.form)for(const t of o){const o=i.form[t];if(o&&("text"===o.type||"textarea"===o.type||"message-editor"===o.type)){const i=e[t]||"";i&&n.push(cc(this.stripLeadingLineBreaks(i),!0))}}const s=e.quick_replies||[];s.length>0&&n.push(W`<div class="quick-replies ${0===n.length?"standalone":""}">${s.map(t=>W`<div class="quick-reply">${t}</div>`)}</div>`);const r=e.attachments||[];return r.length>0&&n.push(this.renderAttachments(r)),0===n.length?W`<span style="color: #bbb; font-style: italic;">Empty</span>`:W`${n}`}renderTranslatedContent(t){const e=t.action,i=ym[e.type],o=(null==i?void 0:i.localizable)||[],n=[];if(null==i?void 0:i.form)for(const t of o){const o=i.form[t];if(o&&("text"===o.type||"textarea"===o.type||"message-editor"===o.type)){const i=this.getTranslatedField(e.uuid,t);"string"==typeof i&&n.push(cc(this.stripLeadingLineBreaks(i),!0))}}const s=this.getTranslatedQuickReplies(e.uuid);s.length>0&&n.push(W`<div class="quick-replies ${0===n.length?"standalone":""}">${s.map(t=>W`<div class="quick-reply">${t}</div>`)}</div>`);const r=this.getTranslatedArrayField(e.uuid,"attachments");return r.length>0&&n.push(this.renderAttachments(r)),0===n.length?W`No translation`:W`${n}`}handleBaseTextClick(t){this.fireCustomEvent(Io.ActionEditRequested,{action:t.action,nodeUuid:t.node.uuid,forceBase:!0})}handleTranslationClick(t){this.fireCustomEvent(Io.ActionEditRequested,{action:t.action,nodeUuid:t.node.uuid})}handleBaseGroupClick(t){var e,i,o;const n=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.node.uuid];n&&this.fireCustomEvent(Io.NodeEditRequested,{node:t.node,nodeUI:n,forceBase:!0})}handleGroupTranslationClick(t){var e,i,o;const n=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.node.uuid];n&&this.fireCustomEvent(Io.NodeEditRequested,{node:t.node,nodeUI:n})}getGroupTranslations(t){const e=t.rules.map(t=>{var e,i,o,n;const s=t.arguments.join(", "),r=(null===(e=kp(t.type))||void 0===e?void 0:e.name)||t.type,a=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.uuid];return{original:s,translated:Array.isArray(null==a?void 0:a.arguments)?a.arguments.join(", "):null,isRule:!0,operatorName:r}});return[...e,...t.categories.map(t=>({original:t.name,translated:this.getTranslatedCategoryName(t.uuid),isRule:!1}))]}getEntryRailColor(t){var e,i,o,n,s,r,a;if("message"===t.kind){const i=ym[t.action.type],o=null==i?void 0:i.group;return o&&(null===(e=Wu[o])||void 0===e?void 0:e.color)||"#cbd5e1"}const l=null===(s=null===(n=null===(o=null===(i=this.definition)||void 0===i?void 0:i._ui)||void 0===o?void 0:o.nodes)||void 0===n?void 0:n[t.node.uuid])||void 0===s?void 0:s.type;if(!l)return"#cbd5e1";const d=wm[l],c=null==d?void 0:d.group;return c&&((null===(r=Wu[c])||void 0===r?void 0:r.color)||(null===(a=Vu[c])||void 0===a?void 0:a.color))||"#cbd5e1"}renderPairedRows(t,e,i,o,n){return W`
15742
15742
  ${t.map((s,r)=>W`
15743
15743
  <tr
15744
15744
  class="category-row localization-paired-row ${0===r?"localization-paired-first":""} ${r===t.length-1?"localization-paired-last":""}"
@@ -15784,7 +15784,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15784
15784
  </tr>
15785
15785
  </thead>
15786
15786
  <tbody>
15787
- ${t.map(t=>{const i="localization-group"===t.kind,o=()=>{"message"===t.kind?this.handleBaseTextClick(t):i&&this.handleBaseGroupClick(t)},n=()=>{"message"===t.kind?this.handleTranslationClick(t):i&&this.handleGroupTranslationClick(t)};if(i&&e){const i=this.getGroupTranslations(t).map(t=>({original:W`${t.isRule&&t.operatorName?W`<span class="rule-operator">${t.operatorName}</span> `:""}${_u(t.original,!0)}`,translated:null!==t.translated?W`${t.isRule&&t.operatorName?W`<span class="rule-operator">${t.operatorName}</span> `:""}${_u(t.translated,!0)}`:null}));return this.renderPairedRows(i,t,o,n,e)}if("message"===t.kind&&this.usesPairedRows(t.action)){const i=this.getPairedFields(t.action).map(t=>({original:W`${t.original?_u(this.stripLeadingLineBreaks(t.original),!0):W`<span style="color: #bbb; font-style: italic;">Empty</span>`}`,translated:null!==t.translated?W`${_u(this.stripLeadingLineBreaks(t.translated),!0)}`:null}));return this.renderPairedRows(i,t,o,n,e)}const s="translation-cell "+("message"===t.kind&&e&&this.hasAnyTranslation(t)?"has-translation":"missing-translation");return W`
15787
+ ${t.map(t=>{const i="localization-group"===t.kind,o=()=>{"message"===t.kind?this.handleBaseTextClick(t):i&&this.handleBaseGroupClick(t)},n=()=>{"message"===t.kind?this.handleTranslationClick(t):i&&this.handleGroupTranslationClick(t)};if(i&&e){const i=this.getGroupTranslations(t).map(t=>({original:W`${t.isRule&&t.operatorName?W`<span class="rule-operator">${t.operatorName}</span> `:""}${cc(t.original,!0)}`,translated:null!==t.translated?W`${t.isRule&&t.operatorName?W`<span class="rule-operator">${t.operatorName}</span> `:""}${cc(t.translated,!0)}`:null}));return this.renderPairedRows(i,t,o,n,e)}if("message"===t.kind&&this.usesPairedRows(t.action)){const i=this.getPairedFields(t.action).map(t=>({original:W`${t.original?cc(this.stripLeadingLineBreaks(t.original),!0):W`<span style="color: #bbb; font-style: italic;">Empty</span>`}`,translated:null!==t.translated?W`${cc(this.stripLeadingLineBreaks(t.translated),!0)}`:null}));return this.renderPairedRows(i,t,o,n,e)}const s="translation-cell "+("message"===t.kind&&e&&this.hasAnyTranslation(t)?"has-translation":"missing-translation");return W`
15788
15788
  <tr
15789
15789
  style=${`--node-rail-color: ${this.getEntryRailColor(t)};`}
15790
15790
  data-node-uuid=${t.node.uuid}
@@ -15801,12 +15801,12 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15801
15801
  <div class="category-stack category-stack-original">
15802
15802
  ${t.rules.map(t=>{var e;return W`
15803
15803
  <div class="category-item category-original-item">
15804
- <span><span class="rule-operator">${(null===(e=kp(t.type))||void 0===e?void 0:e.name)||t.type}</span> ${_u(t.arguments.join(", "),!0)}</span>
15804
+ <span><span class="rule-operator">${(null===(e=kp(t.type))||void 0===e?void 0:e.name)||t.type}</span> ${cc(t.arguments.join(", "),!0)}</span>
15805
15805
  </div>
15806
15806
  `})}
15807
15807
  ${t.categories.map(t=>W`
15808
15808
  <div class="category-item category-original-item">
15809
- <span>${_u(t.name,!0)}</span>
15809
+ <span>${cc(t.name,!0)}</span>
15810
15810
  </div>
15811
15811
  `)}
15812
15812
  </div>
@@ -15826,7 +15826,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15826
15826
  `})}
15827
15827
  </tbody>
15828
15828
  </table>
15829
- `}}function Kk(t,e){window.customElements.get(t)||window.customElements.define(t,e)}Yk.ATTACHMENT_ICONS={image:ko.attachment_image,audio:ko.attachment_audio,video:ko.attachment_video,application:ko.attachment_document},t([Ad(Sd,t=>t.flowDefinition)],Yk.prototype,"definition",void 0),t([Ad(Sd,t=>t.languageCode)],Yk.prototype,"languageCode",void 0),t([Ad(Sd,t=>t.isTranslating)],Yk.prototype,"isTranslating",void 0),Kk("temba-anchor",yh),Kk("temba-alert",ch),Kk("temba-store",Td),Kk("temba-textinput",Lo),Kk("temba-datepicker",Nh),Kk("temba-range-picker",ck),Kk("temba-date",Vh),Kk("temba-completion",fc),Kk("temba-checkbox",Co),Kk("temba-select",gc),Kk("temba-options",Dd),Kk("temba-loading",_c),Kk("temba-lightbox",Yh),Kk("temba-button",wc),Kk("temba-omnibox",gh),Kk("temba-tip",fh),Kk("temba-contact-name",Ch),Kk("temba-contact-name-fetch",Rh),Kk("temba-contact-field",$h),Kk("temba-contact-fields",Ah),Kk("temba-field-manager",qh),Kk("temba-urn",Sh),Kk("temba-content-menu",Hh),Kk("temba-dialog",yc),Kk("temba-modax",xc),Kk("temba-charcount",Ic),Kk("temba-contact-chat",oh),Kk("temba-contact-details",class extends Pc{static get styles(){return a`
15829
+ `}}function Kk(t,e){window.customElements.get(t)||window.customElements.define(t,e)}Yk.ATTACHMENT_ICONS={image:ko.attachment_image,audio:ko.attachment_audio,video:ko.attachment_video,application:ko.attachment_document},t([Ad(Sd,t=>t.flowDefinition)],Yk.prototype,"definition",void 0),t([Ad(Sd,t=>t.languageCode)],Yk.prototype,"languageCode",void 0),t([Ad(Sd,t=>t.isTranslating)],Yk.prototype,"isTranslating",void 0),Kk("temba-anchor",Hh),Kk("temba-alert",Oh),Kk("temba-store",$c),Kk("temba-textinput",Lo),Kk("temba-datepicker",du),Kk("temba-range-picker",ck),Kk("temba-date",vu),Kk("temba-completion",qc),Kk("temba-checkbox",Co),Kk("temba-select",Fc),Kk("temba-options",Tc),Kk("temba-loading",Zc),Kk("temba-lightbox",yu),Kk("temba-button",Vc),Kk("temba-omnibox",Fh),Kk("temba-tip",qh),Kk("temba-contact-name",Kh),Kk("temba-contact-name-fetch",lu),Kk("temba-contact-field",Jh),Kk("temba-contact-fields",Xh),Kk("temba-field-manager",uu),Kk("temba-urn",Gh),Kk("temba-content-menu",gu),Kk("temba-dialog",Hc),Kk("temba-modax",Wc),Kk("temba-charcount",nh),Kk("temba-contact-chat",$h),Kk("temba-contact-details",class extends ah{static get styles(){return a`
15830
15830
  .urn {
15831
15831
  display: flex;
15832
15832
  padding: 0.4em 1em 0.8em 1em;
@@ -15872,7 +15872,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15872
15872
  ${t.name}
15873
15873
  </temba-label>`)}
15874
15874
  </div>`:null}
15875
- ${this.data.urns.map(t=>{const e=t.split(":");let i=dh[e[0]];return i||(i=Se(e[0])),W`<temba-contact-field
15875
+ ${this.data.urns.map(t=>{const e=t.split(":");let i=Lh[e[0]];return i||(i=Se(e[0])),W`<temba-contact-field
15876
15876
  name=${i}
15877
15877
  value=${e[1]}
15878
15878
  disabled
@@ -15885,7 +15885,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15885
15885
 
15886
15886
  <temba-contact-field
15887
15887
  name="Status"
15888
- value=${lh[this.data.status]}
15888
+ value=${Ih[this.data.status]}
15889
15889
  disabled
15890
15890
  ></temba-contact-field>
15891
15891
  ${t?W`<temba-contact-field
@@ -15907,7 +15907,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15907
15907
  disabled
15908
15908
  ></temba-contact-field>
15909
15909
  </div>
15910
- `}}),Kk("temba-ticket-list",ah),Kk("temba-notification-list",class extends rh{static get styles(){return a`
15910
+ `}}),Kk("temba-ticket-list",zh),Kk("temba-notification-list",class extends Mh{static get styles(){return a`
15911
15911
  :host {
15912
15912
  --option-hover-bg: #f9f9f9;
15913
15913
  }
@@ -15950,7 +15950,7 @@ function(t){return(e,i,o)=>((t,e,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.
15950
15950
  </div>`}}renderHeader(){return W`<div class="header">
15951
15951
  <temba-icon name="notification"></temba-icon>
15952
15952
  <div class="title">Notifications</div>
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`
15953
+ </div>`}scrollToTop(){window.setTimeout(()=>{this.shadowRoot.querySelector("temba-options").scrollToTop()},1e3)}}),Kk("temba-list",Mh),Kk("temba-sortable-list",Dc),Kk("temba-run-list",ru),Kk("temba-flow-details",au),Kk("temba-label",Yh),Kk("temba-menu",jh),Kk("temba-contact-search",Ph),Kk("temba-icon",Rh),Kk("temba-dropdown",Wh),Kk("temba-tabs",Vh),Kk("temba-tab",Zh),Kk("temba-contact-badges",eu),Kk("temba-contact-pending",ou),Kk("temba-slider",nu),Kk("temba-content-menu",gu),Kk("temba-compose",bu),Kk("temba-color-picker",xu),Kk("temba-resizer",wu),Kk("temba-thumbnail",Su),Kk("temba-webchat",$u),Kk("temba-image-picker",Du),Kk("temba-mask",Mu),Kk("temba-user",Sl),Kk("temba-template-editor",zu),Kk("temba-toast",Iu),Kk("temba-chat",kh),Kk("temba-media-picker",Ou),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`
15954
15954
  :host {
15955
15955
  line-height: normal;
15956
15956
  }