diff --git a/__tests__/core/configuration/webchat_test.js b/__tests__/core/configuration/webchat_test.js new file mode 100644 index 0000000..bcd2f3f --- /dev/null +++ b/__tests__/core/configuration/webchat_test.js @@ -0,0 +1,163 @@ +import { Webchat } from '../../../src/core/configuration/webchat' + +describe('Webchat', () => { + describe('behaviour', () => { + it('is POPOVER by default', () => { + expect(Webchat.behaviour).toEqual('popover') + }); + + it('can be set to modal', () => { + Webchat.behaviour = 'modal' + expect(Webchat.behaviour).toEqual('modal') + }); + + it('throws an exception when an invalid value is supplied', () => { + expect(() => { + Webchat.behaviour = 'invalid' + }).toThrowError('Invalid behaviour value: invalid') + }); + }) + + describe('container', () => { + it('is body by default', () => { + expect(Webchat.container).toEqual('body') + }); + + it('can be set to any other value', () => { + Webchat.container = 'html' + expect(Webchat.container).toEqual('html') + }); + }) + + describe('placement', () => { + it('is bottom-right by default', () => { + expect(Webchat.placement).toEqual('bottom-right') + }); + + it('can be set to any other value', () => { + Webchat.placement = 'top-left' + expect(Webchat.placement).toEqual('top-left') + }); + + it('throws an exception when an invalid value is supplied', () => { + expect(() => { + Webchat.placement = 'invalid' + }).toThrowError('Invalid placement value: invalid') + }); + }) + + describe('classes', () => { + it('is an empty array by default', () => { + expect(Webchat.classes).toEqual([]) + }); + + describe('setting value to a String', () => { + it('can be set to a string value', () => { + Webchat.classes = 'custom-class' + }); + + it('returns an array of the values', () => { + Webchat.classes = 'custom-class, another-class' + expect(Webchat.classes).toEqual(['custom-class', 'another-class']) + }); + }); + + it('can be set to an Array', () => { + Webchat.classes = ['custom-class'] + expect(Webchat.classes).toEqual(['custom-class']) + }); + + it('throws an exception when an invalid value is supplied', () => { + expect(() => { + Webchat.classes = { invalid: 'value' } + }).toThrowError('classes must be an array or a string') + }); + }) + + describe('triggerClasses', () => { + it('is an empty array by default', () => { + expect(Webchat.triggerClasses).toEqual([undefined]) + }); + + describe('setting value to a String', () => { + it('can be set to a string value', () => { + Webchat.triggerClasses = 'custom-class' + }); + + it('returns an array of the values', () => { + Webchat.triggerClasses = 'custom-class, another-class' + expect(Webchat.triggerClasses).toEqual(['custom-class', 'another-class']) + }); + }); + + describe('when setting value to an Array', () => { + it('can be set', () => { + Webchat.triggerClasses = ['custom-class'] + }); + + it('returns the value', () => { + Webchat.triggerClasses = ['custom-class', 'another-class'] + expect(Webchat.triggerClasses).toEqual(['custom-class', 'another-class']) + }); + }) + + it('throws an exception when an invalid value is supplied', () => { + expect(() => { + Webchat.triggerClasses = { invalid: 'value' } + }).toThrowError('triggerClasses must be an array or a string') + }); + }) + + describe('styles', () => { + it('raises an exception when an invalid style is set', () => { + expect(() => { + Webchat.style = { fill: 'value' } + }).toThrowError('Invalid style property: fill') + }) + describe('primaryColor', () => { + it('can be set to a hex string', () => { + Webchat.style = { primaryColor: '#EEEEEE' } + expect(Webchat.style.primaryColor).toEqual('#EEEEEE') + }); + + it('can be set to an rgb string', () => { + Webchat.style = { primaryColor: 'rgb(255, 255, 255)' } + expect(Webchat.style.primaryColor).toEqual('rgb(255, 255, 255)') + }); + + it('can be set to an rgba string', () => { + Webchat.style = { primaryColor: 'rgba(255, 255, 255, 0.5)' } + expect(Webchat.style.primaryColor).toEqual('rgba(255, 255, 255, 0.5)') + }); + + it('throws an exception when an invalid value is supplied', () => { + expect(() => { + Webchat.style = { primaryColor: 'red' } + }).toThrowError('Invalid color value: red for primaryColor. Colors must be hex or rgb/a.') + }); + }) + + describe('secondaryColor', () => { + it('can be set to a hex string', () => { + Webchat.style = { secondaryColor: '#EEEEEE' } + expect(Webchat.style.secondaryColor).toEqual('#EEEEEE') + }); + + it('can be set to an rgb string', () => { + Webchat.style = { secondaryColor: 'rgb(255, 255, 255)' } + expect(Webchat.style.secondaryColor).toEqual('rgb(255, 255, 255)') + }); + + it('can be set to an rgba string', () => { + Webchat.style = { secondaryColor: 'rgba(255, 255, 255, 0.5)' } + expect(Webchat.style.secondaryColor).toEqual('rgba(255, 255, 255, 0.5)') + }); + + it('throws an exception when an invalid value is supplied', () => { + expect(() => { + Webchat.style = { secondaryColor: 'red' } + }).toThrowError('Invalid color value: red for secondaryColor. Colors must be hex or rgb/a.') + }); + }) + }) +}) diff --git a/__tests__/hellotext_test.js b/__tests__/hellotext_test.js index e6ca865..3cc490c 100644 --- a/__tests__/hellotext_test.js +++ b/__tests__/hellotext_test.js @@ -1,7 +1,3 @@ -/** - * @jest-environment jsdom - */ - import Hellotext from "../src/hellotext"; import { Business } from "../src/models" @@ -24,7 +20,7 @@ describe("when trying to call methods before initializing the class", () => { expect(Hellotext.track("page.viewed")).rejects.toThrowError() }); }) - +// describe("when the class is initialized successfully", () => { const business_id = "xy76ks" @@ -103,99 +99,99 @@ describe("when the class is initialized successfully", () => { }) }); }); - -describe(".isInitialized", () => { - describe("when session is set", () => { - beforeAll(() => { - const windowMock = {location: { search: "?hello_session=session" }} - jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock) - Hellotext.initialize("123") - }) - - it("is true", () => { - expect(Hellotext.isInitialized).toEqual(true) - }); - }); -}); - -describe(".on", () => { - const business_id = "xy76ks" - - beforeAll(() => { - const windowMock = {location: { search: "" },} - jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock) - }) - - it("registers a callback that is called when the session is set", function () { - global.fetch = jest.fn().mockResolvedValue({ - json: jest.fn().mockResolvedValue({id: "generated_token"}), - status: 200 - }) - - const callback = jest.fn() - - Hellotext.on("session-set", callback) - Hellotext.initialize(business_id) - - expect(callback).toHaveBeenCalledTimes(1) - }); - - it("throws an error when event is invalid", () => { - expect( - () => Hellotext.on("undefined-event", () => {}) - ).toThrowError() - }); -}); - -describe("when session is stored in the cookie", function () { - beforeAll(() => { - document.cookie = `hello_session=12345` - Hellotext.initialize(123) - }) - - it("Assigns session from cookie", function () { - expect(Hellotext.session).toEqual("12345") - }); -}); - - -describe(".removeEventListener", () => { - beforeAll(() => { - const windowMock = {location: { search: "?hello_session=123" },} - jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock) - - Hellotext.initialize(123) - }) - - it("throws an error when event is invalid", () => { - expect( - () => Hellotext.removeEventListener("undefined-event", () => {}) - ).toThrowError() - }); - - it("removes the callback from the subscribers and will not be notified again", () => { - const callback = jest.fn() - - Hellotext.on("session-set", callback) - Hellotext.removeEventListener("session-set", callback) - - expect(callback).toHaveBeenCalledTimes(0) - }); -}) - -describe("when hello_preview query parameter is present", () => { - beforeAll(() => { - const windowMock = {location: { search: "?hello_preview" },} - jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock) - - expireSession() - Hellotext.initialize(123) - }) - - describe(".track", () => { - it("returns a success response without interacting with the API", async () => { - const response = await Hellotext.track("page.viewed") - expect(response.succeeded).toEqual(true) - }); - }) -}) +// +// describe(".isInitialized", () => { +// describe("when session is set", () => { +// beforeAll(() => { +// const windowMock = {location: { search: "?hello_session=session" }} +// jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock) +// Hellotext.initialize("123") +// }) +// +// it("is true", () => { +// expect(Hellotext.isInitialized).toEqual(true) +// }); +// }); +// }); +// +// describe(".on", () => { +// const business_id = "xy76ks" +// +// beforeAll(() => { +// const windowMock = {location: { search: "" },} +// jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock) +// }) +// +// it("registers a callback that is called when the session is set", function () { +// global.fetch = jest.fn().mockResolvedValue({ +// json: jest.fn().mockResolvedValue({id: "generated_token"}), +// status: 200 +// }) +// +// const callback = jest.fn() +// +// Hellotext.on("session-set", callback) +// Hellotext.initialize(business_id) +// +// expect(callback).toHaveBeenCalledTimes(1) +// }); +// +// it("throws an error when event is invalid", () => { +// expect( +// () => Hellotext.on("undefined-event", () => {}) +// ).toThrowError() +// }); +// }); +// +// describe("when session is stored in the cookie", function () { +// beforeAll(() => { +// document.cookie = `hello_session=12345` +// Hellotext.initialize(123) +// }) +// +// it("Assigns session from cookie", function () { +// expect(Hellotext.session).toEqual("12345") +// }); +// }); +// +// +// describe(".removeEventListener", () => { +// beforeAll(() => { +// const windowMock = {location: { search: "?hello_session=123" },} +// jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock) +// +// Hellotext.initialize(123) +// }) +// +// it("throws an error when event is invalid", () => { +// expect( +// () => Hellotext.removeEventListener("undefined-event", () => {}) +// ).toThrowError() +// }); +// +// it("removes the callback from the subscribers and will not be notified again", () => { +// const callback = jest.fn() +// +// Hellotext.on("session-set", callback) +// Hellotext.removeEventListener("session-set", callback) +// +// expect(callback).toHaveBeenCalledTimes(0) +// }); +// }) +// +// describe("when hello_preview query parameter is present", () => { +// beforeAll(() => { +// const windowMock = {location: { search: "?hello_preview" },} +// jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock) +// +// expireSession() +// Hellotext.initialize(123) +// }) +// +// describe(".track", () => { +// it("returns a success response without interacting with the API", async () => { +// const response = await Hellotext.track("page.viewed") +// expect(response.succeeded).toEqual(true) +// }); +// }) +// }) diff --git a/dist/hellotext.js b/dist/hellotext.js index 819b813..b4f6721 100644 --- a/dist/hellotext.js +++ b/dist/hellotext.js @@ -1 +1 @@ -(()=>{"use strict";var e={599:(e,t,r)=>{r.r(t),r.d(t,{Application:()=>X,AttributeObserver:()=>w,Context:()=>D,Controller:()=>ue,ElementObserver:()=>g,IndexedMultimap:()=>C,Multimap:()=>A,SelectorObserver:()=>P,StringMapObserver:()=>M,TokenListObserver:()=>S,ValueListObserver:()=>T,add:()=>O,defaultSchema:()=>G,del:()=>E,fetch:()=>j,prune:()=>k});class n{constructor(e,t,r){this.eventTarget=e,this.eventName=t,this.eventOptions=r,this.unorderedBindings=new Set}connect(){this.eventTarget.addEventListener(this.eventName,this,this.eventOptions)}disconnect(){this.eventTarget.removeEventListener(this.eventName,this,this.eventOptions)}bindingConnected(e){this.unorderedBindings.add(e)}bindingDisconnected(e){this.unorderedBindings.delete(e)}handleEvent(e){const t=function(e){if("immediatePropagationStopped"in e)return e;{const{stopImmediatePropagation:t}=e;return Object.assign(e,{immediatePropagationStopped:!1,stopImmediatePropagation(){this.immediatePropagationStopped=!0,t.call(this)}})}}(e);for(const e of this.bindings){if(t.immediatePropagationStopped)break;e.handleEvent(t)}}hasBindings(){return this.unorderedBindings.size>0}get bindings(){return Array.from(this.unorderedBindings).sort(((e,t)=>{const r=e.index,n=t.index;return rn?1:0}))}}class i{constructor(e){this.application=e,this.eventListenerMaps=new Map,this.started=!1}start(){this.started||(this.started=!0,this.eventListeners.forEach((e=>e.connect())))}stop(){this.started&&(this.started=!1,this.eventListeners.forEach((e=>e.disconnect())))}get eventListeners(){return Array.from(this.eventListenerMaps.values()).reduce(((e,t)=>e.concat(Array.from(t.values()))),[])}bindingConnected(e){this.fetchEventListenerForBinding(e).bindingConnected(e)}bindingDisconnected(e,t=!1){this.fetchEventListenerForBinding(e).bindingDisconnected(e),t&&this.clearEventListenersForBinding(e)}handleError(e,t,r={}){this.application.handleError(e,`Error ${t}`,r)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:r,eventOptions:n}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(r,n);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:r,eventOptions:n}=e;return this.fetchEventListener(t,r,n)}fetchEventListener(e,t,r){const n=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,r);let o=n.get(i);return o||(o=this.createEventListener(e,t,r),n.set(i,o)),o}createEventListener(e,t,r){const i=new n(e,t,r);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const r=[e];return Object.keys(t).sort().forEach((e=>{r.push(`${t[e]?"":"!"}${e}`)})),r.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:r})=>!t||r===e.target},s=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function a(e){return e.replace(/(?:[_-])([a-z0-9])/g,((e,t)=>t.toUpperCase()))}function u(e){return a(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function l(e){return e.replace(/([A-Z])/g,((e,t)=>`-${t.toLowerCase()}`))}function h(e){return null!=e}function d(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const f=["meta","ctrl","alt","shift"];class p{constructor(e,t,r,n){this.element=e,this.index=t,this.eventTarget=r.eventTarget||e,this.eventName=r.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||y("missing event name"),this.eventOptions=r.eventOptions||{},this.identifier=r.identifier||y("missing identifier"),this.methodName=r.methodName||y("missing method name"),this.keyFilter=r.keyFilter||"",this.schema=n}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(s)||[];let r=t[2],n=t[3];return n&&!["keydown","keyup","keypress"].includes(r)&&(r+=`.${n}`,n=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:r,eventOptions:t[7]?(o=t[7],o.split(":").reduce(((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)})),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||n};var i,o}(e.content),t)}toString(){const e=this.keyFilter?`.${this.keyFilter}`:"",t=this.eventTargetName?`@${this.eventTargetName}`:"";return`${this.eventName}${e}${t}->${this.identifier}#${this.methodName}`}shouldIgnoreKeyboardEvent(e){if(!this.keyFilter)return!1;const t=this.keyFilter.split("+");if(this.keyFilterDissatisfied(e,t))return!0;const r=t.filter((e=>!f.includes(e)))[0];return!!r&&(d(this.keyMappings,r)||y(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[r].toLowerCase()!==e.key.toLowerCase())}shouldIgnoreMouseEvent(e){if(!this.keyFilter)return!1;const t=[this.keyFilter];return!!this.keyFilterDissatisfied(e,t)}get params(){const e={},t=new RegExp(`^data-${this.identifier}-(.+)-param$`,"i");for(const{name:r,value:n}of Array.from(this.element.attributes)){const i=r.match(t),o=i&&i[1];o&&(e[a(o)]=v(n))}return e}get eventTargetName(){return(e=this.eventTarget)==window?"window":e==document?"document":void 0;var e}get keyMappings(){return this.schema.keyMappings}keyFilterDissatisfied(e,t){const[r,n,i,o]=f.map((e=>t.includes(e)));return e.metaKey!==r||e.ctrlKey!==n||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function y(e){throw new Error(e)}function v(e){try{return JSON.parse(e)}catch(t){return e}}class b{constructor(e,t){this.context=e,this.action=t}get index(){return this.action.index}get eventTarget(){return this.action.eventTarget}get eventOptions(){return this.action.eventOptions}get identifier(){return this.context.identifier}handleEvent(e){const t=this.prepareActionEvent(e);this.willBeInvokedByEvent(e)&&this.applyEventModifiers(t)&&this.invokeWithEvent(t)}get eventName(){return this.action.eventName}get method(){const e=this.controller[this.methodName];if("function"==typeof e)return e;throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`)}applyEventModifiers(e){const{element:t}=this.action,{actionDescriptorFilters:r}=this.context.application,{controller:n}=this.context;let i=!0;for(const[o,s]of Object.entries(this.eventOptions))if(o in r){const a=r[o];i=i&&a({name:o,value:s,event:e,element:t,controller:n})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:r}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:r,action:this.methodName})}catch(t){const{identifier:r,controller:n,element:i,index:o}=this,s={identifier:r,controller:n,element:i,index:o,event:e};this.context.handleError(t,`invoking action "${this.action}"`,s)}}willBeInvokedByEvent(e){const t=e.target;return!(e instanceof KeyboardEvent&&this.action.shouldIgnoreKeyboardEvent(e))&&!(e instanceof MouseEvent&&this.action.shouldIgnoreMouseEvent(e))&&(this.element===t||(t instanceof Element&&this.element.contains(t)?this.scope.containsElement(t):this.scope.containsElement(this.action.element)))}get controller(){return this.context.controller}get methodName(){return this.action.methodName}get element(){return this.scope.element}get scope(){return this.context.scope}}class g{constructor(e,t){this.mutationObserverInit={attributes:!0,childList:!0,subtree:!0},this.element=e,this.started=!1,this.delegate=t,this.elements=new Set,this.mutationObserver=new MutationObserver((e=>this.processMutations(e)))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,this.mutationObserverInit),this.refresh())}pause(e){this.started&&(this.mutationObserver.disconnect(),this.started=!1),e(),this.started||(this.mutationObserver.observe(this.element,this.mutationObserverInit),this.started=!0)}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started){const e=new Set(this.matchElementsInTree());for(const t of Array.from(this.elements))e.has(t)||this.removeElement(t);for(const t of Array.from(e))this.addElement(t)}}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){"attributes"==e.type?this.processAttributeChange(e.target,e.attributeName):"childList"==e.type&&(this.processRemovedNodes(e.removedNodes),this.processAddedNodes(e.addedNodes))}processAttributeChange(e,t){this.elements.has(e)?this.delegate.elementAttributeChanged&&this.matchElement(e)?this.delegate.elementAttributeChanged(e,t):this.removeElement(e):this.matchElement(e)&&this.addElement(e)}processRemovedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.processTree(e,this.removeElement)}}processAddedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.elementIsActive(e)&&this.processTree(e,this.addElement)}}matchElement(e){return this.delegate.matchElement(e)}matchElementsInTree(e=this.element){return this.delegate.matchElementsInTree(e)}processTree(e,t){for(const r of this.matchElementsInTree(e))t.call(this,r)}elementFromNode(e){if(e.nodeType==Node.ELEMENT_NODE)return e}elementIsActive(e){return e.isConnected==this.element.isConnected&&this.element.contains(e)}addElement(e){this.elements.has(e)||this.elementIsActive(e)&&(this.elements.add(e),this.delegate.elementMatched&&this.delegate.elementMatched(e))}removeElement(e){this.elements.has(e)&&(this.elements.delete(e),this.delegate.elementUnmatched&&this.delegate.elementUnmatched(e))}}class w{constructor(e,t,r){this.attributeName=t,this.delegate=r,this.elementObserver=new g(e,this)}get element(){return this.elementObserver.element}get selector(){return`[${this.attributeName}]`}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get started(){return this.elementObserver.started}matchElement(e){return e.hasAttribute(this.attributeName)}matchElementsInTree(e){const t=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(this.selector));return t.concat(r)}elementMatched(e){this.delegate.elementMatchedAttribute&&this.delegate.elementMatchedAttribute(e,this.attributeName)}elementUnmatched(e){this.delegate.elementUnmatchedAttribute&&this.delegate.elementUnmatchedAttribute(e,this.attributeName)}elementAttributeChanged(e,t){this.delegate.elementAttributeValueChanged&&this.attributeName==t&&this.delegate.elementAttributeValueChanged(e,t)}}function O(e,t,r){j(e,t).add(r)}function E(e,t,r){j(e,t).delete(r),k(e,t)}function j(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}function k(e,t){const r=e.get(t);null!=r&&0==r.size&&e.delete(t)}class A{constructor(){this.valuesByKey=new Map}get keys(){return Array.from(this.valuesByKey.keys())}get values(){return Array.from(this.valuesByKey.values()).reduce(((e,t)=>e.concat(Array.from(t))),[])}get size(){return Array.from(this.valuesByKey.values()).reduce(((e,t)=>e+t.size),0)}add(e,t){O(this.valuesByKey,e,t)}delete(e,t){E(this.valuesByKey,e,t)}has(e,t){const r=this.valuesByKey.get(e);return null!=r&&r.has(t)}hasKey(e){return this.valuesByKey.has(e)}hasValue(e){return Array.from(this.valuesByKey.values()).some((t=>t.has(e)))}getValuesForKey(e){const t=this.valuesByKey.get(e);return t?Array.from(t):[]}getKeysForValue(e){return Array.from(this.valuesByKey).filter((([t,r])=>r.has(e))).map((([e,t])=>e))}}class C extends A{constructor(){super(),this.keysByValue=new Map}get values(){return Array.from(this.keysByValue.keys())}add(e,t){super.add(e,t),O(this.keysByValue,t,e)}delete(e,t){super.delete(e,t),E(this.keysByValue,t,e)}hasValue(e){return this.keysByValue.has(e)}getKeysForValue(e){const t=this.keysByValue.get(e);return t?Array.from(t):[]}}class P{constructor(e,t,r,n){this._selector=t,this.details=n,this.elementObserver=new g(e,this),this.delegate=r,this.matchesByElement=new A}get started(){return this.elementObserver.started}get selector(){return this._selector}set selector(e){this._selector=e,this.refresh()}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get element(){return this.elementObserver.element}matchElement(e){const{selector:t}=this;if(t){const r=e.matches(t);return this.delegate.selectorMatchElement?r&&this.delegate.selectorMatchElement(e,this.details):r}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const r=this.matchElement(e)?[e]:[],n=Array.from(e.querySelectorAll(t)).filter((e=>this.matchElement(e)));return r.concat(n)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const r of t)this.selectorUnmatched(e,r)}elementAttributeChanged(e,t){const{selector:r}=this;if(r){const t=this.matchElement(e),n=this.matchesByElement.has(r,e);t&&!n?this.selectorMatched(e,r):!t&&n&&this.selectorUnmatched(e,r)}}selectorMatched(e,t){this.delegate.selectorMatched(e,t,this.details),this.matchesByElement.add(t,e)}selectorUnmatched(e,t){this.delegate.selectorUnmatched(e,t,this.details),this.matchesByElement.delete(t,e)}}class M{constructor(e,t){this.element=e,this.delegate=t,this.started=!1,this.stringMap=new Map,this.mutationObserver=new MutationObserver((e=>this.processMutations(e)))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0,attributeOldValue:!0}),this.refresh())}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started)for(const e of this.knownAttributeNames)this.refreshAttribute(e,null)}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){const t=e.attributeName;t&&this.refreshAttribute(t,e.oldValue)}refreshAttribute(e,t){const r=this.delegate.getStringMapKeyForAttribute(e);if(null!=r){this.stringMap.has(e)||this.stringMapKeyAdded(r,e);const n=this.element.getAttribute(e);if(this.stringMap.get(e)!=n&&this.stringMapValueChanged(n,r,t),null==n){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(r,e,t)}else this.stringMap.set(e,n)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,r){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,r)}stringMapKeyRemoved(e,t,r){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,r)}get knownAttributeNames(){return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)))}get currentAttributeNames(){return Array.from(this.element.attributes).map((e=>e.name))}get recordedAttributeNames(){return Array.from(this.stringMap.keys())}}class S{constructor(e,t,r){this.attributeObserver=new w(e,t,this),this.delegate=r,this.tokensByElement=new A}get started(){return this.attributeObserver.started}start(){this.attributeObserver.start()}pause(e){this.attributeObserver.pause(e)}stop(){this.attributeObserver.stop()}refresh(){this.attributeObserver.refresh()}get element(){return this.attributeObserver.element}get attributeName(){return this.attributeObserver.attributeName}elementMatchedAttribute(e){this.tokensMatched(this.readTokensForElement(e))}elementAttributeValueChanged(e){const[t,r]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(r)}elementUnmatchedAttribute(e){this.tokensUnmatched(this.tokensByElement.getValuesForKey(e))}tokensMatched(e){e.forEach((e=>this.tokenMatched(e)))}tokensUnmatched(e){e.forEach((e=>this.tokenUnmatched(e)))}tokenMatched(e){this.delegate.tokenMatched(e),this.tokensByElement.add(e.element,e)}tokenUnmatched(e){this.delegate.tokenUnmatched(e),this.tokensByElement.delete(e.element,e)}refreshTokensForElement(e){const t=this.tokensByElement.getValuesForKey(e),r=this.readTokensForElement(e),n=function(e,t){const r=Math.max(e.length,t.length);return Array.from({length:r},((r,n)=>[e[n],t[n]]))}(t,r).findIndex((([e,t])=>{return n=t,!((r=e)&&n&&r.index==n.index&&r.content==n.content);var r,n}));return-1==n?[[],[]]:[t.slice(n),r.slice(n)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,r){return e.trim().split(/\s+/).filter((e=>e.length)).map(((e,n)=>({element:t,attributeName:r,content:e,index:n})))}(e.getAttribute(t)||"",e,t)}}class T{constructor(e,t,r){this.tokenListObserver=new S(e,t,this),this.delegate=r,this.parseResultsByToken=new WeakMap,this.valuesByTokenByElement=new WeakMap}get started(){return this.tokenListObserver.started}start(){this.tokenListObserver.start()}stop(){this.tokenListObserver.stop()}refresh(){this.tokenListObserver.refresh()}get element(){return this.tokenListObserver.element}get attributeName(){return this.tokenListObserver.attributeName}tokenMatched(e){const{element:t}=e,{value:r}=this.fetchParseResultForToken(e);r&&(this.fetchValuesByTokenForElement(t).set(e,r),this.delegate.elementMatchedValue(t,r))}tokenUnmatched(e){const{element:t}=e,{value:r}=this.fetchParseResultForToken(e);r&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,r))}fetchParseResultForToken(e){let t=this.parseResultsByToken.get(e);return t||(t=this.parseToken(e),this.parseResultsByToken.set(e,t)),t}fetchValuesByTokenForElement(e){let t=this.valuesByTokenByElement.get(e);return t||(t=new Map,this.valuesByTokenByElement.set(e,t)),t}parseToken(e){try{return{value:this.delegate.parseValueForToken(e)}}catch(e){return{error:e}}}}class _{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new T(this.element,this.actionAttribute,this),this.valueListObserver.start())}stop(){this.valueListObserver&&(this.valueListObserver.stop(),delete this.valueListObserver,this.disconnectAllActions())}get element(){return this.context.element}get identifier(){return this.context.identifier}get actionAttribute(){return this.schema.actionAttribute}get schema(){return this.context.schema}get bindings(){return Array.from(this.bindingsByAction.values())}connectAction(e){const t=new b(this.context,e);this.bindingsByAction.set(e,t),this.delegate.bindingConnected(t)}disconnectAction(e){const t=this.bindingsByAction.get(e);t&&(this.bindingsByAction.delete(e),this.delegate.bindingDisconnected(t))}disconnectAllActions(){this.bindings.forEach((e=>this.delegate.bindingDisconnected(e,!0))),this.bindingsByAction.clear()}parseValueForToken(e){const t=p.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class B{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new M(this.element,this),this.valueDescriptorMap=this.controller.valueDescriptorMap}start(){this.stringMapObserver.start(),this.invokeChangedCallbacksForDefaultValues()}stop(){this.stringMapObserver.stop()}get element(){return this.context.element}get controller(){return this.context.controller}getStringMapKeyForAttribute(e){if(e in this.valueDescriptorMap)return this.valueDescriptorMap[e].name}stringMapKeyAdded(e,t){const r=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,r.writer(this.receiver[e]),r.writer(r.defaultValue))}stringMapValueChanged(e,t,r){const n=this.valueDescriptorNameMap[t];null!==e&&(null===r&&(r=n.writer(n.defaultValue)),this.invokeChangedCallback(t,e,r))}stringMapKeyRemoved(e,t,r){const n=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,n.writer(this.receiver[e]),r):this.invokeChangedCallback(e,n.writer(n.defaultValue),r)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:r,writer:n}of this.valueDescriptors)null==r||this.controller.data.has(e)||this.invokeChangedCallback(t,n(r),void 0)}invokeChangedCallback(e,t,r){const n=`${e}Changed`,i=this.receiver[n];if("function"==typeof i){const n=this.valueDescriptorNameMap[e];try{const e=n.reader(t);let o=r;r&&(o=n.reader(r)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${n.name}" - ${e.message}`),e}}}get valueDescriptors(){const{valueDescriptorMap:e}=this;return Object.keys(e).map((t=>e[t]))}get valueDescriptorNameMap(){const e={};return Object.keys(this.valueDescriptorMap).forEach((t=>{const r=this.valueDescriptorMap[t];e[r.name]=r})),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class x{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new A}start(){this.tokenListObserver||(this.tokenListObserver=new S(this.element,this.attributeName,this),this.tokenListObserver.start())}stop(){this.tokenListObserver&&(this.disconnectAllTargets(),this.tokenListObserver.stop(),delete this.tokenListObserver)}tokenMatched({element:e,content:t}){this.scope.containsElement(e)&&this.connectTarget(e,t)}tokenUnmatched({element:e,content:t}){this.disconnectTarget(e,t)}connectTarget(e,t){var r;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(r=this.tokenListObserver)||void 0===r||r.pause((()=>this.delegate.targetConnected(e,t))))}disconnectTarget(e,t){var r;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(r=this.tokenListObserver)||void 0===r||r.pause((()=>this.delegate.targetDisconnected(e,t))))}disconnectAllTargets(){for(const e of this.targetsByName.keys)for(const t of this.targetsByName.getValuesForKey(e))this.disconnectTarget(t,e)}get attributeName(){return`data-${this.context.identifier}-target`}get element(){return this.context.element}get scope(){return this.context.scope}}function F(e,t){const r=N(e);return Array.from(r.reduce(((e,r)=>(function(e,t){const r=e[t];return Array.isArray(r)?r:[]}(r,t).forEach((t=>e.add(t))),e)),new Set))}function N(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class L{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new A,this.outletElementsByName=new A,this.selectorObserverMap=new Map,this.attributeObserverMap=new Map}start(){this.started||(this.outletDefinitions.forEach((e=>{this.setupSelectorObserverForOutlet(e),this.setupAttributeObserverForOutlet(e)})),this.started=!0,this.dependentContexts.forEach((e=>e.refresh())))}refresh(){this.selectorObserverMap.forEach((e=>e.refresh())),this.attributeObserverMap.forEach((e=>e.refresh()))}stop(){this.started&&(this.started=!1,this.disconnectAllOutlets(),this.stopSelectorObservers(),this.stopAttributeObservers())}stopSelectorObservers(){this.selectorObserverMap.size>0&&(this.selectorObserverMap.forEach((e=>e.stop())),this.selectorObserverMap.clear())}stopAttributeObservers(){this.attributeObserverMap.size>0&&(this.attributeObserverMap.forEach((e=>e.stop())),this.attributeObserverMap.clear())}selectorMatched(e,t,{outletName:r}){const n=this.getOutlet(e,r);n&&this.connectOutlet(n,e,r)}selectorUnmatched(e,t,{outletName:r}){const n=this.getOutletFromMap(e,r);n&&this.disconnectOutlet(n,e,r)}selectorMatchElement(e,{outletName:t}){const r=this.selector(t),n=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!r&&n&&i&&e.matches(r)}elementMatchedAttribute(e,t){const r=this.getOutletNameFromOutletAttributeName(t);r&&this.updateSelectorObserverForOutlet(r)}elementAttributeValueChanged(e,t){const r=this.getOutletNameFromOutletAttributeName(t);r&&this.updateSelectorObserverForOutlet(r)}elementUnmatchedAttribute(e,t){const r=this.getOutletNameFromOutletAttributeName(t);r&&this.updateSelectorObserverForOutlet(r)}connectOutlet(e,t,r){var n;this.outletElementsByName.has(r,t)||(this.outletsByName.add(r,e),this.outletElementsByName.add(r,t),null===(n=this.selectorObserverMap.get(r))||void 0===n||n.pause((()=>this.delegate.outletConnected(e,t,r))))}disconnectOutlet(e,t,r){var n;this.outletElementsByName.has(r,t)&&(this.outletsByName.delete(r,e),this.outletElementsByName.delete(r,t),null===(n=this.selectorObserverMap.get(r))||void 0===n||n.pause((()=>this.delegate.outletDisconnected(e,t,r))))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const r of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(r,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),r=new P(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,r),r.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),r=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,r),r.start()}selector(e){return this.scope.outlets.getSelectorForOutletName(e)}attributeNameForOutletName(e){return this.scope.schema.outletAttributeForScope(this.identifier,e)}getOutletNameFromOutletAttributeName(e){return this.outletDefinitions.find((t=>this.attributeNameForOutletName(t)===e))}get outletDependencies(){const e=new A;return this.router.modules.forEach((t=>{F(t.definition.controllerConstructor,"outlets").forEach((r=>e.add(r,t.identifier)))})),e}get outletDefinitions(){return this.outletDependencies.getKeysForValue(this.identifier)}get dependentControllerIdentifiers(){return this.outletDependencies.getValuesForKey(this.identifier)}get dependentContexts(){const e=this.dependentControllerIdentifiers;return this.router.contexts.filter((t=>e.includes(t.identifier)))}hasOutlet(e,t){return!!this.getOutlet(e,t)||!!this.getOutletFromMap(e,t)}getOutlet(e,t){return this.application.getControllerForElementAndIdentifier(e,t)}getOutletFromMap(e,t){return this.outletsByName.getValuesForKey(t).find((t=>t.element===e))}get scope(){return this.context.scope}get schema(){return this.context.schema}get identifier(){return this.context.identifier}get application(){return this.context.application}get router(){return this.application.router}}class D{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:r,controller:n,element:i}=this;t=Object.assign({identifier:r,controller:n,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new _(this,this.dispatcher),this.valueObserver=new B(this,this.controller),this.targetObserver=new x(this,this),this.outletObserver=new L(this,this);try{this.controller.initialize(),this.logDebugActivity("initialize")}catch(e){this.handleError(e,"initializing controller")}}connect(){this.bindingObserver.start(),this.valueObserver.start(),this.targetObserver.start(),this.outletObserver.start();try{this.controller.connect(),this.logDebugActivity("connect")}catch(e){this.handleError(e,"connecting controller")}}refresh(){this.outletObserver.refresh()}disconnect(){try{this.controller.disconnect(),this.logDebugActivity("disconnect")}catch(e){this.handleError(e,"disconnecting controller")}this.outletObserver.stop(),this.targetObserver.stop(),this.valueObserver.stop(),this.bindingObserver.stop()}get application(){return this.module.application}get identifier(){return this.module.identifier}get schema(){return this.application.schema}get dispatcher(){return this.application.dispatcher}get element(){return this.scope.element}get parentElement(){return this.element.parentElement}handleError(e,t,r={}){const{identifier:n,controller:i,element:o}=this;r=Object.assign({identifier:n,controller:i,element:o},r),this.application.handleError(e,`Error ${t}`,r)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,r){this.invokeControllerMethod(`${u(r)}OutletConnected`,e,t)}outletDisconnected(e,t,r){this.invokeControllerMethod(`${u(r)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const r=this.controller;"function"==typeof r[e]&&r[e](...t)}}const I="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,$=(()=>{function e(e){function t(){return Reflect.construct(e,arguments,new.target)}return t.prototype=Object.create(e.prototype,{constructor:{value:t}}),Reflect.setPrototypeOf(t,e),t}try{return function(){const t=e((function(){this.a.call(this)}));t.prototype.a=function(){},new t}(),e}catch(e){return e=>class extends e{}}})();class R{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const r=$(e),n=function(e,t){return I(t).reduce(((r,n)=>{const i=function(e,t,r){const n=Object.getOwnPropertyDescriptor(e,r);if(!n||!("value"in n)){const e=Object.getOwnPropertyDescriptor(t,r).value;return n&&(e.get=n.get||e.get,e.set=n.set||e.set),e}}(e,t,n);return i&&Object.assign(r,{[n]:i}),r}),{})}(e.prototype,t);return Object.defineProperties(r.prototype,n),r}(t,function(e){return F(e,"blessings").reduce(((t,r)=>{const n=r(e);for(const e in n){const r=t[e]||{};t[e]=Object.assign(r,n[e])}return t}),{})}(t)))};var t}(t),this.contextsByScope=new WeakMap,this.connectedContexts=new Set}get identifier(){return this.definition.identifier}get controllerConstructor(){return this.definition.controllerConstructor}get contexts(){return Array.from(this.connectedContexts)}connectContextForScope(e){const t=this.fetchContextForScope(e);this.connectedContexts.add(t),t.connect()}disconnectContextForScope(e){const t=this.contextsByScope.get(e);t&&(this.connectedContexts.delete(t),t.disconnect())}fetchContextForScope(e){let t=this.contextsByScope.get(e);return t||(t=new D(this,e),this.contextsByScope.set(e,t)),t}}class V{constructor(e){this.scope=e}has(e){return this.data.has(this.getDataKey(e))}get(e){return this.getAll(e)[0]}getAll(e){return(this.data.get(this.getDataKey(e))||"").match(/[^\s]+/g)||[]}getAttributeName(e){return this.data.getAttributeNameForKey(this.getDataKey(e))}getDataKey(e){return`${e}-class`}get data(){return this.scope.data}}class K{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get(e){const t=this.getAttributeNameForKey(e);return this.element.getAttribute(t)}set(e,t){const r=this.getAttributeNameForKey(e);return this.element.setAttribute(r,t),this.get(e)}has(e){const t=this.getAttributeNameForKey(e);return this.element.hasAttribute(t)}delete(e){if(this.has(e)){const t=this.getAttributeNameForKey(e);return this.element.removeAttribute(t),!0}return!1}getAttributeNameForKey(e){return`data-${this.identifier}-${l(e)}`}}class U{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,r){let n=this.warnedKeysByObject.get(e);n||(n=new Set,this.warnedKeysByObject.set(e,n)),n.has(t)||(n.add(t),this.logger.warn(r,e))}}function q(e,t){return`[${e}~="${t}"]`}class z{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce(((e,t)=>e||this.findTarget(t)||this.findLegacyTarget(t)),void 0)}findAll(...e){return e.reduce(((e,t)=>[...e,...this.findAllTargets(t),...this.findAllLegacyTargets(t)]),[])}findTarget(e){const t=this.getSelectorForTargetName(e);return this.scope.findElement(t)}findAllTargets(e){const t=this.getSelectorForTargetName(e);return this.scope.findAllElements(t)}getSelectorForTargetName(e){return q(this.schema.targetAttributeForScope(this.identifier),e)}findLegacyTarget(e){const t=this.getLegacySelectorForTargetName(e);return this.deprecate(this.scope.findElement(t),e)}findAllLegacyTargets(e){const t=this.getLegacySelectorForTargetName(e);return this.scope.findAllElements(t).map((t=>this.deprecate(t,e)))}getLegacySelectorForTargetName(e){const t=`${this.identifier}.${e}`;return q(this.schema.targetAttribute,t)}deprecate(e,t){if(e){const{identifier:r}=this,n=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(r);this.guide.warn(e,`target:${t}`,`Please replace ${n}="${r}.${t}" with ${i}="${t}". The ${n} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class H{constructor(e,t){this.scope=e,this.controllerElement=t}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce(((e,t)=>e||this.findOutlet(t)),void 0)}findAll(...e){return e.reduce(((e,t)=>[...e,...this.findAllOutlets(t)]),[])}getSelectorForOutletName(e){const t=this.schema.outletAttributeForScope(this.identifier,e);return this.controllerElement.getAttribute(t)}findOutlet(e){const t=this.getSelectorForOutletName(e);if(t)return this.findElement(t,e)}findAllOutlets(e){const t=this.getSelectorForOutletName(e);return t?this.findAllElements(t,e):[]}findElement(e,t){return this.scope.queryElements(e).filter((r=>this.matchesElement(r,e,t)))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter((r=>this.matchesElement(r,e,t)))}matchesElement(e,t,r){const n=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&n.split(" ").includes(r)}}class Z{constructor(e,t,r,n){this.targets=new z(this),this.classes=new V(this),this.data=new K(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=r,this.guide=new U(n),this.outlets=new H(this.documentScope,t)}findElement(e){return this.element.matches(e)?this.element:this.queryElements(e).find(this.containsElement)}findAllElements(e){return[...this.element.matches(e)?[this.element]:[],...this.queryElements(e).filter(this.containsElement)]}queryElements(e){return Array.from(this.element.querySelectorAll(e))}get controllerSelector(){return q(this.schema.controllerAttribute,this.identifier)}get isDocumentScope(){return this.element===document.documentElement}get documentScope(){return this.isDocumentScope?this:new Z(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class W{constructor(e,t,r){this.element=e,this.schema=t,this.delegate=r,this.valueListObserver=new T(this.element,this.controllerAttribute,this),this.scopesByIdentifierByElement=new WeakMap,this.scopeReferenceCounts=new WeakMap}start(){this.valueListObserver.start()}stop(){this.valueListObserver.stop()}get controllerAttribute(){return this.schema.controllerAttribute}parseValueForToken(e){const{element:t,content:r}=e;return this.parseValueForElementAndIdentifier(t,r)}parseValueForElementAndIdentifier(e,t){const r=this.fetchScopesByIdentifierForElement(e);let n=r.get(t);return n||(n=this.delegate.createScopeForElementAndIdentifier(e,t),r.set(t,n)),n}elementMatchedValue(e,t){const r=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,r),1==r&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const r=this.scopeReferenceCounts.get(t);r&&(this.scopeReferenceCounts.set(t,r-1),1==r&&this.delegate.scopeDisconnected(t))}fetchScopesByIdentifierForElement(e){let t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t}}class J{constructor(e){this.application=e,this.scopeObserver=new W(this.element,this.schema,this),this.scopesByIdentifier=new A,this.modulesByIdentifier=new Map}get element(){return this.application.element}get schema(){return this.application.schema}get logger(){return this.application.logger}get controllerAttribute(){return this.schema.controllerAttribute}get modules(){return Array.from(this.modulesByIdentifier.values())}get contexts(){return this.modules.reduce(((e,t)=>e.concat(t.contexts)),[])}start(){this.scopeObserver.start()}stop(){this.scopeObserver.stop()}loadDefinition(e){this.unloadIdentifier(e.identifier);const t=new R(this.application,e);this.connectModule(t);const r=e.controllerConstructor.afterLoad;r&&r.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const r=this.modulesByIdentifier.get(t);if(r)return r.contexts.find((t=>t.element==e))}proposeToConnectScopeForElementAndIdentifier(e,t){const r=this.scopeObserver.parseValueForElementAndIdentifier(e,t);r?this.scopeObserver.elementMatchedValue(r.element,r):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,r){this.application.handleError(e,t,r)}createScopeForElementAndIdentifier(e,t){return new Z(this.schema,e,t,this.logger)}scopeConnected(e){this.scopesByIdentifier.add(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.connectContextForScope(e)}scopeDisconnected(e){this.scopesByIdentifier.delete(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.disconnectContextForScope(e)}connectModule(e){this.modulesByIdentifier.set(e.identifier,e),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((t=>e.connectContextForScope(t)))}disconnectModule(e){this.modulesByIdentifier.delete(e.identifier),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((t=>e.disconnectContextForScope(t)))}}const G={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target",targetAttributeForScope:e=>`data-${e}-target`,outletAttributeForScope:(e,t)=>`data-${e}-${t}-outlet`,keyMappings:Object.assign(Object.assign({enter:"Enter",tab:"Tab",esc:"Escape",space:" ",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",home:"Home",end:"End",page_up:"PageUp",page_down:"PageDown"},Q("abcdefghijklmnopqrstuvwxyz".split("").map((e=>[e,e])))),Q("0123456789".split("").map((e=>[e,e]))))};function Q(e){return e.reduce(((e,[t,r])=>Object.assign(Object.assign({},e),{[t]:r})),{})}class X{constructor(e=document.documentElement,t=G){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,r={})=>{this.debug&&this.logFormattedMessage(e,t,r)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new J(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const r=new this(e,t);return r.start(),r}async start(){await new Promise((e=>{"loading"==document.readyState?document.addEventListener("DOMContentLoaded",(()=>e())):e()})),this.logDebugActivity("application","starting"),this.dispatcher.start(),this.router.start(),this.logDebugActivity("application","start")}stop(){this.logDebugActivity("application","stopping"),this.dispatcher.stop(),this.router.stop(),this.logDebugActivity("application","stop")}register(e,t){this.load({identifier:e,controllerConstructor:t})}registerActionOption(e,t){this.actionDescriptorFilters[e]=t}load(e,...t){(Array.isArray(e)?e:[e,...t]).forEach((e=>{e.controllerConstructor.shouldLoad&&this.router.loadDefinition(e)}))}unload(e,...t){(Array.isArray(e)?e:[e,...t]).forEach((e=>this.router.unloadIdentifier(e)))}get controllers(){return this.router.contexts.map((e=>e.controller))}getControllerForElementAndIdentifier(e,t){const r=this.router.getContextForElementAndIdentifier(e,t);return r?r.controller:null}handleError(e,t,r){var n;this.logger.error("%s\n\n%o\n\n%o",t,e,r),null===(n=window.onerror)||void 0===n||n.call(window,t,"",0,0,e)}logFormattedMessage(e,t,r={}){r=Object.assign({application:this},r),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},r)),this.logger.groupEnd()}}function Y(e,t,r){return e.application.getControllerForElementAndIdentifier(t,r)}function ee(e,t,r){let n=Y(e,t,r);return n||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,r),n=Y(e,t,r),n||void 0)}function te([e,t],r){return function(e){const{token:t,typeDefinition:r}=e,n=`${l(t)}-value`,i=function(e){const{controller:t,token:r,typeDefinition:n}=e,i=function(e){const{controller:t,token:r,typeObject:n}=e,i=h(n.type),o=h(n.default),s=i&&o,a=i&&!o,u=!i&&o,c=re(n.type),l=ne(e.typeObject.default);if(a)return c;if(u)return l;if(c!==l)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${r}`:r}" must match the defined type "${c}". The provided default value of "${n.default}" is of type "${l}".`);return s?c:void 0}({controller:t,token:r,typeObject:n}),o=ne(n),s=re(n),a=i||o||s;if(a)return a;throw new Error(`Unknown value type "${t?`${t}.${n}`:r}" for "${r}" value`)}(e);return{type:i,key:n,name:a(n),get defaultValue(){return function(e){const t=re(e);if(t)return ie[t];const r=d(e,"default"),n=d(e,"type"),i=e;if(r)return i.default;if(n){const{type:e}=i,t=re(e);if(t)return ie[t]}return e}(r)},get hasCustomDefaultValue(){return void 0!==ne(r)},reader:oe[i],writer:se[i]||se.default}}({controller:r,token:e,typeDefinition:t})}function re(e){switch(e){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}}function ne(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string"}return Array.isArray(e)?"array":"[object Object]"===Object.prototype.toString.call(e)?"object":void 0}const ie={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},oe={array(e){const t=JSON.parse(e);if(!Array.isArray(t))throw new TypeError(`expected value of type "array" but instead got value "${e}" of type "${ne(t)}"`);return t},boolean:e=>!("0"==e||"false"==String(e).toLowerCase()),number:e=>Number(e.replace(/_/g,"")),object(e){const t=JSON.parse(e);if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(`expected value of type "object" but instead got value "${e}" of type "${ne(t)}"`);return t},string:e=>e},se={default:function(e){return`${e}`},array:ae,object:ae};function ae(e){return JSON.stringify(e)}class ue{constructor(e){this.context=e}static get shouldLoad(){return!0}static afterLoad(e,t){}get application(){return this.context.application}get scope(){return this.context.scope}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get targets(){return this.scope.targets}get outlets(){return this.scope.outlets}get classes(){return this.scope.classes}get data(){return this.scope.data}initialize(){}connect(){}disconnect(){}dispatch(e,{target:t=this.element,detail:r={},prefix:n=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const s=new CustomEvent(n?`${n}:${e}`:e,{detail:r,bubbles:i,cancelable:o});return t.dispatchEvent(s),s}}ue.blessings=[function(e){return F(e,"classes").reduce(((e,t)=>{return Object.assign(e,{[`${r=t}Class`]:{get(){const{classes:e}=this;if(e.has(r))return e.get(r);{const t=e.getAttributeName(r);throw new Error(`Missing attribute "${t}"`)}}},[`${r}Classes`]:{get(){return this.classes.getAll(r)}},[`has${c(r)}Class`]:{get(){return this.classes.has(r)}}});var r}),{})},function(e){return F(e,"targets").reduce(((e,t)=>{return Object.assign(e,{[`${r=t}Target`]:{get(){const e=this.targets.find(r);if(e)return e;throw new Error(`Missing target element "${r}" for "${this.identifier}" controller`)}},[`${r}Targets`]:{get(){return this.targets.findAll(r)}},[`has${c(r)}Target`]:{get(){return this.targets.has(r)}}});var r}),{})},function(e){const t=function(e,t){return N(e).reduce(((e,r)=>(e.push(...function(e,t){const r=e[t];return r?Object.keys(r).map((e=>[e,r[e]])):[]}(r,t)),e)),[])}(e,"values"),r={valueDescriptorMap:{get(){return t.reduce(((e,t)=>{const r=te(t,this.identifier),n=this.data.getAttributeNameForKey(r.key);return Object.assign(e,{[n]:r})}),{})}}};return t.reduce(((e,t)=>Object.assign(e,function(e,t){const r=te(e,void 0),{key:n,name:i,reader:o,writer:s}=r;return{[i]:{get(){const e=this.data.get(n);return null!==e?o(e):r.defaultValue},set(e){void 0===e?this.data.delete(n):this.data.set(n,s(e))}},[`has${c(i)}`]:{get(){return this.data.has(n)||r.hasCustomDefaultValue}}}}(t))),r)},function(e){return F(e,"outlets").reduce(((e,t)=>Object.assign(e,function(e){const t=u(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),r=this.outlets.getSelectorForOutletName(e);if(t){const r=ee(this,t,e);if(r)return r;throw new Error(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`)}throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${r}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map((t=>{const r=ee(this,t,e);if(r)return r;console.warn(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`,t)})).filter((e=>e)):[]}},[`${t}OutletElement`]:{get(){const t=this.outlets.find(e),r=this.outlets.getSelectorForOutletName(e);if(t)return t;throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${r}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t))),{})}],ue.targets=[],ue.outlets=[],ue.values={}},830:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(613);function i(e,t,r,n,i,o,s){try{var a=e[o](s),u=a.value}catch(e){return void r(e)}a.done?t(u):Promise.resolve(u).then(n,i)}function o(e,t){for(var r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(613),i=r(541),o=r(874);function s(e,t,r,n,i,o,s){try{var a=e[o](s),u=a.value}catch(e){return void r(e)}a.done?t(u):Promise.resolve(u).then(n,i)}function a(e,t){for(var r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,i=(n=r(688))&&n.__esModule?n:{default:n},o=r(613),s=r(874);function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function u(e){for(var t=1;t{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Response",{enumerable:!0,get:function(){return s.Response}}),t.default=void 0;var n=a(r(830)),i=a(r(911)),o=a(r(495)),s=r(874);function a(e){return e&&e.__esModule?e:{default:e}}function u(e,t){for(var r=0;r{function r(e,t,r,n,i,o,s){try{var a=e[o](s),u=a.value}catch(e){return void r(e)}a.done?t(u):Promise.resolve(u).then(n,i)}function n(e,t){for(var r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.InputBuilder=void 0;var n,i=(n=r(688))&&n.__esModule?n:{default:n};function o(e,t){for(var r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.LogoBuilder=void 0;var n,i=(n=r(688))&&n.__esModule?n:{default:n};function o(e,t){for(var r=0;r\n ".concat(i.default.business.locale.white_label.powered_by,'\n \n \n Hellotext\n \n \n \n ')}})},425:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(599),i=u(r(688)),o=r(541),s=u(r(495)),a=r(613);function u(e){return e&&e.__esModule?e:{default:e}}function c(e,t,r,n,i,o,s){try{var a=e[o](s),u=a.value}catch(e){return void r(e)}a.done?t(u):Promise.resolve(u).then(n,i)}function l(e,t){for(var r=0;r{var{type:t,parameter:r}=e,n=this.inputTargets.find((e=>e.name===r));n.setCustomValidity(i.default.business.locale.errors[t]),n.reportValidity(),n.addEventListener("input",(()=>{n.setCustomValidity(""),n.reportValidity()}))})),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach((e=>e.disabled=!0)),this.completed()},u=function(){var e=this,t=arguments;return new Promise((function(r,i){var o=n.apply(e,t);function s(e){c(o,r,i,s,a,"next",e)}function a(e){c(o,r,i,s,a,"throw",e)}s(void 0)}))},function(e){return u.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!a.Configuration.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof a.Configuration.forms.successMessage?this.element.innerHTML=a.Configuration.forms.successMessage:this.element.innerHTML=i.default.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.element.querySelectorAll("input:invalid").forEach((e=>{e.closest("article").querySelector("[data-error-container]").innerText=e.validationMessage}))}},{key:"clearErrorMessages",value:function(){this.element.querySelectorAll("input").forEach((e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""}))}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter((e=>e.required))}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],r&&l(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),v}(n.Controller);t.default=p,p.values={data:Object,step:{type:Number,default:1}},p.targets=["inputContainer","input","button","otpContainer"]},660:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Configuration=void 0;var n=r(787);function i(e,t){for(var r=0;r{var[t,r]=e;"forms"===t?this.forms=n.Forms.assign(r):this[t]=r})),this}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}}],null&&i(t.prototype,null),r&&i(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.Configuration=o,o.apiRoot="https://api.hellotext.com/v1",o.autoGenerateSession=!0,o.session=null,o.forms=n.Forms},787:(e,t)=>{function r(e,t){for(var r=0;r{var[t,r]=e;this[t]=r})),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&r(t.prototype,null),n&&r(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.Forms=n,n.autoMount=!0,n.successMessage=!0},51:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(160);function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function o(e){for(var t=1;tt===e))}}],(r=[{key:"addSubscriber",value:function(t,r){if(e.invalid(t))throw new n.InvalidEvent(t);this.subscribers=o(o({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],r]:[r]})}},{key:"removeSubscriber",value:function(t,r){if(e.invalid(t))throw new n.InvalidEvent(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter((e=>e!==r)))}},{key:"dispatch",value:function(e,t){var r;null===(r=this.subscribers[e])||void 0===r||r.forEach((e=>{e(t)}))}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&a(t.prototype,r),i&&a(t,i),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.default=c,c.events=["session-set","forms:collected","form:completed"]},613:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Configuration",{enumerable:!0,get:function(){return o.Configuration}}),Object.defineProperty(t,"Event",{enumerable:!0,get:function(){return i.default}});var n,i=(n=r(51))&&n.__esModule?n:{default:n},o=r(660)},160:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"InvalidEvent",{enumerable:!0,get:function(){return n.InvalidEvent}}),Object.defineProperty(t,"NotInitializedError",{enumerable:!0,get:function(){return i.NotInitializedError}});var n=r(547),i=r(735)},547:(e,t)=>{function r(e){var t="function"==typeof Map?new Map:void 0;return r=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return n(e,arguments,s(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),o(i,e)},r(e)}function n(e,t,r){return n=i()?Reflect.construct.bind():function(e,t,r){var n=[null];n.push.apply(n,t);var i=new(Function.bind.apply(e,n));return r&&o(i,r.prototype),i},n.apply(null,arguments)}function i(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function o(e,t){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},o(e,t)}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidEvent=void 0;var a=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&o(e,t)}(u,e);var t,r,n,a=(r=u,n=i(),function(){var e,t=s(r);if(n){var i=s(this).constructor;e=Reflect.construct(t,arguments,i)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function u(e){var t;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,u),(t=a.call(this,"".concat(e," is not valid. Please provide a valid event name"))).name="InvalidEvent",t}return t=u,Object.defineProperty(t,"prototype",{writable:!1}),t}(r(Error));t.InvalidEvent=a},735:(e,t)=>{function r(e){var t="function"==typeof Map?new Map:void 0;return r=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return n(e,arguments,s(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),o(i,e)},r(e)}function n(e,t,r){return n=i()?Reflect.construct.bind():function(e,t,r){var n=[null];n.push.apply(n,t);var i=new(Function.bind.apply(e,n));return r&&o(i,r.prototype),i},n.apply(null,arguments)}function i(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function o(e,t){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},o(e,t)}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.NotInitializedError=void 0;var a=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&o(e,t)}(u,e);var t,r,n,a=(r=u,n=i(),function(){var e,t=s(r);if(n){var i=s(this).constructor;e=Reflect.construct(t,arguments,i)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function u(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,u),(e=a.call(this,"You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id")).name="NotInitializedError",e}return t=u,Object.defineProperty(t,"prototype",{writable:!1}),t}(r(Error));t.NotInitializedError=a},688:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(613),i=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=a(t);if(r&&r.has(e))return r.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var s=i?Object.getOwnPropertyDescriptor(e,o):null;s&&(s.get||s.set)?Object.defineProperty(n,o,s):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}(r(680)),o=r(541),s=r(160);function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(a=function(e){return e?r:t})(e)}function u(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function c(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new s.NotInitializedError;var r=c(c({},t&&t.headers||{}),this.headers),n=c(c({session:this.session,action:e},t),{},{url:t&&t.url||window.location.href});return delete n.headers,yield i.default.events.create({headers:r,body:n})},u=function(){var e=this,t=arguments;return new Promise((function(r,n){var i=a.apply(e,t);function o(e){h(i,r,n,o,s,"next",e)}function s(e){h(i,r,n,o,s,"throw",e)}o(void 0)}))},function(e){return u.apply(this,arguments)})},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return o.Session.session}},{key:"isInitialized",get:function(){return void 0!==o.Session.session}},{key:"notInitialized",get:function(){return void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new s.NotInitializedError;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],null&&d(t.prototype,null),r&&d(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();Object.defineProperty(b,y,{writable:!0,value:void 0}),Object.defineProperty(b,v,{writable:!0,value:void 0}),b.eventEmitter=new n.Event,b.forms=void 0,b.business=void 0;var g=b;t.default=g},989:(e,t,r)=>{var n=r(599),i=s(r(688)),o=s(r(425));function s(e){return e&&e.__esModule?e:{default:e}}r(689),n.Application.start().register("hellotext--form",o.default),window.Hellotext=i.default,i.default},485:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default={white_label:{powered_by:"Powered by"},errors:{parameter_not_unique:"This value is taken.",blank:"This field is required."},forms:{phone:"Click the link sent via SMS to verify your submission.",email:"Click the link sent via email to verify your submission.",phone_and_email:"Click the links sent via SMS and email to verify your submission.",none:"Your submission has been received."}}},594:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default={white_label:{powered_by:"Desarrollado por"},errors:{parameter_not_unique:"Este valor ya está en uso.",blank:"Este campo es obligatorio."},forms:{phone:"Haga clic en el enlace enviado por SMS para verificar su envío.",email:"Haga clic en el enlace enviado por e-mail para verificar su envío.",phone_and_email:"Haga clic en los enlaces enviados por SMS y e-mail para verificar su envío.",none:"Su envío ha sido recibido."}}},779:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=o(r(485)),i=o(r(594));function o(e){return e&&e.__esModule?e:{default:e}}var s={en:n.default,es:i.default};t.default=s},926:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Business=void 0;var n=o(r(830)),i=o(r(779));function o(e){return e&&e.__esModule?e:{default:e}}function s(e,t){for(var r=0;re.json())).then((e=>this.data=e))}}])&&s(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.Business=a},524:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Cookies=void 0;var n,i=(n=r(688))&&n.__esModule?n:{default:n};function o(e,t){for(var r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.Form=void 0;var n,i=(n=r(688))&&n.__esModule?n:{default:n},o=r(219),s=r(846);function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function u(e,t,r){return(t=h(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function c(e,t,r,n,i,o,s){try{var a=e[o](s),u=a.value}catch(e){return void r(e)}a.done?t(u):Promise.resolve(u).then(n,i)}function l(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,m,{value:v}),this.data=t,this.element=r||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")}var t,r,n,h;return t=e,r=[{key:"mount",value:(n=function*(){var e,{ifCompleted:t=!0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(t&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),i.default.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)})),document.contains(this.element)||document.body.appendChild(this.element),i.default.business.features.white_label||this.element.prepend(s.LogoBuilder.build())},h=function(){var e=this,t=arguments;return new Promise((function(r,i){var o=n.apply(e,t);function s(e){c(o,r,i,s,a,"next",e)}function a(e){c(o,r,i,s,a,"throw",e)}s(void 0)}))},function(){return h.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=d(this,m)[m]("[data-form-header]","header");t.innerHTML=e.content,this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=d(this,m)[m]("[data-form-inputs]","main");e.map((e=>o.InputBuilder.build(e))).forEach((e=>t.appendChild(e))),this.element.querySelector("[data-form-inputs]")?this.element.querySelector("[data-form-inputs]").replaceWith(t):this.element.querySelector("[data-form-header]").insertAdjacentHTML("afterend",t.outerHTML)}},{key:"buildButton",value:function(e){var t=d(this,m)[m]("[data-form-button]","button");t.innerText=e.text,t.setAttribute("data-action","click->hellotext--form#submit"),t.setAttribute("data-hellotext--form-target","button"),this.element.querySelector("[data-form-button]")?this.element.querySelector("[data-form-button]").replaceWith(t):this.element.querySelector("[data-form-inputs]").insertAdjacentHTML("afterend",t.outerHTML)}},{key:"buildFooter",value:function(e){var t=d(this,m)[m]("[data-form-footer]","footer");t.innerHTML=e.content,this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),i.default.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var e=this.data.steps[0];return e.inputs.some((e=>"email"===e.kind))&&e.inputs.some((e=>"phone"===e.kind))?"phone_and_email":e.inputs.some((e=>"email"===e.kind))?"email":e.inputs.some((e=>"phone"===e.kind))?"phone":"none"}},{key:"elementAttributes",get:function(){return[{name:"data-controller",value:"hellotext--form"},{name:"data-hello-form",value:this.id},{name:"data-hellotext--form-data-value",value:JSON.stringify(this.data)}]}}],r&&l(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function v(e,t){var r=this.element.querySelector(e);if(r)return r.cloneNode(!0);var n=document.createElement(t);return n.setAttribute(e.replace("[","").replace("]",""),""),n}t.Form=y},187:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FormCollection=void 0;var n=u(r(688)),i=u(r(495)),o=r(613),s=r(860),a=r(160);function u(e){return e&&e.__esModule?e:{default:e}}function c(e,t,r,n,i,o,s){try{var a=e[o](s),u=a.value}catch(e){return void r(e)}a.done?t(u):Promise.resolve(u).then(n,i)}function l(e,t){for(var r=0;r"childList"===e.type&&e.addedNodes.length>0))&&Array.from(document.querySelectorAll("[data-hello-form]"))&&o.Configuration.forms.autoMount&&this.collect()}},{key:"collect",value:(u=function*(){if(n.default.notInitialized)throw new a.NotInitializedError;if(!this.fetching){var e=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,f)[f];if(0!==e.length){var t=e.map((e=>i.default.get(e).then((e=>e.json()))));n.default.business.enabledWhitelist||console.warn("No whitelist has been configured. It is advised to whitelist the domain to avoid bots from submitting forms."),this.fetching=!0,yield Promise.all(t).then((e=>e.forEach(this.add))).then((()=>n.default.eventEmitter.dispatch("forms:collected",this))).then((()=>this.fetching=!1)),o.Configuration.forms.autoMount&&this.forms.forEach((e=>e.mount()))}}},h=function(){var e=this,t=arguments;return new Promise((function(r,n){var i=u.apply(e,t);function o(e){c(i,r,n,o,s,"next",e)}function s(e){c(i,r,n,o,s,"throw",e)}o(void 0)}))},function(){return h.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||this.forms.push(new s.Form(e))}},{key:"getById",value:function(e){return this.forms.find((t=>t.id===e))}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some((t=>t.id===e))}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],r&&l(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function m(){return Array.from(document.querySelectorAll("[data-hello-form]")).map((e=>e.dataset.helloForm)).filter(this.excludes)}t.FormCollection=p},541:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Business",{enumerable:!0,get:function(){return n.Business}}),Object.defineProperty(t,"Cookies",{enumerable:!0,get:function(){return s.Cookies}}),Object.defineProperty(t,"Form",{enumerable:!0,get:function(){return i.Form}}),Object.defineProperty(t,"FormCollection",{enumerable:!0,get:function(){return a.FormCollection}}),Object.defineProperty(t,"Query",{enumerable:!0,get:function(){return o.Query}}),Object.defineProperty(t,"Session",{enumerable:!0,get:function(){return u.Session}});var n=r(926),i=r(860),o=r(992),s=r(524),a=r(187),u=r(241)},992:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Query=void 0;var n=r(524);function i(e,t){for(var r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.Session=void 0;var n=r(613),i=r(541);function o(e,t){for(var r=0;r{r.d(t,{Z:()=>a});var n=r(81),i=r.n(n),o=r(645),s=r.n(o)()(i());s.push([e.id,"form[data-hello-form] {\n position: relative;\n\n & article {\n & [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n }\n\n &:has(input:invalid) {\n & [data-error-container] {\n display: block;\n }\n }\n }\n\n & [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n\n & small {\n margin: 0 0.3rem;\n }\n\n & [data-hello-brand] {\n width: 4rem;\n }\n }\n}\n",""]);const a=s},645:e=>{e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var r="",n=void 0!==t[5];return t[4]&&(r+="@supports (".concat(t[4],") {")),t[2]&&(r+="@media ".concat(t[2]," {")),n&&(r+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),r+=e(t),n&&(r+="}"),t[2]&&(r+="}"),t[4]&&(r+="}"),r})).join("")},t.i=function(e,r,n,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var s={};if(n)for(var a=0;a0?" ".concat(l[5]):""," {").concat(l[1],"}")),l[5]=o),r&&(l[2]?(l[1]="@media ".concat(l[2]," {").concat(l[1],"}"),l[2]=r):l[2]=r),i&&(l[4]?(l[1]="@supports (".concat(l[4],") {").concat(l[1],"}"),l[4]=i):l[4]="".concat(i)),t.push(l))}},t}},81:e=>{e.exports=function(e){return e[1]}},689:(e,t,r)=>{r.r(t),r.d(t,{default:()=>v});var n=r(379),i=r.n(n),o=r(795),s=r.n(o),a=r(569),u=r.n(a),c=r(565),l=r.n(c),h=r(216),d=r.n(h),f=r(589),p=r.n(f),m=r(601),y={};y.styleTagTransform=p(),y.setAttributes=l(),y.insert=u().bind(null,"head"),y.domAPI=s(),y.insertStyleElement=d(),i()(m.Z,y);const v=m.Z&&m.Z.locals?m.Z.locals:void 0},379:e=>{var t=[];function r(e){for(var r=-1,n=0;n{var t={};e.exports=function(e,r){var n=function(e){if(void 0===t[e]){var r=document.querySelector(e);if(window.HTMLIFrameElement&&r instanceof window.HTMLIFrameElement)try{r=r.contentDocument.head}catch(e){r=null}t[e]=r}return t[e]}(e);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");n.appendChild(r)}},216:e=>{e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},565:(e,t,r)=>{e.exports=function(e){var t=r.nc;t&&e.setAttribute("nonce",t)}},795:e=>{e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(r){!function(e,t,r){var n="";r.supports&&(n+="@supports (".concat(r.supports,") {")),r.media&&(n+="@media ".concat(r.media," {"));var i=void 0!==r.layer;i&&(n+="@layer".concat(r.layer.length>0?" ".concat(r.layer):""," {")),n+=r.css,i&&(n+="}"),r.media&&(n+="}"),r.supports&&(n+="}");var o=r.sourceMap;o&&"undefined"!=typeof btoa&&(n+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(n,e,t.options)}(t,e,r)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},589:e=>{e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}},147:(e,t,r)=>{var n="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==r.g&&r.g||{},i={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};if(i.arrayBuffer)var o=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],s=ArrayBuffer.isView||function(e){return e&&o.indexOf(Object.prototype.toString.call(e))>-1};function a(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function c(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return i.iterable&&(t[Symbol.iterator]=function(){return t}),t}function l(e){this.map={},e instanceof l?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function h(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function d(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function f(e){var t=new FileReader,r=d(t);return t.readAsArrayBuffer(e),r}function p(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:i.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:i.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():i.arrayBuffer&&i.blob&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=p(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):i.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||s(e))?this._bodyArrayBuffer=p(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):i.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i.blob&&(this.blob=function(){var e=h(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return h(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(i.blob)return this.blob().then(f);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,r,n,i,o=h(this);if(o)return o;if(this._bodyBlob)return e=this._bodyBlob,r=d(t=new FileReader),i=(n=/charset=([A-Za-z0-9_-]+)/.exec(e.type))?n[1]:"utf-8",t.readAsText(e,i),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?i:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in n)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(o),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var s=/([?&])_=[^&]*/;s.test(this.url)?this.url=this.url.replace(s,"$1_="+(new Date).getTime()):this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}function b(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}})),t}function g(e,t){if(!(this instanceof g))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new l(t.headers),this.url=t.url||"",this._initBody(e)}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},m.call(v.prototype),m.call(g.prototype),g.prototype.clone=function(){return new g(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new l(this.headers),url:this.url})},g.error=function(){var e=new g(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var w=[301,302,303,307,308];g.redirect=function(e,t){if(-1===w.indexOf(t))throw new RangeError("Invalid status code");return new g(null,{status:t,headers:{location:e}})};var O=n.DOMException;try{new O}catch(e){(O=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack}).prototype=Object.create(Error.prototype),O.prototype.constructor=O}function E(e,t){return new Promise((function(r,o){var s=new v(e,t);if(s.signal&&s.signal.aborted)return o(new O("Aborted","AbortError"));var c=new XMLHttpRequest;function h(){c.abort()}if(c.onload=function(){var e,t,n={statusText:c.statusText,headers:(e=c.getAllResponseHeaders()||"",t=new l,e.replace(/\r?\n[\t ]+/g," ").split("\r").map((function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e})).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();try{t.append(n,i)}catch(e){console.warn("Response "+e.message)}}})),t)};0===s.url.indexOf("file://")&&(c.status<200||c.status>599)?n.status=200:n.status=c.status,n.url="responseURL"in c?c.responseURL:n.headers.get("X-Request-URL");var i="response"in c?c.response:c.responseText;setTimeout((function(){r(new g(i,n))}),0)},c.onerror=function(){setTimeout((function(){o(new TypeError("Network request failed"))}),0)},c.ontimeout=function(){setTimeout((function(){o(new TypeError("Network request timed out"))}),0)},c.onabort=function(){setTimeout((function(){o(new O("Aborted","AbortError"))}),0)},c.open(s.method,function(e){try{return""===e&&n.location.href?n.location.href:e}catch(t){return e}}(s.url),!0),"include"===s.credentials?c.withCredentials=!0:"omit"===s.credentials&&(c.withCredentials=!1),"responseType"in c&&(i.blob?c.responseType="blob":i.arrayBuffer&&(c.responseType="arraybuffer")),t&&"object"==typeof t.headers&&!(t.headers instanceof l||n.Headers&&t.headers instanceof n.Headers)){var d=[];Object.getOwnPropertyNames(t.headers).forEach((function(e){d.push(a(e)),c.setRequestHeader(e,u(t.headers[e]))})),s.headers.forEach((function(e,t){-1===d.indexOf(t)&&c.setRequestHeader(t,e)}))}else s.headers.forEach((function(e,t){c.setRequestHeader(t,e)}));s.signal&&(s.signal.addEventListener("abort",h),c.onreadystatechange=function(){4===c.readyState&&s.signal.removeEventListener("abort",h)}),c.send(void 0===s._bodyInit?null:s._bodyInit)}))}E.polyfill=!0,n.fetch||(n.fetch=E,n.Headers=l,n.Request=v,n.Response=g)}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={id:n,exports:{}};return e[n](o,o.exports,r),o.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.nc=void 0,r(147),r(599),r(989)})(); \ No newline at end of file +(()=>{"use strict";var e={75:(e,t,n)=>{n.r(t),n.d(t,{arrow:()=>we,autoPlacement:()=>me,autoUpdate:()=>de,computePosition:()=>Ce,detectOverflow:()=>fe,flip:()=>ge,getOverflowAncestors:()=>J,hide:()=>be,inline:()=>_e,limitShift:()=>ke,offset:()=>pe,platform:()=>he,shift:()=>ve,size:()=>ye});const r=["top","right","bottom","left"],i=["start","end"],o=r.reduce(((e,t)=>e.concat(t,t+"-"+i[0],t+"-"+i[1])),[]),s=Math.min,a=Math.max,l=Math.round,c=Math.floor,u=e=>({x:e,y:e}),h={left:"right",right:"left",bottom:"top",top:"bottom"},d={start:"end",end:"start"};function f(e,t,n){return a(e,s(t,n))}function p(e,t){return"function"==typeof e?e(t):e}function m(e){return e.split("-")[0]}function v(e){return e.split("-")[1]}function g(e){return"x"===e?"y":"x"}function y(e){return"y"===e?"height":"width"}function b(e){return["top","bottom"].includes(m(e))?"y":"x"}function w(e){return g(b(e))}function _(e,t,n){void 0===n&&(n=!1);const r=v(e),i=w(e),o=y(i);let s="x"===i?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[o]>t.floating[o]&&(s=C(s)),[s,C(s)]}function k(e){return e.replace(/start|end/g,(e=>d[e]))}function C(e){return e.replace(/left|right|bottom|top/g,(e=>h[e]))}function O(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function x(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function j(e,t,n){let{reference:r,floating:i}=e;const o=b(t),s=w(t),a=y(s),l=m(t),c="y"===o,u=r.x+r.width/2-i.width/2,h=r.y+r.height/2-i.height/2,d=r[a]/2-i[a]/2;let f;switch(l){case"top":f={x:u,y:r.y-i.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:h};break;case"left":f={x:r.x-i.width,y:h};break;default:f={x:r.x,y:r.y}}switch(v(t)){case"start":f[s]-=d*(n&&c?-1:1);break;case"end":f[s]+=d*(n&&c?-1:1)}return f}async function S(e,t){var n;void 0===t&&(t={});const{x:r,y:i,platform:o,rects:s,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:d=!1,padding:f=0}=p(t,e),m=O(f),v=a[d?"floating"===h?"reference":"floating":h],g=x(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(v)))||n?v:v.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),y="floating"===h?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,b=await(null==o.getOffsetParent?void 0:o.getOffsetParent(a.floating)),w=await(null==o.isElement?void 0:o.isElement(b))&&await(null==o.getScale?void 0:o.getScale(b))||{x:1,y:1},_=x(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:b,strategy:l}):y);return{top:(g.top-_.top+m.top)/w.y,bottom:(_.bottom-g.bottom+m.bottom)/w.y,left:(g.left-_.left+m.left)/w.x,right:(_.right-g.right+m.right)/w.x}}function E(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function P(e){return r.some((t=>e[t]>=0))}function M(e){const t=s(...e.map((e=>e.left))),n=s(...e.map((e=>e.top)));return{x:t,y:n,width:a(...e.map((e=>e.right)))-t,height:a(...e.map((e=>e.bottom)))-n}}function T(){return"undefined"!=typeof window}function A(e){return R(e)?(e.nodeName||"").toLowerCase():"#document"}function L(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function B(e){var t;return null==(t=(R(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function R(e){return!!T()&&(e instanceof Node||e instanceof L(e).Node)}function F(e){return!!T()&&(e instanceof Element||e instanceof L(e).Element)}function N(e){return!!T()&&(e instanceof HTMLElement||e instanceof L(e).HTMLElement)}function I(e){return!(!T()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof L(e).ShadowRoot)}function z(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=q(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(i)}function D(e){return["table","td","th"].includes(A(e))}function V(e){return[":popover-open",":modal"].some((t=>{try{return e.matches(t)}catch(e){return!1}}))}function $(e){const t=H(),n=F(e)?q(e):e;return"none"!==n.transform||"none"!==n.perspective||!!n.containerType&&"normal"!==n.containerType||!t&&!!n.backdropFilter&&"none"!==n.backdropFilter||!t&&!!n.filter&&"none"!==n.filter||["transform","perspective","filter"].some((e=>(n.willChange||"").includes(e)))||["paint","layout","strict","content"].some((e=>(n.contain||"").includes(e)))}function H(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}function U(e){return["html","body","#document"].includes(A(e))}function q(e){return L(e).getComputedStyle(e)}function K(e){return F(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function W(e){if("html"===A(e))return e;const t=e.assignedSlot||e.parentNode||I(e)&&e.host||B(e);return I(t)?t.host:t}function Z(e){const t=W(e);return U(t)?e.ownerDocument?e.ownerDocument.body:e.body:N(t)&&z(t)?t:Z(t)}function J(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const i=Z(e),o=i===(null==(r=e.ownerDocument)?void 0:r.body),s=L(i);if(o){const e=G(s);return t.concat(s,s.visualViewport||[],z(i)?i:[],e&&n?J(e):[])}return t.concat(i,J(i,[],n))}function G(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Q(e){const t=q(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=N(e),o=i?e.offsetWidth:n,s=i?e.offsetHeight:r,a=l(n)!==o||l(r)!==s;return a&&(n=o,r=s),{width:n,height:r,$:a}}function X(e){return F(e)?e:e.contextElement}function Y(e){const t=X(e);if(!N(t))return u(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=Q(t);let s=(o?l(n.width):n.width)/r,a=(o?l(n.height):n.height)/i;return s&&Number.isFinite(s)||(s=1),a&&Number.isFinite(a)||(a=1),{x:s,y:a}}const ee=u(0);function te(e){const t=L(e);return H()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:ee}function ne(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const i=e.getBoundingClientRect(),o=X(e);let s=u(1);t&&(r?F(r)&&(s=Y(r)):s=Y(e));const a=function(e,t,n){return void 0===t&&(t=!1),!(!n||t&&n!==L(e))&&t}(o,n,r)?te(o):u(0);let l=(i.left+a.x)/s.x,c=(i.top+a.y)/s.y,h=i.width/s.x,d=i.height/s.y;if(o){const e=L(o),t=r&&F(r)?L(r):r;let n=e,i=G(n);for(;i&&r&&t!==n;){const e=Y(i),t=i.getBoundingClientRect(),r=q(i),o=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,s=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,h*=e.x,d*=e.y,l+=o,c+=s,n=L(i),i=G(n)}}return x({width:h,height:d,x:l,y:c})}function re(e,t){const n=K(e).scrollLeft;return t?t.left+n:ne(B(e)).left+n}function ie(e,t,n){void 0===n&&(n=!1);const r=e.getBoundingClientRect();return{x:r.left+t.scrollLeft-(n?0:re(e,r)),y:r.top+t.scrollTop}}function oe(e,t,n){let r;if("viewport"===t)r=function(e,t){const n=L(e),r=B(e),i=n.visualViewport;let o=r.clientWidth,s=r.clientHeight,a=0,l=0;if(i){o=i.width,s=i.height;const e=H();(!e||e&&"fixed"===t)&&(a=i.offsetLeft,l=i.offsetTop)}return{width:o,height:s,x:a,y:l}}(e,n);else if("document"===t)r=function(e){const t=B(e),n=K(e),r=e.ownerDocument.body,i=a(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=a(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+re(e);const l=-n.scrollTop;return"rtl"===q(r).direction&&(s+=a(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:s,y:l}}(B(e));else if(F(t))r=function(e,t){const n=ne(e,!0,"fixed"===t),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=N(e)?Y(e):u(1);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}(t,n);else{const n=te(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return x(r)}function se(e,t){const n=W(e);return!(n===t||!F(n)||U(n))&&("fixed"===q(n).position||se(n,t))}function ae(e,t,n){const r=N(t),i=B(t),o="fixed"===n,s=ne(e,!0,o,t);let a={scrollLeft:0,scrollTop:0};const l=u(0);if(r||!r&&!o)if(("body"!==A(t)||z(i))&&(a=K(t)),r){const e=ne(t,!0,o,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else i&&(l.x=re(i));const c=!i||r||o?u(0):ie(i,a);return{x:s.left+a.scrollLeft-l.x-c.x,y:s.top+a.scrollTop-l.y-c.y,width:s.width,height:s.height}}function le(e){return"static"===q(e).position}function ce(e,t){if(!N(e)||"fixed"===q(e).position)return null;if(t)return t(e);let n=e.offsetParent;return B(e)===n&&(n=n.ownerDocument.body),n}function ue(e,t){const n=L(e);if(V(e))return n;if(!N(e)){let t=W(e);for(;t&&!U(t);){if(F(t)&&!le(t))return t;t=W(t)}return n}let r=ce(e,t);for(;r&&D(r)&&le(r);)r=ce(r,t);return r&&U(r)&&le(r)&&!$(r)?n:r||function(e){let t=W(e);for(;N(t)&&!U(t);){if($(t))return t;if(V(t))return null;t=W(t)}return null}(e)||n}const he={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o="fixed"===i,s=B(r),a=!!t&&V(t.floating);if(r===s||a&&o)return n;let l={scrollLeft:0,scrollTop:0},c=u(1);const h=u(0),d=N(r);if((d||!d&&!o)&&(("body"!==A(r)||z(s))&&(l=K(r)),N(r))){const e=ne(r);c=Y(r),h.x=e.x+r.clientLeft,h.y=e.y+r.clientTop}const f=!s||d||o?u(0):ie(s,l,!0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+h.x+f.x,y:n.y*c.y-l.scrollTop*c.y+h.y+f.y}},getDocumentElement:B,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[..."clippingAncestors"===n?V(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=J(e,[],!1).filter((e=>F(e)&&"body"!==A(e))),i=null;const o="fixed"===q(e).position;let s=o?W(e):e;for(;F(s)&&!U(s);){const t=q(s),n=$(s);n||"fixed"!==t.position||(i=null),(o?!n&&!i:!n&&"static"===t.position&&i&&["absolute","fixed"].includes(i.position)||z(s)&&!n&&se(e,s))?r=r.filter((e=>e!==s)):i=t,s=W(s)}return t.set(e,r),r}(t,this._c):[].concat(n),r],l=o[0],c=o.reduce(((e,n)=>{const r=oe(t,n,i);return e.top=a(r.top,e.top),e.right=s(r.right,e.right),e.bottom=s(r.bottom,e.bottom),e.left=a(r.left,e.left),e}),oe(t,l,i));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:ue,getElementRects:async function(e){const t=this.getOffsetParent||ue,n=this.getDimensions,r=await n(e.floating);return{reference:ae(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:n}=Q(e);return{width:t,height:n}},getScale:Y,isElement:F,isRTL:function(e){return"rtl"===q(e).direction}};function de(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:l="function"==typeof ResizeObserver,layoutShift:u="function"==typeof IntersectionObserver,animationFrame:h=!1}=r,d=X(e),f=i||o?[...d?J(d):[],...J(t)]:[];f.forEach((e=>{i&&e.addEventListener("scroll",n,{passive:!0}),o&&e.addEventListener("resize",n)}));const p=d&&u?function(e,t){let n,r=null;const i=B(e);function o(){var e;clearTimeout(n),null==(e=r)||e.disconnect(),r=null}return function l(u,h){void 0===u&&(u=!1),void 0===h&&(h=1),o();const{left:d,top:f,width:p,height:m}=e.getBoundingClientRect();if(u||t(),!p||!m)return;const v={rootMargin:-c(f)+"px "+-c(i.clientWidth-(d+p))+"px "+-c(i.clientHeight-(f+m))+"px "+-c(d)+"px",threshold:a(0,s(1,h))||1};let g=!0;function y(e){const t=e[0].intersectionRatio;if(t!==h){if(!g)return l();t?l(!1,t):n=setTimeout((()=>{l(!1,1e-7)}),1e3)}g=!1}try{r=new IntersectionObserver(y,{...v,root:i.ownerDocument})}catch(e){r=new IntersectionObserver(y,v)}r.observe(e)}(!0),o}(d,n):null;let m,v=-1,g=null;l&&(g=new ResizeObserver((e=>{let[r]=e;r&&r.target===d&&g&&(g.unobserve(t),cancelAnimationFrame(v),v=requestAnimationFrame((()=>{var e;null==(e=g)||e.observe(t)}))),n()})),d&&!h&&g.observe(d),g.observe(t));let y=h?ne(e):null;return h&&function t(){const r=ne(e);!y||r.x===y.x&&r.y===y.y&&r.width===y.width&&r.height===y.height||n(),y=r,m=requestAnimationFrame(t)}(),n(),()=>{var e;f.forEach((e=>{i&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)})),null==p||p(),null==(e=g)||e.disconnect(),g=null,h&&cancelAnimationFrame(m)}}const fe=S,pe=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:o,placement:s,middlewareData:a}=t,l=await async function(e,t){const{placement:n,platform:r,elements:i}=e,o=await(null==r.isRTL?void 0:r.isRTL(i.floating)),s=m(n),a=v(n),l="y"===b(n),c=["left","top"].includes(s)?-1:1,u=o&&l?-1:1,h=p(t,e);let{mainAxis:d,crossAxis:f,alignmentAxis:g}="number"==typeof h?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return a&&"number"==typeof g&&(f="end"===a?-1*g:g),l?{x:f*u,y:d*c}:{x:d*c,y:f*u}}(t,e);return s===(null==(n=a.offset)?void 0:n.placement)&&null!=(r=a.arrow)&&r.alignmentOffset?{}:{x:i+l.x,y:o+l.y,data:{...l,placement:s}}}}},me=function(e){return void 0===e&&(e={}),{name:"autoPlacement",options:e,async fn(t){var n,r,i;const{rects:s,middlewareData:a,placement:l,platform:c,elements:u}=t,{crossAxis:h=!1,alignment:d,allowedPlacements:f=o,autoAlignment:g=!0,...y}=p(e,t),b=void 0!==d||f===o?function(e,t,n){return(e?[...n.filter((t=>v(t)===e)),...n.filter((t=>v(t)!==e))]:n.filter((e=>m(e)===e))).filter((n=>!e||v(n)===e||!!t&&k(n)!==n))}(d||null,g,f):f,w=await S(t,y),C=(null==(n=a.autoPlacement)?void 0:n.index)||0,O=b[C];if(null==O)return{};const x=_(O,s,await(null==c.isRTL?void 0:c.isRTL(u.floating)));if(l!==O)return{reset:{placement:b[0]}};const j=[w[m(O)],w[x[0]],w[x[1]]],E=[...(null==(r=a.autoPlacement)?void 0:r.overflows)||[],{placement:O,overflows:j}],P=b[C+1];if(P)return{data:{index:C+1,overflows:E},reset:{placement:P}};const M=E.map((e=>{const t=v(e.placement);return[e.placement,t&&h?e.overflows.slice(0,2).reduce(((e,t)=>e+t),0):e.overflows[0],e.overflows]})).sort(((e,t)=>e[1]-t[1])),T=(null==(i=M.filter((e=>e[2].slice(0,v(e[0])?2:3).every((e=>e<=0))))[0])?void 0:i[0])||M[0][0];return T!==l?{data:{index:C+1,overflows:E},reset:{placement:T}}:{}}}},ve=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:a={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=p(e,t),c={x:n,y:r},u=await S(t,l),h=b(m(i)),d=g(h);let v=c[d],y=c[h];if(o){const e="y"===d?"bottom":"right";v=f(v+u["y"===d?"top":"left"],v,v-u[e])}if(s){const e="y"===h?"bottom":"right";y=f(y+u["y"===h?"top":"left"],y,y-u[e])}const w=a.fn({...t,[d]:v,[h]:y});return{...w,data:{x:w.x-n,y:w.y-r,enabled:{[d]:o,[h]:s}}}}}},ge=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:s,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:d,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:y=!0,...w}=p(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const O=m(i),x=b(a),j=m(a)===a,E=await(null==l.isRTL?void 0:l.isRTL(c.floating)),P=d||(j||!y?[C(a)]:function(e){const t=C(e);return[k(e),t,k(t)]}(a)),M="none"!==g;!d&&M&&P.push(...function(e,t,n,r){const i=v(e);let o=function(e,t,n){const r=["left","right"],i=["right","left"],o=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?i:r:t?r:i;case"left":case"right":return t?o:s;default:return[]}}(m(e),"start"===n,r);return i&&(o=o.map((e=>e+"-"+i)),t&&(o=o.concat(o.map(k)))),o}(a,y,g,E));const T=[a,...P],A=await S(t,w),L=[];let B=(null==(r=o.flip)?void 0:r.overflows)||[];if(u&&L.push(A[O]),h){const e=_(i,s,E);L.push(A[e[0]],A[e[1]])}if(B=[...B,{placement:i,overflows:L}],!L.every((e=>e<=0))){var R,F;const e=((null==(R=o.flip)?void 0:R.index)||0)+1,t=T[e];if(t)return{data:{index:e,overflows:B},reset:{placement:t}};let n=null==(F=B.filter((e=>e.overflows[0]<=0)).sort(((e,t)=>e.overflows[1]-t.overflows[1]))[0])?void 0:F.placement;if(!n)switch(f){case"bestFit":{var N;const e=null==(N=B.filter((e=>{if(M){const t=b(e.placement);return t===x||"y"===t}return!0})).map((e=>[e.placement,e.overflows.filter((e=>e>0)).reduce(((e,t)=>e+t),0)])).sort(((e,t)=>e[1]-t[1]))[0])?void 0:N[0];e&&(n=e);break}case"initialPlacement":n=a}if(i!==n)return{reset:{placement:n}}}return{}}}},ye=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:o,platform:l,elements:c}=t,{apply:u=(()=>{}),...h}=p(e,t),d=await S(t,h),f=m(i),g=v(i),y="y"===b(i),{width:w,height:_}=o.floating;let k,C;"top"===f||"bottom"===f?(k=f,C=g===(await(null==l.isRTL?void 0:l.isRTL(c.floating))?"start":"end")?"left":"right"):(C=f,k="end"===g?"top":"bottom");const O=_-d.top-d.bottom,x=w-d.left-d.right,j=s(_-d[k],O),E=s(w-d[C],x),P=!t.middlewareData.shift;let M=j,T=E;if(null!=(n=t.middlewareData.shift)&&n.enabled.x&&(T=x),null!=(r=t.middlewareData.shift)&&r.enabled.y&&(M=O),P&&!g){const e=a(d.left,0),t=a(d.right,0),n=a(d.top,0),r=a(d.bottom,0);y?T=w-2*(0!==e||0!==t?e+t:a(d.left,d.right)):M=_-2*(0!==n||0!==r?n+r:a(d.top,d.bottom))}await u({...t,availableWidth:T,availableHeight:M});const A=await l.getDimensions(c.floating);return w!==A.width||_!==A.height?{reset:{rects:!0}}:{}}}},be=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...i}=p(e,t);switch(r){case"referenceHidden":{const e=E(await S(t,{...i,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:P(e)}}}case"escaped":{const e=E(await S(t,{...i,altBoundary:!0}),n.floating);return{data:{escapedOffsets:e,escaped:P(e)}}}default:return{}}}}},we=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:o,platform:a,elements:l,middlewareData:c}=t,{element:u,padding:h=0}=p(e,t)||{};if(null==u)return{};const d=O(h),m={x:n,y:r},g=w(i),b=y(g),_=await a.getDimensions(u),k="y"===g,C=k?"top":"left",x=k?"bottom":"right",j=k?"clientHeight":"clientWidth",S=o.reference[b]+o.reference[g]-m[g]-o.floating[b],E=m[g]-o.reference[g],P=await(null==a.getOffsetParent?void 0:a.getOffsetParent(u));let M=P?P[j]:0;M&&await(null==a.isElement?void 0:a.isElement(P))||(M=l.floating[j]||o.floating[b]);const T=S/2-E/2,A=M/2-_[b]/2-1,L=s(d[C],A),B=s(d[x],A),R=L,F=M-_[b]-B,N=M/2-_[b]/2+T,I=f(R,N,F),z=!c.arrow&&null!=v(i)&&N!==I&&o.reference[b]/2-(Ne.y-t.y)),n=[];let r=null;for(let e=0;er.height/2?n.push([i]):n[n.length-1].push(i),r=i}return n.map((e=>x(M(e))))}(d),v=x(M(d)),g=O(c),y=await o.getElementRects({reference:{getBoundingClientRect:function(){if(2===f.length&&f[0].left>f[1].right&&null!=u&&null!=h)return f.find((e=>u>e.left-g.left&&ue.top-g.top&&h=2){if("y"===b(n)){const e=f[0],t=f[f.length-1],r="top"===m(n),i=e.top,o=t.bottom,s=r?e.left:t.left,a=r?e.right:t.right;return{top:i,bottom:o,left:s,right:a,width:a-s,height:o-i,x:s,y:i}}const e="left"===m(n),t=a(...f.map((e=>e.right))),r=s(...f.map((e=>e.left))),i=f.filter((n=>e?n.left===r:n.right===t)),o=i[0].top,l=i[i.length-1].bottom;return{top:o,bottom:l,left:r,right:t,width:t-r,height:l-o,x:r,y:o}}return v}},floating:r.floating,strategy:l});return i.reference.x!==y.reference.x||i.reference.y!==y.reference.y||i.reference.width!==y.reference.width||i.reference.height!==y.reference.height?{reset:{rects:y}}:{}}}},ke=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:o,middlewareData:s}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=p(e,t),u={x:n,y:r},h=b(i),d=g(h);let f=u[d],v=u[h];const y=p(a,t),w="number"==typeof y?{mainAxis:y,crossAxis:0}:{mainAxis:0,crossAxis:0,...y};if(l){const e="y"===d?"height":"width",t=o.reference[d]-o.floating[e]+w.mainAxis,n=o.reference[d]+o.reference[e]-w.mainAxis;fn&&(f=n)}if(c){var _,k;const e="y"===d?"width":"height",t=["top","left"].includes(m(i)),n=o.reference[h]-o.floating[e]+(t&&(null==(_=s.offset)?void 0:_[h])||0)+(t?0:w.crossAxis),r=o.reference[h]+o.reference[e]+(t?0:(null==(k=s.offset)?void 0:k[h])||0)-(t?w.crossAxis:0);vr&&(v=r)}return{[d]:f,[h]:v}}}},Ce=(e,t,n)=>{const r=new Map,i={platform:he,...n},o={...i.platform,_c:r};return(async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,a=o.filter(Boolean),l=await(null==s.isRTL?void 0:s.isRTL(t));let c=await s.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:h}=j(c,r,l),d=r,f={},p=0;for(let n=0;n{n.r(t),n.d(t,{Application:()=>X,AttributeObserver:()=>w,Context:()=>N,Controller:()=>le,ElementObserver:()=>b,IndexedMultimap:()=>j,Multimap:()=>x,SelectorObserver:()=>S,StringMapObserver:()=>E,TokenListObserver:()=>P,ValueListObserver:()=>M,add:()=>_,defaultSchema:()=>G,del:()=>k,fetch:()=>C,prune:()=>O});class r{constructor(e,t,n){this.eventTarget=e,this.eventName=t,this.eventOptions=n,this.unorderedBindings=new Set}connect(){this.eventTarget.addEventListener(this.eventName,this,this.eventOptions)}disconnect(){this.eventTarget.removeEventListener(this.eventName,this,this.eventOptions)}bindingConnected(e){this.unorderedBindings.add(e)}bindingDisconnected(e){this.unorderedBindings.delete(e)}handleEvent(e){const t=function(e){if("immediatePropagationStopped"in e)return e;{const{stopImmediatePropagation:t}=e;return Object.assign(e,{immediatePropagationStopped:!1,stopImmediatePropagation(){this.immediatePropagationStopped=!0,t.call(this)}})}}(e);for(const e of this.bindings){if(t.immediatePropagationStopped)break;e.handleEvent(t)}}hasBindings(){return this.unorderedBindings.size>0}get bindings(){return Array.from(this.unorderedBindings).sort(((e,t)=>{const n=e.index,r=t.index;return nr?1:0}))}}class i{constructor(e){this.application=e,this.eventListenerMaps=new Map,this.started=!1}start(){this.started||(this.started=!0,this.eventListeners.forEach((e=>e.connect())))}stop(){this.started&&(this.started=!1,this.eventListeners.forEach((e=>e.disconnect())))}get eventListeners(){return Array.from(this.eventListenerMaps.values()).reduce(((e,t)=>e.concat(Array.from(t.values()))),[])}bindingConnected(e){this.fetchEventListenerForBinding(e).bindingConnected(e)}bindingDisconnected(e,t=!1){this.fetchEventListenerForBinding(e).bindingDisconnected(e),t&&this.clearEventListenersForBinding(e)}handleError(e,t,n={}){this.application.handleError(e,`Error ${t}`,n)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:n,eventOptions:r}=e,i=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(n,r);i.delete(o),0==i.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:n,eventOptions:r}=e;return this.fetchEventListener(t,n,r)}fetchEventListener(e,t,n){const r=this.fetchEventListenerMapForEventTarget(e),i=this.cacheKey(t,n);let o=r.get(i);return o||(o=this.createEventListener(e,t,n),r.set(i,o)),o}createEventListener(e,t,n){const i=new r(e,t,n);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const n=[e];return Object.keys(t).sort().forEach((e=>{n.push(`${t[e]?"":"!"}${e}`)})),n.join(":")}}const o={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:n})=>!t||n===e.target},s=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function a(e){return e.replace(/(?:[_-])([a-z0-9])/g,((e,t)=>t.toUpperCase()))}function l(e){return a(e.replace(/--/g,"-").replace(/__/g,"_"))}function c(e){return e.charAt(0).toUpperCase()+e.slice(1)}function u(e){return e.replace(/([A-Z])/g,((e,t)=>`-${t.toLowerCase()}`))}function h(e){return null!=e}function d(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const f=["meta","ctrl","alt","shift"];class p{constructor(e,t,n,r){this.element=e,this.index=t,this.eventTarget=n.eventTarget||e,this.eventName=n.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||v("missing event name"),this.eventOptions=n.eventOptions||{},this.identifier=n.identifier||v("missing identifier"),this.methodName=n.methodName||v("missing method name"),this.keyFilter=n.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(s)||[];let n=t[2],r=t[3];return r&&!["keydown","keyup","keypress"].includes(n)&&(n+=`.${r}`,r=""),{eventTarget:(i=t[4],"window"==i?window:"document"==i?document:void 0),eventName:n,eventOptions:t[7]?(o=t[7],o.split(":").reduce(((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)})),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||r};var i,o}(e.content),t)}toString(){const e=this.keyFilter?`.${this.keyFilter}`:"",t=this.eventTargetName?`@${this.eventTargetName}`:"";return`${this.eventName}${e}${t}->${this.identifier}#${this.methodName}`}shouldIgnoreKeyboardEvent(e){if(!this.keyFilter)return!1;const t=this.keyFilter.split("+");if(this.keyFilterDissatisfied(e,t))return!0;const n=t.filter((e=>!f.includes(e)))[0];return!!n&&(d(this.keyMappings,n)||v(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[n].toLowerCase()!==e.key.toLowerCase())}shouldIgnoreMouseEvent(e){if(!this.keyFilter)return!1;const t=[this.keyFilter];return!!this.keyFilterDissatisfied(e,t)}get params(){const e={},t=new RegExp(`^data-${this.identifier}-(.+)-param$`,"i");for(const{name:n,value:r}of Array.from(this.element.attributes)){const i=n.match(t),o=i&&i[1];o&&(e[a(o)]=g(r))}return e}get eventTargetName(){return(e=this.eventTarget)==window?"window":e==document?"document":void 0;var e}get keyMappings(){return this.schema.keyMappings}keyFilterDissatisfied(e,t){const[n,r,i,o]=f.map((e=>t.includes(e)));return e.metaKey!==n||e.ctrlKey!==r||e.altKey!==i||e.shiftKey!==o}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function v(e){throw new Error(e)}function g(e){try{return JSON.parse(e)}catch(t){return e}}class y{constructor(e,t){this.context=e,this.action=t}get index(){return this.action.index}get eventTarget(){return this.action.eventTarget}get eventOptions(){return this.action.eventOptions}get identifier(){return this.context.identifier}handleEvent(e){const t=this.prepareActionEvent(e);this.willBeInvokedByEvent(e)&&this.applyEventModifiers(t)&&this.invokeWithEvent(t)}get eventName(){return this.action.eventName}get method(){const e=this.controller[this.methodName];if("function"==typeof e)return e;throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`)}applyEventModifiers(e){const{element:t}=this.action,{actionDescriptorFilters:n}=this.context.application,{controller:r}=this.context;let i=!0;for(const[o,s]of Object.entries(this.eventOptions))if(o in n){const a=n[o];i=i&&a({name:o,value:s,event:e,element:t,controller:r})}return i}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:n}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:n,action:this.methodName})}catch(t){const{identifier:n,controller:r,element:i,index:o}=this,s={identifier:n,controller:r,element:i,index:o,event:e};this.context.handleError(t,`invoking action "${this.action}"`,s)}}willBeInvokedByEvent(e){const t=e.target;return!(e instanceof KeyboardEvent&&this.action.shouldIgnoreKeyboardEvent(e))&&!(e instanceof MouseEvent&&this.action.shouldIgnoreMouseEvent(e))&&(this.element===t||(t instanceof Element&&this.element.contains(t)?this.scope.containsElement(t):this.scope.containsElement(this.action.element)))}get controller(){return this.context.controller}get methodName(){return this.action.methodName}get element(){return this.scope.element}get scope(){return this.context.scope}}class b{constructor(e,t){this.mutationObserverInit={attributes:!0,childList:!0,subtree:!0},this.element=e,this.started=!1,this.delegate=t,this.elements=new Set,this.mutationObserver=new MutationObserver((e=>this.processMutations(e)))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,this.mutationObserverInit),this.refresh())}pause(e){this.started&&(this.mutationObserver.disconnect(),this.started=!1),e(),this.started||(this.mutationObserver.observe(this.element,this.mutationObserverInit),this.started=!0)}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started){const e=new Set(this.matchElementsInTree());for(const t of Array.from(this.elements))e.has(t)||this.removeElement(t);for(const t of Array.from(e))this.addElement(t)}}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){"attributes"==e.type?this.processAttributeChange(e.target,e.attributeName):"childList"==e.type&&(this.processRemovedNodes(e.removedNodes),this.processAddedNodes(e.addedNodes))}processAttributeChange(e,t){this.elements.has(e)?this.delegate.elementAttributeChanged&&this.matchElement(e)?this.delegate.elementAttributeChanged(e,t):this.removeElement(e):this.matchElement(e)&&this.addElement(e)}processRemovedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.processTree(e,this.removeElement)}}processAddedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.elementIsActive(e)&&this.processTree(e,this.addElement)}}matchElement(e){return this.delegate.matchElement(e)}matchElementsInTree(e=this.element){return this.delegate.matchElementsInTree(e)}processTree(e,t){for(const n of this.matchElementsInTree(e))t.call(this,n)}elementFromNode(e){if(e.nodeType==Node.ELEMENT_NODE)return e}elementIsActive(e){return e.isConnected==this.element.isConnected&&this.element.contains(e)}addElement(e){this.elements.has(e)||this.elementIsActive(e)&&(this.elements.add(e),this.delegate.elementMatched&&this.delegate.elementMatched(e))}removeElement(e){this.elements.has(e)&&(this.elements.delete(e),this.delegate.elementUnmatched&&this.delegate.elementUnmatched(e))}}class w{constructor(e,t,n){this.attributeName=t,this.delegate=n,this.elementObserver=new b(e,this)}get element(){return this.elementObserver.element}get selector(){return`[${this.attributeName}]`}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get started(){return this.elementObserver.started}matchElement(e){return e.hasAttribute(this.attributeName)}matchElementsInTree(e){const t=this.matchElement(e)?[e]:[],n=Array.from(e.querySelectorAll(this.selector));return t.concat(n)}elementMatched(e){this.delegate.elementMatchedAttribute&&this.delegate.elementMatchedAttribute(e,this.attributeName)}elementUnmatched(e){this.delegate.elementUnmatchedAttribute&&this.delegate.elementUnmatchedAttribute(e,this.attributeName)}elementAttributeChanged(e,t){this.delegate.elementAttributeValueChanged&&this.attributeName==t&&this.delegate.elementAttributeValueChanged(e,t)}}function _(e,t,n){C(e,t).add(n)}function k(e,t,n){C(e,t).delete(n),O(e,t)}function C(e,t){let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}function O(e,t){const n=e.get(t);null!=n&&0==n.size&&e.delete(t)}class x{constructor(){this.valuesByKey=new Map}get keys(){return Array.from(this.valuesByKey.keys())}get values(){return Array.from(this.valuesByKey.values()).reduce(((e,t)=>e.concat(Array.from(t))),[])}get size(){return Array.from(this.valuesByKey.values()).reduce(((e,t)=>e+t.size),0)}add(e,t){_(this.valuesByKey,e,t)}delete(e,t){k(this.valuesByKey,e,t)}has(e,t){const n=this.valuesByKey.get(e);return null!=n&&n.has(t)}hasKey(e){return this.valuesByKey.has(e)}hasValue(e){return Array.from(this.valuesByKey.values()).some((t=>t.has(e)))}getValuesForKey(e){const t=this.valuesByKey.get(e);return t?Array.from(t):[]}getKeysForValue(e){return Array.from(this.valuesByKey).filter((([t,n])=>n.has(e))).map((([e,t])=>e))}}class j extends x{constructor(){super(),this.keysByValue=new Map}get values(){return Array.from(this.keysByValue.keys())}add(e,t){super.add(e,t),_(this.keysByValue,t,e)}delete(e,t){super.delete(e,t),k(this.keysByValue,t,e)}hasValue(e){return this.keysByValue.has(e)}getKeysForValue(e){const t=this.keysByValue.get(e);return t?Array.from(t):[]}}class S{constructor(e,t,n,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=n,this.matchesByElement=new x}get started(){return this.elementObserver.started}get selector(){return this._selector}set selector(e){this._selector=e,this.refresh()}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get element(){return this.elementObserver.element}matchElement(e){const{selector:t}=this;if(t){const n=e.matches(t);return this.delegate.selectorMatchElement?n&&this.delegate.selectorMatchElement(e,this.details):n}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const n=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter((e=>this.matchElement(e)));return n.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const n of t)this.selectorUnmatched(e,n)}elementAttributeChanged(e,t){const{selector:n}=this;if(n){const t=this.matchElement(e),r=this.matchesByElement.has(n,e);t&&!r?this.selectorMatched(e,n):!t&&r&&this.selectorUnmatched(e,n)}}selectorMatched(e,t){this.delegate.selectorMatched(e,t,this.details),this.matchesByElement.add(t,e)}selectorUnmatched(e,t){this.delegate.selectorUnmatched(e,t,this.details),this.matchesByElement.delete(t,e)}}class E{constructor(e,t){this.element=e,this.delegate=t,this.started=!1,this.stringMap=new Map,this.mutationObserver=new MutationObserver((e=>this.processMutations(e)))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0,attributeOldValue:!0}),this.refresh())}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started)for(const e of this.knownAttributeNames)this.refreshAttribute(e,null)}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){const t=e.attributeName;t&&this.refreshAttribute(t,e.oldValue)}refreshAttribute(e,t){const n=this.delegate.getStringMapKeyForAttribute(e);if(null!=n){this.stringMap.has(e)||this.stringMapKeyAdded(n,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,n,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(n,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,n){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,n)}stringMapKeyRemoved(e,t,n){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,n)}get knownAttributeNames(){return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)))}get currentAttributeNames(){return Array.from(this.element.attributes).map((e=>e.name))}get recordedAttributeNames(){return Array.from(this.stringMap.keys())}}class P{constructor(e,t,n){this.attributeObserver=new w(e,t,this),this.delegate=n,this.tokensByElement=new x}get started(){return this.attributeObserver.started}start(){this.attributeObserver.start()}pause(e){this.attributeObserver.pause(e)}stop(){this.attributeObserver.stop()}refresh(){this.attributeObserver.refresh()}get element(){return this.attributeObserver.element}get attributeName(){return this.attributeObserver.attributeName}elementMatchedAttribute(e){this.tokensMatched(this.readTokensForElement(e))}elementAttributeValueChanged(e){const[t,n]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(n)}elementUnmatchedAttribute(e){this.tokensUnmatched(this.tokensByElement.getValuesForKey(e))}tokensMatched(e){e.forEach((e=>this.tokenMatched(e)))}tokensUnmatched(e){e.forEach((e=>this.tokenUnmatched(e)))}tokenMatched(e){this.delegate.tokenMatched(e),this.tokensByElement.add(e.element,e)}tokenUnmatched(e){this.delegate.tokenUnmatched(e),this.tokensByElement.delete(e.element,e)}refreshTokensForElement(e){const t=this.tokensByElement.getValuesForKey(e),n=this.readTokensForElement(e),r=function(e,t){const n=Math.max(e.length,t.length);return Array.from({length:n},((n,r)=>[e[r],t[r]]))}(t,n).findIndex((([e,t])=>{return r=t,!((n=e)&&r&&n.index==r.index&&n.content==r.content);var n,r}));return-1==r?[[],[]]:[t.slice(r),n.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,n){return e.trim().split(/\s+/).filter((e=>e.length)).map(((e,r)=>({element:t,attributeName:n,content:e,index:r})))}(e.getAttribute(t)||"",e,t)}}class M{constructor(e,t,n){this.tokenListObserver=new P(e,t,this),this.delegate=n,this.parseResultsByToken=new WeakMap,this.valuesByTokenByElement=new WeakMap}get started(){return this.tokenListObserver.started}start(){this.tokenListObserver.start()}stop(){this.tokenListObserver.stop()}refresh(){this.tokenListObserver.refresh()}get element(){return this.tokenListObserver.element}get attributeName(){return this.tokenListObserver.attributeName}tokenMatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).set(e,n),this.delegate.elementMatchedValue(t,n))}tokenUnmatched(e){const{element:t}=e,{value:n}=this.fetchParseResultForToken(e);n&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,n))}fetchParseResultForToken(e){let t=this.parseResultsByToken.get(e);return t||(t=this.parseToken(e),this.parseResultsByToken.set(e,t)),t}fetchValuesByTokenForElement(e){let t=this.valuesByTokenByElement.get(e);return t||(t=new Map,this.valuesByTokenByElement.set(e,t)),t}parseToken(e){try{return{value:this.delegate.parseValueForToken(e)}}catch(e){return{error:e}}}}class T{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new M(this.element,this.actionAttribute,this),this.valueListObserver.start())}stop(){this.valueListObserver&&(this.valueListObserver.stop(),delete this.valueListObserver,this.disconnectAllActions())}get element(){return this.context.element}get identifier(){return this.context.identifier}get actionAttribute(){return this.schema.actionAttribute}get schema(){return this.context.schema}get bindings(){return Array.from(this.bindingsByAction.values())}connectAction(e){const t=new y(this.context,e);this.bindingsByAction.set(e,t),this.delegate.bindingConnected(t)}disconnectAction(e){const t=this.bindingsByAction.get(e);t&&(this.bindingsByAction.delete(e),this.delegate.bindingDisconnected(t))}disconnectAllActions(){this.bindings.forEach((e=>this.delegate.bindingDisconnected(e,!0))),this.bindingsByAction.clear()}parseValueForToken(e){const t=p.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class A{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new E(this.element,this),this.valueDescriptorMap=this.controller.valueDescriptorMap}start(){this.stringMapObserver.start(),this.invokeChangedCallbacksForDefaultValues()}stop(){this.stringMapObserver.stop()}get element(){return this.context.element}get controller(){return this.context.controller}getStringMapKeyForAttribute(e){if(e in this.valueDescriptorMap)return this.valueDescriptorMap[e].name}stringMapKeyAdded(e,t){const n=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,n.writer(this.receiver[e]),n.writer(n.defaultValue))}stringMapValueChanged(e,t,n){const r=this.valueDescriptorNameMap[t];null!==e&&(null===n&&(n=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,n))}stringMapKeyRemoved(e,t,n){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),n):this.invokeChangedCallback(e,r.writer(r.defaultValue),n)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:n,writer:r}of this.valueDescriptors)null==n||this.controller.data.has(e)||this.invokeChangedCallback(t,r(n),void 0)}invokeChangedCallback(e,t,n){const r=`${e}Changed`,i=this.receiver[r];if("function"==typeof i){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let o=n;n&&(o=r.reader(n)),i.call(this.receiver,e,o)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.name}" - ${e.message}`),e}}}get valueDescriptors(){const{valueDescriptorMap:e}=this;return Object.keys(e).map((t=>e[t]))}get valueDescriptorNameMap(){const e={};return Object.keys(this.valueDescriptorMap).forEach((t=>{const n=this.valueDescriptorMap[t];e[n.name]=n})),e}hasValue(e){const t=`has${c(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class L{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new x}start(){this.tokenListObserver||(this.tokenListObserver=new P(this.element,this.attributeName,this),this.tokenListObserver.start())}stop(){this.tokenListObserver&&(this.disconnectAllTargets(),this.tokenListObserver.stop(),delete this.tokenListObserver)}tokenMatched({element:e,content:t}){this.scope.containsElement(e)&&this.connectTarget(e,t)}tokenUnmatched({element:e,content:t}){this.disconnectTarget(e,t)}connectTarget(e,t){var n;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause((()=>this.delegate.targetConnected(e,t))))}disconnectTarget(e,t){var n;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(n=this.tokenListObserver)||void 0===n||n.pause((()=>this.delegate.targetDisconnected(e,t))))}disconnectAllTargets(){for(const e of this.targetsByName.keys)for(const t of this.targetsByName.getValuesForKey(e))this.disconnectTarget(t,e)}get attributeName(){return`data-${this.context.identifier}-target`}get element(){return this.context.element}get scope(){return this.context.scope}}function B(e,t){const n=R(e);return Array.from(n.reduce(((e,n)=>(function(e,t){const n=e[t];return Array.isArray(n)?n:[]}(n,t).forEach((t=>e.add(t))),e)),new Set))}function R(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class F{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new x,this.outletElementsByName=new x,this.selectorObserverMap=new Map,this.attributeObserverMap=new Map}start(){this.started||(this.outletDefinitions.forEach((e=>{this.setupSelectorObserverForOutlet(e),this.setupAttributeObserverForOutlet(e)})),this.started=!0,this.dependentContexts.forEach((e=>e.refresh())))}refresh(){this.selectorObserverMap.forEach((e=>e.refresh())),this.attributeObserverMap.forEach((e=>e.refresh()))}stop(){this.started&&(this.started=!1,this.disconnectAllOutlets(),this.stopSelectorObservers(),this.stopAttributeObservers())}stopSelectorObservers(){this.selectorObserverMap.size>0&&(this.selectorObserverMap.forEach((e=>e.stop())),this.selectorObserverMap.clear())}stopAttributeObservers(){this.attributeObserverMap.size>0&&(this.attributeObserverMap.forEach((e=>e.stop())),this.attributeObserverMap.clear())}selectorMatched(e,t,{outletName:n}){const r=this.getOutlet(e,n);r&&this.connectOutlet(r,e,n)}selectorUnmatched(e,t,{outletName:n}){const r=this.getOutletFromMap(e,n);r&&this.disconnectOutlet(r,e,n)}selectorMatchElement(e,{outletName:t}){const n=this.selector(t),r=this.hasOutlet(e,t),i=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!n&&r&&i&&e.matches(n)}elementMatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementAttributeValueChanged(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}elementUnmatchedAttribute(e,t){const n=this.getOutletNameFromOutletAttributeName(t);n&&this.updateSelectorObserverForOutlet(n)}connectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)||(this.outletsByName.add(n,e),this.outletElementsByName.add(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause((()=>this.delegate.outletConnected(e,t,n))))}disconnectOutlet(e,t,n){var r;this.outletElementsByName.has(n,t)&&(this.outletsByName.delete(n,e),this.outletElementsByName.delete(n,t),null===(r=this.selectorObserverMap.get(n))||void 0===r||r.pause((()=>this.delegate.outletDisconnected(e,t,n))))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const n of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(n,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),n=new S(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,n),n.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),n=new w(this.scope.element,t,this);this.attributeObserverMap.set(e,n),n.start()}selector(e){return this.scope.outlets.getSelectorForOutletName(e)}attributeNameForOutletName(e){return this.scope.schema.outletAttributeForScope(this.identifier,e)}getOutletNameFromOutletAttributeName(e){return this.outletDefinitions.find((t=>this.attributeNameForOutletName(t)===e))}get outletDependencies(){const e=new x;return this.router.modules.forEach((t=>{B(t.definition.controllerConstructor,"outlets").forEach((n=>e.add(n,t.identifier)))})),e}get outletDefinitions(){return this.outletDependencies.getKeysForValue(this.identifier)}get dependentControllerIdentifiers(){return this.outletDependencies.getValuesForKey(this.identifier)}get dependentContexts(){const e=this.dependentControllerIdentifiers;return this.router.contexts.filter((t=>e.includes(t.identifier)))}hasOutlet(e,t){return!!this.getOutlet(e,t)||!!this.getOutletFromMap(e,t)}getOutlet(e,t){return this.application.getControllerForElementAndIdentifier(e,t)}getOutletFromMap(e,t){return this.outletsByName.getValuesForKey(t).find((t=>t.element===e))}get scope(){return this.context.scope}get schema(){return this.context.schema}get identifier(){return this.context.identifier}get application(){return this.context.application}get router(){return this.application.router}}class N{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:n,controller:r,element:i}=this;t=Object.assign({identifier:n,controller:r,element:i},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new T(this,this.dispatcher),this.valueObserver=new A(this,this.controller),this.targetObserver=new L(this,this),this.outletObserver=new F(this,this);try{this.controller.initialize(),this.logDebugActivity("initialize")}catch(e){this.handleError(e,"initializing controller")}}connect(){this.bindingObserver.start(),this.valueObserver.start(),this.targetObserver.start(),this.outletObserver.start();try{this.controller.connect(),this.logDebugActivity("connect")}catch(e){this.handleError(e,"connecting controller")}}refresh(){this.outletObserver.refresh()}disconnect(){try{this.controller.disconnect(),this.logDebugActivity("disconnect")}catch(e){this.handleError(e,"disconnecting controller")}this.outletObserver.stop(),this.targetObserver.stop(),this.valueObserver.stop(),this.bindingObserver.stop()}get application(){return this.module.application}get identifier(){return this.module.identifier}get schema(){return this.application.schema}get dispatcher(){return this.application.dispatcher}get element(){return this.scope.element}get parentElement(){return this.element.parentElement}handleError(e,t,n={}){const{identifier:r,controller:i,element:o}=this;n=Object.assign({identifier:r,controller:i,element:o},n),this.application.handleError(e,`Error ${t}`,n)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletConnected`,e,t)}outletDisconnected(e,t,n){this.invokeControllerMethod(`${l(n)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const n=this.controller;"function"==typeof n[e]&&n[e](...t)}}const I="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,z=(()=>{function e(e){function t(){return Reflect.construct(e,arguments,new.target)}return t.prototype=Object.create(e.prototype,{constructor:{value:t}}),Reflect.setPrototypeOf(t,e),t}try{return function(){const t=e((function(){this.a.call(this)}));t.prototype.a=function(){},new t}(),e}catch(e){return e=>class extends e{}}})();class D{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:(t=e.controllerConstructor,function(e,t){const n=z(e),r=function(e,t){return I(t).reduce(((n,r)=>{const i=function(e,t,n){const r=Object.getOwnPropertyDescriptor(e,n);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,n).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return i&&Object.assign(n,{[r]:i}),n}),{})}(e.prototype,t);return Object.defineProperties(n.prototype,r),n}(t,function(e){return B(e,"blessings").reduce(((t,n)=>{const r=n(e);for(const e in r){const n=t[e]||{};t[e]=Object.assign(n,r[e])}return t}),{})}(t)))};var t}(t),this.contextsByScope=new WeakMap,this.connectedContexts=new Set}get identifier(){return this.definition.identifier}get controllerConstructor(){return this.definition.controllerConstructor}get contexts(){return Array.from(this.connectedContexts)}connectContextForScope(e){const t=this.fetchContextForScope(e);this.connectedContexts.add(t),t.connect()}disconnectContextForScope(e){const t=this.contextsByScope.get(e);t&&(this.connectedContexts.delete(t),t.disconnect())}fetchContextForScope(e){let t=this.contextsByScope.get(e);return t||(t=new N(this,e),this.contextsByScope.set(e,t)),t}}class V{constructor(e){this.scope=e}has(e){return this.data.has(this.getDataKey(e))}get(e){return this.getAll(e)[0]}getAll(e){return(this.data.get(this.getDataKey(e))||"").match(/[^\s]+/g)||[]}getAttributeName(e){return this.data.getAttributeNameForKey(this.getDataKey(e))}getDataKey(e){return`${e}-class`}get data(){return this.scope.data}}class ${constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get(e){const t=this.getAttributeNameForKey(e);return this.element.getAttribute(t)}set(e,t){const n=this.getAttributeNameForKey(e);return this.element.setAttribute(n,t),this.get(e)}has(e){const t=this.getAttributeNameForKey(e);return this.element.hasAttribute(t)}delete(e){if(this.has(e)){const t=this.getAttributeNameForKey(e);return this.element.removeAttribute(t),!0}return!1}getAttributeNameForKey(e){return`data-${this.identifier}-${u(e)}`}}class H{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,n){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(n,e))}}function U(e,t){return`[${e}~="${t}"]`}class q{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce(((e,t)=>e||this.findTarget(t)||this.findLegacyTarget(t)),void 0)}findAll(...e){return e.reduce(((e,t)=>[...e,...this.findAllTargets(t),...this.findAllLegacyTargets(t)]),[])}findTarget(e){const t=this.getSelectorForTargetName(e);return this.scope.findElement(t)}findAllTargets(e){const t=this.getSelectorForTargetName(e);return this.scope.findAllElements(t)}getSelectorForTargetName(e){return U(this.schema.targetAttributeForScope(this.identifier),e)}findLegacyTarget(e){const t=this.getLegacySelectorForTargetName(e);return this.deprecate(this.scope.findElement(t),e)}findAllLegacyTargets(e){const t=this.getLegacySelectorForTargetName(e);return this.scope.findAllElements(t).map((t=>this.deprecate(t,e)))}getLegacySelectorForTargetName(e){const t=`${this.identifier}.${e}`;return U(this.schema.targetAttribute,t)}deprecate(e,t){if(e){const{identifier:n}=this,r=this.schema.targetAttribute,i=this.schema.targetAttributeForScope(n);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${n}.${t}" with ${i}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class K{constructor(e,t){this.scope=e,this.controllerElement=t}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce(((e,t)=>e||this.findOutlet(t)),void 0)}findAll(...e){return e.reduce(((e,t)=>[...e,...this.findAllOutlets(t)]),[])}getSelectorForOutletName(e){const t=this.schema.outletAttributeForScope(this.identifier,e);return this.controllerElement.getAttribute(t)}findOutlet(e){const t=this.getSelectorForOutletName(e);if(t)return this.findElement(t,e)}findAllOutlets(e){const t=this.getSelectorForOutletName(e);return t?this.findAllElements(t,e):[]}findElement(e,t){return this.scope.queryElements(e).filter((n=>this.matchesElement(n,e,t)))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter((n=>this.matchesElement(n,e,t)))}matchesElement(e,t,n){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(n)}}class W{constructor(e,t,n,r){this.targets=new q(this),this.classes=new V(this),this.data=new $(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=n,this.guide=new H(r),this.outlets=new K(this.documentScope,t)}findElement(e){return this.element.matches(e)?this.element:this.queryElements(e).find(this.containsElement)}findAllElements(e){return[...this.element.matches(e)?[this.element]:[],...this.queryElements(e).filter(this.containsElement)]}queryElements(e){return Array.from(this.element.querySelectorAll(e))}get controllerSelector(){return U(this.schema.controllerAttribute,this.identifier)}get isDocumentScope(){return this.element===document.documentElement}get documentScope(){return this.isDocumentScope?this:new W(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class Z{constructor(e,t,n){this.element=e,this.schema=t,this.delegate=n,this.valueListObserver=new M(this.element,this.controllerAttribute,this),this.scopesByIdentifierByElement=new WeakMap,this.scopeReferenceCounts=new WeakMap}start(){this.valueListObserver.start()}stop(){this.valueListObserver.stop()}get controllerAttribute(){return this.schema.controllerAttribute}parseValueForToken(e){const{element:t,content:n}=e;return this.parseValueForElementAndIdentifier(t,n)}parseValueForElementAndIdentifier(e,t){const n=this.fetchScopesByIdentifierForElement(e);let r=n.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),n.set(t,r)),r}elementMatchedValue(e,t){const n=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,n),1==n&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const n=this.scopeReferenceCounts.get(t);n&&(this.scopeReferenceCounts.set(t,n-1),1==n&&this.delegate.scopeDisconnected(t))}fetchScopesByIdentifierForElement(e){let t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t}}class J{constructor(e){this.application=e,this.scopeObserver=new Z(this.element,this.schema,this),this.scopesByIdentifier=new x,this.modulesByIdentifier=new Map}get element(){return this.application.element}get schema(){return this.application.schema}get logger(){return this.application.logger}get controllerAttribute(){return this.schema.controllerAttribute}get modules(){return Array.from(this.modulesByIdentifier.values())}get contexts(){return this.modules.reduce(((e,t)=>e.concat(t.contexts)),[])}start(){this.scopeObserver.start()}stop(){this.scopeObserver.stop()}loadDefinition(e){this.unloadIdentifier(e.identifier);const t=new D(this.application,e);this.connectModule(t);const n=e.controllerConstructor.afterLoad;n&&n.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const n=this.modulesByIdentifier.get(t);if(n)return n.contexts.find((t=>t.element==e))}proposeToConnectScopeForElementAndIdentifier(e,t){const n=this.scopeObserver.parseValueForElementAndIdentifier(e,t);n?this.scopeObserver.elementMatchedValue(n.element,n):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,n){this.application.handleError(e,t,n)}createScopeForElementAndIdentifier(e,t){return new W(this.schema,e,t,this.logger)}scopeConnected(e){this.scopesByIdentifier.add(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.connectContextForScope(e)}scopeDisconnected(e){this.scopesByIdentifier.delete(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.disconnectContextForScope(e)}connectModule(e){this.modulesByIdentifier.set(e.identifier,e),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((t=>e.connectContextForScope(t)))}disconnectModule(e){this.modulesByIdentifier.delete(e.identifier),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((t=>e.disconnectContextForScope(t)))}}const G={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target",targetAttributeForScope:e=>`data-${e}-target`,outletAttributeForScope:(e,t)=>`data-${e}-${t}-outlet`,keyMappings:Object.assign(Object.assign({enter:"Enter",tab:"Tab",esc:"Escape",space:" ",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",home:"Home",end:"End",page_up:"PageUp",page_down:"PageDown"},Q("abcdefghijklmnopqrstuvwxyz".split("").map((e=>[e,e])))),Q("0123456789".split("").map((e=>[e,e]))))};function Q(e){return e.reduce(((e,[t,n])=>Object.assign(Object.assign({},e),{[t]:n})),{})}class X{constructor(e=document.documentElement,t=G){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,n={})=>{this.debug&&this.logFormattedMessage(e,t,n)},this.element=e,this.schema=t,this.dispatcher=new i(this),this.router=new J(this),this.actionDescriptorFilters=Object.assign({},o)}static start(e,t){const n=new this(e,t);return n.start(),n}async start(){await new Promise((e=>{"loading"==document.readyState?document.addEventListener("DOMContentLoaded",(()=>e())):e()})),this.logDebugActivity("application","starting"),this.dispatcher.start(),this.router.start(),this.logDebugActivity("application","start")}stop(){this.logDebugActivity("application","stopping"),this.dispatcher.stop(),this.router.stop(),this.logDebugActivity("application","stop")}register(e,t){this.load({identifier:e,controllerConstructor:t})}registerActionOption(e,t){this.actionDescriptorFilters[e]=t}load(e,...t){(Array.isArray(e)?e:[e,...t]).forEach((e=>{e.controllerConstructor.shouldLoad&&this.router.loadDefinition(e)}))}unload(e,...t){(Array.isArray(e)?e:[e,...t]).forEach((e=>this.router.unloadIdentifier(e)))}get controllers(){return this.router.contexts.map((e=>e.controller))}getControllerForElementAndIdentifier(e,t){const n=this.router.getContextForElementAndIdentifier(e,t);return n?n.controller:null}handleError(e,t,n){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,n),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,n={}){n=Object.assign({application:this},n),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},n)),this.logger.groupEnd()}}function Y(e,t,n){return e.application.getControllerForElementAndIdentifier(t,n)}function ee(e,t,n){let r=Y(e,t,n);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,n),r=Y(e,t,n),r||void 0)}function te([e,t],n){return function(e){const{token:t,typeDefinition:n}=e,r=`${u(t)}-value`,i=function(e){const{controller:t,token:n,typeDefinition:r}=e,i=function(e){const{controller:t,token:n,typeObject:r}=e,i=h(r.type),o=h(r.default),s=i&&o,a=i&&!o,l=!i&&o,c=ne(r.type),u=re(e.typeObject.default);if(a)return c;if(l)return u;if(c!==u)throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${n}`:n}" must match the defined type "${c}". The provided default value of "${r.default}" is of type "${u}".`);return s?c:void 0}({controller:t,token:n,typeObject:r}),o=re(r),s=ne(r),a=i||o||s;if(a)return a;throw new Error(`Unknown value type "${t?`${t}.${r}`:n}" for "${n}" value`)}(e);return{type:i,key:r,name:a(r),get defaultValue(){return function(e){const t=ne(e);if(t)return ie[t];const n=d(e,"default"),r=d(e,"type"),i=e;if(n)return i.default;if(r){const{type:e}=i,t=ne(e);if(t)return ie[t]}return e}(n)},get hasCustomDefaultValue(){return void 0!==re(n)},reader:oe[i],writer:se[i]||se.default}}({controller:n,token:e,typeDefinition:t})}function ne(e){switch(e){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}}function re(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string"}return Array.isArray(e)?"array":"[object Object]"===Object.prototype.toString.call(e)?"object":void 0}const ie={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},oe={array(e){const t=JSON.parse(e);if(!Array.isArray(t))throw new TypeError(`expected value of type "array" but instead got value "${e}" of type "${re(t)}"`);return t},boolean:e=>!("0"==e||"false"==String(e).toLowerCase()),number:e=>Number(e.replace(/_/g,"")),object(e){const t=JSON.parse(e);if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(`expected value of type "object" but instead got value "${e}" of type "${re(t)}"`);return t},string:e=>e},se={default:function(e){return`${e}`},array:ae,object:ae};function ae(e){return JSON.stringify(e)}class le{constructor(e){this.context=e}static get shouldLoad(){return!0}static afterLoad(e,t){}get application(){return this.context.application}get scope(){return this.context.scope}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get targets(){return this.scope.targets}get outlets(){return this.scope.outlets}get classes(){return this.scope.classes}get data(){return this.scope.data}initialize(){}connect(){}disconnect(){}dispatch(e,{target:t=this.element,detail:n={},prefix:r=this.identifier,bubbles:i=!0,cancelable:o=!0}={}){const s=new CustomEvent(r?`${r}:${e}`:e,{detail:n,bubbles:i,cancelable:o});return t.dispatchEvent(s),s}}le.blessings=[function(e){return B(e,"classes").reduce(((e,t)=>{return Object.assign(e,{[`${n=t}Class`]:{get(){const{classes:e}=this;if(e.has(n))return e.get(n);{const t=e.getAttributeName(n);throw new Error(`Missing attribute "${t}"`)}}},[`${n}Classes`]:{get(){return this.classes.getAll(n)}},[`has${c(n)}Class`]:{get(){return this.classes.has(n)}}});var n}),{})},function(e){return B(e,"targets").reduce(((e,t)=>{return Object.assign(e,{[`${n=t}Target`]:{get(){const e=this.targets.find(n);if(e)return e;throw new Error(`Missing target element "${n}" for "${this.identifier}" controller`)}},[`${n}Targets`]:{get(){return this.targets.findAll(n)}},[`has${c(n)}Target`]:{get(){return this.targets.has(n)}}});var n}),{})},function(e){const t=function(e,t){return R(e).reduce(((e,n)=>(e.push(...function(e,t){const n=e[t];return n?Object.keys(n).map((e=>[e,n[e]])):[]}(n,t)),e)),[])}(e,"values"),n={valueDescriptorMap:{get(){return t.reduce(((e,t)=>{const n=te(t,this.identifier),r=this.data.getAttributeNameForKey(n.key);return Object.assign(e,{[r]:n})}),{})}}};return t.reduce(((e,t)=>Object.assign(e,function(e,t){const n=te(e,void 0),{key:r,name:i,reader:o,writer:s}=n;return{[i]:{get(){const e=this.data.get(r);return null!==e?o(e):n.defaultValue},set(e){void 0===e?this.data.delete(r):this.data.set(r,s(e))}},[`has${c(i)}`]:{get(){return this.data.has(r)||n.hasCustomDefaultValue}}}}(t))),n)},function(e){return B(e,"outlets").reduce(((e,t)=>Object.assign(e,function(e){const t=l(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t){const n=ee(this,t,e);if(n)return n;throw new Error(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`)}throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${n}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map((t=>{const n=ee(this,t,e);if(n)return n;console.warn(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`,t)})).filter((e=>e)):[]}},[`${t}OutletElement`]:{get(){const t=this.outlets.find(e),n=this.outlets.getSelectorForOutletName(e);if(t)return t;throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${n}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${c(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t))),{})}],le.targets=[],le.outlets=[],le.values={}},830:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=n(613);function i(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function o(e,t){for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=n(613),i=n(541),o=n(874);function s(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function a(e,t){for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r,i=(r=n(688))&&r.__esModule?r:{default:r},o=n(613),s=n(874);function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function l(e){for(var t=1;t{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Response",{enumerable:!0,get:function(){return a.Response}}),t.default=void 0;var r=l(n(830)),i=l(n(911)),o=l(n(495)),s=l(n(383)),a=n(874);function l(e){return e&&e.__esModule?e:{default:e}}function c(e,t){for(var n=0;n{function n(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function r(e,t){for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r,i=(r=n(688))&&r.__esModule?r:{default:r},o=n(613),s=n(874);function a(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function l(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var o=e.apply(t,n);function s(e){a(o,r,i,s,l,"next",e)}function l(e){a(o,r,i,s,l,"throw",e)}s(void 0)}))}}function c(e,t){for(var n=0;n{var[n,r]=e;t.searchParams.append(n,r)})),yield fetch(t,{method:"GET",headers:i.default.headers})})),function(e){return u.apply(this,arguments)})},{key:"create",value:(a=l((function*(e){var t=yield fetch(this.url,{method:"POST",headers:{Authorization:"Bearer ".concat(i.default.business.id)},body:e});return new s.Response(t.ok,t)})),function(e){return a.apply(this,arguments)})},{key:"url",get:function(){return e.endpoint.replace(":id",this.webchatId)}}],r=[{key:"endpoint",get:function(){return o.Configuration.endpoint("public/webchats/:id/messages")}}],n&&c(t.prototype,n),r&&c(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.default=u},383:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r,i=(r=n(688))&&r.__esModule?r:{default:r},o=n(613);function s(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function a(e,t){for(var n=0;n{var[n,r]=e;t.searchParams.append("style[".concat(n,"]"),r)})),t.searchParams.append("placement",o.Configuration.webchat.placement);var n=yield fetch(t,{method:"GET",headers:i.default.headers}),r=yield n.text();return(new DOMParser).parseFromString(r,"text/html").querySelector("article")},l=function(){var e=this,t=arguments;return new Promise((function(n,i){var o=r.apply(e,t);function a(e){s(o,n,i,a,l,"next",e)}function l(e){s(o,n,i,a,l,"throw",e)}a(void 0)}))},function(e){return l.apply(this,arguments)})}],null&&a(t.prototype,null),n&&a(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.default=l},219:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InputBuilder=void 0;var r,i=(r=n(688))&&r.__esModule?r:{default:r};function o(e,t){for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.LogoBuilder=void 0;var r,i=(r=n(688))&&r.__esModule?r:{default:r};function o(e,t){for(var n=0;n\n ".concat(i.default.business.locale.white_label.powered_by,'\n \n \n \n Hellotext\n \n \n \n \n ')}})},696:(e,t)=>{function n(e,t){for(var n=0;n{this.webSocket.send(JSON.stringify(r))}))}},{key:"onMessage",value:function(e){this.webSocket.addEventListener("message",(t=>{var n=JSON.parse(t.data),{type:r,message:i}=n;this.ignoredEvents.includes(r)||e(i)}))}},{key:"webSocket",get:function(){return e.webSocket?e.webSocket:e.webSocket=new WebSocket("ws://localhost:3000/cable")}},{key:"ignoredEvents",get:function(){return["ping","confirm_subscription","welcome"]}}])&&n(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();r.webSocket=void 0;var i=r;t.default=i},95:(e,t,n)=>{var r;function i(e,t){for(var n=0;n{"message"===t.type&&e(t)}))}},{key:"onConversationAssignment",value:function(e){o(a(u.prototype),"onMessage",this).call(this,(t=>{"conversation.assigned"===t.type&&e(t)}))}},{key:"onAgentOnline",value:function(e){o(a(u.prototype),"onMessage",this).call(this,(t=>{"agent_is_online"===t.type&&e(t)}))}},{key:"onReaction",value:function(e){o(a(u.prototype),"onMessage",this).call(this,(t=>{"reaction.create"!==t.type&&"reaction.destroy"!==t.type||e(t)}))}},{key:"updateSubscriptionWith",value:function(e){this.unsubscribe(),setTimeout((()=>{this.conversation=e,this.subscribe()}),1e3)}}])&&i(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),u}(((r=n(696))&&r.__esModule?r:{default:r}).default);t.default=l},425:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=n(599),i=l(n(688)),o=n(541),s=l(n(495)),a=n(613);function l(e){return e&&e.__esModule?e:{default:e}}function c(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function u(e,t){for(var n=0;n{var{type:t,parameter:n}=e,r=this.inputTargets.find((e=>e.name===n));r.setCustomValidity(i.default.business.locale.errors[t]),r.reportValidity(),r.addEventListener("input",(()=>{r.setCustomValidity(""),r.reportValidity()}))})),this.showErrorMessages();this.buttonTarget.style.display="none",this.element.querySelectorAll("input").forEach((e=>e.disabled=!0)),this.completed()},l=function(){var e=this,t=arguments;return new Promise((function(n,i){var o=r.apply(e,t);function s(e){c(o,n,i,s,a,"next",e)}function a(e){c(o,n,i,s,a,"throw",e)}s(void 0)}))},function(e){return l.apply(this,arguments)})},{key:"completed",value:function(){if(this.form.markAsCompleted(this.formData),!a.Configuration.forms.shouldShowSuccessMessage)return this.element.remove();"string"==typeof a.Configuration.forms.successMessage?this.element.innerHTML=a.Configuration.forms.successMessage:this.element.innerHTML=i.default.business.locale.forms[this.form.localeAuthKey]}},{key:"showErrorMessages",value:function(){this.element.querySelectorAll("input:invalid").forEach((e=>{e.closest("article").querySelector("[data-error-container]").innerText=e.validationMessage}))}},{key:"clearErrorMessages",value:function(){this.element.querySelectorAll("input").forEach((e=>{e.setCustomValidity(""),e.closest("article").querySelector("[data-error-container]").innerText=""}))}},{key:"inputTargetConnected",value:function(e){e.getAttribute("data-default-value")&&(e.value=e.getAttribute("data-default-value"))}},{key:"requiredInputs",get:function(){return this.inputTargets.filter((e=>e.required))}},{key:"invalid",get:function(){return!this.element.checkValidity()}}],n&&u(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),g}(r.Controller);t.default=p,p.values={data:Object,step:{type:Number,default:1}},p.targets=["inputContainer","input","button","otpContainer"]},817:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.usePopover=void 0;var r,i=n(75);(r=n(688))&&r.__esModule,t.usePopover=e=>{Object.assign(e,{show(){this.openValue=!0},hide(){this.openValue=!1},toggle(){this.openValue=!this.openValue},setupFloatingUI(e){var{trigger:t,popover:n}=e;this.floatingUICleanup=(0,i.autoUpdate)(t,n,(()=>{(0,i.computePosition)(t,n,{placement:this.placementValue,middleware:this.middlewares}).then((e=>{var{x:t,y:r}=e,i={left:"".concat(t,"px"),top:"".concat(r,"px")};Object.assign(n.style,i)}))}))},openValueChanged(){this.disabledValue||(this.openValue?(this.popoverTarget.showPopover(),this.popoverTarget.setAttribute("aria-expanded","true"),this.onPopoverOpened&&this.onPopoverOpened()):(this.popoverTarget.hidePopover(),this.popoverTarget.removeAttribute("aria-expanded"),this.onPopoverClosed&&this.onPopoverClosed()))}})}},143:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=n(599),i=n(75),o=n(431),s=n(817);function a(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function l(e,t){for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=n(599),i=n(75),o=h(n(750)),s=h(n(95)),a=h(n(688)),l=n(829),c=n(817),u=n(846);function h(e){return e&&e.__esModule?e:{default:e}}function d(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function f(e){for(var t=1;t300||!this.nextPageValue||this.fetchingNextPage)){this.fetchingNextPage=!0;var e=yield this.messagesAPI.index({page:this.nextPageValue,session:a.default.session}),{next:t,messages:n}=yield e.json();this.nextPageValue=t,this.oldScrollHeight=this.messagesContainerTarget.scrollHeight,n.forEach((e=>{var{body:t,attachments:n}=e,r=document.createElement("div");r.innerHTML=t;var i=this.messageTemplateTarget.cloneNode(!0);i.setAttribute("data-hellotext--webchat-target","message"),i.style.removeProperty("display"),i.querySelector("[data-body]").innerHTML=r.innerHTML,"received"===e.state?i.classList.add("received"):i.classList.remove("received"),n&&n.forEach((e=>{var t=this.attachmentImageTarget.cloneNode(!0);t.removeAttribute("data-hellotext--webchat-target"),t.src=e,t.style.display="block",i.querySelector("[data-attachment-container]").appendChild(t)})),i.setAttribute("data-body",t),this.messagesContainerTarget.prepend(i)})),this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight-this.oldScrollHeight,behavior:"instant"}),this.fetchingNextPage=!1}})),function(){return h.apply(this,arguments)})},{key:"onClickOutside",value:function(e){l.Webchat.behaviour===l.behaviors.POPOVER&&this.openValue&&e.target.nodeType&&!1===this.element.contains(e.target)&&(this.openValue=!1)}},{key:"onPopoverOpened",value:function(){this.inputTarget.focus(),this.scrolled||(this.messagesContainerTarget.scroll({top:this.messagesContainerTarget.scrollHeight,behavior:"instant"}),this.scrolled=!0),a.default.eventEmitter.dispatch("webchat:opened"),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"opened"),this.unreadCounterTarget.style.display="none",this.unreadCounterTarget.innerText="0"}},{key:"onPopoverClosed",value:function(){a.default.eventEmitter.dispatch("webchat:closed"),setTimeout((()=>{this.inputTarget.value=""})),localStorage.setItem("hellotext--webchat--".concat(this.idValue),"closed")}},{key:"onMessageReaction",value:function(e){var{message:t,reaction:n,type:r}=e,i=this.messageTargets.find((e=>e.dataset.id===t)).querySelector("[data-reactions]");if("reaction.destroy"===r)return i.querySelector('[data-id="'.concat(n.id,'"]')).remove();if(i.querySelector('[data-id="'.concat(n.id,'"]')))i.querySelector('[data-id="'.concat(n.id,'"]')).innerText=n.emoji;else{var o=document.createElement("span");o.innerText=n.emoji,o.setAttribute("data-id",n.id),i.appendChild(o)}}},{key:"onMessageReceived",value:function(e){var{body:t,attachments:n}=e,r=document.createElement("div");r.innerHTML=t;var i=this.messageTemplateTarget.cloneNode(!0);if(i.style.display="flex",i.querySelector("[data-body]").innerHTML=r.innerHTML,i.setAttribute("data-hellotext--webchat-target","message"),n&&n.forEach((e=>{var t=this.attachmentImageTarget.cloneNode(!0);t.src=e,t.style.display="block",i.querySelector("[data-attachment-container]").appendChild(t)})),this.messagesContainerTarget.appendChild(i),a.default.eventEmitter.dispatch("webchat:message:received",f(f({},e),{},{body:i.querySelector("[data-body]").innerText})),i.scrollIntoView({behavior:"smooth"}),this.setOfflineTimeout(),!this.openValue){this.unreadCounterTarget.style.display="flex";var o=(parseInt(this.unreadCounterTarget.innerText)||0)+1;this.unreadCounterTarget.innerText=o>99?"99+":o}}},{key:"onConversationAssignment",value:function(e){var{to:t}=e;this.titleTarget.innerText=t.name,t.online?this.onlineStatusTarget.style.display="flex":this.onlineStatusTarget.style.display="none"}},{key:"onAgentOnline",value:function(){this.onlineStatusTarget.style.display="flex",this.setOfflineTimeout()}},{key:"sendMessage",value:(r=v((function*(){var e=new FormData,t={body:this.inputTarget.value,attachments:this.files};e.append("message[body]",this.inputTarget.value),this.files.forEach((t=>{e.append("message[attachments][]",t)})),e.append("session",a.default.session);var n=this.messageTemplateTarget.cloneNode(!0);n.classList.add("received"),n.style.removeProperty("display"),n.setAttribute("data-hellotext--webchat-target","message"),n.querySelector("[data-body]").innerText=this.inputTarget.value;var r=this.attachmentContainerTarget.querySelectorAll("img");r.length>0&&r.forEach((e=>{n.querySelector("[data-attachment-container]").appendChild(e)})),this.messagesContainerTarget.appendChild(n),n.scrollIntoView({behavior:"smooth"}),this.inputTarget.value="",this.files=[],this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.classList.add("hidden"),this.inputTarget.focus();var i=yield this.messagesAPI.create(e);if(i.failed)return n.classList.add("failed");var o=yield i.json();n.setAttribute("data-id",o.id),t.id=o.id,a.default.eventEmitter.dispatch("webchat:message:sent",t),o.conversation!==this.conversationIdValue&&(this.conversationIdValue=o.conversation,this.webChatChannel.updateSubscriptionWith(this.conversationIdValue))})),function(){return r.apply(this,arguments)})},{key:"openAttachment",value:function(){this.attachmentInputTarget.click()}},{key:"onFileInputChange",value:function(){this.errorMessageContainerTarget.classList.add("hidden"),this.files=Array.from(this.attachmentInputTarget.files);var e=this.files.find((e=>{var t=e.type.split("/")[0];return["image","video","audio"].includes(t)?this.mediaValue[t].max_sizethis.createAttachmentElement(e))),this.inputTarget.focus()}},{key:"createAttachmentElement",value:function(e){var t=this.attachmentElement();if(this.attachmentContainerTarget.classList.remove("hidden"),t.setAttribute("data-name",e.name),e.type.startsWith("image/")){var n=this.attachmentImageTarget.cloneNode(!0);n.src=URL.createObjectURL(e),n.style.display="block",t.appendChild(n),this.attachmentContainerTarget.appendChild(t),this.attachmentContainerTarget.style.display="flex"}else t.querySelector("main").classList.add(...this.widthClasses,"h-20","rounded-md","bg-gray-200","p-1"),t.querySelector("p[data-attachment-name]").innerText=e.name}},{key:"removeAttachment",value:function(e){var{currentTarget:t}=e,n=t.closest("[data-hellotext--webchat-target='attachment']");this.files=this.files.filter((e=>e.name!==n.dataset.name)),n.remove(),this.inputTarget.focus()}},{key:"attachmentTargetDisconnected",value:function(){0===this.attachmentTargets.length&&(this.attachmentContainerTarget.innerHTML="",this.attachmentContainerTarget.style.display="none")}},{key:"attachmentElement",value:function(){var e=this.attachmentTemplateTarget.cloneNode(!0);return e.removeAttribute("hidden"),e.style.display="flex",e.setAttribute("data-hellotext--webchat-target","attachment"),e}},{key:"onEmojiSelect",value:function(e){var{detail:t}=e,n=this.inputTarget.value,r=this.inputTarget.selectionStart,i=this.inputTarget.selectionEnd;this.inputTarget.value=n.slice(0,r)+t+n.slice(i),this.inputTarget.selectionStart=this.inputTarget.selectionEnd=r+t.length,this.inputTarget.focus()}},{key:"setOfflineTimeout",value:function(){clearTimeout(this.offlineTimeout),this.offlineTimeout=setTimeout((()=>{this.onlineStatusTarget.style.display="none"}),this.fiveMinutes)}},{key:"byteToMegabyte",value:function(e){return Math.ceil(e/1024/1024)}},{key:"fiveMinutes",get:function(){return 3e5}},{key:"middlewares",get:function(){return[(0,i.offset)(5),(0,i.shift)({padding:24}),(0,i.flip)()]}}],n&&g(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),y}(r.Controller);t.default=k,k.values={id:String,conversationId:String,media:Object,fileSizeErrorMessage:String,placement:{type:String,default:"bottom-end"},open:{type:Boolean,default:!1},autoPlacement:{type:Boolean,default:!1},disabled:{type:Boolean,default:!1},nextPage:{type:Number,default:void 0}},k.targets=["trigger","popover","input","attachmentInput","attachmentButton","errorMessageContainer","attachmentTemplate","attachmentContainer","attachment","messageTemplate","messagesContainer","title","onlineStatus","attachmentImage","footer","toolbar","message","unreadCounter"]},660:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Configuration=void 0;var r=n(787),i=n(829);function o(e,t){for(var n=0;n{var[t,n]=e;"forms"===t?this.forms=r.Forms.assign(n):"webChat"===t?this.webchat=i.Webchat.assign(n):this[t]=n})),this}},{key:"endpoint",value:function(e){return"".concat(this.apiRoot,"/").concat(e)}}],null&&o(t.prototype,null),n&&o(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.Configuration=s,s.apiRoot="https://api.hellotext.com/v1",s.autoGenerateSession=!0,s.session=null,s.forms=r.Forms,s.webchat=i.Webchat},787:(e,t)=>{function n(e,t){for(var n=0;n{var[t,n]=e;this[t]=n})),this}},{key:"shouldShowSuccessMessage",get:function(){return this.successMessage}}],null&&n(t.prototype,null),r&&n(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.Forms=r,r.autoMount=!0,r.successMessage=!0},829:(e,t)=>{function n(e,t){for(var n=0;ne.trim())):this._classes},set:function(e){if(!Array.isArray(e)&&"string"!=typeof e)throw new Error("classes must be an array or a string");this._classes=e}},{key:"triggerClasses",get:function(){return"string"==typeof this._triggerClasses?this._triggerClasses.split(",").map((e=>e.trim())):this._triggerClasses},set:function(e){if(!Array.isArray(e)&&"string"!=typeof e)throw new Error("triggerClasses must be an array or a string");this._triggerClasses=e}},{key:"id",get:function(){return this._id},set:function(e){this._id=e}},{key:"isSet",get:function(){return!!this._id}},{key:"style",get:function(){return this._style},set:function(e){if("object"!=typeof e)throw new Error("Style must be an object");Object.entries(e).forEach((e=>{var[t,n]=e;if(!["primaryColor","secondaryColor","typography"].includes(t))throw new Error("Invalid style property: ".concat(t));if("typography"!==t&&!this.isHexOrRgba(n))throw new Error("Invalid color value: ".concat(n," for ").concat(t,". Colors must be hex or rgb/a."))})),this._style=e}},{key:"behaviour",get:function(){return this._behaviour},set:function(e){if(!Object.values(i).includes(e))throw new Error("Invalid behaviour value: ".concat(e));this._behaviour=e}},{key:"assign",value:function(e){return e&&Object.entries(e).forEach((e=>{var[t,n]=e;this[t]=n})),this}},{key:"isHexOrRgba",value:function(e){return/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(e)||/^rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3},?\s*(0|1|0?\.\d+)?\s*\)$/.test(e)}}],null&&n(t.prototype,null),o&&n(t,o),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.Webchat=o,o._id=void 0,o._container="body",o._placement="bottom-right",o._classes=[],o._triggerClasses=[],o._style={},o._behaviour=i.POPOVER},147:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=n(160);function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function o(e){for(var t=1;tt===e))}}],(n=[{key:"addSubscriber",value:function(t,n){if(e.invalid(t))throw new r.InvalidEvent(t);this.subscribers=o(o({},this.subscribers),{},{[t]:this.subscribers[t]?[...this.subscribers[t],n]:[n]})}},{key:"removeSubscriber",value:function(t,n){if(e.invalid(t))throw new r.InvalidEvent(t);this.subscribers[t]&&(this.subscribers[t]=this.subscribers[t].filter((e=>e!==n)))}},{key:"dispatch",value:function(e,t){var n;null===(n=this.subscribers[e])||void 0===n||n.forEach((e=>{e(t)}))}},{key:"listeners",get:function(){return 0!==Object.keys(this.subscribers).length}}])&&a(t.prototype,n),i&&a(t,i),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.default=c,c.events=["session-set","forms:collected","form:completed","webchat:mounted","webchat:opened","webchat:closed","webchat:message:sent","webchat:message:received"]},613:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Configuration",{enumerable:!0,get:function(){return o.Configuration}}),Object.defineProperty(t,"Event",{enumerable:!0,get:function(){return i.default}});var r,i=(r=n(147))&&r.__esModule?r:{default:r},o=n(660)},160:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"InvalidEvent",{enumerable:!0,get:function(){return r.InvalidEvent}}),Object.defineProperty(t,"NotInitializedError",{enumerable:!0,get:function(){return i.NotInitializedError}});var r=n(547),i=n(735)},547:(e,t)=>{function n(e){var t="function"==typeof Map?new Map:void 0;return n=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return r(e,arguments,s(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),o(i,e)},n(e)}function r(e,t,n){return r=i()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&o(i,n.prototype),i},r.apply(null,arguments)}function i(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function o(e,t){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},o(e,t)}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidEvent=void 0;var a=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&o(e,t)}(l,e);var t,n,r,a=(n=l,r=i(),function(){var e,t=s(n);if(r){var i=s(this).constructor;e=Reflect.construct(t,arguments,i)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function l(e){var t;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,l),(t=a.call(this,"".concat(e," is not valid. Please provide a valid event name"))).name="InvalidEvent",t}return t=l,Object.defineProperty(t,"prototype",{writable:!1}),t}(n(Error));t.InvalidEvent=a},735:(e,t)=>{function n(e){var t="function"==typeof Map?new Map:void 0;return n=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return r(e,arguments,s(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),o(i,e)},n(e)}function r(e,t,n){return r=i()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&o(i,n.prototype),i},r.apply(null,arguments)}function i(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function o(e,t){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},o(e,t)}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.NotInitializedError=void 0;var a=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&o(e,t)}(l,e);var t,n,r,a=(n=l,r=i(),function(){var e,t=s(n);if(r){var i=s(this).constructor;e=Reflect.construct(t,arguments,i)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function l(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,l),(e=a.call(this,"You need to initialize before tracking events. Call Hellotext.initialize and pass your public business id")).name="NotInitializedError",e}return t=l,Object.defineProperty(t,"prototype",{writable:!1}),t}(n(Error));t.NotInitializedError=a},688:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=n(613),i=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=a(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var s=i?Object.getOwnPropertyDescriptor(e,o):null;s&&(s.get||s.set)?Object.defineProperty(r,o,s):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}(n(680)),o=n(541),s=n(160);function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(a=function(e){return e?n:t})(e)}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{};if(this.notInitialized)throw new s.NotInitializedError;var n=c(c({},t&&t.headers||{}),this.headers),r=c(c({session:this.session,action:e},t),{},{url:t&&t.url||window.location.href});return delete r.headers,yield i.default.events.create({headers:n,body:r})})),function(e){return a.apply(this,arguments)})},{key:"on",value:function(e,t){this.eventEmitter.addSubscriber(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeSubscriber(e,t)}},{key:"session",get:function(){return o.Session.session}},{key:"isInitialized",get:function(){return void 0!==o.Session.session}},{key:"notInitialized",get:function(){return void 0===this.business.id}},{key:"headers",get:function(){if(this.notInitialized)throw new s.NotInitializedError;return{Authorization:"Bearer ".concat(this.business.id),Accept:"application/json","Content-Type":"application/json"}}}],n&&f(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();Object.defineProperty(b,g,{writable:!0,value:void 0}),Object.defineProperty(b,y,{writable:!0,value:void 0}),b.eventEmitter=new r.Event,b.forms=void 0,b.business=void 0,b.webchat=void 0;var w=b;t.default=w},989:(e,t,n)=>{var r=n(599),i=l(n(688)),o=l(n(425)),s=l(n(69)),a=l(n(143));function l(e){return e&&e.__esModule?e:{default:e}}n(689);var c=r.Application.start();c.register("hellotext--form",o.default),c.register("hellotext--webchat",s.default),c.register("hellotext--webchat--emoji",a.default),window.Hellotext=i.default,i.default},485:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default={white_label:{powered_by:"Powered by"},errors:{parameter_not_unique:"This value is taken.",blank:"This field is required."},forms:{phone:"Click the link sent via SMS to verify your submission.",email:"Click the link sent via email to verify your submission.",phone_and_email:"Click the links sent via SMS and email to verify your submission.",none:"Your submission has been received."}}},594:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default={white_label:{powered_by:"Desarrollado por"},errors:{parameter_not_unique:"Este valor ya está en uso.",blank:"Este campo es obligatorio."},forms:{phone:"Haga clic en el enlace enviado por SMS para verificar su envío.",email:"Haga clic en el enlace enviado por e-mail para verificar su envío.",phone_and_email:"Haga clic en los enlaces enviados por SMS y e-mail para verificar su envío.",none:"Su envío ha sido recibido."}}},779:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=o(n(485)),i=o(n(594));function o(e){return e&&e.__esModule?e:{default:e}}var s={en:r.default,es:i.default};t.default=s},926:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Business=void 0;var r=o(n(830)),i=o(n(779));function o(e){return e&&e.__esModule?e:{default:e}}function s(e,t){for(var n=0;ne.json())).then((e=>{if(this.data=e,"undefined"!=typeof document){var t=document.createElement("link");t.rel="stylesheet",t.href=e.style_url,document.head.append(t)}}))}}])&&s(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.Business=a},524:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Cookies=void 0;var r,i=(r=n(688))&&r.__esModule?r:{default:r};function o(e,t){for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.Form=void 0;var r,i=(r=n(688))&&r.__esModule?r:{default:r},o=n(219),s=n(846);function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function l(e,t,n){return(t=h(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function u(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Object.defineProperty(this,m,{value:g}),this.data=t,this.element=n||document.querySelector('[data-hello-form="'.concat(this.id,'"]'))||document.createElement("form")}var t,n,r,h;return t=e,n=[{key:"mount",value:(r=function*(){var e,{ifCompleted:t=!0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(t&&this.hasBeenCompleted)return null===(e=this.element)||void 0===e||e.remove(),i.default.eventEmitter.dispatch("form:completed",function(e){for(var t=1;t{this.element.setAttribute(e.name,e.value)})),document.contains(this.element)||document.body.appendChild(this.element),i.default.business.features.white_label||this.element.prepend(s.LogoBuilder.build())},h=function(){var e=this,t=arguments;return new Promise((function(n,i){var o=r.apply(e,t);function s(e){c(o,n,i,s,a,"next",e)}function a(e){c(o,n,i,s,a,"throw",e)}s(void 0)}))},function(){return h.apply(this,arguments)})},{key:"buildHeader",value:function(e){var t=d(this,m)[m]("[data-form-header]","header");t.innerHTML=e.content,this.element.querySelector("[data-form-header]")?this.element.querySelector("[data-form-header]").replaceWith(t):this.element.prepend(t)}},{key:"buildInputs",value:function(e){var t=d(this,m)[m]("[data-form-inputs]","main");e.map((e=>o.InputBuilder.build(e))).forEach((e=>t.appendChild(e))),this.element.querySelector("[data-form-inputs]")?this.element.querySelector("[data-form-inputs]").replaceWith(t):this.element.querySelector("[data-form-header]").insertAdjacentHTML("afterend",t.outerHTML)}},{key:"buildButton",value:function(e){var t=d(this,m)[m]("[data-form-button]","button");t.innerText=e.text,t.setAttribute("data-action","click->hellotext--form#submit"),t.setAttribute("data-hellotext--form-target","button"),this.element.querySelector("[data-form-button]")?this.element.querySelector("[data-form-button]").replaceWith(t):this.element.querySelector("[data-form-inputs]").insertAdjacentHTML("afterend",t.outerHTML)}},{key:"buildFooter",value:function(e){var t=d(this,m)[m]("[data-form-footer]","footer");t.innerHTML=e.content,this.element.querySelector("[data-form-footer]")?this.element.querySelector("[data-form-footer]").replaceWith(t):this.element.appendChild(t)}},{key:"markAsCompleted",value:function(e){var t={state:"completed",id:this.id,data:e,completedAt:(new Date).getTime()};localStorage.setItem("hello-form-".concat(this.id),JSON.stringify(t)),i.default.eventEmitter.dispatch("form:completed",t)}},{key:"hasBeenCompleted",get:function(){return null!==localStorage.getItem("hello-form-".concat(this.id))}},{key:"id",get:function(){return this.data.id}},{key:"localeAuthKey",get:function(){var e=this.data.steps[0];return e.inputs.some((e=>"email"===e.kind))&&e.inputs.some((e=>"phone"===e.kind))?"phone_and_email":e.inputs.some((e=>"email"===e.kind))?"email":e.inputs.some((e=>"phone"===e.kind))?"phone":"none"}},{key:"elementAttributes",get:function(){return[{name:"data-controller",value:"hellotext--form"},{name:"data-hello-form",value:this.id},{name:"data-hellotext--form-data-value",value:JSON.stringify(this.data)}]}}],n&&u(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function g(e,t){var n=this.element.querySelector(e);if(n)return n.cloneNode(!0);var r=document.createElement(t);return r.setAttribute(e.replace("[","").replace("]",""),""),r}t.Form=v},187:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FormCollection=void 0;var r=l(n(688)),i=l(n(495)),o=n(613),s=n(860),a=n(160);function l(e){return e&&e.__esModule?e:{default:e}}function c(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function u(e,t){for(var n=0;n"childList"===e.type&&e.addedNodes.length>0))&&Array.from(document.querySelectorAll("[data-hello-form]"))&&o.Configuration.forms.autoMount&&this.collect()}},{key:"collect",value:(l=function*(){if(r.default.notInitialized)throw new a.NotInitializedError;if(!this.fetching){var e=function(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}(this,f)[f];if(0!==e.length){var t=e.map((e=>i.default.get(e).then((e=>e.json()))));r.default.business.enabledWhitelist||console.warn("No whitelist has been configured. It is advised to whitelist the domain to avoid bots from submitting forms."),this.fetching=!0,yield Promise.all(t).then((e=>e.forEach(this.add))).then((()=>r.default.eventEmitter.dispatch("forms:collected",this))).then((()=>this.fetching=!1)),o.Configuration.forms.autoMount&&this.forms.forEach((e=>e.mount()))}}},h=function(){var e=this,t=arguments;return new Promise((function(n,r){var i=l.apply(e,t);function o(e){c(i,n,r,o,s,"next",e)}function s(e){c(i,n,r,o,s,"throw",e)}o(void 0)}))},function(){return h.apply(this,arguments)})},{key:"forEach",value:function(e){this.forms.forEach(e)}},{key:"map",value:function(e){return this.forms.map(e)}},{key:"add",value:function(e){this.includes(e.id)||this.forms.push(new s.Form(e))}},{key:"getById",value:function(e){return this.forms.find((t=>t.id===e))}},{key:"getByIndex",value:function(e){return this.forms[e]}},{key:"includes",value:function(e){return this.forms.some((t=>t.id===e))}},{key:"excludes",value:function(e){return!this.includes(e)}},{key:"length",get:function(){return this.forms.length}}],n&&u(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();function m(){return Array.from(document.querySelectorAll("[data-hello-form]")).map((e=>e.dataset.helloForm)).filter(this.excludes)}t.FormCollection=p},541:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Business",{enumerable:!0,get:function(){return r.Business}}),Object.defineProperty(t,"Cookies",{enumerable:!0,get:function(){return s.Cookies}}),Object.defineProperty(t,"Form",{enumerable:!0,get:function(){return i.Form}}),Object.defineProperty(t,"FormCollection",{enumerable:!0,get:function(){return a.FormCollection}}),Object.defineProperty(t,"Query",{enumerable:!0,get:function(){return o.Query}}),Object.defineProperty(t,"Session",{enumerable:!0,get:function(){return c.Session}}),Object.defineProperty(t,"Webchat",{enumerable:!0,get:function(){return l.Webchat}});var r=n(926),i=n(860),o=n(992),s=n(524),a=n(187),l=n(516),c=n(241)},992:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Query=void 0;var r=n(524);function i(e,t){for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.Session=void 0;var r=n(613),i=n(541);function o(e,t){for(var n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.Webchat=void 0,o(n(688));var r=n(613),i=o(n(680));function o(e){return e&&e.__esModule?e:{default:e}}function s(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(e){return void n(e)}a.done?t(l):Promise.resolve(l).then(r,i)}function a(e,t){for(var n=0;n{n.d(t,{Z:()=>a});var r=n(81),i=n.n(r),o=n(645),s=n.n(o)()(i());s.push([e.id,".hidden {\n display: none;\n}\n\nform[data-hello-form] {\n position: relative;\n\n & article {\n & [data-error-container] {\n font-size: 0.875rem;\n line-height: 1.25rem;\n display: none;\n }\n\n &:has(input:invalid) {\n & [data-error-container] {\n display: block;\n }\n }\n }\n\n & [data-logo-container] {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n\n & small {\n margin: 0 0.3rem;\n }\n\n & [data-hello-brand] {\n width: 4rem;\n }\n }\n}\n",""]);const a=s},645:e=>{e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n="",r=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),r&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),r&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n})).join("")},t.i=function(e,n,r,i,o){"string"==typeof e&&(e=[[null,e,void 0]]);var s={};if(r)for(var a=0;a0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=o),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),i&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=i):u[4]="".concat(i)),t.push(u))}},t}},81:e=>{e.exports=function(e){return e[1]}},431:(e,t,n)=>{function r(e){return e&&e.__esModule?e.default:e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}n.r(t),n.d(t,{Data:()=>X,Emoji:()=>ye,FrequentlyUsed:()=>Z,I18n:()=>Q,Picker:()=>et,SafeFlags:()=>ce,SearchIndex:()=>le,Store:()=>D,getEmojiDataFromNative:()=>he,init:()=>ie});var o,s,a,l,c,u,h={},d=[],f=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function p(e,t){for(var n in t)e[n]=t[n];return e}function m(e){var t=e.parentNode;t&&t.removeChild(e)}function v(e,t,n){var r,i,s,a={};for(s in t)"key"==s?r=t[s]:"ref"==s?i=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?o.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return g(e,a,r,i,null)}function g(e,t,n,r,i){var o={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==i?++a:i};return null==i&&null!=s.vnode&&s.vnode(o),o}function y(e){return e.children}function b(e,t){this.props=e,this.context=t}function w(e,t){if(null==t)return e.__?w(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t0?g(m.type,m.props,m.key,null,m.__v):m)){if(m.__=n,m.__b=n.__b+1,null===(p=k[u])||p&&m.key==p.key&&m.type===p.type)k[u]=void 0;else for(f=0;f{let e=null;try{navigator.userAgent.includes("jsdom")||(e=document.createElement("canvas").getContext("2d",{willReadFrequently:!0}))}catch{}if(!e)return()=>!1;const t=20,n=Math.floor(12.5);return e.font=n+"px Arial, Sans-Serif",e.textBaseline="top",e.canvas.width=40,e.canvas.height=25,n=>{e.clearRect(0,0,40,25),e.fillStyle="#FF0000",e.fillText(n,0,22),e.fillStyle="#0000FF",e.fillText(n,t,22);const r=e.getImageData(0,0,t,25).data,i=r.length;let o=0;for(;o=i)return!1;const s=t+o/4%t,a=Math.floor(o/4/t),l=e.getImageData(s,a,1,1).data;return r[o]===l[0]&&r[o+2]===l[2]&&!(e.measureText(n).width>=t)}})();var q={latestVersion:function(){for(const{v:e,emoji:t}of $)if(H(t))return e},noCountryFlags:function(){return!H("🇨🇦")}};const K=["+1","grinning","kissing_heart","heart_eyes","laughing","stuck_out_tongue_winking_eye","sweat_smile","joy","scream","disappointed","unamused","weary","sob","sunglasses","heart"];let W=null;var Z={add:function(e){W||(W=D.get("frequently")||{});const t=e.id||e;t&&(W[t]||(W[t]=0),W[t]+=1,D.set("last",t),D.set("frequently",W))},get:function({maxFrequentRows:e,perLine:t}){if(!e)return[];W||(W=D.get("frequently"));let n=[];if(!W){W={};for(let e in K.slice(0,t)){const r=K[e];W[r]=t-e,n.push(r)}return n}const r=e*t,i=D.get("last");for(let e in W)n.push(e);if(n.sort(((e,t)=>{const n=W[t],r=W[e];return n==r?e.localeCompare(t):n-r})),n.length>r){const e=n.slice(r);n=n.slice(0,r);for(let t of e)t!=i&&delete W[t];i&&-1==n.indexOf(i)&&(delete W[n[n.length-1]],n.splice(-1,1,i)),D.set("frequently",W)}return n},DEFAULTS:K},J={};J=JSON.parse('{"search":"Search","search_no_results_1":"Oh no!","search_no_results_2":"That emoji couldn’t be found","pick":"Pick an emoji…","add_custom":"Add custom emoji","categories":{"activity":"Activity","custom":"Custom","flags":"Flags","foods":"Food & Drink","frequent":"Frequently used","nature":"Animals & Nature","objects":"Objects","people":"Smileys & People","places":"Travel & Places","search":"Search Results","symbols":"Symbols"},"skins":{"1":"Default","2":"Light","3":"Medium-Light","4":"Medium","5":"Medium-Dark","6":"Dark","choose":"Choose default skin tone"}}');var G={autoFocus:{value:!1},dynamicWidth:{value:!1},emojiButtonColors:{value:null},emojiButtonRadius:{value:"100%"},emojiButtonSize:{value:36},emojiSize:{value:24},emojiVersion:{value:15,choices:[1,2,3,4,5,11,12,12.1,13,13.1,14,15]},exceptEmojis:{value:[]},icons:{value:"auto",choices:["auto","outline","solid"]},locale:{value:"en",choices:["en","ar","be","cs","de","es","fa","fi","fr","hi","it","ja","ko","nl","pl","pt","ru","sa","tr","uk","vi","zh"]},maxFrequentRows:{value:4},navPosition:{value:"top",choices:["top","bottom","none"]},noCountryFlags:{value:!1},noResultsEmoji:{value:null},perLine:{value:9},previewEmoji:{value:null},previewPosition:{value:"bottom",choices:["top","bottom","none"]},searchPosition:{value:"sticky",choices:["sticky","static","none"]},set:{value:"native",choices:["native","apple","facebook","google","twitter"]},skin:{value:1,choices:[1,2,3,4,5,6]},skinTonePosition:{value:"preview",choices:["preview","search","none"]},theme:{value:"auto",choices:["auto","light","dark"]},categories:null,categoryIcons:null,custom:null,data:null,i18n:null,getImageURL:null,getSpritesheetURL:null,onAddCustomEmoji:null,onClickOutside:null,onEmojiSelect:null,stickySearch:{deprecated:!0,value:!0}};let Q=null,X=null;const Y={};async function ee(e){if(Y[e])return Y[e];const t=await fetch(e),n=await t.json();return Y[e]=n,n}let te=null,ne=null,re=!1;function ie(e,{caller:t}={}){return te||(te=new Promise((e=>{ne=e}))),e?async function(e){re=!0;let{emojiVersion:t,set:n,locale:i}=e;if(t||(t=G.emojiVersion.value),n||(n=G.set.value),i||(i=G.locale.value),X)X.categories=X.categories.filter((e=>!e.name));else{X=("function"==typeof e.data?await e.data():e.data)||await ee(`https://cdn.jsdelivr.net/npm/@emoji-mart/data@latest/sets/${t}/${n}.json`),X.emoticons={},X.natives={},X.categories.unshift({id:"frequent",emojis:[]});for(const e in X.aliases){const t=X.aliases[e],n=X.emojis[t];n&&(n.aliases||(n.aliases=[]),n.aliases.push(e))}X.originalCategories=X.categories}if(Q=("function"==typeof e.i18n?await e.i18n():e.i18n)||("en"==i?r(J):await ee(`https://cdn.jsdelivr.net/npm/@emoji-mart/data@latest/i18n/${i}.json`)),e.custom)for(let t in e.custom){t=parseInt(t);const n=e.custom[t],r=e.custom[t-1];if(n.emojis&&n.emojis.length){n.id||(n.id=`custom_${t+1}`),n.name||(n.name=Q.categories.custom),r&&!n.icon&&(n.target=r.target||r),X.categories.push(n);for(const e of n.emojis)X.emojis[e.id]=e}}e.categories&&(X.categories=X.originalCategories.filter((t=>-1!=e.categories.indexOf(t.id))).sort(((t,n)=>e.categories.indexOf(t.id)-e.categories.indexOf(n.id))));let o=null,s=null;"native"==n&&(o=q.latestVersion(),s=e.noCountryFlags||q.noCountryFlags());let a=X.categories.length,l=!1;for(;a--;){const t=X.categories[a];if("frequent"==t.id){let{maxFrequentRows:n,perLine:r}=e;n=n>=0?n:G.maxFrequentRows.value,r||(r=G.perLine.value),t.emojis=Z.get({maxFrequentRows:n,perLine:r})}if(!t.emojis||!t.emojis.length){X.categories.splice(a,1);continue}const{categoryIcons:n}=e;if(n){const e=n[t.id];e&&!t.icon&&(t.icon=e)}let r=t.emojis.length;for(;r--;){const n=t.emojis[r],i=n.id?n:X.emojis[n],a=()=>{t.emojis.splice(r,1)};if(!i||e.exceptEmojis&&e.exceptEmojis.includes(i.id))a();else if(o&&i.version>o)a();else if(!s||"flags"!=t.id||ce.includes(i.id)){if(!i.search){if(l=!0,i.search=","+[[i.id,!1],[i.name,!0],[i.keywords,!1],[i.emoticons,!1]].map((([e,t])=>{if(e)return(Array.isArray(e)?e:[e]).map((e=>(t?e.split(/[-|_|\s]+/):[e]).map((e=>e.toLowerCase())))).flat()})).flat().filter((e=>e&&e.trim())).join(","),i.emoticons)for(const e of i.emoticons)X.emoticons[e]||(X.emoticons[e]=i.id);let e=0;for(const t of i.skins){if(!t)continue;e++;const{native:n}=t;n&&(X.natives[n]=i.id,i.search+=`,${n}`);const r=1==e?"":`:skin-tone-${e}:`;t.shortcodes=`:${i.id}:${r}`}}}else a()}}l&&le.reset(),ne()}(e):t&&!re&&console.warn(`\`${t}\` requires data to be initialized first. Promise will be pending until \`init\` is called.`),te}function oe(e,t,n){e||(e={});const r={};for(let i in t)r[i]=se(i,e,t,n);return r}function se(e,t,n,r){const i=n[e];let o=r&&r.getAttribute(e)||(null!=t[e]&&null!=t[e]?t[e]:null);return i?(null!=o&&i.value&&typeof i.value!=typeof o&&(o="boolean"==typeof i.value?"false"!=o:i.value.constructor(o)),i.transform&&o&&(o=i.transform(o)),(null==o||i.choices&&-1==i.choices.indexOf(o))&&(o=i.value),o):o}let ae=null;var le={search:async function(e,{maxResults:t,caller:n}={}){if(!e||!e.trim().length)return null;t||(t=90),await ie(null,{caller:n||"SearchIndex.search"});const r=e.toLowerCase().replace(/(\w)-/,"$1 ").split(/[\s|,]+/).filter(((e,t,n)=>e.trim()&&n.indexOf(e)==t));if(!r.length)return;let i,o,s=ae||(ae=Object.values(X.emojis));for(const e of r){if(!s.length)break;i=[],o={};for(const t of s){if(!t.search)continue;const n=t.search.indexOf(`,${e}`);-1!=n&&(i.push(t),o[t.id]||(o[t.id]=0),o[t.id]+=t.id==e?0:n+1)}s=i}return i.length<2||(i.sort(((e,t)=>{const n=o[e.id],r=o[t.id];return n==r?e.id.localeCompare(t.id):n-r})),i.length>t&&(i=i.slice(0,t))),i},get:function(e){return e.id?e:X.emojis[e]||X.emojis[X.aliases[e]]||X.emojis[X.natives[e]]},reset:function(){ae=null},SHORTCODES_REGEX:/^(?:\:([^\:]+)\:)(?:\:skin-tone-(\d)\:)?$/};const ce=["checkered_flag","crossed_flags","pirate_flag","rainbow-flag","transgender_flag","triangular_flag_on_post","waving_black_flag","waving_white_flag"];function ue(e,{skinIndex:t=0}={}){const n=e.skins[t]||(t=0,e.skins[t]),r={id:e.id,name:e.name,native:n.native,unified:n.unified,keywords:e.keywords,shortcodes:n.shortcodes||e.shortcodes};return e.skins.length>1&&(r.skin=t+1),n.src&&(r.src=n.src),e.aliases&&e.aliases.length&&(r.aliases=e.aliases),e.emoticons&&e.emoticons.length&&(r.emoticons=e.emoticons),r}async function he(e){const t=await le.search(e,{maxResults:1,caller:"getEmojiDataFromNative"});if(!t||!t.length)return null;const n=t[0];let r=0;for(let t of n.skins){if(t.native==e)break;r++}return ue(n,{skinIndex:r})}var de={categories:{activity:{outline:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:z("path",{d:"M12 0C5.373 0 0 5.372 0 12c0 6.627 5.373 12 12 12 6.628 0 12-5.373 12-12 0-6.628-5.372-12-12-12m9.949 11H17.05c.224-2.527 1.232-4.773 1.968-6.113A9.966 9.966 0 0 1 21.949 11M13 11V2.051a9.945 9.945 0 0 1 4.432 1.564c-.858 1.491-2.156 4.22-2.392 7.385H13zm-2 0H8.961c-.238-3.165-1.536-5.894-2.393-7.385A9.95 9.95 0 0 1 11 2.051V11zm0 2v8.949a9.937 9.937 0 0 1-4.432-1.564c.857-1.492 2.155-4.221 2.393-7.385H11zm4.04 0c.236 3.164 1.534 5.893 2.392 7.385A9.92 9.92 0 0 1 13 21.949V13h2.04zM4.982 4.887C5.718 6.227 6.726 8.473 6.951 11h-4.9a9.977 9.977 0 0 1 2.931-6.113M2.051 13h4.9c-.226 2.527-1.233 4.771-1.969 6.113A9.972 9.972 0 0 1 2.051 13m16.967 6.113c-.735-1.342-1.744-3.586-1.968-6.113h4.899a9.961 9.961 0 0 1-2.931 6.113"})}),solid:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:z("path",{d:"M16.17 337.5c0 44.98 7.565 83.54 13.98 107.9C35.22 464.3 50.46 496 174.9 496c9.566 0 19.59-.4707 29.84-1.271L17.33 307.3C16.53 317.6 16.17 327.7 16.17 337.5zM495.8 174.5c0-44.98-7.565-83.53-13.98-107.9c-4.688-17.54-18.34-31.23-36.04-35.95C435.5 27.91 392.9 16 337 16c-9.564 0-19.59 .4707-29.84 1.271l187.5 187.5C495.5 194.4 495.8 184.3 495.8 174.5zM26.77 248.8l236.3 236.3c142-36.1 203.9-150.4 222.2-221.1L248.9 26.87C106.9 62.96 45.07 177.2 26.77 248.8zM256 335.1c0 9.141-7.474 16-16 16c-4.094 0-8.188-1.564-11.31-4.689L164.7 283.3C161.6 280.2 160 276.1 160 271.1c0-8.529 6.865-16 16-16c4.095 0 8.189 1.562 11.31 4.688l64.01 64C254.4 327.8 256 331.9 256 335.1zM304 287.1c0 9.141-7.474 16-16 16c-4.094 0-8.188-1.564-11.31-4.689L212.7 235.3C209.6 232.2 208 228.1 208 223.1c0-9.141 7.473-16 16-16c4.094 0 8.188 1.562 11.31 4.688l64.01 64.01C302.5 279.8 304 283.9 304 287.1zM256 175.1c0-9.141 7.473-16 16-16c4.094 0 8.188 1.562 11.31 4.688l64.01 64.01c3.125 3.125 4.688 7.219 4.688 11.31c0 9.133-7.468 16-16 16c-4.094 0-8.189-1.562-11.31-4.688l-64.01-64.01C257.6 184.2 256 180.1 256 175.1z"})})},custom:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",children:z("path",{d:"M417.1 368c-5.937 10.27-16.69 16-27.75 16c-5.422 0-10.92-1.375-15.97-4.281L256 311.4V448c0 17.67-14.33 32-31.1 32S192 465.7 192 448V311.4l-118.3 68.29C68.67 382.6 63.17 384 57.75 384c-11.06 0-21.81-5.734-27.75-16c-8.828-15.31-3.594-34.88 11.72-43.72L159.1 256L41.72 187.7C26.41 178.9 21.17 159.3 29.1 144C36.63 132.5 49.26 126.7 61.65 128.2C65.78 128.7 69.88 130.1 73.72 132.3L192 200.6V64c0-17.67 14.33-32 32-32S256 46.33 256 64v136.6l118.3-68.29c3.838-2.213 7.939-3.539 12.07-4.051C398.7 126.7 411.4 132.5 417.1 144c8.828 15.31 3.594 34.88-11.72 43.72L288 256l118.3 68.28C421.6 333.1 426.8 352.7 417.1 368z"})}),flags:{outline:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:z("path",{d:"M0 0l6.084 24H8L1.916 0zM21 5h-4l-1-4H4l3 12h3l1 4h13L21 5zM6.563 3h7.875l2 8H8.563l-2-8zm8.832 10l-2.856 1.904L12.063 13h3.332zM19 13l-1.5-6h1.938l2 8H16l3-2z"})}),solid:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:z("path",{d:"M64 496C64 504.8 56.75 512 48 512h-32C7.25 512 0 504.8 0 496V32c0-17.75 14.25-32 32-32s32 14.25 32 32V496zM476.3 0c-6.365 0-13.01 1.35-19.34 4.233c-45.69 20.86-79.56 27.94-107.8 27.94c-59.96 0-94.81-31.86-163.9-31.87C160.9 .3055 131.6 4.867 96 15.75v350.5c32-9.984 59.87-14.1 84.85-14.1c73.63 0 124.9 31.78 198.6 31.78c31.91 0 68.02-5.971 111.1-23.09C504.1 355.9 512 344.4 512 332.1V30.73C512 11.1 495.3 0 476.3 0z"})})},foods:{outline:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:z("path",{d:"M17 4.978c-1.838 0-2.876.396-3.68.934.513-1.172 1.768-2.934 4.68-2.934a1 1 0 0 0 0-2c-2.921 0-4.629 1.365-5.547 2.512-.064.078-.119.162-.18.244C11.73 1.838 10.798.023 9.207.023 8.579.022 7.85.306 7 .978 5.027 2.54 5.329 3.902 6.492 4.999 3.609 5.222 0 7.352 0 12.969c0 4.582 4.961 11.009 9 11.009 1.975 0 2.371-.486 3-1 .629.514 1.025 1 3 1 4.039 0 9-6.418 9-11 0-5.953-4.055-8-7-8M8.242 2.546c.641-.508.943-.523.965-.523.426.169.975 1.405 1.357 3.055-1.527-.629-2.741-1.352-2.98-1.846.059-.112.241-.356.658-.686M15 21.978c-1.08 0-1.21-.109-1.559-.402l-.176-.146c-.367-.302-.816-.452-1.266-.452s-.898.15-1.266.452l-.176.146c-.347.292-.477.402-1.557.402-2.813 0-7-5.389-7-9.009 0-5.823 4.488-5.991 5-5.991 1.939 0 2.484.471 3.387 1.251l.323.276a1.995 1.995 0 0 0 2.58 0l.323-.276c.902-.78 1.447-1.251 3.387-1.251.512 0 5 .168 5 6 0 3.617-4.187 9-7 9"})}),solid:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:z("path",{d:"M481.9 270.1C490.9 279.1 496 291.3 496 304C496 316.7 490.9 328.9 481.9 337.9C472.9 346.9 460.7 352 448 352H64C51.27 352 39.06 346.9 30.06 337.9C21.06 328.9 16 316.7 16 304C16 291.3 21.06 279.1 30.06 270.1C39.06 261.1 51.27 256 64 256H448C460.7 256 472.9 261.1 481.9 270.1zM475.3 388.7C478.3 391.7 480 395.8 480 400V416C480 432.1 473.3 449.3 461.3 461.3C449.3 473.3 432.1 480 416 480H96C79.03 480 62.75 473.3 50.75 461.3C38.74 449.3 32 432.1 32 416V400C32 395.8 33.69 391.7 36.69 388.7C39.69 385.7 43.76 384 48 384H464C468.2 384 472.3 385.7 475.3 388.7zM50.39 220.8C45.93 218.6 42.03 215.5 38.97 211.6C35.91 207.7 33.79 203.2 32.75 198.4C31.71 193.5 31.8 188.5 32.99 183.7C54.98 97.02 146.5 32 256 32C365.5 32 457 97.02 479 183.7C480.2 188.5 480.3 193.5 479.2 198.4C478.2 203.2 476.1 207.7 473 211.6C469.1 215.5 466.1 218.6 461.6 220.8C457.2 222.9 452.3 224 447.3 224H64.67C59.73 224 54.84 222.9 50.39 220.8zM372.7 116.7C369.7 119.7 368 123.8 368 128C368 131.2 368.9 134.3 370.7 136.9C372.5 139.5 374.1 141.6 377.9 142.8C380.8 143.1 384 144.3 387.1 143.7C390.2 143.1 393.1 141.6 395.3 139.3C397.6 137.1 399.1 134.2 399.7 131.1C400.3 128 399.1 124.8 398.8 121.9C397.6 118.1 395.5 116.5 392.9 114.7C390.3 112.9 387.2 111.1 384 111.1C379.8 111.1 375.7 113.7 372.7 116.7V116.7zM244.7 84.69C241.7 87.69 240 91.76 240 96C240 99.16 240.9 102.3 242.7 104.9C244.5 107.5 246.1 109.6 249.9 110.8C252.8 111.1 256 112.3 259.1 111.7C262.2 111.1 265.1 109.6 267.3 107.3C269.6 105.1 271.1 102.2 271.7 99.12C272.3 96.02 271.1 92.8 270.8 89.88C269.6 86.95 267.5 84.45 264.9 82.7C262.3 80.94 259.2 79.1 256 79.1C251.8 79.1 247.7 81.69 244.7 84.69V84.69zM116.7 116.7C113.7 119.7 112 123.8 112 128C112 131.2 112.9 134.3 114.7 136.9C116.5 139.5 118.1 141.6 121.9 142.8C124.8 143.1 128 144.3 131.1 143.7C134.2 143.1 137.1 141.6 139.3 139.3C141.6 137.1 143.1 134.2 143.7 131.1C144.3 128 143.1 124.8 142.8 121.9C141.6 118.1 139.5 116.5 136.9 114.7C134.3 112.9 131.2 111.1 128 111.1C123.8 111.1 119.7 113.7 116.7 116.7L116.7 116.7z"})})},frequent:{outline:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[z("path",{d:"M13 4h-2l-.001 7H9v2h2v2h2v-2h4v-2h-4z"}),z("path",{d:"M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0m0 22C6.486 22 2 17.514 2 12S6.486 2 12 2s10 4.486 10 10-4.486 10-10 10"})]}),solid:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:z("path",{d:"M256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512zM232 256C232 264 236 271.5 242.7 275.1L338.7 339.1C349.7 347.3 364.6 344.3 371.1 333.3C379.3 322.3 376.3 307.4 365.3 300L280 243.2V120C280 106.7 269.3 96 255.1 96C242.7 96 231.1 106.7 231.1 120L232 256z"})})},nature:{outline:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[z("path",{d:"M15.5 8a1.5 1.5 0 1 0 .001 3.001A1.5 1.5 0 0 0 15.5 8M8.5 8a1.5 1.5 0 1 0 .001 3.001A1.5 1.5 0 0 0 8.5 8"}),z("path",{d:"M18.933 0h-.027c-.97 0-2.138.787-3.018 1.497-1.274-.374-2.612-.51-3.887-.51-1.285 0-2.616.133-3.874.517C7.245.79 6.069 0 5.093 0h-.027C3.352 0 .07 2.67.002 7.026c-.039 2.479.276 4.238 1.04 5.013.254.258.882.677 1.295.882.191 3.177.922 5.238 2.536 6.38.897.637 2.187.949 3.2 1.102C8.04 20.6 8 20.795 8 21c0 1.773 2.35 3 4 3 1.648 0 4-1.227 4-3 0-.201-.038-.393-.072-.586 2.573-.385 5.435-1.877 5.925-7.587.396-.22.887-.568 1.104-.788.763-.774 1.079-2.534 1.04-5.013C23.929 2.67 20.646 0 18.933 0M3.223 9.135c-.237.281-.837 1.155-.884 1.238-.15-.41-.368-1.349-.337-3.291.051-3.281 2.478-4.972 3.091-5.031.256.015.731.27 1.265.646-1.11 1.171-2.275 2.915-2.352 5.125-.133.546-.398.858-.783 1.313M12 22c-.901 0-1.954-.693-2-1 0-.654.475-1.236 1-1.602V20a1 1 0 1 0 2 0v-.602c.524.365 1 .947 1 1.602-.046.307-1.099 1-2 1m3-3.48v.02a4.752 4.752 0 0 0-1.262-1.02c1.092-.516 2.239-1.334 2.239-2.217 0-1.842-1.781-2.195-3.977-2.195-2.196 0-3.978.354-3.978 2.195 0 .883 1.148 1.701 2.238 2.217A4.8 4.8 0 0 0 9 18.539v-.025c-1-.076-2.182-.281-2.973-.842-1.301-.92-1.838-3.045-1.853-6.478l.023-.041c.496-.826 1.49-1.45 1.804-3.102 0-2.047 1.357-3.631 2.362-4.522C9.37 3.178 10.555 3 11.948 3c1.447 0 2.685.192 3.733.57 1 .9 2.316 2.465 2.316 4.48.313 1.651 1.307 2.275 1.803 3.102.035.058.068.117.102.178-.059 5.967-1.949 7.01-4.902 7.19m6.628-8.202c-.037-.065-.074-.13-.113-.195a7.587 7.587 0 0 0-.739-.987c-.385-.455-.648-.768-.782-1.313-.076-2.209-1.241-3.954-2.353-5.124.531-.376 1.004-.63 1.261-.647.636.071 3.044 1.764 3.096 5.031.027 1.81-.347 3.218-.37 3.235"})]}),solid:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 576 512",children:z("path",{d:"M332.7 19.85C334.6 8.395 344.5 0 356.1 0C363.6 0 370.6 3.52 375.1 9.502L392 32H444.1C456.8 32 469.1 37.06 478.1 46.06L496 64H552C565.3 64 576 74.75 576 88V112C576 156.2 540.2 192 496 192H426.7L421.6 222.5L309.6 158.5L332.7 19.85zM448 64C439.2 64 432 71.16 432 80C432 88.84 439.2 96 448 96C456.8 96 464 88.84 464 80C464 71.16 456.8 64 448 64zM416 256.1V480C416 497.7 401.7 512 384 512H352C334.3 512 320 497.7 320 480V364.8C295.1 377.1 268.8 384 240 384C211.2 384 184 377.1 160 364.8V480C160 497.7 145.7 512 128 512H96C78.33 512 64 497.7 64 480V249.8C35.23 238.9 12.64 214.5 4.836 183.3L.9558 167.8C-3.331 150.6 7.094 133.2 24.24 128.1C41.38 124.7 58.76 135.1 63.05 152.2L66.93 167.8C70.49 182 83.29 191.1 97.97 191.1H303.8L416 256.1z"})})},objects:{outline:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[z("path",{d:"M12 0a9 9 0 0 0-5 16.482V21s2.035 3 5 3 5-3 5-3v-4.518A9 9 0 0 0 12 0zm0 2c3.86 0 7 3.141 7 7s-3.14 7-7 7-7-3.141-7-7 3.14-7 7-7zM9 17.477c.94.332 1.946.523 3 .523s2.06-.19 3-.523v.834c-.91.436-1.925.689-3 .689a6.924 6.924 0 0 1-3-.69v-.833zm.236 3.07A8.854 8.854 0 0 0 12 21c.965 0 1.888-.167 2.758-.451C14.155 21.173 13.153 22 12 22c-1.102 0-2.117-.789-2.764-1.453z"}),z("path",{d:"M14.745 12.449h-.004c-.852-.024-1.188-.858-1.577-1.824-.421-1.061-.703-1.561-1.182-1.566h-.009c-.481 0-.783.497-1.235 1.537-.436.982-.801 1.811-1.636 1.791l-.276-.043c-.565-.171-.853-.691-1.284-1.794-.125-.313-.202-.632-.27-.913-.051-.213-.127-.53-.195-.634C7.067 9.004 7.039 9 6.99 9A1 1 0 0 1 7 7h.01c1.662.017 2.015 1.373 2.198 2.134.486-.981 1.304-2.058 2.797-2.075 1.531.018 2.28 1.153 2.731 2.141l.002-.008C14.944 8.424 15.327 7 16.979 7h.032A1 1 0 1 1 17 9h-.011c-.149.076-.256.474-.319.709a6.484 6.484 0 0 1-.311.951c-.429.973-.79 1.789-1.614 1.789"})]}),solid:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 384 512",children:z("path",{d:"M112.1 454.3c0 6.297 1.816 12.44 5.284 17.69l17.14 25.69c5.25 7.875 17.17 14.28 26.64 14.28h61.67c9.438 0 21.36-6.401 26.61-14.28l17.08-25.68c2.938-4.438 5.348-12.37 5.348-17.7L272 415.1h-160L112.1 454.3zM191.4 .0132C89.44 .3257 16 82.97 16 175.1c0 44.38 16.44 84.84 43.56 115.8c16.53 18.84 42.34 58.23 52.22 91.45c.0313 .25 .0938 .5166 .125 .7823h160.2c.0313-.2656 .0938-.5166 .125-.7823c9.875-33.22 35.69-72.61 52.22-91.45C351.6 260.8 368 220.4 368 175.1C368 78.61 288.9-.2837 191.4 .0132zM192 96.01c-44.13 0-80 35.89-80 79.1C112 184.8 104.8 192 96 192S80 184.8 80 176c0-61.76 50.25-111.1 112-111.1c8.844 0 16 7.159 16 16S200.8 96.01 192 96.01z"})})},people:{outline:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[z("path",{d:"M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0m0 22C6.486 22 2 17.514 2 12S6.486 2 12 2s10 4.486 10 10-4.486 10-10 10"}),z("path",{d:"M8 7a2 2 0 1 0-.001 3.999A2 2 0 0 0 8 7M16 7a2 2 0 1 0-.001 3.999A2 2 0 0 0 16 7M15.232 15c-.693 1.195-1.87 2-3.349 2-1.477 0-2.655-.805-3.347-2H15m3-2H6a6 6 0 1 0 12 0"})]}),solid:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:z("path",{d:"M0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256zM256 432C332.1 432 396.2 382 415.2 314.1C419.1 300.4 407.8 288 393.6 288H118.4C104.2 288 92.92 300.4 96.76 314.1C115.8 382 179.9 432 256 432V432zM176.4 160C158.7 160 144.4 174.3 144.4 192C144.4 209.7 158.7 224 176.4 224C194 224 208.4 209.7 208.4 192C208.4 174.3 194 160 176.4 160zM336.4 224C354 224 368.4 209.7 368.4 192C368.4 174.3 354 160 336.4 160C318.7 160 304.4 174.3 304.4 192C304.4 209.7 318.7 224 336.4 224z"})})},places:{outline:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:[z("path",{d:"M6.5 12C5.122 12 4 13.121 4 14.5S5.122 17 6.5 17 9 15.879 9 14.5 7.878 12 6.5 12m0 3c-.275 0-.5-.225-.5-.5s.225-.5.5-.5.5.225.5.5-.225.5-.5.5M17.5 12c-1.378 0-2.5 1.121-2.5 2.5s1.122 2.5 2.5 2.5 2.5-1.121 2.5-2.5-1.122-2.5-2.5-2.5m0 3c-.275 0-.5-.225-.5-.5s.225-.5.5-.5.5.225.5.5-.225.5-.5.5"}),z("path",{d:"M22.482 9.494l-1.039-.346L21.4 9h.6c.552 0 1-.439 1-.992 0-.006-.003-.008-.003-.008H23c0-1-.889-2-1.984-2h-.642l-.731-1.717C19.262 3.012 18.091 2 16.764 2H7.236C5.909 2 4.738 3.012 4.357 4.283L3.626 6h-.642C1.889 6 1 7 1 8h.003S1 8.002 1 8.008C1 8.561 1.448 9 2 9h.6l-.043.148-1.039.346a2.001 2.001 0 0 0-1.359 2.097l.751 7.508a1 1 0 0 0 .994.901H3v1c0 1.103.896 2 2 2h2c1.104 0 2-.897 2-2v-1h6v1c0 1.103.896 2 2 2h2c1.104 0 2-.897 2-2v-1h1.096a.999.999 0 0 0 .994-.901l.751-7.508a2.001 2.001 0 0 0-1.359-2.097M6.273 4.857C6.402 4.43 6.788 4 7.236 4h9.527c.448 0 .834.43.963.857L19.313 9H4.688l1.585-4.143zM7 21H5v-1h2v1zm12 0h-2v-1h2v1zm2.189-3H2.811l-.662-6.607L3 11h18l.852.393L21.189 18z"})]}),solid:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:z("path",{d:"M39.61 196.8L74.8 96.29C88.27 57.78 124.6 32 165.4 32H346.6C387.4 32 423.7 57.78 437.2 96.29L472.4 196.8C495.6 206.4 512 229.3 512 256V448C512 465.7 497.7 480 480 480H448C430.3 480 416 465.7 416 448V400H96V448C96 465.7 81.67 480 64 480H32C14.33 480 0 465.7 0 448V256C0 229.3 16.36 206.4 39.61 196.8V196.8zM109.1 192H402.9L376.8 117.4C372.3 104.6 360.2 96 346.6 96H165.4C151.8 96 139.7 104.6 135.2 117.4L109.1 192zM96 256C78.33 256 64 270.3 64 288C64 305.7 78.33 320 96 320C113.7 320 128 305.7 128 288C128 270.3 113.7 256 96 256zM416 320C433.7 320 448 305.7 448 288C448 270.3 433.7 256 416 256C398.3 256 384 270.3 384 288C384 305.7 398.3 320 416 320z"})})},symbols:{outline:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:z("path",{d:"M0 0h11v2H0zM4 11h3V6h4V4H0v2h4zM15.5 17c1.381 0 2.5-1.116 2.5-2.493s-1.119-2.493-2.5-2.493S13 13.13 13 14.507 14.119 17 15.5 17m0-2.986c.276 0 .5.222.5.493 0 .272-.224.493-.5.493s-.5-.221-.5-.493.224-.493.5-.493M21.5 19.014c-1.381 0-2.5 1.116-2.5 2.493S20.119 24 21.5 24s2.5-1.116 2.5-2.493-1.119-2.493-2.5-2.493m0 2.986a.497.497 0 0 1-.5-.493c0-.271.224-.493.5-.493s.5.222.5.493a.497.497 0 0 1-.5.493M22 13l-9 9 1.513 1.5 8.99-9.009zM17 11c2.209 0 4-1.119 4-2.5V2s.985-.161 1.498.949C23.01 4.055 23 6 23 6s1-1.119 1-3.135C24-.02 21 0 21 0h-2v6.347A5.853 5.853 0 0 0 17 6c-2.209 0-4 1.119-4 2.5s1.791 2.5 4 2.5M10.297 20.482l-1.475-1.585a47.54 47.54 0 0 1-1.442 1.129c-.307-.288-.989-1.016-2.045-2.183.902-.836 1.479-1.466 1.729-1.892s.376-.871.376-1.336c0-.592-.273-1.178-.818-1.759-.546-.581-1.329-.871-2.349-.871-1.008 0-1.79.293-2.344.879-.556.587-.832 1.181-.832 1.784 0 .813.419 1.748 1.256 2.805-.847.614-1.444 1.208-1.794 1.784a3.465 3.465 0 0 0-.523 1.833c0 .857.308 1.56.924 2.107.616.549 1.423.823 2.42.823 1.173 0 2.444-.379 3.813-1.137L8.235 24h2.819l-2.09-2.383 1.333-1.135zm-6.736-6.389a1.02 1.02 0 0 1 .73-.286c.31 0 .559.085.747.254a.849.849 0 0 1 .283.659c0 .518-.419 1.112-1.257 1.784-.536-.651-.805-1.231-.805-1.742a.901.901 0 0 1 .302-.669M3.74 22c-.427 0-.778-.116-1.057-.349-.279-.232-.418-.487-.418-.766 0-.594.509-1.288 1.527-2.083.968 1.134 1.717 1.946 2.248 2.438-.921.507-1.686.76-2.3.76"})}),solid:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:z("path",{d:"M500.3 7.251C507.7 13.33 512 22.41 512 31.1V175.1C512 202.5 483.3 223.1 447.1 223.1C412.7 223.1 383.1 202.5 383.1 175.1C383.1 149.5 412.7 127.1 447.1 127.1V71.03L351.1 90.23V207.1C351.1 234.5 323.3 255.1 287.1 255.1C252.7 255.1 223.1 234.5 223.1 207.1C223.1 181.5 252.7 159.1 287.1 159.1V63.1C287.1 48.74 298.8 35.61 313.7 32.62L473.7 .6198C483.1-1.261 492.9 1.173 500.3 7.251H500.3zM74.66 303.1L86.5 286.2C92.43 277.3 102.4 271.1 113.1 271.1H174.9C185.6 271.1 195.6 277.3 201.5 286.2L213.3 303.1H239.1C266.5 303.1 287.1 325.5 287.1 351.1V463.1C287.1 490.5 266.5 511.1 239.1 511.1H47.1C21.49 511.1-.0019 490.5-.0019 463.1V351.1C-.0019 325.5 21.49 303.1 47.1 303.1H74.66zM143.1 359.1C117.5 359.1 95.1 381.5 95.1 407.1C95.1 434.5 117.5 455.1 143.1 455.1C170.5 455.1 191.1 434.5 191.1 407.1C191.1 381.5 170.5 359.1 143.1 359.1zM440.3 367.1H496C502.7 367.1 508.6 372.1 510.1 378.4C513.3 384.6 511.6 391.7 506.5 396L378.5 508C372.9 512.1 364.6 513.3 358.6 508.9C352.6 504.6 350.3 496.6 353.3 489.7L391.7 399.1H336C329.3 399.1 323.4 395.9 321 389.6C318.7 383.4 320.4 376.3 325.5 371.1L453.5 259.1C459.1 255 467.4 254.7 473.4 259.1C479.4 263.4 481.6 271.4 478.7 278.3L440.3 367.1zM116.7 219.1L19.85 119.2C-8.112 90.26-6.614 42.31 24.85 15.34C51.82-8.137 93.26-3.642 118.2 21.83L128.2 32.32L137.7 21.83C162.7-3.642 203.6-8.137 231.6 15.34C262.6 42.31 264.1 90.26 236.1 119.2L139.7 219.1C133.2 225.6 122.7 225.6 116.7 219.1H116.7z"})})}},search:{loupe:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",children:z("path",{d:"M12.9 14.32a8 8 0 1 1 1.41-1.41l5.35 5.33-1.42 1.42-5.33-5.34zM8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12z"})}),delete:z("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",children:z("path",{d:"M10 8.586L2.929 1.515 1.515 2.929 8.586 10l-7.071 7.071 1.414 1.414L10 11.414l7.071 7.071 1.414-1.414L11.414 10l7.071-7.071-1.414-1.414L10 8.586z"})})}};function fe(e){let{id:t,skin:n,emoji:r}=e;if(e.shortcodes){const r=e.shortcodes.match(le.SHORTCODES_REGEX);r&&(t=r[1],r[2]&&(n=r[2]))}if(r||(r=le.get(t||e.native)),!r)return e.fallback;const i=r.skins[n-1]||r.skins[0],o=i.src||("native"==e.set||e.spritesheet?void 0:"function"==typeof e.getImageURL?e.getImageURL(e.set,i.unified):`https://cdn.jsdelivr.net/npm/emoji-datasource-${e.set}@15.0.1/img/${e.set}/64/${i.unified}.png`),s="function"==typeof e.getSpritesheetURL?e.getSpritesheetURL(e.set):`https://cdn.jsdelivr.net/npm/emoji-datasource-${e.set}@15.0.1/img/${e.set}/sheets-256/64.png`;return z("span",{class:"emoji-mart-emoji","data-emoji-set":e.set,children:o?z("img",{style:{maxWidth:e.size||"1em",maxHeight:e.size||"1em",display:"inline-block"},alt:i.native||i.shortcodes,src:o}):"native"==e.set?z("span",{style:{fontSize:e.size,fontFamily:'"EmojiMart", "Segoe UI Emoji", "Segoe UI Symbol", "Segoe UI", "Apple Color Emoji", "Twemoji Mozilla", "Noto Color Emoji", "Android Emoji"'},children:i.native}):z("span",{style:{display:"block",width:e.size,height:e.size,backgroundImage:`url(${s})`,backgroundSize:`${100*X.sheet.cols}% ${100*X.sheet.rows}%`,backgroundPosition:`${100/(X.sheet.cols-1)*i.x}% ${100/(X.sheet.rows-1)*i.y}%`}})})}const pe="undefined"!=typeof window&&window.HTMLElement?window.HTMLElement:Object;class me extends pe{static get observedAttributes(){return Object.keys(this.Props)}update(e={}){for(let t in e)this.attributeChangedCallback(t,null,e[t])}attributeChangedCallback(e,t,n){if(!this.component)return;const r=se(e,{[e]:n},this.constructor.Props,this);this.component.componentWillReceiveProps?this.component.componentWillReceiveProps({[e]:r}):(this.component.props[e]=r,this.component.forceUpdate())}disconnectedCallback(){this.disconnected=!0,this.component&&this.component.unregister&&this.component.unregister()}constructor(e={}){if(super(),this.props=e,e.parent||e.ref){let t=null;const n=e.parent||(t=e.ref&&e.ref.current);t&&(t.innerHTML=""),n&&n.appendChild(this)}}}class ve extends me{setShadow(){this.attachShadow({mode:"open"})}injectStyles(e){if(!e)return;const t=document.createElement("style");t.textContent=e,this.shadowRoot.insertBefore(t,this.shadowRoot.firstChild)}constructor(e,{styles:t}={}){super(e),this.setShadow(),this.injectStyles(t)}}var ge={fallback:"",id:"",native:"",shortcodes:"",size:{value:"",transform:e=>/\D/.test(e)?e:`${e}px`},set:G.set,skin:G.skin};class ye extends me{async connectedCallback(){const e=oe(this.props,ge,this);e.element=this,e.ref=e=>{this.component=e},await ie(),this.disconnected||N(z(fe,{...e}),this)}constructor(e){super(e)}}i(ye,"Props",ge),"undefined"==typeof customElements||customElements.get("em-emoji")||customElements.define("em-emoji",ye);var be,we,_e=[],ke=s.__b,Ce=s.__r,Oe=s.diffed,xe=s.__c,je=s.unmount;function Se(){var e;for(_e.sort((function(e,t){return e.__v.__b-t.__v.__b}));e=_e.pop();)if(e.__P)try{e.__H.__h.forEach(Pe),e.__H.__h.forEach(Me),e.__H.__h=[]}catch(t){e.__H.__h=[],s.__e(t,e.__v)}}s.__b=function(e){be=null,ke&&ke(e)},s.__r=function(e){Ce&&Ce(e);var t=(be=e.__c).__H;t&&(t.__h.forEach(Pe),t.__h.forEach(Me),t.__h=[])},s.diffed=function(e){Oe&&Oe(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==_e.push(t)&&we===s.requestAnimationFrame||((we=s.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),Ee&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);Ee&&(t=requestAnimationFrame(n))})(Se)),be=null},s.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Pe),e.__h=e.__h.filter((function(e){return!e.__||Me(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],s.__e(n,e.__v)}})),xe&&xe(e,t)},s.unmount=function(e){je&&je(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{Pe(e)}catch(e){t=e}})),t&&s.__e(t,n.__v))};var Ee="function"==typeof requestAnimationFrame;function Pe(e){var t=be,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),be=t}function Me(e){var t=be;e.__c=e.__(),be=t}function Te(e,t){for(var n in e)if("__source"!==n&&!(n in t))return!0;for(var r in t)if("__source"!==r&&e[r]!==t[r])return!0;return!1}function Ae(e){this.props=e}(Ae.prototype=new b).isPureReactComponent=!0,Ae.prototype.shouldComponentUpdate=function(e,t){return Te(this.props,e)||Te(this.state,t)};var Le=s.__b;s.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Le&&Le(e)},"undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.forward_ref");var Be=s.__e;s.__e=function(e,t,n){if(e.then)for(var r,i=t;i=i.__;)if((r=i.__c)&&r.__c)return null==t.__e&&(t.__e=n.__e,t.__k=n.__k),r.__c(e,t);Be(e,t,n)};var Re=s.unmount;function Fe(){this.__u=0,this.t=null,this.__b=null}function Ne(e){var t=e.__.__c;return t&&t.__e&&t.__e(e)}function Ie(){this.u=null,this.o=null}s.unmount=function(e){var t=e.__c;t&&t.__R&&t.__R(),t&&!0===e.__h&&(e.type=null),Re&&Re(e)},(Fe.prototype=new b).__c=function(e,t){var n=t.__c,r=this;null==r.t&&(r.t=[]),r.t.push(n);var i=Ne(r.__v),o=!1,s=function(){o||(o=!0,n.__R=null,i?i(a):a())};n.__R=s;var a=function(){if(!--r.__u){if(r.state.__e){var e=r.state.__e;r.__v.__k[0]=function e(t,n,r){return t&&(t.__v=null,t.__k=t.__k&&t.__k.map((function(t){return e(t,n,r)})),t.__c&&t.__c.__P===n&&(t.__e&&r.insertBefore(t.__e,t.__d),t.__c.__e=!0,t.__c.__P=r)),t}(e,e.__c.__P,e.__c.__O)}var t;for(r.setState({__e:r.__b=null});t=r.t.pop();)t.forceUpdate()}},l=!0===t.__h;r.__u++||l||r.setState({__e:r.__b=r.__v.__k[0]}),e.then(s,s)},Fe.prototype.componentWillUnmount=function(){this.t=[]},Fe.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=function e(t,n,r){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach((function(e){"function"==typeof e.__c&&e.__c()})),t.__c.__H=null),null!=(t=function(e,t){for(var n in t)e[n]=t[n];return e}({},t)).__c&&(t.__c.__P===r&&(t.__c.__P=n),t.__c=null),t.__k=t.__k&&t.__k.map((function(t){return e(t,n,r)}))),t}(this.__b,n,r.__O=r.__P)}this.__b=null}var i=t.__e&&v(y,null,e.fallback);return i&&(i.__h=null),[v(y,null,t.__e?null:e.children),i]};var ze=function(e,t,n){if(++n[1]===n[0]&&e.o.delete(t),e.props.revealOrder&&("t"!==e.props.revealOrder[0]||!e.o.size))for(n=e.u;n;){for(;n.length>3;)n.pop()();if(n[1]{const r=t.name||Q.categories[t.id],i=!this.props.unfocused&&t.id==this.state.categoryId;return i&&(e=n),z("button",{"aria-label":r,"aria-selected":i||void 0,title:r,type:"button",class:"flex flex-grow flex-center",onMouseDown:e=>e.preventDefault(),onClick:()=>{this.props.onClick({category:t,i:n})},children:this.renderIcon(t)})})),z("div",{class:"bar",style:{width:100/this.categories.length+"%",opacity:null==e?0:1,transform:"rtl"===this.props.dir?`scaleX(-1) translateX(${100*e}%)`:`translateX(${100*e}%)`}})]})})}constructor(){super(),this.categories=X.categories.filter((e=>!e.target)),this.state={categoryId:this.categories[0].id}}}class Xe extends Ae{shouldComponentUpdate(e){for(let t in e)if("children"!=t&&e[t]!=this.props[t])return!0;return!1}render(){return this.props.children}}class Ye extends b{getInitialState(e=this.props){return{skin:D.get("skin")||e.skin,theme:this.initTheme(e.theme)}}componentWillMount(){this.dir=Q.rtl?"rtl":"ltr",this.refs={menu:{current:null},navigation:{current:null},scroll:{current:null},search:{current:null},searchInput:{current:null},skinToneButton:{current:null},skinToneRadio:{current:null}},this.initGrid(),0==this.props.stickySearch&&"sticky"==this.props.searchPosition&&(console.warn("[EmojiMart] Deprecation warning: `stickySearch` has been renamed `searchPosition`."),this.props.searchPosition="static")}componentDidMount(){if(this.register(),this.shadowRoot=this.base.parentNode,this.props.autoFocus){const{searchInput:e}=this.refs;e.current&&e.current.focus()}}componentWillReceiveProps(e){this.nextState||(this.nextState={});for(const t in e)this.nextState[t]=e[t];clearTimeout(this.nextStateTimer),this.nextStateTimer=setTimeout((()=>{let e=!1;for(const t in this.nextState)this.props[t]=this.nextState[t],"custom"!==t&&"categories"!==t||(e=!0);delete this.nextState;const t=this.getInitialState();if(e)return this.reset(t);this.setState(t)}))}componentWillUnmount(){this.unregister()}async reset(e={}){await ie(this.props),this.initGrid(),this.unobserve(),this.setState(e,(()=>{this.observeCategories(),this.observeRows()}))}register(){document.addEventListener("click",this.handleClickOutside),this.observe()}unregister(){document.removeEventListener("click",this.handleClickOutside),this.darkMedia?.removeEventListener("change",this.darkMediaCallback),this.unobserve()}observe(){this.observeCategories(),this.observeRows()}unobserve({except:e=[]}={}){Array.isArray(e)||(e=[e]);for(const t of this.observers)e.includes(t)||t.disconnect();this.observers=[].concat(e)}initGrid(){const{categories:e}=X;this.refs.categories=new Map;const t=X.categories.map((e=>e.id)).join(",");this.navKey&&this.navKey!=t&&this.refs.scroll.current&&(this.refs.scroll.current.scrollTop=0),this.navKey=t,this.grid=[],this.grid.setsize=0;const n=(e,t)=>{const n=[];n.__categoryId=t.id,n.__index=e.length,this.grid.push(n);const r=this.grid.length-1,i=r%10?{}:{current:null};return i.index=r,i.posinset=this.grid.setsize+1,e.push(i),n};for(let t of e){const e=[];let r=n(e,t);for(let i of t.emojis)r.length==this.getPerLine()&&(r=n(e,t)),this.grid.setsize+=1,r.push(i);this.refs.categories.set(t.id,{root:{current:null},rows:e})}}initTheme(e){if("auto"!=e)return e;if(!this.darkMedia){if(this.darkMedia=matchMedia("(prefers-color-scheme: dark)"),this.darkMedia.media.match(/^not/))return"light";this.darkMedia.addEventListener("change",this.darkMediaCallback)}return this.darkMedia.matches?"dark":"light"}initDynamicPerLine(e=this.props){if(!e.dynamicWidth)return;const{element:t,emojiButtonSize:n}=e,r=()=>{const{width:e}=t.getBoundingClientRect();return Math.floor(e/n)},i=new ResizeObserver((()=>{this.unobserve({except:i}),this.setState({perLine:r()},(()=>{this.initGrid(),this.forceUpdate((()=>{this.observeCategories(),this.observeRows()}))}))}));return i.observe(t),this.observers.push(i),r()}getPerLine(){return this.state.perLine||this.props.perLine}getEmojiByPos([e,t]){const n=this.state.searchResults||this.grid,r=n[e]&&n[e][t];if(r)return le.get(r)}observeCategories(){const e=this.refs.navigation.current;if(!e)return;const t=new Map,n={root:this.refs.scroll.current,threshold:[0,1]},r=new IntersectionObserver((n=>{for(const e of n){const n=e.target.dataset.id;t.set(n,e.intersectionRatio)}const r=[...t];for(const[t,n]of r)if(n){(i=t)!=e.state.categoryId&&e.setState({categoryId:i});break}var i}),n);for(const{root:e}of this.refs.categories.values())r.observe(e.current);this.observers.push(r)}observeRows(){const e={...this.state.visibleRows},t=new IntersectionObserver((t=>{for(const n of t){const t=parseInt(n.target.dataset.index);n.isIntersecting?e[t]=!0:delete e[t]}this.setState({visibleRows:e})}),{root:this.refs.scroll.current,rootMargin:`${15*this.props.emojiButtonSize}px 0px ${10*this.props.emojiButtonSize}px`});for(const{rows:e}of this.refs.categories.values())for(const n of e)n.current&&t.observe(n.current);this.observers.push(t)}preventDefault(e){e.preventDefault()}unfocusSearch(){const e=this.refs.searchInput.current;e&&e.blur()}navigate({e,input:t,left:n,right:r,up:i,down:o}){const s=this.state.searchResults||this.grid;if(!s.length)return;let[a,l]=this.state.pos;const c=(()=>{if(0==a&&0==l&&!e.repeat&&(n||i))return null;if(-1==a)return e.repeat||!r&&!o||t.selectionStart!=t.value.length?null:[0,0];if(n||r){let e=s[a];const t=n?-1:1;if(l+=t,!e[l]){if(a+=t,e=s[a],!e)return a=n?0:s.length-1,l=n?0:s[a].length-1,[a,l];l=n?e.length-1:0}return[a,l]}if(i||o){a+=i?-1:1;const e=s[a];return e?(e[l]||(l=e.length-1),[a,l]):(a=i?0:s.length-1,l=i?0:s[a].length-1,[a,l])}})();c?(e.preventDefault(),this.setState({pos:c,keyboard:!0},(()=>{this.scrollTo({row:c[0]})}))):this.state.pos[0]>-1&&this.setState({pos:[-1,-1]})}scrollTo({categoryId:e,row:t}){const n=this.state.searchResults||this.grid;if(!n.length)return;const r=this.refs.scroll.current,i=r.getBoundingClientRect();let o=0;if(t>=0&&(e=n[t].__categoryId),e&&(o=(this.refs[e]||this.refs.categories.get(e).root).current.getBoundingClientRect().top-(i.top-r.scrollTop)+1),t>=0)if(t){const e=o+n[t].__index*this.props.emojiButtonSize,s=e+this.props.emojiButtonSize+.88*this.props.emojiButtonSize;if(er.scrollTop+i.height))return;o=s-i.height}}else o=0;this.ignoreMouse(),r.scrollTop=o}ignoreMouse(){this.mouseIsIgnored=!0,clearTimeout(this.ignoreMouseTimer),this.ignoreMouseTimer=setTimeout((()=>{delete this.mouseIsIgnored}),100)}handleEmojiOver(e){this.mouseIsIgnored||this.state.showSkins||this.setState({pos:e||[-1,-1],keyboard:!1})}handleEmojiClick({e,emoji:t,pos:n}){if(this.props.onEmojiSelect&&(!t&&n&&(t=this.getEmojiByPos(n)),t)){const n=ue(t,{skinIndex:this.state.skin-1});this.props.maxFrequentRows&&Z.add(n,this.props),this.props.onEmojiSelect(n,e)}}closeSkins(){this.state.showSkins&&(this.setState({showSkins:null,tempSkin:null}),this.base.removeEventListener("click",this.handleBaseClick),this.base.removeEventListener("keydown",this.handleBaseKeydown))}handleSkinMouseOver(e){this.setState({tempSkin:e})}handleSkinClick(e){this.ignoreMouse(),this.closeSkins(),this.setState({skin:e,tempSkin:null}),D.set("skin",e)}renderNav(){return z(Qe,{ref:this.refs.navigation,icons:this.props.icons,theme:this.state.theme,dir:this.dir,unfocused:!!this.state.searchResults,position:this.props.navPosition,onClick:this.handleCategoryClick},this.navKey)}renderPreview(){const e=this.getEmojiByPos(this.state.pos),t=this.state.searchResults&&!this.state.searchResults.length;return z("div",{id:"preview",class:"flex flex-middle",dir:this.dir,"data-position":this.props.previewPosition,children:[z("div",{class:"flex flex-middle flex-grow",children:[z("div",{class:"flex flex-auto flex-middle flex-center",style:{height:this.props.emojiButtonSize,fontSize:this.props.emojiButtonSize},children:z(fe,{emoji:e,id:t?this.props.noResultsEmoji||"cry":this.props.previewEmoji||("top"==this.props.previewPosition?"point_down":"point_up"),set:this.props.set,size:this.props.emojiButtonSize,skin:this.state.tempSkin||this.state.skin,spritesheet:!0,getSpritesheetURL:this.props.getSpritesheetURL})}),z("div",{class:`margin-${this.dir[0]}`,children:z("div",e||t?{class:`padding-${this.dir[2]} align-${this.dir[0]}`,children:[z("div",{class:"preview-title ellipsis",children:e?e.name:Q.search_no_results_1}),z("div",{class:"preview-subtitle ellipsis color-c",children:e?e.skins[0].shortcodes:Q.search_no_results_2})]}:{class:"preview-placeholder color-c",children:Q.pick})})]}),!e&&"preview"==this.props.skinTonePosition&&this.renderSkinToneButton()]})}renderEmojiButton(e,{pos:t,posinset:n,grid:r}){const i=this.props.emojiButtonSize,o=this.state.tempSkin||this.state.skin,s=(e.skins[o-1]||e.skins[0]).native,a=(l=this.state.pos,c=t,Array.isArray(l)&&Array.isArray(c)&&l.length===c.length&&l.every(((e,t)=>e==c[t])));var l,c;const u=t.concat(e.id).join("");return z(Xe,{selected:a,skin:o,size:i,children:z("button",{"aria-label":s,"aria-selected":a||void 0,"aria-posinset":n,"aria-setsize":r.setsize,"data-keyboard":this.state.keyboard,title:"none"==this.props.previewPosition?e.name:void 0,type:"button",class:"flex flex-center flex-middle",tabindex:"-1",onClick:t=>this.handleEmojiClick({e:t,emoji:e}),onMouseEnter:()=>this.handleEmojiOver(t),onMouseLeave:()=>this.handleEmojiOver(),style:{width:this.props.emojiButtonSize,height:this.props.emojiButtonSize,fontSize:this.props.emojiSize,lineHeight:0},children:[z("div",{"aria-hidden":"true",class:"background",style:{borderRadius:this.props.emojiButtonRadius,backgroundColor:this.props.emojiButtonColors?this.props.emojiButtonColors[(n-1)%this.props.emojiButtonColors.length]:void 0}}),z(fe,{emoji:e,set:this.props.set,size:this.props.emojiSize,skin:o,spritesheet:!0,getSpritesheetURL:this.props.getSpritesheetURL})]})},u)}renderSearch(){const e="none"==this.props.previewPosition||"search"==this.props.skinTonePosition;return z("div",{children:[z("div",{class:"spacer"}),z("div",{class:"flex flex-middle",children:[z("div",{class:"search relative flex-grow",children:[z("input",{type:"search",ref:this.refs.searchInput,placeholder:Q.search,onClick:this.handleSearchClick,onInput:this.handleSearchInput,onKeyDown:this.handleSearchKeyDown,autoComplete:"off"}),z("span",{class:"icon loupe flex",children:de.search.loupe}),this.state.searchResults&&z("button",{title:"Clear","aria-label":"Clear",type:"button",class:"icon delete flex",onClick:this.clearSearch,onMouseDown:this.preventDefault,children:de.search.delete})]}),e&&this.renderSkinToneButton()]})]})}renderSearchResults(){const{searchResults:e}=this.state;return e?z("div",{class:"category",ref:this.refs.search,children:[z("div",{class:`sticky padding-small align-${this.dir[0]}`,children:Q.categories.search}),z("div",{children:e.length?e.map(((t,n)=>z("div",{class:"flex",children:t.map(((t,r)=>this.renderEmojiButton(t,{pos:[n,r],posinset:n*this.props.perLine+r+1,grid:e})))}))):z("div",{class:`padding-small align-${this.dir[0]}`,children:this.props.onAddCustomEmoji&&z("a",{onClick:this.props.onAddCustomEmoji,children:Q.add_custom})})})]}):null}renderCategories(){const{categories:e}=X,t=!!this.state.searchResults,n=this.getPerLine();return z("div",{style:{visibility:t?"hidden":void 0,display:t?"none":void 0,height:"100%"},children:e.map((e=>{const{root:t,rows:r}=this.refs.categories.get(e.id);return z("div",{"data-id":e.target?e.target.id:e.id,class:"category",ref:t,children:[z("div",{class:`sticky padding-small align-${this.dir[0]}`,children:e.name||Q.categories[e.id]}),z("div",{class:"relative",style:{height:r.length*this.props.emojiButtonSize},children:r.map(((t,r)=>{const i=t.index-t.index%10,o=this.state.visibleRows[i],s="current"in t?t:void 0;if(!o&&!s)return null;const a=r*n,l=a+n,c=e.emojis.slice(a,l);return c.length{if(!e)return z("div",{style:{width:this.props.emojiButtonSize,height:this.props.emojiButtonSize}});const r=le.get(e);return this.renderEmojiButton(r,{pos:[t.index,n],posinset:t.posinset+n,grid:this.grid})}))},t.index)}))})]})}))})}renderSkinToneButton(){return"none"==this.props.skinTonePosition?null:z("div",{class:"flex flex-auto flex-center flex-middle",style:{position:"relative",width:this.props.emojiButtonSize,height:this.props.emojiButtonSize},children:z("button",{type:"button",ref:this.refs.skinToneButton,class:"skin-tone-button flex flex-auto flex-center flex-middle","aria-selected":this.state.showSkins?"":void 0,"aria-label":Q.skins.choose,title:Q.skins.choose,onClick:this.openSkins,style:{width:this.props.emojiSize,height:this.props.emojiSize},children:z("span",{class:`skin-tone skin-tone-${this.state.skin}`})})})}renderLiveRegion(){const e=this.getEmojiByPos(this.state.pos);return z("div",{"aria-live":"polite",class:"sr-only",children:e?e.name:""})}renderSkins(){const e=this.refs.skinToneButton.current.getBoundingClientRect(),t=this.base.getBoundingClientRect(),n={};return"ltr"==this.dir?n.right=t.right-e.right-3:n.left=e.left-t.left-3,"bottom"==this.props.previewPosition&&"preview"==this.props.skinTonePosition?n.bottom=t.bottom-e.top+6:(n.top=e.bottom-t.top+3,n.bottom="auto"),z("div",{ref:this.refs.menu,role:"radiogroup",dir:this.dir,"aria-label":Q.skins.choose,class:"menu hidden","data-position":n.top?"top":"bottom",style:n,children:[...Array(6).keys()].map((e=>{const t=e+1,n=this.state.skin==t;return z("div",{children:[z("input",{type:"radio",name:"skin-tone",value:t,"aria-label":Q.skins[t],ref:n?this.refs.skinToneRadio:null,defaultChecked:n,onChange:()=>this.handleSkinMouseOver(t),onKeyDown:e=>{"Enter"!=e.code&&"Space"!=e.code&&"Tab"!=e.code||(e.preventDefault(),this.handleSkinClick(t))}}),z("button",{"aria-hidden":"true",tabindex:"-1",onClick:()=>this.handleSkinClick(t),onMouseEnter:()=>this.handleSkinMouseOver(t),onMouseLeave:()=>this.handleSkinMouseOver(),class:"option flex flex-grow flex-middle",children:[z("span",{class:`skin-tone skin-tone-${t}`}),z("span",{class:"margin-small-lr",children:Q.skins[t]})]})]})}))})}render(){const e=this.props.perLine*this.props.emojiButtonSize;return z("section",{id:"root",class:"flex flex-column",dir:this.dir,style:{width:this.props.dynamicWidth?"100%":`calc(${e}px + (var(--padding) + var(--sidebar-width)))`},"data-emoji-set":this.props.set,"data-theme":this.state.theme,"data-menu":this.state.showSkins?"":void 0,children:["top"==this.props.previewPosition&&this.renderPreview(),"top"==this.props.navPosition&&this.renderNav(),"sticky"==this.props.searchPosition&&z("div",{class:"padding-lr",children:this.renderSearch()}),z("div",{ref:this.refs.scroll,class:"scroll flex-grow padding-lr",children:z("div",{style:{width:this.props.dynamicWidth?"100%":e,height:"100%"},children:["static"==this.props.searchPosition&&this.renderSearch(),this.renderSearchResults(),this.renderCategories()]})}),"bottom"==this.props.navPosition&&this.renderNav(),"bottom"==this.props.previewPosition&&this.renderPreview(),this.state.showSkins&&this.renderSkins(),this.renderLiveRegion()]})}constructor(e){super(),i(this,"darkMediaCallback",(()=>{"auto"==this.props.theme&&this.setState({theme:this.darkMedia.matches?"dark":"light"})})),i(this,"handleClickOutside",(e=>{const{element:t}=this.props;e.target!=t&&(this.state.showSkins&&this.closeSkins(),this.props.onClickOutside&&this.props.onClickOutside(e))})),i(this,"handleBaseClick",(e=>{this.state.showSkins&&(e.target.closest(".menu")||(e.preventDefault(),e.stopImmediatePropagation(),this.closeSkins()))})),i(this,"handleBaseKeydown",(e=>{this.state.showSkins&&"Escape"==e.key&&(e.preventDefault(),e.stopImmediatePropagation(),this.closeSkins())})),i(this,"handleSearchClick",(()=>{this.getEmojiByPos(this.state.pos)&&this.setState({pos:[-1,-1]})})),i(this,"handleSearchInput",(async()=>{const e=this.refs.searchInput.current;if(!e)return;const{value:t}=e,n=await le.search(t),r=()=>{this.refs.scroll.current&&(this.refs.scroll.current.scrollTop=0)};if(!n)return this.setState({searchResults:n,pos:[-1,-1]},r);const i=e.selectionStart==e.value.length?[0,0]:[-1,-1],o=[];o.setsize=n.length;let s=null;for(let e of n)o.length&&s.length!=this.getPerLine()||(s=[],s.__categoryId="search",s.__index=o.length,o.push(s)),s.push(e);this.ignoreMouse(),this.setState({searchResults:o,pos:i},r)})),i(this,"handleSearchKeyDown",(e=>{const t=e.currentTarget;switch(e.stopImmediatePropagation(),e.key){case"ArrowLeft":this.navigate({e,input:t,left:!0});break;case"ArrowRight":this.navigate({e,input:t,right:!0});break;case"ArrowUp":this.navigate({e,input:t,up:!0});break;case"ArrowDown":this.navigate({e,input:t,down:!0});break;case"Enter":e.preventDefault(),this.handleEmojiClick({e,pos:this.state.pos});break;case"Escape":e.preventDefault(),this.state.searchResults?this.clearSearch():this.unfocusSearch()}})),i(this,"clearSearch",(()=>{const e=this.refs.searchInput.current;e&&(e.value="",e.focus(),this.handleSearchInput())})),i(this,"handleCategoryClick",(({category:e,i:t})=>{this.scrollTo(0==t?{row:-1}:{categoryId:e.id})})),i(this,"openSkins",(e=>{const{currentTarget:t}=e,n=t.getBoundingClientRect();this.setState({showSkins:n},(async()=>{await async function(e=1){for(let t in[...Array(e).keys()])await new Promise(requestAnimationFrame)}(2);const e=this.refs.menu.current;e&&(e.classList.remove("hidden"),this.refs.skinToneRadio.current.focus(),this.base.addEventListener("click",this.handleBaseClick,!0),this.base.addEventListener("keydown",this.handleBaseKeydown,!0))}))})),this.observers=[],this.state={pos:[-1,-1],perLine:this.initDynamicPerLine(e),visibleRows:{0:!0},...this.getInitialState(e)}}}class et extends ve{async connectedCallback(){const e=oe(this.props,G,this);e.element=this,e.ref=e=>{this.component=e},await ie(e),this.disconnected||N(z(Ye,{...e}),this.shadowRoot)}constructor(e){super(e,{styles:r(tt)})}}i(et,"Props",G),"undefined"==typeof customElements||customElements.get("em-emoji-picker")||customElements.define("em-emoji-picker",et);var tt={};tt=':host {\n width: min-content;\n height: 435px;\n min-height: 230px;\n border-radius: var(--border-radius);\n box-shadow: var(--shadow);\n --border-radius: 10px;\n --category-icon-size: 18px;\n --font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;\n --font-size: 15px;\n --preview-placeholder-size: 21px;\n --preview-title-size: 1.1em;\n --preview-subtitle-size: .9em;\n --shadow-color: 0deg 0% 0%;\n --shadow: .3px .5px 2.7px hsl(var(--shadow-color) / .14), .4px .8px 1px -3.2px hsl(var(--shadow-color) / .14), 1px 2px 2.5px -4.5px hsl(var(--shadow-color) / .14);\n display: flex;\n}\n\n[data-theme="light"] {\n --em-rgb-color: var(--rgb-color, 34, 36, 39);\n --em-rgb-accent: var(--rgb-accent, 34, 102, 237);\n --em-rgb-background: var(--rgb-background, 255, 255, 255);\n --em-rgb-input: var(--rgb-input, 255, 255, 255);\n --em-color-border: var(--color-border, rgba(0, 0, 0, .05));\n --em-color-border-over: var(--color-border-over, rgba(0, 0, 0, .1));\n}\n\n[data-theme="dark"] {\n --em-rgb-color: var(--rgb-color, 222, 222, 221);\n --em-rgb-accent: var(--rgb-accent, 58, 130, 247);\n --em-rgb-background: var(--rgb-background, 21, 22, 23);\n --em-rgb-input: var(--rgb-input, 0, 0, 0);\n --em-color-border: var(--color-border, rgba(255, 255, 255, .1));\n --em-color-border-over: var(--color-border-over, rgba(255, 255, 255, .2));\n}\n\n#root {\n --color-a: rgb(var(--em-rgb-color));\n --color-b: rgba(var(--em-rgb-color), .65);\n --color-c: rgba(var(--em-rgb-color), .45);\n --padding: 12px;\n --padding-small: calc(var(--padding) / 2);\n --sidebar-width: 16px;\n --duration: 225ms;\n --duration-fast: 125ms;\n --duration-instant: 50ms;\n --easing: cubic-bezier(.4, 0, .2, 1);\n width: 100%;\n text-align: left;\n border-radius: var(--border-radius);\n background-color: rgb(var(--em-rgb-background));\n position: relative;\n}\n\n@media (prefers-reduced-motion) {\n #root {\n --duration: 0;\n --duration-fast: 0;\n --duration-instant: 0;\n }\n}\n\n#root[data-menu] button {\n cursor: auto;\n}\n\n#root[data-menu] .menu button {\n cursor: pointer;\n}\n\n:host, #root, input, button {\n color: rgb(var(--em-rgb-color));\n font-family: var(--font-family);\n font-size: var(--font-size);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n line-height: normal;\n}\n\n*, :before, :after {\n box-sizing: border-box;\n min-width: 0;\n margin: 0;\n padding: 0;\n}\n\n.relative {\n position: relative;\n}\n\n.flex {\n display: flex;\n}\n\n.flex-auto {\n flex: none;\n}\n\n.flex-center {\n justify-content: center;\n}\n\n.flex-column {\n flex-direction: column;\n}\n\n.flex-grow {\n flex: auto;\n}\n\n.flex-middle {\n align-items: center;\n}\n\n.flex-wrap {\n flex-wrap: wrap;\n}\n\n.padding {\n padding: var(--padding);\n}\n\n.padding-t {\n padding-top: var(--padding);\n}\n\n.padding-lr {\n padding-left: var(--padding);\n padding-right: var(--padding);\n}\n\n.padding-r {\n padding-right: var(--padding);\n}\n\n.padding-small {\n padding: var(--padding-small);\n}\n\n.padding-small-b {\n padding-bottom: var(--padding-small);\n}\n\n.padding-small-lr {\n padding-left: var(--padding-small);\n padding-right: var(--padding-small);\n}\n\n.margin {\n margin: var(--padding);\n}\n\n.margin-r {\n margin-right: var(--padding);\n}\n\n.margin-l {\n margin-left: var(--padding);\n}\n\n.margin-small-l {\n margin-left: var(--padding-small);\n}\n\n.margin-small-lr {\n margin-left: var(--padding-small);\n margin-right: var(--padding-small);\n}\n\n.align-l {\n text-align: left;\n}\n\n.align-r {\n text-align: right;\n}\n\n.color-a {\n color: var(--color-a);\n}\n\n.color-b {\n color: var(--color-b);\n}\n\n.color-c {\n color: var(--color-c);\n}\n\n.ellipsis {\n white-space: nowrap;\n max-width: 100%;\n width: auto;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.sr-only {\n width: 1px;\n height: 1px;\n position: absolute;\n top: auto;\n left: -10000px;\n overflow: hidden;\n}\n\na {\n cursor: pointer;\n color: rgb(var(--em-rgb-accent));\n}\n\na:hover {\n text-decoration: underline;\n}\n\n.spacer {\n height: 10px;\n}\n\n[dir="rtl"] .scroll {\n padding-left: 0;\n padding-right: var(--padding);\n}\n\n.scroll {\n padding-right: 0;\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n.scroll::-webkit-scrollbar {\n width: var(--sidebar-width);\n height: var(--sidebar-width);\n}\n\n.scroll::-webkit-scrollbar-track {\n border: 0;\n}\n\n.scroll::-webkit-scrollbar-button {\n width: 0;\n height: 0;\n display: none;\n}\n\n.scroll::-webkit-scrollbar-corner {\n background-color: rgba(0, 0, 0, 0);\n}\n\n.scroll::-webkit-scrollbar-thumb {\n min-height: 20%;\n min-height: 65px;\n border: 4px solid rgb(var(--em-rgb-background));\n border-radius: 8px;\n}\n\n.scroll::-webkit-scrollbar-thumb:hover {\n background-color: var(--em-color-border-over) !important;\n}\n\n.scroll:hover::-webkit-scrollbar-thumb {\n background-color: var(--em-color-border);\n}\n\n.sticky {\n z-index: 1;\n background-color: rgba(var(--em-rgb-background), .9);\n -webkit-backdrop-filter: blur(4px);\n backdrop-filter: blur(4px);\n font-weight: 500;\n position: sticky;\n top: -1px;\n}\n\n[dir="rtl"] .search input[type="search"] {\n padding: 10px 2.2em 10px 2em;\n}\n\n[dir="rtl"] .search .loupe {\n left: auto;\n right: .7em;\n}\n\n[dir="rtl"] .search .delete {\n left: .7em;\n right: auto;\n}\n\n.search {\n z-index: 2;\n position: relative;\n}\n\n.search input, .search button {\n font-size: calc(var(--font-size) - 1px);\n}\n\n.search input[type="search"] {\n width: 100%;\n background-color: var(--em-color-border);\n transition-duration: var(--duration);\n transition-property: background-color, box-shadow;\n transition-timing-function: var(--easing);\n border: 0;\n border-radius: 10px;\n outline: 0;\n padding: 10px 2em 10px 2.2em;\n display: block;\n}\n\n.search input[type="search"]::-ms-input-placeholder {\n color: inherit;\n opacity: .6;\n}\n\n.search input[type="search"]::placeholder {\n color: inherit;\n opacity: .6;\n}\n\n.search input[type="search"], .search input[type="search"]::-webkit-search-decoration, .search input[type="search"]::-webkit-search-cancel-button, .search input[type="search"]::-webkit-search-results-button, .search input[type="search"]::-webkit-search-results-decoration {\n -webkit-appearance: none;\n -ms-appearance: none;\n appearance: none;\n}\n\n.search input[type="search"]:focus {\n background-color: rgb(var(--em-rgb-input));\n box-shadow: inset 0 0 0 1px rgb(var(--em-rgb-accent)), 0 1px 3px rgba(65, 69, 73, .2);\n}\n\n.search .icon {\n z-index: 1;\n color: rgba(var(--em-rgb-color), .7);\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n}\n\n.search .loupe {\n pointer-events: none;\n left: .7em;\n}\n\n.search .delete {\n right: .7em;\n}\n\nsvg {\n fill: currentColor;\n width: 1em;\n height: 1em;\n}\n\nbutton {\n -webkit-appearance: none;\n -ms-appearance: none;\n appearance: none;\n cursor: pointer;\n color: currentColor;\n background-color: rgba(0, 0, 0, 0);\n border: 0;\n}\n\n#nav {\n z-index: 2;\n padding-top: 12px;\n padding-bottom: 12px;\n padding-right: var(--sidebar-width);\n position: relative;\n}\n\n#nav button {\n color: var(--color-b);\n transition: color var(--duration) var(--easing);\n}\n\n#nav button:hover {\n color: var(--color-a);\n}\n\n#nav svg, #nav img {\n width: var(--category-icon-size);\n height: var(--category-icon-size);\n}\n\n#nav[dir="rtl"] .bar {\n left: auto;\n right: 0;\n}\n\n#nav .bar {\n width: 100%;\n height: 3px;\n background-color: rgb(var(--em-rgb-accent));\n transition: transform var(--duration) var(--easing);\n border-radius: 3px 3px 0 0;\n position: absolute;\n bottom: -12px;\n left: 0;\n}\n\n#nav button[aria-selected] {\n color: rgb(var(--em-rgb-accent));\n}\n\n#preview {\n z-index: 2;\n padding: calc(var(--padding) + 4px) var(--padding);\n padding-right: var(--sidebar-width);\n position: relative;\n}\n\n#preview .preview-placeholder {\n font-size: var(--preview-placeholder-size);\n}\n\n#preview .preview-title {\n font-size: var(--preview-title-size);\n}\n\n#preview .preview-subtitle {\n font-size: var(--preview-subtitle-size);\n}\n\n#nav:before, #preview:before {\n content: "";\n height: 2px;\n position: absolute;\n left: 0;\n right: 0;\n}\n\n#nav[data-position="top"]:before, #preview[data-position="top"]:before {\n background: linear-gradient(to bottom, var(--em-color-border), transparent);\n top: 100%;\n}\n\n#nav[data-position="bottom"]:before, #preview[data-position="bottom"]:before {\n background: linear-gradient(to top, var(--em-color-border), transparent);\n bottom: 100%;\n}\n\n.category:last-child {\n min-height: calc(100% + 1px);\n}\n\n.category button {\n font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, sans-serif;\n position: relative;\n}\n\n.category button > * {\n position: relative;\n}\n\n.category button .background {\n opacity: 0;\n background-color: var(--em-color-border);\n transition: opacity var(--duration-fast) var(--easing) var(--duration-instant);\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n}\n\n.category button:hover .background {\n transition-duration: var(--duration-instant);\n transition-delay: 0s;\n}\n\n.category button[aria-selected] .background {\n opacity: 1;\n}\n\n.category button[data-keyboard] .background {\n transition: none;\n}\n\n.row {\n width: 100%;\n position: absolute;\n top: 0;\n left: 0;\n}\n\n.skin-tone-button {\n border: 1px solid rgba(0, 0, 0, 0);\n border-radius: 100%;\n}\n\n.skin-tone-button:hover {\n border-color: var(--em-color-border);\n}\n\n.skin-tone-button:active .skin-tone {\n transform: scale(.85) !important;\n}\n\n.skin-tone-button .skin-tone {\n transition: transform var(--duration) var(--easing);\n}\n\n.skin-tone-button[aria-selected] {\n background-color: var(--em-color-border);\n border-top-color: rgba(0, 0, 0, .05);\n border-bottom-color: rgba(0, 0, 0, 0);\n border-left-width: 0;\n border-right-width: 0;\n}\n\n.skin-tone-button[aria-selected] .skin-tone {\n transform: scale(.9);\n}\n\n.menu {\n z-index: 2;\n white-space: nowrap;\n border: 1px solid var(--em-color-border);\n background-color: rgba(var(--em-rgb-background), .9);\n -webkit-backdrop-filter: blur(4px);\n backdrop-filter: blur(4px);\n transition-property: opacity, transform;\n transition-duration: var(--duration);\n transition-timing-function: var(--easing);\n border-radius: 10px;\n padding: 4px;\n position: absolute;\n box-shadow: 1px 1px 5px rgba(0, 0, 0, .05);\n}\n\n.menu.hidden {\n opacity: 0;\n}\n\n.menu[data-position="bottom"] {\n transform-origin: 100% 100%;\n}\n\n.menu[data-position="bottom"].hidden {\n transform: scale(.9)rotate(-3deg)translateY(5%);\n}\n\n.menu[data-position="top"] {\n transform-origin: 100% 0;\n}\n\n.menu[data-position="top"].hidden {\n transform: scale(.9)rotate(3deg)translateY(-5%);\n}\n\n.menu input[type="radio"] {\n clip: rect(0 0 0 0);\n width: 1px;\n height: 1px;\n border: 0;\n margin: 0;\n padding: 0;\n position: absolute;\n overflow: hidden;\n}\n\n.menu input[type="radio"]:checked + .option {\n box-shadow: 0 0 0 2px rgb(var(--em-rgb-accent));\n}\n\n.option {\n width: 100%;\n border-radius: 6px;\n padding: 4px 6px;\n}\n\n.option:hover {\n color: #fff;\n background-color: rgb(var(--em-rgb-accent));\n}\n\n.skin-tone {\n width: 16px;\n height: 16px;\n border-radius: 100%;\n display: inline-block;\n position: relative;\n overflow: hidden;\n}\n\n.skin-tone:after {\n content: "";\n mix-blend-mode: overlay;\n background: linear-gradient(rgba(255, 255, 255, .2), rgba(0, 0, 0, 0));\n border: 1px solid rgba(0, 0, 0, .8);\n border-radius: 100%;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n box-shadow: inset 0 -2px 3px #000, inset 0 1px 2px #fff;\n}\n\n.skin-tone-1 {\n background-color: #ffc93a;\n}\n\n.skin-tone-2 {\n background-color: #ffdab7;\n}\n\n.skin-tone-3 {\n background-color: #e7b98f;\n}\n\n.skin-tone-4 {\n background-color: #c88c61;\n}\n\n.skin-tone-5 {\n background-color: #a46134;\n}\n\n.skin-tone-6 {\n background-color: #5d4437;\n}\n\n[data-index] {\n justify-content: space-between;\n}\n\n[data-emoji-set="twitter"] .skin-tone:after {\n box-shadow: none;\n border-color: rgba(0, 0, 0, .5);\n}\n\n[data-emoji-set="twitter"] .skin-tone-1 {\n background-color: #fade72;\n}\n\n[data-emoji-set="twitter"] .skin-tone-2 {\n background-color: #f3dfd0;\n}\n\n[data-emoji-set="twitter"] .skin-tone-3 {\n background-color: #eed3a8;\n}\n\n[data-emoji-set="twitter"] .skin-tone-4 {\n background-color: #cfad8d;\n}\n\n[data-emoji-set="twitter"] .skin-tone-5 {\n background-color: #a8805d;\n}\n\n[data-emoji-set="twitter"] .skin-tone-6 {\n background-color: #765542;\n}\n\n[data-emoji-set="google"] .skin-tone:after {\n box-shadow: inset 0 0 2px 2px rgba(0, 0, 0, .4);\n}\n\n[data-emoji-set="google"] .skin-tone-1 {\n background-color: #f5c748;\n}\n\n[data-emoji-set="google"] .skin-tone-2 {\n background-color: #f1d5aa;\n}\n\n[data-emoji-set="google"] .skin-tone-3 {\n background-color: #d4b48d;\n}\n\n[data-emoji-set="google"] .skin-tone-4 {\n background-color: #aa876b;\n}\n\n[data-emoji-set="google"] .skin-tone-5 {\n background-color: #916544;\n}\n\n[data-emoji-set="google"] .skin-tone-6 {\n background-color: #61493f;\n}\n\n[data-emoji-set="facebook"] .skin-tone:after {\n border-color: rgba(0, 0, 0, .4);\n box-shadow: inset 0 -2px 3px #000, inset 0 1px 4px #fff;\n}\n\n[data-emoji-set="facebook"] .skin-tone-1 {\n background-color: #f5c748;\n}\n\n[data-emoji-set="facebook"] .skin-tone-2 {\n background-color: #f1d5aa;\n}\n\n[data-emoji-set="facebook"] .skin-tone-3 {\n background-color: #d4b48d;\n}\n\n[data-emoji-set="facebook"] .skin-tone-4 {\n background-color: #aa876b;\n}\n\n[data-emoji-set="facebook"] .skin-tone-5 {\n background-color: #916544;\n}\n\n[data-emoji-set="facebook"] .skin-tone-6 {\n background-color: #61493f;\n}\n\n'},689:(e,t,n)=>{n.r(t),n.d(t,{default:()=>g});var r=n(379),i=n.n(r),o=n(795),s=n.n(o),a=n(569),l=n.n(a),c=n(565),u=n.n(c),h=n(216),d=n.n(h),f=n(589),p=n.n(f),m=n(601),v={};v.styleTagTransform=p(),v.setAttributes=u(),v.insert=l().bind(null,"head"),v.domAPI=s(),v.insertStyleElement=d(),i()(m.Z,v);const g=m.Z&&m.Z.locals?m.Z.locals:void 0},379:e=>{var t=[];function n(e){for(var n=-1,r=0;r{var t={};e.exports=function(e,n){var r=function(e){if(void 0===t[e]){var n=document.querySelector(e);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}t[e]=n}return t[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(n)}},216:e=>{e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},565:(e,t,n)=>{e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}},795:e=>{e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(n){!function(e,t,n){var r="";n.supports&&(r+="@supports (".concat(n.supports,") {")),n.media&&(r+="@media ".concat(n.media," {"));var i=void 0!==n.layer;i&&(r+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),r+=n.css,i&&(r+="}"),n.media&&(r+="}"),n.supports&&(r+="}");var o=n.sourceMap;o&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},589:e=>{e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={id:r,exports:{}};return e[r](o,o.exports,n),o.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nc=void 0,n(599),n(989)})(); \ No newline at end of file diff --git a/docs/webchat.md b/docs/webchat.md new file mode 100644 index 0000000..c5e92c7 --- /dev/null +++ b/docs/webchat.md @@ -0,0 +1,101 @@ +## Webchat + +Hellotext allows you to build webchats via the dashboard and allow Hellotext.js to load a given webchat with +a specific ID and show it to the user. A webchat can be specified when initializing the library by passing a `webchat` property +to the configuration option. + +```js +Hellotext.initialize('PUBLIC_BUSINESS_ID', { + webchat: { + id, + container, + placement, + classes, + triggerClasses, + style: { + primaryColor, + secondaryColor, + typography + }, + behaviour, + } +}) +``` + +| Property | Description | Type | Default | +|----------------|------------------------------------------------------------------------------------------------------------------------------------------|--------|----------------| +| id | The id of the webchat to load. **required** | String | null | +| container | The container to append the webchat to, must be a valid CSS selector. If none specified, the webchat is appended at the end of the body. | String | `body` | +| placement | The placement of the webchat, determined according to the parent `container`. | Enum | `bottom-right` | +| classes | An array or comma separated String of additional CSS classes to apply to the webchat popover. | String | null | +| triggerClasses | An array or comma separated String of additional CSS classes to apply to the webchat trigger. | String | null | +| style | Style overrides to the WebChat's style configuration as created on the dashboard. | Object | null | +| behaviour | The behaviour of the webchat when it is open and a click was made outside of it | Enum | `popover` | + +### Position + +The default position for a webchat is `bottom-right`, but you can specify any of the following values + +- `bottom-left` +- `bottom-right` +- `top-left` +- `top-right` + +### Style + +The following properties are accepted for the `style` object. + +- `primaryColor` - The primary color of the Webchat. Must be either in hex or rgb/a formats. Affects the following elements: + - Trigger background + - Popover header background + - Agent icon color + - Toolbar button hover + - Incoming message background + +The primary color is controlled via a `--webchat-primary-color` CSS variable. + +- `secondaryColor` - The secondary color of the webchat. Must be either in hex or rgb/a formats. Affects the following elements: + - Trigger icon color + - Popover header text color + - Agent icon background + - Incoming message text color + +The secondary color is controlled via a `--webchat-secondary-color` CSS variable. +- `typography` - The font family to use for the webchat. + +All properties accept a valid CSS value, for example, `primaryColor: '#EEEEEE'` or `secondaryColor: '#ff0000'`. + +### behaviour + +Determines how the webchat functions when it is open and a click is made outside of it. The following values are accepted. + +- `popover` - Closes the webchat when a click is made outside of it. This is the default behaviour. +- `modal` - Prevents the webchat from closing when a click is made outside of it. The webchat can only be closed by clicking on the trigger. + +### Events + +The webchat emits the following events which can be listened to, to add an event listener you can `Hellotext.addEventListener(event, callback)`. + +- `webchat:mounted` - Emitted when the webchat is mounted +- `webchat:opened` - Emitted when the webchat is opened +- `webchat:closed` - Emitted when the webchat is closed + +- `webchat:message:sent` - Emitted when a message is sent by the user. The message is passed as an argument to the callback, containing the following properties + +```javascript +{ + id: 'xxxxxx' + body: 'The message the client sent', + attachments: [], // An array of File objects that reference the attachments the user sent. +} +``` + +- `webchat:message:received` - Emitted when a message is received by the webchat from Hellotext. The message is passed as an argument to the callback, containing the following properties + +```javascript +{ + id: 'xxxxxx', + body: 'The message the client received from Hellotext', + attachments: [], // An Array of URLs referencing the attachments the user received. +} +``` diff --git a/jest.config.js b/jest.config.js index 6bb9b97..ced2a9e 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,3 +1,4 @@ module.exports = { setupFiles: ['/jest.setup.js'], // Setup file to run before tests + testEnvironment: 'jsdom', }; diff --git a/jest.setup.js b/jest.setup.js index fff3b3f..618b603 100644 --- a/jest.setup.js +++ b/jest.setup.js @@ -1,3 +1,5 @@ +require('whatwg-fetch'); + global.crypto.randomUUID = () => { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = (Math.random() * 16) | 0; @@ -5,3 +7,10 @@ global.crypto.randomUUID = () => { return v.toString(16); }); }; + +global.fetch = jest.fn(() => + Promise.resolve({ + json: () => Promise.resolve({}), + text: () => Promise.resolve(''), + }) +); diff --git a/lib/api/index.js b/lib/api/index.js index 8e98aa2..e96b86e 100644 --- a/lib/api/index.js +++ b/lib/api/index.js @@ -13,6 +13,7 @@ exports.default = void 0; var _businesses = _interopRequireDefault(require("./businesses")); var _events = _interopRequireDefault(require("./events")); var _forms = _interopRequireDefault(require("./forms")); +var _webchats = _interopRequireDefault(require("./webchats")); var _response = require("./response"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } @@ -39,6 +40,11 @@ var API = /*#__PURE__*/function () { get: function get() { return _forms.default; } + }, { + key: "webchats", + get: function get() { + return _webchats.default; + } }]); return API; }(); diff --git a/lib/api/web_chat/messages.js b/lib/api/web_chat/messages.js new file mode 100644 index 0000000..d85371a --- /dev/null +++ b/lib/api/web_chat/messages.js @@ -0,0 +1,74 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _hellotext = _interopRequireDefault(require("../../hellotext")); +var _core = require("../../core"); +var _response = require("../response"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var WebChatMessagesAPI = /*#__PURE__*/function () { + function WebChatMessagesAPI(webChatId) { + _classCallCheck(this, WebChatMessagesAPI); + this.webChatId = webChatId; + } + _createClass(WebChatMessagesAPI, [{ + key: "index", + value: function () { + var _index = _asyncToGenerator(function* (params) { + var url = new URL(this.url); + Object.entries(params).forEach(_ref => { + var [key, value] = _ref; + url.searchParams.append(key, value); + }); + return yield fetch(url, { + method: 'GET', + headers: _hellotext.default.headers + }); + }); + function index(_x) { + return _index.apply(this, arguments); + } + return index; + }() + }, { + key: "create", + value: function () { + var _create = _asyncToGenerator(function* (formData) { + var response = yield fetch(this.url, { + method: 'POST', + headers: { + Authorization: "Bearer ".concat(_hellotext.default.business.id) + }, + body: formData + }); + return new _response.Response(response.ok, response); + }); + function create(_x2) { + return _create.apply(this, arguments); + } + return create; + }() + }, { + key: "url", + get: function get() { + return WebChatMessagesAPI.endpoint.replace(':id', this.webChatId); + } + }], [{ + key: "endpoint", + get: function get() { + return _core.Configuration.endpoint("public/webchats/:id/messages"); + } + }]); + return WebChatMessagesAPI; +}(); +var _default = WebChatMessagesAPI; +exports.default = _default; \ No newline at end of file diff --git a/lib/api/web_chats.js b/lib/api/web_chats.js new file mode 100644 index 0000000..4e29412 --- /dev/null +++ b/lib/api/web_chats.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _hellotext = _interopRequireDefault(require("../hellotext")); +var _core = require("../core"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var WebChatsAPI = /*#__PURE__*/function () { + function WebChatsAPI() { + _classCallCheck(this, WebChatsAPI); + } + _createClass(WebChatsAPI, null, [{ + key: "endpoint", + get: function get() { + return _core.Configuration.endpoint('public/webchats'); + } + }, { + key: "get", + value: function () { + var _get = _asyncToGenerator(function* (id) { + var url = new URL("".concat(this.endpoint, "/").concat(id)); + url.searchParams.append('session', _hellotext.default.session); + Object.entries(_core.Configuration.webChat.style).forEach(_ref => { + var [key, value] = _ref; + url.searchParams.append("style[".concat(key, "]"), value); + }); + url.searchParams.append('placement', _core.Configuration.webChat.placement); + var response = yield fetch(url, { + method: 'GET', + headers: _hellotext.default.headers + }); + var htmlText = yield response.text(); + return new DOMParser().parseFromString(htmlText, "text/html").querySelector('article'); + }); + function get(_x) { + return _get.apply(this, arguments); + } + return get; + }() + }]); + return WebChatsAPI; +}(); +var _default = WebChatsAPI; +exports.default = _default; \ No newline at end of file diff --git a/lib/api/webchat/messages.js b/lib/api/webchat/messages.js new file mode 100644 index 0000000..b99021a --- /dev/null +++ b/lib/api/webchat/messages.js @@ -0,0 +1,74 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _hellotext = _interopRequireDefault(require("../../hellotext")); +var _core = require("../../core"); +var _response = require("../response"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var WebchatMessagesAPI = /*#__PURE__*/function () { + function WebchatMessagesAPI(webchatId) { + _classCallCheck(this, WebchatMessagesAPI); + this.webchatId = webchatId; + } + _createClass(WebchatMessagesAPI, [{ + key: "index", + value: function () { + var _index = _asyncToGenerator(function* (params) { + var url = new URL(this.url); + Object.entries(params).forEach(_ref => { + var [key, value] = _ref; + url.searchParams.append(key, value); + }); + return yield fetch(url, { + method: 'GET', + headers: _hellotext.default.headers + }); + }); + function index(_x) { + return _index.apply(this, arguments); + } + return index; + }() + }, { + key: "create", + value: function () { + var _create = _asyncToGenerator(function* (formData) { + var response = yield fetch(this.url, { + method: 'POST', + headers: { + Authorization: "Bearer ".concat(_hellotext.default.business.id) + }, + body: formData + }); + return new _response.Response(response.ok, response); + }); + function create(_x2) { + return _create.apply(this, arguments); + } + return create; + }() + }, { + key: "url", + get: function get() { + return WebchatMessagesAPI.endpoint.replace(':id', this.webchatId); + } + }], [{ + key: "endpoint", + get: function get() { + return _core.Configuration.endpoint("public/webchats/:id/messages"); + } + }]); + return WebchatMessagesAPI; +}(); +var _default = WebchatMessagesAPI; +exports.default = _default; \ No newline at end of file diff --git a/lib/api/webchats.js b/lib/api/webchats.js new file mode 100644 index 0000000..75d34bd --- /dev/null +++ b/lib/api/webchats.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _hellotext = _interopRequireDefault(require("../hellotext")); +var _core = require("../core"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var WebchatsAPI = /*#__PURE__*/function () { + function WebchatsAPI() { + _classCallCheck(this, WebchatsAPI); + } + _createClass(WebchatsAPI, null, [{ + key: "endpoint", + get: function get() { + return _core.Configuration.endpoint('public/webchats'); + } + }, { + key: "get", + value: function () { + var _get = _asyncToGenerator(function* (id) { + var url = new URL("".concat(this.endpoint, "/").concat(id)); + url.searchParams.append('session', _hellotext.default.session); + Object.entries(_core.Configuration.webchat.style).forEach(_ref => { + var [key, value] = _ref; + url.searchParams.append("style[".concat(key, "]"), value); + }); + url.searchParams.append('placement', _core.Configuration.webchat.placement); + var response = yield fetch(url, { + method: 'GET', + headers: _hellotext.default.headers + }); + var htmlText = yield response.text(); + return new DOMParser().parseFromString(htmlText, "text/html").querySelector('article'); + }); + function get(_x) { + return _get.apply(this, arguments); + } + return get; + }() + }]); + return WebchatsAPI; +}(); +var _default = WebchatsAPI; +exports.default = _default; \ No newline at end of file diff --git a/lib/builders/logo_builder.js b/lib/builders/logo_builder.js index 85c4619..5a1832d 100644 --- a/lib/builders/logo_builder.js +++ b/lib/builders/logo_builder.js @@ -31,7 +31,8 @@ var LogoBuilder = /*#__PURE__*/function () { }(); exports.LogoBuilder = LogoBuilder; function _template2() { - return "\n
\n ".concat(_hellotext.default.business.locale.white_label.powered_by, "\n \n \n Hellotext\n \n \n
\n "); + var url = "https://www.hellotext.com?hello_session=".concat(_hellotext.default.session); + return "\n
\n ".concat(_hellotext.default.business.locale.white_label.powered_by, "\n \n \n \n Hellotext\n \n \n \n
\n "); } Object.defineProperty(LogoBuilder, _template, { value: _template2 diff --git a/lib/channels/application_channel.js b/lib/channels/application_channel.js new file mode 100644 index 0000000..68318f9 --- /dev/null +++ b/lib/channels/application_channel.js @@ -0,0 +1,68 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ApplicationChannel = /*#__PURE__*/function () { + function ApplicationChannel() { + _classCallCheck(this, ApplicationChannel); + } + _createClass(ApplicationChannel, [{ + key: "send", + value: function send(_ref) { + var { + command, + identifier + } = _ref; + var data = { + command, + identifier: JSON.stringify(identifier) + }; + if (this.webSocket.readyState === WebSocket.OPEN) { + this.webSocket.send(JSON.stringify(data)); + } else { + this.webSocket.addEventListener('open', () => { + this.webSocket.send(JSON.stringify(data)); + }); + } + } + }, { + key: "onMessage", + value: function onMessage(callback) { + this.webSocket.addEventListener('message', event => { + var data = JSON.parse(event.data); + var { + type, + message + } = data; + if (this.ignoredEvents.includes(type)) { + return; + } + callback(message); + }); + } + }, { + key: "webSocket", + get: function get() { + if (!ApplicationChannel.webSocket) { + return ApplicationChannel.webSocket = new WebSocket("ws://localhost:3000/cable"); + } + return ApplicationChannel.webSocket; + } + }, { + key: "ignoredEvents", + get: function get() { + return ['ping', 'confirm_subscription', 'welcome']; + } + }]); + return ApplicationChannel; +}(); +ApplicationChannel.webSocket = void 0; +var _default = ApplicationChannel; +exports.default = _default; \ No newline at end of file diff --git a/lib/channels/web_chat_channel.js b/lib/channels/web_chat_channel.js new file mode 100644 index 0000000..250e8a9 --- /dev/null +++ b/lib/channels/web_chat_channel.js @@ -0,0 +1,97 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _application_channel = _interopRequireDefault(require("./application_channel")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var WebChatChannel = /*#__PURE__*/function (_ApplicationChannel) { + _inherits(WebChatChannel, _ApplicationChannel); + var _super = _createSuper(WebChatChannel); + function WebChatChannel(id, session) { + var _this; + _classCallCheck(this, WebChatChannel); + _this = _super.call(this); + _this.id = id; + _this.session = session; + _this.subscribe(); + return _this; + } + _createClass(WebChatChannel, [{ + key: "subscribe", + value: function subscribe() { + var params = { + channel: "WebChatChannel", + id: this.id, + session: this.session + }; + this.send({ + command: 'subscribe', + identifier: params + }); + } + }, { + key: "unsubscribe", + value: function unsubscribe() { + var params = { + channel: "WebChatChannel", + id: this.id, + session: this.session + }; + this.send({ + command: 'unsubscribe', + identifier: params + }); + } + }, { + key: "onMessage", + value: function onMessage(callback) { + _get(_getPrototypeOf(WebChatChannel.prototype), "onMessage", this).call(this, message => { + if (message.type !== 'message') return; + callback(message); + }); + } + }, { + key: "onConversationAssignment", + value: function onConversationAssignment(callback) { + _get(_getPrototypeOf(WebChatChannel.prototype), "onMessage", this).call(this, message => { + if (message.type === 'conversation.assigned') { + callback(message); + } + }); + } + }, { + key: "onAgentOnline", + value: function onAgentOnline(callback) { + _get(_getPrototypeOf(WebChatChannel.prototype), "onMessage", this).call(this, message => { + if (message.type === 'agent_is_online') { + callback(message); + } + }); + } + }, { + key: "updateSubscription", + value: function updateSubscription() { + this.unsubscribe(); + this.subscribe(); + } + }]); + return WebChatChannel; +}(_application_channel.default); +var _default = WebChatChannel; +exports.default = _default; \ No newline at end of file diff --git a/lib/channels/webchat_channel.js b/lib/channels/webchat_channel.js new file mode 100644 index 0000000..3a8c965 --- /dev/null +++ b/lib/channels/webchat_channel.js @@ -0,0 +1,112 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _application_channel = _interopRequireDefault(require("./application_channel")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var WebchatChannel = /*#__PURE__*/function (_ApplicationChannel) { + _inherits(WebchatChannel, _ApplicationChannel); + var _super = _createSuper(WebchatChannel); + function WebchatChannel(id, session, conversation) { + var _this; + _classCallCheck(this, WebchatChannel); + _this = _super.call(this); + _this.id = id; + _this.session = session; + _this.conversation = conversation; + _this.subscribe(); + return _this; + } + _createClass(WebchatChannel, [{ + key: "subscribe", + value: function subscribe() { + var params = { + channel: "WebchatChannel", + id: this.id, + session: this.session, + conversation: this.conversation + }; + this.send({ + command: 'subscribe', + identifier: params + }); + } + }, { + key: "unsubscribe", + value: function unsubscribe() { + var params = { + channel: "WebchatChannel", + id: this.id, + session: this.session, + conversation: this.conversation + }; + this.send({ + command: 'unsubscribe', + identifier: params + }); + } + }, { + key: "onMessage", + value: function onMessage(callback) { + _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + if (message.type !== 'message') return; + callback(message); + }); + } + }, { + key: "onConversationAssignment", + value: function onConversationAssignment(callback) { + _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + if (message.type === 'conversation.assigned') { + callback(message); + } + }); + } + }, { + key: "onAgentOnline", + value: function onAgentOnline(callback) { + _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + if (message.type === 'agent_is_online') { + callback(message); + } + }); + } + }, { + key: "onReaction", + value: function onReaction(callback) { + _get(_getPrototypeOf(WebchatChannel.prototype), "onMessage", this).call(this, message => { + if (message.type === 'reaction.create' || message.type === 'reaction.destroy') { + callback(message); + } + }); + } + }, { + key: "updateSubscriptionWith", + value: function updateSubscriptionWith(conversation) { + this.unsubscribe(); + setTimeout(() => { + this.conversation = conversation; + this.subscribe(); + }, 1000); + } + }]); + return WebchatChannel; +}(_application_channel.default); +var _default = WebchatChannel; +exports.default = _default; \ No newline at end of file diff --git a/lib/controllers/mixins/usePopover.js b/lib/controllers/mixins/usePopover.js new file mode 100644 index 0000000..10896d6 --- /dev/null +++ b/lib/controllers/mixins/usePopover.js @@ -0,0 +1,61 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.usePopover = void 0; +var _dom = require("@floating-ui/dom"); +var _hellotext = _interopRequireDefault(require("../../hellotext")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var usePopover = controller => { + Object.assign(controller, { + show() { + this.openValue = true; + }, + hide() { + this.openValue = false; + }, + toggle() { + this.openValue = !this.openValue; + }, + setupFloatingUI(_ref) { + var { + trigger, + popover + } = _ref; + this.floatingUICleanup = (0, _dom.autoUpdate)(trigger, popover, () => { + (0, _dom.computePosition)(trigger, popover, { + placement: this.placementValue, + middleware: this.middlewares + }).then(_ref2 => { + var { + x, + y + } = _ref2; + var newStyle = { + left: "".concat(x, "px"), + top: "".concat(y, "px") + }; + Object.assign(popover.style, newStyle); + }); + }); + }, + openValueChanged() { + if (this.disabledValue) return; + if (this.openValue) { + this.popoverTarget.showPopover(); + this.popoverTarget.setAttribute("aria-expanded", "true"); + if (this['onPopoverOpened']) { + this.onPopoverOpened(); + } + } else { + this.popoverTarget.hidePopover(); + this.popoverTarget.removeAttribute("aria-expanded"); + if (this['onPopoverClosed']) { + this.onPopoverClosed(); + } + } + } + }); +}; +exports.usePopover = usePopover; \ No newline at end of file diff --git a/lib/controllers/web_chat/pagination_controller.js b/lib/controllers/web_chat/pagination_controller.js new file mode 100644 index 0000000..1e62906 --- /dev/null +++ b/lib/controllers/web_chat/pagination_controller.js @@ -0,0 +1,81 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _stimulus = require("@hotwired/stimulus"); +var _core = require("../../core"); +var _hellotext = _interopRequireDefault(require("../../hellotext")); +var _messages = _interopRequireDefault(require("../../api/web_chat/messages")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var _default = /*#__PURE__*/function (_Controller) { + _inherits(_default, _Controller); + var _super = _createSuper(_default); + function _default() { + _classCallCheck(this, _default); + return _super.apply(this, arguments); + } + _createClass(_default, [{ + key: "initialize", + value: function initialize() { + this.messagesAPI = new _messages.default(_core.Configuration.webChat.id); + this.onScroll = this.onScroll.bind(this); + _get(_getPrototypeOf(_default.prototype), "initialize", this).call(this); + } + }, { + key: "connect", + value: function connect() { + this.scrollableTarget.addEventListener('scroll', this.onScroll); + _get(_getPrototypeOf(_default.prototype), "connect", this).call(this); + } + }, { + key: "disconnect", + value: function disconnect() { + this.scrollableTarget.removeEventListener('scroll', this.onScroll); + _get(_getPrototypeOf(_default.prototype), "disconnect", this).call(this); + } + }, { + key: "onScroll", + value: function () { + var _onScroll = _asyncToGenerator(function* () { + if (this.scrollableTarget.scrollTop > 300 || !this.nextPageValue) return; + console.log('fetching....'); + var response = yield this.messagesAPI.index({ + page: this.nextPageValue, + session: _hellotext.default.session + }); + console.log(yield response.json()); + }); + function onScroll() { + return _onScroll.apply(this, arguments); + } + return onScroll; + }() + }]); + return _default; +}(_stimulus.Controller); +exports.default = _default; +_default.values = { + nextPage: { + type: Number, + default: undefined + } +}; +_default.targets = ['scrollable']; \ No newline at end of file diff --git a/lib/controllers/webchat/emoji_picker_controller.js b/lib/controllers/webchat/emoji_picker_controller.js new file mode 100644 index 0000000..0d33572 --- /dev/null +++ b/lib/controllers/webchat/emoji_picker_controller.js @@ -0,0 +1,134 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _stimulus = require("@hotwired/stimulus"); +var _dom = require("@floating-ui/dom"); +var _emojiMart = require("emoji-mart"); +var _usePopover = require("../mixins/usePopover"); +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var _default = /*#__PURE__*/function (_Controller) { + _inherits(_default, _Controller); + var _super = _createSuper(_default); + function _default() { + _classCallCheck(this, _default); + return _super.apply(this, arguments); + } + _createClass(_default, [{ + key: "initialize", + value: function initialize() { + this.onEmojiSelect = this.onEmojiSelect.bind(this); + _get(_getPrototypeOf(_default.prototype), "initialize", this).call(this); + } + }, { + key: "connect", + value: function connect() { + (0, _usePopover.usePopover)(this); + this.setupFloatingUI({ + trigger: this.buttonTarget, + popover: this.popoverTarget + }); + this.popoverTarget.appendChild(this.pickerObject); + _get(_getPrototypeOf(_default.prototype), "connect", this).call(this); + } + }, { + key: "disconnect", + value: function disconnect() { + this.floatingUICleanup(); + _get(_getPrototypeOf(_default.prototype), "disconnect", this).call(this); + } + }, { + key: "onEmojiSelect", + value: function onEmojiSelect(emoji) { + this.dispatch('selected', { + detail: emoji.native + }); + this.hide(); + } + }, { + key: "onClickOutside", + value: function onClickOutside(event) { + if (this.openValue && event.target.nodeType && this.element.contains(event.target) === false) { + this.openValue = false; + } + } + }, { + key: "pickerObject", + get: function get() { + return new _emojiMart.Picker({ + onEmojiSelect: this.onEmojiSelect, + theme: 'light', + dynamicWidth: true, + previewPosition: 'none', + skinTonePosition: 'none', + emojiSize: this.sizeValue, + perLine: this.perLineValue, + data: function () { + var _data = _asyncToGenerator(function* () { + var response = yield fetch('https://cdn.jsdelivr.net/npm/@emoji-mart/data'); + return response.json(); + }); + function data() { + return _data.apply(this, arguments); + } + return data; + }() + }); + } + }, { + key: "middlewares", + get: function get() { + return [(0, _dom.offset)(5), (0, _dom.shift)({ + padding: 24 + }), (0, _dom.autoPlacement)({ + allowedPlacements: ['top', 'bottom'] + })]; + } + }]); + return _default; +}(_stimulus.Controller); +exports.default = _default; +_default.targets = ['button', 'popover']; +_default.values = { + placement: { + type: String, + default: "bottom-end" + }, + open: { + type: Boolean, + default: false + }, + autoPlacement: { + type: Boolean, + default: false + }, + disabled: { + type: Boolean, + default: false + }, + size: { + type: Number, + default: 24 + }, + perLine: { + type: Number, + default: 9 + } +}; \ No newline at end of file diff --git a/lib/controllers/webchat_controller.js b/lib/controllers/webchat_controller.js new file mode 100644 index 0000000..47041ba --- /dev/null +++ b/lib/controllers/webchat_controller.js @@ -0,0 +1,445 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _stimulus = require("@hotwired/stimulus"); +var _dom = require("@floating-ui/dom"); +var _messages = _interopRequireDefault(require("../api/webchat/messages")); +var _webchat_channel = _interopRequireDefault(require("../channels/webchat_channel")); +var _hellotext = _interopRequireDefault(require("../hellotext")); +var _webchat = require("../core/configuration/webchat"); +var _usePopover = require("./mixins/usePopover"); +var _logo_builder = require("../builders/logo_builder"); +var _locales = _interopRequireDefault(require("../locales")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var _default = /*#__PURE__*/function (_Controller) { + _inherits(_default, _Controller); + var _super = _createSuper(_default); + function _default() { + _classCallCheck(this, _default); + return _super.apply(this, arguments); + } + _createClass(_default, [{ + key: "initialize", + value: function initialize() { + this.messagesAPI = new _messages.default(this.idValue); + this.webChatChannel = new _webchat_channel.default(this.idValue, _hellotext.default.session, this.conversationIdValue); + this.files = []; + this.onMessageReceived = this.onMessageReceived.bind(this); + this.onConversationAssignment = this.onConversationAssignment.bind(this); + this.onAgentOnline = this.onAgentOnline.bind(this); + this.onMessageReaction = this.onMessageReaction.bind(this); + this.onScroll = this.onScroll.bind(this); + _get(_getPrototypeOf(_default.prototype), "initialize", this).call(this); + } + }, { + key: "connect", + value: function connect() { + (0, _usePopover.usePopover)(this); + this.popoverTarget.classList.add(..._webchat.Webchat.classes); + this.triggerTarget.classList.add(..._webchat.Webchat.triggerClasses); + this.setupFloatingUI({ + trigger: this.triggerTarget, + popover: this.popoverTarget + }); + this.webChatChannel.onMessage(this.onMessageReceived); + this.webChatChannel.onConversationAssignment(this.onConversationAssignment); + this.webChatChannel.onAgentOnline(this.onAgentOnline); + this.webChatChannel.onReaction(this.onMessageReaction); + this.messagesContainerTarget.addEventListener('scroll', this.onScroll); + if (!_hellotext.default.business.features.white_label) { + this.toolbarTarget.appendChild(_logo_builder.LogoBuilder.build()); + } + if (localStorage.getItem("hellotext--webchat--".concat(this.idValue)) === 'opened') { + this.openValue = true; + } + _hellotext.default.eventEmitter.dispatch('webchat:mounted'); + _get(_getPrototypeOf(_default.prototype), "connect", this).call(this); + } + }, { + key: "disconnect", + value: function disconnect() { + this.messagesContainerTarget.removeEventListener('scroll', this.onScroll); + this.floatingUICleanup(); + _get(_getPrototypeOf(_default.prototype), "disconnect", this).call(this); + } + }, { + key: "onScroll", + value: function () { + var _onScroll = _asyncToGenerator(function* () { + if (this.messagesContainerTarget.scrollTop > 300 || !this.nextPageValue || this.fetchingNextPage) return; + this.fetchingNextPage = true; + var response = yield this.messagesAPI.index({ + page: this.nextPageValue, + session: _hellotext.default.session + }); + var { + next: nextPage, + messages + } = yield response.json(); + this.nextPageValue = nextPage; + this.oldScrollHeight = this.messagesContainerTarget.scrollHeight; + messages.forEach(message => { + var { + body, + attachments + } = message; + var div = document.createElement('div'); + div.innerHTML = body; + var element = this.messageTemplateTarget.cloneNode(true); + element.setAttribute('data-hellotext--webchat-target', 'message'); + element.style.removeProperty('display'); + element.querySelector('[data-body]').innerHTML = div.innerHTML; + if (message.state === 'received') { + element.classList.add('received'); + } else { + element.classList.remove('received'); + } + if (attachments) { + attachments.forEach(attachmentUrl => { + var image = this.attachmentImageTarget.cloneNode(true); + image.removeAttribute('data-hellotext--webchat-target'); + image.src = attachmentUrl; + image.style.display = 'block'; + element.querySelector('[data-attachment-container]').appendChild(image); + }); + } + element.setAttribute('data-body', body); + this.messagesContainerTarget.prepend(element); + }); + this.messagesContainerTarget.scroll({ + top: this.messagesContainerTarget.scrollHeight - this.oldScrollHeight, + behavior: 'instant' + }); + this.fetchingNextPage = false; + }); + function onScroll() { + return _onScroll.apply(this, arguments); + } + return onScroll; + }() + }, { + key: "onClickOutside", + value: function onClickOutside(event) { + if (_webchat.Webchat.behaviour === _webchat.behaviors.POPOVER && this.openValue && event.target.nodeType && this.element.contains(event.target) === false) { + this.openValue = false; + } + } + }, { + key: "onPopoverOpened", + value: function onPopoverOpened() { + this.inputTarget.focus(); + if (!this.scrolled) { + this.messagesContainerTarget.scroll({ + top: this.messagesContainerTarget.scrollHeight, + behavior: 'instant' + }); + this.scrolled = true; + } + _hellotext.default.eventEmitter.dispatch('webchat:opened'); + localStorage.setItem("hellotext--webchat--".concat(this.idValue), 'opened'); + this.unreadCounterTarget.style.display = 'none'; + this.unreadCounterTarget.innerText = '0'; + } + }, { + key: "onPopoverClosed", + value: function onPopoverClosed() { + _hellotext.default.eventEmitter.dispatch('webchat:closed'); + setTimeout(() => { + this.inputTarget.value = ""; + }); + localStorage.setItem("hellotext--webchat--".concat(this.idValue), 'closed'); + } + }, { + key: "onMessageReaction", + value: function onMessageReaction(message) { + var { + message: messageId, + reaction, + type + } = message; + var messageElement = this.messageTargets.find(element => element.dataset.id === messageId); + var reactionsContainer = messageElement.querySelector('[data-reactions]'); + if (type === 'reaction.destroy') { + var reactionElement = reactionsContainer.querySelector("[data-id=\"".concat(reaction.id, "\"]")); + return reactionElement.remove(); + } + if (reactionsContainer.querySelector("[data-id=\"".concat(reaction.id, "\"]"))) { + var _reactionElement = reactionsContainer.querySelector("[data-id=\"".concat(reaction.id, "\"]")); + _reactionElement.innerText = reaction.emoji; + } else { + var _reactionElement2 = document.createElement('span'); + _reactionElement2.innerText = reaction.emoji; + _reactionElement2.setAttribute('data-id', reaction.id); + reactionsContainer.appendChild(_reactionElement2); + } + } + }, { + key: "onMessageReceived", + value: function onMessageReceived(message) { + var { + body, + attachments + } = message; + var div = document.createElement('div'); + div.innerHTML = body; + var element = this.messageTemplateTarget.cloneNode(true); + element.style.display = 'flex'; + element.querySelector('[data-body]').innerHTML = div.innerHTML; + element.setAttribute('data-hellotext--webchat-target', 'message'); + if (attachments) { + attachments.forEach(attachmentUrl => { + var image = this.attachmentImageTarget.cloneNode(true); + image.src = attachmentUrl; + image.style.display = 'block'; + element.querySelector('[data-attachment-container]').appendChild(image); + }); + } + this.messagesContainerTarget.appendChild(element); + _hellotext.default.eventEmitter.dispatch('webchat:message:received', _objectSpread(_objectSpread({}, message), {}, { + body: element.querySelector('[data-body]').innerText + })); + element.scrollIntoView({ + behavior: 'smooth' + }); + this.setOfflineTimeout(); + if (this.openValue) return; + this.unreadCounterTarget.style.display = 'flex'; + var unreadCount = (parseInt(this.unreadCounterTarget.innerText) || 0) + 1; + this.unreadCounterTarget.innerText = unreadCount > 99 ? '99+' : unreadCount; + } + }, { + key: "onConversationAssignment", + value: function onConversationAssignment(conversation) { + var { + to: user + } = conversation; + this.titleTarget.innerText = user.name; + if (user.online) { + this.onlineStatusTarget.style.display = 'flex'; + } else { + this.onlineStatusTarget.style.display = 'none'; + } + } + }, { + key: "onAgentOnline", + value: function onAgentOnline() { + this.onlineStatusTarget.style.display = 'flex'; + this.setOfflineTimeout(); + } + }, { + key: "sendMessage", + value: function () { + var _sendMessage = _asyncToGenerator(function* () { + var formData = new FormData(); + var message = { + body: this.inputTarget.value, + attachments: this.files + }; + formData.append('message[body]', this.inputTarget.value); + this.files.forEach(file => { + formData.append('message[attachments][]', file); + }); + formData.append('session', _hellotext.default.session); + var element = this.messageTemplateTarget.cloneNode(true); + element.classList.add('received'); + element.style.removeProperty('display'); + element.setAttribute('data-hellotext--webchat-target', 'message'); + element.querySelector('[data-body]').innerText = this.inputTarget.value; + var attachments = this.attachmentContainerTarget.querySelectorAll('img'); + if (attachments.length > 0) { + attachments.forEach(attachment => { + element.querySelector('[data-attachment-container]').appendChild(attachment); + }); + } + this.messagesContainerTarget.appendChild(element); + element.scrollIntoView({ + behavior: 'smooth' + }); + this.inputTarget.value = ""; + this.files = []; + this.attachmentContainerTarget.innerHTML = ""; + this.attachmentContainerTarget.classList.add("hidden"); + this.inputTarget.focus(); + var response = yield this.messagesAPI.create(formData); + if (response.failed) { + return element.classList.add('failed'); + } + var data = yield response.json(); + element.setAttribute('data-id', data.id); + message.id = data.id; + _hellotext.default.eventEmitter.dispatch('webchat:message:sent', message); + if (data.conversation !== this.conversationIdValue) { + this.conversationIdValue = data.conversation; + this.webChatChannel.updateSubscriptionWith(this.conversationIdValue); + } + }); + function sendMessage() { + return _sendMessage.apply(this, arguments); + } + return sendMessage; + }() + }, { + key: "openAttachment", + value: function openAttachment() { + this.attachmentInputTarget.click(); + } + }, { + key: "onFileInputChange", + value: function onFileInputChange() { + this.errorMessageContainerTarget.classList.add('hidden'); + this.files = Array.from(this.attachmentInputTarget.files); + var fileMaxSizeTooMuch = this.files.find(file => { + var type = file.type.split("/")[0]; + if (['image', 'video', 'audio'].includes(type)) { + return this.mediaValue[type].max_size < file.size; + } else { + return this.mediaValue.document.max_size < file.size; + } + }); + if (fileMaxSizeTooMuch) { + var type = fileMaxSizeTooMuch.type.split("/")[0]; + var mediaType = ['image', 'audio', 'video'].includes(type) ? type : 'document'; + this.errorMessageContainerTarget.innerText = this.fileSizeErrorMessageValue.replace('%{limit}', this.byteToMegabyte(this.mediaValue[mediaType].max_size)); + return; + } + this.errorMessageContainerTarget.innerText = ""; + this.files.forEach(file => this.createAttachmentElement(file)); + this.inputTarget.focus(); + } + }, { + key: "createAttachmentElement", + value: function createAttachmentElement(file) { + var element = this.attachmentElement(); + this.attachmentContainerTarget.classList.remove('hidden'); + element.setAttribute('data-name', file.name); + if (file.type.startsWith("image/")) { + var thumbnail = this.attachmentImageTarget.cloneNode(true); + thumbnail.src = URL.createObjectURL(file); + thumbnail.style.display = 'block'; + element.appendChild(thumbnail); + this.attachmentContainerTarget.appendChild(element); + this.attachmentContainerTarget.style.display = 'flex'; + } else { + element.querySelector("main").classList.add(...this.widthClasses, "h-20", "rounded-md", "bg-gray-200", "p-1"); + element.querySelector("p[data-attachment-name]").innerText = file.name; + } + } + }, { + key: "removeAttachment", + value: function removeAttachment(_ref) { + var { + currentTarget + } = _ref; + var attachment = currentTarget.closest("[data-hellotext--webchat-target='attachment']"); + this.files = this.files.filter(file => file.name !== attachment.dataset.name); + attachment.remove(); + this.inputTarget.focus(); + } + }, { + key: "attachmentTargetDisconnected", + value: function attachmentTargetDisconnected() { + if (this.attachmentTargets.length === 0) { + this.attachmentContainerTarget.innerHTML = ""; + this.attachmentContainerTarget.style.display = 'none'; + } + } + }, { + key: "attachmentElement", + value: function attachmentElement() { + var element = this.attachmentTemplateTarget.cloneNode(true); + element.removeAttribute("hidden"); + element.style.display = 'flex'; + element.setAttribute("data-hellotext--webchat-target", "attachment"); + return element; + } + }, { + key: "onEmojiSelect", + value: function onEmojiSelect(_ref2) { + var { + detail: emoji + } = _ref2; + var value = this.inputTarget.value; + var start = this.inputTarget.selectionStart; + var end = this.inputTarget.selectionEnd; + this.inputTarget.value = value.slice(0, start) + emoji + value.slice(end); + this.inputTarget.selectionStart = this.inputTarget.selectionEnd = start + emoji.length; + this.inputTarget.focus(); + } + }, { + key: "setOfflineTimeout", + value: function setOfflineTimeout() { + clearTimeout(this.offlineTimeout); + this.offlineTimeout = setTimeout(() => { + this.onlineStatusTarget.style.display = 'none'; + }, this.fiveMinutes); + } + }, { + key: "byteToMegabyte", + value: function byteToMegabyte(bytes) { + return Math.ceil(bytes / 1024 / 1024); + } + }, { + key: "fiveMinutes", + get: function get() { + return 300000; + } + }, { + key: "middlewares", + get: function get() { + return [(0, _dom.offset)(5), (0, _dom.shift)({ + padding: 24 + }), (0, _dom.flip)()]; + } + }]); + return _default; +}(_stimulus.Controller); +exports.default = _default; +_default.values = { + id: String, + conversationId: String, + media: Object, + fileSizeErrorMessage: String, + placement: { + type: String, + default: "bottom-end" + }, + open: { + type: Boolean, + default: false + }, + autoPlacement: { + type: Boolean, + default: false + }, + disabled: { + type: Boolean, + default: false + }, + nextPage: { + type: Number, + default: undefined + } +}; +_default.targets = ['trigger', 'popover', 'input', 'attachmentInput', 'attachmentButton', 'errorMessageContainer', 'attachmentTemplate', 'attachmentContainer', 'attachment', 'messageTemplate', 'messagesContainer', 'title', 'onlineStatus', 'attachmentImage', 'footer', 'toolbar', 'message', 'unreadCounter']; \ No newline at end of file diff --git a/lib/core/configuration.js b/lib/core/configuration.js index 2ddf0b5..7231d46 100644 --- a/lib/core/configuration.js +++ b/lib/core/configuration.js @@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", { }); exports.Configuration = void 0; var _forms = require("./configuration/forms"); +var _webchat = require("./configuration/webchat"); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } @@ -17,6 +18,7 @@ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === * @property {Boolean} [autoGenerateSession=true] - whether to auto generate session or not * @property {String} [session] - session id * @property {Forms} [forms] - form configuration + * @property {Webchat} [webchat] - webchat configuration */ var Configuration = /*#__PURE__*/function () { function Configuration() { @@ -39,6 +41,8 @@ var Configuration = /*#__PURE__*/function () { var [key, value] = _ref; if (key === 'forms') { this.forms = _forms.Forms.assign(value); + } else if (key === 'webChat') { + this.webchat = _webchat.Webchat.assign(value); } else { this[key] = value; } @@ -58,4 +62,5 @@ exports.Configuration = Configuration; Configuration.apiRoot = 'https://api.hellotext.com/v1'; Configuration.autoGenerateSession = true; Configuration.session = null; -Configuration.forms = _forms.Forms; \ No newline at end of file +Configuration.forms = _forms.Forms; +Configuration.webchat = _webchat.Webchat; \ No newline at end of file diff --git a/lib/core/configuration/web_chat.js b/lib/core/configuration/web_chat.js new file mode 100644 index 0000000..8078e63 --- /dev/null +++ b/lib/core/configuration/web_chat.js @@ -0,0 +1,168 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.behaviors = exports.WebChat = void 0; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +/** + * @typedef {'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'} Placement + * @description Valid placements for the webchat. + */ + +/** + * @enum {Placement} + */ +var placements = { + TOP_LEFT: 'top-left', + TOP_RIGHT: 'top-right', + BOTTOM_LEFT: 'bottom-left', + BOTTOM_RIGHT: 'bottom-right' +}; + +/** + * @typedef {'modal' | 'popover'} Behaviour + */ + +/** + * @enum {Behaviour} + */ +var behaviors = { + MODAL: 'modal', + POPOVER: 'popover' +}; + +/** + * @typedef {Object} Style + * @property {string} background - The background color or style (e.g., a hex code or color name). + * @property {string} foreground - The foreground color or style (e.g., a hex code or color name). + * @property {string} typography - The typography style (e.g., font family). + */ + +/** + * @class WebChat + * @classdesc + * Configuration for webchat + * @property {String} id - the id of the webchat. + * @property {String} container - the container to append the webchat to, defaults to 'body' + * @property {Placement} placement - the placement of the webchat within the container, defaults to "bottom-right". + * @property {String} classes - additional classes to apply to the webchat popup. + * @property {String} triggerClasses - additional classes to apply to the webchat popup trigger. + * @property {Behaviour} behaviour - the behaviour of the webchat, defaults to 'popover'. + * @property {Style} style - the style of the webchat. + */ +exports.behaviors = behaviors; +var WebChat = /*#__PURE__*/function () { + function WebChat() { + _classCallCheck(this, WebChat); + } + _createClass(WebChat, null, [{ + key: "container", + get: function get() { + return this._container; + }, + set: function set(value) { + this._container = value; + } + }, { + key: "placement", + get: function get() { + return this._placement; + }, + set: function set(value) { + if (!Object.values(placements).includes(value)) { + throw new Error("Invalid placement value: ".concat(value)); + } + this._placement = value; + } + }, { + key: "classes", + get: function get() { + if (typeof this._classes === 'string') { + return this._classes.split(',').map(c => c.trim()); + } else { + return this._classes; + } + }, + set: function set(value) { + if (!Array.isArray(value) && typeof value !== 'string') { + throw new Error('classes must be an array or a string'); + } + this._classes = value; + } + }, { + key: "triggerClasses", + get: function get() { + if (typeof this._triggerClasses === 'string') { + return this._triggerClasses.split(',').map(c => c.trim()); + } else { + return this._triggerClasses; + } + }, + set: function set(value) { + if (!Array.isArray(value) && typeof value !== 'string') { + throw new Error('triggerClasses must be an array or a string'); + } + this._triggerClasses = value; + } + }, { + key: "id", + get: function get() { + return this._id; + }, + set: function set(value) { + this._id = value; + } + }, { + key: "isSet", + get: function get() { + return !!this._id; + } + }, { + key: "style", + get: function get() { + return this._style; + }, + set: function set(value) { + if (typeof value !== 'object') { + throw new Error('Style must be an object'); + } + this._style = value; + } + }, { + key: "behaviour", + get: function get() { + return this._behaviour; + }, + set: function set(value) { + if (!Object.values(behaviors).includes(value)) { + throw new Error("Invalid behaviour value: ".concat(value)); + } + this._behaviour = value; + } + }, { + key: "assign", + value: function assign(props) { + if (props) { + Object.entries(props).forEach(_ref => { + var [key, value] = _ref; + this[key] = value; + }); + } + return this; + } + }]); + return WebChat; +}(); +exports.WebChat = WebChat; +WebChat._id = void 0; +WebChat._container = 'body'; +WebChat._placement = 'bottom-right'; +WebChat._classes = []; +WebChat._triggerClasses = []; +WebChat._style = {}; +WebChat._behaviour = behaviors.POPOVER; \ No newline at end of file diff --git a/lib/core/configuration/webchat.js b/lib/core/configuration/webchat.js new file mode 100644 index 0000000..2c6012b --- /dev/null +++ b/lib/core/configuration/webchat.js @@ -0,0 +1,185 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.behaviors = exports.Webchat = void 0; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +/** + * @typedef {'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'} Placement + * @description Valid placements for the webchat. + */ + +/** + * @enum {Placement} + */ +var placements = { + TOP_LEFT: 'top-left', + TOP_RIGHT: 'top-right', + BOTTOM_LEFT: 'bottom-left', + BOTTOM_RIGHT: 'bottom-right' +}; + +/** + * @typedef {'modal' | 'popover'} Behaviour + */ + +/** + * @enum {Behaviour} + */ +var behaviors = { + MODAL: 'modal', + POPOVER: 'popover' +}; + +/** + * @typedef {Object} Style + * @property {string} primaryColor - The primary webchat color (e.g., a hex code or color name). + * @property {string} secondaryColor - The secondary webchat color or style (e.g., a hex code or color name). + * @property {string} typography - The typography style (e.g., font family). + */ + +/** + * @class Webchat + * @classdesc + * Configuration for webchat + * @property {String} id - the id of the webchat. + * @property {String} container - the container to append the webchat to, defaults to 'body' + * @property {Placement} placement - the placement of the webchat within the container, defaults to "bottom-right". + * @property {String} classes - additional classes to apply to the webchat popup. + * @property {String} triggerClasses - additional classes to apply to the webchat popup trigger. + * @property {Behaviour} behaviour - the behaviour of the webchat, defaults to 'popover'. + * @property {Style} style - the style of the webchat. + */ +exports.behaviors = behaviors; +var Webchat = /*#__PURE__*/function () { + function Webchat() { + _classCallCheck(this, Webchat); + } + _createClass(Webchat, null, [{ + key: "container", + get: function get() { + return this._container; + }, + set: function set(value) { + this._container = value; + } + }, { + key: "placement", + get: function get() { + return this._placement; + }, + set: function set(value) { + if (!Object.values(placements).includes(value)) { + throw new Error("Invalid placement value: ".concat(value)); + } + this._placement = value; + } + }, { + key: "classes", + get: function get() { + if (typeof this._classes === 'string') { + return this._classes.split(',').map(c => c.trim()); + } else { + return this._classes; + } + }, + set: function set(value) { + if (!Array.isArray(value) && typeof value !== 'string') { + throw new Error('classes must be an array or a string'); + } + this._classes = value; + } + }, { + key: "triggerClasses", + get: function get() { + if (typeof this._triggerClasses === 'string') { + return this._triggerClasses.split(',').map(c => c.trim()); + } else { + return this._triggerClasses; + } + }, + set: function set(value) { + if (!Array.isArray(value) && typeof value !== 'string') { + throw new Error('triggerClasses must be an array or a string'); + } + this._triggerClasses = value; + } + }, { + key: "id", + get: function get() { + return this._id; + }, + set: function set(value) { + this._id = value; + } + }, { + key: "isSet", + get: function get() { + return !!this._id; + } + }, { + key: "style", + get: function get() { + return this._style; + }, + set: function set(value) { + if (typeof value !== 'object') { + throw new Error('Style must be an object'); + } + Object.entries(value).forEach(_ref => { + var [key, value] = _ref; + if (!['primaryColor', 'secondaryColor', 'typography'].includes(key)) { + throw new Error("Invalid style property: ".concat(key)); + } + if (key === 'typography') { + return; + } + if (!this.isHexOrRgba(value)) { + throw new Error("Invalid color value: ".concat(value, " for ").concat(key, ". Colors must be hex or rgb/a.")); + } + }); + this._style = value; + } + }, { + key: "behaviour", + get: function get() { + return this._behaviour; + }, + set: function set(value) { + if (!Object.values(behaviors).includes(value)) { + throw new Error("Invalid behaviour value: ".concat(value)); + } + this._behaviour = value; + } + }, { + key: "assign", + value: function assign(props) { + if (props) { + Object.entries(props).forEach(_ref2 => { + var [key, value] = _ref2; + this[key] = value; + }); + } + return this; + } + }, { + key: "isHexOrRgba", + value: function isHexOrRgba(value) { + return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(value) || /^rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3},?\s*(0|1|0?\.\d+)?\s*\)$/.test(value); + } + }]); + return Webchat; +}(); +exports.Webchat = Webchat; +Webchat._id = void 0; +Webchat._container = 'body'; +Webchat._placement = 'bottom-right'; +Webchat._classes = []; +Webchat._triggerClasses = []; +Webchat._style = {}; +Webchat._behaviour = behaviors.POPOVER; \ No newline at end of file diff --git a/lib/core/event.js b/lib/core/event.js index 5b17b4b..c87da2d 100644 --- a/lib/core/event.js +++ b/lib/core/event.js @@ -70,4 +70,4 @@ var Event = /*#__PURE__*/function () { return Event; }(); exports.default = Event; -Event.events = ['session-set', 'forms:collected', 'form:completed']; \ No newline at end of file +Event.events = ['session-set', 'forms:collected', 'form:completed', 'webchat:mounted', 'webchat:opened', 'webchat:closed', 'webchat:message:sent', 'webchat:message:received']; \ No newline at end of file diff --git a/lib/hellotext.js b/lib/hellotext.js index 3521ee3..50926ec 100644 --- a/lib/hellotext.js +++ b/lib/hellotext.js @@ -37,14 +37,22 @@ var Hellotext = /*#__PURE__*/function () { * @param business public business id * @param { Configuration } config */ - function initialize(business, config) { - _core.Configuration.assign(config); - _models.Session.initialize(); - _classPrivateFieldLooseBase(this, _query)[_query] = new _models.Query(); - this.business = new _models.Business(business); - this.forms = new _models.FormCollection(); - } - + function () { + var _initialize = _asyncToGenerator(function* (business, config) { + _core.Configuration.assign(config); + _models.Session.initialize(); + _classPrivateFieldLooseBase(this, _query)[_query] = new _models.Query(); + this.business = new _models.Business(business); + this.forms = new _models.FormCollection(); + if (_core.Configuration.webchat.id) { + this.webchat = yield _models.Webchat.load(_core.Configuration.webchat.id); + } + }); + function initialize(_x, _x2) { + return _initialize.apply(this, arguments); + } + return initialize; + }() /** * Tracks an action that has happened on the page * @@ -73,7 +81,7 @@ var Hellotext = /*#__PURE__*/function () { body }); }); - function track(_x) { + function track(_x3) { return _track.apply(this, arguments); } return track; @@ -152,5 +160,6 @@ Object.defineProperty(Hellotext, _query, { Hellotext.eventEmitter = new _core.Event(); Hellotext.forms = void 0; Hellotext.business = void 0; +Hellotext.webchat = void 0; var _default = Hellotext; exports.default = _default; \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index 9c4b46b..ba23750 100644 --- a/lib/index.js +++ b/lib/index.js @@ -7,10 +7,14 @@ exports.default = void 0; var _stimulus = require("@hotwired/stimulus"); var _hellotext = _interopRequireDefault(require("./hellotext")); var _form_controller = _interopRequireDefault(require("./controllers/form_controller")); +var _webchat_controller = _interopRequireDefault(require("./controllers/webchat_controller")); +var _emoji_picker_controller = _interopRequireDefault(require("./controllers/webchat/emoji_picker_controller")); require("../styles/index.css"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var application = _stimulus.Application.start(); application.register('hellotext--form', _form_controller.default); +application.register('hellotext--webchat', _webchat_controller.default); +application.register('hellotext--webchat--emoji', _emoji_picker_controller.default); window.Hellotext = _hellotext.default; var _default = _hellotext.default; exports.default = _default; \ No newline at end of file diff --git a/lib/models/business.js b/lib/models/business.js index d1cde40..9dbfbe3 100644 --- a/lib/models/business.js +++ b/lib/models/business.js @@ -49,7 +49,15 @@ var Business = /*#__PURE__*/function () { }, { key: "fetchPublicData", value: function fetchPublicData() { - _businesses.default.get(this.id).then(response => response.json()).then(data => this.data = data); + _businesses.default.get(this.id).then(response => response.json()).then(data => { + this.data = data; + if (typeof document !== 'undefined') { + var linkTag = document.createElement('link'); + linkTag.rel = 'stylesheet'; + linkTag.href = data.style_url; + document.head.append(linkTag); + } + }); } }]); return Business; diff --git a/lib/models/index.js b/lib/models/index.js index 7e9d61c..77e171c 100644 --- a/lib/models/index.js +++ b/lib/models/index.js @@ -39,9 +39,16 @@ Object.defineProperty(exports, "Session", { return _session.Session; } }); +Object.defineProperty(exports, "Webchat", { + enumerable: true, + get: function get() { + return _webchat.Webchat; + } +}); var _business = require("./business"); var _form = require("./form"); var _query = require("./query"); var _cookies = require("./cookies"); var _form_collection = require("./form_collection"); +var _webchat = require("./webchat"); var _session = require("./session"); \ No newline at end of file diff --git a/lib/models/web_chat.js b/lib/models/web_chat.js new file mode 100644 index 0000000..7d767ed --- /dev/null +++ b/lib/models/web_chat.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.WebChat = void 0; +var _hellotext = _interopRequireDefault(require("../hellotext")); +var _core = require("../core"); +var _api = _interopRequireDefault(require("../api")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var WebChat = /*#__PURE__*/function () { + function WebChat(data) { + _classCallCheck(this, WebChat); + this.data = data; + this.render(); + } + _createClass(WebChat, [{ + key: "render", + value: function render() { + this.containerToAppendTo.appendChild(this.data.html); + } + }, { + key: "containerToAppendTo", + get: function get() { + return document.querySelector(_core.Configuration.webChat.container); + } + }], [{ + key: "load", + value: function () { + var _load = _asyncToGenerator(function* (id) { + return new WebChat({ + id, + html: yield _api.default.webChats.get(id) + }); + }); + function load(_x) { + return _load.apply(this, arguments); + } + return load; + }() + }]); + return WebChat; +}(); +exports.WebChat = WebChat; \ No newline at end of file diff --git a/lib/models/webchat.js b/lib/models/webchat.js new file mode 100644 index 0000000..5f923c0 --- /dev/null +++ b/lib/models/webchat.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Webchat = void 0; +var _hellotext = _interopRequireDefault(require("../hellotext")); +var _core = require("../core"); +var _api = _interopRequireDefault(require("../api")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var Webchat = /*#__PURE__*/function () { + function Webchat(data) { + _classCallCheck(this, Webchat); + this.data = data; + this.render(); + } + _createClass(Webchat, [{ + key: "render", + value: function render() { + this.containerToAppendTo.appendChild(this.data.html); + } + }, { + key: "containerToAppendTo", + get: function get() { + return document.querySelector(_core.Configuration.webchat.container); + } + }], [{ + key: "load", + value: function () { + var _load = _asyncToGenerator(function* (id) { + return new Webchat({ + id, + html: yield _api.default.webchats.get(id) + }); + }); + function load(_x) { + return _load.apply(this, arguments); + } + return load; + }() + }]); + return Webchat; +}(); +exports.Webchat = Webchat; \ No newline at end of file diff --git a/package.json b/package.json index 75e299f..1957028 100644 --- a/package.json +++ b/package.json @@ -14,18 +14,19 @@ "devDependencies": { "@babel/cli": "^7.20.7", "@babel/core": "^7.20.12", + "@babel/plugin-proposal-export-default-from": "^7.20.0", "@babel/plugin-proposal-private-methods": "^7.18.6", "@babel/preset-env": "^7.20.2", - "@babel/plugin-proposal-export-default-from": "^7.20.0", "@testing-library/jest-dom": "^5.16.5", "babel-loader": "^9.1.2", + "css-loader": "^6.5.0", "jest": "^29.3.1", "jest-environment-jsdom": "^29.3.1", "prettier": "2.8.2", + "style-loader": "^3.3.1", "webpack": "^5.75.0", "webpack-cli": "^5.0.1", - "style-loader": "^3.3.1", - "css-loader": "^6.5.0" + "whatwg-fetch": "^3.6.20" }, "repository": { "type": "git", @@ -45,8 +46,8 @@ "url": "https://github.com/hellotext/hellotext.js/issues" }, "dependencies": { - "core-js": "3.27.2", - "whatwg-fetch": "^3.6.2", - "@hotwired/stimulus": "^3.0.0" + "@floating-ui/dom": "^1.6.12", + "@hotwired/stimulus": "^3.0.0", + "emoji-mart": "^5.6.0" } } diff --git a/src/api/index.js b/src/api/index.js index 1ff73c8..8cb289f 100644 --- a/src/api/index.js +++ b/src/api/index.js @@ -1,6 +1,7 @@ import BusinessesAPI from './businesses' import EventsAPI from './events' import FormsAPI from './forms' +import WebchatsAPI from './webchats' export default class API { static get businesses() { @@ -14,6 +15,10 @@ export default class API { static get forms() { return FormsAPI } + + static get webchats() { + return WebchatsAPI + } } export { Response } from './response' diff --git a/src/api/webchat/messages.js b/src/api/webchat/messages.js new file mode 100644 index 0000000..529676e --- /dev/null +++ b/src/api/webchat/messages.js @@ -0,0 +1,45 @@ +import Hellotext from '../../hellotext' +import { Configuration } from '../../core' + +import { Response } from '../response' + +class WebchatMessagesAPI { + static get endpoint() { + return Configuration.endpoint(`public/webchats/:id/messages`) + } + + constructor(webchatId) { + this.webchatId = webchatId + } + + async index(params) { + const url = new URL(this.url) + + Object.entries(params).forEach(([key, value]) => { + url.searchParams.append(key, value) + }) + + return await fetch(url, { + method: 'GET', + headers: Hellotext.headers, + }) + } + + async create(formData) { + const response = await fetch(this.url, { + method: 'POST', + headers: { + Authorization: `Bearer ${Hellotext.business.id}`, + }, + body: formData + }) + + return new Response(response.ok, response) + } + + get url() { + return WebchatMessagesAPI.endpoint.replace(':id', this.webchatId) + } +} + +export default WebchatMessagesAPI diff --git a/src/api/webchats.js b/src/api/webchats.js new file mode 100644 index 0000000..6762634 --- /dev/null +++ b/src/api/webchats.js @@ -0,0 +1,30 @@ +import Hellotext from '../hellotext' +import { Configuration } from '../core' + +class WebchatsAPI { + static get endpoint() { + return Configuration.endpoint('public/webchats') + } + + static async get(id) { + const url = new URL(`${this.endpoint}/${id}`) + + url.searchParams.append('session', Hellotext.session) + + Object.entries(Configuration.webchat.style).forEach(([key, value]) => { + url.searchParams.append(`style[${key}]`, value) + }) + + url.searchParams.append('placement', Configuration.webchat.placement) + + const response = await fetch(url, { + method: 'GET', + headers: Hellotext.headers, + }) + + const htmlText = await response.text() + return (new DOMParser()).parseFromString(htmlText, "text/html").querySelector('article'); + } +} + +export default WebchatsAPI diff --git a/src/builders/logo_builder.js b/src/builders/logo_builder.js index 1dd6a66..cf245be 100644 --- a/src/builders/logo_builder.js +++ b/src/builders/logo_builder.js @@ -9,14 +9,18 @@ class LogoBuilder { } static #template() { + const url = `https://www.hellotext.com?hello_session=${Hellotext.session}` + return `
${Hellotext.business.locale.white_label.powered_by} - - Hellotext - - + + + Hellotext + + +
` } diff --git a/src/channels/application_channel.js b/src/channels/application_channel.js new file mode 100644 index 0000000..bfdcae1 --- /dev/null +++ b/src/channels/application_channel.js @@ -0,0 +1,45 @@ +class ApplicationChannel { + static webSocket; + + send({ command, identifier }) { + const data = { + command, + identifier: JSON.stringify(identifier) + } + + if (this.webSocket.readyState === WebSocket.OPEN) { + this.webSocket.send(JSON.stringify(data)) + } else { + this.webSocket.addEventListener('open', () => { + this.webSocket.send(JSON.stringify(data)) + }) + } + } + + onMessage(callback) { + this.webSocket.addEventListener('message', (event) => { + const data = JSON.parse(event.data) + const { type, message } = data + + if (this.ignoredEvents.includes(type)) { + return; + } + + callback(message) + }) + } + + get webSocket() { + if (!ApplicationChannel.webSocket) { + return ApplicationChannel.webSocket = new WebSocket("ws://localhost:3000/cable") + } + + return ApplicationChannel.webSocket + } + + get ignoredEvents() { + return ['ping', 'confirm_subscription', 'welcome'] + } +} + +export default ApplicationChannel diff --git a/src/channels/webchat_channel.js b/src/channels/webchat_channel.js new file mode 100644 index 0000000..d331db3 --- /dev/null +++ b/src/channels/webchat_channel.js @@ -0,0 +1,77 @@ +import ApplicationChannel from './application_channel' + +class WebchatChannel extends ApplicationChannel { + constructor(id, session, conversation) { + super() + + this.id = id + this.session = session + this.conversation = conversation + + this.subscribe() + } + + subscribe() { + const params = { + channel: "WebchatChannel", + id: this.id, + session: this.session, + conversation: this.conversation, + } + + this.send( { command: 'subscribe', identifier: params }) + } + + unsubscribe() { + const params = { + channel: "WebchatChannel", + id: this.id, + session: this.session, + conversation: this.conversation, + } + + this.send({ command: 'unsubscribe', identifier: params }) + } + + onMessage(callback) { + super.onMessage((message) => { + if(message.type !== 'message') return + callback(message) + }) + } + + onConversationAssignment(callback) { + super.onMessage((message) => { + if(message.type === 'conversation.assigned') { + callback(message) + } + }) + } + + onAgentOnline(callback) { + super.onMessage((message) => { + if(message.type === 'agent_is_online') { + callback(message) + } + }) + } + + onReaction(callback) { + super.onMessage((message) => { + if(message.type === 'reaction.create' || message.type === 'reaction.destroy') { + callback(message) + } + }) + } + + updateSubscriptionWith(conversation) { + this.unsubscribe() + + setTimeout(() => { + this.conversation = conversation + this.subscribe() + }, 1000) + } +} + +export default WebchatChannel diff --git a/src/controllers/mixins/usePopover.js b/src/controllers/mixins/usePopover.js new file mode 100644 index 0000000..9351f50 --- /dev/null +++ b/src/controllers/mixins/usePopover.js @@ -0,0 +1,50 @@ +import { autoUpdate, computePosition } from '@floating-ui/dom' +import Hellotext from "../../hellotext"; + +export const usePopover = (controller) => { + Object.assign(controller, { + show() { + this.openValue = true + }, + hide() { + this.openValue = false + }, + toggle() { + this.openValue = !this.openValue + }, + setupFloatingUI({ trigger, popover }) { + this.floatingUICleanup = autoUpdate(trigger, popover, () => { + computePosition(trigger, popover, { + placement: this.placementValue, + middleware: this.middlewares, + }).then(({x, y}) => { + const newStyle = { + left: `${x}px`, + top: `${y}px` + } + + Object.assign(popover.style, newStyle) + }); + }) + }, + openValueChanged() { + if(this.disabledValue) return + + if(this.openValue) { + this.popoverTarget.showPopover() + this.popoverTarget.setAttribute("aria-expanded", "true") + + if(this['onPopoverOpened']) { + this.onPopoverOpened() + } + } else { + this.popoverTarget.hidePopover() + this.popoverTarget.removeAttribute("aria-expanded") + + if(this['onPopoverClosed']) { + this.onPopoverClosed() + } + } + } + }) +} diff --git a/src/controllers/webchat/emoji_picker_controller.js b/src/controllers/webchat/emoji_picker_controller.js new file mode 100644 index 0000000..90e4f0b --- /dev/null +++ b/src/controllers/webchat/emoji_picker_controller.js @@ -0,0 +1,82 @@ +import { Controller } from '@hotwired/stimulus' +import { computePosition, autoUpdate, shift, autoPlacement, offset } from '@floating-ui/dom' + +import { Picker } from 'emoji-mart' + +import { usePopover } from '../mixins/usePopover' + +export default class extends Controller { + static targets = [ + 'button', + 'popover', + ] + + static values = { + placement: { type: String, default: "bottom-end" }, + open: { type: Boolean, default: false }, + autoPlacement: { type: Boolean, default: false }, + disabled: { type: Boolean, default: false }, + size: { type: Number, default: 24 }, + perLine: { type: Number, default: 9 } + } + + initialize() { + this.onEmojiSelect = this.onEmojiSelect.bind(this) + super.initialize() + } + + connect() { + usePopover(this) + + this.setupFloatingUI({ trigger: this.buttonTarget, popover: this.popoverTarget }) + this.popoverTarget.appendChild(this.pickerObject) + + super.connect() + } + + disconnect() { + this.floatingUICleanup() + super.disconnect() + } + + onEmojiSelect(emoji) { + this.dispatch('selected', { + detail: emoji.native, + }) + + this.hide() + } + + onClickOutside(event) { + if (this.openValue && event.target.nodeType && this.element.contains(event.target) === false) { + this.openValue = false + } + } + + get pickerObject() { + return new Picker({ + onEmojiSelect: this.onEmojiSelect, + theme: 'light', + dynamicWidth: true, + previewPosition: 'none', + skinTonePosition: 'none', + emojiSize: this.sizeValue, + perLine: this.perLineValue, + data: async () => { + const response = await fetch( + 'https://cdn.jsdelivr.net/npm/@emoji-mart/data', + ) + + return response.json() + } + }) + } + + get middlewares() { + return [ + offset(5), + shift({ padding: 24 }), + autoPlacement({ allowedPlacements: ['top', 'bottom' ]}), + ] + } +} diff --git a/src/controllers/webchat_controller.js b/src/controllers/webchat_controller.js new file mode 100644 index 0000000..c04cb79 --- /dev/null +++ b/src/controllers/webchat_controller.js @@ -0,0 +1,445 @@ +import { Controller } from '@hotwired/stimulus' +import { shift, flip, offset } from '@floating-ui/dom' + +import WebchatMessagesAPI from '../api/webchat/messages' +import WebchatChannel from '../channels/webchat_channel' +import Hellotext from "../hellotext" + +import { Webchat as WebchatConfiguration, behaviors } from '../core/configuration/webchat' + +import { usePopover } from './mixins/usePopover' +import { LogoBuilder } from '../builders/logo_builder' +import locales from "../locales"; + +export default class extends Controller { + static values = { + id: String, + conversationId: String, + media: Object, + fileSizeErrorMessage: String, + placement: { type: String, default: "bottom-end" }, + open: { type: Boolean, default: false }, + autoPlacement: { type: Boolean, default: false }, + disabled: { type: Boolean, default: false }, + nextPage: { type: Number, default: undefined }, + } + + static targets = [ + 'trigger', + 'popover', + 'input', + 'attachmentInput', + 'attachmentButton', + 'errorMessageContainer', + 'attachmentTemplate', + 'attachmentContainer', + 'attachment', + 'messageTemplate', + 'messagesContainer', + 'title', + 'onlineStatus', + 'attachmentImage', + 'footer', + 'toolbar', + 'message', + 'unreadCounter', + ] + + initialize() { + this.messagesAPI = new WebchatMessagesAPI(this.idValue) + this.webChatChannel = new WebchatChannel(this.idValue, Hellotext.session, this.conversationIdValue) + this.files = [] + + this.onMessageReceived = this.onMessageReceived.bind(this) + this.onConversationAssignment = this.onConversationAssignment.bind(this) + this.onAgentOnline = this.onAgentOnline.bind(this) + this.onMessageReaction = this.onMessageReaction.bind(this) + + this.onScroll = this.onScroll.bind(this) + + super.initialize() + } + + connect() { + usePopover(this) + + this.popoverTarget.classList.add(...WebchatConfiguration.classes) + this.triggerTarget.classList.add(...WebchatConfiguration.triggerClasses) + + this.setupFloatingUI({ trigger: this.triggerTarget, popover: this.popoverTarget }) + + this.webChatChannel.onMessage(this.onMessageReceived) + this.webChatChannel.onConversationAssignment(this.onConversationAssignment) + + this.webChatChannel.onAgentOnline(this.onAgentOnline) + this.webChatChannel.onReaction(this.onMessageReaction) + + this.messagesContainerTarget.addEventListener('scroll', this.onScroll) + + if (!Hellotext.business.features.white_label) { + this.toolbarTarget.appendChild(LogoBuilder.build()) + } + + if(localStorage.getItem(`hellotext--webchat--${this.idValue}`) === 'opened') { + this.openValue = true + } + + Hellotext.eventEmitter.dispatch('webchat:mounted') + super.connect() + } + + disconnect() { + this.messagesContainerTarget.removeEventListener('scroll', this.onScroll) + this.floatingUICleanup() + + super.disconnect() + } + + async onScroll() { + if(this.messagesContainerTarget.scrollTop > 300 || !this.nextPageValue || this.fetchingNextPage) return + + this.fetchingNextPage = true + const response = await this.messagesAPI.index({ page: this.nextPageValue, session: Hellotext.session }) + + const { next: nextPage, messages } = await response.json() + + this.nextPageValue = nextPage + this.oldScrollHeight = this.messagesContainerTarget.scrollHeight + + messages.forEach(message => { + const { body, attachments } = message + + const div = document.createElement('div') + div.innerHTML = body + + const element = this.messageTemplateTarget.cloneNode(true) + + element.setAttribute('data-hellotext--webchat-target', 'message') + element.style.removeProperty('display') + + element.querySelector('[data-body]').innerHTML = div.innerHTML + + if(message.state === 'received') { + element.classList.add('received') + } else { + element.classList.remove('received') + } + + if(attachments) { + attachments.forEach(attachmentUrl => { + const image = this.attachmentImageTarget.cloneNode(true) + + image.removeAttribute('data-hellotext--webchat-target') + + image.src = attachmentUrl + image.style.display = 'block' + + element.querySelector('[data-attachment-container]').appendChild(image) + }) + } + + element.setAttribute('data-body', body) + this.messagesContainerTarget.prepend(element) + }) + + this.messagesContainerTarget.scroll({ + top: this.messagesContainerTarget.scrollHeight - this.oldScrollHeight, + behavior: 'instant', + }) + + this.fetchingNextPage = false + } + + onClickOutside(event) { + if (WebchatConfiguration.behaviour === behaviors.POPOVER && this.openValue && event.target.nodeType && this.element.contains(event.target) === false) { + this.openValue = false + } + } + + onPopoverOpened() { + this.inputTarget.focus() + + if(!this.scrolled) { + this.messagesContainerTarget.scroll({ + top: this.messagesContainerTarget.scrollHeight, + behavior: 'instant', + }) + + this.scrolled = true + } + + Hellotext.eventEmitter.dispatch('webchat:opened') + + localStorage.setItem(`hellotext--webchat--${this.idValue}`, 'opened') + + this.unreadCounterTarget.style.display = 'none' + this.unreadCounterTarget.innerText = '0' + } + + onPopoverClosed() { + Hellotext.eventEmitter.dispatch('webchat:closed') + + setTimeout(() => { + this.inputTarget.value = "" + }) + + localStorage.setItem(`hellotext--webchat--${this.idValue}`, 'closed') + } + + onMessageReaction(message) { + const { message: messageId, reaction, type } = message + const messageElement = this.messageTargets.find(element => element.dataset.id === messageId) + + const reactionsContainer = messageElement.querySelector('[data-reactions]') + + if(type === 'reaction.destroy') { + const reactionElement = reactionsContainer.querySelector(`[data-id="${reaction.id}"]`) + return reactionElement.remove() + } + + if(reactionsContainer.querySelector(`[data-id="${reaction.id}"]`)) { + const reactionElement = reactionsContainer.querySelector(`[data-id="${reaction.id}"]`) + reactionElement.innerText = reaction.emoji + } else { + const reactionElement = document.createElement('span') + + reactionElement.innerText = reaction.emoji + reactionElement.setAttribute('data-id', reaction.id) + + reactionsContainer.appendChild(reactionElement) + } + } + + onMessageReceived(message) { + const { body, attachments } = message + + const div = document.createElement('div') + div.innerHTML = body + + const element = this.messageTemplateTarget.cloneNode(true) + element.style.display = 'flex' + + element.querySelector('[data-body]').innerHTML = div.innerHTML + element.setAttribute('data-hellotext--webchat-target', 'message') + + if(attachments) { + attachments.forEach(attachmentUrl => { + const image = this.attachmentImageTarget.cloneNode(true) + image.src = attachmentUrl + image.style.display = 'block' + + element.querySelector('[data-attachment-container]').appendChild(image) + }) + } + + this.messagesContainerTarget.appendChild(element) + + Hellotext.eventEmitter.dispatch('webchat:message:received', { + ...message, + body: element.querySelector('[data-body]').innerText, + }) + + element.scrollIntoView({ behavior: 'smooth' }) + this.setOfflineTimeout() + + if(this.openValue) return + + this.unreadCounterTarget.style.display = 'flex' + + const unreadCount = (parseInt(this.unreadCounterTarget.innerText) || 0) + 1 + this.unreadCounterTarget.innerText = unreadCount > 99 ? '99+' : unreadCount + } + + onConversationAssignment(conversation) { + const { to: user } = conversation + + this.titleTarget.innerText = user.name + + if(user.online) { + this.onlineStatusTarget.style.display = 'flex' + } else { + this.onlineStatusTarget.style.display = 'none' + } + } + + onAgentOnline() { + this.onlineStatusTarget.style.display = 'flex' + this.setOfflineTimeout() + } + + async sendMessage() { + const formData = new FormData() + + const message = { + body: this.inputTarget.value, + attachments: this.files + } + + formData.append('message[body]', this.inputTarget.value) + + this.files.forEach(file => { + formData.append('message[attachments][]', file) + }) + + formData.append('session', Hellotext.session) + + const element = this.messageTemplateTarget.cloneNode(true) + + element.classList.add('received') + element.style.removeProperty('display') + + element.setAttribute('data-hellotext--webchat-target', 'message') + element.querySelector('[data-body]').innerText = this.inputTarget.value + + const attachments = this.attachmentContainerTarget.querySelectorAll('img') + + if(attachments.length > 0) { + attachments.forEach(attachment => { + element.querySelector('[data-attachment-container]').appendChild(attachment) + }) + } + + this.messagesContainerTarget.appendChild(element) + element.scrollIntoView({ behavior: 'smooth' }) + + this.inputTarget.value = "" + this.files = [] + this.attachmentContainerTarget.innerHTML = "" + this.attachmentContainerTarget.classList.add("hidden") + + this.inputTarget.focus() + + const response = await this.messagesAPI.create(formData) + + if(response.failed) { + return element.classList.add('failed') + } + + const data = await response.json() + element.setAttribute('data-id', data.id) + message.id = data.id + + Hellotext.eventEmitter.dispatch('webchat:message:sent', message) + + if(data.conversation !== this.conversationIdValue) { + this.conversationIdValue = data.conversation + this.webChatChannel.updateSubscriptionWith(this.conversationIdValue) + } + } + + openAttachment() { + this.attachmentInputTarget.click() + } + + onFileInputChange() { + this.errorMessageContainerTarget.classList.add('hidden') + + this.files = Array.from(this.attachmentInputTarget.files) + + const fileMaxSizeTooMuch = this.files.find(file => { + const type = file.type.split("/")[0] + + if(['image', 'video', 'audio'].includes(type)) { + return this.mediaValue[type].max_size < file.size + } else { + return this.mediaValue.document.max_size < file.size + } + }) + + if(fileMaxSizeTooMuch) { + const type = fileMaxSizeTooMuch.type.split("/")[0] + const mediaType = ['image', 'audio', 'video'].includes(type) ? type : 'document' + + this.errorMessageContainerTarget.innerText = this.fileSizeErrorMessageValue.replace('%{limit}', this.byteToMegabyte(this.mediaValue[mediaType].max_size)) + return + } + + this.errorMessageContainerTarget.innerText = "" + this.files.forEach(file => this.createAttachmentElement(file)) + this.inputTarget.focus() + } + + createAttachmentElement(file) { + const element = this.attachmentElement() + + this.attachmentContainerTarget.classList.remove('hidden') + + element.setAttribute('data-name', file.name) + + if(file.type.startsWith("image/")) { + const thumbnail = this.attachmentImageTarget.cloneNode(true) + + thumbnail.src = URL.createObjectURL(file) + thumbnail.style.display = 'block' + + element.appendChild(thumbnail) + + this.attachmentContainerTarget.appendChild(element) + this.attachmentContainerTarget.style.display = 'flex' + } else { + element.querySelector("main").classList.add(...this.widthClasses, "h-20", "rounded-md", "bg-gray-200", "p-1") + element.querySelector("p[data-attachment-name]").innerText = file.name + } + } + + removeAttachment({ currentTarget }) { + const attachment = currentTarget.closest("[data-hellotext--webchat-target='attachment']") + + this.files = this.files.filter(file => file.name !== attachment.dataset.name) + + attachment.remove() + this.inputTarget.focus() + } + + attachmentTargetDisconnected() { + if(this.attachmentTargets.length === 0) { + this.attachmentContainerTarget.innerHTML = "" + this.attachmentContainerTarget.style.display = 'none' + } + } + + attachmentElement() { + const element = this.attachmentTemplateTarget.cloneNode(true) + element.removeAttribute("hidden") + element.style.display = 'flex' + + element.setAttribute("data-hellotext--webchat-target", "attachment") + + return element + } + + onEmojiSelect({ detail: emoji }) { + const value = this.inputTarget.value + const start = this.inputTarget.selectionStart + const end = this.inputTarget.selectionEnd + + this.inputTarget.value = value.slice(0, start) + emoji + value.slice(end) + + this.inputTarget.selectionStart = this.inputTarget.selectionEnd = start + emoji.length + this.inputTarget.focus() + } + + setOfflineTimeout() { + clearTimeout(this.offlineTimeout) + + this.offlineTimeout = setTimeout(() => { + this.onlineStatusTarget.style.display = 'none' + }, this.fiveMinutes) + } + + byteToMegabyte(bytes) { + return Math.ceil(bytes / 1024 / 1024) + } + + get fiveMinutes() { + return 300000 + } + + get middlewares() { + return [ + offset(5), + shift({ padding: 24 }), + flip(), + ] + } +} diff --git a/src/core/configuration.js b/src/core/configuration.js index e2ea755..da854fd 100644 --- a/src/core/configuration.js +++ b/src/core/configuration.js @@ -1,4 +1,5 @@ import { Forms } from './configuration/forms' +import { Webchat } from './configuration/webchat' /** * @class Configuration @@ -7,6 +8,7 @@ import { Forms } from './configuration/forms' * @property {Boolean} [autoGenerateSession=true] - whether to auto generate session or not * @property {String} [session] - session id * @property {Forms} [forms] - form configuration + * @property {Webchat} [webchat] - webchat configuration */ class Configuration { static apiRoot = 'https://api.hellotext.com/v1' @@ -15,6 +17,7 @@ class Configuration { static session = null static forms = Forms + static webchat = Webchat /** * @@ -29,6 +32,8 @@ class Configuration { Object.entries(props).forEach(([key, value]) => { if (key === 'forms') { this.forms = Forms.assign(value) + } else if(key === 'webChat') { + this.webchat = Webchat.assign(value) } else { this[key] = value } diff --git a/src/core/configuration/webchat.js b/src/core/configuration/webchat.js new file mode 100644 index 0000000..6970485 --- /dev/null +++ b/src/core/configuration/webchat.js @@ -0,0 +1,176 @@ +/** + * @typedef {'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'} Placement + * @description Valid placements for the webchat. + */ + +/** + * @enum {Placement} + */ +const placements = { + TOP_LEFT: 'top-left', + TOP_RIGHT: 'top-right', + BOTTOM_LEFT: 'bottom-left', + BOTTOM_RIGHT: 'bottom-right' +} + + +/** + * @typedef {'modal' | 'popover'} Behaviour + */ + +/** + * @enum {Behaviour} + */ +const behaviors = { + MODAL: 'modal', + POPOVER: 'popover' +} + +/** + * @typedef {Object} Style + * @property {string} primaryColor - The primary webchat color (e.g., a hex code or color name). + * @property {string} secondaryColor - The secondary webchat color or style (e.g., a hex code or color name). + * @property {string} typography - The typography style (e.g., font family). + */ + + +/** + * @class Webchat + * @classdesc + * Configuration for webchat + * @property {String} id - the id of the webchat. + * @property {String} container - the container to append the webchat to, defaults to 'body' + * @property {Placement} placement - the placement of the webchat within the container, defaults to "bottom-right". + * @property {String} classes - additional classes to apply to the webchat popup. + * @property {String} triggerClasses - additional classes to apply to the webchat popup trigger. + * @property {Behaviour} behaviour - the behaviour of the webchat, defaults to 'popover'. + * @property {Style} style - the style of the webchat. + */ + +class Webchat { + static _id + static _container = 'body' + static _placement = 'bottom-right' + static _classes = [] + static _triggerClasses = [] + static _style = {} + static _behaviour = behaviors.POPOVER + + static set container(value) { + this._container = value + } + + static get container() { + return this._container + } + + static set placement(value) { + if(!Object.values(placements).includes(value)) { + throw new Error(`Invalid placement value: ${value}`) + } + + this._placement = value + } + + static get placement() { + return this._placement + } + + static set classes(value) { + if(!Array.isArray(value) && typeof value !== 'string') { + throw new Error('classes must be an array or a string') + } + + this._classes = value; + } + + static get classes() { + if(typeof this._classes === 'string') { + return this._classes.split(',').map(c => c.trim()) + } else { + return this._classes; + } + } + + static set triggerClasses(value) { + if(!Array.isArray(value) && typeof value !== 'string') { + throw new Error('triggerClasses must be an array or a string') + } + + this._triggerClasses = value; + } + + static get triggerClasses() { + if(typeof this._triggerClasses === 'string') { + return this._triggerClasses.split(',').map(c => c.trim()) + } else { + return this._triggerClasses; + } + } + + static set id(value) { + this._id = value + } + + static get id() { + return this._id + } + + static get isSet() { + return !!this._id + } + + static get style() { + return this._style + } + + static set style(value) { + if(typeof value !== 'object') { + throw new Error('Style must be an object') + } + + Object.entries(value).forEach(([key, value]) => { + if(!['primaryColor', 'secondaryColor', 'typography'].includes(key)) { + throw new Error(`Invalid style property: ${key}`) + } + + if(key === 'typography') { + return + } + + if(!this.isHexOrRgba(value)) { + throw new Error(`Invalid color value: ${value} for ${key}. Colors must be hex or rgb/a.`) + } + }) + + this._style = value + } + + static get behaviour() { + return this._behaviour + } + + static set behaviour(value) { + if(!Object.values(behaviors).includes(value)) { + throw new Error(`Invalid behaviour value: ${value}`) + } + + this._behaviour = value + } + + static assign(props) { + if(props) { + Object.entries(props).forEach(([key, value]) => { + this[key] = value + }) + } + + return this + } + + static isHexOrRgba(value) { + return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(value) || /^rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3},?\s*(0|1|0?\.\d+)?\s*\)$/.test(value); + } +} + +export { Webchat, behaviors } diff --git a/src/core/event.js b/src/core/event.js index f060c5b..609a079 100644 --- a/src/core/event.js +++ b/src/core/event.js @@ -1,7 +1,16 @@ import { InvalidEvent } from '../errors' export default class Event { - static events = ['session-set', 'forms:collected', 'form:completed'] + static events = [ + 'session-set', + 'forms:collected', + 'form:completed', + 'webchat:mounted', + 'webchat:opened', + 'webchat:closed', + 'webchat:message:sent', + 'webchat:message:received', + ] static valid(name) { return Event.exists(name) diff --git a/src/hellotext.js b/src/hellotext.js index 96b3d11..ad20423 100644 --- a/src/hellotext.js +++ b/src/hellotext.js @@ -1,7 +1,7 @@ import { Event, Configuration } from './core' import API, { Response } from './api' -import { Business, Query, FormCollection, Session } from './models' +import { Business, Query, FormCollection, Session, Webchat } from './models' import { NotInitializedError } from './errors' @@ -13,13 +13,14 @@ class Hellotext { static eventEmitter = new Event() static forms static business + static webchat /** * initialize the module. * @param business public business id * @param { Configuration } config */ - static initialize(business, config) { + static async initialize(business, config) { Configuration.assign(config) Session.initialize() @@ -27,6 +28,10 @@ class Hellotext { this.business = new Business(business) this.forms = new FormCollection() + + if (Configuration.webchat.id) { + this.webchat = await Webchat.load(Configuration.webchat.id) + } } /** diff --git a/src/index.js b/src/index.js index 575af77..afb09c0 100644 --- a/src/index.js +++ b/src/index.js @@ -2,9 +2,14 @@ import { Application } from '@hotwired/stimulus' import Hellotext from './hellotext' import FormController from './controllers/form_controller' +import WebchatController from './controllers/webchat_controller' +import WebChatEmojiController from './controllers/webchat/emoji_picker_controller' const application = Application.start() + application.register('hellotext--form', FormController) +application.register('hellotext--webchat', WebchatController) +application.register('hellotext--webchat--emoji', WebChatEmojiController) import '../styles/index.css' diff --git a/src/models/business.js b/src/models/business.js index 3482135..5640448 100644 --- a/src/models/business.js +++ b/src/models/business.js @@ -34,7 +34,17 @@ class Business { fetchPublicData() { API.get(this.id) .then(response => response.json()) - .then(data => (this.data = data)) + .then(data => { + this.data = data + + if(typeof document !== 'undefined') { + const linkTag = document.createElement('link') + linkTag.rel = 'stylesheet' + linkTag.href = data.style_url + + document.head.append(linkTag) + } + }) } } diff --git a/src/models/index.js b/src/models/index.js index ce4e4b9..a2accc6 100644 --- a/src/models/index.js +++ b/src/models/index.js @@ -3,4 +3,5 @@ export { Form } from './form' export { Query } from './query' export { Cookies } from './cookies' export { FormCollection } from './form_collection' +export { Webchat } from './webchat' export { Session } from './session' diff --git a/src/models/webchat.js b/src/models/webchat.js new file mode 100644 index 0000000..a9d5fbe --- /dev/null +++ b/src/models/webchat.js @@ -0,0 +1,28 @@ +import Hellotext from '../hellotext'; +import { Configuration } from '../core' + +import API from '../api'; + +class Webchat { + static async load(id) { + return new Webchat({ + id, + html: await API.webchats.get(id), + }) + } + + constructor(data) { + this.data = data + this.render() + } + + render() { + this.containerToAppendTo.appendChild(this.data.html) + } + + get containerToAppendTo() { + return document.querySelector(Configuration.webchat.container) + } +} + +export { Webchat } diff --git a/styles/index.css b/styles/index.css index 5398004..3af32a1 100644 --- a/styles/index.css +++ b/styles/index.css @@ -1,3 +1,7 @@ +.hidden { + display: none; +} + form[data-hello-form] { position: relative; diff --git a/webpack.config.js b/webpack.config.js index 5453f90..164ced5 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,6 +1,6 @@ module.exports = { mode: 'production', - entry: ['whatwg-fetch', '@hotwired/stimulus', './lib/index.js'], + entry: ['@hotwired/stimulus', './lib/index.js'], output: { filename: 'hellotext.js', }, diff --git a/yarn.lock b/yarn.lock index f5200fb..f0940cd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -988,6 +988,26 @@ resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70" integrity sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw== +"@floating-ui/core@^1.6.0": + version "1.6.8" + resolved "https://registry.yarnpkg.com/@floating-ui/core/-/core-1.6.8.tgz#aa43561be075815879305965020f492cdb43da12" + integrity sha512-7XJ9cPU+yI2QeLS+FCSlqNFZJq8arvswefkZrYI1yQBbftw6FyrZOxYSh+9S7z7TpeWlRt9zJ5IhM1WIL334jA== + dependencies: + "@floating-ui/utils" "^0.2.8" + +"@floating-ui/dom@^1.6.12": + version "1.6.12" + resolved "https://registry.yarnpkg.com/@floating-ui/dom/-/dom-1.6.12.tgz#6333dcb5a8ead3b2bf82f33d6bc410e95f54e556" + integrity sha512-NP83c0HjokcGVEMeoStg317VD9W7eDlGK7457dMBANbKA6GJZdc7rjujdgqzTaz93jkGgc5P/jeWbaCHnMNc+w== + dependencies: + "@floating-ui/core" "^1.6.0" + "@floating-ui/utils" "^0.2.8" + +"@floating-ui/utils@^0.2.8": + version "0.2.8" + resolved "https://registry.yarnpkg.com/@floating-ui/utils/-/utils-0.2.8.tgz#21a907684723bbbaa5f0974cf7730bd797eb8e62" + integrity sha512-kym7SodPp8/wloecOpcmSnWJsK7M0E5Wg8UcFA+uO4B9s5d0ywXOEro/8HM9x0rW+TljRzul/14UYz3TleT3ig== + "@hotwired/stimulus@^3.0.0": version "3.2.2" resolved "https://registry.yarnpkg.com/@hotwired/stimulus/-/stimulus-3.2.2.tgz#071aab59c600fed95b97939e605ff261a4251608" @@ -2055,11 +2075,6 @@ core-js-compat@^3.25.1: dependencies: browserslist "^4.21.4" -core-js@3.27.2: - version "3.27.2" - resolved "https://registry.yarnpkg.com/core-js/-/core-js-3.27.2.tgz#85b35453a424abdcacb97474797815f4d62ebbf7" - integrity sha512-9ashVQskuh5AZEZ1JdQWp1GqSoC1e1G87MzRqg2gIfVAQ7Qn9K+uFj8EcniUFA4P2NLZfV+TOlX1SzoKfo+s7w== - cross-spawn@^7.0.3: version "7.0.3" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" @@ -2214,6 +2229,11 @@ emittery@^0.13.1: resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.13.1.tgz#c04b8c3457490e0847ae51fced3af52d338e3dad" integrity sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ== +emoji-mart@^5.6.0: + version "5.6.0" + resolved "https://registry.yarnpkg.com/emoji-mart/-/emoji-mart-5.6.0.tgz#71b3ed0091d3e8c68487b240d9d6d9a73c27f023" + integrity sha512-eJp3QRe79pjwa+duv+n7+5YsNhRcMl812EcFVwrnRvYKoNPoQb5qxU8DG6Bgwji0akHdp6D4Ln6tYLG58MFSow== + emoji-regex@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" @@ -4375,10 +4395,10 @@ whatwg-encoding@^2.0.0: dependencies: iconv-lite "0.6.3" -whatwg-fetch@^3.6.2: - version "3.6.2" - resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-3.6.2.tgz#dced24f37f2624ed0281725d51d0e2e3fe677f8c" - integrity sha512-bJlen0FcuU/0EMLrdbJ7zOnW6ITZLrZMIarMUVmdKtsGvZna8vxKYaexICWPfZ8qwf9fzNq+UEIZrnSaApt6RA== +whatwg-fetch@^3.6.20: + version "3.6.20" + resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-3.6.20.tgz#580ce6d791facec91d37c72890995a0b48d31c70" + integrity sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg== whatwg-mimetype@^3.0.0: version "3.0.0"