@tradecanvas/chart 1.70.0 → 1.71.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Chart.d.ts +4 -11
- package/dist/Chart.d.ts.map +1 -1
- package/dist/{LayoutSession-Bcy79w0l.js → LayoutSession-BOQCN6yY.js} +584 -529
- package/dist/LayoutSession-BOQCN6yY.js.map +1 -0
- package/dist/LayoutSession-RF8OqOXy.cjs +2 -0
- package/dist/LayoutSession-RF8OqOXy.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +60 -60
- package/dist/model/AlertWatch.d.ts +60 -0
- package/dist/model/AlertWatch.d.ts.map +1 -0
- package/dist/model/ReplayMarks.d.ts +42 -0
- package/dist/model/ReplayMarks.d.ts.map +1 -0
- package/dist/widget/WidgetIndicatorSettings.d.ts +1 -0
- package/dist/widget/WidgetIndicatorSettings.d.ts.map +1 -1
- package/dist/widget/index.cjs +4 -4
- package/dist/widget/index.cjs.map +1 -1
- package/dist/widget/index.js +544 -528
- package/dist/widget/index.js.map +1 -1
- package/dist/widget/settingsControls.d.ts +1 -0
- package/dist/widget/settingsControls.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/LayoutSession-Bcy79w0l.js.map +0 -1
- package/dist/LayoutSession-D7S6GZgJ.cjs +0 -2
- package/dist/LayoutSession-D7S6GZgJ.cjs.map +0 -1
package/dist/widget/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-D7S6GZgJ.cjs`),t=require(`../i18n-BsstZ9md.cjs`);let n=require(`@tradecanvas/commons`),r=require(`@tradecanvas/core`);function i(e,t,r={}){return(0,n.resampleBars)(e,t,{weekStartsOn:r.weekStartsOn??1,timeZone:r.timeZone})}function a(e){if(e.length<2)return 0;let t=[];for(let n=1;n<e.length;n++){let r=e[n].time-e[n-1].time;r>0&&t.push(r)}return t.length===0?0:(t.sort((e,t)=>e-t),t[Math.floor(t.length/2)])}var o=[{zone:`Pacific/Honolulu`,city:`Honolulu`},{zone:`America/Los_Angeles`,city:`Los Angeles`},{zone:`America/Denver`,city:`Denver`},{zone:`America/Chicago`,city:`Chicago`},{zone:`America/New_York`,city:`New York`},{zone:`America/Toronto`,city:`Toronto`},{zone:`America/Sao_Paulo`,city:`São Paulo`},{zone:`UTC`,city:`UTC`},{zone:`Europe/London`,city:`London`},{zone:`Europe/Berlin`,city:`Frankfurt`},{zone:`Europe/Paris`,city:`Paris`},{zone:`Europe/Zurich`,city:`Zurich`},{zone:`Africa/Johannesburg`,city:`Johannesburg`},{zone:`Europe/Istanbul`,city:`Istanbul`},{zone:`Europe/Moscow`,city:`Moscow`},{zone:`Asia/Dubai`,city:`Dubai`},{zone:`Asia/Kolkata`,city:`Mumbai`},{zone:`Asia/Bangkok`,city:`Bangkok`},{zone:`Asia/Ho_Chi_Minh`,city:`Ho Chi Minh City`},{zone:`Asia/Jakarta`,city:`Jakarta`},{zone:`Asia/Singapore`,city:`Singapore`},{zone:`Asia/Hong_Kong`,city:`Hong Kong`},{zone:`Asia/Shanghai`,city:`Shanghai`},{zone:`Asia/Taipei`,city:`Taipei`},{zone:`Asia/Seoul`,city:`Seoul`},{zone:`Asia/Tokyo`,city:`Tokyo`},{zone:`Australia/Sydney`,city:`Sydney`},{zone:`Pacific/Auckland`,city:`Auckland`}],s=/^-?\d+$/,c=840;function l(e){if(!s.test(e))return null;let t=Number(e);return Math.abs(t)<=c?t:null}function u(e){return!e||e===`local`?null:e===`exchange`?`exchange`:s.test(e)?l(e):(0,n.isValidTimeZone)(e)?e:null}function d(e){return e===null?`local`:String(e)}function f(e,t,r,i){let a=(0,n.offsetAt)(null,t),s=o.filter(({zone:e})=>(0,n.isValidTimeZone)(e)).map(({zone:e,city:r})=>{let i=(0,n.offsetAt)(e,t);return{value:e,label:e===`UTC`?`UTC`:`(${(0,n.tzLabel)(i)}) ${r}`,offset:i}}),c=u(e);typeof c==`number`&&s.push({value:e,label:(0,n.tzLabel)(c),offset:c}),s.sort((e,t)=>e.offset-t.offset);let l=[{value:`local`,label:`${r} (${(0,n.tzLabel)(a)})`,offset:a}];if(i){let e=(0,n.offsetAt)(i.zone&&(0,n.isValidTimeZone)(i.zone)?i.zone:`UTC`,t);l.push({value:`exchange`,label:`${i.label} (${(0,n.tzLabel)(e)})`,offset:e})}return[...l,...s]}var p=6,m=8,h=120;function g(e,t,n=`left`){let r=e.style,i=t.getBoundingClientRect();r.position=`fixed`,r.margin=`0`,r.top=r.bottom=r.left=r.right=``;let a=window.innerHeight-i.bottom-p-m,o=i.top-p-m;e.scrollHeight<=a||a>=o?(r.top=`${i.bottom+p}px`,r.bottom=`auto`,r.maxHeight=`${Math.max(h,a)}px`):(r.top=`auto`,r.bottom=`${window.innerHeight-i.top+p}px`,r.maxHeight=`${Math.max(h,o)}px`);let s=getComputedStyle(t).direction===`rtl`,c=n===`right`!==s,l=e.offsetWidth,u=c?i.right-l:i.left;r.left=`${Math.max(m,Math.min(u,window.innerWidth-l-m))}px`}var ee=700,_=class{select=null;panel=null;rows=[];active=-1;typed=``;typedAt=0;onOutside=e=>{let t=e.target;this.panel?.contains(t)||this.select?.contains(t)||this.close(!1)};onAway=()=>this.close(!1);onScroll=e=>{e.target instanceof Node&&this.panel?.contains(e.target)||this.close(!1)};watch=new MutationObserver(()=>{this.select&&!this.select.isConnected&&this.close(!1)});constructor(e){this.layer=e}isOpenFor(e){return this.select===e}owns(e){return e!==null&&(e===this.select||this.panel?.contains(e)===!0)}open(e){this.close(!1),this.select=e;let t=document.createElement(`div`);t.className=`tcw-dropdown tcw-select-menu`,t.setAttribute(`role`,`listbox`),t.id=`tcw-select-menu-${Math.random().toString(36).slice(2,9)}`;let n=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;n&&t.setAttribute(`aria-label`,n.trim()),t.style.minWidth=`${e.getBoundingClientRect().width}px`,this.rows=[];for(let n of e.children)if(n instanceof HTMLOptGroupElement){let e=document.createElement(`div`);e.className=`tcw-select-group`,e.textContent=n.label,t.appendChild(e);for(let e of n.querySelectorAll(`option`))this.addRow(t,e,n.disabled)}else n instanceof HTMLOptionElement&&this.addRow(t,n,!1);t.addEventListener(`mousedown`,e=>e.preventDefault());let r=e=>this.rows.findIndex(t=>t.el.contains(e.target));t.addEventListener(`click`,e=>{let t=r(e);t>=0&&this.pick(t)}),t.addEventListener(`mousemove`,e=>{let t=r(e);t>=0&&t!==this.active&&this.enabled(t)&&this.setActive(t,!1)}),this.layer().appendChild(t),this.panel=t,g(t,e),e.setAttribute(`aria-expanded`,`true`),e.setAttribute(`aria-controls`,t.id),this.setActive(this.rows.findIndex(e=>e.option.selected)),document.addEventListener(`pointerdown`,this.onOutside,!0),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0}),this.watch.observe(document.documentElement,{childList:!0,subtree:!0})}close(e){let t=this.select;t&&(document.removeEventListener(`pointerdown`,this.onOutside,!0),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}),this.watch.disconnect(),this.panel?.remove(),this.panel=null,this.rows=[],this.select=null,t.setAttribute(`aria-expanded`,`false`),t.removeAttribute(`aria-controls`),t.removeAttribute(`aria-activedescendant`),e&&t.isConnected&&t.focus())}key(e){if(!this.select)return!1;switch(e.key){case`ArrowDown`:return this.step(1),!0;case`ArrowUp`:return this.step(-1),!0;case`Home`:return this.setActive(this.nextEnabled(-1,1)),!0;case`End`:return this.setActive(this.nextEnabled(this.rows.length,-1)),!0;case`PageDown`:return this.step(8),!0;case`PageUp`:return this.step(-8),!0;case` `:return this.typed&&Date.now()-this.typedAt<=ee?(this.typeahead(` `),!0):(this.active>=0?this.pick(this.active):this.close(!0),!0);case`Enter`:return this.active>=0?this.pick(this.active):this.close(!0),!0;case`Escape`:return this.close(!0),!0;case`Tab`:return this.close(!1),!1;default:return e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey?(this.typeahead(e.key),!0):!1}}destroy(){this.close(!1)}addRow(e,t,n){let r=document.createElement(`div`);r.className=`tcw-select-option`,r.id=`${e.id}-${this.rows.length}`,r.setAttribute(`role`,`option`),r.setAttribute(`aria-selected`,String(t.selected)),(t.disabled||n)&&r.setAttribute(`aria-disabled`,`true`);let i=document.createElement(`span`);i.className=`tcw-select-option-text`,i.textContent=t.label||t.textContent||``,t.dir&&(i.dir=t.dir);let a=document.createElement(`span`);a.className=`tcw-select-check`,a.setAttribute(`aria-hidden`,`true`),r.append(a,i),e.appendChild(r),this.rows.push({option:t,el:r})}enabled(e){return this.rows[e]?.el.getAttribute(`aria-disabled`)!==`true`}nextEnabled(e,t){for(let n=e+t;n>=0&&n<this.rows.length;n+=t)if(this.enabled(n))return n;return-1}step(e){let t=e>0?1:-1,n=this.active;for(let r=0;r<Math.abs(e);r++){let e=this.nextEnabled(n,t);if(e<0)break;n=e}n>=0&&this.setActive(n)}setActive(e,t=!0){this.rows[this.active]?.el.classList.remove(`tcw-active`),this.active=e;let n=this.rows[e];n&&(n.el.classList.add(`tcw-active`),this.select?.setAttribute(`aria-activedescendant`,n.el.id),t&&n.el.scrollIntoView?.({block:`nearest`}))}typeahead(e){let t=Date.now();this.typed=t-this.typedAt>ee?e.toLowerCase():this.typed+e.toLowerCase(),this.typedAt=t;let n=e=>this.enabled(e)&&(this.rows[e].el.textContent??``).trim().toLowerCase().startsWith(this.typed),r=this.typed.length===1?this.active+1:Math.max(0,this.active);for(let e=0;e<this.rows.length;e++){let t=(r+e)%this.rows.length;if(n(t)){this.setActive(t);return}}}pick(e){let t=this.select,n=this.rows[e];if(!t||!n||!this.enabled(e))return;let r=!n.option.selected;n.option.selected=!0,this.close(!0),r&&(t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})))}},v=42,y=7,b=new Set([`US`,`CA`,`MX`,`BR`,`JP`,`KR`,`TW`,`HK`,`IL`,`PH`,`IN`,`ZA`,`AU`,`TH`,`SA`,`PE`,`CO`]);function x(e){try{let t=new Intl.Locale(e),n=t.getWeekInfo?.()??t.weekInfo;return n?n.firstDay===7?0:1:+!b.has(t.maximize().region??``)}catch{return 1}}function te(e,t,n){let r=(new Date(Date.UTC(e,t,1)).getUTCDay()-n+y)%y,i=[];for(let n=0;n<v;n++){let a=new Date(Date.UTC(e,t,1-r+n));i.push({year:a.getUTCFullYear(),month:a.getUTCMonth(),day:a.getUTCDate()})}return i}var ne=e=>String(e).padStart(2,`0`),S=e=>`${String(e.year).padStart(4,`0`)}-${ne(e.month+1)}-${ne(e.day)}`;function re(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e??``);return t?{year:Number(t[1]),month:Number(t[2])-1,day:Number(t[3])}:null}function ie(){let e=new Date;return{year:e.getFullYear(),month:e.getMonth(),day:e.getDate()}}function ae(e,t){let n=new Date(Date.UTC(e.year,e.month,e.day+t));return{year:n.getUTCFullYear(),month:n.getUTCMonth(),day:n.getUTCDate()}}var oe=class{element;grid;titleEl;chosen=``;limits={};today=S(ie());view={year:0,month:0};focusDay=ie();constructor(e,t,n){this.locale=t,this.onPick=n;let r=document.createElement(`div`);r.className=`tcw-calendar`;let i=document.createElement(`div`);i.className=`tcw-calendar-head`;let a=document.createElement(`div`);a.className=`tcw-calendar-title`,a.setAttribute(`aria-live`,`polite`),i.append(this.navButton(e.prevMonth,-1),a,this.navButton(e.nextMonth,1));let o=document.createElement(`div`);o.className=`tcw-calendar-weekdays`,o.setAttribute(`aria-hidden`,`true`);let s=x(t),c=new Intl.DateTimeFormat(t,{weekday:`narrow`,timeZone:`UTC`});for(let e=0;e<y;e++){let t=document.createElement(`span`);t.className=`tcw-calendar-weekday`,t.textContent=c.format(new Date(Date.UTC(2023,0,1+(s+e)%y))),o.appendChild(t)}let l=document.createElement(`div`);l.className=`tcw-calendar-grid`,l.setAttribute(`role`,`grid`),l.addEventListener(`keydown`,e=>this.onKey(e)),l.addEventListener(`click`,e=>{let t=e.target.closest(`.tcw-calendar-day`);t&&!t.disabled&&t.dataset.date&&this.pick(t.dataset.date)});let u=document.createElement(`div`);u.className=`tcw-calendar-foot`;let d=document.createElement(`button`);d.type=`button`,d.className=`tcw-calendar-today`,d.textContent=e.today,d.addEventListener(`click`,()=>this.pick(this.today)),u.appendChild(d),r.append(i,o,l,u),this.element=r,this.grid=l,this.titleEl=a}show(e,t={}){this.chosen=e,this.limits=t,this.today=re(t.today)?t.today:S(ie());let n=this.clamp(re(e)??re(this.today));this.focusDay=n,this.view={year:n.year,month:n.month},this.render()}focusGrid(){this.grid.querySelector(`[tabindex="0"]`)?.focus()}navButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-calendar-nav`,n.setAttribute(`aria-label`,e),n.innerHTML=t<0?`<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3.5L5.5 8l4.5 4.5"/></svg>`:`<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6 3.5L10.5 8 6 12.5"/></svg>`,n.addEventListener(`click`,()=>this.turn(t)),n}turn(e){let t=new Date(Date.UTC(this.view.year,this.view.month+e,1));this.view={year:t.getUTCFullYear(),month:t.getUTCMonth()};let n=new Date(Date.UTC(this.view.year,this.view.month+1,0)).getUTCDate();this.focusDay=this.clamp({...this.view,day:Math.min(this.focusDay.day,n)}),this.view={year:this.focusDay.year,month:this.focusDay.month},this.render()}clamp(e){let t=S(e),n=re(this.limits.min),r=re(this.limits.max);return n&&t<S(n)?n:r&&t>S(r)?r:e}allowed(e){let{min:t,max:n}=this.limits;return!(t&&e<t)&&!(n&&e>n)}render(){let e=this.locale;this.titleEl.textContent=new Intl.DateTimeFormat(e,{month:`long`,year:`numeric`,timeZone:`UTC`}).format(new Date(Date.UTC(this.view.year,this.view.month,1)));let t=this.today,n=S(this.focusDay),r=new Intl.DateTimeFormat(e,{dateStyle:`full`,timeZone:`UTC`});this.grid.textContent=``;let i=null;for(let[a,o]of te(this.view.year,this.view.month,x(e)).entries()){a%y===0&&(i=document.createElement(`div`),i.className=`tcw-calendar-week`,i.setAttribute(`role`,`row`),this.grid.appendChild(i));let e=S(o),s=document.createElement(`button`);s.type=`button`,s.className=`tcw-calendar-day`,s.dataset.date=e,s.setAttribute(`role`,`gridcell`),s.textContent=String(o.day),s.setAttribute(`aria-label`,r.format(new Date(Date.UTC(o.year,o.month,o.day)))),s.setAttribute(`aria-selected`,String(e===this.chosen)),s.tabIndex=e===n?0:-1,o.month!==this.view.month&&s.classList.add(`tcw-outside`),e===t&&s.classList.add(`tcw-today`),this.allowed(e)||(s.disabled=!0),i?.appendChild(s)}}onKey(e){let t={ArrowLeft:-1,ArrowRight:1,ArrowUp:-y,ArrowDown:y},n=this.element.isConnected&&getComputedStyle(this.element).direction===`rtl`;if(e.key in t){let r=n&&(e.key===`ArrowLeft`||e.key===`ArrowRight`)?-t[e.key]:t[e.key];this.moveFocus(ae(this.focusDay,r))}else if(e.key===`PageUp`||e.key===`PageDown`)this.turn(e.key===`PageUp`?-1:1),this.focusGrid();else if(e.key===`Home`||e.key===`End`){let t=new Date(Date.UTC(this.view.year,this.view.month+1,0)).getUTCDate();this.moveFocus({...this.view,day:e.key===`Home`?1:t})}else if(e.key===`Enter`||e.key===` `)this.pick(S(this.focusDay));else return;e.preventDefault()}moveFocus(e){let t=this.clamp(e);this.focusDay=t,(t.year!==this.view.year||t.month!==this.view.month)&&(this.view={year:t.year,month:t.month}),this.render(),this.focusGrid()}pick(e){this.allowed(e)&&this.onPick(e)}},se=class{input=null;view=null;onOutside=e=>{let t=e.target;this.view?.element.contains(t)||this.input?.contains(t)||this.close(!1)};onAway=()=>this.close(!1);onScroll=e=>{e.target instanceof Node&&this.view?.element.contains(e.target)||this.close(!1)};watch=new MutationObserver(()=>{this.input&&!this.input.isConnected&&this.close(!1)});constructor(e,t,n){this.layer=e,this.labels=t,this.locale=n}isOpenFor(e){return this.input===e}owns(e){return e!==null&&(e===this.input||this.view?.element.contains(e)===!0)}open(e){this.close(!1),this.input=e;let t=new oe(this.labels(),this.locale(),e=>this.pick(e));t.show(e.value,{min:e.min||void 0,max:e.max||void 0});let n=t.element;n.setAttribute(`role`,`dialog`);let r=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;r&&n.setAttribute(`aria-label`,r.trim()),n.addEventListener(`mousedown`,e=>{e.target.closest(`button`)||e.preventDefault()}),n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&(e.preventDefault(),this.close(!0))}),this.view=t,this.layer().appendChild(n),g(n,e),document.addEventListener(`pointerdown`,this.onOutside,!0),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0}),this.watch.observe(document.documentElement,{childList:!0,subtree:!0})}close(e){let t=this.input;t&&(document.removeEventListener(`pointerdown`,this.onOutside,!0),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}),this.watch.disconnect(),this.view?.element.remove(),this.view=null,this.input=null,e&&t.isConnected&&t.focus())}focusGrid(){this.view?.focusGrid()}destroy(){this.close(!1)}pick(e){let t=this.input;if(!t)return;let n=t.value!==e;t.value=e,this.close(!0),n&&(t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})))}},ce=()=>typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches,le=()=>typeof CSS>`u`||typeof CSS.supports!=`function`||CSS.supports(`selector(::-webkit-calendar-picker-indicator)`);function ue(e){if(!(e instanceof Element))return null;let t=e.closest(`select`);return!t||t.matches(`:disabled`)||t.multiple||t.size>1?null:t}function de(e){return!(e instanceof HTMLInputElement)||e.type!==`date`||e.dataset.tcwCalendar===`inline`||e.matches(`:disabled`)||e.readOnly?null:e}function fe(e,t){let n=new _(t.layer),r=new se(t.layer,t.labels,t.locale),i=t.native??ce,a=t.calendar??le,o=new WeakSet,s=e=>o.has(e)?!1:(o.add(e),!0),c=e=>{if(e.button!==0||i()||!s(e))return;let t=ue(e.target);if(t){if(e.preventDefault(),n.isOpenFor(t)){n.close(!0);return}t.focus(),n.open(t)}},l=e=>{if(i()||!a()||!s(e))return;let t=de(e.target);t&&(e.preventDefault(),r.isOpenFor(t)||r.open(t))},u=e=>{if(i()||!s(e))return;let t=ue(e.target);if(t){if(n.isOpenFor(t)){n.key(e)&&(e.preventDefault(),e.stopPropagation());return}(e.key===`Enter`||e.key===` `||e.altKey&&(e.key===`ArrowDown`||e.key===`ArrowUp`)||e.key===`F4`)&&(e.preventDefault(),e.stopPropagation(),n.open(t));return}let o=de(e.target);!o||!a()||(e.key===`Escape`&&r.isOpenFor(o)?(e.preventDefault(),e.stopPropagation(),r.close(!0)):(e.altKey&&e.key===`ArrowDown`||e.key===`F4`)&&(e.preventDefault(),r.isOpenFor(o)||r.open(o),r.focusGrid()))},d=e=>{if(!s(e))return;let t=e.target instanceof Node?e.target:null,i=e.relatedTarget instanceof Node?e.relatedTarget:null;n.owns(t)&&!n.owns(i)&&n.close(!1),r.owns(t)&&!r.owns(i)&&r.close(!1)};for(let t of e)t.addEventListener(`mousedown`,c,!0),t.addEventListener(`click`,l,!0),t.addEventListener(`keydown`,u,!0),t.addEventListener(`focusout`,d,!0);return()=>{for(let t of e)t.removeEventListener(`mousedown`,c,!0),t.removeEventListener(`click`,l,!0),t.removeEventListener(`keydown`,u,!0),t.removeEventListener(`focusout`,d,!0);n.destroy(),r.destroy()}}var pe=[{label:`Candlestick`,value:`candlestick`},{label:`Line`,value:`line`},{label:`Area`,value:`area`},{label:`Bar`,value:`bar`},{label:`Heikin-Ashi`,value:`heikinAshi`},{label:`Hollow Candle`,value:`hollowCandle`},{label:`Baseline`,value:`baseline`},{label:`Volume Candles`,value:`volumeCandles`},{label:`Equivolume`,value:`equivolume`},{label:`HLC Area`,value:`hlcArea`},{label:`Step Line`,value:`stepLine`},{label:`Line + Markers`,value:`lineWithMarkers`},{label:`High-Low`,value:`hiLo`},{label:`Renko`,value:`renko`},{label:`Line Break`,value:`lineBreak`},{label:`Kagi`,value:`kagi`},{label:`Point & Figure`,value:`pointAndFigure`},{label:`Range Bars`,value:`rangeBars`}],me=[{label:`Lines`,section:`lines`,tools:[{label:`Trend Line`,value:`trendLine`},{label:`Ray`,value:`ray`},{label:`Extended Line`,value:`extendedLine`},{label:`Info Line`,value:`infoLine`},{label:`Trend Angle`,value:`trendAngle`}]},{label:`Horizontal/Vertical`,section:`lines`,tools:[{label:`Horizontal Line`,value:`horizontalLine`},{label:`Horizontal Ray`,value:`horizontalRay`},{label:`Vertical Line`,value:`verticalLine`},{label:`Cross Line`,value:`crossLine`}]},{label:`Channels`,section:`lines`,tools:[{label:`Parallel Channel`,value:`parallelChannel`},{label:`Regression Channel`,value:`regressionChannel`}]},{label:`Fibonacci`,section:`fibonacci`,tools:[{label:`Fib Retracement`,value:`fibRetracement`},{label:`Fib Extension`,value:`fibExtension`},{label:`Fib Channel`,value:`fibChannel`},{label:`Fib Time Zones`,value:`fibTimeZones`},{label:`Fib Speed Resistance Fan`,value:`fibSpeedResistanceFan`},{label:`Fib Speed Resistance Arcs`,value:`fibArcs`},{label:`Fib Circles`,value:`fibCircles`},{label:`Fib Spiral`,value:`fibSpiral`},{label:`Fib Wedge`,value:`fibWedge`}]},{label:`Gann & Pitchforks`,section:`fibonacci`,tools:[{label:`Pitchfork`,value:`pitchfork`},{label:`Schiff Pitchfork`,value:`schiffPitchfork`},{label:`Modified Schiff Pitchfork`,value:`modifiedSchiffPitchfork`},{label:`Gann Fan`,value:`gannFan`},{label:`Gann Box`,value:`gannBox`},{label:`Gann Square`,value:`gannSquare`},{label:`Pitchfan`,value:`pitchfan`}]},{label:`Cycles`,section:`fibonacci`,tools:[{label:`Cyclic Lines`,value:`cyclicLines`},{label:`Time Cycles`,value:`timeCycles`},{label:`Sine Line`,value:`sineLine`}]},{label:`Patterns`,section:`patterns`,tools:[{label:`XABCD Pattern`,value:`xabcdPattern`},{label:`ABCD Pattern`,value:`abcdPattern`},{label:`Head and Shoulders`,value:`headAndShoulders`},{label:`Cypher Pattern`,value:`cypherPattern`},{label:`Three Drives Pattern`,value:`threeDrives`}]},{label:`Elliott Waves`,section:`patterns`,tools:[{label:`Elliott Wave`,value:`elliottWave`},{label:`Elliott Impulse Wave`,value:`elliottImpulse`},{label:`Elliott Correction Wave`,value:`elliottCorrection`},{label:`Elliott Triangle Wave`,value:`elliottTriangle`},{label:`Elliott Double Combo Wave`,value:`elliottDoubleCombo`},{label:`Elliott Triple Combo Wave`,value:`elliottTripleCombo`}]},{label:`Forecasting`,section:`forecasting`,tools:[{label:`Long/Short Position`,value:`riskReward`},{label:`Anchored VWAP`,value:`anchoredVWAP`},{label:`Fixed Range Volume Profile`,value:`volumeProfileRange`},{label:`Forecast`,value:`forecast`},{label:`Projection`,value:`projection`},{label:`Bars Pattern`,value:`barsPattern`}]},{label:`Measure`,section:`forecasting`,tools:[{label:`Price Range`,value:`priceRange`},{label:`Date Range`,value:`dateRange`},{label:`Date and Price Range`,value:`dateAndPriceRange`},{label:`Measure`,value:`measure`}]},{label:`Shapes`,section:`annotation`,tools:[{label:`Rectangle`,value:`rectangle`},{label:`Circle`,value:`circle`},{label:`Ellipse`,value:`ellipse`},{label:`Triangle`,value:`triangle`},{label:`Polyline`,value:`polyline`},{label:`Curve`,value:`curve`},{label:`Arc`,value:`arc`}]},{label:`Brushes`,section:`annotation`,tools:[{label:`Brush`,value:`brush`},{label:`Highlighter`,value:`highlighter`},{label:`Path`,value:`path`}]},{label:`Annotation`,section:`annotation`,tools:[{label:`Text`,value:`text`},{label:`Price Label`,value:`priceLabel`},{label:`Arrow`,value:`arrow`},{label:`Note`,value:`note`},{label:`Callout`,value:`callout`},{label:`Flag Mark`,value:`flag`},{label:`Arrow Mark`,value:`arrowMark`},{label:`Icon`,value:`icon`},{label:`Signpost`,value:`signpost`},{label:`Balloon`,value:`balloon`},{label:`Anchored Text`,value:`anchoredText`},{label:`Anchored Note`,value:`anchoredNote`}]}],he=[`BTCUSDT`,`ETHUSDT`,`SOLUSDT`,`BNBUSDT`],ge={gridVisible:!0,volumeVisible:!0,volumeProfileVisible:!1,marketProfileVisible:!1,marketProfileSplit:!1,marketProfileLetters:!1,marketProfileBuckets:48,marketProfileOpacity:.32,depthHeatmapVisible:!1,depthHeatmapOpacity:.7,sessionShadingVisible:!1,pivotMarkersVisible:!1,pivotStrength:5,pivotStructureLabels:!1,periodLevelsVisible:!1,periodLevelsPeriod:`day`,legendVisible:!0,barCountdown:!0,indicatorValueLabels:!1,alignAxisLabels:!0,logScale:!1,scaleMode:`regular`,autoScale:!0,invertScale:!1,leftPriceScale:!1,crosshairMode:`magnet`,numberLocale:`en-US`,timezone:`local`,highLowLines:!1,mainSeriesVisible:!0,extendedHours:!0,chartTypeOptions:{}},C=(e,...t)=>({label:e,keys:t}),w=(e,t,n={})=>({label:e,keys:[t],auto:n}),T=e=>({hint:e}),_e={from:`panes.titleColor`},ve={title:`settings.section.lastPrice`,rows:[C(`settings.priceLine`,`lastPrice.visible`),C(`settings.up`,`lastPrice.upColor`),C(`settings.down`,`lastPrice.downColor`),C(`drawingSettings.lineStyle`,`lastPrice.style`),C(`drawingSettings.lineWidth`,`lastPrice.width`)]},ye={title:`settings.volume`,rows:[C(`settings.up`,`volume.upColor`),C(`settings.down`,`volume.downColor`)]},be={title:`settings.highLowLines`,rows:[w(`drawingSettings.color`,`highLow.color`,_e)]},xe=[ve,ye,be],Se=[C(`settings.legendText`,`legend.textColor`),C(`settings.legendLabels`,`legend.labelColor`)],Ce=[...Se,C(`settings.paneTitles`,`panes.titleColor`)],we=[C(`drawingSettings.text`,`axis.price.textColor`,`axis.time.textColor`),C(`settings.scaleLines`,`axis.price.lineColor`,`axis.time.lineColor`)],Te=[{title:`settings.section.background`,rows:[C(`settings.background`,`background.color`),C(`settings.paneBackground`,`panes.background`),C(`settings.paneSeparator`,`panes.separatorColor`),w(`settings.watermark`,`watermark.color`,_e)]},{title:`settings.gridLines`,rows:[C(`settings.horizontal`,`grid.horizontal.visible`),C(`settings.vertical`,`grid.vertical.visible`),C(`drawingSettings.color`,`grid.horizontal.color`,`grid.vertical.color`),C(`drawingSettings.lineStyle`,`grid.horizontal.style`,`grid.vertical.style`),C(`drawingSettings.lineWidth`,`grid.horizontal.width`,`grid.vertical.width`)]},{title:`settings.crosshairMode`,rows:[C(`settings.horizontal`,`crosshair.horizontal.visible`),C(`settings.vertical`,`crosshair.vertical.visible`),C(`drawingSettings.color`,`crosshair.horizontal.color`,`crosshair.vertical.color`),C(`drawingSettings.lineStyle`,`crosshair.horizontal.style`,`crosshair.vertical.style`),C(`drawingSettings.lineWidth`,`crosshair.horizontal.width`,`crosshair.vertical.width`),C(`settings.labelBackground`,`crosshair.labelBackground`),C(`settings.labelText`,`crosshair.labelTextColor`)]},{title:`settings.sessionBreaks`,rows:[w(`drawingSettings.color`,`sessionBreaks.color`,{from:`axis.price.lineColor`}),w(`drawingSettings.lineStyle`,`sessionBreaks.style`),w(`drawingSettings.lineWidth`,`sessionBreaks.width`)]},{title:`objects.drawings`,rows:[w(`settings.handles`,`drawings.handleColor`,T(`#ffffff`))]}],Ee=[{title:`settings.section.orders`,trading:!0,rows:[w(`ticket.buy`,`trading.buyColor`,T(n.DEFAULT_TRADING_CONFIG.orderColors?.buy)),w(`ticket.sell`,`trading.sellColor`,T(n.DEFAULT_TRADING_CONFIG.orderColors?.sell)),w(`settings.profit`,`trading.profitColor`,T(n.DEFAULT_TRADING_CONFIG.positionColors?.profit)),w(`settings.loss`,`trading.lossColor`,T(n.DEFAULT_TRADING_CONFIG.positionColors?.loss)),w(`account.entry`,`trading.entryColor`,T(n.DEFAULT_TRADING_CONFIG.positionColors?.entry))]},{title:`settings.section.signals`,rows:[w(`account.long`,`markers.longColor`,T(n.DEFAULT_SIGNAL_STYLE.longColor)),w(`account.short`,`markers.shortColor`,T(n.DEFAULT_SIGNAL_STYLE.shortColor)),w(`markers.neutral`,`markers.neutralColor`,T(n.DEFAULT_SIGNAL_STYLE.neutralColor))]},{title:`settings.section.tradeZones`,rows:[w(`settings.profit`,`tradeZones.profitColor`,T(n.DEFAULT_TRADE_ZONE_STYLE.profitColor)),w(`settings.loss`,`tradeZones.lossColor`,T(n.DEFAULT_TRADE_ZONE_STYLE.lossColor)),w(`settings.openTrade`,`tradeZones.activeColor`,T(n.DEFAULT_TRADE_ZONE_STYLE.activeColor))]}],De={upColor:`settings.up`,downColor:`settings.down`,wickUpColor:`settings.upWick`,wickDownColor:`settings.downWick`,color:`drawingSettings.color`,lineColor:`drawingSettings.color`,lineWidth:`drawingSettings.lineWidth`,topColor:`settings.areaTop`,bottomColor:`settings.areaBottom`},Oe=new Set([`candlestick`,`heikinAshi`,`volumeCandles`,`equivolume`]);function ke(e){let t=`series.${e}.`;return Object.keys(n.CHART_STYLE_KEYS).filter(e=>e.startsWith(t)).map(n=>{let r=n.slice(t.length),i=De[r]??`drawingSettings.color`;return Oe.has(e)&&r===`upColor`&&(i=`settings.upBody`),Oe.has(e)&&r===`downColor`&&(i=`settings.downBody`),e===`baseline`&&r===`upColor`&&(i=`settings.aboveBase`),e===`baseline`&&r===`downColor`&&(i=`settings.belowBase`),C(i,n)})}var E=[...new Set([...Object.keys(n.CHART_STYLE_KEYS).filter(e=>e.startsWith(`series.`)),...[...xe,...Te,...Ee].flatMap(e=>e.rows.flatMap(e=>e.keys)),...[...Ce,...we].flatMap(e=>e.keys)])],Ae=`/* === TradeCanvas Widget — Premium Styles === */
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-RF8OqOXy.cjs`),t=require(`../i18n-BsstZ9md.cjs`);let n=require(`@tradecanvas/commons`),r=require(`@tradecanvas/core`);function i(e,t,r={}){return(0,n.resampleBars)(e,t,{weekStartsOn:r.weekStartsOn??1,timeZone:r.timeZone})}function a(e){if(e.length<2)return 0;let t=[];for(let n=1;n<e.length;n++){let r=e[n].time-e[n-1].time;r>0&&t.push(r)}return t.length===0?0:(t.sort((e,t)=>e-t),t[Math.floor(t.length/2)])}var o=[{zone:`Pacific/Honolulu`,city:`Honolulu`},{zone:`America/Los_Angeles`,city:`Los Angeles`},{zone:`America/Denver`,city:`Denver`},{zone:`America/Chicago`,city:`Chicago`},{zone:`America/New_York`,city:`New York`},{zone:`America/Toronto`,city:`Toronto`},{zone:`America/Sao_Paulo`,city:`São Paulo`},{zone:`UTC`,city:`UTC`},{zone:`Europe/London`,city:`London`},{zone:`Europe/Berlin`,city:`Frankfurt`},{zone:`Europe/Paris`,city:`Paris`},{zone:`Europe/Zurich`,city:`Zurich`},{zone:`Africa/Johannesburg`,city:`Johannesburg`},{zone:`Europe/Istanbul`,city:`Istanbul`},{zone:`Europe/Moscow`,city:`Moscow`},{zone:`Asia/Dubai`,city:`Dubai`},{zone:`Asia/Kolkata`,city:`Mumbai`},{zone:`Asia/Bangkok`,city:`Bangkok`},{zone:`Asia/Ho_Chi_Minh`,city:`Ho Chi Minh City`},{zone:`Asia/Jakarta`,city:`Jakarta`},{zone:`Asia/Singapore`,city:`Singapore`},{zone:`Asia/Hong_Kong`,city:`Hong Kong`},{zone:`Asia/Shanghai`,city:`Shanghai`},{zone:`Asia/Taipei`,city:`Taipei`},{zone:`Asia/Seoul`,city:`Seoul`},{zone:`Asia/Tokyo`,city:`Tokyo`},{zone:`Australia/Sydney`,city:`Sydney`},{zone:`Pacific/Auckland`,city:`Auckland`}],s=/^-?\d+$/,c=840;function l(e){if(!s.test(e))return null;let t=Number(e);return Math.abs(t)<=c?t:null}function u(e){return!e||e===`local`?null:e===`exchange`?`exchange`:s.test(e)?l(e):(0,n.isValidTimeZone)(e)?e:null}function d(e){return e===null?`local`:String(e)}function f(e,t,r,i){let a=(0,n.offsetAt)(null,t),s=o.filter(({zone:e})=>(0,n.isValidTimeZone)(e)).map(({zone:e,city:r})=>{let i=(0,n.offsetAt)(e,t);return{value:e,label:e===`UTC`?`UTC`:`(${(0,n.tzLabel)(i)}) ${r}`,offset:i}}),c=u(e);typeof c==`number`&&s.push({value:e,label:(0,n.tzLabel)(c),offset:c}),s.sort((e,t)=>e.offset-t.offset);let l=[{value:`local`,label:`${r} (${(0,n.tzLabel)(a)})`,offset:a}];if(i){let e=(0,n.offsetAt)(i.zone&&(0,n.isValidTimeZone)(i.zone)?i.zone:`UTC`,t);l.push({value:`exchange`,label:`${i.label} (${(0,n.tzLabel)(e)})`,offset:e})}return[...l,...s]}var p=6,m=8,h=120;function g(e,t,n=`left`){let r=e.style,i=t.getBoundingClientRect();r.position=`fixed`,r.margin=`0`,r.top=r.bottom=r.left=r.right=``;let a=window.innerHeight-i.bottom-p-m,o=i.top-p-m;e.scrollHeight<=a||a>=o?(r.top=`${i.bottom+p}px`,r.bottom=`auto`,r.maxHeight=`${Math.max(h,a)}px`):(r.top=`auto`,r.bottom=`${window.innerHeight-i.top+p}px`,r.maxHeight=`${Math.max(h,o)}px`);let s=getComputedStyle(t).direction===`rtl`,c=n===`right`!==s,l=e.offsetWidth,u=c?i.right-l:i.left;r.left=`${Math.max(m,Math.min(u,window.innerWidth-l-m))}px`}var ee=700,_=class{select=null;panel=null;rows=[];active=-1;typed=``;typedAt=0;onOutside=e=>{let t=e.target;this.panel?.contains(t)||this.select?.contains(t)||this.close(!1)};onAway=()=>this.close(!1);onScroll=e=>{e.target instanceof Node&&this.panel?.contains(e.target)||this.close(!1)};watch=new MutationObserver(()=>{this.select&&!this.select.isConnected&&this.close(!1)});constructor(e){this.layer=e}isOpenFor(e){return this.select===e}owns(e){return e!==null&&(e===this.select||this.panel?.contains(e)===!0)}open(e){this.close(!1),this.select=e;let t=document.createElement(`div`);t.className=`tcw-dropdown tcw-select-menu`,t.setAttribute(`role`,`listbox`),t.id=`tcw-select-menu-${Math.random().toString(36).slice(2,9)}`;let n=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;n&&t.setAttribute(`aria-label`,n.trim()),t.style.minWidth=`${e.getBoundingClientRect().width}px`,this.rows=[];for(let n of e.children)if(n instanceof HTMLOptGroupElement){let e=document.createElement(`div`);e.className=`tcw-select-group`,e.textContent=n.label,t.appendChild(e);for(let e of n.querySelectorAll(`option`))this.addRow(t,e,n.disabled)}else n instanceof HTMLOptionElement&&this.addRow(t,n,!1);t.addEventListener(`mousedown`,e=>e.preventDefault());let r=e=>this.rows.findIndex(t=>t.el.contains(e.target));t.addEventListener(`click`,e=>{let t=r(e);t>=0&&this.pick(t)}),t.addEventListener(`mousemove`,e=>{let t=r(e);t>=0&&t!==this.active&&this.enabled(t)&&this.setActive(t,!1)}),this.layer().appendChild(t),this.panel=t,g(t,e),e.setAttribute(`aria-expanded`,`true`),e.setAttribute(`aria-controls`,t.id),this.setActive(this.rows.findIndex(e=>e.option.selected)),document.addEventListener(`pointerdown`,this.onOutside,!0),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0}),this.watch.observe(document.documentElement,{childList:!0,subtree:!0})}close(e){let t=this.select;t&&(document.removeEventListener(`pointerdown`,this.onOutside,!0),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}),this.watch.disconnect(),this.panel?.remove(),this.panel=null,this.rows=[],this.select=null,t.setAttribute(`aria-expanded`,`false`),t.removeAttribute(`aria-controls`),t.removeAttribute(`aria-activedescendant`),e&&t.isConnected&&t.focus())}key(e){if(!this.select)return!1;switch(e.key){case`ArrowDown`:return this.step(1),!0;case`ArrowUp`:return this.step(-1),!0;case`Home`:return this.setActive(this.nextEnabled(-1,1)),!0;case`End`:return this.setActive(this.nextEnabled(this.rows.length,-1)),!0;case`PageDown`:return this.step(8),!0;case`PageUp`:return this.step(-8),!0;case` `:return this.typed&&Date.now()-this.typedAt<=ee?(this.typeahead(` `),!0):(this.active>=0?this.pick(this.active):this.close(!0),!0);case`Enter`:return this.active>=0?this.pick(this.active):this.close(!0),!0;case`Escape`:return this.close(!0),!0;case`Tab`:return this.close(!1),!1;default:return e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey?(this.typeahead(e.key),!0):!1}}destroy(){this.close(!1)}addRow(e,t,n){let r=document.createElement(`div`);r.className=`tcw-select-option`,r.id=`${e.id}-${this.rows.length}`,r.setAttribute(`role`,`option`),r.setAttribute(`aria-selected`,String(t.selected)),(t.disabled||n)&&r.setAttribute(`aria-disabled`,`true`);let i=document.createElement(`span`);i.className=`tcw-select-option-text`,i.textContent=t.label||t.textContent||``,t.dir&&(i.dir=t.dir);let a=document.createElement(`span`);a.className=`tcw-select-check`,a.setAttribute(`aria-hidden`,`true`),r.append(a,i),e.appendChild(r),this.rows.push({option:t,el:r})}enabled(e){return this.rows[e]?.el.getAttribute(`aria-disabled`)!==`true`}nextEnabled(e,t){for(let n=e+t;n>=0&&n<this.rows.length;n+=t)if(this.enabled(n))return n;return-1}step(e){let t=e>0?1:-1,n=this.active;for(let r=0;r<Math.abs(e);r++){let e=this.nextEnabled(n,t);if(e<0)break;n=e}n>=0&&this.setActive(n)}setActive(e,t=!0){this.rows[this.active]?.el.classList.remove(`tcw-active`),this.active=e;let n=this.rows[e];n&&(n.el.classList.add(`tcw-active`),this.select?.setAttribute(`aria-activedescendant`,n.el.id),t&&n.el.scrollIntoView?.({block:`nearest`}))}typeahead(e){let t=Date.now();this.typed=t-this.typedAt>ee?e.toLowerCase():this.typed+e.toLowerCase(),this.typedAt=t;let n=e=>this.enabled(e)&&(this.rows[e].el.textContent??``).trim().toLowerCase().startsWith(this.typed),r=this.typed.length===1?this.active+1:Math.max(0,this.active);for(let e=0;e<this.rows.length;e++){let t=(r+e)%this.rows.length;if(n(t)){this.setActive(t);return}}}pick(e){let t=this.select,n=this.rows[e];if(!t||!n||!this.enabled(e))return;let r=!n.option.selected;n.option.selected=!0,this.close(!0),r&&(t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})))}},v=42,y=7,b=new Set([`US`,`CA`,`MX`,`BR`,`JP`,`KR`,`TW`,`HK`,`IL`,`PH`,`IN`,`ZA`,`AU`,`TH`,`SA`,`PE`,`CO`]);function x(e){try{let t=new Intl.Locale(e),n=t.getWeekInfo?.()??t.weekInfo;return n?n.firstDay===7?0:1:+!b.has(t.maximize().region??``)}catch{return 1}}function S(e,t,n){let r=(new Date(Date.UTC(e,t,1)).getUTCDay()-n+y)%y,i=[];for(let n=0;n<v;n++){let a=new Date(Date.UTC(e,t,1-r+n));i.push({year:a.getUTCFullYear(),month:a.getUTCMonth(),day:a.getUTCDate()})}return i}var te=e=>String(e).padStart(2,`0`),C=e=>`${String(e.year).padStart(4,`0`)}-${te(e.month+1)}-${te(e.day)}`;function ne(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e??``);return t?{year:Number(t[1]),month:Number(t[2])-1,day:Number(t[3])}:null}function re(){let e=new Date;return{year:e.getFullYear(),month:e.getMonth(),day:e.getDate()}}function ie(e,t){let n=new Date(Date.UTC(e.year,e.month,e.day+t));return{year:n.getUTCFullYear(),month:n.getUTCMonth(),day:n.getUTCDate()}}var ae=class{element;grid;titleEl;chosen=``;limits={};today=C(re());view={year:0,month:0};focusDay=re();constructor(e,t,n){this.locale=t,this.onPick=n;let r=document.createElement(`div`);r.className=`tcw-calendar`;let i=document.createElement(`div`);i.className=`tcw-calendar-head`;let a=document.createElement(`div`);a.className=`tcw-calendar-title`,a.setAttribute(`aria-live`,`polite`),i.append(this.navButton(e.prevMonth,-1),a,this.navButton(e.nextMonth,1));let o=document.createElement(`div`);o.className=`tcw-calendar-weekdays`,o.setAttribute(`aria-hidden`,`true`);let s=x(t),c=new Intl.DateTimeFormat(t,{weekday:`narrow`,timeZone:`UTC`});for(let e=0;e<y;e++){let t=document.createElement(`span`);t.className=`tcw-calendar-weekday`,t.textContent=c.format(new Date(Date.UTC(2023,0,1+(s+e)%y))),o.appendChild(t)}let l=document.createElement(`div`);l.className=`tcw-calendar-grid`,l.setAttribute(`role`,`grid`),l.addEventListener(`keydown`,e=>this.onKey(e)),l.addEventListener(`click`,e=>{let t=e.target.closest(`.tcw-calendar-day`);t&&!t.disabled&&t.dataset.date&&this.pick(t.dataset.date)});let u=document.createElement(`div`);u.className=`tcw-calendar-foot`;let d=document.createElement(`button`);d.type=`button`,d.className=`tcw-calendar-today`,d.textContent=e.today,d.addEventListener(`click`,()=>this.pick(this.today)),u.appendChild(d),r.append(i,o,l,u),this.element=r,this.grid=l,this.titleEl=a}show(e,t={}){this.chosen=e,this.limits=t,this.today=ne(t.today)?t.today:C(re());let n=this.clamp(ne(e)??ne(this.today));this.focusDay=n,this.view={year:n.year,month:n.month},this.render()}focusGrid(){this.grid.querySelector(`[tabindex="0"]`)?.focus()}navButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-calendar-nav`,n.setAttribute(`aria-label`,e),n.innerHTML=t<0?`<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3.5L5.5 8l4.5 4.5"/></svg>`:`<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6 3.5L10.5 8 6 12.5"/></svg>`,n.addEventListener(`click`,()=>this.turn(t)),n}turn(e){let t=new Date(Date.UTC(this.view.year,this.view.month+e,1));this.view={year:t.getUTCFullYear(),month:t.getUTCMonth()};let n=new Date(Date.UTC(this.view.year,this.view.month+1,0)).getUTCDate();this.focusDay=this.clamp({...this.view,day:Math.min(this.focusDay.day,n)}),this.view={year:this.focusDay.year,month:this.focusDay.month},this.render()}clamp(e){let t=C(e),n=ne(this.limits.min),r=ne(this.limits.max);return n&&t<C(n)?n:r&&t>C(r)?r:e}allowed(e){let{min:t,max:n}=this.limits;return!(t&&e<t)&&!(n&&e>n)}render(){let e=this.locale;this.titleEl.textContent=new Intl.DateTimeFormat(e,{month:`long`,year:`numeric`,timeZone:`UTC`}).format(new Date(Date.UTC(this.view.year,this.view.month,1)));let t=this.today,n=C(this.focusDay),r=new Intl.DateTimeFormat(e,{dateStyle:`full`,timeZone:`UTC`});this.grid.textContent=``;let i=null;for(let[a,o]of S(this.view.year,this.view.month,x(e)).entries()){a%y===0&&(i=document.createElement(`div`),i.className=`tcw-calendar-week`,i.setAttribute(`role`,`row`),this.grid.appendChild(i));let e=C(o),s=document.createElement(`button`);s.type=`button`,s.className=`tcw-calendar-day`,s.dataset.date=e,s.setAttribute(`role`,`gridcell`),s.textContent=String(o.day),s.setAttribute(`aria-label`,r.format(new Date(Date.UTC(o.year,o.month,o.day)))),s.setAttribute(`aria-selected`,String(e===this.chosen)),s.tabIndex=e===n?0:-1,o.month!==this.view.month&&s.classList.add(`tcw-outside`),e===t&&s.classList.add(`tcw-today`),this.allowed(e)||(s.disabled=!0),i?.appendChild(s)}}onKey(e){let t={ArrowLeft:-1,ArrowRight:1,ArrowUp:-y,ArrowDown:y},n=this.element.isConnected&&getComputedStyle(this.element).direction===`rtl`;if(e.key in t){let r=n&&(e.key===`ArrowLeft`||e.key===`ArrowRight`)?-t[e.key]:t[e.key];this.moveFocus(ie(this.focusDay,r))}else if(e.key===`PageUp`||e.key===`PageDown`)this.turn(e.key===`PageUp`?-1:1),this.focusGrid();else if(e.key===`Home`||e.key===`End`){let t=new Date(Date.UTC(this.view.year,this.view.month+1,0)).getUTCDate();this.moveFocus({...this.view,day:e.key===`Home`?1:t})}else if(e.key===`Enter`||e.key===` `)this.pick(C(this.focusDay));else return;e.preventDefault()}moveFocus(e){let t=this.clamp(e);this.focusDay=t,(t.year!==this.view.year||t.month!==this.view.month)&&(this.view={year:t.year,month:t.month}),this.render(),this.focusGrid()}pick(e){this.allowed(e)&&this.onPick(e)}},oe=class{input=null;view=null;onOutside=e=>{let t=e.target;this.view?.element.contains(t)||this.input?.contains(t)||this.close(!1)};onAway=()=>this.close(!1);onScroll=e=>{e.target instanceof Node&&this.view?.element.contains(e.target)||this.close(!1)};watch=new MutationObserver(()=>{this.input&&!this.input.isConnected&&this.close(!1)});constructor(e,t,n){this.layer=e,this.labels=t,this.locale=n}isOpenFor(e){return this.input===e}owns(e){return e!==null&&(e===this.input||this.view?.element.contains(e)===!0)}open(e){this.close(!1),this.input=e;let t=new ae(this.labels(),this.locale(),e=>this.pick(e));t.show(e.value,{min:e.min||void 0,max:e.max||void 0});let n=t.element;n.setAttribute(`role`,`dialog`);let r=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;r&&n.setAttribute(`aria-label`,r.trim()),n.addEventListener(`mousedown`,e=>{e.target.closest(`button`)||e.preventDefault()}),n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&(e.preventDefault(),this.close(!0))}),this.view=t,this.layer().appendChild(n),g(n,e),document.addEventListener(`pointerdown`,this.onOutside,!0),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0}),this.watch.observe(document.documentElement,{childList:!0,subtree:!0})}close(e){let t=this.input;t&&(document.removeEventListener(`pointerdown`,this.onOutside,!0),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}),this.watch.disconnect(),this.view?.element.remove(),this.view=null,this.input=null,e&&t.isConnected&&t.focus())}focusGrid(){this.view?.focusGrid()}destroy(){this.close(!1)}pick(e){let t=this.input;if(!t)return;let n=t.value!==e;t.value=e,this.close(!0),n&&(t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0})))}},se=()=>typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches,ce=()=>typeof CSS>`u`||typeof CSS.supports!=`function`||CSS.supports(`selector(::-webkit-calendar-picker-indicator)`);function le(e){if(!(e instanceof Element))return null;let t=e.closest(`select`);return!t||t.matches(`:disabled`)||t.multiple||t.size>1?null:t}function ue(e){return!(e instanceof HTMLInputElement)||e.type!==`date`||e.dataset.tcwCalendar===`inline`||e.matches(`:disabled`)||e.readOnly?null:e}function de(e,t){let n=new _(t.layer),r=new oe(t.layer,t.labels,t.locale),i=t.native??se,a=t.calendar??ce,o=new WeakSet,s=e=>o.has(e)?!1:(o.add(e),!0),c=e=>{if(e.button!==0||i()||!s(e))return;let t=le(e.target);if(t){if(e.preventDefault(),n.isOpenFor(t)){n.close(!0);return}t.focus(),n.open(t)}},l=e=>{if(i()||!a()||!s(e))return;let t=ue(e.target);t&&(e.preventDefault(),r.isOpenFor(t)||r.open(t))},u=e=>{if(i()||!s(e))return;let t=le(e.target);if(t){if(n.isOpenFor(t)){n.key(e)&&(e.preventDefault(),e.stopPropagation());return}(e.key===`Enter`||e.key===` `||e.altKey&&(e.key===`ArrowDown`||e.key===`ArrowUp`)||e.key===`F4`)&&(e.preventDefault(),e.stopPropagation(),n.open(t));return}let o=ue(e.target);!o||!a()||(e.key===`Escape`&&r.isOpenFor(o)?(e.preventDefault(),e.stopPropagation(),r.close(!0)):(e.altKey&&e.key===`ArrowDown`||e.key===`F4`)&&(e.preventDefault(),r.isOpenFor(o)||r.open(o),r.focusGrid()))},d=e=>{if(!s(e))return;let t=e.target instanceof Node?e.target:null,i=e.relatedTarget instanceof Node?e.relatedTarget:null;n.owns(t)&&!n.owns(i)&&n.close(!1),r.owns(t)&&!r.owns(i)&&r.close(!1)};for(let t of e)t.addEventListener(`mousedown`,c,!0),t.addEventListener(`click`,l,!0),t.addEventListener(`keydown`,u,!0),t.addEventListener(`focusout`,d,!0);return()=>{for(let t of e)t.removeEventListener(`mousedown`,c,!0),t.removeEventListener(`click`,l,!0),t.removeEventListener(`keydown`,u,!0),t.removeEventListener(`focusout`,d,!0);n.destroy(),r.destroy()}}var fe=[{label:`Candlestick`,value:`candlestick`},{label:`Line`,value:`line`},{label:`Area`,value:`area`},{label:`Bar`,value:`bar`},{label:`Heikin-Ashi`,value:`heikinAshi`},{label:`Hollow Candle`,value:`hollowCandle`},{label:`Baseline`,value:`baseline`},{label:`Volume Candles`,value:`volumeCandles`},{label:`Equivolume`,value:`equivolume`},{label:`HLC Area`,value:`hlcArea`},{label:`Step Line`,value:`stepLine`},{label:`Line + Markers`,value:`lineWithMarkers`},{label:`High-Low`,value:`hiLo`},{label:`Renko`,value:`renko`},{label:`Line Break`,value:`lineBreak`},{label:`Kagi`,value:`kagi`},{label:`Point & Figure`,value:`pointAndFigure`},{label:`Range Bars`,value:`rangeBars`}],pe=[{label:`Lines`,section:`lines`,tools:[{label:`Trend Line`,value:`trendLine`},{label:`Ray`,value:`ray`},{label:`Extended Line`,value:`extendedLine`},{label:`Info Line`,value:`infoLine`},{label:`Trend Angle`,value:`trendAngle`}]},{label:`Horizontal/Vertical`,section:`lines`,tools:[{label:`Horizontal Line`,value:`horizontalLine`},{label:`Horizontal Ray`,value:`horizontalRay`},{label:`Vertical Line`,value:`verticalLine`},{label:`Cross Line`,value:`crossLine`}]},{label:`Channels`,section:`lines`,tools:[{label:`Parallel Channel`,value:`parallelChannel`},{label:`Regression Channel`,value:`regressionChannel`}]},{label:`Fibonacci`,section:`fibonacci`,tools:[{label:`Fib Retracement`,value:`fibRetracement`},{label:`Fib Extension`,value:`fibExtension`},{label:`Fib Channel`,value:`fibChannel`},{label:`Fib Time Zones`,value:`fibTimeZones`},{label:`Fib Speed Resistance Fan`,value:`fibSpeedResistanceFan`},{label:`Fib Speed Resistance Arcs`,value:`fibArcs`},{label:`Fib Circles`,value:`fibCircles`},{label:`Fib Spiral`,value:`fibSpiral`},{label:`Fib Wedge`,value:`fibWedge`}]},{label:`Gann & Pitchforks`,section:`fibonacci`,tools:[{label:`Pitchfork`,value:`pitchfork`},{label:`Schiff Pitchfork`,value:`schiffPitchfork`},{label:`Modified Schiff Pitchfork`,value:`modifiedSchiffPitchfork`},{label:`Gann Fan`,value:`gannFan`},{label:`Gann Box`,value:`gannBox`},{label:`Gann Square`,value:`gannSquare`},{label:`Pitchfan`,value:`pitchfan`}]},{label:`Cycles`,section:`fibonacci`,tools:[{label:`Cyclic Lines`,value:`cyclicLines`},{label:`Time Cycles`,value:`timeCycles`},{label:`Sine Line`,value:`sineLine`}]},{label:`Patterns`,section:`patterns`,tools:[{label:`XABCD Pattern`,value:`xabcdPattern`},{label:`ABCD Pattern`,value:`abcdPattern`},{label:`Head and Shoulders`,value:`headAndShoulders`},{label:`Cypher Pattern`,value:`cypherPattern`},{label:`Three Drives Pattern`,value:`threeDrives`}]},{label:`Elliott Waves`,section:`patterns`,tools:[{label:`Elliott Wave`,value:`elliottWave`},{label:`Elliott Impulse Wave`,value:`elliottImpulse`},{label:`Elliott Correction Wave`,value:`elliottCorrection`},{label:`Elliott Triangle Wave`,value:`elliottTriangle`},{label:`Elliott Double Combo Wave`,value:`elliottDoubleCombo`},{label:`Elliott Triple Combo Wave`,value:`elliottTripleCombo`}]},{label:`Forecasting`,section:`forecasting`,tools:[{label:`Long/Short Position`,value:`riskReward`},{label:`Anchored VWAP`,value:`anchoredVWAP`},{label:`Fixed Range Volume Profile`,value:`volumeProfileRange`},{label:`Forecast`,value:`forecast`},{label:`Projection`,value:`projection`},{label:`Bars Pattern`,value:`barsPattern`}]},{label:`Measure`,section:`forecasting`,tools:[{label:`Price Range`,value:`priceRange`},{label:`Date Range`,value:`dateRange`},{label:`Date and Price Range`,value:`dateAndPriceRange`},{label:`Measure`,value:`measure`}]},{label:`Shapes`,section:`annotation`,tools:[{label:`Rectangle`,value:`rectangle`},{label:`Circle`,value:`circle`},{label:`Ellipse`,value:`ellipse`},{label:`Triangle`,value:`triangle`},{label:`Polyline`,value:`polyline`},{label:`Curve`,value:`curve`},{label:`Arc`,value:`arc`}]},{label:`Brushes`,section:`annotation`,tools:[{label:`Brush`,value:`brush`},{label:`Highlighter`,value:`highlighter`},{label:`Path`,value:`path`}]},{label:`Annotation`,section:`annotation`,tools:[{label:`Text`,value:`text`},{label:`Price Label`,value:`priceLabel`},{label:`Arrow`,value:`arrow`},{label:`Note`,value:`note`},{label:`Callout`,value:`callout`},{label:`Flag Mark`,value:`flag`},{label:`Arrow Mark`,value:`arrowMark`},{label:`Icon`,value:`icon`},{label:`Signpost`,value:`signpost`},{label:`Balloon`,value:`balloon`},{label:`Anchored Text`,value:`anchoredText`},{label:`Anchored Note`,value:`anchoredNote`}]}],me=[`BTCUSDT`,`ETHUSDT`,`SOLUSDT`,`BNBUSDT`],he={gridVisible:!0,volumeVisible:!0,volumeProfileVisible:!1,marketProfileVisible:!1,marketProfileSplit:!1,marketProfileLetters:!1,marketProfileBuckets:48,marketProfileOpacity:.32,depthHeatmapVisible:!1,depthHeatmapOpacity:.7,sessionShadingVisible:!1,pivotMarkersVisible:!1,pivotStrength:5,pivotStructureLabels:!1,periodLevelsVisible:!1,periodLevelsPeriod:`day`,legendVisible:!0,barCountdown:!0,indicatorValueLabels:!1,alignAxisLabels:!0,logScale:!1,scaleMode:`regular`,autoScale:!0,invertScale:!1,leftPriceScale:!1,crosshairMode:`magnet`,numberLocale:`en-US`,timezone:`local`,highLowLines:!1,mainSeriesVisible:!0,extendedHours:!0,chartTypeOptions:{}},w=(e,...t)=>({label:e,keys:t}),T=(e,t,n={})=>({label:e,keys:[t],auto:n}),E=e=>({hint:e}),ge={from:`panes.titleColor`},_e={title:`settings.section.lastPrice`,rows:[w(`settings.priceLine`,`lastPrice.visible`),w(`settings.up`,`lastPrice.upColor`),w(`settings.down`,`lastPrice.downColor`),w(`drawingSettings.lineStyle`,`lastPrice.style`),w(`drawingSettings.lineWidth`,`lastPrice.width`)]},ve={title:`settings.volume`,rows:[w(`settings.up`,`volume.upColor`),w(`settings.down`,`volume.downColor`)]},ye={title:`settings.highLowLines`,rows:[T(`drawingSettings.color`,`highLow.color`,ge)]},be=[_e,ve,ye],xe=[w(`settings.legendText`,`legend.textColor`),w(`settings.legendLabels`,`legend.labelColor`)],Se=[...xe,w(`settings.paneTitles`,`panes.titleColor`)],Ce=[w(`drawingSettings.text`,`axis.price.textColor`,`axis.time.textColor`),w(`settings.scaleLines`,`axis.price.lineColor`,`axis.time.lineColor`)],we=[{title:`settings.section.background`,rows:[w(`settings.background`,`background.color`),w(`settings.paneBackground`,`panes.background`),w(`settings.paneSeparator`,`panes.separatorColor`),T(`settings.watermark`,`watermark.color`,ge)]},{title:`settings.gridLines`,rows:[w(`settings.horizontal`,`grid.horizontal.visible`),w(`settings.vertical`,`grid.vertical.visible`),w(`drawingSettings.color`,`grid.horizontal.color`,`grid.vertical.color`),w(`drawingSettings.lineStyle`,`grid.horizontal.style`,`grid.vertical.style`),w(`drawingSettings.lineWidth`,`grid.horizontal.width`,`grid.vertical.width`)]},{title:`settings.crosshairMode`,rows:[w(`settings.horizontal`,`crosshair.horizontal.visible`),w(`settings.vertical`,`crosshair.vertical.visible`),w(`drawingSettings.color`,`crosshair.horizontal.color`,`crosshair.vertical.color`),w(`drawingSettings.lineStyle`,`crosshair.horizontal.style`,`crosshair.vertical.style`),w(`drawingSettings.lineWidth`,`crosshair.horizontal.width`,`crosshair.vertical.width`),w(`settings.labelBackground`,`crosshair.labelBackground`),w(`settings.labelText`,`crosshair.labelTextColor`)]},{title:`settings.sessionBreaks`,rows:[T(`drawingSettings.color`,`sessionBreaks.color`,{from:`axis.price.lineColor`}),T(`drawingSettings.lineStyle`,`sessionBreaks.style`),T(`drawingSettings.lineWidth`,`sessionBreaks.width`)]},{title:`objects.drawings`,rows:[T(`settings.handles`,`drawings.handleColor`,E(`#ffffff`))]}],Te=[{title:`settings.section.orders`,trading:!0,rows:[T(`ticket.buy`,`trading.buyColor`,E(n.DEFAULT_TRADING_CONFIG.orderColors?.buy)),T(`ticket.sell`,`trading.sellColor`,E(n.DEFAULT_TRADING_CONFIG.orderColors?.sell)),T(`settings.profit`,`trading.profitColor`,E(n.DEFAULT_TRADING_CONFIG.positionColors?.profit)),T(`settings.loss`,`trading.lossColor`,E(n.DEFAULT_TRADING_CONFIG.positionColors?.loss)),T(`account.entry`,`trading.entryColor`,E(n.DEFAULT_TRADING_CONFIG.positionColors?.entry))]},{title:`settings.section.signals`,rows:[T(`account.long`,`markers.longColor`,E(n.DEFAULT_SIGNAL_STYLE.longColor)),T(`account.short`,`markers.shortColor`,E(n.DEFAULT_SIGNAL_STYLE.shortColor)),T(`markers.neutral`,`markers.neutralColor`,E(n.DEFAULT_SIGNAL_STYLE.neutralColor))]},{title:`settings.section.tradeZones`,rows:[T(`settings.profit`,`tradeZones.profitColor`,E(n.DEFAULT_TRADE_ZONE_STYLE.profitColor)),T(`settings.loss`,`tradeZones.lossColor`,E(n.DEFAULT_TRADE_ZONE_STYLE.lossColor)),T(`settings.openTrade`,`tradeZones.activeColor`,E(n.DEFAULT_TRADE_ZONE_STYLE.activeColor))]}],Ee={upColor:`settings.up`,downColor:`settings.down`,wickUpColor:`settings.upWick`,wickDownColor:`settings.downWick`,color:`drawingSettings.color`,lineColor:`drawingSettings.color`,lineWidth:`drawingSettings.lineWidth`,topColor:`settings.areaTop`,bottomColor:`settings.areaBottom`},De=new Set([`candlestick`,`heikinAshi`,`volumeCandles`,`equivolume`]);function Oe(e){let t=`series.${e}.`;return Object.keys(n.CHART_STYLE_KEYS).filter(e=>e.startsWith(t)).map(n=>{let r=n.slice(t.length),i=Ee[r]??`drawingSettings.color`;return De.has(e)&&r===`upColor`&&(i=`settings.upBody`),De.has(e)&&r===`downColor`&&(i=`settings.downBody`),e===`baseline`&&r===`upColor`&&(i=`settings.aboveBase`),e===`baseline`&&r===`downColor`&&(i=`settings.belowBase`),w(i,n)})}var ke=[...new Set([...Object.keys(n.CHART_STYLE_KEYS).filter(e=>e.startsWith(`series.`)),...[...be,...we,...Te].flatMap(e=>e.rows.flatMap(e=>e.keys)),...[...Se,...Ce].flatMap(e=>e.keys)])],Ae=`/* === TradeCanvas Widget — Premium Styles === */
|
|
2
2
|
|
|
3
3
|
/*
|
|
4
4
|
* The HTML \`hidden\` attribute only sets \`display: none\` via the UA stylesheet,
|
|
@@ -7699,7 +7699,7 @@ img.tcw-ss-badge {
|
|
|
7699
7699
|
${je}
|
|
7700
7700
|
${Me}
|
|
7701
7701
|
${Ne}
|
|
7702
|
-
${Ge()}`,document.head.insertBefore(e,document.head.firstChild)}function $e(){if(Xe--,Xe>0)return;let e=document.getElementById(Ze);e&&e.remove()}var et=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function O(e,t=14){let r=et(n.UI_ICONS,e);return r?(0,n.iconSvg)(r,t):``}function tt(e,t=16){return(0,n.iconSvg)(et(n.DRAWING_TOOL_ICONS,e)??n.UI_ICONS.penLine,t)}function nt(e,t=14){return(0,n.iconSvg)(et(n.CHART_TYPE_ICONS,e)??n.UI_ICONS.barChart,t)}function k(e){return e.replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e])}var rt=class{trigger;panel;_isOpen=!1;onOutsideClick;onEscapeKey;onTriggerClick;layer;align;onAway=()=>this.close();onScroll=e=>{e.target instanceof Node&&this.panel.contains(e.target)||this.close()};constructor(e,t={}){this.trigger=e,this.layer=t.layer??null,this.align=t.align??`left`,this.panel=document.createElement(`div`),this.panel.className=`tcw-dropdown`,this.panel.style.minWidth=t.width??`200px`,this.panel.style.display=`none`,this.layer?(this.layer().appendChild(this.panel),this.panel.addEventListener(`click`,()=>this.close())):(this.align===`right`?this.panel.style.insetInlineEnd=`0px`:this.panel.style.insetInlineStart=`0px`,e.style.position=`relative`,e.appendChild(this.panel)),this.onTriggerClick=()=>{this._isOpen?this.close():this.open()},this.onOutsideClick=e=>{let t=e.target;!this.trigger.contains(t)&&!this.panel.contains(t)&&this.close()},this.onEscapeKey=e=>{e.key===`Escape`&&this.close()},e.addEventListener(`click`,this.onTriggerClick)}setContent(e){this.panel.innerHTML=e}open(){if(!this._isOpen){if(this._isOpen=!0,this.layer){let e=this.layer();this.panel.parentElement!==e&&e.appendChild(this.panel)}this.panel.style.display=``,this.layer&&(this.place(),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0})),document.addEventListener(`pointerdown`,this.onOutsideClick),document.addEventListener(`keydown`,this.onEscapeKey)}}close(){this._isOpen&&(this._isOpen=!1,this.panel.style.display=`none`,document.removeEventListener(`pointerdown`,this.onOutsideClick),document.removeEventListener(`keydown`,this.onEscapeKey),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}))}isOpen(){return this._isOpen}destroy(){this.close(),this.trigger.removeEventListener(`click`,this.onTriggerClick),this.panel.remove()}place(){g(this.panel,this.trigger,this.align)}},it=4,at=2,ot=150,st=`[role=menuitem], [role=menuitemcheckbox], [role=menuitemradio]`,ct=`(max-width: 640px)`,lt=`tcw:back`,ut=new Set;function dt(e,t,n,r=e,i=!1){let a=i?r-t>=0?r-t:e:e+t>n?r-t:e;return Math.max(0,Math.min(a,n-t))}function ft(e){return e.radio?`menuitemradio`:e.checked===void 0?`menuitem`:`menuitemcheckbox`}function pt(e){let t=`<span class="tcw-context-icon"></span>`;return e.radio?e.checked?`<span class="tcw-context-icon tcw-context-dot"></span>`:t:e.checked?O(`check`,14):e.icon&&O(e.icon,14)||t}var A=class e{el;onPick=null;onRemove=null;returnFocus=null;anchor=null;child=null;parent=null;hoverTimer=null;hoverItem=null;onDocPointer=e=>{let t=e.target;this.holds(t)||this.anchor?.contains(t)||this.close()};onWheel=e=>{this.holds(e.target)||this.close()};onAway=()=>this.close();constructor(e,t,n=``){this.host=e,this.backLabel=n,this.el=document.createElement(`div`),this.el.className=`tcw-context-menu`,this.el.setAttribute(`role`,`menu`),this.el.setAttribute(`aria-label`,t),this.el.hidden=!0,this.el.addEventListener(`keydown`,e=>this.onKeyDown(e)),e.appendChild(this.el)}open(e,t,n,r,i,a,o=t,s=!1){this.show(e,{x:t,y:n,xBack:o,yBack:n,before:s},r,i,a,!0)}openUnder(e,t,n,r=`start`,i=at){let a=t.getBoundingClientRect(),o=this.host.getBoundingClientRect(),s=r===`end`!==this.rtl();this.open(e,a.left-o.left,a.bottom-o.top+i,n,t,void 0,a.right-o.left,s)}openBeside(e,t,n){let r=t.getBoundingClientRect(),i=this.host.getBoundingClientRect(),a=r.right-i.left+at,o=r.left-i.left-at;this.show(e,{x:a,y:r.top-i.top,xBack:o,yBack:r.bottom-i.top,before:this.rtl()},n,t,void 0,!0),this.returnFocus=t}static closeAnchoredTo(e){let t=[...ut].filter(t=>t.anchor===e);for(let e of t)e.close();return t.length>0}static focusedAnchor(){return[...ut].find(e=>e.anchor!==null&&e.hasFocus())?.anchor??null}close(){if(this.clearHover(),this.child?.close(),this.el.hidden)return;ut.delete(this);let e=!this.parent||this.el.contains(document.activeElement);this.el.hidden=!0,this.onPick=null,this.onRemove=null,this.anchor?.setAttribute(`aria-expanded`,`false`),this.anchor=null,document.removeEventListener(`pointerdown`,this.onDocPointer,!0),document.removeEventListener(`wheel`,this.onWheel,{capture:!0}),window.removeEventListener(`resize`,this.onAway),window.removeEventListener(`blur`,this.onAway),e&&this.returnFocus?.isConnected&&this.returnFocus.focus({preventScroll:!0}),this.returnFocus=null}isOpen(){return!this.el.hidden}hasFocus(){return document.activeElement!==null&&this.holds(document.activeElement)}destroy(){this.close(),this.child?.destroy(),this.el.remove()}show(e,t,n,r,i,a){this.clearHover(),this.child?.close(),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.onPick=n,this.onRemove=i??null,this.anchor=r??null,this.anchor?.setAttribute(`aria-expanded`,`true`),this.el.replaceChildren(...e.map(e=>this.entry(e))),this.el.hidden=!1,ut.add(this);let o=this.host.getBoundingClientRect(),s=Math.min(this.host.clientWidth,window.innerWidth-o.left)-it,c=Math.min(this.host.clientHeight,window.innerHeight-o.top)-it;this.el.style.maxHeight=`${Math.max(0,c-this.frameHeight())}px`,this.el.style.left=`${dt(t.x,this.el.offsetWidth,s,t.xBack,t.before)}px`,this.el.style.top=`${dt(t.y,this.el.offsetHeight,c,t.yBack)}px`,document.addEventListener(`pointerdown`,this.onDocPointer,!0),document.addEventListener(`wheel`,this.onWheel,{capture:!0,passive:!0}),window.addEventListener(`resize`,this.onAway),window.addEventListener(`blur`,this.onAway);let l=this.revealChoice();a&&(l??this.items()[0])?.focus({preventScroll:!0})}frameHeight(){let e=getComputedStyle(this.el);if(e.boxSizing===`border-box`)return 0;let t=e=>parseFloat(e)||0;return t(e.paddingTop)+t(e.paddingBottom)+t(e.borderTopWidth)+t(e.borderBottomWidth)}revealChoice(){let e=this.el.querySelector(`[role=menuitemradio][aria-checked=true]`);return!e||e.offsetTop+e.offsetHeight<=this.el.clientHeight?null:(this.el.scrollTop=e.offsetTop-(this.el.clientHeight-e.offsetHeight)/2,e)}rtl(){return this.host.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`}holds(e){return this.el.contains(e)||(this.child?.holds(e)??!1)}entry(e){if(e===`separator`){let e=document.createElement(`div`);return e.className=`tcw-context-sep`,e.setAttribute(`role`,`separator`),e}let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-context-item${e.danger?` tcw-context-danger`:``}`,t.setAttribute(`role`,ft(e)),(e.radio||e.checked!==void 0)&&t.setAttribute(`aria-checked`,String(e.checked??!1)),t.tabIndex=-1,t.dataset.id=e.id,t.innerHTML=pt(e);let n=document.createElement(`span`);n.className=`tcw-context-label`,n.textContent=e.label,t.appendChild(n),this.appendEnd(t,e);let r=e.submenu;return t.addEventListener(`pointermove`,n=>{n.pointerType!==`touch`&&this.hover(t,e.label,r)}),t.addEventListener(`click`,()=>{r?this.openSubmenu(t,e.label,r,!0):this.pick(e.id)}),e.remove?this.removableRow(t,e.remove):t}appendEnd(e,t){if(t.count!==void 0){let n=document.createElement(`span`);n.className=`tcw-context-count`,n.textContent=String(t.count),e.appendChild(n)}if(t.shortcut){e.setAttribute(`aria-keyshortcuts`,t.shortcut);let n=document.createElement(`kbd`);n.className=`tcw-context-key`,n.setAttribute(`aria-hidden`,`true`),n.textContent=t.shortcut,e.appendChild(n)}t.submenu&&(e.setAttribute(`aria-haspopup`,`menu`),e.setAttribute(`aria-expanded`,`false`),e.insertAdjacentHTML(`beforeend`,O(`chevronRight`,12)),e.lastElementChild?.classList.add(`tcw-context-more`))}removableRow(e,t){e.setAttribute(`aria-keyshortcuts`,`Delete`);let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-context-remove`,n.tabIndex=-1,n.setAttribute(`aria-hidden`,`true`),n.title=t,n.innerHTML=O(`x`,12),n.addEventListener(`click`,()=>this.remove(e));let r=document.createElement(`div`);return r.className=`tcw-context-row`,r.setAttribute(`role`,`none`),r.append(e,n),r}openSubmenu(e,t,n,r){this.clearHover();let i=this.child??this.makeChild();if(i.isOpen()&&i.anchor===e){r&&i.items()[0]?.focus({preventScroll:!0});return}i.close(),i.el.setAttribute(`aria-label`,t);let a=this.host.getBoundingClientRect(),o=e.getBoundingClientRect(),s={x:o.right-a.left,y:o.top-a.top,xBack:o.left-a.left,yBack:o.bottom-a.top,before:this.rtl()},c=window.matchMedia?.(ct).matches??!1,l=c?[{id:lt,label:t,icon:`chevronLeft`},`separator`,...n]:n;i.show(l,s,e=>{e!==lt&&this.pick(e)},e,e=>this.onRemove?.(e),r);let u=c?i.el.querySelector(`[data-id="${lt}"]`):null;u?.classList.add(`tcw-context-back`),u&&this.backLabel&&u.setAttribute(`aria-label`,`${this.backLabel}: ${t}`),i.returnFocus=e}makeChild(){let t=new e(this.host,``,this.backLabel);return t.parent=this,t.el.addEventListener(`pointerenter`,()=>this.clearHover()),this.child=t,t}hover(e,t,n){if(this.hoverTimer!==null&&this.hoverItem===e)return;this.clearHover();let r=this.child?.isOpen()?this.child.anchor:null;(n?r===e:r===null)||(this.hoverItem=e,this.hoverTimer=setTimeout(()=>{this.hoverTimer=null,this.hoverItem=null,n?this.openSubmenu(e,t,n,!1):this.child?.close()},ot))}clearHover(){this.hoverItem=null,this.hoverTimer!==null&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}remove(e){let t=e.dataset.id,n=e.closest(`.tcw-context-row`);if(!t||!n)return;let r=this.items().indexOf(e);this.onRemove?.(t),n.remove();let i=[...this.el.children].filter((e,t,n)=>e.classList.contains(`tcw-context-sep`)&&(t===0||t===n.length-1||n[t-1].classList.contains(`tcw-context-sep`)));for(let e of i)e.remove();let a=this.items();if(a.length===0){this.close();return}a[Math.min(r,a.length-1)].focus({preventScroll:!0})}pick(e){let t=this.onPick;this.close(),t?.(e)}items(){return[...this.el.querySelectorAll(st)]}onKeyDown(e){let t=this.items(),n=t.indexOf(document.activeElement),[r,i]=this.rtl()?[`ArrowLeft`,`ArrowRight`]:[`ArrowRight`,`ArrowLeft`],a=-1;if(e.key===`ArrowDown`)a=(n+1)%t.length;else if(e.key===`ArrowUp`)a=(n-1+t.length)%t.length;else if(e.key===`Home`)a=0;else if(e.key===`End`)a=t.length-1;else if(e.key===r&&t[n]?.hasAttribute(`aria-haspopup`)){e.preventDefault(),t[n].click();return}else if(e.key===i&&this.parent){e.preventDefault(),this.close();return}else if(e.key===`Delete`&&n>=0){e.preventDefault(),this.remove(t[n]);return}else if(e.key===`Escape`||e.key===`Tab`){e.preventDefault(),e.stopPropagation();let t=this;for(;e.key===`Tab`&&t.parent;)t=t.parent;t.close();return}else return;e.preventDefault(),this.child?.close(),t[a]?.focus({preventScroll:!0})}},mt=[`en-US`,`en-GB`,`en-IN`,`de-DE`,`fr-FR`,`es-ES`,`it-IT`,`pt-BR`,`ru-RU`,`tr-TR`,`vi-VN`,`id-ID`,`th-TH`,`zh-CN`,`zh-TW`,`ja-JP`,`ko-KR`],ht=65234;function gt(e){return(e&&!mt.includes(e)?[e,...mt]:mt).map(e=>{let t;try{t=new Intl.NumberFormat(e,{minimumFractionDigits:2,maximumFractionDigits:2}).format(ht)}catch{t=``}return{value:e,label:t?`${e} (${t})`:e}})}var _t={Lines:`toolGroup.lines`,"Horizontal/Vertical":`toolGroup.horizontalVertical`,Channels:`toolGroup.channels`,Fibonacci:`toolGroup.fibonacci`,Shapes:`toolGroup.shapes`,"Gann & Pitchforks":`toolGroup.gannPitchforks`,Patterns:`toolGroup.patterns`,Measure:`toolGroup.measure`,Annotation:`toolGroup.annotation`,Forecasting:`toolGroup.forecasting`,Brushes:`toolGroup.brushes`,Cycles:`toolGroup.cycles`,"Elliott Waves":`toolGroup.elliott`};function vt(e,t){let n=`chartType.${e.value}`,r=t(n);return r===n?e.label:r}function yt(e,t){return e.map(e=>({...e,label:_t[e.label]?t(_t[e.label]):e.label,tools:e.tools.map(e=>{let n=`tool.${e.value}`,r=t(n);return{...e,label:r===n?e.label:r}})}))}var bt=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`,`1w`,`1M`],xt=[`1m`,`5m`,`15m`,`1h`,`4h`,`1d`],St=6;function Ct(e){let t=e.slice(-1);return t===`h`||t===`d`||t===`w`?e.slice(0,-1)+t.toUpperCase():e}var wt=e=>Number.isFinite((0,n.timeframeToMs)(e))||(0,n.tickBarCount)(e)!==null,Tt=(e,t)=>{let r=(0,n.tickBarCount)(e),i=(0,n.tickBarCount)(t);return r!==null||i!==null?r===null?1:i===null?-1:r-i:(0,n.timeframeToMs)(e)-(0,n.timeframeToMs)(t)};function Et(e,t){let n=t?.length?t:null,r=e?.length?e:n??bt;return[...new Set(r)].filter(e=>wt(e)&&(!n||n.includes(e))).sort(Tt)}function Dt(e,t,n=!1){if(t?.length)return e.filter(e=>t.includes(e));if(n)return[...e];let r=e.filter(e=>xt.includes(e));return r.length>0?r:e.slice(0,St)}var Ot=9999,kt={"":`m`,s:`s`,S:`s`,m:`m`,h:`h`,H:`h`,d:`d`,D:`d`,w:`w`,W:`w`,M:`M`},At={s:[`m`,60],m:[`h`,60],h:[`d`,24]};function jt(e){let t=/^(\d+)([a-zA-Z]?)$/.exec(e.trim());if(!t)return null;if(t[2]===`T`||t[2]===`t`){let e=`${Number(t[1])}T`;return Number(t[1])<=Ot&&(0,n.tickBarCount)(e)!==null?e:null}let r=Number(t[1]),i=kt[t[2]];if(!i||!Number.isSafeInteger(r)||r<1)return null;for(let e=At[i];e&&r%e[1]===0;e=At[i])r/=e[1],i=e[0];if(r>Ot)return null;let a=`${r}${i}`;return(0,n.isTimeFrame)(a)?a:null}function Mt(e,t,n){let r=n?.length?n:null,i=t.filter(e=>wt(e)&&(!r||r.includes(e)));return[...new Set([...e,...i])].sort(Tt)}var Nt=[`T`,`s`,`m`,`h`,`d`,`w`,`M`];function Pt(e){let t=e=>{let t=e.slice(-1);return Nt.includes(t)?t:`m`};return Nt.map(n=>({unit:n,timeframes:e.filter(e=>t(e.value)===n)})).filter(e=>e.timeframes.length>0)}var Ft=864e5,It=5/7;function Lt(e){let t=(0,n.timeframeToMs)(e.current),r=(0,n.timeframeToMs)(e.chosen);if(!Number.isFinite(t)||!Number.isFinite(r)||!(e.width>0)||!(e.spanMs>0))return e.current;let i=n=>{if(n===t)return e.barsInSpan;if(n<Ft)return e.barsInSpan*t/n;let r=e.spanMs/n;return n===Ft?r*(e.dayShare??It):r},a=[...new Set([...e.available,e.current])].filter(e=>{let t=(0,n.timeframeToMs)(e);return Number.isFinite(t)&&t>=r}).sort(Tt);for(let t of a)if(i((0,n.timeframeToMs)(t))*2<=e.width)return t;return a[a.length-1]??e.current}var Rt={ticket:`receipt`,long:`trendingUp`,short:`trendingDown`,ladder:`ladder`,account:`layers`},zt=[`ladder`,`account`];function Bt(e,t){let n=[];e.onOrderTicket&&n.push({id:`ticket`,label:t(`chartMenu.orderTicket`),parts:[`orderTicket`],run:e.onOrderTicket});let r=e.onBracket;return r&&(n.push({id:`long`,label:t(`toolbar.longBracket`),parts:[`bracketOrders`,`toolbar.bracketOrders`],run:()=>r(`buy`)}),n.push({id:`short`,label:t(`toolbar.shortBracket`),parts:[`bracketOrders`,`toolbar.bracketOrders`],run:()=>r(`sell`)})),e.onToggleLadder&&n.push({id:`ladder`,label:t(`toolbar.depthLadder`),parts:[`depthLadder`,`toolbar.depthLadder`],run:e.onToggleLadder}),e.onToggleAccount&&n.push({id:`account`,label:t(`toolbar.account`),parts:[`accountPanel`,`toolbar.accountPanel`],run:e.onToggleAccount}),n}var Vt=class e{button;menu=null;open=new Set;static create(t,n,r,i){let a=Bt(t,n);return a.length>0?new e(a,n,r,i):null}constructor(e,t,n,r){this.items=e,this.t=t,this.root=n;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-dropdown-trigger tcw-toolbar-overflow`,i.dataset.role=`trade`,i.dataset.icon=`trendingUp`,i.title=t(`toolbar.trade`),i.setAttribute(`aria-haspopup`,`menu`),i.setAttribute(`aria-expanded`,`false`),D(i,`toolbar.trade`),i.innerHTML=`${O(`trendingUp`,14)} <span class="tcw-trigger-label">${k(t(`toolbar.trade`))}</span> ${O(`chevronDown`,12)}`,i.addEventListener(`click`,()=>this.toggle(r(i))),this.button=i}tidy(){this.button.hidden=this.items.every(e=>this.isOff(e.parts))}setOpen(e,t){let n=zt.find(t=>t===e);n&&(t?this.open.add(n):this.open.delete(n))}destroy(){this.menu?.destroy(),this.button.remove()}isOff(e){let t=new Set((this.root().getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean));return e.some(e=>t.has(e))}toggle(e){if(this.menu?.isOpen()){this.menu.close();return}let t=this.items.filter(e=>!this.isOff(e.parts));if(t.length===0)return;let n=t.filter(e=>!zt.includes(e.id)),r=t.filter(e=>zt.includes(e.id)),i=[...n.map(e=>({id:e.id,label:e.label,icon:Rt[e.id]})),...n.length>0&&r.length>0?[`separator`]:[],...r.map(e=>({id:e.id,label:e.label,checked:this.open.has(e.id)}))],a=this.root();this.menu??=new A(a,this.t(`toolbar.trade`)),this.menu.openUnder(i,e,e=>{t.find(t=>t.id===e)?.run()})}},Ht=2048,Ut=65536,Wt=/^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/i,Gt=new Set([`https:`,`http:`,`blob:`]),Kt=new Set([`description`,`exchange`,`type`,`logo`]);function qt(e){if(typeof e!=`string`)return null;let t=e.trim();return t&&t.length<=64?t:null}function Jt(e){let t=[],n=new Map;if(!Array.isArray(e))return{names:t,info:n};let r=new Set;for(let i of e){let e=typeof i==`object`&&!!i,a=qt(e?i.symbol:i);!a||r.has(a)||(r.add(a),t.push(a),e&&n.set(a,Yt(i,a)))}return{names:t,info:n}}function Yt(e,t){return{...Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==`__proto__`&&(!Kt.has(e)||typeof t==`string`&&t.trim()!==``))),symbol:t}}function Xt(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.symbol==`string`&&e.symbol!==``).map(e=>Yt(e,e.symbol)):[]}function Zt(e,t){if(!t)return e;if(!e)return t;let n=Object.entries(t).filter(([,e])=>e!=null);return Object.fromEntries([...Object.entries(e),...n])}function Qt(e){let t=e.lastIndexOf(`:`);return t<=0||t===e.length-1?{venue:``,ticker:e}:{venue:e.slice(0,t+1),ticker:e.slice(t+1)}}var $t=e=>Qt(e).ticker.toUpperCase();function en(e,t){return!t||typeof t.symbol!=`string`?null:t.symbol.toUpperCase()===e.toUpperCase()||t.symbol.includes(`:`)!==e.includes(`:`)&&$t(t.symbol)===$t(e)?t:null}function tn(e){return[e?.description,e?.exchange].filter(Boolean).join(` · `)||null}var nn=()=>typeof document>`u`?void 0:document.baseURI;function rn(e,t=nn()){if(typeof e!=`string`)return null;let n=e.trim();if(!n||n.length>Ut)return null;let r;try{r=new URL(n,t)}catch{return null}return r.protocol===`data:`?Wt.test(r.href)&&r.href.length<=Ut?r.href:null:Gt.has(r.protocol)&&r.href.length<=Ht?r.href:null}var an=0,j=`data-tcw-folded`,on=1/64,sn=[`venue`,`ticker`,`cut`],cn={T:`toolbar.timeframes.ticks`,s:`toolbar.timeframes.seconds`,m:`toolbar.timeframes.minutes`,h:`toolbar.timeframes.hours`,d:`toolbar.timeframes.days`,w:`toolbar.timeframes.weeks`,M:`toolbar.timeframes.months`};function ln(e,t){let n=e.querySelector(`.tcw-host-btn-text`)?.textContent??``;n===t?e.removeAttribute(`aria-label`):e.setAttribute(`aria-label`,n?`${t}: ${n}`:t)}var un=class{config;callbacks;t;el;chartTypeDropdown=null;tfGroup=null;tfDropdown=null;tfFavorites=[];uid=(an++).toString(36);tfRendered=``;themeBtn=null;fullscreenBtn=null;hostLeft=null;hostRight=null;moreMenu=null;tfCurrent=null;resizeObserver=null;hostObserver=null;moreBtn=null;fitFrame=0;destroyed=!1;undoBtn=null;redoBtn=null;trade=null;layoutShown=``;symbolShown=null;constructor(e,t,n,r,i){if(this.host=e,this.layer=i,this.config=t,this.callbacks=n,this.t=r,this.el=document.createElement(`div`),this.el.className=`tcw-toolbar`,D(this.el,`toolbar`),this.build(),e.appendChild(this.el),typeof ResizeObserver<`u`){this.resizeObserver=new ResizeObserver(()=>this.fit()),this.resizeObserver.observe(this.el),this.hostObserver=new ResizeObserver(()=>this.scheduleFit());for(let e of[this.hostLeft,this.hostRight])e&&this.hostObserver.observe(e)}document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.destroyed||this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.destroyed||this.fit()}))}menuAnchor(e){return(e.hasAttribute(j)||this.el.closest(`[data-tcw-narrow]`)!==null)&&this.moreBtn?this.moreBtn:e}fit(){let e=this.toolbarFocus(),t=this.foldedState();this.refit(),this.foldedState()!==t&&this.closeStaleMenus(),e&&this.keepFocus(e)}refit(){let{el:e}=this,t=()=>this.fits(),n=[...e.querySelectorAll(`.tcw-toolbar-overflow`)];for(let e of n)e.removeAttribute(j);if(e.classList.remove(`tcw-toolbar--collapsed`,`tcw-toolbar--icons`),delete e.dataset.tcwSqueeze,!(e.clientWidth===0||t())){e.classList.add(`tcw-toolbar--collapsed`);for(let e=n.length-1;e>=0;e--)if(n[e].setAttribute(j,``),t())return;e.classList.add(`tcw-toolbar--icons`);for(let e of n)if(e.removeAttribute(j),!t()){e.setAttribute(j,``);break}for(let n of sn){if(t())return;e.dataset.tcwSqueeze=n}}}fits(){let{el:e}=this,t=e.getBoundingClientRect(),n=e.offsetWidth>0&&Math.abs(t.width-e.offsetWidth)>=1?t.width/e.offsetWidth:1,r=getComputedStyle(e),i=r.direction===`rtl`,a=e=>parseFloat(e)||0,o=t.width/n-(i?a(r.borderLeftWidth)+a(r.paddingLeft):a(r.borderRightWidth)+a(r.paddingRight)),s=0;for(let r of e.children){if(r.getClientRects().length===0)continue;let e=r.getBoundingClientRect();s=Math.max(s,(i?t.right-e.left:e.right-t.left)/n)}return Math.ceil(s-on)<=Math.floor(o+on)}foldedState(){let e=[...this.el.querySelectorAll(`.tcw-toolbar-overflow`)];return`${this.el.classList.contains(`tcw-toolbar--collapsed`)}:${e.map(e=>Number(e.hasAttribute(j))).join(``)}`}closeStaleMenus(){this.moreBtn&&A.closeAnchoredTo(this.moreBtn);for(let e of this.el.querySelectorAll(`[${j}], [${j}] button`))A.closeAnchoredTo(e)}toolbarFocus(){let e=A.focusedAnchor();if(e&&this.el.contains(e))return e;let t=document.activeElement;return t instanceof HTMLElement&&this.el.contains(t)?t:null}keepFocus(e){if(A.focusedAnchor())return;let t=e;this.shows(e)||(t=(this.moreBtn&&e!==this.moreBtn&&this.shows(this.moreBtn)?this.moreBtn:null)??this.overflowButtons().filter(e=>this.shows(e)).at(-1)),t&&document.activeElement!==t&&t.focus({preventScroll:!0})}overflowButtons(){return[...this.el.querySelectorAll(`button.tcw-toolbar-overflow, .tcw-toolbar-overflow button`)]}shows(e){if(e.closest(`[hidden]`)||e.closest(`[${j}]`)||this.isOff(e))return!1;let t=this.el.closest(`[data-tcw-narrow]`)!==null;return e===this.moreBtn?t||this.el.classList.contains(`tcw-toolbar--collapsed`):!(t&&e.closest(`.tcw-toolbar-overflow`))}isOff(e){let t=new Set((this.rootEl().getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean));for(let n=e;n&&n!==this.el;n=n.parentElement)if((n.dataset.tcwPart??``).split(/\s+/).some(e=>t.has(e)))return!0;return!1}build(){let{config:e,callbacks:t,el:n}=this,r=document.createElement(`button`);if(r.className=`tcw-toolbar-symbol`,r.dataset.role=`symbol`,r.dir=`ltr`,D(r,`toolbar.symbol`),r.addEventListener(`click`,t.onSymbolClick),n.appendChild(r),t.onSymbolInfo){let e=this.iconBtn(`info`,this.t(`symbolInfo.title`),t.onSymbolInfo);e.classList.remove(`tcw-toolbar-overflow`),e.dataset.role=`symbolInfo`,D(e,`symbolInfo`,`toolbar.symbolInfo`),n.appendChild(e)}if(n.appendChild(this.sep()),this.tfFavorites=[...e.timeframeFavorites??e.timeframes.map(e=>e.value)],this.tfGroup=document.createElement(`div`),this.tfGroup.className=`tcw-toolbar-group tcw-tf-group`,D(this.tfGroup,`toolbar.timeframes`),n.appendChild(this.tfGroup),t.onToggleTimeframeFavorite&&e.timeframes.length>0){let e=document.createElement(`div`);e.style.position=`relative`,e.style.display=`inline-flex`,D(e,`toolbar.timeframeMenu`);let t=document.createElement(`button`);t.className=`tcw-btn tcw-tf-more`,t.dataset.role=`timeframes`,t.title=this.t(`toolbar.timeframes`),t.setAttribute(`aria-label`,this.t(`toolbar.timeframes`)),this.tfCurrent=document.createElement(`span`),this.tfCurrent.className=`tcw-tf-current`,t.appendChild(this.tfCurrent),t.insertAdjacentHTML(`beforeend`,O(`chevronDown`,12)),e.appendChild(t),n.appendChild(e),this.tfDropdown=new rt(e,{width:`150px`,layer:this.layer}),n.classList.add(`tcw-toolbar--tf-menu`),this.buildTimeframeMenu()}n.appendChild(this.sep());let i=document.createElement(`div`);i.style.position=`relative`,i.style.display=`inline-flex`,D(i,`toolbar.chartType`);let a=document.createElement(`button`);a.className=`tcw-dropdown-trigger`,a.dataset.role=`charttype`,i.appendChild(a),n.appendChild(i),this.chartTypeDropdown=new rt(i,{width:`160px`,layer:this.layer}),this.buildChartTypeMenu(),n.appendChild(this.sep());let o=document.createElement(`button`);if(o.type=`button`,o.className=`tcw-dropdown-trigger`,o.dataset.role=`indicators`,o.setAttribute(`aria-haspopup`,`dialog`),o.setAttribute(`aria-expanded`,`false`),D(o,`toolbar.indicators`),o.addEventListener(`click`,()=>t.onIndicators()),n.appendChild(o),t.onCompare){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-dropdown-trigger`,e.dataset.role=`compare`,D(e,`compare`,`toolbar.compare`);let r=this.t(`objects.compare`);e.setAttribute(`aria-label`,r),e.title=r,e.innerHTML=`${O(`plus`,14)} <span class="tcw-trigger-label">${k(r)}</span>`,e.addEventListener(`click`,t.onCompare),n.appendChild(e)}if(this.hostLeft=this.hostGroup(),n.appendChild(this.hostLeft),t.onUndo&&t.onRedo&&(n.appendChild(this.sep()),this.undoBtn=this.iconBtn(`undo`,this.t(`drawing.undo`),t.onUndo),this.undoBtn.dataset.role=`undo`,D(this.undoBtn,`toolbar.undo`,`sidebar.undo`),this.redoBtn=this.iconBtn(`redo`,this.t(`drawing.redo`),t.onRedo),this.redoBtn.dataset.role=`redo`,D(this.redoBtn,`toolbar.redo`,`sidebar.redo`),n.append(this.undoBtn,this.redoBtn),this.setHistory(!1,!1)),n.appendChild(this.spacer()),t.onLayouts){let e=t.onLayouts,r=document.createElement(`button`);r.type=`button`,r.className=`tcw-dropdown-trigger tcw-layouts-btn tcw-toolbar-overflow`,r.dataset.role=`layouts`,r.dataset.icon=`save`,D(r,`layouts`,`toolbar.layouts`),r.setAttribute(`aria-haspopup`,`menu`),r.addEventListener(`click`,()=>e(this.menuAnchor(r))),n.appendChild(r),this.setLayout(null,!1)}if(this.hostRight=this.hostGroup(),n.appendChild(this.hostRight),n.appendChild(this.sep()),t.onToggleReplay){let e=this.iconBtn(`play`,this.t(`toolbar.replay`),t.onToggleReplay);e.dataset.role=`replay`,D(e,`replay`,`toolbar.replay`),n.appendChild(e)}if(t.onToggleObjects){let e=this.iconBtn(`layers`,this.t(`toolbar.objects`),t.onToggleObjects);e.dataset.role=`objects`,e.setAttribute(`aria-pressed`,`false`),D(e,`objectTree`,`toolbar.objectTree`),n.appendChild(e)}if(t.onToggleAlerts){let e=this.iconBtn(`bell`,this.t(`toolbar.priceAlerts`),t.onToggleAlerts);e.dataset.role=`alerts`,e.setAttribute(`aria-pressed`,`false`),D(e,`alerts`,`toolbar.alerts`),n.appendChild(e)}this.trade=Vt.create(t,this.t,()=>this.rootEl(),e=>this.menuAnchor(e)),this.trade&&n.appendChild(this.trade.button),n.appendChild(this.sep());let s=this.iconBtn(`camera`,this.t(`toolbar.screenshot`),t.onScreenshot);D(s,`screenshot`,`toolbar.screenshot`),n.appendChild(s);let c=this.iconBtn(`settings`,this.t(`toolbar.settings`),t.onSettings);D(c,`settings`,`toolbar.settings`),n.appendChild(c),this.themeBtn=this.iconBtn(`moon`,this.t(`toolbar.toggleTheme`),t.onToggleTheme),this.themeBtn.dataset.role=`theme`,D(this.themeBtn,`themeToggle`,`toolbar.themeToggle`),n.appendChild(this.themeBtn),t.onToggleFullscreen&&(this.fullscreenBtn=this.iconBtn(`maximize`,this.t(`toolbar.fullscreen`),t.onToggleFullscreen),this.fullscreenBtn.dataset.role=`fullscreen`,D(this.fullscreenBtn,`fullscreen`,`toolbar.fullscreen`),this.fullscreenBtn.setAttribute(`aria-pressed`,`false`),n.appendChild(this.fullscreenBtn));let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-btn-icon tcw-toolbar-more`,l.title=this.t(`toolbar.more`),l.setAttribute(`aria-haspopup`,`menu`),l.setAttribute(`aria-expanded`,`false`),l.innerHTML=O(`more`,16),l.addEventListener(`click`,()=>this.toggleMore(l)),n.appendChild(l),this.moreBtn=l}toggleMore(e){if(A.closeAnchoredTo(e))return;let t=this.rootEl(),n=this.el.closest(`[data-tcw-narrow]`)!==null,r=[];for(let e of this.el.querySelectorAll(`.tcw-toolbar-overflow`)){if(this.isOff(e)||!n&&!e.hasAttribute(j))continue;let t=e instanceof HTMLButtonElement?[e]:[...e.querySelectorAll(`button`)];r.push(...t.filter(e=>!e.hidden&&!e.disabled&&!this.isOff(e)))}if(r.length===0)return;let i=r.map((e,t)=>{let n=e.getAttribute(`aria-label`)||e.title||e.textContent?.trim()||``,r=e.getAttribute(`aria-pressed`);return r===null?{id:String(t),label:n,icon:e.dataset.icon}:{id:String(t),label:n,icon:e.dataset.icon,checked:r===`true`}});this.moreMenu??=new A(t,this.t(`toolbar.more`)),this.moreMenu.openUnder(i,e,e=>r[Number(e)]?.click(),`end`)}addHostButton(e){let t=document.createElement(`button`);t.type=`button`,t.className=`${e.text||!e.icon?`tcw-btn`:`tcw-btn-icon`} tcw-host-btn tcw-toolbar-overflow`,t.dataset.hostButton=e.id,typeof e.icon==`string`&&(t.dataset.icon=e.icon),t.title=e.label,e.toggle&&t.setAttribute(`aria-pressed`,`false`),typeof e.icon==`string`?t.innerHTML=O(e.icon,14):e.icon&&t.appendChild(e.icon);let n=e.text??(e.icon?``:e.label);if(n){let e=document.createElement(`span`);e.className=`tcw-host-btn-text`,e.textContent=n,t.appendChild(e)}return ln(t,e.label),t.addEventListener(`click`,()=>e.onClick(t)),(e.side===`left`?this.hostLeft:this.hostRight)?.appendChild(t),this.scheduleFit(),t}hostSlot(e){return e===`left`?this.hostLeft:this.hostRight}hostGroup(){let e=document.createElement(`div`);return e.className=`tcw-toolbar-host`,e}setSymbolSearch(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(e?t.removeAttribute(`aria-disabled`):t.setAttribute(`aria-disabled`,`true`))}tidy(){this.trade?.tidy(),Je(this.el,`tcw-toolbar-sep`,`tcw-toolbar-spacer`),this.scheduleFit()}setHistory(e,t){this.undoBtn&&(this.undoBtn.disabled=!e),this.redoBtn&&(this.redoBtn.disabled=!t)}rootEl(){return this.el.closest(`.tcw-root`)??this.host}setActive(e,t){this.trade?.setOpen(e,t);let n=this.el.querySelector(`[data-role="${e}"]`);n&&(n.classList.toggle(`tcw-active`,t),n.setAttribute(`aria-pressed`,String(t)))}setRailed(e,t){let n=this.el.querySelector(`[data-role="${e}"]`);n&&(n.hidden=t)}setLayout(e,t){let n=this.el.querySelector(`[data-role="layouts"]`);if(!n)return;let r=e??this.t(`layouts.unnamed`);if(this.layoutShown===`${t}:${r}`)return;this.layoutShown=`${t}:${r}`;let i=`${this.t(`toolbar.layouts`)}: ${r}${t?` (${this.t(`layouts.unsavedChanges`)})`:``}`;n.innerHTML=`${O(`save`,14)}<span class="tcw-layouts-label">${k(r)}</span>`+(t?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+O(`chevronDown`,12),n.title=i,n.setAttribute(`aria-label`,i),this.scheduleFit()}setFullscreen(e){if(!this.fullscreenBtn)return;let t=this.t(e?`toolbar.exitFullscreen`:`toolbar.fullscreen`);this.fullscreenBtn.innerHTML=O(e?`minimize`:`maximize`,14),this.fullscreenBtn.title=t,this.fullscreenBtn.setAttribute(`aria-pressed`,String(e))}chartTypeLabel(e){return vt(e,this.t)}buildChartTypeMenu(){if(!this.chartTypeDropdown)return;let e=this.config.chartTypes.map(e=>`<button class="tcw-dropdown-item tcw-dropdown-item--icon" data-ct="${k(e.value)}">${nt(e.value,16)}<span>${k(this.chartTypeLabel(e))}</span></button>`).join(``);this.chartTypeDropdown.setContent(e),this.chartTypeDropdown.panel.querySelectorAll(`.tcw-dropdown-item`).forEach(e=>{e.addEventListener(`click`,e=>{let t=e.currentTarget.dataset.ct;this.callbacks.onChartType(t),this.chartTypeDropdown?.close()})})}setSymbolDescription(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(e?t.title=e:t.removeAttribute(`title`))}setTimeframes(e,t){this.config={...this.config,timeframes:e},this.setTimeframeFavorites(t)}setTimeframeFavorites(e){this.tfFavorites=[...e],this.tfRendered=``,this.buildTimeframeMenu()}buildTimeframeMenu(){if(!this.tfDropdown)return;let e=k(this.t(`toolbar.timeframes.pin`)),t=k(this.t(`toolbar.timeframes.remove`)),n=``;for(let{unit:r,timeframes:i}of Pt(this.config.timeframes)){n+=`<div class="tcw-tf-section" data-tf-section="${r}" role="group" aria-label="${k(this.t(cn[r]))}"><div class="tcw-dropdown-label">${k(this.t(cn[r]))}</div>`;for(let r of i){let i=this.tfFavorites.includes(r.value),[a,o]=[k(r.value),k(r.label)];n+=`<div class="tcw-tf-row"><button class="tcw-dropdown-item" data-tf-pick="${a}">${o}</button>`+(r.custom&&this.callbacks.onRemoveTimeframe?`<button class="tcw-tf-remove" data-tf-remove="${a}" title="${t}" aria-label="${t}: ${o}">${O(`x`,12)}</button>`:``)+`<button class="tcw-tf-star${i?` tcw-active`:``}" data-tf-star="${a}" aria-pressed="${i}" title="${e}" aria-label="${e}: ${o}">${O(`star`,12)}</button></div>`}n+=`</div>`}if(this.callbacks.onAddTimeframe){let e=k(this.t(`toolbar.timeframes.custom`)),t=k(this.t(`toolbar.timeframes.add`));n+=`<form class="tcw-tf-custom" ${Ke(`customTimeframes`)} novalidate><input class="tcw-tf-custom-input" type="text" autocomplete="off" spellcheck="false" maxlength="6" placeholder="7m, 90m, 2h…" aria-label="${e}" aria-describedby="tcw-tf-hint-${this.uid}"><button type="submit" class="tcw-tf-custom-add" title="${t}" aria-label="${t}">${O(`plus`,12)}</button><div class="tcw-tf-custom-hint" id="tcw-tf-hint-${this.uid}" role="status"></div></form>`}this.tfDropdown.setContent(n);let r=this.tfDropdown.panel;r.querySelectorAll(`[data-tf-pick]`).forEach(e=>{e.addEventListener(`click`,()=>this.callbacks.onTimeframe(e.dataset.tfPick))}),r.querySelectorAll(`[data-tf-star]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onToggleTimeframeFavorite?.(e.dataset.tfStar)})}),r.querySelectorAll(`[data-tf-remove]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemoveTimeframe?.(e.dataset.tfRemove)})});let i=r.querySelector(`.tcw-tf-custom`);i&&this.wireCustomTimeframe(i)}wireCustomTimeframe(e){let t=e.querySelector(`.tcw-tf-custom-input`),n=e.querySelector(`.tcw-tf-custom-hint`);e.addEventListener(`click`,e=>e.stopPropagation()),t.addEventListener(`input`,()=>{t.removeAttribute(`aria-invalid`),n.textContent=``}),e.addEventListener(`submit`,e=>{e.preventDefault(),e.stopPropagation(),this.callbacks.onAddTimeframe?.(t.value)?(t.value=``,n.textContent=``,this.tfDropdown?.close(),this.el.querySelector(`[data-role="timeframes"]`)?.focus()):(t.setAttribute(`aria-invalid`,`true`),n.textContent=this.t(`toolbar.timeframes.invalid`))})}renderTimeframes(e){if(!this.tfGroup)return;let t=this.config.timeframes.filter(t=>this.tfFavorites.includes(t.value)||t.value===e),n=`${t.map(e=>e.value).join(`,`)}|${e}`;n!==this.tfRendered&&(this.tfRendered=n,this.tfCurrent&&(this.tfCurrent.textContent=this.config.timeframes.find(t=>t.value===e)?.label??e),this.tfGroup.replaceChildren(...t.map(t=>{let n=document.createElement(`button`);return n.className=`tcw-btn`,n.textContent=t.label,n.dataset.tf=t.value,n.classList.toggle(`tcw-active`,t.value===e),n.addEventListener(`click`,()=>this.callbacks.onTimeframe(t.value)),n})),(this.tfDropdown?.panel)?.querySelectorAll(`[data-tf-pick]`).forEach(t=>{t.classList.toggle(`tcw-active`,t.dataset.tfPick===e)}))}setIndicatorsOpen(e){this.el.querySelector(`[data-role="indicators"]`)?.setAttribute(`aria-expanded`,String(e))}renderSymbol(e){let t=this.el.querySelector(`[data-role="symbol"]`);if(!t||this.symbolShown===e)return;this.symbolShown=e;let{venue:n,ticker:r}=Qt(e),i=(e,t)=>{let n=document.createElement(`span`);return n.className=e,n.textContent=t,n};t.replaceChildren(...n?[i(`tcw-toolbar-venue`,n)]:[],i(`tcw-toolbar-ticker`,r)),t.classList.toggle(`tcw-toolbar-symbol--venue`,n!==``),t.setAttribute(`aria-label`,e)}update(e){this.renderSymbol(e.symbol),this.renderTimeframes(e.timeframe);let t=this.el.querySelector(`[data-role="charttype"]`);if(t){let n=this.config.chartTypes.find(t=>t.value===e.chartType),r=n?this.chartTypeLabel(n):e.chartType;t.innerHTML=nt(e.chartType,16),t.title=r,t.setAttribute(`aria-label`,r)}let n=this.el.querySelector(`[data-role="indicators"]`);if(n){let t=[...e.activeIndicators.values()].filter(e=>!r.SYMBOL_INDICATOR_IDS.has(e.id)).length,i=`${O(`trendingUp`,14)} <span class="tcw-trigger-label">${k(this.t(`toolbar.indicators`))}</span>`;n.setAttribute(`aria-label`,this.t(`toolbar.indicators`)),t>0&&(i+=` <span class="tcw-badge-count">${t}</span>`),n.innerHTML=i}if(this.themeBtn){let t=e.isDark?`moon`:`sun`;this.themeBtn.innerHTML=O(t,14),this.themeBtn.dataset.icon=t}this.scheduleFit()}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}spacer(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-spacer`,e}iconBtn(e,t,n){let r=document.createElement(`button`);return r.className=`tcw-btn-icon tcw-toolbar-overflow`,r.dataset.icon=e,r.title=t,r.innerHTML=O(e,14),r.addEventListener(`click`,n),r}destroy(){this.destroyed=!0,this.resizeObserver?.disconnect(),this.hostObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.chartTypeDropdown?.destroy(),this.tfDropdown?.destroy(),this.moreMenu?.destroy(),this.trade?.destroy(),this.el.remove()}};function dn(e,t,n){e.classList.toggle(`tcw-active`,t),n&&e.setAttribute(`aria-pressed`,String(t))}function fn(e,t,n){let r=n==null?``:String(n),i=e.querySelector(`.tcw-host-btn-text`);return(i?.textContent??``)===r?!1:(i||(i=document.createElement(`span`),i.className=`tcw-host-btn-text`,e.appendChild(i)),i.textContent=r,ln(e,t),!0)}var pn=16,mn=150,hn=4;function gn(e){let t=`sidebar.${e}`;return Pe.includes(t)?t:null}function _n(e,t){for(let n of e){let e=n.tools.find(e=>e.value===t);if(e)return e.label}return t}var vn=`--tcw-fab-plot-left`,yn=class{config;callbacks;el;groupWraps=[];groupButtons=[];groupIcons=[];groupTools=[];cursorBtn=null;magnetBtn=null;eraserBtn=null;zoomBtn=null;stayBtn=null;lockAllBtn=null;hideAllBtn=null;drawings={locked:!1,hidden:!1};flyoutEl=null;flyoutIdx=-1;flyoutHideTimer=null;hostEl=null;favoritesEl=null;favoritesDivider=null;favorites=[];fab;fabShows=``;onPressAway=e=>{let t=e.target;t&&(this.el.contains(t)||this.fab.contains(t)||this.flyoutEl?.contains(t))||this.setOpen(!1)};onEscape=e=>{e.key===`Escape`&&!this.flyoutEl&&this.setOpen(!1)};constructor(e,n,r,i=t.t){this.host=e,this.t=i,this.config=n,this.callbacks=r,this.el=document.createElement(`div`),this.el.className=`tcw-sidebar`,D(this.el,`sidebar`),this.build(),this.el.addEventListener(`scroll`,()=>this.hideFlyout(),{passive:!0}),e.appendChild(this.el),this.fab=document.createElement(`button`),this.fab.type=`button`,this.fab.className=`tcw-sidebar-fab`,this.fab.setAttribute(`aria-label`,this.t(`drawing.tools`)),this.fab.setAttribute(`aria-expanded`,`false`),this.fab.innerHTML=O(`penLine`,18),D(this.fab,`sidebar`),this.fab.addEventListener(`click`,()=>this.setOpen(!this.isOpen())),e.appendChild(this.fab)}setPlotLeft(e){let t=`${Math.max(0,Math.round(e))}px`;this.fab.style.getPropertyValue(vn)!==t&&this.fab.style.setProperty(vn,t)}isNarrow(){return this.el.closest(`[data-tcw-narrow]`)!==null}isOpen(){return this.el.classList.contains(`tcw-sidebar-open`)}setOpen(e){if(e!==this.isOpen())if(this.el.classList.toggle(`tcw-sidebar-open`,e),this.fab.setAttribute(`aria-expanded`,String(e)),e)document.addEventListener(`pointerdown`,this.onPressAway,!0),document.addEventListener(`keydown`,this.onEscape);else{let e=this.el.contains(document.activeElement)||!!this.flyoutEl?.contains(document.activeElement);this.hideFlyout(),document.removeEventListener(`pointerdown`,this.onPressAway,!0),document.removeEventListener(`keydown`,this.onEscape),e&&this.isNarrow()&&this.fab.focus({preventScroll:!0})}}closeOverlay(){this.setOpen(!1)}closeForChart(){this.isNarrow()&&this.setOpen(!1)}pick(e){this.callbacks.onDrawingTool(e),this.closeForChart()}build(){let{config:e,callbacks:t,el:n}=this;this.cursorBtn=document.createElement(`button`),this.cursorBtn.className=`tcw-sidebar-btn`,this.cursorBtn.title=this.t(`drawing.cursor`),this.cursorBtn.innerHTML=O(`cursor`,14),this.cursorBtn.addEventListener(`click`,()=>{t.onCancelDrawing(),this.closeForChart()}),D(this.cursorBtn,`sidebar.cursor`),n.appendChild(this.cursorBtn),n.appendChild(this.divider()),t.onToggleFavorite&&(this.favorites=[...e.favorites??[]],this.favoritesEl=document.createElement(`div`),this.favoritesEl.className=`tcw-sidebar-favorites`,D(this.favoritesEl,`sidebar.favorites`),n.appendChild(this.favoritesEl),this.favoritesDivider=this.divider(),D(this.favoritesDivider,`sidebar.favorites`),n.appendChild(this.favoritesDivider),this.renderFavorites());let r;e.drawingToolGroups.forEach((e,t)=>{if(!e.tools[0])return;e.section!==void 0&&r!==void 0&&e.section!==r&&this.appendDivider(),r=e.section;let i=document.createElement(`div`);i.className=`tcw-tool-group-wrap`;let a=gn(e.section);a&&D(i,a);let o=document.createElement(`button`);o.className=`tcw-sidebar-btn`;let s=e.tools[0].value;e.tools.length>1?o.setAttribute(`aria-label`,`${e.label}: ${e.tools[0].label}`):o.title=e.label;let c=document.createElement(`span`);if(c.className=`tcw-sidebar-icon`,c.innerHTML=tt(s,pn),o.appendChild(c),this.groupIcons.push(c),this.groupTools.push(s),e.tools.length>1){let e=document.createElement(`span`);e.className=`tcw-multi-dot`,o.appendChild(e)}o.addEventListener(`click`,()=>{if(this.isNarrow()&&e.tools.length>1){this.flyoutEl&&this.flyoutIdx===t?this.hideFlyout():this.showFlyout(t);return}this.pick(this.groupTools[t])}),i.appendChild(o),i.addEventListener(`mouseenter`,()=>{this.isNarrow()||this.showFlyout(t)}),i.addEventListener(`mouseleave`,()=>{this.isNarrow()||this.scheduleHideFlyout()}),e.tools.length>1&&(o.setAttribute(`aria-haspopup`,`menu`),o.setAttribute(`aria-expanded`,`false`),o.addEventListener(`keydown`,e=>{e.key===`ArrowRight`||e.key===`ArrowDown`?(e.preventDefault(),this.showFlyout(t),this.focusFlyoutItem(0)):e.key===`Escape`&&this.flyoutEl&&(e.stopPropagation(),this.hideFlyout())})),i.addEventListener(`focusout`,e=>{let t=e.relatedTarget;!i.contains(t)&&!this.flyoutEl?.contains(t)&&this.scheduleHideFlyout()}),n.appendChild(i),this.groupWraps.push(i),this.groupButtons.push(o)});let i=document.createElement(`div`);if(i.className=`tcw-sidebar-spacer`,n.appendChild(i),n.appendChild(this.divider()),t.onToggleStyle){let e=document.createElement(`button`);e.className=`tcw-sidebar-btn`,e.title=this.t(`drawing.style`),e.dataset.role=`style`,D(e,`sidebar.style`),e.innerHTML=O(`palette`,14);let r=t.onToggleStyle;e.addEventListener(`click`,()=>{r(),this.closeForChart()}),n.appendChild(e)}if(t.onToggleMagnet&&(this.magnetBtn=document.createElement(`button`),this.magnetBtn.className=`tcw-sidebar-btn`,this.magnetBtn.title=this.t(`drawing.magnet`),this.magnetBtn.innerHTML=O(`magnet`,14),this.magnetBtn.addEventListener(`click`,t.onToggleMagnet),D(this.magnetBtn,`sidebar.magnet`),n.appendChild(this.magnetBtn)),t.onToggleEraser){let e=t.onToggleEraser;this.eraserBtn=this.toggleButton(`eraser`,this.t(`drawing.eraser`),()=>{e(),this.closeForChart()}),D(this.eraserBtn,`sidebar.eraser`),n.appendChild(this.eraserBtn)}if(t.onToggleZoomArea){let e=t.onToggleZoomArea;this.zoomBtn=this.toggleButton(`zoomIn`,this.t(`drawing.zoomArea`),()=>{e(),this.closeForChart()}),D(this.zoomBtn,`sidebar.zoomArea`),n.appendChild(this.zoomBtn)}if(t.onToggleStayInDrawing&&(this.stayBtn=document.createElement(`button`),this.stayBtn.className=`tcw-sidebar-btn`,this.stayBtn.dataset.role=`stay`,this.stayBtn.title=this.t(`drawing.stay`),this.stayBtn.setAttribute(`aria-pressed`,`false`),this.stayBtn.innerHTML=O(`repeat`,14),this.stayBtn.addEventListener(`click`,t.onToggleStayInDrawing),D(this.stayBtn,`sidebar.stayInDrawing`),n.appendChild(this.stayBtn)),this.hostEl=document.createElement(`div`),this.hostEl.className=`tcw-sidebar-host`,n.appendChild(this.hostEl),this.appendDivider(),t.onLockAll){let e=t.onLockAll;this.lockAllBtn=this.toggleButton(`lock`,this.t(`drawing.lockAll`),()=>e(!this.drawings.locked)),this.lockAllBtn.dataset.role=`lockAll`,D(this.lockAllBtn,`sidebar.lockAll`),n.appendChild(this.lockAllBtn)}if(t.onHideAll){let e=t.onHideAll;this.hideAllBtn=this.toggleButton(`eyeOff`,this.t(`drawing.hideAll`),()=>e(!this.drawings.hidden)),this.hideAllBtn.dataset.role=`hideAll`,D(this.hideAllBtn,`sidebar.hideAll`),n.appendChild(this.hideAllBtn)}let a=document.createElement(`button`);a.className=`tcw-sidebar-btn tcw-danger`,a.title=this.t(`drawing.clearAll`),a.innerHTML=O(`trash`,14),a.setAttribute(`aria-haspopup`,`menu`),a.setAttribute(`aria-expanded`,`false`),a.addEventListener(`click`,()=>t.onClear(a)),D(a,`sidebar.clear`),n.appendChild(a)}setDrawingsState(e){if(!(e.locked===this.drawings.locked&&e.hidden===this.drawings.hidden)){this.drawings={...e};for(let[t,n]of[[this.lockAllBtn,e.locked],[this.hideAllBtn,e.hidden]])t?.setAttribute(`aria-pressed`,String(n)),t?.classList.toggle(`tcw-active`,n)}}setFavorites(e){this.favorites=[...e],this.renderFavorites();for(let e of this.flyoutEl?.querySelectorAll(`.tcw-flyout-row`)??[]){let t=this.favorites.includes(e.dataset.toolValue??``);e.classList.toggle(`tcw-flyout-faved`,t),e.querySelector(`[data-pin]`)?.setAttribute(`aria-pressed`,String(t))}}renderFavorites(){if(!this.favoritesEl)return;this.favoritesEl.replaceChildren();let e=this.favorites.length>0;this.favoritesEl.style.display=e?``:`none`,this.favoritesDivider&&(this.favoritesDivider.style.display=e?``:`none`);for(let e of this.favorites){let n=document.createElement(`button`);n.className=`tcw-sidebar-btn`,n.title=t.r(this.t(`sidebar.unpinHint`),{tool:_n(this.config.drawingToolGroups,e)}),n.dataset.toolValue=e,n.innerHTML=tt(e,pn),n.addEventListener(`click`,()=>this.pick(e)),n.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.callbacks.onToggleFavorite?.(e)}),this.favoritesEl.appendChild(n)}}showFlyout(e){if(this.cancelHideFlyout(),this.flyoutEl&&this.flyoutIdx===e)return;let t=this.config.drawingToolGroups[e];if(!t||t.tools.length<=1){this.hideFlyout();return}this.hideFlyout();let n=document.createElement(`div`);n.className=`tcw-flyout`,n.setAttribute(`role`,`menu`),n.setAttribute(`aria-label`,t.label),n.addEventListener(`keydown`,t=>this.onFlyoutKey(t,e));let r=document.createElement(`div`);r.className=`tcw-flyout-header`,r.textContent=t.label,n.appendChild(r);let i=this.t(`drawing.pinFavorite`);for(let e of t.tools){let t=document.createElement(`div`);t.className=`tcw-flyout-row`,t.setAttribute(`role`,`none`),t.dataset.toolValue=e.value;let r=document.createElement(`button`);r.className=`tcw-flyout-item`,r.setAttribute(`role`,`menuitem`),r.tabIndex=-1,r.innerHTML=tt(e.value,pn);let a=document.createElement(`span`);a.className=`tcw-flyout-name`,a.textContent=e.label,r.appendChild(a);let o=this.config.shortcuts?.[e.value];if(o){let e=document.createElement(`kbd`);e.className=`tcw-flyout-key`,e.textContent=o,D(e,`hotkeys`,`hotkeys.tools`),r.appendChild(e)}if(r.dataset.toolValue=e.value,r.addEventListener(`click`,()=>{this.hideFlyout(),this.pick(e.value)}),t.appendChild(r),this.callbacks.onToggleFavorite){let n=this.favorites.includes(e.value);t.classList.toggle(`tcw-flyout-faved`,n);let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-flyout-pin`,a.dataset.pin=e.value,a.tabIndex=-1,a.title=i,a.setAttribute(`aria-label`,`${i}: ${e.label}`),a.setAttribute(`aria-pressed`,String(n)),a.innerHTML=O(`star`,12),a.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onToggleFavorite?.(e.value)}),t.appendChild(a),r.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.callbacks.onToggleFavorite?.(e.value)})}n.appendChild(t)}n.addEventListener(`mouseenter`,()=>this.cancelHideFlyout()),n.addEventListener(`mouseleave`,()=>this.scheduleHideFlyout()),n.addEventListener(`focusout`,t=>{let r=t.relatedTarget;!n.contains(r)&&!this.groupWraps[e].contains(r)&&this.scheduleHideFlyout()}),this.flyoutEl=n,this.flyoutIdx=e,this.host.appendChild(n),this.placeFlyout(n,this.groupButtons[e]),this.groupButtons[e].setAttribute(`aria-expanded`,`true`)}flyoutItems(){return this.flyoutEl?[...this.flyoutEl.querySelectorAll(`.tcw-flyout-item`)]:[]}focusFlyoutItem(e){let t=this.flyoutItems();t.length!==0&&t[(e+t.length)%t.length].focus()}onFlyoutKey(e,t){let n=this.flyoutItems(),r=n.indexOf(document.activeElement);switch(e.key){case`ArrowDown`:this.focusFlyoutItem(r+1);break;case`ArrowUp`:this.focusFlyoutItem(r-1);break;case`Home`:this.focusFlyoutItem(0);break;case`End`:this.focusFlyoutItem(n.length-1);break;case`Escape`:case`ArrowLeft`:e.stopPropagation(),this.hideFlyout(),this.groupButtons[t]?.focus();break;case`Tab`:this.hideFlyout(),this.groupButtons[t]?.focus();return;default:return}e.preventDefault()}placeFlyout(e,t){let n=this.host.getBoundingClientRect(),r=t.getBoundingClientRect();e.style.maxHeight=`${Math.max(0,this.host.clientHeight-hn*2)}px`;let i=this.host.clientHeight-e.offsetHeight-hn;this.host.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?(e.style.left=``,e.style.right=`${n.right-r.left}px`):(e.style.right=``,e.style.left=`${r.right-n.left}px`),e.style.top=`${Math.max(0,Math.min(r.top-n.top,i))}px`}scheduleHideFlyout(){this.cancelHideFlyout(),this.flyoutHideTimer=setTimeout(()=>{this.flyoutHideTimer=null,this.hideFlyout()},mn)}cancelHideFlyout(){this.flyoutHideTimer!==null&&(clearTimeout(this.flyoutHideTimer),this.flyoutHideTimer=null)}hideFlyout(){this.cancelHideFlyout(),this.flyoutEl&&=(this.flyoutEl.remove(),null),this.groupButtons[this.flyoutIdx]?.setAttribute(`aria-expanded`,`false`),this.flyoutIdx=-1}update(e){this.cursorBtn&&this.cursorBtn.classList.toggle(`tcw-active`,e.activeTool===null);let t=e.activeTool??``;t!==this.fabShows&&(this.fabShows=t,this.fab.innerHTML=e.activeTool?tt(e.activeTool,18):O(`penLine`,18)),this.fab.classList.toggle(`tcw-active`,e.activeTool!==null||e.eraser||e.zoomArea);let{drawingToolGroups:n}=this.config;for(let t=0;t<n.length;t++){let r=n[t].tools.some(t=>t.value===e.activeTool);this.groupButtons[t].classList.toggle(`tcw-active`,r),r&&e.activeTool&&e.activeTool!==this.groupTools[t]&&(this.groupTools[t]=e.activeTool,this.groupIcons[t].innerHTML=tt(e.activeTool,pn),n[t].tools.length>1&&this.groupButtons[t].setAttribute(`aria-label`,`${n[t].label}: ${_n(n,e.activeTool)}`))}if(this.flyoutEl&&this.flyoutEl.querySelectorAll(`.tcw-flyout-item`).forEach(t=>{let n=t;n.classList.toggle(`tcw-active`,n.dataset.toolValue===e.activeTool)}),this.magnetBtn){let t=e.magnetEnabled&&e.magnetStrong;this.magnetBtn.classList.toggle(`tcw-active`,e.magnetEnabled),this.magnetBtn.innerHTML=O(t?`magnetStrong`:`magnet`,14),this.magnetBtn.title=t?this.t(`drawing.magnetStrong`):e.magnetEnabled?this.t(`drawing.magnetOn`):this.t(`drawing.magnetOff`),this.magnetBtn.setAttribute(`aria-label`,this.magnetBtn.title)}for(let[t,n]of[[this.eraserBtn,e.eraser],[this.zoomBtn,e.zoomArea]])t&&(t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n)));this.stayBtn&&(this.stayBtn.classList.toggle(`tcw-active`,e.stayInDrawing),this.stayBtn.setAttribute(`aria-pressed`,String(e.stayInDrawing)))}addHostButton(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-sidebar-btn tcw-host-btn`,t.dataset.hostButton=e.id,t.title=e.label,t.setAttribute(`aria-label`,e.label),e.toggle&&t.setAttribute(`aria-pressed`,`false`),typeof e.icon==`string`?t.innerHTML=O(e.icon,14):t.appendChild(e.icon),t.addEventListener(`click`,()=>e.onClick(t)),this.hostEl?.appendChild(t),this.tidy(),t}hostSlot(){return this.hostEl}tidy(){Je(this.el,`tcw-sidebar-divider`,`tcw-sidebar-spacer`)}toggleButton(e,t,n){let r=document.createElement(`button`);return r.className=`tcw-sidebar-btn`,r.title=t,r.setAttribute(`aria-label`,t),r.setAttribute(`aria-pressed`,`false`),r.innerHTML=O(e,14),r.addEventListener(`click`,n),r}appendDivider(){this.el.lastElementChild?.classList.contains(`tcw-sidebar-divider`)||this.el.appendChild(this.divider())}divider(){let e=document.createElement(`div`);return e.className=`tcw-sidebar-divider`,e}destroy(){this.setOpen(!1),this.hideFlyout(),this.fab.remove(),this.el.remove()}},bn=`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function M(e,t){if(e.key!==`Tab`)return;let n=document.activeElement,r=[...t.querySelectorAll(bn)].filter(e=>e.tabIndex>=0&&(e.getClientRects().length>0||e===n));if(r.length===0)return;let i=r[0],a=r[r.length-1],o=n instanceof Node&&t.contains(n),s=(e,t)=>(e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_PRECEDING)!==0;e.shiftKey&&(!o||n===i||s(i,n))?(e.preventDefault(),a.focus()):!e.shiftKey&&(!o||n===a||s(n,a))&&(e.preventDefault(),i.focus())}function N(e,t){let n=document.createElement(`label`);n.className=`tcw-settings-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=e,n.append(r,t),n}function xn(e,t,n){let r=document.createElement(`label`);r.className=`tcw-settings-row tcw-check-row`;let i=document.createElement(`input`);i.type=`checkbox`,i.checked=t,i.addEventListener(`change`,()=>n(i.checked));let a=document.createElement(`span`);return a.className=`tcw-settings-label`,a.textContent=e,r.append(i,a),r}function Sn(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-toggle${e?` tcw-on`:``}`,n.setAttribute(`role`,`switch`),n.setAttribute(`aria-checked`,String(e)),n.addEventListener(`click`,()=>{let e=!n.classList.contains(`tcw-on`);n.classList.toggle(`tcw-on`,e),n.setAttribute(`aria-checked`,String(e)),t(e)}),n}function P(e,t,n){let r=document.createElement(`input`);return r.type=`number`,r.className=`tcw-indi-input`,r.value=String(e),r.step=String(t.step??(Number.isInteger(e)?1:.001)),t.min!==void 0&&(r.min=String(t.min)),t.max!==void 0&&(r.max=String(t.max)),r.addEventListener(`change`,()=>{if(r.value.trim()===``)return;let e=Number(r.value);Number.isFinite(e)&&(t.min!==void 0&&(e=Math.max(t.min,e)),t.max!==void 0&&(e=Math.min(t.max,e)),r.value=String(e),n(e))}),r}function F(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=L(e),n.addEventListener(`input`,()=>t(n.value)),n}function I(e,t,n){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;for(let t of e){let e=document.createElement(`option`);e.value=t.value,e.textContent=t.label,r.appendChild(e)}return r.value=t,r.addEventListener(`change`,()=>n(r.value)),r}function L(e){if(typeof e!=`string`)return`#000000`;let t=e.trim();if(/^#[0-9a-f]{6}$/i.test(t))return t.toLowerCase();if(/^#[0-9a-f]{8}$/i.test(t))return t.slice(0,7).toLowerCase();if(/^#[0-9a-f]{3,4}$/i.test(t))return`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`.toLowerCase();let n=/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/i.exec(t);if(n)return`#${[n[1],n[2],n[3]].map(e=>Math.min(255,Number(e)).toString(16).padStart(2,`0`)).join(``)}`;let r=Cn(t);return r!==null&&r!==t?L(r):`#000000`}var R;function Cn(e){if(R===void 0)try{R=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):null}catch{R=null}if(!R)return null;R.fillStyle=`#010203`,R.fillStyle=e;let t=String(R.fillStyle);return t===`#010203`?null:t}function wn(e){if(typeof e!=`string`)return 1;let t=/^rgba\([^)]*,\s*([\d.]+)\s*\)$/i.exec(e.trim());return t?Math.max(0,Math.min(1,Number(t[1]))):1}function Tn(e,t){let n=L(e),[r,i,a]=[1,3,5].map(e=>parseInt(n.slice(e,e+2),16));return`rgba(${r}, ${i}, ${a}, ${Math.round(t*100)/100})`}var En={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1};function Dn(e,t,n,r){let i=document.createElement(`div`);i.className=`tcw-segmented`,i.setAttribute(`role`,`radiogroup`),i.setAttribute(`aria-label`,r);let a=e.map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-segment`,t.setAttribute(`role`,`radio`),t.dataset.value=e.value,t.textContent=e.label,t.addEventListener(`click`,()=>s(e.value)),t}),o=e=>{let t=Math.max(0,a.findIndex(t=>t.dataset.value===e));a.forEach((n,r)=>{n.setAttribute(`aria-checked`,String(n.dataset.value===e)),n.tabIndex=r===t?0:-1})},s=e=>{o(e),n(e)};return i.addEventListener(`keydown`,t=>{let n=a.findIndex(e=>e===t.target);if(n<0||t.altKey||t.ctrlKey||t.metaKey)return;let r=a.length-1,o;if(t.key===`Home`)o=0;else if(t.key===`End`)o=r;else if(t.key in En){let e=i.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`,r=t.key===`ArrowLeft`||t.key===`ArrowRight`;o=(n+(e&&r?-En[t.key]:En[t.key])+a.length)%a.length}else return;t.preventDefault(),a[o].focus(),s(e[o].value)}),o(t),i.append(...a),i}function On(e,t,r){if(!(r>0)||!Number.isFinite(e))return e;let i=e/r,a=Math.round(i),o=Math.abs(i-a)<1e-9*Math.max(1,Math.abs(i)),s=t>0?o?a+1:Math.ceil(i):o?a-1:Math.floor(i);return s<1?e:Number((s*r).toFixed((0,n.stepDecimals)(r)))}function kn(e,t){let n=document.createElement(`div`);n.className=`tcw-stepper`,n.dir=`ltr`;let r=n=>{let r=Number(e.value),i=e.value.trim()!==``&&Number.isFinite(r)?r:t.fallback?.()??0,a=On(i,n,t.step(i,n));e.value=t.format?t.format(a):String(a),e.dispatchEvent(new Event(`input`))},i=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-stepper-btn`,n.tabIndex=-1,n.setAttribute(`aria-label`,t),n.innerHTML=O(e>0?`plus`:`minus`,14),n.addEventListener(`click`,()=>r(e)),n};e.addEventListener(`keydown`,e=>{e.key!==`ArrowUp`&&e.key!==`ArrowDown`||(e.preventDefault(),r(e.key===`ArrowUp`?1:-1))});let a=i(-1,t.labels.down),o=i(1,t.labels.up);return n.append(a,e,o),{element:n,down:a,up:o}}var An=0,jn=0,Mn=20;function Nn(e){let t=document.createElement(`div`);if(t.className=`tcw-settings-section`,e){let n=document.createElement(`div`);n.className=`tcw-settings-section-title`,n.textContent=e,t.appendChild(n),t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,e)}return t}function Pn(e){let t=document.createElement(`div`);t.className=`tcw-settings-row`;let n=document.createElement(`span`);return n.className=`tcw-settings-label`,n.textContent=e,t.appendChild(n),t}function Fn(e,t,n,r,i){let a=Pn(e),o=document.createElement(`div`);o.className=`tcw-color-picker-wrap`;let s=document.createElement(`input`);s.type=`color`,s.setAttribute(`aria-label`,e);let c=document.createElement(`span`);c.className=`tcw-color-hex`,c.id=`tcw-color-${++An}`,s.setAttribute(`aria-describedby`,c.id);let l=null,u=t=>{s.value=L(t??r.start?.()),c.textContent=t??i(`settings.auto`),a.classList.toggle(`tcw-color-auto`,t===null),t!==null&&r.start&&!l?(l=document.createElement(`button`),l.type=`button`,l.className=`tcw-color-auto-btn`,l.textContent=i(`settings.auto`),l.setAttribute(`aria-label`,`${e}: ${i(`settings.auto`)}`),l.addEventListener(`click`,()=>{n(null),s.focus(),u(r.read())}),o.appendChild(l)):t===null&&l&&(l.remove(),l=null)};return s.addEventListener(`input`,()=>{n(s.value),u(s.value)}),o.append(s,c),a.appendChild(o),u(t),{row:a,sync:()=>u(r.read())}}function z(e,t,n){let r=Pn(e),i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-toggle${t?` tcw-on`:``}`,i.setAttribute(`role`,`switch`),i.setAttribute(`aria-checked`,String(t)),i.setAttribute(`aria-label`,e),i.addEventListener(`click`,()=>{let e=!i.classList.contains(`tcw-on`);i.classList.toggle(`tcw-on`,e),i.setAttribute(`aria-checked`,String(e)),n(e)}),r.appendChild(i),r}function B(e,t,n,r){let i=Pn(e),a=document.createElement(`select`);a.className=`tcw-settings-select`,a.setAttribute(`aria-label`,e);for(let e of n){let n=document.createElement(`option`);n.value=e.value,n.textContent=e.label,e.value===t&&(n.selected=!0),a.appendChild(n)}return n.some(e=>e.value===t)||(a.selectedIndex=-1),a.addEventListener(`change`,()=>r(a.value)),i.appendChild(a),i}function In(e,t,n,r,i=e=>String(e)){let a=Pn(e),o=document.createElement(`div`);o.className=`tcw-settings-range`;let s=document.createElement(`input`);s.type=`range`,s.min=String(n.min),s.max=String(n.max),s.step=String(n.step),s.value=String(t),s.setAttribute(`aria-label`,e);let c=document.createElement(`span`);return c.className=`tcw-settings-range-val`,c.textContent=i(t),s.addEventListener(`input`,()=>{let e=Number(s.value);c.textContent=i(e),r(e)}),o.append(s,c),a.appendChild(o),a}function Ln(e,n,r){let i=new Intl.NumberFormat(r,{maximumFractionDigits:Mn}).format;return e.step===`1`&&Number.isFinite(e.max)?t.r(n(`settings.numberWhole`),{min:i(Math.max(1,e.min??1)),max:i(e.max)}):t.r(n(`settings.numberAtLeast`),{min:i(e.min??0)})}function Rn(e,t,n,r,i,a=`en-US`){let o=document.createElement(`div`);o.className=`tcw-settings-row tcw-settings-row--number`;let s=document.createElement(`label`);s.className=`tcw-settings-label`,s.textContent=e,o.appendChild(s);let c=document.createElement(`input`);c.type=`number`,c.className=`tcw-settings-number`,c.min=`0`,c.step=n.step,Number.isFinite(n.max)&&(c.max=String(n.max)),c.placeholder=i(`settings.auto`),c.value=t===null?``:String(t),c.setAttribute(`aria-label`,e);let l=document.createElement(`div`);l.className=`tcw-settings-hint`,l.id=`tcw-number-hint-${++jn}`,l.setAttribute(`role`,`status`),c.setAttribute(`aria-describedby`,l.id);let u=e=>{e?c.removeAttribute(`aria-invalid`):c.setAttribute(`aria-invalid`,`true`),l.textContent=e?``:Ln(n,i,a)};return c.addEventListener(`change`,()=>{if(c.value.trim()===``){u(!0),r(null);return}let e=Number(c.value),t=Number.isFinite(e)&&e>0&&e>=(n.min??0)&&e<=n.max&&(n.step!==`1`||Number.isInteger(e));u(t),t&&r(e)}),o.append(c,l),o}var V=[{id:`symbol`,icon:`chartType:candlestick`},{id:`statusLine`,icon:`type`},{id:`scales`,icon:`ruler`},{id:`appearance`,icon:`palette`},{id:`layers`,icon:`layers`},{id:`trading`,icon:`trendingUp`}],zn=[1,2,3,4],Bn=`t:`,Vn={step:`any`,max:1/0,min:1e-8},Hn=1,Un=class{callbacks;t;backdrop=null;modal=null;bodyEl=null;tabButtons=[];templateBtn=null;menu=null;currentTab=`symbol`;currentSettings=null;chartType=null;lookRows=[];returnFocus=null;uid=Hn++;constructor(e,t,n={},r=()=>document.body){this.available=n,this.host=r,this.callbacks=e,this.t=t}open(e,t=null,n=`symbol`){this.modal&&this.remove(),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.currentSettings={...e},this.chartType=t,this.currentTab=n,this.buildModal(),this.tabButtons.find(e=>e.dataset.tab===n)?.focus()}isOpen(){return this.modal!==null}refresh(e,t){if(!this.modal)return;this.currentSettings={...e},t!==void 0&&(this.chartType=t);let n=this.focusedControl();this.renderTabContent(),n!==null&&this.focusControl(n)}focusedControl(){let e=document.activeElement;if(!this.bodyEl||!(e instanceof HTMLElement)||!this.bodyEl.contains(e))return null;let t=this.panelControls().indexOf(e);return t<0?null:t}focusControl(e){let t=this.panelControls();(t[Math.min(e,t.length-1)]??this.tabButtons.find(e=>e.dataset.tab===this.currentTab))?.focus()}panelControls(){return this.bodyEl?[...this.bodyEl.querySelectorAll(bn)]:[]}close(){this.finish(!0)}destroy(){this.remove()}finish(e){this.modal&&(e?this.callbacks.onClose():this.callbacks.onCancel?.(),this.remove(),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}remove(){this.menu?.destroy(),this.menu=null,this.backdrop?.remove(),this.backdrop=this.modal=this.bodyEl=this.templateBtn=null,this.tabButtons=[]}buildModal(){let e=document.createElement(`div`);e.className=`tcw-modal-backdrop`;let t=!1;e.addEventListener(`pointerdown`,n=>{t=n.target===e}),e.addEventListener(`click`,n=>{n.target===e&&t&&this.finish(!1),t=!1});let n=document.createElement(`div`);n.className=`tcw-modal tcw-set`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-labelledby`,`tcw-set-title-${this.uid}`),n.tabIndex=-1,n.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.finish(!1);return}M(e,n)}),this.backdrop=e,this.modal=n,n.append(this.buildHeader(),this.buildBody(),this.buildFooter()),e.appendChild(n),this.host().appendChild(e),this.markTabs(),this.renderTabContent()}buildHeader(){let e=document.createElement(`div`);e.className=`tcw-modal-header`;let t=document.createElement(`h3`);t.id=`tcw-set-title-${this.uid}`,t.textContent=this.t(`settings.title`);let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-modal-close`,n.setAttribute(`aria-label`,this.t(`common.close`)),n.innerHTML=O(`x`,16),n.addEventListener(`click`,()=>this.finish(!1)),e.append(t,n),e}buildBody(){let e=document.createElement(`div`);e.className=`tcw-set-body`;let t=document.createElement(`div`);t.className=`tcw-set-nav`,t.setAttribute(`role`,`tablist`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,this.t(`settings.title`)),t.addEventListener(`keydown`,e=>this.onTabKey(e)),this.tabButtons=V.map(({id:e,icon:t})=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-set-tab`,n.id=`tcw-set-tab-${this.uid}-${e}`,n.dataset.tab=e,n.setAttribute(`role`,`tab`),n.setAttribute(`aria-controls`,`tcw-set-panel-${this.uid}`),n.innerHTML=`${t.startsWith(`chartType:`)?nt(t.slice(10),16):O(t,16)}<span></span>`,n.querySelector(`span`).textContent=this.t(`settings.tab.${e}`),n.addEventListener(`click`,()=>this.selectTab(e)),n}),t.append(...this.tabButtons);let n=document.createElement(`div`);return n.className=`tcw-modal-body tcw-set-panel`,n.id=`tcw-set-panel-${this.uid}`,n.setAttribute(`role`,`tabpanel`),this.bodyEl=n,e.append(t,n),e}buildFooter(){let e=document.createElement(`div`);e.className=`tcw-modal-footer`;let t=this.footerButton(`template`,`tcw-footer-menu`,()=>this.openTemplates());t.setAttribute(`aria-haspopup`,`menu`),t.setAttribute(`aria-expanded`,`false`),t.innerHTML=`<span></span>${O(`chevronDown`,12)}`,t.querySelector(`span`).textContent=this.t(`settings.template`),this.templateBtn=t;let n=document.createElement(`div`);return n.className=`tcw-footer-end`,n.append(this.footerButton(`cancel`,`tcw-footer-cancel`,()=>this.finish(!1),this.t(`common.cancel`)),this.footerButton(`ok`,`tcw-done-btn`,()=>this.finish(!0),this.t(`drawingSettings.ok`))),e.append(t,n),e}footerButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=t,i.dataset.act=e,r&&(i.textContent=r),i.addEventListener(`click`,n),i}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.currentTab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl?.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.currentTab=e,this.markTabs(),this.renderTabContent(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=V.findIndex(e=>e.id===this.currentTab),n=e.key===`ArrowDown`||e.key===`ArrowRight`?(t+1)%V.length:e.key===`ArrowUp`||e.key===`ArrowLeft`?(t-1+V.length)%V.length:e.key===`Home`?0:e.key===`End`?V.length-1:-1;n<0||(e.preventDefault(),this.selectTab(V[n].id,!0))}openTemplates(){let e=this.templateBtn;if(!this.modal||!e)return;if(this.menu?.isOpen()){this.menu.close();return}let n=this.callbacks.templates,r=(n?.list()??[]).map(e=>({id:`${Bn}${e}`,label:e,icon:`layers`,remove:t.r(this.t(`templates.delete`),{name:e})})),i=[...r,...r.length>0?[`separator`]:[],...n?[{id:`save`,label:this.t(`settings.saveTemplate`),icon:`save`}]:[],{id:`reset`,label:this.t(`settings.resetToDefaults`),icon:`reset`}];this.menu??=new A(this.modal,this.t(`settings.template`));let a=e.getBoundingClientRect(),o=this.modal.getBoundingClientRect();this.menu.open(i,a.left-o.left,a.top-o.top,e=>{e===`reset`?this.callbacks.onReset():e===`save`?n?.save():e.startsWith(Bn)&&n?.apply(e.slice(2))},e,e=>n?.remove(e.slice(2)))}renderTabContent(){if(!(!this.bodyEl||!this.currentSettings))switch(this.bodyEl.replaceChildren(),this.lookRows=[],this.currentTab){case`symbol`:this.renderSymbolTab(this.currentSettings);break;case`statusLine`:this.renderStatusLineTab(this.currentSettings);break;case`scales`:this.renderScalesTab(this.currentSettings);break;case`appearance`:this.renderAppearanceTab(this.currentSettings);break;case`layers`:this.renderLayersTab(this.currentSettings);break;case`trading`:for(let e of Ee)(!e.trading||this.available.trading!==!1)&&this.renderLookSection(e);break}}renderSymbolTab(e){this.renderChartTypeSection(),this.addSection(void 0,[z(this.t(`settings.mainSeries`),e.mainSeriesVisible,e=>this.patch({mainSeriesVisible:e})),z(this.t(`settings.extendedHours`),e.extendedHours,e=>this.patch({extendedHours:e}))]);let t=this.t(`common.show`);this.renderLookSection(ve),this.available.volume!==!1&&this.renderLookSection(ye,[z(t,e.volumeVisible,e=>this.patch({volumeVisible:e}))]),this.renderLookSection(be,[z(t,e.highLowLines,e=>this.patch({highLowLines:e}))])}renderStatusLineTab(e){let t=this.available.legend!==!1,n=t?Ce:Ce.filter(e=>!Se.includes(e));this.addSection(void 0,[...t?[z(this.t(`settings.ohlcLegend`),e.legendVisible,e=>this.patch({legendVisible:e}))]:[],...n.map(e=>this.lookRow(e))])}renderScalesTab(e){let t=[{value:`regular`,label:this.t(`settings.scale.regular`)},{value:`logarithmic`,label:this.t(`settings.scale.logarithmic`)},{value:`percentage`,label:this.t(`settings.scale.percentage`)},{value:`indexedTo100`,label:this.t(`settings.scale.indexedTo100`)}].filter(e=>e.value!==`logarithmic`||this.available.logScale!==!1),n=this.available.exchangeZone?.(),r=f(e.timezone,Date.now(),this.t(`settings.timezone.local`),n===void 0?void 0:{label:this.t(`settings.timezone.exchange`),zone:n});this.addSection(void 0,[B(this.t(`settings.priceScale`),e.scaleMode,t,e=>this.patch({scaleMode:e})),z(this.t(`settings.autoScale`),e.autoScale,e=>this.patch({autoScale:e})),z(this.t(`settings.invertScale`),e.invertScale,e=>this.patch({invertScale:e})),z(this.t(`settings.leftScale`),e.leftPriceScale,e=>this.patch({leftPriceScale:e})),z(this.t(`settings.indicatorValues`),e.indicatorValueLabels,e=>this.patch({indicatorValueLabels:e})),z(this.t(`settings.alignAxisLabels`),e.alignAxisLabels,e=>this.patch({alignAxisLabels:e})),...this.available.barCountdown===!1?[]:[z(this.t(`settings.barCountdown`),e.barCountdown,e=>this.patch({barCountdown:e}))],B(this.t(`settings.timezone`),e.timezone,r,e=>this.patch({timezone:e})),B(this.t(`settings.numberLocale`),e.numberLocale,gt(e.numberLocale),e=>this.patch({numberLocale:e}))]),this.addSection(this.t(`settings.section.axes`),we.map(e=>this.lookRow(e)))}renderAppearanceTab(e){let[t,n,r,...i]=Te;this.renderLookSection(t),this.renderLookSection(n,[z(this.t(`common.show`),e.gridVisible,e=>this.patch({gridVisible:e}))]),this.renderLookSection(r,[B(this.t(`settings.crosshairMode`),e.crosshairMode,[{label:this.t(`settings.crosshair.magnet`),value:`magnet`},{label:this.t(`settings.crosshair.normal`),value:`normal`},{label:this.t(`settings.crosshair.hidden`),value:`hidden`}],e=>this.patch({crosshairMode:e}))]);for(let e of i)this.renderLookSection(e)}renderLayersTab(e){let t=e=>`${Math.round(e*100)}%`,n=e=>this.t(e);this.addSection(void 0,[z(n(`settings.volumeProfile`),e.volumeProfileVisible,e=>this.patch({volumeProfileVisible:e}))]),this.addSection(void 0,[z(n(`settings.marketProfile`),e.marketProfileVisible,e=>this.patch({marketProfileVisible:e})),z(n(`settings.marketProfileSplit`),e.marketProfileSplit,e=>this.patch({marketProfileSplit:e})),z(n(`settings.marketProfileLetters`),e.marketProfileLetters,e=>this.patch({marketProfileLetters:e})),In(n(`settings.marketProfileBuckets`),e.marketProfileBuckets,{min:8,max:200,step:1},e=>this.patch({marketProfileBuckets:e})),In(n(`settings.marketProfileOpacity`),e.marketProfileOpacity,{min:.05,max:1,step:.05},e=>this.patch({marketProfileOpacity:e}),t)]),this.addSection(void 0,[z(n(`settings.depthHeatmap`),e.depthHeatmapVisible,e=>this.patch({depthHeatmapVisible:e})),In(n(`settings.depthHeatmapOpacity`),e.depthHeatmapOpacity,{min:.1,max:1,step:.05},e=>this.patch({depthHeatmapOpacity:e}),t)]),this.addSection(void 0,[z(n(`settings.swingMarkers`),e.pivotMarkersVisible,e=>this.patch({pivotMarkersVisible:e})),In(n(`settings.swingStrength`),e.pivotStrength,{min:2,max:20,step:1},e=>this.patch({pivotStrength:e})),z(n(`settings.swingStructure`),e.pivotStructureLabels,e=>this.patch({pivotStructureLabels:e}))]),this.addSection(void 0,[z(n(`settings.sessionShading`),e.sessionShadingVisible,e=>this.patch({sessionShadingVisible:e})),z(n(`settings.periodLevels`),e.periodLevelsVisible,e=>this.patch({periodLevelsVisible:e})),B(n(`settings.periodLevelsBasis`),e.periodLevelsPeriod,[{value:`day`,label:n(`settings.priorDay`)},{value:`week`,label:n(`settings.priorWeek`)}],e=>this.patch({periodLevelsPeriod:e}))])}addSection(e,t){let n=Nn(e);return n.append(...t),this.bodyEl?.appendChild(n),n}renderLookSection(e,t=[]){this.addSection(this.t(e.title),[...t,...e.rows.map(e=>this.lookRow(e))])}lookRow(e){let t=this.t(e.label),r=()=>this.callbacks.styleValue(e.keys[0]),i=()=>{let t=e.keys.map(e=>this.callbacks.styleValue(e));return t.every(e=>e===t[0])&&t[0]!==null?String(t[0]):``},a,o=t=>{this.callbacks.onStyleChange(Object.fromEntries(e.keys.map(e=>[e,t])));for(let e of this.lookRows)e.el!==a&&e.sync()},s=e.auto?[{value:``,label:this.t(`settings.auto`)}]:[],c;switch(n.CHART_STYLE_KEYS[e.keys[0]]){case`boolean`:{a=z(t,r()===!0,o);let e=a.querySelector(`button`);c=()=>{let t=r()===!0;e.classList.toggle(`tcw-on`,t),e.setAttribute(`aria-checked`,String(t))};break}case`lineStyle`:a=B(t,i(),[...s,...this.lineStyles()],e=>o(e===``?null:Gn(e))),c=()=>{a.querySelector(`select`).value=i()};break;case`width`:{let e=r(),n=typeof e==`number`&&!zn.includes(e)?[...zn,e].sort((e,t)=>e-t):zn;a=B(t,i(),[...s,...n.map(e=>({value:String(e),label:`${e}px`}))],e=>o(e===``?null:Number(e))),c=()=>{a.querySelector(`select`).value=i()};break}default:{let n=r(),i=Fn(t,typeof n==`string`?n:null,o,{read:()=>{let e=r();return typeof e==`string`?e:null},start:e.auto?()=>(e.auto?.from?this.callbacks.styleValue(e.auto.from):e.auto?.hint)??null:void 0},this.t);a=i.row,c=i.sync}}return this.lookRows.push({el:a,sync:c}),a}lineStyles(){return[{value:`solid`,label:this.t(`drawingSettings.lineStyle.solid`)},{value:`dashed`,label:this.t(`drawingSettings.lineStyle.dashed`)},{value:`dotted`,label:this.t(`drawingSettings.lineStyle.dotted`)}]}renderChartTypeSection(){if(!this.bodyEl||!this.currentSettings||!this.chartType)return;let e=this.chartType,t=this.currentSettings.chartTypeOptions??{},n=pe.find(t=>t.value===e),r=Nn(n?vt(n,this.t):e),i=()=>this.currentSettings?.chartTypeOptions??{},a=(e,t)=>this.patch({chartTypeOptions:{...i(),[e]:t}}),o=(e,t,n,i)=>r.appendChild(Rn(this.t(e),t,n,i,this.t,this.currentSettings?.numberLocale||void 0));switch(e){case`renko`:{let e=t.renko??{};o(`settings.boxSize`,typeof e.boxSize==`number`?e.boxSize:null,Vn,e=>a(`renko`,{...i().renko??{},boxSize:e??`atr`})),o(`settings.atrPeriod`,e.atrPeriod??null,{step:`1`,max:500},e=>a(`renko`,Wn(i().renko,`atrPeriod`,e)));break}case`lineBreak`:o(`settings.lineBreakLines`,t.lineBreak?.lines??null,{step:`1`,max:10},e=>a(`lineBreak`,Wn(i().lineBreak,`lines`,e)));break;case`kagi`:o(`settings.reversal`,t.kagi?.reversal??null,Vn,e=>a(`kagi`,Wn(i().kagi,`reversal`,e))),r.appendChild(B(this.t(`settings.reversalType`),t.kagi?.reversalType??`percent`,[{value:`percent`,label:this.t(`settings.reversalType.percent`)},{value:`price`,label:this.t(`settings.reversalType.price`)}],e=>a(`kagi`,{...i().kagi??{},reversalType:e===`price`?`price`:`percent`})));break;case`pointAndFigure`:o(`settings.boxSize`,typeof t.pointAndFigure?.boxSize==`number`?t.pointAndFigure.boxSize:null,Vn,e=>a(`pointAndFigure`,{...i().pointAndFigure??{},boxSize:e??`auto`})),o(`settings.reversalBoxes`,t.pointAndFigure?.reversal??null,{step:`1`,max:10},e=>a(`pointAndFigure`,Wn(i().pointAndFigure,`reversal`,e)));break;case`rangeBars`:o(`settings.barRange`,typeof t.rangeBars?.range==`number`?t.rangeBars.range:null,Vn,e=>a(`rangeBars`,{range:e??`auto`}));break;default:break}for(let t of ke(e))r.appendChild(this.lookRow(t));this.bodyEl.appendChild(r)}patch(e){this.currentSettings&&Object.assign(this.currentSettings,e),this.callbacks.onChange(e)}};function Wn(e,t,n){let r={...e??{}};return n===null?delete r[t]:r[t]=n,r}function Gn(e){return e===`dashed`||e===`dotted`?e:`solid`}var Kn=`data-tcw-folded`,qn=`tcw-statusbar--folded`,Jn=`tcw-statusbar--short-market`,Yn=1,Xn=13,Zn=`goto`,Qn=`Alt+G`,$n=e=>e.goToKeys?e.goToKeys():Qn;function er(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}var tr=class{el;dotEl;messageEl;marketEl;hostLeft;hostRight;clockBtn=null;clockMenu=null;scaleBtns=null;scaleShown=``;marketShown=``;rightEl;rangeEl=null;presetBtns=[];moreBtn=null;goToBtn=null;rangeMenu=null;resizeObserver=null;fitFrame=0;destroyed=!1;constructor(e,t,n={}){this.host=e,this.extras=n,this.el=document.createElement(`div`),this.el.className=`tcw-statusbar`,D(this.el,`statusBar`),n.label&&(this.el.setAttribute(`role`,`group`),this.el.setAttribute(`aria-label`,n.label)),t&&this.el.appendChild(this.buildRange(t)),this.hostLeft=this.hostGroup(),this.el.appendChild(this.hostLeft);let r=document.createElement(`div`);r.className=`tcw-status-right`,this.rightEl=r,this.hostRight=this.hostGroup(),r.appendChild(this.hostRight);let i=document.createElement(`div`);i.className=`tcw-status-indicator`,D(i,`statusBar.connection`),this.dotEl=document.createElement(`span`),this.dotEl.className=`tcw-status-dot`,i.appendChild(this.dotEl),this.messageEl=document.createElement(`span`),i.appendChild(this.messageEl),this.marketEl=document.createElement(`span`),this.marketEl.className=`tcw-status-market`,this.marketEl.hidden=!0,D(this.marketEl,`statusBar.market`),r.appendChild(this.marketEl),r.appendChild(i),n.clock&&r.appendChild(this.buildClock(n.clock)),n.scale&&r.appendChild(this.buildScale(n.scale)),this.el.appendChild(r),e.appendChild(this.el),this.watchWidths(r)}watchWidths(e){if(typeof ResizeObserver<`u`){this.resizeObserver=new ResizeObserver(()=>this.scheduleFit());for(let t of[this.el,e,this.hostLeft])this.resizeObserver.observe(t)}document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.destroyed||this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.destroyed||this.fit()}))}fit(){let e=this.foldedCount(),t=this.rangeFocus();this.refit(),this.foldedCount()!==e&&this.rangeMenu?.close(),this.keepFocus(t)}refit(){let e=this.foldSteps(),t=this.goToBtn?[...this.presetBtns,this.goToBtn]:this.presetBtns,n=n=>{let r=new Set(e.slice(0,n));for(let e of t)e.toggleAttribute(Kn,r.has(e));this.el.classList.toggle(qn,n>0)};if(n(0),this.el.classList.remove(Jn),this.el.clientWidth===0||this.fits())return;let r=0;for(;r<e.length;)if(n(++r),this.fits())return;if(!(this.marketEl.hidden||this.isOff(this.marketEl))){for(this.el.classList.add(Jn);r>0;r--)if(n(r-1),!this.fits()){n(r);return}}}fits(){return this.rangeFits()&&this.rightFits()}rangeFits(){let e=this.rangeEl;return!e||e.scrollWidth<=e.clientWidth+Yn}rightFits(){if(this.rightEl.offsetParent!==this.el)return!0;let e=getComputedStyle(this.el),t=this.rightEl.offsetLeft;return(e.direction===`rtl`?(parseFloat(e.paddingLeft)||0)-t:t+this.rightEl.offsetWidth-(this.el.clientWidth-(parseFloat(e.paddingRight)||0)))<=Yn}foldedCount(){return this.rangeEl?.querySelectorAll(`[${Kn}]`).length??0}rangeFocus(){if(this.rangeMenu?.hasFocus())return this.moreBtn;let e=document.activeElement;return e instanceof HTMLElement&&this.rangeEl?.contains(e)?e:null}keepFocus(e){if(!e||this.rangeMenu?.isOpen())return;let t=this.focusAfterRefit(e);t===this.el?this.focusBar():document.activeElement!==t&&t.focus({preventScroll:!0})}focusAfterRefit(e){if(this.shows(e))return e;let t=this.presetBtns.filter(e=>this.shows(e)).at(-1);return[e===this.moreBtn?null:this.moreBtn,this.goToBtn,t].find(e=>e!=null&&this.shows(e))??this.firstOtherControl()??this.el}firstOtherControl(){return[...this.el.querySelectorAll(`button`)].filter(e=>!this.rangeEl?.contains(e)).find(e=>!e.disabled&&e.getClientRects().length>0)??null}focusBar(){if(document.activeElement===this.el)return;let e=()=>this.el.removeAttribute(`tabindex`);this.el.tabIndex=-1,this.el.addEventListener(`blur`,e,{once:!0}),this.el.focus({preventScroll:!0}),document.activeElement!==this.el&&(this.el.removeEventListener(`blur`,e),e())}shows(e){return e===this.moreBtn&&!this.el.classList.contains(qn)?!1:!e.hasAttribute(Kn)&&!this.isOff(e)}foldSteps(){if(this.presetBtns.length===0||this.isOff(this.presetBtns[0]))return[];let e=[...this.presetBtns].reverse();return this.goToBtn&&e.push(this.goToBtn),e}isOff(e){let t=((this.el.closest(`.tcw-root`)??this.host).getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean);return(e.dataset.tcwPart??``).split(/\s+/).some(e=>t.includes(e))}update(e){this.dotEl.className=`tcw-status-dot`,e.connectionState===`connected`?this.dotEl.classList.add(`tcw-connected`):e.connectionState===`error`&&this.dotEl.classList.add(`tcw-error`),this.messageEl.textContent=e.message}tick(){if(!this.clockBtn||!this.extras.clock)return;let{time:e,zone:t}=this.extras.clock.now(),n=`${e} ${t}`;this.clockBtn.textContent!==n&&(this.clockBtn.textContent=n)}setScale(e){let t=`${e.mode}|${e.auto}`;!this.scaleBtns||t===this.scaleShown||(this.scaleShown=t,this.scaleBtns.percent?.setAttribute(`aria-pressed`,String(e.mode===`percentage`)),this.scaleBtns.log?.setAttribute(`aria-pressed`,String(e.mode===`logarithmic`)),this.scaleBtns.auto?.setAttribute(`aria-pressed`,String(e.auto)))}setMarket(e,t,n=t){let r=`${e}|${t}|${n}`;if(r===this.marketShown)return;if(this.marketShown=r,this.marketEl.hidden=e===`always`,this.marketEl.dataset.state=e,e===`always`){this.marketEl.replaceChildren(),this.marketEl.removeAttribute(`title`);return}this.marketEl.title=t;let i=er(`tcw-status-market-short`,n);i.setAttribute(`aria-hidden`,`true`),this.marketEl.replaceChildren(er(`tcw-status-market-text`,t),i)}addHostItem(e){let t=e.onClick,n=t?document.createElement(`button`):document.createElement(`span`);return n.className=t?`tcw-status-host-item tcw-status-host-btn`:`tcw-status-host-item`,n.dataset.hostItem=e.id,n.dir=`auto`,n.textContent=e.text,e.label&&(n.title=e.label,t||n.setAttribute(`role`,`group`),e.label!==e.text&&n.setAttribute(`aria-label`,`${e.label}: ${e.text}`)),n instanceof HTMLButtonElement&&t&&(n.type=`button`,n.addEventListener(`click`,()=>t(n))),(e.side===`left`?this.hostLeft:this.hostRight).appendChild(n),n}hostSlot(e){return e===`left`?this.hostLeft:this.hostRight}destroy(){this.destroyed=!0,this.resizeObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.clockMenu?.destroy(),this.rangeMenu?.destroy(),this.el.remove()}buildClock(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-status-clock`,t.dataset.role=`clock`,t.dir=`auto`,t.title=e.label,t.setAttribute(`aria-haspopup`,`menu`),D(t,`statusBar.clock`),t.addEventListener(`click`,()=>this.toggleZones(t,e)),this.clockBtn=t,this.tick(),t}toggleRangeMenu(e,t){if(this.rangeMenu?.isOpen()){this.rangeMenu.close();return}let n=e=>e.hasAttribute(Kn)&&!this.isOff(e),r=t.presets.filter((e,t)=>n(this.presetBtns[t])).map(e=>({id:e,label:t.presetLabels?.[e]??e}));if(this.goToBtn&&n(this.goToBtn)&&(r.length>0&&r.push(`separator`),r.push({id:Zn,label:t.goToLabel,icon:`calendar`,shortcut:$n(t)})),r.length===0)return;this.rangeMenu??=new A(this.host,t.groupLabel);let i=e.getBoundingClientRect(),a=this.host.getBoundingClientRect();this.rangeMenu.open(r,i.left-a.left,i.top-a.top,e=>e===Zn?t.onGoTo():t.onPreset(e),e,void 0,i.right-a.left)}toggleZones(e,t){if(this.clockMenu?.isOpen()){this.clockMenu.close();return}let{current:n,list:r}=t.options();this.clockMenu??=new A(this.host,t.label);let i=e.getBoundingClientRect(),a=this.host.getBoundingClientRect();this.clockMenu.open(r.map(e=>({id:e.value,label:e.label,checked:e.value===n})),i.left-a.left,i.top-a.top,e=>t.onPick(e),e,void 0,i.right-a.left)}buildScale(e){let t=document.createElement(`div`);t.className=`tcw-status-scale`,t.setAttribute(`role`,`group`),e.labels.group&&t.setAttribute(`aria-label`,e.labels.group),D(t,`statusBar.scale`);let n=(n,r,i)=>{let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-status-scale-btn`,a.dataset.scale=n,a.textContent=r,a.title=e.labels[n],a.setAttribute(`aria-label`,e.labels[n]),a.setAttribute(`aria-pressed`,`false`),a.addEventListener(`click`,i),t.appendChild(a),a};return this.scaleBtns={percent:n(`percent`,`%`,e.onPercent),...e.onLog?{log:n(`log`,e.texts?.log??`log`,e.onLog)}:{},auto:n(`auto`,e.texts?.auto??`auto`,e.onAuto)},t}hostGroup(){let e=document.createElement(`div`);return e.className=`tcw-status-host`,e}buildRange(e){let t=document.createElement(`div`);t.className=`tcw-range-bar`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,e.groupLabel);for(let n of e.presets){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-range-btn`,r.dataset.range=n,D(r,`statusBar.range`),r.textContent=e.presetLabels?.[n]??n,r.addEventListener(`click`,()=>e.onPreset(n)),t.appendChild(r),this.presetBtns.push(r)}let n=this.rangeIconBtn(`tcw-range-more`,`rangeMore`,`more`,e.moreLabel);D(n,`statusBar.range`),n.setAttribute(`aria-haspopup`,`menu`),n.setAttribute(`aria-expanded`,`false`),n.addEventListener(`click`,()=>this.toggleRangeMenu(n,e)),t.appendChild(n),this.moreBtn=n;let r=this.rangeIconBtn(`tcw-range-goto`,`goto`,`calendar`,e.goToLabel);D(r,`goToDate`,`statusBar.goToDate`);let i=()=>{let t=$n(e);r.title=t?`${e.goToLabel} (${t})`:e.goToLabel};return i(),r.addEventListener(`pointerover`,i),r.addEventListener(`focusin`,i),r.addEventListener(`click`,e.onGoTo),t.appendChild(r),this.goToBtn=r,this.rangeEl=t,t}rangeIconBtn(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-range-btn ${e}`,i.dataset.role=t,i.title=r,i.setAttribute(`aria-label`,r),i.innerHTML=O(n,Xn),i}},nr=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent)?`⌘`:`Ctrl`,rr=e=>e.toLowerCase().replace(/[\s+]+/g,``).replace(/[\u2010-\u2015\u2212]/g,`-`),ir=5,ar=229,or=[`action`,`drawing`,`chartType`,`timeframe`,`indicator`],sr={indicator:`palette.group.indicator`,chartType:`palette.group.chartType`,drawing:`palette.group.drawing`,timeframe:`palette.group.timeframe`,action:`palette.group.action`},cr=e=>`${e.category}:${e.id}`;function lr(e,t){let n=e.label.toLowerCase(),r=rr(n);return e.id.toLowerCase()===t||r===t?5:r.startsWith(t)?4:n.split(/[\s/()-]+/).some(e=>e.startsWith(t))?3:r.includes(t)||e.id.toLowerCase().includes(t)?2:e.shortcut&&rr(e.shortcut).includes(t)?1:0}var ur=0,dr=class{backdrop=null;input=null;list=null;emptyEl=null;liveEl=null;items=[];shown=[];selectedIndex=0;returnFocus=null;uid=++ur;constructor(e,n=()=>document.body,r=t.t,i){this.callbacks=e,this.host=n,this.t=r,this.recents=i}open(e){this.backdrop||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.items=e,this.build(),this.render(),this.input?.focus())}close(){if(!this.backdrop)return;this.backdrop.remove(),this.backdrop=this.input=this.list=this.emptyEl=this.liveEl=null,this.callbacks.onClose();let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}isOpen(){return this.backdrop!==null}destroy(){this.close()}build(){let e=document.createElement(`div`);e.className=`tcw-modal-backdrop`;let t=!1;e.addEventListener(`pointerdown`,n=>{t=n.target===e}),e.addEventListener(`click`,n=>{n.target===e&&t&&this.close(),t=!1});let n=document.createElement(`div`);n.className=`tcw-modal tcw-cp`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-label`,this.t(`hotkeys.commandPalette`)),n.tabIndex=-1,n.addEventListener(`keydown`,e=>this.onKeyDown(e,n));let r=document.createElement(`label`);r.className=`tcw-ss-search tcw-cp-search`,r.innerHTML=O(`search`,16);let i=document.createElement(`input`);i.type=`search`,i.className=`tcw-cp-input`,i.placeholder=this.t(`palette.placeholder`),i.setAttribute(`aria-label`,this.t(`palette.placeholder`)),i.setAttribute(`role`,`combobox`),i.setAttribute(`aria-expanded`,`true`),i.setAttribute(`aria-autocomplete`,`list`),i.setAttribute(`aria-controls`,`tcw-cp-list-${this.uid}`),i.autocomplete=`off`,i.spellcheck=!1,i.addEventListener(`input`,()=>this.render()),r.appendChild(i);let a=document.createElement(`div`);a.className=`tcw-cp-results`;let o=document.createElement(`div`);o.className=`tcw-cp-list`,o.id=`tcw-cp-list-${this.uid}`,o.setAttribute(`role`,`listbox`),o.setAttribute(`aria-label`,this.t(`hotkeys.commandPalette`));let s=document.createElement(`div`);s.className=`tcw-cp-empty`,a.append(o,s),a.addEventListener(`mousedown`,e=>e.preventDefault());let c=document.createElement(`div`);c.className=`tcw-cp-live tcw-visually-hidden`,c.setAttribute(`aria-live`,`polite`),n.append(r,a,c),e.appendChild(n),this.host().appendChild(e),this.backdrop=e,this.input=i,this.list=o,this.emptyEl=s,this.liveEl=c}groups(){let e=rr((this.input?.value??``).trim()),t=[];if(!e){let e=new Map(this.items.map(e=>[cr(e),e])),n=(this.recents?.list()??[]).map(t=>e.get(t)).filter(e=>!!e).slice(0,ir);n.length>0&&t.push({key:`recent`,label:this.t(`palette.group.recent`),items:n})}for(let n of or){let r=this.items.filter(e=>e.category===n);e&&(r=r.map((t,n)=>({item:t,at:n,s:lr(t,e)})).filter(e=>e.s>0).sort((e,t)=>t.s-e.s||e.at-t.at).map(e=>e.item)),r.length>0&&t.push({key:n,label:this.t(sr[n]),items:r})}return e&&t.sort((t,n)=>lr(n.items[0],e)-lr(t.items[0],e)),t}render(){let e=this.list;if(!e)return;let t=this.groups();this.shown=t.flatMap(e=>e.items),this.selectedIndex=0;let n=0;e.replaceChildren(...t.map(e=>{let t=document.createElement(`div`);t.setAttribute(`role`,`group`),t.className=`tcw-cp-group`;let r=document.createElement(`div`);return r.className=`tcw-cp-heading`,r.id=`tcw-cp-${e.key}-${this.uid}`,r.setAttribute(`role`,`presentation`),r.textContent=e.label,t.setAttribute(`aria-labelledby`,r.id),t.append(r,...e.items.map(e=>this.row(e,n++))),t}));let r=this.shown.length===0?this.t(`palette.empty`):``;this.emptyEl&&(this.emptyEl.textContent=r),this.emptyEl?.toggleAttribute(`hidden`,this.shown.length>0),this.liveEl&&(this.liveEl.textContent=r),this.markSelection()}row(e,t){let n=document.createElement(`div`);n.className=`tcw-cp-row`,n.id=`tcw-cp-opt-${this.uid}-${t}`,n.dataset.id=e.id,n.setAttribute(`role`,`option`),n.classList.toggle(`tcw-on`,!!e.active);let r=document.createElement(`span`);if(r.className=`tcw-cp-label`,r.textContent=e.label,n.appendChild(r),e.shortcut){let t=document.createElement(`kbd`);t.className=`tcw-cp-key`,t.dir=`ltr`,t.textContent=e.shortcut,n.appendChild(t)}if(e.active){let e=document.createElement(`span`);e.className=`tcw-cp-check`,e.innerHTML=O(`check`,14),n.appendChild(e)}return n.addEventListener(`click`,()=>this.run(t)),n.addEventListener(`mousemove`,()=>{this.selectedIndex!==t&&(this.selectedIndex=t,this.markSelection())}),n}markSelection(){let e=this.list?.querySelectorAll(`.tcw-cp-row`)??[],t=null;e.forEach((e,n)=>{let r=n===this.selectedIndex;e.setAttribute(`aria-selected`,String(r)),e.classList.toggle(`tcw-selected`,r),r&&(t=e)});let n=t;n?(this.input?.setAttribute(`aria-activedescendant`,n.id),n.scrollIntoView?.({block:`nearest`})):this.input?.removeAttribute(`aria-activedescendant`)}run(e){let t=this.shown[e];if(t)switch(this.recents?.add(cr(t)),this.close(),t.category){case`indicator`:this.callbacks.onIndicator(t.id);break;case`chartType`:this.callbacks.onChartType(t.id);break;case`drawing`:this.callbacks.onDrawingTool(t.id);break;case`timeframe`:this.callbacks.onTimeframe(t.id);break;case`action`:this.callbacks.onAction(t.id);break}}onKeyDown(e,t){if(e.stopPropagation(),e.isComposing||e.keyCode===ar)return;let n=(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`k`;if(e.key===`Escape`||n){e.preventDefault(),this.close();return}if(M(e,t),e.target!==this.input)return;let r=this.shown.length;if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),r===0)return;this.selectedIndex=(this.selectedIndex+(e.key===`ArrowDown`?1:-1)+r)%r,this.markSelection()}else e.key===`Enter`&&(e.preventDefault(),e.repeat||this.run(this.selectedIndex))}},fr=20,pr=1e3,mr=new Set,hr={stock:1,stocks:1,equity:1,share:1,shares:1,"cổ phiếu":1,株式:1,株:1,股票:1,주식:1,futures:2,future:2,derivative:2,derivatives:2,option:2,options:2,"phái sinh":2,先物:2,期货:2,期貨:2,선물:2,warrant:2,warrants:2,"covered warrant":2,"chứng quyền":2,index:3,indices:3,"chỉ số":3,指数:3,指數:3,지수:3,fund:3,funds:3,etf:3,etfs:3,"chứng chỉ quỹ":3,crypto:4,cryptocurrency:4,perpetual:4,perpetuals:4,perp:4,perps:4,"tiền mã hóa":4,"tiền mã hoá":4,"tiền điện tử":4,暗号資産:4,仮想通貨:4,加密货币:4,加密貨幣:4,数字货币:4,數字貨幣:4,虚拟货币:4,虛擬貨幣:4,암호화폐:4,가상자산:4,가상화폐:4,forex:5,fx:5,currency:5,"ngoại hối":5,為替:5,外国為替:5,外汇:5,外匯:5,외환:5,bond:5,bonds:5,"trái phiếu":5},gr=1e3,_r=new Map,vr=/i\u0307|\u0131/g;function yr(e){if(typeof e!=`string`)return``;let t=_r.get(e);return t===void 0&&(t=e.trim().normalize(`NFC`).toLowerCase().replace(vr,`i`),_r.size>=gr&&_r.clear(),_r.set(e,t)),t}function br(e){let t=yr(e);return t?Object.prototype.hasOwnProperty.call(hr,t)?hr[t]:1+xr(t)%5:0}function xr(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0),t=Math.imul(t,16777619)>>>0;return t}function Sr(e){let{ticker:t}=Qt(e),n=/[\p{L}\p{N}]/u.exec(t);return n?n[0].toUpperCase():``}function Cr(e,t){let n=rn(t?.logo);if(!n||mr.has(n))return Tr(e,t);let r=document.createElement(`img`);return r.className=`tcw-ss-badge`,r.alt=``,r.width=fr,r.height=fr,r.draggable=!1,r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`loading`,`lazy`),r.setAttribute(`decoding`,`async`),r.setAttribute(`referrerpolicy`,`no-referrer`),r.addEventListener(`error`,()=>{wr(n),r.replaceWith(Tr(e,t))},{once:!0}),r.src=n,r}function wr(e){mr.size>=pr&&mr.clear(),mr.add(e)}function Tr(e,t){let n=document.createElement(`span`);return n.className=`tcw-ss-badge`,n.setAttribute(`aria-hidden`,`true`),n.dataset.kind=String(br(t?.type)),n.textContent=Sr(e),n}var Er=180,Dr=150,Or=50;function kr(e){return{upper:e.toUpperCase(),folded:Nr(e)}}function Ar(e,t,n){return Math.max(jr(e.toUpperCase(),n.upper),Mr(t,n.folded))}function jr(e,t){if(e===t)return 1e3;if(e.startsWith(t))return 500+(50-Math.min(50,e.length-t.length));if(e.includes(t))return 200+(50-Math.min(50,e.length-t.length));let n=0,r=-1,i=0;for(let a=0;a<e.length&&n<t.length;a++)e[a]===t[n]&&(r>=0&&(i+=a-r-1),r=a,n++);return n<t.length?0:100-Math.min(99,i)}function Mr(e,t){if(!e||!t)return 0;if(e.startsWith(t))return Er;let n=e.indexOf(t);return n<0?0:Dr-Math.min(Or,n)}function Nr(e){return e.normalize(`NFD`).replace(/\p{M}+/gu,``).replace(/[đĐ]/g,`D`).toUpperCase()}function Pr(e,t,n=0,r=e.length){let i=t?Fr(e.toUpperCase(),t):new Set,a=``;for(let t=n;t<r;t++)a+=i.has(t)?`<mark>${k(e[t])}</mark>`:k(e[t]);return a}function Fr(e,t){let n=new Set,r=e.indexOf(t);if(r>=0){for(let e=r;e<r+t.length;e++)n.add(e);return n}let i=0;for(let r=0;r<e.length&&i<t.length;r++)e[r]===t[i]&&(n.add(r),i++);return i<t.length?new Set:n}function Ir(e,t){let n=document.createElement(`span`);n.className=`tcw-ss-symbol`,n.dir=`ltr`;let{venue:r}=Qt(e),i=(n,r,i)=>{let a=document.createElement(`span`);return a.className=n,a.innerHTML=Pr(e,t,r,i),a};return r&&n.appendChild(i(`tcw-ss-venue`,0,r.length)),n.appendChild(i(`tcw-ss-ticker`,r.length,e.length)),n}var Lr=yr,Rr=2,zr=1,Br=class{el;kindsEl;exchangeEl;kinds=new Map;exchanges=new Map;kind=null;exchange=null;resize;constructor(e,t){this.t=e,this.onChange=t,this.el=document.createElement(`div`),this.el.className=`tcw-ss-filters`,this.el.hidden=!0,this.kindsEl=document.createElement(`div`),this.kindsEl.className=`tcw-ss-kinds`,this.kindsEl.setAttribute(`role`,`group`),this.kindsEl.setAttribute(`aria-label`,e(`symbolSearch.kinds`)),this.kindsEl.hidden=!0,this.kindsEl.addEventListener(`scroll`,()=>this.markMore(),{passive:!0}),this.resize=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>this.markMore()),this.resize?.observe(this.kindsEl),this.exchangeEl=document.createElement(`select`),this.exchangeEl.className=`tcw-settings-select tcw-ss-exchange-filter`,this.exchangeEl.setAttribute(`aria-label`,e(`symbolSearch.exchange`)),this.exchangeEl.hidden=!0,this.exchangeEl.addEventListener(`change`,()=>{this.exchange=Lr(this.exchangeEl.value)||null,this.onChange(!1)}),this.el.append(this.kindsEl,this.exchangeEl)}see(e){let t=this.kinds.size,n=this.exchanges.size;for(let t of e)Vr(this.kinds,t?.type),Vr(this.exchanges,t?.exchange);this.kinds.size!==t&&this.renderKinds(),this.exchanges.size!==n&&this.renderExchanges(),this.kindsEl.hidden=this.kinds.size===0,this.exchangeEl.hidden=this.exchanges.size<Rr,this.el.hidden=this.kindsEl.hidden&&this.exchangeEl.hidden,this.markMore()}destroy(){this.resize?.disconnect()}markMore(){let e=this.kindsEl,t=Math.abs(e.scrollLeft),n=e.scrollWidth-e.clientWidth,r=[t>zr?`start`:``,t<n-zr?`end`:``].filter(Boolean);r.length>0?e.dataset.more=r.join(` `):delete e.dataset.more}passes(e,t){return Hr(this.kind,Lr(e?.type),t)&&Hr(this.exchange,Lr(e?.exchange),t)}renderKinds(){let e=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-ss-type`,n.textContent=t,e!==null&&(n.dir=`auto`),n.setAttribute(`aria-pressed`,String(this.kind===e)),n.addEventListener(`click`,()=>{this.kind=e;for(let e of this.kindsEl.children)e.setAttribute(`aria-pressed`,String(e===n));this.onChange(!0)}),n},t=[...this.kinds].map(([t,n])=>e(t,n));this.kindsEl.replaceChildren(e(null,this.t(`symbolSearch.allKinds`)),...t)}renderExchanges(){let e=(e,t)=>{let n=document.createElement(`option`);return n.value=e,n.textContent=t,e&&(n.dir=`auto`),n},t=[...this.exchanges.values()].map(t=>e(t,t));this.exchangeEl.replaceChildren(e(``,this.t(`symbolSearch.allExchanges`)),...t),this.exchangeEl.value=this.exchange===null?``:this.exchanges.get(this.exchange)??``}};function Vr(e,t){let n=Lr(t);n&&!e.has(n)&&e.set(n,t.trim())}function Hr(e,t,n){return e===null||t===e||n&&t===``}var Ur=229,Wr=1,Gr=class{backdrop=null;input=null;list=null;results=null;live=null;columns=null;filters=null;mode=null;given=[];rows=[];rowsGiven=!1;shown=[];compared=[];way=``;selectedIndex=0;searchFn=null;searchTimer=null;searchAbort=null;status=`idle`;pickOnResults=!1;heard=new Map;givenInfo=new Map;foldedNames=new Map;returnFocus=null;uid=Wr++;constructor(e,n=()=>document.body,r=t.t){this.callbacks=e,this.host=n,this.t=r}open(e){this.begin({kind:`search`,start:e})}openCompare(e){this.compared=e.compared,this.way=e.ways.some(t=>t.id===e.way)?e.way:e.ways[0]?.id??``,this.begin({kind:`compare`,start:e})}setCompared(e){if(this.compared=e,this.mode?.kind!==`compare`||!this.results)return;let t=this.results.contains(document.activeElement);this.renderList(),t&&!this.results.contains(document.activeElement)&&this.input?.focus()}close(){if(!this.backdrop)return;this.cancelSearch(),this.pickOnResults=!1,this.searchFn=null,this.backdrop.remove(),this.backdrop=this.input=this.list=this.results=this.live=this.columns=null,this.filters?.destroy(),this.filters=null,this.mode=null,this.callbacks.onClose();let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}isOpen(){return this.backdrop!==null}isComparing(){return this.mode?.kind===`compare`}destroy(){this.close()}begin(e){this.backdrop&&this.close(),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.mode=e,this.searchFn=e.start.search??null,this.status=`idle`,this.learnGiven(e),this.build(e);let t=e.kind===`search`?e.start.query??``:``;this.input&&(this.input.value=t),t?(this.filter(),this.searchFn&&this.searchNow()):this.listGiven(),this.input?.focus()}learnGiven(e){let t=Jt(e.start.symbols);this.given=t.names,this.givenInfo=t.info,this.foldedNames=new Map;let n=e.start.current,r=e.kind===`search`?e.start.currentInfo:null;if(r&&typeof r==`object`&&n){let{description:e,logo:t}=Yt(r,n);this.givenInfo.set(n,Zt({symbol:n,description:e,logo:t},this.givenInfo.get(n)))}}infoOf(e){return Zt(this.givenInfo.get(e),this.heard.get(e))}build(e){let t=document.createElement(`div`);t.className=`tcw-modal-backdrop`;let n=!1;t.addEventListener(`pointerdown`,e=>{n=e.target===t}),t.addEventListener(`click`,e=>{e.target===t&&n&&this.close(),n=!1});let r=document.createElement(`div`);r.className=`tcw-modal tcw-ss${e.kind===`compare`?` tcw-ss--compare`:``}`,D(r,e.kind===`compare`?`compare`:`symbolSearch`),r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.setAttribute(`aria-labelledby`,`tcw-ss-title-${this.uid}`),r.tabIndex=-1,r.addEventListener(`keydown`,e=>this.onKeyDown(e,r)),r.append(this.buildHeader(e),this.buildSearch()),e.kind===`compare`&&r.appendChild(this.buildWay(e.start));let i=new Br(this.t,e=>{this.afterResults(!1),e&&this.input?.focus()}),a=document.createElement(`div`);a.className=`tcw-ss-list`,a.id=`tcw-ss-list-${this.uid}`,a.setAttribute(`role`,`listbox`);let o=document.createElement(`div`);o.className=`tcw-ss-results`;let s=this.buildColumns();o.append(s,a),o.addEventListener(`mousedown`,e=>{e.target.closest(`button`)||e.preventDefault()});let c=document.createElement(`div`);c.className=`tcw-ss-live tcw-visually-hidden`,c.setAttribute(`aria-live`,`polite`),r.append(i.el,o,c);let l=e.kind===`search`?e.start.hint:void 0;if(l){let e=document.createElement(`div`);e.className=`tcw-ss-foot`,e.textContent=l,r.appendChild(e)}t.appendChild(r),this.host().appendChild(t),this.backdrop=t,this.filters=i,this.columns=s,this.list=a,this.results=o,this.live=c}buildColumns(){let e=document.createElement(`div`);e.className=`tcw-ss-columns`,e.setAttribute(`aria-hidden`,`true`);let t=[``,this.t(`symbolSearch.symbol`),this.t(`symbolSearch.description`),this.t(`symbolSearch.type`),this.t(`symbolSearch.exchange`)];return e.append(...t.map(e=>this.tag(`tcw-ss-head`,e))),e}buildHeader(e){let t=document.createElement(`div`);t.className=`tcw-modal-header`;let n=document.createElement(`h3`);n.id=`tcw-ss-title-${this.uid}`,n.textContent=this.t(e.kind===`compare`?`compare.title`:`symbolSearch.title`);let r=document.createElement(`button`);return r.type=`button`,r.className=`tcw-modal-close`,r.setAttribute(`aria-label`,this.t(`common.close`)),r.innerHTML=O(`x`,16),r.addEventListener(`click`,()=>this.close()),t.append(n,r),t}buildSearch(){let e=document.createElement(`label`);e.className=`tcw-ss-search`,e.innerHTML=O(`search`,16);let t=document.createElement(`input`);return t.type=`search`,t.className=`tcw-ss-input`,t.placeholder=this.t(`symbolSearch.placeholder`),t.setAttribute(`aria-label`,this.t(`symbolSearch.placeholder`)),t.setAttribute(`role`,`combobox`),t.setAttribute(`aria-expanded`,`true`),t.setAttribute(`aria-controls`,`tcw-ss-list-${this.uid}`),t.setAttribute(`aria-autocomplete`,`list`),t.autocomplete=`off`,t.spellcheck=!1,t.addEventListener(`input`,()=>this.filter()),e.appendChild(t),this.input=t,e}buildWay(e){let t=document.createElement(`label`);t.className=`tcw-ss-way`;let n=document.createElement(`span`);n.textContent=this.t(`compare.addAs`);let r=document.createElement(`select`);r.className=`tcw-settings-select tcw-ss-way-select`;for(let t of e.ways){let e=document.createElement(`option`);e.value=t.id,e.textContent=t.label,r.appendChild(e)}return r.value=this.way,r.addEventListener(`change`,()=>{this.way=r.value}),t.append(n,r),t}listGiven(){this.rows=this.given.map(e=>({symbol:e,score:0,info:this.infoOf(e)})),this.rowsGiven=!0,this.afterResults(!0)}filter(){this.pickOnResults=!1;let e=this.input?.value.trim()??``;if(this.searchFn&&e){this.scheduleSearch(e);return}if(this.cancelSearch(),this.status=`idle`,!e){this.listGiven();return}let t=kr(e);this.rows=this.given.map(e=>{let n=this.infoOf(e);return{symbol:e,score:Ar(e,this.foldedName(n?.description),t),info:n}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score),this.rowsGiven=!0,this.afterResults(!1)}foldedName(e){if(!e)return``;let t=this.foldedNames.get(e);return t===void 0&&(t=Nr(e),this.foldedNames.set(e,t)),t}scheduleSearch(e){this.searchTimer!==null&&clearTimeout(this.searchTimer),this.searchTimer=setTimeout(()=>{this.searchTimer=null,this.runSearch(e)},150)}searchNow(){this.searchTimer!==null&&clearTimeout(this.searchTimer),this.searchTimer=null,this.runSearch(this.input?.value.trim()??``)}async runSearch(e){let t=this.searchFn;if(!t)return;this.searchAbort?.abort();let n=new AbortController;this.searchAbort=n,this.status=`searching`,this.shown.length===0&&this.renderList();try{let r=await t(e,n.signal);if(n.signal.aborted)return;let i=Xt(r);for(let e of i)this.heard.set(e.symbol,Zt(this.heard.get(e.symbol),e));this.rows=i.map(e=>({symbol:e.symbol,score:0,info:this.infoOf(e.symbol)})),this.status=`idle`}catch{if(n.signal.aborted)return;this.rows=[],this.status=`failed`}this.rowsGiven=!1,this.afterResults(!1),this.pickOnResults&&(this.pickOnResults=!1,this.pick(0))}cancelSearch(){this.searchTimer!==null&&clearTimeout(this.searchTimer),this.searchTimer=null,this.searchAbort?.abort(),this.searchAbort=null}afterResults(e){let t=this.listableRows();this.filters?.see(t.map(e=>e.info)),this.shown=this.visibleRows(t);let n=e?this.shown.findIndex(e=>e.symbol===this.mode?.start.current):-1;this.selectedIndex=n>=0&&n<this.listedCount()?n:0,this.renderList()}listedCount(){return Math.min(this.shown.length,200)}listableRows(){if(this.mode?.kind!==`compare`)return this.rows;let e=this.mode.start.current;return this.rows.filter(t=>t.symbol!==e)}visibleRows(e){let t=this.filters;return t?e.filter(e=>t.passes(e.info,this.rowsGiven)):[...e]}renderList(){let e=this.list,t=this.results;if(!e||!t)return;let n=(this.input?.value??``).trim(),r=this.mode?.kind===`compare`,i=[];if(r&&!n&&this.compared.length>0){let t=this.heading(this.t(`compare.onChart`),`added`),n=document.createElement(`div`);n.className=`tcw-ss-added`,n.setAttribute(`role`,`group`),n.setAttribute(`aria-labelledby`,t.id),n.append(...this.compared.map(e=>this.addedRow(e)));let r=this.heading(this.t(`compare.symbols`),`symbols`);r.hidden=this.shown.length===0,i.push(t,n,r),e.setAttribute(`aria-labelledby`,r.id)}else e.setAttribute(`aria-labelledby`,`tcw-ss-title-${this.uid}`);let a=n.toUpperCase(),o=new Set(this.compared.map(e=>e.symbol)),s=this.shown.slice(0,200);e.replaceChildren(...s.map((e,t)=>this.row(e,t,a,r&&o.has(e.symbol))));let c=this.shown.length===0?this.emptyNote(n,r):this.moreNote(this.shown.length-s.length);t.replaceChildren(...this.columns?[this.columns]:[],...i,e,...c?[c]:[]),this.live&&(this.live.textContent=this.shown.length===0?c?.textContent??``:``),this.markSelection()}emptyNote(e,t){let n;if(this.status===`searching`)n=this.t(`symbolSearch.searching`);else if(this.status===`failed`)n=this.t(`symbolSearch.failed`);else if(t&&!e){if(this.compared.length>0)return null;n=this.t(`compare.empty`)}else n=this.t(`symbolSearch.empty`);let r=document.createElement(`div`);return r.className=`tcw-ss-empty`,r.textContent=n,r}moreNote(e){if(e<=0)return null;let n=document.createElement(`div`);return n.className=`tcw-ss-more`,n.textContent=t.r(this.t(`symbolSearch.more`),{count:e}),n}heading(e,t){let n=document.createElement(`div`);return n.className=`tcw-ss-heading`,n.id=`tcw-ss-${t}-${this.uid}`,n.textContent=e,n}row(e,t,n,r){let i=document.createElement(`div`);i.className=`tcw-ss-row`,i.id=`tcw-ss-opt-${this.uid}-${t}`,i.dataset.symbol=e.symbol,i.setAttribute(`role`,`option`);let a=this.mode?.kind===`search`&&e.symbol===this.mode.start.current;i.classList.toggle(`tcw-current`,a),i.classList.toggle(`tcw-on-chart`,r),a&&i.setAttribute(`aria-current`,`true`);let o=this.tag(`tcw-ss-kind`,e.info?.type?.trim()??``),s=this.tag(`tcw-ss-exchange`,e.info?.exchange?.trim()??``);if(o.dir=s.dir=`auto`,i.append(Cr(e.symbol,e.info),Ir(e.symbol,n),this.descriptionCell(e),o,s),a||r){let e=document.createElement(`span`);e.className=`tcw-ss-check`,e.innerHTML=O(`check`,14),i.appendChild(e)}return r&&i.appendChild(this.tag(`tcw-visually-hidden`,this.t(`compare.onChart`))),i.addEventListener(`click`,()=>this.pick(t)),i.addEventListener(`mousemove`,()=>{this.selectedIndex!==t&&(this.selectedIndex=t,this.markSelection())}),i}descriptionCell(e){let t=document.createElement(`span`);t.className=`tcw-ss-desc-cell`;let n=e.info?.description&&e.info.description!==e.symbol?e.info.description:``;if(n){let e=this.tag(`tcw-ss-desc`,n);e.dir=`auto`,t.appendChild(e)}return t}addedRow(e){let n=document.createElement(`div`);if(n.className=`tcw-ss-added-row`,n.setAttribute(`role`,`presentation`),e.color){let t=document.createElement(`span`);t.className=`tcw-ss-swatch`,t.style.background=e.color,n.appendChild(t)}let r=document.createElement(`span`);r.className=`tcw-ss-way-cell`,r.appendChild(this.tag(`tcw-ss-way-label`,e.way));let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-ss-remove`;let a=t.r(this.t(`compare.remove`),{symbol:e.symbol});return i.title=a,i.setAttribute(`aria-label`,a),i.innerHTML=O(`x`,12),i.addEventListener(`click`,()=>{this.mode?.kind===`compare`&&this.mode.start.onRemove(e.id)}),n.append(Ir(e.symbol,``),r,i),n}tag(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}markSelection(){let e=this.list?.querySelectorAll(`.tcw-ss-row`)??[],t=null;e.forEach((e,n)=>{let r=n===this.selectedIndex;e.setAttribute(`aria-selected`,String(r)),e.classList.toggle(`tcw-selected`,r),r&&(t=e)});let n=t;n?(this.input?.setAttribute(`aria-activedescendant`,n.id),n.scrollIntoView?.({block:`nearest`})):this.input?.removeAttribute(`aria-activedescendant`)}pick(e){let t=this.shown[e],n=this.mode;if(!t||!n)return;if(n.kind===`compare`){this.selectedIndex=e,this.markSelection(),n.start.onAdd(t.symbol,this.way);return}let r=n.start.onPick??this.callbacks.onPick;this.close(),r(t.symbol)}onKeyDown(e,t){if(e.stopPropagation(),e.isComposing||e.keyCode===Ur)return;if(e.key===`Escape`){e.preventDefault(),this.close();return}if(M(e,t),e.target!==this.input)return;let n=this.listedCount();if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),n===0)return;this.selectedIndex=(this.selectedIndex+(e.key===`ArrowDown`?1:-1)+n)%n,this.markSelection()}else if(e.key===`Enter`){if(e.preventDefault(),e.repeat&&this.mode?.kind===`compare`)return;if(this.searchTimer!==null||this.status===`searching`){this.pickOnResults=!0,this.searchTimer!==null&&this.searchNow();return}this.pick(this.selectedIndex)}}},Kr=229,qr={"Search & navigation":`hotkeys.group.searchNavigation`,"Chart manipulation":`hotkeys.group.chartManipulation`,"Touch (mobile / tablet)":`hotkeys.group.touch`,Keyboard:`hotkeys.group.keyboard`,"Bar replay":`toolbar.replay`,Drawing:`hotkeys.group.drawing`,More:`hotkeys.group.more`},H=nr,Jr=[{title:`Search & navigation`,entries:[{keys:[H,`K`],label:`hotkeys.commandPalette`,feature:`hotkeys.commandPalette`},{keys:[H,`P`],label:`hotkeys.symbolSearch`,feature:`hotkeys.symbolSearch`},{keys:[`Alt`,`G`],label:`hotkeys.goToDate`,feature:`hotkeys.goToDate`},{keys:[`Alt`,`I`],label:`hotkeys.invertScale`,feature:`hotkeys.invertScale`},{keys:[`Alt`,`R`],label:`chartMenu.resetView`,feature:`hotkeys.resetView`},{keys:[H,`S`],label:`hotkeys.saveLayout`,feature:`hotkeys.save`},{keys:[`0–9`],label:`hotkeys.typeInterval`,feature:`intervalTyping`},{keys:[`A–Z`],label:`hotkeys.typeSymbol`,feature:`symbolTyping`},{keys:[`?`],label:`hotkeys.showSheet`,feature:`hotkeys.help`}]},{title:`Chart manipulation`,entries:[{keys:[`key.drag`],label:`hotkeys.pan`},{keys:[H,`key.drag`],label:`hotkeys.boxSelect`},{keys:[H,`key.click`],label:`hotkeys.toggleSelect`},{keys:[`Shift`,`key.drag`],label:`hotkeys.measure`},{keys:[`key.drag`,`key.priceAxis`],label:`hotkeys.scalePrice`},{keys:[`key.drag`,`key.timeAxis`],label:`hotkeys.zoomTime`},{keys:[`key.doubleClick`,`key.priceAxis`],label:`hotkeys.autoScale`},{keys:[`key.doubleClick`,`key.timeAxis`],label:`hotkeys.fit`},{keys:[`key.scroll`],label:`hotkeys.zoomCursor`}]},{title:`Touch (mobile / tablet)`,entries:[{keys:[`key.oneFinger`,`key.drag`],label:`hotkeys.touchPan`},{keys:[`key.twoFingers`,`key.pinch`],label:`hotkeys.pinch`},{keys:[`key.longPress`],label:`hotkeys.longPress`},{keys:[`key.drag`,`key.axisStrip`],label:`hotkeys.touchAxis`}]},{title:`Keyboard`,entries:[{keys:[`←`,`→`],label:`hotkeys.panBar`},{keys:[`+`,`−`],label:`hotkeys.zoomInOut`},{keys:[`Home`],label:`hotkeys.toStart`},{keys:[`End`],label:`hotkeys.toEnd`},{keys:[`Space`],label:`hotkeys.fit`}]},{title:`Bar replay`,entries:[{keys:[`Shift`,`←`,`→`],label:`hotkeys.replayStep`,feature:`replay`},{keys:[`Space`],label:`hotkeys.replayPlay`,feature:`replay`},{keys:[`Esc`],label:`hotkeys.replayCancel`,feature:`replay`}]},{title:`Drawing`,entries:[{keys:[H,`Z`],label:`hotkeys.undo`},{keys:[H,`Shift`,`Z`],label:`hotkeys.redo`},{keys:[`Esc`],label:`hotkeys.cancelDrawing`},{keys:[H,`C`],label:`hotkeys.copy`},{keys:[H,`V`],label:`hotkeys.paste`},{keys:[`key.rightClick`],label:`hotkeys.drawingMenu`},{keys:[`key.doubleClick`],label:`hotkeys.drawingSettings`},{keys:[H,`G`],label:`hotkeys.group`},{keys:[H,`Shift`,`G`],label:`hotkeys.ungroup`},{keys:[H,`]`,`[`],label:`hotkeys.orderStep`},{keys:[H,`Shift`,`]`,`[`],label:`hotkeys.orderEnd`},{keys:[`Enter`],label:`hotkeys.finishPath`},{keys:[H,`key.drag`],label:`hotkeys.copyDrag`},{keys:[`Shift`],label:`hotkeys.keepAngle`},{keys:[H],label:`hotkeys.flipMagnet`},{keys:[`←`,`→`,`↑`,`↓`],label:`hotkeys.nudge`},{keys:[`Alt`,`T`],label:`tool.trendLine`,feature:`hotkeys.tools`},{keys:[`Alt`,`H`],label:`tool.horizontalLine`,feature:`hotkeys.tools`},{keys:[`Alt`,`J`],label:`tool.horizontalRay`,feature:`hotkeys.tools`},{keys:[`Alt`,`V`],label:`tool.verticalLine`,feature:`hotkeys.tools`},{keys:[`Alt`,`C`],label:`tool.crossLine`,feature:`hotkeys.tools`},{keys:[`Alt`,`F`],label:`tool.fibRetracement`,feature:`hotkeys.tools`}]}],Yr=0,Xr=class{backdrop=null;bodyEl=null;searchEl=null;liveEl=null;groups=[];returnFocus=null;uid=++Yr;constructor(e,t,n=()=>document.body){this.callbacks=e,this.t=t,this.host=n}open(e={}){if(this.backdrop)return;this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=e.isOn??(()=>!0),n=new Set((e.extra??[]).map(e=>e.keys.join(`+`).toLowerCase()));this.groups=Jr.map(e=>({title:e.title,entries:e.entries.filter(e=>(!e.feature||t(e.feature))&&!n.has(e.keys.join(`+`).toLowerCase()))})).filter(e=>e.entries.length>0),e.extra&&e.extra.length>0&&this.groups.push({title:`More`,entries:[...e.extra]}),this.build(t(`hotkeys.help`)),this.render(),this.searchEl?.focus()}close(){if(!this.backdrop)return;this.backdrop.remove(),this.backdrop=this.bodyEl=this.searchEl=this.liveEl=null,this.callbacks.onClose();let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}isOpen(){return this.backdrop!==null}destroy(){this.close()}build(e){let t=document.createElement(`div`);t.className=`tcw-modal-backdrop`;let n=!1;t.addEventListener(`pointerdown`,e=>{n=e.target===t}),t.addEventListener(`click`,e=>{e.target===t&&n&&this.close(),n=!1});let r=document.createElement(`div`);r.className=`tcw-modal tcw-hotkey-sheet`,r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.setAttribute(`aria-labelledby`,`tcw-hotkey-title-${this.uid}`),r.tabIndex=-1,r.addEventListener(`keydown`,e=>{if(e.stopPropagation(),e.key===`Escape`&&!e.isComposing&&e.keyCode!==Kr){e.preventDefault(),this.close();return}M(e,r)});let i=document.createElement(`div`);i.className=`tcw-modal-header`;let a=document.createElement(`h3`);a.id=`tcw-hotkey-title-${this.uid}`,a.textContent=this.t(`hotkeys.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`hotkeys.close`)),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.close()),i.append(a,o);let s=document.createElement(`label`);s.className=`tcw-ss-search tcw-hotkey-search`,s.innerHTML=O(`search`,16);let c=document.createElement(`input`);c.type=`search`,c.placeholder=this.t(`hotkeys.search`),c.setAttribute(`aria-label`,this.t(`hotkeys.search`)),c.autocomplete=`off`,c.spellcheck=!1,c.addEventListener(`input`,()=>this.render()),s.appendChild(c);let l=document.createElement(`div`);l.className=`tcw-hotkey-body`;let u=document.createElement(`div`);if(u.className=`tcw-hotkey-live tcw-visually-hidden`,u.setAttribute(`aria-live`,`polite`),r.append(i,s,l,u),e){let e=document.createElement(`div`);e.className=`tcw-hotkey-foot`,e.textContent=this.t(`hotkeys.footer`),r.appendChild(e)}t.appendChild(r),this.host().appendChild(t),this.backdrop=t,this.bodyEl=l,this.searchEl=c,this.liveEl=u}render(){let e=this.bodyEl;if(!e)return;let t=rr((this.searchEl?.value??``).trim()),n=[];for(let e of this.groups){let r=t?e.entries.filter(e=>this.matches(e,t)):e.entries;if(r.length===0)continue;let i=document.createElement(`section`);i.className=`tcw-hotkey-group`;let a=document.createElement(`div`);a.className=`tcw-hotkey-heading`;let o=qr[e.title];a.textContent=o?this.t(o):e.title,i.append(a,...r.map(e=>this.row(e))),n.push(i)}if(this.liveEl&&(this.liveEl.textContent=n.length===0?this.t(`hotkeys.noMatch`):``),n.length===0){let t=document.createElement(`div`);t.className=`tcw-hotkey-empty`,t.textContent=this.t(`hotkeys.noMatch`),e.replaceChildren(t);return}let r=document.createElement(`div`);r.className=`tcw-hotkey-columns`,r.append(...n),e.replaceChildren(r)}label(e){return`text`in e?e.text:this.t(e.label)}keyText(e){return e.startsWith(`key.`)?this.t(e):e}matches(e,t){return rr(this.label(e)).includes(t)?!0:rr(e.keys.map(e=>this.keyText(e)).join(`+`)).includes(t)}row(e){let t=document.createElement(`div`);t.className=`tcw-hotkey-row`;let n=document.createElement(`span`);n.className=`tcw-hotkey-label`,n.textContent=this.label(e);let r=document.createElement(`span`);return r.className=`tcw-hotkey-keys`,r.dir=`ltr`,e.keys.forEach((e,t)=>{if(t>0){let e=document.createElement(`span`);e.className=`tcw-hotkey-sep`,e.textContent=`+`,r.appendChild(e)}let n=e.startsWith(`key.`),i=document.createElement(n?`span`:`kbd`);i.className=n?`tcw-hotkey-gesture`:`tcw-hotkey-key`,i.textContent=this.keyText(e),r.appendChild(i)}),t.append(n,r),t}},Zr={selectHint:`Click a bar to start the replay`,random:`Random bar`,realtime:`Back to realtime`,play:`Play`,pause:`Pause`,stepBack:`Step back (Shift+←)`,stepForward:`Step forward (Shift+→)`,replay:`Replay`,position:`Replay position`,speed:`Speed`,step:`Step`,loading:`Loading chart...`,selectBar:`Select bar`,cancel:`Cancel`,rate:`{rate}×`,rateHint:`1× plays one bar a second`,playingAt:`Playing at {rate}`,pausedAt:`Paused at {time}`,endedAt:`Replay ended at {time}`},Qr=[.1,.2,.3,.5,1,2,3,5,10,20,30,50],$r=[`full`,`compact`,`stack`],ei=300,ti=2,ni=[`random`,`stepBack`,`stepForward`,`seek`,`step`,`selectBar`],ri=class{root=null;scrubber=null;timeLabel=null;playBtn=null;realtimeBtn=null;liveRegion=null;hintText=null;state=`stopped`;mode=`select`;ended=!1;pending=!1;total=0;rate=1;steps=[];step=`bar`;dir=`ltr`;formatRate;where=``;announceTimer=null;widths=new Map;labels;constructor(e,t={}){this.callbacks=e,this.labels={...Zr,...t},this.formatRate=e=>this.labels.rate.replace(`{rate}`,String(e))}mount(e,t){this.root||(this.total=Math.max(0,t.total),this.rate=t.rate??1,this.steps=t.steps??[],this.step=t.step??`bar`,this.dir=t.dir??`ltr`,t.formatRate&&(this.formatRate=t.formatRate),this.state=`paused`,this.mode=t.mode??`select`,this.root=document.createElement(`div`),this.root.className=`tcw-replay-bar`,D(this.root,`replay`),this.root.setAttribute(`role`,`group`),this.root.setAttribute(`aria-label`,this.labels.replay),this.root.dataset.fit=`full`,this.root.innerHTML=this.markup(),e.appendChild(this.root),this.wireEvents(),this.syncUi())}unmount(){this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=null,this.root?.remove(),this.root=null,this.hintText=null,this.scrubber=null,this.timeLabel=null,this.playBtn=null,this.realtimeBtn=null,this.liveRegion=null,this.state=`stopped`,this.ended=!1,this.where=``}isMounted(){return this.root!==null}element(){return this.root}getMode(){return this.mode}setMode(e){let t=!!this.root?.contains(document.activeElement);this.mode=e,this.syncUi(),t&&(e===`replay`?(this.playBtn&&!this.playBtn.disabled?this.playBtn:this.realtimeBtn)?.focus():this.root?.querySelector(`[data-act="random"]`)?.focus())}setState(e){e!==this.state&&(this.state=e,this.syncUi(),this.mode===`replay`&&(e===`playing`?this.announce(this.labels.playingAt.replace(`{rate}`,this.formatRate(this.rate))):e===`paused`&&this.where&&this.announce(this.labels.pausedAt.replace(`{time}`,this.where))))}setEnded(e){this.ended!==e&&(this.ended=e,this.syncUi(),e&&this.where&&this.announce(this.labels.endedAt.replace(`{time}`,this.where)))}setPending(e){if(this.pending===e)return;this.pending=e;let t=document.activeElement;e&&t&&t!==this.playBtn&&this.root?.contains(t)&&ni.includes(t.dataset.act??``)&&this.playBtn?.focus(),this.syncUi(),e&&this.mode===`replay`&&this.announce(this.labels.loading)}isPending(){return this.pending}setSteps(e,t){this.steps=e,this.step=t,this.widths.clear();let n=this.root?.querySelector(`[data-tcw="stepSlot"]`);n&&(n.innerHTML=this.stepMarkup(),this.wireStep(),this.syncUi())}setProgress(e,t,n){this.total=t;let r=n??`${Math.min(e+1,t)} / ${t}`,i=r!==this.where;if(this.where=r,this.scrubber){this.scrubber.max=String(Math.max(0,t-1)),this.scrubber.value=String(e),this.scrubber.setAttribute(`aria-valuetext`,r);let n=t>1?Math.min(e,t-1)/(t-1)*100:0;this.scrubber.style.setProperty(`--tcw-replay-done`,`${Number(n.toFixed(ti))}%`)}if(this.timeLabel){this.timeLabel.textContent=r;let e=Number.parseFloat(this.timeLabel.style.minInlineSize)||0;r.length>e&&(this.timeLabel.style.minInlineSize=`${r.length}ch`)}let a=this.scrubber!==null&&document.activeElement===this.scrubber;i&&this.mode===`replay`&&this.state!==`playing`&&!a&&this.announce(r)}setRoom(e){let t=this.root;if(t){for(let n of $r)if(n===`stack`||this.widthIn(n)<=e){t.dataset.fit=n,this.orderFor(n);return}}}orderFor(e){let t=this.root,n=t?.querySelector(`.tcw-replay-timeline`),r=t?.querySelector(`.tcw-replay-transport`),i=this.realtimeBtn;if(!t||!n||!r||!i)return;let a=e===`stack`;if(a===(n.nextElementSibling===i))return;let o=document.activeElement;a?r.before(n,i):(r.nextElementSibling?.after(n),t.querySelector(`[data-act="cancel"]`)?.before(i)),o&&t.contains(o)&&document.activeElement!==o&&o.focus()}getFit(){return this.root?.dataset.fit??`full`}destroy(){this.unmount()}widthIn(e){let t=this.root,n=`${this.mode}|${this.steps.length}|${e}`,r=this.widths.get(n);if(r!==void 0)return r;let i=t.dataset.fit;t.dataset.fit=e,t.dataset.measure=``;let a=t.getBoundingClientRect().width;return delete t.dataset.measure,i&&(t.dataset.fit=i),a>0&&this.widths.set(n,a),a}markup(){let e=this.labels,t=`dir="${this.dir}"`,n=Qr.map(e=>`<option value="${e}"${e===this.rate?` selected`:``}>${k(this.formatRate(e))}</option>`).join(``),r=(e,t,n,r=`tcw-replay-btn`,i=``)=>`<button type="button" class="${r}" data-act="${e}" title="${k(t)}" aria-label="${k(t)}"${i}>${n}</button>`;return`
|
|
7702
|
+
${Ge()}`,document.head.insertBefore(e,document.head.firstChild)}function $e(){if(Xe--,Xe>0)return;let e=document.getElementById(Ze);e&&e.remove()}var et=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function O(e,t=14){let r=et(n.UI_ICONS,e);return r?(0,n.iconSvg)(r,t):``}function tt(e,t=16){return(0,n.iconSvg)(et(n.DRAWING_TOOL_ICONS,e)??n.UI_ICONS.penLine,t)}function nt(e,t=14){return(0,n.iconSvg)(et(n.CHART_TYPE_ICONS,e)??n.UI_ICONS.barChart,t)}function k(e){return e.replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e])}var rt=class{trigger;panel;_isOpen=!1;onOutsideClick;onEscapeKey;onTriggerClick;layer;align;onAway=()=>this.close();onScroll=e=>{e.target instanceof Node&&this.panel.contains(e.target)||this.close()};constructor(e,t={}){this.trigger=e,this.layer=t.layer??null,this.align=t.align??`left`,this.panel=document.createElement(`div`),this.panel.className=`tcw-dropdown`,this.panel.style.minWidth=t.width??`200px`,this.panel.style.display=`none`,this.layer?(this.layer().appendChild(this.panel),this.panel.addEventListener(`click`,()=>this.close())):(this.align===`right`?this.panel.style.insetInlineEnd=`0px`:this.panel.style.insetInlineStart=`0px`,e.style.position=`relative`,e.appendChild(this.panel)),this.onTriggerClick=()=>{this._isOpen?this.close():this.open()},this.onOutsideClick=e=>{let t=e.target;!this.trigger.contains(t)&&!this.panel.contains(t)&&this.close()},this.onEscapeKey=e=>{e.key===`Escape`&&this.close()},e.addEventListener(`click`,this.onTriggerClick)}setContent(e){this.panel.innerHTML=e}open(){if(!this._isOpen){if(this._isOpen=!0,this.layer){let e=this.layer();this.panel.parentElement!==e&&e.appendChild(this.panel)}this.panel.style.display=``,this.layer&&(this.place(),window.addEventListener(`resize`,this.onAway),document.addEventListener(`scroll`,this.onScroll,{capture:!0,passive:!0})),document.addEventListener(`pointerdown`,this.onOutsideClick),document.addEventListener(`keydown`,this.onEscapeKey)}}close(){this._isOpen&&(this._isOpen=!1,this.panel.style.display=`none`,document.removeEventListener(`pointerdown`,this.onOutsideClick),document.removeEventListener(`keydown`,this.onEscapeKey),window.removeEventListener(`resize`,this.onAway),document.removeEventListener(`scroll`,this.onScroll,{capture:!0}))}isOpen(){return this._isOpen}destroy(){this.close(),this.trigger.removeEventListener(`click`,this.onTriggerClick),this.panel.remove()}place(){g(this.panel,this.trigger,this.align)}},it=4,at=2,ot=150,st=`[role=menuitem], [role=menuitemcheckbox], [role=menuitemradio]`,ct=`(max-width: 640px)`,lt=`tcw:back`,ut=new Set;function dt(e,t,n,r=e,i=!1){let a=i?r-t>=0?r-t:e:e+t>n?r-t:e;return Math.max(0,Math.min(a,n-t))}function ft(e){return e.radio?`menuitemradio`:e.checked===void 0?`menuitem`:`menuitemcheckbox`}function pt(e){let t=`<span class="tcw-context-icon"></span>`;return e.radio?e.checked?`<span class="tcw-context-icon tcw-context-dot"></span>`:t:e.checked?O(`check`,14):e.icon&&O(e.icon,14)||t}var A=class e{el;onPick=null;onRemove=null;returnFocus=null;anchor=null;child=null;parent=null;hoverTimer=null;hoverItem=null;onDocPointer=e=>{let t=e.target;this.holds(t)||this.anchor?.contains(t)||this.close()};onWheel=e=>{this.holds(e.target)||this.close()};onAway=()=>this.close();constructor(e,t,n=``){this.host=e,this.backLabel=n,this.el=document.createElement(`div`),this.el.className=`tcw-context-menu`,this.el.setAttribute(`role`,`menu`),this.el.setAttribute(`aria-label`,t),this.el.hidden=!0,this.el.addEventListener(`keydown`,e=>this.onKeyDown(e)),e.appendChild(this.el)}open(e,t,n,r,i,a,o=t,s=!1){this.show(e,{x:t,y:n,xBack:o,yBack:n,before:s},r,i,a,!0)}openUnder(e,t,n,r=`start`,i=at){let a=t.getBoundingClientRect(),o=this.host.getBoundingClientRect(),s=r===`end`!==this.rtl();this.open(e,a.left-o.left,a.bottom-o.top+i,n,t,void 0,a.right-o.left,s)}openBeside(e,t,n){let r=t.getBoundingClientRect(),i=this.host.getBoundingClientRect(),a=r.right-i.left+at,o=r.left-i.left-at;this.show(e,{x:a,y:r.top-i.top,xBack:o,yBack:r.bottom-i.top,before:this.rtl()},n,t,void 0,!0),this.returnFocus=t}static closeAnchoredTo(e){let t=[...ut].filter(t=>t.anchor===e);for(let e of t)e.close();return t.length>0}static focusedAnchor(){return[...ut].find(e=>e.anchor!==null&&e.hasFocus())?.anchor??null}close(){if(this.clearHover(),this.child?.close(),this.el.hidden)return;ut.delete(this);let e=!this.parent||this.el.contains(document.activeElement);this.el.hidden=!0,this.onPick=null,this.onRemove=null,this.anchor?.setAttribute(`aria-expanded`,`false`),this.anchor=null,document.removeEventListener(`pointerdown`,this.onDocPointer,!0),document.removeEventListener(`wheel`,this.onWheel,{capture:!0}),window.removeEventListener(`resize`,this.onAway),window.removeEventListener(`blur`,this.onAway),e&&this.returnFocus?.isConnected&&this.returnFocus.focus({preventScroll:!0}),this.returnFocus=null}isOpen(){return!this.el.hidden}hasFocus(){return document.activeElement!==null&&this.holds(document.activeElement)}destroy(){this.close(),this.child?.destroy(),this.el.remove()}show(e,t,n,r,i,a){this.clearHover(),this.child?.close(),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.onPick=n,this.onRemove=i??null,this.anchor=r??null,this.anchor?.setAttribute(`aria-expanded`,`true`),this.el.replaceChildren(...e.map(e=>this.entry(e))),this.el.hidden=!1,ut.add(this);let o=this.host.getBoundingClientRect(),s=Math.min(this.host.clientWidth,window.innerWidth-o.left)-it,c=Math.min(this.host.clientHeight,window.innerHeight-o.top)-it;this.el.style.maxHeight=`${Math.max(0,c-this.frameHeight())}px`,this.el.style.left=`${dt(t.x,this.el.offsetWidth,s,t.xBack,t.before)}px`,this.el.style.top=`${dt(t.y,this.el.offsetHeight,c,t.yBack)}px`,document.addEventListener(`pointerdown`,this.onDocPointer,!0),document.addEventListener(`wheel`,this.onWheel,{capture:!0,passive:!0}),window.addEventListener(`resize`,this.onAway),window.addEventListener(`blur`,this.onAway);let l=this.revealChoice();a&&(l??this.items()[0])?.focus({preventScroll:!0})}frameHeight(){let e=getComputedStyle(this.el);if(e.boxSizing===`border-box`)return 0;let t=e=>parseFloat(e)||0;return t(e.paddingTop)+t(e.paddingBottom)+t(e.borderTopWidth)+t(e.borderBottomWidth)}revealChoice(){let e=this.el.querySelector(`[role=menuitemradio][aria-checked=true]`);return!e||e.offsetTop+e.offsetHeight<=this.el.clientHeight?null:(this.el.scrollTop=e.offsetTop-(this.el.clientHeight-e.offsetHeight)/2,e)}rtl(){return this.host.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`}holds(e){return this.el.contains(e)||(this.child?.holds(e)??!1)}entry(e){if(e===`separator`){let e=document.createElement(`div`);return e.className=`tcw-context-sep`,e.setAttribute(`role`,`separator`),e}let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-context-item${e.danger?` tcw-context-danger`:``}`,t.setAttribute(`role`,ft(e)),(e.radio||e.checked!==void 0)&&t.setAttribute(`aria-checked`,String(e.checked??!1)),t.tabIndex=-1,t.dataset.id=e.id,t.innerHTML=pt(e);let n=document.createElement(`span`);n.className=`tcw-context-label`,n.textContent=e.label,t.appendChild(n),this.appendEnd(t,e);let r=e.submenu;return t.addEventListener(`pointermove`,n=>{n.pointerType!==`touch`&&this.hover(t,e.label,r)}),t.addEventListener(`click`,()=>{r?this.openSubmenu(t,e.label,r,!0):this.pick(e.id)}),e.remove?this.removableRow(t,e.remove):t}appendEnd(e,t){if(t.count!==void 0){let n=document.createElement(`span`);n.className=`tcw-context-count`,n.textContent=String(t.count),e.appendChild(n)}if(t.shortcut){e.setAttribute(`aria-keyshortcuts`,t.shortcut);let n=document.createElement(`kbd`);n.className=`tcw-context-key`,n.setAttribute(`aria-hidden`,`true`),n.textContent=t.shortcut,e.appendChild(n)}t.submenu&&(e.setAttribute(`aria-haspopup`,`menu`),e.setAttribute(`aria-expanded`,`false`),e.insertAdjacentHTML(`beforeend`,O(`chevronRight`,12)),e.lastElementChild?.classList.add(`tcw-context-more`))}removableRow(e,t){e.setAttribute(`aria-keyshortcuts`,`Delete`);let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-context-remove`,n.tabIndex=-1,n.setAttribute(`aria-hidden`,`true`),n.title=t,n.innerHTML=O(`x`,12),n.addEventListener(`click`,()=>this.remove(e));let r=document.createElement(`div`);return r.className=`tcw-context-row`,r.setAttribute(`role`,`none`),r.append(e,n),r}openSubmenu(e,t,n,r){this.clearHover();let i=this.child??this.makeChild();if(i.isOpen()&&i.anchor===e){r&&i.items()[0]?.focus({preventScroll:!0});return}i.close(),i.el.setAttribute(`aria-label`,t);let a=this.host.getBoundingClientRect(),o=e.getBoundingClientRect(),s={x:o.right-a.left,y:o.top-a.top,xBack:o.left-a.left,yBack:o.bottom-a.top,before:this.rtl()},c=window.matchMedia?.(ct).matches??!1,l=c?[{id:lt,label:t,icon:`chevronLeft`},`separator`,...n]:n;i.show(l,s,e=>{e!==lt&&this.pick(e)},e,e=>this.onRemove?.(e),r);let u=c?i.el.querySelector(`[data-id="${lt}"]`):null;u?.classList.add(`tcw-context-back`),u&&this.backLabel&&u.setAttribute(`aria-label`,`${this.backLabel}: ${t}`),i.returnFocus=e}makeChild(){let t=new e(this.host,``,this.backLabel);return t.parent=this,t.el.addEventListener(`pointerenter`,()=>this.clearHover()),this.child=t,t}hover(e,t,n){if(this.hoverTimer!==null&&this.hoverItem===e)return;this.clearHover();let r=this.child?.isOpen()?this.child.anchor:null;(n?r===e:r===null)||(this.hoverItem=e,this.hoverTimer=setTimeout(()=>{this.hoverTimer=null,this.hoverItem=null,n?this.openSubmenu(e,t,n,!1):this.child?.close()},ot))}clearHover(){this.hoverItem=null,this.hoverTimer!==null&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}remove(e){let t=e.dataset.id,n=e.closest(`.tcw-context-row`);if(!t||!n)return;let r=this.items().indexOf(e);this.onRemove?.(t),n.remove();let i=[...this.el.children].filter((e,t,n)=>e.classList.contains(`tcw-context-sep`)&&(t===0||t===n.length-1||n[t-1].classList.contains(`tcw-context-sep`)));for(let e of i)e.remove();let a=this.items();if(a.length===0){this.close();return}a[Math.min(r,a.length-1)].focus({preventScroll:!0})}pick(e){let t=this.onPick;this.close(),t?.(e)}items(){return[...this.el.querySelectorAll(st)]}onKeyDown(e){let t=this.items(),n=t.indexOf(document.activeElement),[r,i]=this.rtl()?[`ArrowLeft`,`ArrowRight`]:[`ArrowRight`,`ArrowLeft`],a=-1;if(e.key===`ArrowDown`)a=(n+1)%t.length;else if(e.key===`ArrowUp`)a=(n-1+t.length)%t.length;else if(e.key===`Home`)a=0;else if(e.key===`End`)a=t.length-1;else if(e.key===r&&t[n]?.hasAttribute(`aria-haspopup`)){e.preventDefault(),t[n].click();return}else if(e.key===i&&this.parent){e.preventDefault(),this.close();return}else if(e.key===`Delete`&&n>=0){e.preventDefault(),this.remove(t[n]);return}else if(e.key===`Escape`||e.key===`Tab`){e.preventDefault(),e.stopPropagation();let t=this;for(;e.key===`Tab`&&t.parent;)t=t.parent;t.close();return}else return;e.preventDefault(),this.child?.close(),t[a]?.focus({preventScroll:!0})}},mt=[`en-US`,`en-GB`,`en-IN`,`de-DE`,`fr-FR`,`es-ES`,`it-IT`,`pt-BR`,`ru-RU`,`tr-TR`,`vi-VN`,`id-ID`,`th-TH`,`zh-CN`,`zh-TW`,`ja-JP`,`ko-KR`],ht=65234;function gt(e){return(e&&!mt.includes(e)?[e,...mt]:mt).map(e=>{let t;try{t=new Intl.NumberFormat(e,{minimumFractionDigits:2,maximumFractionDigits:2}).format(ht)}catch{t=``}return{value:e,label:t?`${e} (${t})`:e}})}var _t={Lines:`toolGroup.lines`,"Horizontal/Vertical":`toolGroup.horizontalVertical`,Channels:`toolGroup.channels`,Fibonacci:`toolGroup.fibonacci`,Shapes:`toolGroup.shapes`,"Gann & Pitchforks":`toolGroup.gannPitchforks`,Patterns:`toolGroup.patterns`,Measure:`toolGroup.measure`,Annotation:`toolGroup.annotation`,Forecasting:`toolGroup.forecasting`,Brushes:`toolGroup.brushes`,Cycles:`toolGroup.cycles`,"Elliott Waves":`toolGroup.elliott`};function vt(e,t){let n=`chartType.${e.value}`,r=t(n);return r===n?e.label:r}function yt(e,t){return e.map(e=>({...e,label:_t[e.label]?t(_t[e.label]):e.label,tools:e.tools.map(e=>{let n=`tool.${e.value}`,r=t(n);return{...e,label:r===n?e.label:r}})}))}var bt=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`,`1w`,`1M`],xt=[`1m`,`5m`,`15m`,`1h`,`4h`,`1d`],St=6;function Ct(e){let t=e.slice(-1);return t===`h`||t===`d`||t===`w`?e.slice(0,-1)+t.toUpperCase():e}var wt=e=>Number.isFinite((0,n.timeframeToMs)(e))||(0,n.tickBarCount)(e)!==null,Tt=(e,t)=>{let r=(0,n.tickBarCount)(e),i=(0,n.tickBarCount)(t);return r!==null||i!==null?r===null?1:i===null?-1:r-i:(0,n.timeframeToMs)(e)-(0,n.timeframeToMs)(t)};function Et(e,t){let n=t?.length?t:null,r=e?.length?e:n??bt;return[...new Set(r)].filter(e=>wt(e)&&(!n||n.includes(e))).sort(Tt)}function Dt(e,t,n=!1){if(t?.length)return e.filter(e=>t.includes(e));if(n)return[...e];let r=e.filter(e=>xt.includes(e));return r.length>0?r:e.slice(0,St)}var Ot=9999,kt={"":`m`,s:`s`,S:`s`,m:`m`,h:`h`,H:`h`,d:`d`,D:`d`,w:`w`,W:`w`,M:`M`},At={s:[`m`,60],m:[`h`,60],h:[`d`,24]};function jt(e){let t=/^(\d+)([a-zA-Z]?)$/.exec(e.trim());if(!t)return null;if(t[2]===`T`||t[2]===`t`){let e=`${Number(t[1])}T`;return Number(t[1])<=Ot&&(0,n.tickBarCount)(e)!==null?e:null}let r=Number(t[1]),i=kt[t[2]];if(!i||!Number.isSafeInteger(r)||r<1)return null;for(let e=At[i];e&&r%e[1]===0;e=At[i])r/=e[1],i=e[0];if(r>Ot)return null;let a=`${r}${i}`;return(0,n.isTimeFrame)(a)?a:null}function Mt(e,t,n){let r=n?.length?n:null,i=t.filter(e=>wt(e)&&(!r||r.includes(e)));return[...new Set([...e,...i])].sort(Tt)}var Nt=[`T`,`s`,`m`,`h`,`d`,`w`,`M`];function Pt(e){let t=e=>{let t=e.slice(-1);return Nt.includes(t)?t:`m`};return Nt.map(n=>({unit:n,timeframes:e.filter(e=>t(e.value)===n)})).filter(e=>e.timeframes.length>0)}var Ft=864e5,It=5/7;function Lt(e){let t=(0,n.timeframeToMs)(e.current),r=(0,n.timeframeToMs)(e.chosen);if(!Number.isFinite(t)||!Number.isFinite(r)||!(e.width>0)||!(e.spanMs>0))return e.current;let i=n=>{if(n===t)return e.barsInSpan;if(n<Ft)return e.barsInSpan*t/n;let r=e.spanMs/n;return n===Ft?r*(e.dayShare??It):r},a=[...new Set([...e.available,e.current])].filter(e=>{let t=(0,n.timeframeToMs)(e);return Number.isFinite(t)&&t>=r}).sort(Tt);for(let t of a)if(i((0,n.timeframeToMs)(t))*2<=e.width)return t;return a[a.length-1]??e.current}var Rt={ticket:`receipt`,long:`trendingUp`,short:`trendingDown`,ladder:`ladder`,account:`layers`},zt=[`ladder`,`account`];function Bt(e,t){let n=[];e.onOrderTicket&&n.push({id:`ticket`,label:t(`chartMenu.orderTicket`),parts:[`orderTicket`],run:e.onOrderTicket});let r=e.onBracket;return r&&(n.push({id:`long`,label:t(`toolbar.longBracket`),parts:[`bracketOrders`,`toolbar.bracketOrders`],run:()=>r(`buy`)}),n.push({id:`short`,label:t(`toolbar.shortBracket`),parts:[`bracketOrders`,`toolbar.bracketOrders`],run:()=>r(`sell`)})),e.onToggleLadder&&n.push({id:`ladder`,label:t(`toolbar.depthLadder`),parts:[`depthLadder`,`toolbar.depthLadder`],run:e.onToggleLadder}),e.onToggleAccount&&n.push({id:`account`,label:t(`toolbar.account`),parts:[`accountPanel`,`toolbar.accountPanel`],run:e.onToggleAccount}),n}var Vt=class e{button;menu=null;open=new Set;static create(t,n,r,i){let a=Bt(t,n);return a.length>0?new e(a,n,r,i):null}constructor(e,t,n,r){this.items=e,this.t=t,this.root=n;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-dropdown-trigger tcw-toolbar-overflow`,i.dataset.role=`trade`,i.dataset.icon=`trendingUp`,i.title=t(`toolbar.trade`),i.setAttribute(`aria-haspopup`,`menu`),i.setAttribute(`aria-expanded`,`false`),D(i,`toolbar.trade`),i.innerHTML=`${O(`trendingUp`,14)} <span class="tcw-trigger-label">${k(t(`toolbar.trade`))}</span> ${O(`chevronDown`,12)}`,i.addEventListener(`click`,()=>this.toggle(r(i))),this.button=i}tidy(){this.button.hidden=this.items.every(e=>this.isOff(e.parts))}setOpen(e,t){let n=zt.find(t=>t===e);n&&(t?this.open.add(n):this.open.delete(n))}destroy(){this.menu?.destroy(),this.button.remove()}isOff(e){let t=new Set((this.root().getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean));return e.some(e=>t.has(e))}toggle(e){if(this.menu?.isOpen()){this.menu.close();return}let t=this.items.filter(e=>!this.isOff(e.parts));if(t.length===0)return;let n=t.filter(e=>!zt.includes(e.id)),r=t.filter(e=>zt.includes(e.id)),i=[...n.map(e=>({id:e.id,label:e.label,icon:Rt[e.id]})),...n.length>0&&r.length>0?[`separator`]:[],...r.map(e=>({id:e.id,label:e.label,checked:this.open.has(e.id)}))],a=this.root();this.menu??=new A(a,this.t(`toolbar.trade`)),this.menu.openUnder(i,e,e=>{t.find(t=>t.id===e)?.run()})}},Ht=2048,Ut=65536,Wt=/^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/i,Gt=new Set([`https:`,`http:`,`blob:`]),Kt=new Set([`description`,`exchange`,`type`,`logo`]);function qt(e){if(typeof e!=`string`)return null;let t=e.trim();return t&&t.length<=64?t:null}function Jt(e){let t=[],n=new Map;if(!Array.isArray(e))return{names:t,info:n};let r=new Set;for(let i of e){let e=typeof i==`object`&&!!i,a=qt(e?i.symbol:i);!a||r.has(a)||(r.add(a),t.push(a),e&&n.set(a,Yt(i,a)))}return{names:t,info:n}}function Yt(e,t){return{...Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==`__proto__`&&(!Kt.has(e)||typeof t==`string`&&t.trim()!==``))),symbol:t}}function Xt(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.symbol==`string`&&e.symbol!==``).map(e=>Yt(e,e.symbol)):[]}function Zt(e,t){if(!t)return e;if(!e)return t;let n=Object.entries(t).filter(([,e])=>e!=null);return Object.fromEntries([...Object.entries(e),...n])}function Qt(e){let t=e.lastIndexOf(`:`);return t<=0||t===e.length-1?{venue:``,ticker:e}:{venue:e.slice(0,t+1),ticker:e.slice(t+1)}}var $t=e=>Qt(e).ticker.toUpperCase();function en(e,t){return!t||typeof t.symbol!=`string`?null:t.symbol.toUpperCase()===e.toUpperCase()||t.symbol.includes(`:`)!==e.includes(`:`)&&$t(t.symbol)===$t(e)?t:null}function tn(e){return[e?.description,e?.exchange].filter(Boolean).join(` · `)||null}var nn=()=>typeof document>`u`?void 0:document.baseURI;function rn(e,t=nn()){if(typeof e!=`string`)return null;let n=e.trim();if(!n||n.length>Ut)return null;let r;try{r=new URL(n,t)}catch{return null}return r.protocol===`data:`?Wt.test(r.href)&&r.href.length<=Ut?r.href:null:Gt.has(r.protocol)&&r.href.length<=Ht?r.href:null}var an=0,j=`data-tcw-folded`,on=1/64,sn=[`venue`,`ticker`,`cut`],cn={T:`toolbar.timeframes.ticks`,s:`toolbar.timeframes.seconds`,m:`toolbar.timeframes.minutes`,h:`toolbar.timeframes.hours`,d:`toolbar.timeframes.days`,w:`toolbar.timeframes.weeks`,M:`toolbar.timeframes.months`};function ln(e,t){let n=e.querySelector(`.tcw-host-btn-text`)?.textContent??``;n===t?e.removeAttribute(`aria-label`):e.setAttribute(`aria-label`,n?`${t}: ${n}`:t)}var un=class{config;callbacks;t;el;chartTypeDropdown=null;tfGroup=null;tfDropdown=null;tfFavorites=[];uid=(an++).toString(36);tfRendered=``;themeBtn=null;fullscreenBtn=null;hostLeft=null;hostRight=null;moreMenu=null;tfCurrent=null;resizeObserver=null;hostObserver=null;moreBtn=null;fitFrame=0;destroyed=!1;undoBtn=null;redoBtn=null;trade=null;layoutShown=``;symbolShown=null;constructor(e,t,n,r,i){if(this.host=e,this.layer=i,this.config=t,this.callbacks=n,this.t=r,this.el=document.createElement(`div`),this.el.className=`tcw-toolbar`,D(this.el,`toolbar`),this.build(),e.appendChild(this.el),typeof ResizeObserver<`u`){this.resizeObserver=new ResizeObserver(()=>this.fit()),this.resizeObserver.observe(this.el),this.hostObserver=new ResizeObserver(()=>this.scheduleFit());for(let e of[this.hostLeft,this.hostRight])e&&this.hostObserver.observe(e)}document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.destroyed||this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.destroyed||this.fit()}))}menuAnchor(e){return(e.hasAttribute(j)||this.el.closest(`[data-tcw-narrow]`)!==null)&&this.moreBtn?this.moreBtn:e}fit(){let e=this.toolbarFocus(),t=this.foldedState();this.refit(),this.foldedState()!==t&&this.closeStaleMenus(),e&&this.keepFocus(e)}refit(){let{el:e}=this,t=()=>this.fits(),n=[...e.querySelectorAll(`.tcw-toolbar-overflow`)];for(let e of n)e.removeAttribute(j);if(e.classList.remove(`tcw-toolbar--collapsed`,`tcw-toolbar--icons`),delete e.dataset.tcwSqueeze,!(e.clientWidth===0||t())){e.classList.add(`tcw-toolbar--collapsed`);for(let e=n.length-1;e>=0;e--)if(n[e].setAttribute(j,``),t())return;e.classList.add(`tcw-toolbar--icons`);for(let e of n)if(e.removeAttribute(j),!t()){e.setAttribute(j,``);break}for(let n of sn){if(t())return;e.dataset.tcwSqueeze=n}}}fits(){let{el:e}=this,t=e.getBoundingClientRect(),n=e.offsetWidth>0&&Math.abs(t.width-e.offsetWidth)>=1?t.width/e.offsetWidth:1,r=getComputedStyle(e),i=r.direction===`rtl`,a=e=>parseFloat(e)||0,o=t.width/n-(i?a(r.borderLeftWidth)+a(r.paddingLeft):a(r.borderRightWidth)+a(r.paddingRight)),s=0;for(let r of e.children){if(r.getClientRects().length===0)continue;let e=r.getBoundingClientRect();s=Math.max(s,(i?t.right-e.left:e.right-t.left)/n)}return Math.ceil(s-on)<=Math.floor(o+on)}foldedState(){let e=[...this.el.querySelectorAll(`.tcw-toolbar-overflow`)];return`${this.el.classList.contains(`tcw-toolbar--collapsed`)}:${e.map(e=>Number(e.hasAttribute(j))).join(``)}`}closeStaleMenus(){this.moreBtn&&A.closeAnchoredTo(this.moreBtn);for(let e of this.el.querySelectorAll(`[${j}], [${j}] button`))A.closeAnchoredTo(e)}toolbarFocus(){let e=A.focusedAnchor();if(e&&this.el.contains(e))return e;let t=document.activeElement;return t instanceof HTMLElement&&this.el.contains(t)?t:null}keepFocus(e){if(A.focusedAnchor())return;let t=e;this.shows(e)||(t=(this.moreBtn&&e!==this.moreBtn&&this.shows(this.moreBtn)?this.moreBtn:null)??this.overflowButtons().filter(e=>this.shows(e)).at(-1)),t&&document.activeElement!==t&&t.focus({preventScroll:!0})}overflowButtons(){return[...this.el.querySelectorAll(`button.tcw-toolbar-overflow, .tcw-toolbar-overflow button`)]}shows(e){if(e.closest(`[hidden]`)||e.closest(`[${j}]`)||this.isOff(e))return!1;let t=this.el.closest(`[data-tcw-narrow]`)!==null;return e===this.moreBtn?t||this.el.classList.contains(`tcw-toolbar--collapsed`):!(t&&e.closest(`.tcw-toolbar-overflow`))}isOff(e){let t=new Set((this.rootEl().getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean));for(let n=e;n&&n!==this.el;n=n.parentElement)if((n.dataset.tcwPart??``).split(/\s+/).some(e=>t.has(e)))return!0;return!1}build(){let{config:e,callbacks:t,el:n}=this,r=document.createElement(`button`);if(r.className=`tcw-toolbar-symbol`,r.dataset.role=`symbol`,r.dir=`ltr`,D(r,`toolbar.symbol`),r.addEventListener(`click`,t.onSymbolClick),n.appendChild(r),t.onSymbolInfo){let e=this.iconBtn(`info`,this.t(`symbolInfo.title`),t.onSymbolInfo);e.classList.remove(`tcw-toolbar-overflow`),e.dataset.role=`symbolInfo`,D(e,`symbolInfo`,`toolbar.symbolInfo`),n.appendChild(e)}if(n.appendChild(this.sep()),this.tfFavorites=[...e.timeframeFavorites??e.timeframes.map(e=>e.value)],this.tfGroup=document.createElement(`div`),this.tfGroup.className=`tcw-toolbar-group tcw-tf-group`,D(this.tfGroup,`toolbar.timeframes`),n.appendChild(this.tfGroup),t.onToggleTimeframeFavorite&&e.timeframes.length>0){let e=document.createElement(`div`);e.style.position=`relative`,e.style.display=`inline-flex`,D(e,`toolbar.timeframeMenu`);let t=document.createElement(`button`);t.className=`tcw-btn tcw-tf-more`,t.dataset.role=`timeframes`,t.title=this.t(`toolbar.timeframes`),t.setAttribute(`aria-label`,this.t(`toolbar.timeframes`)),this.tfCurrent=document.createElement(`span`),this.tfCurrent.className=`tcw-tf-current`,t.appendChild(this.tfCurrent),t.insertAdjacentHTML(`beforeend`,O(`chevronDown`,12)),e.appendChild(t),n.appendChild(e),this.tfDropdown=new rt(e,{width:`150px`,layer:this.layer}),n.classList.add(`tcw-toolbar--tf-menu`),this.buildTimeframeMenu()}n.appendChild(this.sep());let i=document.createElement(`div`);i.style.position=`relative`,i.style.display=`inline-flex`,D(i,`toolbar.chartType`);let a=document.createElement(`button`);a.className=`tcw-dropdown-trigger`,a.dataset.role=`charttype`,i.appendChild(a),n.appendChild(i),this.chartTypeDropdown=new rt(i,{width:`160px`,layer:this.layer}),this.buildChartTypeMenu(),n.appendChild(this.sep());let o=document.createElement(`button`);if(o.type=`button`,o.className=`tcw-dropdown-trigger`,o.dataset.role=`indicators`,o.setAttribute(`aria-haspopup`,`dialog`),o.setAttribute(`aria-expanded`,`false`),D(o,`toolbar.indicators`),o.addEventListener(`click`,()=>t.onIndicators()),n.appendChild(o),t.onCompare){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-dropdown-trigger`,e.dataset.role=`compare`,D(e,`compare`,`toolbar.compare`);let r=this.t(`objects.compare`);e.setAttribute(`aria-label`,r),e.title=r,e.innerHTML=`${O(`plus`,14)} <span class="tcw-trigger-label">${k(r)}</span>`,e.addEventListener(`click`,t.onCompare),n.appendChild(e)}if(this.hostLeft=this.hostGroup(),n.appendChild(this.hostLeft),t.onUndo&&t.onRedo&&(n.appendChild(this.sep()),this.undoBtn=this.iconBtn(`undo`,this.t(`drawing.undo`),t.onUndo),this.undoBtn.dataset.role=`undo`,D(this.undoBtn,`toolbar.undo`,`sidebar.undo`),this.redoBtn=this.iconBtn(`redo`,this.t(`drawing.redo`),t.onRedo),this.redoBtn.dataset.role=`redo`,D(this.redoBtn,`toolbar.redo`,`sidebar.redo`),n.append(this.undoBtn,this.redoBtn),this.setHistory(!1,!1)),n.appendChild(this.spacer()),t.onLayouts){let e=t.onLayouts,r=document.createElement(`button`);r.type=`button`,r.className=`tcw-dropdown-trigger tcw-layouts-btn tcw-toolbar-overflow`,r.dataset.role=`layouts`,r.dataset.icon=`save`,D(r,`layouts`,`toolbar.layouts`),r.setAttribute(`aria-haspopup`,`menu`),r.addEventListener(`click`,()=>e(this.menuAnchor(r))),n.appendChild(r),this.setLayout(null,!1)}if(this.hostRight=this.hostGroup(),n.appendChild(this.hostRight),n.appendChild(this.sep()),t.onToggleReplay){let e=this.iconBtn(`play`,this.t(`toolbar.replay`),t.onToggleReplay);e.dataset.role=`replay`,D(e,`replay`,`toolbar.replay`),n.appendChild(e)}if(t.onToggleObjects){let e=this.iconBtn(`layers`,this.t(`toolbar.objects`),t.onToggleObjects);e.dataset.role=`objects`,e.setAttribute(`aria-pressed`,`false`),D(e,`objectTree`,`toolbar.objectTree`),n.appendChild(e)}if(t.onToggleAlerts){let e=this.iconBtn(`bell`,this.t(`toolbar.priceAlerts`),t.onToggleAlerts);e.dataset.role=`alerts`,e.setAttribute(`aria-pressed`,`false`),D(e,`alerts`,`toolbar.alerts`),n.appendChild(e)}this.trade=Vt.create(t,this.t,()=>this.rootEl(),e=>this.menuAnchor(e)),this.trade&&n.appendChild(this.trade.button),n.appendChild(this.sep());let s=this.iconBtn(`camera`,this.t(`toolbar.screenshot`),t.onScreenshot);D(s,`screenshot`,`toolbar.screenshot`),n.appendChild(s);let c=this.iconBtn(`settings`,this.t(`toolbar.settings`),t.onSettings);D(c,`settings`,`toolbar.settings`),n.appendChild(c),this.themeBtn=this.iconBtn(`moon`,this.t(`toolbar.toggleTheme`),t.onToggleTheme),this.themeBtn.dataset.role=`theme`,D(this.themeBtn,`themeToggle`,`toolbar.themeToggle`),n.appendChild(this.themeBtn),t.onToggleFullscreen&&(this.fullscreenBtn=this.iconBtn(`maximize`,this.t(`toolbar.fullscreen`),t.onToggleFullscreen),this.fullscreenBtn.dataset.role=`fullscreen`,D(this.fullscreenBtn,`fullscreen`,`toolbar.fullscreen`),this.fullscreenBtn.setAttribute(`aria-pressed`,`false`),n.appendChild(this.fullscreenBtn));let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-btn-icon tcw-toolbar-more`,l.title=this.t(`toolbar.more`),l.setAttribute(`aria-haspopup`,`menu`),l.setAttribute(`aria-expanded`,`false`),l.innerHTML=O(`more`,16),l.addEventListener(`click`,()=>this.toggleMore(l)),n.appendChild(l),this.moreBtn=l}toggleMore(e){if(A.closeAnchoredTo(e))return;let t=this.rootEl(),n=this.el.closest(`[data-tcw-narrow]`)!==null,r=[];for(let e of this.el.querySelectorAll(`.tcw-toolbar-overflow`)){if(this.isOff(e)||!n&&!e.hasAttribute(j))continue;let t=e instanceof HTMLButtonElement?[e]:[...e.querySelectorAll(`button`)];r.push(...t.filter(e=>!e.hidden&&!e.disabled&&!this.isOff(e)))}if(r.length===0)return;let i=r.map((e,t)=>{let n=e.getAttribute(`aria-label`)||e.title||e.textContent?.trim()||``,r=e.getAttribute(`aria-pressed`);return r===null?{id:String(t),label:n,icon:e.dataset.icon}:{id:String(t),label:n,icon:e.dataset.icon,checked:r===`true`}});this.moreMenu??=new A(t,this.t(`toolbar.more`)),this.moreMenu.openUnder(i,e,e=>r[Number(e)]?.click(),`end`)}addHostButton(e){let t=document.createElement(`button`);t.type=`button`,t.className=`${e.text||!e.icon?`tcw-btn`:`tcw-btn-icon`} tcw-host-btn tcw-toolbar-overflow`,t.dataset.hostButton=e.id,typeof e.icon==`string`&&(t.dataset.icon=e.icon),t.title=e.label,e.toggle&&t.setAttribute(`aria-pressed`,`false`),typeof e.icon==`string`?t.innerHTML=O(e.icon,14):e.icon&&t.appendChild(e.icon);let n=e.text??(e.icon?``:e.label);if(n){let e=document.createElement(`span`);e.className=`tcw-host-btn-text`,e.textContent=n,t.appendChild(e)}return ln(t,e.label),t.addEventListener(`click`,()=>e.onClick(t)),(e.side===`left`?this.hostLeft:this.hostRight)?.appendChild(t),this.scheduleFit(),t}hostSlot(e){return e===`left`?this.hostLeft:this.hostRight}hostGroup(){let e=document.createElement(`div`);return e.className=`tcw-toolbar-host`,e}setSymbolSearch(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(e?t.removeAttribute(`aria-disabled`):t.setAttribute(`aria-disabled`,`true`))}tidy(){this.trade?.tidy(),Je(this.el,`tcw-toolbar-sep`,`tcw-toolbar-spacer`),this.scheduleFit()}setHistory(e,t){this.undoBtn&&(this.undoBtn.disabled=!e),this.redoBtn&&(this.redoBtn.disabled=!t)}rootEl(){return this.el.closest(`.tcw-root`)??this.host}setActive(e,t){this.trade?.setOpen(e,t);let n=this.el.querySelector(`[data-role="${e}"]`);n&&(n.classList.toggle(`tcw-active`,t),n.setAttribute(`aria-pressed`,String(t)))}setRailed(e,t){let n=this.el.querySelector(`[data-role="${e}"]`);n&&(n.hidden=t)}setLayout(e,t){let n=this.el.querySelector(`[data-role="layouts"]`);if(!n)return;let r=e??this.t(`layouts.unnamed`);if(this.layoutShown===`${t}:${r}`)return;this.layoutShown=`${t}:${r}`;let i=`${this.t(`toolbar.layouts`)}: ${r}${t?` (${this.t(`layouts.unsavedChanges`)})`:``}`;n.innerHTML=`${O(`save`,14)}<span class="tcw-layouts-label">${k(r)}</span>`+(t?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+O(`chevronDown`,12),n.title=i,n.setAttribute(`aria-label`,i),this.scheduleFit()}setFullscreen(e){if(!this.fullscreenBtn)return;let t=this.t(e?`toolbar.exitFullscreen`:`toolbar.fullscreen`);this.fullscreenBtn.innerHTML=O(e?`minimize`:`maximize`,14),this.fullscreenBtn.title=t,this.fullscreenBtn.setAttribute(`aria-pressed`,String(e))}chartTypeLabel(e){return vt(e,this.t)}buildChartTypeMenu(){if(!this.chartTypeDropdown)return;let e=this.config.chartTypes.map(e=>`<button class="tcw-dropdown-item tcw-dropdown-item--icon" data-ct="${k(e.value)}">${nt(e.value,16)}<span>${k(this.chartTypeLabel(e))}</span></button>`).join(``);this.chartTypeDropdown.setContent(e),this.chartTypeDropdown.panel.querySelectorAll(`.tcw-dropdown-item`).forEach(e=>{e.addEventListener(`click`,e=>{let t=e.currentTarget.dataset.ct;this.callbacks.onChartType(t),this.chartTypeDropdown?.close()})})}setSymbolDescription(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(e?t.title=e:t.removeAttribute(`title`))}setTimeframes(e,t){this.config={...this.config,timeframes:e},this.setTimeframeFavorites(t)}setTimeframeFavorites(e){this.tfFavorites=[...e],this.tfRendered=``,this.buildTimeframeMenu()}buildTimeframeMenu(){if(!this.tfDropdown)return;let e=k(this.t(`toolbar.timeframes.pin`)),t=k(this.t(`toolbar.timeframes.remove`)),n=``;for(let{unit:r,timeframes:i}of Pt(this.config.timeframes)){n+=`<div class="tcw-tf-section" data-tf-section="${r}" role="group" aria-label="${k(this.t(cn[r]))}"><div class="tcw-dropdown-label">${k(this.t(cn[r]))}</div>`;for(let r of i){let i=this.tfFavorites.includes(r.value),[a,o]=[k(r.value),k(r.label)];n+=`<div class="tcw-tf-row"><button class="tcw-dropdown-item" data-tf-pick="${a}">${o}</button>`+(r.custom&&this.callbacks.onRemoveTimeframe?`<button class="tcw-tf-remove" data-tf-remove="${a}" title="${t}" aria-label="${t}: ${o}">${O(`x`,12)}</button>`:``)+`<button class="tcw-tf-star${i?` tcw-active`:``}" data-tf-star="${a}" aria-pressed="${i}" title="${e}" aria-label="${e}: ${o}">${O(`star`,12)}</button></div>`}n+=`</div>`}if(this.callbacks.onAddTimeframe){let e=k(this.t(`toolbar.timeframes.custom`)),t=k(this.t(`toolbar.timeframes.add`));n+=`<form class="tcw-tf-custom" ${Ke(`customTimeframes`)} novalidate><input class="tcw-tf-custom-input" type="text" autocomplete="off" spellcheck="false" maxlength="6" placeholder="7m, 90m, 2h…" aria-label="${e}" aria-describedby="tcw-tf-hint-${this.uid}"><button type="submit" class="tcw-tf-custom-add" title="${t}" aria-label="${t}">${O(`plus`,12)}</button><div class="tcw-tf-custom-hint" id="tcw-tf-hint-${this.uid}" role="status"></div></form>`}this.tfDropdown.setContent(n);let r=this.tfDropdown.panel;r.querySelectorAll(`[data-tf-pick]`).forEach(e=>{e.addEventListener(`click`,()=>this.callbacks.onTimeframe(e.dataset.tfPick))}),r.querySelectorAll(`[data-tf-star]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onToggleTimeframeFavorite?.(e.dataset.tfStar)})}),r.querySelectorAll(`[data-tf-remove]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemoveTimeframe?.(e.dataset.tfRemove)})});let i=r.querySelector(`.tcw-tf-custom`);i&&this.wireCustomTimeframe(i)}wireCustomTimeframe(e){let t=e.querySelector(`.tcw-tf-custom-input`),n=e.querySelector(`.tcw-tf-custom-hint`);e.addEventListener(`click`,e=>e.stopPropagation()),t.addEventListener(`input`,()=>{t.removeAttribute(`aria-invalid`),n.textContent=``}),e.addEventListener(`submit`,e=>{e.preventDefault(),e.stopPropagation(),this.callbacks.onAddTimeframe?.(t.value)?(t.value=``,n.textContent=``,this.tfDropdown?.close(),this.el.querySelector(`[data-role="timeframes"]`)?.focus()):(t.setAttribute(`aria-invalid`,`true`),n.textContent=this.t(`toolbar.timeframes.invalid`))})}renderTimeframes(e){if(!this.tfGroup)return;let t=this.config.timeframes.filter(t=>this.tfFavorites.includes(t.value)||t.value===e),n=`${t.map(e=>e.value).join(`,`)}|${e}`;n!==this.tfRendered&&(this.tfRendered=n,this.tfCurrent&&(this.tfCurrent.textContent=this.config.timeframes.find(t=>t.value===e)?.label??e),this.tfGroup.replaceChildren(...t.map(t=>{let n=document.createElement(`button`);return n.className=`tcw-btn`,n.textContent=t.label,n.dataset.tf=t.value,n.classList.toggle(`tcw-active`,t.value===e),n.addEventListener(`click`,()=>this.callbacks.onTimeframe(t.value)),n})),(this.tfDropdown?.panel)?.querySelectorAll(`[data-tf-pick]`).forEach(t=>{t.classList.toggle(`tcw-active`,t.dataset.tfPick===e)}))}setIndicatorsOpen(e){this.el.querySelector(`[data-role="indicators"]`)?.setAttribute(`aria-expanded`,String(e))}renderSymbol(e){let t=this.el.querySelector(`[data-role="symbol"]`);if(!t||this.symbolShown===e)return;this.symbolShown=e;let{venue:n,ticker:r}=Qt(e),i=(e,t)=>{let n=document.createElement(`span`);return n.className=e,n.textContent=t,n};t.replaceChildren(...n?[i(`tcw-toolbar-venue`,n)]:[],i(`tcw-toolbar-ticker`,r)),t.classList.toggle(`tcw-toolbar-symbol--venue`,n!==``),t.setAttribute(`aria-label`,e)}update(e){this.renderSymbol(e.symbol),this.renderTimeframes(e.timeframe);let t=this.el.querySelector(`[data-role="charttype"]`);if(t){let n=this.config.chartTypes.find(t=>t.value===e.chartType),r=n?this.chartTypeLabel(n):e.chartType;t.innerHTML=nt(e.chartType,16),t.title=r,t.setAttribute(`aria-label`,r)}let n=this.el.querySelector(`[data-role="indicators"]`);if(n){let t=[...e.activeIndicators.values()].filter(e=>!r.SYMBOL_INDICATOR_IDS.has(e.id)).length,i=`${O(`trendingUp`,14)} <span class="tcw-trigger-label">${k(this.t(`toolbar.indicators`))}</span>`;n.setAttribute(`aria-label`,this.t(`toolbar.indicators`)),t>0&&(i+=` <span class="tcw-badge-count">${t}</span>`),n.innerHTML=i}if(this.themeBtn){let t=e.isDark?`moon`:`sun`;this.themeBtn.innerHTML=O(t,14),this.themeBtn.dataset.icon=t}this.scheduleFit()}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}spacer(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-spacer`,e}iconBtn(e,t,n){let r=document.createElement(`button`);return r.className=`tcw-btn-icon tcw-toolbar-overflow`,r.dataset.icon=e,r.title=t,r.innerHTML=O(e,14),r.addEventListener(`click`,n),r}destroy(){this.destroyed=!0,this.resizeObserver?.disconnect(),this.hostObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.chartTypeDropdown?.destroy(),this.tfDropdown?.destroy(),this.moreMenu?.destroy(),this.trade?.destroy(),this.el.remove()}};function dn(e,t,n){e.classList.toggle(`tcw-active`,t),n&&e.setAttribute(`aria-pressed`,String(t))}function fn(e,t,n){let r=n==null?``:String(n),i=e.querySelector(`.tcw-host-btn-text`);return(i?.textContent??``)===r?!1:(i||(i=document.createElement(`span`),i.className=`tcw-host-btn-text`,e.appendChild(i)),i.textContent=r,ln(e,t),!0)}var pn=16,mn=150,hn=4;function gn(e){let t=`sidebar.${e}`;return Pe.includes(t)?t:null}function _n(e,t){for(let n of e){let e=n.tools.find(e=>e.value===t);if(e)return e.label}return t}var vn=`--tcw-fab-plot-left`,yn=class{config;callbacks;el;groupWraps=[];groupButtons=[];groupIcons=[];groupTools=[];cursorBtn=null;magnetBtn=null;eraserBtn=null;zoomBtn=null;stayBtn=null;lockAllBtn=null;hideAllBtn=null;drawings={locked:!1,hidden:!1};flyoutEl=null;flyoutIdx=-1;flyoutHideTimer=null;hostEl=null;favoritesEl=null;favoritesDivider=null;favorites=[];fab;fabShows=``;onPressAway=e=>{let t=e.target;t&&(this.el.contains(t)||this.fab.contains(t)||this.flyoutEl?.contains(t))||this.setOpen(!1)};onEscape=e=>{e.key===`Escape`&&!this.flyoutEl&&this.setOpen(!1)};constructor(e,n,r,i=t.t){this.host=e,this.t=i,this.config=n,this.callbacks=r,this.el=document.createElement(`div`),this.el.className=`tcw-sidebar`,D(this.el,`sidebar`),this.build(),this.el.addEventListener(`scroll`,()=>this.hideFlyout(),{passive:!0}),e.appendChild(this.el),this.fab=document.createElement(`button`),this.fab.type=`button`,this.fab.className=`tcw-sidebar-fab`,this.fab.setAttribute(`aria-label`,this.t(`drawing.tools`)),this.fab.setAttribute(`aria-expanded`,`false`),this.fab.innerHTML=O(`penLine`,18),D(this.fab,`sidebar`),this.fab.addEventListener(`click`,()=>this.setOpen(!this.isOpen())),e.appendChild(this.fab)}setPlotLeft(e){let t=`${Math.max(0,Math.round(e))}px`;this.fab.style.getPropertyValue(vn)!==t&&this.fab.style.setProperty(vn,t)}isNarrow(){return this.el.closest(`[data-tcw-narrow]`)!==null}isOpen(){return this.el.classList.contains(`tcw-sidebar-open`)}setOpen(e){if(e!==this.isOpen())if(this.el.classList.toggle(`tcw-sidebar-open`,e),this.fab.setAttribute(`aria-expanded`,String(e)),e)document.addEventListener(`pointerdown`,this.onPressAway,!0),document.addEventListener(`keydown`,this.onEscape);else{let e=this.el.contains(document.activeElement)||!!this.flyoutEl?.contains(document.activeElement);this.hideFlyout(),document.removeEventListener(`pointerdown`,this.onPressAway,!0),document.removeEventListener(`keydown`,this.onEscape),e&&this.isNarrow()&&this.fab.focus({preventScroll:!0})}}closeOverlay(){this.setOpen(!1)}closeForChart(){this.isNarrow()&&this.setOpen(!1)}pick(e){this.callbacks.onDrawingTool(e),this.closeForChart()}build(){let{config:e,callbacks:t,el:n}=this;this.cursorBtn=document.createElement(`button`),this.cursorBtn.className=`tcw-sidebar-btn`,this.cursorBtn.title=this.t(`drawing.cursor`),this.cursorBtn.innerHTML=O(`cursor`,14),this.cursorBtn.addEventListener(`click`,()=>{t.onCancelDrawing(),this.closeForChart()}),D(this.cursorBtn,`sidebar.cursor`),n.appendChild(this.cursorBtn),n.appendChild(this.divider()),t.onToggleFavorite&&(this.favorites=[...e.favorites??[]],this.favoritesEl=document.createElement(`div`),this.favoritesEl.className=`tcw-sidebar-favorites`,D(this.favoritesEl,`sidebar.favorites`),n.appendChild(this.favoritesEl),this.favoritesDivider=this.divider(),D(this.favoritesDivider,`sidebar.favorites`),n.appendChild(this.favoritesDivider),this.renderFavorites());let r;e.drawingToolGroups.forEach((e,t)=>{if(!e.tools[0])return;e.section!==void 0&&r!==void 0&&e.section!==r&&this.appendDivider(),r=e.section;let i=document.createElement(`div`);i.className=`tcw-tool-group-wrap`;let a=gn(e.section);a&&D(i,a);let o=document.createElement(`button`);o.className=`tcw-sidebar-btn`;let s=e.tools[0].value;e.tools.length>1?o.setAttribute(`aria-label`,`${e.label}: ${e.tools[0].label}`):o.title=e.label;let c=document.createElement(`span`);if(c.className=`tcw-sidebar-icon`,c.innerHTML=tt(s,pn),o.appendChild(c),this.groupIcons.push(c),this.groupTools.push(s),e.tools.length>1){let e=document.createElement(`span`);e.className=`tcw-multi-dot`,o.appendChild(e)}o.addEventListener(`click`,()=>{if(this.isNarrow()&&e.tools.length>1){this.flyoutEl&&this.flyoutIdx===t?this.hideFlyout():this.showFlyout(t);return}this.pick(this.groupTools[t])}),i.appendChild(o),i.addEventListener(`mouseenter`,()=>{this.isNarrow()||this.showFlyout(t)}),i.addEventListener(`mouseleave`,()=>{this.isNarrow()||this.scheduleHideFlyout()}),e.tools.length>1&&(o.setAttribute(`aria-haspopup`,`menu`),o.setAttribute(`aria-expanded`,`false`),o.addEventListener(`keydown`,e=>{e.key===`ArrowRight`||e.key===`ArrowDown`?(e.preventDefault(),this.showFlyout(t),this.focusFlyoutItem(0)):e.key===`Escape`&&this.flyoutEl&&(e.stopPropagation(),this.hideFlyout())})),i.addEventListener(`focusout`,e=>{let t=e.relatedTarget;!i.contains(t)&&!this.flyoutEl?.contains(t)&&this.scheduleHideFlyout()}),n.appendChild(i),this.groupWraps.push(i),this.groupButtons.push(o)});let i=document.createElement(`div`);if(i.className=`tcw-sidebar-spacer`,n.appendChild(i),n.appendChild(this.divider()),t.onToggleStyle){let e=document.createElement(`button`);e.className=`tcw-sidebar-btn`,e.title=this.t(`drawing.style`),e.dataset.role=`style`,D(e,`sidebar.style`),e.innerHTML=O(`palette`,14);let r=t.onToggleStyle;e.addEventListener(`click`,()=>{r(),this.closeForChart()}),n.appendChild(e)}if(t.onToggleMagnet&&(this.magnetBtn=document.createElement(`button`),this.magnetBtn.className=`tcw-sidebar-btn`,this.magnetBtn.title=this.t(`drawing.magnet`),this.magnetBtn.innerHTML=O(`magnet`,14),this.magnetBtn.addEventListener(`click`,t.onToggleMagnet),D(this.magnetBtn,`sidebar.magnet`),n.appendChild(this.magnetBtn)),t.onToggleEraser){let e=t.onToggleEraser;this.eraserBtn=this.toggleButton(`eraser`,this.t(`drawing.eraser`),()=>{e(),this.closeForChart()}),D(this.eraserBtn,`sidebar.eraser`),n.appendChild(this.eraserBtn)}if(t.onToggleZoomArea){let e=t.onToggleZoomArea;this.zoomBtn=this.toggleButton(`zoomIn`,this.t(`drawing.zoomArea`),()=>{e(),this.closeForChart()}),D(this.zoomBtn,`sidebar.zoomArea`),n.appendChild(this.zoomBtn)}if(t.onToggleStayInDrawing&&(this.stayBtn=document.createElement(`button`),this.stayBtn.className=`tcw-sidebar-btn`,this.stayBtn.dataset.role=`stay`,this.stayBtn.title=this.t(`drawing.stay`),this.stayBtn.setAttribute(`aria-pressed`,`false`),this.stayBtn.innerHTML=O(`repeat`,14),this.stayBtn.addEventListener(`click`,t.onToggleStayInDrawing),D(this.stayBtn,`sidebar.stayInDrawing`),n.appendChild(this.stayBtn)),this.hostEl=document.createElement(`div`),this.hostEl.className=`tcw-sidebar-host`,n.appendChild(this.hostEl),this.appendDivider(),t.onLockAll){let e=t.onLockAll;this.lockAllBtn=this.toggleButton(`lock`,this.t(`drawing.lockAll`),()=>e(!this.drawings.locked)),this.lockAllBtn.dataset.role=`lockAll`,D(this.lockAllBtn,`sidebar.lockAll`),n.appendChild(this.lockAllBtn)}if(t.onHideAll){let e=t.onHideAll;this.hideAllBtn=this.toggleButton(`eyeOff`,this.t(`drawing.hideAll`),()=>e(!this.drawings.hidden)),this.hideAllBtn.dataset.role=`hideAll`,D(this.hideAllBtn,`sidebar.hideAll`),n.appendChild(this.hideAllBtn)}let a=document.createElement(`button`);a.className=`tcw-sidebar-btn tcw-danger`,a.title=this.t(`drawing.clearAll`),a.innerHTML=O(`trash`,14),a.setAttribute(`aria-haspopup`,`menu`),a.setAttribute(`aria-expanded`,`false`),a.addEventListener(`click`,()=>t.onClear(a)),D(a,`sidebar.clear`),n.appendChild(a)}setDrawingsState(e){if(!(e.locked===this.drawings.locked&&e.hidden===this.drawings.hidden)){this.drawings={...e};for(let[t,n]of[[this.lockAllBtn,e.locked],[this.hideAllBtn,e.hidden]])t?.setAttribute(`aria-pressed`,String(n)),t?.classList.toggle(`tcw-active`,n)}}setFavorites(e){this.favorites=[...e],this.renderFavorites();for(let e of this.flyoutEl?.querySelectorAll(`.tcw-flyout-row`)??[]){let t=this.favorites.includes(e.dataset.toolValue??``);e.classList.toggle(`tcw-flyout-faved`,t),e.querySelector(`[data-pin]`)?.setAttribute(`aria-pressed`,String(t))}}renderFavorites(){if(!this.favoritesEl)return;this.favoritesEl.replaceChildren();let e=this.favorites.length>0;this.favoritesEl.style.display=e?``:`none`,this.favoritesDivider&&(this.favoritesDivider.style.display=e?``:`none`);for(let e of this.favorites){let n=document.createElement(`button`);n.className=`tcw-sidebar-btn`,n.title=t.r(this.t(`sidebar.unpinHint`),{tool:_n(this.config.drawingToolGroups,e)}),n.dataset.toolValue=e,n.innerHTML=tt(e,pn),n.addEventListener(`click`,()=>this.pick(e)),n.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.callbacks.onToggleFavorite?.(e)}),this.favoritesEl.appendChild(n)}}showFlyout(e){if(this.cancelHideFlyout(),this.flyoutEl&&this.flyoutIdx===e)return;let t=this.config.drawingToolGroups[e];if(!t||t.tools.length<=1){this.hideFlyout();return}this.hideFlyout();let n=document.createElement(`div`);n.className=`tcw-flyout`,n.setAttribute(`role`,`menu`),n.setAttribute(`aria-label`,t.label),n.addEventListener(`keydown`,t=>this.onFlyoutKey(t,e));let r=document.createElement(`div`);r.className=`tcw-flyout-header`,r.textContent=t.label,n.appendChild(r);let i=this.t(`drawing.pinFavorite`);for(let e of t.tools){let t=document.createElement(`div`);t.className=`tcw-flyout-row`,t.setAttribute(`role`,`none`),t.dataset.toolValue=e.value;let r=document.createElement(`button`);r.className=`tcw-flyout-item`,r.setAttribute(`role`,`menuitem`),r.tabIndex=-1,r.innerHTML=tt(e.value,pn);let a=document.createElement(`span`);a.className=`tcw-flyout-name`,a.textContent=e.label,r.appendChild(a);let o=this.config.shortcuts?.[e.value];if(o){let e=document.createElement(`kbd`);e.className=`tcw-flyout-key`,e.textContent=o,D(e,`hotkeys`,`hotkeys.tools`),r.appendChild(e)}if(r.dataset.toolValue=e.value,r.addEventListener(`click`,()=>{this.hideFlyout(),this.pick(e.value)}),t.appendChild(r),this.callbacks.onToggleFavorite){let n=this.favorites.includes(e.value);t.classList.toggle(`tcw-flyout-faved`,n);let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-flyout-pin`,a.dataset.pin=e.value,a.tabIndex=-1,a.title=i,a.setAttribute(`aria-label`,`${i}: ${e.label}`),a.setAttribute(`aria-pressed`,String(n)),a.innerHTML=O(`star`,12),a.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onToggleFavorite?.(e.value)}),t.appendChild(a),r.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.callbacks.onToggleFavorite?.(e.value)})}n.appendChild(t)}n.addEventListener(`mouseenter`,()=>this.cancelHideFlyout()),n.addEventListener(`mouseleave`,()=>this.scheduleHideFlyout()),n.addEventListener(`focusout`,t=>{let r=t.relatedTarget;!n.contains(r)&&!this.groupWraps[e].contains(r)&&this.scheduleHideFlyout()}),this.flyoutEl=n,this.flyoutIdx=e,this.host.appendChild(n),this.placeFlyout(n,this.groupButtons[e]),this.groupButtons[e].setAttribute(`aria-expanded`,`true`)}flyoutItems(){return this.flyoutEl?[...this.flyoutEl.querySelectorAll(`.tcw-flyout-item`)]:[]}focusFlyoutItem(e){let t=this.flyoutItems();t.length!==0&&t[(e+t.length)%t.length].focus()}onFlyoutKey(e,t){let n=this.flyoutItems(),r=n.indexOf(document.activeElement);switch(e.key){case`ArrowDown`:this.focusFlyoutItem(r+1);break;case`ArrowUp`:this.focusFlyoutItem(r-1);break;case`Home`:this.focusFlyoutItem(0);break;case`End`:this.focusFlyoutItem(n.length-1);break;case`Escape`:case`ArrowLeft`:e.stopPropagation(),this.hideFlyout(),this.groupButtons[t]?.focus();break;case`Tab`:this.hideFlyout(),this.groupButtons[t]?.focus();return;default:return}e.preventDefault()}placeFlyout(e,t){let n=this.host.getBoundingClientRect(),r=t.getBoundingClientRect();e.style.maxHeight=`${Math.max(0,this.host.clientHeight-hn*2)}px`;let i=this.host.clientHeight-e.offsetHeight-hn;this.host.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?(e.style.left=``,e.style.right=`${n.right-r.left}px`):(e.style.right=``,e.style.left=`${r.right-n.left}px`),e.style.top=`${Math.max(0,Math.min(r.top-n.top,i))}px`}scheduleHideFlyout(){this.cancelHideFlyout(),this.flyoutHideTimer=setTimeout(()=>{this.flyoutHideTimer=null,this.hideFlyout()},mn)}cancelHideFlyout(){this.flyoutHideTimer!==null&&(clearTimeout(this.flyoutHideTimer),this.flyoutHideTimer=null)}hideFlyout(){this.cancelHideFlyout(),this.flyoutEl&&=(this.flyoutEl.remove(),null),this.groupButtons[this.flyoutIdx]?.setAttribute(`aria-expanded`,`false`),this.flyoutIdx=-1}update(e){this.cursorBtn&&this.cursorBtn.classList.toggle(`tcw-active`,e.activeTool===null);let t=e.activeTool??``;t!==this.fabShows&&(this.fabShows=t,this.fab.innerHTML=e.activeTool?tt(e.activeTool,18):O(`penLine`,18)),this.fab.classList.toggle(`tcw-active`,e.activeTool!==null||e.eraser||e.zoomArea);let{drawingToolGroups:n}=this.config;for(let t=0;t<n.length;t++){let r=n[t].tools.some(t=>t.value===e.activeTool);this.groupButtons[t].classList.toggle(`tcw-active`,r),r&&e.activeTool&&e.activeTool!==this.groupTools[t]&&(this.groupTools[t]=e.activeTool,this.groupIcons[t].innerHTML=tt(e.activeTool,pn),n[t].tools.length>1&&this.groupButtons[t].setAttribute(`aria-label`,`${n[t].label}: ${_n(n,e.activeTool)}`))}if(this.flyoutEl&&this.flyoutEl.querySelectorAll(`.tcw-flyout-item`).forEach(t=>{let n=t;n.classList.toggle(`tcw-active`,n.dataset.toolValue===e.activeTool)}),this.magnetBtn){let t=e.magnetEnabled&&e.magnetStrong;this.magnetBtn.classList.toggle(`tcw-active`,e.magnetEnabled),this.magnetBtn.innerHTML=O(t?`magnetStrong`:`magnet`,14),this.magnetBtn.title=t?this.t(`drawing.magnetStrong`):e.magnetEnabled?this.t(`drawing.magnetOn`):this.t(`drawing.magnetOff`),this.magnetBtn.setAttribute(`aria-label`,this.magnetBtn.title)}for(let[t,n]of[[this.eraserBtn,e.eraser],[this.zoomBtn,e.zoomArea]])t&&(t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n)));this.stayBtn&&(this.stayBtn.classList.toggle(`tcw-active`,e.stayInDrawing),this.stayBtn.setAttribute(`aria-pressed`,String(e.stayInDrawing)))}addHostButton(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-sidebar-btn tcw-host-btn`,t.dataset.hostButton=e.id,t.title=e.label,t.setAttribute(`aria-label`,e.label),e.toggle&&t.setAttribute(`aria-pressed`,`false`),typeof e.icon==`string`?t.innerHTML=O(e.icon,14):t.appendChild(e.icon),t.addEventListener(`click`,()=>e.onClick(t)),this.hostEl?.appendChild(t),this.tidy(),t}hostSlot(){return this.hostEl}tidy(){Je(this.el,`tcw-sidebar-divider`,`tcw-sidebar-spacer`)}toggleButton(e,t,n){let r=document.createElement(`button`);return r.className=`tcw-sidebar-btn`,r.title=t,r.setAttribute(`aria-label`,t),r.setAttribute(`aria-pressed`,`false`),r.innerHTML=O(e,14),r.addEventListener(`click`,n),r}appendDivider(){this.el.lastElementChild?.classList.contains(`tcw-sidebar-divider`)||this.el.appendChild(this.divider())}divider(){let e=document.createElement(`div`);return e.className=`tcw-sidebar-divider`,e}destroy(){this.setOpen(!1),this.hideFlyout(),this.fab.remove(),this.el.remove()}},bn=`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function M(e,t){if(e.key!==`Tab`)return;let n=document.activeElement,r=[...t.querySelectorAll(bn)].filter(e=>e.tabIndex>=0&&(e.getClientRects().length>0||e===n));if(r.length===0)return;let i=r[0],a=r[r.length-1],o=n instanceof Node&&t.contains(n),s=(e,t)=>(e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_PRECEDING)!==0;e.shiftKey&&(!o||n===i||s(i,n))?(e.preventDefault(),a.focus()):!e.shiftKey&&(!o||n===a||s(n,a))&&(e.preventDefault(),i.focus())}function N(e,t){let n=document.createElement(`label`);n.className=`tcw-settings-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=e,n.append(r,t),n}function xn(e,t,n){let r=document.createElement(`label`);r.className=`tcw-settings-row tcw-check-row`;let i=document.createElement(`input`);i.type=`checkbox`,i.checked=t,i.addEventListener(`change`,()=>n(i.checked));let a=document.createElement(`span`);return a.className=`tcw-settings-label`,a.textContent=e,r.append(i,a),r}function Sn(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-toggle${e?` tcw-on`:``}`,n.setAttribute(`role`,`switch`),n.setAttribute(`aria-checked`,String(e)),n.addEventListener(`click`,()=>{let e=!n.classList.contains(`tcw-on`);n.classList.toggle(`tcw-on`,e),n.setAttribute(`aria-checked`,String(e)),t(e)}),n}function P(e,t,n){let r=document.createElement(`input`);return r.type=`number`,r.className=`tcw-indi-input`,r.value=String(e),r.step=String(t.step??(Number.isInteger(e)?1:.001)),t.min!==void 0&&(r.min=String(t.min)),t.max!==void 0&&(r.max=String(t.max)),r.addEventListener(`change`,()=>{if(r.value.trim()===``)return;let e=Number(r.value);Number.isFinite(e)&&(t.whole&&(e=Math.round(e)),t.min!==void 0&&(e=Math.max(t.min,e)),t.max!==void 0&&(e=Math.min(t.max,e)),r.value=String(e),n(e))}),r}function F(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=Cn(e),n.addEventListener(`input`,()=>t(n.value)),n}function I(e,t,n){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;for(let t of e){let e=document.createElement(`option`);e.value=t.value,e.textContent=t.label,r.appendChild(e)}return r.value=t,r.addEventListener(`change`,()=>n(r.value)),r}function Cn(e){if(typeof e!=`string`)return`#000000`;let t=e.trim();if(/^#[0-9a-f]{6}$/i.test(t))return t.toLowerCase();if(/^#[0-9a-f]{8}$/i.test(t))return t.slice(0,7).toLowerCase();if(/^#[0-9a-f]{3,4}$/i.test(t))return`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`.toLowerCase();let n=/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/i.exec(t);if(n)return`#${[n[1],n[2],n[3]].map(e=>Math.min(255,Number(e)).toString(16).padStart(2,`0`)).join(``)}`;let r=wn(t);return r!==null&&r!==t?Cn(r):`#000000`}var L;function wn(e){if(L===void 0)try{L=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):null}catch{L=null}if(!L)return null;L.fillStyle=`#010203`,L.fillStyle=e;let t=String(L.fillStyle);return t===`#010203`?null:t}function Tn(e){if(typeof e!=`string`)return 1;let t=/^rgba\([^)]*,\s*([\d.]+)\s*\)$/i.exec(e.trim());return t?Math.max(0,Math.min(1,Number(t[1]))):1}function En(e,t){let n=Cn(e),[r,i,a]=[1,3,5].map(e=>parseInt(n.slice(e,e+2),16));return`rgba(${r}, ${i}, ${a}, ${Math.round(t*100)/100})`}var Dn={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1};function On(e,t,n,r){let i=document.createElement(`div`);i.className=`tcw-segmented`,i.setAttribute(`role`,`radiogroup`),i.setAttribute(`aria-label`,r);let a=e.map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-segment`,t.setAttribute(`role`,`radio`),t.dataset.value=e.value,t.textContent=e.label,t.addEventListener(`click`,()=>s(e.value)),t}),o=e=>{let t=Math.max(0,a.findIndex(t=>t.dataset.value===e));a.forEach((n,r)=>{n.setAttribute(`aria-checked`,String(n.dataset.value===e)),n.tabIndex=r===t?0:-1})},s=e=>{o(e),n(e)};return i.addEventListener(`keydown`,t=>{let n=a.findIndex(e=>e===t.target);if(n<0||t.altKey||t.ctrlKey||t.metaKey)return;let r=a.length-1,o;if(t.key===`Home`)o=0;else if(t.key===`End`)o=r;else if(t.key in Dn){let e=i.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`,r=t.key===`ArrowLeft`||t.key===`ArrowRight`;o=(n+(e&&r?-Dn[t.key]:Dn[t.key])+a.length)%a.length}else return;t.preventDefault(),a[o].focus(),s(e[o].value)}),o(t),i.append(...a),i}function kn(e,t,r){if(!(r>0)||!Number.isFinite(e))return e;let i=e/r,a=Math.round(i),o=Math.abs(i-a)<1e-9*Math.max(1,Math.abs(i)),s=t>0?o?a+1:Math.ceil(i):o?a-1:Math.floor(i);return s<1?e:Number((s*r).toFixed((0,n.stepDecimals)(r)))}function An(e,t){let n=document.createElement(`div`);n.className=`tcw-stepper`,n.dir=`ltr`;let r=n=>{let r=Number(e.value),i=e.value.trim()!==``&&Number.isFinite(r)?r:t.fallback?.()??0,a=kn(i,n,t.step(i,n));e.value=t.format?t.format(a):String(a),e.dispatchEvent(new Event(`input`))},i=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-stepper-btn`,n.tabIndex=-1,n.setAttribute(`aria-label`,t),n.innerHTML=O(e>0?`plus`:`minus`,14),n.addEventListener(`click`,()=>r(e)),n};e.addEventListener(`keydown`,e=>{e.key!==`ArrowUp`&&e.key!==`ArrowDown`||(e.preventDefault(),r(e.key===`ArrowUp`?1:-1))});let a=i(-1,t.labels.down),o=i(1,t.labels.up);return n.append(a,e,o),{element:n,down:a,up:o}}var jn=0,Mn=0,Nn=20;function Pn(e){let t=document.createElement(`div`);if(t.className=`tcw-settings-section`,e){let n=document.createElement(`div`);n.className=`tcw-settings-section-title`,n.textContent=e,t.appendChild(n),t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,e)}return t}function Fn(e){let t=document.createElement(`div`);t.className=`tcw-settings-row`;let n=document.createElement(`span`);return n.className=`tcw-settings-label`,n.textContent=e,t.appendChild(n),t}function In(e,t,n,r,i){let a=Fn(e),o=document.createElement(`div`);o.className=`tcw-color-picker-wrap`;let s=document.createElement(`input`);s.type=`color`,s.setAttribute(`aria-label`,e);let c=document.createElement(`span`);c.className=`tcw-color-hex`,c.id=`tcw-color-${++jn}`,s.setAttribute(`aria-describedby`,c.id);let l=null,u=t=>{s.value=Cn(t??r.start?.()),c.textContent=t??i(`settings.auto`),a.classList.toggle(`tcw-color-auto`,t===null),t!==null&&r.start&&!l?(l=document.createElement(`button`),l.type=`button`,l.className=`tcw-color-auto-btn`,l.textContent=i(`settings.auto`),l.setAttribute(`aria-label`,`${e}: ${i(`settings.auto`)}`),l.addEventListener(`click`,()=>{n(null),s.focus(),u(r.read())}),o.appendChild(l)):t===null&&l&&(l.remove(),l=null)};return s.addEventListener(`input`,()=>{n(s.value),u(s.value)}),o.append(s,c),a.appendChild(o),u(t),{row:a,sync:()=>u(r.read())}}function R(e,t,n){let r=Fn(e),i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-toggle${t?` tcw-on`:``}`,i.setAttribute(`role`,`switch`),i.setAttribute(`aria-checked`,String(t)),i.setAttribute(`aria-label`,e),i.addEventListener(`click`,()=>{let e=!i.classList.contains(`tcw-on`);i.classList.toggle(`tcw-on`,e),i.setAttribute(`aria-checked`,String(e)),n(e)}),r.appendChild(i),r}function z(e,t,n,r){let i=Fn(e),a=document.createElement(`select`);a.className=`tcw-settings-select`,a.setAttribute(`aria-label`,e);for(let e of n){let n=document.createElement(`option`);n.value=e.value,n.textContent=e.label,e.value===t&&(n.selected=!0),a.appendChild(n)}return n.some(e=>e.value===t)||(a.selectedIndex=-1),a.addEventListener(`change`,()=>r(a.value)),i.appendChild(a),i}function Ln(e,t,n,r,i=e=>String(e)){let a=Fn(e),o=document.createElement(`div`);o.className=`tcw-settings-range`;let s=document.createElement(`input`);s.type=`range`,s.min=String(n.min),s.max=String(n.max),s.step=String(n.step),s.value=String(t),s.setAttribute(`aria-label`,e);let c=document.createElement(`span`);return c.className=`tcw-settings-range-val`,c.textContent=i(t),s.addEventListener(`input`,()=>{let e=Number(s.value);c.textContent=i(e),r(e)}),o.append(s,c),a.appendChild(o),a}function Rn(e,n,r){let i=new Intl.NumberFormat(r,{maximumFractionDigits:Nn}).format;return e.step===`1`&&Number.isFinite(e.max)?t.r(n(`settings.numberWhole`),{min:i(Math.max(1,e.min??1)),max:i(e.max)}):t.r(n(`settings.numberAtLeast`),{min:i(e.min??0)})}function zn(e,t,n,r,i,a=`en-US`){let o=document.createElement(`div`);o.className=`tcw-settings-row tcw-settings-row--number`;let s=document.createElement(`label`);s.className=`tcw-settings-label`,s.textContent=e,o.appendChild(s);let c=document.createElement(`input`);c.type=`number`,c.className=`tcw-settings-number`,c.min=`0`,c.step=n.step,Number.isFinite(n.max)&&(c.max=String(n.max)),c.placeholder=i(`settings.auto`),c.value=t===null?``:String(t),c.setAttribute(`aria-label`,e);let l=document.createElement(`div`);l.className=`tcw-settings-hint`,l.id=`tcw-number-hint-${++Mn}`,l.setAttribute(`role`,`status`),c.setAttribute(`aria-describedby`,l.id);let u=e=>{e?c.removeAttribute(`aria-invalid`):c.setAttribute(`aria-invalid`,`true`),l.textContent=e?``:Rn(n,i,a)};return c.addEventListener(`change`,()=>{if(c.value.trim()===``){u(!0),r(null);return}let e=Number(c.value),t=Number.isFinite(e)&&e>0&&e>=(n.min??0)&&e<=n.max&&(n.step!==`1`||Number.isInteger(e));u(t),t&&r(e)}),o.append(c,l),o}var B=[{id:`symbol`,icon:`chartType:candlestick`},{id:`statusLine`,icon:`type`},{id:`scales`,icon:`ruler`},{id:`appearance`,icon:`palette`},{id:`layers`,icon:`layers`},{id:`trading`,icon:`trendingUp`}],Bn=[1,2,3,4],Vn=`t:`,Hn={step:`any`,max:1/0,min:1e-8},Un=1,Wn=class{callbacks;t;backdrop=null;modal=null;bodyEl=null;tabButtons=[];templateBtn=null;menu=null;currentTab=`symbol`;currentSettings=null;chartType=null;lookRows=[];returnFocus=null;uid=Un++;constructor(e,t,n={},r=()=>document.body){this.available=n,this.host=r,this.callbacks=e,this.t=t}open(e,t=null,n=`symbol`){this.modal&&this.remove(),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.currentSettings={...e},this.chartType=t,this.currentTab=n,this.buildModal(),this.tabButtons.find(e=>e.dataset.tab===n)?.focus()}isOpen(){return this.modal!==null}refresh(e,t){if(!this.modal)return;this.currentSettings={...e},t!==void 0&&(this.chartType=t);let n=this.focusedControl();this.renderTabContent(),n!==null&&this.focusControl(n)}focusedControl(){let e=document.activeElement;if(!this.bodyEl||!(e instanceof HTMLElement)||!this.bodyEl.contains(e))return null;let t=this.panelControls().indexOf(e);return t<0?null:t}focusControl(e){let t=this.panelControls();(t[Math.min(e,t.length-1)]??this.tabButtons.find(e=>e.dataset.tab===this.currentTab))?.focus()}panelControls(){return this.bodyEl?[...this.bodyEl.querySelectorAll(bn)]:[]}close(){this.finish(!0)}destroy(){this.remove()}finish(e){this.modal&&(e?this.callbacks.onClose():this.callbacks.onCancel?.(),this.remove(),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}remove(){this.menu?.destroy(),this.menu=null,this.backdrop?.remove(),this.backdrop=this.modal=this.bodyEl=this.templateBtn=null,this.tabButtons=[]}buildModal(){let e=document.createElement(`div`);e.className=`tcw-modal-backdrop`;let t=!1;e.addEventListener(`pointerdown`,n=>{t=n.target===e}),e.addEventListener(`click`,n=>{n.target===e&&t&&this.finish(!1),t=!1});let n=document.createElement(`div`);n.className=`tcw-modal tcw-set`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-labelledby`,`tcw-set-title-${this.uid}`),n.tabIndex=-1,n.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.finish(!1);return}M(e,n)}),this.backdrop=e,this.modal=n,n.append(this.buildHeader(),this.buildBody(),this.buildFooter()),e.appendChild(n),this.host().appendChild(e),this.markTabs(),this.renderTabContent()}buildHeader(){let e=document.createElement(`div`);e.className=`tcw-modal-header`;let t=document.createElement(`h3`);t.id=`tcw-set-title-${this.uid}`,t.textContent=this.t(`settings.title`);let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-modal-close`,n.setAttribute(`aria-label`,this.t(`common.close`)),n.innerHTML=O(`x`,16),n.addEventListener(`click`,()=>this.finish(!1)),e.append(t,n),e}buildBody(){let e=document.createElement(`div`);e.className=`tcw-set-body`;let t=document.createElement(`div`);t.className=`tcw-set-nav`,t.setAttribute(`role`,`tablist`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,this.t(`settings.title`)),t.addEventListener(`keydown`,e=>this.onTabKey(e)),this.tabButtons=B.map(({id:e,icon:t})=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-set-tab`,n.id=`tcw-set-tab-${this.uid}-${e}`,n.dataset.tab=e,n.setAttribute(`role`,`tab`),n.setAttribute(`aria-controls`,`tcw-set-panel-${this.uid}`),n.innerHTML=`${t.startsWith(`chartType:`)?nt(t.slice(10),16):O(t,16)}<span></span>`,n.querySelector(`span`).textContent=this.t(`settings.tab.${e}`),n.addEventListener(`click`,()=>this.selectTab(e)),n}),t.append(...this.tabButtons);let n=document.createElement(`div`);return n.className=`tcw-modal-body tcw-set-panel`,n.id=`tcw-set-panel-${this.uid}`,n.setAttribute(`role`,`tabpanel`),this.bodyEl=n,e.append(t,n),e}buildFooter(){let e=document.createElement(`div`);e.className=`tcw-modal-footer`;let t=this.footerButton(`template`,`tcw-footer-menu`,()=>this.openTemplates());t.setAttribute(`aria-haspopup`,`menu`),t.setAttribute(`aria-expanded`,`false`),t.innerHTML=`<span></span>${O(`chevronDown`,12)}`,t.querySelector(`span`).textContent=this.t(`settings.template`),this.templateBtn=t;let n=document.createElement(`div`);return n.className=`tcw-footer-end`,n.append(this.footerButton(`cancel`,`tcw-footer-cancel`,()=>this.finish(!1),this.t(`common.cancel`)),this.footerButton(`ok`,`tcw-done-btn`,()=>this.finish(!0),this.t(`drawingSettings.ok`))),e.append(t,n),e}footerButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=t,i.dataset.act=e,r&&(i.textContent=r),i.addEventListener(`click`,n),i}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.currentTab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl?.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.currentTab=e,this.markTabs(),this.renderTabContent(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=B.findIndex(e=>e.id===this.currentTab),n=e.key===`ArrowDown`||e.key===`ArrowRight`?(t+1)%B.length:e.key===`ArrowUp`||e.key===`ArrowLeft`?(t-1+B.length)%B.length:e.key===`Home`?0:e.key===`End`?B.length-1:-1;n<0||(e.preventDefault(),this.selectTab(B[n].id,!0))}openTemplates(){let e=this.templateBtn;if(!this.modal||!e)return;if(this.menu?.isOpen()){this.menu.close();return}let n=this.callbacks.templates,r=(n?.list()??[]).map(e=>({id:`${Vn}${e}`,label:e,icon:`layers`,remove:t.r(this.t(`templates.delete`),{name:e})})),i=[...r,...r.length>0?[`separator`]:[],...n?[{id:`save`,label:this.t(`settings.saveTemplate`),icon:`save`}]:[],{id:`reset`,label:this.t(`settings.resetToDefaults`),icon:`reset`}];this.menu??=new A(this.modal,this.t(`settings.template`));let a=e.getBoundingClientRect(),o=this.modal.getBoundingClientRect();this.menu.open(i,a.left-o.left,a.top-o.top,e=>{e===`reset`?this.callbacks.onReset():e===`save`?n?.save():e.startsWith(Vn)&&n?.apply(e.slice(2))},e,e=>n?.remove(e.slice(2)))}renderTabContent(){if(!(!this.bodyEl||!this.currentSettings))switch(this.bodyEl.replaceChildren(),this.lookRows=[],this.currentTab){case`symbol`:this.renderSymbolTab(this.currentSettings);break;case`statusLine`:this.renderStatusLineTab(this.currentSettings);break;case`scales`:this.renderScalesTab(this.currentSettings);break;case`appearance`:this.renderAppearanceTab(this.currentSettings);break;case`layers`:this.renderLayersTab(this.currentSettings);break;case`trading`:for(let e of Te)(!e.trading||this.available.trading!==!1)&&this.renderLookSection(e);break}}renderSymbolTab(e){this.renderChartTypeSection(),this.addSection(void 0,[R(this.t(`settings.mainSeries`),e.mainSeriesVisible,e=>this.patch({mainSeriesVisible:e})),R(this.t(`settings.extendedHours`),e.extendedHours,e=>this.patch({extendedHours:e}))]);let t=this.t(`common.show`);this.renderLookSection(_e),this.available.volume!==!1&&this.renderLookSection(ve,[R(t,e.volumeVisible,e=>this.patch({volumeVisible:e}))]),this.renderLookSection(ye,[R(t,e.highLowLines,e=>this.patch({highLowLines:e}))])}renderStatusLineTab(e){let t=this.available.legend!==!1,n=t?Se:Se.filter(e=>!xe.includes(e));this.addSection(void 0,[...t?[R(this.t(`settings.ohlcLegend`),e.legendVisible,e=>this.patch({legendVisible:e}))]:[],...n.map(e=>this.lookRow(e))])}renderScalesTab(e){let t=[{value:`regular`,label:this.t(`settings.scale.regular`)},{value:`logarithmic`,label:this.t(`settings.scale.logarithmic`)},{value:`percentage`,label:this.t(`settings.scale.percentage`)},{value:`indexedTo100`,label:this.t(`settings.scale.indexedTo100`)}].filter(e=>e.value!==`logarithmic`||this.available.logScale!==!1),n=this.available.exchangeZone?.(),r=f(e.timezone,Date.now(),this.t(`settings.timezone.local`),n===void 0?void 0:{label:this.t(`settings.timezone.exchange`),zone:n});this.addSection(void 0,[z(this.t(`settings.priceScale`),e.scaleMode,t,e=>this.patch({scaleMode:e})),R(this.t(`settings.autoScale`),e.autoScale,e=>this.patch({autoScale:e})),R(this.t(`settings.invertScale`),e.invertScale,e=>this.patch({invertScale:e})),R(this.t(`settings.leftScale`),e.leftPriceScale,e=>this.patch({leftPriceScale:e})),R(this.t(`settings.indicatorValues`),e.indicatorValueLabels,e=>this.patch({indicatorValueLabels:e})),R(this.t(`settings.alignAxisLabels`),e.alignAxisLabels,e=>this.patch({alignAxisLabels:e})),...this.available.barCountdown===!1?[]:[R(this.t(`settings.barCountdown`),e.barCountdown,e=>this.patch({barCountdown:e}))],z(this.t(`settings.timezone`),e.timezone,r,e=>this.patch({timezone:e})),z(this.t(`settings.numberLocale`),e.numberLocale,gt(e.numberLocale),e=>this.patch({numberLocale:e}))]),this.addSection(this.t(`settings.section.axes`),Ce.map(e=>this.lookRow(e)))}renderAppearanceTab(e){let[t,n,r,...i]=we;this.renderLookSection(t),this.renderLookSection(n,[R(this.t(`common.show`),e.gridVisible,e=>this.patch({gridVisible:e}))]),this.renderLookSection(r,[z(this.t(`settings.crosshairMode`),e.crosshairMode,[{label:this.t(`settings.crosshair.magnet`),value:`magnet`},{label:this.t(`settings.crosshair.normal`),value:`normal`},{label:this.t(`settings.crosshair.hidden`),value:`hidden`}],e=>this.patch({crosshairMode:e}))]);for(let e of i)this.renderLookSection(e)}renderLayersTab(e){let t=e=>`${Math.round(e*100)}%`,n=e=>this.t(e);this.addSection(void 0,[R(n(`settings.volumeProfile`),e.volumeProfileVisible,e=>this.patch({volumeProfileVisible:e}))]),this.addSection(void 0,[R(n(`settings.marketProfile`),e.marketProfileVisible,e=>this.patch({marketProfileVisible:e})),R(n(`settings.marketProfileSplit`),e.marketProfileSplit,e=>this.patch({marketProfileSplit:e})),R(n(`settings.marketProfileLetters`),e.marketProfileLetters,e=>this.patch({marketProfileLetters:e})),Ln(n(`settings.marketProfileBuckets`),e.marketProfileBuckets,{min:8,max:200,step:1},e=>this.patch({marketProfileBuckets:e})),Ln(n(`settings.marketProfileOpacity`),e.marketProfileOpacity,{min:.05,max:1,step:.05},e=>this.patch({marketProfileOpacity:e}),t)]),this.addSection(void 0,[R(n(`settings.depthHeatmap`),e.depthHeatmapVisible,e=>this.patch({depthHeatmapVisible:e})),Ln(n(`settings.depthHeatmapOpacity`),e.depthHeatmapOpacity,{min:.1,max:1,step:.05},e=>this.patch({depthHeatmapOpacity:e}),t)]),this.addSection(void 0,[R(n(`settings.swingMarkers`),e.pivotMarkersVisible,e=>this.patch({pivotMarkersVisible:e})),Ln(n(`settings.swingStrength`),e.pivotStrength,{min:2,max:20,step:1},e=>this.patch({pivotStrength:e})),R(n(`settings.swingStructure`),e.pivotStructureLabels,e=>this.patch({pivotStructureLabels:e}))]),this.addSection(void 0,[R(n(`settings.sessionShading`),e.sessionShadingVisible,e=>this.patch({sessionShadingVisible:e})),R(n(`settings.periodLevels`),e.periodLevelsVisible,e=>this.patch({periodLevelsVisible:e})),z(n(`settings.periodLevelsBasis`),e.periodLevelsPeriod,[{value:`day`,label:n(`settings.priorDay`)},{value:`week`,label:n(`settings.priorWeek`)}],e=>this.patch({periodLevelsPeriod:e}))])}addSection(e,t){let n=Pn(e);return n.append(...t),this.bodyEl?.appendChild(n),n}renderLookSection(e,t=[]){this.addSection(this.t(e.title),[...t,...e.rows.map(e=>this.lookRow(e))])}lookRow(e){let t=this.t(e.label),r=()=>this.callbacks.styleValue(e.keys[0]),i=()=>{let t=e.keys.map(e=>this.callbacks.styleValue(e));return t.every(e=>e===t[0])&&t[0]!==null?String(t[0]):``},a,o=t=>{this.callbacks.onStyleChange(Object.fromEntries(e.keys.map(e=>[e,t])));for(let e of this.lookRows)e.el!==a&&e.sync()},s=e.auto?[{value:``,label:this.t(`settings.auto`)}]:[],c;switch(n.CHART_STYLE_KEYS[e.keys[0]]){case`boolean`:{a=R(t,r()===!0,o);let e=a.querySelector(`button`);c=()=>{let t=r()===!0;e.classList.toggle(`tcw-on`,t),e.setAttribute(`aria-checked`,String(t))};break}case`lineStyle`:a=z(t,i(),[...s,...this.lineStyles()],e=>o(e===``?null:Kn(e))),c=()=>{a.querySelector(`select`).value=i()};break;case`width`:{let e=r(),n=typeof e==`number`&&!Bn.includes(e)?[...Bn,e].sort((e,t)=>e-t):Bn;a=z(t,i(),[...s,...n.map(e=>({value:String(e),label:`${e}px`}))],e=>o(e===``?null:Number(e))),c=()=>{a.querySelector(`select`).value=i()};break}default:{let n=r(),i=In(t,typeof n==`string`?n:null,o,{read:()=>{let e=r();return typeof e==`string`?e:null},start:e.auto?()=>(e.auto?.from?this.callbacks.styleValue(e.auto.from):e.auto?.hint)??null:void 0},this.t);a=i.row,c=i.sync}}return this.lookRows.push({el:a,sync:c}),a}lineStyles(){return[{value:`solid`,label:this.t(`drawingSettings.lineStyle.solid`)},{value:`dashed`,label:this.t(`drawingSettings.lineStyle.dashed`)},{value:`dotted`,label:this.t(`drawingSettings.lineStyle.dotted`)}]}renderChartTypeSection(){if(!this.bodyEl||!this.currentSettings||!this.chartType)return;let e=this.chartType,t=this.currentSettings.chartTypeOptions??{},n=fe.find(t=>t.value===e),r=Pn(n?vt(n,this.t):e),i=()=>this.currentSettings?.chartTypeOptions??{},a=(e,t)=>this.patch({chartTypeOptions:{...i(),[e]:t}}),o=(e,t,n,i)=>r.appendChild(zn(this.t(e),t,n,i,this.t,this.currentSettings?.numberLocale||void 0));switch(e){case`renko`:{let e=t.renko??{};o(`settings.boxSize`,typeof e.boxSize==`number`?e.boxSize:null,Hn,e=>a(`renko`,{...i().renko??{},boxSize:e??`atr`})),o(`settings.atrPeriod`,e.atrPeriod??null,{step:`1`,max:500},e=>a(`renko`,Gn(i().renko,`atrPeriod`,e)));break}case`lineBreak`:o(`settings.lineBreakLines`,t.lineBreak?.lines??null,{step:`1`,max:10},e=>a(`lineBreak`,Gn(i().lineBreak,`lines`,e)));break;case`kagi`:o(`settings.reversal`,t.kagi?.reversal??null,Hn,e=>a(`kagi`,Gn(i().kagi,`reversal`,e))),r.appendChild(z(this.t(`settings.reversalType`),t.kagi?.reversalType??`percent`,[{value:`percent`,label:this.t(`settings.reversalType.percent`)},{value:`price`,label:this.t(`settings.reversalType.price`)}],e=>a(`kagi`,{...i().kagi??{},reversalType:e===`price`?`price`:`percent`})));break;case`pointAndFigure`:o(`settings.boxSize`,typeof t.pointAndFigure?.boxSize==`number`?t.pointAndFigure.boxSize:null,Hn,e=>a(`pointAndFigure`,{...i().pointAndFigure??{},boxSize:e??`auto`})),o(`settings.reversalBoxes`,t.pointAndFigure?.reversal??null,{step:`1`,max:10},e=>a(`pointAndFigure`,Gn(i().pointAndFigure,`reversal`,e)));break;case`rangeBars`:o(`settings.barRange`,typeof t.rangeBars?.range==`number`?t.rangeBars.range:null,Hn,e=>a(`rangeBars`,{range:e??`auto`}));break;default:break}for(let t of Oe(e))r.appendChild(this.lookRow(t));this.bodyEl.appendChild(r)}patch(e){this.currentSettings&&Object.assign(this.currentSettings,e),this.callbacks.onChange(e)}};function Gn(e,t,n){let r={...e??{}};return n===null?delete r[t]:r[t]=n,r}function Kn(e){return e===`dashed`||e===`dotted`?e:`solid`}var qn=`data-tcw-folded`,Jn=`tcw-statusbar--folded`,Yn=`tcw-statusbar--short-market`,Xn=1,Zn=13,Qn=`goto`,$n=`Alt+G`,er=e=>e.goToKeys?e.goToKeys():$n;function tr(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}var nr=class{el;dotEl;messageEl;marketEl;hostLeft;hostRight;clockBtn=null;clockMenu=null;scaleBtns=null;scaleShown=``;marketShown=``;rightEl;rangeEl=null;presetBtns=[];moreBtn=null;goToBtn=null;rangeMenu=null;resizeObserver=null;fitFrame=0;destroyed=!1;constructor(e,t,n={}){this.host=e,this.extras=n,this.el=document.createElement(`div`),this.el.className=`tcw-statusbar`,D(this.el,`statusBar`),n.label&&(this.el.setAttribute(`role`,`group`),this.el.setAttribute(`aria-label`,n.label)),t&&this.el.appendChild(this.buildRange(t)),this.hostLeft=this.hostGroup(),this.el.appendChild(this.hostLeft);let r=document.createElement(`div`);r.className=`tcw-status-right`,this.rightEl=r,this.hostRight=this.hostGroup(),r.appendChild(this.hostRight);let i=document.createElement(`div`);i.className=`tcw-status-indicator`,D(i,`statusBar.connection`),this.dotEl=document.createElement(`span`),this.dotEl.className=`tcw-status-dot`,i.appendChild(this.dotEl),this.messageEl=document.createElement(`span`),i.appendChild(this.messageEl),this.marketEl=document.createElement(`span`),this.marketEl.className=`tcw-status-market`,this.marketEl.hidden=!0,D(this.marketEl,`statusBar.market`),r.appendChild(this.marketEl),r.appendChild(i),n.clock&&r.appendChild(this.buildClock(n.clock)),n.scale&&r.appendChild(this.buildScale(n.scale)),this.el.appendChild(r),e.appendChild(this.el),this.watchWidths(r)}watchWidths(e){if(typeof ResizeObserver<`u`){this.resizeObserver=new ResizeObserver(()=>this.scheduleFit());for(let t of[this.el,e,this.hostLeft])this.resizeObserver.observe(t)}document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.destroyed||this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.destroyed||this.fit()}))}fit(){let e=this.foldedCount(),t=this.rangeFocus();this.refit(),this.foldedCount()!==e&&this.rangeMenu?.close(),this.keepFocus(t)}refit(){let e=this.foldSteps(),t=this.goToBtn?[...this.presetBtns,this.goToBtn]:this.presetBtns,n=n=>{let r=new Set(e.slice(0,n));for(let e of t)e.toggleAttribute(qn,r.has(e));this.el.classList.toggle(Jn,n>0)};if(n(0),this.el.classList.remove(Yn),this.el.clientWidth===0||this.fits())return;let r=0;for(;r<e.length;)if(n(++r),this.fits())return;if(!(this.marketEl.hidden||this.isOff(this.marketEl))){for(this.el.classList.add(Yn);r>0;r--)if(n(r-1),!this.fits()){n(r);return}}}fits(){return this.rangeFits()&&this.rightFits()}rangeFits(){let e=this.rangeEl;return!e||e.scrollWidth<=e.clientWidth+Xn}rightFits(){if(this.rightEl.offsetParent!==this.el)return!0;let e=getComputedStyle(this.el),t=this.rightEl.offsetLeft;return(e.direction===`rtl`?(parseFloat(e.paddingLeft)||0)-t:t+this.rightEl.offsetWidth-(this.el.clientWidth-(parseFloat(e.paddingRight)||0)))<=Xn}foldedCount(){return this.rangeEl?.querySelectorAll(`[${qn}]`).length??0}rangeFocus(){if(this.rangeMenu?.hasFocus())return this.moreBtn;let e=document.activeElement;return e instanceof HTMLElement&&this.rangeEl?.contains(e)?e:null}keepFocus(e){if(!e||this.rangeMenu?.isOpen())return;let t=this.focusAfterRefit(e);t===this.el?this.focusBar():document.activeElement!==t&&t.focus({preventScroll:!0})}focusAfterRefit(e){if(this.shows(e))return e;let t=this.presetBtns.filter(e=>this.shows(e)).at(-1);return[e===this.moreBtn?null:this.moreBtn,this.goToBtn,t].find(e=>e!=null&&this.shows(e))??this.firstOtherControl()??this.el}firstOtherControl(){return[...this.el.querySelectorAll(`button`)].filter(e=>!this.rangeEl?.contains(e)).find(e=>!e.disabled&&e.getClientRects().length>0)??null}focusBar(){if(document.activeElement===this.el)return;let e=()=>this.el.removeAttribute(`tabindex`);this.el.tabIndex=-1,this.el.addEventListener(`blur`,e,{once:!0}),this.el.focus({preventScroll:!0}),document.activeElement!==this.el&&(this.el.removeEventListener(`blur`,e),e())}shows(e){return e===this.moreBtn&&!this.el.classList.contains(Jn)?!1:!e.hasAttribute(qn)&&!this.isOff(e)}foldSteps(){if(this.presetBtns.length===0||this.isOff(this.presetBtns[0]))return[];let e=[...this.presetBtns].reverse();return this.goToBtn&&e.push(this.goToBtn),e}isOff(e){let t=((this.el.closest(`.tcw-root`)??this.host).getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean);return(e.dataset.tcwPart??``).split(/\s+/).some(e=>t.includes(e))}update(e){this.dotEl.className=`tcw-status-dot`,e.connectionState===`connected`?this.dotEl.classList.add(`tcw-connected`):e.connectionState===`error`&&this.dotEl.classList.add(`tcw-error`),this.messageEl.textContent=e.message}tick(){if(!this.clockBtn||!this.extras.clock)return;let{time:e,zone:t}=this.extras.clock.now(),n=`${e} ${t}`;this.clockBtn.textContent!==n&&(this.clockBtn.textContent=n)}setScale(e){let t=`${e.mode}|${e.auto}`;!this.scaleBtns||t===this.scaleShown||(this.scaleShown=t,this.scaleBtns.percent?.setAttribute(`aria-pressed`,String(e.mode===`percentage`)),this.scaleBtns.log?.setAttribute(`aria-pressed`,String(e.mode===`logarithmic`)),this.scaleBtns.auto?.setAttribute(`aria-pressed`,String(e.auto)))}setMarket(e,t,n=t){let r=`${e}|${t}|${n}`;if(r===this.marketShown)return;if(this.marketShown=r,this.marketEl.hidden=e===`always`,this.marketEl.dataset.state=e,e===`always`){this.marketEl.replaceChildren(),this.marketEl.removeAttribute(`title`);return}this.marketEl.title=t;let i=tr(`tcw-status-market-short`,n);i.setAttribute(`aria-hidden`,`true`),this.marketEl.replaceChildren(tr(`tcw-status-market-text`,t),i)}addHostItem(e){let t=e.onClick,n=t?document.createElement(`button`):document.createElement(`span`);return n.className=t?`tcw-status-host-item tcw-status-host-btn`:`tcw-status-host-item`,n.dataset.hostItem=e.id,n.dir=`auto`,n.textContent=e.text,e.label&&(n.title=e.label,t||n.setAttribute(`role`,`group`),e.label!==e.text&&n.setAttribute(`aria-label`,`${e.label}: ${e.text}`)),n instanceof HTMLButtonElement&&t&&(n.type=`button`,n.addEventListener(`click`,()=>t(n))),(e.side===`left`?this.hostLeft:this.hostRight).appendChild(n),n}hostSlot(e){return e===`left`?this.hostLeft:this.hostRight}destroy(){this.destroyed=!0,this.resizeObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.clockMenu?.destroy(),this.rangeMenu?.destroy(),this.el.remove()}buildClock(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-status-clock`,t.dataset.role=`clock`,t.dir=`auto`,t.title=e.label,t.setAttribute(`aria-haspopup`,`menu`),D(t,`statusBar.clock`),t.addEventListener(`click`,()=>this.toggleZones(t,e)),this.clockBtn=t,this.tick(),t}toggleRangeMenu(e,t){if(this.rangeMenu?.isOpen()){this.rangeMenu.close();return}let n=e=>e.hasAttribute(qn)&&!this.isOff(e),r=t.presets.filter((e,t)=>n(this.presetBtns[t])).map(e=>({id:e,label:t.presetLabels?.[e]??e}));if(this.goToBtn&&n(this.goToBtn)&&(r.length>0&&r.push(`separator`),r.push({id:Qn,label:t.goToLabel,icon:`calendar`,shortcut:er(t)})),r.length===0)return;this.rangeMenu??=new A(this.host,t.groupLabel);let i=e.getBoundingClientRect(),a=this.host.getBoundingClientRect();this.rangeMenu.open(r,i.left-a.left,i.top-a.top,e=>e===Qn?t.onGoTo():t.onPreset(e),e,void 0,i.right-a.left)}toggleZones(e,t){if(this.clockMenu?.isOpen()){this.clockMenu.close();return}let{current:n,list:r}=t.options();this.clockMenu??=new A(this.host,t.label);let i=e.getBoundingClientRect(),a=this.host.getBoundingClientRect();this.clockMenu.open(r.map(e=>({id:e.value,label:e.label,checked:e.value===n})),i.left-a.left,i.top-a.top,e=>t.onPick(e),e,void 0,i.right-a.left)}buildScale(e){let t=document.createElement(`div`);t.className=`tcw-status-scale`,t.setAttribute(`role`,`group`),e.labels.group&&t.setAttribute(`aria-label`,e.labels.group),D(t,`statusBar.scale`);let n=(n,r,i)=>{let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-status-scale-btn`,a.dataset.scale=n,a.textContent=r,a.title=e.labels[n],a.setAttribute(`aria-label`,e.labels[n]),a.setAttribute(`aria-pressed`,`false`),a.addEventListener(`click`,i),t.appendChild(a),a};return this.scaleBtns={percent:n(`percent`,`%`,e.onPercent),...e.onLog?{log:n(`log`,e.texts?.log??`log`,e.onLog)}:{},auto:n(`auto`,e.texts?.auto??`auto`,e.onAuto)},t}hostGroup(){let e=document.createElement(`div`);return e.className=`tcw-status-host`,e}buildRange(e){let t=document.createElement(`div`);t.className=`tcw-range-bar`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,e.groupLabel);for(let n of e.presets){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-range-btn`,r.dataset.range=n,D(r,`statusBar.range`),r.textContent=e.presetLabels?.[n]??n,r.addEventListener(`click`,()=>e.onPreset(n)),t.appendChild(r),this.presetBtns.push(r)}let n=this.rangeIconBtn(`tcw-range-more`,`rangeMore`,`more`,e.moreLabel);D(n,`statusBar.range`),n.setAttribute(`aria-haspopup`,`menu`),n.setAttribute(`aria-expanded`,`false`),n.addEventListener(`click`,()=>this.toggleRangeMenu(n,e)),t.appendChild(n),this.moreBtn=n;let r=this.rangeIconBtn(`tcw-range-goto`,`goto`,`calendar`,e.goToLabel);D(r,`goToDate`,`statusBar.goToDate`);let i=()=>{let t=er(e);r.title=t?`${e.goToLabel} (${t})`:e.goToLabel};return i(),r.addEventListener(`pointerover`,i),r.addEventListener(`focusin`,i),r.addEventListener(`click`,e.onGoTo),t.appendChild(r),this.goToBtn=r,this.rangeEl=t,t}rangeIconBtn(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-range-btn ${e}`,i.dataset.role=t,i.title=r,i.setAttribute(`aria-label`,r),i.innerHTML=O(n,Zn),i}},rr=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent)?`⌘`:`Ctrl`,ir=e=>e.toLowerCase().replace(/[\s+]+/g,``).replace(/[\u2010-\u2015\u2212]/g,`-`),ar=5,or=229,sr=[`action`,`drawing`,`chartType`,`timeframe`,`indicator`],cr={indicator:`palette.group.indicator`,chartType:`palette.group.chartType`,drawing:`palette.group.drawing`,timeframe:`palette.group.timeframe`,action:`palette.group.action`},lr=e=>`${e.category}:${e.id}`;function ur(e,t){let n=e.label.toLowerCase(),r=ir(n);return e.id.toLowerCase()===t||r===t?5:r.startsWith(t)?4:n.split(/[\s/()-]+/).some(e=>e.startsWith(t))?3:r.includes(t)||e.id.toLowerCase().includes(t)?2:e.shortcut&&ir(e.shortcut).includes(t)?1:0}var dr=0,fr=class{backdrop=null;input=null;list=null;emptyEl=null;liveEl=null;items=[];shown=[];selectedIndex=0;returnFocus=null;uid=++dr;constructor(e,n=()=>document.body,r=t.t,i){this.callbacks=e,this.host=n,this.t=r,this.recents=i}open(e){this.backdrop||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.items=e,this.build(),this.render(),this.input?.focus())}close(){if(!this.backdrop)return;this.backdrop.remove(),this.backdrop=this.input=this.list=this.emptyEl=this.liveEl=null,this.callbacks.onClose();let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}isOpen(){return this.backdrop!==null}destroy(){this.close()}build(){let e=document.createElement(`div`);e.className=`tcw-modal-backdrop`;let t=!1;e.addEventListener(`pointerdown`,n=>{t=n.target===e}),e.addEventListener(`click`,n=>{n.target===e&&t&&this.close(),t=!1});let n=document.createElement(`div`);n.className=`tcw-modal tcw-cp`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-label`,this.t(`hotkeys.commandPalette`)),n.tabIndex=-1,n.addEventListener(`keydown`,e=>this.onKeyDown(e,n));let r=document.createElement(`label`);r.className=`tcw-ss-search tcw-cp-search`,r.innerHTML=O(`search`,16);let i=document.createElement(`input`);i.type=`search`,i.className=`tcw-cp-input`,i.placeholder=this.t(`palette.placeholder`),i.setAttribute(`aria-label`,this.t(`palette.placeholder`)),i.setAttribute(`role`,`combobox`),i.setAttribute(`aria-expanded`,`true`),i.setAttribute(`aria-autocomplete`,`list`),i.setAttribute(`aria-controls`,`tcw-cp-list-${this.uid}`),i.autocomplete=`off`,i.spellcheck=!1,i.addEventListener(`input`,()=>this.render()),r.appendChild(i);let a=document.createElement(`div`);a.className=`tcw-cp-results`;let o=document.createElement(`div`);o.className=`tcw-cp-list`,o.id=`tcw-cp-list-${this.uid}`,o.setAttribute(`role`,`listbox`),o.setAttribute(`aria-label`,this.t(`hotkeys.commandPalette`));let s=document.createElement(`div`);s.className=`tcw-cp-empty`,a.append(o,s),a.addEventListener(`mousedown`,e=>e.preventDefault());let c=document.createElement(`div`);c.className=`tcw-cp-live tcw-visually-hidden`,c.setAttribute(`aria-live`,`polite`),n.append(r,a,c),e.appendChild(n),this.host().appendChild(e),this.backdrop=e,this.input=i,this.list=o,this.emptyEl=s,this.liveEl=c}groups(){let e=ir((this.input?.value??``).trim()),t=[];if(!e){let e=new Map(this.items.map(e=>[lr(e),e])),n=(this.recents?.list()??[]).map(t=>e.get(t)).filter(e=>!!e).slice(0,ar);n.length>0&&t.push({key:`recent`,label:this.t(`palette.group.recent`),items:n})}for(let n of sr){let r=this.items.filter(e=>e.category===n);e&&(r=r.map((t,n)=>({item:t,at:n,s:ur(t,e)})).filter(e=>e.s>0).sort((e,t)=>t.s-e.s||e.at-t.at).map(e=>e.item)),r.length>0&&t.push({key:n,label:this.t(cr[n]),items:r})}return e&&t.sort((t,n)=>ur(n.items[0],e)-ur(t.items[0],e)),t}render(){let e=this.list;if(!e)return;let t=this.groups();this.shown=t.flatMap(e=>e.items),this.selectedIndex=0;let n=0;e.replaceChildren(...t.map(e=>{let t=document.createElement(`div`);t.setAttribute(`role`,`group`),t.className=`tcw-cp-group`;let r=document.createElement(`div`);return r.className=`tcw-cp-heading`,r.id=`tcw-cp-${e.key}-${this.uid}`,r.setAttribute(`role`,`presentation`),r.textContent=e.label,t.setAttribute(`aria-labelledby`,r.id),t.append(r,...e.items.map(e=>this.row(e,n++))),t}));let r=this.shown.length===0?this.t(`palette.empty`):``;this.emptyEl&&(this.emptyEl.textContent=r),this.emptyEl?.toggleAttribute(`hidden`,this.shown.length>0),this.liveEl&&(this.liveEl.textContent=r),this.markSelection()}row(e,t){let n=document.createElement(`div`);n.className=`tcw-cp-row`,n.id=`tcw-cp-opt-${this.uid}-${t}`,n.dataset.id=e.id,n.setAttribute(`role`,`option`),n.classList.toggle(`tcw-on`,!!e.active);let r=document.createElement(`span`);if(r.className=`tcw-cp-label`,r.textContent=e.label,n.appendChild(r),e.shortcut){let t=document.createElement(`kbd`);t.className=`tcw-cp-key`,t.dir=`ltr`,t.textContent=e.shortcut,n.appendChild(t)}if(e.active){let e=document.createElement(`span`);e.className=`tcw-cp-check`,e.innerHTML=O(`check`,14),n.appendChild(e)}return n.addEventListener(`click`,()=>this.run(t)),n.addEventListener(`mousemove`,()=>{this.selectedIndex!==t&&(this.selectedIndex=t,this.markSelection())}),n}markSelection(){let e=this.list?.querySelectorAll(`.tcw-cp-row`)??[],t=null;e.forEach((e,n)=>{let r=n===this.selectedIndex;e.setAttribute(`aria-selected`,String(r)),e.classList.toggle(`tcw-selected`,r),r&&(t=e)});let n=t;n?(this.input?.setAttribute(`aria-activedescendant`,n.id),n.scrollIntoView?.({block:`nearest`})):this.input?.removeAttribute(`aria-activedescendant`)}run(e){let t=this.shown[e];if(t)switch(this.recents?.add(lr(t)),this.close(),t.category){case`indicator`:this.callbacks.onIndicator(t.id);break;case`chartType`:this.callbacks.onChartType(t.id);break;case`drawing`:this.callbacks.onDrawingTool(t.id);break;case`timeframe`:this.callbacks.onTimeframe(t.id);break;case`action`:this.callbacks.onAction(t.id);break}}onKeyDown(e,t){if(e.stopPropagation(),e.isComposing||e.keyCode===or)return;let n=(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`k`;if(e.key===`Escape`||n){e.preventDefault(),this.close();return}if(M(e,t),e.target!==this.input)return;let r=this.shown.length;if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),r===0)return;this.selectedIndex=(this.selectedIndex+(e.key===`ArrowDown`?1:-1)+r)%r,this.markSelection()}else e.key===`Enter`&&(e.preventDefault(),e.repeat||this.run(this.selectedIndex))}},pr=20,mr=1e3,hr=new Set,gr={stock:1,stocks:1,equity:1,share:1,shares:1,"cổ phiếu":1,株式:1,株:1,股票:1,주식:1,futures:2,future:2,derivative:2,derivatives:2,option:2,options:2,"phái sinh":2,先物:2,期货:2,期貨:2,선물:2,warrant:2,warrants:2,"covered warrant":2,"chứng quyền":2,index:3,indices:3,"chỉ số":3,指数:3,指數:3,지수:3,fund:3,funds:3,etf:3,etfs:3,"chứng chỉ quỹ":3,crypto:4,cryptocurrency:4,perpetual:4,perpetuals:4,perp:4,perps:4,"tiền mã hóa":4,"tiền mã hoá":4,"tiền điện tử":4,暗号資産:4,仮想通貨:4,加密货币:4,加密貨幣:4,数字货币:4,數字貨幣:4,虚拟货币:4,虛擬貨幣:4,암호화폐:4,가상자산:4,가상화폐:4,forex:5,fx:5,currency:5,"ngoại hối":5,為替:5,外国為替:5,外汇:5,外匯:5,외환:5,bond:5,bonds:5,"trái phiếu":5},_r=1e3,vr=new Map,yr=/i\u0307|\u0131/g;function br(e){if(typeof e!=`string`)return``;let t=vr.get(e);return t===void 0&&(t=e.trim().normalize(`NFC`).toLowerCase().replace(yr,`i`),vr.size>=_r&&vr.clear(),vr.set(e,t)),t}function xr(e){let t=br(e);return t?Object.prototype.hasOwnProperty.call(gr,t)?gr[t]:1+Sr(t)%5:0}function Sr(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0),t=Math.imul(t,16777619)>>>0;return t}function Cr(e){let{ticker:t}=Qt(e),n=/[\p{L}\p{N}]/u.exec(t);return n?n[0].toUpperCase():``}function wr(e,t){let n=rn(t?.logo);if(!n||hr.has(n))return Er(e,t);let r=document.createElement(`img`);return r.className=`tcw-ss-badge`,r.alt=``,r.width=pr,r.height=pr,r.draggable=!1,r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`loading`,`lazy`),r.setAttribute(`decoding`,`async`),r.setAttribute(`referrerpolicy`,`no-referrer`),r.addEventListener(`error`,()=>{Tr(n),r.replaceWith(Er(e,t))},{once:!0}),r.src=n,r}function Tr(e){hr.size>=mr&&hr.clear(),hr.add(e)}function Er(e,t){let n=document.createElement(`span`);return n.className=`tcw-ss-badge`,n.setAttribute(`aria-hidden`,`true`),n.dataset.kind=String(xr(t?.type)),n.textContent=Cr(e),n}var Dr=180,Or=150,kr=50;function Ar(e){return{upper:e.toUpperCase(),folded:Pr(e)}}function jr(e,t,n){return Math.max(Mr(e.toUpperCase(),n.upper),Nr(t,n.folded))}function Mr(e,t){if(e===t)return 1e3;if(e.startsWith(t))return 500+(50-Math.min(50,e.length-t.length));if(e.includes(t))return 200+(50-Math.min(50,e.length-t.length));let n=0,r=-1,i=0;for(let a=0;a<e.length&&n<t.length;a++)e[a]===t[n]&&(r>=0&&(i+=a-r-1),r=a,n++);return n<t.length?0:100-Math.min(99,i)}function Nr(e,t){if(!e||!t)return 0;if(e.startsWith(t))return Dr;let n=e.indexOf(t);return n<0?0:Or-Math.min(kr,n)}function Pr(e){return e.normalize(`NFD`).replace(/\p{M}+/gu,``).replace(/[đĐ]/g,`D`).toUpperCase()}function Fr(e,t,n=0,r=e.length){let i=t?Ir(e.toUpperCase(),t):new Set,a=``;for(let t=n;t<r;t++)a+=i.has(t)?`<mark>${k(e[t])}</mark>`:k(e[t]);return a}function Ir(e,t){let n=new Set,r=e.indexOf(t);if(r>=0){for(let e=r;e<r+t.length;e++)n.add(e);return n}let i=0;for(let r=0;r<e.length&&i<t.length;r++)e[r]===t[i]&&(n.add(r),i++);return i<t.length?new Set:n}function Lr(e,t){let n=document.createElement(`span`);n.className=`tcw-ss-symbol`,n.dir=`ltr`;let{venue:r}=Qt(e),i=(n,r,i)=>{let a=document.createElement(`span`);return a.className=n,a.innerHTML=Fr(e,t,r,i),a};return r&&n.appendChild(i(`tcw-ss-venue`,0,r.length)),n.appendChild(i(`tcw-ss-ticker`,r.length,e.length)),n}var Rr=br,zr=2,Br=1,Vr=class{el;kindsEl;exchangeEl;kinds=new Map;exchanges=new Map;kind=null;exchange=null;resize;constructor(e,t){this.t=e,this.onChange=t,this.el=document.createElement(`div`),this.el.className=`tcw-ss-filters`,this.el.hidden=!0,this.kindsEl=document.createElement(`div`),this.kindsEl.className=`tcw-ss-kinds`,this.kindsEl.setAttribute(`role`,`group`),this.kindsEl.setAttribute(`aria-label`,e(`symbolSearch.kinds`)),this.kindsEl.hidden=!0,this.kindsEl.addEventListener(`scroll`,()=>this.markMore(),{passive:!0}),this.resize=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>this.markMore()),this.resize?.observe(this.kindsEl),this.exchangeEl=document.createElement(`select`),this.exchangeEl.className=`tcw-settings-select tcw-ss-exchange-filter`,this.exchangeEl.setAttribute(`aria-label`,e(`symbolSearch.exchange`)),this.exchangeEl.hidden=!0,this.exchangeEl.addEventListener(`change`,()=>{this.exchange=Rr(this.exchangeEl.value)||null,this.onChange(!1)}),this.el.append(this.kindsEl,this.exchangeEl)}see(e){let t=this.kinds.size,n=this.exchanges.size;for(let t of e)Hr(this.kinds,t?.type),Hr(this.exchanges,t?.exchange);this.kinds.size!==t&&this.renderKinds(),this.exchanges.size!==n&&this.renderExchanges(),this.kindsEl.hidden=this.kinds.size===0,this.exchangeEl.hidden=this.exchanges.size<zr,this.el.hidden=this.kindsEl.hidden&&this.exchangeEl.hidden,this.markMore()}destroy(){this.resize?.disconnect()}markMore(){let e=this.kindsEl,t=Math.abs(e.scrollLeft),n=e.scrollWidth-e.clientWidth,r=[t>Br?`start`:``,t<n-Br?`end`:``].filter(Boolean);r.length>0?e.dataset.more=r.join(` `):delete e.dataset.more}passes(e,t){return Ur(this.kind,Rr(e?.type),t)&&Ur(this.exchange,Rr(e?.exchange),t)}renderKinds(){let e=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-ss-type`,n.textContent=t,e!==null&&(n.dir=`auto`),n.setAttribute(`aria-pressed`,String(this.kind===e)),n.addEventListener(`click`,()=>{this.kind=e;for(let e of this.kindsEl.children)e.setAttribute(`aria-pressed`,String(e===n));this.onChange(!0)}),n},t=[...this.kinds].map(([t,n])=>e(t,n));this.kindsEl.replaceChildren(e(null,this.t(`symbolSearch.allKinds`)),...t)}renderExchanges(){let e=(e,t)=>{let n=document.createElement(`option`);return n.value=e,n.textContent=t,e&&(n.dir=`auto`),n},t=[...this.exchanges.values()].map(t=>e(t,t));this.exchangeEl.replaceChildren(e(``,this.t(`symbolSearch.allExchanges`)),...t),this.exchangeEl.value=this.exchange===null?``:this.exchanges.get(this.exchange)??``}};function Hr(e,t){let n=Rr(t);n&&!e.has(n)&&e.set(n,t.trim())}function Ur(e,t,n){return e===null||t===e||n&&t===``}var Wr=229,Gr=1,Kr=class{backdrop=null;input=null;list=null;results=null;live=null;columns=null;filters=null;mode=null;given=[];rows=[];rowsGiven=!1;shown=[];compared=[];way=``;selectedIndex=0;searchFn=null;searchTimer=null;searchAbort=null;status=`idle`;pickOnResults=!1;heard=new Map;givenInfo=new Map;foldedNames=new Map;returnFocus=null;uid=Gr++;constructor(e,n=()=>document.body,r=t.t){this.callbacks=e,this.host=n,this.t=r}open(e){this.begin({kind:`search`,start:e})}openCompare(e){this.compared=e.compared,this.way=e.ways.some(t=>t.id===e.way)?e.way:e.ways[0]?.id??``,this.begin({kind:`compare`,start:e})}setCompared(e){if(this.compared=e,this.mode?.kind!==`compare`||!this.results)return;let t=this.results.contains(document.activeElement);this.renderList(),t&&!this.results.contains(document.activeElement)&&this.input?.focus()}close(){if(!this.backdrop)return;this.cancelSearch(),this.pickOnResults=!1,this.searchFn=null,this.backdrop.remove(),this.backdrop=this.input=this.list=this.results=this.live=this.columns=null,this.filters?.destroy(),this.filters=null,this.mode=null,this.callbacks.onClose();let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}isOpen(){return this.backdrop!==null}isComparing(){return this.mode?.kind===`compare`}destroy(){this.close()}begin(e){this.backdrop&&this.close(),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.mode=e,this.searchFn=e.start.search??null,this.status=`idle`,this.learnGiven(e),this.build(e);let t=e.kind===`search`?e.start.query??``:``;this.input&&(this.input.value=t),t?(this.filter(),this.searchFn&&this.searchNow()):this.listGiven(),this.input?.focus()}learnGiven(e){let t=Jt(e.start.symbols);this.given=t.names,this.givenInfo=t.info,this.foldedNames=new Map;let n=e.start.current,r=e.kind===`search`?e.start.currentInfo:null;if(r&&typeof r==`object`&&n){let{description:e,logo:t}=Yt(r,n);this.givenInfo.set(n,Zt({symbol:n,description:e,logo:t},this.givenInfo.get(n)))}}infoOf(e){return Zt(this.givenInfo.get(e),this.heard.get(e))}build(e){let t=document.createElement(`div`);t.className=`tcw-modal-backdrop`;let n=!1;t.addEventListener(`pointerdown`,e=>{n=e.target===t}),t.addEventListener(`click`,e=>{e.target===t&&n&&this.close(),n=!1});let r=document.createElement(`div`);r.className=`tcw-modal tcw-ss${e.kind===`compare`?` tcw-ss--compare`:``}`,D(r,e.kind===`compare`?`compare`:`symbolSearch`),r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.setAttribute(`aria-labelledby`,`tcw-ss-title-${this.uid}`),r.tabIndex=-1,r.addEventListener(`keydown`,e=>this.onKeyDown(e,r)),r.append(this.buildHeader(e),this.buildSearch()),e.kind===`compare`&&r.appendChild(this.buildWay(e.start));let i=new Vr(this.t,e=>{this.afterResults(!1),e&&this.input?.focus()}),a=document.createElement(`div`);a.className=`tcw-ss-list`,a.id=`tcw-ss-list-${this.uid}`,a.setAttribute(`role`,`listbox`);let o=document.createElement(`div`);o.className=`tcw-ss-results`;let s=this.buildColumns();o.append(s,a),o.addEventListener(`mousedown`,e=>{e.target.closest(`button`)||e.preventDefault()});let c=document.createElement(`div`);c.className=`tcw-ss-live tcw-visually-hidden`,c.setAttribute(`aria-live`,`polite`),r.append(i.el,o,c);let l=e.kind===`search`?e.start.hint:void 0;if(l){let e=document.createElement(`div`);e.className=`tcw-ss-foot`,e.textContent=l,r.appendChild(e)}t.appendChild(r),this.host().appendChild(t),this.backdrop=t,this.filters=i,this.columns=s,this.list=a,this.results=o,this.live=c}buildColumns(){let e=document.createElement(`div`);e.className=`tcw-ss-columns`,e.setAttribute(`aria-hidden`,`true`);let t=[``,this.t(`symbolSearch.symbol`),this.t(`symbolSearch.description`),this.t(`symbolSearch.type`),this.t(`symbolSearch.exchange`)];return e.append(...t.map(e=>this.tag(`tcw-ss-head`,e))),e}buildHeader(e){let t=document.createElement(`div`);t.className=`tcw-modal-header`;let n=document.createElement(`h3`);n.id=`tcw-ss-title-${this.uid}`,n.textContent=this.t(e.kind===`compare`?`compare.title`:`symbolSearch.title`);let r=document.createElement(`button`);return r.type=`button`,r.className=`tcw-modal-close`,r.setAttribute(`aria-label`,this.t(`common.close`)),r.innerHTML=O(`x`,16),r.addEventListener(`click`,()=>this.close()),t.append(n,r),t}buildSearch(){let e=document.createElement(`label`);e.className=`tcw-ss-search`,e.innerHTML=O(`search`,16);let t=document.createElement(`input`);return t.type=`search`,t.className=`tcw-ss-input`,t.placeholder=this.t(`symbolSearch.placeholder`),t.setAttribute(`aria-label`,this.t(`symbolSearch.placeholder`)),t.setAttribute(`role`,`combobox`),t.setAttribute(`aria-expanded`,`true`),t.setAttribute(`aria-controls`,`tcw-ss-list-${this.uid}`),t.setAttribute(`aria-autocomplete`,`list`),t.autocomplete=`off`,t.spellcheck=!1,t.addEventListener(`input`,()=>this.filter()),e.appendChild(t),this.input=t,e}buildWay(e){let t=document.createElement(`label`);t.className=`tcw-ss-way`;let n=document.createElement(`span`);n.textContent=this.t(`compare.addAs`);let r=document.createElement(`select`);r.className=`tcw-settings-select tcw-ss-way-select`;for(let t of e.ways){let e=document.createElement(`option`);e.value=t.id,e.textContent=t.label,r.appendChild(e)}return r.value=this.way,r.addEventListener(`change`,()=>{this.way=r.value}),t.append(n,r),t}listGiven(){this.rows=this.given.map(e=>({symbol:e,score:0,info:this.infoOf(e)})),this.rowsGiven=!0,this.afterResults(!0)}filter(){this.pickOnResults=!1;let e=this.input?.value.trim()??``;if(this.searchFn&&e){this.scheduleSearch(e);return}if(this.cancelSearch(),this.status=`idle`,!e){this.listGiven();return}let t=Ar(e);this.rows=this.given.map(e=>{let n=this.infoOf(e);return{symbol:e,score:jr(e,this.foldedName(n?.description),t),info:n}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score),this.rowsGiven=!0,this.afterResults(!1)}foldedName(e){if(!e)return``;let t=this.foldedNames.get(e);return t===void 0&&(t=Pr(e),this.foldedNames.set(e,t)),t}scheduleSearch(e){this.searchTimer!==null&&clearTimeout(this.searchTimer),this.searchTimer=setTimeout(()=>{this.searchTimer=null,this.runSearch(e)},150)}searchNow(){this.searchTimer!==null&&clearTimeout(this.searchTimer),this.searchTimer=null,this.runSearch(this.input?.value.trim()??``)}async runSearch(e){let t=this.searchFn;if(!t)return;this.searchAbort?.abort();let n=new AbortController;this.searchAbort=n,this.status=`searching`,this.shown.length===0&&this.renderList();try{let r=await t(e,n.signal);if(n.signal.aborted)return;let i=Xt(r);for(let e of i)this.heard.set(e.symbol,Zt(this.heard.get(e.symbol),e));this.rows=i.map(e=>({symbol:e.symbol,score:0,info:this.infoOf(e.symbol)})),this.status=`idle`}catch{if(n.signal.aborted)return;this.rows=[],this.status=`failed`}this.rowsGiven=!1,this.afterResults(!1),this.pickOnResults&&(this.pickOnResults=!1,this.pick(0))}cancelSearch(){this.searchTimer!==null&&clearTimeout(this.searchTimer),this.searchTimer=null,this.searchAbort?.abort(),this.searchAbort=null}afterResults(e){let t=this.listableRows();this.filters?.see(t.map(e=>e.info)),this.shown=this.visibleRows(t);let n=e?this.shown.findIndex(e=>e.symbol===this.mode?.start.current):-1;this.selectedIndex=n>=0&&n<this.listedCount()?n:0,this.renderList()}listedCount(){return Math.min(this.shown.length,200)}listableRows(){if(this.mode?.kind!==`compare`)return this.rows;let e=this.mode.start.current;return this.rows.filter(t=>t.symbol!==e)}visibleRows(e){let t=this.filters;return t?e.filter(e=>t.passes(e.info,this.rowsGiven)):[...e]}renderList(){let e=this.list,t=this.results;if(!e||!t)return;let n=(this.input?.value??``).trim(),r=this.mode?.kind===`compare`,i=[];if(r&&!n&&this.compared.length>0){let t=this.heading(this.t(`compare.onChart`),`added`),n=document.createElement(`div`);n.className=`tcw-ss-added`,n.setAttribute(`role`,`group`),n.setAttribute(`aria-labelledby`,t.id),n.append(...this.compared.map(e=>this.addedRow(e)));let r=this.heading(this.t(`compare.symbols`),`symbols`);r.hidden=this.shown.length===0,i.push(t,n,r),e.setAttribute(`aria-labelledby`,r.id)}else e.setAttribute(`aria-labelledby`,`tcw-ss-title-${this.uid}`);let a=n.toUpperCase(),o=new Set(this.compared.map(e=>e.symbol)),s=this.shown.slice(0,200);e.replaceChildren(...s.map((e,t)=>this.row(e,t,a,r&&o.has(e.symbol))));let c=this.shown.length===0?this.emptyNote(n,r):this.moreNote(this.shown.length-s.length);t.replaceChildren(...this.columns?[this.columns]:[],...i,e,...c?[c]:[]),this.live&&(this.live.textContent=this.shown.length===0?c?.textContent??``:``),this.markSelection()}emptyNote(e,t){let n;if(this.status===`searching`)n=this.t(`symbolSearch.searching`);else if(this.status===`failed`)n=this.t(`symbolSearch.failed`);else if(t&&!e){if(this.compared.length>0)return null;n=this.t(`compare.empty`)}else n=this.t(`symbolSearch.empty`);let r=document.createElement(`div`);return r.className=`tcw-ss-empty`,r.textContent=n,r}moreNote(e){if(e<=0)return null;let n=document.createElement(`div`);return n.className=`tcw-ss-more`,n.textContent=t.r(this.t(`symbolSearch.more`),{count:e}),n}heading(e,t){let n=document.createElement(`div`);return n.className=`tcw-ss-heading`,n.id=`tcw-ss-${t}-${this.uid}`,n.textContent=e,n}row(e,t,n,r){let i=document.createElement(`div`);i.className=`tcw-ss-row`,i.id=`tcw-ss-opt-${this.uid}-${t}`,i.dataset.symbol=e.symbol,i.setAttribute(`role`,`option`);let a=this.mode?.kind===`search`&&e.symbol===this.mode.start.current;i.classList.toggle(`tcw-current`,a),i.classList.toggle(`tcw-on-chart`,r),a&&i.setAttribute(`aria-current`,`true`);let o=this.tag(`tcw-ss-kind`,e.info?.type?.trim()??``),s=this.tag(`tcw-ss-exchange`,e.info?.exchange?.trim()??``);if(o.dir=s.dir=`auto`,i.append(wr(e.symbol,e.info),Lr(e.symbol,n),this.descriptionCell(e),o,s),a||r){let e=document.createElement(`span`);e.className=`tcw-ss-check`,e.innerHTML=O(`check`,14),i.appendChild(e)}return r&&i.appendChild(this.tag(`tcw-visually-hidden`,this.t(`compare.onChart`))),i.addEventListener(`click`,()=>this.pick(t)),i.addEventListener(`mousemove`,()=>{this.selectedIndex!==t&&(this.selectedIndex=t,this.markSelection())}),i}descriptionCell(e){let t=document.createElement(`span`);t.className=`tcw-ss-desc-cell`;let n=e.info?.description&&e.info.description!==e.symbol?e.info.description:``;if(n){let e=this.tag(`tcw-ss-desc`,n);e.dir=`auto`,t.appendChild(e)}return t}addedRow(e){let n=document.createElement(`div`);if(n.className=`tcw-ss-added-row`,n.setAttribute(`role`,`presentation`),e.color){let t=document.createElement(`span`);t.className=`tcw-ss-swatch`,t.style.background=e.color,n.appendChild(t)}let r=document.createElement(`span`);r.className=`tcw-ss-way-cell`,r.appendChild(this.tag(`tcw-ss-way-label`,e.way));let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-ss-remove`;let a=t.r(this.t(`compare.remove`),{symbol:e.symbol});return i.title=a,i.setAttribute(`aria-label`,a),i.innerHTML=O(`x`,12),i.addEventListener(`click`,()=>{this.mode?.kind===`compare`&&this.mode.start.onRemove(e.id)}),n.append(Lr(e.symbol,``),r,i),n}tag(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}markSelection(){let e=this.list?.querySelectorAll(`.tcw-ss-row`)??[],t=null;e.forEach((e,n)=>{let r=n===this.selectedIndex;e.setAttribute(`aria-selected`,String(r)),e.classList.toggle(`tcw-selected`,r),r&&(t=e)});let n=t;n?(this.input?.setAttribute(`aria-activedescendant`,n.id),n.scrollIntoView?.({block:`nearest`})):this.input?.removeAttribute(`aria-activedescendant`)}pick(e){let t=this.shown[e],n=this.mode;if(!t||!n)return;if(n.kind===`compare`){this.selectedIndex=e,this.markSelection(),n.start.onAdd(t.symbol,this.way);return}let r=n.start.onPick??this.callbacks.onPick;this.close(),r(t.symbol)}onKeyDown(e,t){if(e.stopPropagation(),e.isComposing||e.keyCode===Wr)return;if(e.key===`Escape`){e.preventDefault(),this.close();return}if(M(e,t),e.target!==this.input)return;let n=this.listedCount();if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),n===0)return;this.selectedIndex=(this.selectedIndex+(e.key===`ArrowDown`?1:-1)+n)%n,this.markSelection()}else if(e.key===`Enter`){if(e.preventDefault(),e.repeat&&this.mode?.kind===`compare`)return;if(this.searchTimer!==null||this.status===`searching`){this.pickOnResults=!0,this.searchTimer!==null&&this.searchNow();return}this.pick(this.selectedIndex)}}},qr=229,Jr={"Search & navigation":`hotkeys.group.searchNavigation`,"Chart manipulation":`hotkeys.group.chartManipulation`,"Touch (mobile / tablet)":`hotkeys.group.touch`,Keyboard:`hotkeys.group.keyboard`,"Bar replay":`toolbar.replay`,Drawing:`hotkeys.group.drawing`,More:`hotkeys.group.more`},V=rr,Yr=[{title:`Search & navigation`,entries:[{keys:[V,`K`],label:`hotkeys.commandPalette`,feature:`hotkeys.commandPalette`},{keys:[V,`P`],label:`hotkeys.symbolSearch`,feature:`hotkeys.symbolSearch`},{keys:[`Alt`,`G`],label:`hotkeys.goToDate`,feature:`hotkeys.goToDate`},{keys:[`Alt`,`I`],label:`hotkeys.invertScale`,feature:`hotkeys.invertScale`},{keys:[`Alt`,`R`],label:`chartMenu.resetView`,feature:`hotkeys.resetView`},{keys:[V,`S`],label:`hotkeys.saveLayout`,feature:`hotkeys.save`},{keys:[`0–9`],label:`hotkeys.typeInterval`,feature:`intervalTyping`},{keys:[`A–Z`],label:`hotkeys.typeSymbol`,feature:`symbolTyping`},{keys:[`?`],label:`hotkeys.showSheet`,feature:`hotkeys.help`}]},{title:`Chart manipulation`,entries:[{keys:[`key.drag`],label:`hotkeys.pan`},{keys:[V,`key.drag`],label:`hotkeys.boxSelect`},{keys:[V,`key.click`],label:`hotkeys.toggleSelect`},{keys:[`Shift`,`key.drag`],label:`hotkeys.measure`},{keys:[`key.drag`,`key.priceAxis`],label:`hotkeys.scalePrice`},{keys:[`key.drag`,`key.timeAxis`],label:`hotkeys.zoomTime`},{keys:[`key.doubleClick`,`key.priceAxis`],label:`hotkeys.autoScale`},{keys:[`key.doubleClick`,`key.timeAxis`],label:`hotkeys.fit`},{keys:[`key.scroll`],label:`hotkeys.zoomCursor`}]},{title:`Touch (mobile / tablet)`,entries:[{keys:[`key.oneFinger`,`key.drag`],label:`hotkeys.touchPan`},{keys:[`key.twoFingers`,`key.pinch`],label:`hotkeys.pinch`},{keys:[`key.longPress`],label:`hotkeys.longPress`},{keys:[`key.drag`,`key.axisStrip`],label:`hotkeys.touchAxis`}]},{title:`Keyboard`,entries:[{keys:[`←`,`→`],label:`hotkeys.panBar`},{keys:[`+`,`−`],label:`hotkeys.zoomInOut`},{keys:[`Home`],label:`hotkeys.toStart`},{keys:[`End`],label:`hotkeys.toEnd`},{keys:[`Space`],label:`hotkeys.fit`}]},{title:`Bar replay`,entries:[{keys:[`Shift`,`←`,`→`],label:`hotkeys.replayStep`,feature:`replay`},{keys:[`Space`],label:`hotkeys.replayPlay`,feature:`replay`},{keys:[`Esc`],label:`hotkeys.replayCancel`,feature:`replay`}]},{title:`Drawing`,entries:[{keys:[V,`Z`],label:`hotkeys.undo`},{keys:[V,`Shift`,`Z`],label:`hotkeys.redo`},{keys:[`Esc`],label:`hotkeys.cancelDrawing`},{keys:[V,`C`],label:`hotkeys.copy`},{keys:[V,`V`],label:`hotkeys.paste`},{keys:[`key.rightClick`],label:`hotkeys.drawingMenu`},{keys:[`key.doubleClick`],label:`hotkeys.drawingSettings`},{keys:[V,`G`],label:`hotkeys.group`},{keys:[V,`Shift`,`G`],label:`hotkeys.ungroup`},{keys:[V,`]`,`[`],label:`hotkeys.orderStep`},{keys:[V,`Shift`,`]`,`[`],label:`hotkeys.orderEnd`},{keys:[`Enter`],label:`hotkeys.finishPath`},{keys:[V,`key.drag`],label:`hotkeys.copyDrag`},{keys:[`Shift`],label:`hotkeys.keepAngle`},{keys:[V],label:`hotkeys.flipMagnet`},{keys:[`←`,`→`,`↑`,`↓`],label:`hotkeys.nudge`},{keys:[`Alt`,`T`],label:`tool.trendLine`,feature:`hotkeys.tools`},{keys:[`Alt`,`H`],label:`tool.horizontalLine`,feature:`hotkeys.tools`},{keys:[`Alt`,`J`],label:`tool.horizontalRay`,feature:`hotkeys.tools`},{keys:[`Alt`,`V`],label:`tool.verticalLine`,feature:`hotkeys.tools`},{keys:[`Alt`,`C`],label:`tool.crossLine`,feature:`hotkeys.tools`},{keys:[`Alt`,`F`],label:`tool.fibRetracement`,feature:`hotkeys.tools`}]}],Xr=0,Zr=class{backdrop=null;bodyEl=null;searchEl=null;liveEl=null;groups=[];returnFocus=null;uid=++Xr;constructor(e,t,n=()=>document.body){this.callbacks=e,this.t=t,this.host=n}open(e={}){if(this.backdrop)return;this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=e.isOn??(()=>!0),n=new Set((e.extra??[]).map(e=>e.keys.join(`+`).toLowerCase()));this.groups=Yr.map(e=>({title:e.title,entries:e.entries.filter(e=>(!e.feature||t(e.feature))&&!n.has(e.keys.join(`+`).toLowerCase()))})).filter(e=>e.entries.length>0),e.extra&&e.extra.length>0&&this.groups.push({title:`More`,entries:[...e.extra]}),this.build(t(`hotkeys.help`)),this.render(),this.searchEl?.focus()}close(){if(!this.backdrop)return;this.backdrop.remove(),this.backdrop=this.bodyEl=this.searchEl=this.liveEl=null,this.callbacks.onClose();let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}isOpen(){return this.backdrop!==null}destroy(){this.close()}build(e){let t=document.createElement(`div`);t.className=`tcw-modal-backdrop`;let n=!1;t.addEventListener(`pointerdown`,e=>{n=e.target===t}),t.addEventListener(`click`,e=>{e.target===t&&n&&this.close(),n=!1});let r=document.createElement(`div`);r.className=`tcw-modal tcw-hotkey-sheet`,r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.setAttribute(`aria-labelledby`,`tcw-hotkey-title-${this.uid}`),r.tabIndex=-1,r.addEventListener(`keydown`,e=>{if(e.stopPropagation(),e.key===`Escape`&&!e.isComposing&&e.keyCode!==qr){e.preventDefault(),this.close();return}M(e,r)});let i=document.createElement(`div`);i.className=`tcw-modal-header`;let a=document.createElement(`h3`);a.id=`tcw-hotkey-title-${this.uid}`,a.textContent=this.t(`hotkeys.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`hotkeys.close`)),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.close()),i.append(a,o);let s=document.createElement(`label`);s.className=`tcw-ss-search tcw-hotkey-search`,s.innerHTML=O(`search`,16);let c=document.createElement(`input`);c.type=`search`,c.placeholder=this.t(`hotkeys.search`),c.setAttribute(`aria-label`,this.t(`hotkeys.search`)),c.autocomplete=`off`,c.spellcheck=!1,c.addEventListener(`input`,()=>this.render()),s.appendChild(c);let l=document.createElement(`div`);l.className=`tcw-hotkey-body`;let u=document.createElement(`div`);if(u.className=`tcw-hotkey-live tcw-visually-hidden`,u.setAttribute(`aria-live`,`polite`),r.append(i,s,l,u),e){let e=document.createElement(`div`);e.className=`tcw-hotkey-foot`,e.textContent=this.t(`hotkeys.footer`),r.appendChild(e)}t.appendChild(r),this.host().appendChild(t),this.backdrop=t,this.bodyEl=l,this.searchEl=c,this.liveEl=u}render(){let e=this.bodyEl;if(!e)return;let t=ir((this.searchEl?.value??``).trim()),n=[];for(let e of this.groups){let r=t?e.entries.filter(e=>this.matches(e,t)):e.entries;if(r.length===0)continue;let i=document.createElement(`section`);i.className=`tcw-hotkey-group`;let a=document.createElement(`div`);a.className=`tcw-hotkey-heading`;let o=Jr[e.title];a.textContent=o?this.t(o):e.title,i.append(a,...r.map(e=>this.row(e))),n.push(i)}if(this.liveEl&&(this.liveEl.textContent=n.length===0?this.t(`hotkeys.noMatch`):``),n.length===0){let t=document.createElement(`div`);t.className=`tcw-hotkey-empty`,t.textContent=this.t(`hotkeys.noMatch`),e.replaceChildren(t);return}let r=document.createElement(`div`);r.className=`tcw-hotkey-columns`,r.append(...n),e.replaceChildren(r)}label(e){return`text`in e?e.text:this.t(e.label)}keyText(e){return e.startsWith(`key.`)?this.t(e):e}matches(e,t){return ir(this.label(e)).includes(t)?!0:ir(e.keys.map(e=>this.keyText(e)).join(`+`)).includes(t)}row(e){let t=document.createElement(`div`);t.className=`tcw-hotkey-row`;let n=document.createElement(`span`);n.className=`tcw-hotkey-label`,n.textContent=this.label(e);let r=document.createElement(`span`);return r.className=`tcw-hotkey-keys`,r.dir=`ltr`,e.keys.forEach((e,t)=>{if(t>0){let e=document.createElement(`span`);e.className=`tcw-hotkey-sep`,e.textContent=`+`,r.appendChild(e)}let n=e.startsWith(`key.`),i=document.createElement(n?`span`:`kbd`);i.className=n?`tcw-hotkey-gesture`:`tcw-hotkey-key`,i.textContent=this.keyText(e),r.appendChild(i)}),t.append(n,r),t}},Qr={selectHint:`Click a bar to start the replay`,random:`Random bar`,realtime:`Back to realtime`,play:`Play`,pause:`Pause`,stepBack:`Step back (Shift+←)`,stepForward:`Step forward (Shift+→)`,replay:`Replay`,position:`Replay position`,speed:`Speed`,step:`Step`,loading:`Loading chart...`,selectBar:`Select bar`,cancel:`Cancel`,rate:`{rate}×`,rateHint:`1× plays one bar a second`,playingAt:`Playing at {rate}`,pausedAt:`Paused at {time}`,endedAt:`Replay ended at {time}`},$r=[.1,.2,.3,.5,1,2,3,5,10,20,30,50],ei=[`full`,`compact`,`stack`],ti=300,ni=2,ri=[`random`,`stepBack`,`stepForward`,`seek`,`step`,`selectBar`],ii=class{root=null;scrubber=null;timeLabel=null;playBtn=null;realtimeBtn=null;liveRegion=null;hintText=null;state=`stopped`;mode=`select`;ended=!1;pending=!1;total=0;rate=1;steps=[];step=`bar`;dir=`ltr`;formatRate;where=``;announceTimer=null;widths=new Map;labels;constructor(e,t={}){this.callbacks=e,this.labels={...Qr,...t},this.formatRate=e=>this.labels.rate.replace(`{rate}`,String(e))}mount(e,t){this.root||(this.total=Math.max(0,t.total),this.rate=t.rate??1,this.steps=t.steps??[],this.step=t.step??`bar`,this.dir=t.dir??`ltr`,t.formatRate&&(this.formatRate=t.formatRate),this.state=`paused`,this.mode=t.mode??`select`,this.root=document.createElement(`div`),this.root.className=`tcw-replay-bar`,D(this.root,`replay`),this.root.setAttribute(`role`,`group`),this.root.setAttribute(`aria-label`,this.labels.replay),this.root.dataset.fit=`full`,this.root.innerHTML=this.markup(),e.appendChild(this.root),this.wireEvents(),this.syncUi())}unmount(){this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=null,this.root?.remove(),this.root=null,this.hintText=null,this.scrubber=null,this.timeLabel=null,this.playBtn=null,this.realtimeBtn=null,this.liveRegion=null,this.state=`stopped`,this.ended=!1,this.where=``}isMounted(){return this.root!==null}element(){return this.root}getMode(){return this.mode}setMode(e){let t=!!this.root?.contains(document.activeElement);this.mode=e,this.syncUi(),t&&(e===`replay`?(this.playBtn&&!this.playBtn.disabled?this.playBtn:this.realtimeBtn)?.focus():this.root?.querySelector(`[data-act="random"]`)?.focus())}setState(e){e!==this.state&&(this.state=e,this.syncUi(),this.mode===`replay`&&(e===`playing`?this.announce(this.labels.playingAt.replace(`{rate}`,this.formatRate(this.rate))):e===`paused`&&this.where&&this.announce(this.labels.pausedAt.replace(`{time}`,this.where))))}setEnded(e){this.ended!==e&&(this.ended=e,this.syncUi(),e&&this.where&&this.announce(this.labels.endedAt.replace(`{time}`,this.where)))}setPending(e){if(this.pending===e)return;this.pending=e;let t=document.activeElement;e&&t&&t!==this.playBtn&&this.root?.contains(t)&&ri.includes(t.dataset.act??``)&&this.playBtn?.focus(),this.syncUi(),e&&this.mode===`replay`&&this.announce(this.labels.loading)}isPending(){return this.pending}setSteps(e,t){this.steps=e,this.step=t,this.widths.clear();let n=this.root?.querySelector(`[data-tcw="stepSlot"]`);n&&(n.innerHTML=this.stepMarkup(),this.wireStep(),this.syncUi())}setProgress(e,t,n){this.total=t;let r=n??`${Math.min(e+1,t)} / ${t}`,i=r!==this.where;if(this.where=r,this.scrubber){this.scrubber.max=String(Math.max(0,t-1)),this.scrubber.value=String(e),this.scrubber.setAttribute(`aria-valuetext`,r);let n=t>1?Math.min(e,t-1)/(t-1)*100:0;this.scrubber.style.setProperty(`--tcw-replay-done`,`${Number(n.toFixed(ni))}%`)}if(this.timeLabel){this.timeLabel.textContent=r;let e=Number.parseFloat(this.timeLabel.style.minInlineSize)||0;r.length>e&&(this.timeLabel.style.minInlineSize=`${r.length}ch`)}let a=this.scrubber!==null&&document.activeElement===this.scrubber;i&&this.mode===`replay`&&this.state!==`playing`&&!a&&this.announce(r)}setRoom(e){let t=this.root;if(t){for(let n of ei)if(n===`stack`||this.widthIn(n)<=e){t.dataset.fit=n,this.orderFor(n);return}}}orderFor(e){let t=this.root,n=t?.querySelector(`.tcw-replay-timeline`),r=t?.querySelector(`.tcw-replay-transport`),i=this.realtimeBtn;if(!t||!n||!r||!i)return;let a=e===`stack`;if(a===(n.nextElementSibling===i))return;let o=document.activeElement;a?r.before(n,i):(r.nextElementSibling?.after(n),t.querySelector(`[data-act="cancel"]`)?.before(i)),o&&t.contains(o)&&document.activeElement!==o&&o.focus()}getFit(){return this.root?.dataset.fit??`full`}destroy(){this.unmount()}widthIn(e){let t=this.root,n=`${this.mode}|${this.steps.length}|${e}`,r=this.widths.get(n);if(r!==void 0)return r;let i=t.dataset.fit;t.dataset.fit=e,t.dataset.measure=``;let a=t.getBoundingClientRect().width;return delete t.dataset.measure,i&&(t.dataset.fit=i),a>0&&this.widths.set(n,a),a}markup(){let e=this.labels,t=`dir="${this.dir}"`,n=$r.map(e=>`<option value="${e}"${e===this.rate?` selected`:``}>${k(this.formatRate(e))}</option>`).join(``),r=(e,t,n,r=`tcw-replay-btn`,i=``)=>`<button type="button" class="${r}" data-act="${e}" title="${k(t)}" aria-label="${k(t)}"${i}>${n}</button>`;return`
|
|
7703
7703
|
<span class="tcw-replay-group tcw-replay-picking" data-mode="select">
|
|
7704
7704
|
<span class="tcw-replay-hint" ${t}>${O(`cursor`,14)}<span data-tcw="hint">${k(e.selectHint)}</span></span>
|
|
7705
7705
|
<button type="button" class="tcw-replay-text-btn tcw-replay-ghost" data-act="random" ${t}>${k(e.random)}</button>
|
|
@@ -7729,7 +7729,7 @@ ${Ge()}`,document.head.insertBefore(e,document.head.firstChild)}function $e(){if
|
|
|
7729
7729
|
<button type="button" class="tcw-replay-text-btn" data-act="cancel" data-mode="select" ${t}>${k(e.cancel)}</button>
|
|
7730
7730
|
</span>
|
|
7731
7731
|
<span class="tcw-visually-hidden" role="status" aria-live="polite" data-tcw="announce" ${t}></span>
|
|
7732
|
-
`}stepMarkup(){let e=this.labels;if(this.steps.length<=1)return``;let t=this.steps.map(e=>`<option value="${k(e.value)}"${e.value===this.step?` selected`:``}>${k(e.label)}</option>`).join(``);return`<label class="tcw-replay-chip"><span class="tcw-replay-chip-label" dir="${this.dir}">${k(e.step)}</span><select class="tcw-replay-speed tcw-replay-step" data-act="step" dir="ltr">${t}</select></label>`}wireStep(){(this.root?.querySelector(`[data-act="step"]`))?.addEventListener(`change`,e=>{this.step=e.target.value,this.callbacks.onStepChange?.(this.step)})}wireEvents(){let e=this.root;if(!e)return;this.hintText=e.querySelector(`[data-tcw="hint"]`),this.scrubber=e.querySelector(`input[data-act="seek"]`),this.timeLabel=e.querySelector(`[data-tcw="time"]`),this.playBtn=e.querySelector(`button[data-act="play"]`),this.realtimeBtn=e.querySelector(`button[data-act="realtime"]`),this.liveRegion=e.querySelector(`[data-tcw="announce"]`);let t=(t,n)=>e.querySelector(`[data-act="${t}"]`)?.addEventListener(`click`,n);t(`realtime`,()=>this.callbacks.onClose()),t(`random`,()=>this.callbacks.onRandomStart()),t(`stepBack`,()=>this.callbacks.onStepBack()),t(`stepForward`,()=>this.callbacks.onStepForward()),t(`selectBar`,()=>this.callbacks.onSelectBar?.()),t(`cancel`,()=>(this.callbacks.onCancelPick??this.callbacks.onClose)()),t(`play`,()=>this.togglePlay()),this.scrubber?.addEventListener(`input`,()=>this.callbacks.onSeek(Number(this.scrubber.value))),e.querySelector(`[data-act="speed"]`)?.addEventListener(`change`,e=>{let t=Number(e.target.value);this.rate=t,this.callbacks.onSpeedChange(t)}),e.addEventListener(`keydown`,this.onKeydown),this.wireStep()}togglePlay(){this.state===`playing`?this.callbacks.onPause():this.callbacks.onPlay()}onKeydown=e=>{if(e.key!==` `||this.mode!==`replay`||e.defaultPrevented)return;let t=e.target;t!==this.scrubber&&t!==this.root||(e.preventDefault(),e.stopPropagation(),this.playBtn?.disabled||this.togglePlay())};announce(e){this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>{this.announceTimer=null,this.liveRegion&&(this.liveRegion.textContent=e)},ei)}syncUi(){let e=this.root;if(e){for(let t of e.querySelectorAll(`[data-mode]`))t.hidden=t.dataset.mode!==this.mode;if(e.dataset.mode=this.mode,e.classList.toggle(`tcw-replay-bar--ended`,this.ended),this.syncPending(e),this.playBtn){let e=this.state===`playing`;this.playBtn.innerHTML=O(e?`pause`:`play`,14),this.playBtn.title=e?this.labels.pause:this.labels.play,this.playBtn.setAttribute(`aria-label`,this.playBtn.title);let t=this.ended&&!e;t&&document.activeElement===this.playBtn&&this.realtimeBtn?.focus(),this.playBtn.disabled=t}}}syncPending(e){for(let t of e.querySelectorAll(`.tcw-replay-group`))this.pending?t.setAttribute(`aria-busy`,`true`):t.removeAttribute(`aria-busy`);this.hintText&&(this.hintText.textContent=this.pending?this.labels.loading:this.labels.selectHint);for(let t of ni){let n=e.querySelector(`[data-act="${t}"]`);n&&(n.disabled=this.pending)}}},ii=class{el;headerEl;nameBtn;menuEl;listEl;rowMap=new Map;entries=new Map;lists=[];activeList=``;active=null;locale;dragging=null;onOutside=e=>{this.headerEl.contains(e.target)||this.closeMenu()};constructor(e,t,n){this.callbacks=t,this.labels=n,this.el=document.createElement(`div`),this.el.className=`tcw-watchlist`,this.el.setAttribute(`aria-label`,n.title),this.headerEl=document.createElement(`div`),this.headerEl.className=`tcw-watchlist-header`,this.nameBtn=document.createElement(`button`),this.nameBtn.type=`button`,this.nameBtn.className=`tcw-watchlist-name`,this.nameBtn.setAttribute(`aria-haspopup`,`menu`),this.nameBtn.setAttribute(`aria-expanded`,`false`),this.nameBtn.title=n.lists,this.nameBtn.addEventListener(`click`,()=>this.menuEl.hidden?this.openMenu():this.closeMenu());let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-add`,r.innerHTML=O(`plus`,14),r.title=n.add,r.setAttribute(`aria-label`,n.add),r.hidden=!t.onAdd,r.addEventListener(`click`,()=>t.onAdd?.());let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-watchlist-close`,i.setAttribute(`aria-label`,n.close??n.title),i.innerHTML=O(`x`,14),i.hidden=!t.onClose,i.addEventListener(`click`,()=>t.onClose?.()),this.menuEl=document.createElement(`div`),this.menuEl.className=`tcw-dropdown tcw-watchlist-menu`,this.menuEl.setAttribute(`role`,`menu`),this.menuEl.hidden=!0,this.headerEl.append(this.nameBtn,r,i,this.menuEl),this.el.appendChild(this.headerEl),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.listEl.setAttribute(`role`,`list`),this.el.appendChild(this.listEl),e.appendChild(this.el)}get element(){return this.el}setLists(e,t){this.lists=e.map(e=>({...e,symbols:[...e.symbols]})),this.activeList=e.some(e=>e.id===t)?t:e[0]?.id??``;let n=this.shownList();this.nameBtn.textContent=n?.name??this.labels.title,this.renderRows(n?.symbols??[]),this.menuEl.hidden||this.renderMenu()}redraw(){for(let e of this.rowMap.keys())this.renderRow(e)}setLocale(e){this.locale=e;for(let e of this.rowMap.keys())this.renderRow(e)}setActive(e){this.active=e;for(let[t,n]of this.rowMap){let r=t===e;n.row.classList.toggle(`tcw-watchlist-active`,r),r?n.row.setAttribute(`aria-current`,`true`):n.row.removeAttribute(`aria-current`)}}setEntry(e,t){let n=this.entries.get(e)??{symbol:e};this.entries.set(e,{...n,...t,symbol:e}),this.renderRow(e)}destroy(){this.closeMenu(),this.el.remove(),this.rowMap.clear(),this.entries.clear()}shownList(){return this.lists.find(e=>e.id===this.activeList)}renderRows(e){for(let t of[...this.rowMap.keys()])e.includes(t)||(this.rowMap.get(t).row.remove(),this.rowMap.delete(t));for(let t of e)this.rowMap.has(t)||this.makeRow(t);if(this.listEl.replaceChildren(...e.map(e=>this.rowMap.get(e).row)),e.length===0){let e=document.createElement(`div`);e.className=`tcw-watchlist-empty`,e.textContent=this.labels.empty,this.listEl.appendChild(e)}this.active&&this.setActive(this.active)}makeRow(e){let n=document.createElement(`div`);n.className=`tcw-watchlist-row`,n.setAttribute(`role`,`listitem`),n.dataset.symbol=e,n.tabIndex=0,n.draggable=!!this.callbacks.onMove;let r=document.createElement(`div`);r.className=`tcw-watchlist-symbol`,r.textContent=ai(e);let i=document.createElement(`canvas`);i.className=`tcw-watchlist-spark`,i.width=64,i.height=22;let a=document.createElement(`div`);a.className=`tcw-watchlist-stats`;let o=document.createElement(`span`);o.className=`tcw-watchlist-price`,o.textContent=`—`;let s=document.createElement(`span`);if(s.className=`tcw-watchlist-change`,a.append(o,s),n.append(r,i,a),this.callbacks.onRemove){n.classList.add(`tcw-watchlist-removable`);let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-remove`,r.innerHTML=O(`x`,12),r.tabIndex=-1;let i=t.r(this.labels.remove,{symbol:e});r.title=i,r.setAttribute(`aria-label`,i),r.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemove?.(e)}),n.appendChild(r)}n.addEventListener(`click`,()=>this.callbacks.onSelect(e)),n.addEventListener(`keydown`,t=>this.onRowKey(t,e)),n.addEventListener(`dragstart`,t=>{this.dragging=e,t.dataTransfer?.setData(`text/plain`,e),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`),n.classList.add(`tcw-watchlist-dragging`)}),n.addEventListener(`dragend`,()=>{this.dragging=null,n.classList.remove(`tcw-watchlist-dragging`)}),n.addEventListener(`dragover`,t=>{this.dragging&&this.dragging!==e&&t.preventDefault()}),n.addEventListener(`drop`,t=>{t.preventDefault();let n=this.dragging;if(this.dragging=null,!n||n===e)return;let r=this.shownList()?.symbols??[];this.callbacks.onMove?.(n,r.indexOf(e))}),this.rowMap.set(e,{row:n,priceEl:o,changeEl:s,sparkCanvas:i}),this.renderRow(e)}onRowKey(e,t){let n=this.shownList()?.symbols??[],r=n.indexOf(t);if([`Enter`,` `,`Delete`,`Backspace`,`ArrowDown`,`ArrowUp`].includes(e.key)&&e.stopPropagation(),e.key===`Enter`||e.key===` `)e.preventDefault(),this.callbacks.onSelect(t);else if((e.key===`Delete`||e.key===`Backspace`)&&this.callbacks.onRemove){e.preventDefault();let i=n[r+1]??n[r-1];this.callbacks.onRemove(t),i&&this.rowMap.get(i)?.row.focus()}else if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let i=r+(e.key===`ArrowDown`?1:-1);if(i<0||i>=n.length)return;e.altKey?(this.callbacks.onMove?.(t,i),this.rowMap.get(t)?.row.focus()):this.rowMap.get(n[i])?.row.focus()}}renderRow(e){let t=this.rowMap.get(e),n=this.entries.get(e);if(!(!t||!n)){if(n.lastPrice!==void 0&&(t.priceEl.textContent=oi(n.lastPrice,this.locale)),n.lastPrice!==void 0&&n.refPrice!==void 0&&n.refPrice!==0){let e=n.lastPrice-n.refPrice,r=e/n.refPrice*100,i=e>=0?`+`:`-`,a=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.changeEl.textContent=`${i}${a}%`,t.changeEl.className=`tcw-watchlist-change ${e>=0?`tcw-up`:`tcw-down`}`}else t.changeEl.textContent=``;n.sparkline&&n.sparkline.length>=2&&si(t.sparkCanvas,n.sparkline,n.refPrice??n.sparkline[0])}}openMenu(){this.renderMenu(),this.menuEl.hidden=!1,this.nameBtn.setAttribute(`aria-expanded`,`true`),document.addEventListener(`mousedown`,this.onOutside)}closeMenu(){this.menuEl.hidden=!0,this.nameBtn.setAttribute(`aria-expanded`,`false`),document.removeEventListener(`mousedown`,this.onOutside)}renderMenu(){let e=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-dropdown-item`,n.setAttribute(`role`,`menuitem`),n.textContent=e,n.addEventListener(`click`,t),n},n=this.lists.map(t=>{let n=e(``,()=>{this.closeMenu(),this.callbacks.onPickList?.(t.id)});n.dataset.list=t.id,n.classList.toggle(`tcw-active`,t.id===this.activeList);let r=document.createElement(`span`);r.textContent=t.name;let i=document.createElement(`span`);return i.className=`tcw-watchlist-count`,i.textContent=String(t.symbols.length),n.append(r,i),n}),r=document.createElement(`div`);if(r.className=`tcw-dropdown-divider`,n.push(r),this.callbacks.onCreateList){let t=e(this.labels.newList,()=>this.editName(``,e=>this.callbacks.onCreateList?.(e)));t.dataset.action=`new`,n.push(t)}let i=this.shownList();if(i&&this.callbacks.onRenameList){let t=e(this.labels.rename,()=>this.editName(i.name,e=>this.callbacks.onRenameList?.(i.id,e)));t.dataset.action=`rename`,n.push(t)}if(i&&this.callbacks.onDeleteList&&this.lists.length>1){let r=!1,a=e(this.labels.deleteList,()=>{if(!r){r=!0,a.textContent=t.r(this.labels.confirmDelete,{name:i.name}),a.classList.add(`tcw-danger`);return}this.closeMenu(),this.callbacks.onDeleteList?.(i.id)});a.dataset.action=`delete`,n.push(a)}this.menuEl.replaceChildren(...n)}editName(e,t){this.closeMenu();let n=document.createElement(`input`);n.className=`tcw-watchlist-input`,n.type=`text`,n.maxLength=60,n.value=e,n.placeholder=this.labels.listName,n.setAttribute(`aria-label`,this.labels.listName),this.nameBtn.hidden=!0,this.headerEl.insertBefore(n,this.nameBtn);let r=!1,i=i=>{if(r)return;r=!0;let a=n.value.trim();n.remove(),this.nameBtn.hidden=!1,i&&a&&a!==e&&t(a),this.nameBtn.focus()};n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),i(!0)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),i(!1))}),n.addEventListener(`blur`,()=>i(!1)),n.focus()}};function ai(e){for(let t of[`USDT`,`USD`,`BTC`,`ETH`,`EUR`])if(e.length>t.length&&e.endsWith(t))return e.slice(0,-t.length)+`/`+t;return e}function oi(e,t){if(e===0)return`0`;let n=Math.abs(e);return n>=1e3?e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2}):n>=1?e.toLocaleString(t,{minimumFractionDigits:4,maximumFractionDigits:4}):Number(e.toPrecision(4)).toLocaleString(t,{maximumFractionDigits:10})}function si(e,t,n){let r=e.getContext(`2d`);if(!r)return;let i=window.devicePixelRatio||1;e.width!==e.clientWidth*i&&(e.width=(e.clientWidth||64)*i,e.height=(e.clientHeight||22)*i);let a=e.width,o=e.height,s=1/0,c=-1/0;for(let e of t)e<s&&(s=e),e>c&&(c=e);let l=Math.max(c-s,1e-9),u=t[t.length-1]>=n?`#1fa874`:`#e8505b`;r.clearRect(0,0,a,o),r.lineWidth=1.4*i,r.strokeStyle=u,r.beginPath();let d=a/(t.length-1);for(let e=0;e<t.length;e++){let n=e*d,i=o-(t[e]-s)/l*(o-4)-2;e===0?r.moveTo(n,i):r.lineTo(n,i)}r.stroke()}var ci=50,li=500,ui=60,di=e=>typeof e==`string`&&e.trim().slice(0,ui)||null;function fi(e){let t=[];for(let n of e){let e=qt(n);if(e&&!t.includes(e)&&t.push(e),t.length===li)break}return t}function pi(e){if(!e||typeof e!=`object`)return null;let t=e;if(!Array.isArray(t.lists))return null;let n=[];for(let e of t.lists){if(n.length===ci)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=64?t.id:null,i=di(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?fi(t.symbols):[]})}return n.length===0?null:{lists:n,active:typeof t.active==`string`&&n.some(e=>e.id===t.active)?t.active:n[0].id}}var mi=e=>({...e,symbols:[...e.symbols]}),hi=class{lists;active;listeners=new Set;storage;storageKey;constructor(e){this.storage=e.storage??null,this.storageKey=e.storageKey??`tcw:watchlists`;let t=this.load(),n=e.lists?pi({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:di(e.defaultName)??`Watchlist`,symbols:fi(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map(mi)}getActive(){return mi(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=pi({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=di(e);if(!t||this.lists.length>=ci)return null;let n=this.lists.length+1;for(;this.lists.some(e=>e.id===`list-${n}`);)n++;let r={id:`list-${n}`,name:t,symbols:[]};return this.lists=[...this.lists,r],this.active=r.id,this.changed(),mi(r)}rename(e,t){let n=di(t);n&&this.update(e,e=>({...e,name:n}))}remove(e){this.lists.length<=1||!this.lists.some(t=>t.id===e)||(this.lists=this.lists.filter(t=>t.id!==e),this.active===e&&(this.active=this.lists[0].id),this.changed())}add(e,t=this.active){let n=qt(e),r=this.lists.find(e=>e.id===t);return!n||!r||r.symbols.includes(n)||r.symbols.length>=li?!1:(this.update(t,e=>({...e,symbols:[...e.symbols,n]})),!0)}removeSymbol(e,t=this.active){this.lists.find(e=>e.id===t)?.symbols.includes(e)&&this.update(t,t=>({...t,symbols:t.symbols.filter(t=>t!==e)}))}move(e,t,n=this.active){let r=this.lists.find(e=>e.id===n);if(!r)return;let i=r.symbols.indexOf(e);if(i<0)return;let a=r.symbols.filter(t=>t!==e),o=Math.max(0,Math.min(Math.round(t),a.length));o!==i&&this.update(n,t=>({...t,symbols:[...a.slice(0,o),e,...a.slice(o)]}))}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}activeList(){return this.lists.find(e=>e.id===this.active)??this.lists[0]}update(e,t){this.lists=this.lists.map(n=>n.id===e?t(n):n),this.changed()}changed(){this.save();for(let e of this.listeners)e()}load(){if(!this.storage)return null;try{let e=this.storage.getItem(this.storageKey);return e?pi(JSON.parse(e)):null}catch{return null}}save(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify({lists:this.lists,active:this.active}))}catch{}}},gi=class{el;bodyEl;newsEl;shown=!1;constructor(e,n=t.t,r={}){this.t=n,this.callbacks=r,this.el=document.createElement(`div`),this.el.className=`tcw-syminfo`,D(this.el,`symbolInfo`),this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,n(`symbolInfo.title`)),this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-syminfo-header`;let a=document.createElement(`span`);a.textContent=n(`symbolInfo.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-syminfo-close`,o.setAttribute(`aria-label`,n(`common.close`)),o.innerHTML=O(`x`,14),o.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),i.append(a,o),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-syminfo-body`,this.newsEl=document.createElement(`div`),this.newsEl.className=`tcw-syminfo-news`,this.newsEl.hidden=!0,this.el.append(i,this.bodyEl,this.newsEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.shown}toggle(){this.shown?this.close():this.open()}open(){this.shown||(this.shown=!0,this.el.hidden=!1,this.callbacks.onToggle?.(!0))}close(){this.shown&&(this.shown=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}render(e){let t=document.createElement(`div`);t.className=`tcw-syminfo-head`,t.append(U(`div`,`tcw-syminfo-symbol`,e.symbol)),e.description&&t.append(U(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(U(`div`,`tcw-syminfo-meta`,e.meta));let n=document.createElement(`div`);if(n.className=`tcw-syminfo-quote`,e.price&&n.append(U(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=U(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),n.append(t)}let r=U(`div`,`tcw-syminfo-status`,e.status.text);r.dataset.state=e.status.state;let i=document.createElement(`dl`);i.className=`tcw-syminfo-stats`;for(let t of e.stats){let e=document.createElement(`div`);e.className=`tcw-syminfo-stat`,e.append(U(`dt`,``,t.label),U(`dd`,``,t.value)),i.append(e)}this.bodyEl.replaceChildren(t,n,r,i)}renderNews(e){if(this.newsEl.hidden=e.kind===`none`,e.kind===`none`){this.newsEl.replaceChildren();return}let t=U(`div`,`tcw-syminfo-news-title`,this.t(`symbolInfo.news`));if(e.kind===`loading`||e.kind===`failed`||e.items.length===0){let t=e.kind===`loading`?`symbolInfo.loading`:e.kind===`failed`?`symbolInfo.newsFailed`:`symbolInfo.noNews`;this.newsEl.replaceChildren(U(`div`,`tcw-syminfo-news-note`,this.t(t)));return}let n=document.createElement(`ul`);n.className=`tcw-syminfo-news-list`;for(let t of e.items){let e=document.createElement(`li`);if(e.className=`tcw-syminfo-news-item`,t.url){let n=document.createElement(`a`);n.href=t.url,n.target=`_blank`,n.rel=`noopener noreferrer`,n.textContent=t.title,e.append(n)}else e.append(U(`span`,``,t.title));t.meta&&e.append(U(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function U(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var _i=10,vi=5*6e4,yi=864e5,bi=2;function xi(e){let{info:r,quote:i,t:a,textLocale:o}=e,s=(0,n.symbolTimeZone)(r),c=Ci(e.bars,s),l=e.formatPrice,u=i?.last??c?.close,d=i?.prevClose??c?.prevClose,f=i?.change??(u!==void 0&&d!==void 0?u-d:void 0),p=u!==void 0&&f!==void 0?u-f:void 0,m=i?.changePercent??(f!==void 0&&p?f/p*100:void 0),h=(0,n.marketStatus)(r,e.now),g=a(h.state===`open`?`symbolInfo.open`:h.state===`closed`?`symbolInfo.closed`:`symbolInfo.always`);if(h.state!==`always`&&h.next!==null){let n=wi(h.next-e.now,o);g+=` · ${t.r(a(h.state===`open`?`symbolInfo.closesIn`:`symbolInfo.opensIn`),{when:n})}`}let ee=[],_=(e,t)=>{t&&ee.push({label:e,value:t})},v=e=>e===void 0?void 0:l(e);_(a(`dataWindow.open`),v(i?.open??c?.open)),_(a(`dataWindow.high`),v(i?.high??c?.high)),_(a(`dataWindow.low`),v(i?.low??c?.low)),_(a(`symbolInfo.prevClose`),v(d));let y=i?.volume??c?.volume;_(a(`dataWindow.volume`),y===void 0?void 0:Ei(y,e.numberLocale)),_(a(`symbolInfo.bid`),v(i?.bid)),_(a(`symbolInfo.ask`),v(i?.ask)),_(a(`symbolInfo.tick`),r?.minTick===void 0?void 0:String(r.minTick)),_(a(`symbolInfo.currency`),r?.currency),_(a(`symbolInfo.timezone`),s),_(a(`symbolInfo.hours`),Di(r,o));let b=(f??0)>=0?`+`:`-`,x=e.names===void 0?r:e.names;return{symbol:e.symbol,description:x?.description,meta:[x?.exchange,x?.type].filter(Boolean).join(` · `)||void 0,price:u===void 0?void 0:l(u),change:f===void 0?void 0:{text:`${b}${l(Math.abs(f))}${m===void 0?``:` (${b}${Ti(Math.abs(m),bi,e.numberLocale)}%)`}`,up:f>=0},status:{state:h.state,text:g},stats:ee}}var Si=class{request=0;cache=new Map;load(e,t,r,i,a){let o=++this.request;if(!t){r({kind:`none`});return}let s=e=>{let t=Date.now();r({kind:`items`,items:e.map(e=>({title:e.title,url:e.url,meta:[e.source,wi(e.time-t,i)].filter(Boolean).join(` · `)}))})},c=this.cache.get(e);if(c&&Date.now()-c.at<vi){s(c.items);return}r({kind:`loading`}),Promise.resolve().then(()=>t(e,_i)).then(t=>{if(o!==this.request||a())return;let r=(0,n.readNews)(t,_i);this.cache.set(e,{at:Date.now(),items:r}),s(r)}).catch(()=>{o===this.request&&!a()&&r({kind:`failed`})})}};function Ci(e,t){if(e.length===0)return null;let r=t&&(0,n.isValidTimeZone)(t)?t:null,i=(0,n.barTimeUnit)(e),a=e=>{let t=e*i;return Math.floor((t+(r?(0,n.zoneOffsetMinutes)(r,t)*6e4:0))/yi)},o=e[e.length-1],s=a(o.time),c=e.length-1;for(;c>0&&a(e[c-1].time)===s;)c--;let l=-1/0,u=1/0,d=0;for(let t=c;t<e.length;t++)l=Math.max(l,e[t].high),u=Math.min(u,e[t].low),d+=e[t].volume??0;return{open:e[c].open,high:l,low:u,close:o.close,volume:d,prevClose:c>0?e[c-1].close:void 0}}function wi(e,t){let n=e/6e4,[r,i]=Math.abs(n)<60?[Math.round(n)||Math.sign(n)||1,`minute`]:Math.abs(n)<1440?[Math.round(n/60),`hour`]:[Math.round(n/1440),`day`];try{return new Intl.RelativeTimeFormat(t,{numeric:`auto`}).format(r,i)}catch{return new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}).format(r,i)}}function Ti(e,t,r){try{return(0,n.formatPrice)(e,t,r)}catch{return e.toFixed(t)}}function Ei(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function Di(e,t){let n=e?.sessions??[];if(n.length===0)return;let r;try{let e=new Intl.DateTimeFormat(t,{weekday:`short`,timeZone:`UTC`});r=Array.from({length:7},(t,n)=>e.format(Date.UTC(1970,0,4+n)))}catch{r=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]}let i=e=>{let t=[...new Set((e??[]).filter(e=>Number.isInteger(e)&&e>=0&&e<=6))].sort((e,t)=>e-t);return t.length===0||t.length===7?``:t.every((e,n)=>n===0||e===t[n-1]+1)&&t.length>2?`${r[t[0]]}–${r[t[t.length-1]]}`:t.map(e=>r[e]).join(`, `)};return n.map(e=>[`${e.start}–${e.end}`,i(e.days)].filter(Boolean).join(` `)).join(`, `)}var Oi={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function ki(){let e={};for(let[t,n]of Object.entries(Oi))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var Ai=300,ji=80,Mi=n.PHI**-3,Ni=80,Pi=class{el;holdTimer=null;repeatTimer=null;pressed=!1;keyboardFocus=!1;onMove=e=>{if(e.pointerType!==`touch`&&!(this.holdTimer||this.repeatTimer)){if(!this.nearBottom(e)&&!this.keyboardFocus){this.el.classList.remove(`tcw-nav-shown`),this.stopHold();return}this.el.classList.contains(`tcw-nav-shown`)||this.place(),this.el.classList.add(`tcw-nav-shown`)}};onLeave=()=>{this.el.classList.remove(`tcw-nav-shown`),this.stopHold()};constructor(e,n,r=t.t){this.host=e,this.actions=n,this.el=document.createElement(`div`),this.el.className=`tcw-nav`,D(this.el,`navigation`),this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,r(`nav.label`));let i=[[`zoomOut`,`minus`,r(`nav.zoomOut`),`navigation.zoom`],[`zoomIn`,`plus`,r(`nav.zoomIn`),`navigation.zoom`],[`scrollLeft`,`chevronLeft`,r(`nav.scrollLeft`),`navigation.scroll`],[`scrollRight`,`chevronRight`,r(`nav.scrollRight`),`navigation.scroll`],[`reset`,`reset`,r(`nav.reset`),`navigation.reset`]];for(let[e,t,r,a]of i){let i=document.createElement(`button`);if(i.type=`button`,i.className=`tcw-nav-btn`,i.dataset.nav=e,D(i,a),i.title=r,i.setAttribute(`aria-label`,r),i.innerHTML=O(t,16),e===`scrollLeft`||e===`scrollRight`){let t=e===`scrollRight`?1:-1;i.addEventListener(`pointerdown`,e=>{if(e.button===0){e.preventDefault();try{i.setPointerCapture(e.pointerId)}catch{}this.startHold(t)}});for(let e of[`pointerup`,`pointercancel`,`pointerleave`])i.addEventListener(e,()=>this.stopHold());i.addEventListener(`click`,e=>{e.detail===0&&n.scroll(t)})}else i.addEventListener(`click`,()=>{e===`zoomIn`?n.zoomIn():e===`zoomOut`?n.zoomOut():n.reset()});this.el.appendChild(i)}for(let e of[`dblclick`,`contextmenu`,`pointerdown`,`mousedown`])this.el.addEventListener(e,e=>e.stopPropagation());this.el.addEventListener(`pointerdown`,()=>{this.pressed=!0},{capture:!0}),this.el.addEventListener(`pointerup`,()=>{this.pressed=!1},{capture:!0}),this.el.addEventListener(`focusin`,()=>{this.keyboardFocus=!this.pressed,this.pressed=!1,this.place(),this.el.classList.add(`tcw-nav-shown`)}),this.el.addEventListener(`focusout`,e=>{this.el.contains(e.relatedTarget)||(this.keyboardFocus=!1,this.el.classList.remove(`tcw-nav-shown`))}),e.appendChild(this.el),e.addEventListener(`pointermove`,this.onMove),e.addEventListener(`pointerleave`,this.onLeave)}destroy(){this.stopHold(),this.host.removeEventListener(`pointermove`,this.onMove),this.host.removeEventListener(`pointerleave`,this.onLeave),this.el.remove()}nearBottom(e){let t=this.actions.plotRect(),n=this.host.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=Math.max(Ni,t.height*Mi);return r>=t.x&&r<=t.x+t.width&&i<=t.y+t.height&&i>=t.y+t.height-a}place(){let e=this.actions.plotRect();this.el.style.left=`${Math.round(e.x+e.width/2)}px`,this.el.style.top=`${Math.round(e.y+e.height)}px`}startHold(e){this.stopHold(),this.actions.scroll(e),this.holdTimer=setTimeout(()=>{this.repeatTimer=setInterval(()=>this.actions.scroll(e),ji)},Ai)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function Fi(e,n,r,i=!1){let a=e.label??n(`alerts.source.price`),o=Bi.get(e.condition),s=o?n(o):e.condition;if(Li.includes(e.condition))return`${a} ${s} ${t.r(n(`alerts.moveSummary`),{percent:e.percent??0,bars:e.bars??0})}`;if(e.target)return`${a} ${s} ${e.targetLabel??e.target}`;let c=e.channel&&e.channel!==`price`,l=Number.isFinite(e.price)?c?Hi(e.price):r(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:i?`${a} `:``}${s} ${l}`}var Ii=[{value:`crossing`,key:`alerts.condition.crossing`},{value:`crossingUp`,key:`alerts.condition.crossingUp`},{value:`crossingDown`,key:`alerts.condition.crossingDown`},{value:`greaterThan`,key:`alerts.condition.greaterThan`},{value:`lessThan`,key:`alerts.condition.lessThan`},{value:`movesUp`,key:`alerts.condition.movesUp`},{value:`movesDown`,key:`alerts.condition.movesDown`}],Li=[`movesUp`,`movesDown`],Ri={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},zi=``,Bi=new Map(Ii.map(e=>[e.value,e.key]));function Vi(e){return Math.round(e*1e6)/1e6}function Hi(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var Ui=class{el;listEl;priceInput;conditionSelect;sourceSelect;targetSelect;percentInput;barsInput;levelRow;moveRow;closeCheck;expirySelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources;constructor(e,n,i=t.t){this.t=i,this.callbacks=n,this.sources=[{channel:`price`,label:this.t(`alerts.source.price`)}],this.el=document.createElement(`div`),this.el.className=`tcw-alerts-panel`,D(this.el,`alerts`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-alerts-header`;let o=document.createElement(`span`);o.textContent=this.t(`alerts.title`);let s=document.createElement(`button`);s.className=`tcw-alerts-close`,s.type=`button`,s.setAttribute(`aria-label`,this.t(`alerts.close`)),s.innerHTML=O(`x`,14),s.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a);let c=document.createElement(`form`);c.className=`tcw-alerts-form`,c.noValidate=!0,this.sourceSelect=document.createElement(`select`),this.sourceSelect.className=`tcw-alerts-source`,this.sourceSelect.setAttribute(`aria-label`,this.t(`alerts.source`)),this.sourceSelect.addEventListener(`change`,()=>{this.renderTargets(),this.prefillPrice()}),this.conditionSelect=document.createElement(`select`),this.conditionSelect.className=`tcw-alerts-condition`,this.conditionSelect.setAttribute(`aria-label`,this.t(`alerts.conditionLabel`));for(let e of Ii){let t=document.createElement(`option`);t.value=e.value,t.textContent=this.t(e.key),this.conditionSelect.appendChild(t)}this.conditionSelect.addEventListener(`change`,()=>this.showFields()),this.levelRow=document.createElement(`div`),this.levelRow.className=`tcw-alerts-row-fields`,this.targetSelect=document.createElement(`select`),this.targetSelect.className=`tcw-alerts-target`,this.targetSelect.setAttribute(`aria-label`,this.t(`alerts.compareWith`)),this.targetSelect.addEventListener(`change`,()=>this.showFields()),this.priceInput=document.createElement(`input`),this.priceInput.type=`number`,this.priceInput.step=`any`,this.priceInput.placeholder=this.t(`alerts.value`),this.priceInput.setAttribute(`aria-label`,this.t(`alerts.value`)),this.priceInput.className=`tcw-alerts-price`,this.levelRow.append(this.targetSelect,this.priceInput),this.moveRow=document.createElement(`div`),this.moveRow.className=`tcw-alerts-row-fields`,this.percentInput=this.numberField(`tcw-alerts-percent`,this.t(`alerts.percent`),`1`,`0.01`),this.barsInput=this.numberField(`tcw-alerts-bars`,this.t(`alerts.bars`),`10`,`1`),this.barsInput.min=String(r.MIN_ALERT_BARS),this.barsInput.max=String(r.MAX_ALERT_BARS),this.moveRow.append(this.percentInput,this.barsInput);let l=document.createElement(`div`);l.className=`tcw-alerts-row-fields tcw-alerts-options`;let u=document.createElement(`label`);u.className=`tcw-alerts-check`,this.closeCheck=document.createElement(`input`),this.closeCheck.type=`checkbox`,u.append(this.closeCheck,document.createTextNode(this.t(`alerts.onBarClose`))),this.expirySelect=document.createElement(`select`),this.expirySelect.className=`tcw-alerts-expiry`,this.expirySelect.setAttribute(`aria-label`,this.t(`alerts.expires`));for(let e of[`never`,`hour`,`day`,`week`,`month`]){let t=document.createElement(`option`);t.value=e,t.textContent=this.t(`alerts.expires.${e}`),this.expirySelect.appendChild(t)}l.append(u,this.expirySelect),this.messageInput=document.createElement(`input`),this.messageInput.type=`text`,this.messageInput.placeholder=this.t(`alerts.note`),this.messageInput.setAttribute(`aria-label`,this.t(`alerts.note`)),this.messageInput.className=`tcw-alerts-message`;let d=document.createElement(`button`);d.type=`submit`,d.className=`tcw-alerts-add`,d.innerHTML=`${O(`plus`,14)}<span>${k(this.t(`alerts.add`))}</span>`,c.append(this.sourceSelect,this.conditionSelect,this.levelRow,this.moveRow,l,this.messageInput,d),c.addEventListener(`submit`,e=>{e.preventDefault(),this.submitForm()}),this.el.appendChild(c),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-alerts-list`,this.el.appendChild(this.listEl),this.emptyEl=document.createElement(`div`),this.emptyEl.className=`tcw-alerts-empty`,this.emptyEl.textContent=this.t(`alerts.empty`),this.listEl.appendChild(this.emptyEl),this.renderSources(),this.showFields(),e.appendChild(this.el)}numberField(e,t,n,r){let i=document.createElement(`input`);return i.type=`number`,i.step=r,i.min=`0`,i.value=n,i.className=e,i.placeholder=t,i.setAttribute(`aria-label`,t),i}showFields(){let e=Li.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==zi}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=zi,n.textContent=this.t(`alerts.compare.value`),this.targetSelect.appendChild(n);for(let e of this.sources){if(e.channel===t)continue;let n=document.createElement(`option`);n.value=e.channel,n.textContent=e.label,this.targetSelect.appendChild(n)}this.targetSelect.value=[...this.targetSelect.options].some(t=>t.value===e)?e:zi,this.showFields()}setSources(e){this.sources=e.length>0?e:[{channel:`price`,label:this.t(`alerts.source.price`)}],this.renderSources()}renderSources(){let e=this.sourceSelect.value||`price`;this.sourceSelect.replaceChildren();for(let e of this.sources){let t=document.createElement(`option`);t.value=e.channel,t.textContent=e.label,this.sourceSelect.appendChild(t)}this.sourceSelect.value=this.sources.some(t=>t.channel===e)?e:`price`,this.renderTargets()}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.priceInput.value===``&&this.prefillPrice()}prefillPrice(){let e=this.callbacks.getChannelValue(this.sourceSelect.value||`price`);this.priceInput.value=e===null?``:String(Vi(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,this.renderList()}destroy(){this.el.remove()}submitForm(){let e=this.conditionSelect.value,t=this.messageInput.value.trim()||void 0,n=this.sourceSelect.value||`price`,i=this.sources.find(e=>e.channel===n)?.label??this.t(`alerts.source.price`),a={},o=NaN;if(Li.includes(e)){a.percent=Number(this.percentInput.value),a.bars=Number(this.barsInput.value);let e=Number.isInteger(a.bars)&&a.bars>=r.MIN_ALERT_BARS&&a.bars<=r.MAX_ALERT_BARS;if(!(a.percent>0)||!e){this.markInvalid(a.percent>0?this.barsInput:this.percentInput);return}}else if(this.targetSelect.value!==zi)a.target=this.targetSelect.value;else if(o=Number(this.priceInput.value),this.priceInput.value.trim()===``||!Number.isFinite(o)){this.markInvalid(this.priceInput);return}this.closeCheck.checked&&(a.onBarClose=!0);let s=Ri[this.expirySelect.value];s&&(a.expiresAt=(this.callbacks.now??Date.now)()+s),this.callbacks.onAdd({price:o,condition:e,message:t,channel:n,label:i,options:a})!==!1&&(this.messageInput.value=``,this.prefillPrice())}markInvalid(e){e.setAttribute(`aria-invalid`,`true`),e.focus(),e.addEventListener(`input`,()=>e.removeAttribute(`aria-invalid`),{once:!0})}describe(e){return Fi(e,this.t,this.callbacks.formatPrice)}renderList(){if(this.listEl.replaceChildren(),this.alerts.length===0){this.listEl.appendChild(this.emptyEl);return}for(let e of[...this.alerts].reverse()){let n=document.createElement(`div`);n.className=`tcw-alerts-row`+(e.triggered?` tcw-alerts-triggered`:``)+(e.expired?` tcw-alerts-expired`:``);let r=document.createElement(`div`);r.className=`tcw-alerts-info`;let i=document.createElement(`div`);i.className=`tcw-alerts-row-main`,i.textContent=this.describe(e),r.appendChild(i);let a=[];if(e.onBarClose&&a.push(this.t(`alerts.onClose`)),e.expiresAt!==void 0&&!e.expired){let n=this.callbacks.formatTime?.(e.expiresAt)??new Date(e.expiresAt).toISOString();a.push(t.r(this.t(`alerts.until`),{time:n}))}if(a.length>0){let e=document.createElement(`div`);e.className=`tcw-alerts-row-meta`,e.textContent=a.join(` · `),r.appendChild(e)}if(e.message){let t=document.createElement(`div`);t.className=`tcw-alerts-row-note`,t.textContent=e.message,r.appendChild(t)}if(e.triggered||e.expired){let t=document.createElement(`span`);t.className=`tcw-alerts-badge`,t.textContent=this.t(e.expired?`alerts.expired`:`alerts.triggered`),i.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-alerts-del`,o.setAttribute(`aria-label`,this.t(`alerts.delete`)),o.innerHTML=O(`trash`,14),o.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),n.appendChild(r),n.appendChild(o),this.listEl.appendChild(n)}}};function Wi(e){return Object.prototype.hasOwnProperty.call(t.c,e)}function Gi(e,t){let n=`indicatorInput.${e}`;return Wi(n)?t(n):null}function Ki(e,t,n){let r=`indicatorInput.${e}.${t}`;return Wi(r)?n(r):null}function qi(t,n){let{defaultConfig:r,shortName:i,inputs:a}=t.descriptor,o=Object.entries(a??{}).flatMap(([e,i])=>{let a=t.params[e];return!i.options||typeof a!=`string`&&typeof a!=`number`||a===r[e]?[]:Ki(e,a,n)??[]});return[e.O(t.id,t.params,r,i),...o].join(` `)}var Ji=`print`,Yi=3,Xi=10,Zi=[[3400,1/2],[2560,1/3],[1800,1/6]],Qi=.75,$i=2;function ea(e){let t=Zi.find(([t])=>e>=t);return t?n.PHI**t[1]:1}function ta(e,t){if(t===1)return e;let n=e.sizes,r=e=>Math.round(e*t);return{...e,sizes:{toolbar:r(n.toolbar),control:r(n.control),controlSmall:r(n.controlSmall),icon:r(n.icon),sidebar:r(n.sidebar),menuItem:r(n.menuItem)},font:{...e.font,size:r(e.font.size)}}}function na(e,t){return Math.max(Xi,(0,n.phiStep)(e,t,Yi))}var ra=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,ia=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,aa=n.SANS_FONT_FAMILY,oa=`'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`,sa=`Tahoma, Verdana, 'Segoe UI', 'DejaVu Sans', sans-serif`,ca={print:{radius:{xs:1,sm:2,md:3,lg:5,xl:8},components:{tag:2,toolbar:0,sidebar:0},sizes:{toolbar:42,control:26,controlSmall:20,icon:16,sidebar:42,menuItem:33},density:{compact:{toolbar:33,control:20,controlSmall:20,icon:16,sidebar:33,menuItem:26},spacious:{toolbar:53,control:33,controlSmall:26,icon:20,sidebar:53,menuItem:42}},font:{family:aa,mono:oa,size:13,weight:400,strongWeight:600,labelCase:`uppercase`,labelTracking:.06},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border), var(--tcw-shadow-md)`,dialog:`0 0 0 1px var(--tcw-border), var(--tcw-shadow-lg)`,tooltip:`var(--tcw-shadow-sm)`},blur:0,active:`solid`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:2},studio:{radius:{xs:3,sm:5,md:7,lg:11,xl:16},components:{toolbar:0,sidebar:0},sizes:{toolbar:46,control:30,controlSmall:24,icon:18,sidebar:48,menuItem:30},font:{family:`'Manrope', 'Inter', ${ra}`,mono:ia,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`var(--tcw-shadow-lg)`,dialog:`var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-md)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`segmented`,tagRadius:4},terminal:{radius:{xs:1,sm:2,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:36,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${ra}`,mono:`'IBM Plex Mono', ui-monospace, monospace`,size:12,weight:500,strongWeight:600,labelCase:`uppercase`,labelTracking:.08},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-lg)`,tooltip:`none`},blur:0,active:`underline`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0},capsule:{radius:{xs:6,sm:10,md:999,lg:18,xl:24},components:{tooltip:10,toolbar:999,sidebar:999,toast:999,tag:999},sizes:{toolbar:44,control:32,controlSmall:26,icon:18,sidebar:48,menuItem:34},font:{family:`'Sora', 'Manrope', ${ra}`,mono:ia,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,dialog:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-lg)`},blur:16,active:`solid`,toolbar:`floating`,sidebar:`floating`,intervals:`segmented`,tagRadius:999},desk:{radius:{xs:0,sm:1,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:34,control:24,controlSmall:20,icon:16,sidebar:36,menuItem:24},font:{family:sa,mono:sa,size:12,weight:400,strongWeight:700,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-sm)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-md)`,tooltip:`0 0 0 1px var(--tcw-border)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0}},la={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:54,menuItem:34}};function ua(e,t){return{control:e.md,input:e.md,menu:e.lg,dialog:e.xl,panel:e.lg,tooltip:e.sm,tag:e.sm,toast:e.lg,toolbar:0,sidebar:0,...t}}var da=Object.freeze(Object.fromEntries(Object.keys(ca).map(e=>[e,pa(fa(e))])));function fa(e){let{density:t,...n}=ca[e];return{...n,preset:e,density:`comfortable`,scale:`auto`,radius:{...n.radius},components:ua(n.radius,n.components),sizes:{...n.sizes},font:{...n.font},borders:{...n.borders},shadows:{...n.shadows}}}function pa(e){for(let t of Object.values(e))t&&typeof t==`object`&&pa(t);return Object.freeze(e)}var ma=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(ca,e),W=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,ha=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&ga(e);function ga(e){let t=0,n=``;for(let r of e)if(n)r===n&&(n=``);else if(r===`"`||r===`'`)n=r;else if(r===`(`)t++;else if(r===`)`&&--t<0)return!1;return t===0&&!n}var _a=(e,t)=>typeof e==`string`&&t.includes(e);function va(e,t,n){let r={...e};if(!t||typeof t!=`object`)return r;for(let i of Object.keys(e)){let e=t[i];e!==void 0&&n(i,e)&&(r[i]=e)}return r}function G(e){let t=typeof e==`string`?{preset:e}:e??{},n=ma(t.preset)?t.preset:Ji,r=ca[n],i=va(r.radius,t.radius,(e,t)=>W(t,0,999)),a=_a(t.density,[`compact`,`comfortable`,`spacious`,`airy`])?t.density:`comfortable`,o=a===`airy`?`spacious`:a,s=va(o===`compact`||o===`spacious`?(r.density??la)[o]:r.sizes,t.sizes,(e,t)=>e===`icon`?W(t,10,32):W(t,16,80)),c=va(r.font,t.font,(e,t)=>e===`family`||e===`mono`?ha(t):e===`size`?W(t,11,20):e===`weight`||e===`strongWeight`?W(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:W(t,0,.5)),l=a===`airy`&&t.font?.mono===void 0?{...c,mono:c.family}:c;return{preset:n,density:a,radius:i,components:va(ua(i,r.components),t.components,(e,t)=>W(t,0,999)),sizes:s,font:l,borders:va(r.borders,t.borders,(e,t)=>e===`width`?W(t,0,4):typeof t==`boolean`),shadows:va(r.shadows,t.shadows,(e,t)=>ha(t)),blur:W(t.blur,0,40)?t.blur:r.blur,active:_a(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:_a(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:_a(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:_a(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:W(t.tagRadius,0,999)?t.tagRadius:r.tagRadius,scale:typeof t.scale==`number`&&Number.isFinite(t.scale)&&t.scale>=Qi&&t.scale<=$i?t.scale:`auto`}}function ya(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font;return{"--tcw-radius-xs":t(n.xs),"--tcw-radius-sm":t(n.sm),"--tcw-radius":t(n.md),"--tcw-radius-lg":t(n.lg),"--tcw-radius-xl":t(n.xl),"--tcw-control-radius":t(r.control),"--tcw-input-radius":t(r.input),"--tcw-menu-radius":t(r.menu),"--tcw-dialog-radius":t(r.dialog),"--tcw-panel-radius":t(r.panel),"--tcw-tooltip-radius":t(r.tooltip),"--tcw-tag-radius":t(r.tag),"--tcw-toast-radius":t(r.toast),"--tcw-toolbar-radius":t(r.toolbar),"--tcw-sidebar-radius":t(r.sidebar),"--tcw-toolbar-h":t(i.toolbar),"--tcw-control-h":t(i.control),"--tcw-control-h-sm":t(i.controlSmall),"--tcw-icon":t(i.icon),"--tcw-sidebar-w":t(i.sidebar),"--tcw-menu-item-h":t(i.menuItem),"--tcw-font":a.family,"--tcw-font-mono":a.mono,"--tcw-font-size":t(a.size),"--tcw-font-size-sm":t(na(a.size,-1)),"--tcw-font-size-xs":t(na(a.size,-2)),"--tcw-font-size-lg":t(na(a.size,1)),"--tcw-font-size-xl":t(na(a.size,2)),"--tcw-font-size-display":t(na(a.size,3)),"--tcw-weight":String(a.weight),"--tcw-weight-strong":String(a.strongWeight),"--tcw-label-case":a.labelCase,"--tcw-label-tracking":`${a.labelTracking}em`,"--tcw-border-w":t(e.borders.width),"--tcw-sep-w":e.borders.separators?t(Math.max(1,e.borders.width)):`0px`,"--tcw-menu-shadow":e.shadows.menu,"--tcw-dialog-shadow":e.shadows.dialog,"--tcw-tooltip-shadow":e.shadows.tooltip,"--tcw-blur":t(e.blur),"--tcw-surface-opacity":e.blur>0?`82%`:`100%`}}function ba(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(ya(t)))r?e.style.setProperty(n,i):e.style.removeProperty(n);e.dataset.tcwUi=t.preset,e.dataset.tcwActive=t.active,e.dataset.tcwToolbar=t.toolbar,e.dataset.tcwSidebar=t.sidebar,e.dataset.tcwIntervals=t.intervals,e.dataset.tcwSeparators=t.borders.separators?`on`:`off`}var xa=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;drawingIndex=new Map;loose=[];pending=null;renaming=!1;dragging=null;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,D(this.el,`objectTree`),this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-tree-header`;let a=document.createElement(`span`);a.textContent=this.t(`objects.title`);let o=document.createElement(`button`);if(o.type=`button`,o.className=`tcw-tree-close`,o.setAttribute(`aria-label`,this.t(`objects.close`)),o.innerHTML=O(`x`,14),o.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),i.appendChild(a),i.appendChild(o),this.el.appendChild(i),this.indicatorsEl=this.makeSection(this.t(`objects.indicators`)),this.drawingsEl=this.makeSection(this.t(`objects.drawings`)),this.callbacks.onAddCompare){this.compareEl=this.makeSection(this.t(`objects.compare`),{label:this.t(`objects.addCompare`),run:()=>this.callbacks.onAddCompare?.()});let e=this.compareEl.parentElement?.querySelector(`.tcw-tree-add`);e&&D(e,`compare`)}e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.pending=null,this.dragging?.stop(),this.el.remove()}setObjects(e,t,n=[]){this.renderIndicators(e),this.renderDrawings(t),this.renderCompares(n)}makeSection(e,t){let n=document.createElement(`div`);n.className=`tcw-tree-section`;let r=document.createElement(`div`);r.className=`tcw-tree-section-head`;let i=document.createElement(`span`);if(i.textContent=e,r.appendChild(i),t){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-add`,e.setAttribute(`aria-label`,t.label),e.title=t.label,e.innerHTML=O(`plus`,13),e.addEventListener(`click`,t.run),r.appendChild(e)}let a=document.createElement(`div`);return a.className=`tcw-tree-list`,n.appendChild(r),n.appendChild(a),this.el.appendChild(n),a}renderIndicators(e){if(this.indicatorsEl.replaceChildren(),e.length===0){this.indicatorsEl.appendChild(this.emptyRow(this.t(`objects.noIndicators`)));return}for(let t of e){let e=this.row(t.name,t.title);t.visible||e.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);if(n.className=`tcw-tree-actions`,this.callbacks.onToggleIndicatorVisible&&n.appendChild(this.iconButton(t.visible?`eye`:`eyeOff`,t.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleIndicatorVisible?.(t.instanceId,!t.visible))),this.callbacks.onConfigureIndicator){let e=this.iconButton(`settings`,this.t(`objects.indicatorSettings`),``,()=>this.callbacks.onConfigureIndicator?.(t.instanceId));D(e,`indicatorSettings`),n.appendChild(e)}n.appendChild(this.iconButton(`trash`,this.t(`objects.removeIndicator`),`tcw-tree-del`,()=>this.callbacks.onRemoveIndicator(t.instanceId))),e.appendChild(n),this.indicatorsEl.appendChild(e)}}renderDrawings(e){if(this.renaming||this.dragging){this.pending=e;return}this.pending=null;let t=document.activeElement?.closest(`.tcw-tree-grip`)?.closest(`[data-drawing-id]`)?.dataset.drawingId;this.drawingIndex=new Map(e.map((e,t)=>[e.id,t]));let n=[...e].reverse();this.loose=n.filter(e=>!e.group).map(e=>e.id),this.drawingsEl.replaceChildren(),this.listDrawings(n),t&&this.drawingsEl.querySelector(`[data-drawing-id="${t}"] .tcw-tree-grip`)?.focus()}flushPending(){this.pending&&!this.renaming&&!this.dragging&&this.renderDrawings(this.pending)}listDrawings(e){if(e.length===0){this.drawingsEl.appendChild(this.emptyRow(this.t(`objects.noDrawings`)));return}let t=new Set;for(let n of e){if(!n.group){this.drawingsEl.appendChild(this.drawingRow(n));continue}if(t.has(n.group.id))continue;t.add(n.group.id);let r=n.group.id,i=e.filter(e=>e.group?.id===r);this.drawingsEl.appendChild(this.groupRow(r,n.group.name,i));for(let e of i){let t=this.drawingRow(e);t.classList.add(`tcw-tree-member`),this.drawingsEl.appendChild(t)}}}groupRow(e,t,n){let r=this.row(t);r.classList.add(`tcw-tree-group`);let i=n.some(e=>e.visible),a=n.every(e=>e.locked);i||r.classList.add(`tcw-tree-hidden`);let o=r.querySelector(`.tcw-tree-name`);o.innerHTML=O(`layers`,13),o.append(` ${t}`);let s=document.createElement(`div`);return s.className=`tcw-tree-actions`,this.callbacks.onRenameGroup&&(o.addEventListener(`dblclick`,()=>this.renameGroup(o,e,t)),s.appendChild(this.iconButton(`penLine`,this.t(`objects.renameGroup`),``,()=>this.renameGroup(o,e,t)))),this.callbacks.onToggleGroupVisible&&s.appendChild(this.iconButton(i?`eye`:`eyeOff`,i?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleGroupVisible?.(e,!i))),this.callbacks.onToggleGroupLocked&&s.appendChild(this.iconButton(a?`lock`:`unlock`,a?this.t(`common.unlock`):this.t(`common.lock`),a?`tcw-tree-on`:``,()=>this.callbacks.onToggleGroupLocked?.(e,!a))),this.callbacks.onUngroup&&s.appendChild(this.iconButton(`x`,this.t(`drawingMenu.ungroup`),``,()=>this.callbacks.onUngroup?.(e))),r.appendChild(s),r}renameGroup(e,t,n){this.renameInline(e,n,this.t(`objects.renameGroup`),e=>{e&&e!==n&&this.callbacks.onRenameGroup?.(t,e)})}renameInline(e,t,n,r){if(!e.isConnected)return;this.renaming=!0;let i=document.createElement(`input`);i.type=`text`,i.className=`tcw-tree-rename`,i.value=t,i.maxLength=Sa,i.setAttribute(`aria-label`,n);let a=!1,o=t=>{if(a)return;a=!0;let n=i.value.trim();i.isConnected&&i.replaceWith(e),this.renaming=!1,t&&r(n),this.flushPending()};i.addEventListener(`keydown`,e=>{e.key===`Enter`?o(!0):e.key===`Escape`&&(e.stopPropagation(),o(!1))}),i.addEventListener(`blur`,()=>o(!0)),e.replaceWith(i),i.focus(),i.select()}drawingRow(e){let t=this.row(e.label);t.dataset.drawingId=e.id,(!e.visible||e.offInterval)&&t.classList.add(`tcw-tree-hidden`),e.offInterval&&(t.title=this.t(`indicatorSettings.offInterval`)),this.callbacks.onMoveDrawing&&!e.group&&(t.dataset.reorder=`true`,t.insertBefore(this.grip(e.id),t.firstChild));let n=t.querySelector(`.tcw-tree-name`);this.callbacks.onSelectDrawing&&(n.classList.add(`tcw-tree-pick`),n.addEventListener(`click`,()=>this.callbacks.onSelectDrawing?.(e.id))),this.callbacks.onRenameDrawing&&n.addEventListener(`dblclick`,()=>this.renameInline(n,e.label,this.t(`objects.renameDrawing`),t=>{t!==e.label&&this.callbacks.onRenameDrawing?.(e.id,t)}));let r=document.createElement(`div`);if(r.className=`tcw-tree-actions`,r.appendChild(this.iconButton(e.visible?`eye`:`eyeOff`,e.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleDrawingVisible(e.id,!e.visible))),r.appendChild(this.iconButton(e.locked?`lock`:`unlock`,e.locked?this.t(`common.unlock`):this.t(`common.lock`),e.locked?`tcw-tree-on`:``,()=>this.callbacks.onToggleDrawingLocked(e.id,!e.locked))),this.callbacks.onCloneDrawing&&r.appendChild(this.iconButton(`copy`,this.t(`objects.cloneDrawing`),``,()=>this.callbacks.onCloneDrawing?.(e.id))),this.callbacks.onConfigureDrawing){let t=this.iconButton(`settings`,this.t(`objects.drawingSettings`),``,()=>this.callbacks.onConfigureDrawing?.(e.id));D(t,`drawingSettings`),r.appendChild(t)}return r.appendChild(this.iconButton(`trash`,this.t(`objects.removeDrawing`),`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(e.id))),t.appendChild(r),t}grip(e){let t=this.iconButton(`grip`,this.t(`objects.dragToReorder`),`tcw-tree-grip`,()=>{});return t.setAttribute(`aria-keyshortcuts`,`ArrowUp ArrowDown`),t.addEventListener(`pointerdown`,t=>{t.button===0&&(t.preventDefault(),this.beginRowDrag(e))}),t.addEventListener(`keydown`,t=>{let n=t.key===`ArrowUp`?-1:+(t.key===`ArrowDown`);if(!n)return;t.preventDefault();let r=this.loose[this.loose.indexOf(e)+n],i=r===void 0?void 0:this.drawingIndex.get(r);i!==void 0&&this.callbacks.onMoveDrawing?.(e,i)}),t}beginRowDrag(e){this.dragging?.stop();let t=null,n=n=>{t?.classList.remove(`tcw-tree-drop`),t=n&&n.dataset.drawingId!==e?n:null,t?.classList.add(`tcw-tree-drop`)},r=(e,t)=>[...this.drawingsEl.querySelectorAll(`.tcw-tree-row[data-reorder]`)].find(n=>{let r=n.getBoundingClientRect();return t>=r.top&&t<r.bottom&&e>=r.left&&e<r.right})??null,i=e=>r(e.clientX,e.clientY),a=e=>n(i(e)),o=e=>{e.key===`Escape`&&(e.stopPropagation(),c())},s=r=>{n(i(r));let a=t?this.drawingIndex.get(t.dataset.drawingId??``):void 0;c(),a!==void 0&&this.callbacks.onMoveDrawing?.(e,a)},c=()=>{n(null),document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,s),document.removeEventListener(`pointercancel`,c),document.removeEventListener(`keydown`,o,!0),this.dragging=null,this.flushPending()};document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,s),document.addEventListener(`pointercancel`,c),document.addEventListener(`keydown`,o,!0),this.dragging={id:e,stop:c}}renderCompares(e){if(!this.compareEl)return;if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(this.t(`objects.noComparisons`)));return}let t=e.some(e=>e.color);for(let n of e){let e=this.row(n.label);if(e.classList.add(`tcw-tree-compare`),t){let t=document.createElement(`span`);t.className=`tcw-tree-dot`,n.color&&(t.style.background=n.color),e.insertBefore(t,e.firstChild)}if(n.way){let t=document.createElement(`span`);t.className=`tcw-tree-way`,t.textContent=n.way,t.title=n.way,e.appendChild(t)}this.callbacks.onRemoveCompare&&e.appendChild(this.iconButton(`trash`,this.t(`objects.removeComparison`),`tcw-tree-del`,()=>this.callbacks.onRemoveCompare?.(n.id))),this.compareEl.appendChild(e)}}row(e,t=e){let n=document.createElement(`div`);n.className=`tcw-tree-row`;let r=document.createElement(`span`);return r.className=`tcw-tree-name`,r.textContent=e,r.title=t,n.appendChild(r),n}emptyRow(e){let t=document.createElement(`div`);return t.className=`tcw-tree-empty`,t.textContent=e,t}iconButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-tree-btn ${n}`.trim(),i.setAttribute(`aria-label`,t),i.title=t,i.innerHTML=O(e,14),i.addEventListener(`click`,r),i}},Sa=80,Ca={trendLine:`Trend Line`,ray:`Ray`,extendedLine:`Extended Line`,horizontalLine:`Horizontal Line`,horizontalRay:`Horizontal Ray`,crossLine:`Cross Line`,infoLine:`Info Line`,trendAngle:`Trend Angle`,circle:`Circle`,fibChannel:`Fib Channel`,fibSpeedResistanceFan:`Fib Speed Resistance Fan`,schiffPitchfork:`Schiff Pitchfork`,modifiedSchiffPitchfork:`Modified Schiff Pitchfork`,xabcdPattern:`XABCD Pattern`,abcdPattern:`ABCD Pattern`,headAndShoulders:`Head and Shoulders`,dateAndPriceRange:`Date and Price Range`,cyclicLines:`Cyclic Lines`,priceLabel:`Price Label`,verticalLine:`Vertical Line`,rectangle:`Rectangle`,ellipse:`Ellipse`,triangle:`Triangle`,arrow:`Arrow`,parallelChannel:`Parallel Channel`,regressionChannel:`Regression Channel`,pitchfork:`Pitchfork`,fibRetracement:`Fib Retracement`,fibExtension:`Fib Extension`,fibTimeZones:`Fib Time Zones`,gannBox:`Gann Box`,gannFan:`Gann Fan`,elliottWave:`Elliott Wave`,priceRange:`Price Range`,dateRange:`Date Range`,measure:`Measure`,text:`Text`,textAnnotation:`Text`,anchoredVWAP:`Anchored VWAP`,volumeProfileRange:`Volume Profile`,riskReward:`Long/Short Position`,signpost:`Signpost`,balloon:`Balloon`,anchoredText:`Anchored Text`,anchoredNote:`Anchored Note`};function wa(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:Ca[e]??e}var Ta=[1,1.5,2,3,4],Ea=[`solid`,`dashed`,`dotted`],Da=`#4c8dff`,Oa=10,ka={ticks:`toolbar.timeframes.ticks`,seconds:`toolbar.timeframes.seconds`,minutes:`toolbar.timeframes.minutes`,hours:`toolbar.timeframes.hours`,days:`toolbar.timeframes.days`,weeks:`toolbar.timeframes.weeks`,months:`toolbar.timeframes.months`};function Aa(e,t,n,r,i){let a=Fa();for(let e of[...t.plots].sort((e,t)=>e.color-t.color))a.appendChild(ja(e,t,n,r));let o=I(Ta.map(e=>({value:String(e),label:`${e} px`})),String(t.lineWidth),e=>n.lineWidth(Number(e)));if(o.dataset.role=`line-width`,a.appendChild(N(r(`indicatorSettings.lineWidth`),o)),t.scale&&n.scale){let e=I([{value:`right`,label:r(`indicatorSettings.scale.right`)},{value:`left`,label:r(`indicatorSettings.scale.left`)}],t.scale,e=>n.scale?.(e===`left`?`left`:`right`));e.dataset.role=`scale`,a.appendChild(N(r(`indicatorSettings.scale`),e))}e.appendChild(a),t.levels&&n.levels&&e.appendChild(Ma([...t.levels],n.levels,r,i))}function ja(e,t,n,r){let i=t.plotStyles[e.key]??{},a=document.createElement(`div`);a.className=`tcw-settings-row tcw-indi-plot`,a.dataset.plot=e.key;let o=document.createElement(`label`);o.className=`tcw-indi-plot-name`;let s=document.createElement(`input`);s.type=`checkbox`,s.checked=i.visible!==!1,s.addEventListener(`change`,()=>n.plot(e.key,{visible:s.checked}));let c=document.createElement(`span`);c.className=`tcw-settings-label`,c.textContent=e.title,o.append(s,c);let l=document.createElement(`span`);l.className=`tcw-indi-plot-controls`;let u=(e,r)=>{let i=F(t.colors[e]??t.colors[0]??Da,t=>n.color(e,t));return i.setAttribute(`aria-label`,r),i};if(e.tone!==void 0&&e.downColor!==void 0?l.append(u(e.color,`${e.title} ${r(`indicatorSettings.up`)}`),u(e.downColor,`${e.title} ${r(`indicatorSettings.down`)}`)):l.appendChild(u(e.color,e.title)),(e.kind??`line`)===`line`||e.kind===`step`){let t=I(Ea.map(e=>({value:e,label:r(`drawingSettings.lineStyle.${e}`)})),i.lineStyle??`solid`,t=>n.plot(e.key,{lineStyle:t}));t.setAttribute(`aria-label`,`${e.title}: ${r(`drawingSettings.lineStyle`)}`),l.appendChild(t)}return a.append(o,l),a}function Ma(e,t,n,r){let i=Fa(),a=e,o=()=>{let e=document.createElement(`div`);e.className=`tcw-settings-section-title`,e.textContent=n(`indicatorSettings.tab.levels`);let t=a.map((e,t)=>c(e,t)),r=document.createElement(`button`);r.type=`button`,r.className=`tcw-reset-link tcw-indi-add`,r.textContent=`+ ${n(`indicatorSettings.addLevel`)}`,r.addEventListener(`click`,()=>{let e=a[a.length-1];s([...a,e===void 0?0:e+Oa]);let t=i.querySelectorAll(`.tcw-indi-level input`);t[t.length-1]?.focus()}),i.replaceChildren(e,...a.length===0?[Ia(n(`indicatorSettings.noLevels`))]:t,r)},s=e=>{a=e,t([...e]),o()},c=(e,o)=>{let c=P(e,{step:`any`},e=>{a=a.map((t,n)=>n===o?e:t),t([...a])});c.id=`tcw-indi-level-${r}-${o}`;let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-indi-remove`,l.innerHTML=O(`x`,12);let u=n(`indicatorSettings.removeLevel`);l.title=u,l.setAttribute(`aria-label`,`${u} ${o+1}`),l.addEventListener(`click`,()=>{s(a.filter((e,t)=>t!==o)),(i.querySelectorAll(`.tcw-indi-remove`)[o]??i.querySelector(`.tcw-indi-add`))?.focus()});let d=document.createElement(`span`);d.className=`tcw-indi-level`,d.append(c,l);let f=document.createElement(`div`);f.className=`tcw-settings-row`;let p=document.createElement(`label`);return p.className=`tcw-settings-label`,p.htmlFor=c.id,p.textContent=`${n(`indicatorSettings.level`)} ${o+1}`,f.append(p,d),f};return o(),i}function Na(e,t,n,i){let a=new Map(r.INTERVAL_UNITS.map(e=>{let n=t?.[e],i=Array.isArray(n)?n:[1,r.INTERVAL_LIMITS[e]];return[e,{on:n!==!1,from:i[0],to:i[1]}]})),o=()=>{let e={};for(let[t,{on:n,from:i,to:o}]of a){let[a,s]=[Math.min(i,o),Math.max(i,o)];n?(a>1||s<r.INTERVAL_LIMITS[t])&&(e[t]=[a,s]):e[t]=!1}n(Object.keys(e).length>0?e:null)},s=Fa();for(let e of r.INTERVAL_UNITS)s.appendChild(Pa(e,a.get(e),o,i));e.appendChild(s)}function Pa(e,t,n,i){let a=document.createElement(`div`);a.className=`tcw-settings-row tcw-indi-unit`,a.dataset.unit=e;let o=document.createElement(`label`);o.className=`tcw-indi-plot-name`;let s=document.createElement(`input`);s.type=`checkbox`,s.checked=t.on;let c=document.createElement(`span`);c.className=`tcw-settings-label`,c.textContent=i(ka[e]),o.append(s,c),a.appendChild(o);let l=[];if(e!==`ticks`){let o=(a,o)=>{let s=P(t[a],{min:1,max:r.INTERVAL_LIMITS[e],step:1},e=>{t[a]=Math.round(e),s.value=String(t[a]),n()});return s.setAttribute(`aria-label`,`${i(ka[e])}: ${i(o)}`),s.disabled=!t.on,l.push(s),s},s=document.createElement(`span`);s.className=`tcw-indi-range`;let c=document.createElement(`span`);c.setAttribute(`aria-hidden`,`true`),c.textContent=`–`,s.append(o(`from`,`indicatorSettings.rangeFrom`),c,o(`to`,`indicatorSettings.rangeTo`)),a.appendChild(s)}return s.addEventListener(`change`,()=>{t.on=s.checked;for(let e of l)e.disabled=!s.checked;n()}),a}function Fa(){let e=document.createElement(`div`);return e.className=`tcw-settings-section`,e}function Ia(e){let t=document.createElement(`div`);return t.className=`tcw-settings-label`,t.textContent=e,t}var La=1,Ra=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,za=1.5,Ba={visible:!0,lineStyle:`solid`},Va=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ha=e=>JSON.parse(JSON.stringify(e));function Ua(e){return e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase())}function Wa(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].map(e=>[e,{...Ba,...t[e]}]))}var Ga=class{backdrop;modal;bodyEl;titleEl;tabsEl;defaultsBtn;menu=null;callbacks;target=null;draft={};initial=null;look={colors:[],lineWidth:za,plots:{},levels:[],intervals:null};tab=`inputs`;tabButtons=[];returnFocus=null;uid=La++;t;constructor(e,n,r){this.callbacks=n,this.t=r??(e=>t.c[e]),this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.finish(!1),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow tcw-indi`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-indi-title-${this.uid}`),this.modal.tabIndex=-1,this.modal.addEventListener(`keydown`,e=>this.onKeyDown(e));let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-indi-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`indicatorSettings.close`)),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.finish(!1)),a.append(this.titleEl,o),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-modal-tabs`,this.tabsEl.setAttribute(`role`,`tablist`),this.tabsEl.addEventListener(`keydown`,e=>this.onTabKey(e)),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`,this.bodyEl.id=`tcw-indi-panel-${this.uid}`,this.bodyEl.setAttribute(`role`,`tabpanel`),this.defaultsBtn=this.footerButton(`defaults`,`tcw-footer-menu`,()=>this.openDefaults()),this.modal.append(a,this.tabsEl,this.bodyEl,this.buildFooter()),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}buildFooter(){this.defaultsBtn.setAttribute(`aria-haspopup`,`menu`),this.defaultsBtn.setAttribute(`aria-expanded`,`false`),this.defaultsBtn.innerHTML=`<span></span>${O(`chevronDown`,12)}`,this.defaultsBtn.querySelector(`span`).textContent=this.t(`indicatorSettings.defaults`);let e=document.createElement(`div`);e.className=`tcw-footer-end`,e.append(this.footerButton(`cancel`,`tcw-footer-cancel`,()=>this.finish(!1),this.t(`common.cancel`)),this.footerButton(`ok`,`tcw-done-btn`,()=>this.finish(!0),this.t(`drawingSettings.ok`)));let t=document.createElement(`div`);return t.className=`tcw-modal-footer`,t.append(this.defaultsBtn,e),t}open(e){this.target&&this.finish(!0),this.backdrop.hidden&&(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.target=e,this.titleEl.textContent=this.t(`indicatorSettings.title`).replace(`{name}`,e.name),this.draft={},this.look={colors:[...e.colors??[]],lineWidth:e.lineWidth??za,plots:Object.fromEntries(Object.entries(e.plotStyles??{}).map(([e,t])=>[e,{...t}])),levels:[...e.levels??[]],scale:e.scale,intervals:e.intervals??null},this.initial={params:this.currentParams(),look:Ha(this.look)},this.tab=`inputs`,this.renderTabs(),this.renderBody(),this.backdrop.hidden=!1;let t=this.tabsEl.hidden?null:this.tabButtons[0]??null;(this.bodyEl.querySelector(`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)??t??this.modal).focus()}close(){this.finish(!0)}isOpen(){return!this.backdrop.hidden}destroy(){this.menu?.destroy(),this.backdrop.remove()}finish(e){if(this.target){if(e){let e=document.activeElement;(e instanceof HTMLInputElement||e instanceof HTMLSelectElement)&&this.modal.contains(e)&&e.dispatchEvent(new Event(`change`))}else this.revert();this.target=null,this.menu?.close(),this.backdrop.hidden=!0,this.callbacks.onClose(),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null}}revert(){let e=this.target,t=this.initial;if(!e||!t)return;let n=e.instanceId;Va(this.currentParams(),t.params)||this.callbacks.onApply(n,{...t.params});let r=t.look,i={};Va(this.look.colors,r.colors)||(i.colors=[...r.colors]),this.look.lineWidth!==r.lineWidth&&(i.lineWidths=[r.lineWidth]),Va(this.look.plots,r.plots)||(i.plots=Wa(this.look.plots,r.plots)),Object.keys(i).length>0&&this.callbacks.onStyle?.(n,i),Va(this.look.levels,r.levels)||this.callbacks.onLevels?.(n,e.ownLevels?[...r.levels]:null),this.look.scale!==r.scale&&r.scale&&this.callbacks.onScale?.(n,r.scale),Va(this.look.intervals,r.intervals)||this.callbacks.onIntervals?.(n,r.intervals)}currentParams(){let e=this.target;return e?{...e.defaults,...e.params,...this.draft}:{}}tabs(){let e=this.target;if(!e)return[];let t=!!(e.plots?.length&&e.colors&&this.callbacks.onStyle),n=!!(e.levels&&this.callbacks.onLevels);return[`inputs`,...t||n?[`style`]:[],...this.callbacks.onIntervals?[`visibility`]:[]]}renderTabs(){let e=this.tabs();this.tabsEl.hidden=e.length<2,this.tabButtons=e.map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-modal-tab`,t.id=`tcw-indi-tab-${this.uid}-${e}`,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,this.bodyEl.id),t.dataset.tab=e,t.textContent=this.t(`indicatorSettings.tab.${e}`),t.addEventListener(`click`,()=>this.selectTab(e)),t}),this.tabsEl.replaceChildren(...this.tabButtons),this.markTabs()}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.tab=e,this.markTabs(),this.renderBody(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=this.tabButtons.map(e=>e.dataset.tab),n=t.indexOf(this.tab),[r,i]=this.modal.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowLeft`,`ArrowRight`]:[`ArrowRight`,`ArrowLeft`],a=e.key===r?(n+1)%t.length:e.key===i?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;a<0||t.length===0||(e.preventDefault(),this.selectTab(t[a],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.finish(!1);return}M(e,this.modal)}renderBody(){this.bodyEl.replaceChildren();let e=this.target;e&&(this.tab===`style`?this.renderStyle(e):this.tab===`visibility`?Na(this.bodyEl,this.look.intervals,e=>this.setIntervals(e),this.t):this.renderInputs())}currentValue(e){if(e in this.draft)return this.draft[e];let t=this.target?.params[e],n=this.target?.defaults[e];return t??n}setValue(e,t){this.target&&(this.draft[e]=t,this.callbacks.onApply(this.target.instanceId,{...this.draft}))}renderInputs(){let e=document.createElement(`div`);e.className=`tcw-settings-section`;let t=Object.keys(this.target.defaults);t.length===0&&e.appendChild(this.note(this.t(`indicatorSettings.noInputs`)));for(let n of t)e.appendChild(this.fieldRow(n));this.bodyEl.appendChild(e)}fieldRow(e){let t=this.target?.inputs?.[e],n=this.currentValue(e),r=typeof(this.target?.defaults[e]??n),i;if(t?.source)i=this.sourceControl(e,String(n??`close`));else if(t?.options)i=this.choiceControl(e,t.options,n);else if(r===`boolean`)i=Sn(!!n,t=>this.setValue(e,t));else if(r===`number`){let r=Number(n);i=P(r,{min:t?.min,max:t?.max,step:t?.step??(Number.isInteger(r)?1:.1)},t=>this.setValue(e,t))}else i=typeof n==`string`&&Ra.test(n)?F(n,t=>this.setValue(e,t)):this.textControl(e,String(n??``));return N(t?.label??Gi(e,this.t)??Ua(e),i)}sourceControl(e,t){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;let i=document.createElement(`optgroup`);i.label=this.t(`indicatorSettings.source.prices`);for(let e of n.PRICE_SOURCES)i.appendChild(this.option(e,e));r.appendChild(i);let a=this.target?.lineSources??[];if(a.length){let e=document.createElement(`optgroup`);e.label=this.t(`indicatorSettings.source.indicators`);for(let t of a)e.appendChild(this.option(t.value,t.label));r.appendChild(e)}return r.value=t,r.value!==t&&(r.value=`close`),r.addEventListener(`change`,()=>this.setValue(e,r.value)),r}choiceControl(e,t,n){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;for(let n of t)r.appendChild(this.option(String(n),Ki(e,n,this.t)??String(n)));return r.value=String(n),r.addEventListener(`change`,()=>{let n=t.find(e=>String(e)===r.value);n!==void 0&&this.setValue(e,n)}),r}textControl(e,t){let n=document.createElement(`input`);return n.type=`text`,n.className=`tcw-indi-input`,n.value=t,n.addEventListener(`change`,()=>this.setValue(e,n.value)),n}renderStyle(e){let t=e.instanceId,n=()=>this.target===e,r=e=>n()&&this.callbacks.onStyle?.(t,e),i=e=>n()&&this.callbacks.onLevels?.(t,e),a=e=>n()&&this.callbacks.onScale?.(t,e);Aa(this.bodyEl,{plots:e.colors&&this.callbacks.onStyle?e.plots??[]:[],colors:this.look.colors,plotStyles:this.look.plots,lineWidth:this.look.lineWidth,scale:e.scale&&this.callbacks.onScale?this.look.scale:void 0,levels:e.levels&&this.callbacks.onLevels?this.look.levels:void 0},{color:(e,t)=>{if(!n())return;let i=[...this.look.colors];for(;i.length<=e;)i.push(i[0]??t);i[e]=t,this.look.colors=i,r({colors:[...i]})},plot:(e,t)=>{n()&&(this.look.plots={...this.look.plots,[e]:{...this.look.plots[e],...t}},r({plots:{[e]:t}}))},lineWidth:e=>{n()&&(this.look.lineWidth=e,r({lineWidths:[e]}))},scale:e=>{n()&&(this.look.scale=e,a(e))},levels:e=>{n()&&(this.look.levels=e,i([...e]))}},this.t,this.uid)}setIntervals(e){this.target&&(this.look.intervals=e,this.callbacks.onIntervals?.(this.target.instanceId,e))}openDefaults(){if(this.menu?.isOpen()){this.menu.close();return}this.menu??=new A(this.modal,this.t(`indicatorSettings.defaults`));let e=this.defaultsBtn.getBoundingClientRect(),t=this.modal.getBoundingClientRect(),n=[{id:`reset`,label:this.t(`indicatorSettings.resetSettings`),icon:`reset`},...this.callbacks.onSaveDefault?[{id:`save`,label:this.t(`indicatorSettings.saveAsDefault`),icon:`save`}]:[]];this.menu.open(n,e.left-t.left,e.top-t.top,e=>{e===`reset`?this.resetAll():this.saveDefault()},this.defaultsBtn)}resetAll(){let e=this.target;if(!e)return;let t=e.instanceId,n={...e.defaults};this.draft={...n},this.callbacks.onApply(t,{...n}),Object.keys(this.look.plots).length>0&&(this.callbacks.onStyle?.(t,{plots:Wa(this.look.plots,{})}),this.look.plots={}),e.levels&&this.callbacks.onLevels&&(this.callbacks.onLevels(t,null),this.look.levels=[...e.defaultLevels??[]]),this.look.intervals&&this.setIntervals(null),this.renderBody()}saveDefault(){let e=this.target;if(!e)return;let t=Object.fromEntries(Object.entries(this.currentParams()).filter(([t,r])=>!Va(r,e.defaults[t])&&!(typeof r==`string`&&(0,n.parseIndicatorSource)(r)))),i={};(0,r.isSeriesPalette)(this.look.colors)||(i.colors=[...this.look.colors]),this.look.lineWidth!==za&&(i.lineWidths=[this.look.lineWidth]),Object.keys(this.look.plots).length>0&&(i.plots=Ha(this.look.plots)),this.callbacks.onSaveDefault?.(e.indicatorId,{params:t,style:i})}footerButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=t,i.dataset.act=e,r&&(i.textContent=r),i.addEventListener(`click`,n),i}note(e){let t=document.createElement(`div`);return t.className=`tcw-settings-label`,t.textContent=e,t}option(e,t){let n=document.createElement(`option`);return n.value=e,n.textContent=t,n}};function Ka(e){return e.normalize(`NFD`).replace(/[̀-ͯ]/g,``).toLowerCase()}var qa=/[\s/()%-]+/;function Ja(e,t){let n=Ka(e.shortName),r=Ka(e.name);return n===t||Ka(e.id)===t?0:n.startsWith(t)||r.startsWith(t)?1:[...r.split(qa),...n.split(qa)].some(e=>e.startsWith(t))?2:r.includes(t)||n.includes(t)?3:null}function Ya(e,t){let n=Ka(t.trim());return n?e.map(e=>({item:e,rank:Ja(e,n)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.item.name.localeCompare(t.item.name)).map(e=>e.item):[]}var Xa=1,Za=(e,t)=>e.name.localeCompare(t.name),Qa=class{backdrop=null;listEl=null;navEl=null;searchEl=null;liveEl=null;content={items:[],favorites:[],templates:[]};favorites=new Set;counts=new Map;view=`all`;lastView=null;query=``;returnFocus=null;uid=Xa++;constructor(e,t,n){this.layer=e,this.callbacks=t,this.t=n}open(e){this.backdrop&&this.close(!1),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.content=e,this.favorites=new Set(e.favorites),this.counts=e.counts??new Map,this.query=``,this.view=this.startView(),this.build(),this.searchEl?.focus()}close(e=!0){this.backdrop&&(this.backdrop.remove(),this.backdrop=this.listEl=this.navEl=this.searchEl=this.liveEl=null,this.callbacks.onClose?.(),e&&this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return this.backdrop!==null}setTemplates(e){if(this.content={...this.content,templates:[...e]},!this.listEl||this.view!==`templates`||this.query)return;let t=this.listEl.contains(document.activeElement);this.renderList(),t&&!this.listEl.contains(document.activeElement)&&this.listEl.querySelector(`[data-tpl-save]`)?.focus()}setCounts(e){this.counts=e,this.listEl?.querySelectorAll(`.tcw-ip-row[data-ind]`).forEach(e=>this.markCount(e))}destroy(){this.close(!1)}startView(){let e=this.views();return this.lastView&&e.includes(this.lastView)&&!(this.lastView===`favorites`&&this.favorites.size===0)?this.lastView:this.favorites.size>0?`favorites`:`all`}views(){let e=new Set(this.content.items.map(e=>e.category));return[`favorites`,...this.callbacks.templates&&this.content.templates?[`templates`]:[],`all`,...r.INDICATOR_CATEGORIES.filter(t=>e.has(t))]}viewLabel(e){return e===`favorites`?this.t(`indicatorPicker.favorites`):e===`templates`?this.t(`toolbar.indicators.templates`):e===`all`?this.t(`toolbar.indicators.all`):this.t(`indicatorCategory.${e}`)}build(){let e=document.createElement(`div`);e.className=`tcw-modal-backdrop`,e.addEventListener(`click`,t=>{t.target===e&&this.close()});let t=document.createElement(`div`);t.className=`tcw-modal tcw-ip`,t.setAttribute(`role`,`dialog`),t.setAttribute(`aria-modal`,`true`),t.setAttribute(`aria-labelledby`,`tcw-ip-title-${this.uid}`),t.tabIndex=-1,t.addEventListener(`keydown`,e=>this.onKeyDown(e,t));let n=document.createElement(`div`);n.className=`tcw-visually-hidden`,n.setAttribute(`aria-live`,`polite`),t.append(this.buildHeader(),this.buildSearch(),this.buildBody(),n),e.appendChild(t),this.layer().appendChild(e),this.backdrop=e,this.liveEl=n,this.renderNav(),this.renderList()}buildHeader(){let e=document.createElement(`div`);e.className=`tcw-modal-header`;let t=document.createElement(`h3`);t.id=`tcw-ip-title-${this.uid}`,t.textContent=this.t(`toolbar.indicators`);let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-modal-close`,n.setAttribute(`aria-label`,this.t(`indicatorSettings.close`)),n.innerHTML=O(`x`,16),n.addEventListener(`click`,()=>this.close()),e.append(t,n),e}buildSearch(){let e=document.createElement(`label`);e.className=`tcw-ip-search`;let t=document.createElement(`input`);return t.type=`search`,t.id=`tcw-ip-search-${this.uid}`,t.placeholder=this.t(`indicatorPicker.search`),t.setAttribute(`aria-label`,this.t(`indicatorPicker.search`)),t.autocomplete=`off`,t.spellcheck=!1,t.addEventListener(`input`,()=>{this.query=t.value,this.renderList()}),t.addEventListener(`keydown`,e=>this.onSearchKey(e)),e.innerHTML=O(`search`,16),e.appendChild(t),this.searchEl=t,e}buildBody(){let e=document.createElement(`div`);e.className=`tcw-ip-body`;let t=document.createElement(`div`);t.className=`tcw-ip-nav`,t.setAttribute(`role`,`tablist`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,this.t(`indicatorPicker.groups`)),t.addEventListener(`keydown`,e=>this.onNavKey(e));let n=document.createElement(`div`);return n.className=`tcw-ip-list`,n.id=`tcw-ip-list-${this.uid}`,n.setAttribute(`role`,`tabpanel`),n.addEventListener(`keydown`,e=>this.onListKey(e)),n.addEventListener(`focusin`,e=>this.rove(e.target)),e.append(t,n),this.navEl=t,this.listEl=n,e}renderNav(){let e=this.navEl;e&&(e.replaceChildren(...this.views().map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-ip-tab`,t.id=`tcw-ip-tab-${this.uid}-${e}`,t.dataset.view=e,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,`tcw-ip-list-${this.uid}`),t.innerHTML=`${e===`favorites`?O(`star`,14):e===`templates`?O(`layers`,14):``}<span></span>`,t.querySelector(`span`).textContent=this.viewLabel(e),e===`templates`&&D(t,`indicatorTemplates`),t.addEventListener(`click`,()=>this.select(e)),t})),this.markNav())}markNav(){this.navEl?.querySelectorAll(`.tcw-ip-tab`).forEach(e=>{let t=e.dataset.view===this.view;e.setAttribute(`aria-selected`,String(t)),e.classList.toggle(`tcw-active`,t),e.tabIndex=t?0:-1}),this.labelList()}labelList(){let e=this.query.trim()!==``;this.listEl?.setAttribute(`aria-labelledby`,e?`tcw-ip-search-${this.uid}`:`tcw-ip-tab-${this.uid}-${this.view}`)}select(e,t=!1){this.view=this.lastView=e,this.searchEl&&this.query&&(this.searchEl.value=this.query=``),this.markNav(),this.renderList(),t&&this.navEl?.querySelector(`[data-view="${e}"]`)?.focus()}renderList(){let e=this.listEl;if(!e)return;e.replaceChildren();let n=this.content.items;if(this.navEl?.classList.toggle(`tcw-ip-nav--searching`,this.query.trim()!==``),this.labelList(),this.query.trim()){let r=Ya(n,this.query);r.length===0?e.appendChild(this.note(t.r(this.t(`indicatorPicker.noMatch`),{query:this.query.trim()}))):e.append(...r.map(e=>this.row(e)))}else if(this.view===`templates`)this.renderTemplates(e);else if(this.view===`favorites`){let t=n.filter(e=>this.favorites.has(e.id)).sort(Za);t.length===0?e.appendChild(this.note(this.t(`indicatorPicker.noFavorites`))):e.append(...t.map(e=>this.row(e)))}else if(this.view===`all`)for(let t of r.INDICATOR_CATEGORIES){let r=n.filter(e=>e.category===t).sort(Za);if(r.length===0)continue;let i=document.createElement(`div`);i.className=`tcw-ip-heading`,i.textContent=this.viewLabel(t),e.append(i,...r.map(e=>this.row(e)))}else e.append(...n.filter(e=>e.category===this.view).sort(Za).map(e=>this.row(e)));e.querySelector(`.tcw-ip-add`)?.setAttribute(`tabindex`,`0`)}row(e){let t=document.createElement(`div`);t.className=`tcw-ip-row`,t.dataset.ind=e.id;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-ip-add`,n.dataset.ind=e.id,n.tabIndex=-1;let r=document.createElement(`span`);r.className=`tcw-ip-name`,r.textContent=e.name,n.appendChild(r),e.shortName&&e.shortName!==e.name&&n.appendChild(this.tag(`tcw-ip-short`,e.shortName)),n.appendChild(this.tag(`tcw-ip-kind`,this.t(`indicatorType.${e.placement}`))),n.addEventListener(`click`,()=>this.add(e));let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-ip-aside tcw-ip-star`,i.tabIndex=-1,i.title=this.t(`indicatorPicker.favorite`),i.setAttribute(`aria-label`,`${this.t(`indicatorPicker.favorite`)}: ${e.name}`),i.setAttribute(`aria-pressed`,String(this.favorites.has(e.id))),i.innerHTML=O(`star`,14),i.addEventListener(`click`,()=>this.toggleFavorite(e.id,i)),t.append(n,i),this.markCount(t),t}renderTemplates(e){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-ip-add tcw-ip-save`,n.tabIndex=-1,n.dataset.tplSave=``,n.innerHTML=`${O(`save`,14)}<span class="tcw-ip-name"></span>`,n.querySelector(`span`).textContent=this.t(`templates.save`),n.addEventListener(`click`,()=>{this.close(),this.callbacks.templates?.onSave()}),e.appendChild(n);let r=this.content.templates??[];r.length===0&&e.appendChild(this.note(this.t(`indicatorPicker.noTemplates`)));for(let n of r){let r=document.createElement(`div`);r.className=`tcw-ip-row`;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-ip-add`,i.tabIndex=-1,i.dataset.tplApply=n,i.innerHTML=`${O(`layers`,14)}<span class="tcw-ip-name"></span>`,i.querySelector(`span`).textContent=n,i.addEventListener(`click`,()=>{this.close(),this.callbacks.templates?.onApply(n)});let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-ip-aside tcw-ip-remove`,a.tabIndex=-1,a.dataset.tplDelete=n;let o=t.r(this.t(`templates.delete`),{name:n});a.title=o,a.setAttribute(`aria-label`,o),a.innerHTML=O(`x`,12),a.addEventListener(`click`,()=>this.callbacks.templates?.onDelete(n)),r.append(i,a),e.appendChild(r)}}add(e){if(this.callbacks.onAdd(e.id)===!1||!this.liveEl)return;let n=t.r(this.t(`indicatorPicker.added`),{name:e.name});this.liveEl.textContent=this.liveEl.textContent===n?`${n}\u00a0`:n}toggleFavorite(e,t){let n=!this.favorites.has(e);if(n?this.favorites.add(e):this.favorites.delete(e),this.callbacks.onFavorite(e,n),t.setAttribute(`aria-pressed`,String(n)),this.view!==`favorites`||this.query||n)return;let r=[...this.listEl?.querySelectorAll(`.tcw-ip-star`)??[]].indexOf(t),i=document.activeElement===t;if(this.renderList(),!i)return;let a=[...this.listEl?.querySelectorAll(`.tcw-ip-star`)??[]];(a[r]??a[a.length-1]??this.searchEl)?.focus()}markCount(e){let n=this.counts.get(e.dataset.ind??``)??0,r=e.querySelector(`.tcw-ip-add`),i=e.querySelector(`.tcw-ip-count`);if(n===0){i?.remove();return}i||(i=this.tag(`tcw-ip-count`,``),r?.appendChild(i)),i.textContent=String(n),i.title=t.r(this.t(`indicatorPicker.onChart`),{count:String(n)})}tag(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}note(e){let t=document.createElement(`div`);return t.className=`tcw-ip-empty`,t.textContent=e,t}rove(e){!(e instanceof HTMLElement)||!e.classList.contains(`tcw-ip-add`)||(this.listEl?.querySelectorAll(`.tcw-ip-add[tabindex="0"]`).forEach(t=>{t!==e&&(t.tabIndex=-1)}),e.tabIndex=0)}onKeyDown(e,t){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.close();return}M(e,t)}onSearchKey(e){let t=this.listEl?.querySelector(`.tcw-ip-add`);e.key===`ArrowDown`&&t?(e.preventDefault(),t.focus()):e.key===`Enter`&&this.query.trim()&&t&&(e.preventDefault(),t.click())}onNavKey(e){let t=this.views(),n=t.indexOf(this.view),r=e.key===`ArrowDown`?Math.min(t.length-1,n+1):e.key===`ArrowUp`?Math.max(0,n-1):e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),this.select(t[r],!0))}onListKey(e){let t=e.target,n=t.closest(`.tcw-ip-row, .tcw-ip-save`),r=[...this.listEl?.querySelectorAll(`.tcw-ip-add`)??[]],i=n?.classList.contains(`tcw-ip-save`)?n:n?.querySelector(`.tcw-ip-add`),a=i?r.indexOf(i):-1,o=null;e.key===`ArrowDown`?o=r[a+1]:e.key===`ArrowUp`?o=a>0?r[a-1]:this.searchEl:e.key===`Home`?o=r[0]:e.key===`End`?o=r[r.length-1]:e.key===`ArrowRight`&&t===i?o=n?.querySelector(`.tcw-ip-aside`):e.key===`ArrowLeft`&&t!==i&&(o=i),o&&(e.preventDefault(),o.focus())}};function $a(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var eo=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function to(e){return eo(e)?Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`number`&&Number.isFinite(e)||typeof e==`string`&&!(0,n.parseIndicatorSource)(e)||typeof e==`boolean`)):{}}function no(e){if(!eo(e))return{};let t={};if(Array.isArray(e.colors)){let n=e.colors.filter(e=>typeof e==`string`&&e.trim()!==``);n.length>0&&(t.colors=n)}if(Array.isArray(e.lineWidths)){let n=e.lineWidths.filter(e=>typeof e==`number`&&Number.isFinite(e)&&e>0);n.length>0&&(t.lineWidths=n)}let r=(0,n.readIndicatorPlotStyles)(e.plots);return r&&(t.plots=r),t}var ro=class{constructor(e=`tcw:indicator-defaults`,t=$a()){this.key=e,this.storage=t}all(){let e=new Map,t;try{t=JSON.parse(this.storage?.getItem(this.key)??`{}`)}catch{return e}if(!eo(t))return e;for(let[n,r]of Object.entries(t))eo(r)&&e.set(n,{params:to(r.params),style:no(r.style)});return e}get(e){return this.all().get(e)??null}save(e,t){if(!this.storage)return!1;let n=Object.fromEntries([...this.all(),[e,{params:to(t.params),style:no(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},io=1,ao=[`logScale`,`autoScale`],oo=new Set([`timezone`,`numberLocale`]),so=new Set([...ao,`chartTypeOptions`]),co=new Set([...ao,...oo,`scaleMode`,`invertScale`,`chartTypeOptions`]),lo=new Set([...ao,...oo,`scaleMode`]),uo=new Set,fo=[`renko`,`lineBreak`,`kagi`,`pointAndFigure`,`rangeBars`];function po(e){return fo.includes(e)}function mo(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>vo(e)&&Object.keys(e).length>0))}function ho(){return Object.fromEntries(fo.map(e=>[e,{}]))}var go={crosshairMode:[`normal`,`magnet`,`hidden`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},_o={marketProfileBuckets:{min:8,max:200,whole:!0},marketProfileOpacity:{min:.05,max:1},depthHeatmapOpacity:{min:.1,max:1},pivotStrength:{min:2,max:20,whole:!0}},vo=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function yo(e){return e===`local`||u(e)!==null}function bo(e){try{return Intl.NumberFormat.supportedLocalesOf(e).length>0}catch{return!1}}function xo(e,t){let r=ge[e];if(e===`chartTypeOptions`)return vo(t)?(0,n.readChartTypeOptions)(t):void 0;if(typeof t!=typeof r)return;if(typeof t==`number`){if(!Number.isFinite(t))return;let n=_o[e];if(!n)return t;let r=Math.min(n.max,Math.max(n.min,t));return n.whole?Math.round(r):r}if(typeof t!=`string`)return t;let i=go[e];return i?i.includes(t)?t:void 0:e===`timezone`?yo(t)?t:void 0:e===`numberLocale`?bo(t)?t:void 0:t}function K(e,t=uo){if(!vo(e))return{};let n={};for(let r of Object.keys(ge)){if(t.has(r)||!Object.prototype.hasOwnProperty.call(e,r))continue;let i=xo(r,e[r]);i!==void 0&&(n[r]=i)}return n}function So(e,t){return Object.fromEntries(Object.keys(e).filter(e=>!t.has(e)).map(t=>[t,e[t]]))}function Co(e,t,n){return Object.fromEntries(Object.keys(e).filter(r=>!n.has(r)&&JSON.stringify(e[r])!==JSON.stringify(t[r])).map(t=>[t,e[t]]))}function wo(e,t){return Co({...e,chartTypeOptions:mo(e.chartTypeOptions)},t,lo)}function To(e){return e?(e===!0?void 0:e.key)||`tcw:chart-settings`:null}function Eo(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Do=class{constructor(e,t=Eo()){this.key=e,this.storage=t}load(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`null`)}catch{return{}}return!vo(e)||e.v!==io?{}:K(e.settings,so)}save(e,t){try{this.storage?.setItem(this.key,JSON.stringify({v:io,settings:Co(e,t,so)}))}catch{}}},Oo=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),ko=80,Ao=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function jo(e){return K(e,Oo)}function Mo(e){let{overrides:t}=(0,n.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(t).filter(([e,t])=>t!==null&&E.includes(e)))}function No(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Po=class{constructor(e=`tcw:chart-templates`,t=No()){this.key=e,this.storage=t}list(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e)!Ao(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,ko).trim(),settings:jo(n.settings),style:Mo(n.style)});return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t,n){let r=e.replace(/\s+/g,` `).slice(0,ko).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:jo(t),style:Mo(n)}];try{return this.storage.setItem(this.key,JSON.stringify(i)),!0}catch{return!1}}remove(e){try{this.storage?.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}};function Fo(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Io=80;function Lo(e){let{text:t,...r}=(0,n.sanitizeDrawingStyle)(e);return r}function Ro(e){let t={name:e.name,style:{...e.style}};return e.type&&(t.type=e.type),e.options&&(t.options=structuredClone(e.options)),t}var zo=class{templates=[];constructor(e=`tcw:draw-templates`,t=Fo()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(Ro)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?Ro(n):null}save(e,t,n){let r=e.trim().slice(0,Io);if(!r)return;let i={name:r,style:Lo(t)};n&&(i.type=n.type,i.options=structuredClone(n.options)),this.templates=this.templates.filter(e=>!(e.name===r&&e.type===i.type)),this.templates.push(i),this.persist()}remove(e,t){this.templates=this.templates.filter(n=>!(n.name===e&&n.type===t)),this.persist()}clear(){this.templates=[],this.persist()}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;this.templates=t.filter(e=>e&&typeof e.name==`string`&&e.name.trim()!==``).map(e=>{let t={name:e.name.trim().slice(0,Io),style:Lo(e.style)};return typeof e.type==`string`&&(t.type=e.type),e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&(t.options=e.options),t})}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.templates))}catch{}}},Bo=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=Fo()){this.storageKey=e,this.storage=t;try{let e=this.storage?.getItem(this.storageKey),t=e?JSON.parse(e):null;if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,n]of Object.entries(t))n&&typeof n==`object`&&!Array.isArray(n)&&(this.defaults[e]=n)}catch{}}all(){return structuredClone(this.defaults)}set(e,t){t&&Object.keys(t).length>0?this.defaults[e]=structuredClone(t):delete this.defaults[e];try{this.storage?.setItem(this.storageKey,JSON.stringify(this.defaults))}catch{}}},Vo=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],Ho=[1,2,3,4],Uo=[`solid`,`dashed`,`dotted`],Wo=class{el;templatesEl;nameInput;callbacks;store;open=!1;constructor(e,n,r,i=t.t){this.t=i,this.callbacks=n,this.store=r,this.el=document.createElement(`div`),this.el.className=`tcw-style-panel`,this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-style-header`;let o=document.createElement(`span`);o.textContent=this.t(`drawingStyle.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-style-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=O(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a),this.el.appendChild(this.colorRow()),this.el.appendChild(this.widthRow()),this.el.appendChild(this.lineStyleRow());let c=document.createElement(`div`);c.className=`tcw-style-subhead`,c.textContent=this.t(`drawingStyle.templates`),this.el.appendChild(c);let l=document.createElement(`div`);l.className=`tcw-style-save`,this.nameInput=document.createElement(`input`),this.nameInput.type=`text`,this.nameInput.placeholder=this.t(`drawingStyle.templateName`),this.nameInput.className=`tcw-style-name`;let u=document.createElement(`button`);u.type=`button`,u.className=`tcw-style-savebtn`,u.innerHTML=`${O(`plus`,13)}<span>${k(this.t(`common.save`))}</span>`,u.addEventListener(`click`,()=>this.saveTemplate()),l.appendChild(this.nameInput),l.appendChild(u),this.el.appendChild(l),this.templatesEl=document.createElement(`div`),this.templatesEl.className=`tcw-style-templates`,this.el.appendChild(this.templatesEl),e.appendChild(this.el),this.renderTemplates()}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.syncActiveControls(),this.renderTemplates()}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}colorRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-colors`;for(let t of Vo){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-swatch`,n.style.background=t,n.dataset.color=t,n.setAttribute(`aria-label`,t),n.addEventListener(`click`,()=>this.applyStyle({color:t})),e.appendChild(n)}let t=document.createElement(`input`);return t.type=`color`,t.className=`tcw-style-picker`,t.addEventListener(`input`,()=>this.applyStyle({color:t.value})),e.appendChild(t),e}widthRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-widths`;for(let t of Ho){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-width`,n.dataset.width=String(t);let r=document.createElement(`span`);r.style.height=`${t}px`,n.appendChild(r),n.addEventListener(`click`,()=>this.applyStyle({lineWidth:t})),e.appendChild(n)}return e}lineStyleRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-dashes`;for(let t of Uo){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-dash`,n.dataset.linestyle=t,n.textContent=t===`solid`?`──`:t===`dashed`?`╌╌`:`┄┄`,n.title=t,n.addEventListener(`click`,()=>this.applyStyle({lineStyle:t})),e.appendChild(n)}return e}applyStyle(e){this.callbacks.onStyleChange(e),this.syncActiveControls()}syncActiveControls(){let e=this.callbacks.getStyle();this.el.querySelectorAll(`.tcw-style-swatch`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.color?.toLowerCase()===e.color?.toLowerCase())}),this.el.querySelectorAll(`.tcw-style-width`).forEach(t=>{t.classList.toggle(`tcw-on`,Number(t.dataset.width)===e.lineWidth)}),this.el.querySelectorAll(`.tcw-style-dash`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.linestyle===e.lineStyle)})}saveTemplate(){let e=this.nameInput.value.trim();e&&(this.store.save(e,this.callbacks.getStyle()),this.nameInput.value=``,this.renderTemplates())}renderTemplates(){this.templatesEl.replaceChildren();let e=this.store.list();if(e.length===0){let e=document.createElement(`div`);e.className=`tcw-style-empty`,e.textContent=this.t(`drawingStyle.noTemplates`),this.templatesEl.appendChild(e);return}for(let t of e){let e=document.createElement(`div`);e.className=`tcw-style-template`;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-apply`;let r=document.createElement(`span`);r.className=`tcw-style-tdot`,r.style.background=t.style.color??`var(--tcw-text-muted)`;let i=document.createElement(`span`);i.textContent=t.name,n.appendChild(r),n.appendChild(i),n.addEventListener(`click`,()=>{this.callbacks.onStyleChange({...t.style}),this.syncActiveControls()});let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-style-tdel`,a.setAttribute(`aria-label`,this.t(`drawingStyle.deleteTemplate`)),a.innerHTML=O(`trash`,13),a.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(a),this.templatesEl.appendChild(e)}}},Go={color:`color`,fill:`fillColor`,textColor:`textColor`},Ko=10,q=4,qo=4,Jo=20,Yo=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function Xo(e){return typeof e==`string`&&Yo.test(e.trim())?e.trim():`#7d8696`}function Zo(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,Jo):1}function Qo(e){return Uo.includes(e)?e:`solid`}var $o=class{el;pop;target=null;built=``;size=null;openPop=null;pinned=null;drag=null;onDragMove=e=>{!this.drag||!this.target||e.pointerId!==this.drag.id||(this.pinned={left:this.drag.left+e.clientX-this.drag.x,top:this.drag.top+e.clientY-this.drag.y},this.place(this.target))};onDragEnd=e=>{e&&this.drag&&e.pointerId!==this.drag.id||(this.drag=null,document.removeEventListener(`pointermove`,this.onDragMove),document.removeEventListener(`pointerup`,this.onDragEnd),document.removeEventListener(`pointercancel`,this.onDragEnd))};onDocDown=e=>{this.openPop&&!this.el.contains(e.target)&&!this.pop.contains(e.target)&&this.closePop()};constructor(e,n,r=t.t){this.host=e,this.callbacks=n,this.t=r,this.el=document.createElement(`div`),this.el.className=`tcw-sel-toolbar`,this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,r(`selectionToolbar.label`)),this.el.hidden=!0,this.pop=document.createElement(`div`),this.pop.className=`tcw-sel-pop`,this.pop.setAttribute(`role`,`dialog`),this.pop.hidden=!0,e.append(this.el,this.pop),this.el.addEventListener(`click`,e=>this.onClick(e)),this.el.addEventListener(`keydown`,e=>this.onKey(e)),this.pop.addEventListener(`click`,e=>this.onPick(e)),this.pop.addEventListener(`keydown`,e=>this.onPopKey(e));for(let e of[this.el,this.pop])e.addEventListener(`pointerdown`,e=>e.stopPropagation());this.el.addEventListener(`pointerdown`,e=>{e.target.closest(`.tcw-sel-grip`)&&(e.preventDefault(),this.closePop(),this.drag={id:e.pointerId,x:e.clientX,y:e.clientY,left:parseFloat(this.el.style.left)||0,top:parseFloat(this.el.style.top)||0},document.addEventListener(`pointermove`,this.onDragMove),document.addEventListener(`pointerup`,this.onDragEnd),document.addEventListener(`pointercancel`,this.onDragEnd))}),this.el.addEventListener(`dblclick`,e=>{!e.target.closest(`.tcw-sel-grip`)||!this.target||(this.pinned=null,this.place(this.target))}),document.addEventListener(`pointerdown`,this.onDocDown,!0)}isOpen(){return!this.el.hidden}show(e){this.target=e;let t=e.style,n=[Xo(t.color),Zo(t.lineWidth),Qo(t.lineStyle),e.locked,e.canDelete,e.canSettings,e.canAlert,e.canFill===!0,e.canText===!0,t.fillColor,t.textColor].join(`|`);n!==this.built&&(this.built=n,this.render(e),this.size=null),this.el.hidden=!1,this.size||={w:this.el.offsetWidth,h:this.el.offsetHeight},this.place(e),this.openPop&&this.placePop()}hide(){this.closePop(),this.el.hidden=!0,this.target=null}destroy(){this.onDragEnd(),document.removeEventListener(`pointerdown`,this.onDocDown,!0),this.el.remove(),this.pop.remove()}render(e){let t=this.t,n=Xo(e.style.color),r=Zo(e.style.lineWidth),i=Qo(e.style.lineStyle),a=e.locked,o=this.el.contains(document.activeElement)?document.activeElement.dataset.action:void 0,s=(e,t,n,r=``)=>`<button type="button" class="tcw-sel-btn${r}" data-action="${e}" aria-label="${k(t)}" title="${k(t)}">${n}</button>`,c=(e,t,n)=>s(e,t,n,` tcw-sel-has-pop`).replace(`<button `,`<button aria-haspopup="dialog" aria-expanded="false" `);this.el.innerHTML=[`<span class="tcw-sel-grip" aria-hidden="true"></span>`,c(`color`,t(`drawingSettings.color`),`<span class="tcw-sel-color" style="background:${k(n)}"></span>`),c(`width`,t(`drawingSettings.lineWidth`),`<span class="tcw-sel-width" style="--w:${r}px"></span><span class="tcw-sel-num">${r}px</span>`),c(`lineStyle`,t(`drawingSettings.lineStyle`),es(i)),e.canFill?c(`fill`,t(`drawingSettings.fill`),`<span class="tcw-sel-color tcw-sel-fill" style="background:${k(Xo(e.style.fillColor??n))}"></span>`):``,e.canText?c(`textColor`,t(`drawingSettings.textColor`),`<span class="tcw-sel-text" style="--c:${k(Xo(e.style.textColor??n))}">T</span>`):``,`<span class="tcw-sel-sep" aria-hidden="true"></span>`,e.canSettings?s(`settings`,t(`legend.settings`),O(`settings`,15)):``,e.canAlert?s(`alert`,t(`drawingSettings.addAlert`),O(`bell`,15)):``,s(`lock`,t(a?`common.unlock`:`common.lock`),O(a?`lock`:`unlock`,15),a?` tcw-sel-on`:``).replace(`<button `,`<button aria-pressed="${a}" `),s(`more`,t(`legend.more`),O(`more`,15)),e.canDelete?s(`delete`,t(`drawingMenu.delete`),O(`trash`,15),` tcw-sel-danger`):``].join(``);let l=this.buttons(),u=l.find(e=>e.dataset.action===o)??(o?l.find(e=>e.dataset.action===`lock`):void 0);this.rove(u??l[0],u!==void 0)}buttons(){return[...this.el.querySelectorAll(`button`)]}rove(e,t){for(let t of this.buttons())t.tabIndex=t===e?0:-1;t&&e?.focus()}place(e){let{rect:t,bounds:n}=e,{w:r,h:i}=this.size??{w:0,h:0};if(this.pinned){let e=Math.max(n.x+q,Math.min(this.pinned.left,n.x+n.width-r-q)),t=Math.max(n.y+q,Math.min(this.pinned.top,n.y+n.height-i-q));this.el.style.left=`${Math.round(e)}px`,this.el.style.top=`${Math.round(t)}px`;return}let a=t.x+t.width/2-r/2;a=Math.max(n.x+q,Math.min(a,n.x+n.width-r-q));let o=t.y-i-Ko;o<n.y+q&&(o=Math.min(t.y+t.height+Ko,n.y+n.height-i-q)),o=Math.max(o,n.y+q),this.el.style.left=`${Math.round(a)}px`,this.el.style.top=`${Math.round(o)}px`}onClick(e){let t=e.target.closest(`[data-action]`);if(!t)return;this.rove(t,!1);let n=t.dataset.action;if(n===`color`||n===`width`||n===`lineStyle`||n===`fill`||n===`textColor`){this.openPop===n?this.closePop():this.openPopover(n,t);return}if(this.closePop(),n===`settings`)this.callbacks.onSettings();else if(n===`alert`)this.callbacks.onAlert();else if(n===`lock`)this.callbacks.onLock(!this.target?.locked);else if(n===`delete`)this.callbacks.onDelete();else if(n===`more`){let e=t.getBoundingClientRect(),n=this.host.getBoundingClientRect();this.callbacks.onMore(e.left-n.left,e.bottom-n.top+q)}}onKey(e){if(e.key===`Escape`&&this.openPop){e.stopPropagation(),this.closePop(!0);return}let t=this.buttons(),n=t.indexOf(document.activeElement);if(n<0)return;let r=e.key===`ArrowRight`?(n+1)%t.length:e.key===`ArrowLeft`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),this.rove(t[r],!0))}openPopover(e,t){let n=this.target.style,r=Xo(e===`fill`?n.fillColor??n.color:e===`textColor`?n.textColor??n.color:n.color).toLowerCase(),i=Zo(n.lineWidth),a=Qo(n.lineStyle),o=(e,t,n,r=``)=>`<button type="button" class="${e}${t?` tcw-sel-on`:``}" aria-pressed="${t}" ${n}>${r}</button>`;this.openPop=e,e===`color`||e===`fill`||e===`textColor`?this.pop.innerHTML=Vo.map(e=>o(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=Ho.map(e=>o(`tcw-sel-option`,e===i,`data-width="${e}"`,`<span class="tcw-sel-width" style="--w:${e}px"></span>${e}px`)).join(``):this.pop.innerHTML=Uo.map(e=>o(`tcw-sel-option`,e===a,`data-style="${e}"`,es(e)+k(this.t(`drawingSettings.lineStyle.${e}`)))).join(``),this.pop.className=`tcw-sel-pop tcw-sel-pop--${e}`,this.pop.setAttribute(`aria-label`,t.getAttribute(`aria-label`)??``),this.pop.hidden=!1;for(let e of this.el.querySelectorAll(`[aria-expanded="true"]`))e.setAttribute(`aria-expanded`,`false`);t.setAttribute(`aria-expanded`,`true`),this.placePop(),this.pop.querySelector(`.tcw-sel-on, button`)?.focus()}onPopKey(e){if(e.key===`Escape`){e.stopPropagation(),this.closePop(!0);return}let t=[...this.pop.querySelectorAll(`button`)],n=t.indexOf(document.activeElement);if(n<0)return;let r=this.openPop===`color`||this.openPop===`fill`||this.openPop===`textColor`?qo:1,i=e.key===`ArrowRight`?1:e.key===`ArrowLeft`?-1:e.key===`ArrowDown`?r:e.key===`ArrowUp`?-r:0;i&&(e.preventDefault(),t[(n+i+t.length)%t.length].focus())}placePop(){let e=this.el.querySelector(`[data-action="${this.openPop}"]`);e&&(this.pop.style.left=`${this.el.offsetLeft+e.offsetLeft}px`,this.pop.style.top=`${this.el.offsetTop+this.el.offsetHeight+6}px`)}onPick(e){let t=e.target.closest(`button`);if(!t)return;let n=this.openPop&&this.openPop in Go?Go[this.openPop]:`color`;t.dataset.color?this.callbacks.onStyle({[n]:t.dataset.color}):t.dataset.width?this.callbacks.onStyle({lineWidth:Number(t.dataset.width)}):t.dataset.style&&this.callbacks.onStyle({lineStyle:Qo(t.dataset.style)}),this.closePop(!0)}closePop(e=!1){if(!this.openPop)return;let t=this.el.querySelector(`[data-action="${this.openPop}"]`);t?.setAttribute(`aria-expanded`,`false`),this.openPop=null,this.pop.hidden=!0,e&&t?.focus()}};function es(e){return`<svg class="tcw-sel-line" width="22" height="10" viewBox="0 0 22 10" aria-hidden="true"><line x1="1" y1="5" x2="21" y2="5" stroke="currentColor" stroke-width="2"${e===`dashed`?` stroke-dasharray="4 3"`:e===`dotted`?` stroke-dasharray="1 3" stroke-linecap="round"`:``}/></svg>`}var ts=[1,2,3,4],ns=[`solid`,`dashed`,`dotted`],rs=[10,11,12,13,14,16,18,20,24,28,32],is=12,as=48,os=.5,ss=.1,cs=[`leftEnd`,`rightEnd`];function ls(e,t,n){let r=`drawingOption.${t}`,i=e(r);return i===r?n:i}function us(){let e=document.createElement(`div`);return e.className=`tcw-settings-section`,e}function J(e,...t){let n=document.createElement(`div`);n.className=`tcw-settings-row`;let r=document.createElement(`span`);r.className=`tcw-settings-label`,r.textContent=e;let i=document.createElement(`span`);return i.className=`tcw-indi-plot-controls`,i.append(...t),n.append(r,i),n}function Y(e,t){return e.setAttribute(`aria-label`,t),e}function ds(e,t,n,r){let i=[],a=us();a.appendChild(fs(t.style(),n,i,r));let o=cs.filter(e=>t.defs[e]?.kind===`choice`);o.length>0&&a.appendChild(J(r(`drawingSettings.lineEnds`),...o.map(e=>Y(I([{value:`normal`,label:r(`drawingSettings.lineEnd.normal`)},{value:`arrow`,label:r(`drawingSettings.lineEnd.arrow`)}],String(t.options()[e]??`normal`),t=>n.options({[e]:t})),ls(r,e,t.defs[e].label))))),t.fill&&a.appendChild(ps(t.style(),n,i,r)),e.appendChild(a);let s=Object.entries(t.defs).filter(([e,t])=>t.kind!==`levels`&&!o.includes(e));if(s.length>0){let i=us();for(let[e,a]of s)i.appendChild(ms(e,a,t.options(),n,r));e.appendChild(i)}for(let[a,o]of Object.entries(t.defs))o.kind===`levels`&&e.appendChild(hs(a,o,t,n,i,r))}function fs(e,t,n,r){let i=Y(F(e.color,e=>{t.style({color:e});for(let t of n)t(e)}),r(`drawingSettings.color`)),a=Y(I(ts.map(e=>({value:String(e),label:`${e} px`})),String(e.lineWidth),e=>t.style({lineWidth:Number(e)})),r(`drawingSettings.lineWidth`)),o=Y(I(ns.map(e=>({value:e,label:r(`drawingSettings.lineStyle.${e}`)})),e.lineStyle,e=>t.style({lineStyle:e})),r(`drawingSettings.lineStyle`));return J(r(`drawingSettings.line`),i,a,o)}function ps(e,t,n,r){let i=e.fillColor??Tn(e.color,ss),a=L(i),o=wn(i),s=e.fillColor!==void 0,c=()=>{s=!0,t.style({fillColor:Tn(a,o),fillOpacity:o})},l=Y(F(a,e=>{a=e,c()}),r(`drawingSettings.fill`));n.push(e=>{s||(a=L(e),l.value=a)});let u=Y(P(Math.round(o*100),{min:0,max:100,step:5},e=>{o=e/100,c()}),r(`drawingSettings.opacity`)),d=document.createElement(`span`);return d.className=`tcw-unit`,d.setAttribute(`aria-hidden`,`true`),d.textContent=`%`,J(r(`drawingSettings.fill`),l,u,d)}function ms(e,t,n,r,i){let a=ls(i,e,t.label),o=n[e];switch(t.kind){case`boolean`:return xn(a,!!o,t=>r.options({[e]:t}));case`number`:return N(a,P(Number(o),{min:t.min,max:t.max,step:t.step},t=>r.options({[e]:t})));case`choice`:return N(a,I(t.choices.map(t=>({value:t.value,label:ls(i,`${e}.${t.value}`,t.label)})),String(o),t=>r.options({[e]:t})));case`text`:{let t=document.createElement(`input`);return t.type=`text`,t.className=`tcw-indi-input`,t.value=String(o??``),t.addEventListener(`change`,()=>r.options({[e]:t.value})),N(a,t)}}}function hs(e,t,n,r,i,a){let o=document.createElement(`div`);o.className=`tcw-settings-section tcw-levels-editor`;let s=document.createElement(`div`);s.className=`tcw-settings-section-title`,s.textContent=ls(a,e,t.label),o.appendChild(s);let c=()=>{let t=n.options()[e];return Array.isArray(t)?t:[]},l=t=>r.options({[e]:t}),u=document.createElement(`div`);u.className=`tcw-levels-grid`,c().forEach((e,t)=>{let o=document.createElement(`div`);o.className=`tcw-level-row`;let s=` ${t+1}`,d=document.createElement(`input`);d.type=`checkbox`,d.checked=e.visible,d.setAttribute(`aria-label`,a(`drawingSettings.levelVisible`)+s),d.addEventListener(`change`,()=>l(c().map((e,n)=>n===t?{...e,visible:d.checked}:e)));let f=Y(P(e.value,{step:.001},e=>l(c().map((n,r)=>r===t?{...n,value:e}:n))),a(`drawingSettings.levelValue`)+s),p=Y(F(e.color??n.style().color,e=>l(c().map((n,r)=>r===t?{...n,color:e}:n))),a(`drawingSettings.levelColor`)+s);i.push(e=>{c()[t]?.color===void 0&&(p.value=L(e))});let m=document.createElement(`button`);m.type=`button`,m.className=`tcw-level-remove`,m.setAttribute(`aria-label`,a(`drawingSettings.removeLevel`)+s),m.innerHTML=O(`x`,12),m.addEventListener(`click`,()=>{l(c().filter((e,n)=>n!==t)),r.redraw([`.tcw-level-row:nth-child(${t+1}) .tcw-level-remove`,`.tcw-level-row:last-child .tcw-level-remove`,`.tcw-level-add`])}),o.append(d,f,p,m),u.appendChild(o)}),o.appendChild(u);let d=document.createElement(`button`);return d.type=`button`,d.className=`tcw-reset-link tcw-level-add`,d.textContent=a(`drawingSettings.addLevel`),d.disabled=c().length>=as,d.addEventListener(`click`,()=>{let e=c().at(-1)?.value??0;l([...c(),{value:Math.round((e+os)*1e3)/1e3,visible:!0}]),r.redraw([`.tcw-level-row:last-child input[type="number"]`])}),o.appendChild(d),o}var gs={text:{box:!1,border:!1,wrap:0,fontSize:14},note:{box:!0,border:!0,wrap:240,fontSize:13},callout:{box:!0,border:!0,wrap:240,fontSize:13},signpost:{box:!0,border:!0,wrap:200,fontSize:13},balloon:{box:!0,border:!0,wrap:200,fontSize:13},anchoredText:{box:!1,border:!1,wrap:0,fontSize:14},anchoredNote:{box:!0,border:!0,wrap:240,fontSize:13}},_s=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalLine`,`horizontalRay`,`verticalLine`,`rectangle`]),vs={priceLabel:`#ffffff`},ys=240,bs=40,xs=4e3,Ss=10,Cs=[`left`,`center`,`right`],ws=[`top`,`middle`,`bottom`];function Ts(e,t,n,r=!1){let i=document.createElement(`label`);i.className=`tcw-inline-check`;let a=document.createElement(`input`);if(a.type=`checkbox`,a.checked=t,a.setAttribute(`aria-label`,e),a.addEventListener(`change`,()=>n(a.checked)),i.append(a),!r){let t=document.createElement(`span`);t.textContent=e,i.append(t)}return i}function Es(e,t,n,r,i,a,o=!1){let s=us(),c=document.createElement(`textarea`);c.className=`tcw-indi-input tcw-drawing-text`,c.rows=3,c.value=t.text??``,c.addEventListener(`input`,()=>n({text:c.value}));let l=N(r(`drawingSettings.text`),c);l.classList.add(`tcw-text-row`),s.appendChild(l);let u=Y(I(rs.map(e=>({value:String(e),label:`${e} px`})),String(t.fontSize??i?.fontSize??is),e=>n({fontSize:Number(e)})),r(`drawingSettings.fontSize`));s.appendChild(J(r(`drawingSettings.fontSize`),u,Ts(r(`drawingSettings.bold`),t.bold===!0,e=>n({bold:e})),Ts(r(`drawingSettings.italic`),t.italic===!0,e=>n({italic:e})))),s.appendChild(J(r(`drawingSettings.textColor`),Y(F(t.textColor??a??t.color,e=>n({textColor:e})),r(`drawingSettings.textColor`)))),e.appendChild(s),i&&e.appendChild(Os(t,n,r,i)),o&&e.appendChild(Ds(t,n,r))}function Ds(e,t,n){let r=us();return r.appendChild(J(n(`drawingSettings.align`),Y(I(Cs.map(e=>({value:e,label:n(`drawingSettings.align.${e}`)})),e.textAlign??`center`,e=>t({textAlign:e})),n(`drawingSettings.align`)))),r.appendChild(J(n(`drawingSettings.vAlign`),Y(I(ws.map(e=>({value:e,label:n(`drawingSettings.vAlign.${e}`)})),e.textVAlign??`top`,e=>t({textVAlign:e})),n(`drawingSettings.vAlign`)))),r}function Os(e,t,n,r){let i=us();i.appendChild(J(n(`drawingSettings.align`),Y(I(Cs.map(e=>({value:e,label:n(`drawingSettings.align.${e}`)})),e.textAlign??`left`,e=>t({textAlign:e})),n(`drawingSettings.align`))));let a=e.fillColor??Tn(e.color,ss);i.appendChild(J(n(`drawingSettings.background`),Ts(n(`drawingSettings.background`),e.textBackground??r.box,e=>t({textBackground:e}),!0),Y(F(a,e=>t({fillColor:Tn(e,wn(a))})),n(`drawingSettings.backgroundColor`)))),i.appendChild(J(n(`drawingSettings.border`),Ts(n(`drawingSettings.border`),e.textBorder??r.border,e=>t({textBorder:e}),!0),Y(F(e.borderColor??e.color,e=>t({borderColor:e})),n(`drawingSettings.borderColor`))));let o=e.textWrap??r.wrap,s=o>0?o:r.wrap>0?r.wrap:ys,c=o>0,l=Y(P(s,{min:bs,max:xs,step:Ss},e=>{s=e,c&&t({textWrap:e})}),n(`drawingSettings.wrapWidth`));return l.disabled=!c,i.appendChild(J(n(`drawingSettings.wrap`),Ts(n(`drawingSettings.wrap`),c,e=>{c=e,l.disabled=!e,t({textWrap:e?s:0})},!0),l)),i}function ks(e,n,r,i){let a=us();n.forEach((e,n)=>{let o=t.r(i(`drawingSettings.point`),{n:n+1}),s=r.toWallTime(e.time),c=document.createElement(`input`);c.type=`date`,c.className=`tcw-indi-input`,c.value=s.date;let l=document.createElement(`input`);l.type=`time`,l.className=`tcw-indi-input`,l.value=s.time;let u=()=>{let e=r.fromWallTime(c.value,l.value);e!==null&&r.move(n,{time:e})};c.addEventListener(`change`,u),l.addEventListener(`change`,u);let d=J(o,Y(As(e.price,r,e=>r.move(n,{price:e})),`${o}: ${i(`drawingSettings.price`)}`),Y(c,`${o}: ${i(`drawingSettings.date`)}`),Y(l,`${o}: ${i(`drawingSettings.time`)}`));d.classList.add(`tcw-draw-point`),a.appendChild(d)}),e.appendChild(a)}function As(e,t,n){let r=t.roundPrice??(e=>e),i=t.priceStep?.(),a=P(r(e),{step:i!==void 0&&i>0?i:`any`},e=>{let t=r(e);a.value=String(t),n(t)});return a}var js=12,Ms=`t:`,Ns=1,Ps=class{backdrop;modal;titleEl;tabsEl;bodyEl;templateBtn;menu=null;tabButtons=[];target=null;style;options={};anchors=[];intervals=null;tab=`style`;returnFocus=null;uid=Ns++;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(!0),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow tcw-drawing-settings`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-draw-title-${this.uid}`),this.modal.tabIndex=-1,this.modal.addEventListener(`keydown`,e=>this.onKeyDown(e));let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-draw-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.close(!0)),a.append(this.titleEl,o),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-modal-tabs`,this.tabsEl.setAttribute(`role`,`tablist`),this.tabsEl.addEventListener(`keydown`,e=>this.onTabKey(e)),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`,this.bodyEl.id=`tcw-draw-panel-${this.uid}`,this.bodyEl.setAttribute(`role`,`tabpanel`),this.templateBtn=this.footerButton(`template`,`tcw-footer-menu`,()=>this.openTemplates()),this.modal.append(a,this.tabsEl,this.bodyEl,this.buildFooter()),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}buildFooter(){this.templateBtn.setAttribute(`aria-haspopup`,`menu`),this.templateBtn.setAttribute(`aria-expanded`,`false`),this.templateBtn.innerHTML=`<span></span>${O(`chevronDown`,12)}`,this.templateBtn.querySelector(`span`).textContent=this.t(`settings.template`);let e=document.createElement(`div`);e.className=`tcw-footer-end`,e.append(this.footerButton(`cancel`,`tcw-footer-cancel`,()=>this.close(!0),this.t(`common.cancel`)),this.footerButton(`ok`,`tcw-done-btn`,()=>this.close(!1),this.t(`drawingSettings.ok`)));let t=document.createElement(`div`);return t.className=`tcw-modal-footer`,t.append(this.templateBtn,e),t}open(e,t={}){this.target&&this.close(!1),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.target=e,this.style={...e.style},this.options=structuredClone(e.options),this.anchors=e.anchors.map(e=>({...e})),this.intervals=e.intervals??null,this.titleEl.textContent=e.name,this.tab=t.tab===`text`&&e.text?`text`:`style`,this.callbacks.onBegin(e.id);try{this.renderTabs(),this.renderBody()}catch(t){throw this.target=null,this.callbacks.onEnd(e.id,!0),t}this.backdrop.hidden=!1;let n=this.tab===`text`?this.bodyEl.querySelector(`textarea`):null;n?(n.focus(),n.select()):(this.tabButtons[0]??this.modal).focus()}close(e){let t=this.target;if(!t)return;let n=document.activeElement;!e&&(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&this.modal.contains(n)&&n.dispatchEvent(new Event(`change`)),this.target=null,this.menu?.close(),this.backdrop.hidden=!0,this.callbacks.onEnd(t.id,e),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null}isOpen(){return this.target!==null}editing(){return this.target?.id??null}destroy(){this.close(!0),this.menu?.destroy(),this.backdrop.remove()}tabs(){let e=this.target;return e?[`style`,...e.text?[`text`]:[],...e.coordinates!==!1&&e.anchors.length<=js?[`coordinates`]:[],`visibility`]:[]}renderTabs(){this.tabButtons=this.tabs().map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-modal-tab`,t.id=`tcw-draw-tab-${this.uid}-${e}`,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,this.bodyEl.id),t.dataset.tab=e,t.textContent=this.t(`drawingSettings.tab.${e}`),t.addEventListener(`click`,()=>this.selectTab(e)),t}),this.tabsEl.replaceChildren(...this.tabButtons),this.markTabs()}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.tab=e,this.markTabs(),this.renderBody(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=this.tabButtons.map(e=>e.dataset.tab),n=t.indexOf(this.tab),[r,i]=this.modal.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowLeft`,`ArrowRight`]:[`ArrowRight`,`ArrowLeft`],a=e.key===r?(n+1)%t.length:e.key===i?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;a<0||(e.preventDefault(),this.selectTab(t[a],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.close(!0);return}M(e,this.modal)}renderBody(){this.bodyEl.replaceChildren();let e=this.target;if(e)switch(this.tab){case`text`:Es(this.bodyEl,this.style,e=>this.setStyle(e),this.t,e.textLayout,e.textColor,e.textPlace);break;case`coordinates`:ks(this.bodyEl,this.anchors,{toWallTime:this.callbacks.toWallTime,fromWallTime:this.callbacks.fromWallTime,roundPrice:this.callbacks.roundPrice,priceStep:this.callbacks.priceStep,move:(e,t)=>this.setAnchor(e,t)},this.t);break;case`visibility`:Na(this.bodyEl,this.intervals,e=>this.setIntervals(e),this.t);break;default:ds(this.bodyEl,{style:()=>this.style,options:()=>this.options,defs:e.defs,fill:e.fill},{style:e=>this.setStyle(e),options:e=>this.setOptions(e),redraw:(e=[])=>{this.renderBody();for(let t of e){let e=this.bodyEl.querySelector(t);if(e){e.focus();break}}}},this.t)}}change(e){this.target&&this.callbacks.onChange(this.target.id,e)}setStyle(e){this.target&&(this.style={...this.style,...e},this.change({style:e}))}setOptions(e){this.target&&(this.options={...this.options,...structuredClone(e)},this.change({options:e}))}setAnchor(e,t){this.target&&(this.anchors=this.anchors.map((n,r)=>r===e?{...n,...t}:n),this.change({anchors:this.anchors.map(e=>({...e}))}))}setIntervals(e){this.target&&(this.intervals=e,this.change({intervals:e}))}openTemplates(){let e=this.target;if(!e)return;if(this.menu?.isOpen()){this.menu.close();return}let n=this.callbacks.templates,r=n?.list(e.type)??[],i=[...r.map((e,n)=>({id:`${Ms}${n}`,label:e.name,icon:`layers`,remove:t.r(this.t(`templates.delete`),{name:e.name})})),...r.length>0?[`separator`]:[],...n?[{id:`save`,label:this.t(`settings.saveTemplate`),icon:`save`}]:[],...this.callbacks.onSaveDefault?[{id:`default`,label:this.t(`drawingSettings.saveDefault`),icon:`pin`}]:[],{id:`reset`,label:this.t(`settings.resetToDefaults`),icon:`reset`}],a=e=>r[Number(e.slice(2))];this.menu??=new A(this.modal,this.t(`settings.template`));let o=this.templateBtn.getBoundingClientRect(),s=this.modal.getBoundingClientRect();this.menu.open(i,o.left-s.left,o.top-s.top,t=>{t===`save`?n?.save({type:e.type,style:{...this.style},options:structuredClone(this.options)}):t===`default`?this.callbacks.onSaveDefault?.(e.type,structuredClone(this.options)):t===`reset`?this.resetOptions():t.startsWith(Ms)&&this.applyTemplate(a(t))},this.templateBtn,e=>{let t=a(e);t&&n?.remove(t.name,t.type)})}applyTemplate(e){let t=this.target;!e||!t||(Object.keys(e.style).length>0&&this.setStyle(e.style),e.options&&this.setOptions((0,n.sanitizeDrawingOptions)(t.defs,e.options)),this.renderBody())}resetOptions(){let e=this.target;if(!e)return;let t={};for(let[n,r]of Object.entries(e.defs))t[n]=structuredClone(r.default);this.setOptions(t),this.renderBody()}footerButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=t,i.dataset.act=e,r&&(i.textContent=r),i.addEventListener(`click`,n),i}},Fs=8,Is=6,Ls=1.3,Rs=120,zs=229,Bs=500,Vs=8,Hs=400,Us=class{wrap=null;area=null;target=null;frame=0;done=!0;openedAt=0;offSince=0;onPressAway=e=>{if(!(!this.area||e.target===this.area)){if(this.area.value===this.target?.text&&performance.now()-this.openedAt<Bs){e.preventDefault(),e.stopPropagation();return}this.finish(!0,!1)}};constructor(e){this.layer=e}isOpen(){return this.area!==null}open(e){this.area&&this.finish(!0,!1);let t=e.rect();if(!t)return!1;this.target=e,this.done=!1;let n=document.createElement(`div`);n.className=`tcw-inline-text`;let r=document.createElement(`textarea`);r.className=`tcw-inline-text-input`,r.value=e.text,r.rows=1,r.spellcheck=!1,r.setAttribute(`aria-label`,e.label);let{size:i,bold:a,italic:o,family:s}=e.font;return Object.assign(r.style,{fontSize:`${i}px`,fontWeight:a?`bold`:`normal`,fontStyle:o?`italic`:`normal`,fontFamily:s,lineHeight:String(Ls),color:e.color,padding:`${Is}px ${Fs}px`}),r.addEventListener(`input`,()=>{this.fit(),this.target?.onInput(r.value);let e=this.target?.rect();e&&this.place(e)}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),!(e.isComposing||e.keyCode===zs)&&(e.key===`Escape`?(e.preventDefault(),this.finish(!1,!0)):e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.finish(!0,!0)))}),r.addEventListener(`blur`,()=>this.finish(!0,!1)),n.appendChild(r),this.layer().appendChild(n),this.wrap=n,this.area=r,this.place(t),this.fit(),r.focus(),r.select(),this.openedAt=performance.now(),this.offSince=0,document.addEventListener(`pointerdown`,this.onPressAway,!0),document.addEventListener(`mousedown`,this.onPressAway,!0),this.follow(),!0}commit(){this.finish(!0,!1)}close(){this.done=!0,this.teardown()}finish(e,t){if(this.done||!this.area||!this.target)return;this.done=!0;let n=this.area.value,r=this.target;this.teardown(),e?r.onCommit(n):r.onCancel(),t&&r.returnFocus?.()?.focus({preventScroll:!0})}teardown(){document.removeEventListener(`pointerdown`,this.onPressAway,!0),document.removeEventListener(`mousedown`,this.onPressAway,!0),cancelAnimationFrame(this.frame),this.frame=0,this.wrap?.remove(),this.wrap=null,this.area=null,this.target=null}place(e){let t=this.area;if(!t)return;let n=Math.max(Rs,window.innerWidth-Vs*2);t.style.maxWidth=`${n}px`,t.style.width=`${Math.min(n,Math.max(Rs,e.width))}px`,t.style.minHeight=`${e.height}px`;let r=t.offsetWidth||Math.max(Rs,e.width),i=t.offsetHeight||e.height;t.style.left=`${Math.max(Vs,Math.min(e.x,window.innerWidth-Vs-r))}px`,t.style.top=`${Math.max(Vs,Math.min(e.y,window.innerHeight-Vs-i))}px`}offWindow(e){return e.x>window.innerWidth||e.x+e.width<0||e.y>window.innerHeight||e.y+e.height<0}fit(){let e=this.area;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)}follow(){this.frame=requestAnimationFrame(()=>{if(!this.target||this.done)return;let e=this.target.rect(),t=e!==null&&this.offWindow(e);if(t?this.offSince===0&&(this.offSince=performance.now()):this.offSince=0,!e||t&&performance.now()-this.offSince>Hs){this.finish(!0,!1);return}this.place(e),this.follow()})}};function Ws(e,t){let{selected:n}=e,r=n.length===1,i=new Set(n.map(e=>e.groupId)),a=i.size===1&&!i.has(null),o=[];e.canConfigure&&r&&o.push({id:`settings`,label:t(`drawingMenu.settings`),icon:`settings`}),e.canAlert&&r&&o.push({id:`alert`,label:t(`drawingSettings.addAlert`),icon:`bell`}),o.length>0&&o.push(`separator`),r&&o.push({id:`front`,label:t(`drawingMenu.front`)},{id:`forward`,label:t(`drawingMenu.forward`)},{id:`backward`,label:t(`drawingMenu.backward`)},{id:`back`,label:t(`drawingMenu.back`)},`separator`),n.length>1&&!a&&o.push({id:`group`,label:t(`drawingMenu.group`),icon:`layers`}),n.some(e=>e.groupId)&&o.push({id:`ungroup`,label:t(`drawingMenu.ungroup`),icon:`layers`});let s=n.every(e=>e.locked);return o.push(s?{id:`unlock`,label:t(`common.unlock`),icon:`unlock`}:{id:`lock`,label:t(`common.lock`),icon:`lock`},{id:`hide`,label:t(`common.hide`),icon:`eyeOff`}),r&&o.push({id:`duplicate`,label:t(`drawingMenu.duplicate`),icon:`plus`}),s||o.push(`separator`,{id:`delete`,label:t(`drawingMenu.delete`),icon:`trash`,danger:!0}),o}var Gs=[{id:`regularScale`,mode:`regular`,label:`settings.scale.regular`},{id:`logScale`,mode:`logarithmic`,label:`settings.scale.logarithmic`},{id:`percentScale`,mode:`percentage`,label:`settings.scale.percentage`},{id:`indexedScale`,mode:`indexedTo100`,label:`settings.scale.indexedTo100`}],Ks=[{action:`resetView`,keys:`Alt+R`,feature:`hotkeys.resetView`},{action:`invertScale`,keys:`Alt+I`,feature:`hotkeys.invertScale`},{action:`goToDate`,keys:`Alt+G`,feature:`hotkeys.goToDate`}];function qs(e){return Gs.find(t=>t.id===e)?.mode}function Js(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function Ys(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function Xs(e,n){if(e.price===void 0||!Number.isFinite(e.price))return[];let r=e.formatPrice(e.price),i=[];if(e.canAlert&&i.push({id:`alert`,label:t.r(n(`chartMenu.addAlert`),{price:r}),icon:`bell`}),e.canTrade){let a=e.lastPrice===null||e.price<=e.lastPrice;i.push(a?{id:`buyLimit`,label:t.r(n(`chartMenu.buyLimit`),{price:r}),icon:`trendingUp`}:{id:`buyStop`,label:t.r(n(`chartMenu.buyStop`),{price:r}),icon:`trendingUp`},a?{id:`sellStop`,label:t.r(n(`chartMenu.sellStop`),{price:r}),icon:`trendingDown`}:{id:`sellLimit`,label:t.r(n(`chartMenu.sellLimit`),{price:r}),icon:`trendingDown`}),e.canOrderTicket&&i.push({id:`orderTicket`,label:n(`chartMenu.orderTicket`),icon:`receipt`})}return e.canDraw&&i.push({id:`horizontalLine`,label:t.r(n(`chartMenu.horizontalLine`),{price:r}),icon:`minus`}),i}var Zs=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function Qs(e,t){let n=[Ys({id:`resetView`,label:t(`chartMenu.resetView`)},e)];e.canPaste&&n.push({id:`paste`,label:t(`chartMenu.paste`)});let r=[];e.hasDrawings&&r.push(e.drawingsHidden?{id:`showDrawings`,label:t(`chartMenu.showDrawings`),icon:`eye`}:{id:`hideDrawings`,label:t(`chartMenu.hideDrawings`),icon:`eyeOff`},{id:`removeDrawings`,label:t(`chartMenu.removeDrawings`),icon:`trash`,danger:!0}),e.hasIndicators&&r.push({id:`removeIndicators`,label:t(`chartMenu.removeIndicators`),icon:`trash`,danger:!0});let i=e.canExport?[{id:`exportData`,label:t(`chartMenu.exportData`),icon:`save`}]:[];return Js(Xs(e,t),n,r,[...i,Zs(t)])}function $s(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},Ys({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=Gs.filter(t=>t.mode!==`logarithmic`||e.canLog).map(n=>({id:n.id,label:t(n.label),radio:!0,checked:e.scaleMode===n.mode})),i=[{id:`indicatorValueLabels`,label:t(`settings.indicatorValues`),checked:e.labels.values},{id:`alignAxisLabels`,label:t(`settings.alignAxisLabels`),checked:e.labels.aligned}];e.labels.countdown!==void 0&&i.push({id:`barCountdown`,label:t(`settings.barCountdown`),checked:e.labels.countdown});let a=[{id:`highLowLines`,label:t(`settings.highLowLines`),checked:e.lines.highLow},{id:`lastPriceLine`,label:t(`chartMenu.lastPriceLine`),checked:e.lines.lastPrice}];return Js(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],Xs({...e,canTrade:!1,canDraw:!1},t),[Zs(t)])}function ec(e,t){let n=[Ys({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(Ys({id:`goToDate`,label:t(`chartMenu.goToDate`),icon:`calendar`},e));let r=e.timezone.options.map(t=>({id:`tz:${t.value}`,label:t.label,radio:!0,checked:t.value===e.timezone.current}));return Js(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function tc(e,t){let n=e.pane?[{id:`paneLog`,label:t(`chartMenu.paneLog`),checked:e.pane.log},{id:`paneInvert`,label:t(`chartMenu.paneInvert`),checked:e.pane.invert},{id:`panePercent`,label:t(`chartMenu.panePercent`),checked:e.pane.percent}]:[];return Js([Ys({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[Zs(t)])}function nc(e,t,n){switch(e){case`priceAxis`:return $s(t,n);case`timeAxis`:return ec(t,n);case`pane`:return tc(t,n);default:return Qs(t,n)}}var rc=/^[-+−]/;function ic(e,t,n){let r=e.replace(rc,``);return r===n.replace(rc,``)?r:t>0?`+${r}`:t<0?`-${r}`:r}function ac(e){return e.startsWith(`+`)?`up`:e.startsWith(`-`)?`down`:null}var oc=[`positions`,`orders`,`history`],sc=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],cc=[`market`,`limit`,`stop`],lc=[`gtc`,`day`],uc=`—`,dc=`{pnl}`,fc=3;function pc(e,t,n){return e.includes(t??``)?t:n}function mc(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function hc(e,t){if(t===null)return null;let n=e.quantity-(e.closedQuantity??0),r=e.side===`buy`?1:-1;return{pnl:(t-e.entryPrice)*n*r,pct:e.entryPrice===0?0:(t-e.entryPrice)/e.entryPrice*100*r}}function gc(e){let t=document.createElement(`span`);return t.dir=`ltr`,t.textContent=e,t}function _c(e){let t=ac(e);return t?`tcw-account-${t}`:``}var vc=class{el;tabButtons=new Map;tabLabels=new Map;tabCounts=new Map;totalsEl;content;tab=`positions`;snapshot={positions:[],orders:[],fills:[],price:null};open=!1;live=[];constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.el=document.createElement(`section`),this.el.className=`tcw-account`,this.el.hidden=!0,this.el.setAttribute(`aria-label`,this.t(`account.title`));let i=document.createElement(`div`);i.className=`tcw-account-head`;let a=document.createElement(`div`);a.className=`tcw-account-tabs`,a.setAttribute(`role`,`tablist`),a.addEventListener(`keydown`,e=>this.onTabKey(e));for(let e of oc){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-account-tab`,t.setAttribute(`role`,`tab`),t.id=`tcw-account-tab-${e}`;let n=document.createElement(`span`);n.className=`tcw-account-tab-label`,n.textContent=this.t(`account.${e}`);let r=document.createElement(`span`);r.className=`tcw-account-count`,t.append(n,r),t.addEventListener(`click`,()=>this.selectTab(e)),this.tabButtons.set(e,t),this.tabLabels.set(e,n.textContent),this.tabCounts.set(e,r),a.appendChild(t)}this.totalsEl=document.createElement(`div`),this.totalsEl.className=`tcw-account-totals`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-account-new`,D(o,`orderTicket`),o.innerHTML=O(`plus`,13),o.append(this.t(`account.newOrder`)),o.addEventListener(`click`,()=>this.callbacks.onNewOrder());let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-tree-close`,s.setAttribute(`aria-label`,this.t(`account.close`)),s.innerHTML=O(`x`,14),s.addEventListener(`click`,()=>this.closePanel()),i.append(a,this.totalsEl,o,s),this.content=document.createElement(`div`),this.content.className=`tcw-account-body`,this.content.setAttribute(`role`,`tabpanel`),this.el.append(i,this.content),e.appendChild(this.el),this.renderTabs()}isOpen(){return this.open}toggle(){this.open?this.closePanel():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}closePanel(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}update(e){let t=this.snapshot;if(this.snapshot=e,mc(t.positions,e.positions)&&mc(t.orders,e.orders)&&mc(t.fills,e.fills)&&t.realisedPnl===e.realisedPnl){t.price!==e.price&&(this.renderTotals(),this.open&&this.tab===`positions`&&this.patchPrices());return}this.renderTabs(),this.open&&this.render()}destroy(){this.el.remove()}selectTab(e){this.tab=e,this.renderTabs(),this.render()}onTabKey(e){let t=oc.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=oc[(n+oc.length)%oc.length];this.selectTab(r),this.tabButtons.get(r)?.focus()}renderTabs(){let e={positions:this.snapshot.positions.length,orders:this.snapshot.orders.length,history:this.snapshot.fills.length};for(let[t,n]of this.tabButtons){let r=t===this.tab;this.tabCounts.get(t).textContent=String(e[t]),n.setAttribute(`aria-label`,`${this.tabLabels.get(t)} (${e[t]})`),n.setAttribute(`aria-selected`,String(r)),n.tabIndex=r?0:-1,r&&this.content.setAttribute(`aria-labelledby`,n.id)}this.renderTotals()}renderTotals(){let{positions:e,price:t,fills:n,realisedPnl:r}=this.snapshot,i=[],a=e.reduce((e,n)=>{let r=hc(n,t);return r===null?e:(e??0)+r.pnl},null);a!==null&&i.push(this.total(`account.openPnl`,a)),(n.length>0||r!==void 0&&r!==0)&&i.push(this.total(`account.realised`,r??n.reduce((e,t)=>e+(t.pnl??0),0))),this.totalsEl.replaceChildren(...i)}total(e,t){let n=document.createElement(`span`),r=this.amount(t);n.className=`tcw-account-total ${_c(r)}`.trim();let i=this.t(e),a=i.indexOf(dc),o=gc(r);return a<0?n.append(`${i} `,o):n.append(i.slice(0,a),o,i.slice(a+5)),n}render(){let e=document.activeElement,t=e instanceof HTMLElement&&this.content.contains(e)?e.dataset.focusKey:void 0;this.live=[],this.tab===`positions`?this.renderPositions():this.tab===`orders`?this.renderOrders():this.renderHistory(),t&&[...this.content.querySelectorAll(`[data-focus-key]`)].find(e=>e.dataset.focusKey===t)?.focus()}patchPrices(){let{price:e}=this.snapshot;for(let t of this.live)t.price.textContent=e===null?uc:this.callbacks.formatPrice(e),this.writePnl(t.pnl,hc(t.position,e))}amount(e){return ic(this.money(Math.abs(e)),e,this.money(0))}money(e){return this.callbacks.formatAmount?this.callbacks.formatAmount(e):e.toFixed(2)}percent(e){let t=e=>this.callbacks.formatNumber?this.callbacks.formatNumber(e,2):e.toFixed(2);return`${ic(t(Math.abs(e)),e,t(0))}%`}writePnl(e,t){if(t===null){e.className=``,e.textContent=uc;return}let n=this.amount(t.pnl);e.className=_c(n),e.textContent=`${n} · ${this.percent(t.pct)}`}table(e,t,n){if(t.length===0){let e=document.createElement(`p`);return e.className=`tcw-account-empty`,e.textContent=this.t(n),this.content.replaceChildren(e),null}let r=e.map(e=>e.key?this.t(e.key):``),i=document.createElement(`table`);i.className=`tcw-account-table`,i.setAttribute(`role`,`table`);let a=i.createTHead().insertRow();a.setAttribute(`role`,`row`),e.forEach((e,t)=>{let n=document.createElement(`th`);n.scope=`col`,n.setAttribute(`role`,`columnheader`),n.textContent=r[t],e.num&&(n.className=`tcw-num`),a.appendChild(n)});let o=i.createTBody();for(let n of t){let t=o.insertRow();t.setAttribute(`role`,`row`),n.forEach((n,i)=>{let a=t.insertCell();a.setAttribute(`role`,`cell`),a.dataset.label=r[i],e[i].num&&(a.className=`tcw-num`),typeof n==`string`?a.textContent=n:a.appendChild(n)})}return this.content.replaceChildren(i),i}sideCell(e,t=`position`){let n=document.createElement(`span`);return n.className=`tcw-account-side tcw-account-${e}`,n.textContent=this.sideText(e,t),n}sideText(e,t){return t===`trade`?this.t(e===`buy`?`ticket.buy`:`ticket.sell`):this.t(e===`buy`?`account.long`:`account.short`)}actions(...e){let t=document.createElement(`div`);t.className=`tcw-account-actions`;for(let n of e){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-btn${n.danger?` tcw-tree-del`:``}`,e.setAttribute(`aria-label`,n.label),e.title=n.label,e.dataset.focusKey=n.key,e.innerHTML=O(n.icon,14),e.addEventListener(`click`,n.run),t.appendChild(e)}return t}price(e){return e===void 0?uc:this.callbacks.formatPrice(e)}renderPositions(){let{formatPrice:e}=this.callbacks,{price:t}=this.snapshot,n=[],r=this.snapshot.positions.map(r=>{let i=r.quantity-(r.closedQuantity??0),a=gc(``);this.writePnl(a,hc(r,t)),n.push(a);let o=`${this.sideText(r.side,`position`)} ${i} @ ${e(r.entryPrice)}`;return[this.sideCell(r.side),String(i),e(r.entryPrice),t===null?uc:e(t),a,this.price(r.stopLoss),this.price(r.takeProfit),this.actions({icon:`arrowUpDown`,label:`${this.t(`account.reverse`)}: ${o}`,key:`reverse:${r.id}`,run:()=>this.callbacks.onReversePosition(r.id)},{icon:`x`,label:`${this.t(`account.closePosition`)}: ${o}`,key:`close:${r.id}`,run:()=>this.callbacks.onClosePosition(r.id),danger:!0})]}),i=this.table([{key:`account.side`},{key:`account.quantity`,num:!0},{key:`account.entry`,num:!0},{key:`account.price`,num:!0},{key:`account.pnl`,num:!0},{key:`account.stopLoss`,num:!0},{key:`account.takeProfit`,num:!0},{key:null}],r,`account.noPositions`);if(!i)return;let a=[...i.tBodies[0].rows];this.snapshot.positions.forEach((e,t)=>this.live.push({position:e,price:a[t].cells[fc],pnl:n[t]}))}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=pc(cc,t.type===`stopLimit`?`stop`:t.type,`limit`),r=`${this.sideText(t.side,`trade`)} ${t.quantity} @ ${e(t.price)}`;return[this.sideCell(t.side,`trade`),this.t(`ticket.type.${n}`),String(t.quantity),e(t.price),this.price(t.stopLoss),this.price(t.takeProfit),t.timeInForce?this.t(`ticket.tif.${pc(lc,t.timeInForce,`gtc`)}`):uc,this.actions({icon:`x`,label:`${this.t(`account.cancelOrder`)}: ${r}`,key:`cancel:${t.id}`,run:()=>this.callbacks.onCancelOrder(t.id),danger:!0})]});this.table([{key:`account.side`},{key:`ticket.type`},{key:`account.quantity`,num:!0},{key:`account.price`,num:!0},{key:`account.stopLoss`,num:!0},{key:`account.takeProfit`,num:!0},{key:`ticket.timeInForce`},{key:null}],t,`account.noOrders`)}renderHistory(){let{formatPrice:e,formatTime:t}=this.callbacks,n=[...this.snapshot.fills].reverse().map(n=>{let r=gc(``);return n.pnl===void 0?r.textContent=uc:(r.textContent=this.amount(n.pnl),r.className=_c(r.textContent)),[t(n.time),this.sideCell(n.side,`trade`),String(n.quantity),e(n.price),this.t(`account.reason.${pc(sc,n.reason,`order`)}`),r]});this.table([{key:`account.time`},{key:`account.side`},{key:`account.quantity`,num:!0},{key:`account.price`,num:!0},{key:`account.reason`},{key:`account.pnl`,num:!0}],n,`account.noFills`)}},yc=1e-9;function bc(e,t){return e.type===`market`?t:e.price}function xc(e,t,n={}){let r=[];(!(e.quantity>0)||!Number.isFinite(e.quantity))&&r.push(`quantity`),e.type!==`market`&&(!(e.price>0)||!Number.isFinite(e.price))&&r.push(`price`),e.type===`market`&&!((t??e.price)>0)&&r.push(`market`);let i=e.side===`buy`;if(t!==null&&e.type!==`market`&&e.price>0){let n=e.price<t;e.type===`limit`&&n!==i&&e.price!==t&&r.push(`limitSide`),e.type===`stop`&&n===i&&e.price!==t&&r.push(`stopSide`)}let a=e=>e===null||Number.isFinite(e)&&e>0;a(e.stopLoss)||r.push(`stopLoss`),a(e.takeProfit)||r.push(`takeProfit`);let o=bc(e,t);return o!==null&&o>0&&(e.stopLoss!==null&&a(e.stopLoss)&&(i?e.stopLoss>=o:e.stopLoss<=o)&&r.push(`stopLossSide`),e.takeProfit!==null&&a(e.takeProfit)&&(i?e.takeProfit<=o:e.takeProfit>=o)&&r.push(`takeProfitSide`)),[...r,...Sc(e,n)]}function Sc(e,t){let n=[],r=e.type===`market`?null:e.price,i=[r,e.stopLoss,e.takeProfit].filter(e=>e!==null&&Number.isFinite(e)&&e>0),{roundPrice:a,limits:o,lot:s}=t;return a&&i.some(e=>Math.abs(a(e)-e)>yc)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+yc||r<o.floor-yc)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function Cc(e,t){let n={side:e.side,type:e.type,price:e.type===`market`?t??e.price:e.price,quantity:e.quantity};return e.type===`stop`&&(n.stopPrice=e.price),e.type!==`market`&&(n.timeInForce=e.timeInForce),e.stopLoss!==null&&(n.stopLoss=e.stopLoss),e.takeProfit!==null&&(n.takeProfit=e.takeProfit),n}function wc(e,t){let n=bc(e,t);if(n===null||e.stopLoss===null||e.takeProfit===null)return null;let r=Math.abs(n-e.stopLoss);return r>0?Math.abs(e.takeProfit-n)/r:null}function Tc(e,t,n,r=1){let i=bc(e,t);if(i===null||!(i>0)||!Number.isFinite(n)||!(e.quantity>0))return null;let a=e.side===`buy`?1:-1;return{pct:(n-i)/i*100*a,amount:(n-i)*e.quantity*a*r}}function Ec(e,t,n={}){let r=n.multiplier!==void 0&&n.multiplier>0?n.multiplier:1,i=bc(e,t),a=i!==null&&i>0&&e.quantity>0?i*e.quantity*r:null,o=xc(e,t),s=(n,i)=>n===null||o.includes(i)?null:Tc(e,t,n,r)?.amount??null,c=s(e.stopLoss,`stopLossSide`),l=s(e.takeProfit,`takeProfitSide`);return{value:a,risk:c,reward:l,ratio:c!==null&&l!==null?wc(e,t):null}}var Dc=229,Oc=1,kc=2,Ac=.999999999,jc=0,Mc=class{backdrop;modal;symbolEl;body;summaryEl;problemsEl;submit;draft=null;lastPrice=null;rules={};step=Pc;round=e=>Fc(e,e);typed=new Map;returnFocus=null;uid=++jc;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-order-ticket`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-ticket-title-${this.uid}`),this.modal.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&!e.isComposing&&e.keyCode!==Dc){e.stopPropagation(),this.close();return}M(e,this.modal)});let a=document.createElement(`div`);a.className=`tcw-modal-header`;let o=document.createElement(`div`);o.className=`tcw-ticket-heading`;let s=document.createElement(`h3`);s.id=`tcw-ticket-title-${this.uid}`,s.textContent=this.t(`ticket.title`),this.symbolEl=document.createElement(`span`),this.symbolEl.className=`tcw-ticket-symbol`,o.append(s,this.symbolEl);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-modal-close`,c.setAttribute(`aria-label`,this.t(`common.close`)),c.innerHTML=O(`x`,16),c.addEventListener(`click`,()=>this.close()),a.append(o,c),this.body=document.createElement(`div`),this.body.className=`tcw-modal-body tcw-ticket-body`,this.summaryEl=document.createElement(`div`),this.summaryEl.className=`tcw-ticket-summary`,this.problemsEl=document.createElement(`div`),this.problemsEl.className=`tcw-ticket-problems`,this.problemsEl.setAttribute(`aria-live`,`polite`);let l=document.createElement(`div`);l.className=`tcw-modal-footer`;let u=document.createElement(`button`);u.type=`button`,u.className=`tcw-footer-cancel`,u.textContent=this.t(`common.cancel`),u.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`button`,this.submit.className=`tcw-ticket-place`,this.submit.addEventListener(`click`,()=>this.place());let d=document.createElement(`div`);d.className=`tcw-footer-end`,d.append(u,this.submit),l.append(d),this.modal.append(a,this.body,this.summaryEl,this.problemsEl,l),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.lastPrice=e.lastPrice,this.rules=e.rules??{},this.step=e.step??Pc,this.round=e.round??(e=>Fc(e,e)),this.typed.clear(),this.symbolEl.textContent=e.symbol??``;let t=this.round(e.price??e.lastPrice??0),n=e.side??`buy`,r=`market`;e.price!==void 0&&e.lastPrice!==null&&t!==e.lastPrice&&(r=t<e.lastPrice==(n===`buy`)?`limit`:`stop`),this.draft={side:n,type:r,quantity:this.lot(),price:t,stopLoss:null,takeProfit:null,timeInForce:`gtc`},this.problemsEl.replaceChildren(),this.render(),this.backdrop.hidden=!1,this.body.querySelector(`button[aria-pressed="true"]`)?.focus()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.draft=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}setLastPrice(e){if(!this.draft||e===this.lastPrice)return;this.lastPrice=e;let t=this.body.querySelector(`.tcw-ticket-market`);t&&(t.textContent=this.marketText()),this.check()}destroy(){this.close(),this.backdrop.remove()}lot(){return this.rules.lot!==void 0&&this.rules.lot>1?this.rules.lot:1}quantityStep(e){if(this.rules.lot!==void 0&&this.rules.lot>1)return this.rules.lot;let t=Number.isFinite(e)?(0,n.stepDecimals)(e):0;return t>0?Number((10**-t).toFixed(t)):1}priceStep(e,t){return this.step(t>0?e:e*Ac)}writePrice(e){return Number.isFinite(e)?this.step===Pc?String(e):e.toFixed((0,n.stepDecimals)(this.step(e))):``}place(){let e=this.draft;!e||xc(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(Cc(e,this.lastPrice)),this.close())}set(e,t=!1){this.draft&&(this.draft={...this.draft,...e},t?this.render():this.check())}render(){let e=this.draft;if(!e)return;let t=this.focusedField();if(this.modal.dataset.side=e.side,this.body.replaceChildren(this.sideToggle(e.side),this.row(`ticket.type`,this.choices(`type`,[`market`,`limit`,`stop`],e.type,`ticket.type`,e=>this.set({type:e},!0))),this.row(`ticket.quantity`,this.stepped(`quantity`,e.quantity,e=>this.quantityStep(e),()=>this.lot(),String,e=>this.set({quantity:e})))),e.type===`market`){let e=document.createElement(`span`);e.className=`tcw-ticket-market`,e.textContent=this.marketText(),this.body.append(this.row(`ticket.price`,e))}else this.body.append(this.row(`ticket.price`,this.priceField(`price`,e.price,e=>this.set({price:e}))),this.row(`ticket.timeInForce`,this.choices(`timeInForce`,[`gtc`,`day`],e.timeInForce,`ticket.timeInForce`,e=>this.set({timeInForce:e}))));this.body.append(this.optionalPrice(`stopLoss`,e.stopLoss),this.optionalPrice(`takeProfit`,e.takeProfit)),t&&this.body.querySelector(t)?.focus(),this.check()}focusedField(){let e=document.activeElement;if(!(e instanceof HTMLElement)||!this.body.contains(e))return null;let t=e.dataset.ticketField;return t?`[data-ticket-field="${t}"]`:null}row(e,t){let n=document.createElement(`div`);n.className=`tcw-settings-row tcw-ticket-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=this.t(e),n.append(r,t),n}choices(e,t,n,r,i){let a=e===`type`?`ticket.type`:`ticket.tif`,o=Nc(e,Dn(t.map(e=>({value:e,label:this.t(`${a}.${e}`)})),n,i,this.t(r)));for(let t of o.querySelectorAll(`[role=radio]`))t.dataset.ticketField=`${e}-${t.dataset.value}`;return o}marketText(){let e=this.t(`ticket.type.market`);return this.lastPrice===null?e:`${e} · ${this.callbacks.formatPrice(this.lastPrice)}`}typeFor(e,t){return e.type===`market`||this.lastPrice===null||!(e.price>0)||e.price===this.lastPrice?e.type:e.price<this.lastPrice==(t===`buy`)?`limit`:`stop`}sideToggle(e){let t=document.createElement(`div`);t.className=`tcw-ticket-side`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`${this.t(`ticket.buy`)} / ${this.t(`ticket.sell`)}`);for(let n of[`buy`,`sell`]){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-ticket-side-btn tcw-ticket-${n}`,r.textContent=this.t(`ticket.${n}`),r.setAttribute(`aria-pressed`,String(e===n)),r.dataset.ticketField=`side-${n}`,r.addEventListener(`click`,()=>{let e=this.draft;!e||e.side===n||this.set({side:n,type:this.typeFor(e,n)},!0)}),t.appendChild(r)}return t}priceField(e,t,n){return this.stepped(e,t,(e,t)=>this.priceStep(e,t),()=>this.lastPrice??this.draft?.price??0,e=>this.writePrice(e),n)}stepped(e,n,r,i,a,o){let s=Nc(e,document.createElement(`input`));s.type=`number`,s.className=`tcw-indi-input`,s.step=`any`,s.min=`0`,s.value=this.typed.get(e)??a(n);let c=this.t(`ticket.${e}`);s.setAttribute(`aria-label`,c),s.addEventListener(`input`,()=>{this.typed.set(e,s.value),o(s.value.trim()===``?NaN:Number(s.value))});let l=kn(s,{step:r,fallback:i,format:a,labels:{down:t.r(this.t(`ticket.stepDown`),{field:c}),up:t.r(this.t(`ticket.stepUp`),{field:c})}});return l.down.dataset.ticketField=`${e}-down`,l.up.dataset.ticketField=`${e}-up`,l.element}optionalPrice(e,t){let n=e===`stopLoss`?`ticket.stopLoss`:`ticket.takeProfit`,r=document.createElement(`div`);r.className=`tcw-settings-row tcw-ticket-optional`;let i=Sn(t!==null,t=>{this.typed.delete(e),this.set({[e]:t?this.startOf(e):null},!0)});i.setAttribute(`aria-label`,this.t(n)),i.dataset.ticketField=`${e}-switch`;let a=document.createElement(`div`);a.className=`tcw-ticket-optional-name`;let o=document.createElement(`span`);if(o.className=`tcw-settings-label`,o.textContent=this.t(n),a.appendChild(o),r.append(i,a),t!==null){let n=document.createElement(`span`);n.className=`tcw-ticket-away`,n.dataset.for=e,n.dir=`ltr`,a.appendChild(n),r.appendChild(this.priceField(e,t,t=>this.set({[e]:Number.isFinite(t)?t:NaN})))}return r}startOf(e){let t=this.draft;if(!t)return NaN;let n=t.type===`market`?this.lastPrice??t.price:t.price;if(!(n>0))return NaN;let r=e===`stopLoss`?-Oc:kc;return this.round(n*(1+(t.side===`buy`?r:-r)/100))}check(){let e=this.draft;if(!e)return;let t=xc(e,this.lastPrice,this.rules),n=t.map(e=>this.problemText(e));n.join(`
|
|
7732
|
+
`}stepMarkup(){let e=this.labels;if(this.steps.length<=1)return``;let t=this.steps.map(e=>`<option value="${k(e.value)}"${e.value===this.step?` selected`:``}>${k(e.label)}</option>`).join(``);return`<label class="tcw-replay-chip"><span class="tcw-replay-chip-label" dir="${this.dir}">${k(e.step)}</span><select class="tcw-replay-speed tcw-replay-step" data-act="step" dir="ltr">${t}</select></label>`}wireStep(){(this.root?.querySelector(`[data-act="step"]`))?.addEventListener(`change`,e=>{this.step=e.target.value,this.callbacks.onStepChange?.(this.step)})}wireEvents(){let e=this.root;if(!e)return;this.hintText=e.querySelector(`[data-tcw="hint"]`),this.scrubber=e.querySelector(`input[data-act="seek"]`),this.timeLabel=e.querySelector(`[data-tcw="time"]`),this.playBtn=e.querySelector(`button[data-act="play"]`),this.realtimeBtn=e.querySelector(`button[data-act="realtime"]`),this.liveRegion=e.querySelector(`[data-tcw="announce"]`);let t=(t,n)=>e.querySelector(`[data-act="${t}"]`)?.addEventListener(`click`,n);t(`realtime`,()=>this.callbacks.onClose()),t(`random`,()=>this.callbacks.onRandomStart()),t(`stepBack`,()=>this.callbacks.onStepBack()),t(`stepForward`,()=>this.callbacks.onStepForward()),t(`selectBar`,()=>this.callbacks.onSelectBar?.()),t(`cancel`,()=>(this.callbacks.onCancelPick??this.callbacks.onClose)()),t(`play`,()=>this.togglePlay()),this.scrubber?.addEventListener(`input`,()=>this.callbacks.onSeek(Number(this.scrubber.value))),e.querySelector(`[data-act="speed"]`)?.addEventListener(`change`,e=>{let t=Number(e.target.value);this.rate=t,this.callbacks.onSpeedChange(t)}),e.addEventListener(`keydown`,this.onKeydown),this.wireStep()}togglePlay(){this.state===`playing`?this.callbacks.onPause():this.callbacks.onPlay()}onKeydown=e=>{if(e.key!==` `||this.mode!==`replay`||e.defaultPrevented)return;let t=e.target;t!==this.scrubber&&t!==this.root||(e.preventDefault(),e.stopPropagation(),this.playBtn?.disabled||this.togglePlay())};announce(e){this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>{this.announceTimer=null,this.liveRegion&&(this.liveRegion.textContent=e)},ti)}syncUi(){let e=this.root;if(e){for(let t of e.querySelectorAll(`[data-mode]`))t.hidden=t.dataset.mode!==this.mode;if(e.dataset.mode=this.mode,e.classList.toggle(`tcw-replay-bar--ended`,this.ended),this.syncPending(e),this.playBtn){let e=this.state===`playing`;this.playBtn.innerHTML=O(e?`pause`:`play`,14),this.playBtn.title=e?this.labels.pause:this.labels.play,this.playBtn.setAttribute(`aria-label`,this.playBtn.title);let t=this.ended&&!e;t&&document.activeElement===this.playBtn&&this.realtimeBtn?.focus(),this.playBtn.disabled=t}}}syncPending(e){for(let t of e.querySelectorAll(`.tcw-replay-group`))this.pending?t.setAttribute(`aria-busy`,`true`):t.removeAttribute(`aria-busy`);this.hintText&&(this.hintText.textContent=this.pending?this.labels.loading:this.labels.selectHint);for(let t of ri){let n=e.querySelector(`[data-act="${t}"]`);n&&(n.disabled=this.pending)}}},ai=class{el;headerEl;nameBtn;menuEl;listEl;rowMap=new Map;entries=new Map;lists=[];activeList=``;active=null;locale;dragging=null;onOutside=e=>{this.headerEl.contains(e.target)||this.closeMenu()};constructor(e,t,n){this.callbacks=t,this.labels=n,this.el=document.createElement(`div`),this.el.className=`tcw-watchlist`,this.el.setAttribute(`aria-label`,n.title),this.headerEl=document.createElement(`div`),this.headerEl.className=`tcw-watchlist-header`,this.nameBtn=document.createElement(`button`),this.nameBtn.type=`button`,this.nameBtn.className=`tcw-watchlist-name`,this.nameBtn.setAttribute(`aria-haspopup`,`menu`),this.nameBtn.setAttribute(`aria-expanded`,`false`),this.nameBtn.title=n.lists,this.nameBtn.addEventListener(`click`,()=>this.menuEl.hidden?this.openMenu():this.closeMenu());let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-add`,r.innerHTML=O(`plus`,14),r.title=n.add,r.setAttribute(`aria-label`,n.add),r.hidden=!t.onAdd,r.addEventListener(`click`,()=>t.onAdd?.());let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-watchlist-close`,i.setAttribute(`aria-label`,n.close??n.title),i.innerHTML=O(`x`,14),i.hidden=!t.onClose,i.addEventListener(`click`,()=>t.onClose?.()),this.menuEl=document.createElement(`div`),this.menuEl.className=`tcw-dropdown tcw-watchlist-menu`,this.menuEl.setAttribute(`role`,`menu`),this.menuEl.hidden=!0,this.headerEl.append(this.nameBtn,r,i,this.menuEl),this.el.appendChild(this.headerEl),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.listEl.setAttribute(`role`,`list`),this.el.appendChild(this.listEl),e.appendChild(this.el)}get element(){return this.el}setLists(e,t){this.lists=e.map(e=>({...e,symbols:[...e.symbols]})),this.activeList=e.some(e=>e.id===t)?t:e[0]?.id??``;let n=this.shownList();this.nameBtn.textContent=n?.name??this.labels.title,this.renderRows(n?.symbols??[]),this.menuEl.hidden||this.renderMenu()}redraw(){for(let e of this.rowMap.keys())this.renderRow(e)}setLocale(e){this.locale=e;for(let e of this.rowMap.keys())this.renderRow(e)}setActive(e){this.active=e;for(let[t,n]of this.rowMap){let r=t===e;n.row.classList.toggle(`tcw-watchlist-active`,r),r?n.row.setAttribute(`aria-current`,`true`):n.row.removeAttribute(`aria-current`)}}setEntry(e,t){let n=this.entries.get(e)??{symbol:e};this.entries.set(e,{...n,...t,symbol:e}),this.renderRow(e)}destroy(){this.closeMenu(),this.el.remove(),this.rowMap.clear(),this.entries.clear()}shownList(){return this.lists.find(e=>e.id===this.activeList)}renderRows(e){for(let t of[...this.rowMap.keys()])e.includes(t)||(this.rowMap.get(t).row.remove(),this.rowMap.delete(t));for(let t of e)this.rowMap.has(t)||this.makeRow(t);if(this.listEl.replaceChildren(...e.map(e=>this.rowMap.get(e).row)),e.length===0){let e=document.createElement(`div`);e.className=`tcw-watchlist-empty`,e.textContent=this.labels.empty,this.listEl.appendChild(e)}this.active&&this.setActive(this.active)}makeRow(e){let n=document.createElement(`div`);n.className=`tcw-watchlist-row`,n.setAttribute(`role`,`listitem`),n.dataset.symbol=e,n.tabIndex=0,n.draggable=!!this.callbacks.onMove;let r=document.createElement(`div`);r.className=`tcw-watchlist-symbol`,r.textContent=oi(e);let i=document.createElement(`canvas`);i.className=`tcw-watchlist-spark`,i.width=64,i.height=22;let a=document.createElement(`div`);a.className=`tcw-watchlist-stats`;let o=document.createElement(`span`);o.className=`tcw-watchlist-price`,o.textContent=`—`;let s=document.createElement(`span`);if(s.className=`tcw-watchlist-change`,a.append(o,s),n.append(r,i,a),this.callbacks.onRemove){n.classList.add(`tcw-watchlist-removable`);let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-remove`,r.innerHTML=O(`x`,12),r.tabIndex=-1;let i=t.r(this.labels.remove,{symbol:e});r.title=i,r.setAttribute(`aria-label`,i),r.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemove?.(e)}),n.appendChild(r)}n.addEventListener(`click`,()=>this.callbacks.onSelect(e)),n.addEventListener(`keydown`,t=>this.onRowKey(t,e)),n.addEventListener(`dragstart`,t=>{this.dragging=e,t.dataTransfer?.setData(`text/plain`,e),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`),n.classList.add(`tcw-watchlist-dragging`)}),n.addEventListener(`dragend`,()=>{this.dragging=null,n.classList.remove(`tcw-watchlist-dragging`)}),n.addEventListener(`dragover`,t=>{this.dragging&&this.dragging!==e&&t.preventDefault()}),n.addEventListener(`drop`,t=>{t.preventDefault();let n=this.dragging;if(this.dragging=null,!n||n===e)return;let r=this.shownList()?.symbols??[];this.callbacks.onMove?.(n,r.indexOf(e))}),this.rowMap.set(e,{row:n,priceEl:o,changeEl:s,sparkCanvas:i}),this.renderRow(e)}onRowKey(e,t){let n=this.shownList()?.symbols??[],r=n.indexOf(t);if([`Enter`,` `,`Delete`,`Backspace`,`ArrowDown`,`ArrowUp`].includes(e.key)&&e.stopPropagation(),e.key===`Enter`||e.key===` `)e.preventDefault(),this.callbacks.onSelect(t);else if((e.key===`Delete`||e.key===`Backspace`)&&this.callbacks.onRemove){e.preventDefault();let i=n[r+1]??n[r-1];this.callbacks.onRemove(t),i&&this.rowMap.get(i)?.row.focus()}else if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let i=r+(e.key===`ArrowDown`?1:-1);if(i<0||i>=n.length)return;e.altKey?(this.callbacks.onMove?.(t,i),this.rowMap.get(t)?.row.focus()):this.rowMap.get(n[i])?.row.focus()}}renderRow(e){let t=this.rowMap.get(e),n=this.entries.get(e);if(!(!t||!n)){if(n.lastPrice!==void 0&&(t.priceEl.textContent=si(n.lastPrice,this.locale)),n.lastPrice!==void 0&&n.refPrice!==void 0&&n.refPrice!==0){let e=n.lastPrice-n.refPrice,r=e/n.refPrice*100,i=e>=0?`+`:`-`,a=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.changeEl.textContent=`${i}${a}%`,t.changeEl.className=`tcw-watchlist-change ${e>=0?`tcw-up`:`tcw-down`}`}else t.changeEl.textContent=``;n.sparkline&&n.sparkline.length>=2&&ci(t.sparkCanvas,n.sparkline,n.refPrice??n.sparkline[0])}}openMenu(){this.renderMenu(),this.menuEl.hidden=!1,this.nameBtn.setAttribute(`aria-expanded`,`true`),document.addEventListener(`mousedown`,this.onOutside)}closeMenu(){this.menuEl.hidden=!0,this.nameBtn.setAttribute(`aria-expanded`,`false`),document.removeEventListener(`mousedown`,this.onOutside)}renderMenu(){let e=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-dropdown-item`,n.setAttribute(`role`,`menuitem`),n.textContent=e,n.addEventListener(`click`,t),n},n=this.lists.map(t=>{let n=e(``,()=>{this.closeMenu(),this.callbacks.onPickList?.(t.id)});n.dataset.list=t.id,n.classList.toggle(`tcw-active`,t.id===this.activeList);let r=document.createElement(`span`);r.textContent=t.name;let i=document.createElement(`span`);return i.className=`tcw-watchlist-count`,i.textContent=String(t.symbols.length),n.append(r,i),n}),r=document.createElement(`div`);if(r.className=`tcw-dropdown-divider`,n.push(r),this.callbacks.onCreateList){let t=e(this.labels.newList,()=>this.editName(``,e=>this.callbacks.onCreateList?.(e)));t.dataset.action=`new`,n.push(t)}let i=this.shownList();if(i&&this.callbacks.onRenameList){let t=e(this.labels.rename,()=>this.editName(i.name,e=>this.callbacks.onRenameList?.(i.id,e)));t.dataset.action=`rename`,n.push(t)}if(i&&this.callbacks.onDeleteList&&this.lists.length>1){let r=!1,a=e(this.labels.deleteList,()=>{if(!r){r=!0,a.textContent=t.r(this.labels.confirmDelete,{name:i.name}),a.classList.add(`tcw-danger`);return}this.closeMenu(),this.callbacks.onDeleteList?.(i.id)});a.dataset.action=`delete`,n.push(a)}this.menuEl.replaceChildren(...n)}editName(e,t){this.closeMenu();let n=document.createElement(`input`);n.className=`tcw-watchlist-input`,n.type=`text`,n.maxLength=60,n.value=e,n.placeholder=this.labels.listName,n.setAttribute(`aria-label`,this.labels.listName),this.nameBtn.hidden=!0,this.headerEl.insertBefore(n,this.nameBtn);let r=!1,i=i=>{if(r)return;r=!0;let a=n.value.trim();n.remove(),this.nameBtn.hidden=!1,i&&a&&a!==e&&t(a),this.nameBtn.focus()};n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),i(!0)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),i(!1))}),n.addEventListener(`blur`,()=>i(!1)),n.focus()}};function oi(e){for(let t of[`USDT`,`USD`,`BTC`,`ETH`,`EUR`])if(e.length>t.length&&e.endsWith(t))return e.slice(0,-t.length)+`/`+t;return e}function si(e,t){if(e===0)return`0`;let n=Math.abs(e);return n>=1e3?e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2}):n>=1?e.toLocaleString(t,{minimumFractionDigits:4,maximumFractionDigits:4}):Number(e.toPrecision(4)).toLocaleString(t,{maximumFractionDigits:10})}function ci(e,t,n){let r=e.getContext(`2d`);if(!r)return;let i=window.devicePixelRatio||1;e.width!==e.clientWidth*i&&(e.width=(e.clientWidth||64)*i,e.height=(e.clientHeight||22)*i);let a=e.width,o=e.height,s=1/0,c=-1/0;for(let e of t)e<s&&(s=e),e>c&&(c=e);let l=Math.max(c-s,1e-9),u=t[t.length-1]>=n?`#1fa874`:`#e8505b`;r.clearRect(0,0,a,o),r.lineWidth=1.4*i,r.strokeStyle=u,r.beginPath();let d=a/(t.length-1);for(let e=0;e<t.length;e++){let n=e*d,i=o-(t[e]-s)/l*(o-4)-2;e===0?r.moveTo(n,i):r.lineTo(n,i)}r.stroke()}var li=50,ui=500,di=60,fi=e=>typeof e==`string`&&e.trim().slice(0,di)||null;function pi(e){let t=[];for(let n of e){let e=qt(n);if(e&&!t.includes(e)&&t.push(e),t.length===ui)break}return t}function mi(e){if(!e||typeof e!=`object`)return null;let t=e;if(!Array.isArray(t.lists))return null;let n=[];for(let e of t.lists){if(n.length===li)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=64?t.id:null,i=fi(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?pi(t.symbols):[]})}return n.length===0?null:{lists:n,active:typeof t.active==`string`&&n.some(e=>e.id===t.active)?t.active:n[0].id}}var hi=e=>({...e,symbols:[...e.symbols]}),gi=class{lists;active;listeners=new Set;storage;storageKey;constructor(e){this.storage=e.storage??null,this.storageKey=e.storageKey??`tcw:watchlists`;let t=this.load(),n=e.lists?mi({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:fi(e.defaultName)??`Watchlist`,symbols:pi(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map(hi)}getActive(){return hi(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=mi({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=fi(e);if(!t||this.lists.length>=li)return null;let n=this.lists.length+1;for(;this.lists.some(e=>e.id===`list-${n}`);)n++;let r={id:`list-${n}`,name:t,symbols:[]};return this.lists=[...this.lists,r],this.active=r.id,this.changed(),hi(r)}rename(e,t){let n=fi(t);n&&this.update(e,e=>({...e,name:n}))}remove(e){this.lists.length<=1||!this.lists.some(t=>t.id===e)||(this.lists=this.lists.filter(t=>t.id!==e),this.active===e&&(this.active=this.lists[0].id),this.changed())}add(e,t=this.active){let n=qt(e),r=this.lists.find(e=>e.id===t);return!n||!r||r.symbols.includes(n)||r.symbols.length>=ui?!1:(this.update(t,e=>({...e,symbols:[...e.symbols,n]})),!0)}removeSymbol(e,t=this.active){this.lists.find(e=>e.id===t)?.symbols.includes(e)&&this.update(t,t=>({...t,symbols:t.symbols.filter(t=>t!==e)}))}move(e,t,n=this.active){let r=this.lists.find(e=>e.id===n);if(!r)return;let i=r.symbols.indexOf(e);if(i<0)return;let a=r.symbols.filter(t=>t!==e),o=Math.max(0,Math.min(Math.round(t),a.length));o!==i&&this.update(n,t=>({...t,symbols:[...a.slice(0,o),e,...a.slice(o)]}))}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}activeList(){return this.lists.find(e=>e.id===this.active)??this.lists[0]}update(e,t){this.lists=this.lists.map(n=>n.id===e?t(n):n),this.changed()}changed(){this.save();for(let e of this.listeners)e()}load(){if(!this.storage)return null;try{let e=this.storage.getItem(this.storageKey);return e?mi(JSON.parse(e)):null}catch{return null}}save(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify({lists:this.lists,active:this.active}))}catch{}}},_i=class{el;bodyEl;newsEl;shown=!1;constructor(e,n=t.t,r={}){this.t=n,this.callbacks=r,this.el=document.createElement(`div`),this.el.className=`tcw-syminfo`,D(this.el,`symbolInfo`),this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,n(`symbolInfo.title`)),this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-syminfo-header`;let a=document.createElement(`span`);a.textContent=n(`symbolInfo.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-syminfo-close`,o.setAttribute(`aria-label`,n(`common.close`)),o.innerHTML=O(`x`,14),o.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),i.append(a,o),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-syminfo-body`,this.newsEl=document.createElement(`div`),this.newsEl.className=`tcw-syminfo-news`,this.newsEl.hidden=!0,this.el.append(i,this.bodyEl,this.newsEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.shown}toggle(){this.shown?this.close():this.open()}open(){this.shown||(this.shown=!0,this.el.hidden=!1,this.callbacks.onToggle?.(!0))}close(){this.shown&&(this.shown=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}render(e){let t=document.createElement(`div`);t.className=`tcw-syminfo-head`,t.append(H(`div`,`tcw-syminfo-symbol`,e.symbol)),e.description&&t.append(H(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(H(`div`,`tcw-syminfo-meta`,e.meta));let n=document.createElement(`div`);if(n.className=`tcw-syminfo-quote`,e.price&&n.append(H(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=H(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),n.append(t)}let r=H(`div`,`tcw-syminfo-status`,e.status.text);r.dataset.state=e.status.state;let i=document.createElement(`dl`);i.className=`tcw-syminfo-stats`;for(let t of e.stats){let e=document.createElement(`div`);e.className=`tcw-syminfo-stat`,e.append(H(`dt`,``,t.label),H(`dd`,``,t.value)),i.append(e)}this.bodyEl.replaceChildren(t,n,r,i)}renderNews(e){if(this.newsEl.hidden=e.kind===`none`,e.kind===`none`){this.newsEl.replaceChildren();return}let t=H(`div`,`tcw-syminfo-news-title`,this.t(`symbolInfo.news`));if(e.kind===`loading`||e.kind===`failed`||e.items.length===0){let t=e.kind===`loading`?`symbolInfo.loading`:e.kind===`failed`?`symbolInfo.newsFailed`:`symbolInfo.noNews`;this.newsEl.replaceChildren(H(`div`,`tcw-syminfo-news-note`,this.t(t)));return}let n=document.createElement(`ul`);n.className=`tcw-syminfo-news-list`;for(let t of e.items){let e=document.createElement(`li`);if(e.className=`tcw-syminfo-news-item`,t.url){let n=document.createElement(`a`);n.href=t.url,n.target=`_blank`,n.rel=`noopener noreferrer`,n.textContent=t.title,e.append(n)}else e.append(H(`span`,``,t.title));t.meta&&e.append(H(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function H(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var vi=10,yi=5*6e4,bi=864e5,xi=2;function Si(e){let{info:r,quote:i,t:a,textLocale:o}=e,s=(0,n.symbolTimeZone)(r),c=wi(e.bars,s),l=e.formatPrice,u=i?.last??c?.close,d=i?.prevClose??c?.prevClose,f=i?.change??(u!==void 0&&d!==void 0?u-d:void 0),p=u!==void 0&&f!==void 0?u-f:void 0,m=i?.changePercent??(f!==void 0&&p?f/p*100:void 0),h=(0,n.marketStatus)(r,e.now),g=a(h.state===`open`?`symbolInfo.open`:h.state===`closed`?`symbolInfo.closed`:`symbolInfo.always`);if(h.state!==`always`&&h.next!==null){let n=Ti(h.next-e.now,o);g+=` · ${t.r(a(h.state===`open`?`symbolInfo.closesIn`:`symbolInfo.opensIn`),{when:n})}`}let ee=[],_=(e,t)=>{t&&ee.push({label:e,value:t})},v=e=>e===void 0?void 0:l(e);_(a(`dataWindow.open`),v(i?.open??c?.open)),_(a(`dataWindow.high`),v(i?.high??c?.high)),_(a(`dataWindow.low`),v(i?.low??c?.low)),_(a(`symbolInfo.prevClose`),v(d));let y=i?.volume??c?.volume;_(a(`dataWindow.volume`),y===void 0?void 0:Di(y,e.numberLocale)),_(a(`symbolInfo.bid`),v(i?.bid)),_(a(`symbolInfo.ask`),v(i?.ask)),_(a(`symbolInfo.tick`),r?.minTick===void 0?void 0:String(r.minTick)),_(a(`symbolInfo.currency`),r?.currency),_(a(`symbolInfo.timezone`),s),_(a(`symbolInfo.hours`),Oi(r,o));let b=(f??0)>=0?`+`:`-`,x=e.names===void 0?r:e.names;return{symbol:e.symbol,description:x?.description,meta:[x?.exchange,x?.type].filter(Boolean).join(` · `)||void 0,price:u===void 0?void 0:l(u),change:f===void 0?void 0:{text:`${b}${l(Math.abs(f))}${m===void 0?``:` (${b}${Ei(Math.abs(m),xi,e.numberLocale)}%)`}`,up:f>=0},status:{state:h.state,text:g},stats:ee}}var Ci=class{request=0;cache=new Map;load(e,t,r,i,a){let o=++this.request;if(!t){r({kind:`none`});return}let s=e=>{let t=Date.now();r({kind:`items`,items:e.map(e=>({title:e.title,url:e.url,meta:[e.source,Ti(e.time-t,i)].filter(Boolean).join(` · `)}))})},c=this.cache.get(e);if(c&&Date.now()-c.at<yi){s(c.items);return}r({kind:`loading`}),Promise.resolve().then(()=>t(e,vi)).then(t=>{if(o!==this.request||a())return;let r=(0,n.readNews)(t,vi);this.cache.set(e,{at:Date.now(),items:r}),s(r)}).catch(()=>{o===this.request&&!a()&&r({kind:`failed`})})}};function wi(e,t){if(e.length===0)return null;let r=t&&(0,n.isValidTimeZone)(t)?t:null,i=(0,n.barTimeUnit)(e),a=e=>{let t=e*i;return Math.floor((t+(r?(0,n.zoneOffsetMinutes)(r,t)*6e4:0))/bi)},o=e[e.length-1],s=a(o.time),c=e.length-1;for(;c>0&&a(e[c-1].time)===s;)c--;let l=-1/0,u=1/0,d=0;for(let t=c;t<e.length;t++)l=Math.max(l,e[t].high),u=Math.min(u,e[t].low),d+=e[t].volume??0;return{open:e[c].open,high:l,low:u,close:o.close,volume:d,prevClose:c>0?e[c-1].close:void 0}}function Ti(e,t){let n=e/6e4,[r,i]=Math.abs(n)<60?[Math.round(n)||Math.sign(n)||1,`minute`]:Math.abs(n)<1440?[Math.round(n/60),`hour`]:[Math.round(n/1440),`day`];try{return new Intl.RelativeTimeFormat(t,{numeric:`auto`}).format(r,i)}catch{return new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}).format(r,i)}}function Ei(e,t,r){try{return(0,n.formatPrice)(e,t,r)}catch{return e.toFixed(t)}}function Di(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function Oi(e,t){let n=e?.sessions??[];if(n.length===0)return;let r;try{let e=new Intl.DateTimeFormat(t,{weekday:`short`,timeZone:`UTC`});r=Array.from({length:7},(t,n)=>e.format(Date.UTC(1970,0,4+n)))}catch{r=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]}let i=e=>{let t=[...new Set((e??[]).filter(e=>Number.isInteger(e)&&e>=0&&e<=6))].sort((e,t)=>e-t);return t.length===0||t.length===7?``:t.every((e,n)=>n===0||e===t[n-1]+1)&&t.length>2?`${r[t[0]]}–${r[t[t.length-1]]}`:t.map(e=>r[e]).join(`, `)};return n.map(e=>[`${e.start}–${e.end}`,i(e.days)].filter(Boolean).join(` `)).join(`, `)}var ki={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function Ai(){let e={};for(let[t,n]of Object.entries(ki))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var ji=300,Mi=80,Ni=n.PHI**-3,Pi=80,Fi=class{el;holdTimer=null;repeatTimer=null;pressed=!1;keyboardFocus=!1;onMove=e=>{if(e.pointerType!==`touch`&&!(this.holdTimer||this.repeatTimer)){if(!this.nearBottom(e)&&!this.keyboardFocus){this.el.classList.remove(`tcw-nav-shown`),this.stopHold();return}this.el.classList.contains(`tcw-nav-shown`)||this.place(),this.el.classList.add(`tcw-nav-shown`)}};onLeave=()=>{this.el.classList.remove(`tcw-nav-shown`),this.stopHold()};constructor(e,n,r=t.t){this.host=e,this.actions=n,this.el=document.createElement(`div`),this.el.className=`tcw-nav`,D(this.el,`navigation`),this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,r(`nav.label`));let i=[[`zoomOut`,`minus`,r(`nav.zoomOut`),`navigation.zoom`],[`zoomIn`,`plus`,r(`nav.zoomIn`),`navigation.zoom`],[`scrollLeft`,`chevronLeft`,r(`nav.scrollLeft`),`navigation.scroll`],[`scrollRight`,`chevronRight`,r(`nav.scrollRight`),`navigation.scroll`],[`reset`,`reset`,r(`nav.reset`),`navigation.reset`]];for(let[e,t,r,a]of i){let i=document.createElement(`button`);if(i.type=`button`,i.className=`tcw-nav-btn`,i.dataset.nav=e,D(i,a),i.title=r,i.setAttribute(`aria-label`,r),i.innerHTML=O(t,16),e===`scrollLeft`||e===`scrollRight`){let t=e===`scrollRight`?1:-1;i.addEventListener(`pointerdown`,e=>{if(e.button===0){e.preventDefault();try{i.setPointerCapture(e.pointerId)}catch{}this.startHold(t)}});for(let e of[`pointerup`,`pointercancel`,`pointerleave`])i.addEventListener(e,()=>this.stopHold());i.addEventListener(`click`,e=>{e.detail===0&&n.scroll(t)})}else i.addEventListener(`click`,()=>{e===`zoomIn`?n.zoomIn():e===`zoomOut`?n.zoomOut():n.reset()});this.el.appendChild(i)}for(let e of[`dblclick`,`contextmenu`,`pointerdown`,`mousedown`])this.el.addEventListener(e,e=>e.stopPropagation());this.el.addEventListener(`pointerdown`,()=>{this.pressed=!0},{capture:!0}),this.el.addEventListener(`pointerup`,()=>{this.pressed=!1},{capture:!0}),this.el.addEventListener(`focusin`,()=>{this.keyboardFocus=!this.pressed,this.pressed=!1,this.place(),this.el.classList.add(`tcw-nav-shown`)}),this.el.addEventListener(`focusout`,e=>{this.el.contains(e.relatedTarget)||(this.keyboardFocus=!1,this.el.classList.remove(`tcw-nav-shown`))}),e.appendChild(this.el),e.addEventListener(`pointermove`,this.onMove),e.addEventListener(`pointerleave`,this.onLeave)}destroy(){this.stopHold(),this.host.removeEventListener(`pointermove`,this.onMove),this.host.removeEventListener(`pointerleave`,this.onLeave),this.el.remove()}nearBottom(e){let t=this.actions.plotRect(),n=this.host.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=Math.max(Pi,t.height*Ni);return r>=t.x&&r<=t.x+t.width&&i<=t.y+t.height&&i>=t.y+t.height-a}place(){let e=this.actions.plotRect();this.el.style.left=`${Math.round(e.x+e.width/2)}px`,this.el.style.top=`${Math.round(e.y+e.height)}px`}startHold(e){this.stopHold(),this.actions.scroll(e),this.holdTimer=setTimeout(()=>{this.repeatTimer=setInterval(()=>this.actions.scroll(e),Mi)},ji)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function Ii(e,n,r,i=!1){let a=e.label??n(`alerts.source.price`),o=Vi.get(e.condition),s=o?n(o):e.condition;if(Ri.includes(e.condition))return`${a} ${s} ${t.r(n(`alerts.moveSummary`),{percent:e.percent??0,bars:e.bars??0})}`;if(e.target)return`${a} ${s} ${e.targetLabel??e.target}`;let c=e.channel&&e.channel!==`price`,l=Number.isFinite(e.price)?c?Ui(e.price):r(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:i?`${a} `:``}${s} ${l}`}var Li=[{value:`crossing`,key:`alerts.condition.crossing`},{value:`crossingUp`,key:`alerts.condition.crossingUp`},{value:`crossingDown`,key:`alerts.condition.crossingDown`},{value:`greaterThan`,key:`alerts.condition.greaterThan`},{value:`lessThan`,key:`alerts.condition.lessThan`},{value:`movesUp`,key:`alerts.condition.movesUp`},{value:`movesDown`,key:`alerts.condition.movesDown`}],Ri=[`movesUp`,`movesDown`],zi={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},Bi=``,Vi=new Map(Li.map(e=>[e.value,e.key]));function Hi(e){return Math.round(e*1e6)/1e6}function Ui(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var Wi=class{el;listEl;priceInput;conditionSelect;sourceSelect;targetSelect;percentInput;barsInput;levelRow;moveRow;closeCheck;expirySelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources;constructor(e,n,i=t.t){this.t=i,this.callbacks=n,this.sources=[{channel:`price`,label:this.t(`alerts.source.price`)}],this.el=document.createElement(`div`),this.el.className=`tcw-alerts-panel`,D(this.el,`alerts`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-alerts-header`;let o=document.createElement(`span`);o.textContent=this.t(`alerts.title`);let s=document.createElement(`button`);s.className=`tcw-alerts-close`,s.type=`button`,s.setAttribute(`aria-label`,this.t(`alerts.close`)),s.innerHTML=O(`x`,14),s.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a);let c=document.createElement(`form`);c.className=`tcw-alerts-form`,c.noValidate=!0,this.sourceSelect=document.createElement(`select`),this.sourceSelect.className=`tcw-alerts-source`,this.sourceSelect.setAttribute(`aria-label`,this.t(`alerts.source`)),this.sourceSelect.addEventListener(`change`,()=>{this.renderTargets(),this.prefillPrice()}),this.conditionSelect=document.createElement(`select`),this.conditionSelect.className=`tcw-alerts-condition`,this.conditionSelect.setAttribute(`aria-label`,this.t(`alerts.conditionLabel`));for(let e of Li){let t=document.createElement(`option`);t.value=e.value,t.textContent=this.t(e.key),this.conditionSelect.appendChild(t)}this.conditionSelect.addEventListener(`change`,()=>this.showFields()),this.levelRow=document.createElement(`div`),this.levelRow.className=`tcw-alerts-row-fields`,this.targetSelect=document.createElement(`select`),this.targetSelect.className=`tcw-alerts-target`,this.targetSelect.setAttribute(`aria-label`,this.t(`alerts.compareWith`)),this.targetSelect.addEventListener(`change`,()=>this.showFields()),this.priceInput=document.createElement(`input`),this.priceInput.type=`number`,this.priceInput.step=`any`,this.priceInput.placeholder=this.t(`alerts.value`),this.priceInput.setAttribute(`aria-label`,this.t(`alerts.value`)),this.priceInput.className=`tcw-alerts-price`,this.levelRow.append(this.targetSelect,this.priceInput),this.moveRow=document.createElement(`div`),this.moveRow.className=`tcw-alerts-row-fields`,this.percentInput=this.numberField(`tcw-alerts-percent`,this.t(`alerts.percent`),`1`,`0.01`),this.barsInput=this.numberField(`tcw-alerts-bars`,this.t(`alerts.bars`),`10`,`1`),this.barsInput.min=String(r.MIN_ALERT_BARS),this.barsInput.max=String(r.MAX_ALERT_BARS),this.moveRow.append(this.percentInput,this.barsInput);let l=document.createElement(`div`);l.className=`tcw-alerts-row-fields tcw-alerts-options`;let u=document.createElement(`label`);u.className=`tcw-alerts-check`,this.closeCheck=document.createElement(`input`),this.closeCheck.type=`checkbox`,u.append(this.closeCheck,document.createTextNode(this.t(`alerts.onBarClose`))),this.expirySelect=document.createElement(`select`),this.expirySelect.className=`tcw-alerts-expiry`,this.expirySelect.setAttribute(`aria-label`,this.t(`alerts.expires`));for(let e of[`never`,`hour`,`day`,`week`,`month`]){let t=document.createElement(`option`);t.value=e,t.textContent=this.t(`alerts.expires.${e}`),this.expirySelect.appendChild(t)}l.append(u,this.expirySelect),this.messageInput=document.createElement(`input`),this.messageInput.type=`text`,this.messageInput.placeholder=this.t(`alerts.note`),this.messageInput.setAttribute(`aria-label`,this.t(`alerts.note`)),this.messageInput.className=`tcw-alerts-message`;let d=document.createElement(`button`);d.type=`submit`,d.className=`tcw-alerts-add`,d.innerHTML=`${O(`plus`,14)}<span>${k(this.t(`alerts.add`))}</span>`,c.append(this.sourceSelect,this.conditionSelect,this.levelRow,this.moveRow,l,this.messageInput,d),c.addEventListener(`submit`,e=>{e.preventDefault(),this.submitForm()}),this.el.appendChild(c),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-alerts-list`,this.el.appendChild(this.listEl),this.emptyEl=document.createElement(`div`),this.emptyEl.className=`tcw-alerts-empty`,this.emptyEl.textContent=this.t(`alerts.empty`),this.listEl.appendChild(this.emptyEl),this.renderSources(),this.showFields(),e.appendChild(this.el)}numberField(e,t,n,r){let i=document.createElement(`input`);return i.type=`number`,i.step=r,i.min=`0`,i.value=n,i.className=e,i.placeholder=t,i.setAttribute(`aria-label`,t),i}showFields(){let e=Ri.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==Bi}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=Bi,n.textContent=this.t(`alerts.compare.value`),this.targetSelect.appendChild(n);for(let e of this.sources){if(e.channel===t)continue;let n=document.createElement(`option`);n.value=e.channel,n.textContent=e.label,this.targetSelect.appendChild(n)}this.targetSelect.value=[...this.targetSelect.options].some(t=>t.value===e)?e:Bi,this.showFields()}setSources(e){this.sources=e.length>0?e:[{channel:`price`,label:this.t(`alerts.source.price`)}],this.renderSources()}renderSources(){let e=this.sourceSelect.value||`price`;this.sourceSelect.replaceChildren();for(let e of this.sources){let t=document.createElement(`option`);t.value=e.channel,t.textContent=e.label,this.sourceSelect.appendChild(t)}this.sourceSelect.value=this.sources.some(t=>t.channel===e)?e:`price`,this.renderTargets()}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.priceInput.value===``&&this.prefillPrice()}prefillPrice(){let e=this.callbacks.getChannelValue(this.sourceSelect.value||`price`);this.priceInput.value=e===null?``:String(Hi(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,this.renderList()}destroy(){this.el.remove()}submitForm(){let e=this.conditionSelect.value,t=this.messageInput.value.trim()||void 0,n=this.sourceSelect.value||`price`,i=this.sources.find(e=>e.channel===n)?.label??this.t(`alerts.source.price`),a={},o=NaN;if(Ri.includes(e)){a.percent=Number(this.percentInput.value),a.bars=Number(this.barsInput.value);let e=Number.isInteger(a.bars)&&a.bars>=r.MIN_ALERT_BARS&&a.bars<=r.MAX_ALERT_BARS;if(!(a.percent>0)||!e){this.markInvalid(a.percent>0?this.barsInput:this.percentInput);return}}else if(this.targetSelect.value!==Bi)a.target=this.targetSelect.value;else if(o=Number(this.priceInput.value),this.priceInput.value.trim()===``||!Number.isFinite(o)){this.markInvalid(this.priceInput);return}this.closeCheck.checked&&(a.onBarClose=!0);let s=zi[this.expirySelect.value];s&&(a.expiresAt=(this.callbacks.now??Date.now)()+s),this.callbacks.onAdd({price:o,condition:e,message:t,channel:n,label:i,options:a})!==!1&&(this.messageInput.value=``,this.prefillPrice())}markInvalid(e){e.setAttribute(`aria-invalid`,`true`),e.focus(),e.addEventListener(`input`,()=>e.removeAttribute(`aria-invalid`),{once:!0})}describe(e){return Ii(e,this.t,this.callbacks.formatPrice)}renderList(){if(this.listEl.replaceChildren(),this.alerts.length===0){this.listEl.appendChild(this.emptyEl);return}for(let e of[...this.alerts].reverse()){let n=document.createElement(`div`);n.className=`tcw-alerts-row`+(e.triggered?` tcw-alerts-triggered`:``)+(e.expired?` tcw-alerts-expired`:``);let r=document.createElement(`div`);r.className=`tcw-alerts-info`;let i=document.createElement(`div`);i.className=`tcw-alerts-row-main`,i.textContent=this.describe(e),r.appendChild(i);let a=[];if(e.onBarClose&&a.push(this.t(`alerts.onClose`)),e.expiresAt!==void 0&&!e.expired){let n=this.callbacks.formatTime?.(e.expiresAt)??new Date(e.expiresAt).toISOString();a.push(t.r(this.t(`alerts.until`),{time:n}))}if(a.length>0){let e=document.createElement(`div`);e.className=`tcw-alerts-row-meta`,e.textContent=a.join(` · `),r.appendChild(e)}if(e.message){let t=document.createElement(`div`);t.className=`tcw-alerts-row-note`,t.textContent=e.message,r.appendChild(t)}if(e.triggered||e.expired){let t=document.createElement(`span`);t.className=`tcw-alerts-badge`,t.textContent=this.t(e.expired?`alerts.expired`:`alerts.triggered`),i.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-alerts-del`,o.setAttribute(`aria-label`,this.t(`alerts.delete`)),o.innerHTML=O(`trash`,14),o.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),n.appendChild(r),n.appendChild(o),this.listEl.appendChild(n)}}};function Gi(e){return Object.prototype.hasOwnProperty.call(t.c,e)}function Ki(e,t){let n=`indicatorInput.${e}`;return Gi(n)?t(n):null}function qi(e,t,n){let r=`indicatorInput.${e}.${t}`;return Gi(r)?n(r):null}function Ji(t,n){let{defaultConfig:r,shortName:i,inputs:a}=t.descriptor,o=Object.entries(a??{}).flatMap(([e,i])=>{let a=t.params[e];return!i.options||typeof a!=`string`&&typeof a!=`number`||a===r[e]?[]:qi(e,a,n)??[]});return[e.O(t.id,t.params,r,i),...o].join(` `)}var Yi=`print`,Xi=3,Zi=10,Qi=[[3400,1/2],[2560,1/3],[1800,1/6]],$i=.75,ea=2;function ta(e){let t=Qi.find(([t])=>e>=t);return t?n.PHI**t[1]:1}function na(e,t){if(t===1)return e;let n=e.sizes,r=e=>Math.round(e*t);return{...e,sizes:{toolbar:r(n.toolbar),control:r(n.control),controlSmall:r(n.controlSmall),icon:r(n.icon),sidebar:r(n.sidebar),menuItem:r(n.menuItem)},font:{...e.font,size:r(e.font.size)}}}function ra(e,t){return Math.max(Zi,(0,n.phiStep)(e,t,Xi))}var ia=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,aa=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,oa=n.SANS_FONT_FAMILY,sa=`'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`,ca=`Tahoma, Verdana, 'Segoe UI', 'DejaVu Sans', sans-serif`,la={print:{radius:{xs:1,sm:2,md:3,lg:5,xl:8},components:{tag:2,toolbar:0,sidebar:0},sizes:{toolbar:42,control:26,controlSmall:20,icon:16,sidebar:42,menuItem:33},density:{compact:{toolbar:33,control:20,controlSmall:20,icon:16,sidebar:33,menuItem:26},spacious:{toolbar:53,control:33,controlSmall:26,icon:20,sidebar:53,menuItem:42}},font:{family:oa,mono:sa,size:13,weight:400,strongWeight:600,labelCase:`uppercase`,labelTracking:.06},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border), var(--tcw-shadow-md)`,dialog:`0 0 0 1px var(--tcw-border), var(--tcw-shadow-lg)`,tooltip:`var(--tcw-shadow-sm)`},blur:0,active:`solid`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:2},studio:{radius:{xs:3,sm:5,md:7,lg:11,xl:16},components:{toolbar:0,sidebar:0},sizes:{toolbar:46,control:30,controlSmall:24,icon:18,sidebar:48,menuItem:30},font:{family:`'Manrope', 'Inter', ${ia}`,mono:aa,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`var(--tcw-shadow-lg)`,dialog:`var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-md)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`segmented`,tagRadius:4},terminal:{radius:{xs:1,sm:2,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:36,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${ia}`,mono:`'IBM Plex Mono', ui-monospace, monospace`,size:12,weight:500,strongWeight:600,labelCase:`uppercase`,labelTracking:.08},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-lg)`,tooltip:`none`},blur:0,active:`underline`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0},capsule:{radius:{xs:6,sm:10,md:999,lg:18,xl:24},components:{tooltip:10,toolbar:999,sidebar:999,toast:999,tag:999},sizes:{toolbar:44,control:32,controlSmall:26,icon:18,sidebar:48,menuItem:34},font:{family:`'Sora', 'Manrope', ${ia}`,mono:aa,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,dialog:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-lg)`},blur:16,active:`solid`,toolbar:`floating`,sidebar:`floating`,intervals:`segmented`,tagRadius:999},desk:{radius:{xs:0,sm:1,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:34,control:24,controlSmall:20,icon:16,sidebar:36,menuItem:24},font:{family:ca,mono:ca,size:12,weight:400,strongWeight:700,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-sm)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-md)`,tooltip:`0 0 0 1px var(--tcw-border)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0}},ua={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:54,menuItem:34}};function da(e,t){return{control:e.md,input:e.md,menu:e.lg,dialog:e.xl,panel:e.lg,tooltip:e.sm,tag:e.sm,toast:e.lg,toolbar:0,sidebar:0,...t}}var fa=Object.freeze(Object.fromEntries(Object.keys(la).map(e=>[e,ma(pa(e))])));function pa(e){let{density:t,...n}=la[e];return{...n,preset:e,density:`comfortable`,scale:`auto`,radius:{...n.radius},components:da(n.radius,n.components),sizes:{...n.sizes},font:{...n.font},borders:{...n.borders},shadows:{...n.shadows}}}function ma(e){for(let t of Object.values(e))t&&typeof t==`object`&&ma(t);return Object.freeze(e)}var ha=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(la,e),U=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,ga=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&_a(e);function _a(e){let t=0,n=``;for(let r of e)if(n)r===n&&(n=``);else if(r===`"`||r===`'`)n=r;else if(r===`(`)t++;else if(r===`)`&&--t<0)return!1;return t===0&&!n}var va=(e,t)=>typeof e==`string`&&t.includes(e);function ya(e,t,n){let r={...e};if(!t||typeof t!=`object`)return r;for(let i of Object.keys(e)){let e=t[i];e!==void 0&&n(i,e)&&(r[i]=e)}return r}function W(e){let t=typeof e==`string`?{preset:e}:e??{},n=ha(t.preset)?t.preset:Yi,r=la[n],i=ya(r.radius,t.radius,(e,t)=>U(t,0,999)),a=va(t.density,[`compact`,`comfortable`,`spacious`,`airy`])?t.density:`comfortable`,o=a===`airy`?`spacious`:a,s=ya(o===`compact`||o===`spacious`?(r.density??ua)[o]:r.sizes,t.sizes,(e,t)=>e===`icon`?U(t,10,32):U(t,16,80)),c=ya(r.font,t.font,(e,t)=>e===`family`||e===`mono`?ga(t):e===`size`?U(t,11,20):e===`weight`||e===`strongWeight`?U(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:U(t,0,.5)),l=a===`airy`&&t.font?.mono===void 0?{...c,mono:c.family}:c;return{preset:n,density:a,radius:i,components:ya(da(i,r.components),t.components,(e,t)=>U(t,0,999)),sizes:s,font:l,borders:ya(r.borders,t.borders,(e,t)=>e===`width`?U(t,0,4):typeof t==`boolean`),shadows:ya(r.shadows,t.shadows,(e,t)=>ga(t)),blur:U(t.blur,0,40)?t.blur:r.blur,active:va(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:va(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:va(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:va(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:U(t.tagRadius,0,999)?t.tagRadius:r.tagRadius,scale:typeof t.scale==`number`&&Number.isFinite(t.scale)&&t.scale>=$i&&t.scale<=ea?t.scale:`auto`}}function ba(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font;return{"--tcw-radius-xs":t(n.xs),"--tcw-radius-sm":t(n.sm),"--tcw-radius":t(n.md),"--tcw-radius-lg":t(n.lg),"--tcw-radius-xl":t(n.xl),"--tcw-control-radius":t(r.control),"--tcw-input-radius":t(r.input),"--tcw-menu-radius":t(r.menu),"--tcw-dialog-radius":t(r.dialog),"--tcw-panel-radius":t(r.panel),"--tcw-tooltip-radius":t(r.tooltip),"--tcw-tag-radius":t(r.tag),"--tcw-toast-radius":t(r.toast),"--tcw-toolbar-radius":t(r.toolbar),"--tcw-sidebar-radius":t(r.sidebar),"--tcw-toolbar-h":t(i.toolbar),"--tcw-control-h":t(i.control),"--tcw-control-h-sm":t(i.controlSmall),"--tcw-icon":t(i.icon),"--tcw-sidebar-w":t(i.sidebar),"--tcw-menu-item-h":t(i.menuItem),"--tcw-font":a.family,"--tcw-font-mono":a.mono,"--tcw-font-size":t(a.size),"--tcw-font-size-sm":t(ra(a.size,-1)),"--tcw-font-size-xs":t(ra(a.size,-2)),"--tcw-font-size-lg":t(ra(a.size,1)),"--tcw-font-size-xl":t(ra(a.size,2)),"--tcw-font-size-display":t(ra(a.size,3)),"--tcw-weight":String(a.weight),"--tcw-weight-strong":String(a.strongWeight),"--tcw-label-case":a.labelCase,"--tcw-label-tracking":`${a.labelTracking}em`,"--tcw-border-w":t(e.borders.width),"--tcw-sep-w":e.borders.separators?t(Math.max(1,e.borders.width)):`0px`,"--tcw-menu-shadow":e.shadows.menu,"--tcw-dialog-shadow":e.shadows.dialog,"--tcw-tooltip-shadow":e.shadows.tooltip,"--tcw-blur":t(e.blur),"--tcw-surface-opacity":e.blur>0?`82%`:`100%`}}function xa(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(ba(t)))r?e.style.setProperty(n,i):e.style.removeProperty(n);e.dataset.tcwUi=t.preset,e.dataset.tcwActive=t.active,e.dataset.tcwToolbar=t.toolbar,e.dataset.tcwSidebar=t.sidebar,e.dataset.tcwIntervals=t.intervals,e.dataset.tcwSeparators=t.borders.separators?`on`:`off`}var Sa=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;drawingIndex=new Map;loose=[];pending=null;renaming=!1;dragging=null;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,D(this.el,`objectTree`),this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-tree-header`;let a=document.createElement(`span`);a.textContent=this.t(`objects.title`);let o=document.createElement(`button`);if(o.type=`button`,o.className=`tcw-tree-close`,o.setAttribute(`aria-label`,this.t(`objects.close`)),o.innerHTML=O(`x`,14),o.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),i.appendChild(a),i.appendChild(o),this.el.appendChild(i),this.indicatorsEl=this.makeSection(this.t(`objects.indicators`)),this.drawingsEl=this.makeSection(this.t(`objects.drawings`)),this.callbacks.onAddCompare){this.compareEl=this.makeSection(this.t(`objects.compare`),{label:this.t(`objects.addCompare`),run:()=>this.callbacks.onAddCompare?.()});let e=this.compareEl.parentElement?.querySelector(`.tcw-tree-add`);e&&D(e,`compare`)}e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.pending=null,this.dragging?.stop(),this.el.remove()}setObjects(e,t,n=[]){this.renderIndicators(e),this.renderDrawings(t),this.renderCompares(n)}makeSection(e,t){let n=document.createElement(`div`);n.className=`tcw-tree-section`;let r=document.createElement(`div`);r.className=`tcw-tree-section-head`;let i=document.createElement(`span`);if(i.textContent=e,r.appendChild(i),t){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-add`,e.setAttribute(`aria-label`,t.label),e.title=t.label,e.innerHTML=O(`plus`,13),e.addEventListener(`click`,t.run),r.appendChild(e)}let a=document.createElement(`div`);return a.className=`tcw-tree-list`,n.appendChild(r),n.appendChild(a),this.el.appendChild(n),a}renderIndicators(e){if(this.indicatorsEl.replaceChildren(),e.length===0){this.indicatorsEl.appendChild(this.emptyRow(this.t(`objects.noIndicators`)));return}for(let t of e){let e=this.row(t.name,t.title);t.visible||e.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);if(n.className=`tcw-tree-actions`,this.callbacks.onToggleIndicatorVisible&&n.appendChild(this.iconButton(t.visible?`eye`:`eyeOff`,t.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleIndicatorVisible?.(t.instanceId,!t.visible))),this.callbacks.onConfigureIndicator){let e=this.iconButton(`settings`,this.t(`objects.indicatorSettings`),``,()=>this.callbacks.onConfigureIndicator?.(t.instanceId));D(e,`indicatorSettings`),n.appendChild(e)}n.appendChild(this.iconButton(`trash`,this.t(`objects.removeIndicator`),`tcw-tree-del`,()=>this.callbacks.onRemoveIndicator(t.instanceId))),e.appendChild(n),this.indicatorsEl.appendChild(e)}}renderDrawings(e){if(this.renaming||this.dragging){this.pending=e;return}this.pending=null;let t=document.activeElement?.closest(`.tcw-tree-grip`)?.closest(`[data-drawing-id]`)?.dataset.drawingId;this.drawingIndex=new Map(e.map((e,t)=>[e.id,t]));let n=[...e].reverse();this.loose=n.filter(e=>!e.group).map(e=>e.id),this.drawingsEl.replaceChildren(),this.listDrawings(n),t&&this.drawingsEl.querySelector(`[data-drawing-id="${t}"] .tcw-tree-grip`)?.focus()}flushPending(){this.pending&&!this.renaming&&!this.dragging&&this.renderDrawings(this.pending)}listDrawings(e){if(e.length===0){this.drawingsEl.appendChild(this.emptyRow(this.t(`objects.noDrawings`)));return}let t=new Set;for(let n of e){if(!n.group){this.drawingsEl.appendChild(this.drawingRow(n));continue}if(t.has(n.group.id))continue;t.add(n.group.id);let r=n.group.id,i=e.filter(e=>e.group?.id===r);this.drawingsEl.appendChild(this.groupRow(r,n.group.name,i));for(let e of i){let t=this.drawingRow(e);t.classList.add(`tcw-tree-member`),this.drawingsEl.appendChild(t)}}}groupRow(e,t,n){let r=this.row(t);r.classList.add(`tcw-tree-group`);let i=n.some(e=>e.visible),a=n.every(e=>e.locked);i||r.classList.add(`tcw-tree-hidden`);let o=r.querySelector(`.tcw-tree-name`);o.innerHTML=O(`layers`,13),o.append(` ${t}`);let s=document.createElement(`div`);return s.className=`tcw-tree-actions`,this.callbacks.onRenameGroup&&(o.addEventListener(`dblclick`,()=>this.renameGroup(o,e,t)),s.appendChild(this.iconButton(`penLine`,this.t(`objects.renameGroup`),``,()=>this.renameGroup(o,e,t)))),this.callbacks.onToggleGroupVisible&&s.appendChild(this.iconButton(i?`eye`:`eyeOff`,i?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleGroupVisible?.(e,!i))),this.callbacks.onToggleGroupLocked&&s.appendChild(this.iconButton(a?`lock`:`unlock`,a?this.t(`common.unlock`):this.t(`common.lock`),a?`tcw-tree-on`:``,()=>this.callbacks.onToggleGroupLocked?.(e,!a))),this.callbacks.onUngroup&&s.appendChild(this.iconButton(`x`,this.t(`drawingMenu.ungroup`),``,()=>this.callbacks.onUngroup?.(e))),r.appendChild(s),r}renameGroup(e,t,n){this.renameInline(e,n,this.t(`objects.renameGroup`),e=>{e&&e!==n&&this.callbacks.onRenameGroup?.(t,e)})}renameInline(e,t,n,r){if(!e.isConnected)return;this.renaming=!0;let i=document.createElement(`input`);i.type=`text`,i.className=`tcw-tree-rename`,i.value=t,i.maxLength=Ca,i.setAttribute(`aria-label`,n);let a=!1,o=t=>{if(a)return;a=!0;let n=i.value.trim();i.isConnected&&i.replaceWith(e),this.renaming=!1,t&&r(n),this.flushPending()};i.addEventListener(`keydown`,e=>{e.key===`Enter`?o(!0):e.key===`Escape`&&(e.stopPropagation(),o(!1))}),i.addEventListener(`blur`,()=>o(!0)),e.replaceWith(i),i.focus(),i.select()}drawingRow(e){let t=this.row(e.label);t.dataset.drawingId=e.id,(!e.visible||e.offInterval)&&t.classList.add(`tcw-tree-hidden`),e.offInterval&&(t.title=this.t(`indicatorSettings.offInterval`)),this.callbacks.onMoveDrawing&&!e.group&&(t.dataset.reorder=`true`,t.insertBefore(this.grip(e.id),t.firstChild));let n=t.querySelector(`.tcw-tree-name`);this.callbacks.onSelectDrawing&&(n.classList.add(`tcw-tree-pick`),n.addEventListener(`click`,()=>this.callbacks.onSelectDrawing?.(e.id))),this.callbacks.onRenameDrawing&&n.addEventListener(`dblclick`,()=>this.renameInline(n,e.label,this.t(`objects.renameDrawing`),t=>{t!==e.label&&this.callbacks.onRenameDrawing?.(e.id,t)}));let r=document.createElement(`div`);if(r.className=`tcw-tree-actions`,r.appendChild(this.iconButton(e.visible?`eye`:`eyeOff`,e.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleDrawingVisible(e.id,!e.visible))),r.appendChild(this.iconButton(e.locked?`lock`:`unlock`,e.locked?this.t(`common.unlock`):this.t(`common.lock`),e.locked?`tcw-tree-on`:``,()=>this.callbacks.onToggleDrawingLocked(e.id,!e.locked))),this.callbacks.onCloneDrawing&&r.appendChild(this.iconButton(`copy`,this.t(`objects.cloneDrawing`),``,()=>this.callbacks.onCloneDrawing?.(e.id))),this.callbacks.onConfigureDrawing){let t=this.iconButton(`settings`,this.t(`objects.drawingSettings`),``,()=>this.callbacks.onConfigureDrawing?.(e.id));D(t,`drawingSettings`),r.appendChild(t)}return r.appendChild(this.iconButton(`trash`,this.t(`objects.removeDrawing`),`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(e.id))),t.appendChild(r),t}grip(e){let t=this.iconButton(`grip`,this.t(`objects.dragToReorder`),`tcw-tree-grip`,()=>{});return t.setAttribute(`aria-keyshortcuts`,`ArrowUp ArrowDown`),t.addEventListener(`pointerdown`,t=>{t.button===0&&(t.preventDefault(),this.beginRowDrag(e))}),t.addEventListener(`keydown`,t=>{let n=t.key===`ArrowUp`?-1:+(t.key===`ArrowDown`);if(!n)return;t.preventDefault();let r=this.loose[this.loose.indexOf(e)+n],i=r===void 0?void 0:this.drawingIndex.get(r);i!==void 0&&this.callbacks.onMoveDrawing?.(e,i)}),t}beginRowDrag(e){this.dragging?.stop();let t=null,n=n=>{t?.classList.remove(`tcw-tree-drop`),t=n&&n.dataset.drawingId!==e?n:null,t?.classList.add(`tcw-tree-drop`)},r=(e,t)=>[...this.drawingsEl.querySelectorAll(`.tcw-tree-row[data-reorder]`)].find(n=>{let r=n.getBoundingClientRect();return t>=r.top&&t<r.bottom&&e>=r.left&&e<r.right})??null,i=e=>r(e.clientX,e.clientY),a=e=>n(i(e)),o=e=>{e.key===`Escape`&&(e.stopPropagation(),c())},s=r=>{n(i(r));let a=t?this.drawingIndex.get(t.dataset.drawingId??``):void 0;c(),a!==void 0&&this.callbacks.onMoveDrawing?.(e,a)},c=()=>{n(null),document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,s),document.removeEventListener(`pointercancel`,c),document.removeEventListener(`keydown`,o,!0),this.dragging=null,this.flushPending()};document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,s),document.addEventListener(`pointercancel`,c),document.addEventListener(`keydown`,o,!0),this.dragging={id:e,stop:c}}renderCompares(e){if(!this.compareEl)return;if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(this.t(`objects.noComparisons`)));return}let t=e.some(e=>e.color);for(let n of e){let e=this.row(n.label);if(e.classList.add(`tcw-tree-compare`),t){let t=document.createElement(`span`);t.className=`tcw-tree-dot`,n.color&&(t.style.background=n.color),e.insertBefore(t,e.firstChild)}if(n.way){let t=document.createElement(`span`);t.className=`tcw-tree-way`,t.textContent=n.way,t.title=n.way,e.appendChild(t)}this.callbacks.onRemoveCompare&&e.appendChild(this.iconButton(`trash`,this.t(`objects.removeComparison`),`tcw-tree-del`,()=>this.callbacks.onRemoveCompare?.(n.id))),this.compareEl.appendChild(e)}}row(e,t=e){let n=document.createElement(`div`);n.className=`tcw-tree-row`;let r=document.createElement(`span`);return r.className=`tcw-tree-name`,r.textContent=e,r.title=t,n.appendChild(r),n}emptyRow(e){let t=document.createElement(`div`);return t.className=`tcw-tree-empty`,t.textContent=e,t}iconButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-tree-btn ${n}`.trim(),i.setAttribute(`aria-label`,t),i.title=t,i.innerHTML=O(e,14),i.addEventListener(`click`,r),i}},Ca=80,wa={trendLine:`Trend Line`,ray:`Ray`,extendedLine:`Extended Line`,horizontalLine:`Horizontal Line`,horizontalRay:`Horizontal Ray`,crossLine:`Cross Line`,infoLine:`Info Line`,trendAngle:`Trend Angle`,circle:`Circle`,fibChannel:`Fib Channel`,fibSpeedResistanceFan:`Fib Speed Resistance Fan`,schiffPitchfork:`Schiff Pitchfork`,modifiedSchiffPitchfork:`Modified Schiff Pitchfork`,xabcdPattern:`XABCD Pattern`,abcdPattern:`ABCD Pattern`,headAndShoulders:`Head and Shoulders`,dateAndPriceRange:`Date and Price Range`,cyclicLines:`Cyclic Lines`,priceLabel:`Price Label`,verticalLine:`Vertical Line`,rectangle:`Rectangle`,ellipse:`Ellipse`,triangle:`Triangle`,arrow:`Arrow`,parallelChannel:`Parallel Channel`,regressionChannel:`Regression Channel`,pitchfork:`Pitchfork`,fibRetracement:`Fib Retracement`,fibExtension:`Fib Extension`,fibTimeZones:`Fib Time Zones`,gannBox:`Gann Box`,gannFan:`Gann Fan`,elliottWave:`Elliott Wave`,priceRange:`Price Range`,dateRange:`Date Range`,measure:`Measure`,text:`Text`,textAnnotation:`Text`,anchoredVWAP:`Anchored VWAP`,volumeProfileRange:`Volume Profile`,riskReward:`Long/Short Position`,signpost:`Signpost`,balloon:`Balloon`,anchoredText:`Anchored Text`,anchoredNote:`Anchored Note`};function Ta(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:wa[e]??e}var Ea=[1,1.5,2,3,4],Da=[`solid`,`dashed`,`dotted`],Oa=`#4c8dff`,ka=10,Aa={ticks:`toolbar.timeframes.ticks`,seconds:`toolbar.timeframes.seconds`,minutes:`toolbar.timeframes.minutes`,hours:`toolbar.timeframes.hours`,days:`toolbar.timeframes.days`,weeks:`toolbar.timeframes.weeks`,months:`toolbar.timeframes.months`};function ja(e,t,n,r,i){let a=Ia();for(let e of[...t.plots].sort((e,t)=>e.color-t.color))a.appendChild(Ma(e,t,n,r));let o=I(Ea.map(e=>({value:String(e),label:`${e} px`})),String(t.lineWidth),e=>n.lineWidth(Number(e)));if(o.dataset.role=`line-width`,a.appendChild(N(r(`indicatorSettings.lineWidth`),o)),t.scale&&n.scale){let e=I([{value:`right`,label:r(`indicatorSettings.scale.right`)},{value:`left`,label:r(`indicatorSettings.scale.left`)}],t.scale,e=>n.scale?.(e===`left`?`left`:`right`));e.dataset.role=`scale`,a.appendChild(N(r(`indicatorSettings.scale`),e))}e.appendChild(a),t.levels&&n.levels&&e.appendChild(Na([...t.levels],n.levels,r,i))}function Ma(e,t,n,r){let i=t.plotStyles[e.key]??{},a=document.createElement(`div`);a.className=`tcw-settings-row tcw-indi-plot`,a.dataset.plot=e.key;let o=document.createElement(`label`);o.className=`tcw-indi-plot-name`;let s=document.createElement(`input`);s.type=`checkbox`,s.checked=i.visible!==!1,s.addEventListener(`change`,()=>n.plot(e.key,{visible:s.checked}));let c=document.createElement(`span`);c.className=`tcw-settings-label`,c.textContent=e.title,o.append(s,c);let l=document.createElement(`span`);l.className=`tcw-indi-plot-controls`;let u=(e,r)=>{let i=F(t.colors[e]??t.colors[0]??Oa,t=>n.color(e,t));return i.setAttribute(`aria-label`,r),i};if(e.tone!==void 0&&e.downColor!==void 0?l.append(u(e.color,`${e.title} ${r(`indicatorSettings.up`)}`),u(e.downColor,`${e.title} ${r(`indicatorSettings.down`)}`)):l.appendChild(u(e.color,e.title)),(e.kind??`line`)===`line`||e.kind===`step`){let t=I(Da.map(e=>({value:e,label:r(`drawingSettings.lineStyle.${e}`)})),i.lineStyle??`solid`,t=>n.plot(e.key,{lineStyle:t}));t.setAttribute(`aria-label`,`${e.title}: ${r(`drawingSettings.lineStyle`)}`),l.appendChild(t)}return a.append(o,l),a}function Na(e,t,n,r){let i=Ia(),a=e,o=()=>{let e=document.createElement(`div`);e.className=`tcw-settings-section-title`,e.textContent=n(`indicatorSettings.tab.levels`);let t=a.map((e,t)=>c(e,t)),r=document.createElement(`button`);r.type=`button`,r.className=`tcw-reset-link tcw-indi-add`,r.textContent=`+ ${n(`indicatorSettings.addLevel`)}`,r.addEventListener(`click`,()=>{let e=a[a.length-1];s([...a,e===void 0?0:e+ka]);let t=i.querySelectorAll(`.tcw-indi-level input`);t[t.length-1]?.focus()}),i.replaceChildren(e,...a.length===0?[La(n(`indicatorSettings.noLevels`))]:t,r)},s=e=>{a=e,t([...e]),o()},c=(e,o)=>{let c=P(e,{step:`any`},e=>{a=a.map((t,n)=>n===o?e:t),t([...a])});c.id=`tcw-indi-level-${r}-${o}`;let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-indi-remove`,l.innerHTML=O(`x`,12);let u=n(`indicatorSettings.removeLevel`);l.title=u,l.setAttribute(`aria-label`,`${u} ${o+1}`),l.addEventListener(`click`,()=>{s(a.filter((e,t)=>t!==o)),(i.querySelectorAll(`.tcw-indi-remove`)[o]??i.querySelector(`.tcw-indi-add`))?.focus()});let d=document.createElement(`span`);d.className=`tcw-indi-level`,d.append(c,l);let f=document.createElement(`div`);f.className=`tcw-settings-row`;let p=document.createElement(`label`);return p.className=`tcw-settings-label`,p.htmlFor=c.id,p.textContent=`${n(`indicatorSettings.level`)} ${o+1}`,f.append(p,d),f};return o(),i}function Pa(e,t,n,i){let a=new Map(r.INTERVAL_UNITS.map(e=>{let n=t?.[e],i=Array.isArray(n)?n:[1,r.INTERVAL_LIMITS[e]];return[e,{on:n!==!1,from:i[0],to:i[1]}]})),o=()=>{let e={};for(let[t,{on:n,from:i,to:o}]of a){let[a,s]=[Math.min(i,o),Math.max(i,o)];n?(a>1||s<r.INTERVAL_LIMITS[t])&&(e[t]=[a,s]):e[t]=!1}n(Object.keys(e).length>0?e:null)},s=Ia();for(let e of r.INTERVAL_UNITS)s.appendChild(Fa(e,a.get(e),o,i));e.appendChild(s)}function Fa(e,t,n,i){let a=document.createElement(`div`);a.className=`tcw-settings-row tcw-indi-unit`,a.dataset.unit=e;let o=document.createElement(`label`);o.className=`tcw-indi-plot-name`;let s=document.createElement(`input`);s.type=`checkbox`,s.checked=t.on;let c=document.createElement(`span`);c.className=`tcw-settings-label`,c.textContent=i(Aa[e]),o.append(s,c),a.appendChild(o);let l=[];if(e!==`ticks`){let o=(a,o)=>{let s=P(t[a],{min:1,max:r.INTERVAL_LIMITS[e],step:1},e=>{t[a]=Math.round(e),s.value=String(t[a]),n()});return s.setAttribute(`aria-label`,`${i(Aa[e])}: ${i(o)}`),s.disabled=!t.on,l.push(s),s},s=document.createElement(`span`);s.className=`tcw-indi-range`;let c=document.createElement(`span`);c.setAttribute(`aria-hidden`,`true`),c.textContent=`–`,s.append(o(`from`,`indicatorSettings.rangeFrom`),c,o(`to`,`indicatorSettings.rangeTo`)),a.appendChild(s)}return s.addEventListener(`change`,()=>{t.on=s.checked;for(let e of l)e.disabled=!s.checked;n()}),a}function Ia(){let e=document.createElement(`div`);return e.className=`tcw-settings-section`,e}function La(e){let t=document.createElement(`div`);return t.className=`tcw-settings-label`,t.textContent=e,t}var Ra=1,za=1.5,Ba={visible:!0,lineStyle:`solid`},Va=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ha=e=>JSON.parse(JSON.stringify(e));function Ua(e){return e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase())}function Wa(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].map(e=>[e,{...Ba,...t[e]}]))}var Ga=class{backdrop;modal;bodyEl;titleEl;tabsEl;defaultsBtn;menu=null;callbacks;target=null;draft={};initial=null;look={colors:[],lineWidth:za,plots:{},levels:[],intervals:null};tab=`inputs`;tabButtons=[];returnFocus=null;uid=Ra++;t;constructor(e,n,r){this.callbacks=n,this.t=r??(e=>t.c[e]),this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.finish(!1),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow tcw-indi`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-indi-title-${this.uid}`),this.modal.tabIndex=-1,this.modal.addEventListener(`keydown`,e=>this.onKeyDown(e));let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-indi-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`indicatorSettings.close`)),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.finish(!1)),a.append(this.titleEl,o),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-modal-tabs`,this.tabsEl.setAttribute(`role`,`tablist`),this.tabsEl.addEventListener(`keydown`,e=>this.onTabKey(e)),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`,this.bodyEl.id=`tcw-indi-panel-${this.uid}`,this.bodyEl.setAttribute(`role`,`tabpanel`),this.defaultsBtn=this.footerButton(`defaults`,`tcw-footer-menu`,()=>this.openDefaults()),this.modal.append(a,this.tabsEl,this.bodyEl,this.buildFooter()),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}buildFooter(){this.defaultsBtn.setAttribute(`aria-haspopup`,`menu`),this.defaultsBtn.setAttribute(`aria-expanded`,`false`),this.defaultsBtn.innerHTML=`<span></span>${O(`chevronDown`,12)}`,this.defaultsBtn.querySelector(`span`).textContent=this.t(`indicatorSettings.defaults`);let e=document.createElement(`div`);e.className=`tcw-footer-end`,e.append(this.footerButton(`cancel`,`tcw-footer-cancel`,()=>this.finish(!1),this.t(`common.cancel`)),this.footerButton(`ok`,`tcw-done-btn`,()=>this.finish(!0),this.t(`drawingSettings.ok`)));let t=document.createElement(`div`);return t.className=`tcw-modal-footer`,t.append(this.defaultsBtn,e),t}open(e){this.target&&this.finish(!0),this.backdrop.hidden&&(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.target=e,this.titleEl.textContent=this.t(`indicatorSettings.title`).replace(`{name}`,e.name),this.draft={},this.look={colors:[...e.colors??[]],lineWidth:e.lineWidth??za,plots:Object.fromEntries(Object.entries(e.plotStyles??{}).map(([e,t])=>[e,{...t}])),levels:[...e.levels??[]],scale:e.scale,intervals:e.intervals??null},this.initial={params:this.currentParams(),look:Ha(this.look)},this.tab=`inputs`,this.renderTabs(),this.renderBody(),this.backdrop.hidden=!1;let t=this.tabsEl.hidden?null:this.tabButtons[0]??null;(this.bodyEl.querySelector(`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)??t??this.modal).focus()}close(){this.finish(!0)}isOpen(){return!this.backdrop.hidden}destroy(){this.menu?.destroy(),this.backdrop.remove()}finish(e){if(this.target){if(e){let e=document.activeElement;(e instanceof HTMLInputElement||e instanceof HTMLSelectElement)&&this.modal.contains(e)&&e.dispatchEvent(new Event(`change`))}else this.revert();this.target=null,this.menu?.close(),this.backdrop.hidden=!0,this.callbacks.onClose(),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null}}revert(){let e=this.target,t=this.initial;if(!e||!t)return;let n=e.instanceId;Va(this.currentParams(),t.params)||this.callbacks.onApply(n,{...t.params});let r=t.look,i={};Va(this.look.colors,r.colors)||(i.colors=[...r.colors]),this.look.lineWidth!==r.lineWidth&&(i.lineWidths=[r.lineWidth]),Va(this.look.plots,r.plots)||(i.plots=Wa(this.look.plots,r.plots)),Object.keys(i).length>0&&this.callbacks.onStyle?.(n,i),Va(this.look.levels,r.levels)||this.callbacks.onLevels?.(n,e.ownLevels?[...r.levels]:null),this.look.scale!==r.scale&&r.scale&&this.callbacks.onScale?.(n,r.scale),Va(this.look.intervals,r.intervals)||this.callbacks.onIntervals?.(n,r.intervals)}currentParams(){let e=this.target;return e?{...e.defaults,...e.params,...this.draft}:{}}tabs(){let e=this.target;if(!e)return[];let t=!!(e.plots?.length&&e.colors&&this.callbacks.onStyle),n=!!(e.levels&&this.callbacks.onLevels);return[`inputs`,...t||n?[`style`]:[],...this.callbacks.onIntervals?[`visibility`]:[]]}renderTabs(){let e=this.tabs();this.tabsEl.hidden=e.length<2,this.tabButtons=e.map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-modal-tab`,t.id=`tcw-indi-tab-${this.uid}-${e}`,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,this.bodyEl.id),t.dataset.tab=e,t.textContent=this.t(`indicatorSettings.tab.${e}`),t.addEventListener(`click`,()=>this.selectTab(e)),t}),this.tabsEl.replaceChildren(...this.tabButtons),this.markTabs()}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.tab=e,this.markTabs(),this.renderBody(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=this.tabButtons.map(e=>e.dataset.tab),n=t.indexOf(this.tab),[r,i]=this.modal.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowLeft`,`ArrowRight`]:[`ArrowRight`,`ArrowLeft`],a=e.key===r?(n+1)%t.length:e.key===i?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;a<0||t.length===0||(e.preventDefault(),this.selectTab(t[a],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.finish(!1);return}M(e,this.modal)}renderBody(){this.bodyEl.replaceChildren();let e=this.target;e&&(this.tab===`style`?this.renderStyle(e):this.tab===`visibility`?Pa(this.bodyEl,this.look.intervals,e=>this.setIntervals(e),this.t):this.renderInputs())}currentValue(e){if(e in this.draft)return this.draft[e];let t=this.target?.params[e],n=this.target?.defaults[e];return t??n}setValue(e,t){this.target&&(this.draft[e]=t,this.callbacks.onApply(this.target.instanceId,{...this.draft}))}renderInputs(){let e=document.createElement(`div`);e.className=`tcw-settings-section`;let t=(0,r.describeInputs)({defaultConfig:this.target.defaults,inputs:this.target.inputs});t.length===0&&e.appendChild(this.note(this.t(`indicatorSettings.noInputs`)));for(let n of t)e.appendChild(this.fieldRow(n));this.bodyEl.appendChild(e)}fieldRow(e){let t=e.name,n=this.currentValue(t),r;switch(e.kind){case`source`:r=this.sourceControl(t,String(n??`close`));break;case`choice`:r=this.choiceControl(t,e.options??[],n);break;case`boolean`:r=Sn(!!n,e=>this.setValue(t,e));break;case`int`:case`number`:r=P(Number(n),{min:e.min,max:e.max,step:e.step,whole:e.kind===`int`},e=>this.setValue(t,e));break;case`color`:r=F(String(n),e=>this.setValue(t,e));break;default:r=this.textControl(t,String(n??``))}return N(e.label??Ki(t,this.t)??Ua(t),r)}sourceControl(e,t){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;let i=document.createElement(`optgroup`);i.label=this.t(`indicatorSettings.source.prices`);for(let e of n.PRICE_SOURCES)i.appendChild(this.option(e,e));r.appendChild(i);let a=this.target?.lineSources??[];if(a.length){let e=document.createElement(`optgroup`);e.label=this.t(`indicatorSettings.source.indicators`);for(let t of a)e.appendChild(this.option(t.value,t.label));r.appendChild(e)}return r.value=t,r.value!==t&&(r.value=`close`),r.addEventListener(`change`,()=>this.setValue(e,r.value)),r}choiceControl(e,t,n){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;for(let n of t)r.appendChild(this.option(String(n),qi(e,n,this.t)??String(n)));return r.value=String(n),r.addEventListener(`change`,()=>{let n=t.find(e=>String(e)===r.value);n!==void 0&&this.setValue(e,n)}),r}textControl(e,t){let n=document.createElement(`input`);return n.type=`text`,n.className=`tcw-indi-input`,n.value=t,n.addEventListener(`change`,()=>this.setValue(e,n.value)),n}renderStyle(e){let t=e.instanceId,n=()=>this.target===e,r=e=>n()&&this.callbacks.onStyle?.(t,e),i=e=>n()&&this.callbacks.onLevels?.(t,e),a=e=>n()&&this.callbacks.onScale?.(t,e);ja(this.bodyEl,{plots:e.colors&&this.callbacks.onStyle?e.plots??[]:[],colors:this.look.colors,plotStyles:this.look.plots,lineWidth:this.look.lineWidth,scale:e.scale&&this.callbacks.onScale?this.look.scale:void 0,levels:e.levels&&this.callbacks.onLevels?this.look.levels:void 0},{color:(e,t)=>{if(!n())return;let i=[...this.look.colors];for(;i.length<=e;)i.push(i[0]??t);i[e]=t,this.look.colors=i,r({colors:[...i]})},plot:(e,t)=>{n()&&(this.look.plots={...this.look.plots,[e]:{...this.look.plots[e],...t}},r({plots:{[e]:t}}))},lineWidth:e=>{n()&&(this.look.lineWidth=e,r({lineWidths:[e]}))},scale:e=>{n()&&(this.look.scale=e,a(e))},levels:e=>{n()&&(this.look.levels=e,i([...e]))}},this.t,this.uid)}setIntervals(e){this.target&&(this.look.intervals=e,this.callbacks.onIntervals?.(this.target.instanceId,e))}openDefaults(){if(this.menu?.isOpen()){this.menu.close();return}this.menu??=new A(this.modal,this.t(`indicatorSettings.defaults`));let e=this.defaultsBtn.getBoundingClientRect(),t=this.modal.getBoundingClientRect(),n=[{id:`reset`,label:this.t(`indicatorSettings.resetSettings`),icon:`reset`},...this.callbacks.onSaveDefault?[{id:`save`,label:this.t(`indicatorSettings.saveAsDefault`),icon:`save`}]:[]];this.menu.open(n,e.left-t.left,e.top-t.top,e=>{e===`reset`?this.resetAll():this.saveDefault()},this.defaultsBtn)}resetAll(){let e=this.target;if(!e)return;let t=e.instanceId,n={...e.defaults};this.draft={...n},this.callbacks.onApply(t,{...n}),Object.keys(this.look.plots).length>0&&(this.callbacks.onStyle?.(t,{plots:Wa(this.look.plots,{})}),this.look.plots={}),e.levels&&this.callbacks.onLevels&&(this.callbacks.onLevels(t,null),this.look.levels=[...e.defaultLevels??[]]),this.look.intervals&&this.setIntervals(null),this.renderBody()}saveDefault(){let e=this.target;if(!e)return;let t=Object.fromEntries(Object.entries(this.currentParams()).filter(([t,r])=>!Va(r,e.defaults[t])&&!(typeof r==`string`&&(0,n.parseIndicatorSource)(r)))),i={};(0,r.isSeriesPalette)(this.look.colors)||(i.colors=[...this.look.colors]),this.look.lineWidth!==za&&(i.lineWidths=[this.look.lineWidth]),Object.keys(this.look.plots).length>0&&(i.plots=Ha(this.look.plots)),this.callbacks.onSaveDefault?.(e.indicatorId,{params:t,style:i})}footerButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=t,i.dataset.act=e,r&&(i.textContent=r),i.addEventListener(`click`,n),i}note(e){let t=document.createElement(`div`);return t.className=`tcw-settings-label`,t.textContent=e,t}option(e,t){let n=document.createElement(`option`);return n.value=e,n.textContent=t,n}};function Ka(e){return e.normalize(`NFD`).replace(/[̀-ͯ]/g,``).toLowerCase()}var qa=/[\s/()%-]+/;function Ja(e,t){let n=Ka(e.shortName),r=Ka(e.name);return n===t||Ka(e.id)===t?0:n.startsWith(t)||r.startsWith(t)?1:[...r.split(qa),...n.split(qa)].some(e=>e.startsWith(t))?2:r.includes(t)||n.includes(t)?3:null}function Ya(e,t){let n=Ka(t.trim());return n?e.map(e=>({item:e,rank:Ja(e,n)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.item.name.localeCompare(t.item.name)).map(e=>e.item):[]}var Xa=1,Za=(e,t)=>e.name.localeCompare(t.name),Qa=class{backdrop=null;listEl=null;navEl=null;searchEl=null;liveEl=null;content={items:[],favorites:[],templates:[]};favorites=new Set;counts=new Map;view=`all`;lastView=null;query=``;returnFocus=null;uid=Xa++;constructor(e,t,n){this.layer=e,this.callbacks=t,this.t=n}open(e){this.backdrop&&this.close(!1),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.content=e,this.favorites=new Set(e.favorites),this.counts=e.counts??new Map,this.query=``,this.view=this.startView(),this.build(),this.searchEl?.focus()}close(e=!0){this.backdrop&&(this.backdrop.remove(),this.backdrop=this.listEl=this.navEl=this.searchEl=this.liveEl=null,this.callbacks.onClose?.(),e&&this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return this.backdrop!==null}setTemplates(e){if(this.content={...this.content,templates:[...e]},!this.listEl||this.view!==`templates`||this.query)return;let t=this.listEl.contains(document.activeElement);this.renderList(),t&&!this.listEl.contains(document.activeElement)&&this.listEl.querySelector(`[data-tpl-save]`)?.focus()}setCounts(e){this.counts=e,this.listEl?.querySelectorAll(`.tcw-ip-row[data-ind]`).forEach(e=>this.markCount(e))}destroy(){this.close(!1)}startView(){let e=this.views();return this.lastView&&e.includes(this.lastView)&&!(this.lastView===`favorites`&&this.favorites.size===0)?this.lastView:this.favorites.size>0?`favorites`:`all`}views(){let e=new Set(this.content.items.map(e=>e.category));return[`favorites`,...this.callbacks.templates&&this.content.templates?[`templates`]:[],`all`,...r.INDICATOR_CATEGORIES.filter(t=>e.has(t))]}viewLabel(e){return e===`favorites`?this.t(`indicatorPicker.favorites`):e===`templates`?this.t(`toolbar.indicators.templates`):e===`all`?this.t(`toolbar.indicators.all`):this.t(`indicatorCategory.${e}`)}build(){let e=document.createElement(`div`);e.className=`tcw-modal-backdrop`,e.addEventListener(`click`,t=>{t.target===e&&this.close()});let t=document.createElement(`div`);t.className=`tcw-modal tcw-ip`,t.setAttribute(`role`,`dialog`),t.setAttribute(`aria-modal`,`true`),t.setAttribute(`aria-labelledby`,`tcw-ip-title-${this.uid}`),t.tabIndex=-1,t.addEventListener(`keydown`,e=>this.onKeyDown(e,t));let n=document.createElement(`div`);n.className=`tcw-visually-hidden`,n.setAttribute(`aria-live`,`polite`),t.append(this.buildHeader(),this.buildSearch(),this.buildBody(),n),e.appendChild(t),this.layer().appendChild(e),this.backdrop=e,this.liveEl=n,this.renderNav(),this.renderList()}buildHeader(){let e=document.createElement(`div`);e.className=`tcw-modal-header`;let t=document.createElement(`h3`);t.id=`tcw-ip-title-${this.uid}`,t.textContent=this.t(`toolbar.indicators`);let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-modal-close`,n.setAttribute(`aria-label`,this.t(`indicatorSettings.close`)),n.innerHTML=O(`x`,16),n.addEventListener(`click`,()=>this.close()),e.append(t,n),e}buildSearch(){let e=document.createElement(`label`);e.className=`tcw-ip-search`;let t=document.createElement(`input`);return t.type=`search`,t.id=`tcw-ip-search-${this.uid}`,t.placeholder=this.t(`indicatorPicker.search`),t.setAttribute(`aria-label`,this.t(`indicatorPicker.search`)),t.autocomplete=`off`,t.spellcheck=!1,t.addEventListener(`input`,()=>{this.query=t.value,this.renderList()}),t.addEventListener(`keydown`,e=>this.onSearchKey(e)),e.innerHTML=O(`search`,16),e.appendChild(t),this.searchEl=t,e}buildBody(){let e=document.createElement(`div`);e.className=`tcw-ip-body`;let t=document.createElement(`div`);t.className=`tcw-ip-nav`,t.setAttribute(`role`,`tablist`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,this.t(`indicatorPicker.groups`)),t.addEventListener(`keydown`,e=>this.onNavKey(e));let n=document.createElement(`div`);return n.className=`tcw-ip-list`,n.id=`tcw-ip-list-${this.uid}`,n.setAttribute(`role`,`tabpanel`),n.addEventListener(`keydown`,e=>this.onListKey(e)),n.addEventListener(`focusin`,e=>this.rove(e.target)),e.append(t,n),this.navEl=t,this.listEl=n,e}renderNav(){let e=this.navEl;e&&(e.replaceChildren(...this.views().map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-ip-tab`,t.id=`tcw-ip-tab-${this.uid}-${e}`,t.dataset.view=e,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,`tcw-ip-list-${this.uid}`),t.innerHTML=`${e===`favorites`?O(`star`,14):e===`templates`?O(`layers`,14):``}<span></span>`,t.querySelector(`span`).textContent=this.viewLabel(e),e===`templates`&&D(t,`indicatorTemplates`),t.addEventListener(`click`,()=>this.select(e)),t})),this.markNav())}markNav(){this.navEl?.querySelectorAll(`.tcw-ip-tab`).forEach(e=>{let t=e.dataset.view===this.view;e.setAttribute(`aria-selected`,String(t)),e.classList.toggle(`tcw-active`,t),e.tabIndex=t?0:-1}),this.labelList()}labelList(){let e=this.query.trim()!==``;this.listEl?.setAttribute(`aria-labelledby`,e?`tcw-ip-search-${this.uid}`:`tcw-ip-tab-${this.uid}-${this.view}`)}select(e,t=!1){this.view=this.lastView=e,this.searchEl&&this.query&&(this.searchEl.value=this.query=``),this.markNav(),this.renderList(),t&&this.navEl?.querySelector(`[data-view="${e}"]`)?.focus()}renderList(){let e=this.listEl;if(!e)return;e.replaceChildren();let n=this.content.items;if(this.navEl?.classList.toggle(`tcw-ip-nav--searching`,this.query.trim()!==``),this.labelList(),this.query.trim()){let r=Ya(n,this.query);r.length===0?e.appendChild(this.note(t.r(this.t(`indicatorPicker.noMatch`),{query:this.query.trim()}))):e.append(...r.map(e=>this.row(e)))}else if(this.view===`templates`)this.renderTemplates(e);else if(this.view===`favorites`){let t=n.filter(e=>this.favorites.has(e.id)).sort(Za);t.length===0?e.appendChild(this.note(this.t(`indicatorPicker.noFavorites`))):e.append(...t.map(e=>this.row(e)))}else if(this.view===`all`)for(let t of r.INDICATOR_CATEGORIES){let r=n.filter(e=>e.category===t).sort(Za);if(r.length===0)continue;let i=document.createElement(`div`);i.className=`tcw-ip-heading`,i.textContent=this.viewLabel(t),e.append(i,...r.map(e=>this.row(e)))}else e.append(...n.filter(e=>e.category===this.view).sort(Za).map(e=>this.row(e)));e.querySelector(`.tcw-ip-add`)?.setAttribute(`tabindex`,`0`)}row(e){let t=document.createElement(`div`);t.className=`tcw-ip-row`,t.dataset.ind=e.id;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-ip-add`,n.dataset.ind=e.id,n.tabIndex=-1;let r=document.createElement(`span`);r.className=`tcw-ip-name`,r.textContent=e.name,n.appendChild(r),e.shortName&&e.shortName!==e.name&&n.appendChild(this.tag(`tcw-ip-short`,e.shortName)),n.appendChild(this.tag(`tcw-ip-kind`,this.t(`indicatorType.${e.placement}`))),n.addEventListener(`click`,()=>this.add(e));let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-ip-aside tcw-ip-star`,i.tabIndex=-1,i.title=this.t(`indicatorPicker.favorite`),i.setAttribute(`aria-label`,`${this.t(`indicatorPicker.favorite`)}: ${e.name}`),i.setAttribute(`aria-pressed`,String(this.favorites.has(e.id))),i.innerHTML=O(`star`,14),i.addEventListener(`click`,()=>this.toggleFavorite(e.id,i)),t.append(n,i),this.markCount(t),t}renderTemplates(e){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-ip-add tcw-ip-save`,n.tabIndex=-1,n.dataset.tplSave=``,n.innerHTML=`${O(`save`,14)}<span class="tcw-ip-name"></span>`,n.querySelector(`span`).textContent=this.t(`templates.save`),n.addEventListener(`click`,()=>{this.close(),this.callbacks.templates?.onSave()}),e.appendChild(n);let r=this.content.templates??[];r.length===0&&e.appendChild(this.note(this.t(`indicatorPicker.noTemplates`)));for(let n of r){let r=document.createElement(`div`);r.className=`tcw-ip-row`;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-ip-add`,i.tabIndex=-1,i.dataset.tplApply=n,i.innerHTML=`${O(`layers`,14)}<span class="tcw-ip-name"></span>`,i.querySelector(`span`).textContent=n,i.addEventListener(`click`,()=>{this.close(),this.callbacks.templates?.onApply(n)});let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-ip-aside tcw-ip-remove`,a.tabIndex=-1,a.dataset.tplDelete=n;let o=t.r(this.t(`templates.delete`),{name:n});a.title=o,a.setAttribute(`aria-label`,o),a.innerHTML=O(`x`,12),a.addEventListener(`click`,()=>this.callbacks.templates?.onDelete(n)),r.append(i,a),e.appendChild(r)}}add(e){if(this.callbacks.onAdd(e.id)===!1||!this.liveEl)return;let n=t.r(this.t(`indicatorPicker.added`),{name:e.name});this.liveEl.textContent=this.liveEl.textContent===n?`${n}\u00a0`:n}toggleFavorite(e,t){let n=!this.favorites.has(e);if(n?this.favorites.add(e):this.favorites.delete(e),this.callbacks.onFavorite(e,n),t.setAttribute(`aria-pressed`,String(n)),this.view!==`favorites`||this.query||n)return;let r=[...this.listEl?.querySelectorAll(`.tcw-ip-star`)??[]].indexOf(t),i=document.activeElement===t;if(this.renderList(),!i)return;let a=[...this.listEl?.querySelectorAll(`.tcw-ip-star`)??[]];(a[r]??a[a.length-1]??this.searchEl)?.focus()}markCount(e){let n=this.counts.get(e.dataset.ind??``)??0,r=e.querySelector(`.tcw-ip-add`),i=e.querySelector(`.tcw-ip-count`);if(n===0){i?.remove();return}i||(i=this.tag(`tcw-ip-count`,``),r?.appendChild(i)),i.textContent=String(n),i.title=t.r(this.t(`indicatorPicker.onChart`),{count:String(n)})}tag(e,t){let n=document.createElement(`span`);return n.className=e,n.textContent=t,n}note(e){let t=document.createElement(`div`);return t.className=`tcw-ip-empty`,t.textContent=e,t}rove(e){!(e instanceof HTMLElement)||!e.classList.contains(`tcw-ip-add`)||(this.listEl?.querySelectorAll(`.tcw-ip-add[tabindex="0"]`).forEach(t=>{t!==e&&(t.tabIndex=-1)}),e.tabIndex=0)}onKeyDown(e,t){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.close();return}M(e,t)}onSearchKey(e){let t=this.listEl?.querySelector(`.tcw-ip-add`);e.key===`ArrowDown`&&t?(e.preventDefault(),t.focus()):e.key===`Enter`&&this.query.trim()&&t&&(e.preventDefault(),t.click())}onNavKey(e){let t=this.views(),n=t.indexOf(this.view),r=e.key===`ArrowDown`?Math.min(t.length-1,n+1):e.key===`ArrowUp`?Math.max(0,n-1):e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),this.select(t[r],!0))}onListKey(e){let t=e.target,n=t.closest(`.tcw-ip-row, .tcw-ip-save`),r=[...this.listEl?.querySelectorAll(`.tcw-ip-add`)??[]],i=n?.classList.contains(`tcw-ip-save`)?n:n?.querySelector(`.tcw-ip-add`),a=i?r.indexOf(i):-1,o=null;e.key===`ArrowDown`?o=r[a+1]:e.key===`ArrowUp`?o=a>0?r[a-1]:this.searchEl:e.key===`Home`?o=r[0]:e.key===`End`?o=r[r.length-1]:e.key===`ArrowRight`&&t===i?o=n?.querySelector(`.tcw-ip-aside`):e.key===`ArrowLeft`&&t!==i&&(o=i),o&&(e.preventDefault(),o.focus())}};function $a(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var eo=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function to(e){return eo(e)?Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`number`&&Number.isFinite(e)||typeof e==`string`&&!(0,n.parseIndicatorSource)(e)||typeof e==`boolean`)):{}}function no(e){if(!eo(e))return{};let t={};if(Array.isArray(e.colors)){let n=e.colors.filter(e=>typeof e==`string`&&e.trim()!==``);n.length>0&&(t.colors=n)}if(Array.isArray(e.lineWidths)){let n=e.lineWidths.filter(e=>typeof e==`number`&&Number.isFinite(e)&&e>0);n.length>0&&(t.lineWidths=n)}let r=(0,n.readIndicatorPlotStyles)(e.plots);return r&&(t.plots=r),t}var ro=class{constructor(e=`tcw:indicator-defaults`,t=$a()){this.key=e,this.storage=t}all(){let e=new Map,t;try{t=JSON.parse(this.storage?.getItem(this.key)??`{}`)}catch{return e}if(!eo(t))return e;for(let[n,r]of Object.entries(t))eo(r)&&e.set(n,{params:to(r.params),style:no(r.style)});return e}get(e){return this.all().get(e)??null}save(e,t){if(!this.storage)return!1;let n=Object.fromEntries([...this.all(),[e,{params:to(t.params),style:no(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},io=1,ao=[`logScale`,`autoScale`],oo=new Set([`timezone`,`numberLocale`]),so=new Set([...ao,`chartTypeOptions`]),co=new Set([...ao,...oo,`scaleMode`,`invertScale`,`chartTypeOptions`]),lo=new Set([...ao,...oo,`scaleMode`]),uo=new Set,fo=[`renko`,`lineBreak`,`kagi`,`pointAndFigure`,`rangeBars`];function po(e){return fo.includes(e)}function mo(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>vo(e)&&Object.keys(e).length>0))}function ho(){return Object.fromEntries(fo.map(e=>[e,{}]))}var go={crosshairMode:[`normal`,`magnet`,`hidden`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},_o={marketProfileBuckets:{min:8,max:200,whole:!0},marketProfileOpacity:{min:.05,max:1},depthHeatmapOpacity:{min:.1,max:1},pivotStrength:{min:2,max:20,whole:!0}},vo=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function yo(e){return e===`local`||u(e)!==null}function bo(e){try{return Intl.NumberFormat.supportedLocalesOf(e).length>0}catch{return!1}}function xo(e,t){let r=he[e];if(e===`chartTypeOptions`)return vo(t)?(0,n.readChartTypeOptions)(t):void 0;if(typeof t!=typeof r)return;if(typeof t==`number`){if(!Number.isFinite(t))return;let n=_o[e];if(!n)return t;let r=Math.min(n.max,Math.max(n.min,t));return n.whole?Math.round(r):r}if(typeof t!=`string`)return t;let i=go[e];return i?i.includes(t)?t:void 0:e===`timezone`?yo(t)?t:void 0:e===`numberLocale`?bo(t)?t:void 0:t}function G(e,t=uo){if(!vo(e))return{};let n={};for(let r of Object.keys(he)){if(t.has(r)||!Object.prototype.hasOwnProperty.call(e,r))continue;let i=xo(r,e[r]);i!==void 0&&(n[r]=i)}return n}function So(e,t){return Object.fromEntries(Object.keys(e).filter(e=>!t.has(e)).map(t=>[t,e[t]]))}function Co(e,t,n){return Object.fromEntries(Object.keys(e).filter(r=>!n.has(r)&&JSON.stringify(e[r])!==JSON.stringify(t[r])).map(t=>[t,e[t]]))}function wo(e,t){return Co({...e,chartTypeOptions:mo(e.chartTypeOptions)},t,lo)}function To(e){return e?(e===!0?void 0:e.key)||`tcw:chart-settings`:null}function Eo(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Do=class{constructor(e,t=Eo()){this.key=e,this.storage=t}load(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`null`)}catch{return{}}return!vo(e)||e.v!==io?{}:G(e.settings,so)}save(e,t){try{this.storage?.setItem(this.key,JSON.stringify({v:io,settings:Co(e,t,so)}))}catch{}}},Oo=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),ko=80,Ao=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function jo(e){return G(e,Oo)}function Mo(e){let{overrides:t}=(0,n.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(t).filter(([e,t])=>t!==null&&ke.includes(e)))}function No(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Po=class{constructor(e=`tcw:chart-templates`,t=No()){this.key=e,this.storage=t}list(){let e;try{e=JSON.parse(this.storage?.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e)!Ao(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,ko).trim(),settings:jo(n.settings),style:Mo(n.style)});return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t,n){let r=e.replace(/\s+/g,` `).slice(0,ko).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:jo(t),style:Mo(n)}];try{return this.storage.setItem(this.key,JSON.stringify(i)),!0}catch{return!1}}remove(e){try{this.storage?.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}};function Fo(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Io=80;function Lo(e){let{text:t,...r}=(0,n.sanitizeDrawingStyle)(e);return r}function Ro(e){let t={name:e.name,style:{...e.style}};return e.type&&(t.type=e.type),e.options&&(t.options=structuredClone(e.options)),t}var zo=class{templates=[];constructor(e=`tcw:draw-templates`,t=Fo()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(Ro)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?Ro(n):null}save(e,t,n){let r=e.trim().slice(0,Io);if(!r)return;let i={name:r,style:Lo(t)};n&&(i.type=n.type,i.options=structuredClone(n.options)),this.templates=this.templates.filter(e=>!(e.name===r&&e.type===i.type)),this.templates.push(i),this.persist()}remove(e,t){this.templates=this.templates.filter(n=>!(n.name===e&&n.type===t)),this.persist()}clear(){this.templates=[],this.persist()}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;this.templates=t.filter(e=>e&&typeof e.name==`string`&&e.name.trim()!==``).map(e=>{let t={name:e.name.trim().slice(0,Io),style:Lo(e.style)};return typeof e.type==`string`&&(t.type=e.type),e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&(t.options=e.options),t})}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.templates))}catch{}}},Bo=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=Fo()){this.storageKey=e,this.storage=t;try{let e=this.storage?.getItem(this.storageKey),t=e?JSON.parse(e):null;if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,n]of Object.entries(t))n&&typeof n==`object`&&!Array.isArray(n)&&(this.defaults[e]=n)}catch{}}all(){return structuredClone(this.defaults)}set(e,t){t&&Object.keys(t).length>0?this.defaults[e]=structuredClone(t):delete this.defaults[e];try{this.storage?.setItem(this.storageKey,JSON.stringify(this.defaults))}catch{}}},Vo=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],Ho=[1,2,3,4],Uo=[`solid`,`dashed`,`dotted`],Wo=class{el;templatesEl;nameInput;callbacks;store;open=!1;constructor(e,n,r,i=t.t){this.t=i,this.callbacks=n,this.store=r,this.el=document.createElement(`div`),this.el.className=`tcw-style-panel`,this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-style-header`;let o=document.createElement(`span`);o.textContent=this.t(`drawingStyle.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-style-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=O(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a),this.el.appendChild(this.colorRow()),this.el.appendChild(this.widthRow()),this.el.appendChild(this.lineStyleRow());let c=document.createElement(`div`);c.className=`tcw-style-subhead`,c.textContent=this.t(`drawingStyle.templates`),this.el.appendChild(c);let l=document.createElement(`div`);l.className=`tcw-style-save`,this.nameInput=document.createElement(`input`),this.nameInput.type=`text`,this.nameInput.placeholder=this.t(`drawingStyle.templateName`),this.nameInput.className=`tcw-style-name`;let u=document.createElement(`button`);u.type=`button`,u.className=`tcw-style-savebtn`,u.innerHTML=`${O(`plus`,13)}<span>${k(this.t(`common.save`))}</span>`,u.addEventListener(`click`,()=>this.saveTemplate()),l.appendChild(this.nameInput),l.appendChild(u),this.el.appendChild(l),this.templatesEl=document.createElement(`div`),this.templatesEl.className=`tcw-style-templates`,this.el.appendChild(this.templatesEl),e.appendChild(this.el),this.renderTemplates()}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.syncActiveControls(),this.renderTemplates()}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}colorRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-colors`;for(let t of Vo){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-swatch`,n.style.background=t,n.dataset.color=t,n.setAttribute(`aria-label`,t),n.addEventListener(`click`,()=>this.applyStyle({color:t})),e.appendChild(n)}let t=document.createElement(`input`);return t.type=`color`,t.className=`tcw-style-picker`,t.addEventListener(`input`,()=>this.applyStyle({color:t.value})),e.appendChild(t),e}widthRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-widths`;for(let t of Ho){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-width`,n.dataset.width=String(t);let r=document.createElement(`span`);r.style.height=`${t}px`,n.appendChild(r),n.addEventListener(`click`,()=>this.applyStyle({lineWidth:t})),e.appendChild(n)}return e}lineStyleRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-dashes`;for(let t of Uo){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-dash`,n.dataset.linestyle=t,n.textContent=t===`solid`?`──`:t===`dashed`?`╌╌`:`┄┄`,n.title=t,n.addEventListener(`click`,()=>this.applyStyle({lineStyle:t})),e.appendChild(n)}return e}applyStyle(e){this.callbacks.onStyleChange(e),this.syncActiveControls()}syncActiveControls(){let e=this.callbacks.getStyle();this.el.querySelectorAll(`.tcw-style-swatch`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.color?.toLowerCase()===e.color?.toLowerCase())}),this.el.querySelectorAll(`.tcw-style-width`).forEach(t=>{t.classList.toggle(`tcw-on`,Number(t.dataset.width)===e.lineWidth)}),this.el.querySelectorAll(`.tcw-style-dash`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.linestyle===e.lineStyle)})}saveTemplate(){let e=this.nameInput.value.trim();e&&(this.store.save(e,this.callbacks.getStyle()),this.nameInput.value=``,this.renderTemplates())}renderTemplates(){this.templatesEl.replaceChildren();let e=this.store.list();if(e.length===0){let e=document.createElement(`div`);e.className=`tcw-style-empty`,e.textContent=this.t(`drawingStyle.noTemplates`),this.templatesEl.appendChild(e);return}for(let t of e){let e=document.createElement(`div`);e.className=`tcw-style-template`;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-apply`;let r=document.createElement(`span`);r.className=`tcw-style-tdot`,r.style.background=t.style.color??`var(--tcw-text-muted)`;let i=document.createElement(`span`);i.textContent=t.name,n.appendChild(r),n.appendChild(i),n.addEventListener(`click`,()=>{this.callbacks.onStyleChange({...t.style}),this.syncActiveControls()});let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-style-tdel`,a.setAttribute(`aria-label`,this.t(`drawingStyle.deleteTemplate`)),a.innerHTML=O(`trash`,13),a.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(a),this.templatesEl.appendChild(e)}}},Go={color:`color`,fill:`fillColor`,textColor:`textColor`},Ko=10,K=4,qo=4,Jo=20,Yo=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function Xo(e){return typeof e==`string`&&Yo.test(e.trim())?e.trim():`#7d8696`}function Zo(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,Jo):1}function Qo(e){return Uo.includes(e)?e:`solid`}var $o=class{el;pop;target=null;built=``;size=null;openPop=null;pinned=null;drag=null;onDragMove=e=>{!this.drag||!this.target||e.pointerId!==this.drag.id||(this.pinned={left:this.drag.left+e.clientX-this.drag.x,top:this.drag.top+e.clientY-this.drag.y},this.place(this.target))};onDragEnd=e=>{e&&this.drag&&e.pointerId!==this.drag.id||(this.drag=null,document.removeEventListener(`pointermove`,this.onDragMove),document.removeEventListener(`pointerup`,this.onDragEnd),document.removeEventListener(`pointercancel`,this.onDragEnd))};onDocDown=e=>{this.openPop&&!this.el.contains(e.target)&&!this.pop.contains(e.target)&&this.closePop()};constructor(e,n,r=t.t){this.host=e,this.callbacks=n,this.t=r,this.el=document.createElement(`div`),this.el.className=`tcw-sel-toolbar`,this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,r(`selectionToolbar.label`)),this.el.hidden=!0,this.pop=document.createElement(`div`),this.pop.className=`tcw-sel-pop`,this.pop.setAttribute(`role`,`dialog`),this.pop.hidden=!0,e.append(this.el,this.pop),this.el.addEventListener(`click`,e=>this.onClick(e)),this.el.addEventListener(`keydown`,e=>this.onKey(e)),this.pop.addEventListener(`click`,e=>this.onPick(e)),this.pop.addEventListener(`keydown`,e=>this.onPopKey(e));for(let e of[this.el,this.pop])e.addEventListener(`pointerdown`,e=>e.stopPropagation());this.el.addEventListener(`pointerdown`,e=>{e.target.closest(`.tcw-sel-grip`)&&(e.preventDefault(),this.closePop(),this.drag={id:e.pointerId,x:e.clientX,y:e.clientY,left:parseFloat(this.el.style.left)||0,top:parseFloat(this.el.style.top)||0},document.addEventListener(`pointermove`,this.onDragMove),document.addEventListener(`pointerup`,this.onDragEnd),document.addEventListener(`pointercancel`,this.onDragEnd))}),this.el.addEventListener(`dblclick`,e=>{!e.target.closest(`.tcw-sel-grip`)||!this.target||(this.pinned=null,this.place(this.target))}),document.addEventListener(`pointerdown`,this.onDocDown,!0)}isOpen(){return!this.el.hidden}show(e){this.target=e;let t=e.style,n=[Xo(t.color),Zo(t.lineWidth),Qo(t.lineStyle),e.locked,e.canDelete,e.canSettings,e.canAlert,e.canFill===!0,e.canText===!0,t.fillColor,t.textColor].join(`|`);n!==this.built&&(this.built=n,this.render(e),this.size=null),this.el.hidden=!1,this.size||={w:this.el.offsetWidth,h:this.el.offsetHeight},this.place(e),this.openPop&&this.placePop()}hide(){this.closePop(),this.el.hidden=!0,this.target=null}destroy(){this.onDragEnd(),document.removeEventListener(`pointerdown`,this.onDocDown,!0),this.el.remove(),this.pop.remove()}render(e){let t=this.t,n=Xo(e.style.color),r=Zo(e.style.lineWidth),i=Qo(e.style.lineStyle),a=e.locked,o=this.el.contains(document.activeElement)?document.activeElement.dataset.action:void 0,s=(e,t,n,r=``)=>`<button type="button" class="tcw-sel-btn${r}" data-action="${e}" aria-label="${k(t)}" title="${k(t)}">${n}</button>`,c=(e,t,n)=>s(e,t,n,` tcw-sel-has-pop`).replace(`<button `,`<button aria-haspopup="dialog" aria-expanded="false" `);this.el.innerHTML=[`<span class="tcw-sel-grip" aria-hidden="true"></span>`,c(`color`,t(`drawingSettings.color`),`<span class="tcw-sel-color" style="background:${k(n)}"></span>`),c(`width`,t(`drawingSettings.lineWidth`),`<span class="tcw-sel-width" style="--w:${r}px"></span><span class="tcw-sel-num">${r}px</span>`),c(`lineStyle`,t(`drawingSettings.lineStyle`),es(i)),e.canFill?c(`fill`,t(`drawingSettings.fill`),`<span class="tcw-sel-color tcw-sel-fill" style="background:${k(Xo(e.style.fillColor??n))}"></span>`):``,e.canText?c(`textColor`,t(`drawingSettings.textColor`),`<span class="tcw-sel-text" style="--c:${k(Xo(e.style.textColor??n))}">T</span>`):``,`<span class="tcw-sel-sep" aria-hidden="true"></span>`,e.canSettings?s(`settings`,t(`legend.settings`),O(`settings`,15)):``,e.canAlert?s(`alert`,t(`drawingSettings.addAlert`),O(`bell`,15)):``,s(`lock`,t(a?`common.unlock`:`common.lock`),O(a?`lock`:`unlock`,15),a?` tcw-sel-on`:``).replace(`<button `,`<button aria-pressed="${a}" `),s(`more`,t(`legend.more`),O(`more`,15)),e.canDelete?s(`delete`,t(`drawingMenu.delete`),O(`trash`,15),` tcw-sel-danger`):``].join(``);let l=this.buttons(),u=l.find(e=>e.dataset.action===o)??(o?l.find(e=>e.dataset.action===`lock`):void 0);this.rove(u??l[0],u!==void 0)}buttons(){return[...this.el.querySelectorAll(`button`)]}rove(e,t){for(let t of this.buttons())t.tabIndex=t===e?0:-1;t&&e?.focus()}place(e){let{rect:t,bounds:n}=e,{w:r,h:i}=this.size??{w:0,h:0};if(this.pinned){let e=Math.max(n.x+K,Math.min(this.pinned.left,n.x+n.width-r-K)),t=Math.max(n.y+K,Math.min(this.pinned.top,n.y+n.height-i-K));this.el.style.left=`${Math.round(e)}px`,this.el.style.top=`${Math.round(t)}px`;return}let a=t.x+t.width/2-r/2;a=Math.max(n.x+K,Math.min(a,n.x+n.width-r-K));let o=t.y-i-Ko;o<n.y+K&&(o=Math.min(t.y+t.height+Ko,n.y+n.height-i-K)),o=Math.max(o,n.y+K),this.el.style.left=`${Math.round(a)}px`,this.el.style.top=`${Math.round(o)}px`}onClick(e){let t=e.target.closest(`[data-action]`);if(!t)return;this.rove(t,!1);let n=t.dataset.action;if(n===`color`||n===`width`||n===`lineStyle`||n===`fill`||n===`textColor`){this.openPop===n?this.closePop():this.openPopover(n,t);return}if(this.closePop(),n===`settings`)this.callbacks.onSettings();else if(n===`alert`)this.callbacks.onAlert();else if(n===`lock`)this.callbacks.onLock(!this.target?.locked);else if(n===`delete`)this.callbacks.onDelete();else if(n===`more`){let e=t.getBoundingClientRect(),n=this.host.getBoundingClientRect();this.callbacks.onMore(e.left-n.left,e.bottom-n.top+K)}}onKey(e){if(e.key===`Escape`&&this.openPop){e.stopPropagation(),this.closePop(!0);return}let t=this.buttons(),n=t.indexOf(document.activeElement);if(n<0)return;let r=e.key===`ArrowRight`?(n+1)%t.length:e.key===`ArrowLeft`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),this.rove(t[r],!0))}openPopover(e,t){let n=this.target.style,r=Xo(e===`fill`?n.fillColor??n.color:e===`textColor`?n.textColor??n.color:n.color).toLowerCase(),i=Zo(n.lineWidth),a=Qo(n.lineStyle),o=(e,t,n,r=``)=>`<button type="button" class="${e}${t?` tcw-sel-on`:``}" aria-pressed="${t}" ${n}>${r}</button>`;this.openPop=e,e===`color`||e===`fill`||e===`textColor`?this.pop.innerHTML=Vo.map(e=>o(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=Ho.map(e=>o(`tcw-sel-option`,e===i,`data-width="${e}"`,`<span class="tcw-sel-width" style="--w:${e}px"></span>${e}px`)).join(``):this.pop.innerHTML=Uo.map(e=>o(`tcw-sel-option`,e===a,`data-style="${e}"`,es(e)+k(this.t(`drawingSettings.lineStyle.${e}`)))).join(``),this.pop.className=`tcw-sel-pop tcw-sel-pop--${e}`,this.pop.setAttribute(`aria-label`,t.getAttribute(`aria-label`)??``),this.pop.hidden=!1;for(let e of this.el.querySelectorAll(`[aria-expanded="true"]`))e.setAttribute(`aria-expanded`,`false`);t.setAttribute(`aria-expanded`,`true`),this.placePop(),this.pop.querySelector(`.tcw-sel-on, button`)?.focus()}onPopKey(e){if(e.key===`Escape`){e.stopPropagation(),this.closePop(!0);return}let t=[...this.pop.querySelectorAll(`button`)],n=t.indexOf(document.activeElement);if(n<0)return;let r=this.openPop===`color`||this.openPop===`fill`||this.openPop===`textColor`?qo:1,i=e.key===`ArrowRight`?1:e.key===`ArrowLeft`?-1:e.key===`ArrowDown`?r:e.key===`ArrowUp`?-r:0;i&&(e.preventDefault(),t[(n+i+t.length)%t.length].focus())}placePop(){let e=this.el.querySelector(`[data-action="${this.openPop}"]`);e&&(this.pop.style.left=`${this.el.offsetLeft+e.offsetLeft}px`,this.pop.style.top=`${this.el.offsetTop+this.el.offsetHeight+6}px`)}onPick(e){let t=e.target.closest(`button`);if(!t)return;let n=this.openPop&&this.openPop in Go?Go[this.openPop]:`color`;t.dataset.color?this.callbacks.onStyle({[n]:t.dataset.color}):t.dataset.width?this.callbacks.onStyle({lineWidth:Number(t.dataset.width)}):t.dataset.style&&this.callbacks.onStyle({lineStyle:Qo(t.dataset.style)}),this.closePop(!0)}closePop(e=!1){if(!this.openPop)return;let t=this.el.querySelector(`[data-action="${this.openPop}"]`);t?.setAttribute(`aria-expanded`,`false`),this.openPop=null,this.pop.hidden=!0,e&&t?.focus()}};function es(e){return`<svg class="tcw-sel-line" width="22" height="10" viewBox="0 0 22 10" aria-hidden="true"><line x1="1" y1="5" x2="21" y2="5" stroke="currentColor" stroke-width="2"${e===`dashed`?` stroke-dasharray="4 3"`:e===`dotted`?` stroke-dasharray="1 3" stroke-linecap="round"`:``}/></svg>`}var ts=[1,2,3,4],ns=[`solid`,`dashed`,`dotted`],rs=[10,11,12,13,14,16,18,20,24,28,32],is=12,as=48,os=.5,ss=.1,cs=[`leftEnd`,`rightEnd`];function ls(e,t,n){let r=`drawingOption.${t}`,i=e(r);return i===r?n:i}function us(){let e=document.createElement(`div`);return e.className=`tcw-settings-section`,e}function q(e,...t){let n=document.createElement(`div`);n.className=`tcw-settings-row`;let r=document.createElement(`span`);r.className=`tcw-settings-label`,r.textContent=e;let i=document.createElement(`span`);return i.className=`tcw-indi-plot-controls`,i.append(...t),n.append(r,i),n}function J(e,t){return e.setAttribute(`aria-label`,t),e}function ds(e,t,n,r){let i=[],a=us();a.appendChild(fs(t.style(),n,i,r));let o=cs.filter(e=>t.defs[e]?.kind===`choice`);o.length>0&&a.appendChild(q(r(`drawingSettings.lineEnds`),...o.map(e=>J(I([{value:`normal`,label:r(`drawingSettings.lineEnd.normal`)},{value:`arrow`,label:r(`drawingSettings.lineEnd.arrow`)}],String(t.options()[e]??`normal`),t=>n.options({[e]:t})),ls(r,e,t.defs[e].label))))),t.fill&&a.appendChild(ps(t.style(),n,i,r)),e.appendChild(a);let s=Object.entries(t.defs).filter(([e,t])=>t.kind!==`levels`&&!o.includes(e));if(s.length>0){let i=us();for(let[e,a]of s)i.appendChild(ms(e,a,t.options(),n,r));e.appendChild(i)}for(let[a,o]of Object.entries(t.defs))o.kind===`levels`&&e.appendChild(hs(a,o,t,n,i,r))}function fs(e,t,n,r){let i=J(F(e.color,e=>{t.style({color:e});for(let t of n)t(e)}),r(`drawingSettings.color`)),a=J(I(ts.map(e=>({value:String(e),label:`${e} px`})),String(e.lineWidth),e=>t.style({lineWidth:Number(e)})),r(`drawingSettings.lineWidth`)),o=J(I(ns.map(e=>({value:e,label:r(`drawingSettings.lineStyle.${e}`)})),e.lineStyle,e=>t.style({lineStyle:e})),r(`drawingSettings.lineStyle`));return q(r(`drawingSettings.line`),i,a,o)}function ps(e,t,n,r){let i=e.fillColor??En(e.color,ss),a=Cn(i),o=Tn(i),s=e.fillColor!==void 0,c=()=>{s=!0,t.style({fillColor:En(a,o),fillOpacity:o})},l=J(F(a,e=>{a=e,c()}),r(`drawingSettings.fill`));n.push(e=>{s||(a=Cn(e),l.value=a)});let u=J(P(Math.round(o*100),{min:0,max:100,step:5},e=>{o=e/100,c()}),r(`drawingSettings.opacity`)),d=document.createElement(`span`);return d.className=`tcw-unit`,d.setAttribute(`aria-hidden`,`true`),d.textContent=`%`,q(r(`drawingSettings.fill`),l,u,d)}function ms(e,t,n,r,i){let a=ls(i,e,t.label),o=n[e];switch(t.kind){case`boolean`:return xn(a,!!o,t=>r.options({[e]:t}));case`number`:return N(a,P(Number(o),{min:t.min,max:t.max,step:t.step},t=>r.options({[e]:t})));case`choice`:return N(a,I(t.choices.map(t=>({value:t.value,label:ls(i,`${e}.${t.value}`,t.label)})),String(o),t=>r.options({[e]:t})));case`text`:{let t=document.createElement(`input`);return t.type=`text`,t.className=`tcw-indi-input`,t.value=String(o??``),t.addEventListener(`change`,()=>r.options({[e]:t.value})),N(a,t)}}}function hs(e,t,n,r,i,a){let o=document.createElement(`div`);o.className=`tcw-settings-section tcw-levels-editor`;let s=document.createElement(`div`);s.className=`tcw-settings-section-title`,s.textContent=ls(a,e,t.label),o.appendChild(s);let c=()=>{let t=n.options()[e];return Array.isArray(t)?t:[]},l=t=>r.options({[e]:t}),u=document.createElement(`div`);u.className=`tcw-levels-grid`,c().forEach((e,t)=>{let o=document.createElement(`div`);o.className=`tcw-level-row`;let s=` ${t+1}`,d=document.createElement(`input`);d.type=`checkbox`,d.checked=e.visible,d.setAttribute(`aria-label`,a(`drawingSettings.levelVisible`)+s),d.addEventListener(`change`,()=>l(c().map((e,n)=>n===t?{...e,visible:d.checked}:e)));let f=J(P(e.value,{step:.001},e=>l(c().map((n,r)=>r===t?{...n,value:e}:n))),a(`drawingSettings.levelValue`)+s),p=J(F(e.color??n.style().color,e=>l(c().map((n,r)=>r===t?{...n,color:e}:n))),a(`drawingSettings.levelColor`)+s);i.push(e=>{c()[t]?.color===void 0&&(p.value=Cn(e))});let m=document.createElement(`button`);m.type=`button`,m.className=`tcw-level-remove`,m.setAttribute(`aria-label`,a(`drawingSettings.removeLevel`)+s),m.innerHTML=O(`x`,12),m.addEventListener(`click`,()=>{l(c().filter((e,n)=>n!==t)),r.redraw([`.tcw-level-row:nth-child(${t+1}) .tcw-level-remove`,`.tcw-level-row:last-child .tcw-level-remove`,`.tcw-level-add`])}),o.append(d,f,p,m),u.appendChild(o)}),o.appendChild(u);let d=document.createElement(`button`);return d.type=`button`,d.className=`tcw-reset-link tcw-level-add`,d.textContent=a(`drawingSettings.addLevel`),d.disabled=c().length>=as,d.addEventListener(`click`,()=>{let e=c().at(-1)?.value??0;l([...c(),{value:Math.round((e+os)*1e3)/1e3,visible:!0}]),r.redraw([`.tcw-level-row:last-child input[type="number"]`])}),o.appendChild(d),o}var gs={text:{box:!1,border:!1,wrap:0,fontSize:14},note:{box:!0,border:!0,wrap:240,fontSize:13},callout:{box:!0,border:!0,wrap:240,fontSize:13},signpost:{box:!0,border:!0,wrap:200,fontSize:13},balloon:{box:!0,border:!0,wrap:200,fontSize:13},anchoredText:{box:!1,border:!1,wrap:0,fontSize:14},anchoredNote:{box:!0,border:!0,wrap:240,fontSize:13}},_s=new Set([`trendLine`,`ray`,`extendedLine`,`infoLine`,`trendAngle`,`arrow`,`horizontalLine`,`horizontalRay`,`verticalLine`,`rectangle`]),vs={priceLabel:`#ffffff`},ys=240,bs=40,xs=4e3,Ss=10,Cs=[`left`,`center`,`right`],ws=[`top`,`middle`,`bottom`];function Ts(e,t,n,r=!1){let i=document.createElement(`label`);i.className=`tcw-inline-check`;let a=document.createElement(`input`);if(a.type=`checkbox`,a.checked=t,a.setAttribute(`aria-label`,e),a.addEventListener(`change`,()=>n(a.checked)),i.append(a),!r){let t=document.createElement(`span`);t.textContent=e,i.append(t)}return i}function Es(e,t,n,r,i,a,o=!1){let s=us(),c=document.createElement(`textarea`);c.className=`tcw-indi-input tcw-drawing-text`,c.rows=3,c.value=t.text??``,c.addEventListener(`input`,()=>n({text:c.value}));let l=N(r(`drawingSettings.text`),c);l.classList.add(`tcw-text-row`),s.appendChild(l);let u=J(I(rs.map(e=>({value:String(e),label:`${e} px`})),String(t.fontSize??i?.fontSize??is),e=>n({fontSize:Number(e)})),r(`drawingSettings.fontSize`));s.appendChild(q(r(`drawingSettings.fontSize`),u,Ts(r(`drawingSettings.bold`),t.bold===!0,e=>n({bold:e})),Ts(r(`drawingSettings.italic`),t.italic===!0,e=>n({italic:e})))),s.appendChild(q(r(`drawingSettings.textColor`),J(F(t.textColor??a??t.color,e=>n({textColor:e})),r(`drawingSettings.textColor`)))),e.appendChild(s),i&&e.appendChild(Os(t,n,r,i)),o&&e.appendChild(Ds(t,n,r))}function Ds(e,t,n){let r=us();return r.appendChild(q(n(`drawingSettings.align`),J(I(Cs.map(e=>({value:e,label:n(`drawingSettings.align.${e}`)})),e.textAlign??`center`,e=>t({textAlign:e})),n(`drawingSettings.align`)))),r.appendChild(q(n(`drawingSettings.vAlign`),J(I(ws.map(e=>({value:e,label:n(`drawingSettings.vAlign.${e}`)})),e.textVAlign??`top`,e=>t({textVAlign:e})),n(`drawingSettings.vAlign`)))),r}function Os(e,t,n,r){let i=us();i.appendChild(q(n(`drawingSettings.align`),J(I(Cs.map(e=>({value:e,label:n(`drawingSettings.align.${e}`)})),e.textAlign??`left`,e=>t({textAlign:e})),n(`drawingSettings.align`))));let a=e.fillColor??En(e.color,ss);i.appendChild(q(n(`drawingSettings.background`),Ts(n(`drawingSettings.background`),e.textBackground??r.box,e=>t({textBackground:e}),!0),J(F(a,e=>t({fillColor:En(e,Tn(a))})),n(`drawingSettings.backgroundColor`)))),i.appendChild(q(n(`drawingSettings.border`),Ts(n(`drawingSettings.border`),e.textBorder??r.border,e=>t({textBorder:e}),!0),J(F(e.borderColor??e.color,e=>t({borderColor:e})),n(`drawingSettings.borderColor`))));let o=e.textWrap??r.wrap,s=o>0?o:r.wrap>0?r.wrap:ys,c=o>0,l=J(P(s,{min:bs,max:xs,step:Ss},e=>{s=e,c&&t({textWrap:e})}),n(`drawingSettings.wrapWidth`));return l.disabled=!c,i.appendChild(q(n(`drawingSettings.wrap`),Ts(n(`drawingSettings.wrap`),c,e=>{c=e,l.disabled=!e,t({textWrap:e?s:0})},!0),l)),i}function ks(e,n,r,i){let a=us();n.forEach((e,n)=>{let o=t.r(i(`drawingSettings.point`),{n:n+1}),s=r.toWallTime(e.time),c=document.createElement(`input`);c.type=`date`,c.className=`tcw-indi-input`,c.value=s.date;let l=document.createElement(`input`);l.type=`time`,l.className=`tcw-indi-input`,l.value=s.time;let u=()=>{let e=r.fromWallTime(c.value,l.value);e!==null&&r.move(n,{time:e})};c.addEventListener(`change`,u),l.addEventListener(`change`,u);let d=q(o,J(As(e.price,r,e=>r.move(n,{price:e})),`${o}: ${i(`drawingSettings.price`)}`),J(c,`${o}: ${i(`drawingSettings.date`)}`),J(l,`${o}: ${i(`drawingSettings.time`)}`));d.classList.add(`tcw-draw-point`),a.appendChild(d)}),e.appendChild(a)}function As(e,t,n){let r=t.roundPrice??(e=>e),i=t.priceStep?.(),a=P(r(e),{step:i!==void 0&&i>0?i:`any`},e=>{let t=r(e);a.value=String(t),n(t)});return a}var js=12,Ms=`t:`,Ns=1,Ps=class{backdrop;modal;titleEl;tabsEl;bodyEl;templateBtn;menu=null;tabButtons=[];target=null;style;options={};anchors=[];intervals=null;tab=`style`;returnFocus=null;uid=Ns++;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(!0),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow tcw-drawing-settings`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-draw-title-${this.uid}`),this.modal.tabIndex=-1,this.modal.addEventListener(`keydown`,e=>this.onKeyDown(e));let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-draw-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.close(!0)),a.append(this.titleEl,o),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-modal-tabs`,this.tabsEl.setAttribute(`role`,`tablist`),this.tabsEl.addEventListener(`keydown`,e=>this.onTabKey(e)),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`,this.bodyEl.id=`tcw-draw-panel-${this.uid}`,this.bodyEl.setAttribute(`role`,`tabpanel`),this.templateBtn=this.footerButton(`template`,`tcw-footer-menu`,()=>this.openTemplates()),this.modal.append(a,this.tabsEl,this.bodyEl,this.buildFooter()),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}buildFooter(){this.templateBtn.setAttribute(`aria-haspopup`,`menu`),this.templateBtn.setAttribute(`aria-expanded`,`false`),this.templateBtn.innerHTML=`<span></span>${O(`chevronDown`,12)}`,this.templateBtn.querySelector(`span`).textContent=this.t(`settings.template`);let e=document.createElement(`div`);e.className=`tcw-footer-end`,e.append(this.footerButton(`cancel`,`tcw-footer-cancel`,()=>this.close(!0),this.t(`common.cancel`)),this.footerButton(`ok`,`tcw-done-btn`,()=>this.close(!1),this.t(`drawingSettings.ok`)));let t=document.createElement(`div`);return t.className=`tcw-modal-footer`,t.append(this.templateBtn,e),t}open(e,t={}){this.target&&this.close(!1),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.target=e,this.style={...e.style},this.options=structuredClone(e.options),this.anchors=e.anchors.map(e=>({...e})),this.intervals=e.intervals??null,this.titleEl.textContent=e.name,this.tab=t.tab===`text`&&e.text?`text`:`style`,this.callbacks.onBegin(e.id);try{this.renderTabs(),this.renderBody()}catch(t){throw this.target=null,this.callbacks.onEnd(e.id,!0),t}this.backdrop.hidden=!1;let n=this.tab===`text`?this.bodyEl.querySelector(`textarea`):null;n?(n.focus(),n.select()):(this.tabButtons[0]??this.modal).focus()}close(e){let t=this.target;if(!t)return;let n=document.activeElement;!e&&(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&this.modal.contains(n)&&n.dispatchEvent(new Event(`change`)),this.target=null,this.menu?.close(),this.backdrop.hidden=!0,this.callbacks.onEnd(t.id,e),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null}isOpen(){return this.target!==null}editing(){return this.target?.id??null}destroy(){this.close(!0),this.menu?.destroy(),this.backdrop.remove()}tabs(){let e=this.target;return e?[`style`,...e.text?[`text`]:[],...e.coordinates!==!1&&e.anchors.length<=js?[`coordinates`]:[],`visibility`]:[]}renderTabs(){this.tabButtons=this.tabs().map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-modal-tab`,t.id=`tcw-draw-tab-${this.uid}-${e}`,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,this.bodyEl.id),t.dataset.tab=e,t.textContent=this.t(`drawingSettings.tab.${e}`),t.addEventListener(`click`,()=>this.selectTab(e)),t}),this.tabsEl.replaceChildren(...this.tabButtons),this.markTabs()}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.tab=e,this.markTabs(),this.renderBody(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=this.tabButtons.map(e=>e.dataset.tab),n=t.indexOf(this.tab),[r,i]=this.modal.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowLeft`,`ArrowRight`]:[`ArrowRight`,`ArrowLeft`],a=e.key===r?(n+1)%t.length:e.key===i?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;a<0||(e.preventDefault(),this.selectTab(t[a],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.close(!0);return}M(e,this.modal)}renderBody(){this.bodyEl.replaceChildren();let e=this.target;if(e)switch(this.tab){case`text`:Es(this.bodyEl,this.style,e=>this.setStyle(e),this.t,e.textLayout,e.textColor,e.textPlace);break;case`coordinates`:ks(this.bodyEl,this.anchors,{toWallTime:this.callbacks.toWallTime,fromWallTime:this.callbacks.fromWallTime,roundPrice:this.callbacks.roundPrice,priceStep:this.callbacks.priceStep,move:(e,t)=>this.setAnchor(e,t)},this.t);break;case`visibility`:Pa(this.bodyEl,this.intervals,e=>this.setIntervals(e),this.t);break;default:ds(this.bodyEl,{style:()=>this.style,options:()=>this.options,defs:e.defs,fill:e.fill},{style:e=>this.setStyle(e),options:e=>this.setOptions(e),redraw:(e=[])=>{this.renderBody();for(let t of e){let e=this.bodyEl.querySelector(t);if(e){e.focus();break}}}},this.t)}}change(e){this.target&&this.callbacks.onChange(this.target.id,e)}setStyle(e){this.target&&(this.style={...this.style,...e},this.change({style:e}))}setOptions(e){this.target&&(this.options={...this.options,...structuredClone(e)},this.change({options:e}))}setAnchor(e,t){this.target&&(this.anchors=this.anchors.map((n,r)=>r===e?{...n,...t}:n),this.change({anchors:this.anchors.map(e=>({...e}))}))}setIntervals(e){this.target&&(this.intervals=e,this.change({intervals:e}))}openTemplates(){let e=this.target;if(!e)return;if(this.menu?.isOpen()){this.menu.close();return}let n=this.callbacks.templates,r=n?.list(e.type)??[],i=[...r.map((e,n)=>({id:`${Ms}${n}`,label:e.name,icon:`layers`,remove:t.r(this.t(`templates.delete`),{name:e.name})})),...r.length>0?[`separator`]:[],...n?[{id:`save`,label:this.t(`settings.saveTemplate`),icon:`save`}]:[],...this.callbacks.onSaveDefault?[{id:`default`,label:this.t(`drawingSettings.saveDefault`),icon:`pin`}]:[],{id:`reset`,label:this.t(`settings.resetToDefaults`),icon:`reset`}],a=e=>r[Number(e.slice(2))];this.menu??=new A(this.modal,this.t(`settings.template`));let o=this.templateBtn.getBoundingClientRect(),s=this.modal.getBoundingClientRect();this.menu.open(i,o.left-s.left,o.top-s.top,t=>{t===`save`?n?.save({type:e.type,style:{...this.style},options:structuredClone(this.options)}):t===`default`?this.callbacks.onSaveDefault?.(e.type,structuredClone(this.options)):t===`reset`?this.resetOptions():t.startsWith(Ms)&&this.applyTemplate(a(t))},this.templateBtn,e=>{let t=a(e);t&&n?.remove(t.name,t.type)})}applyTemplate(e){let t=this.target;!e||!t||(Object.keys(e.style).length>0&&this.setStyle(e.style),e.options&&this.setOptions((0,n.sanitizeDrawingOptions)(t.defs,e.options)),this.renderBody())}resetOptions(){let e=this.target;if(!e)return;let t={};for(let[n,r]of Object.entries(e.defs))t[n]=structuredClone(r.default);this.setOptions(t),this.renderBody()}footerButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=t,i.dataset.act=e,r&&(i.textContent=r),i.addEventListener(`click`,n),i}},Fs=8,Is=6,Ls=1.3,Rs=120,zs=229,Bs=500,Vs=8,Hs=400,Us=class{wrap=null;area=null;target=null;frame=0;done=!0;openedAt=0;offSince=0;onPressAway=e=>{if(!(!this.area||e.target===this.area)){if(this.area.value===this.target?.text&&performance.now()-this.openedAt<Bs){e.preventDefault(),e.stopPropagation();return}this.finish(!0,!1)}};constructor(e){this.layer=e}isOpen(){return this.area!==null}open(e){this.area&&this.finish(!0,!1);let t=e.rect();if(!t)return!1;this.target=e,this.done=!1;let n=document.createElement(`div`);n.className=`tcw-inline-text`;let r=document.createElement(`textarea`);r.className=`tcw-inline-text-input`,r.value=e.text,r.rows=1,r.spellcheck=!1,r.setAttribute(`aria-label`,e.label);let{size:i,bold:a,italic:o,family:s}=e.font;return Object.assign(r.style,{fontSize:`${i}px`,fontWeight:a?`bold`:`normal`,fontStyle:o?`italic`:`normal`,fontFamily:s,lineHeight:String(Ls),color:e.color,padding:`${Is}px ${Fs}px`}),r.addEventListener(`input`,()=>{this.fit(),this.target?.onInput(r.value);let e=this.target?.rect();e&&this.place(e)}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),!(e.isComposing||e.keyCode===zs)&&(e.key===`Escape`?(e.preventDefault(),this.finish(!1,!0)):e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.finish(!0,!0)))}),r.addEventListener(`blur`,()=>this.finish(!0,!1)),n.appendChild(r),this.layer().appendChild(n),this.wrap=n,this.area=r,this.place(t),this.fit(),r.focus(),r.select(),this.openedAt=performance.now(),this.offSince=0,document.addEventListener(`pointerdown`,this.onPressAway,!0),document.addEventListener(`mousedown`,this.onPressAway,!0),this.follow(),!0}commit(){this.finish(!0,!1)}close(){this.done=!0,this.teardown()}finish(e,t){if(this.done||!this.area||!this.target)return;this.done=!0;let n=this.area.value,r=this.target;this.teardown(),e?r.onCommit(n):r.onCancel(),t&&r.returnFocus?.()?.focus({preventScroll:!0})}teardown(){document.removeEventListener(`pointerdown`,this.onPressAway,!0),document.removeEventListener(`mousedown`,this.onPressAway,!0),cancelAnimationFrame(this.frame),this.frame=0,this.wrap?.remove(),this.wrap=null,this.area=null,this.target=null}place(e){let t=this.area;if(!t)return;let n=Math.max(Rs,window.innerWidth-Vs*2);t.style.maxWidth=`${n}px`,t.style.width=`${Math.min(n,Math.max(Rs,e.width))}px`,t.style.minHeight=`${e.height}px`;let r=t.offsetWidth||Math.max(Rs,e.width),i=t.offsetHeight||e.height;t.style.left=`${Math.max(Vs,Math.min(e.x,window.innerWidth-Vs-r))}px`,t.style.top=`${Math.max(Vs,Math.min(e.y,window.innerHeight-Vs-i))}px`}offWindow(e){return e.x>window.innerWidth||e.x+e.width<0||e.y>window.innerHeight||e.y+e.height<0}fit(){let e=this.area;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)}follow(){this.frame=requestAnimationFrame(()=>{if(!this.target||this.done)return;let e=this.target.rect(),t=e!==null&&this.offWindow(e);if(t?this.offSince===0&&(this.offSince=performance.now()):this.offSince=0,!e||t&&performance.now()-this.offSince>Hs){this.finish(!0,!1);return}this.place(e),this.follow()})}};function Ws(e,t){let{selected:n}=e,r=n.length===1,i=new Set(n.map(e=>e.groupId)),a=i.size===1&&!i.has(null),o=[];e.canConfigure&&r&&o.push({id:`settings`,label:t(`drawingMenu.settings`),icon:`settings`}),e.canAlert&&r&&o.push({id:`alert`,label:t(`drawingSettings.addAlert`),icon:`bell`}),o.length>0&&o.push(`separator`),r&&o.push({id:`front`,label:t(`drawingMenu.front`)},{id:`forward`,label:t(`drawingMenu.forward`)},{id:`backward`,label:t(`drawingMenu.backward`)},{id:`back`,label:t(`drawingMenu.back`)},`separator`),n.length>1&&!a&&o.push({id:`group`,label:t(`drawingMenu.group`),icon:`layers`}),n.some(e=>e.groupId)&&o.push({id:`ungroup`,label:t(`drawingMenu.ungroup`),icon:`layers`});let s=n.every(e=>e.locked);return o.push(s?{id:`unlock`,label:t(`common.unlock`),icon:`unlock`}:{id:`lock`,label:t(`common.lock`),icon:`lock`},{id:`hide`,label:t(`common.hide`),icon:`eyeOff`}),r&&o.push({id:`duplicate`,label:t(`drawingMenu.duplicate`),icon:`plus`}),s||o.push(`separator`,{id:`delete`,label:t(`drawingMenu.delete`),icon:`trash`,danger:!0}),o}var Gs=[{id:`regularScale`,mode:`regular`,label:`settings.scale.regular`},{id:`logScale`,mode:`logarithmic`,label:`settings.scale.logarithmic`},{id:`percentScale`,mode:`percentage`,label:`settings.scale.percentage`},{id:`indexedScale`,mode:`indexedTo100`,label:`settings.scale.indexedTo100`}],Ks=[{action:`resetView`,keys:`Alt+R`,feature:`hotkeys.resetView`},{action:`invertScale`,keys:`Alt+I`,feature:`hotkeys.invertScale`},{action:`goToDate`,keys:`Alt+G`,feature:`hotkeys.goToDate`}];function qs(e){return Gs.find(t=>t.id===e)?.mode}function Js(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function Ys(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function Xs(e,n){if(e.price===void 0||!Number.isFinite(e.price))return[];let r=e.formatPrice(e.price),i=[];if(e.canAlert&&i.push({id:`alert`,label:t.r(n(`chartMenu.addAlert`),{price:r}),icon:`bell`}),e.canTrade){let a=e.lastPrice===null||e.price<=e.lastPrice;i.push(a?{id:`buyLimit`,label:t.r(n(`chartMenu.buyLimit`),{price:r}),icon:`trendingUp`}:{id:`buyStop`,label:t.r(n(`chartMenu.buyStop`),{price:r}),icon:`trendingUp`},a?{id:`sellStop`,label:t.r(n(`chartMenu.sellStop`),{price:r}),icon:`trendingDown`}:{id:`sellLimit`,label:t.r(n(`chartMenu.sellLimit`),{price:r}),icon:`trendingDown`}),e.canOrderTicket&&i.push({id:`orderTicket`,label:n(`chartMenu.orderTicket`),icon:`receipt`})}return e.canDraw&&i.push({id:`horizontalLine`,label:t.r(n(`chartMenu.horizontalLine`),{price:r}),icon:`minus`}),i}var Zs=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function Qs(e,t){let n=[Ys({id:`resetView`,label:t(`chartMenu.resetView`)},e)];e.canPaste&&n.push({id:`paste`,label:t(`chartMenu.paste`)});let r=[];e.hasDrawings&&r.push(e.drawingsHidden?{id:`showDrawings`,label:t(`chartMenu.showDrawings`),icon:`eye`}:{id:`hideDrawings`,label:t(`chartMenu.hideDrawings`),icon:`eyeOff`},{id:`removeDrawings`,label:t(`chartMenu.removeDrawings`),icon:`trash`,danger:!0}),e.hasIndicators&&r.push({id:`removeIndicators`,label:t(`chartMenu.removeIndicators`),icon:`trash`,danger:!0});let i=e.canExport?[{id:`exportData`,label:t(`chartMenu.exportData`),icon:`save`}]:[];return Js(Xs(e,t),n,r,[...i,Zs(t)])}function $s(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},Ys({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=Gs.filter(t=>t.mode!==`logarithmic`||e.canLog).map(n=>({id:n.id,label:t(n.label),radio:!0,checked:e.scaleMode===n.mode})),i=[{id:`indicatorValueLabels`,label:t(`settings.indicatorValues`),checked:e.labels.values},{id:`alignAxisLabels`,label:t(`settings.alignAxisLabels`),checked:e.labels.aligned}];e.labels.countdown!==void 0&&i.push({id:`barCountdown`,label:t(`settings.barCountdown`),checked:e.labels.countdown});let a=[{id:`highLowLines`,label:t(`settings.highLowLines`),checked:e.lines.highLow},{id:`lastPriceLine`,label:t(`chartMenu.lastPriceLine`),checked:e.lines.lastPrice}];return Js(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],Xs({...e,canTrade:!1,canDraw:!1},t),[Zs(t)])}function ec(e,t){let n=[Ys({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(Ys({id:`goToDate`,label:t(`chartMenu.goToDate`),icon:`calendar`},e));let r=e.timezone.options.map(t=>({id:`tz:${t.value}`,label:t.label,radio:!0,checked:t.value===e.timezone.current}));return Js(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function tc(e,t){let n=e.pane?[{id:`paneLog`,label:t(`chartMenu.paneLog`),checked:e.pane.log},{id:`paneInvert`,label:t(`chartMenu.paneInvert`),checked:e.pane.invert},{id:`panePercent`,label:t(`chartMenu.panePercent`),checked:e.pane.percent}]:[];return Js([Ys({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[Zs(t)])}function nc(e,t,n){switch(e){case`priceAxis`:return $s(t,n);case`timeAxis`:return ec(t,n);case`pane`:return tc(t,n);default:return Qs(t,n)}}var rc=/^[-+−]/;function ic(e,t,n){let r=e.replace(rc,``);return r===n.replace(rc,``)?r:t>0?`+${r}`:t<0?`-${r}`:r}function ac(e){return e.startsWith(`+`)?`up`:e.startsWith(`-`)?`down`:null}var oc=[`positions`,`orders`,`history`],sc=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],cc=[`market`,`limit`,`stop`],lc=[`gtc`,`day`],uc=`—`,dc=`{pnl}`,fc=3;function pc(e,t,n){return e.includes(t??``)?t:n}function mc(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function hc(e,t){if(t===null)return null;let n=e.quantity-(e.closedQuantity??0),r=e.side===`buy`?1:-1;return{pnl:(t-e.entryPrice)*n*r,pct:e.entryPrice===0?0:(t-e.entryPrice)/e.entryPrice*100*r}}function gc(e){let t=document.createElement(`span`);return t.dir=`ltr`,t.textContent=e,t}function _c(e){let t=ac(e);return t?`tcw-account-${t}`:``}var vc=class{el;tabButtons=new Map;tabLabels=new Map;tabCounts=new Map;totalsEl;content;tab=`positions`;snapshot={positions:[],orders:[],fills:[],price:null};open=!1;live=[];constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.el=document.createElement(`section`),this.el.className=`tcw-account`,this.el.hidden=!0,this.el.setAttribute(`aria-label`,this.t(`account.title`));let i=document.createElement(`div`);i.className=`tcw-account-head`;let a=document.createElement(`div`);a.className=`tcw-account-tabs`,a.setAttribute(`role`,`tablist`),a.addEventListener(`keydown`,e=>this.onTabKey(e));for(let e of oc){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-account-tab`,t.setAttribute(`role`,`tab`),t.id=`tcw-account-tab-${e}`;let n=document.createElement(`span`);n.className=`tcw-account-tab-label`,n.textContent=this.t(`account.${e}`);let r=document.createElement(`span`);r.className=`tcw-account-count`,t.append(n,r),t.addEventListener(`click`,()=>this.selectTab(e)),this.tabButtons.set(e,t),this.tabLabels.set(e,n.textContent),this.tabCounts.set(e,r),a.appendChild(t)}this.totalsEl=document.createElement(`div`),this.totalsEl.className=`tcw-account-totals`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-account-new`,D(o,`orderTicket`),o.innerHTML=O(`plus`,13),o.append(this.t(`account.newOrder`)),o.addEventListener(`click`,()=>this.callbacks.onNewOrder());let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-tree-close`,s.setAttribute(`aria-label`,this.t(`account.close`)),s.innerHTML=O(`x`,14),s.addEventListener(`click`,()=>this.closePanel()),i.append(a,this.totalsEl,o,s),this.content=document.createElement(`div`),this.content.className=`tcw-account-body`,this.content.setAttribute(`role`,`tabpanel`),this.el.append(i,this.content),e.appendChild(this.el),this.renderTabs()}isOpen(){return this.open}toggle(){this.open?this.closePanel():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}closePanel(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}update(e){let t=this.snapshot;if(this.snapshot=e,mc(t.positions,e.positions)&&mc(t.orders,e.orders)&&mc(t.fills,e.fills)&&t.realisedPnl===e.realisedPnl){t.price!==e.price&&(this.renderTotals(),this.open&&this.tab===`positions`&&this.patchPrices());return}this.renderTabs(),this.open&&this.render()}destroy(){this.el.remove()}selectTab(e){this.tab=e,this.renderTabs(),this.render()}onTabKey(e){let t=oc.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=oc[(n+oc.length)%oc.length];this.selectTab(r),this.tabButtons.get(r)?.focus()}renderTabs(){let e={positions:this.snapshot.positions.length,orders:this.snapshot.orders.length,history:this.snapshot.fills.length};for(let[t,n]of this.tabButtons){let r=t===this.tab;this.tabCounts.get(t).textContent=String(e[t]),n.setAttribute(`aria-label`,`${this.tabLabels.get(t)} (${e[t]})`),n.setAttribute(`aria-selected`,String(r)),n.tabIndex=r?0:-1,r&&this.content.setAttribute(`aria-labelledby`,n.id)}this.renderTotals()}renderTotals(){let{positions:e,price:t,fills:n,realisedPnl:r}=this.snapshot,i=[],a=e.reduce((e,n)=>{let r=hc(n,t);return r===null?e:(e??0)+r.pnl},null);a!==null&&i.push(this.total(`account.openPnl`,a)),(n.length>0||r!==void 0&&r!==0)&&i.push(this.total(`account.realised`,r??n.reduce((e,t)=>e+(t.pnl??0),0))),this.totalsEl.replaceChildren(...i)}total(e,t){let n=document.createElement(`span`),r=this.amount(t);n.className=`tcw-account-total ${_c(r)}`.trim();let i=this.t(e),a=i.indexOf(dc),o=gc(r);return a<0?n.append(`${i} `,o):n.append(i.slice(0,a),o,i.slice(a+5)),n}render(){let e=document.activeElement,t=e instanceof HTMLElement&&this.content.contains(e)?e.dataset.focusKey:void 0;this.live=[],this.tab===`positions`?this.renderPositions():this.tab===`orders`?this.renderOrders():this.renderHistory(),t&&[...this.content.querySelectorAll(`[data-focus-key]`)].find(e=>e.dataset.focusKey===t)?.focus()}patchPrices(){let{price:e}=this.snapshot;for(let t of this.live)t.price.textContent=e===null?uc:this.callbacks.formatPrice(e),this.writePnl(t.pnl,hc(t.position,e))}amount(e){return ic(this.money(Math.abs(e)),e,this.money(0))}money(e){return this.callbacks.formatAmount?this.callbacks.formatAmount(e):e.toFixed(2)}percent(e){let t=e=>this.callbacks.formatNumber?this.callbacks.formatNumber(e,2):e.toFixed(2);return`${ic(t(Math.abs(e)),e,t(0))}%`}writePnl(e,t){if(t===null){e.className=``,e.textContent=uc;return}let n=this.amount(t.pnl);e.className=_c(n),e.textContent=`${n} · ${this.percent(t.pct)}`}table(e,t,n){if(t.length===0){let e=document.createElement(`p`);return e.className=`tcw-account-empty`,e.textContent=this.t(n),this.content.replaceChildren(e),null}let r=e.map(e=>e.key?this.t(e.key):``),i=document.createElement(`table`);i.className=`tcw-account-table`,i.setAttribute(`role`,`table`);let a=i.createTHead().insertRow();a.setAttribute(`role`,`row`),e.forEach((e,t)=>{let n=document.createElement(`th`);n.scope=`col`,n.setAttribute(`role`,`columnheader`),n.textContent=r[t],e.num&&(n.className=`tcw-num`),a.appendChild(n)});let o=i.createTBody();for(let n of t){let t=o.insertRow();t.setAttribute(`role`,`row`),n.forEach((n,i)=>{let a=t.insertCell();a.setAttribute(`role`,`cell`),a.dataset.label=r[i],e[i].num&&(a.className=`tcw-num`),typeof n==`string`?a.textContent=n:a.appendChild(n)})}return this.content.replaceChildren(i),i}sideCell(e,t=`position`){let n=document.createElement(`span`);return n.className=`tcw-account-side tcw-account-${e}`,n.textContent=this.sideText(e,t),n}sideText(e,t){return t===`trade`?this.t(e===`buy`?`ticket.buy`:`ticket.sell`):this.t(e===`buy`?`account.long`:`account.short`)}actions(...e){let t=document.createElement(`div`);t.className=`tcw-account-actions`;for(let n of e){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-btn${n.danger?` tcw-tree-del`:``}`,e.setAttribute(`aria-label`,n.label),e.title=n.label,e.dataset.focusKey=n.key,e.innerHTML=O(n.icon,14),e.addEventListener(`click`,n.run),t.appendChild(e)}return t}price(e){return e===void 0?uc:this.callbacks.formatPrice(e)}renderPositions(){let{formatPrice:e}=this.callbacks,{price:t}=this.snapshot,n=[],r=this.snapshot.positions.map(r=>{let i=r.quantity-(r.closedQuantity??0),a=gc(``);this.writePnl(a,hc(r,t)),n.push(a);let o=`${this.sideText(r.side,`position`)} ${i} @ ${e(r.entryPrice)}`;return[this.sideCell(r.side),String(i),e(r.entryPrice),t===null?uc:e(t),a,this.price(r.stopLoss),this.price(r.takeProfit),this.actions({icon:`arrowUpDown`,label:`${this.t(`account.reverse`)}: ${o}`,key:`reverse:${r.id}`,run:()=>this.callbacks.onReversePosition(r.id)},{icon:`x`,label:`${this.t(`account.closePosition`)}: ${o}`,key:`close:${r.id}`,run:()=>this.callbacks.onClosePosition(r.id),danger:!0})]}),i=this.table([{key:`account.side`},{key:`account.quantity`,num:!0},{key:`account.entry`,num:!0},{key:`account.price`,num:!0},{key:`account.pnl`,num:!0},{key:`account.stopLoss`,num:!0},{key:`account.takeProfit`,num:!0},{key:null}],r,`account.noPositions`);if(!i)return;let a=[...i.tBodies[0].rows];this.snapshot.positions.forEach((e,t)=>this.live.push({position:e,price:a[t].cells[fc],pnl:n[t]}))}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=pc(cc,t.type===`stopLimit`?`stop`:t.type,`limit`),r=`${this.sideText(t.side,`trade`)} ${t.quantity} @ ${e(t.price)}`;return[this.sideCell(t.side,`trade`),this.t(`ticket.type.${n}`),String(t.quantity),e(t.price),this.price(t.stopLoss),this.price(t.takeProfit),t.timeInForce?this.t(`ticket.tif.${pc(lc,t.timeInForce,`gtc`)}`):uc,this.actions({icon:`x`,label:`${this.t(`account.cancelOrder`)}: ${r}`,key:`cancel:${t.id}`,run:()=>this.callbacks.onCancelOrder(t.id),danger:!0})]});this.table([{key:`account.side`},{key:`ticket.type`},{key:`account.quantity`,num:!0},{key:`account.price`,num:!0},{key:`account.stopLoss`,num:!0},{key:`account.takeProfit`,num:!0},{key:`ticket.timeInForce`},{key:null}],t,`account.noOrders`)}renderHistory(){let{formatPrice:e,formatTime:t}=this.callbacks,n=[...this.snapshot.fills].reverse().map(n=>{let r=gc(``);return n.pnl===void 0?r.textContent=uc:(r.textContent=this.amount(n.pnl),r.className=_c(r.textContent)),[t(n.time),this.sideCell(n.side,`trade`),String(n.quantity),e(n.price),this.t(`account.reason.${pc(sc,n.reason,`order`)}`),r]});this.table([{key:`account.time`},{key:`account.side`},{key:`account.quantity`,num:!0},{key:`account.price`,num:!0},{key:`account.reason`},{key:`account.pnl`,num:!0}],n,`account.noFills`)}},yc=1e-9;function bc(e,t){return e.type===`market`?t:e.price}function xc(e,t,n={}){let r=[];(!(e.quantity>0)||!Number.isFinite(e.quantity))&&r.push(`quantity`),e.type!==`market`&&(!(e.price>0)||!Number.isFinite(e.price))&&r.push(`price`),e.type===`market`&&!((t??e.price)>0)&&r.push(`market`);let i=e.side===`buy`;if(t!==null&&e.type!==`market`&&e.price>0){let n=e.price<t;e.type===`limit`&&n!==i&&e.price!==t&&r.push(`limitSide`),e.type===`stop`&&n===i&&e.price!==t&&r.push(`stopSide`)}let a=e=>e===null||Number.isFinite(e)&&e>0;a(e.stopLoss)||r.push(`stopLoss`),a(e.takeProfit)||r.push(`takeProfit`);let o=bc(e,t);return o!==null&&o>0&&(e.stopLoss!==null&&a(e.stopLoss)&&(i?e.stopLoss>=o:e.stopLoss<=o)&&r.push(`stopLossSide`),e.takeProfit!==null&&a(e.takeProfit)&&(i?e.takeProfit<=o:e.takeProfit>=o)&&r.push(`takeProfitSide`)),[...r,...Sc(e,n)]}function Sc(e,t){let n=[],r=e.type===`market`?null:e.price,i=[r,e.stopLoss,e.takeProfit].filter(e=>e!==null&&Number.isFinite(e)&&e>0),{roundPrice:a,limits:o,lot:s}=t;return a&&i.some(e=>Math.abs(a(e)-e)>yc)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+yc||r<o.floor-yc)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function Cc(e,t){let n={side:e.side,type:e.type,price:e.type===`market`?t??e.price:e.price,quantity:e.quantity};return e.type===`stop`&&(n.stopPrice=e.price),e.type!==`market`&&(n.timeInForce=e.timeInForce),e.stopLoss!==null&&(n.stopLoss=e.stopLoss),e.takeProfit!==null&&(n.takeProfit=e.takeProfit),n}function wc(e,t){let n=bc(e,t);if(n===null||e.stopLoss===null||e.takeProfit===null)return null;let r=Math.abs(n-e.stopLoss);return r>0?Math.abs(e.takeProfit-n)/r:null}function Tc(e,t,n,r=1){let i=bc(e,t);if(i===null||!(i>0)||!Number.isFinite(n)||!(e.quantity>0))return null;let a=e.side===`buy`?1:-1;return{pct:(n-i)/i*100*a,amount:(n-i)*e.quantity*a*r}}function Ec(e,t,n={}){let r=n.multiplier!==void 0&&n.multiplier>0?n.multiplier:1,i=bc(e,t),a=i!==null&&i>0&&e.quantity>0?i*e.quantity*r:null,o=xc(e,t),s=(n,i)=>n===null||o.includes(i)?null:Tc(e,t,n,r)?.amount??null,c=s(e.stopLoss,`stopLossSide`),l=s(e.takeProfit,`takeProfitSide`);return{value:a,risk:c,reward:l,ratio:c!==null&&l!==null?wc(e,t):null}}var Dc=229,Oc=1,kc=2,Ac=.999999999,jc=0,Mc=class{backdrop;modal;symbolEl;body;summaryEl;problemsEl;submit;draft=null;lastPrice=null;rules={};step=Pc;round=e=>Fc(e,e);typed=new Map;returnFocus=null;uid=++jc;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-order-ticket`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-ticket-title-${this.uid}`),this.modal.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&!e.isComposing&&e.keyCode!==Dc){e.stopPropagation(),this.close();return}M(e,this.modal)});let a=document.createElement(`div`);a.className=`tcw-modal-header`;let o=document.createElement(`div`);o.className=`tcw-ticket-heading`;let s=document.createElement(`h3`);s.id=`tcw-ticket-title-${this.uid}`,s.textContent=this.t(`ticket.title`),this.symbolEl=document.createElement(`span`),this.symbolEl.className=`tcw-ticket-symbol`,o.append(s,this.symbolEl);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-modal-close`,c.setAttribute(`aria-label`,this.t(`common.close`)),c.innerHTML=O(`x`,16),c.addEventListener(`click`,()=>this.close()),a.append(o,c),this.body=document.createElement(`div`),this.body.className=`tcw-modal-body tcw-ticket-body`,this.summaryEl=document.createElement(`div`),this.summaryEl.className=`tcw-ticket-summary`,this.problemsEl=document.createElement(`div`),this.problemsEl.className=`tcw-ticket-problems`,this.problemsEl.setAttribute(`aria-live`,`polite`);let l=document.createElement(`div`);l.className=`tcw-modal-footer`;let u=document.createElement(`button`);u.type=`button`,u.className=`tcw-footer-cancel`,u.textContent=this.t(`common.cancel`),u.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`button`,this.submit.className=`tcw-ticket-place`,this.submit.addEventListener(`click`,()=>this.place());let d=document.createElement(`div`);d.className=`tcw-footer-end`,d.append(u,this.submit),l.append(d),this.modal.append(a,this.body,this.summaryEl,this.problemsEl,l),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.lastPrice=e.lastPrice,this.rules=e.rules??{},this.step=e.step??Pc,this.round=e.round??(e=>Fc(e,e)),this.typed.clear(),this.symbolEl.textContent=e.symbol??``;let t=this.round(e.price??e.lastPrice??0),n=e.side??`buy`,r=`market`;e.price!==void 0&&e.lastPrice!==null&&t!==e.lastPrice&&(r=t<e.lastPrice==(n===`buy`)?`limit`:`stop`),this.draft={side:n,type:r,quantity:this.lot(),price:t,stopLoss:null,takeProfit:null,timeInForce:`gtc`},this.problemsEl.replaceChildren(),this.render(),this.backdrop.hidden=!1,this.body.querySelector(`button[aria-pressed="true"]`)?.focus()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.draft=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}setLastPrice(e){if(!this.draft||e===this.lastPrice)return;this.lastPrice=e;let t=this.body.querySelector(`.tcw-ticket-market`);t&&(t.textContent=this.marketText()),this.check()}destroy(){this.close(),this.backdrop.remove()}lot(){return this.rules.lot!==void 0&&this.rules.lot>1?this.rules.lot:1}quantityStep(e){if(this.rules.lot!==void 0&&this.rules.lot>1)return this.rules.lot;let t=Number.isFinite(e)?(0,n.stepDecimals)(e):0;return t>0?Number((10**-t).toFixed(t)):1}priceStep(e,t){return this.step(t>0?e:e*Ac)}writePrice(e){return Number.isFinite(e)?this.step===Pc?String(e):e.toFixed((0,n.stepDecimals)(this.step(e))):``}place(){let e=this.draft;!e||xc(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(Cc(e,this.lastPrice)),this.close())}set(e,t=!1){this.draft&&(this.draft={...this.draft,...e},t?this.render():this.check())}render(){let e=this.draft;if(!e)return;let t=this.focusedField();if(this.modal.dataset.side=e.side,this.body.replaceChildren(this.sideToggle(e.side),this.row(`ticket.type`,this.choices(`type`,[`market`,`limit`,`stop`],e.type,`ticket.type`,e=>this.set({type:e},!0))),this.row(`ticket.quantity`,this.stepped(`quantity`,e.quantity,e=>this.quantityStep(e),()=>this.lot(),String,e=>this.set({quantity:e})))),e.type===`market`){let e=document.createElement(`span`);e.className=`tcw-ticket-market`,e.textContent=this.marketText(),this.body.append(this.row(`ticket.price`,e))}else this.body.append(this.row(`ticket.price`,this.priceField(`price`,e.price,e=>this.set({price:e}))),this.row(`ticket.timeInForce`,this.choices(`timeInForce`,[`gtc`,`day`],e.timeInForce,`ticket.timeInForce`,e=>this.set({timeInForce:e}))));this.body.append(this.optionalPrice(`stopLoss`,e.stopLoss),this.optionalPrice(`takeProfit`,e.takeProfit)),t&&this.body.querySelector(t)?.focus(),this.check()}focusedField(){let e=document.activeElement;if(!(e instanceof HTMLElement)||!this.body.contains(e))return null;let t=e.dataset.ticketField;return t?`[data-ticket-field="${t}"]`:null}row(e,t){let n=document.createElement(`div`);n.className=`tcw-settings-row tcw-ticket-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=this.t(e),n.append(r,t),n}choices(e,t,n,r,i){let a=e===`type`?`ticket.type`:`ticket.tif`,o=Nc(e,On(t.map(e=>({value:e,label:this.t(`${a}.${e}`)})),n,i,this.t(r)));for(let t of o.querySelectorAll(`[role=radio]`))t.dataset.ticketField=`${e}-${t.dataset.value}`;return o}marketText(){let e=this.t(`ticket.type.market`);return this.lastPrice===null?e:`${e} · ${this.callbacks.formatPrice(this.lastPrice)}`}typeFor(e,t){return e.type===`market`||this.lastPrice===null||!(e.price>0)||e.price===this.lastPrice?e.type:e.price<this.lastPrice==(t===`buy`)?`limit`:`stop`}sideToggle(e){let t=document.createElement(`div`);t.className=`tcw-ticket-side`,t.setAttribute(`role`,`group`),t.setAttribute(`aria-label`,`${this.t(`ticket.buy`)} / ${this.t(`ticket.sell`)}`);for(let n of[`buy`,`sell`]){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-ticket-side-btn tcw-ticket-${n}`,r.textContent=this.t(`ticket.${n}`),r.setAttribute(`aria-pressed`,String(e===n)),r.dataset.ticketField=`side-${n}`,r.addEventListener(`click`,()=>{let e=this.draft;!e||e.side===n||this.set({side:n,type:this.typeFor(e,n)},!0)}),t.appendChild(r)}return t}priceField(e,t,n){return this.stepped(e,t,(e,t)=>this.priceStep(e,t),()=>this.lastPrice??this.draft?.price??0,e=>this.writePrice(e),n)}stepped(e,n,r,i,a,o){let s=Nc(e,document.createElement(`input`));s.type=`number`,s.className=`tcw-indi-input`,s.step=`any`,s.min=`0`,s.value=this.typed.get(e)??a(n);let c=this.t(`ticket.${e}`);s.setAttribute(`aria-label`,c),s.addEventListener(`input`,()=>{this.typed.set(e,s.value),o(s.value.trim()===``?NaN:Number(s.value))});let l=An(s,{step:r,fallback:i,format:a,labels:{down:t.r(this.t(`ticket.stepDown`),{field:c}),up:t.r(this.t(`ticket.stepUp`),{field:c})}});return l.down.dataset.ticketField=`${e}-down`,l.up.dataset.ticketField=`${e}-up`,l.element}optionalPrice(e,t){let n=e===`stopLoss`?`ticket.stopLoss`:`ticket.takeProfit`,r=document.createElement(`div`);r.className=`tcw-settings-row tcw-ticket-optional`;let i=Sn(t!==null,t=>{this.typed.delete(e),this.set({[e]:t?this.startOf(e):null},!0)});i.setAttribute(`aria-label`,this.t(n)),i.dataset.ticketField=`${e}-switch`;let a=document.createElement(`div`);a.className=`tcw-ticket-optional-name`;let o=document.createElement(`span`);if(o.className=`tcw-settings-label`,o.textContent=this.t(n),a.appendChild(o),r.append(i,a),t!==null){let n=document.createElement(`span`);n.className=`tcw-ticket-away`,n.dataset.for=e,n.dir=`ltr`,a.appendChild(n),r.appendChild(this.priceField(e,t,t=>this.set({[e]:Number.isFinite(t)?t:NaN})))}return r}startOf(e){let t=this.draft;if(!t)return NaN;let n=t.type===`market`?this.lastPrice??t.price:t.price;if(!(n>0))return NaN;let r=e===`stopLoss`?-Oc:kc;return this.round(n*(1+(t.side===`buy`?r:-r)/100))}check(){let e=this.draft;if(!e)return;let t=xc(e,this.lastPrice,this.rules),n=t.map(e=>this.problemText(e));n.join(`
|
|
7733
7733
|
`)!==[...this.problemsEl.children].map(e=>e.textContent).join(`
|
|
7734
|
-
`)&&this.problemsEl.replaceChildren(...n.map(e=>{let t=document.createElement(`p`);return t.textContent=e,t}));for(let t of[`stopLoss`,`takeProfit`]){let n=this.body.querySelector(`.tcw-ticket-away[data-for="${t}"]`),r=e[t],i=r===null?null:Tc(e,this.lastPrice,r,this.rules.multiplier);n&&(n.textContent=i?`${this.signedNumber(i.pct,2)}% · ${this.amount(i.amount)}`:``)}this.renderSummary(e),this.submit.disabled=t.length>0,this.submit.textContent=this.t(e.side===`buy`?`ticket.placeBuy`:`ticket.placeSell`)}renderSummary(e){let t=Ec(e,this.lastPrice,this.rules),n=t.risk===null?null:this.amount(t.risk),r=t.reward===null?null:this.amount(t.reward),i=[[`value`,`ticket.value`,t.value===null?null:this.money(t.value),null],[`risk`,`ticket.risk`,n,n===null?null:ac(n)],[`reward`,`ticket.reward`,r,r===null?null:ac(r)],[`ratio`,`ticket.rewardRisk`,t.ratio===null?null:this.number(t.ratio,2),null]];this.summaryEl.replaceChildren(...i.filter(([,,e])=>e!==null).map(([e,t,n,r])=>{let i=document.createElement(`div`);i.className=`tcw-ticket-summary-row`,i.dataset.row=e;let a=document.createElement(`span`);a.textContent=this.t(t);let o=document.createElement(`span`);return o.className=`tcw-ticket-figure${r?` tcw-ticket-${r}`:``}`,o.dir=`ltr`,o.textContent=n,i.append(a,o),i}))}number(e,t){return this.callbacks.formatNumber?this.callbacks.formatNumber(e,t):e.toFixed(t)}signedNumber(e,t){return ic(this.number(Math.abs(e),t),e,this.number(0,t))}amount(e){return ic(this.money(Math.abs(e)),e,this.money(0))}money(e){return(this.callbacks.formatAmount??this.callbacks.formatPrice)(e)}problemText(e){let n=this.t(`ticket.problem.${e}`),{limits:r,lot:i}=this.rules;return e===`priceLimits`&&r?t.r(n,{floor:this.callbacks.formatPrice(r.floor),ceiling:this.callbacks.formatPrice(r.ceiling)}):e===`lot`?t.r(n,{lot:i??1}):n}};function Nc(e,t){return t.dataset.ticketField=e,t}function Pc(e){let t=Math.abs(e);return t>0?10**Math.floor(Math.log10(t/100)):1}function Fc(e,t){let n=Math.abs(t),r=n>=10||n===0?2:n>=1?4:Math.min(10,Math.ceil(-Math.log10(n))+3);return Number(e.toFixed(r))}var Ic=0,Lc=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++Ic;constructor(e,n=t.t){this.t=n,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let r=!1;this.backdrop.addEventListener(`pointerdown`,e=>{r=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&r&&this.close(),r=!1});let i=document.createElement(`form`);i.className=`tcw-modal tcw-modal-narrow tcw-name-prompt`,i.noValidate=!0,i.setAttribute(`role`,`dialog`),i.setAttribute(`aria-modal`,`true`),i.setAttribute(`aria-labelledby`,`tcw-name-title-${this.uid}`),i.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.stopPropagation(),this.close();return}M(e,i)}),i.addEventListener(`submit`,e=>{e.preventDefault(),this.done()});let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-name-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.close()),a.append(this.titleEl,o);let s=document.createElement(`div`);s.className=`tcw-modal-body`;let c=document.createElement(`label`);c.className=`tcw-name-field`;let l=document.createElement(`span`);l.textContent=this.t(`layouts.name`),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-indi-input`,this.input.maxLength=80,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.placeholder=this.t(`layouts.namePlaceholder`),this.input.addEventListener(`input`,()=>this.check()),c.append(l,this.input),s.appendChild(c);let u=document.createElement(`div`);u.className=`tcw-modal-footer`;let d=document.createElement(`button`);d.type=`button`,d.className=`tcw-reset-link`,d.textContent=this.t(`common.cancel`),d.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`submit`,this.submit.className=`tcw-done-btn`,u.append(d,this.submit),i.append(a,s,u),this.backdrop.appendChild(i),e.appendChild(this.backdrop)}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.request=e,this.busy=!1,this.titleEl.textContent=e.title,this.submit.textContent=e.submitLabel,this.input.value=e.value??``,this.input.placeholder=e.placeholder??this.t(`layouts.namePlaceholder`),this.check(),this.backdrop.parentElement?.appendChild(this.backdrop),this.backdrop.hidden=!1,this.input.focus(),this.input.select()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.request=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}check(){this.submit.disabled=this.busy||e.r(this.input.value)===null}async done(){let t=this.request,n=e.r(this.input.value);if(!(!t||n===null||this.busy)){this.busy=!0,this.check();try{await t.onSubmit(n),this.request===t&&this.close()}catch{}finally{this.busy=!1,this.check()}}}},Rc=0,zc=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++Rc;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(),i=!1});let a=document.createElement(`div`);a.className=`tcw-modal tcw-layouts-dialog`,a.setAttribute(`role`,`dialog`),a.setAttribute(`aria-modal`,`true`),a.setAttribute(`aria-labelledby`,`tcw-layouts-title-${this.uid}`),a.addEventListener(`keydown`,e=>{if(e.key!==`Escape`){M(e,a);return}e.stopPropagation(),this.confirming?this.setConfirming(null):this.close()});let o=document.createElement(`div`);o.className=`tcw-modal-header`;let s=document.createElement(`h3`);s.id=`tcw-layouts-title-${this.uid}`,s.textContent=this.t(`layouts.dialogTitle`);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-modal-close`,c.setAttribute(`aria-label`,this.t(`common.close`)),c.innerHTML=O(`x`,16),c.addEventListener(`click`,()=>this.close()),o.append(s,c);let l=document.createElement(`label`);l.className=`tcw-ss-search tcw-layouts-search-row`,l.innerHTML=O(`search`,16),this.search=document.createElement(`input`),this.search.type=`search`,this.search.className=`tcw-layouts-search`,this.search.placeholder=this.t(`layouts.search`),this.search.setAttribute(`aria-label`,this.t(`layouts.search`)),this.search.autocomplete=`off`,this.search.addEventListener(`input`,()=>this.render()),l.appendChild(this.search),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-layouts-list`,this.listEl.setAttribute(`role`,`list`);let u=document.createElement(`div`);u.className=`tcw-layouts-body`,u.appendChild(this.listEl),a.append(o,l,u),this.backdrop.appendChild(a),e.appendChild(this.backdrop)}async open(){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.search.value=``,this.confirming=null,this.backdrop.hidden=!1,this.search.focus(),await this.refresh()}async refresh(){let e=++this.loadSeq,t;try{t=await this.callbacks.list()}catch{t=[]}e===this.loadSeq&&(this.layouts=t,this.render())}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.confirming=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}shown(){let e=this.search.value.trim().toLowerCase();return e?this.layouts.filter(t=>t.name.toLowerCase().includes(e)||(t.symbol??``).toLowerCase().includes(e)):this.layouts}render(){let e=this.shown();if(e.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(this.layouts.length===0?`layouts.empty`:`layouts.noMatch`),this.listEl.replaceChildren(e);return}let t=this.callbacks.currentId();this.listEl.replaceChildren(...e.map(e=>this.row(e,e.id===t)))}row(e,n){let r=document.createElement(`div`);r.className=`tcw-layouts-row`,r.setAttribute(`role`,`listitem`),r.dataset.id=e.id;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-layouts-open`,n&&i.setAttribute(`aria-current`,`true`);let a=document.createElement(`span`);a.className=`tcw-layouts-name`,a.textContent=e.name;let o=document.createElement(`span`);if(o.className=`tcw-layouts-meta`,o.textContent=[[e.symbol,e.timeframe].filter(Boolean).join(` · `),t.r(this.t(`layouts.updated`),{time:this.callbacks.formatTime(e.updatedAt)})].filter(Boolean).join(` — `),i.append(a,o),n){let e=document.createElement(`span`);e.className=`tcw-layouts-check`,e.innerHTML=O(`check`,14);let t=document.createElement(`span`);t.className=`tcw-visually-hidden`,t.textContent=this.t(`layouts.current`),i.prepend(e),i.appendChild(t)}i.addEventListener(`click`,()=>{this.callbacks.onOpen(e.id),this.close()});let s=document.createElement(`div`);if(s.className=`tcw-account-actions`,this.confirming===e.id){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-layouts-confirm`,n.textContent=this.t(`layouts.deleteConfirm`),n.setAttribute(`aria-label`,t.r(this.t(`layouts.deleteNamed`),{name:e.name})),n.addEventListener(`click`,()=>void this.remove(e.id));let r=this.iconButton(`x`,this.t(`common.cancel`),()=>this.setConfirming(null));s.append(n,r)}else s.append(this.iconButton(`penLine`,t.r(this.t(`layouts.renameNamed`),{name:e.name}),()=>this.callbacks.onRename(e)),this.iconButton(`trash`,t.r(this.t(`layouts.deleteNamed`),{name:e.name}),()=>this.setConfirming(e.id),!0));return r.append(i,s),r}iconButton(e,t,n,r=!1){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-tree-btn${r?` tcw-tree-del`:``}`,i.setAttribute(`aria-label`,t),i.title=t,i.innerHTML=O(e,14),i.addEventListener(`click`,n),i}setConfirming(e){let t=this.confirming;this.confirming=e,this.render();let n=e??t;n&&[...this.listEl.querySelectorAll(`.tcw-layouts-row`)].find(e=>e.dataset.id===n)?.querySelector(e?`.tcw-layouts-confirm`:`.tcw-tree-del`)?.focus()}async remove(e){try{await this.callbacks.onDelete(e)}finally{this.confirming=null,await this.refresh(),this.isOpen()&&this.search.focus()}}},Bc=5,Vc=class{menu;prompt;dialog;destroyed=!1;constructor(e,t){this.session=e,this.host=t;let{root:n,t:r}=t;this.menu=new A(n,r(`toolbar.layouts`)),this.prompt=new Lc(n,r),this.dialog=new zc(n,{list:()=>e.list(),currentId:()=>e.current()?.id??null,onOpen:e=>void this.open(e),onRename:e=>this.promptRename(e),onDelete:async t=>{try{await e.remove(t)}catch{this.host.toast(r(`layouts.deleteFailed`),`error`)}},formatTime:t.formatTime},r)}async save(){if(this.prompt.isOpen())return;if(!this.session.current()){this.promptSaveAs();return}let{t:e,toast:n}=this.host;try{let r=await this.session.save();r&&n(t.r(e(`layouts.saved`),{name:r.name}))}catch{n(e(`layouts.saveFailed`),`error`)}}async open(e){try{if(await this.session.open(e))return!0}catch{}return this.destroyed||this.host.toast(this.host.t(`layouts.openFailed`),`error`),!1}promptSaveAs(){let{t:e,toast:n}=this.host,r=this.session.current();this.prompt.open({title:e(`layouts.saveAsTitle`),value:r?t.r(e(`layouts.copyName`),{name:r.name}):``,submitLabel:e(`common.save`),onSubmit:async r=>{try{let i=await this.session.saveAs(r);n(t.r(e(`layouts.saved`),{name:i.name}))}catch(t){throw n(e(`layouts.saveFailed`),`error`),t}}})}promptRename(e=this.session.current()){if(!e)return;let{t,toast:n}=this.host;this.prompt.open({title:t(`layouts.renameTitle`),value:e.name,submitLabel:t(`layouts.renameSubmit`),onSubmit:async r=>{try{await this.session.rename(e.id,r)}catch(e){throw n(t(`layouts.saveFailed`),`error`),e}this.dialog.isOpen()&&this.dialog.refresh()}})}openDialog(){return this.dialog.open()}async openMenu(e){if(this.menu.isOpen()){this.menu.close();return}let{session:t}=this,{t:n}=this.host,r=[];try{r=(await t.list()).slice(0,Bc)}catch{}if(this.destroyed)return;let i=t.current(),a=[{id:`save`,label:n(`layouts.save`),icon:`save`,shortcut:this.host.saveKeys?.()},{id:`saveAs`,label:n(`layouts.saveAs`),icon:`plus`}];i&&a.push({id:`rename`,label:n(`layouts.rename`),icon:`penLine`}),a.push({id:`autoSave`,label:n(`layouts.autoSave`),checked:t.isAutoSave()}),r.length>0&&a.push(`separator`,...r.map(e=>({id:`open:${e.id}`,label:e.name,checked:e.id===i?.id}))),a.push(`separator`,{id:`manage`,label:n(`layouts.open`),icon:`folder`}),this.menu.openUnder(a,e,e=>{e===`save`?this.save():e===`saveAs`?this.promptSaveAs():e===`rename`?this.promptRename():e===`autoSave`?t.setAutoSave(!t.isAutoSave()):e===`manage`?this.openDialog():e.startsWith(`open:`)&&this.open(e.slice(5))})}destroy(){this.destroyed=!0,this.menu.destroy(),this.prompt.destroy(),this.dialog.destroy()}},Hc=0,Uc=class{el;input;hint;returnFocus=null;constructor(e,t,n){this.labels=t,this.onApply=n,this.el=document.createElement(`div`),this.el.className=`tcw-interval-input`,this.el.hidden=!0,this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,t.title),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-interval-field`,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.maxLength=6,this.input.setAttribute(`aria-label`,t.title),this.hint=document.createElement(`div`),this.hint.className=`tcw-interval-hint`,this.hint.setAttribute(`role`,`status`),this.hint.id=`tcw-interval-hint-${++Hc}`,this.input.setAttribute(`aria-describedby`,this.hint.id),this.el.append(this.input,this.hint),e.appendChild(this.el),this.input.addEventListener(`input`,()=>this.check()),this.input.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),this.apply()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.close())}),this.input.addEventListener(`blur`,()=>this.close(!1))}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.el.hidden=!1,this.input.value=e,this.check(),this.input.focus(),this.input.setSelectionRange(e.length,e.length)}close(e=!0){if(this.el.hidden)return;this.el.hidden=!0;let t=this.returnFocus;this.returnFocus=null,e&&t?.isConnected&&t.focus({preventScroll:!0})}isOpen(){return!this.el.hidden}destroy(){this.el.remove()}check(){let e=jt(this.input.value)!==null;!e&&this.input.value.trim()!==``?this.input.setAttribute(`aria-invalid`,`true`):this.input.removeAttribute(`aria-invalid`),this.hint.textContent=e||this.input.value.trim()===``?this.labels.hint:this.labels.invalid}apply(){let e=jt(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},Wc=class{constructor(e=`tcw:indicator-templates`){this.key=e}list(){let e;try{e=JSON.parse(localStorage.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let{name:e,indicators:i}=n;if(typeof e!=`string`||!e.trim()||!Array.isArray(i))continue;let a=r.ChartStateManager.deserialize(JSON.stringify({version:2,indicators:i})).indicators;a.length>0&&t.push({name:e.slice(0,60),indicators:a})}return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t){let n=e.replace(/\s+/g,` `).trim().slice(0,60);if(!n)throw Error(`A template needs a name`);let r=[...this.list().filter(e=>e.name!==n),{name:n,indicators:[...t]}];localStorage.setItem(this.key,JSON.stringify(r))}remove(e){try{localStorage.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}},X=[],Gc=new Map,Kc=null,qc=e=>{let t=e.target instanceof Node?e.target:null;t!==null&&X.some(e=>e.contains(t)||Gc.get(e)?.some(e=>e.contains(t)))||(Kc=null)};function Jc(e,t=[]){let n=()=>{Kc=e},r=[e,...t];for(let e of r)e.addEventListener(`pointerdown`,n,!0);return X.length===0&&document.addEventListener(`pointerdown`,qc,!0),X.push(e),Gc.set(e,t),()=>{for(let e of r)e.removeEventListener(`pointerdown`,n,!0);let t=X.indexOf(e);t>=0&&X.splice(t,1),Gc.delete(e),X.length===0&&document.removeEventListener(`pointerdown`,qc,!0),Kc===e&&(Kc=null)}}function Yc(e,t=!1){let n=Kc?.isConnected?Kc:null;if(!n){let e=document.activeElement;n=e?X.find(t=>t.contains(e))??null:null}return!n&&!t&&(n=X.find(e=>e.isConnected)??null),n!==null&&e.contains(n)}function Z(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable)}var Xc=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],Zc=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Qc(e){let{theme:t,timestamp:n,...r}=e;return r}function $c(e){return!Zc(e)||e.v!==1||typeof e.symbol!=`string`||!e.symbol||typeof e.timeframe!=`string`||!((0,n.isTimeFrame)(e.timeframe)||(0,n.tickBarCount)(e.timeframe)!==null)?null:{v:1,symbol:e.symbol,timeframe:e.timeframe,scaleMode:Xc.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:Zc(e.chart)?Qc(e.chart):null,...Zc(e.settings)?{settings:K(e.settings,co)}:{}}}function el(e){try{return JSON.parse(e)}catch{return null}}function tl(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var nl=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=tl()){this.storageKey=e,this.storage=t,this.load()}list(){return[...this.favorites]}has(e){return this.favorites.includes(e)}add(e){!e||this.favorites.includes(e)||(this.favorites=[...this.favorites,e],this.persist())}remove(e){this.favorites.includes(e)&&(this.favorites=this.favorites.filter(t=>t!==e),this.persist())}toggle(e){return this.has(e)?(this.remove(e),!1):(this.add(e),!0)}seedDefaults(e){this.favorites.length>0||(this.favorites=[...new Set(e.filter(Boolean))],this.persist())}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.favorites=[...new Set(t.filter(e=>typeof e==`string`))])}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.favorites))}catch{}}};function rl(e){let t=typeof window<`u`?window.visualViewport:null;if(!t)return()=>{};let n=-1,r=()=>{let r=(t.scale??1)>1.01?0:Math.max(0,Math.round(window.innerHeight-t.height-t.offsetTop));if(r!==n){n=r;for(let t of e)t.style.setProperty(`--tcw-keyboard-inset`,`${r}px`)}};return r(),t.addEventListener(`resize`,r),t.addEventListener(`scroll`,r),()=>{t.removeEventListener(`resize`,r),t.removeEventListener(`scroll`,r)}}function il(e,t){let n=null,r=()=>{let r=e.clientWidth;if(r===0&&n!==null)return;let i=r<641;i!==n&&(n=i,e.toggleAttribute(`data-tcw-narrow`,i),t?.(i))};if(r(),typeof ResizeObserver>`u`)return()=>{};let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()}var al=/^(\d{4})-(\d{2})-(\d{2})$/,ol=/^(\d{2}):(\d{2})$/;function sl(e,t,r){let i=al.exec(e),a=t?ol.exec(t):[``,`00`,`00`];if(!i||!a)return null;let[o,s,c,l,u]=[+i[1],+i[2],+i[3],+a[1],+a[2]];if(s<1||s>12||c<1||c>31||l>23||u>59)return null;let d=Date.UTC(o,s-1,c,l,u);return new Date(d).getUTCDate()===c?(0,n.wallToUtc)(d,r):null}function Q(e,t){let r=e=>String(e).padStart(2,`0`),i=(0,n.timeParts)(e,t);return{date:`${i.year}-${r(i.month)}-${r(i.day)}`,time:`${r(i.hours)}:${r(i.minutes)}`}}var cl=[`date`,`range`],ll=1,ul=class{backdrop=null;fieldsEl=null;tabButtons=[];month=null;active=null;values={date:``,time:``,fromDate:``,fromTime:``,toDate:``,toTime:``};start=null;tab=`date`;returnFocus=null;uid=ll++;constructor(e,t,n,r){this.layer=e,this.labels=t,this.locale=n,this.onSubmit=r}isOpen(){return this.backdrop!==null}open(e){this.close(!1),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.start=e,this.values={date:e.date.date,time:e.date.time,fromDate:e.range.from.date,fromTime:e.range.from.time,toDate:e.range.to.date,toTime:e.range.to.time},this.build(),this.renderTab(!0)}close(e=!0){if(!this.backdrop)return;this.backdrop.remove(),this.backdrop=this.fieldsEl=this.month=this.active=this.start=null,this.tabButtons=[];let t=this.returnFocus;this.returnFocus=null,e&&t?.isConnected&&t.focus()}destroy(){this.close(!1)}build(){let e=this.labels(),t=document.createElement(`div`);t.className=`tcw-modal-backdrop`;let n=!1;t.addEventListener(`pointerdown`,e=>{n=e.target===t}),t.addEventListener(`click`,e=>{e.target===t&&n&&this.close(),n=!1});let r=document.createElement(`div`);r.className=`tcw-modal tcw-goto`,D(r,`goToDate`),r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.setAttribute(`aria-labelledby`,`tcw-goto-title-${this.uid}`),r.tabIndex=-1,r.addEventListener(`keydown`,e=>{if(e.stopPropagation(),e.key===`Escape`){e.preventDefault(),this.close();return}M(e,r)});let i=document.createElement(`div`);i.className=`tcw-modal-header`;let a=document.createElement(`h3`);a.id=`tcw-goto-title-${this.uid}`,a.textContent=e.title;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,e.close),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.close()),i.append(a,o);let s=document.createElement(`form`);s.className=`tcw-goto-form`,s.noValidate=!0,s.addEventListener(`submit`,e=>{e.preventDefault(),this.submit()});let c=document.createElement(`div`);c.className=`tcw-goto-fields`,c.id=`tcw-goto-panel-${this.uid}`,c.setAttribute(`role`,`tabpanel`);let l=new oe(e.calendar,this.locale(),e=>this.pickDay(e));l.element.classList.add(`tcw-goto-calendar`),s.append(c,l.element,this.buildFooter(e)),r.append(i,this.buildTabs(e),s),t.appendChild(r),this.layer().appendChild(t),this.backdrop=t,this.fieldsEl=c,this.month=l}buildTabs(e){let t=document.createElement(`div`);return t.className=`tcw-modal-tabs`,t.setAttribute(`role`,`tablist`),t.addEventListener(`keydown`,e=>this.onTabKey(e)),this.tabButtons=cl.map(t=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-modal-tab`,n.id=`tcw-goto-tab-${this.uid}-${t}`,n.dataset.tab=t,n.setAttribute(`role`,`tab`),n.setAttribute(`aria-controls`,`tcw-goto-panel-${this.uid}`),n.textContent=t===`date`?e.date:e.range,n.addEventListener(`click`,()=>this.select(t,!1)),n}),t.append(...this.tabButtons),t}buildFooter(e){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-footer-cancel`,t.dataset.act=`cancel`,t.textContent=e.cancel,t.addEventListener(`click`,()=>this.close());let n=document.createElement(`button`);n.type=`submit`,n.className=`tcw-done-btn`,n.dataset.act=`go`,n.textContent=e.submit;let r=document.createElement(`div`);r.className=`tcw-footer-end`,r.append(t,n);let i=document.createElement(`div`);return i.className=`tcw-modal-footer`,i.appendChild(r),i}select(e,t){this.tab=e,this.renderTab(!t),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}renderTab(e){let t=this.fieldsEl,n=this.start;if(!t||!n)return;for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.setAttribute(`aria-selected`,String(t)),e.classList.toggle(`tcw-active`,t),e.tabIndex=t?0:-1}t.setAttribute(`aria-labelledby`,`tcw-goto-tab-${this.uid}-${this.tab}`);let r=this.labels();t.replaceChildren(...this.tab===`date`?[this.row(null,`date`,`time`,r)]:[this.row(r.from,`fromDate`,`fromTime`,r),this.row(r.to,`toDate`,`toTime`,r)]);let i=t.querySelector(`input[type="date"]`);this.setActive(i),e&&i?.focus()}row(e,t,n,r){let i=document.createElement(`div`);if(i.className=`tcw-goto-row`,e){let t=document.createElement(`span`);t.className=`tcw-goto-label`,t.textContent=e,i.appendChild(t)}let a=e?`${e} · `:``,o=this.input(`date`,t,`${a}${r.date}`);return o.required=!0,o.dataset.tcwCalendar=`inline`,this.start?.max&&(o.max=this.start.max),o.addEventListener(`focus`,()=>this.setActive(o)),o.addEventListener(`input`,()=>{o.removeAttribute(`aria-invalid`),this.active===o&&this.showMonth()}),i.appendChild(o),this.start?.withTime&&i.appendChild(this.input(`time`,n,`${a}${r.time}`)),i}input(e,t,n){let r=document.createElement(`input`);return r.type=e,r.className=`tcw-goto-input`,r.dataset.field=t,r.value=this.values[t],r.setAttribute(`aria-label`,n),r.addEventListener(`input`,()=>{this.values[t]=r.value}),r}setActive(e){this.active=e,this.showMonth()}showMonth(){this.active&&this.month?.show(this.active.value,{max:this.start?.max,today:this.start?.today})}pickDay(e){let t=this.active;if(!t)return;let n=this.month?.element.contains(document.activeElement)??!1;t.value=e,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0}));let r=t.dataset.field===`fromDate`?this.fieldsEl?.querySelector(`[data-field="toDate"]`):null;if(r){r.focus(),this.setActive(r);return}this.showMonth(),n&&this.month?.focusGrid()}submit(){let e=[...this.fieldsEl?.querySelectorAll(`[data-field]`)??[]];for(let t of e)this.values[t.dataset.field]=t.value;let t=this.start?.max,n=e.find(e=>e.type===`date`&&(!e.value||t!==void 0&&e.value>t));if(n){n.setAttribute(`aria-invalid`,`true`),n.focus();return}let r=this.values,i=this.start?.withTime??!1,a=e=>i?e:``,o;if(this.tab===`date`){if(!r.date)return;o={kind:`date`,date:r.date,time:a(r.time)}}else{if(!r.fromDate||!r.toDate)return;o={kind:`range`,from:{date:r.fromDate,time:a(r.fromTime)},to:{date:r.toDate,time:a(r.toTime)}}}this.close(),this.onSubmit(o)}onTabKey(e){let t=cl.indexOf(this.tab),[n,r]=this.backdrop?.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowLeft`,`ArrowRight`]:[`ArrowRight`,`ArrowLeft`],i=e.key===n?(t+1)%cl.length:e.key===r?(t-1+cl.length)%cl.length:e.key===`Home`?0:e.key===`End`?cl.length-1:-1;i<0||(e.preventDefault(),this.select(cl[i],!0))}},$={min:233,default:296,max:377},dl=.382,fl=e=>!e.hidden&&getComputedStyle(e).display!==`none`,pl=class{element;panel;rail;handle;pages=new Map;open_=null;width;drag=null;observer=null;onMove=e=>{!this.drag||!this.samePointer(e)||this.setWidth(this.drag.width+(this.drag.x-e.clientX)*this.drag.dir)};onUp=e=>{!this.drag||!this.samePointer(e)||(this.drag=null,this.stopDrag(),this.options.saveWidth?.(this.width))};constructor(e,t){this.options=t;let n=document.createElement(`div`);n.className=`tcw-dock`;let r=document.createElement(`div`);r.className=`tcw-dock-panel`,r.hidden=!0,r.addEventListener(`keydown`,e=>this.onPanelKey(e));let i=document.createElement(`div`);i.className=`tcw-dock-resize`,i.setAttribute(`role`,`separator`),i.setAttribute(`aria-orientation`,`vertical`),i.setAttribute(`aria-label`,t.labels.resize),i.setAttribute(`aria-valuemin`,String($.min)),i.tabIndex=0,i.addEventListener(`pointerdown`,e=>this.startDrag(e)),i.addEventListener(`keydown`,e=>this.onHandleKey(e)),r.appendChild(i);let a=document.createElement(`div`);a.className=`tcw-dock-rail`,a.setAttribute(`role`,`toolbar`),a.setAttribute(`aria-orientation`,`vertical`),a.setAttribute(`aria-label`,t.labels.rail),D(a,`dock`),a.addEventListener(`keydown`,e=>this.onRailKey(e)),n.append(r,a),e.appendChild(n),this.element=n,this.panel=r,this.rail=a,this.handle=i,this.width=this.clamp(t.savedWidth?.()??$.default,$.max),this.applyWidth(),t.room&&typeof ResizeObserver<`u`&&(this.observer=new ResizeObserver(()=>this.fit()),this.observer.observe(e))}addPage(e){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-dock-btn`,t.dataset.page=e.id,t.title=e.label,t.setAttribute(`aria-label`,e.label),t.setAttribute(`aria-pressed`,`false`),t.tabIndex=-1,t.innerHTML=O(e.icon,18),e.parts?.length&&D(t,...e.parts),t.addEventListener(`click`,()=>{this.toggle(e.id)}),t.addEventListener(`focus`,()=>this.rove(t)),this.rail.appendChild(t),e.element.hidden=!0,e.element.classList.add(`tcw-dock-page`),this.panel.appendChild(e.element),this.pages.set(e.id,{page:e,button:t}),this.syncRail()}open(e){let t=this.pages.get(e);!t||this.open_===e||(this.hideCurrent(),this.open_=e,this.panel.hidden=!1,t.page.element.hidden=!1,t.button.setAttribute(`aria-pressed`,`true`),this.fit(),t.page.onShow?.(),this.options.onChange?.(e))}close(){let e=this.open_;if(e===null)return;let t=this.panel.contains(document.activeElement);if(this.hideCurrent(),this.panel.hidden=!0,t){let t=this.pages.get(e)?.button;(t&&(this.options.railShown?.()??!0)&&fl(t)?t:this.options.focusAfterClose?.(e))?.focus()}this.options.onChange?.(null)}toggle(e){this.open_===e?this.close():this.open(e)}closePage(e){this.open_===e&&this.close()}current(){return this.open_}isOpen(e){return this.open_===e}syncRail(){let e=[...this.pages.values()].map(e=>e.button),t=e.filter(fl),n=e.find(e=>e.tabIndex===0);if(n&&t.includes(n))return;let r=t.find(e=>e.getAttribute(`aria-pressed`)===`true`)??t[0];for(let t of e)t.tabIndex=t===r?0:-1}fit(){this.applyWidth()}destroy(){this.drag=null,this.stopDrag(),this.observer?.disconnect(),this.element.remove()}hideCurrent(){let e=this.open_===null?null:this.pages.get(this.open_);this.open_=null,e&&(e.page.element.hidden=!0,e.button.setAttribute(`aria-pressed`,`false`),e.page.onHide?.())}maxNow(){let e=this.options.room?.()??0;return e<=0?$.max:Math.max($.min,Math.min($.max,Math.floor(e*dl)))}clamp(e,t=this.maxNow()){return Math.round(Math.min(t,Math.max($.min,e)))}shownWidth(){return this.clamp(this.width)}setWidth(e){this.width=this.clamp(e),this.applyWidth()}applyWidth(){let e=this.shownWidth();this.element.style.setProperty(`--tcw-dock-w`,`${e}px`),this.handle.setAttribute(`aria-valuemax`,String(this.maxNow())),this.handle.setAttribute(`aria-valuenow`,String(e))}samePointer(e){let t=e.pointerId;return this.drag?.pointer===void 0||t===void 0||t===this.drag.pointer}startDrag(e){if(e.button!==0)return;e.preventDefault();let t=getComputedStyle(this.element).direction===`rtl`||this.element.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`;this.drag={x:e.clientX,width:this.shownWidth(),dir:t?-1:1,pointer:e.pointerId},document.addEventListener(`pointermove`,this.onMove),document.addEventListener(`pointerup`,this.onUp),document.addEventListener(`pointercancel`,this.onUp)}stopDrag(){document.removeEventListener(`pointermove`,this.onMove),document.removeEventListener(`pointerup`,this.onUp),document.removeEventListener(`pointercancel`,this.onUp)}onHandleKey(e){let[t,n]=this.element.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowRight`,`ArrowLeft`]:[`ArrowLeft`,`ArrowRight`],r=this.shownWidth(),i=e.key===t?r+13:e.key===n?r-13:e.key===`Home`?$.min:e.key===`End`?$.max:null;i!==null&&(e.preventDefault(),this.setWidth(i),this.options.saveWidth?.(this.width))}onPanelKey(e){e.key!==`Escape`||e.defaultPrevented||!this.element.closest(`[data-tcw-narrow]`)||(e.preventDefault(),e.stopPropagation(),this.close())}rove(e){for(let{button:t}of this.pages.values())t.tabIndex=t===e?0:-1}onRailKey(e){let t=[...this.pages.values()].map(e=>e.button).filter(fl),n=t.indexOf(e.target);if(n<0)return;let r=e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),t[r].focus())}},ml=[`percent`,`scale`,`pane`,`spread`,`ratio`,`correlation`,`correlationLog`],hl={percent:`compare.percent`,scale:`compare.ownScale`,pane:`compare.ownPane`,spread:`compare.way.spread`,ratio:`compare.way.ratio`,correlation:`compare.way.correlation`,correlationLog:`compare.way.correlationLog`};function gl(e){return ml.includes(e)}function _l(e){return ml.map(t=>({id:t,label:e(hl[t])}))}function vl(e,t){let n=e.findIndex(e=>e.time>=t);return n<0?e.length:n}function yl(e,t){let n=e[0]?.time??1/0,r=t.filter(e=>e.time<n);return r.length>0?[...r,...e]:null}function bl(e,t){switch(e.id){case`compareSymbol`:return t?`pane`:`scale`;case`compareSymbolPane`:return`pane`;case`spread`:return e.params.mode===`ratio`?`ratio`:`spread`;case`correlation`:return`correlation`;case`correlationlog`:return`correlationLog`;default:return null}}function xl(e,t,n,r){let i=e.map(e=>({id:e.id,symbol:e.symbol,way:r(hl.percent),color:e.color}));for(let e of t){let t=e.params.symbol,a=bl(e,n.has(e.instanceId));!a||typeof t!=`string`||!t||i.push({id:e.instanceId,symbol:t,way:r(hl[a])})}return i}var Sl=8,Cl=4,wl=3,Tl=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,El=class{el;target=null;source=null;pressed=null;showTimer=null;watchFrame=0;warmUntil=0;observer;constructor(e){this.root=e,this.el=document.createElement(`div`),this.el.className=`tcw-tooltip`,this.el.setAttribute(`aria-hidden`,`true`),e.appendChild(this.el),e.addEventListener(`pointerover`,this.onOver),e.addEventListener(`pointerout`,this.onOut),e.addEventListener(`pointerdown`,this.onPress,!0),e.addEventListener(`keydown`,this.onPress,!0),e.addEventListener(`focusin`,this.onFocus),e.addEventListener(`focusout`,this.onBlur),e.addEventListener(`wheel`,this.hide,{passive:!0}),this.observer=new MutationObserver(()=>{this.pressed?.hasAttribute(`title`)&&Dl(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(Dl(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&Ol(this.pressed),this.observer.disconnect(),this.root.removeEventListener(`pointerover`,this.onOver),this.root.removeEventListener(`pointerout`,this.onOut),this.root.removeEventListener(`pointerdown`,this.onPress,!0),this.root.removeEventListener(`keydown`,this.onPress,!0),this.root.removeEventListener(`focusin`,this.onFocus),this.root.removeEventListener(`focusout`,this.onBlur),this.root.removeEventListener(`wheel`,this.hide),this.el.remove()}onOver=e=>{if(e.pointerType===`touch`)return;let t=this.tipTarget(e.target);!t||t===this.pressed||t===this.target&&this.source===`pointer`||(Dl(t),this.schedule(t,`pointer`,Date.now()<this.warmUntil||this.isVisible()))};onOut=e=>{let t=e.relatedTarget,n=e=>!!e&&!!t&&e.contains(t);this.pressed&&!n(this.pressed)&&(Ol(this.pressed),this.pressed=null),this.source===`pointer`&&!n(this.target)&&this.hide()};onPress=()=>{let e=this.target,t=this.source===`pointer`;this.warmUntil=0,this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.el.classList.remove(`tcw-tooltip--visible`),this.target=null,this.source=null,this.pressed&&this.pressed!==e&&Ol(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!jl(t)||t===this.pressed||this.schedule(t,`focus`,!0)};onBlur=e=>{if(this.source!==`focus`)return;let t=e.relatedTarget;this.target&&t&&this.target.contains(t)||this.hide()};hide=()=>{this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.isVisible()&&(this.warmUntil=Date.now()+500),this.el.classList.remove(`tcw-tooltip--visible`),this.target&&this.source===`pointer`&&Ol(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(Tl);return t&&t!==this.el&&this.root.contains(t)?t:null}schedule(e,t,n){let r=this.target;if(this.clearTimer(),cancelAnimationFrame(this.watchFrame),r&&r!==e&&this.source===`pointer`&&Ol(r),this.target=e,this.source=t,n){this.show(e);return}this.el.classList.remove(`tcw-tooltip--visible`),this.showTimer=setTimeout(()=>{this.showTimer=null,this.target===e&&this.show(e)},300)}show(e){if(!Al(e)){this.hide();return}this.el.textContent=kl(e),this.place(e),this.el.classList.add(`tcw-tooltip--visible`),this.watch(e)}watch(e){cancelAnimationFrame(this.watchFrame),this.watchFrame=requestAnimationFrame(()=>{this.target===e&&(Al(e)?this.watch(e):this.hide())})}place(e){let t=this.root.getBoundingClientRect(),n=e.getBoundingClientRect(),r=this.el.offsetWidth,i=this.el.offsetHeight,a=n.left-t.left,o=n.top-t.top,s=Ml(e);s===`bottom`&&o+n.height+Sl+i>t.height?s=`top`:s===`top`&&o-Sl-i<0?s=`bottom`:s===`right`&&a+n.width+Sl+r>t.width&&(s=`left`);let c,l;s===`top`||s===`bottom`?(c=a+n.width/2-r/2,l=s===`bottom`?o+n.height+Sl:o-Sl-i):(c=s===`right`?a+n.width+Sl:a-Sl-r,l=o+n.height/2-i/2),c=Math.max(Cl,Math.min(t.width-r-Cl,c)),l=Math.max(Cl,Math.min(t.height-i-Cl,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,wl],bottom:[0,-wl],left:[wl,0],right:[-wl,0]}[s];this.el.style.setProperty(`--tcw-tip-dx`,`${u[0]}px`),this.el.style.setProperty(`--tcw-tip-dy`,`${u[1]}px`),this.el.dataset.side=s}isVisible(){return this.el.classList.contains(`tcw-tooltip--visible`)}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}};function Dl(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function Ol(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function kl(e){return e.dataset.tip??e.getAttribute(`title`)??``}function Al(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function jl(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function Ml(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var Nl=2,Pl=1.5,Fl=`tcw-ind-legend-values--no-room`,Il=0,Ll=class{stack;toggle;rows=new Map;panes=new Map;collapsed=!1;toggleKey=``;stackKey=``;valuesObserver;stackObserver;constructor(e,t,n){this.host=e,this.callbacks=t,this.labels=n,this.stack=document.createElement(`div`),this.stack.className=`tcw-ind-legend`,D(this.stack,`indicatorLegend`),this.toggle=document.createElement(`button`),this.toggle.type=`button`,this.toggle.className=`tcw-ind-legend-toggle`,this.toggle.addEventListener(`click`,()=>{this.setCollapsed(!this.collapsed),this.renderToggle(this.overlayCount())}),this.stack.appendChild(this.toggle),e.appendChild(this.stack),this.stackObserver=typeof ResizeObserver>`u`||!t.onStackResize?null:new ResizeObserver(()=>this.reportStackSize()),this.stackObserver?.observe(this.stack),this.valuesObserver=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>{for(let t of e)Rl(t.target,t.contentRect.width)})}update(e,t,n=[]){this.updatePanes(n);let r=`${Math.round(t.left)},${Math.round(t.top)}`;r!==this.stackKey&&(this.stackKey=r,this.stack.style.left=`${Math.round(t.left)}px`,this.stack.style.top=`${Math.round(t.top)}px`);let i=new Set(e.map(e=>e.instanceId));for(let[e,t]of this.rows)i.has(e)||(this.valuesObserver?.unobserve(t.values),t.el.remove(),this.rows.delete(e));let a=!1,o=null;for(let t of e){let e=this.rows.get(t.instanceId)??this.createRow(t.instanceId,t.kind);if(this.fill(e,t),t.pane)e.el.parentElement!==this.host&&this.host.appendChild(e.el);else{let t=o?o.nextElementSibling:this.stack.firstElementChild;e.el.parentElement!==this.stack&&(a=!0),e.el!==t&&this.stack.insertBefore(e.el,t),o=e.el}this.place(e,t.pane)}a&&this.collapsed&&this.setCollapsed(!1),this.renderToggle(e.filter(e=>!e.pane).length)}destroy(){this.valuesObserver?.disconnect(),this.stackObserver?.disconnect();for(let e of this.rows.values())e.el.remove();this.rows.clear();for(let e of this.panes.values())e.el.remove();this.panes.clear(),this.stack.remove()}reportStackSize(){let e=this.stack.offsetWidth,t=this.stack.offsetHeight;this.callbacks.onStackResize?.(e>0&&t>0?{width:e,height:t}:null)}updatePanes(e){if(!this.callbacks.onPaneAction)return;let t=new Set;for(let n of e){t.add(n.instanceId);let e=this.panes.get(n.instanceId)??this.createPane(n.instanceId),r=`${Math.round(n.x)},${Math.round(n.y)}|${n.label}|${n.collapsed}|${n.maximized}|${n.canMoveUp}|${n.canMoveDown}`;if(r===e.key)continue;e.key=r,e.el.style.left=`${Math.round(n.x)}px`,e.el.style.top=`${Math.round(n.y)}px`;let i=this.labels,a=(t,r,i,a)=>{let o=e.buttons.get(t);!r&&document.activeElement===o&&e.buttons.get(`max`).focus(),o.hidden=!r,o.innerHTML=O(i,12),zl(o,a??t,n.label)};a(`up`,n.canMoveUp&&!n.maximized,`arrowUp`,i.paneUp),a(`down`,n.canMoveDown&&!n.maximized,`arrowDown`,i.paneDown),a(`fold`,!n.maximized,n.collapsed?`chevronDown`:`chevronUp`,n.collapsed?i.paneExpand:i.paneCollapse),a(`max`,!0,n.maximized?`minimize`:`maximize`,n.maximized?i.paneRestore:i.paneMaximize),e.el.dataset.collapsed=String(n.collapsed),e.el.dataset.maximized=String(n.maximized)}for(let[e,n]of this.panes)t.has(e)||(n.el.remove(),this.panes.delete(e))}createPane(e){let t=document.createElement(`div`);t.className=`tcw-pane-controls`,D(t,`indicatorLegend`),t.dataset.instance=e;let n=new Map,r=e=>e===`up`||e===`down`?e:e===`fold`?t.dataset.collapsed===`true`?`expand`:`collapse`:t.dataset.maximized===`true`?`restore`:`maximize`,i={up:`pane.move`,down:`pane.move`,fold:`pane.collapse`,max:`pane.maximize`};for(let a of[`up`,`down`,`fold`,`max`]){let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-pane-btn`,o.dataset.act=a,D(o,i[a]),o.addEventListener(`click`,()=>this.callbacks.onPaneAction?.(e,r(a))),n.set(a,o),t.appendChild(o)}this.host.appendChild(t);let a={el:t,buttons:n,key:``};return this.panes.set(e,a),a}createRow(e,t){let n=t===`compare`,r=document.createElement(`div`);r.className=n?`tcw-ind-legend-row tcw-ind-legend-row--compare`:`tcw-ind-legend-row`,D(r,`indicatorLegend`),r.dataset.instance=e;let i=document.createElement(n?`span`:`button`);i.className=`tcw-ind-legend-name`,i instanceof HTMLButtonElement&&(i.type=`button`,i.addEventListener(`click`,()=>this.callbacks.onSettings(e)));let a=document.createElement(`span`);a.className=`tcw-ind-legend-values`,D(a,`indicatorLegend.values`),this.valuesObserver?.observe(a);let o=document.createElement(`span`);o.className=`tcw-ind-legend-actions`;let s=(e,t,n,...r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-ind-legend-act`,i.dataset.act=e,D(i,...r),i.innerHTML=O(t,13),i.addEventListener(`click`,n),o.appendChild(i),i},c=s(`visible`,`eye`,()=>{this.callbacks.onToggleVisible(e,!m.visible,t)},`indicatorLegend.visibility`),l=n?null:s(`settings`,`settings`,()=>this.callbacks.onSettings(e),`indicatorSettings`,`indicatorLegend.settings`),u=this.callbacks.onMore&&!n?s(`more`,`more`,()=>this.callbacks.onMore?.(e,u),`indicatorLegend.more`):null,d=s(`remove`,`x`,()=>this.callbacks.onRemove(e,t),`indicatorLegend.remove`),f=document.createElement(`span`);f.className=`tcw-visually-hidden`,f.id=`tcw-ind-note-${++Il}`;let p=n?document.createElement(`span`):null;p&&(p.className=`tcw-ind-legend-swatch`,p.setAttribute(`aria-hidden`,`true`),r.append(p)),r.append(i,a,o,f);let m={el:r,name:i,swatch:p,values:a,eye:c,settings:l,more:u,remove:d,note:f,visible:!0,valuesKey:``,state:``,placeKey:``};return this.rows.set(e,m),m}fill(e,t){let n=this.offNote(t),r=`${t.label}|${t.visible}|${n}|${t.swatch??``}`;r!==e.state&&(e.state=r,e.swatch&&(e.swatch.style.backgroundColor=t.swatch??``),e.visible=t.visible,e.name.textContent=t.label,e.settings&&(e.name.title=this.labels.settings),e.el.classList.toggle(`tcw-ind-legend-row--hidden`,!t.visible||n!==null),n?e.el.title=n:e.el.removeAttribute(`title`),this.describe(e,n),e.eye.innerHTML=O(t.visible?`eye`:`eyeOff`,13),zl(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),e.settings&&zl(e.settings,this.labels.settings,t.label),e.more&&(zl(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),zl(e.remove,this.labels.remove,t.label));let i=t.values.map(e=>`${e.text}${e.color??``}`).join(``);i!==e.valuesKey&&(e.valuesKey=i,e.values.replaceChildren(...t.values.map(e=>{let t=document.createElement(`span`);return t.textContent=e.text,e.color&&(t.style.color=e.color),t})))}describe(e,t){e.note.textContent=t??``;let n=[e.name,e.eye,e.settings,e.more,e.remove].filter(e=>e instanceof HTMLButtonElement);for(let r of n)t?r.setAttribute(`aria-describedby`,e.note.id):r.removeAttribute(`aria-describedby`)}offNote(e){return e.offInterval?this.labels.offInterval??``:e.offChartType?this.labels.offChartType??``:null}place(e,t){let n=t?`${Math.round(t.x)},${Math.round(t.y)},${Math.round(t.width)}`:``;n!==e.placeKey&&(e.placeKey=n,e.el.classList.toggle(`tcw-ind-legend-row--pane`,t!==null),e.el.style.left=t?`${Math.round(t.x)}px`:``,e.el.style.top=t?`${Math.round(t.y)}px`:``,e.el.style.maxWidth=t?`${Math.max(0,Math.round(t.width))}px`:``)}setCollapsed(e){this.collapsed=e,this.stack.classList.toggle(`tcw-ind-legend--collapsed`,e)}overlayCount(){return this.stack.querySelectorAll(`:scope > .tcw-ind-legend-row`).length}renderToggle(e){let t=e>=Nl;!t&&this.collapsed&&this.setCollapsed(!1);let n=`${t}|${this.collapsed}|${e}`;if(n===this.toggleKey||(this.toggleKey=n,this.toggle.hidden=!t,!t))return;let r=this.collapsed?this.labels.expand:this.labels.collapse;zl(this.toggle,r,this.collapsed?`(${e})`:void 0),this.toggle.setAttribute(`aria-expanded`,String(!this.collapsed));let i=O(this.collapsed?`chevronDown`:`chevronUp`,12);this.toggle.innerHTML=this.collapsed?`${i}<span>${e}</span>`:i}};function Rl(e,t){let n=(parseFloat(getComputedStyle(e).fontSize)||0)*Pl;e.classList.toggle(Fl,t<n)}function zl(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function Bl(e,t){return!e||e.length===0?null:e[t===null?e.length-1:Math.min(Math.max(t,0),e.length-1)]??null}function Vl(e,t,n,i){if(!t)return[];let a=e.plots;if(!a){let e=[];for(let n in t){let r=t[n];typeof r==`number`&&Number.isFinite(r)&&e.push(r)}let r=e.length===1?n[0]??null:null;return e.map(e=>({value:e,color:r}))}let o={colors:[...n],lineWidths:[],opacity:1},s=[];for(let e of a){if(!(0,r.plotShown)(e,{plots:i}))continue;let a=t[e.key];typeof a!=`number`||!Number.isFinite(a)||s.push({value:a,color:n.length?(0,r.plotColor)(e,o,t):null})}return s}var Hl=new Map;function Ul(e){let t=Hl.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),Hl.set(e,t)),t}function Wl(e,t=`en-US`){return Math.abs(e)>=1e6?Ul(t).format(e):(0,n.formatPrice)(e,(0,r.indicatorValuePrecision)(e),t)}var Gl=2,Kl=2;function ql(e,t=`en-US`){return(0,n.formatPrice)(e,Math.max(Gl,(0,r.indicatorValuePrecision)(e)),t)}function Jl(e,t=`en-US`){return`${ic((0,n.formatPrice)(Math.abs(e),Kl,t),e,(0,n.formatPrice)(0,Kl,t))}%`}function Yl(e,t=`en-US`,n=!0){return e.map(e=>({instanceId:e.id,kind:`compare`,label:e.label,swatch:e.color,visible:e.visible,...n?{values:Xl(e,t)}:{values:[],offChartType:!0},pane:null}))}function Xl(e,t){return[...e.close===null?[]:[{text:ql(e.close,t),color:null}],...e.change===null?[]:[{text:Jl(e.change,t),color:null}]]}var Zl=class{el;labelEl;callbacks;visible=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-bracket-bar`,this.el.setAttribute(`role`,`group`),this.el.hidden=!0,this.labelEl=document.createElement(`span`),this.labelEl.className=`tcw-bracket-label`,this.el.appendChild(this.labelEl);let i=document.createElement(`span`);i.className=`tcw-bracket-hint`,i.textContent=this.t(`bracket.hint`),this.el.appendChild(i);let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-bracket-cancel`,a.innerHTML=`${O(`x`,14)}<span>${k(this.t(`common.cancel`))}</span>`,a.addEventListener(`click`,()=>this.callbacks.onCancel());let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-bracket-confirm`,o.innerHTML=`${O(`check`,14)}<span>${k(this.t(`bracket.place`))}</span>`,o.addEventListener(`click`,()=>this.callbacks.onConfirm()),this.el.appendChild(a),this.el.appendChild(o),e.appendChild(this.el)}show(e){this.visible=!0;let t=e===`buy`?this.t(`toolbar.longBracket`):this.t(`toolbar.shortBracket`);this.labelEl.textContent=t,this.el.setAttribute(`aria-label`,t),this.el.dataset.side=e,this.el.dir=this.el.closest(`.tcw-root`)?.dir||`auto`,this.el.hidden=!1}hide(){this.visible=!1,this.el.hidden=!0}isVisible(){return this.visible}destroy(){this.el.remove()}},Ql=class{options;audioCtx=null;audioEl=null;permissionAsked=!1;constructor(e={}){if(this.options=e,typeof e.sound==`string`)try{this.audioEl=new Audio(e.sound),this.audioEl.preload=`auto`}catch{this.audioEl=null}e.desktop&&this.ensurePermission()}setOptions(e){this.options={...this.options,...e}}notify(e){this.options.sound&&this.playSound(),this.options.desktop&&this.showDesktop(e)}playSound(){if(this.audioEl){this.audioEl.currentTime=0,this.audioEl.play().catch(()=>{});return}this.beep()}beep(){try{let e=window.AudioContext??window.webkitAudioContext;if(!e)return;this.audioCtx||=new e;let t=this.audioCtx,n=t.currentTime,r=t.createGain();r.gain.setValueAtTime(1e-4,n),r.gain.exponentialRampToValueAtTime(.2,n+.01),r.gain.exponentialRampToValueAtTime(1e-4,n+.35),r.connect(t.destination);let i=t.createOscillator();i.type=`sine`,i.frequency.setValueAtTime(880,n),i.frequency.setValueAtTime(1320,n+.16),i.connect(r),i.start(n),i.stop(n+.36)}catch{}}ensurePermission(){this.permissionAsked||(this.permissionAsked=!0,!(typeof Notification>`u`)&&Notification.permission===`default`&&Notification.requestPermission().catch(()=>{}))}showDesktop(e){if(!(typeof Notification>`u`)){if(Notification.permission!==`granted`){this.ensurePermission();return}try{new Notification(this.options.title??`Price alert`,{body:e})}catch{}}}destroy(){try{this.audioCtx?.close()}catch{}this.audioCtx=null,this.audioEl=null}};function $l(e,t=12){let n=[...e.asks].sort((e,t)=>e.price-t.price).slice(0,t),r=[...e.bids].sort((e,t)=>t.price-e.price).slice(0,t),i=n.length>0?n[0].price:null,a=r.length>0?r[0].price:null,o=i!==null&&a!==null?(i+a)/2:null,s=new Map,c=e=>{let t=s.get(e);return t||(t={price:e,bidVolume:0,askVolume:0},s.set(e,t)),t};for(let e of n)c(e.price).askVolume+=e.volume;for(let e of r)c(e.price).bidVolume+=e.volume;let l=[...s.values()].sort((e,t)=>t.price-e.price),u=0;for(let e of l)u=Math.max(u,e.bidVolume,e.askVolume);return{rows:l,maxVolume:u,mid:o,spread:i!==null&&a!==null?i-a:null,bestBid:a}}var eu=1e-9,tu=class{el;colsEl;bodyEl;callbacks;open=!1;levels;model=null;orders=[];drawn=[];spreadEl;placed=!1;constructor(e,n,r=12,i=t.t){this.t=i,this.callbacks=n,this.levels=r,this.el=document.createElement(`section`),this.el.className=`tcw-ladder`,this.el.setAttribute(`aria-label`,this.t(`ladder.title`)),D(this.el,`depthLadder`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-ladder-header`;let o=document.createElement(`h3`);o.className=`tcw-ladder-title`,o.textContent=this.t(`ladder.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-ladder-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=O(`x`,14),s.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.append(o,s),this.colsEl=document.createElement(`div`),this.colsEl.className=`tcw-ladder-cols`;for(let e of[`ladder.bid`,`ladder.price`,`ladder.ask`]){let t=document.createElement(`span`);t.textContent=this.t(e),this.colsEl.appendChild(t)}this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-ladder-body`,this.spreadEl=document.createElement(`div`),this.spreadEl.className=`tcw-ladder-spread`,this.el.append(a,this.colsEl,this.bodyEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.placed=!1,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}close(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}setData(e){this.model=e?$l(e,this.levels):null,this.render()}setOrders(e){this.orders=e,this.render()}destroy(){this.el.remove()}render(){if(!this.open)return;let e=this.model;if(!e||e.rows.length===0){let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=this.t(`ladder.empty`),this.bodyEl.replaceChildren(e),this.drawn=[];return}let t=nu(e.rows);e.rows.length===this.drawn.length&&e.rows.every((e,t)=>e.price===this.drawn[t].price)||(this.drawn=e.rows.map(e=>this.newRow(e.price)),this.bodyEl.replaceChildren(...this.drawn.map(e=>e.row)));let n=e.maxVolume>0?100/e.maxVolume:0;e.rows.forEach((e,r)=>this.fillRow(this.drawn[r],e,n,this.nearness(e.price,t))),this.putSpread(e,t),this.placeSpread()}putSpread(e,n){let{spread:r,bestBid:i}=e,a=r===null||i===null?-1:e.rows.findIndex(e=>e.price<i+n);if(r===null||a<0){this.spreadEl.remove();return}this.spreadEl.textContent=t.r(this.t(`ladder.spread`),{spread:this.callbacks.formatPrice(r)});let o=this.drawn[a].row;this.spreadEl.nextElementSibling!==o&&this.bodyEl.insertBefore(this.spreadEl,o)}nearness(e,t){let n=this.callbacks.priceStep?.(e)??0;return n>0?Math.min(n/2,t):t}newRow(e){let t=document.createElement(`div`);t.className=`tcw-ladder-row`;let n=document.createElement(`div`);n.className=`tcw-ladder-price`;let r=document.createElement(`span`);r.className=`tcw-ladder-figure`,n.appendChild(r);let i=this.newCell(`sell`,e),a=this.newCell(`buy`,e);return t.append(i,n,a),{price:e,row:t,bid:i,ask:a,cell:n,figure:r}}newCell(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-ladder-cell ${e===`sell`?`tcw-ladder-bid`:`tcw-ladder-ask`}`,n.addEventListener(`click`,()=>this.callbacks.onTrade(e,t)),n}fillRow(e,t,n,r){e.cell.className=`tcw-ladder-price ${t.askVolume>0?`tcw-ask`:`tcw-bid`}`,e.figure.textContent=this.callbacks.formatPrice(t.price),this.fillCell(e.bid,`sell`,t.bidVolume,t.price,n),this.fillCell(e.ask,`buy`,t.askVolume,t.price,n);for(let t of e.cell.querySelectorAll(`.tcw-ladder-own`))t.remove();for(let n of[`buy`,`sell`]){let i=this.orders.filter(e=>e.side===n&&Math.abs(e.price-t.price)<r).reduce((e,t)=>e+t.quantity,0);if(i<=0)continue;let a=document.createElement(`span`);a.className=`tcw-ladder-own`,a.dataset.side=n,a.textContent=String(i);let o=`${this.t(n===`buy`?`ticket.buy`:`ticket.sell`)} ${i}`;a.setAttribute(`aria-label`,o),a.title=o,n===`buy`?e.cell.insertBefore(a,e.figure):e.cell.appendChild(a)}}fillCell(e,n,r,i,a){if(!(r>0)){e.disabled=!0,e.textContent=``,e.removeAttribute(`aria-label`),e.title=``,e.style.removeProperty(`--w`);return}e.disabled=!1;let o=ru(r);e.textContent=o,e.style.setProperty(`--w`,`${(r*a).toFixed(1)}%`);let s=t.r(this.t(n===`sell`?`ladder.sellAt`:`ladder.buyAt`),{price:this.callbacks.formatPrice(i)});e.setAttribute(`aria-label`,`${o}, ${s}`),e.title=s}placeSpread(){let e=this.el;if(this.placed||!this.spreadEl.isConnected||e.clientHeight===0)return;let t=e.getBoundingClientRect().top,n=this.colsEl.getBoundingClientRect().bottom-t,r=this.spreadEl.getBoundingClientRect().top-t;e.scrollTop+=r-n-(e.clientHeight-n-this.spreadEl.offsetHeight)/2,this.placed=!0}};function nu(e){let t=1/0;for(let n=1;n<e.length;n++)t=Math.min(t,Math.abs(e[n-1].price-e[n].price));return Number.isFinite(t)&&t>0?t/2:eu}function ru(e){return e>=1e3?`${Number((e/1e3).toFixed(1))}k`:String(Number(e>=1?e.toFixed(2):e.toPrecision(2)))}var iu=class{el;bodyEl;callbacks;open=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-datawin`,D(this.el,`dataWindow`),this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-datawin-header`;let a=document.createElement(`span`);a.textContent=this.t(`dataWindow.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-datawin-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=O(`x`,14),o.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),i.appendChild(a),i.appendChild(o),this.el.appendChild(i),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-datawin-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}render(e){if(!this.open)return;if(this.bodyEl.replaceChildren(),!e.ohlc){let e=document.createElement(`div`);e.className=`tcw-datawin-empty`,e.textContent=this.t(ce()?`dataWindow.touch`:`dataWindow.hover`),this.bodyEl.appendChild(e);return}let t=this.callbacks.formatPrice,n=e.ohlc;this.bodyEl.appendChild(this.row(this.t(`dataWindow.open`),t(n.open))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.high`),t(n.high))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.low`),t(n.low))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.close`),t(n.close)));let r=e.change>0?`up`:e.change<0?`down`:``,i=e.change>0?`+`:``,a=this.callbacks.formatPercent?.(e.changePct)??e.changePct.toFixed(2),o=e.changeText??t(e.change);this.bodyEl.appendChild(this.row(this.t(`dataWindow.change`),`${i}${o} (${i}${a}%)`,r)),this.bodyEl.appendChild(this.row(this.t(`dataWindow.volume`),(this.callbacks.formatVolume??ou)(n.volume)));for(let t of e.indicators){let e=document.createElement(`div`);e.className=`tcw-datawin-sub`,e.textContent=t.name,this.bodyEl.appendChild(e);for(let e of t.values)this.bodyEl.appendChild(this.row(e.key,e.text??au(e.value)))}}row(e,t,n=``){let r=document.createElement(`div`);r.className=`tcw-datawin-row`;let i=document.createElement(`span`);i.className=`tcw-datawin-label`,i.textContent=e;let a=document.createElement(`span`);return a.className=`tcw-datawin-value${n?` tcw-${n}`:``}`,a.textContent=t,r.appendChild(i),r.appendChild(a),r}};function au(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toPrecision(4)}function ou(e){return e>=1e9?(e/1e9).toFixed(2)+`B`:e>=1e6?(e/1e6).toFixed(2)+`M`:e>=1e3?(e/1e3).toFixed(2)+`K`:e.toFixed(0)}var su=e=>typeof e==`object`&&!!e&&!Array.isArray(e),cu=globalThis.Buffer;function lu(e){if(cu)return cu.from(e,`utf8`).toString(`base64`);let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function uu(e){if(cu)return cu.from(e,`base64`).toString(`utf8`);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return new TextDecoder().decode(n)}function du(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function fu(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function pu(e){return du(lu(JSON.stringify(e)))}function mu(e){if(!e)return null;try{let t=uu(fu(e)),n=JSON.parse(t);return!n||n.v!==1||typeof n.symbol!=`string`?null:{v:1,symbol:n.symbol,timeframe:n.timeframe,chartType:n.chartType,scaleMode:Xc.find(e=>e===n.scaleMode)??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[],...su(n.settings)?{settings:K(n.settings,lo)}:{}}}catch{return null}}var hu=`tcw`;function gu(e){let t=e.startsWith(`#`)?e.slice(1):e;for(let e of t.split(`&`)){let t=e.indexOf(`=`);if(!(t<=0||e.slice(0,t)!==hu))try{return decodeURIComponent(e.slice(t+1))}catch{return null}}return null}function _u(e,t){let[n]=e.split(`#`);return`${n}#${hu}=${t}`}var vu=[[34,16,28,26,!1],[30,14,24,26,!0],[26,18,20,30,!0],[30,10,24,22,!1],[20,16,14,28,!0],[14,18,8,30,!0],[18,10,12,20,!1],[8,18,2,30,!0]],yu=class{el;label;showTimer=null;phase=`loading`;constructor(e,t){this.loadingText=t,this.el=document.createElement(`div`),this.el.className=`tcw-loading-overlay`,this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`div`);n.className=`tcw-loading-card`;let r=document.createElement(`div`);r.className=`tcw-loading-candles`,r.setAttribute(`aria-hidden`,`true`),vu.forEach(([e,t,n,i,a],o)=>{let s=document.createElement(`span`);s.className=a?`tcw-loading-candle tcw-loading-candle--up`:`tcw-loading-candle`,s.style.setProperty(`--tcw-body-top`,`${e}px`),s.style.setProperty(`--tcw-body-h`,`${t}px`),s.style.setProperty(`--tcw-wick-top`,`${n}px`),s.style.setProperty(`--tcw-wick-h`,`${i}px`),s.style.setProperty(`--tcw-delay`,`${o*110}ms`),r.appendChild(s)}),n.appendChild(r);let i=document.createElement(`div`);i.className=`tcw-loading-track`,i.setAttribute(`aria-hidden`,`true`),i.appendChild(document.createElement(`span`)),n.appendChild(i),this.label=document.createElement(`div`),this.label.className=`tcw-loading-label`,this.label.textContent=t,n.appendChild(this.label),this.el.appendChild(n),e.appendChild(this.el)}begin(e,t=!1){if(this.phase=`loading`,this.clearTimer(),this.label.textContent=this.loadingText,this.el.classList.remove(`tcw-loading-overlay--error`),this.el.classList.toggle(`tcw-loading-overlay--veil`,e),!e||t||this.isShown()){this.el.classList.remove(`tcw-loading-overlay--hidden`);return}this.showTimer=setTimeout(()=>{this.showTimer=null,this.el.classList.remove(`tcw-loading-overlay--hidden`)},200)}end(){this.phase=`idle`,this.clearTimer(),this.el.classList.add(`tcw-loading-overlay--hidden`)}fail(e){this.phase!==`idle`&&(this.phase=`failed`,this.clearTimer(),this.label.textContent=e,this.el.classList.add(`tcw-loading-overlay--error`),this.el.classList.remove(`tcw-loading-overlay--hidden`))}isActive(){return this.phase!==`idle`}hasFailed(){return this.phase===`failed`}isShown(){return!this.el.classList.contains(`tcw-loading-overlay--hidden`)}destroy(){this.clearTimer(),this.el.remove()}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}},bu=4e3,xu=class{el;text;hideTimer=null;constructor(e,t){this.texts=t,this.el=document.createElement(`div`),this.el.className=`tcw-history-pill tcw-history-pill--hidden`,this.el.setAttribute(`aria-hidden`,`true`),this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`span`);n.className=`tcw-history-spinner`,n.setAttribute(`aria-hidden`,`true`),this.text=document.createElement(`span`),this.el.append(n,this.text),e.appendChild(this.el)}update(e){this.clearTimer(),e.state===`loading`?this.show(this.texts.loading,!1):e.state===`error`?(this.show(this.texts.failed,!0),this.hideTimer=setTimeout(()=>this.hide(),bu)):this.hide()}destroy(){this.clearTimer(),this.el.remove()}show(e,t){this.text.textContent=e,this.el.classList.toggle(`tcw-history-pill--error`,t),this.el.classList.remove(`tcw-history-pill--hidden`),this.el.removeAttribute(`aria-hidden`)}hide(){this.hideTimer=null,this.el.classList.add(`tcw-history-pill--hidden`),this.el.setAttribute(`aria-hidden`,`true`),this.text.textContent=``}clearTimer(){this.hideTimer!==null&&clearTimeout(this.hideTimer),this.hideTimer=null}},Su=`host:`;function Cu(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${Su}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function wu(e,t){return e.startsWith(Su)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var Tu=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),Eu={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},Du={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function Ou(e){let t=e.split(`+`).map(e=>e.trim()),n=t.pop();if(!n)return null;let r={ctrl:!1,alt:!1,shift:!1,display:[]};for(let e of t){let t=Eu[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(Eu[i])return null;if(/^[a-z]$/.test(i))r.code=`Key${i.toUpperCase()}`,r.char=i;else if(/^[0-9]$/.test(i))r.code=`Digit${i}`,r.char=i;else if(r.key=Du[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[Tu?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function ku(e,t){if((e.ctrlKey||e.metaKey)!==t.ctrl||e.altKey!==t.alt)return!1;if(t.code!==void 0){if(e.shiftKey!==t.shift)return!1;if(t.alt)return e.code===t.code;let n=e.key.length===1&&/^[a-z0-9]$/i.test(e.key)?e.key.toLowerCase():null;return n===null?e.code===t.code:n===t.char}return t.shift&&!e.shiftKey?!1:e.key.toLowerCase()===t.key}var Au=new Set(`escape(enter(delete(backspace(arrowleft(arrowright(arrowup(arrowdown(home(end(+(-(=( (,(.(ctrl+z(ctrl+shift+z(ctrl+y(ctrl+c(ctrl+v(ctrl+d(ctrl+g(ctrl+shift+g(ctrl+[(ctrl+]`.split(`(`));function ju(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return Au.has(t)}function Mu(e){let t=typeof e.composedPath==`function`?e.composedPath()[0]:e.target;return t instanceof HTMLElement?t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName):!1}var Nu=600,Pu=13,Fu=24,Iu=[`--tcw-toolbar-h`,`--tcw-control-h`,`--tcw-control-h-sm`,`--tcw-icon`,`--tcw-sidebar-w`,`--tcw-menu-item-h`,`--tcw-font-size`,`--tcw-font-size-sm`,`--tcw-font-size-xs`,`--tcw-font-size-lg`,`--tcw-font-size-xl`,`--tcw-font-size-display`],Lu=48,Ru=5e4,zu=100;function Bu(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,zu);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var Vu=[`#b552c9`,`#1398a8`,`#d4622b`,`#e25592`,`#6f7a8c`,`#3e9a4f`],Hu=864e5,Uu=1e3,Wu={alerts:`alerts`,objectTree:`objectTree`,dataWindow:`dataWindow`,symbolInfo:`symbolInfo`,depthLadder:`depthLadder`},Gu=2,Ku={alerts:`alerts`,objectTree:`objects`,symbolInfo:`symbolInfo`,depthLadder:`trade`};function qu(e){if(e.ctrlKey||e.metaKey||e.altKey||e.isComposing||e.keyCode===id||e.getModifierState?.(`AltGraph`))return null;if(/^[a-z]$/i.test(e.key))return e.key;let t=/^Key([A-Z])$/.exec(e.code??``);return t&&[...e.key].length===1&&!/[\s\d]/.test(e.key)?t[1].toLowerCase():null}var Ju=4,Yu=1,Xu=7,Zu=17,Qu=3,$u=150,ed=5e3,td=8,nd=6e4,rd=()=>{let e=document.activeElement;return e instanceof Element&&e.closest(`[role="dialog"], [aria-modal="true"], [role="menu"]`)!==null},id=229,ad=1e3,od=new Set([...oo,`autoScale`]),sd=[[`barCountdown`,`barCountdown`],[`logScale`,`logScale`],[`legendVisible`,`legend`],[`volumeVisible`,`volume`]],cd=[`legendVisible`,`volumeVisible`,`barCountdown`,`indicatorValueLabels`,`alignAxisLabels`],ld=E.filter(e=>n.CHART_STYLE_KEYS[e]!==`color`),ud=()=>typeof document<`u`&&document.hidden,dd=200;function fd(e){if(!e.feed)return e;if(e.adapter)throw TypeError(`A widget takes an adapter or a feed, not both`);return{...e,adapter:(0,r.adapterFromFeed)(e.feed),feed:void 0}}var pd=class{chart;state;themeOf={dark:n.DARK_THEME,light:n.LIGHT_THEME};toolbar=null;sidebar=null;settings=null;statusBar=null;goToDate=null;tooltip;indicatorLegend=null;legendFrame=0;portal=document.createElement(`div`);stopKeyboardInset=null;stopNarrow=null;stopFormControls=null;overlayHost=()=>{let e=document.fullscreenElement===this.root?this.root:document.body;return this.portal.parentElement!==e&&e.appendChild(this.portal),this.portal};unregisterKeys=()=>{};onFullscreenChange=()=>{this.inlineText?.commit(),this.toolbar?.setFullscreen(document.fullscreenElement===this.root),this.portal.isConnected&&this.overlayHost()};commandPalette=null;symbolSearch=null;dock=null;dockNarrow=null;dockObserver=null;hotkeySheet=null;replayBar=null;dragDrop=null;alertsPanel=null;objectTree=null;indicatorSettings=null;indicatorPicker=null;drawingStyle=null;drawingSettings=null;drawingMenu=null;justDrawnText=null;inlineText=null;inlineTextId=null;inlineTextNew=!1;chartFontWritten=null;cancelTextPrompt=null;clearMenu=null;selectionToolbar=null;selectionToolbarFrame=null;chartMenu=null;menuPane=null;canExport=!0;symbolLoads=new Map;ui;uiScale=1;uiVariables=!1;chartFontBase=null;scaleObserver=null;legendMenu=null;templates=new Wc;templatePrompt=null;chartTemplates=new Po;chartTemplatePrompt=null;drawingTemplatePrompt=null;settingsEdit=null;intervalInput=null;markerTip=null;accountPanel=null;orderTicket=null;accountFrame=0;layoutSession=null;layoutsUI=null;bracketBar=null;alertNotifier=null;depthLadder=null;dataWindow=null;lastHoverIndex=null;lastHoverBar=null;lastHoverPrevClose=null;legendHoverIndex=null;pointerOnChart=!1;favoritesStore=new nl;indicatorFavorites=new nl(`tcw:indicator-favorites`);indicatorDefaults=new ro;timeframeFavorites=new nl(`tcw:tf-favorites`);customTimeframes=new nl(`tcw:tf-custom`);timeframes=[];watchlist=null;watchlistSparkBuffer=new Map;sessionRefPrice=null;hostWatchlistRefPrice=new Map;watchlistInterval=null;watchlistStore=null;watchlistFromSymbols=!1;quoteSource=null;stopQuotes=null;quotedKey=``;quotes=new Map;symbolInfoPanel=null;news=new Si;marketTimer=null;clockTimer=null;onPageShown=null;chartNav=null;visibleBarCount=50;replayPollInterval=null;replaySpeed=1;replayBarsTotal=null;replayStepTime=null;replayStepsKey=null;replayStep=`auto`;replayStartSeq=0;replayPickTime=null;replayStartPending=!1;replayPlayWanted=!1;replayStepsCache=null;replayShade=null;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;root;chartContainer;loading;historyPill;connectSeq=0;localSeq=0;lastLocalSwitchMs=0;destroyed=!1;options;symbols;symbolCatalog;chartInfoAtSwitch=null;settingsState;settingsDefaults;settingsStore=null;settingsPublished=null;linkSettings=null;settingsListeners=new Set;settingsLocked=new Set;t;adapter=null;boundGlobalKeydown=null;baseSeries=null;baseTimeframeMs=0;builtInZone=void 0;chosenTimeframe=null;rangeSeq=0;rangeQueue=Promise.resolve();compares=[];compareWay=`percent`;comparesLoading=new Set;compareScaleHeld=!1;compareFetchSeq=0;compareOlderBusy=!1;compareOlderAgain=!1;compareOlderPassed=!1;featureState;hostHotkeys=[];hostMenus=new Set;hostLayer=null;priceAxisAddDefault=!1;constructor(i,a={}){let o=fd(a);this.options=o,this.replayStep=o.replayStep??`auto`;let s=Jt(o.symbols??he);this.symbols=s.names,this.symbolCatalog=s.info;let c=o.chartOptions;if(this.settingsState={...ge,...c?.crosshair?.mode?{crosshairMode:c.crosshair.mode}:{},...c?.logScale&&c.features?.logScale!==!1?{logScale:!0,scaleMode:`logarithmic`}:{},...c?.numberLocale?{numberLocale:c.numberLocale}:{},...c?.timeZone==null?{}:{timezone:d(c.timeZone)},...c?.leftPriceScale===void 0?{}:{leftPriceScale:c.leftPriceScale},...c?.highLowLines===void 0?{}:{highLowLines:c.highLowLines},...c?.extendedHours===void 0?{}:{extendedHours:c.extendedHours},...c?.chartTypeOptions?{chartTypeOptions:(0,n.readChartTypeOptions)(c.chartTypeOptions)}:{}},this.t=t.n(t.o(o.locale,o.messages)),this.featureState=Ve(o),o.persistLayouts){let e=o.persistLayouts===!0?{}:o.persistLayouts;this.layoutKeyPrefix=e.keyPrefix??`tcw:layout:`,this.layoutDebounceMs=e.debounceMs??1500}let l=To(o.persistSettings);l&&(this.settingsStore=new Do(l));let u=this.resolveIsDark(o.theme),p=this.resolveTheme(o.theme);this.themeOf={...this.themeOf,[u?`dark`:`light`]:p};let m={drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:o.trading!==!1,tradingContextMenu:!1,priceAxisAddButton:this.featureState.alerts||o.trading!==!1||this.featureState.sidebar,volume:!0,legend:!0,crosshair:!0,crosshairTooltip:!1,keyboard:!0,screenshot:!0,alerts:!0,barCountdown:!0,logScale:!0,watermark:!0,...o.chartOptions?.features};this.priceAxisAddDefault=m.priceAxisAddButton===!0;let h={...m,priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]};if(this.canExport=m.dataExport!==!1,this.settingsLocked=new Set(sd.filter(([,e])=>m[e]===!1).map(([e])=>e)),this.settingsDefaults={...this.settingsState,legendVisible:m.legend!==!1,volumeVisible:m.volume!==!1,barCountdown:m.barCountdown!==!1,indicatorValueLabels:m.indicatorValueLabels===!0,alignAxisLabels:m.alignAxisLabels!==!1},this.settingsState={...this.settingsDefaults},this.timeframes=Mt(Et(o.timeframes,m.timeframes),this.customTimeframes.list(),m.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let e=Dt(this.timeframes,m.defaultTimeframeFavorites,!!o.timeframes?.length);for(let t of e)this.timeframeFavorites.add(t)}let g=o.timeframe??`5m`,ee=!m.timeframes?.length||m.timeframes.includes(g)?g:this.timeframes[0]??g;this.state={symbol:o.symbol??this.symbols[0]??`BTCUSDT`,timeframe:ee,chartType:o.chartOptions?.chartType??`candlestick`,isDark:u,activeIndicators:new Map,activeTool:null,magnetEnabled:!1,magnetStrong:!1,eraser:!1,zoomArea:!1,stayInDrawing:!1,connectionState:o.adapter?`connecting`:`disconnected`,connectionMessage:o.adapter?this.t(`status.connecting`):``},Qe(),this.root=document.createElement(`div`),this.root.className=`tcw-root`,this.root.dataset.tcwTheme=u?`dark`:`light`;let _=o.dir===`ltr`||o.dir===`rtl`?o.dir:wd(o.locale)?`rtl`:`ltr`;this.root.dir=_,this.portal.dir=_,i.appendChild(this.root),this.tooltip=new El(this.root),this.portal.className=`tcw-root tcw-portal`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.stopKeyboardInset=rl([this.root,this.portal]),this.stopNarrow=il(this.root,e=>{this.toolbar?.fit(),e||this.sidebar?.closeOverlay(),this.syncRail()}),this.ui=G(o.ui),this.uiVariables=o.ui!==void 0,this.uiScale=this.scaleNow(),this.applyLookTokens(),typeof ResizeObserver<`u`&&(this.scaleObserver=new ResizeObserver(()=>this.fitScale()),this.scaleObserver.observe(this.root)),this.markSwitchedOff(),this.stopFormControls=fe([this.root,this.portal],{layer:this.overlayHost,labels:()=>({prevMonth:this.t(`calendar.prevMonth`),nextMonth:this.t(`calendar.nextMonth`),today:this.t(`calendar.today`)}),locale:()=>this.intlLocale()}),this.toolbar=new un(this.root,{symbols:this.symbols,timeframes:this.timeframeMenu(),timeframeFavorites:this.pinnedTimeframes(),chartTypes:o.chartTypes?pe.filter(e=>o.chartTypes.includes(e.value)):pe},{onSymbolClick:()=>this.handleSymbolClick(),onSymbolInfo:()=>this.toggleSymbolInfo(),onTimeframe:e=>this.handleTimeframe(e),onToggleTimeframeFavorite:e=>this.handleToggleTimeframeFavorite(e),onAddTimeframe:e=>this.handleAddTimeframe(e),onRemoveTimeframe:e=>this.handleRemoveTimeframe(e),onChartType:e=>this.handleChartType(e),onIndicators:()=>this.toggleIndicatorPicker(),onScreenshot:()=>this.chart.screenshot(),onSettings:()=>this.openSettings(),onToggleTheme:()=>this.handleToggleTheme(),onToggleReplay:()=>this.toggleReplay(),onToggleAlerts:()=>this.toggleAlerts(),onToggleObjects:()=>this.toggleObjects(),onToggleAccount:o.trading===!1?void 0:()=>this.toggleAccountPanel(),onLayouts:o.layouts===!1?void 0:e=>void this.layoutsUI?.openMenu(e),onBracket:o.trading===!1?void 0:e=>this.startBracket(e),onToggleLadder:o.trading!==!1&&o.depthLadder?()=>this.toggleLadder():void 0,onOrderTicket:o.trading===!1?void 0:()=>this.openOrderTicket(),onCompare:o.adapter&&m.compareSymbols!==!1?()=>this.handleAddCompare():void 0,onUndo:()=>this.chart.undo(),onRedo:()=>this.chart.redo(),onToggleFullscreen:typeof document<`u`&&document.fullscreenEnabled?()=>this.toggleFullscreen():void 0},this.t,this.overlayHost);let v=document.createElement(`div`);v.className=`tcw-body`,o.drawingFavorites&&this.favoritesStore.seedDefaults(o.drawingFavorites),this.sidebar=new yn(v,{drawingToolGroups:yt(me,this.t),favorites:this.favoritesStore.list(),shortcuts:ki()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onToggleMagnet:m.drawingMagnet===!1?void 0:()=>this.handleToggleMagnet(),onToggleEraser:()=>this.chart.setEraserMode(!this.chart.isEraserMode()),onToggleZoomArea:()=>this.chart.setZoomAreaMode(!this.chart.isZoomAreaMode()),onToggleFavorite:e=>this.handleToggleFavorite(e),onClear:e=>this.openClearMenu(e),onToggleStyle:()=>this.drawingStyle?.toggle(),onToggleStayInDrawing:()=>this.handleToggleStayInDrawing(),onLockAll:e=>{this.chart.setDrawingsLocked(this.chart.getDrawings().map(e=>e.id),e),this.refreshDrawingsState(),this.refreshObjects()},onHideAll:e=>{this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!e),this.refreshDrawingsState(),this.refreshObjects()}},this.t),this.chartContainer=document.createElement(`div`),this.chartContainer.className=`tcw-chart-container`,this.chartContainer.dir=`ltr`,v.appendChild(this.chartContainer),this.loading=new yu(this.chartContainer,this.t(`status.loading`)),this.historyPill=new xu(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),this.dock=new pl(v,{labels:{rail:this.t(`dock.rail`),resize:this.t(`dock.resize`)},savedWidth:()=>bd(),saveWidth:e=>xd(e),railShown:()=>this.railShown(),focusAfterClose:e=>this.panelFocusTarget(e),room:()=>v.clientWidth}),o.watchlist&&this.createWatchlist(v,o.watchlist===!0?{}:o.watchlist),this.root.appendChild(v);let y=document.createElement(`div`);y.className=`tcw-account-dock`,D(y,`accountPanel`),this.root.appendChild(y),this.chart=new e.c(this.chartContainer,{chartType:this.state.chartType,theme:p,autoScale:!0,crosshair:{mode:`magnet`},a11y:{labels:{role:this.t(`a11y.role`),summary:this.t(`a11y.summary`),empty:this.t(`a11y.empty`),view:this.t(`a11y.view`),bar:this.t(`a11y.bar`),keys:this.t(`a11y.keys`),typeName:e=>{let t=`chartType.${e}`,n=this.t(t);return n===t?e:n}}},...o.chartOptions,features:h}),o.chartOptions?.shapes||this.applyChartShapes(),this.chartInfoAtSwitch=this.chart.getSymbolInfo(),this.applyLegendFont(),this.applyChartLook();for(let[e,t]of this.indicatorDefaults.all())this.chart.setIndicatorDefaults(e,t.style);this.chart.on(`visibleRangeChange`,e=>{let{from:t,to:n}=e.payload;Number.isFinite(t)&&Number.isFinite(n)&&(this.visibleBarCount=Math.max(1,n-t))}),this.chartNav=new Pi(this.chartContainer,{zoomIn:()=>this.chart.zoomIn(),zoomOut:()=>this.chart.zoomOut(),scroll:e=>this.chart.scrollBars(e*Math.max(1,Math.round(this.visibleBarCount/10))),reset:()=>this.resetView(),plotRect:()=>this.chart.getPlotRect()},this.t),this.chart.on(`dataUpdate`,e=>this.handleDataUpdate(e.payload)),this.chart.on(`historyLoad`,e=>{let t=e.payload;this.historyPill.update(t),t.state===`loaded`&&this.extendPercentCompares()}),this.chart.on(`symbolInfoChange`,()=>{this.refreshSymbolTitle(),this.refreshMarket(),this.rebuildForZone(),this.refreshPriceTexts()}),this.chart.on(`marketChange`,()=>this.rebuildForZone()),this.refreshSymbolTitle(),this.symbolInfoPanel=new gi(this.root,this.t,{onClose:()=>this.closePanelByHand(`symbolInfo`),onToggle:e=>{this.toolbar?.setActive(`symbolInfo`,e),e&&(this.refreshSymbolInfo(),this.loadNews())}}),this.marketTimer=setInterval(()=>this.refreshMarket(),3e4),this.onPageShown=()=>{ud()||this.refreshMarket()},document.addEventListener(`visibilitychange`,this.onPageShown),this.dragDrop=new e.o(this.chartContainer,{onData:(e,n,r)=>{this.setData(e);let i=t.r(this.t(`toast.fileLoaded`),{count:n.data.length,file:r.name});this.say(n.skipped>0?`${i} (${t.r(this.t(`toast.fileSkipped`),{count:n.skipped})})`:i)},onError:(e,t)=>{this.say(`${t.name}: ${e.message}`,`error`)}}),this.featureState.dragDropImport&&this.dragDrop.attach(),m.drawingMagnet!==!1&&this.chart.setDrawingMagnetMode(`off`),this.statusBar=new tr(this.root,{presets:r.RANGE_PRESETS,presetLabels:{All:this.t(`range.all`)},groupLabel:this.t(`range.presets`),goToLabel:this.t(`range.goTo`),moreLabel:this.t(`toolbar.more`),onPreset:e=>void this.applyRangePreset(e),onGoTo:()=>this.toggleGoToDate(),goToKeys:()=>this.keysShown(`hotkeys.goToDate`,`Alt+G`)},{label:this.t(`statusBar.label`),clock:{label:this.t(`settings.timezone`),now:()=>this.clockNow(),options:()=>({current:this.settingsState.timezone,list:f(this.settingsState.timezone,Date.now(),this.t(`settings.timezone.local`),this.exchangeChoice())}),onPick:e=>this.changeSettings({timezone:e})},scale:{labels:{group:this.t(`settings.priceScale`),percent:this.t(`settings.scale.percentage`),log:this.t(`settings.scale.logarithmic`),auto:this.t(`settings.autoScale`)},texts:{log:this.t(`statusBar.log`),auto:this.t(`statusBar.auto`)},onPercent:()=>this.toggleScaleMode(`percentage`),onLog:m.logScale===!1?void 0:()=>this.toggleScaleMode(`logarithmic`),onAuto:()=>this.changeSettings({autoScale:!this.chart.isAutoScale()})}}),this.clockTimer=setInterval(()=>{!ud()&&this.featureState.statusBar&&this.featureState[`statusBar.clock`]&&this.statusBar?.tick()},ad),this.chart.on(`priceRangeChange`,()=>this.refreshScaleSwitches()),this.refreshScaleSwitches(),this.goToDate=new ul(this.overlayHost,()=>({title:this.t(`goTo.title`),date:this.t(`range.date`),range:this.t(`goTo.range`),from:this.t(`goTo.from`),to:this.t(`goTo.to`),time:this.t(`range.time`),submit:this.t(`range.goToSubmit`),cancel:this.t(`range.cancel`),close:this.t(`common.close`),calendar:{prevMonth:this.t(`calendar.prevMonth`),nextMonth:this.t(`calendar.nextMonth`),today:this.t(`calendar.today`)}}),()=>this.intlLocale(),e=>this.goTo(e)),this.settings=new Un({onChange:e=>this.changeSettings(e),onReset:()=>this.resetSettings(),onClose:()=>this.endSettingsEdit(!0),onCancel:()=>this.endSettingsEdit(!1),templates:{list:()=>this.chartTemplates.list().map(e=>e.name),apply:e=>this.applyChartTemplate(e),remove:e=>this.chartTemplates.remove(e),save:()=>this.promptSaveChartTemplate()},styleValue:e=>this.chart.getStyleValue?.(e)??null,onStyleChange:e=>this.changeStyle(e)},this.t,{barCountdown:m.barCountdown,logScale:m.logScale,legend:m.legend,volume:m.volume,trading:m.trading!==!1,exchangeZone:()=>this.exchangeChoice()?.zone},this.overlayHost),this.symbolSearch=new Gr({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t),this.hotkeySheet=new Xr({onClose:()=>{}},this.t,this.overlayHost),this.chart.on(`drawingToolChange`,e=>{let t=e.payload.tool;t!==this.state.activeTool&&(this.state={...this.state,activeTool:t},this.updateUI())}),this.chart.on(`toolModeChange`,e=>{let{eraser:t,zoomArea:n}=e.payload;this.state={...this.state,eraser:t??this.state.eraser,zoomArea:n??this.state.zoomArea},this.updateUI()}),this.chart.on(`indicatorAdd`,()=>this.syncIndicatorsFromChart()),this.chart.on(`indicatorRemove`,()=>this.syncIndicatorsFromChart()),this.chart.on(`legendResize`,()=>this.scheduleLegend()),this.chart.setPaneTitlesVisible(!this.featureState.indicatorLegend),this.indicatorLegend=new Ll(this.chartContainer,{onToggleVisible:(e,t,n)=>{n===`compare`?this.chart.setCompareVisible(e,t):this.chart.setIndicatorVisible(e,t),this.scheduleLegend(),this.objectTree?.isOpen()&&this.refreshObjects()},onSettings:e=>{this.featureState[`indicatorLegend.settings`]&&this.openIndicatorSettings(e)},onRemove:(e,t)=>{this.isPercentCompare(e)?this.handleRemoveCompare(e):t===`compare`?this.removeHostCompare(e):this.handleRemoveIndicator(e)},onMore:(e,t)=>this.openLegendMenu(e,t),onPaneAction:(e,t)=>this.runPaneAction(e,t),onStackResize:e=>this.chart.setLegendStack?.(e?{width:Ju+e.width,height:Yu+e.height}:null)},{show:this.t(`legend.show`),hide:this.t(`legend.hide`),settings:this.t(`legend.settings`),remove:this.t(`legend.remove`),collapse:this.t(`legend.collapse`),expand:this.t(`legend.expand`),more:this.t(`legend.more`),paneUp:this.t(`pane.moveUp`),paneDown:this.t(`pane.moveDown`),paneCollapse:this.t(`pane.collapse`),paneExpand:this.t(`pane.expand`),paneMaximize:this.t(`pane.maximize`),paneRestore:this.t(`pane.restore`),offInterval:this.t(`indicatorSettings.offInterval`),offChartType:this.t(`legend.offChartType`)}),this.legendMenu=new A(this.root,this.t(`legend.more`)),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.pointerOnChart=!0,this.legendHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.scheduleLegend()}),this.chart.on(`crosshairLeave`,()=>{this.pointerOnChart=!1,this.legendHoverIndex=null,this.scheduleLegend()}),this.chart.on(`crosshairSync`,e=>{if(this.pointerOnChart)return;let t=e.payload;this.legendHoverIndex=t.bar&&t.barIndex!==null?t.barIndex:null,this.scheduleLegend()});for(let e of[`indicatorUpdate`,`indicatorChange`,`dataUpdate`,`resize`,`paneResize`,`paneChange`,`themeChange`,`timeframeChange`,`visibleRangeChange`,`compareChange`])this.chart.on(e,()=>this.scheduleLegend());this.chart.on(`chartTypeChange`,()=>{this.compareScaleHeld&&this.showHeldScale(),this.scheduleLegend()}),this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let{barIndex:t,bar:n}=e.payload;if(typeof t==`number`){if(this.seriesPending()){let e=n?.time??this.chart.getData()[t]?.time;this.replayBar.getMode()===`select`&&typeof e==`number`&&(this.replayPickTime=e);return}if(this.replayBar.getMode()===`select`){this.startReplayAt(t,!1,!0);return}this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeekToBar(t),this.replayBar.setState(`paused`)}}),this.chart.on(`crosshairMove`,e=>{if(this.replayBar?.getMode()!==`select`||!this.replayBar.isMounted())return;let t=e.payload.point;this.positionReplayShade(this.seriesPending()?null:t?.x??null)}),this.chart.on(`replayStep`,e=>{let t=e.payload;this.replayBarsTotal=t.total,this.replayStepTime=typeof t.stepTime==`number`?t.stepTime:t.time,queueMicrotask(()=>{this.destroyed||(t.cause===`series`?this.afterReplayCarryOver():this.syncReplayBar())})});for(let e of[`resize`,`dataUpdate`,`symbolInfoChange`])this.chart.on(e,()=>this.placeDrawingButton());this.placeDrawingButton();for(let e of[`resize`,`paneResize`,`paneChange`])this.chart.on(e,()=>this.layoutReplayBar());this.chart.on(`replayStepsLoad`,e=>{e.payload.state===`error`&&this.say(this.t(`replay.stepsFailed`),`error`)}),this.chart.on(`timeframeChange`,()=>this.refreshReplaySteps()),this.dataWindow=new iu(this.root,{formatPrice:e=>this.formatAlertPrice(e),formatPercent:e=>this.formatNumber(e,2),formatVolume:e=>this.formatVolume(e),onClose:()=>this.closePanelByHand(`dataWindow`)},this.t),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.lastHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.lastHoverBar=t.bar??null,this.lastHoverPrevClose=typeof t.prevClose==`number`?t.prevClose:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())}),this.chart.on(`crosshairSync`,e=>{if(this.pointerOnChart)return;let t=e.payload;this.lastHoverIndex=t.bar&&t.barIndex!==null?t.barIndex:null,this.lastHoverBar=t.bar??null,this.lastHoverPrevClose=typeof t.prevClose==`number`?t.prevClose:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())});let b=new zo,x=new Bo;for(let[e,t]of Object.entries(x.all()))this.chart.setDrawingToolDefaults(e,t??null);this.drawingSettings=new Ps(this.root,{onBegin:e=>this.chart.beginDrawingEdit(e),onChange:(e,t)=>this.chart.updateDrawing(e,t),onEnd:(e,t)=>{this.chart.endDrawingEdit(e,{cancel:t}),t&&e===this.justDrawnText&&this.chart.takeBackDrawing(e),this.justDrawnText=null,this.refreshObjects()},toWallTime:e=>Q(e*(0,n.barTimeUnit)(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let r=sl(e,t,this.displayTimezone());return r===null?null:r/(0,n.barTimeUnit)(this.chart.getData())},roundPrice:e=>this.chart.roundPrice(e),priceStep:()=>this.chart.getPriceStep(),onSaveDefault:(e,n)=>{this.chart.setDrawingToolDefaults(e,n),x.set(e,this.chart.getDrawingToolDefaults(e)),this.say(t.r(this.t(`drawingSettings.defaultSaved`),{name:this.drawingToolName(e)}))},templates:{list:e=>b.list(e),save:e=>this.promptSaveDrawingTemplate(b,e),remove:(e,t)=>b.remove(e,t)}},this.t),this.inlineText=new Us(this.overlayHost),this.chart.on(`drawingDoubleClick`,e=>{let t=e.payload.id,n=this.chart.getDrawings().find(e=>e.id===t)?.type;n&&gs[n]&&this.editTextInPlace(t,!1)||this.openDrawingSettings(t,n&&gs[n]?{tab:`text`}:{})}),this.chart.on(`drawingRemove`,e=>{let t=e.payload.id;t===this.inlineTextId&&(this.inlineText?.close(),this.inlineTextNew||this.chart.endDrawingEdit(t),this.inlineTextId=null)}),this.chart.on(`drawingCreate`,e=>{let{id:t,type:n,drawn:r}=e.payload;if(!r||!gs[n])return;this.cancelTextPrompt?.();let i=0,a=()=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,s),clearTimeout(i),this.cancelTextPrompt=null},o=()=>{a(),!(this.destroyed||!this.chart.getDrawings().some(e=>e.id===t))&&(this.editTextInPlace(t,!0)||(this.openDrawingSettings(t,{tab:`text`}),this.drawingSettings?.isOpen()&&(this.justDrawnText=t)))},s=()=>setTimeout(o,0);window.addEventListener(`pointerup`,s),window.addEventListener(`pointercancel`,s),i=window.setTimeout(o,Nu),this.cancelTextPrompt=a}),this.drawingStyle=new Wo(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},b,this.t),this.drawingMenu=new A(this.root,this.t(`drawingMenu.label`)),this.chart.on(`drawingContextMenu`,e=>{let{id:t,x:n,y:r}=e.payload;this.openDrawingMenu(t,n,r)}),this.selectionToolbar=new $o(this.root,{onStyle:e=>{for(let t of this.chart.getSelectedDrawingIds()){let n=this.chart.getDrawings().find(e=>e.id===t)?.type,r=n?gs[n]:void 0,i=e.fillColor!==void 0&&r&&!r.box?{...e,textBackground:!0}:e;this.chart.setSelectedDrawingStyle(i,t)}this.updateSelectionToolbar()},onSettings:()=>{let e=this.chart.getSelectedDrawingIds()[0];e&&this.openDrawingSettings(e)},onAlert:()=>{let e=this.chart.getSelectedDrawingIds()[0];e&&this.addDrawingAlert(e)},onLock:e=>{this.chart.setDrawingsLocked(this.chart.getSelectedDrawingIds(),e),this.refreshObjects(),this.updateSelectionToolbar()},onMore:(e,t)=>{let n=this.chart.getSelectedDrawingIds()[0];if(!n)return;let r=this.chartOffset();this.openDrawingMenu(n,e-r.x,t-r.y)},onDelete:()=>{this.chart.removeDrawings(this.chart.getSelectedDrawingIds()),this.refreshObjects(),this.updateSelectionToolbar()}},this.t);for(let e of[`drawingCreate`,`drawingUpdate`,`drawingRemove`])this.chart.on(e,()=>this.refreshDrawingsState());this.chart.on(`historyChange`,e=>{let{canUndo:t,canRedo:n}=e.payload;this.toolbar?.setHistory(t,n)});for(let e of[`drawingSelect`,`drawingToolChange`,`toolModeChange`])this.chart.on(e,()=>this.updateSelectionToolbar());for(let e of[`drawingUpdate`,`drawingRemove`,`historyChange`,`visibleRangeChange`,`priceRangeChange`,`zoomChange`,`resize`,`paneResize`,`paneChange`,`dataUpdate`,`replayStep`,`chartTypeChange`])this.chart.on(e,()=>this.scheduleSelectionToolbar());if(this.chartMenu=new A(this.root,this.t(`chartMenu.label`),this.t(`common.back`)),this.chart.on(`symbolSeriesRequest`,e=>void this.loadSymbolSeries(e.payload.symbol)),this.chart.on(`chartContextMenu`,e=>{if(!this.featureState[`menu.chart`])return;let{area:t,x:n,y:r,price:i,time:a,pane:o}=e.payload,s=i===void 0?void 0:this.chart.roundPrice(i),c={...this.chartMenuContext(s),...o?{pane:this.chart.getPaneScale(o)}:{}};this.menuPane=o??null,this.openChartMenu(Ye(nc(t,c,this.t),Le,this.featureState),n,r,{area:t,price:s,time:a})}),this.chart.on(`priceAxisAdd`,e=>{if(!this.featureState[`menu.priceAxisAdd`])return;let{price:t,x:n,y:r}=e.payload,i=this.chart.roundPrice(t),a=Ye(Xs(this.chartMenuContext(i),this.t),Le,this.featureState);this.openChartMenu(a,n,r,{area:`priceAxisAdd`,price:i})}),this.chart.on(`signalMarkerHover`,e=>this.showMarkerTip(e.payload)),this.intervalInput=new Uc(this.chartContainer,{title:this.t(`interval.title`),hint:this.t(`interval.hint`),invalid:this.t(`interval.invalid`)},e=>this.selectTypedTimeframe(e)),o.layouts!==!1&&this.setupLayouts(o.layouts===!0||o.layouts===void 0?{}:o.layouts),o.trading!==!1){this.orderTicket=new Mc(this.root,{onSubmit:e=>{this.chart.placeOrderIntent(e),this.say(t.r(this.t(`ticket.sent`),{side:this.t(e.side===`buy`?`ticket.buy`:`ticket.sell`),quantity:e.quantity??1,price:this.formatAlertPrice(e.price)}))},formatPrice:e=>this.formatAlertPrice(e),formatAmount:e=>this.formatMoney(e),formatNumber:(e,t)=>this.formatNumber(e,t)},this.t),this.accountPanel=new vc(y,{onClosePosition:e=>this.chart.closePositionIntent(e),onReversePosition:e=>this.chart.reversePositionIntent(e),onCancelOrder:e=>this.chart.cancelOrderIntent(e),onNewOrder:()=>this.openOrderTicket(),formatPrice:e=>this.formatAlertPrice(e),formatTime:e=>{let{date:t,time:n}=Q(e,this.displayTimezone());return`${t} ${n}`},formatAmount:e=>this.formatMoney(e),formatNumber:(e,t)=>this.formatNumber(e,t),onToggle:e=>{this.toolbar?.setActive(`account`,e),this.refreshAccount()}},this.t);for(let e of[`ordersChange`,`positionsChange`,`executionFill`,`dataUpdate`,`indicatorUpdate`])this.chart.on(e,()=>this.refreshAccountSoon())}if(o.trading!==!1){if(this.bracketBar=new Zl(this.chartContainer,{onConfirm:()=>this.chart.confirmBracket(),onCancel:()=>{this.chart.cancelBracket(),this.bracketBar?.hide()}},this.t),this.chart.on(`bracketPlace`,e=>{let n=e.payload;this.bracketBar?.hide(),this.say(t.r(this.t(n.side===`buy`?`bracket.longPlaced`:`bracket.shortPlaced`),{rr:n.riskReward.toFixed(2)}))}),o.depthLadder){this.depthLadder=new tu(this.root,{onTrade:(e,n)=>{this.chart.placeOrderIntent({side:e,type:`limit`,price:n}),this.say(t.r(this.t(e===`buy`?`order.buyLimit`:`order.sellLimit`),{price:this.formatAlertPrice(n)}))},formatPrice:e=>this.formatAlertPrice(e),priceStep:e=>this.chart.getPriceStep(e),onToggle:e=>this.toolbar?.setActive(`ladder`,e),onClose:()=>this.closePanelByHand(`depthLadder`)},void 0,this.t);let e=this.depthLadder;this.chart.on(`ordersChange`,()=>e.setOrders(this.chart.getOrders()))}this.chart.on(`dataUpdate`,e=>{e.payload.kind===`bracket`&&this.bracketBar?.hide()})}this.alertsPanel=new Ui(this.root,{onClose:()=>this.closePanelByHand(`alerts`),onAdd:({price:e,condition:t,message:n,channel:r,label:i,options:a})=>{try{return this.chart.addAlert(e,t,n,r,i,a),!0}catch{return this.say(this.t(`alerts.invalid`),`error`),!1}},formatTime:e=>{let{date:t,time:n}=Q(e,this.displayTimezone());return`${t} ${n}`},onRemove:e=>this.chart.removeAlert(e),onClear:()=>this.chart.clearAlerts(),getChannelValue:e=>this.getAlertChannelValue(e),formatPrice:e=>this.formatAlertPrice(e)},this.t),this.chart.on(`alertAdd`,()=>this.refreshAlerts()),this.chart.on(`alertRemove`,()=>this.refreshAlerts()),this.chart.on(`alertUpdate`,()=>this.refreshAlerts()),this.chart.on(`alertExpired`,e=>{let n=e.payload;this.refreshAlerts(),this.featureState.alerts&&this.say(t.r(this.t(`alerts.expiredToast`),{text:n.message??this.alertText(n)}))}),o.alertNotifications&&(this.alertNotifier=new Ql(o.alertNotifications)),this.chart.on(`alertTriggered`,e=>{let n=e.payload;if(this.refreshAlerts(),!this.featureState.alerts)return;let r=`${this.alertText(n)}${n.message?` — ${n.message}`:``}`;this.say(t.r(this.t(`alerts.fired`),{text:r}),`info`,`bell`),this.alertNotifier?.notify(r)}),this.indicatorPicker=new Qa(this.overlayHost,{onAdd:e=>this.handleAddIndicator(e),onFavorite:(e,t)=>t?this.indicatorFavorites.add(e):this.indicatorFavorites.remove(e),templates:{onApply:e=>this.applyIndicatorTemplate(e),onDelete:e=>{this.templates.remove(e),this.indicatorPicker?.setTemplates(this.templateNames())},onSave:()=>this.promptSaveIndicatorTemplate()},onClose:()=>this.toolbar?.setIndicatorsOpen(!1)},this.t),this.indicatorSettings=new Ga(this.root,{onApply:(e,t)=>{this.chart.updateIndicator(e,t),this.syncIndicatorsFromChart()},onStyle:(e,t)=>this.chart.updateIndicatorStyle(e,t),onLevels:(e,t)=>this.chart.setIndicatorLevels(e,t),onScale:(e,t)=>this.chart.setIndicatorScale(e,t),onIntervals:(e,t)=>this.chart.setIndicatorIntervals(e,t),onSaveDefault:(e,t)=>this.saveIndicatorDefault(e,t),onClose:()=>this.chart.endIndicatorEdit()},this.t),this.objectTree=new xa(this.root,{onClose:()=>this.closePanelByHand(`objectTree`),onRemoveIndicator:e=>this.handleRemoveIndicator(e),onConfigureIndicator:e=>this.openIndicatorSettings(e),onToggleIndicatorVisible:(e,t)=>{this.chart.setIndicatorVisible(e,t),this.refreshObjects(),this.scheduleLegend()},onRemoveDrawing:e=>{this.drawingSettings?.editing()===e&&this.drawingSettings.close(!0),this.chart.removeDrawing(e),this.refreshObjects()},onConfigureDrawing:this.drawingSettings?e=>this.openDrawingSettings(e):void 0,onToggleDrawingVisible:(e,t)=>{this.chart.setDrawingVisible(e,t),this.refreshObjects()},onToggleDrawingLocked:(e,t)=>{this.chart.setDrawingLocked(e,t),this.refreshObjects()},onToggleGroupVisible:(e,t)=>{this.chart.setDrawingGroupVisible(e,t),this.refreshObjects()},onToggleGroupLocked:(e,t)=>{this.chart.setDrawingGroupLocked(e,t),this.refreshObjects()},onUngroup:e=>{this.chart.ungroupDrawings(e),this.refreshObjects()},onRenameGroup:(e,t)=>{this.chart.renameDrawingGroup(e,t),this.refreshObjects()},onSelectDrawing:e=>this.chart.selectDrawing(e),onRenameDrawing:(e,t)=>{this.chart.updateDrawing(e,{name:t||null}),this.refreshObjects()},onCloneDrawing:e=>{this.chart.duplicateDrawing(e),this.refreshObjects()},onMoveDrawing:(e,t)=>{this.chart.moveDrawing(e,t),this.refreshObjects()},onAddCompare:m.compareSymbols===!1?void 0:()=>this.handleAddCompare(),onRemoveCompare:e=>this.removeCompared(e)},this.t);let te=()=>{this.objectTree?.isOpen()&&this.refreshObjects()},ne=0,S=()=>{ne||!this.objectTree?.isOpen()||(ne=requestAnimationFrame(()=>{ne=0,this.destroyed||te()}))};this.chart.on(`drawingCreate`,te),this.chart.on(`drawingRemove`,te),this.chart.on(`drawingUpdate`,S),this.chart.on(`timeframeChange`,S),this.chart.on(`indicatorAdd`,te),this.chart.on(`indicatorRemove`,te),this.chart.on(`indicatorChange`,te);for(let e of[`indicatorAdd`,`indicatorRemove`,`indicatorChange`])this.chart.on(e,()=>this.refreshCompareDialog());this.setupDock(),this.commandPalette=new dr({onIndicator:e=>this.handleAddIndicator(e),onChartType:e=>this.handleChartType(e),onDrawingTool:e=>this.handleDrawingTool(e),onTimeframe:e=>this.handleTimeframe(e),onAction:e=>this.handleAction(e),onClose:()=>{}},this.overlayHost,this.t,{list:()=>_d(),add:e=>vd([e,..._d().filter(t=>t!==e)])}),this.boundGlobalKeydown=e=>{if(this.handleHostHotkey(e)||this.featureState.hotkeys&&this.replayBar?.isMounted()&&this.handleReplayKey(e))return;let t=Yc(this.root),n=e=>this.featureState.hotkeys&&this.featureState[e];if((e.ctrlKey||e.metaKey)&&e.key===`k`){if(!t||!n(`hotkeys.commandPalette`)||!this.featureState.commandPalette)return;e.preventDefault(),this.toggleCommandPalette()}else if((e.ctrlKey||e.metaKey)&&(e.key===`p`||e.key===`P`)){if(!t||!n(`hotkeys.symbolSearch`)||!this.featureState.symbolSearch)return;e.preventDefault(),this.openSymbolSearch()}else if((e.ctrlKey||e.metaKey)&&!e.altKey&&!e.shiftKey&&(e.key===`s`||e.key===`S`)){if(!this.layoutSession||!n(`hotkeys.save`)||!this.featureState.layouts||Z()||!Yc(this.root,!0))return;e.preventDefault(),this.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&Oi[e.code]){if(e.defaultPrevented||Z()||!t||rd()||!n(`hotkeys.tools`))return;e.preventDefault(),this.handleDrawingTool(Oi[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervalInput||!n(`intervalTyping`)||Z()||rd()||!Yc(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.intervalInput.open(e.key)}else if(qu(e)!==null){if(e.defaultPrevented||!n(`symbolTyping`)||!this.featureState.symbolSearch||Z()||rd()||!Yc(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.openSymbolSearch(qu(e))}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`||e.code===`KeyR`)){if(Z()||!t)return;if(e.code===`KeyI`){if(!n(`hotkeys.invertScale`))return;e.preventDefault(),this.changeSettings({invertScale:!this.settingsState.invertScale}),this.settings?.refresh(this.shownSettings())}else if(e.code===`KeyR`){if(!n(`hotkeys.resetView`))return;e.preventDefault(),this.resetView()}else this.goToDate&&n(`hotkeys.goToDate`)&&this.featureState.goToDate&&(e.preventDefault(),this.toggleGoToDate())}else if(e.key===`?`&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(Z()||!t||!n(`hotkeys.help`)||!this.featureState.hotkeySheet)return;e.preventDefault(),this.openHotkeySheet()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=Jc(this.root,[this.portal]),this.restoreKeptSettings(),o.adapter?(this.adapter=o.adapter,this.connectStream()):this.chart.setDataTimeframe(this.state.timeframe),this.watchlist&&(this.watchlistInterval=setInterval(()=>this.tickWatchlist(),1e3)),this.markSwitchedOff(),requestAnimationFrame(()=>{this.destroyed||(this.toolbar?.tidy(),this.sidebar?.tidy())}),this.refreshMarket(),this.updateUI(),queueMicrotask(()=>{if(!this.destroyed)try{o.onReady?.(this.chart,this)}finally{this.destroyed||this.restoreSharedView()}})}restoreSharedView(){if(!this.options.shareUrl||typeof location>`u`)return;let e=gu(location.hash);e&&this.importState(e)}setSymbols(e){let t=Jt(e);this.symbols=t.names,this.symbolCatalog=t.info;let n=this.watchlistStore;n&&this.watchlistFromSymbols&&n.replace(n.getLists().map(e=>e.id===`default`?{...e,symbols:t.names}:e)),this.refreshSymbolTitle(),this.refreshSymbolInfo()}symbolEntries(){return this.symbols.map(e=>this.symbolCatalog.get(e)??e)}chartSymbolInfo(){let e=this.chart.getSymbolInfo(),t=e&&e!==this.chartInfoAtSwitch?e:en(this.state.symbol,e);return t?Yt(t,this.state.symbol):null}displayInfo(){return Zt(this.symbolCatalog.get(this.state.symbol),this.chartSymbolInfo())??null}refreshSymbolTitle(){this.toolbar?.setSymbolDescription(tn(this.displayInfo()))}getWatchlists(){return this.watchlistStore?.getLists()??[]}getActiveWatchlist(){return this.watchlistStore?.getActive().id??null}setWatchlists(e,t){this.watchlistFromSymbols=!1,this.watchlistStore?.replace(e,t)}setActiveWatchlist(e){this.watchlistStore?.setActive(e)}addToWatchlist(e,t){this.watchlistStore?.add(e,t)}removeFromWatchlist(e,t){this.watchlistStore?.removeSymbol(e,t)}setQuotes(e){let t=e.map(n.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)}getQuote(e){let t=this.quotes.get(e);return t?{...t}:null}openPanel(e){return!this.hasPanel(e)||!this.dock?!1:(this.dock.open(e),this.dock.current()===e)}hasPanel(e){return e===`watchlist`?this.watchlist!==null:e===`depthLadder`&&this.depthLadder===null?!1:this.featureState[Wu[e]]}closePanel(){this.dock?.close()}getOpenPanel(){return this.dock?.current()??null}toggleSymbolInfo(e){let t=this.symbolInfoPanel;if(!t)return;let n=e??!t.isOpen();n&&!this.featureState.symbolInfo||(n?this.dock?.open(`symbolInfo`):this.dock?.closePage(`symbolInfo`))}refreshMarket(){if(ud())return;let e=(0,n.marketStatus)(this.chart.getSymbolInfo(),Date.now()),t=e.state===`open`;this.statusBar?.setMarket(e.state,this.t(t?`symbolInfo.open`:`symbolInfo.closed`),this.t(t?`statusBar.marketOpen`:`statusBar.marketClosed`)),this.refreshSymbolInfo()}refreshSymbolInfo(){let e=this.symbolInfoPanel;!e?.isOpen()||this.destroyed||e.render(this.symbolInfoView())}symbolInfoView(){let e=this.state.symbol;return xi({symbol:e,info:this.chart.getSymbolInfo(),names:this.displayInfo(),quote:this.quotes.get(e),bars:this.chart.getData(),formatPrice:e=>this.formatAlertPrice(e),t:this.t,textLocale:this.textLocale(),numberLocale:this.intlLocale(),now:Date.now()})}loadNews(){let e=this.symbolInfoPanel;if(!e?.isOpen())return;let t=this.options.adapter,n=this.options.news??(t?.fetchNews?t.fetchNews.bind(t):null);this.news.load(this.state.symbol,n,t=>e.renderNews(t),this.textLocale(),()=>this.destroyed)}intlLocale(){return this.settingsState.numberLocale||this.options.locale||`en`}textLocale(){return this.options.locale||`en`}createWatchlist(e,t){let n=t.persist?Sd():null,r=new hi({lists:t.lists,activeList:t.activeList,symbols:this.symbols,defaultName:this.t(`watchlist.title`),storage:n,storageKey:t.storageKey});this.watchlistStore=r,this.watchlistFromSymbols=!t.lists&&!t.persist,this.quoteSource=t.quotes===!1?null:t.quotes??(this.options.adapter?.subscribeQuotes?this.options.adapter:null);let i=e=>this.t(e);this.watchlist=new ii(e,{onSelect:e=>{this.setSymbol(e)},onAdd:()=>this.symbolSearch?.open({symbols:this.symbolEntries(),current:this.state.symbol,currentInfo:this.chartSymbolInfo(),onPick:e=>r.add(e),search:this.symbolSearchFn()}),onRemove:e=>r.removeSymbol(e),onMove:(e,t)=>r.move(e,t),onPickList:e=>r.setActive(e),onCreateList:e=>r.create(e),onRenameList:(e,t)=>r.rename(e,t),onDeleteList:e=>r.remove(e),onClose:()=>this.closePanelByHand(`watchlist`)},{close:i(`common.close`),title:i(`watchlist.title`),lists:i(`watchlist.lists`),newList:i(`watchlist.newList`),rename:i(`watchlist.rename`),deleteList:i(`watchlist.deleteList`),confirmDelete:i(`watchlist.confirmDelete`),add:i(`watchlist.add`),remove:i(`watchlist.remove`),empty:i(`watchlist.empty`),listName:i(`watchlist.listName`)}),this.watchlist.setActive(this.state.symbol),this.watchlist.setLocale(this.settingsState.numberLocale||void 0);let a=()=>{this.watchlist?.setLists(r.getLists(),r.getActive().id),this.followQuotes()};r.subscribe(()=>{a(),t.onChange?.(r.getLists(),r.getActive().id)}),a()}followQuotes(){if(!this.quoteSource||!this.watchlistStore||this.destroyed)return;let e=this.watchlistStore.getActive().symbols,t=[...e].sort().join(`\0`);if(t!==this.quotedKey&&(this.quotedKey=t,this.stopQuotes?.(),this.stopQuotes=null,e.length!==0))try{this.stopQuotes=this.quoteSource.subscribeQuotes(e,e=>{if(this.destroyed||!Array.isArray(e))return;let t=e.map(n.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)})}catch{this.stopQuotes=null}}takeQuotes(e){for(let t of e){let e={...this.quotes.get(t.symbol),...t};this.quotes.set(e.symbol,e);let n=this.watchlistSparkBuffer.get(e.symbol)??[];n.push(e.last),n.length>40&&n.shift(),this.watchlistSparkBuffer.set(e.symbol,n);let r=this.hostWatchlistRefPrice.get(e.symbol);this.watchlist?.setEntry(e.symbol,{lastPrice:e.last,refPrice:r??(e.change===void 0?void 0:e.last-e.change),sparkline:n.slice()})}e.some(e=>e.symbol===this.state.symbol)&&this.refreshSymbolInfo()}async setSymbol(e){this.flushActiveLayout(),e!==this.state.symbol&&(this.chart.clearFills(),this.chartInfoAtSwitch=this.chart.getSymbolInfo()),this.state={...this.state,symbol:e},this.sessionRefPrice=null,this.options.onSymbolChange?.(e),this.updateUI(),this.refreshSymbolTitle(),this.watchlist?.setActive(e),this.refreshMarket(),this.loadNews(),this.layoutSession?.changed(),this.adapter&&await this.connectStream()}setWatchlistEntry(e,t){t.refPrice!==void 0&&this.hostWatchlistRefPrice.set(e,t.refPrice),this.watchlist?.setEntry(e,t)}tickWatchlist(){if(!this.watchlist||this.quotes.has(this.state.symbol)||ud())return;let e=this.chart.getData();if(e.length===0)return;let t=e[e.length-1],n=this.hostWatchlistRefPrice.get(this.state.symbol);n===void 0&&this.sessionRefPrice===null&&(this.sessionRefPrice=e[0].open);let r=this.watchlistSparkBuffer.get(this.state.symbol)??[];r.push(t.close),r.length>40&&r.shift(),this.watchlistSparkBuffer.set(this.state.symbol,r),this.watchlist.setEntry(this.state.symbol,{lastPrice:t.close,refPrice:n??this.sessionRefPrice??e[0].open,sparkline:r.slice()})}async setTimeframe(e){this.chart.isTimeframeAllowed(e)&&(this.chosenTimeframe=e,this.rangeSeq++,await this.switchTimeframe(e))}async switchTimeframe(e){if(this.state={...this.state,timeframe:e},this.options.onTimeframeChange?.(e),this.updateUI(),this.layoutSession?.changed(),this.adapter){await this.connectStream();return}if(this.chart.setDataTimeframe(e),this.options.resampleTimeframes!==!1){if(!this.baseSeries){let e=this.chart.getData();e.length>0&&(this.baseSeries=e,this.baseTimeframeMs=a(e))}await this.switchLocalTimeframe()}}setTheme(e){let t=this.resolveIsDark(e),n=this.resolveTheme(e);this.themeOf={...this.themeOf,[t?`dark`:`light`]:n},this.state={...this.state,isDark:t},this.root.dataset.tcwTheme=t?`dark`:`light`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.keepingLook(()=>this.chart.setTheme(n)),this.updateUI()}getChart(){return this.chart}setUI(e){this.ui=G(e),this.uiVariables=!0,this.uiScale=this.scaleNow(),this.applyLookTokens(),this.applyChartShapes(),this.applyLegendFont(),this.applyChartLook()}scaleNow(){if(this.ui.scale!==`auto`&&this.ui.scale!==void 0)return this.ui.scale;let e=this.root.clientWidth;return e>0?ea(e):1}applyLookTokens(){let e=ta(this.ui,this.uiScale);for(let t of[this.root,this.portal]){if(ba(t,e,{variables:this.uiVariables}),this.uiVariables)continue;let n=ya(e);for(let e of Iu)this.uiScale===1?t.style.removeProperty(e):t.style.setProperty(e,n[e])}}fitScale(){if(this.destroyed)return;let e=this.scaleNow();if(e!==this.uiScale){if(this.ui.scale===`auto`){let t=this.root.clientWidth;if((e>this.uiScale?ea(t-Fu):ea(t+Fu))===this.uiScale)return}this.uiScale=e,this.applyLookTokens(),this.applyLegendFont(),this.applyChartLook(),this.toolbar?.fit()}}getUI(){return G({...this.ui})}applyLegendFont(){this.chart.setLegend({fontFamily:this.ui.font.mono,fontSize:na(Math.round(this.ui.font.size*this.uiScale),-1)})}applyChartLook(){let e=this.ui.density===`airy`,t=this.options.chartOptions;t?.barLayout||this.chart.setBarLayout(e?`golden`:`classic`);let n=this.scaledChartSizes();t?.font?.family?Object.keys(n).length>0&&this.chart.setFont(n):this.chart.setFont({family:this.ui.font.mono,...n})}scaledChartSizes(){let e=this.options.chartOptions?.font;if(e?.sizeSmall!==void 0||e?.sizeMedium!==void 0||e?.sizeLarge!==void 0)return{};let t=this.chart.getFont?.();if(!t)return{};let n={sizeSmall:t.sizeSmall,sizeMedium:t.sizeMedium,sizeLarge:t.sizeLarge},r=this.chartFontWritten;if((!r||r.sizeSmall!==n.sizeSmall||r.sizeMedium!==n.sizeMedium||r.sizeLarge!==n.sizeLarge)&&(this.chartFontBase=n),this.uiScale===1&&!r)return{};let i=this.chartFontBase??n,a=e=>this.uiScale===1?e:Math.round(e*this.uiScale),o={sizeSmall:a(i.sizeSmall),sizeMedium:a(i.sizeMedium),sizeLarge:a(i.sizeLarge)};return this.chartFontWritten=this.uiScale===1?null:o,o}applyChartShapes(){this.chart.setShapes({tagRadius:this.ui.tagRadius})}destroy(){if(!this.destroyed){this.destroyed=!0,this.stopKeyboardInset?.(),this.stopKeyboardInset=null,this.stopNarrow?.(),this.dockObserver?.disconnect(),this.scaleObserver?.disconnect(),this.inlineText?.close(),this.stopNarrow=null,this.stopFormControls?.(),this.stopFormControls=null,this.boundGlobalKeydown&&document.removeEventListener(`keydown`,this.boundGlobalKeydown),document.removeEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys(),this.tooltip.destroy(),this.legendFrame&&cancelAnimationFrame(this.legendFrame),this.indicatorLegend?.destroy(),this.portal.remove(),document.fullscreenElement===this.root&&document.exitFullscreen().catch(()=>{}),this.flushActiveLayout(),this.commandPalette?.destroy(),this.symbolSearch?.destroy(),this.hotkeySheet?.destroy(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayShade?.remove(),this.replayBar?.destroy(),this.dragDrop?.detach(),this.alertsPanel?.destroy(),this.objectTree?.destroy(),this.indicatorSettings?.destroy(),this.indicatorPicker?.destroy(),this.drawingStyle?.destroy(),this.drawingSettings?.destroy(),this.drawingMenu?.destroy(),this.clearMenu?.destroy(),this.cancelTextPrompt?.(),this.selectionToolbar?.destroy(),this.selectionToolbarFrame!==null&&cancelAnimationFrame(this.selectionToolbarFrame),this.chartMenu?.destroy(),this.legendMenu?.destroy();for(let e of this.hostMenus)e.destroy();this.hostMenus.clear(),this.templatePrompt?.destroy(),this.chartTemplatePrompt?.destroy(),this.drawingTemplatePrompt?.destroy(),this.intervalInput?.destroy(),this.markerTip?.remove(),this.layoutSession?.destroy(),this.layoutsUI?.destroy(),this.settingsListeners.clear(),this.accountPanel?.destroy(),this.orderTicket?.destroy(),this.accountFrame&&cancelAnimationFrame(this.accountFrame),this.bracketBar?.destroy(),this.alertNotifier?.destroy(),this.depthLadder?.destroy(),this.dataWindow?.destroy(),this.watchlistInterval&&clearInterval(this.watchlistInterval),this.marketTimer&&clearInterval(this.marketTimer),this.clockTimer&&clearInterval(this.clockTimer),this.onPageShown&&document.removeEventListener(`visibilitychange`,this.onPageShown),this.onPageShown=null,this.chartNav?.destroy(),this.symbolInfoPanel?.destroy(),this.dock?.destroy(),this.stopQuotes?.(),this.stopQuotes=null,this.watchlist?.destroy(),this.toolbar?.destroy(),this.sidebar?.destroy(),this.settings?.destroy(),this.statusBar?.destroy(),this.goToDate?.destroy(),this.loading.destroy(),this.historyPill.destroy(),this.chart.destroy(),this.root.remove(),$e()}}handleSymbolClick(){this.featureState.symbolSearch&&this.openSymbolSearch()}openSymbolSearch(e){this.symbolSearch?.open({symbols:this.symbolEntries(),current:this.state.symbol,currentInfo:this.chartSymbolInfo(),search:this.symbolSearchFn(),query:e,hint:this.sheetKeyOn(`symbolTyping`)?this.t(`symbolSearch.typeHint`):void 0})}symbolSearchFn(){if(this.options.searchSymbols)return this.options.searchSymbols;let e=this.adapter;if(e?.searchSymbols)return(t,n)=>e.searchSymbols(t,{signal:n,limit:50})}handleTimeframe(e){this.setTimeframe(e)}applyRangePreset(e){let t=++this.rangeSeq;return this.rangeQueue=this.rangeQueue.then(()=>this.runRangePreset(e,t)).catch(e=>{this.say(e instanceof Error?e.message:String(e),`error`)}),this.rangeQueue}async runRangePreset(e,t){let n=()=>t===this.rangeSeq&&!this.destroyed;if(!n())return;this.chosenTimeframe??=this.state.timeframe;let r=this.featureState[`statusBar.rangeTimeframe`]?this.timeframeForPreset(e):this.state.timeframe;r!==this.state.timeframe&&(await this.switchTimeframe(r),!n()||this.adapter&&this.state.connectionState===`error`)||this.chart.setVisibleRangePreset(e)}timeframeForPreset(e){let t=this.state.timeframe,i=this.chart.getData();if(i.length<2)return t;let a=(0,n.barTimeUnit)(i),o=i[i.length-1].time*a,s=e===`All`?i[0].time*a:(0,r.rangePresetStart)(e,o,this.displayTimezone());if(s===null)return t;let c=i.length-1;for(;c>0&&i[c-1].time*a>=s;)c--;let l=this.displayTimezone();return Lt({dayShare:i.slice(-dd).some(e=>{let t=e.time*a,r=new Date(t+(0,n.offsetAt)(l,t)*6e4).getUTCDay();return r===0||r===6})?1:5/7,spanMs:o-s,barsInSpan:i.length-c,width:this.chart.getPlotRect().width,current:t,chosen:this.chosenTimeframe??t,available:this.timeframes.filter(e=>this.chart.isTimeframeAllowed(e)&&this.canShowTimeframe(e))})}canShowTimeframe(e){if(this.adapter)return(0,r.servesTimeframe)(this.adapter,e);if(this.options.resampleTimeframes===!1)return!1;let t=this.chart.getData();if(t.length<2)return!1;let i=this.baseSeries?this.baseTimeframeMs:a(t);return!(i>0)||(0,n.timeframeToMs)(e)>=i}toggleFullscreen(){if(document.fullscreenElement===this.root){document.exitFullscreen().catch(()=>{});return}this.root.requestFullscreen().catch(e=>{this.say(e instanceof Error?e.message:this.t(`toast.fullscreenUnavailable`),`error`)})}drawingToolName(e){let t=`tool.${e}`,n=this.t(t);return n===t?this.chart.getDrawingToolDescriptor(e)?.name??e:n}chartOffset(){let e=this.chartContainer.getBoundingClientRect(),t=this.root.getBoundingClientRect();return{x:e.left-t.left,y:e.top-t.top}}scheduleSelectionToolbar(){this.selectionToolbarFrame!==null||!this.selectionToolbar?.isOpen()||(this.selectionToolbarFrame=requestAnimationFrame(()=>{this.selectionToolbarFrame=null,this.updateSelectionToolbar()}))}updateSelectionToolbar(){let e=this.selectionToolbar;if(!e||this.destroyed)return;let t=this.chart.getSelectedDrawingIds();if(!this.featureState.selectionToolbar||!t?.length){e.hide();return}let n=new Set(t),r=this.chart.getDrawings().filter(e=>n.has(e.id)&&this.chart.isDrawingShown(e.id));if(this.chart.getDrawingTool()!==null||this.chart.isEraserMode()||this.chart.isZoomAreaMode()||r.length===0){e.hide();return}let i=this.chartOffset(),a=r[0],o=(a.paneId===void 0?void 0:this.chart.getIndicatorPanes().find(e=>e.instanceId===a.paneId)?.rect)??this.chart.getPlotRect(),s=Cd(r.flatMap(e=>[this.chart.getDrawingRect(e.id),this.chart.getDrawingTextRect?.(e.id)??null]))??{x:o.x+o.width/2,y:o.y,width:0,height:0};e.show({rect:{x:s.x+i.x,y:s.y+i.y,width:s.width,height:s.height},bounds:{x:o.x+i.x,y:o.y+i.y,width:o.width,height:o.height},style:a.style,locked:r.every(e=>e.locked),canDelete:r.some(e=>!e.locked),canSettings:this.drawingSettings!==null&&this.featureState.drawingSettings&&r.length===1,canAlert:this.featureState.alerts&&r.length===1&&this.chart.canAddDrawingAlert(a.id),canFill:this.chart.getDrawingToolDescriptor(a.type)?.fill===!0,canText:this.chart.getDrawingToolDescriptor(a.type)?.text===!0})}editTextInPlace(e,t){if(e===this.inlineTextId&&this.inlineText?.isOpen())return!0;let n=this.chart.getDrawings().find(t=>t.id===e),r=this.inlineText;if(!n||!r||n.locked||!t&&!this.chart.beginDrawingEdit(e))return!1;let i=gs[n.type],a=n.style,o=a.text??``,s=n=>{this.inlineTextId=null,t?n||this.chart.takeBackDrawing(e):this.chart.endDrawingEdit(e,{cancel:!n}),this.refreshObjects()};return r.open({rect:()=>{let t=this.chart.getDrawingTextRect(e);if(!t)return null;let n=this.chartContainer.getBoundingClientRect();return{x:n.left+t.x,y:n.top+t.y,width:t.width,height:t.height}},text:o,font:{size:a.fontSize||i?.fontSize||Pu,bold:a.bold===!0,italic:a.italic===!0,family:this.chart.getFont?.()?.family??this.ui.font.family},color:a.textColor??vs[n.type]??a.color,label:this.t(`drawingSettings.text`),onInput:n=>t?this.chart.amendNewDrawing(e,{style:{text:n}}):this.chart.updateDrawing(e,{style:{text:n}}),onCommit:n=>{let r=n.replace(/\s+$/,``);r&&r!==n&&(t?this.chart.amendNewDrawing(e,{style:{text:r}}):this.chart.updateDrawing(e,{style:{text:r}})),s(r.length>0)},onCancel:()=>s(!1),returnFocus:()=>this.chartContainer.querySelector(`[tabindex]`)??this.chartContainer})?(this.inlineTextId=e,this.inlineTextNew=t,!0):(t||this.chart.endDrawingEdit(e,{cancel:!0}),!1)}openDrawingSettings(e,t={}){let n=this.chart.getDrawings().find(t=>t.id===e),r=n?this.chart.getDrawingToolDescriptor(n.type):null;!n||!r||!this.drawingSettings||!this.featureState.drawingSettings||this.drawingSettings.open({id:e,type:n.type,name:this.drawingToolName(n.type),style:{...n.style},options:this.chart.getDrawingOptions(e),defs:r.options??{},anchors:n.anchors.map(e=>({...e})),fill:r.fill===!0,text:r.text===!0,textLayout:gs[n.type],textColor:vs[n.type],textPlace:_s.has(n.type),coordinates:r.anchoring!==`screen`,intervals:n.intervals??null},t)}promptSaveDrawingTemplate(e,n){this.drawingTemplatePrompt??=new Lc(this.root,this.t),this.drawingTemplatePrompt.open({title:this.t(`drawingSettings.saveTemplateTitle`),submitLabel:this.t(`common.save`),placeholder:this.drawingToolName(n.type),onSubmit:r=>{e.save(r,n.style,{type:n.type,options:n.options}),this.say(t.r(this.t(`templates.saved`),{name:r.trim()}))}})}addDrawingAlert(e){if(!this.featureState.alerts)return;let n=this.chart.getDrawings().find(t=>t.id===e),r=n?this.drawingToolName(n.type):``;this.chart.addDrawingAlert(e,{label:r})&&this.say(t.r(this.t(`drawingSettings.alertAdded`),{name:r}))}openDrawingMenu(e,t,n){if(!this.drawingMenu||!this.featureState[`menu.drawing`])return;let r=new Map(this.chart.getDrawings().map(e=>[e.id,e])),i=this.chart.getSelectedDrawingIds().flatMap(e=>{let t=r.get(e);return t?[{id:t.id,locked:t.locked,groupId:t.group?.id??null}]:[]});if(i.length===0)return;let a=Ye(Ws({selected:i,canConfigure:this.drawingSettings!==null,canAlert:this.chart.canAddDrawingAlert(e)},this.t),Re,this.featureState),o=i.map(e=>e.id),s=r.get(e),c=s?this.options.drawingMenuItems?.({id:e,type:s.type,selected:o})??[]:[],l=Cu(a,c);if(l.length===0)return;let u=this.chartContainer.getBoundingClientRect(),d=this.root.getBoundingClientRect();this.drawingMenu.open(l,u.left-d.left+t,u.top-d.top+n,t=>{wu(t,c)||this.runDrawingMenuAction(e,o,t)})}runDrawingMenuAction(e,t,n){switch(n){case`settings`:this.openDrawingSettings(e);return;case`alert`:this.addDrawingAlert(e);return;case`front`:case`forward`:case`backward`:case`back`:this.chart.moveDrawing(e,n);break;case`group`:this.chart.groupDrawings(t);break;case`ungroup`:{let e=new Set(this.chart.getDrawings().filter(e=>t.includes(e.id)).map(e=>e.group?.id));for(let t of e)t&&this.chart.ungroupDrawings(t);break}case`lock`:case`unlock`:this.chart.setDrawingsLocked(t,n===`lock`);break;case`hide`:this.chart.setDrawingsVisible(t,!1);break;case`duplicate`:this.chart.duplicateDrawing(e);break;case`delete`:{let e=this.drawingSettings?.editing();e&&t.includes(e)&&this.drawingSettings?.close(!0),this.chart.removeDrawings(t);break}}this.objectTree?.isOpen()&&this.refreshObjects()}chartMenuContext(e){let t=this.chart.getDrawings(),n=this.chart.getData(),r=this.settingsState,i=this.chart.getFeatures();return{price:e,lastPrice:n.length>0?n[n.length-1].close:null,formatPrice:e=>this.formatAlertPrice(e),canAlert:this.alertsPanel!==null,canTrade:this.options.trading!==!1,canOrderTicket:this.orderTicket!==null,canDraw:!0,hasDrawings:t.length>0,drawingsHidden:t.length>0&&t.every(e=>!e.visible),canPaste:this.chart.canPasteDrawings(),hasIndicators:i.indicators!==!1&&this.removableIndicators().length>0,canGoToDate:this.goToDate!==null,canExport:this.canExport,autoScale:this.chart.isAutoScale(),scaleMode:this.effectiveScaleMode(),canLog:i.logScale!==!1,inverted:this.chart.isInvertScale(),leftScale:r.leftPriceScale,labels:{values:r.indicatorValueLabels,aligned:r.alignAxisLabels,...i.barCountdown===!1?{}:{countdown:r.barCountdown}},lines:{highLow:r.highLowLines,lastPrice:this.chart.getStyleValue(`lastPrice.visible`)!==!1},timezone:{current:r.timezone,options:this.timezoneChoices()},keys:Object.fromEntries(Ks.filter(e=>this.featureState.hotkeys&&this.featureState[e.feature]).map(e=>[e.action,e.keys]))}}removableIndicators(){return this.chart.getActiveIndicators().filter(e=>!r.SYMBOL_INDICATOR_IDS.has(e.id)).map(e=>e.instanceId)}exchangeChoice(){let e=this.chart.getExchangeTimeZone()??null;if(!(e===null&&!this.adapter?.resolveSymbol))return{label:this.t(`settings.timezone.exchange`),zone:e}}timezoneChoices(){return f(this.settingsState.timezone,Date.now(),this.t(`settings.timezone.local`),this.exchangeChoice()).map(({value:e,label:t})=>({value:e,label:t}))}openChartMenu(e,t,n,r){if(!this.chartMenu)return;let i=this.options.chartMenuItems?.(r)??[],a=Cu(e,i);if(a.length===0)return;let o=this.chartContainer.getBoundingClientRect(),s=this.root.getBoundingClientRect();this.chartMenu.open(a,o.left-s.left+t,o.top-s.top+n,e=>{wu(e,i)||(e.startsWith(`tz:`)?this.changeSettings({timezone:e.slice(3)}):this.runChartMenuAction(e,r))})}setFeatures(e){let t=this.featureState;this.featureState={...t,...Be(e)};let n=e=>t[e]!==this.featureState[e];this.markSwitchedOff(),this.closeSwitchedOff(e=>t[e]&&!this.featureState[e]),n(`selectionToolbar`)&&this.updateSelectionToolbar(),n(`indicatorLegend`)&&(this.chart.setPaneTitlesVisible(!this.featureState.indicatorLegend),this.scheduleLegend()),n(`menu.priceAxisAdd`)&&this.chart.setFeatures({priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]}),n(`dragDropImport`)&&(this.featureState.dragDropImport?this.dragDrop?.attach():this.dragDrop?.detach()),[`toolbar`,`sidebar`,`statusBar`,`accountPanel`].some(n)&&this.chart.resize()}getFeatures(){return{...this.featureState}}isFeatureOn(e){return this.featureState[e]===!0}closeSwitchedOff(e){e(`replay`)&&this.replayBar?.isMounted()&&this.exitReplay();let t=[[`alerts`,()=>this.dock?.closePage(`alerts`)],[`objectTree`,()=>this.dock?.closePage(`objectTree`)],[`symbolInfo`,()=>this.dock?.closePage(`symbolInfo`)],[`dataWindow`,()=>this.dock?.closePage(`dataWindow`)],[`accountPanel`,()=>this.toggleAccountPanel(!1)],[`orderTicket`,()=>this.orderTicket?.close()],[`depthLadder`,()=>this.dock?.closePage(`depthLadder`)],[`goToDate`,()=>this.goToDate?.close()],[`settings`,()=>this.settings?.close()],[`indicatorSettings`,()=>this.indicatorSettings?.close()],[`toolbar.indicators`,()=>this.indicatorPicker?.close()],[`drawingSettings`,()=>this.drawingSettings?.close(!1)],[`sidebar`,()=>this.drawingStyle?.close()],[`commandPalette`,()=>this.commandPalette?.close()],[`hotkeySheet`,()=>this.hotkeySheet?.close()],[`symbolSearch`,()=>this.symbolSearch?.close()],[`compare`,()=>{this.symbolSearch?.isComparing()&&this.symbolSearch.close()}],[`menu.chart`,()=>this.chartMenu?.close()],[`menu.priceAxisAdd`,()=>this.chartMenu?.close()],[`menu.drawing`,()=>this.drawingMenu?.close()],[`indicatorLegend`,()=>this.legendMenu?.close()],[`indicatorLegend.more`,()=>this.legendMenu?.close()]];for(let[n,r]of t)e(n)&&r()}addHotkey(e){let t=Ou(e.keys);if(!t)return console.warn(`[ChartWidget] Can't read the shortcut "${e.keys}": modifiers (Ctrl, Alt, Shift) and a key, joined by +.`),null;ju(t)&&console.warn(`[ChartWidget] The chart answers ${e.keys} itself (drawings, scrolling or zoom): both will run.`);let n={spec:e,parsed:t};return this.hostHotkeys=[...this.hostHotkeys,n],{remove:()=>{this.hostHotkeys=this.hostHotkeys.filter(e=>e!==n)}}}handleHostHotkey(e){if(this.hostHotkeys.length===0||!this.featureState.hotkeys||e.isComposing||e.keyCode===id||e.getModifierState?.(`AltGraph`)||e.defaultPrevented||Z()||Mu(e)||rd())return!1;let t=this.hostHotkeys.find(t=>ku(e,t.parsed));if(!t)return!1;let n=!t.parsed.ctrl&&!t.parsed.alt;if(!Yc(this.root,n))return!1;let r=document.activeElement;return n&&r&&r!==document.body&&!this.root.contains(r)?!1:(e.preventDefault(),t.spec.onPress(e),!0)}keepingLook(e){this.settingsEdit&&this.settings?.close();let t=this.chart.getOverrides?.({layer:`user`})??{},n=Object.fromEntries(ld.filter(e=>t[e]!==void 0).map(e=>[e,t[e]]));e(),Object.keys(n).length>0&&this.chart.applyOverrides(n,{layer:`user`})}sheetKeyOn(e){let t=this.featureState;if(!t.hotkeys||!t[e])return!1;switch(e){case`hotkeys.commandPalette`:return t.commandPalette;case`hotkeys.symbolSearch`:return t.symbolSearch;case`hotkeys.goToDate`:return t.goToDate;case`hotkeys.save`:return t.layouts&&this.layoutSession!==null;case`hotkeys.help`:return t.hotkeySheet;case`intervalTyping`:return this.intervalInput!==null;case`symbolTyping`:return t.symbolSearch;default:return!0}}markSwitchedOff(){let e=He(this.featureState);for(let t of[this.root,this.portal])e?t.dataset.tcwOff=e:delete t.dataset.tcwOff;this.toolbar?.setSymbolSearch(this.featureState.symbolSearch),this.toolbar?.tidy(),this.sidebar?.tidy(),this.syncRail(),this.statusBar?.fit()}addToolbarButton(e){if(!this.toolbar)return null;let t=this.toolbar,n=t.addHostButton(e);return t.tidy(),{element:n,setActive:t=>dn(n,t,e.toggle===!0),setText:t=>void fn(n,e.label,t),remove:()=>{n.remove(),t.tidy()}}}addToolbarDropdown(e){let t=this.toolbar;if(!t)return null;let n=new A(this.root,e.label);this.hostMenus.add(n);let r=t.addHostButton({id:e.id,label:e.label,icon:e.icon,text:e.text,side:e.side,onClick:r=>{if(n.isOpen()){n.close();return}let i=e.items();if(i.length===0)return;let a=t.menuAnchor(r);n.openUnder(Cu([],i),a,e=>wu(e,i))}});return r.setAttribute(`aria-haspopup`,`menu`),r.setAttribute(`aria-expanded`,`false`),t.tidy(),{element:r,setText:t=>void fn(r,e.label,t),remove:()=>{n.destroy(),this.hostMenus.delete(n),r.remove(),t.tidy()}}}addSidebarButton(e){let t=this.sidebar;if(!t)return null;let n=t.addHostButton(e);return{element:n,setActive:t=>dn(n,t,e.toggle===!0),remove:()=>{n.remove(),t.tidy()}}}addStatusBarItem(e){if(!this.statusBar)return null;let t=this.statusBar.addHostItem(e);return{element:t,setText:n=>{t.textContent=n,e.label&&e.label!==n?t.setAttribute(`aria-label`,`${e.label}: ${n}`):t.removeAttribute(`aria-label`)},remove:()=>t.remove()}}getSlot(e){switch(e){case`toolbar.left`:return this.toolbar?.hostSlot(`left`)??null;case`toolbar.right`:return this.toolbar?.hostSlot(`right`)??null;case`sidebar`:return this.sidebar?.hostSlot()??null;case`statusBar.left`:return this.statusBar?.hostSlot(`left`)??null;case`statusBar.right`:return this.statusBar?.hostSlot(`right`)??null;case`chart`:return this.hostLayer||(this.hostLayer=document.createElement(`div`),this.hostLayer.className=`tcw-host-layer`,this.chartContainer.appendChild(this.hostLayer)),this.hostLayer;default:return null}}runChartMenuAction(e,n){let{price:r}=n,i=r??NaN,a=this.settingsState,o=qs(e);if(o){this.changeSettings({scaleMode:o});return}switch(e){case`alert`:this.chart.addAlert(i,`crossing`),this.say(t.r(this.t(`chartMenu.alertAdded`),{price:this.formatAlertPrice(i)}));break;case`buyLimit`:case`sellLimit`:case`buyStop`:case`sellStop`:this.placeOrderAt(e,i);break;case`orderTicket`:this.openOrderTicket(r);break;case`exportData`:this.chart.exportAllData(`csv`,`${this.state.symbol}-${this.state.timeframe}.csv`.replace(/[^\w.-]+/g,`_`));break;case`paneLog`:case`paneInvert`:case`panePercent`:{let t=this.menuPane;if(!t)break;let n=this.chart.getPaneScale(t);this.chart.setPaneScale(t,e===`paneLog`?{log:!n.log}:e===`paneInvert`?{invert:!n.invert}:{percent:!n.percent});break}case`horizontalLine`:{let e=this.chart.getData();e.length>0&&this.chart.addDrawing({type:`horizontalLine`,anchors:[{time:e[e.length-1].time,price:i}]});break}case`resetView`:this.resetView();break;case`resetPriceScale`:this.changeSettings({autoScale:!0});break;case`paste`:this.chart.pasteDrawings();break;case`removeIndicators`:this.chart.removeIndicators(this.removableIndicators());break;case`hideDrawings`:this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!1);break;case`showDrawings`:this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!0);break;case`removeDrawings`:this.chart.removeDrawings(this.chart.getDrawings().map(e=>e.id));break;case`settings`:this.openSettings(n.area===`priceAxis`?`scales`:void 0);break;case`autoScale`:this.changeSettings({autoScale:!this.chart.isAutoScale()});break;case`invertScale`:this.changeSettings({invertScale:!this.chart.isInvertScale()});break;case`leftScale`:this.changeSettings({leftPriceScale:!a.leftPriceScale});break;case`indicatorValueLabels`:this.changeSettings({indicatorValueLabels:!a.indicatorValueLabels});break;case`alignAxisLabels`:this.changeSettings({alignAxisLabels:!a.alignAxisLabels});break;case`barCountdown`:this.changeSettings({barCountdown:!a.barCountdown});break;case`highLowLines`:this.changeSettings({highLowLines:!a.highLowLines});break;case`lastPriceLine`:this.changeStyle({"lastPrice.visible":this.chart.getStyleValue(`lastPrice.visible`)===!1});break;case`goToDate`:this.toggleGoToDate();break}this.objectTree?.isOpen()&&this.refreshObjects()}toggleAccountPanel(e){let t=this.accountPanel;!t||e===t.isOpen()||!t.isOpen()&&!this.featureState.accountPanel||t.toggle()}openOrderTicket(e){if(!this.featureState.orderTicket)return;let t=this.chart.getData();this.orderTicket?.open({price:e,lastPrice:t.length>0?t[t.length-1].close:null,rules:this.orderRules(),symbol:this.state.symbol,step:e=>this.chart.getPriceStep(e),round:e=>this.chart.roundPrice(e)})}orderRules(){let e=this.chart.getMarket();return e?{roundPrice:e.priceStep!==void 0||(e.priceSteps?.length??0)>0?e=>this.chart.roundPrice(e):void 0,limits:this.chart.getPriceLimits(),lot:e.volumeUnit,multiplier:e.contractMultiplier}:{}}refreshAccountSoon(){this.accountFrame||!this.accountPanel||(this.accountFrame=requestAnimationFrame(()=>{this.accountFrame=0,this.destroyed||this.refreshAccount()}))}refreshAccount(){if(!this.accountPanel)return;let e=this.chart.getData(),t=e.length>0?e[e.length-1].close:null;this.accountPanel.update({positions:this.chart.getPositions(),orders:this.chart.getOrders(),fills:this.chart.getFills(),price:t,realisedPnl:this.chart.getRealisedPnl()}),this.orderTicket?.setLastPrice(t)}placeOrderAt(e,n){let r=e.startsWith(`buy`)?`buy`:`sell`,i=e.endsWith(`Stop`);this.chart.placeOrderIntent(i?{side:r,type:`stop`,price:n,stopPrice:n,quantity:1}:{side:r,type:`limit`,price:n,quantity:1}),this.say(t.r(this.t(`order.${e}`),{price:this.formatAlertPrice(n)}))}clockNow(){let e=Date.now(),t=this.displayTimezone(),r=e=>String(e).padStart(2,`0`),{time:i}=Q(e,t);return{time:`${i}:${r(new Date(e).getUTCSeconds())}`,zone:(0,n.tzLabel)((0,n.offsetAt)(t,e))}}refreshDrawingsState(){let e=this.chart.getDrawings()??[],t=e.length>0;this.sidebar?.setDrawingsState({locked:t&&e.every(e=>e.locked),hidden:t&&e.every(e=>!e.visible)})}refreshScaleSwitches(){this.statusBar?.setScale({mode:this.chart.getScaleMode(),auto:this.chart.isAutoScale()})}toggleScaleMode(e){this.changeSettings({scaleMode:this.chart.getScaleMode()===e?`regular`:e})}displayTimezone(){let e=u(this.settingsState.timezone);return e===`exchange`?this.chart.getEffectiveTimeZone():e}toggleGoToDate(){if(!this.goToDate||!this.featureState.goToDate)return;if(this.goToDate.isOpen()){this.goToDate.close();return}let e=this.chart.getData();if(e.length===0)return;let t=this.displayTimezone(),r=(0,n.barTimeUnit)(e),i=e=>Q(e*r,t),a=e[e.length-1].time,o=this.chart.getVisibleTimeRange()??{from:e[0].time,to:a},s=Q(Date.now(),t).date;this.goToDate.open({date:i(a),range:{from:i(o.from),to:i(o.to)},withTime:!((0,n.timeframeToMs)(this.state.timeframe)>=Hu),max:s,today:s})}goTo(e){let t=this.chart.getData(),r=this.displayTimezone();if(t.length===0)return;let i=(0,n.barTimeUnit)(t);if(e.kind===`date`){let n=sl(e.date,e.time,r);if(n===null)return;this.chart.goToTime(n/i),n/i<t[0].time&&this.say(this.t(`range.beforeData`));return}let a=sl(e.from.date,e.from.time,r),o=sl(e.to.date,e.to.time,r);a===null||o===null||(this.chart.setVisibleRange(a/i,o/i),Math.min(a,o)/i<t[0].time&&this.say(this.t(`range.beforeData`)))}pinnedTimeframes(){let e=this.timeframeFavorites.list();return this.timeframes.filter(t=>e.includes(t))}timeframeMenu(){return this.timeframes.map(e=>({value:e,label:Ct(e),custom:this.customTimeframes.has(e)}))}handleAddTimeframe(e){if(!this.featureState.customTimeframes)return!1;let t=jt(e);return!t||!this.chart.isTimeframeAllowed(t)||this.adapter&&!(0,r.servesTimeframe)(this.adapter,t)||!this.adapter&&(0,n.tickBarCount)(t)!==null?!1:(this.timeframes.includes(t)||(this.customTimeframes.add(t),this.timeframeFavorites.add(t),this.timeframes=Mt(this.timeframes,[t]),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.handleTimeframe(t),!0)}showMarkerTip(e){let{marker:n}=e;if(!n){this.markerTip&&(this.markerTip.hidden=!0);return}this.markerTip||(this.markerTip=document.createElement(`div`),this.markerTip.className=`tcw-marker-tip`,this.markerTip.setAttribute(`role`,`tooltip`),this.chartContainer.appendChild(this.markerTip));let r=n.direction===`long`?this.t(`account.long`):n.direction===`short`?this.t(`account.short`):this.t(`markers.neutral`),i=document.createElement(`strong`);i.textContent=n.label?`${n.label} · ${n.source}`:n.source;let a=document.createElement(`div`);a.textContent=`${r} · ${this.formatAlertPrice(n.price)} · ${t.r(this.t(`markers.confidence`),{pct:Math.round(n.confidence*100)})}`;let o=document.createElement(`div`),{date:s,time:c}=Q(n.time,this.displayTimezone());o.textContent=`${s} ${c}`,this.markerTip.replaceChildren(i,a,o),this.markerTip.hidden=!1;let l=this.chartContainer.getBoundingClientRect(),u=Math.min(e.x+12,Math.max(0,l.width-this.markerTip.offsetWidth-4)),d=Math.max(0,e.y-this.markerTip.offsetHeight-10);this.markerTip.style.left=`${u}px`,this.markerTip.style.top=`${d}px`}selectTypedTimeframe(e){return!this.chart.isTimeframeAllowed(e)||!this.timeframes.includes(e)&&!this.featureState.customTimeframes||this.adapter&&!(0,r.servesTimeframe)(this.adapter,e)?!1:(this.timeframes.includes(e)||(this.customTimeframes.add(e),this.timeframes=Mt(this.timeframes,[e]),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.handleTimeframe(e),!0)}applyIndicatorTemplate(e){if(!this.featureState.indicatorTemplates)return;let n=this.templates.get(e);n&&(this.chart.applyIndicatorSetup(n.indicators),this.syncIndicatorsFromChart(),this.updateUI(),this.say(t.r(this.t(`templates.applied`),{name:n.name})))}promptSaveIndicatorTemplate(){if(this.featureState.indicatorTemplates){if(this.chart.getActiveIndicators().length===0){this.say(this.t(`templates.nothing`),`error`);return}this.templatePrompt??=new Lc(this.root,this.t),this.templatePrompt.open({title:this.t(`templates.saveTitle`),submitLabel:this.t(`common.save`),placeholder:this.t(`templates.namePlaceholder`),onSubmit:e=>{try{this.templates.save(e,this.chart.getIndicatorSetup())}catch(e){throw this.say(this.t(`templates.saveFailed`),`error`),e}this.indicatorPicker?.setTemplates(this.templateNames()),this.say(t.r(this.t(`templates.saved`),{name:e}))}})}}handleRemoveTimeframe(e){this.customTimeframes.has(e)&&(this.customTimeframes.remove(e),this.timeframeFavorites.remove(e),this.timeframes=this.timeframes.filter(t=>t!==e),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes()),this.updateUI())}handleToggleTimeframeFavorite(e){this.timeframeFavorites.toggle(e),this.toolbar?.setTimeframeFavorites(this.pinnedTimeframes()),this.updateUI()}setData(e){this.localSeq++,this.baseSeries=e,this.baseTimeframeMs=a(e),this.applyTimeframeData(),this.adapter||this.loading.end()}async switchLocalTimeframe(){if(!this.baseSeries)return;let e=++this.localSeq,t=this.lastLocalSwitchMs>=Lu||this.baseSeries.length>=Ru;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await Bu(),e!==this.localSeq||this.destroyed))return;this.applyTimeframeData()}finally{e===this.localSeq&&this.loading.end()}}applyTimeframeData(){if(!this.baseSeries)return;let e=performance.now(),t=(0,n.timeframeToMs)(this.state.timeframe);if(this.baseTimeframeMs>0&&t>this.baseTimeframeMs){let e=this.chart.getExchangeTimeZone()??null;this.chart.setData(i(this.baseSeries,this.state.timeframe,this.resampleOptions(e))),this.builtInZone=e}else this.chart.setData(this.baseSeries),this.builtInZone=void 0;this.lastLocalSwitchMs=performance.now()-e}resampleOptions(e){return{weekStartsOn:this.options.weekStartsOn??1,timeZone:e??void 0}}rebuildForZone(){if(this.adapter||this.builtInZone===void 0)return;let e=this.chart.getExchangeTimeZone()??null;if(e===this.builtInZone)return;if(!(0,n.timeframeFollowsDays)(this.state.timeframe)){this.builtInZone=e;return}let t=this.timeToKeepInView();this.applyTimeframeData(),t!==null&&this.chart.scrollTo(t)}timeToKeepInView(){if(!this.chart.isTimeAligned())return null;let e=this.chart.getVisibleTimeRange(),t=this.chart.getData();if(!e||t.length<2||e.to>=t[t.length-1].time)return null;let n=t.findIndex(t=>t.time===e.from);return n<0?null:e.from-(t[n+1].time-e.from)/2}handleDataUpdate(e){if(e.kind===`bars`){e.length>0&&this.loading.isActive()&&(this.loading.end(),this.state.connectionState===`error`&&this.setConnectionState(`connected`,this.t(`status.live`)));return}if(e.kind===`error`){this.loading.isActive()&&(this.loading.fail(this.t(`status.connectionFailed`)),this.setConnectionState(`error`,e.error||this.t(`status.connectionFailed`)));return}if(e.kind===`connection`)switch(e.connection.state){case`connected`:this.loading.hasFailed()&&this.loading.end(),!this.loading.isActive()&&this.state.connectionState!==`connected`&&this.setConnectionState(`connected`,this.t(`status.live`));break;case`reconnecting`:this.loading.isActive()||this.setConnectionState(`connecting`,this.t(`status.connecting`));break;case`error`:this.loading.isActive()||this.setConnectionState(`error`,this.t(`status.connectionFailed`));break}}setConnectionState(e,t){this.state={...this.state,connectionState:e,connectionMessage:t},this.updateUI()}toggleLadder(){!this.depthLadder||!this.featureState.depthLadder||this.dock?.toggle(`depthLadder`)}toggleAlerts(){!this.alertsPanel||!this.featureState.alerts||this.dock?.toggle(`alerts`)}handleToggleFavorite(e){let t=this.favoritesStore.toggle(e);this.sidebar?.setFavorites(this.favoritesStore.list()),this.say(t?this.t(`toast.pinned`):this.t(`toast.unpinned`))}exportState(){let e=this.chart.getActiveIndicators().map(e=>({id:e.id,params:e.params})),t=this.getSettings(),n=wo(t,{...ge,...Object.fromEntries(cd.map(e=>[e,this.settingsDefaults[e]]))});return pu({v:1,symbol:this.state.symbol,timeframe:this.state.timeframe,chartType:this.state.chartType,scaleMode:t.scaleMode,indicators:e,drawings:this.chart.getDrawings(),...Object.keys(n).length>0?{settings:n}:{}})}showLinkSettings(e){let t=this.getSettings(),n=Object.keys(e),r=this.linkSettings,i={...Object.fromEntries(n.map(e=>[e,t[e]])),...r?.own};this.applySettings(e,!1),this.linkSettings={shown:{...r?.shown,...e},own:i},this.markSettingsTold()}ownSettings(e){let t=this.linkSettings;if(!t)return e;let n=Object.keys(t.shown).filter(n=>JSON.stringify(e[n])===JSON.stringify(t.shown[n]));return{...e,...Object.fromEntries(n.map(e=>[e,t.own[e]]))}}claimSettings(e){let t=this.linkSettings;if(!t)return;let n=new Set(e),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e))),i=r(t.shown);Object.keys(i).length!==Object.keys(t.shown).length&&(this.linkSettings=Object.keys(i).length>0?{shown:i,own:r(t.own)}:null,this.settingsPublished!==null&&!this.destroyed&&this.settingsStore?.save(this.ownSettings(this.getSettings()),this.settingsDefaults))}async importState(e){let t=mu(e);if(!t)return!1;t.symbol&&t.symbol!==this.state.symbol&&await this.setSymbol(t.symbol),t.timeframe&&t.timeframe!==this.state.timeframe&&await this.setTimeframe(t.timeframe),t.chartType&&this.applyChartType(t.chartType);let{chartTypeOptions:n,...r}=this.allowedSettings({scaleMode:t.scaleMode,...K(t.settings,lo)}),i=this.overViewerTypeOptions(t.chartType,n);return this.showLinkSettings(i?{...r,chartTypeOptions:i}:r),this.settings?.refresh(this.shownSettings()),this.chart.applyIndicatorSetup(t.indicators.map((e,t)=>({id:e.id,instanceId:`shared_${t}`,params:e.params}))),this.chart.setDrawings(t.drawings),this.updateUI(),!0}overViewerTypeOptions(e,t){let n={...po(e)?{[e]:{}}:{},...t};if(Object.keys(n).length!==0)return{...this.getSettings().chartTypeOptions,...n}}async copyChartImage(){let e=await this.chart.copyScreenshot();this.say(e?this.t(`toast.imageCopied`):this.t(`toast.imageCopyFailed`),e?`info`:`error`)}async copyShareLink(){let e=_u(typeof location<`u`?location.href:``,this.exportState());try{await navigator.clipboard.writeText(e),this.say(this.t(`toast.linkCopied`))}catch{this.say(this.t(`toast.copyFailed`),`error`)}}setDepth(e){this.chart.setDepthData(e),this.depthLadder?.setData(e),e&&this.chart.pushDepthSnapshot(e)}startBracket(e){this.chart.startBracket(e)&&this.bracketBar?.show(e)}hoveredBar(){let e=this.lastHoverIndex;if(e===null||e<0)return null;if(!this.chart.isTimeAligned()){let e=this.lastHoverBar;return e?{bar:e,prevClose:this.lastHoverPrevClose??e.open}:null}let t=this.chart.getData();return e>=t.length?null:{bar:t[e],prevClose:e>0?t[e-1].close:t[e].open}}buildDataWindowModel(){let e=this.lastHoverIndex,t=this.hoveredBar();if(e===null||!t)return{ohlc:null,change:0,changePct:0,indicators:[]};let{bar:n,prevClose:r}=t,i=n.close-r,a=r===0?0:i/r*100,o=new Set(this.chart.getIndicatorPanes().flatMap(e=>e.instanceIds??[e.instanceId])),s=this.settingsState.numberLocale||`en-US`,c=this.chart.getActiveIndicators().map(t=>{let n=this.chart.getIndicatorOutput(t.instanceId)?.series?.[e]??null,r=!o.has(t.instanceId)&&Ed(t),i=t.descriptor.plots?.map(e=>[e.key,e.title])??Object.keys(n??{}).map(e=>[e,e]),a=n?i.filter(([e])=>typeof n[e]==`number`&&Number.isFinite(n[e])).map(([e,t])=>{let i=n[e];return{key:t,value:i,text:this.indicatorValueText(i,r,s)}}):[];return{name:t.descriptor.name,values:a}}).filter(e=>e.values.length>0);return{ohlc:{open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume},change:i,changeText:this.formatAlertPrice(i,n.close),changePct:a,indicators:c}}toggleDataWindow(){!this.dataWindow||!this.featureState.dataWindow||this.dock?.toggle(`dataWindow`)}toggleObjects(){!this.objectTree||!this.featureState.objectTree||this.dock?.toggle(`objectTree`)}setupDock(){let e=this.dock;if(!e)return;if(this.watchlist){let t=this.watchlist;e.addPage({id:`watchlist`,label:this.t(`watchlist.title`),icon:`list`,element:t.element,parts:[`dock.watchlist`],onShow:()=>t.redraw()})}let t=this.alertsPanel;t&&e.addPage({id:`alerts`,label:this.t(`alerts.title`),icon:`bell`,element:t.element,parts:[`dock.alerts`,`alerts`],onShow:()=>{t.openPanel(),this.refreshAlerts(),this.toolbar?.setActive(`alerts`,!0)},onHide:()=>{t.close(),this.toolbar?.setActive(`alerts`,!1)}});let n=this.objectTree;n&&e.addPage({id:`objectTree`,label:this.t(`objects.title`),icon:`layers`,element:n.element,parts:[`dock.objectTree`,`objectTree`],onShow:()=>{n.openPanel(),this.refreshObjects(),this.toolbar?.setActive(`objects`,!0)},onHide:()=>{n.close(),this.toolbar?.setActive(`objects`,!1)}});let r=this.dataWindow;r&&e.addPage({id:`dataWindow`,label:this.t(`dataWindow.title`),icon:`table`,element:r.element,parts:[`dock.dataWindow`,`dataWindow`],onShow:()=>{r.openPanel(),r.render(this.buildDataWindowModel())},onHide:()=>r.close()});let i=this.symbolInfoPanel;i&&e.addPage({id:`symbolInfo`,label:this.t(`symbolInfo.title`),icon:`info`,element:i.element,parts:[`dock.symbolInfo`,`symbolInfo`],onShow:()=>i.open(),onHide:()=>i.close()});let a=this.depthLadder;a&&e.addPage({id:`depthLadder`,label:this.t(`ladder.title`),icon:`ladder`,element:a.element,parts:[`dock.depthLadder`,`depthLadder`],onShow:()=>a.openPanel(),onHide:()=>a.close()}),this.syncRail(),this.fitDockToWidth(),typeof ResizeObserver<`u`&&(this.dockObserver=new ResizeObserver(()=>this.fitDockToWidth()),this.dockObserver.observe(this.root))}fitDockToWidth(){let e=this.dock,t=this.root.clientWidth;if(!e||t===0)return;let n=t<641,r=this.dockNarrow;this.dockNarrow=n,n&&r!==!0&&e.close()}railShown(){return this.featureState.dock&&!this.root.hasAttribute(`data-tcw-narrow`)}syncRail(){this.dock?.syncRail();let e=this.railShown();this.toolbar?.setRailed(`alerts`,e&&this.featureState[`dock.alerts`]),this.toolbar?.setRailed(`objects`,e&&this.featureState[`dock.objectTree`]),this.toolbar?.fit()}panelFocusTarget(e){let t=Ku[e],n=t?this.root.querySelector(`.tcw-toolbar [data-role="${t}"]`):null,r=this.root.hasAttribute(`data-tcw-narrow`);return n&&!n.hidden&&!(r&&n.classList.contains(`tcw-toolbar-overflow`))?n:this.root.querySelector(`.tcw-toolbar-more`)??this.chartContainer}closePanelByHand(e){this.dock?.closePage(e)}openIndicatorSettings(e){if(!this.indicatorSettings||!this.featureState.indicatorSettings)return;let t=this.chart.getActiveIndicators(),n=t.find(t=>t.instanceId===e);if(!n)return;let r=this.chart.getIndicatorStyle(e),i=n.descriptor.placement===`panel`||!!n.pane,a=(this.chart.getIndicatorSetup()??[]).find(t=>t.instanceId===e)?.levels!==void 0;this.chart.beginIndicatorEdit(e),this.indicatorSettings.open({instanceId:e,indicatorId:n.id,name:n.descriptor.name,defaults:n.descriptor.defaultConfig,params:n.params,inputs:n.descriptor.inputs,lineSources:md(e,t,this.t),plots:n.descriptor.plots,colors:r?.colors,lineWidth:r?.lineWidths[0],plotStyles:r?.plots,intervals:this.chart.getIndicatorIntervals(e)??null,levels:i?this.chart.getIndicatorLevels(e):void 0,defaultLevels:n.descriptor.levels,ownLevels:a,scale:i?void 0:this.chart.getIndicatorScale(e)})}refreshObjects(){if(this.refreshDrawingsState(),!this.objectTree)return;let e=this.chart.getActiveIndicators().map(e=>({instanceId:e.instanceId,name:qi(e,this.t),title:e.descriptor.name,visible:e.visible})),t=this.chart.getDrawings().map(e=>({id:e.id,label:e.name||wa(e.type,this.t),visible:e.visible,offInterval:e.visible&&!this.chart.isDrawingShown(e.id),locked:e.locked,group:e.group})),n=this.comparedNow().map(e=>({id:e.id,label:e.symbol,color:e.color,way:e.way}));this.objectTree.setObjects(e,t,n)}async handleAddCompare(){if(this.featureState.compare){if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}this.symbolSearch?.openCompare({symbols:this.symbolEntries(),current:this.state.symbol,search:this.symbolSearchFn(),ways:_l(this.t),way:this.compareWay,compared:this.comparedNow(),onAdd:(e,t)=>{gl(t)&&(this.compareWay=t,this.addCompareSymbol(e,t))},onRemove:e=>this.removeCompared(e)})}}comparedNow(){let e=new Set(this.chart.getIndicatorPanes().flatMap(e=>e.instanceIds));return xl(this.compares,this.chart.getActiveIndicators(),e,this.t)}refreshCompareDialog(){this.symbolSearch?.isComparing()&&this.symbolSearch.setCompared(this.comparedNow())}async addCompareSymbol(e,n=`percent`){if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}if(n!==`percent`){await this.addCompareIndicator(this.adapter,e,n);return}if(this.chart.getFeatures()?.compareSymbols===!1||this.compares.some(t=>t.symbol===e)||this.comparesLoading.has(e))return;let r=`cmp_${e}`;this.comparesLoading.add(e);try{let n=await this.fetchCompareBars(this.adapter,e);if(!n||this.compares.some(t=>t.symbol===e))return;let i=this.state.timeframe,a=Vu[this.compares.length%Vu.length];this.compares.length===0&&this.chart.setCompareMode(`percent`),this.chart.addCompareSymbol(r,e,n,a),this.compares=[...this.compares,{id:r,symbol:e,color:a,bars:n,timeframe:i}],this.compares.length===1&&this.holdCompareScale(!0),this.scheduleLegend(),this.refreshObjects(),this.refreshCompareDialog(),this.say(t.r(this.t(`toast.comparing`),{symbol:e}))}finally{this.comparesLoading.delete(e)}}async addCompareIndicator(e,t,n){let r=await this.fetchCompareBars(e,t);r&&(this.chart.setSymbolSeries(t,r),n===`scale`?this.chart.addIndicator(`compareSymbol`,{symbol:t},`bottom`,{scale:`left`}):n===`pane`?this.chart.addIndicator(`compareSymbolPane`,{symbol:t}):n===`correlation`?this.chart.addIndicator(`correlation`,{symbol:t}):n===`correlationLog`?this.chart.addIndicator(`correlationlog`,{symbol:t}):this.chart.addIndicator(`spread`,{symbol:t,mode:n}))}async fetchCompareBars(e,n){for(;;){let i=this.state.timeframe,a=null,o=null;try{a=await(0,r.withResampling)(e).fetchHistory(n,i,this.compareDepth())}catch(e){o=e}if(this.destroyed)return null;if(i===this.state.timeframe)return a&&a.length>0?a:(o===null?this.say(t.r(this.t(`toast.compareNoBars`),{symbol:n,interval:Ct(i)}),`error`):this.sayCompareFailed(n,o),null)}}sayCompareFailed(e,t){this.say(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}removeCompared(e){this.compares.some(t=>t.id===e)?this.handleRemoveCompare(e):this.chart.removeIndicator(e)}handleRemoveCompare(e){this.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.compares.length===0&&this.holdCompareScale(!1),this.scheduleLegend(),this.refreshObjects(),this.refreshCompareDialog()}removeHostCompare(e){this.chart.removeCompareSymbol(e),this.scheduleLegend()}isPercentCompare(e){return this.compares.some(t=>t.id===e)}compareDepth(){return Math.max(this.chart.getData().length,this.options.historyLimit??500)}holdsPercentScale(){return this.compareScaleHeld&&this.compares.length>0&&this.settingsState.scaleMode===`regular`&&this.chart.isTimeAligned()}effectiveScaleMode(){return this.holdsPercentScale()?`percentage`:this.settingsState.scaleMode}userScaleMode(){return this.holdsPercentScale()?this.settingsState.scaleMode:this.chart.getScaleMode()}shownSettings(){return{...this.settingsState,scaleMode:this.effectiveScaleMode()}}showScaleMode(){let e=this.effectiveScaleMode();this.chart.getScaleMode()!==e&&this.chart.setScaleMode(e)}holdCompareScale(e){e!==this.compareScaleHeld&&(this.compareScaleHeld=e,this.showHeldScale())}showHeldScale(){this.showScaleMode(),this.refreshScaleSwitches(),this.settings?.refresh(this.shownSettings())}async loadSymbolSeries(e){if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}let t=this.state.timeframe,n=(this.symbolLoads.get(e)??0)+1;this.symbolLoads.set(e,n);let i=()=>this.destroyed||t!==this.state.timeframe||this.symbolLoads.get(e)!==n;try{let n=await(0,r.withResampling)(this.adapter).fetchHistory(e,t,this.compareDepth());if(i())return;this.chart.setSymbolSeries(e,n)}catch(t){if(i())return;this.chart.setSymbolSeries(e,this.chart.getSymbolSeries(e)),this.sayCompareFailed(e,t)}}async refetchCompares(){for(let e of this.chart.getRequiredSymbols?.()??[])this.loadSymbolSeries(e);if(!this.adapter||this.compares.length===0)return;let e=this.compares.filter(e=>e.symbol===this.state.symbol);for(let t of e)this.handleRemoveCompare(t.id);await this.refetchPercentCompares()}async refetchPercentCompares(){if(!this.adapter||this.compares.length===0)return;let e=++this.compareFetchSeq,t=(0,r.withResampling)(this.adapter);this.compares=this.compares.map(e=>({...e,failedAt:void 0}));for(let n of this.compares){let r=this.state.timeframe;try{let i=await t.fetchHistory(n.symbol,r,this.compareDepth());if(this.destroyed||e!==this.compareFetchSeq)return;this.isPercentCompare(n.id)&&this.setCompareBars(n.id,i,r)}catch{!this.destroyed&&e===this.compareFetchSeq&&this.compareFailedAt(n.id,r)}}this.compareOlderPassed&&(this.compareOlderPassed=!1,this.extendPercentCompares())}async extendPercentCompares(){if(this.compareOlderBusy){this.compareOlderAgain=!0;return}this.compareOlderBusy=!0;try{do this.compareOlderAgain=!1,await this.fetchOlderCompares();while(this.compareOlderAgain&&!this.destroyed)}finally{this.compareOlderBusy=!1}}async fetchOlderCompares(){if(!this.adapter||this.compares.length===0)return;let e=(0,r.withResampling)(this.adapter),t=this.compareFetchSeq,n=this.state.timeframe;for(let r of this.compares){if(r.timeframe!==n){r.failedAt!==n&&(this.compareOlderPassed=!0);continue}let i=r.bars[0]?.time;if(i===void 0||r.atStart)continue;let a=vl(this.chart.getData(),i);if(a!==0)try{if(e.fetchHistoryBefore){let o=await e.fetchHistoryBefore(r.symbol,n,i,a);if(this.destroyed||t!==this.compareFetchSeq)return;this.prependCompareBars(r.id,o,n)}else{let a=this.compareDepth(),o=await e.fetchHistory(r.symbol,n,a);if(this.destroyed||t!==this.compareFetchSeq)return;this.deepenCompareBars(r.id,o,a,i,n)}}catch{}}}deepenCompareBars(e,t,n,r,i){this.isPercentCompare(e)&&(this.setCompareBars(e,t,i),(t.length<n||!(t[0].time<r))&&(this.compares=this.compares.map(t=>t.id===e?{...t,atStart:!0}:t)))}prependCompareBars(e,t,n){let r=this.compares.find(t=>t.id===e);if(!r)return;let i=yl(r.bars,t);i?this.setCompareBars(e,i,n):this.compares=this.compares.map(t=>t.id===e?{...t,atStart:!0}:t)}setCompareBars(e,t,n){this.chart.updateCompareData(e,t),this.compares=this.compares.map(r=>r.id===e?{...r,bars:t,timeframe:n,atStart:!1,failedAt:void 0}:r)}compareFailedAt(e,t){this.compares=this.compares.map(n=>n.id===e?{...n,failedAt:t}:n)}refreshAlerts(){if(!this.alertsPanel)return;let e=this.buildAlertSources();this.alertsPanel.setSources(e),this.alertsPanel.setAlerts(this.chart.getAlerts().map(t=>this.alertListItem(t,e)))}refreshPriceTexts(){this.refreshAlerts(),this.refreshAccountSoon(),this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())}alertListItem(e,t){return{id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,targetLabel:e.target?t.find(t=>t.channel===e.target)?.label:void 0,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}}alertText(e){return Fi(this.alertListItem(e,this.buildAlertSources()),this.t,e=>this.formatAlertPrice(e),!0)}buildAlertSources(){let e=[{channel:`price`,label:this.t(`alerts.source.price`)}];for(let t of this.chart.getActiveIndicators()){let n=this.chart.getIndicatorOutput(t.instanceId)?.series,r=n&&n.length>0?n[n.length-1]:null,i=r?Object.keys(r).filter(e=>typeof r[e]==`number`):[];for(let n of i){let r=i.length>1?`${t.descriptor.name} ${n}`:t.descriptor.name;e.push({channel:`${t.instanceId}:${n}`,label:r})}}return e}getAlertChannelValue(e){let t=this.chart.getData();if(e===`price`)return t.length>0?this.chart.roundPrice(t[t.length-1].close):null;let n=e.indexOf(`:`);if(n<0||t.length===0)return null;let r=e.slice(0,n),i=e.slice(n+1),a=Bl(this.chart.getIndicatorOutput(r)?.series,null)?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}formatMoney(e){return this.formatNumber(e,Math.min((0,n.stepDecimals)(this.chart.getPriceStep()),Gu))}formatVolume(e){return(0,n.formatVolumeLoc)(e,this.settingsState.numberLocale||`en-US`)}formatNumber(e,t){let n=this.settingsState.numberLocale||void 0;return e.toLocaleString(n,{minimumFractionDigits:t,maximumFractionDigits:t})}formatAlertPrice(e,t=e){if(this.chart.getPriceFormatter?.()||this.chartSetsDecimals())return this.chart.formatPrice(e);let n=Math.abs(t),r=n>=1e3?2:n>=1?4:6,i=this.settingsState.numberLocale||void 0;return e.toLocaleString(i,{minimumFractionDigits:2,maximumFractionDigits:r})}indicatorValueText(e,t,n){return t?this.chart.formatPrice(e):Wl(e,n)}chartSetsDecimals(){return this.chart.getMarket?.()?.pricePrecision!=null||this.chart.getSymbolInfo?.()?.pricePrecision!=null}handleChartType(e){let t=this.state.chartType;e!==t&&(this.applyChartType(e),this.chart.recordUndo({subject:`chartType`,undo:()=>this.applyChartType(t),redo:()=>this.applyChartType(e)}))}applyChartType(e){this.state={...this.state,chartType:e},this.chart.setChartType(e),this.settings?.refresh(this.shownSettings(),e),this.updateUI()}handleAddIndicator(e){return this.chart.addIndicator(e,this.indicatorDefaults.get(e)?.params??{})!==null}saveIndicatorDefault(e,n){if(!this.indicatorDefaults.save(e,n)){this.say(this.t(`indicatorSettings.defaultSaveFailed`),`error`);return}this.chart.setIndicatorDefaults(e,n.style);let r=this.chart.getAvailableIndicators()?.find(t=>t.id===e)?.shortName??e.toUpperCase();this.say(t.r(this.t(`indicatorSettings.defaultSaved`),{name:r}))}handleRemoveIndicator(e){this.chart.removeIndicator(e)}toggleCommandPalette(){if(this.commandPalette?.isOpen()){this.commandPalette.close();return}this.featureState.commandPalette&&this.commandPalette?.open(this.buildCommandItems())}buildCommandItems(){let e=[];for(let t of this.indicatorPickerItems())e.push({id:t.id,label:t.name,category:`indicator`,active:[...this.state.activeIndicators.values()].some(e=>e.id===t.id)});for(let t of pe)e.push({id:t.value,label:vt(t,this.t),category:`chartType`,active:this.state.chartType===t.value});let t=ki();for(let n of yt(me,this.t))for(let r of n.tools)e.push({id:r.value,label:r.label,category:`drawing`,shortcut:t[r.value]?this.keysShown(`hotkeys.tools`,t[r.value]):void 0,active:this.state.activeTool===r.value});for(let t of this.timeframes)e.push({id:t,label:Ct(t),category:`timeframe`,active:this.state.timeframe===t});return e.push({id:`symbolSearch`,label:this.t(`hotkeys.symbolSearch`),category:`action`,shortcut:this.keysShown(`hotkeys.symbolSearch`,`${nr}+P`)},{id:`compare`,label:this.t(`compare.title`),category:`action`},{id:`goToDate`,label:this.t(`hotkeys.goToDate`),category:`action`,shortcut:this.keysShown(`hotkeys.goToDate`,`Alt+G`)},{id:`resetView`,label:this.t(`chartMenu.resetView`),category:`action`,shortcut:this.keysShown(`hotkeys.resetView`,`Alt+R`)},{id:`invertScale`,label:this.t(`hotkeys.invertScale`),category:`action`,shortcut:this.keysShown(`hotkeys.invertScale`,`Alt+I`)},{id:`saveLayout`,label:this.t(`hotkeys.saveLayout`),category:`action`,shortcut:this.keysShown(`hotkeys.save`,`${nr}+S`)},{id:`watchlist`,label:this.t(`watchlist.title`),category:`action`},{id:`alerts`,label:this.t(`alerts.title`),category:`action`},{id:`objectTree`,label:this.t(`objects.title`),category:`action`},{id:`dataWindow`,label:this.t(`action.dataWindow`),category:`action`},{id:`symbolInfo`,label:this.t(`action.symbolInfo`),category:`action`},{id:`screenshot`,label:this.t(`action.screenshot`),category:`action`},{id:`copyImage`,label:this.t(`action.copyImage`),category:`action`},{id:`shareView`,label:this.t(`action.shareView`),category:`action`},{id:`toggleTheme`,label:this.t(`action.toggleTheme`),category:`action`},{id:`settings`,label:this.t(`action.settings`),category:`action`},{id:`autoFib`,label:this.t(`action.autoFib`),category:`action`},{id:`clearDrawings`,label:this.t(`action.clearDrawings`),category:`action`},{id:`clearIndicators`,label:this.t(`clear.indicators`),category:`action`},{id:`clearAll`,label:this.t(`clear.all`),category:`action`},{id:`hotkeys`,label:this.t(`hotkeys.title`),category:`action`,shortcut:this.keysShown(`hotkeys.help`,`?`)}),e.filter(e=>e.category!==`action`||this.commandOn(e.id)&&this.commandThere(e.id))}commandThere(e){return e===`watchlist`?this.watchlist!==null:e===`compare`?this.adapter!==null&&this.options.chartOptions?.features?.compareSymbols!==!1:e===`saveLayout`?this.layoutSession!==null:!0}keysShown(e,t){if(this.sheetKeyOn(e))return this.hostHotkeys.some(e=>e.parsed.display.join(`+`).toLowerCase()===t.toLowerCase())?void 0:t}openHotkeySheet(){this.hotkeySheet?.open({isOn:e=>this.sheetKeyOn(e),extra:this.hostHotkeys.map(e=>({keys:e.parsed.display,text:e.spec.label}))})}commandOn(e){let t=qe(e);return t===void 0||this.featureState[t]}openClearMenu(e){if(A.closeAnchoredTo(e))return;let t=this.chart.getDrawings().filter(e=>!e.locked).length,n=this.chart.getActiveIndicators().length,r=[];t>0&&r.push({id:`drawings`,label:this.t(`clear.drawings`),icon:`penLine`,count:t}),n>0&&r.push({id:`indicators`,label:this.t(`clear.indicators`),icon:`trendingUp`,count:n}),t>0&&n>0&&r.push(`separator`,{id:`all`,label:this.t(`clear.all`),icon:`trash`,danger:!0}),r.length!==0&&(this.clearMenu??=new A(this.root,this.t(`drawing.clearAll`)),this.clearMenu.openBeside(r,e,e=>this.removeAll(e)))}removeAll(e){this.chart.removeAll(e),this.state={...this.state,activeTool:null},this.updateUI(),this.refreshDrawingsState(),this.refreshObjects()}handleAction(e){if(this.commandOn(e))switch(e){case`symbolSearch`:this.openSymbolSearch();break;case`compare`:this.handleAddCompare();break;case`goToDate`:this.toggleGoToDate();break;case`resetView`:this.resetView();break;case`invertScale`:this.changeSettings({invertScale:!this.settingsState.invertScale}),this.settings?.refresh(this.shownSettings());break;case`saveLayout`:this.saveLayout();break;case`watchlist`:case`alerts`:case`objectTree`:this.openPanel(e);break;case`hotkeys`:this.openHotkeySheet();break;case`screenshot`:this.chart.screenshot();break;case`toggleTheme`:this.handleToggleTheme();break;case`settings`:this.openSettings();break;case`copyImage`:this.copyChartImage();break;case`shareView`:this.copyShareLink();break;case`autoFib`:{let e=this.chart.autoFib();this.say(e?this.t(`toast.autoFibAdded`):this.t(`toast.noSwing`));break}case`dataWindow`:this.toggleDataWindow();break;case`symbolInfo`:this.toggleSymbolInfo();break;case`clearDrawings`:this.removeAll(`drawings`);break;case`clearIndicators`:this.removeAll(`indicators`);break;case`clearAll`:this.removeAll(`all`);break}}handleDrawingTool(e){this.state={...this.state,activeTool:e},this.chart.setDrawingTool(e),this.updateUI()}handleCancelDrawing(){this.state={...this.state,activeTool:null},this.chart.setDrawingTool(null),this.chart.setEraserMode(!1),this.chart.setZoomAreaMode(!1),this.updateUI()}handleToggleStayInDrawing(){let e=!this.state.stayInDrawing;this.state={...this.state,stayInDrawing:e},this.chart.setStayInDrawingMode(e),this.updateUI()}handleToggleMagnet(){let e=this.state.magnetEnabled?this.state.magnetStrong?`off`:`strong`:`weak`;this.state={...this.state,magnetEnabled:e!==`off`,magnetStrong:e===`strong`},this.chart.setDrawingMagnetMode(e),this.updateUI()}handleToggleTheme(){if(!this.featureState.themeToggle)return;let e=!this.state.isDark;this.state={...this.state,isDark:e},this.root.dataset.tcwTheme=e?`dark`:`light`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.keepingLook(()=>this.chart.setTheme(e?this.themeOf.dark:this.themeOf.light)),this.chart.setWatermark(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:48,color:e?`rgba(255,255,255,0.03)`:`rgba(0,0,0,0.03)`}),this.updateUI()}openSettings(e){!this.featureState.settings||this.settings?.isOpen()||(this.syncSettingsFromChart(),this.markSettingsTold(),this.settingsEdit={settings:{...this.settingsState},style:this.settingsStyle(),keys:new Set,styleKeys:new Set,held:this.compareScaleHeld},this.settings?.open(this.shownSettings(),this.state.chartType,e))}resetView(){this.chart.fitContent(),this.changeSettings({autoScale:!0}),this.settings?.refresh(this.shownSettings())}endSettingsEdit(e){let t=this.settingsEdit;if(this.settingsEdit=null,!t)return;let n=[...t.keys],r=e=>Object.fromEntries(n.map(t=>[t,e[t]])),i=[...t.styleKeys],a=r(t.settings),o=i.length>0?{theme:t.style.theme,overrides:Object.fromEntries(i.map(e=>[e,t.style.overrides[e]??null]))}:null,s=t.keys.has(`scaleMode`),c=this.compareScaleHeld;if(!e){this.restoreSettings(a,o,s?t.held:void 0);return}let l=r(this.getSettings()),u=i.length>0?this.settingsStyle(i):null;(JSON.stringify([a,o])!==JSON.stringify([l,u])||s&&t.held!==c)&&this.chart.recordUndo({undo:()=>this.restoreSettings(a,o,s?t.held:void 0),redo:()=>this.restoreSettings(l,u,s?c:void 0)}),this.claimSettings(n),this.publishSettings()}touchSettings(e,t=[]){if(!this.settingsEdit){this.claimSettings(e);return}for(let t of e)this.settingsEdit.keys.add(t);for(let e of t)this.settingsEdit.styleKeys.add(e)}applyChartTemplate(e){let n=this.chartTemplates.get(e);if(!n)return;let r=this.allowedSettings(n.settings);this.touchSettings(Object.keys(r),E),this.applySettings(r),this.chart.resetOverrides([...E],{layer:`user`}),this.chart.applyOverrides(n.style,{layer:`user`}),this.settings?.refresh(this.shownSettings()),this.say(t.r(this.t(`templates.applied`),{name:e}))}promptSaveChartTemplate(){this.chartTemplatePrompt??=new Lc(this.overlayHost(),this.t),this.chartTemplatePrompt.open({title:this.t(`settings.saveTemplateTitle`),submitLabel:this.t(`common.save`),placeholder:this.t(`settings.templatePlaceholder`),onSubmit:e=>{if(!this.chartTemplates.save(e,this.settingsState,this.settingsStyle().overrides))throw this.say(this.t(`templates.saveFailed`),`error`),Error(`The template could not be saved`);this.say(t.r(this.t(`templates.saved`),{name:e}))}})}toast(e,t=`info`,n){let r=document.createElement(`div`);r.className=`tcw-toast ${t===`error`?`tcw-toast-error`:``}`,r.setAttribute(`role`,t===`error`?`alert`:`status`);let i=n?O(n,14):``;if(i){let e=document.createElement(`span`);e.className=`tcw-toast-icon`,e.innerHTML=i,r.appendChild(e)}r.appendChild(document.createTextNode(e));let a=e=>e.querySelector(`.tcw-modal-backdrop:not([hidden])`)!==null,o=a(this.portal)?this.portal:this.root;r.classList.toggle(`tcw-toast-over`,o===this.portal||a(this.root)),o.appendChild(r),requestAnimationFrame(()=>r.classList.add(`tcw-toast-in`)),setTimeout(()=>{r.classList.remove(`tcw-toast-in`),r.addEventListener(`transitionend`,()=>r.remove(),{once:!0}),setTimeout(()=>r.remove(),400)},3500)}say(e,t=`info`,n){(this.featureState.toasts||t===`error`)&&this.toast(e,t,n)}getLayoutSession(){return this.layoutSession}getSymbol(){return this.state.symbol}getTimeframe(){return this.state.timeframe}captureLayout(){let e=this.getSettings(),t=this.chart.saveState(),n=t?el(t):null,r=n&&typeof n==`object`?Qc(n):null;return{v:1,symbol:this.state.symbol,timeframe:this.chosenTimeframe??this.state.timeframe,scaleMode:e.scaleMode,invertScale:e.invertScale,chart:r,settings:So(e,co)}}async restoreLayout(e){if(e.symbol!==this.state.symbol&&await this.setSymbol(e.symbol),e.timeframe!==this.state.timeframe&&await this.setTimeframe(e.timeframe),this.destroyed)return;if(e.chart){this.chart.loadState(JSON.stringify(Qc(e.chart)));let t=e.chart.chartType;typeof t==`string`&&(this.state={...this.state,chartType:t})}let t=this.allowedSettings({scaleMode:e.scaleMode,invertScale:e.invertScale,...K(e.settings,co)});this.claimSettings(Object.keys(t)),this.applySettings(t),this.syncIndicatorsFromChart(),this.updateUI(),this.settings?.refresh(this.shownSettings(),this.state.chartType)}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=$c(el(e));return t?(await this.restoreLayout(t),!0):!1}getSettings(){return this.syncSettingsFromChart(),JSON.parse(JSON.stringify(this.settingsState))}setSettings(e){let t=this.allowedSettings(this.withoutEarlyFreeze(K(e)));this.claimSettings(Object.keys(t)),this.applySettings(t),this.settings?.refresh(this.shownSettings())}withoutEarlyFreeze(e){return e.autoScale!==!1||this.chart.getData().length>0?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==`autoScale`))}onSettingsChange(e){return this.settingsListeners.add(e),()=>{this.settingsListeners.delete(e)}}syncSettingsFromChart(){let e=this.chart,t=e.getTimeZone?.(),n=e.getMarketProfileConfig?.(),r=e.getPivotMarkersConfig?.(),i=this.allowedSettings(K({gridVisible:e.isGridVisible?.(),volumeVisible:e.isVolumeVisible?.(),legendVisible:e.isLegendVisible?.(),barCountdown:e.isBarCountdownVisible?.(),indicatorValueLabels:e.isIndicatorValueLabelsVisible?.(),alignAxisLabels:e.isAxisLabelsAligned?.(),leftPriceScale:e.isLeftPriceScaleVisible?.(),volumeProfileVisible:e.isVolumeProfileVisible?.(),marketProfileVisible:e.isMarketProfileVisible?.(),marketProfileSplit:n?.splitBySession,marketProfileLetters:n?.letters,marketProfileBuckets:n?.buckets,marketProfileOpacity:n?.opacity,depthHeatmapVisible:e.isDepthHeatmapVisible?.(),depthHeatmapOpacity:e.getDepthHeatmapConfig?.()?.opacity,pivotMarkersVisible:e.isPivotMarkersVisible?.(),pivotStrength:r?.left,pivotStructureLabels:r?.structureLabels,sessionShadingVisible:e.isSessionShadingVisible?.(),periodLevelsVisible:e.isPeriodLevelsVisible?.(),periodLevelsPeriod:e.getPeriodLevelsPeriod?.(),crosshairMode:e.getCrosshairMode?.(),scaleMode:this.userScaleMode(),autoScale:e.isAutoScale?.(),invertScale:e.isInvertScale?.(),timezone:t===void 0?void 0:d(t),numberLocale:e.getNumberLocale?.(),highLowLines:e.isHighLowLinesVisible?.(),extendedHours:e.isExtendedHoursVisible?.(),mainSeriesVisible:e.isMainSeriesVisible?.(),chartTypeOptions:e.getChartTypeOptions?.()})),a=i.scaleMode?{logScale:i.scaleMode===`logarithmic`}:{},o=i.chartTypeOptions?{chartTypeOptions:mo(i.chartTypeOptions)}:{};this.settingsState={...this.settingsState,...i,...a,...o}}allowedSettings(e){let t=this.settingsLocked,n=(e,n)=>e===`scaleMode`?n===`logarithmic`&&t.has(`logScale`):n===!0&&t.has(e);return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0&&!n(e,t)))}restoreKeptSettings(){let e=this.allowedSettings(this.settingsStore?.load()??{});Object.keys(e).length>0&&this.applySettings(e),this.settingsPublished=JSON.stringify(this.getSettings())}markSettingsTold(){this.settingsPublished!==null&&(this.settingsPublished=JSON.stringify(this.getSettings()))}publishSettings(){if(this.settingsPublished===null||this.destroyed)return;let e=this.getSettings(),t=JSON.stringify(e);if(t!==this.settingsPublished){this.settingsPublished=t,this.settingsStore?.save(this.ownSettings(e),this.settingsDefaults);for(let e of[...this.settingsListeners])try{e(JSON.parse(t))}catch(e){console.error(`[TradeCanvas] An onSettingsChange listener threw:`,e)}}}setupLayouts(t){let n=new e.t(t.storage??e.i(),{capture:()=>({content:this.getLayoutContent(),symbol:this.state.symbol,timeframe:this.chosenTimeframe??this.state.timeframe}),apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a widget layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,onChange:()=>this.toolbar?.setLayout(n.current()?.name??null,n.isDirty()),onError:()=>this.say(this.t(`layouts.saveFailed`),`error`)});this.layoutSession=n,this.layoutsUI=new Vc(n,{root:this.root,t:this.t,saveKeys:()=>this.keysShown(`hotkeys.save`,`${nr}+S`),toast:(e,t)=>this.say(e,t),formatTime:e=>{let{date:t,time:n}=Q(e,this.displayTimezone());return`${t} ${n}`}}),this.chart.on(`stateChange`,()=>n.changed()),t.openLast&&n.list().then(([e])=>e&&!this.destroyed?this.openLayout(e.id):void 0,()=>void 0)}async saveLayout(){await this.layoutsUI?.save()}async openLayout(e){return await this.layoutsUI?.open(e)??!1}clearSavedLayout(e){if(!this.layoutKeyPrefix)return;let t=e??this.state.symbol;try{localStorage.removeItem(this.layoutKeyPrefix+t)}catch{}}applySymbolLayout(e){if(!this.layoutKeyPrefix)return;let t=this.layoutKeyPrefix+e;this.activeLayoutKey=t;try{this.chart.loadStateFromStorage(t)&&this.syncIndicatorsFromChart()}catch{}this.chart.setAutoSave(t,this.layoutDebounceMs)}flushActiveLayout(){if(this.activeLayoutKey){try{this.chart.saveState(this.activeLayoutKey)}catch{}this.chart.disableAutoSave(),this.activeLayoutKey=null}}syncIndicatorsFromChart(){let e=new Map;for(let t of this.chart.getActiveIndicators())e.set(t.instanceId,{id:t.id,label:qi(t,this.t)});this.state={...this.state,activeIndicators:e},this.updateUI(),this.indicatorPicker?.setCounts(this.indicatorCounts())}toggleIndicatorPicker(){if(this.indicatorPicker?.isOpen()){this.indicatorPicker.close();return}!this.indicatorPicker||!this.featureState[`toolbar.indicators`]||(this.indicatorPicker.open({items:this.indicatorPickerItems(),favorites:this.indicatorFavorites.list(),templates:this.featureState.indicatorTemplates?this.templateNames():null,counts:this.indicatorCounts()}),this.toolbar?.setIndicatorsOpen(!0))}indicatorPickerItems(){return(this.chart.getAvailableIndicators()??[]).filter(e=>!r.SYMBOL_INDICATOR_IDS.has(e.id)&&this.chart.isIndicatorAllowed(e.id)!==!1).map(e=>({id:e.id,name:e.name,shortName:e.shortName??e.id.toUpperCase(),placement:e.placement===`panel`?`panel`:`overlay`,category:(0,r.indicatorCategory)(e)}))}indicatorCounts(){let e=new Map;for(let{id:t}of this.state.activeIndicators.values())e.set(t,(e.get(t)??0)+1);return e}templateNames(){return this.templates.list().map(e=>e.name)}toggleReplay(){this.replayBar?.isMounted()?this.exitReplay():this.featureState.replay&&this.enterReplay()}enterReplay(){if(this.replayTotal()<2)return;let e=this.t;this.replayBar=new ri({onPlay:()=>{if(this.replayBar?.getMode()===`select`){this.seriesPending()||this.startReplayAt(Math.max(1,this.replayTotal()-100),!0);return}this.replayStartPending?this.replayPlayWanted=!0:this.chart.getReplayState()===`paused`&&this.chart.replayResume(),this.syncReplayBar()},onPause:()=>{this.replayPlayWanted=!1,this.chart.replayPause(),this.syncReplayBar()},onStepBack:()=>this.stepReplay(-1),onStepForward:()=>this.stepReplay(1),onSeek:e=>{this.seriesPending()||(this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(e),this.replayBar?.setState(`paused`))},onSpeedChange:e=>{this.replaySpeed=e,this.chart.setReplaySpeed(e)},onRandomStart:()=>{if(this.seriesPending())return;let e=this.replayBarCount(),t=Math.max(1,Math.floor(e*.1)),n=Math.max(t,Math.floor(e*.9));this.startReplayAt(t+Math.floor(Math.random()*(n-t+1)),!1,!0)},onClose:()=>this.exitReplay(),onSelectBar:()=>this.pickReplayBarAgain(),onCancelPick:()=>this.cancelReplayPick(),onStepChange:e=>{if(this.replayStep=e,this.replayBar?.getMode()!==`replay`)return;let t=this.chart.getReplayState()===`playing`;this.startReplayAt(Math.max(0,this.chart.getReplayBarIndex()-1),t)}},{selectHint:e(`replay.selectHint`),loading:e(`status.loading`),random:e(`replay.random`),realtime:e(`replay.realtime`),play:e(`replay.play`),pause:e(`replay.pause`),stepBack:e(`replay.stepBack`),stepForward:e(`replay.stepForward`),replay:e(`replay.label`),position:e(`replay.position`),speed:e(`replay.speed`),step:e(`replay.step`),selectBar:e(`replay.selectBar`),cancel:e(`common.cancel`),rate:e(`replay.rate`),rateHint:e(`replay.rateHint`),playingAt:e(`replay.playingAt`),pausedAt:e(`replay.pausedAt`),endedAt:e(`replay.endedAt`)});let n=this.replayStepMenu();this.replayBar.mount(this.chartContainer,{total:this.replayTotal(),rate:this.replaySpeed,mode:`select`,steps:n,step:this.replayStep,dir:this.root.dir===`rtl`?`rtl`:`ltr`,formatRate:n=>t.r(e(`replay.rate`),{rate:n.toLocaleString(this.intlLocale())})}),this.watchReplayBar(),this.toolbar?.setActive(`replay`,!0),this.root.setAttribute(`data-tcw-replay`,``),this.showReplayShade(),this.layoutReplayBar()}showReplayShade(){this.replayShade||(this.replayShade=document.createElement(`div`),this.replayShade.className=`tcw-replay-shade`,this.replayShade.hidden=!0,this.chartContainer.appendChild(this.replayShade),this.chartContainer.addEventListener(`mouseleave`,this.hideReplayShade))}removeReplayShade(){this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade)}pickReplayBarAgain(){let e=this.replayBar;!e?.isMounted()||this.seriesPending()||(this.replayPlayWanted=!1,this.chart.getReplayState()===`playing`&&this.chart.replayPause(),e.setState(`paused`),e.setMode(`select`),this.showReplayShade(),this.layoutReplayBar())}cancelReplayPick(){let e=this.replayBar;if(e?.isMounted()){if(!this.chart.isReplayActive()&&!this.replayStartPending){this.exitReplay();return}this.removeReplayShade(),e.setMode(`replay`),this.syncReplayBar(),this.layoutReplayBar()}}layoutReplayBar(){let e=this.replayBar?.element();if(!e||!this.replayBar)return;let t=this.chart.getPlotRect(),n=this.chartContainer,r=e=>`${Math.max(0,Math.round(e))}px`;e.style.setProperty(`--tcw-replay-foot`,r(n.clientHeight-(t.y+t.height))),e.style.setProperty(`--tcw-replay-plot-start`,r(t.x)),e.style.setProperty(`--tcw-replay-plot-end`,r(n.clientWidth-(t.x+t.width))),this.replayBar.setRoom(t.width-2*td),this.liftOverReplayBar()}liftOverReplayBar(){let e=this.replayBar?.element();if(!e)return;let t=e.getBoundingClientRect().top,n=e=>{if(!e)return;let n=`${Math.max(0,Math.round(e.getBoundingClientRect().bottom-t))}px`;e.style.getPropertyValue(`--tcw-replay-lift`)!==n&&e.style.setProperty(`--tcw-replay-lift`,n)};n(this.root),n(this.bodyEl())}placeDrawingButton(){let e=this.bodyEl();if(!this.sidebar||!e)return;let t=this.chartContainer.getBoundingClientRect().left-e.getBoundingClientRect().left;this.sidebar.setPlotLeft(t+this.chart.getPlotRect().x)}bodyEl(){return this.root.querySelector(`:scope > .tcw-body`)}replayTimeText(){let e=this.chart.getReplayProgress(),t=(this.chart.getReplayBarIndex()>e.current?e.time:null)??this.replayStepTime;if(t===null)return;let r=this.textLocale(),i=this.chart.getTimeZone?.()??null,a=(0,n.timeframeToMs)(this.state.timeframe),o=(0,n.zonedDateFormatter)(r,{year:`numeric`},i),s={month:`short`,day:`numeric`};o(t)!==o(Date.now())&&(s.year=`numeric`);let c=(0,n.zonedDateFormatter)(r,s,i)(t);if(Number.isFinite(a)&&a>=Hu)return c;let l={hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`};return(!Number.isFinite(a)||a<nd)&&(l.second=`2-digit`),`${c} · ${(0,n.zonedDateFormatter)(r,l,i)(t)}`}replayBarCount(){return this.chart.isReplayActive()&&this.replayBarsTotal!==null?this.replayBarsTotal:this.chart.getData().length}hideReplayShade=()=>this.positionReplayShade(null);replayFrom(e,t=!1){this.featureState.replay&&(this.replayBar?.isMounted()||this.enterReplay(),this.startReplayAt(e,t))}replayStepMenu(){let e=[{value:`auto`,label:this.t(`replay.step.auto`)},{value:`bar`,label:this.t(`replay.step.bar`)},...this.replayStepOptions().map(e=>({value:e,label:e}))];return e.some(e=>e.value===this.replayStep)||(this.replayStep=`auto`),e}refreshReplaySteps(){if(!this.replayBar?.isMounted())return;let e=this.replayStepMenu();this.replayBar.setSteps(e,this.replayStep)}afterReplayCarryOver(){let e=this.replayBar;!e?.isMounted()||e.getMode()!==`replay`||(this.syncReplayBar(),!(this.replayStep===`bar`||this.chartFetchesReplaySteps())&&this.replayStepsKey!==this.replayStepsKeyNow()&&this.startReplayAt(this.chart.getReplayBarIndex(),this.chart.getReplayState()===`playing`))}startPickedReplay(){let e=this.replayPickTime;if(e===null)return;if(this.loading.hasFailed()||this.replayBar?.getMode()!==`select`){this.replayPickTime=null;return}if(this.seriesPending())return;this.replayPickTime=null;let t=this.chart.getData();if(!Td(t,e))return;let n=0;for(;n+1<t.length&&t[n+1].time<=e;)n++;this.startReplayAt(n,!1,!0)}seriesPending(){return this.loading.isActive()&&!this.loading.hasFailed()}watchReplayBar(){this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayPollInterval=setInterval(()=>this.syncReplayBar(),$u)}startReplayAt(e,t=!1,n=!1){let r=this.replayBar;if(!r)return;let i=n?this.replayBarCount():this.replayTotal(),a=Math.max(0,Math.min(Number.isFinite(e)?Math.floor(e):0,i-1)),o=this.chart.getData()[a]?.time;this.removeReplayShade(),r.setMode(`replay`),this.layoutReplayBar();let s=++this.replayStartSeq;this.replayPlayWanted=t;let c=this.options.replayAnimate!==!1,l=this.chartFetchesReplaySteps(),u=e=>{this.destroyed||this.replayBar!==r||!r.isMounted()||s!==this.replayStartSeq||(this.replayStartPending=!1,this.replayStepsKey=e?this.replayStepsKeyNow():null,this.chart.replayStart({speed:this.replaySpeed,interval:c?Uu:Uu/this.replayStepsPerBar(e?d:null),...o===void 0?{startIndex:a}:{startTime:o},paused:!0,revealMarks:this.options.replayRevealMarks!==!1,animate:c,...l?{step:this.replayStep}:{},...e?{steps:e}:{}}),this.replayPlayWanted&&this.chart.replayResume(),this.replayPlayWanted=!1,this.syncReplayBar(),this.watchReplayBar())},d=this.replayStepInterval();if(l||d===null){u(null);return}this.replayStartPending=!0,this.replayStepsFor(d).then(e=>{s===this.replayStartSeq&&(e||this.say(this.t(`replay.stepsFailed`),`error`),u(e))})}replayStepsKeyNow(){return`${this.state.symbol}|${this.state.timeframe}`}replayStepsPerBar(e){if(e===null)return 1;let t=(0,n.timeframeToMs)(this.state.timeframe)/(0,n.timeframeToMs)(e);return Number.isFinite(t)&&t>=1?Math.round(t):1}replayStepOptions(){return e.d(this.state.timeframe,e=>this.hasReplayStep(e))}hasReplayStep(e){if(this.adapter)return(0,r.servesTimeframe)(this.adapter,e);let t=(0,n.timeframeToMs)(e);return this.baseSeries!==null&&this.baseTimeframeMs>0&&t>=this.baseTimeframeMs&&t%this.baseTimeframeMs===0}replayStepInterval(){return this.replayStep===`bar`||this.replayStep===`auto`&&this.options.replayAnimate===!1?null:e.f(this.replayStep,this.state.timeframe,e=>this.hasReplayStep(e))}chartFetchesReplaySteps(){return this.options.replayAnimate===!1||!this.adapter||this.replayStep===`bar`?!1:(0,r.withResampling)(this.adapter).fetchHistoryBefore!==void 0}async replayStepsFor(e){let t=this.chart.getExchangeTimeZone()??null,{symbol:a,timeframe:o}=this.state,s=()=>`${a}|${o}|${e}|${t}|${this.builtStepsZone(a,e)}`;if(this.replayStepsCache?.key===s())return this.replayStepsCache.steps;let c=null;if(this.adapter){let t=Math.max(1,Math.round((0,n.timeframeToMs)(o)/(0,n.timeframeToMs)(e))),i=Math.min(ed,Math.max(this.chart.getData().length,100)*t);try{c=await(0,r.withResampling)(this.adapter).fetchHistory(a,e,i)}catch{c=null}}else this.baseSeries&&(c=(0,n.timeframeToMs)(e)===this.baseTimeframeMs?this.baseSeries:i(this.baseSeries,e,this.resampleOptions(t)));return!c||c.length===0?null:(this.replayStepsCache={key:s(),steps:c},c)}builtStepsZone(e,t){let n=this.adapter?(0,r.withResampling)(this.adapter):null;if(!(n instanceof r.ResamplingAdapter))return``;let i=n.bucketFor(e,t);return i?String(i.timeZone??`UTC`):``}replayTotal(){return this.chart.isReplayActive()?this.chart.getReplayProgress().total:this.chart.getData().length}syncReplayBar(){let e=this.replayBar;if(!e?.isMounted()||(e.setPending(this.seriesPending()),this.startPickedReplay(),this.liftOverReplayBar(),e.getMode()!==`replay`))return;if(this.replayStartPending){e.setState(`paused`);return}if(!this.chart.isReplayActive()){this.teardownReplayUi();return}let t=this.chart.getReplayProgress(),n=this.chart.getReplayState();e.setProgress(t.current,t.total,this.replayTimeText()),e.setState(n===`stopped`?`paused`:n),e.setEnded(n!==`playing`&&t.total>0&&t.current>=t.total-1)}stepReplay(e){if(this.replayBar?.getMode()!==`replay`||this.seriesPending())return;let t=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause();let n=this.chart.getReplayBarIndex()>t.current?e>0?this.chart.getReplayBarIndex():t.current:t.current+e;this.chart.replaySeek(Math.max(0,Math.min(t.total-1,n))),this.replayBar.setState(`paused`),this.syncReplayBar()}handleReplayKey(e){if(e.defaultPrevented||e.isComposing||e.keyCode===id||Z()||rd()||!Yc(this.root,!0))return!1;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t)||t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable))return!1;let n=this.replayBar?.getMode();return e.shiftKey&&(e.key===`ArrowRight`||e.key===`ArrowLeft`)&&n===`replay`?(e.preventDefault(),e.stopPropagation(),this.stepReplay(e.key===`ArrowRight`?1:-1),!0):e.key===` `&&n===`replay`&&this.onChartSurface(t)?(e.preventDefault(),e.stopPropagation(),this.toggleReplayPlay(),!0):e.key===`Escape`&&n===`select`?(this.cancelReplayPick(),!0):!1}onChartSurface(e){return!e||!this.chartContainer.contains(e)?!1:e===this.chartContainer||e.closest(`button, [role="button"], a, .tcw-replay-bar`)===null}toggleReplayPlay(){if(this.replayStartPending){this.replayPlayWanted=!this.replayPlayWanted;return}this.chart.getReplayState()===`playing`?this.chart.replayPause():this.replayBarAtEnd()||this.chart.replayResume(),this.syncReplayBar()}replayBarAtEnd(){let e=this.chart.getReplayProgress();return e.total>0&&e.current>=e.total-1}positionReplayShade(e){let t=this.replayShade;if(!t)return;let n=this.chart.getPlotRect();if(e===null||e<n.x||e>n.x+n.width){t.hidden=!0;return}t.hidden=!1,t.style.left=`${e}px`,t.style.top=`${n.y}px`,t.style.width=`${n.x+n.width-e}px`,t.style.height=`${n.height}px`}exitReplay(){this.teardownReplayUi(),this.chart.replayStop()}teardownReplayUi(){this.replayStartSeq++,this.replayPickTime=null,this.replayStartPending=!1,this.replayPlayWanted=!1,this.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.removeReplayShade();let e=!!this.replayBar?.element()?.contains(document.activeElement);this.replayBar?.unmount(),this.replayBar=null,this.replayBarsTotal=null,this.replayStepTime=null,this.toolbar?.setActive(`replay`,!1),this.root.removeAttribute(`data-tcw-replay`),this.root.style.removeProperty(`--tcw-replay-lift`),this.bodyEl()?.style.removeProperty(`--tcw-replay-lift`),e&&this.focusAfterReplay()}focusAfterReplay(){let e=e=>!!e&&!e.hidden&&!e.closest(`[hidden]`)&&getComputedStyle(e).display!==`none`,t=this.root.querySelector(`.tcw-toolbar [data-role="replay"]`),n=this.root.querySelector(`.tcw-toolbar .tcw-toolbar-more`);(e(t)?t:e(n)?n:this.chartContainer)?.focus()}applySettings(e,t=!0){this.settingsState={...this.settingsState,...e},Object.keys(e).some(e=>!od.has(e))&&this.layoutSession?.changed(),this.scheduleLegend(),e.gridVisible!==void 0&&this.chart.setGridVisible(e.gridVisible),e.volumeVisible!==void 0&&this.chart.setVolumeVisible(e.volumeVisible),e.volumeProfileVisible!==void 0&&this.chart.setVolumeProfileVisible(e.volumeProfileVisible),e.marketProfileVisible!==void 0&&this.chart.setMarketProfileVisible(e.marketProfileVisible),e.marketProfileSplit!==void 0&&this.chart.setMarketProfileConfig({splitBySession:e.marketProfileSplit}),e.marketProfileLetters!==void 0&&this.chart.setMarketProfileConfig({letters:e.marketProfileLetters}),e.marketProfileBuckets!==void 0&&this.chart.setMarketProfileConfig({buckets:e.marketProfileBuckets}),e.marketProfileOpacity!==void 0&&this.chart.setMarketProfileConfig({opacity:e.marketProfileOpacity}),e.depthHeatmapVisible!==void 0&&this.chart.setDepthHeatmapVisible(e.depthHeatmapVisible),e.depthHeatmapOpacity!==void 0&&this.chart.setDepthHeatmapConfig({opacity:e.depthHeatmapOpacity}),e.sessionShadingVisible!==void 0&&this.chart.setSessionShadingVisible(e.sessionShadingVisible),e.pivotMarkersVisible!==void 0&&this.chart.setPivotMarkersVisible(e.pivotMarkersVisible),e.pivotStrength!==void 0&&this.chart.setPivotMarkersConfig({left:e.pivotStrength,right:e.pivotStrength}),e.pivotStructureLabels!==void 0&&this.chart.setPivotMarkersConfig({structureLabels:e.pivotStructureLabels}),e.periodLevelsVisible!==void 0&&this.chart.setPeriodLevelsVisible(e.periodLevelsVisible),e.periodLevelsPeriod!==void 0&&this.chart.setPeriodLevelsPeriod(e.periodLevelsPeriod),e.legendVisible!==void 0&&this.chart.setLegend({visible:e.legendVisible}),e.barCountdown!==void 0&&this.chart.setBarCountdownVisible(e.barCountdown),e.indicatorValueLabels!==void 0&&this.chart.setIndicatorValueLabelsVisible(e.indicatorValueLabels),e.alignAxisLabels!==void 0&&this.chart.setAxisLabelsAligned(e.alignAxisLabels),e.crosshairMode!==void 0&&this.chart.setCrosshairMode(e.crosshairMode),e.autoScale!==void 0&&this.chart.setAutoScale(e.autoScale),e.invertScale!==void 0&&this.chart.setInvertScale(e.invertScale),e.leftPriceScale!==void 0&&(this.chart.setLeftPriceScaleVisible(e.leftPriceScale),this.placeDrawingButton()),(e.scaleMode!==void 0||e.autoScale!==void 0)&&queueMicrotask(()=>this.refreshScaleSwitches()),e.timezone!==void 0&&queueMicrotask(()=>this.statusBar?.tick()),e.scaleMode===void 0?e.logScale!==void 0&&(this.settingsState={...this.settingsState,scaleMode:e.logScale?`logarithmic`:`regular`},this.showScaleMode()):(this.settingsState={...this.settingsState,logScale:e.scaleMode===`logarithmic`},this.showScaleMode()),e.numberLocale!==void 0&&(this.chart.setNumberLocale(e.numberLocale),this.watchlist?.setLocale(e.numberLocale||void 0)),e.timezone!==void 0&&this.chart.setTimeZone(u(e.timezone)),e.highLowLines!==void 0&&this.chart.setHighLowLines(e.highLowLines),e.extendedHours!==void 0&&this.chart.setExtendedHours(e.extendedHours),e.mainSeriesVisible!==void 0&&this.chart.setMainSeriesVisible(e.mainSeriesVisible),e.chartTypeOptions!==void 0&&this.chart.setChartTypeOptions({...ho(),...e.chartTypeOptions}),t&&!this.settingsEdit&&this.publishSettings()}resetSettings(){let e={...this.settingsState},t=this.settingsStyle(),n={...this.settingsDefaults};this.touchSettings(Object.keys(n),E),this.applySettings(n),this.chart.resetOverrides([...E],{layer:`user`});let r={...this.settingsState},i=this.settingsStyle();this.settings?.refresh(this.shownSettings()),!(this.settingsEdit||JSON.stringify([e,t])===JSON.stringify([r,i]))&&this.chart.recordUndo({undo:()=>this.restoreSettings(e,t),redo:()=>this.restoreSettings(r,i)})}changeStyle(e){let t=Object.keys(e);this.touchSettings([],t);let n=this.settingsStyle(t);this.chart.applyOverrides(e,{layer:`user`});let r=this.settingsStyle(t);this.settingsEdit||JSON.stringify(n)===JSON.stringify(r)||this.chart.recordUndo({subject:`style:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings({},n),redo:()=>this.restoreSettings({},r)})}changeSettings(e){let t=Object.keys(e);if(t.includes(`scaleMode`)||t.includes(`logScale`))for(let e of[`scaleMode`,`logScale`])t.includes(e)||t.push(e);let n=()=>Object.fromEntries(t.map(e=>[e,this.settingsState[e]]));this.touchSettings(t);let r=n(),i=t.includes(`scaleMode`),a=this.compareScaleHeld;i&&(this.compareScaleHeld=!1),this.applySettings(e);let o=n();this.settingsEdit||JSON.stringify(r)===JSON.stringify(o)&&a===this.compareScaleHeld||this.chart.recordUndo({subject:`settings:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings(r,null,i?a:void 0),redo:()=>this.restoreSettings(o,null,i?!1:void 0)})}settingsStyle(e=E){let t=this.chart.getOverrides?.({layer:`user`})??{},n=Object.fromEntries(e.map(e=>{let n=t[e];return[e,typeof n==`string`||typeof n==`boolean`||typeof n==`number`?n:null]}));return{theme:this.chart.getTheme()?.name??``,overrides:n}}restoreSettings(e,t=null,n){n!==void 0&&(this.compareScaleHeld=n&&this.compares.length>0),this.applySettings(e),t&&t.theme===(this.chart.getTheme()?.name??``)&&this.chart.applyOverrides(t.overrides,{layer:`user`}),this.settings?.refresh(this.shownSettings())}async connectStream(){if(!this.adapter)return;let e=++this.connectSeq;this.state={...this.state,connectionState:`connecting`,connectionMessage:this.t(`status.connecting`)},this.updateUI(),this.loading.begin(this.chart.getData().length>0);try{if(this.chart.disconnectStream(),await this.chart.connect({adapter:this.adapter,symbol:this.state.symbol,timeframe:this.state.timeframe,historyLimit:this.options.historyLimit??500,historyPageSize:this.options.historyPageSize}),e!==this.connectSeq||this.destroyed)return;this.chart.setWatermark(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:48,color:this.state.isDark?`rgba(255,255,255,0.03)`:`rgba(0,0,0,0.03)`}),this.applySymbolLayout(this.state.symbol),this.loading.hasFailed()?this.state={...this.state,connectionState:`error`}:(this.loading.end(),this.state={...this.state,connectionState:`connected`,connectionMessage:this.t(`status.live`)}),this.refetchCompares()}catch(t){if(e!==this.connectSeq||this.destroyed)return;this.loading.fail(this.t(`status.connectionFailed`)),this.state={...this.state,connectionState:`error`,connectionMessage:t instanceof Error?t.message:this.t(`status.connectionFailed`)}}this.updateUI()}scheduleLegend(){!this.indicatorLegend||this.legendFrame||!this.featureState.indicatorLegend||(this.legendFrame=requestAnimationFrame(()=>{this.legendFrame=0,this.renderLegend()}))}renderLegend(){if(!this.indicatorLegend||this.destroyed)return;let e=this.chart.getData().length-1,t=this.chart.isTimeAligned(),n=this.legendHoverIndex,r=n===null?e:Math.min(Math.max(n,0),e),i=new Map;for(let e of this.chart.getIndicatorPanes())(e.instanceIds??[e.instanceId]).forEach((t,n)=>i.set(t,{...e.rect,row:n}));let a=this.settingsState.numberLocale||`en-US`,o=Yl(r>=0?this.chart.getCompareValues?.(n===null||!t?void 0:r)??[]:[],a,t),s=this.chart.getActiveIndicators().map(e=>{let t=i.get(e.instanceId)??null,r=Bl(this.chart.getIndicatorOutput(e.instanceId)?.series,n),o=this.chart.getIndicatorStyle(e.instanceId),s=e.visible&&e.offChartType===!0,c=e.visible&&e.shown===!1&&!s,l=c||s?[]:Vl(e.descriptor,r,o?.colors??[],o?.plots);return{instanceId:e.instanceId,label:qi(e,this.t),visible:e.visible,offInterval:c,offChartType:s,values:l.map(n=>({text:this.indicatorValueText(n.value,t===null&&Ed(e),a),color:n.color})),pane:t?{x:t.x+Ju,y:t.y+Math.min(Xu+t.row*Zu,Math.max(Xu,t.height-Zu)),width:t.width-2*Ju}:null}}),c=[...o,...s],l=this.chart.getPlotRect(),u=this.chart.getMaximizedPane(),d=e=>c.find(t=>t.instanceId===e)?.label??``,f=this.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-Ju,y:e.rect.y+Qu,label:d(e.instanceId),collapsed:this.chart.isPaneCollapsed(e.instanceId),maximized:u===e.instanceId,canMoveUp:this.chart.canMovePane(e.instanceId,-1),canMoveDown:this.chart.canMovePane(e.instanceId,1)}));this.indicatorLegend.update(c,{left:l.x+Ju,top:this.chart.getLegendBottom()+Yu},f)}runPaneAction(e,t){t===`up`||t===`down`?this.chart.movePane(e,t===`up`?-1:1):t===`collapse`||t===`expand`?this.chart.setPaneCollapsed(e,t===`collapse`):this.chart.setMaximizedPane(t===`maximize`?e:null),this.scheduleLegend()}openLegendMenu(e,t){let n=this.legendMenu;if(!n)return;if(n.isOpen()){n.close();return}let r=[`price`,...this.chart.getIndicatorPanes().map(e=>e.instanceId)],i=1+this.chart.getIndicatorPanes().findIndex(t=>t.instanceIds.includes(e)),a=r[i-1],o=r[i+1],s=t=>t!==void 0&&this.chart.canMoveIndicatorToPane(e,t),c=[];s(a)&&c.push({id:`move:${a}`,label:this.t(a===`price`?`legend.movePrice`:`legend.moveUp`),icon:`arrowUp`}),s(o)&&c.push({id:`move:${o}`,label:this.t(`legend.moveDown`),icon:`arrowDown`}),s(`new`)&&c.push({id:`move:new`,label:this.t(`legend.moveNew`),icon:`plus`}),a!==`price`&&s(`price`)&&c.push({id:`move:price`,label:this.t(`legend.movePrice`),icon:`trendingUp`});let l=[];this.featureState.indicatorSettings&&this.featureState[`indicatorLegend.settings`]&&l.push({id:`settings`,label:this.t(`legend.settings`),icon:`settings`}),this.featureState[`indicatorLegend.remove`]&&l.push({id:`remove`,label:this.t(`legend.remove`),icon:`trash`,danger:!0}),c.length>0&&l.length>0&&c.push(`separator`),c.push(...l);let u=this.chart.getActiveIndicators().find(t=>t.instanceId===e)?.id??``,d=this.options.indicatorMenuItems?.({instanceId:e,indicatorId:u})??[],f=Cu(c,d);if(f.length===0)return;let p=t.getBoundingClientRect(),m=this.root.getBoundingClientRect();n.open(f,p.left-m.left,p.bottom-m.top+2,t=>{wu(t,d)||(t===`settings`?this.openIndicatorSettings(e):t===`remove`?this.handleRemoveIndicator(e):t.startsWith(`move:`)&&this.chart.moveIndicatorToPane(e,t.slice(5)),this.scheduleLegend())},t)}updateUI(){this.refreshDrawingsState(),this.scheduleLegend(),this.toolbar?.update(this.state),this.sidebar?.update(this.state),this.statusBar?.update({connectionState:this.state.connectionState,message:this.state.connectionMessage,symbol:this.state.symbol,timeframe:this.state.timeframe})}resolveIsDark(e){return e===void 0||e===`dark`?!0:e===`light`?!1:typeof e==`object`&&e.background?this.isColorDark(e.background):!0}resolveTheme(e){return e===void 0||e===`dark`?n.DARK_THEME:e===`light`?n.LIGHT_THEME:typeof e==`object`?e:n.DARK_THEME}isColorDark(e){if(e.startsWith(`#`)&&e.length>=7){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return t+n+r<384}return!0}};function md(e,t,i){let a=e=>{let t=(0,r.sourceParam)(e.descriptor);return t&&(0,n.parseIndicatorSource)(e.params[t])?.instanceId||null},o=new Set([e]);for(let e=!0;e;){e=!1;for(let n of t){let t=a(n);t&&o.has(t)&&!o.has(n.instanceId)&&(o.add(n.instanceId),e=!0)}}let s=[];for(let e of t){if(o.has(e.instanceId))continue;let t=qi(e,i);for(let r of e.descriptor.plots??[])s.push({value:(0,n.indicatorSource)(e.instanceId,r.key),label:`${t}: ${r.title}`})}return s}var hd=`tcw:recentCommands`,gd=10;function _d(){try{let e=JSON.parse(Sd()?.getItem(hd)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`).slice(0,gd):[]}catch{return[]}}function vd(e){try{Sd()?.setItem(hd,JSON.stringify(e.slice(0,gd)))}catch{}}var yd=`tcw:dockWidth`;function bd(){try{let e=Number(Sd()?.getItem(yd)??NaN);return Number.isFinite(e)&&e>0?e:null}catch{return null}}function xd(e){try{Sd()?.setItem(yd,String(e))}catch{}}function Sd(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}function Cd(e){let t=e.filter(e=>e!==null);if(t.length===0)return null;let n=Math.min(...t.map(e=>e.x)),r=Math.min(...t.map(e=>e.y)),i=Math.max(...t.map(e=>e.x+e.width)),a=Math.max(...t.map(e=>e.y+e.height));return{x:n,y:r,width:i-n,height:a-r}}function wd(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}function Td(e,t){let n=e.length;if(n===0||t<e[0].time)return!1;let r=e[n-1].time;return t<r+(n>1?r-e[n-2].time:0)||t===r}function Ed(e){return!r.SYMBOL_INDICATOR_IDS.has(e.id)&&e.scale!==`left`}var Dd={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},Od=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],kd={"1x1":{cols:1,rows:1},"1x2":{cols:2,rows:1},"2x1":{cols:1,rows:2},"2x2":{cols:2,rows:2},"1x3":{cols:3,rows:1},"3x1":{cols:1,rows:3},"2x3":{cols:3,rows:2},"3x2":{cols:2,rows:3}};function Ad(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(kd,e)}function jd(e){return JSON.parse(JSON.stringify(e))}function Md(e,t,n=16){let r=(20-2*(e-1))/e,i=(20-2*(t-1))/t,a=``;for(let n=0;n<t;n++)for(let t=0;t<e;t++)a+=`<rect x="${2+t*(r+2)}" y="${2+n*(i+2)}" width="${r}" height="${i}" rx="1"/>`;return`<svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" aria-hidden="true">${a}</svg>`}function Nd(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!Ad(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map($c);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...Dd};for(let e of Od)typeof r[e]==`boolean`&&(i[e]=r[e]);let a=typeof t.active==`number`&&Number.isInteger(t.active)?t.active:0;return{v:1,kind:`grid`,layout:t.layout,sync:i,active:a,cells:n}}var Pd=class{root;cellsEl;cells=[];layout;sync;active=0;hovered=null;relayDepth=0;uiTheme=null;styleOverrides={};featureSwitches={};parked=new Map;drawingFrame=0;drawingSource=null;layoutButtons=new Map;syncButtons=new Map;layoutsButton=null;tabsEl=null;stopNarrow=()=>{};session=null;layoutsUI=null;t;destroyed=!1;unregisterKeys=()=>{};onKeyDown=e=>{!(e.ctrlKey||e.metaKey)||e.altKey||e.shiftKey||e.key!==`s`&&e.key!==`S`||!this.layoutsUI||Z()||!Yc(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,n={}){this.options=n,this.layout=Ad(n.layout)?n.layout:`1x2`,this.sync={...Dd,...n.sync},this.t=t.n(t.o(n.widget?.locale,n.widget?.messages)),Qe(),this.root=document.createElement(`div`),this.root.className=`tcw-root tcw-grid`,this.root.dataset.tcwTheme=n.widget?.theme===`light`?`light`:`dark`,ba(this.root,G(n.widget?.ui),{variables:n.widget?.ui!==void 0}),n.bar!==!1&&this.root.appendChild(this.buildBar()),this.cellsEl=document.createElement(`div`),this.cellsEl.className=`tcw-grid-cells`,this.root.appendChild(this.cellsEl),e.appendChild(this.root),this.stopNarrow=il(this.root),this.applyShape();for(let e=0;e<this.shapeCount();e++)this.cells.push(this.createCell(e));this.markActive();let r=this.cells[0]?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;r&&(this.root.dataset.tcwTheme=r),n.layouts!==!1&&this.setupLayouts(n.layouts===!0||n.layouts===void 0?{}:n.layouts),this.unregisterKeys=Jc(this.root),document.addEventListener(`keydown`,this.onKeyDown)}get relaying(){return this.relayDepth>0}quietly(e){this.relayDepth++;try{return e()}finally{this.relayDepth--}}getWidget(e){return this.cells[e]?.widget??null}getWidgets(){return this.cells.map(e=>e.widget)}getActiveIndex(){return this.active}getActiveWidget(){return this.cells[this.active].widget}setActive(e){e<0||e>=this.cells.length||e===this.active||(this.active=e,this.markActive(),this.options.onActiveChange?.(e,this.cells[e].widget),this.session?.changed())}getLayout(){return this.layout}setLayout(e){if(e===this.layout||!Ad(e))return;this.layout=e;let t=this.shapeCount();for(;this.cells.length>t;){let e=this.cells.length-1,t=this.cells.pop();this.parked.set(e,t.widget.captureLayout()),this.destroyCell(t)}this.applyShape();for(let e=this.cells.length;e<t;e++){let t=this.createCell(e);this.cells.push(t),this.unpark(e,t)}this.active>=t&&(this.active=0,this.options.onActiveChange?.(0,this.cells[0].widget)),this.markActive(),this.renderBar(),this.session?.changed()}getSync(){return{...this.sync}}setUI(e){let t=G(e);ba(this.root,t);for(let e of this.cells)e.widget.setUI(t);this.uiTheme=t}getUI(){return G(this.uiTheme??this.options.widget?.ui)}setSync(e){let t=this.sync;if(this.sync={...this.sync,...e},t.crosshair&&!this.sync.crosshair)for(let e of this.cells)e.widget.getChart().setCrosshairTime(null);let n=this.cells[this.active];if(n&&!this.relaying){let e=n.widget.getSymbol(),r=n.widget.getTimeframe();!t.symbol&&this.sync.symbol&&this.relay(n,t=>void t.setSymbol(e)),!t.interval&&this.sync.interval&&this.relay(n,e=>void e.setTimeframe(r)),!t.drawings&&this.sync.drawings&&this.mergeDrawings()}this.renderBar(),this.session?.changed()}applyOverrides(e){for(let t of this.cells)t.widget.getChart().applyOverrides(e);let t={...this.styleOverrides};for(let[n,r]of Object.entries(e))r==null?delete t[n]:t[n]=r;this.styleOverrides=t}setFeatures(e){let t=Be(e);for(let e of this.cells)e.widget.setFeatures(t);this.featureSwitches={...this.featureSwitches,...t}}setTheme(e){for(let t of this.cells)t.widget.setTheme(e);this.followTheme()}getLayoutSession(){return this.session}captureLayout(){let e=[...this.parked.entries()].sort(([e],[t])=>e-t).map(([,e])=>e);return{v:1,kind:`grid`,layout:this.layout,sync:{...this.sync},active:this.active,cells:[...this.cells.map(e=>e.widget.captureLayout()),...e]}}async restoreLayout(e){this.relayDepth++;let t;try{this.parked.clear(),this.setLayout(e.layout),this.sync={...e.sync},this.renderBar();let n=this.cells.length;e.cells.slice(n).forEach((e,t)=>this.parked.set(n+t,e)),t=await Promise.allSettled(this.cells.map((t,n)=>e.cells[n]?t.widget.restoreLayout(e.cells[n]):Promise.resolve()))}finally{this.relayDepth--}if(this.destroyed)return;this.setActive(Math.min(Math.max(0,e.active),this.cells.length-1)),this.renderTabs();let n=t.find(e=>e.status===`rejected`);if(n)throw n.reason}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=Nd(el(e));return t?(await this.restoreLayout(t),!0):!1}destroy(){if(!this.destroyed){this.destroyed=!0,document.removeEventListener(`keydown`,this.onKeyDown),this.unregisterKeys(),this.stopNarrow(),this.drawingFrame&&cancelAnimationFrame(this.drawingFrame),this.session?.destroy(),this.layoutsUI?.destroy();for(let e of this.cells)this.destroyCell(e);this.cells=[],this.root.remove(),$e()}}shapeCount(){let{cols:e,rows:t}=kd[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=kd[this.layout];this.cellsEl.style.gridTemplateColumns=`repeat(${e}, minmax(0, 1fr))`,this.cellsEl.style.gridTemplateRows=`repeat(${t}, minmax(0, 1fr))`}createCell(e){let n=document.createElement(`div`);n.className=`tcw-grid-cell`,n.setAttribute(`role`,`region`),n.setAttribute(`aria-label`,t.r(this.t(`grid.chart`),{n:e+1})),this.cellsEl.appendChild(n);let r=this.options.widget??{},i=this.options.cells?.[e]??{},a=this.cells[this.active]?.widget,o={},s=new pd(n,{...r,...i,...i.adapter?{feed:void 0}:{},...i.feed?{adapter:void 0}:{},...a&&this.sync.symbol?{symbol:a.getSymbol()}:{},...a&&this.sync.interval?{timeframe:a.getTimeframe()}:{},...this.options.adapter&&!i.adapter&&!i.feed&&!r.feed?{adapter:this.options.adapter(e)}:{},...this.uiTheme?{ui:this.uiTheme}:{},layouts:!1,...i.persistSettings===void 0&&r.persistSettings?{persistSettings:{key:`${To(r.persistSettings)}:${e}`}}:{},features:{dock:!1,...r.features,...i.features},onSymbolChange:e=>{i.onSymbolChange?.(e),r.onSymbolChange?.(e),this.sync.symbol&&this.relay(o,t=>void t.setSymbol(e)),this.renderTabs(),this.session?.changed()},onTimeframeChange:e=>{i.onTimeframeChange?.(e),r.onTimeframeChange?.(e),this.sync.interval&&this.relay(o,t=>void t.setTimeframe(e)),this.renderTabs(),this.session?.changed()}});return o.el=n,o.widget=s,Object.keys(this.styleOverrides).length>0&&s.getChart().applyOverrides(this.styleOverrides),Object.keys(this.featureSwitches).length>0&&s.setFeatures(this.featureSwitches),this.wireCell(o),n.addEventListener(`pointerdown`,()=>this.setActive(this.cells.indexOf(o)),!0),n.addEventListener(`pointerenter`,()=>{this.hovered=o}),n.addEventListener(`pointerleave`,()=>{this.hovered===o&&(this.hovered=null)}),this.options.onChartAdd?.(s,e),o}wireCell(e){let t=e.widget.getChart(),n=()=>this.cells.filter(t=>t!==e);t.on(`crosshairMove`,e=>{let t=e.payload.bar?.time;if(!(!this.sync.crosshair||t===void 0))for(let e of n())e.widget.getChart().setCrosshairTime(t)}),t.on(`crosshairLeave`,()=>{if(this.sync.crosshair)for(let e of n())e.widget.getChart().setCrosshairTime(null)}),t.on(`visibleRangeChange`,n=>{if(!this.sync.time||this.relaying||(this.hovered??this.cells[this.active])!==e)return;let{from:r,to:i}=n.payload,a=t.getData(),o=a[r]?.time,s=a[i]?.time;o===void 0||s===void 0||this.relay(e,e=>e.getChart().setVisibleRange(o,s))});for(let n of[`drawingCreate`,`drawingUpdate`,`drawingRemove`])t.on(n,()=>{this.sync.drawings&&!this.relaying&&this.copyDrawingsSoon(e)});t.on(`replayStep`,t=>{if(!this.sync.replay||this.relaying||t.payload.cause===`series`)return;let{until:n}=t.payload;this.relay(e,e=>{let t=e.getChart();if(t.isReplayActive()){t.replaySeekToTime(n);return}let r=Fd(t.getData(),n);r>=0&&t.replayStart({startIndex:r,paused:!0})})}),t.on(`replayState`,t=>{!this.sync.replay||this.relaying||t.payload.state!==`stopped`||this.relay(e,e=>{e.getChart().isReplayActive()&&e.getChart().replayStop()})}),t.on(`stateChange`,()=>this.session?.changed()),e.widget.onSettingsChange(()=>this.session?.changed()),t.on(`themeChange`,()=>{this.relaying||this.followTheme(e)})}destroyCell(e){this.hovered===e&&(this.hovered=null),this.drawingSource===e&&(this.drawingSource=null),this.quietly(()=>e.widget.destroy()),e.el.remove()}relay(e,t){this.relaying||this.quietly(()=>{for(let n of this.cells)n!==e&&t(n.widget)})}unpark(e,t){let n=this.parked.get(e);if(!n)return;this.parked.delete(e);let r=this.cells[this.active]?.widget,i={...n,...r&&this.sync.symbol?{symbol:r.getSymbol()}:{},...r&&this.sync.interval?{timeframe:r.getTimeframe()}:{}};this.relayDepth++,t.widget.restoreLayout(i).catch(()=>t.widget.toast(this.t(`layouts.openFailed`),`error`)).finally(()=>{this.relayDepth--})}copyDrawingsSoon(e){this.drawingSource=e,!this.drawingFrame&&(this.drawingFrame=requestAnimationFrame(()=>{this.drawingFrame=0;let e=this.drawingSource;this.drawingSource=null,e&&!this.destroyed&&!this.relaying&&this.copyDrawings(e)}))}copyDrawings(e){let t=e.widget.getSymbol(),n=e.widget.getChart().getDrawings();this.quietly(()=>{for(let r of this.cells)r!==e&&r.widget.getSymbol()===t&&r.widget.getChart().setDrawings(jd(n))})}mergeDrawings(){let e=new Map;for(let t of this.cells)e.set(t.widget.getSymbol(),[...e.get(t.widget.getSymbol())??[],t]);this.quietly(()=>{for(let t of e.values()){if(t.length<2)continue;let e=new Map;for(let n of t)for(let t of n.widget.getChart().getDrawings())e.has(t.id)||e.set(t.id,t);let n=[...e.values()];for(let e of t)e.widget.getChart().setDrawings(jd(n))}})}followTheme(e=this.cells[this.active]){let t=e?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;t&&(this.root.dataset.tcwTheme=t,this.quietly(()=>{for(let n of this.cells)n!==e&&n.el.querySelector(`.tcw-root`)?.dataset.tcwTheme!==t&&n.widget.setTheme(t)}))}markActive(){this.cells.forEach((e,t)=>{e.el.classList.toggle(`tcw-grid-cell-active`,t===this.active&&this.cells.length>1),e.el.classList.toggle(`tcw-grid-cell-current`,t===this.active)}),this.renderTabs()}renderTabs(){let e=this.tabsEl;if(!e)return;let t=this.cells.map(e=>`${e.widget.getSymbol()} · ${e.widget.getTimeframe()}`);for(;e.children.length>t.length;)e.lastElementChild?.remove();for(;e.children.length<t.length;){let t=e.children.length,n=document.createElement(`button`);n.type=`button`,n.className=`tcw-btn tcw-grid-tab`,n.addEventListener(`click`,()=>this.setActive(t)),e.appendChild(n)}t.forEach((t,n)=>{let r=e.children[n];r.textContent!==t&&(r.textContent=t);let i=n===this.active;r.classList.toggle(`tcw-active`,i),r.setAttribute(`aria-pressed`,String(i))})}buildBar(){let e=document.createElement(`div`);e.className=`tcw-grid-bar`,e.setAttribute(`role`,`toolbar`),e.setAttribute(`aria-label`,this.t(`grid.bar`)),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-grid-group tcw-grid-tabs`,this.root.classList.add(`tcw-grid-has-tabs`),this.tabsEl.setAttribute(`role`,`group`),this.tabsEl.setAttribute(`aria-label`,this.t(`grid.charts`)),e.appendChild(this.tabsEl);let n=document.createElement(`div`);n.className=`tcw-grid-group`,n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,this.t(`grid.layout`));let r=this.options.layoutChoices?.filter(Ad)??Object.keys(kd);for(let e of r){let{cols:r,rows:i}=kd[e],a=r*i===1?this.t(`grid.single`):t.r(this.t(`grid.layoutOption`),{count:r*i,cols:r,rows:i}),o=document.createElement(`button`);o.type=`button`,o.className=`tcw-btn-icon`,o.title=a,o.setAttribute(`aria-label`,a),o.innerHTML=Md(r,i),o.addEventListener(`click`,()=>this.setLayout(e)),this.layoutButtons.set(e,o),n.appendChild(o)}let i=document.createElement(`div`);i.className=`tcw-grid-group`,i.setAttribute(`role`,`group`),i.setAttribute(`aria-label`,this.t(`grid.sync`));let a=document.createElement(`span`);a.className=`tcw-grid-label`,a.innerHTML=`${O(`link`,13)}<span>${k(this.t(`grid.sync`))}</span>`,i.appendChild(a);for(let e of Od){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-btn tcw-grid-sync`,t.textContent=this.t(`grid.sync.${e}`),t.title=this.t(`grid.sync.${e}.hint`),t.addEventListener(`click`,()=>this.setSync({[e]:!this.sync[e]})),this.syncButtons.set(e,t),i.appendChild(t)}let o=document.createElement(`span`);return o.className=`tcw-toolbar-spacer`,e.append(n,this.sep(),i,o),this.options.layouts!==!1&&(this.layoutsButton=document.createElement(`button`),this.layoutsButton.type=`button`,this.layoutsButton.className=`tcw-dropdown-trigger tcw-layouts-btn`,this.layoutsButton.setAttribute(`aria-haspopup`,`menu`),this.layoutsButton.addEventListener(`click`,()=>{this.layoutsButton&&this.layoutsUI?.openMenu(this.layoutsButton)}),e.appendChild(this.layoutsButton)),this.renderBar(),e}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}renderBar(){for(let[e,t]of this.layoutButtons){let n=e===this.layout;t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n))}for(let[e,t]of this.syncButtons)t.classList.toggle(`tcw-active`,this.sync[e]),t.setAttribute(`aria-pressed`,String(this.sync[e]));this.renderLayoutsButton()}renderLayoutsButton(){let e=this.layoutsButton;if(!e)return;let t=this.session?.current()?.name??this.t(`layouts.unnamed`),n=this.session?.isDirty()??!1,r=`${this.t(`toolbar.layouts`)}: ${t}${n?` (${this.t(`layouts.unsavedChanges`)})`:``}`;e.innerHTML=`${O(`save`,14)}<span class="tcw-layouts-label">${k(t)}</span>`+(n?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+O(`chevronDown`,12),e.title=r,e.setAttribute(`aria-label`,r)}setupLayouts(t){let n=new e.t(t.storage??e.i(`tcw:grid-layouts:`),{capture:()=>{let e=this.cells[this.active].widget;return{content:this.getLayoutContent(),symbol:e.getSymbol(),timeframe:e.getTimeframe()}},apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a grid layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,kind:`grid`,onChange:()=>this.renderLayoutsButton(),onError:()=>this.toast(this.t(`layouts.saveFailed`),`error`)});this.session=n,this.layoutsUI=new Vc(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=Q(e,null);return`${t} ${n}`}}),this.renderLayoutsButton(),t.openLast&&n.list().then(([e])=>e&&!this.destroyed?this.layoutsUI?.open(e.id):void 0,()=>void 0)}toast(e,t=`info`){this.cells[this.active]?.widget.toast(e,t)}};function Fd(e,t){let n=-1;for(let r=0;r<e.length&&e[r].time<t;r++)n=r;return n}Object.defineProperty(exports,`CHART_TYPE_ICONS`,{enumerable:!0,get:function(){return n.CHART_TYPE_ICONS}}),exports.ChartWidget=pd,exports.ChartWidgetGrid=Pd,exports.DEFAULT_GRID_SYNC=Dd,Object.defineProperty(exports,`DRAWING_TOOL_ICONS`,{enumerable:!0,get:function(){return n.DRAWING_TOOL_ICONS}}),exports.EN_MESSAGES=t.c,exports.GRID_SHAPES=kd,exports.LayoutSession=e.t,exports.MAX_LAYOUT_NAME=e.n,Object.defineProperty(exports,`UI_ICONS`,{enumerable:!0,get:function(){return n.UI_ICONS}}),exports.VI_MESSAGES=t.s,exports.WIDGET_FEATURES=Pe,exports.WIDGET_UI_PRESETS=da,exports.applyWidgetUI=ba,exports.cleanLayoutName=e.r,exports.createChartTypeIcon=nt,exports.createIcon=O,exports.createToolIcon=tt,exports.findWidgetLocale=t.i,Object.defineProperty(exports,`iconSvg`,{enumerable:!0,get:function(){return n.iconSvg}}),exports.localStorageLayouts=e.i,exports.memoryLayouts=e.a,exports.readGridLayout=Nd,exports.readWatchlists=pi,exports.readWidgetLayout=$c,exports.registerWidgetLocale=t.a,exports.resolveWidgetUI=G,exports.widgetUIVariables=ya;
|
|
7734
|
+
`)&&this.problemsEl.replaceChildren(...n.map(e=>{let t=document.createElement(`p`);return t.textContent=e,t}));for(let t of[`stopLoss`,`takeProfit`]){let n=this.body.querySelector(`.tcw-ticket-away[data-for="${t}"]`),r=e[t],i=r===null?null:Tc(e,this.lastPrice,r,this.rules.multiplier);n&&(n.textContent=i?`${this.signedNumber(i.pct,2)}% · ${this.amount(i.amount)}`:``)}this.renderSummary(e),this.submit.disabled=t.length>0,this.submit.textContent=this.t(e.side===`buy`?`ticket.placeBuy`:`ticket.placeSell`)}renderSummary(e){let t=Ec(e,this.lastPrice,this.rules),n=t.risk===null?null:this.amount(t.risk),r=t.reward===null?null:this.amount(t.reward),i=[[`value`,`ticket.value`,t.value===null?null:this.money(t.value),null],[`risk`,`ticket.risk`,n,n===null?null:ac(n)],[`reward`,`ticket.reward`,r,r===null?null:ac(r)],[`ratio`,`ticket.rewardRisk`,t.ratio===null?null:this.number(t.ratio,2),null]];this.summaryEl.replaceChildren(...i.filter(([,,e])=>e!==null).map(([e,t,n,r])=>{let i=document.createElement(`div`);i.className=`tcw-ticket-summary-row`,i.dataset.row=e;let a=document.createElement(`span`);a.textContent=this.t(t);let o=document.createElement(`span`);return o.className=`tcw-ticket-figure${r?` tcw-ticket-${r}`:``}`,o.dir=`ltr`,o.textContent=n,i.append(a,o),i}))}number(e,t){return this.callbacks.formatNumber?this.callbacks.formatNumber(e,t):e.toFixed(t)}signedNumber(e,t){return ic(this.number(Math.abs(e),t),e,this.number(0,t))}amount(e){return ic(this.money(Math.abs(e)),e,this.money(0))}money(e){return(this.callbacks.formatAmount??this.callbacks.formatPrice)(e)}problemText(e){let n=this.t(`ticket.problem.${e}`),{limits:r,lot:i}=this.rules;return e===`priceLimits`&&r?t.r(n,{floor:this.callbacks.formatPrice(r.floor),ceiling:this.callbacks.formatPrice(r.ceiling)}):e===`lot`?t.r(n,{lot:i??1}):n}};function Nc(e,t){return t.dataset.ticketField=e,t}function Pc(e){let t=Math.abs(e);return t>0?10**Math.floor(Math.log10(t/100)):1}function Fc(e,t){let n=Math.abs(t),r=n>=10||n===0?2:n>=1?4:Math.min(10,Math.ceil(-Math.log10(n))+3);return Number(e.toFixed(r))}var Ic=0,Lc=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++Ic;constructor(e,n=t.t){this.t=n,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let r=!1;this.backdrop.addEventListener(`pointerdown`,e=>{r=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&r&&this.close(),r=!1});let i=document.createElement(`form`);i.className=`tcw-modal tcw-modal-narrow tcw-name-prompt`,i.noValidate=!0,i.setAttribute(`role`,`dialog`),i.setAttribute(`aria-modal`,`true`),i.setAttribute(`aria-labelledby`,`tcw-name-title-${this.uid}`),i.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.stopPropagation(),this.close();return}M(e,i)}),i.addEventListener(`submit`,e=>{e.preventDefault(),this.done()});let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-name-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.close()),a.append(this.titleEl,o);let s=document.createElement(`div`);s.className=`tcw-modal-body`;let c=document.createElement(`label`);c.className=`tcw-name-field`;let l=document.createElement(`span`);l.textContent=this.t(`layouts.name`),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-indi-input`,this.input.maxLength=80,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.placeholder=this.t(`layouts.namePlaceholder`),this.input.addEventListener(`input`,()=>this.check()),c.append(l,this.input),s.appendChild(c);let u=document.createElement(`div`);u.className=`tcw-modal-footer`;let d=document.createElement(`button`);d.type=`button`,d.className=`tcw-reset-link`,d.textContent=this.t(`common.cancel`),d.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`submit`,this.submit.className=`tcw-done-btn`,u.append(d,this.submit),i.append(a,s,u),this.backdrop.appendChild(i),e.appendChild(this.backdrop)}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.request=e,this.busy=!1,this.titleEl.textContent=e.title,this.submit.textContent=e.submitLabel,this.input.value=e.value??``,this.input.placeholder=e.placeholder??this.t(`layouts.namePlaceholder`),this.check(),this.backdrop.parentElement?.appendChild(this.backdrop),this.backdrop.hidden=!1,this.input.focus(),this.input.select()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.request=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}check(){this.submit.disabled=this.busy||e.r(this.input.value)===null}async done(){let t=this.request,n=e.r(this.input.value);if(!(!t||n===null||this.busy)){this.busy=!0,this.check();try{await t.onSubmit(n),this.request===t&&this.close()}catch{}finally{this.busy=!1,this.check()}}}},Rc=0,zc=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++Rc;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(),i=!1});let a=document.createElement(`div`);a.className=`tcw-modal tcw-layouts-dialog`,a.setAttribute(`role`,`dialog`),a.setAttribute(`aria-modal`,`true`),a.setAttribute(`aria-labelledby`,`tcw-layouts-title-${this.uid}`),a.addEventListener(`keydown`,e=>{if(e.key!==`Escape`){M(e,a);return}e.stopPropagation(),this.confirming?this.setConfirming(null):this.close()});let o=document.createElement(`div`);o.className=`tcw-modal-header`;let s=document.createElement(`h3`);s.id=`tcw-layouts-title-${this.uid}`,s.textContent=this.t(`layouts.dialogTitle`);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-modal-close`,c.setAttribute(`aria-label`,this.t(`common.close`)),c.innerHTML=O(`x`,16),c.addEventListener(`click`,()=>this.close()),o.append(s,c);let l=document.createElement(`label`);l.className=`tcw-ss-search tcw-layouts-search-row`,l.innerHTML=O(`search`,16),this.search=document.createElement(`input`),this.search.type=`search`,this.search.className=`tcw-layouts-search`,this.search.placeholder=this.t(`layouts.search`),this.search.setAttribute(`aria-label`,this.t(`layouts.search`)),this.search.autocomplete=`off`,this.search.addEventListener(`input`,()=>this.render()),l.appendChild(this.search),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-layouts-list`,this.listEl.setAttribute(`role`,`list`);let u=document.createElement(`div`);u.className=`tcw-layouts-body`,u.appendChild(this.listEl),a.append(o,l,u),this.backdrop.appendChild(a),e.appendChild(this.backdrop)}async open(){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.search.value=``,this.confirming=null,this.backdrop.hidden=!1,this.search.focus(),await this.refresh()}async refresh(){let e=++this.loadSeq,t;try{t=await this.callbacks.list()}catch{t=[]}e===this.loadSeq&&(this.layouts=t,this.render())}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.confirming=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}shown(){let e=this.search.value.trim().toLowerCase();return e?this.layouts.filter(t=>t.name.toLowerCase().includes(e)||(t.symbol??``).toLowerCase().includes(e)):this.layouts}render(){let e=this.shown();if(e.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(this.layouts.length===0?`layouts.empty`:`layouts.noMatch`),this.listEl.replaceChildren(e);return}let t=this.callbacks.currentId();this.listEl.replaceChildren(...e.map(e=>this.row(e,e.id===t)))}row(e,n){let r=document.createElement(`div`);r.className=`tcw-layouts-row`,r.setAttribute(`role`,`listitem`),r.dataset.id=e.id;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-layouts-open`,n&&i.setAttribute(`aria-current`,`true`);let a=document.createElement(`span`);a.className=`tcw-layouts-name`,a.textContent=e.name;let o=document.createElement(`span`);if(o.className=`tcw-layouts-meta`,o.textContent=[[e.symbol,e.timeframe].filter(Boolean).join(` · `),t.r(this.t(`layouts.updated`),{time:this.callbacks.formatTime(e.updatedAt)})].filter(Boolean).join(` — `),i.append(a,o),n){let e=document.createElement(`span`);e.className=`tcw-layouts-check`,e.innerHTML=O(`check`,14);let t=document.createElement(`span`);t.className=`tcw-visually-hidden`,t.textContent=this.t(`layouts.current`),i.prepend(e),i.appendChild(t)}i.addEventListener(`click`,()=>{this.callbacks.onOpen(e.id),this.close()});let s=document.createElement(`div`);if(s.className=`tcw-account-actions`,this.confirming===e.id){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-layouts-confirm`,n.textContent=this.t(`layouts.deleteConfirm`),n.setAttribute(`aria-label`,t.r(this.t(`layouts.deleteNamed`),{name:e.name})),n.addEventListener(`click`,()=>void this.remove(e.id));let r=this.iconButton(`x`,this.t(`common.cancel`),()=>this.setConfirming(null));s.append(n,r)}else s.append(this.iconButton(`penLine`,t.r(this.t(`layouts.renameNamed`),{name:e.name}),()=>this.callbacks.onRename(e)),this.iconButton(`trash`,t.r(this.t(`layouts.deleteNamed`),{name:e.name}),()=>this.setConfirming(e.id),!0));return r.append(i,s),r}iconButton(e,t,n,r=!1){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-tree-btn${r?` tcw-tree-del`:``}`,i.setAttribute(`aria-label`,t),i.title=t,i.innerHTML=O(e,14),i.addEventListener(`click`,n),i}setConfirming(e){let t=this.confirming;this.confirming=e,this.render();let n=e??t;n&&[...this.listEl.querySelectorAll(`.tcw-layouts-row`)].find(e=>e.dataset.id===n)?.querySelector(e?`.tcw-layouts-confirm`:`.tcw-tree-del`)?.focus()}async remove(e){try{await this.callbacks.onDelete(e)}finally{this.confirming=null,await this.refresh(),this.isOpen()&&this.search.focus()}}},Bc=5,Vc=class{menu;prompt;dialog;destroyed=!1;constructor(e,t){this.session=e,this.host=t;let{root:n,t:r}=t;this.menu=new A(n,r(`toolbar.layouts`)),this.prompt=new Lc(n,r),this.dialog=new zc(n,{list:()=>e.list(),currentId:()=>e.current()?.id??null,onOpen:e=>void this.open(e),onRename:e=>this.promptRename(e),onDelete:async t=>{try{await e.remove(t)}catch{this.host.toast(r(`layouts.deleteFailed`),`error`)}},formatTime:t.formatTime},r)}async save(){if(this.prompt.isOpen())return;if(!this.session.current()){this.promptSaveAs();return}let{t:e,toast:n}=this.host;try{let r=await this.session.save();r&&n(t.r(e(`layouts.saved`),{name:r.name}))}catch{n(e(`layouts.saveFailed`),`error`)}}async open(e){try{if(await this.session.open(e))return!0}catch{}return this.destroyed||this.host.toast(this.host.t(`layouts.openFailed`),`error`),!1}promptSaveAs(){let{t:e,toast:n}=this.host,r=this.session.current();this.prompt.open({title:e(`layouts.saveAsTitle`),value:r?t.r(e(`layouts.copyName`),{name:r.name}):``,submitLabel:e(`common.save`),onSubmit:async r=>{try{let i=await this.session.saveAs(r);n(t.r(e(`layouts.saved`),{name:i.name}))}catch(t){throw n(e(`layouts.saveFailed`),`error`),t}}})}promptRename(e=this.session.current()){if(!e)return;let{t,toast:n}=this.host;this.prompt.open({title:t(`layouts.renameTitle`),value:e.name,submitLabel:t(`layouts.renameSubmit`),onSubmit:async r=>{try{await this.session.rename(e.id,r)}catch(e){throw n(t(`layouts.saveFailed`),`error`),e}this.dialog.isOpen()&&this.dialog.refresh()}})}openDialog(){return this.dialog.open()}async openMenu(e){if(this.menu.isOpen()){this.menu.close();return}let{session:t}=this,{t:n}=this.host,r=[];try{r=(await t.list()).slice(0,Bc)}catch{}if(this.destroyed)return;let i=t.current(),a=[{id:`save`,label:n(`layouts.save`),icon:`save`,shortcut:this.host.saveKeys?.()},{id:`saveAs`,label:n(`layouts.saveAs`),icon:`plus`}];i&&a.push({id:`rename`,label:n(`layouts.rename`),icon:`penLine`}),a.push({id:`autoSave`,label:n(`layouts.autoSave`),checked:t.isAutoSave()}),r.length>0&&a.push(`separator`,...r.map(e=>({id:`open:${e.id}`,label:e.name,checked:e.id===i?.id}))),a.push(`separator`,{id:`manage`,label:n(`layouts.open`),icon:`folder`}),this.menu.openUnder(a,e,e=>{e===`save`?this.save():e===`saveAs`?this.promptSaveAs():e===`rename`?this.promptRename():e===`autoSave`?t.setAutoSave(!t.isAutoSave()):e===`manage`?this.openDialog():e.startsWith(`open:`)&&this.open(e.slice(5))})}destroy(){this.destroyed=!0,this.menu.destroy(),this.prompt.destroy(),this.dialog.destroy()}},Hc=0,Uc=class{el;input;hint;returnFocus=null;constructor(e,t,n){this.labels=t,this.onApply=n,this.el=document.createElement(`div`),this.el.className=`tcw-interval-input`,this.el.hidden=!0,this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,t.title),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-interval-field`,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.maxLength=6,this.input.setAttribute(`aria-label`,t.title),this.hint=document.createElement(`div`),this.hint.className=`tcw-interval-hint`,this.hint.setAttribute(`role`,`status`),this.hint.id=`tcw-interval-hint-${++Hc}`,this.input.setAttribute(`aria-describedby`,this.hint.id),this.el.append(this.input,this.hint),e.appendChild(this.el),this.input.addEventListener(`input`,()=>this.check()),this.input.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),this.apply()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.close())}),this.input.addEventListener(`blur`,()=>this.close(!1))}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.el.hidden=!1,this.input.value=e,this.check(),this.input.focus(),this.input.setSelectionRange(e.length,e.length)}close(e=!0){if(this.el.hidden)return;this.el.hidden=!0;let t=this.returnFocus;this.returnFocus=null,e&&t?.isConnected&&t.focus({preventScroll:!0})}isOpen(){return!this.el.hidden}destroy(){this.el.remove()}check(){let e=jt(this.input.value)!==null;!e&&this.input.value.trim()!==``?this.input.setAttribute(`aria-invalid`,`true`):this.input.removeAttribute(`aria-invalid`),this.hint.textContent=e||this.input.value.trim()===``?this.labels.hint:this.labels.invalid}apply(){let e=jt(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},Wc=class{constructor(e=`tcw:indicator-templates`){this.key=e}list(){let e;try{e=JSON.parse(localStorage.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let{name:e,indicators:i}=n;if(typeof e!=`string`||!e.trim()||!Array.isArray(i))continue;let a=r.ChartStateManager.deserialize(JSON.stringify({version:2,indicators:i})).indicators;a.length>0&&t.push({name:e.slice(0,60),indicators:a})}return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t){let n=e.replace(/\s+/g,` `).trim().slice(0,60);if(!n)throw Error(`A template needs a name`);let r=[...this.list().filter(e=>e.name!==n),{name:n,indicators:[...t]}];localStorage.setItem(this.key,JSON.stringify(r))}remove(e){try{localStorage.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}},Y=[],Gc=new Map,Kc=null,qc=e=>{let t=e.target instanceof Node?e.target:null;t!==null&&Y.some(e=>e.contains(t)||Gc.get(e)?.some(e=>e.contains(t)))||(Kc=null)};function Jc(e,t=[]){let n=()=>{Kc=e},r=[e,...t];for(let e of r)e.addEventListener(`pointerdown`,n,!0);return Y.length===0&&document.addEventListener(`pointerdown`,qc,!0),Y.push(e),Gc.set(e,t),()=>{for(let e of r)e.removeEventListener(`pointerdown`,n,!0);let t=Y.indexOf(e);t>=0&&Y.splice(t,1),Gc.delete(e),Y.length===0&&document.removeEventListener(`pointerdown`,qc,!0),Kc===e&&(Kc=null)}}function X(e,t=!1){let n=Kc?.isConnected?Kc:null;if(!n){let e=document.activeElement;n=e?Y.find(t=>t.contains(e))??null:null}return!n&&!t&&(n=Y.find(e=>e.isConnected)??null),n!==null&&e.contains(n)}function Z(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable)}var Yc=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],Xc=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Zc(e){let{theme:t,timestamp:n,...r}=e;return r}function Qc(e){return!Xc(e)||e.v!==1||typeof e.symbol!=`string`||!e.symbol||typeof e.timeframe!=`string`||!((0,n.isTimeFrame)(e.timeframe)||(0,n.tickBarCount)(e.timeframe)!==null)?null:{v:1,symbol:e.symbol,timeframe:e.timeframe,scaleMode:Yc.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:Xc(e.chart)?Zc(e.chart):null,...Xc(e.settings)?{settings:G(e.settings,co)}:{}}}function $c(e){try{return JSON.parse(e)}catch{return null}}function el(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var tl=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=el()){this.storageKey=e,this.storage=t,this.load()}list(){return[...this.favorites]}has(e){return this.favorites.includes(e)}add(e){!e||this.favorites.includes(e)||(this.favorites=[...this.favorites,e],this.persist())}remove(e){this.favorites.includes(e)&&(this.favorites=this.favorites.filter(t=>t!==e),this.persist())}toggle(e){return this.has(e)?(this.remove(e),!1):(this.add(e),!0)}seedDefaults(e){this.favorites.length>0||(this.favorites=[...new Set(e.filter(Boolean))],this.persist())}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.favorites=[...new Set(t.filter(e=>typeof e==`string`))])}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.favorites))}catch{}}};function nl(e){let t=typeof window<`u`?window.visualViewport:null;if(!t)return()=>{};let n=-1,r=()=>{let r=(t.scale??1)>1.01?0:Math.max(0,Math.round(window.innerHeight-t.height-t.offsetTop));if(r!==n){n=r;for(let t of e)t.style.setProperty(`--tcw-keyboard-inset`,`${r}px`)}};return r(),t.addEventListener(`resize`,r),t.addEventListener(`scroll`,r),()=>{t.removeEventListener(`resize`,r),t.removeEventListener(`scroll`,r)}}function rl(e,t){let n=null,r=()=>{let r=e.clientWidth;if(r===0&&n!==null)return;let i=r<641;i!==n&&(n=i,e.toggleAttribute(`data-tcw-narrow`,i),t?.(i))};if(r(),typeof ResizeObserver>`u`)return()=>{};let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()}var il=/^(\d{4})-(\d{2})-(\d{2})$/,al=/^(\d{2}):(\d{2})$/;function ol(e,t,r){let i=il.exec(e),a=t?al.exec(t):[``,`00`,`00`];if(!i||!a)return null;let[o,s,c,l,u]=[+i[1],+i[2],+i[3],+a[1],+a[2]];if(s<1||s>12||c<1||c>31||l>23||u>59)return null;let d=Date.UTC(o,s-1,c,l,u);return new Date(d).getUTCDate()===c?(0,n.wallToUtc)(d,r):null}function Q(e,t){let r=e=>String(e).padStart(2,`0`),i=(0,n.timeParts)(e,t);return{date:`${i.year}-${r(i.month)}-${r(i.day)}`,time:`${r(i.hours)}:${r(i.minutes)}`}}var sl=[`date`,`range`],cl=1,ll=class{backdrop=null;fieldsEl=null;tabButtons=[];month=null;active=null;values={date:``,time:``,fromDate:``,fromTime:``,toDate:``,toTime:``};start=null;tab=`date`;returnFocus=null;uid=cl++;constructor(e,t,n,r){this.layer=e,this.labels=t,this.locale=n,this.onSubmit=r}isOpen(){return this.backdrop!==null}open(e){this.close(!1),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.start=e,this.values={date:e.date.date,time:e.date.time,fromDate:e.range.from.date,fromTime:e.range.from.time,toDate:e.range.to.date,toTime:e.range.to.time},this.build(),this.renderTab(!0)}close(e=!0){if(!this.backdrop)return;this.backdrop.remove(),this.backdrop=this.fieldsEl=this.month=this.active=this.start=null,this.tabButtons=[];let t=this.returnFocus;this.returnFocus=null,e&&t?.isConnected&&t.focus()}destroy(){this.close(!1)}build(){let e=this.labels(),t=document.createElement(`div`);t.className=`tcw-modal-backdrop`;let n=!1;t.addEventListener(`pointerdown`,e=>{n=e.target===t}),t.addEventListener(`click`,e=>{e.target===t&&n&&this.close(),n=!1});let r=document.createElement(`div`);r.className=`tcw-modal tcw-goto`,D(r,`goToDate`),r.setAttribute(`role`,`dialog`),r.setAttribute(`aria-modal`,`true`),r.setAttribute(`aria-labelledby`,`tcw-goto-title-${this.uid}`),r.tabIndex=-1,r.addEventListener(`keydown`,e=>{if(e.stopPropagation(),e.key===`Escape`){e.preventDefault(),this.close();return}M(e,r)});let i=document.createElement(`div`);i.className=`tcw-modal-header`;let a=document.createElement(`h3`);a.id=`tcw-goto-title-${this.uid}`,a.textContent=e.title;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,e.close),o.innerHTML=O(`x`,16),o.addEventListener(`click`,()=>this.close()),i.append(a,o);let s=document.createElement(`form`);s.className=`tcw-goto-form`,s.noValidate=!0,s.addEventListener(`submit`,e=>{e.preventDefault(),this.submit()});let c=document.createElement(`div`);c.className=`tcw-goto-fields`,c.id=`tcw-goto-panel-${this.uid}`,c.setAttribute(`role`,`tabpanel`);let l=new ae(e.calendar,this.locale(),e=>this.pickDay(e));l.element.classList.add(`tcw-goto-calendar`),s.append(c,l.element,this.buildFooter(e)),r.append(i,this.buildTabs(e),s),t.appendChild(r),this.layer().appendChild(t),this.backdrop=t,this.fieldsEl=c,this.month=l}buildTabs(e){let t=document.createElement(`div`);return t.className=`tcw-modal-tabs`,t.setAttribute(`role`,`tablist`),t.addEventListener(`keydown`,e=>this.onTabKey(e)),this.tabButtons=sl.map(t=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-modal-tab`,n.id=`tcw-goto-tab-${this.uid}-${t}`,n.dataset.tab=t,n.setAttribute(`role`,`tab`),n.setAttribute(`aria-controls`,`tcw-goto-panel-${this.uid}`),n.textContent=t===`date`?e.date:e.range,n.addEventListener(`click`,()=>this.select(t,!1)),n}),t.append(...this.tabButtons),t}buildFooter(e){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-footer-cancel`,t.dataset.act=`cancel`,t.textContent=e.cancel,t.addEventListener(`click`,()=>this.close());let n=document.createElement(`button`);n.type=`submit`,n.className=`tcw-done-btn`,n.dataset.act=`go`,n.textContent=e.submit;let r=document.createElement(`div`);r.className=`tcw-footer-end`,r.append(t,n);let i=document.createElement(`div`);return i.className=`tcw-modal-footer`,i.appendChild(r),i}select(e,t){this.tab=e,this.renderTab(!t),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}renderTab(e){let t=this.fieldsEl,n=this.start;if(!t||!n)return;for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.setAttribute(`aria-selected`,String(t)),e.classList.toggle(`tcw-active`,t),e.tabIndex=t?0:-1}t.setAttribute(`aria-labelledby`,`tcw-goto-tab-${this.uid}-${this.tab}`);let r=this.labels();t.replaceChildren(...this.tab===`date`?[this.row(null,`date`,`time`,r)]:[this.row(r.from,`fromDate`,`fromTime`,r),this.row(r.to,`toDate`,`toTime`,r)]);let i=t.querySelector(`input[type="date"]`);this.setActive(i),e&&i?.focus()}row(e,t,n,r){let i=document.createElement(`div`);if(i.className=`tcw-goto-row`,e){let t=document.createElement(`span`);t.className=`tcw-goto-label`,t.textContent=e,i.appendChild(t)}let a=e?`${e} · `:``,o=this.input(`date`,t,`${a}${r.date}`);return o.required=!0,o.dataset.tcwCalendar=`inline`,this.start?.max&&(o.max=this.start.max),o.addEventListener(`focus`,()=>this.setActive(o)),o.addEventListener(`input`,()=>{o.removeAttribute(`aria-invalid`),this.active===o&&this.showMonth()}),i.appendChild(o),this.start?.withTime&&i.appendChild(this.input(`time`,n,`${a}${r.time}`)),i}input(e,t,n){let r=document.createElement(`input`);return r.type=e,r.className=`tcw-goto-input`,r.dataset.field=t,r.value=this.values[t],r.setAttribute(`aria-label`,n),r.addEventListener(`input`,()=>{this.values[t]=r.value}),r}setActive(e){this.active=e,this.showMonth()}showMonth(){this.active&&this.month?.show(this.active.value,{max:this.start?.max,today:this.start?.today})}pickDay(e){let t=this.active;if(!t)return;let n=this.month?.element.contains(document.activeElement)??!1;t.value=e,t.dispatchEvent(new Event(`input`,{bubbles:!0})),t.dispatchEvent(new Event(`change`,{bubbles:!0}));let r=t.dataset.field===`fromDate`?this.fieldsEl?.querySelector(`[data-field="toDate"]`):null;if(r){r.focus(),this.setActive(r);return}this.showMonth(),n&&this.month?.focusGrid()}submit(){let e=[...this.fieldsEl?.querySelectorAll(`[data-field]`)??[]];for(let t of e)this.values[t.dataset.field]=t.value;let t=this.start?.max,n=e.find(e=>e.type===`date`&&(!e.value||t!==void 0&&e.value>t));if(n){n.setAttribute(`aria-invalid`,`true`),n.focus();return}let r=this.values,i=this.start?.withTime??!1,a=e=>i?e:``,o;if(this.tab===`date`){if(!r.date)return;o={kind:`date`,date:r.date,time:a(r.time)}}else{if(!r.fromDate||!r.toDate)return;o={kind:`range`,from:{date:r.fromDate,time:a(r.fromTime)},to:{date:r.toDate,time:a(r.toTime)}}}this.close(),this.onSubmit(o)}onTabKey(e){let t=sl.indexOf(this.tab),[n,r]=this.backdrop?.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowLeft`,`ArrowRight`]:[`ArrowRight`,`ArrowLeft`],i=e.key===n?(t+1)%sl.length:e.key===r?(t-1+sl.length)%sl.length:e.key===`Home`?0:e.key===`End`?sl.length-1:-1;i<0||(e.preventDefault(),this.select(sl[i],!0))}},$={min:233,default:296,max:377},ul=.382,dl=e=>!e.hidden&&getComputedStyle(e).display!==`none`,fl=class{element;panel;rail;handle;pages=new Map;open_=null;width;drag=null;observer=null;onMove=e=>{!this.drag||!this.samePointer(e)||this.setWidth(this.drag.width+(this.drag.x-e.clientX)*this.drag.dir)};onUp=e=>{!this.drag||!this.samePointer(e)||(this.drag=null,this.stopDrag(),this.options.saveWidth?.(this.width))};constructor(e,t){this.options=t;let n=document.createElement(`div`);n.className=`tcw-dock`;let r=document.createElement(`div`);r.className=`tcw-dock-panel`,r.hidden=!0,r.addEventListener(`keydown`,e=>this.onPanelKey(e));let i=document.createElement(`div`);i.className=`tcw-dock-resize`,i.setAttribute(`role`,`separator`),i.setAttribute(`aria-orientation`,`vertical`),i.setAttribute(`aria-label`,t.labels.resize),i.setAttribute(`aria-valuemin`,String($.min)),i.tabIndex=0,i.addEventListener(`pointerdown`,e=>this.startDrag(e)),i.addEventListener(`keydown`,e=>this.onHandleKey(e)),r.appendChild(i);let a=document.createElement(`div`);a.className=`tcw-dock-rail`,a.setAttribute(`role`,`toolbar`),a.setAttribute(`aria-orientation`,`vertical`),a.setAttribute(`aria-label`,t.labels.rail),D(a,`dock`),a.addEventListener(`keydown`,e=>this.onRailKey(e)),n.append(r,a),e.appendChild(n),this.element=n,this.panel=r,this.rail=a,this.handle=i,this.width=this.clamp(t.savedWidth?.()??$.default,$.max),this.applyWidth(),t.room&&typeof ResizeObserver<`u`&&(this.observer=new ResizeObserver(()=>this.fit()),this.observer.observe(e))}addPage(e){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-dock-btn`,t.dataset.page=e.id,t.title=e.label,t.setAttribute(`aria-label`,e.label),t.setAttribute(`aria-pressed`,`false`),t.tabIndex=-1,t.innerHTML=O(e.icon,18),e.parts?.length&&D(t,...e.parts),t.addEventListener(`click`,()=>{this.toggle(e.id)}),t.addEventListener(`focus`,()=>this.rove(t)),this.rail.appendChild(t),e.element.hidden=!0,e.element.classList.add(`tcw-dock-page`),this.panel.appendChild(e.element),this.pages.set(e.id,{page:e,button:t}),this.syncRail()}open(e){let t=this.pages.get(e);!t||this.open_===e||(this.hideCurrent(),this.open_=e,this.panel.hidden=!1,t.page.element.hidden=!1,t.button.setAttribute(`aria-pressed`,`true`),this.fit(),t.page.onShow?.(),this.options.onChange?.(e))}close(){let e=this.open_;if(e===null)return;let t=this.panel.contains(document.activeElement);if(this.hideCurrent(),this.panel.hidden=!0,t){let t=this.pages.get(e)?.button;(t&&(this.options.railShown?.()??!0)&&dl(t)?t:this.options.focusAfterClose?.(e))?.focus()}this.options.onChange?.(null)}toggle(e){this.open_===e?this.close():this.open(e)}closePage(e){this.open_===e&&this.close()}current(){return this.open_}isOpen(e){return this.open_===e}syncRail(){let e=[...this.pages.values()].map(e=>e.button),t=e.filter(dl),n=e.find(e=>e.tabIndex===0);if(n&&t.includes(n))return;let r=t.find(e=>e.getAttribute(`aria-pressed`)===`true`)??t[0];for(let t of e)t.tabIndex=t===r?0:-1}fit(){this.applyWidth()}destroy(){this.drag=null,this.stopDrag(),this.observer?.disconnect(),this.element.remove()}hideCurrent(){let e=this.open_===null?null:this.pages.get(this.open_);this.open_=null,e&&(e.page.element.hidden=!0,e.button.setAttribute(`aria-pressed`,`false`),e.page.onHide?.())}maxNow(){let e=this.options.room?.()??0;return e<=0?$.max:Math.max($.min,Math.min($.max,Math.floor(e*ul)))}clamp(e,t=this.maxNow()){return Math.round(Math.min(t,Math.max($.min,e)))}shownWidth(){return this.clamp(this.width)}setWidth(e){this.width=this.clamp(e),this.applyWidth()}applyWidth(){let e=this.shownWidth();this.element.style.setProperty(`--tcw-dock-w`,`${e}px`),this.handle.setAttribute(`aria-valuemax`,String(this.maxNow())),this.handle.setAttribute(`aria-valuenow`,String(e))}samePointer(e){let t=e.pointerId;return this.drag?.pointer===void 0||t===void 0||t===this.drag.pointer}startDrag(e){if(e.button!==0)return;e.preventDefault();let t=getComputedStyle(this.element).direction===`rtl`||this.element.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`;this.drag={x:e.clientX,width:this.shownWidth(),dir:t?-1:1,pointer:e.pointerId},document.addEventListener(`pointermove`,this.onMove),document.addEventListener(`pointerup`,this.onUp),document.addEventListener(`pointercancel`,this.onUp)}stopDrag(){document.removeEventListener(`pointermove`,this.onMove),document.removeEventListener(`pointerup`,this.onUp),document.removeEventListener(`pointercancel`,this.onUp)}onHandleKey(e){let[t,n]=this.element.closest(`[dir]`)?.getAttribute(`dir`)===`rtl`?[`ArrowRight`,`ArrowLeft`]:[`ArrowLeft`,`ArrowRight`],r=this.shownWidth(),i=e.key===t?r+13:e.key===n?r-13:e.key===`Home`?$.min:e.key===`End`?$.max:null;i!==null&&(e.preventDefault(),this.setWidth(i),this.options.saveWidth?.(this.width))}onPanelKey(e){e.key!==`Escape`||e.defaultPrevented||!this.element.closest(`[data-tcw-narrow]`)||(e.preventDefault(),e.stopPropagation(),this.close())}rove(e){for(let{button:t}of this.pages.values())t.tabIndex=t===e?0:-1}onRailKey(e){let t=[...this.pages.values()].map(e=>e.button).filter(dl),n=t.indexOf(e.target);if(n<0)return;let r=e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),t[r].focus())}},pl=[`percent`,`scale`,`pane`,`spread`,`ratio`,`correlation`,`correlationLog`],ml={percent:`compare.percent`,scale:`compare.ownScale`,pane:`compare.ownPane`,spread:`compare.way.spread`,ratio:`compare.way.ratio`,correlation:`compare.way.correlation`,correlationLog:`compare.way.correlationLog`};function hl(e){return pl.includes(e)}function gl(e){return pl.map(t=>({id:t,label:e(ml[t])}))}function _l(e,t){let n=e.findIndex(e=>e.time>=t);return n<0?e.length:n}function vl(e,t){let n=e[0]?.time??1/0,r=t.filter(e=>e.time<n);return r.length>0?[...r,...e]:null}function yl(e,t){switch(e.id){case`compareSymbol`:return t?`pane`:`scale`;case`compareSymbolPane`:return`pane`;case`spread`:return e.params.mode===`ratio`?`ratio`:`spread`;case`correlation`:return`correlation`;case`correlationlog`:return`correlationLog`;default:return null}}function bl(e,t,n,r){let i=e.map(e=>({id:e.id,symbol:e.symbol,way:r(ml.percent),color:e.color}));for(let e of t){let t=e.params.symbol,a=yl(e,n.has(e.instanceId));!a||typeof t!=`string`||!t||i.push({id:e.instanceId,symbol:t,way:r(ml[a])})}return i}var xl=8,Sl=4,Cl=3,wl=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,Tl=class{el;target=null;source=null;pressed=null;showTimer=null;watchFrame=0;warmUntil=0;observer;constructor(e){this.root=e,this.el=document.createElement(`div`),this.el.className=`tcw-tooltip`,this.el.setAttribute(`aria-hidden`,`true`),e.appendChild(this.el),e.addEventListener(`pointerover`,this.onOver),e.addEventListener(`pointerout`,this.onOut),e.addEventListener(`pointerdown`,this.onPress,!0),e.addEventListener(`keydown`,this.onPress,!0),e.addEventListener(`focusin`,this.onFocus),e.addEventListener(`focusout`,this.onBlur),e.addEventListener(`wheel`,this.hide,{passive:!0}),this.observer=new MutationObserver(()=>{this.pressed?.hasAttribute(`title`)&&El(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(El(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&Dl(this.pressed),this.observer.disconnect(),this.root.removeEventListener(`pointerover`,this.onOver),this.root.removeEventListener(`pointerout`,this.onOut),this.root.removeEventListener(`pointerdown`,this.onPress,!0),this.root.removeEventListener(`keydown`,this.onPress,!0),this.root.removeEventListener(`focusin`,this.onFocus),this.root.removeEventListener(`focusout`,this.onBlur),this.root.removeEventListener(`wheel`,this.hide),this.el.remove()}onOver=e=>{if(e.pointerType===`touch`)return;let t=this.tipTarget(e.target);!t||t===this.pressed||t===this.target&&this.source===`pointer`||(El(t),this.schedule(t,`pointer`,Date.now()<this.warmUntil||this.isVisible()))};onOut=e=>{let t=e.relatedTarget,n=e=>!!e&&!!t&&e.contains(t);this.pressed&&!n(this.pressed)&&(Dl(this.pressed),this.pressed=null),this.source===`pointer`&&!n(this.target)&&this.hide()};onPress=()=>{let e=this.target,t=this.source===`pointer`;this.warmUntil=0,this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.el.classList.remove(`tcw-tooltip--visible`),this.target=null,this.source=null,this.pressed&&this.pressed!==e&&Dl(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!Al(t)||t===this.pressed||this.schedule(t,`focus`,!0)};onBlur=e=>{if(this.source!==`focus`)return;let t=e.relatedTarget;this.target&&t&&this.target.contains(t)||this.hide()};hide=()=>{this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.isVisible()&&(this.warmUntil=Date.now()+500),this.el.classList.remove(`tcw-tooltip--visible`),this.target&&this.source===`pointer`&&Dl(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(wl);return t&&t!==this.el&&this.root.contains(t)?t:null}schedule(e,t,n){let r=this.target;if(this.clearTimer(),cancelAnimationFrame(this.watchFrame),r&&r!==e&&this.source===`pointer`&&Dl(r),this.target=e,this.source=t,n){this.show(e);return}this.el.classList.remove(`tcw-tooltip--visible`),this.showTimer=setTimeout(()=>{this.showTimer=null,this.target===e&&this.show(e)},300)}show(e){if(!kl(e)){this.hide();return}this.el.textContent=Ol(e),this.place(e),this.el.classList.add(`tcw-tooltip--visible`),this.watch(e)}watch(e){cancelAnimationFrame(this.watchFrame),this.watchFrame=requestAnimationFrame(()=>{this.target===e&&(kl(e)?this.watch(e):this.hide())})}place(e){let t=this.root.getBoundingClientRect(),n=e.getBoundingClientRect(),r=this.el.offsetWidth,i=this.el.offsetHeight,a=n.left-t.left,o=n.top-t.top,s=jl(e);s===`bottom`&&o+n.height+xl+i>t.height?s=`top`:s===`top`&&o-xl-i<0?s=`bottom`:s===`right`&&a+n.width+xl+r>t.width&&(s=`left`);let c,l;s===`top`||s===`bottom`?(c=a+n.width/2-r/2,l=s===`bottom`?o+n.height+xl:o-xl-i):(c=s===`right`?a+n.width+xl:a-xl-r,l=o+n.height/2-i/2),c=Math.max(Sl,Math.min(t.width-r-Sl,c)),l=Math.max(Sl,Math.min(t.height-i-Sl,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,Cl],bottom:[0,-Cl],left:[Cl,0],right:[-Cl,0]}[s];this.el.style.setProperty(`--tcw-tip-dx`,`${u[0]}px`),this.el.style.setProperty(`--tcw-tip-dy`,`${u[1]}px`),this.el.dataset.side=s}isVisible(){return this.el.classList.contains(`tcw-tooltip--visible`)}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}};function El(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function Dl(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function Ol(e){return e.dataset.tip??e.getAttribute(`title`)??``}function kl(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function Al(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function jl(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var Ml=2,Nl=1.5,Pl=`tcw-ind-legend-values--no-room`,Fl=0,Il=class{stack;toggle;rows=new Map;panes=new Map;collapsed=!1;toggleKey=``;stackKey=``;valuesObserver;stackObserver;constructor(e,t,n){this.host=e,this.callbacks=t,this.labels=n,this.stack=document.createElement(`div`),this.stack.className=`tcw-ind-legend`,D(this.stack,`indicatorLegend`),this.toggle=document.createElement(`button`),this.toggle.type=`button`,this.toggle.className=`tcw-ind-legend-toggle`,this.toggle.addEventListener(`click`,()=>{this.setCollapsed(!this.collapsed),this.renderToggle(this.overlayCount())}),this.stack.appendChild(this.toggle),e.appendChild(this.stack),this.stackObserver=typeof ResizeObserver>`u`||!t.onStackResize?null:new ResizeObserver(()=>this.reportStackSize()),this.stackObserver?.observe(this.stack),this.valuesObserver=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>{for(let t of e)Ll(t.target,t.contentRect.width)})}update(e,t,n=[]){this.updatePanes(n);let r=`${Math.round(t.left)},${Math.round(t.top)}`;r!==this.stackKey&&(this.stackKey=r,this.stack.style.left=`${Math.round(t.left)}px`,this.stack.style.top=`${Math.round(t.top)}px`);let i=new Set(e.map(e=>e.instanceId));for(let[e,t]of this.rows)i.has(e)||(this.valuesObserver?.unobserve(t.values),t.el.remove(),this.rows.delete(e));let a=!1,o=null;for(let t of e){let e=this.rows.get(t.instanceId)??this.createRow(t.instanceId,t.kind);if(this.fill(e,t),t.pane)e.el.parentElement!==this.host&&this.host.appendChild(e.el);else{let t=o?o.nextElementSibling:this.stack.firstElementChild;e.el.parentElement!==this.stack&&(a=!0),e.el!==t&&this.stack.insertBefore(e.el,t),o=e.el}this.place(e,t.pane)}a&&this.collapsed&&this.setCollapsed(!1),this.renderToggle(e.filter(e=>!e.pane).length)}destroy(){this.valuesObserver?.disconnect(),this.stackObserver?.disconnect();for(let e of this.rows.values())e.el.remove();this.rows.clear();for(let e of this.panes.values())e.el.remove();this.panes.clear(),this.stack.remove()}reportStackSize(){let e=this.stack.offsetWidth,t=this.stack.offsetHeight;this.callbacks.onStackResize?.(e>0&&t>0?{width:e,height:t}:null)}updatePanes(e){if(!this.callbacks.onPaneAction)return;let t=new Set;for(let n of e){t.add(n.instanceId);let e=this.panes.get(n.instanceId)??this.createPane(n.instanceId),r=`${Math.round(n.x)},${Math.round(n.y)}|${n.label}|${n.collapsed}|${n.maximized}|${n.canMoveUp}|${n.canMoveDown}`;if(r===e.key)continue;e.key=r,e.el.style.left=`${Math.round(n.x)}px`,e.el.style.top=`${Math.round(n.y)}px`;let i=this.labels,a=(t,r,i,a)=>{let o=e.buttons.get(t);!r&&document.activeElement===o&&e.buttons.get(`max`).focus(),o.hidden=!r,o.innerHTML=O(i,12),Rl(o,a??t,n.label)};a(`up`,n.canMoveUp&&!n.maximized,`arrowUp`,i.paneUp),a(`down`,n.canMoveDown&&!n.maximized,`arrowDown`,i.paneDown),a(`fold`,!n.maximized,n.collapsed?`chevronDown`:`chevronUp`,n.collapsed?i.paneExpand:i.paneCollapse),a(`max`,!0,n.maximized?`minimize`:`maximize`,n.maximized?i.paneRestore:i.paneMaximize),e.el.dataset.collapsed=String(n.collapsed),e.el.dataset.maximized=String(n.maximized)}for(let[e,n]of this.panes)t.has(e)||(n.el.remove(),this.panes.delete(e))}createPane(e){let t=document.createElement(`div`);t.className=`tcw-pane-controls`,D(t,`indicatorLegend`),t.dataset.instance=e;let n=new Map,r=e=>e===`up`||e===`down`?e:e===`fold`?t.dataset.collapsed===`true`?`expand`:`collapse`:t.dataset.maximized===`true`?`restore`:`maximize`,i={up:`pane.move`,down:`pane.move`,fold:`pane.collapse`,max:`pane.maximize`};for(let a of[`up`,`down`,`fold`,`max`]){let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-pane-btn`,o.dataset.act=a,D(o,i[a]),o.addEventListener(`click`,()=>this.callbacks.onPaneAction?.(e,r(a))),n.set(a,o),t.appendChild(o)}this.host.appendChild(t);let a={el:t,buttons:n,key:``};return this.panes.set(e,a),a}createRow(e,t){let n=t===`compare`,r=document.createElement(`div`);r.className=n?`tcw-ind-legend-row tcw-ind-legend-row--compare`:`tcw-ind-legend-row`,D(r,`indicatorLegend`),r.dataset.instance=e;let i=document.createElement(n?`span`:`button`);i.className=`tcw-ind-legend-name`,i instanceof HTMLButtonElement&&(i.type=`button`,i.addEventListener(`click`,()=>this.callbacks.onSettings(e)));let a=document.createElement(`span`);a.className=`tcw-ind-legend-values`,D(a,`indicatorLegend.values`),this.valuesObserver?.observe(a);let o=document.createElement(`span`);o.className=`tcw-ind-legend-actions`;let s=(e,t,n,...r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-ind-legend-act`,i.dataset.act=e,D(i,...r),i.innerHTML=O(t,13),i.addEventListener(`click`,n),o.appendChild(i),i},c=s(`visible`,`eye`,()=>{this.callbacks.onToggleVisible(e,!m.visible,t)},`indicatorLegend.visibility`),l=n?null:s(`settings`,`settings`,()=>this.callbacks.onSettings(e),`indicatorSettings`,`indicatorLegend.settings`),u=this.callbacks.onMore&&!n?s(`more`,`more`,()=>this.callbacks.onMore?.(e,u),`indicatorLegend.more`):null,d=s(`remove`,`x`,()=>this.callbacks.onRemove(e,t),`indicatorLegend.remove`),f=document.createElement(`span`);f.className=`tcw-visually-hidden`,f.id=`tcw-ind-note-${++Fl}`;let p=n?document.createElement(`span`):null;p&&(p.className=`tcw-ind-legend-swatch`,p.setAttribute(`aria-hidden`,`true`),r.append(p)),r.append(i,a,o,f);let m={el:r,name:i,swatch:p,values:a,eye:c,settings:l,more:u,remove:d,note:f,visible:!0,valuesKey:``,state:``,placeKey:``};return this.rows.set(e,m),m}fill(e,t){let n=this.offNote(t),r=`${t.label}|${t.visible}|${n}|${t.swatch??``}`;r!==e.state&&(e.state=r,e.swatch&&(e.swatch.style.backgroundColor=t.swatch??``),e.visible=t.visible,e.name.textContent=t.label,e.settings&&(e.name.title=this.labels.settings),e.el.classList.toggle(`tcw-ind-legend-row--hidden`,!t.visible||n!==null),n?e.el.title=n:e.el.removeAttribute(`title`),this.describe(e,n),e.eye.innerHTML=O(t.visible?`eye`:`eyeOff`,13),Rl(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),e.settings&&Rl(e.settings,this.labels.settings,t.label),e.more&&(Rl(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),Rl(e.remove,this.labels.remove,t.label));let i=t.values.map(e=>`${e.text}${e.color??``}`).join(``);i!==e.valuesKey&&(e.valuesKey=i,e.values.replaceChildren(...t.values.map(e=>{let t=document.createElement(`span`);return t.textContent=e.text,e.color&&(t.style.color=e.color),t})))}describe(e,t){e.note.textContent=t??``;let n=[e.name,e.eye,e.settings,e.more,e.remove].filter(e=>e instanceof HTMLButtonElement);for(let r of n)t?r.setAttribute(`aria-describedby`,e.note.id):r.removeAttribute(`aria-describedby`)}offNote(e){return e.offInterval?this.labels.offInterval??``:e.offChartType?this.labels.offChartType??``:null}place(e,t){let n=t?`${Math.round(t.x)},${Math.round(t.y)},${Math.round(t.width)}`:``;n!==e.placeKey&&(e.placeKey=n,e.el.classList.toggle(`tcw-ind-legend-row--pane`,t!==null),e.el.style.left=t?`${Math.round(t.x)}px`:``,e.el.style.top=t?`${Math.round(t.y)}px`:``,e.el.style.maxWidth=t?`${Math.max(0,Math.round(t.width))}px`:``)}setCollapsed(e){this.collapsed=e,this.stack.classList.toggle(`tcw-ind-legend--collapsed`,e)}overlayCount(){return this.stack.querySelectorAll(`:scope > .tcw-ind-legend-row`).length}renderToggle(e){let t=e>=Ml;!t&&this.collapsed&&this.setCollapsed(!1);let n=`${t}|${this.collapsed}|${e}`;if(n===this.toggleKey||(this.toggleKey=n,this.toggle.hidden=!t,!t))return;let r=this.collapsed?this.labels.expand:this.labels.collapse;Rl(this.toggle,r,this.collapsed?`(${e})`:void 0),this.toggle.setAttribute(`aria-expanded`,String(!this.collapsed));let i=O(this.collapsed?`chevronDown`:`chevronUp`,12);this.toggle.innerHTML=this.collapsed?`${i}<span>${e}</span>`:i}};function Ll(e,t){let n=(parseFloat(getComputedStyle(e).fontSize)||0)*Nl;e.classList.toggle(Pl,t<n)}function Rl(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function zl(e,t){return!e||e.length===0?null:e[t===null?e.length-1:Math.min(Math.max(t,0),e.length-1)]??null}function Bl(e,t,n,i){if(!t)return[];let a=e.plots;if(!a){let e=[];for(let n in t){let r=t[n];typeof r==`number`&&Number.isFinite(r)&&e.push(r)}let r=e.length===1?n[0]??null:null;return e.map(e=>({value:e,color:r}))}let o={colors:[...n],lineWidths:[],opacity:1},s=[];for(let e of a){if(!(0,r.plotShown)(e,{plots:i}))continue;let a=t[e.key];typeof a!=`number`||!Number.isFinite(a)||s.push({value:a,color:n.length?(0,r.plotColor)(e,o,t):null})}return s}var Vl=new Map;function Hl(e){let t=Vl.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),Vl.set(e,t)),t}function Ul(e,t=`en-US`){return Math.abs(e)>=1e6?Hl(t).format(e):(0,n.formatPrice)(e,(0,r.indicatorValuePrecision)(e),t)}var Wl=2,Gl=2;function Kl(e,t=`en-US`){return(0,n.formatPrice)(e,Math.max(Wl,(0,r.indicatorValuePrecision)(e)),t)}function ql(e,t=`en-US`){return`${ic((0,n.formatPrice)(Math.abs(e),Gl,t),e,(0,n.formatPrice)(0,Gl,t))}%`}function Jl(e,t=`en-US`,n=!0){return e.map(e=>({instanceId:e.id,kind:`compare`,label:e.label,swatch:e.color,visible:e.visible,...n?{values:Yl(e,t)}:{values:[],offChartType:!0},pane:null}))}function Yl(e,t){return[...e.close===null?[]:[{text:Kl(e.close,t),color:null}],...e.change===null?[]:[{text:ql(e.change,t),color:null}]]}var Xl=class{el;labelEl;callbacks;visible=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-bracket-bar`,this.el.setAttribute(`role`,`group`),this.el.hidden=!0,this.labelEl=document.createElement(`span`),this.labelEl.className=`tcw-bracket-label`,this.el.appendChild(this.labelEl);let i=document.createElement(`span`);i.className=`tcw-bracket-hint`,i.textContent=this.t(`bracket.hint`),this.el.appendChild(i);let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-bracket-cancel`,a.innerHTML=`${O(`x`,14)}<span>${k(this.t(`common.cancel`))}</span>`,a.addEventListener(`click`,()=>this.callbacks.onCancel());let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-bracket-confirm`,o.innerHTML=`${O(`check`,14)}<span>${k(this.t(`bracket.place`))}</span>`,o.addEventListener(`click`,()=>this.callbacks.onConfirm()),this.el.appendChild(a),this.el.appendChild(o),e.appendChild(this.el)}show(e){this.visible=!0;let t=e===`buy`?this.t(`toolbar.longBracket`):this.t(`toolbar.shortBracket`);this.labelEl.textContent=t,this.el.setAttribute(`aria-label`,t),this.el.dataset.side=e,this.el.dir=this.el.closest(`.tcw-root`)?.dir||`auto`,this.el.hidden=!1}hide(){this.visible=!1,this.el.hidden=!0}isVisible(){return this.visible}destroy(){this.el.remove()}},Zl=class{options;audioCtx=null;audioEl=null;permissionAsked=!1;constructor(e={}){if(this.options=e,typeof e.sound==`string`)try{this.audioEl=new Audio(e.sound),this.audioEl.preload=`auto`}catch{this.audioEl=null}e.desktop&&this.ensurePermission()}setOptions(e){this.options={...this.options,...e}}notify(e){this.options.sound&&this.playSound(),this.options.desktop&&this.showDesktop(e)}playSound(){if(this.audioEl){this.audioEl.currentTime=0,this.audioEl.play().catch(()=>{});return}this.beep()}beep(){try{let e=window.AudioContext??window.webkitAudioContext;if(!e)return;this.audioCtx||=new e;let t=this.audioCtx,n=t.currentTime,r=t.createGain();r.gain.setValueAtTime(1e-4,n),r.gain.exponentialRampToValueAtTime(.2,n+.01),r.gain.exponentialRampToValueAtTime(1e-4,n+.35),r.connect(t.destination);let i=t.createOscillator();i.type=`sine`,i.frequency.setValueAtTime(880,n),i.frequency.setValueAtTime(1320,n+.16),i.connect(r),i.start(n),i.stop(n+.36)}catch{}}ensurePermission(){this.permissionAsked||(this.permissionAsked=!0,!(typeof Notification>`u`)&&Notification.permission===`default`&&Notification.requestPermission().catch(()=>{}))}showDesktop(e){if(!(typeof Notification>`u`)){if(Notification.permission!==`granted`){this.ensurePermission();return}try{new Notification(this.options.title??`Price alert`,{body:e})}catch{}}}destroy(){try{this.audioCtx?.close()}catch{}this.audioCtx=null,this.audioEl=null}};function Ql(e,t=12){let n=[...e.asks].sort((e,t)=>e.price-t.price).slice(0,t),r=[...e.bids].sort((e,t)=>t.price-e.price).slice(0,t),i=n.length>0?n[0].price:null,a=r.length>0?r[0].price:null,o=i!==null&&a!==null?(i+a)/2:null,s=new Map,c=e=>{let t=s.get(e);return t||(t={price:e,bidVolume:0,askVolume:0},s.set(e,t)),t};for(let e of n)c(e.price).askVolume+=e.volume;for(let e of r)c(e.price).bidVolume+=e.volume;let l=[...s.values()].sort((e,t)=>t.price-e.price),u=0;for(let e of l)u=Math.max(u,e.bidVolume,e.askVolume);return{rows:l,maxVolume:u,mid:o,spread:i!==null&&a!==null?i-a:null,bestBid:a}}var $l=1e-9,eu=class{el;colsEl;bodyEl;callbacks;open=!1;levels;model=null;orders=[];drawn=[];spreadEl;placed=!1;constructor(e,n,r=12,i=t.t){this.t=i,this.callbacks=n,this.levels=r,this.el=document.createElement(`section`),this.el.className=`tcw-ladder`,this.el.setAttribute(`aria-label`,this.t(`ladder.title`)),D(this.el,`depthLadder`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-ladder-header`;let o=document.createElement(`h3`);o.className=`tcw-ladder-title`,o.textContent=this.t(`ladder.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-ladder-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=O(`x`,14),s.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),a.append(o,s),this.colsEl=document.createElement(`div`),this.colsEl.className=`tcw-ladder-cols`;for(let e of[`ladder.bid`,`ladder.price`,`ladder.ask`]){let t=document.createElement(`span`);t.textContent=this.t(e),this.colsEl.appendChild(t)}this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-ladder-body`,this.spreadEl=document.createElement(`div`),this.spreadEl.className=`tcw-ladder-spread`,this.el.append(a,this.colsEl,this.bodyEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.placed=!1,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}close(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}setData(e){this.model=e?Ql(e,this.levels):null,this.render()}setOrders(e){this.orders=e,this.render()}destroy(){this.el.remove()}render(){if(!this.open)return;let e=this.model;if(!e||e.rows.length===0){let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=this.t(`ladder.empty`),this.bodyEl.replaceChildren(e),this.drawn=[];return}let t=tu(e.rows);e.rows.length===this.drawn.length&&e.rows.every((e,t)=>e.price===this.drawn[t].price)||(this.drawn=e.rows.map(e=>this.newRow(e.price)),this.bodyEl.replaceChildren(...this.drawn.map(e=>e.row)));let n=e.maxVolume>0?100/e.maxVolume:0;e.rows.forEach((e,r)=>this.fillRow(this.drawn[r],e,n,this.nearness(e.price,t))),this.putSpread(e,t),this.placeSpread()}putSpread(e,n){let{spread:r,bestBid:i}=e,a=r===null||i===null?-1:e.rows.findIndex(e=>e.price<i+n);if(r===null||a<0){this.spreadEl.remove();return}this.spreadEl.textContent=t.r(this.t(`ladder.spread`),{spread:this.callbacks.formatPrice(r)});let o=this.drawn[a].row;this.spreadEl.nextElementSibling!==o&&this.bodyEl.insertBefore(this.spreadEl,o)}nearness(e,t){let n=this.callbacks.priceStep?.(e)??0;return n>0?Math.min(n/2,t):t}newRow(e){let t=document.createElement(`div`);t.className=`tcw-ladder-row`;let n=document.createElement(`div`);n.className=`tcw-ladder-price`;let r=document.createElement(`span`);r.className=`tcw-ladder-figure`,n.appendChild(r);let i=this.newCell(`sell`,e),a=this.newCell(`buy`,e);return t.append(i,n,a),{price:e,row:t,bid:i,ask:a,cell:n,figure:r}}newCell(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-ladder-cell ${e===`sell`?`tcw-ladder-bid`:`tcw-ladder-ask`}`,n.addEventListener(`click`,()=>this.callbacks.onTrade(e,t)),n}fillRow(e,t,n,r){e.cell.className=`tcw-ladder-price ${t.askVolume>0?`tcw-ask`:`tcw-bid`}`,e.figure.textContent=this.callbacks.formatPrice(t.price),this.fillCell(e.bid,`sell`,t.bidVolume,t.price,n),this.fillCell(e.ask,`buy`,t.askVolume,t.price,n);for(let t of e.cell.querySelectorAll(`.tcw-ladder-own`))t.remove();for(let n of[`buy`,`sell`]){let i=this.orders.filter(e=>e.side===n&&Math.abs(e.price-t.price)<r).reduce((e,t)=>e+t.quantity,0);if(i<=0)continue;let a=document.createElement(`span`);a.className=`tcw-ladder-own`,a.dataset.side=n,a.textContent=String(i);let o=`${this.t(n===`buy`?`ticket.buy`:`ticket.sell`)} ${i}`;a.setAttribute(`aria-label`,o),a.title=o,n===`buy`?e.cell.insertBefore(a,e.figure):e.cell.appendChild(a)}}fillCell(e,n,r,i,a){if(!(r>0)){e.disabled=!0,e.textContent=``,e.removeAttribute(`aria-label`),e.title=``,e.style.removeProperty(`--w`);return}e.disabled=!1;let o=nu(r);e.textContent=o,e.style.setProperty(`--w`,`${(r*a).toFixed(1)}%`);let s=t.r(this.t(n===`sell`?`ladder.sellAt`:`ladder.buyAt`),{price:this.callbacks.formatPrice(i)});e.setAttribute(`aria-label`,`${o}, ${s}`),e.title=s}placeSpread(){let e=this.el;if(this.placed||!this.spreadEl.isConnected||e.clientHeight===0)return;let t=e.getBoundingClientRect().top,n=this.colsEl.getBoundingClientRect().bottom-t,r=this.spreadEl.getBoundingClientRect().top-t;e.scrollTop+=r-n-(e.clientHeight-n-this.spreadEl.offsetHeight)/2,this.placed=!0}};function tu(e){let t=1/0;for(let n=1;n<e.length;n++)t=Math.min(t,Math.abs(e[n-1].price-e[n].price));return Number.isFinite(t)&&t>0?t/2:$l}function nu(e){return e>=1e3?`${Number((e/1e3).toFixed(1))}k`:String(Number(e>=1?e.toFixed(2):e.toPrecision(2)))}var ru=class{el;bodyEl;callbacks;open=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-datawin`,D(this.el,`dataWindow`),this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-datawin-header`;let a=document.createElement(`span`);a.textContent=this.t(`dataWindow.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-datawin-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=O(`x`,14),o.addEventListener(`click`,()=>this.callbacks.onClose?this.callbacks.onClose():this.close()),i.appendChild(a),i.appendChild(o),this.el.appendChild(i),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-datawin-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}get element(){return this.el}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}render(e){if(!this.open)return;if(this.bodyEl.replaceChildren(),!e.ohlc){let e=document.createElement(`div`);e.className=`tcw-datawin-empty`,e.textContent=this.t(se()?`dataWindow.touch`:`dataWindow.hover`),this.bodyEl.appendChild(e);return}let t=this.callbacks.formatPrice,n=e.ohlc;this.bodyEl.appendChild(this.row(this.t(`dataWindow.open`),t(n.open))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.high`),t(n.high))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.low`),t(n.low))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.close`),t(n.close)));let r=e.change>0?`up`:e.change<0?`down`:``,i=e.change>0?`+`:``,a=this.callbacks.formatPercent?.(e.changePct)??e.changePct.toFixed(2),o=e.changeText??t(e.change);this.bodyEl.appendChild(this.row(this.t(`dataWindow.change`),`${i}${o} (${i}${a}%)`,r)),this.bodyEl.appendChild(this.row(this.t(`dataWindow.volume`),(this.callbacks.formatVolume??au)(n.volume)));for(let t of e.indicators){let e=document.createElement(`div`);e.className=`tcw-datawin-sub`,e.textContent=t.name,this.bodyEl.appendChild(e);for(let e of t.values)this.bodyEl.appendChild(this.row(e.key,e.text??iu(e.value)))}}row(e,t,n=``){let r=document.createElement(`div`);r.className=`tcw-datawin-row`;let i=document.createElement(`span`);i.className=`tcw-datawin-label`,i.textContent=e;let a=document.createElement(`span`);return a.className=`tcw-datawin-value${n?` tcw-${n}`:``}`,a.textContent=t,r.appendChild(i),r.appendChild(a),r}};function iu(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toPrecision(4)}function au(e){return e>=1e9?(e/1e9).toFixed(2)+`B`:e>=1e6?(e/1e6).toFixed(2)+`M`:e>=1e3?(e/1e3).toFixed(2)+`K`:e.toFixed(0)}var ou=e=>typeof e==`object`&&!!e&&!Array.isArray(e),su=globalThis.Buffer;function cu(e){if(su)return su.from(e,`utf8`).toString(`base64`);let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function lu(e){if(su)return su.from(e,`base64`).toString(`utf8`);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return new TextDecoder().decode(n)}function uu(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function du(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function fu(e){return uu(cu(JSON.stringify(e)))}function pu(e){if(!e)return null;try{let t=lu(du(e)),n=JSON.parse(t);return!n||n.v!==1||typeof n.symbol!=`string`?null:{v:1,symbol:n.symbol,timeframe:n.timeframe,chartType:n.chartType,scaleMode:Yc.find(e=>e===n.scaleMode)??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[],...ou(n.settings)?{settings:G(n.settings,lo)}:{}}}catch{return null}}var mu=`tcw`;function hu(e){let t=e.startsWith(`#`)?e.slice(1):e;for(let e of t.split(`&`)){let t=e.indexOf(`=`);if(!(t<=0||e.slice(0,t)!==mu))try{return decodeURIComponent(e.slice(t+1))}catch{return null}}return null}function gu(e,t){let[n]=e.split(`#`);return`${n}#${mu}=${t}`}var _u=[[34,16,28,26,!1],[30,14,24,26,!0],[26,18,20,30,!0],[30,10,24,22,!1],[20,16,14,28,!0],[14,18,8,30,!0],[18,10,12,20,!1],[8,18,2,30,!0]],vu=class{el;label;showTimer=null;phase=`loading`;constructor(e,t){this.loadingText=t,this.el=document.createElement(`div`),this.el.className=`tcw-loading-overlay`,this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`div`);n.className=`tcw-loading-card`;let r=document.createElement(`div`);r.className=`tcw-loading-candles`,r.setAttribute(`aria-hidden`,`true`),_u.forEach(([e,t,n,i,a],o)=>{let s=document.createElement(`span`);s.className=a?`tcw-loading-candle tcw-loading-candle--up`:`tcw-loading-candle`,s.style.setProperty(`--tcw-body-top`,`${e}px`),s.style.setProperty(`--tcw-body-h`,`${t}px`),s.style.setProperty(`--tcw-wick-top`,`${n}px`),s.style.setProperty(`--tcw-wick-h`,`${i}px`),s.style.setProperty(`--tcw-delay`,`${o*110}ms`),r.appendChild(s)}),n.appendChild(r);let i=document.createElement(`div`);i.className=`tcw-loading-track`,i.setAttribute(`aria-hidden`,`true`),i.appendChild(document.createElement(`span`)),n.appendChild(i),this.label=document.createElement(`div`),this.label.className=`tcw-loading-label`,this.label.textContent=t,n.appendChild(this.label),this.el.appendChild(n),e.appendChild(this.el)}begin(e,t=!1){if(this.phase=`loading`,this.clearTimer(),this.label.textContent=this.loadingText,this.el.classList.remove(`tcw-loading-overlay--error`),this.el.classList.toggle(`tcw-loading-overlay--veil`,e),!e||t||this.isShown()){this.el.classList.remove(`tcw-loading-overlay--hidden`);return}this.showTimer=setTimeout(()=>{this.showTimer=null,this.el.classList.remove(`tcw-loading-overlay--hidden`)},200)}end(){this.phase=`idle`,this.clearTimer(),this.el.classList.add(`tcw-loading-overlay--hidden`)}fail(e){this.phase!==`idle`&&(this.phase=`failed`,this.clearTimer(),this.label.textContent=e,this.el.classList.add(`tcw-loading-overlay--error`),this.el.classList.remove(`tcw-loading-overlay--hidden`))}isActive(){return this.phase!==`idle`}hasFailed(){return this.phase===`failed`}isShown(){return!this.el.classList.contains(`tcw-loading-overlay--hidden`)}destroy(){this.clearTimer(),this.el.remove()}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}},yu=4e3,bu=class{el;text;hideTimer=null;constructor(e,t){this.texts=t,this.el=document.createElement(`div`),this.el.className=`tcw-history-pill tcw-history-pill--hidden`,this.el.setAttribute(`aria-hidden`,`true`),this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`span`);n.className=`tcw-history-spinner`,n.setAttribute(`aria-hidden`,`true`),this.text=document.createElement(`span`),this.el.append(n,this.text),e.appendChild(this.el)}update(e){this.clearTimer(),e.state===`loading`?this.show(this.texts.loading,!1):e.state===`error`?(this.show(this.texts.failed,!0),this.hideTimer=setTimeout(()=>this.hide(),yu)):this.hide()}destroy(){this.clearTimer(),this.el.remove()}show(e,t){this.text.textContent=e,this.el.classList.toggle(`tcw-history-pill--error`,t),this.el.classList.remove(`tcw-history-pill--hidden`),this.el.removeAttribute(`aria-hidden`)}hide(){this.hideTimer=null,this.el.classList.add(`tcw-history-pill--hidden`),this.el.setAttribute(`aria-hidden`,`true`),this.text.textContent=``}clearTimer(){this.hideTimer!==null&&clearTimeout(this.hideTimer),this.hideTimer=null}},xu=`host:`;function Su(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${xu}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function Cu(e,t){return e.startsWith(xu)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var wu=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),Tu={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},Eu={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function Du(e){let t=e.split(`+`).map(e=>e.trim()),n=t.pop();if(!n)return null;let r={ctrl:!1,alt:!1,shift:!1,display:[]};for(let e of t){let t=Tu[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(Tu[i])return null;if(/^[a-z]$/.test(i))r.code=`Key${i.toUpperCase()}`,r.char=i;else if(/^[0-9]$/.test(i))r.code=`Digit${i}`,r.char=i;else if(r.key=Eu[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[wu?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function Ou(e,t){if((e.ctrlKey||e.metaKey)!==t.ctrl||e.altKey!==t.alt)return!1;if(t.code!==void 0){if(e.shiftKey!==t.shift)return!1;if(t.alt)return e.code===t.code;let n=e.key.length===1&&/^[a-z0-9]$/i.test(e.key)?e.key.toLowerCase():null;return n===null?e.code===t.code:n===t.char}return t.shift&&!e.shiftKey?!1:e.key.toLowerCase()===t.key}var ku=new Set(`escape(enter(delete(backspace(arrowleft(arrowright(arrowup(arrowdown(home(end(+(-(=( (,(.(ctrl+z(ctrl+shift+z(ctrl+y(ctrl+c(ctrl+v(ctrl+d(ctrl+g(ctrl+shift+g(ctrl+[(ctrl+]`.split(`(`));function Au(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return ku.has(t)}function ju(e){let t=typeof e.composedPath==`function`?e.composedPath()[0]:e.target;return t instanceof HTMLElement?t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName):!1}var Mu=600,Nu=13,Pu=24,Fu=[`--tcw-toolbar-h`,`--tcw-control-h`,`--tcw-control-h-sm`,`--tcw-icon`,`--tcw-sidebar-w`,`--tcw-menu-item-h`,`--tcw-font-size`,`--tcw-font-size-sm`,`--tcw-font-size-xs`,`--tcw-font-size-lg`,`--tcw-font-size-xl`,`--tcw-font-size-display`],Iu=48,Lu=5e4,Ru=100;function zu(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,Ru);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var Bu=[`#b552c9`,`#1398a8`,`#d4622b`,`#e25592`,`#6f7a8c`,`#3e9a4f`],Vu=864e5,Hu=1e3,Uu={alerts:`alerts`,objectTree:`objectTree`,dataWindow:`dataWindow`,symbolInfo:`symbolInfo`,depthLadder:`depthLadder`},Wu=2,Gu={alerts:`alerts`,objectTree:`objects`,symbolInfo:`symbolInfo`,depthLadder:`trade`};function Ku(e){if(e.ctrlKey||e.metaKey||e.altKey||e.isComposing||e.keyCode===rd||e.getModifierState?.(`AltGraph`))return null;if(/^[a-z]$/i.test(e.key))return e.key;let t=/^Key([A-Z])$/.exec(e.code??``);return t&&[...e.key].length===1&&!/[\s\d]/.test(e.key)?t[1].toLowerCase():null}var qu=4,Ju=1,Yu=7,Xu=17,Zu=3,Qu=150,$u=5e3,ed=8,td=6e4,nd=()=>{let e=document.activeElement;return e instanceof Element&&e.closest(`[role="dialog"], [aria-modal="true"], [role="menu"]`)!==null},rd=229,id=1e3,ad=new Set([...oo,`autoScale`]),od=[[`barCountdown`,`barCountdown`],[`logScale`,`logScale`],[`legendVisible`,`legend`],[`volumeVisible`,`volume`]],sd=[`legendVisible`,`volumeVisible`,`barCountdown`,`indicatorValueLabels`,`alignAxisLabels`],cd=ke.filter(e=>n.CHART_STYLE_KEYS[e]!==`color`),ld=()=>typeof document<`u`&&document.hidden,ud=200;function dd(e){if(!e.feed)return e;if(e.adapter)throw TypeError(`A widget takes an adapter or a feed, not both`);return{...e,adapter:(0,r.adapterFromFeed)(e.feed),feed:void 0}}var fd=class{chart;state;themeOf={dark:n.DARK_THEME,light:n.LIGHT_THEME};toolbar=null;sidebar=null;settings=null;statusBar=null;goToDate=null;tooltip;indicatorLegend=null;legendFrame=0;portal=document.createElement(`div`);stopKeyboardInset=null;stopNarrow=null;stopFormControls=null;overlayHost=()=>{let e=document.fullscreenElement===this.root?this.root:document.body;return this.portal.parentElement!==e&&e.appendChild(this.portal),this.portal};unregisterKeys=()=>{};onFullscreenChange=()=>{this.inlineText?.commit(),this.toolbar?.setFullscreen(document.fullscreenElement===this.root),this.portal.isConnected&&this.overlayHost()};commandPalette=null;symbolSearch=null;dock=null;dockNarrow=null;dockObserver=null;hotkeySheet=null;replayBar=null;dragDrop=null;alertsPanel=null;objectTree=null;indicatorSettings=null;indicatorPicker=null;drawingStyle=null;drawingSettings=null;drawingMenu=null;justDrawnText=null;inlineText=null;inlineTextId=null;inlineTextNew=!1;chartFontWritten=null;cancelTextPrompt=null;clearMenu=null;selectionToolbar=null;selectionToolbarFrame=null;chartMenu=null;menuPane=null;canExport=!0;symbolLoads=new Map;ui;uiScale=1;uiVariables=!1;chartFontBase=null;scaleObserver=null;legendMenu=null;templates=new Wc;templatePrompt=null;chartTemplates=new Po;chartTemplatePrompt=null;drawingTemplatePrompt=null;settingsEdit=null;intervalInput=null;markerTip=null;accountPanel=null;orderTicket=null;accountFrame=0;layoutSession=null;layoutsUI=null;bracketBar=null;alertNotifier=null;depthLadder=null;dataWindow=null;lastHoverIndex=null;lastHoverBar=null;lastHoverPrevClose=null;legendHoverIndex=null;pointerOnChart=!1;favoritesStore=new tl;indicatorFavorites=new tl(`tcw:indicator-favorites`);indicatorDefaults=new ro;timeframeFavorites=new tl(`tcw:tf-favorites`);customTimeframes=new tl(`tcw:tf-custom`);timeframes=[];watchlist=null;watchlistSparkBuffer=new Map;sessionRefPrice=null;hostWatchlistRefPrice=new Map;watchlistInterval=null;watchlistStore=null;watchlistFromSymbols=!1;quoteSource=null;stopQuotes=null;quotedKey=``;quotes=new Map;symbolInfoPanel=null;news=new Ci;marketTimer=null;clockTimer=null;onPageShown=null;chartNav=null;visibleBarCount=50;replayPollInterval=null;replaySpeed=1;replayBarsTotal=null;replayStepTime=null;replayStepsKey=null;replayStep=`auto`;replayStartSeq=0;replayPickTime=null;replayStartPending=!1;replayPlayWanted=!1;replayStepsCache=null;replayShade=null;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;root;chartContainer;loading;historyPill;connectSeq=0;localSeq=0;lastLocalSwitchMs=0;destroyed=!1;options;symbols;symbolCatalog;chartInfoAtSwitch=null;settingsState;settingsDefaults;settingsStore=null;settingsPublished=null;linkSettings=null;settingsListeners=new Set;settingsLocked=new Set;t;adapter=null;boundGlobalKeydown=null;baseSeries=null;baseTimeframeMs=0;builtInZone=void 0;chosenTimeframe=null;rangeSeq=0;rangeQueue=Promise.resolve();compares=[];compareWay=`percent`;comparesLoading=new Set;compareScaleHeld=!1;compareFetchSeq=0;compareOlderBusy=!1;compareOlderAgain=!1;compareOlderPassed=!1;featureState;hostHotkeys=[];hostMenus=new Set;hostLayer=null;priceAxisAddDefault=!1;constructor(i,a={}){let o=dd(a);this.options=o,this.replayStep=o.replayStep??`auto`;let s=Jt(o.symbols??me);this.symbols=s.names,this.symbolCatalog=s.info;let c=o.chartOptions;if(this.settingsState={...he,...c?.crosshair?.mode?{crosshairMode:c.crosshair.mode}:{},...c?.logScale&&c.features?.logScale!==!1?{logScale:!0,scaleMode:`logarithmic`}:{},...c?.numberLocale?{numberLocale:c.numberLocale}:{},...c?.timeZone==null?{}:{timezone:d(c.timeZone)},...c?.leftPriceScale===void 0?{}:{leftPriceScale:c.leftPriceScale},...c?.highLowLines===void 0?{}:{highLowLines:c.highLowLines},...c?.extendedHours===void 0?{}:{extendedHours:c.extendedHours},...c?.chartTypeOptions?{chartTypeOptions:(0,n.readChartTypeOptions)(c.chartTypeOptions)}:{}},this.t=t.n(t.o(o.locale,o.messages)),this.featureState=Ve(o),o.persistLayouts){let e=o.persistLayouts===!0?{}:o.persistLayouts;this.layoutKeyPrefix=e.keyPrefix??`tcw:layout:`,this.layoutDebounceMs=e.debounceMs??1500}let l=To(o.persistSettings);l&&(this.settingsStore=new Do(l));let u=this.resolveIsDark(o.theme),p=this.resolveTheme(o.theme);this.themeOf={...this.themeOf,[u?`dark`:`light`]:p};let m={drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:o.trading!==!1,tradingContextMenu:!1,priceAxisAddButton:this.featureState.alerts||o.trading!==!1||this.featureState.sidebar,volume:!0,legend:!0,crosshair:!0,crosshairTooltip:!1,keyboard:!0,screenshot:!0,alerts:!0,barCountdown:!0,logScale:!0,watermark:!0,...o.chartOptions?.features};this.priceAxisAddDefault=m.priceAxisAddButton===!0;let h={...m,priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]};if(this.canExport=m.dataExport!==!1,this.settingsLocked=new Set(od.filter(([,e])=>m[e]===!1).map(([e])=>e)),this.settingsDefaults={...this.settingsState,legendVisible:m.legend!==!1,volumeVisible:m.volume!==!1,barCountdown:m.barCountdown!==!1,indicatorValueLabels:m.indicatorValueLabels===!0,alignAxisLabels:m.alignAxisLabels!==!1},this.settingsState={...this.settingsDefaults},this.timeframes=Mt(Et(o.timeframes,m.timeframes),this.customTimeframes.list(),m.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let e=Dt(this.timeframes,m.defaultTimeframeFavorites,!!o.timeframes?.length);for(let t of e)this.timeframeFavorites.add(t)}let g=o.timeframe??`5m`,ee=!m.timeframes?.length||m.timeframes.includes(g)?g:this.timeframes[0]??g;this.state={symbol:o.symbol??this.symbols[0]??`BTCUSDT`,timeframe:ee,chartType:o.chartOptions?.chartType??`candlestick`,isDark:u,activeIndicators:new Map,activeTool:null,magnetEnabled:!1,magnetStrong:!1,eraser:!1,zoomArea:!1,stayInDrawing:!1,connectionState:o.adapter?`connecting`:`disconnected`,connectionMessage:o.adapter?this.t(`status.connecting`):``},Qe(),this.root=document.createElement(`div`),this.root.className=`tcw-root`,this.root.dataset.tcwTheme=u?`dark`:`light`;let _=o.dir===`ltr`||o.dir===`rtl`?o.dir:Cd(o.locale)?`rtl`:`ltr`;this.root.dir=_,this.portal.dir=_,i.appendChild(this.root),this.tooltip=new Tl(this.root),this.portal.className=`tcw-root tcw-portal`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.stopKeyboardInset=nl([this.root,this.portal]),this.stopNarrow=rl(this.root,e=>{this.toolbar?.fit(),e||this.sidebar?.closeOverlay(),this.syncRail()}),this.ui=W(o.ui),this.uiVariables=o.ui!==void 0,this.uiScale=this.scaleNow(),this.applyLookTokens(),typeof ResizeObserver<`u`&&(this.scaleObserver=new ResizeObserver(()=>this.fitScale()),this.scaleObserver.observe(this.root)),this.markSwitchedOff(),this.stopFormControls=de([this.root,this.portal],{layer:this.overlayHost,labels:()=>({prevMonth:this.t(`calendar.prevMonth`),nextMonth:this.t(`calendar.nextMonth`),today:this.t(`calendar.today`)}),locale:()=>this.intlLocale()}),this.toolbar=new un(this.root,{symbols:this.symbols,timeframes:this.timeframeMenu(),timeframeFavorites:this.pinnedTimeframes(),chartTypes:o.chartTypes?fe.filter(e=>o.chartTypes.includes(e.value)):fe},{onSymbolClick:()=>this.handleSymbolClick(),onSymbolInfo:()=>this.toggleSymbolInfo(),onTimeframe:e=>this.handleTimeframe(e),onToggleTimeframeFavorite:e=>this.handleToggleTimeframeFavorite(e),onAddTimeframe:e=>this.handleAddTimeframe(e),onRemoveTimeframe:e=>this.handleRemoveTimeframe(e),onChartType:e=>this.handleChartType(e),onIndicators:()=>this.toggleIndicatorPicker(),onScreenshot:()=>this.chart.screenshot(),onSettings:()=>this.openSettings(),onToggleTheme:()=>this.handleToggleTheme(),onToggleReplay:()=>this.toggleReplay(),onToggleAlerts:()=>this.toggleAlerts(),onToggleObjects:()=>this.toggleObjects(),onToggleAccount:o.trading===!1?void 0:()=>this.toggleAccountPanel(),onLayouts:o.layouts===!1?void 0:e=>void this.layoutsUI?.openMenu(e),onBracket:o.trading===!1?void 0:e=>this.startBracket(e),onToggleLadder:o.trading!==!1&&o.depthLadder?()=>this.toggleLadder():void 0,onOrderTicket:o.trading===!1?void 0:()=>this.openOrderTicket(),onCompare:o.adapter&&m.compareSymbols!==!1?()=>this.handleAddCompare():void 0,onUndo:()=>this.chart.undo(),onRedo:()=>this.chart.redo(),onToggleFullscreen:typeof document<`u`&&document.fullscreenEnabled?()=>this.toggleFullscreen():void 0},this.t,this.overlayHost);let v=document.createElement(`div`);v.className=`tcw-body`,o.drawingFavorites&&this.favoritesStore.seedDefaults(o.drawingFavorites),this.sidebar=new yn(v,{drawingToolGroups:yt(pe,this.t),favorites:this.favoritesStore.list(),shortcuts:Ai()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onToggleMagnet:m.drawingMagnet===!1?void 0:()=>this.handleToggleMagnet(),onToggleEraser:()=>this.chart.setEraserMode(!this.chart.isEraserMode()),onToggleZoomArea:()=>this.chart.setZoomAreaMode(!this.chart.isZoomAreaMode()),onToggleFavorite:e=>this.handleToggleFavorite(e),onClear:e=>this.openClearMenu(e),onToggleStyle:()=>this.drawingStyle?.toggle(),onToggleStayInDrawing:()=>this.handleToggleStayInDrawing(),onLockAll:e=>{this.chart.setDrawingsLocked(this.chart.getDrawings().map(e=>e.id),e),this.refreshDrawingsState(),this.refreshObjects()},onHideAll:e=>{this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!e),this.refreshDrawingsState(),this.refreshObjects()}},this.t),this.chartContainer=document.createElement(`div`),this.chartContainer.className=`tcw-chart-container`,this.chartContainer.dir=`ltr`,v.appendChild(this.chartContainer),this.loading=new vu(this.chartContainer,this.t(`status.loading`)),this.historyPill=new bu(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),this.dock=new fl(v,{labels:{rail:this.t(`dock.rail`),resize:this.t(`dock.resize`)},savedWidth:()=>yd(),saveWidth:e=>bd(e),railShown:()=>this.railShown(),focusAfterClose:e=>this.panelFocusTarget(e),room:()=>v.clientWidth}),o.watchlist&&this.createWatchlist(v,o.watchlist===!0?{}:o.watchlist),this.root.appendChild(v);let y=document.createElement(`div`);y.className=`tcw-account-dock`,D(y,`accountPanel`),this.root.appendChild(y),this.chart=new e.c(this.chartContainer,{chartType:this.state.chartType,theme:p,autoScale:!0,crosshair:{mode:`magnet`},a11y:{labels:{role:this.t(`a11y.role`),summary:this.t(`a11y.summary`),empty:this.t(`a11y.empty`),view:this.t(`a11y.view`),bar:this.t(`a11y.bar`),keys:this.t(`a11y.keys`),typeName:e=>{let t=`chartType.${e}`,n=this.t(t);return n===t?e:n}}},...o.chartOptions,features:h}),o.chartOptions?.shapes||this.applyChartShapes(),this.chartInfoAtSwitch=this.chart.getSymbolInfo(),this.applyLegendFont(),this.applyChartLook();for(let[e,t]of this.indicatorDefaults.all())this.chart.setIndicatorDefaults(e,t.style);this.chart.on(`visibleRangeChange`,e=>{let{from:t,to:n}=e.payload;Number.isFinite(t)&&Number.isFinite(n)&&(this.visibleBarCount=Math.max(1,n-t))}),this.chartNav=new Fi(this.chartContainer,{zoomIn:()=>this.chart.zoomIn(),zoomOut:()=>this.chart.zoomOut(),scroll:e=>this.chart.scrollBars(e*Math.max(1,Math.round(this.visibleBarCount/10))),reset:()=>this.resetView(),plotRect:()=>this.chart.getPlotRect()},this.t),this.chart.on(`dataUpdate`,e=>this.handleDataUpdate(e.payload)),this.chart.on(`historyLoad`,e=>{let t=e.payload;this.historyPill.update(t),t.state===`loaded`&&this.extendPercentCompares()}),this.chart.on(`symbolInfoChange`,()=>{this.refreshSymbolTitle(),this.refreshMarket(),this.rebuildForZone(),this.refreshPriceTexts()}),this.chart.on(`marketChange`,()=>this.rebuildForZone()),this.refreshSymbolTitle(),this.symbolInfoPanel=new _i(this.root,this.t,{onClose:()=>this.closePanelByHand(`symbolInfo`),onToggle:e=>{this.toolbar?.setActive(`symbolInfo`,e),e&&(this.refreshSymbolInfo(),this.loadNews())}}),this.marketTimer=setInterval(()=>this.refreshMarket(),3e4),this.onPageShown=()=>{ld()||this.refreshMarket()},document.addEventListener(`visibilitychange`,this.onPageShown),this.dragDrop=new e.o(this.chartContainer,{onData:(e,n,r)=>{this.setData(e);let i=t.r(this.t(`toast.fileLoaded`),{count:n.data.length,file:r.name});this.say(n.skipped>0?`${i} (${t.r(this.t(`toast.fileSkipped`),{count:n.skipped})})`:i)},onError:(e,t)=>{this.say(`${t.name}: ${e.message}`,`error`)}}),this.featureState.dragDropImport&&this.dragDrop.attach(),m.drawingMagnet!==!1&&this.chart.setDrawingMagnetMode(`off`),this.statusBar=new nr(this.root,{presets:r.RANGE_PRESETS,presetLabels:{All:this.t(`range.all`)},groupLabel:this.t(`range.presets`),goToLabel:this.t(`range.goTo`),moreLabel:this.t(`toolbar.more`),onPreset:e=>void this.applyRangePreset(e),onGoTo:()=>this.toggleGoToDate(),goToKeys:()=>this.keysShown(`hotkeys.goToDate`,`Alt+G`)},{label:this.t(`statusBar.label`),clock:{label:this.t(`settings.timezone`),now:()=>this.clockNow(),options:()=>({current:this.settingsState.timezone,list:f(this.settingsState.timezone,Date.now(),this.t(`settings.timezone.local`),this.exchangeChoice())}),onPick:e=>this.changeSettings({timezone:e})},scale:{labels:{group:this.t(`settings.priceScale`),percent:this.t(`settings.scale.percentage`),log:this.t(`settings.scale.logarithmic`),auto:this.t(`settings.autoScale`)},texts:{log:this.t(`statusBar.log`),auto:this.t(`statusBar.auto`)},onPercent:()=>this.toggleScaleMode(`percentage`),onLog:m.logScale===!1?void 0:()=>this.toggleScaleMode(`logarithmic`),onAuto:()=>this.changeSettings({autoScale:!this.chart.isAutoScale()})}}),this.clockTimer=setInterval(()=>{!ld()&&this.featureState.statusBar&&this.featureState[`statusBar.clock`]&&this.statusBar?.tick()},id),this.chart.on(`priceRangeChange`,()=>this.refreshScaleSwitches()),this.refreshScaleSwitches(),this.goToDate=new ll(this.overlayHost,()=>({title:this.t(`goTo.title`),date:this.t(`range.date`),range:this.t(`goTo.range`),from:this.t(`goTo.from`),to:this.t(`goTo.to`),time:this.t(`range.time`),submit:this.t(`range.goToSubmit`),cancel:this.t(`range.cancel`),close:this.t(`common.close`),calendar:{prevMonth:this.t(`calendar.prevMonth`),nextMonth:this.t(`calendar.nextMonth`),today:this.t(`calendar.today`)}}),()=>this.intlLocale(),e=>this.goTo(e)),this.settings=new Wn({onChange:e=>this.changeSettings(e),onReset:()=>this.resetSettings(),onClose:()=>this.endSettingsEdit(!0),onCancel:()=>this.endSettingsEdit(!1),templates:{list:()=>this.chartTemplates.list().map(e=>e.name),apply:e=>this.applyChartTemplate(e),remove:e=>this.chartTemplates.remove(e),save:()=>this.promptSaveChartTemplate()},styleValue:e=>this.chart.getStyleValue?.(e)??null,onStyleChange:e=>this.changeStyle(e)},this.t,{barCountdown:m.barCountdown,logScale:m.logScale,legend:m.legend,volume:m.volume,trading:m.trading!==!1,exchangeZone:()=>this.exchangeChoice()?.zone},this.overlayHost),this.symbolSearch=new Kr({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t),this.hotkeySheet=new Zr({onClose:()=>{}},this.t,this.overlayHost),this.chart.on(`drawingToolChange`,e=>{let t=e.payload.tool;t!==this.state.activeTool&&(this.state={...this.state,activeTool:t},this.updateUI())}),this.chart.on(`toolModeChange`,e=>{let{eraser:t,zoomArea:n}=e.payload;this.state={...this.state,eraser:t??this.state.eraser,zoomArea:n??this.state.zoomArea},this.updateUI()}),this.chart.on(`indicatorAdd`,()=>this.syncIndicatorsFromChart()),this.chart.on(`indicatorRemove`,()=>this.syncIndicatorsFromChart()),this.chart.on(`legendResize`,()=>this.scheduleLegend()),this.chart.setPaneTitlesVisible(!this.featureState.indicatorLegend),this.indicatorLegend=new Il(this.chartContainer,{onToggleVisible:(e,t,n)=>{n===`compare`?this.chart.setCompareVisible(e,t):this.chart.setIndicatorVisible(e,t),this.scheduleLegend(),this.objectTree?.isOpen()&&this.refreshObjects()},onSettings:e=>{this.featureState[`indicatorLegend.settings`]&&this.openIndicatorSettings(e)},onRemove:(e,t)=>{this.isPercentCompare(e)?this.handleRemoveCompare(e):t===`compare`?this.removeHostCompare(e):this.handleRemoveIndicator(e)},onMore:(e,t)=>this.openLegendMenu(e,t),onPaneAction:(e,t)=>this.runPaneAction(e,t),onStackResize:e=>this.chart.setLegendStack?.(e?{width:qu+e.width,height:Ju+e.height}:null)},{show:this.t(`legend.show`),hide:this.t(`legend.hide`),settings:this.t(`legend.settings`),remove:this.t(`legend.remove`),collapse:this.t(`legend.collapse`),expand:this.t(`legend.expand`),more:this.t(`legend.more`),paneUp:this.t(`pane.moveUp`),paneDown:this.t(`pane.moveDown`),paneCollapse:this.t(`pane.collapse`),paneExpand:this.t(`pane.expand`),paneMaximize:this.t(`pane.maximize`),paneRestore:this.t(`pane.restore`),offInterval:this.t(`indicatorSettings.offInterval`),offChartType:this.t(`legend.offChartType`)}),this.legendMenu=new A(this.root,this.t(`legend.more`)),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.pointerOnChart=!0,this.legendHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.scheduleLegend()}),this.chart.on(`crosshairLeave`,()=>{this.pointerOnChart=!1,this.legendHoverIndex=null,this.scheduleLegend()}),this.chart.on(`crosshairSync`,e=>{if(this.pointerOnChart)return;let t=e.payload;this.legendHoverIndex=t.bar&&t.barIndex!==null?t.barIndex:null,this.scheduleLegend()});for(let e of[`indicatorUpdate`,`indicatorChange`,`dataUpdate`,`resize`,`paneResize`,`paneChange`,`themeChange`,`timeframeChange`,`visibleRangeChange`,`compareChange`])this.chart.on(e,()=>this.scheduleLegend());this.chart.on(`chartTypeChange`,()=>{this.compareScaleHeld&&this.showHeldScale(),this.scheduleLegend()}),this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let{barIndex:t,bar:n}=e.payload;if(typeof t==`number`){if(this.seriesPending()){let e=n?.time??this.chart.getData()[t]?.time;this.replayBar.getMode()===`select`&&typeof e==`number`&&(this.replayPickTime=e);return}if(this.replayBar.getMode()===`select`){this.startReplayAt(t,!1,!0);return}this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeekToBar(t),this.replayBar.setState(`paused`)}}),this.chart.on(`crosshairMove`,e=>{if(this.replayBar?.getMode()!==`select`||!this.replayBar.isMounted())return;let t=e.payload.point;this.positionReplayShade(this.seriesPending()?null:t?.x??null)}),this.chart.on(`replayStep`,e=>{let t=e.payload;this.replayBarsTotal=t.total,this.replayStepTime=typeof t.stepTime==`number`?t.stepTime:t.time,queueMicrotask(()=>{this.destroyed||(t.cause===`series`?this.afterReplayCarryOver():this.syncReplayBar())})});for(let e of[`resize`,`dataUpdate`,`symbolInfoChange`])this.chart.on(e,()=>this.placeDrawingButton());this.placeDrawingButton();for(let e of[`resize`,`paneResize`,`paneChange`])this.chart.on(e,()=>this.layoutReplayBar());this.chart.on(`replayStepsLoad`,e=>{e.payload.state===`error`&&this.say(this.t(`replay.stepsFailed`),`error`)}),this.chart.on(`timeframeChange`,()=>this.refreshReplaySteps()),this.dataWindow=new ru(this.root,{formatPrice:e=>this.formatAlertPrice(e),formatPercent:e=>this.formatNumber(e,2),formatVolume:e=>this.formatVolume(e),onClose:()=>this.closePanelByHand(`dataWindow`)},this.t),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.lastHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.lastHoverBar=t.bar??null,this.lastHoverPrevClose=typeof t.prevClose==`number`?t.prevClose:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())}),this.chart.on(`crosshairSync`,e=>{if(this.pointerOnChart)return;let t=e.payload;this.lastHoverIndex=t.bar&&t.barIndex!==null?t.barIndex:null,this.lastHoverBar=t.bar??null,this.lastHoverPrevClose=typeof t.prevClose==`number`?t.prevClose:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())});let b=new zo,x=new Bo;for(let[e,t]of Object.entries(x.all()))this.chart.setDrawingToolDefaults(e,t??null);this.drawingSettings=new Ps(this.root,{onBegin:e=>this.chart.beginDrawingEdit(e),onChange:(e,t)=>this.chart.updateDrawing(e,t),onEnd:(e,t)=>{this.chart.endDrawingEdit(e,{cancel:t}),t&&e===this.justDrawnText&&this.chart.takeBackDrawing(e),this.justDrawnText=null,this.refreshObjects()},toWallTime:e=>Q(e*(0,n.barTimeUnit)(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let r=ol(e,t,this.displayTimezone());return r===null?null:r/(0,n.barTimeUnit)(this.chart.getData())},roundPrice:e=>this.chart.roundPrice(e),priceStep:()=>this.chart.getPriceStep(),onSaveDefault:(e,n)=>{this.chart.setDrawingToolDefaults(e,n),x.set(e,this.chart.getDrawingToolDefaults(e)),this.say(t.r(this.t(`drawingSettings.defaultSaved`),{name:this.drawingToolName(e)}))},templates:{list:e=>b.list(e),save:e=>this.promptSaveDrawingTemplate(b,e),remove:(e,t)=>b.remove(e,t)}},this.t),this.inlineText=new Us(this.overlayHost),this.chart.on(`drawingDoubleClick`,e=>{let t=e.payload.id,n=this.chart.getDrawings().find(e=>e.id===t)?.type;n&&gs[n]&&this.editTextInPlace(t,!1)||this.openDrawingSettings(t,n&&gs[n]?{tab:`text`}:{})}),this.chart.on(`drawingRemove`,e=>{let t=e.payload.id;t===this.inlineTextId&&(this.inlineText?.close(),this.inlineTextNew||this.chart.endDrawingEdit(t),this.inlineTextId=null)}),this.chart.on(`drawingCreate`,e=>{let{id:t,type:n,drawn:r}=e.payload;if(!r||!gs[n])return;this.cancelTextPrompt?.();let i=0,a=()=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,s),clearTimeout(i),this.cancelTextPrompt=null},o=()=>{a(),!(this.destroyed||!this.chart.getDrawings().some(e=>e.id===t))&&(this.editTextInPlace(t,!0)||(this.openDrawingSettings(t,{tab:`text`}),this.drawingSettings?.isOpen()&&(this.justDrawnText=t)))},s=()=>setTimeout(o,0);window.addEventListener(`pointerup`,s),window.addEventListener(`pointercancel`,s),i=window.setTimeout(o,Mu),this.cancelTextPrompt=a}),this.drawingStyle=new Wo(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},b,this.t),this.drawingMenu=new A(this.root,this.t(`drawingMenu.label`)),this.chart.on(`drawingContextMenu`,e=>{let{id:t,x:n,y:r}=e.payload;this.openDrawingMenu(t,n,r)}),this.selectionToolbar=new $o(this.root,{onStyle:e=>{for(let t of this.chart.getSelectedDrawingIds()){let n=this.chart.getDrawings().find(e=>e.id===t)?.type,r=n?gs[n]:void 0,i=e.fillColor!==void 0&&r&&!r.box?{...e,textBackground:!0}:e;this.chart.setSelectedDrawingStyle(i,t)}this.updateSelectionToolbar()},onSettings:()=>{let e=this.chart.getSelectedDrawingIds()[0];e&&this.openDrawingSettings(e)},onAlert:()=>{let e=this.chart.getSelectedDrawingIds()[0];e&&this.addDrawingAlert(e)},onLock:e=>{this.chart.setDrawingsLocked(this.chart.getSelectedDrawingIds(),e),this.refreshObjects(),this.updateSelectionToolbar()},onMore:(e,t)=>{let n=this.chart.getSelectedDrawingIds()[0];if(!n)return;let r=this.chartOffset();this.openDrawingMenu(n,e-r.x,t-r.y)},onDelete:()=>{this.chart.removeDrawings(this.chart.getSelectedDrawingIds()),this.refreshObjects(),this.updateSelectionToolbar()}},this.t);for(let e of[`drawingCreate`,`drawingUpdate`,`drawingRemove`])this.chart.on(e,()=>this.refreshDrawingsState());this.chart.on(`historyChange`,e=>{let{canUndo:t,canRedo:n}=e.payload;this.toolbar?.setHistory(t,n)});for(let e of[`drawingSelect`,`drawingToolChange`,`toolModeChange`])this.chart.on(e,()=>this.updateSelectionToolbar());for(let e of[`drawingUpdate`,`drawingRemove`,`historyChange`,`visibleRangeChange`,`priceRangeChange`,`zoomChange`,`resize`,`paneResize`,`paneChange`,`dataUpdate`,`replayStep`,`chartTypeChange`])this.chart.on(e,()=>this.scheduleSelectionToolbar());if(this.chartMenu=new A(this.root,this.t(`chartMenu.label`),this.t(`common.back`)),this.chart.on(`symbolSeriesRequest`,e=>void this.loadSymbolSeries(e.payload.symbol)),this.chart.on(`chartContextMenu`,e=>{if(!this.featureState[`menu.chart`])return;let{area:t,x:n,y:r,price:i,time:a,pane:o}=e.payload,s=i===void 0?void 0:this.chart.roundPrice(i),c={...this.chartMenuContext(s),...o?{pane:this.chart.getPaneScale(o)}:{}};this.menuPane=o??null,this.openChartMenu(Ye(nc(t,c,this.t),Le,this.featureState),n,r,{area:t,price:s,time:a})}),this.chart.on(`priceAxisAdd`,e=>{if(!this.featureState[`menu.priceAxisAdd`])return;let{price:t,x:n,y:r}=e.payload,i=this.chart.roundPrice(t),a=Ye(Xs(this.chartMenuContext(i),this.t),Le,this.featureState);this.openChartMenu(a,n,r,{area:`priceAxisAdd`,price:i})}),this.chart.on(`signalMarkerHover`,e=>this.showMarkerTip(e.payload)),this.intervalInput=new Uc(this.chartContainer,{title:this.t(`interval.title`),hint:this.t(`interval.hint`),invalid:this.t(`interval.invalid`)},e=>this.selectTypedTimeframe(e)),o.layouts!==!1&&this.setupLayouts(o.layouts===!0||o.layouts===void 0?{}:o.layouts),o.trading!==!1){this.orderTicket=new Mc(this.root,{onSubmit:e=>{this.chart.placeOrderIntent(e),this.say(t.r(this.t(`ticket.sent`),{side:this.t(e.side===`buy`?`ticket.buy`:`ticket.sell`),quantity:e.quantity??1,price:this.formatAlertPrice(e.price)}))},formatPrice:e=>this.formatAlertPrice(e),formatAmount:e=>this.formatMoney(e),formatNumber:(e,t)=>this.formatNumber(e,t)},this.t),this.accountPanel=new vc(y,{onClosePosition:e=>this.chart.closePositionIntent(e),onReversePosition:e=>this.chart.reversePositionIntent(e),onCancelOrder:e=>this.chart.cancelOrderIntent(e),onNewOrder:()=>this.openOrderTicket(),formatPrice:e=>this.formatAlertPrice(e),formatTime:e=>{let{date:t,time:n}=Q(e,this.displayTimezone());return`${t} ${n}`},formatAmount:e=>this.formatMoney(e),formatNumber:(e,t)=>this.formatNumber(e,t),onToggle:e=>{this.toolbar?.setActive(`account`,e),this.refreshAccount()}},this.t);for(let e of[`ordersChange`,`positionsChange`,`executionFill`,`dataUpdate`,`indicatorUpdate`])this.chart.on(e,()=>this.refreshAccountSoon())}if(o.trading!==!1){if(this.bracketBar=new Xl(this.chartContainer,{onConfirm:()=>this.chart.confirmBracket(),onCancel:()=>{this.chart.cancelBracket(),this.bracketBar?.hide()}},this.t),this.chart.on(`bracketPlace`,e=>{let n=e.payload;this.bracketBar?.hide(),this.say(t.r(this.t(n.side===`buy`?`bracket.longPlaced`:`bracket.shortPlaced`),{rr:n.riskReward.toFixed(2)}))}),o.depthLadder){this.depthLadder=new eu(this.root,{onTrade:(e,n)=>{this.chart.placeOrderIntent({side:e,type:`limit`,price:n}),this.say(t.r(this.t(e===`buy`?`order.buyLimit`:`order.sellLimit`),{price:this.formatAlertPrice(n)}))},formatPrice:e=>this.formatAlertPrice(e),priceStep:e=>this.chart.getPriceStep(e),onToggle:e=>this.toolbar?.setActive(`ladder`,e),onClose:()=>this.closePanelByHand(`depthLadder`)},void 0,this.t);let e=this.depthLadder;this.chart.on(`ordersChange`,()=>e.setOrders(this.chart.getOrders()))}this.chart.on(`dataUpdate`,e=>{e.payload.kind===`bracket`&&this.bracketBar?.hide()})}this.alertsPanel=new Wi(this.root,{onClose:()=>this.closePanelByHand(`alerts`),onAdd:({price:e,condition:t,message:n,channel:r,label:i,options:a})=>{try{return this.chart.addAlert(e,t,n,r,i,a),!0}catch{return this.say(this.t(`alerts.invalid`),`error`),!1}},formatTime:e=>{let{date:t,time:n}=Q(e,this.displayTimezone());return`${t} ${n}`},onRemove:e=>this.chart.removeAlert(e),onClear:()=>this.chart.clearAlerts(),getChannelValue:e=>this.getAlertChannelValue(e),formatPrice:e=>this.formatAlertPrice(e)},this.t),this.chart.on(`alertAdd`,()=>this.refreshAlerts()),this.chart.on(`alertRemove`,()=>this.refreshAlerts()),this.chart.on(`alertUpdate`,()=>this.refreshAlerts()),this.chart.on(`alertExpired`,e=>{let n=e.payload;this.refreshAlerts(),this.featureState.alerts&&this.say(t.r(this.t(`alerts.expiredToast`),{text:n.message??this.alertText(n)}))}),o.alertNotifications&&(this.alertNotifier=new Zl(o.alertNotifications)),this.chart.on(`alertTriggered`,e=>{let n=e.payload;if(this.refreshAlerts(),!this.featureState.alerts)return;let r=`${this.alertText(n)}${n.message?` — ${n.message}`:``}`;this.say(t.r(this.t(`alerts.fired`),{text:r}),`info`,`bell`),this.alertNotifier?.notify(r)}),this.indicatorPicker=new Qa(this.overlayHost,{onAdd:e=>this.handleAddIndicator(e),onFavorite:(e,t)=>t?this.indicatorFavorites.add(e):this.indicatorFavorites.remove(e),templates:{onApply:e=>this.applyIndicatorTemplate(e),onDelete:e=>{this.templates.remove(e),this.indicatorPicker?.setTemplates(this.templateNames())},onSave:()=>this.promptSaveIndicatorTemplate()},onClose:()=>this.toolbar?.setIndicatorsOpen(!1)},this.t),this.indicatorSettings=new Ga(this.root,{onApply:(e,t)=>{this.chart.updateIndicator(e,t),this.syncIndicatorsFromChart()},onStyle:(e,t)=>this.chart.updateIndicatorStyle(e,t),onLevels:(e,t)=>this.chart.setIndicatorLevels(e,t),onScale:(e,t)=>this.chart.setIndicatorScale(e,t),onIntervals:(e,t)=>this.chart.setIndicatorIntervals(e,t),onSaveDefault:(e,t)=>this.saveIndicatorDefault(e,t),onClose:()=>this.chart.endIndicatorEdit()},this.t),this.objectTree=new Sa(this.root,{onClose:()=>this.closePanelByHand(`objectTree`),onRemoveIndicator:e=>this.handleRemoveIndicator(e),onConfigureIndicator:e=>this.openIndicatorSettings(e),onToggleIndicatorVisible:(e,t)=>{this.chart.setIndicatorVisible(e,t),this.refreshObjects(),this.scheduleLegend()},onRemoveDrawing:e=>{this.drawingSettings?.editing()===e&&this.drawingSettings.close(!0),this.chart.removeDrawing(e),this.refreshObjects()},onConfigureDrawing:this.drawingSettings?e=>this.openDrawingSettings(e):void 0,onToggleDrawingVisible:(e,t)=>{this.chart.setDrawingVisible(e,t),this.refreshObjects()},onToggleDrawingLocked:(e,t)=>{this.chart.setDrawingLocked(e,t),this.refreshObjects()},onToggleGroupVisible:(e,t)=>{this.chart.setDrawingGroupVisible(e,t),this.refreshObjects()},onToggleGroupLocked:(e,t)=>{this.chart.setDrawingGroupLocked(e,t),this.refreshObjects()},onUngroup:e=>{this.chart.ungroupDrawings(e),this.refreshObjects()},onRenameGroup:(e,t)=>{this.chart.renameDrawingGroup(e,t),this.refreshObjects()},onSelectDrawing:e=>this.chart.selectDrawing(e),onRenameDrawing:(e,t)=>{this.chart.updateDrawing(e,{name:t||null}),this.refreshObjects()},onCloneDrawing:e=>{this.chart.duplicateDrawing(e),this.refreshObjects()},onMoveDrawing:(e,t)=>{this.chart.moveDrawing(e,t),this.refreshObjects()},onAddCompare:m.compareSymbols===!1?void 0:()=>this.handleAddCompare(),onRemoveCompare:e=>this.removeCompared(e)},this.t);let S=()=>{this.objectTree?.isOpen()&&this.refreshObjects()},te=0,C=()=>{te||!this.objectTree?.isOpen()||(te=requestAnimationFrame(()=>{te=0,this.destroyed||S()}))};this.chart.on(`drawingCreate`,S),this.chart.on(`drawingRemove`,S),this.chart.on(`drawingUpdate`,C),this.chart.on(`timeframeChange`,C),this.chart.on(`indicatorAdd`,S),this.chart.on(`indicatorRemove`,S),this.chart.on(`indicatorChange`,S);for(let e of[`indicatorAdd`,`indicatorRemove`,`indicatorChange`])this.chart.on(e,()=>this.refreshCompareDialog());this.setupDock(),this.commandPalette=new fr({onIndicator:e=>this.handleAddIndicator(e),onChartType:e=>this.handleChartType(e),onDrawingTool:e=>this.handleDrawingTool(e),onTimeframe:e=>this.handleTimeframe(e),onAction:e=>this.handleAction(e),onClose:()=>{}},this.overlayHost,this.t,{list:()=>gd(),add:e=>_d([e,...gd().filter(t=>t!==e)])}),this.boundGlobalKeydown=e=>{if(this.handleHostHotkey(e)||this.featureState.hotkeys&&this.replayBar?.isMounted()&&this.handleReplayKey(e))return;let t=X(this.root),n=e=>this.featureState.hotkeys&&this.featureState[e];if((e.ctrlKey||e.metaKey)&&e.key===`k`){if(!t||!n(`hotkeys.commandPalette`)||!this.featureState.commandPalette)return;e.preventDefault(),this.toggleCommandPalette()}else if((e.ctrlKey||e.metaKey)&&(e.key===`p`||e.key===`P`)){if(!t||!n(`hotkeys.symbolSearch`)||!this.featureState.symbolSearch)return;e.preventDefault(),this.openSymbolSearch()}else if((e.ctrlKey||e.metaKey)&&!e.altKey&&!e.shiftKey&&(e.key===`s`||e.key===`S`)){if(!this.layoutSession||!n(`hotkeys.save`)||!this.featureState.layouts||Z()||!X(this.root,!0))return;e.preventDefault(),this.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&ki[e.code]){if(e.defaultPrevented||Z()||!t||nd()||!n(`hotkeys.tools`))return;e.preventDefault(),this.handleDrawingTool(ki[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervalInput||!n(`intervalTyping`)||Z()||nd()||!X(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.intervalInput.open(e.key)}else if(Ku(e)!==null){if(e.defaultPrevented||!n(`symbolTyping`)||!this.featureState.symbolSearch||Z()||nd()||!X(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.openSymbolSearch(Ku(e))}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`||e.code===`KeyR`)){if(Z()||!t)return;if(e.code===`KeyI`){if(!n(`hotkeys.invertScale`))return;e.preventDefault(),this.changeSettings({invertScale:!this.settingsState.invertScale}),this.settings?.refresh(this.shownSettings())}else if(e.code===`KeyR`){if(!n(`hotkeys.resetView`))return;e.preventDefault(),this.resetView()}else this.goToDate&&n(`hotkeys.goToDate`)&&this.featureState.goToDate&&(e.preventDefault(),this.toggleGoToDate())}else if(e.key===`?`&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(Z()||!t||!n(`hotkeys.help`)||!this.featureState.hotkeySheet)return;e.preventDefault(),this.openHotkeySheet()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=Jc(this.root,[this.portal]),this.restoreKeptSettings(),o.adapter?(this.adapter=o.adapter,this.connectStream()):this.chart.setDataTimeframe(this.state.timeframe),this.watchlist&&(this.watchlistInterval=setInterval(()=>this.tickWatchlist(),1e3)),this.markSwitchedOff(),requestAnimationFrame(()=>{this.destroyed||(this.toolbar?.tidy(),this.sidebar?.tidy())}),this.refreshMarket(),this.updateUI(),queueMicrotask(()=>{if(!this.destroyed)try{o.onReady?.(this.chart,this)}finally{this.destroyed||this.restoreSharedView()}})}restoreSharedView(){if(!this.options.shareUrl||typeof location>`u`)return;let e=hu(location.hash);e&&this.importState(e)}setSymbols(e){let t=Jt(e);this.symbols=t.names,this.symbolCatalog=t.info;let n=this.watchlistStore;n&&this.watchlistFromSymbols&&n.replace(n.getLists().map(e=>e.id===`default`?{...e,symbols:t.names}:e)),this.refreshSymbolTitle(),this.refreshSymbolInfo()}symbolEntries(){return this.symbols.map(e=>this.symbolCatalog.get(e)??e)}chartSymbolInfo(){let e=this.chart.getSymbolInfo(),t=e&&e!==this.chartInfoAtSwitch?e:en(this.state.symbol,e);return t?Yt(t,this.state.symbol):null}displayInfo(){return Zt(this.symbolCatalog.get(this.state.symbol),this.chartSymbolInfo())??null}refreshSymbolTitle(){this.toolbar?.setSymbolDescription(tn(this.displayInfo()))}getWatchlists(){return this.watchlistStore?.getLists()??[]}getActiveWatchlist(){return this.watchlistStore?.getActive().id??null}setWatchlists(e,t){this.watchlistFromSymbols=!1,this.watchlistStore?.replace(e,t)}setActiveWatchlist(e){this.watchlistStore?.setActive(e)}addToWatchlist(e,t){this.watchlistStore?.add(e,t)}removeFromWatchlist(e,t){this.watchlistStore?.removeSymbol(e,t)}setQuotes(e){let t=e.map(n.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)}getQuote(e){let t=this.quotes.get(e);return t?{...t}:null}openPanel(e){return!this.hasPanel(e)||!this.dock?!1:(this.dock.open(e),this.dock.current()===e)}hasPanel(e){return e===`watchlist`?this.watchlist!==null:e===`depthLadder`&&this.depthLadder===null?!1:this.featureState[Uu[e]]}closePanel(){this.dock?.close()}getOpenPanel(){return this.dock?.current()??null}toggleSymbolInfo(e){let t=this.symbolInfoPanel;if(!t)return;let n=e??!t.isOpen();n&&!this.featureState.symbolInfo||(n?this.dock?.open(`symbolInfo`):this.dock?.closePage(`symbolInfo`))}refreshMarket(){if(ld())return;let e=(0,n.marketStatus)(this.chart.getSymbolInfo(),Date.now()),t=e.state===`open`;this.statusBar?.setMarket(e.state,this.t(t?`symbolInfo.open`:`symbolInfo.closed`),this.t(t?`statusBar.marketOpen`:`statusBar.marketClosed`)),this.refreshSymbolInfo()}refreshSymbolInfo(){let e=this.symbolInfoPanel;!e?.isOpen()||this.destroyed||e.render(this.symbolInfoView())}symbolInfoView(){let e=this.state.symbol;return Si({symbol:e,info:this.chart.getSymbolInfo(),names:this.displayInfo(),quote:this.quotes.get(e),bars:this.chart.getData(),formatPrice:e=>this.formatAlertPrice(e),t:this.t,textLocale:this.textLocale(),numberLocale:this.intlLocale(),now:Date.now()})}loadNews(){let e=this.symbolInfoPanel;if(!e?.isOpen())return;let t=this.options.adapter,n=this.options.news??(t?.fetchNews?t.fetchNews.bind(t):null);this.news.load(this.state.symbol,n,t=>e.renderNews(t),this.textLocale(),()=>this.destroyed)}intlLocale(){return this.settingsState.numberLocale||this.options.locale||`en`}textLocale(){return this.options.locale||`en`}createWatchlist(e,t){let n=t.persist?xd():null,r=new gi({lists:t.lists,activeList:t.activeList,symbols:this.symbols,defaultName:this.t(`watchlist.title`),storage:n,storageKey:t.storageKey});this.watchlistStore=r,this.watchlistFromSymbols=!t.lists&&!t.persist,this.quoteSource=t.quotes===!1?null:t.quotes??(this.options.adapter?.subscribeQuotes?this.options.adapter:null);let i=e=>this.t(e);this.watchlist=new ai(e,{onSelect:e=>{this.setSymbol(e)},onAdd:()=>this.symbolSearch?.open({symbols:this.symbolEntries(),current:this.state.symbol,currentInfo:this.chartSymbolInfo(),onPick:e=>r.add(e),search:this.symbolSearchFn()}),onRemove:e=>r.removeSymbol(e),onMove:(e,t)=>r.move(e,t),onPickList:e=>r.setActive(e),onCreateList:e=>r.create(e),onRenameList:(e,t)=>r.rename(e,t),onDeleteList:e=>r.remove(e),onClose:()=>this.closePanelByHand(`watchlist`)},{close:i(`common.close`),title:i(`watchlist.title`),lists:i(`watchlist.lists`),newList:i(`watchlist.newList`),rename:i(`watchlist.rename`),deleteList:i(`watchlist.deleteList`),confirmDelete:i(`watchlist.confirmDelete`),add:i(`watchlist.add`),remove:i(`watchlist.remove`),empty:i(`watchlist.empty`),listName:i(`watchlist.listName`)}),this.watchlist.setActive(this.state.symbol),this.watchlist.setLocale(this.settingsState.numberLocale||void 0);let a=()=>{this.watchlist?.setLists(r.getLists(),r.getActive().id),this.followQuotes()};r.subscribe(()=>{a(),t.onChange?.(r.getLists(),r.getActive().id)}),a()}followQuotes(){if(!this.quoteSource||!this.watchlistStore||this.destroyed)return;let e=this.watchlistStore.getActive().symbols,t=[...e].sort().join(`\0`);if(t!==this.quotedKey&&(this.quotedKey=t,this.stopQuotes?.(),this.stopQuotes=null,e.length!==0))try{this.stopQuotes=this.quoteSource.subscribeQuotes(e,e=>{if(this.destroyed||!Array.isArray(e))return;let t=e.map(n.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)})}catch{this.stopQuotes=null}}takeQuotes(e){for(let t of e){let e={...this.quotes.get(t.symbol),...t};this.quotes.set(e.symbol,e);let n=this.watchlistSparkBuffer.get(e.symbol)??[];n.push(e.last),n.length>40&&n.shift(),this.watchlistSparkBuffer.set(e.symbol,n);let r=this.hostWatchlistRefPrice.get(e.symbol);this.watchlist?.setEntry(e.symbol,{lastPrice:e.last,refPrice:r??(e.change===void 0?void 0:e.last-e.change),sparkline:n.slice()})}e.some(e=>e.symbol===this.state.symbol)&&this.refreshSymbolInfo()}async setSymbol(e){this.flushActiveLayout(),e!==this.state.symbol&&(this.chart.clearFills(),this.chartInfoAtSwitch=this.chart.getSymbolInfo()),this.state={...this.state,symbol:e},this.sessionRefPrice=null,this.options.onSymbolChange?.(e),this.updateUI(),this.refreshSymbolTitle(),this.watchlist?.setActive(e),this.refreshMarket(),this.loadNews(),this.layoutSession?.changed(),this.adapter&&await this.connectStream()}setWatchlistEntry(e,t){t.refPrice!==void 0&&this.hostWatchlistRefPrice.set(e,t.refPrice),this.watchlist?.setEntry(e,t)}tickWatchlist(){if(!this.watchlist||this.quotes.has(this.state.symbol)||ld())return;let e=this.chart.getData();if(e.length===0)return;let t=e[e.length-1],n=this.hostWatchlistRefPrice.get(this.state.symbol);n===void 0&&this.sessionRefPrice===null&&(this.sessionRefPrice=e[0].open);let r=this.watchlistSparkBuffer.get(this.state.symbol)??[];r.push(t.close),r.length>40&&r.shift(),this.watchlistSparkBuffer.set(this.state.symbol,r),this.watchlist.setEntry(this.state.symbol,{lastPrice:t.close,refPrice:n??this.sessionRefPrice??e[0].open,sparkline:r.slice()})}async setTimeframe(e){this.chart.isTimeframeAllowed(e)&&(this.chosenTimeframe=e,this.rangeSeq++,await this.switchTimeframe(e))}async switchTimeframe(e){if(this.state={...this.state,timeframe:e},this.options.onTimeframeChange?.(e),this.updateUI(),this.layoutSession?.changed(),this.adapter){await this.connectStream();return}if(this.chart.setDataTimeframe(e),this.options.resampleTimeframes!==!1){if(!this.baseSeries){let e=this.chart.getData();e.length>0&&(this.baseSeries=e,this.baseTimeframeMs=a(e))}await this.switchLocalTimeframe()}}setTheme(e){let t=this.resolveIsDark(e),n=this.resolveTheme(e);this.themeOf={...this.themeOf,[t?`dark`:`light`]:n},this.state={...this.state,isDark:t},this.root.dataset.tcwTheme=t?`dark`:`light`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.keepingLook(()=>this.chart.setTheme(n)),this.updateUI()}getChart(){return this.chart}setUI(e){this.ui=W(e),this.uiVariables=!0,this.uiScale=this.scaleNow(),this.applyLookTokens(),this.applyChartShapes(),this.applyLegendFont(),this.applyChartLook()}scaleNow(){if(this.ui.scale!==`auto`&&this.ui.scale!==void 0)return this.ui.scale;let e=this.root.clientWidth;return e>0?ta(e):1}applyLookTokens(){let e=na(this.ui,this.uiScale);for(let t of[this.root,this.portal]){if(xa(t,e,{variables:this.uiVariables}),this.uiVariables)continue;let n=ba(e);for(let e of Fu)this.uiScale===1?t.style.removeProperty(e):t.style.setProperty(e,n[e])}}fitScale(){if(this.destroyed)return;let e=this.scaleNow();if(e!==this.uiScale){if(this.ui.scale===`auto`){let t=this.root.clientWidth;if((e>this.uiScale?ta(t-Pu):ta(t+Pu))===this.uiScale)return}this.uiScale=e,this.applyLookTokens(),this.applyLegendFont(),this.applyChartLook(),this.toolbar?.fit()}}getUI(){return W({...this.ui})}applyLegendFont(){this.chart.setLegend({fontFamily:this.ui.font.mono,fontSize:ra(Math.round(this.ui.font.size*this.uiScale),-1)})}applyChartLook(){let e=this.ui.density===`airy`,t=this.options.chartOptions;t?.barLayout||this.chart.setBarLayout(e?`golden`:`classic`);let n=this.scaledChartSizes();t?.font?.family?Object.keys(n).length>0&&this.chart.setFont(n):this.chart.setFont({family:this.ui.font.mono,...n})}scaledChartSizes(){let e=this.options.chartOptions?.font;if(e?.sizeSmall!==void 0||e?.sizeMedium!==void 0||e?.sizeLarge!==void 0)return{};let t=this.chart.getFont?.();if(!t)return{};let n={sizeSmall:t.sizeSmall,sizeMedium:t.sizeMedium,sizeLarge:t.sizeLarge},r=this.chartFontWritten;if((!r||r.sizeSmall!==n.sizeSmall||r.sizeMedium!==n.sizeMedium||r.sizeLarge!==n.sizeLarge)&&(this.chartFontBase=n),this.uiScale===1&&!r)return{};let i=this.chartFontBase??n,a=e=>this.uiScale===1?e:Math.round(e*this.uiScale),o={sizeSmall:a(i.sizeSmall),sizeMedium:a(i.sizeMedium),sizeLarge:a(i.sizeLarge)};return this.chartFontWritten=this.uiScale===1?null:o,o}applyChartShapes(){this.chart.setShapes({tagRadius:this.ui.tagRadius})}destroy(){if(!this.destroyed){this.destroyed=!0,this.stopKeyboardInset?.(),this.stopKeyboardInset=null,this.stopNarrow?.(),this.dockObserver?.disconnect(),this.scaleObserver?.disconnect(),this.inlineText?.close(),this.stopNarrow=null,this.stopFormControls?.(),this.stopFormControls=null,this.boundGlobalKeydown&&document.removeEventListener(`keydown`,this.boundGlobalKeydown),document.removeEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys(),this.tooltip.destroy(),this.legendFrame&&cancelAnimationFrame(this.legendFrame),this.indicatorLegend?.destroy(),this.portal.remove(),document.fullscreenElement===this.root&&document.exitFullscreen().catch(()=>{}),this.flushActiveLayout(),this.commandPalette?.destroy(),this.symbolSearch?.destroy(),this.hotkeySheet?.destroy(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayShade?.remove(),this.replayBar?.destroy(),this.dragDrop?.detach(),this.alertsPanel?.destroy(),this.objectTree?.destroy(),this.indicatorSettings?.destroy(),this.indicatorPicker?.destroy(),this.drawingStyle?.destroy(),this.drawingSettings?.destroy(),this.drawingMenu?.destroy(),this.clearMenu?.destroy(),this.cancelTextPrompt?.(),this.selectionToolbar?.destroy(),this.selectionToolbarFrame!==null&&cancelAnimationFrame(this.selectionToolbarFrame),this.chartMenu?.destroy(),this.legendMenu?.destroy();for(let e of this.hostMenus)e.destroy();this.hostMenus.clear(),this.templatePrompt?.destroy(),this.chartTemplatePrompt?.destroy(),this.drawingTemplatePrompt?.destroy(),this.intervalInput?.destroy(),this.markerTip?.remove(),this.layoutSession?.destroy(),this.layoutsUI?.destroy(),this.settingsListeners.clear(),this.accountPanel?.destroy(),this.orderTicket?.destroy(),this.accountFrame&&cancelAnimationFrame(this.accountFrame),this.bracketBar?.destroy(),this.alertNotifier?.destroy(),this.depthLadder?.destroy(),this.dataWindow?.destroy(),this.watchlistInterval&&clearInterval(this.watchlistInterval),this.marketTimer&&clearInterval(this.marketTimer),this.clockTimer&&clearInterval(this.clockTimer),this.onPageShown&&document.removeEventListener(`visibilitychange`,this.onPageShown),this.onPageShown=null,this.chartNav?.destroy(),this.symbolInfoPanel?.destroy(),this.dock?.destroy(),this.stopQuotes?.(),this.stopQuotes=null,this.watchlist?.destroy(),this.toolbar?.destroy(),this.sidebar?.destroy(),this.settings?.destroy(),this.statusBar?.destroy(),this.goToDate?.destroy(),this.loading.destroy(),this.historyPill.destroy(),this.chart.destroy(),this.root.remove(),$e()}}handleSymbolClick(){this.featureState.symbolSearch&&this.openSymbolSearch()}openSymbolSearch(e){this.symbolSearch?.open({symbols:this.symbolEntries(),current:this.state.symbol,currentInfo:this.chartSymbolInfo(),search:this.symbolSearchFn(),query:e,hint:this.sheetKeyOn(`symbolTyping`)?this.t(`symbolSearch.typeHint`):void 0})}symbolSearchFn(){if(this.options.searchSymbols)return this.options.searchSymbols;let e=this.adapter;if(e?.searchSymbols)return(t,n)=>e.searchSymbols(t,{signal:n,limit:50})}handleTimeframe(e){this.setTimeframe(e)}applyRangePreset(e){let t=++this.rangeSeq;return this.rangeQueue=this.rangeQueue.then(()=>this.runRangePreset(e,t)).catch(e=>{this.say(e instanceof Error?e.message:String(e),`error`)}),this.rangeQueue}async runRangePreset(e,t){let n=()=>t===this.rangeSeq&&!this.destroyed;if(!n())return;this.chosenTimeframe??=this.state.timeframe;let r=this.featureState[`statusBar.rangeTimeframe`]?this.timeframeForPreset(e):this.state.timeframe;r!==this.state.timeframe&&(await this.switchTimeframe(r),!n()||this.adapter&&this.state.connectionState===`error`)||this.chart.setVisibleRangePreset(e)}timeframeForPreset(e){let t=this.state.timeframe,i=this.chart.getData();if(i.length<2)return t;let a=(0,n.barTimeUnit)(i),o=i[i.length-1].time*a,s=e===`All`?i[0].time*a:(0,r.rangePresetStart)(e,o,this.displayTimezone());if(s===null)return t;let c=i.length-1;for(;c>0&&i[c-1].time*a>=s;)c--;let l=this.displayTimezone();return Lt({dayShare:i.slice(-ud).some(e=>{let t=e.time*a,r=new Date(t+(0,n.offsetAt)(l,t)*6e4).getUTCDay();return r===0||r===6})?1:5/7,spanMs:o-s,barsInSpan:i.length-c,width:this.chart.getPlotRect().width,current:t,chosen:this.chosenTimeframe??t,available:this.timeframes.filter(e=>this.chart.isTimeframeAllowed(e)&&this.canShowTimeframe(e))})}canShowTimeframe(e){if(this.adapter)return(0,r.servesTimeframe)(this.adapter,e);if(this.options.resampleTimeframes===!1)return!1;let t=this.chart.getData();if(t.length<2)return!1;let i=this.baseSeries?this.baseTimeframeMs:a(t);return!(i>0)||(0,n.timeframeToMs)(e)>=i}toggleFullscreen(){if(document.fullscreenElement===this.root){document.exitFullscreen().catch(()=>{});return}this.root.requestFullscreen().catch(e=>{this.say(e instanceof Error?e.message:this.t(`toast.fullscreenUnavailable`),`error`)})}drawingToolName(e){let t=`tool.${e}`,n=this.t(t);return n===t?this.chart.getDrawingToolDescriptor(e)?.name??e:n}chartOffset(){let e=this.chartContainer.getBoundingClientRect(),t=this.root.getBoundingClientRect();return{x:e.left-t.left,y:e.top-t.top}}scheduleSelectionToolbar(){this.selectionToolbarFrame!==null||!this.selectionToolbar?.isOpen()||(this.selectionToolbarFrame=requestAnimationFrame(()=>{this.selectionToolbarFrame=null,this.updateSelectionToolbar()}))}updateSelectionToolbar(){let e=this.selectionToolbar;if(!e||this.destroyed)return;let t=this.chart.getSelectedDrawingIds();if(!this.featureState.selectionToolbar||!t?.length){e.hide();return}let n=new Set(t),r=this.chart.getDrawings().filter(e=>n.has(e.id)&&this.chart.isDrawingShown(e.id));if(this.chart.getDrawingTool()!==null||this.chart.isEraserMode()||this.chart.isZoomAreaMode()||r.length===0){e.hide();return}let i=this.chartOffset(),a=r[0],o=(a.paneId===void 0?void 0:this.chart.getIndicatorPanes().find(e=>e.instanceId===a.paneId)?.rect)??this.chart.getPlotRect(),s=Sd(r.flatMap(e=>[this.chart.getDrawingRect(e.id),this.chart.getDrawingTextRect?.(e.id)??null]))??{x:o.x+o.width/2,y:o.y,width:0,height:0};e.show({rect:{x:s.x+i.x,y:s.y+i.y,width:s.width,height:s.height},bounds:{x:o.x+i.x,y:o.y+i.y,width:o.width,height:o.height},style:a.style,locked:r.every(e=>e.locked),canDelete:r.some(e=>!e.locked),canSettings:this.drawingSettings!==null&&this.featureState.drawingSettings&&r.length===1,canAlert:this.featureState.alerts&&r.length===1&&this.chart.canAddDrawingAlert(a.id),canFill:this.chart.getDrawingToolDescriptor(a.type)?.fill===!0,canText:this.chart.getDrawingToolDescriptor(a.type)?.text===!0})}editTextInPlace(e,t){if(e===this.inlineTextId&&this.inlineText?.isOpen())return!0;let n=this.chart.getDrawings().find(t=>t.id===e),r=this.inlineText;if(!n||!r||n.locked||!t&&!this.chart.beginDrawingEdit(e))return!1;let i=gs[n.type],a=n.style,o=a.text??``,s=n=>{this.inlineTextId=null,t?n||this.chart.takeBackDrawing(e):this.chart.endDrawingEdit(e,{cancel:!n}),this.refreshObjects()};return r.open({rect:()=>{let t=this.chart.getDrawingTextRect(e);if(!t)return null;let n=this.chartContainer.getBoundingClientRect();return{x:n.left+t.x,y:n.top+t.y,width:t.width,height:t.height}},text:o,font:{size:a.fontSize||i?.fontSize||Nu,bold:a.bold===!0,italic:a.italic===!0,family:this.chart.getFont?.()?.family??this.ui.font.family},color:a.textColor??vs[n.type]??a.color,label:this.t(`drawingSettings.text`),onInput:n=>t?this.chart.amendNewDrawing(e,{style:{text:n}}):this.chart.updateDrawing(e,{style:{text:n}}),onCommit:n=>{let r=n.replace(/\s+$/,``);r&&r!==n&&(t?this.chart.amendNewDrawing(e,{style:{text:r}}):this.chart.updateDrawing(e,{style:{text:r}})),s(r.length>0)},onCancel:()=>s(!1),returnFocus:()=>this.chartContainer.querySelector(`[tabindex]`)??this.chartContainer})?(this.inlineTextId=e,this.inlineTextNew=t,!0):(t||this.chart.endDrawingEdit(e,{cancel:!0}),!1)}openDrawingSettings(e,t={}){let n=this.chart.getDrawings().find(t=>t.id===e),r=n?this.chart.getDrawingToolDescriptor(n.type):null;!n||!r||!this.drawingSettings||!this.featureState.drawingSettings||this.drawingSettings.open({id:e,type:n.type,name:this.drawingToolName(n.type),style:{...n.style},options:this.chart.getDrawingOptions(e),defs:r.options??{},anchors:n.anchors.map(e=>({...e})),fill:r.fill===!0,text:r.text===!0,textLayout:gs[n.type],textColor:vs[n.type],textPlace:_s.has(n.type),coordinates:r.anchoring!==`screen`,intervals:n.intervals??null},t)}promptSaveDrawingTemplate(e,n){this.drawingTemplatePrompt??=new Lc(this.root,this.t),this.drawingTemplatePrompt.open({title:this.t(`drawingSettings.saveTemplateTitle`),submitLabel:this.t(`common.save`),placeholder:this.drawingToolName(n.type),onSubmit:r=>{e.save(r,n.style,{type:n.type,options:n.options}),this.say(t.r(this.t(`templates.saved`),{name:r.trim()}))}})}addDrawingAlert(e){if(!this.featureState.alerts)return;let n=this.chart.getDrawings().find(t=>t.id===e),r=n?this.drawingToolName(n.type):``;this.chart.addDrawingAlert(e,{label:r})&&this.say(t.r(this.t(`drawingSettings.alertAdded`),{name:r}))}openDrawingMenu(e,t,n){if(!this.drawingMenu||!this.featureState[`menu.drawing`])return;let r=new Map(this.chart.getDrawings().map(e=>[e.id,e])),i=this.chart.getSelectedDrawingIds().flatMap(e=>{let t=r.get(e);return t?[{id:t.id,locked:t.locked,groupId:t.group?.id??null}]:[]});if(i.length===0)return;let a=Ye(Ws({selected:i,canConfigure:this.drawingSettings!==null,canAlert:this.chart.canAddDrawingAlert(e)},this.t),Re,this.featureState),o=i.map(e=>e.id),s=r.get(e),c=s?this.options.drawingMenuItems?.({id:e,type:s.type,selected:o})??[]:[],l=Su(a,c);if(l.length===0)return;let u=this.chartContainer.getBoundingClientRect(),d=this.root.getBoundingClientRect();this.drawingMenu.open(l,u.left-d.left+t,u.top-d.top+n,t=>{Cu(t,c)||this.runDrawingMenuAction(e,o,t)})}runDrawingMenuAction(e,t,n){switch(n){case`settings`:this.openDrawingSettings(e);return;case`alert`:this.addDrawingAlert(e);return;case`front`:case`forward`:case`backward`:case`back`:this.chart.moveDrawing(e,n);break;case`group`:this.chart.groupDrawings(t);break;case`ungroup`:{let e=new Set(this.chart.getDrawings().filter(e=>t.includes(e.id)).map(e=>e.group?.id));for(let t of e)t&&this.chart.ungroupDrawings(t);break}case`lock`:case`unlock`:this.chart.setDrawingsLocked(t,n===`lock`);break;case`hide`:this.chart.setDrawingsVisible(t,!1);break;case`duplicate`:this.chart.duplicateDrawing(e);break;case`delete`:{let e=this.drawingSettings?.editing();e&&t.includes(e)&&this.drawingSettings?.close(!0),this.chart.removeDrawings(t);break}}this.objectTree?.isOpen()&&this.refreshObjects()}chartMenuContext(e){let t=this.chart.getDrawings(),n=this.chart.getData(),r=this.settingsState,i=this.chart.getFeatures();return{price:e,lastPrice:n.length>0?n[n.length-1].close:null,formatPrice:e=>this.formatAlertPrice(e),canAlert:this.alertsPanel!==null,canTrade:this.options.trading!==!1,canOrderTicket:this.orderTicket!==null,canDraw:!0,hasDrawings:t.length>0,drawingsHidden:t.length>0&&t.every(e=>!e.visible),canPaste:this.chart.canPasteDrawings(),hasIndicators:i.indicators!==!1&&this.removableIndicators().length>0,canGoToDate:this.goToDate!==null,canExport:this.canExport,autoScale:this.chart.isAutoScale(),scaleMode:this.effectiveScaleMode(),canLog:i.logScale!==!1,inverted:this.chart.isInvertScale(),leftScale:r.leftPriceScale,labels:{values:r.indicatorValueLabels,aligned:r.alignAxisLabels,...i.barCountdown===!1?{}:{countdown:r.barCountdown}},lines:{highLow:r.highLowLines,lastPrice:this.chart.getStyleValue(`lastPrice.visible`)!==!1},timezone:{current:r.timezone,options:this.timezoneChoices()},keys:Object.fromEntries(Ks.filter(e=>this.featureState.hotkeys&&this.featureState[e.feature]).map(e=>[e.action,e.keys]))}}removableIndicators(){return this.chart.getActiveIndicators().filter(e=>!r.SYMBOL_INDICATOR_IDS.has(e.id)).map(e=>e.instanceId)}exchangeChoice(){let e=this.chart.getExchangeTimeZone()??null;if(!(e===null&&!this.adapter?.resolveSymbol))return{label:this.t(`settings.timezone.exchange`),zone:e}}timezoneChoices(){return f(this.settingsState.timezone,Date.now(),this.t(`settings.timezone.local`),this.exchangeChoice()).map(({value:e,label:t})=>({value:e,label:t}))}openChartMenu(e,t,n,r){if(!this.chartMenu)return;let i=this.options.chartMenuItems?.(r)??[],a=Su(e,i);if(a.length===0)return;let o=this.chartContainer.getBoundingClientRect(),s=this.root.getBoundingClientRect();this.chartMenu.open(a,o.left-s.left+t,o.top-s.top+n,e=>{Cu(e,i)||(e.startsWith(`tz:`)?this.changeSettings({timezone:e.slice(3)}):this.runChartMenuAction(e,r))})}setFeatures(e){let t=this.featureState;this.featureState={...t,...Be(e)};let n=e=>t[e]!==this.featureState[e];this.markSwitchedOff(),this.closeSwitchedOff(e=>t[e]&&!this.featureState[e]),n(`selectionToolbar`)&&this.updateSelectionToolbar(),n(`indicatorLegend`)&&(this.chart.setPaneTitlesVisible(!this.featureState.indicatorLegend),this.scheduleLegend()),n(`menu.priceAxisAdd`)&&this.chart.setFeatures({priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]}),n(`dragDropImport`)&&(this.featureState.dragDropImport?this.dragDrop?.attach():this.dragDrop?.detach()),[`toolbar`,`sidebar`,`statusBar`,`accountPanel`].some(n)&&this.chart.resize()}getFeatures(){return{...this.featureState}}isFeatureOn(e){return this.featureState[e]===!0}closeSwitchedOff(e){e(`replay`)&&this.replayBar?.isMounted()&&this.exitReplay();let t=[[`alerts`,()=>this.dock?.closePage(`alerts`)],[`objectTree`,()=>this.dock?.closePage(`objectTree`)],[`symbolInfo`,()=>this.dock?.closePage(`symbolInfo`)],[`dataWindow`,()=>this.dock?.closePage(`dataWindow`)],[`accountPanel`,()=>this.toggleAccountPanel(!1)],[`orderTicket`,()=>this.orderTicket?.close()],[`depthLadder`,()=>this.dock?.closePage(`depthLadder`)],[`goToDate`,()=>this.goToDate?.close()],[`settings`,()=>this.settings?.close()],[`indicatorSettings`,()=>this.indicatorSettings?.close()],[`toolbar.indicators`,()=>this.indicatorPicker?.close()],[`drawingSettings`,()=>this.drawingSettings?.close(!1)],[`sidebar`,()=>this.drawingStyle?.close()],[`commandPalette`,()=>this.commandPalette?.close()],[`hotkeySheet`,()=>this.hotkeySheet?.close()],[`symbolSearch`,()=>this.symbolSearch?.close()],[`compare`,()=>{this.symbolSearch?.isComparing()&&this.symbolSearch.close()}],[`menu.chart`,()=>this.chartMenu?.close()],[`menu.priceAxisAdd`,()=>this.chartMenu?.close()],[`menu.drawing`,()=>this.drawingMenu?.close()],[`indicatorLegend`,()=>this.legendMenu?.close()],[`indicatorLegend.more`,()=>this.legendMenu?.close()]];for(let[n,r]of t)e(n)&&r()}addHotkey(e){let t=Du(e.keys);if(!t)return console.warn(`[ChartWidget] Can't read the shortcut "${e.keys}": modifiers (Ctrl, Alt, Shift) and a key, joined by +.`),null;Au(t)&&console.warn(`[ChartWidget] The chart answers ${e.keys} itself (drawings, scrolling or zoom): both will run.`);let n={spec:e,parsed:t};return this.hostHotkeys=[...this.hostHotkeys,n],{remove:()=>{this.hostHotkeys=this.hostHotkeys.filter(e=>e!==n)}}}handleHostHotkey(e){if(this.hostHotkeys.length===0||!this.featureState.hotkeys||e.isComposing||e.keyCode===rd||e.getModifierState?.(`AltGraph`)||e.defaultPrevented||Z()||ju(e)||nd())return!1;let t=this.hostHotkeys.find(t=>Ou(e,t.parsed));if(!t)return!1;let n=!t.parsed.ctrl&&!t.parsed.alt;if(!X(this.root,n))return!1;let r=document.activeElement;return n&&r&&r!==document.body&&!this.root.contains(r)?!1:(e.preventDefault(),t.spec.onPress(e),!0)}keepingLook(e){this.settingsEdit&&this.settings?.close();let t=this.chart.getOverrides?.({layer:`user`})??{},n=Object.fromEntries(cd.filter(e=>t[e]!==void 0).map(e=>[e,t[e]]));e(),Object.keys(n).length>0&&this.chart.applyOverrides(n,{layer:`user`})}sheetKeyOn(e){let t=this.featureState;if(!t.hotkeys||!t[e])return!1;switch(e){case`hotkeys.commandPalette`:return t.commandPalette;case`hotkeys.symbolSearch`:return t.symbolSearch;case`hotkeys.goToDate`:return t.goToDate;case`hotkeys.save`:return t.layouts&&this.layoutSession!==null;case`hotkeys.help`:return t.hotkeySheet;case`intervalTyping`:return this.intervalInput!==null;case`symbolTyping`:return t.symbolSearch;default:return!0}}markSwitchedOff(){let e=He(this.featureState);for(let t of[this.root,this.portal])e?t.dataset.tcwOff=e:delete t.dataset.tcwOff;this.toolbar?.setSymbolSearch(this.featureState.symbolSearch),this.toolbar?.tidy(),this.sidebar?.tidy(),this.syncRail(),this.statusBar?.fit()}addToolbarButton(e){if(!this.toolbar)return null;let t=this.toolbar,n=t.addHostButton(e);return t.tidy(),{element:n,setActive:t=>dn(n,t,e.toggle===!0),setText:t=>void fn(n,e.label,t),remove:()=>{n.remove(),t.tidy()}}}addToolbarDropdown(e){let t=this.toolbar;if(!t)return null;let n=new A(this.root,e.label);this.hostMenus.add(n);let r=t.addHostButton({id:e.id,label:e.label,icon:e.icon,text:e.text,side:e.side,onClick:r=>{if(n.isOpen()){n.close();return}let i=e.items();if(i.length===0)return;let a=t.menuAnchor(r);n.openUnder(Su([],i),a,e=>Cu(e,i))}});return r.setAttribute(`aria-haspopup`,`menu`),r.setAttribute(`aria-expanded`,`false`),t.tidy(),{element:r,setText:t=>void fn(r,e.label,t),remove:()=>{n.destroy(),this.hostMenus.delete(n),r.remove(),t.tidy()}}}addSidebarButton(e){let t=this.sidebar;if(!t)return null;let n=t.addHostButton(e);return{element:n,setActive:t=>dn(n,t,e.toggle===!0),remove:()=>{n.remove(),t.tidy()}}}addStatusBarItem(e){if(!this.statusBar)return null;let t=this.statusBar.addHostItem(e);return{element:t,setText:n=>{t.textContent=n,e.label&&e.label!==n?t.setAttribute(`aria-label`,`${e.label}: ${n}`):t.removeAttribute(`aria-label`)},remove:()=>t.remove()}}getSlot(e){switch(e){case`toolbar.left`:return this.toolbar?.hostSlot(`left`)??null;case`toolbar.right`:return this.toolbar?.hostSlot(`right`)??null;case`sidebar`:return this.sidebar?.hostSlot()??null;case`statusBar.left`:return this.statusBar?.hostSlot(`left`)??null;case`statusBar.right`:return this.statusBar?.hostSlot(`right`)??null;case`chart`:return this.hostLayer||(this.hostLayer=document.createElement(`div`),this.hostLayer.className=`tcw-host-layer`,this.chartContainer.appendChild(this.hostLayer)),this.hostLayer;default:return null}}runChartMenuAction(e,n){let{price:r}=n,i=r??NaN,a=this.settingsState,o=qs(e);if(o){this.changeSettings({scaleMode:o});return}switch(e){case`alert`:this.chart.addAlert(i,`crossing`),this.say(t.r(this.t(`chartMenu.alertAdded`),{price:this.formatAlertPrice(i)}));break;case`buyLimit`:case`sellLimit`:case`buyStop`:case`sellStop`:this.placeOrderAt(e,i);break;case`orderTicket`:this.openOrderTicket(r);break;case`exportData`:this.chart.exportAllData(`csv`,`${this.state.symbol}-${this.state.timeframe}.csv`.replace(/[^\w.-]+/g,`_`));break;case`paneLog`:case`paneInvert`:case`panePercent`:{let t=this.menuPane;if(!t)break;let n=this.chart.getPaneScale(t);this.chart.setPaneScale(t,e===`paneLog`?{log:!n.log}:e===`paneInvert`?{invert:!n.invert}:{percent:!n.percent});break}case`horizontalLine`:{let e=this.chart.getData();e.length>0&&this.chart.addDrawing({type:`horizontalLine`,anchors:[{time:e[e.length-1].time,price:i}]});break}case`resetView`:this.resetView();break;case`resetPriceScale`:this.changeSettings({autoScale:!0});break;case`paste`:this.chart.pasteDrawings();break;case`removeIndicators`:this.chart.removeIndicators(this.removableIndicators());break;case`hideDrawings`:this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!1);break;case`showDrawings`:this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!0);break;case`removeDrawings`:this.chart.removeDrawings(this.chart.getDrawings().map(e=>e.id));break;case`settings`:this.openSettings(n.area===`priceAxis`?`scales`:void 0);break;case`autoScale`:this.changeSettings({autoScale:!this.chart.isAutoScale()});break;case`invertScale`:this.changeSettings({invertScale:!this.chart.isInvertScale()});break;case`leftScale`:this.changeSettings({leftPriceScale:!a.leftPriceScale});break;case`indicatorValueLabels`:this.changeSettings({indicatorValueLabels:!a.indicatorValueLabels});break;case`alignAxisLabels`:this.changeSettings({alignAxisLabels:!a.alignAxisLabels});break;case`barCountdown`:this.changeSettings({barCountdown:!a.barCountdown});break;case`highLowLines`:this.changeSettings({highLowLines:!a.highLowLines});break;case`lastPriceLine`:this.changeStyle({"lastPrice.visible":this.chart.getStyleValue(`lastPrice.visible`)===!1});break;case`goToDate`:this.toggleGoToDate();break}this.objectTree?.isOpen()&&this.refreshObjects()}toggleAccountPanel(e){let t=this.accountPanel;!t||e===t.isOpen()||!t.isOpen()&&!this.featureState.accountPanel||t.toggle()}openOrderTicket(e){if(!this.featureState.orderTicket)return;let t=this.chart.getData();this.orderTicket?.open({price:e,lastPrice:t.length>0?t[t.length-1].close:null,rules:this.orderRules(),symbol:this.state.symbol,step:e=>this.chart.getPriceStep(e),round:e=>this.chart.roundPrice(e)})}orderRules(){let e=this.chart.getMarket();return e?{roundPrice:e.priceStep!==void 0||(e.priceSteps?.length??0)>0?e=>this.chart.roundPrice(e):void 0,limits:this.chart.getPriceLimits(),lot:e.volumeUnit,multiplier:e.contractMultiplier}:{}}refreshAccountSoon(){this.accountFrame||!this.accountPanel||(this.accountFrame=requestAnimationFrame(()=>{this.accountFrame=0,this.destroyed||this.refreshAccount()}))}refreshAccount(){if(!this.accountPanel)return;let e=this.chart.getData(),t=e.length>0?e[e.length-1].close:null;this.accountPanel.update({positions:this.chart.getPositions(),orders:this.chart.getOrders(),fills:this.chart.getFills(),price:t,realisedPnl:this.chart.getRealisedPnl()}),this.orderTicket?.setLastPrice(t)}placeOrderAt(e,n){let r=e.startsWith(`buy`)?`buy`:`sell`,i=e.endsWith(`Stop`);this.chart.placeOrderIntent(i?{side:r,type:`stop`,price:n,stopPrice:n,quantity:1}:{side:r,type:`limit`,price:n,quantity:1}),this.say(t.r(this.t(`order.${e}`),{price:this.formatAlertPrice(n)}))}clockNow(){let e=Date.now(),t=this.displayTimezone(),r=e=>String(e).padStart(2,`0`),{time:i}=Q(e,t);return{time:`${i}:${r(new Date(e).getUTCSeconds())}`,zone:(0,n.tzLabel)((0,n.offsetAt)(t,e))}}refreshDrawingsState(){let e=this.chart.getDrawings()??[],t=e.length>0;this.sidebar?.setDrawingsState({locked:t&&e.every(e=>e.locked),hidden:t&&e.every(e=>!e.visible)})}refreshScaleSwitches(){this.statusBar?.setScale({mode:this.chart.getScaleMode(),auto:this.chart.isAutoScale()})}toggleScaleMode(e){this.changeSettings({scaleMode:this.chart.getScaleMode()===e?`regular`:e})}displayTimezone(){let e=u(this.settingsState.timezone);return e===`exchange`?this.chart.getEffectiveTimeZone():e}toggleGoToDate(){if(!this.goToDate||!this.featureState.goToDate)return;if(this.goToDate.isOpen()){this.goToDate.close();return}let e=this.chart.getData();if(e.length===0)return;let t=this.displayTimezone(),r=(0,n.barTimeUnit)(e),i=e=>Q(e*r,t),a=e[e.length-1].time,o=this.chart.getVisibleTimeRange()??{from:e[0].time,to:a},s=Q(Date.now(),t).date;this.goToDate.open({date:i(a),range:{from:i(o.from),to:i(o.to)},withTime:!((0,n.timeframeToMs)(this.state.timeframe)>=Vu),max:s,today:s})}goTo(e){let t=this.chart.getData(),r=this.displayTimezone();if(t.length===0)return;let i=(0,n.barTimeUnit)(t);if(e.kind===`date`){let n=ol(e.date,e.time,r);if(n===null)return;this.chart.goToTime(n/i),n/i<t[0].time&&this.say(this.t(`range.beforeData`));return}let a=ol(e.from.date,e.from.time,r),o=ol(e.to.date,e.to.time,r);a===null||o===null||(this.chart.setVisibleRange(a/i,o/i),Math.min(a,o)/i<t[0].time&&this.say(this.t(`range.beforeData`)))}pinnedTimeframes(){let e=this.timeframeFavorites.list();return this.timeframes.filter(t=>e.includes(t))}timeframeMenu(){return this.timeframes.map(e=>({value:e,label:Ct(e),custom:this.customTimeframes.has(e)}))}handleAddTimeframe(e){if(!this.featureState.customTimeframes)return!1;let t=jt(e);return!t||!this.chart.isTimeframeAllowed(t)||this.adapter&&!(0,r.servesTimeframe)(this.adapter,t)||!this.adapter&&(0,n.tickBarCount)(t)!==null?!1:(this.timeframes.includes(t)||(this.customTimeframes.add(t),this.timeframeFavorites.add(t),this.timeframes=Mt(this.timeframes,[t]),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.handleTimeframe(t),!0)}showMarkerTip(e){let{marker:n}=e;if(!n){this.markerTip&&(this.markerTip.hidden=!0);return}this.markerTip||(this.markerTip=document.createElement(`div`),this.markerTip.className=`tcw-marker-tip`,this.markerTip.setAttribute(`role`,`tooltip`),this.chartContainer.appendChild(this.markerTip));let r=n.direction===`long`?this.t(`account.long`):n.direction===`short`?this.t(`account.short`):this.t(`markers.neutral`),i=document.createElement(`strong`);i.textContent=n.label?`${n.label} · ${n.source}`:n.source;let a=document.createElement(`div`);a.textContent=`${r} · ${this.formatAlertPrice(n.price)} · ${t.r(this.t(`markers.confidence`),{pct:Math.round(n.confidence*100)})}`;let o=document.createElement(`div`),{date:s,time:c}=Q(n.time,this.displayTimezone());o.textContent=`${s} ${c}`,this.markerTip.replaceChildren(i,a,o),this.markerTip.hidden=!1;let l=this.chartContainer.getBoundingClientRect(),u=Math.min(e.x+12,Math.max(0,l.width-this.markerTip.offsetWidth-4)),d=Math.max(0,e.y-this.markerTip.offsetHeight-10);this.markerTip.style.left=`${u}px`,this.markerTip.style.top=`${d}px`}selectTypedTimeframe(e){return!this.chart.isTimeframeAllowed(e)||!this.timeframes.includes(e)&&!this.featureState.customTimeframes||this.adapter&&!(0,r.servesTimeframe)(this.adapter,e)?!1:(this.timeframes.includes(e)||(this.customTimeframes.add(e),this.timeframes=Mt(this.timeframes,[e]),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.handleTimeframe(e),!0)}applyIndicatorTemplate(e){if(!this.featureState.indicatorTemplates)return;let n=this.templates.get(e);n&&(this.chart.applyIndicatorSetup(n.indicators),this.syncIndicatorsFromChart(),this.updateUI(),this.say(t.r(this.t(`templates.applied`),{name:n.name})))}promptSaveIndicatorTemplate(){if(this.featureState.indicatorTemplates){if(this.chart.getActiveIndicators().length===0){this.say(this.t(`templates.nothing`),`error`);return}this.templatePrompt??=new Lc(this.root,this.t),this.templatePrompt.open({title:this.t(`templates.saveTitle`),submitLabel:this.t(`common.save`),placeholder:this.t(`templates.namePlaceholder`),onSubmit:e=>{try{this.templates.save(e,this.chart.getIndicatorSetup())}catch(e){throw this.say(this.t(`templates.saveFailed`),`error`),e}this.indicatorPicker?.setTemplates(this.templateNames()),this.say(t.r(this.t(`templates.saved`),{name:e}))}})}}handleRemoveTimeframe(e){this.customTimeframes.has(e)&&(this.customTimeframes.remove(e),this.timeframeFavorites.remove(e),this.timeframes=this.timeframes.filter(t=>t!==e),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes()),this.updateUI())}handleToggleTimeframeFavorite(e){this.timeframeFavorites.toggle(e),this.toolbar?.setTimeframeFavorites(this.pinnedTimeframes()),this.updateUI()}setData(e){this.localSeq++,this.baseSeries=e,this.baseTimeframeMs=a(e),this.applyTimeframeData(),this.adapter||this.loading.end()}async switchLocalTimeframe(){if(!this.baseSeries)return;let e=++this.localSeq,t=this.lastLocalSwitchMs>=Iu||this.baseSeries.length>=Lu;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await zu(),e!==this.localSeq||this.destroyed))return;this.applyTimeframeData()}finally{e===this.localSeq&&this.loading.end()}}applyTimeframeData(){if(!this.baseSeries)return;let e=performance.now(),t=(0,n.timeframeToMs)(this.state.timeframe);if(this.baseTimeframeMs>0&&t>this.baseTimeframeMs){let e=this.chart.getExchangeTimeZone()??null;this.chart.setData(i(this.baseSeries,this.state.timeframe,this.resampleOptions(e))),this.builtInZone=e}else this.chart.setData(this.baseSeries),this.builtInZone=void 0;this.lastLocalSwitchMs=performance.now()-e}resampleOptions(e){return{weekStartsOn:this.options.weekStartsOn??1,timeZone:e??void 0}}rebuildForZone(){if(this.adapter||this.builtInZone===void 0)return;let e=this.chart.getExchangeTimeZone()??null;if(e===this.builtInZone)return;if(!(0,n.timeframeFollowsDays)(this.state.timeframe)){this.builtInZone=e;return}let t=this.timeToKeepInView();this.applyTimeframeData(),t!==null&&this.chart.scrollTo(t)}timeToKeepInView(){if(!this.chart.isTimeAligned())return null;let e=this.chart.getVisibleTimeRange(),t=this.chart.getData();if(!e||t.length<2||e.to>=t[t.length-1].time)return null;let n=t.findIndex(t=>t.time===e.from);return n<0?null:e.from-(t[n+1].time-e.from)/2}handleDataUpdate(e){if(e.kind===`bars`){e.length>0&&this.loading.isActive()&&(this.loading.end(),this.state.connectionState===`error`&&this.setConnectionState(`connected`,this.t(`status.live`)));return}if(e.kind===`error`){this.loading.isActive()&&(this.loading.fail(this.t(`status.connectionFailed`)),this.setConnectionState(`error`,e.error||this.t(`status.connectionFailed`)));return}if(e.kind===`connection`)switch(e.connection.state){case`connected`:this.loading.hasFailed()&&this.loading.end(),!this.loading.isActive()&&this.state.connectionState!==`connected`&&this.setConnectionState(`connected`,this.t(`status.live`));break;case`reconnecting`:this.loading.isActive()||this.setConnectionState(`connecting`,this.t(`status.connecting`));break;case`error`:this.loading.isActive()||this.setConnectionState(`error`,this.t(`status.connectionFailed`));break}}setConnectionState(e,t){this.state={...this.state,connectionState:e,connectionMessage:t},this.updateUI()}toggleLadder(){!this.depthLadder||!this.featureState.depthLadder||this.dock?.toggle(`depthLadder`)}toggleAlerts(){!this.alertsPanel||!this.featureState.alerts||this.dock?.toggle(`alerts`)}handleToggleFavorite(e){let t=this.favoritesStore.toggle(e);this.sidebar?.setFavorites(this.favoritesStore.list()),this.say(t?this.t(`toast.pinned`):this.t(`toast.unpinned`))}exportState(){let e=this.chart.getActiveIndicators().map(e=>({id:e.id,params:e.params})),t=this.getSettings(),n=wo(t,{...he,...Object.fromEntries(sd.map(e=>[e,this.settingsDefaults[e]]))});return fu({v:1,symbol:this.state.symbol,timeframe:this.state.timeframe,chartType:this.state.chartType,scaleMode:t.scaleMode,indicators:e,drawings:this.chart.getDrawings(),...Object.keys(n).length>0?{settings:n}:{}})}showLinkSettings(e){let t=this.getSettings(),n=Object.keys(e),r=this.linkSettings,i={...Object.fromEntries(n.map(e=>[e,t[e]])),...r?.own};this.applySettings(e,!1),this.linkSettings={shown:{...r?.shown,...e},own:i},this.markSettingsTold()}ownSettings(e){let t=this.linkSettings;if(!t)return e;let n=Object.keys(t.shown).filter(n=>JSON.stringify(e[n])===JSON.stringify(t.shown[n]));return{...e,...Object.fromEntries(n.map(e=>[e,t.own[e]]))}}claimSettings(e){let t=this.linkSettings;if(!t)return;let n=new Set(e),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e))),i=r(t.shown);Object.keys(i).length!==Object.keys(t.shown).length&&(this.linkSettings=Object.keys(i).length>0?{shown:i,own:r(t.own)}:null,this.settingsPublished!==null&&!this.destroyed&&this.settingsStore?.save(this.ownSettings(this.getSettings()),this.settingsDefaults))}async importState(e){let t=pu(e);if(!t)return!1;t.symbol&&t.symbol!==this.state.symbol&&await this.setSymbol(t.symbol),t.timeframe&&t.timeframe!==this.state.timeframe&&await this.setTimeframe(t.timeframe),t.chartType&&this.applyChartType(t.chartType);let{chartTypeOptions:n,...r}=this.allowedSettings({scaleMode:t.scaleMode,...G(t.settings,lo)}),i=this.overViewerTypeOptions(t.chartType,n);return this.showLinkSettings(i?{...r,chartTypeOptions:i}:r),this.settings?.refresh(this.shownSettings()),this.chart.applyIndicatorSetup(t.indicators.map((e,t)=>({id:e.id,instanceId:`shared_${t}`,params:e.params}))),this.chart.setDrawings(t.drawings),this.updateUI(),!0}overViewerTypeOptions(e,t){let n={...po(e)?{[e]:{}}:{},...t};if(Object.keys(n).length!==0)return{...this.getSettings().chartTypeOptions,...n}}async copyChartImage(){let e=await this.chart.copyScreenshot();this.say(e?this.t(`toast.imageCopied`):this.t(`toast.imageCopyFailed`),e?`info`:`error`)}async copyShareLink(){let e=gu(typeof location<`u`?location.href:``,this.exportState());try{await navigator.clipboard.writeText(e),this.say(this.t(`toast.linkCopied`))}catch{this.say(this.t(`toast.copyFailed`),`error`)}}setDepth(e){this.chart.setDepthData(e),this.depthLadder?.setData(e),e&&this.chart.pushDepthSnapshot(e)}startBracket(e){this.chart.startBracket(e)&&this.bracketBar?.show(e)}hoveredBar(){let e=this.lastHoverIndex;if(e===null||e<0)return null;if(!this.chart.isTimeAligned()){let e=this.lastHoverBar;return e?{bar:e,prevClose:this.lastHoverPrevClose??e.open}:null}let t=this.chart.getData();return e>=t.length?null:{bar:t[e],prevClose:e>0?t[e-1].close:t[e].open}}buildDataWindowModel(){let e=this.lastHoverIndex,t=this.hoveredBar();if(e===null||!t)return{ohlc:null,change:0,changePct:0,indicators:[]};let{bar:n,prevClose:r}=t,i=n.close-r,a=r===0?0:i/r*100,o=new Set(this.chart.getIndicatorPanes().flatMap(e=>e.instanceIds??[e.instanceId])),s=this.settingsState.numberLocale||`en-US`,c=this.chart.getActiveIndicators().map(t=>{let n=this.chart.getIndicatorOutput(t.instanceId)?.series?.[e]??null,r=!o.has(t.instanceId)&&Td(t),i=t.descriptor.plots?.map(e=>[e.key,e.title])??Object.keys(n??{}).map(e=>[e,e]),a=n?i.filter(([e])=>typeof n[e]==`number`&&Number.isFinite(n[e])).map(([e,t])=>{let i=n[e];return{key:t,value:i,text:this.indicatorValueText(i,r,s)}}):[];return{name:t.descriptor.name,values:a}}).filter(e=>e.values.length>0);return{ohlc:{open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume},change:i,changeText:this.formatAlertPrice(i,n.close),changePct:a,indicators:c}}toggleDataWindow(){!this.dataWindow||!this.featureState.dataWindow||this.dock?.toggle(`dataWindow`)}toggleObjects(){!this.objectTree||!this.featureState.objectTree||this.dock?.toggle(`objectTree`)}setupDock(){let e=this.dock;if(!e)return;if(this.watchlist){let t=this.watchlist;e.addPage({id:`watchlist`,label:this.t(`watchlist.title`),icon:`list`,element:t.element,parts:[`dock.watchlist`],onShow:()=>t.redraw()})}let t=this.alertsPanel;t&&e.addPage({id:`alerts`,label:this.t(`alerts.title`),icon:`bell`,element:t.element,parts:[`dock.alerts`,`alerts`],onShow:()=>{t.openPanel(),this.refreshAlerts(),this.toolbar?.setActive(`alerts`,!0)},onHide:()=>{t.close(),this.toolbar?.setActive(`alerts`,!1)}});let n=this.objectTree;n&&e.addPage({id:`objectTree`,label:this.t(`objects.title`),icon:`layers`,element:n.element,parts:[`dock.objectTree`,`objectTree`],onShow:()=>{n.openPanel(),this.refreshObjects(),this.toolbar?.setActive(`objects`,!0)},onHide:()=>{n.close(),this.toolbar?.setActive(`objects`,!1)}});let r=this.dataWindow;r&&e.addPage({id:`dataWindow`,label:this.t(`dataWindow.title`),icon:`table`,element:r.element,parts:[`dock.dataWindow`,`dataWindow`],onShow:()=>{r.openPanel(),r.render(this.buildDataWindowModel())},onHide:()=>r.close()});let i=this.symbolInfoPanel;i&&e.addPage({id:`symbolInfo`,label:this.t(`symbolInfo.title`),icon:`info`,element:i.element,parts:[`dock.symbolInfo`,`symbolInfo`],onShow:()=>i.open(),onHide:()=>i.close()});let a=this.depthLadder;a&&e.addPage({id:`depthLadder`,label:this.t(`ladder.title`),icon:`ladder`,element:a.element,parts:[`dock.depthLadder`,`depthLadder`],onShow:()=>a.openPanel(),onHide:()=>a.close()}),this.syncRail(),this.fitDockToWidth(),typeof ResizeObserver<`u`&&(this.dockObserver=new ResizeObserver(()=>this.fitDockToWidth()),this.dockObserver.observe(this.root))}fitDockToWidth(){let e=this.dock,t=this.root.clientWidth;if(!e||t===0)return;let n=t<641,r=this.dockNarrow;this.dockNarrow=n,n&&r!==!0&&e.close()}railShown(){return this.featureState.dock&&!this.root.hasAttribute(`data-tcw-narrow`)}syncRail(){this.dock?.syncRail();let e=this.railShown();this.toolbar?.setRailed(`alerts`,e&&this.featureState[`dock.alerts`]),this.toolbar?.setRailed(`objects`,e&&this.featureState[`dock.objectTree`]),this.toolbar?.fit()}panelFocusTarget(e){let t=Gu[e],n=t?this.root.querySelector(`.tcw-toolbar [data-role="${t}"]`):null,r=this.root.hasAttribute(`data-tcw-narrow`);return n&&!n.hidden&&!(r&&n.classList.contains(`tcw-toolbar-overflow`))?n:this.root.querySelector(`.tcw-toolbar-more`)??this.chartContainer}closePanelByHand(e){this.dock?.closePage(e)}openIndicatorSettings(e){if(!this.indicatorSettings||!this.featureState.indicatorSettings)return;let t=this.chart.getActiveIndicators(),n=t.find(t=>t.instanceId===e);if(!n)return;let r=this.chart.getIndicatorStyle(e),i=n.descriptor.placement===`panel`||!!n.pane,a=(this.chart.getIndicatorSetup()??[]).find(t=>t.instanceId===e)?.levels!==void 0;this.chart.beginIndicatorEdit(e),this.indicatorSettings.open({instanceId:e,indicatorId:n.id,name:n.descriptor.name,defaults:n.descriptor.defaultConfig,params:n.params,inputs:n.descriptor.inputs,lineSources:pd(e,t,this.t),plots:n.descriptor.plots,colors:r?.colors,lineWidth:r?.lineWidths[0],plotStyles:r?.plots,intervals:this.chart.getIndicatorIntervals(e)??null,levels:i?this.chart.getIndicatorLevels(e):void 0,defaultLevels:n.descriptor.levels,ownLevels:a,scale:i?void 0:this.chart.getIndicatorScale(e)})}refreshObjects(){if(this.refreshDrawingsState(),!this.objectTree)return;let e=this.chart.getActiveIndicators().map(e=>({instanceId:e.instanceId,name:Ji(e,this.t),title:e.descriptor.name,visible:e.visible})),t=this.chart.getDrawings().map(e=>({id:e.id,label:e.name||Ta(e.type,this.t),visible:e.visible,offInterval:e.visible&&!this.chart.isDrawingShown(e.id),locked:e.locked,group:e.group})),n=this.comparedNow().map(e=>({id:e.id,label:e.symbol,color:e.color,way:e.way}));this.objectTree.setObjects(e,t,n)}async handleAddCompare(){if(this.featureState.compare){if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}this.symbolSearch?.openCompare({symbols:this.symbolEntries(),current:this.state.symbol,search:this.symbolSearchFn(),ways:gl(this.t),way:this.compareWay,compared:this.comparedNow(),onAdd:(e,t)=>{hl(t)&&(this.compareWay=t,this.addCompareSymbol(e,t))},onRemove:e=>this.removeCompared(e)})}}comparedNow(){let e=new Set(this.chart.getIndicatorPanes().flatMap(e=>e.instanceIds));return bl(this.compares,this.chart.getActiveIndicators(),e,this.t)}refreshCompareDialog(){this.symbolSearch?.isComparing()&&this.symbolSearch.setCompared(this.comparedNow())}async addCompareSymbol(e,n=`percent`){if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}if(n!==`percent`){await this.addCompareIndicator(this.adapter,e,n);return}if(this.chart.getFeatures()?.compareSymbols===!1||this.compares.some(t=>t.symbol===e)||this.comparesLoading.has(e))return;let r=`cmp_${e}`;this.comparesLoading.add(e);try{let n=await this.fetchCompareBars(this.adapter,e);if(!n||this.compares.some(t=>t.symbol===e))return;let i=this.state.timeframe,a=Bu[this.compares.length%Bu.length];this.compares.length===0&&this.chart.setCompareMode(`percent`),this.chart.addCompareSymbol(r,e,n,a),this.compares=[...this.compares,{id:r,symbol:e,color:a,bars:n,timeframe:i}],this.compares.length===1&&this.holdCompareScale(!0),this.scheduleLegend(),this.refreshObjects(),this.refreshCompareDialog(),this.say(t.r(this.t(`toast.comparing`),{symbol:e}))}finally{this.comparesLoading.delete(e)}}async addCompareIndicator(e,t,n){let r=await this.fetchCompareBars(e,t);r&&(this.chart.setSymbolSeries(t,r),n===`scale`?this.chart.addIndicator(`compareSymbol`,{symbol:t},`bottom`,{scale:`left`}):n===`pane`?this.chart.addIndicator(`compareSymbolPane`,{symbol:t}):n===`correlation`?this.chart.addIndicator(`correlation`,{symbol:t}):n===`correlationLog`?this.chart.addIndicator(`correlationlog`,{symbol:t}):this.chart.addIndicator(`spread`,{symbol:t,mode:n}))}async fetchCompareBars(e,n){for(;;){let i=this.state.timeframe,a=null,o=null;try{a=await(0,r.withResampling)(e).fetchHistory(n,i,this.compareDepth())}catch(e){o=e}if(this.destroyed)return null;if(i===this.state.timeframe)return a&&a.length>0?a:(o===null?this.say(t.r(this.t(`toast.compareNoBars`),{symbol:n,interval:Ct(i)}),`error`):this.sayCompareFailed(n,o),null)}}sayCompareFailed(e,t){this.say(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}removeCompared(e){this.compares.some(t=>t.id===e)?this.handleRemoveCompare(e):this.chart.removeIndicator(e)}handleRemoveCompare(e){this.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.compares.length===0&&this.holdCompareScale(!1),this.scheduleLegend(),this.refreshObjects(),this.refreshCompareDialog()}removeHostCompare(e){this.chart.removeCompareSymbol(e),this.scheduleLegend()}isPercentCompare(e){return this.compares.some(t=>t.id===e)}compareDepth(){return Math.max(this.chart.getData().length,this.options.historyLimit??500)}holdsPercentScale(){return this.compareScaleHeld&&this.compares.length>0&&this.settingsState.scaleMode===`regular`&&this.chart.isTimeAligned()}effectiveScaleMode(){return this.holdsPercentScale()?`percentage`:this.settingsState.scaleMode}userScaleMode(){return this.holdsPercentScale()?this.settingsState.scaleMode:this.chart.getScaleMode()}shownSettings(){return{...this.settingsState,scaleMode:this.effectiveScaleMode()}}showScaleMode(){let e=this.effectiveScaleMode();this.chart.getScaleMode()!==e&&this.chart.setScaleMode(e)}holdCompareScale(e){e!==this.compareScaleHeld&&(this.compareScaleHeld=e,this.showHeldScale())}showHeldScale(){this.showScaleMode(),this.refreshScaleSwitches(),this.settings?.refresh(this.shownSettings())}async loadSymbolSeries(e){if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}let t=this.state.timeframe,n=(this.symbolLoads.get(e)??0)+1;this.symbolLoads.set(e,n);let i=()=>this.destroyed||t!==this.state.timeframe||this.symbolLoads.get(e)!==n;try{let n=await(0,r.withResampling)(this.adapter).fetchHistory(e,t,this.compareDepth());if(i())return;this.chart.setSymbolSeries(e,n)}catch(t){if(i())return;this.chart.setSymbolSeries(e,this.chart.getSymbolSeries(e)),this.sayCompareFailed(e,t)}}async refetchCompares(){for(let e of this.chart.getRequiredSymbols?.()??[])this.loadSymbolSeries(e);if(!this.adapter||this.compares.length===0)return;let e=this.compares.filter(e=>e.symbol===this.state.symbol);for(let t of e)this.handleRemoveCompare(t.id);await this.refetchPercentCompares()}async refetchPercentCompares(){if(!this.adapter||this.compares.length===0)return;let e=++this.compareFetchSeq,t=(0,r.withResampling)(this.adapter);this.compares=this.compares.map(e=>({...e,failedAt:void 0}));for(let n of this.compares){let r=this.state.timeframe;try{let i=await t.fetchHistory(n.symbol,r,this.compareDepth());if(this.destroyed||e!==this.compareFetchSeq)return;this.isPercentCompare(n.id)&&this.setCompareBars(n.id,i,r)}catch{!this.destroyed&&e===this.compareFetchSeq&&this.compareFailedAt(n.id,r)}}this.compareOlderPassed&&(this.compareOlderPassed=!1,this.extendPercentCompares())}async extendPercentCompares(){if(this.compareOlderBusy){this.compareOlderAgain=!0;return}this.compareOlderBusy=!0;try{do this.compareOlderAgain=!1,await this.fetchOlderCompares();while(this.compareOlderAgain&&!this.destroyed)}finally{this.compareOlderBusy=!1}}async fetchOlderCompares(){if(!this.adapter||this.compares.length===0)return;let e=(0,r.withResampling)(this.adapter),t=this.compareFetchSeq,n=this.state.timeframe;for(let r of this.compares){if(r.timeframe!==n){r.failedAt!==n&&(this.compareOlderPassed=!0);continue}let i=r.bars[0]?.time;if(i===void 0||r.atStart)continue;let a=_l(this.chart.getData(),i);if(a!==0)try{if(e.fetchHistoryBefore){let o=await e.fetchHistoryBefore(r.symbol,n,i,a);if(this.destroyed||t!==this.compareFetchSeq)return;this.prependCompareBars(r.id,o,n)}else{let a=this.compareDepth(),o=await e.fetchHistory(r.symbol,n,a);if(this.destroyed||t!==this.compareFetchSeq)return;this.deepenCompareBars(r.id,o,a,i,n)}}catch{}}}deepenCompareBars(e,t,n,r,i){this.isPercentCompare(e)&&(this.setCompareBars(e,t,i),(t.length<n||!(t[0].time<r))&&(this.compares=this.compares.map(t=>t.id===e?{...t,atStart:!0}:t)))}prependCompareBars(e,t,n){let r=this.compares.find(t=>t.id===e);if(!r)return;let i=vl(r.bars,t);i?this.setCompareBars(e,i,n):this.compares=this.compares.map(t=>t.id===e?{...t,atStart:!0}:t)}setCompareBars(e,t,n){this.chart.updateCompareData(e,t),this.compares=this.compares.map(r=>r.id===e?{...r,bars:t,timeframe:n,atStart:!1,failedAt:void 0}:r)}compareFailedAt(e,t){this.compares=this.compares.map(n=>n.id===e?{...n,failedAt:t}:n)}refreshAlerts(){if(!this.alertsPanel)return;let e=this.buildAlertSources();this.alertsPanel.setSources(e),this.alertsPanel.setAlerts(this.chart.getAlerts().map(t=>this.alertListItem(t,e)))}refreshPriceTexts(){this.refreshAlerts(),this.refreshAccountSoon(),this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())}alertListItem(e,t){return{id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,targetLabel:e.target?t.find(t=>t.channel===e.target)?.label:void 0,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}}alertText(e){return Ii(this.alertListItem(e,this.buildAlertSources()),this.t,e=>this.formatAlertPrice(e),!0)}buildAlertSources(){let e=[{channel:`price`,label:this.t(`alerts.source.price`)}];for(let t of this.chart.getActiveIndicators()){let n=this.chart.getIndicatorOutput(t.instanceId)?.series,r=n&&n.length>0?n[n.length-1]:null,i=r?Object.keys(r).filter(e=>typeof r[e]==`number`):[];for(let n of i){let r=i.length>1?`${t.descriptor.name} ${n}`:t.descriptor.name;e.push({channel:`${t.instanceId}:${n}`,label:r})}}return e}getAlertChannelValue(e){let t=this.chart.getData();if(e===`price`)return t.length>0?this.chart.roundPrice(t[t.length-1].close):null;let n=e.indexOf(`:`);if(n<0||t.length===0)return null;let r=e.slice(0,n),i=e.slice(n+1),a=zl(this.chart.getIndicatorOutput(r)?.series,null)?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}formatMoney(e){return this.formatNumber(e,Math.min((0,n.stepDecimals)(this.chart.getPriceStep()),Wu))}formatVolume(e){return(0,n.formatVolumeLoc)(e,this.settingsState.numberLocale||`en-US`)}formatNumber(e,t){let n=this.settingsState.numberLocale||void 0;return e.toLocaleString(n,{minimumFractionDigits:t,maximumFractionDigits:t})}formatAlertPrice(e,t=e){if(this.chart.getPriceFormatter?.()||this.chartSetsDecimals())return this.chart.formatPrice(e);let n=Math.abs(t),r=n>=1e3?2:n>=1?4:6,i=this.settingsState.numberLocale||void 0;return e.toLocaleString(i,{minimumFractionDigits:2,maximumFractionDigits:r})}indicatorValueText(e,t,n){return t?this.chart.formatPrice(e):Ul(e,n)}chartSetsDecimals(){return this.chart.getMarket?.()?.pricePrecision!=null||this.chart.getSymbolInfo?.()?.pricePrecision!=null}handleChartType(e){let t=this.state.chartType;e!==t&&(this.applyChartType(e),this.chart.recordUndo({subject:`chartType`,undo:()=>this.applyChartType(t),redo:()=>this.applyChartType(e)}))}applyChartType(e){this.state={...this.state,chartType:e},this.chart.setChartType(e),this.settings?.refresh(this.shownSettings(),e),this.updateUI()}handleAddIndicator(e){return this.chart.addIndicator(e,this.indicatorDefaults.get(e)?.params??{})!==null}saveIndicatorDefault(e,n){if(!this.indicatorDefaults.save(e,n)){this.say(this.t(`indicatorSettings.defaultSaveFailed`),`error`);return}this.chart.setIndicatorDefaults(e,n.style);let r=this.chart.getAvailableIndicators()?.find(t=>t.id===e)?.shortName??e.toUpperCase();this.say(t.r(this.t(`indicatorSettings.defaultSaved`),{name:r}))}handleRemoveIndicator(e){this.chart.removeIndicator(e)}toggleCommandPalette(){if(this.commandPalette?.isOpen()){this.commandPalette.close();return}this.featureState.commandPalette&&this.commandPalette?.open(this.buildCommandItems())}buildCommandItems(){let e=[];for(let t of this.indicatorPickerItems())e.push({id:t.id,label:t.name,category:`indicator`,active:[...this.state.activeIndicators.values()].some(e=>e.id===t.id)});for(let t of fe)e.push({id:t.value,label:vt(t,this.t),category:`chartType`,active:this.state.chartType===t.value});let t=Ai();for(let n of yt(pe,this.t))for(let r of n.tools)e.push({id:r.value,label:r.label,category:`drawing`,shortcut:t[r.value]?this.keysShown(`hotkeys.tools`,t[r.value]):void 0,active:this.state.activeTool===r.value});for(let t of this.timeframes)e.push({id:t,label:Ct(t),category:`timeframe`,active:this.state.timeframe===t});return e.push({id:`symbolSearch`,label:this.t(`hotkeys.symbolSearch`),category:`action`,shortcut:this.keysShown(`hotkeys.symbolSearch`,`${rr}+P`)},{id:`compare`,label:this.t(`compare.title`),category:`action`},{id:`goToDate`,label:this.t(`hotkeys.goToDate`),category:`action`,shortcut:this.keysShown(`hotkeys.goToDate`,`Alt+G`)},{id:`resetView`,label:this.t(`chartMenu.resetView`),category:`action`,shortcut:this.keysShown(`hotkeys.resetView`,`Alt+R`)},{id:`invertScale`,label:this.t(`hotkeys.invertScale`),category:`action`,shortcut:this.keysShown(`hotkeys.invertScale`,`Alt+I`)},{id:`saveLayout`,label:this.t(`hotkeys.saveLayout`),category:`action`,shortcut:this.keysShown(`hotkeys.save`,`${rr}+S`)},{id:`watchlist`,label:this.t(`watchlist.title`),category:`action`},{id:`alerts`,label:this.t(`alerts.title`),category:`action`},{id:`objectTree`,label:this.t(`objects.title`),category:`action`},{id:`dataWindow`,label:this.t(`action.dataWindow`),category:`action`},{id:`symbolInfo`,label:this.t(`action.symbolInfo`),category:`action`},{id:`screenshot`,label:this.t(`action.screenshot`),category:`action`},{id:`copyImage`,label:this.t(`action.copyImage`),category:`action`},{id:`shareView`,label:this.t(`action.shareView`),category:`action`},{id:`toggleTheme`,label:this.t(`action.toggleTheme`),category:`action`},{id:`settings`,label:this.t(`action.settings`),category:`action`},{id:`autoFib`,label:this.t(`action.autoFib`),category:`action`},{id:`clearDrawings`,label:this.t(`action.clearDrawings`),category:`action`},{id:`clearIndicators`,label:this.t(`clear.indicators`),category:`action`},{id:`clearAll`,label:this.t(`clear.all`),category:`action`},{id:`hotkeys`,label:this.t(`hotkeys.title`),category:`action`,shortcut:this.keysShown(`hotkeys.help`,`?`)}),e.filter(e=>e.category!==`action`||this.commandOn(e.id)&&this.commandThere(e.id))}commandThere(e){return e===`watchlist`?this.watchlist!==null:e===`compare`?this.adapter!==null&&this.options.chartOptions?.features?.compareSymbols!==!1:e===`saveLayout`?this.layoutSession!==null:!0}keysShown(e,t){if(this.sheetKeyOn(e))return this.hostHotkeys.some(e=>e.parsed.display.join(`+`).toLowerCase()===t.toLowerCase())?void 0:t}openHotkeySheet(){this.hotkeySheet?.open({isOn:e=>this.sheetKeyOn(e),extra:this.hostHotkeys.map(e=>({keys:e.parsed.display,text:e.spec.label}))})}commandOn(e){let t=qe(e);return t===void 0||this.featureState[t]}openClearMenu(e){if(A.closeAnchoredTo(e))return;let t=this.chart.getDrawings().filter(e=>!e.locked).length,n=this.chart.getActiveIndicators().length,r=[];t>0&&r.push({id:`drawings`,label:this.t(`clear.drawings`),icon:`penLine`,count:t}),n>0&&r.push({id:`indicators`,label:this.t(`clear.indicators`),icon:`trendingUp`,count:n}),t>0&&n>0&&r.push(`separator`,{id:`all`,label:this.t(`clear.all`),icon:`trash`,danger:!0}),r.length!==0&&(this.clearMenu??=new A(this.root,this.t(`drawing.clearAll`)),this.clearMenu.openBeside(r,e,e=>this.removeAll(e)))}removeAll(e){this.chart.removeAll(e),this.state={...this.state,activeTool:null},this.updateUI(),this.refreshDrawingsState(),this.refreshObjects()}handleAction(e){if(this.commandOn(e))switch(e){case`symbolSearch`:this.openSymbolSearch();break;case`compare`:this.handleAddCompare();break;case`goToDate`:this.toggleGoToDate();break;case`resetView`:this.resetView();break;case`invertScale`:this.changeSettings({invertScale:!this.settingsState.invertScale}),this.settings?.refresh(this.shownSettings());break;case`saveLayout`:this.saveLayout();break;case`watchlist`:case`alerts`:case`objectTree`:this.openPanel(e);break;case`hotkeys`:this.openHotkeySheet();break;case`screenshot`:this.chart.screenshot();break;case`toggleTheme`:this.handleToggleTheme();break;case`settings`:this.openSettings();break;case`copyImage`:this.copyChartImage();break;case`shareView`:this.copyShareLink();break;case`autoFib`:{let e=this.chart.autoFib();this.say(e?this.t(`toast.autoFibAdded`):this.t(`toast.noSwing`));break}case`dataWindow`:this.toggleDataWindow();break;case`symbolInfo`:this.toggleSymbolInfo();break;case`clearDrawings`:this.removeAll(`drawings`);break;case`clearIndicators`:this.removeAll(`indicators`);break;case`clearAll`:this.removeAll(`all`);break}}handleDrawingTool(e){this.state={...this.state,activeTool:e},this.chart.setDrawingTool(e),this.updateUI()}handleCancelDrawing(){this.state={...this.state,activeTool:null},this.chart.setDrawingTool(null),this.chart.setEraserMode(!1),this.chart.setZoomAreaMode(!1),this.updateUI()}handleToggleStayInDrawing(){let e=!this.state.stayInDrawing;this.state={...this.state,stayInDrawing:e},this.chart.setStayInDrawingMode(e),this.updateUI()}handleToggleMagnet(){let e=this.state.magnetEnabled?this.state.magnetStrong?`off`:`strong`:`weak`;this.state={...this.state,magnetEnabled:e!==`off`,magnetStrong:e===`strong`},this.chart.setDrawingMagnetMode(e),this.updateUI()}handleToggleTheme(){if(!this.featureState.themeToggle)return;let e=!this.state.isDark;this.state={...this.state,isDark:e},this.root.dataset.tcwTheme=e?`dark`:`light`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.keepingLook(()=>this.chart.setTheme(e?this.themeOf.dark:this.themeOf.light)),this.chart.setWatermark(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:48,color:e?`rgba(255,255,255,0.03)`:`rgba(0,0,0,0.03)`}),this.updateUI()}openSettings(e){!this.featureState.settings||this.settings?.isOpen()||(this.syncSettingsFromChart(),this.markSettingsTold(),this.settingsEdit={settings:{...this.settingsState},style:this.settingsStyle(),keys:new Set,styleKeys:new Set,held:this.compareScaleHeld},this.settings?.open(this.shownSettings(),this.state.chartType,e))}resetView(){this.chart.fitContent(),this.changeSettings({autoScale:!0}),this.settings?.refresh(this.shownSettings())}endSettingsEdit(e){let t=this.settingsEdit;if(this.settingsEdit=null,!t)return;let n=[...t.keys],r=e=>Object.fromEntries(n.map(t=>[t,e[t]])),i=[...t.styleKeys],a=r(t.settings),o=i.length>0?{theme:t.style.theme,overrides:Object.fromEntries(i.map(e=>[e,t.style.overrides[e]??null]))}:null,s=t.keys.has(`scaleMode`),c=this.compareScaleHeld;if(!e){this.restoreSettings(a,o,s?t.held:void 0);return}let l=r(this.getSettings()),u=i.length>0?this.settingsStyle(i):null;(JSON.stringify([a,o])!==JSON.stringify([l,u])||s&&t.held!==c)&&this.chart.recordUndo({undo:()=>this.restoreSettings(a,o,s?t.held:void 0),redo:()=>this.restoreSettings(l,u,s?c:void 0)}),this.claimSettings(n),this.publishSettings()}touchSettings(e,t=[]){if(!this.settingsEdit){this.claimSettings(e);return}for(let t of e)this.settingsEdit.keys.add(t);for(let e of t)this.settingsEdit.styleKeys.add(e)}applyChartTemplate(e){let n=this.chartTemplates.get(e);if(!n)return;let r=this.allowedSettings(n.settings);this.touchSettings(Object.keys(r),ke),this.applySettings(r),this.chart.resetOverrides([...ke],{layer:`user`}),this.chart.applyOverrides(n.style,{layer:`user`}),this.settings?.refresh(this.shownSettings()),this.say(t.r(this.t(`templates.applied`),{name:e}))}promptSaveChartTemplate(){this.chartTemplatePrompt??=new Lc(this.overlayHost(),this.t),this.chartTemplatePrompt.open({title:this.t(`settings.saveTemplateTitle`),submitLabel:this.t(`common.save`),placeholder:this.t(`settings.templatePlaceholder`),onSubmit:e=>{if(!this.chartTemplates.save(e,this.settingsState,this.settingsStyle().overrides))throw this.say(this.t(`templates.saveFailed`),`error`),Error(`The template could not be saved`);this.say(t.r(this.t(`templates.saved`),{name:e}))}})}toast(e,t=`info`,n){let r=document.createElement(`div`);r.className=`tcw-toast ${t===`error`?`tcw-toast-error`:``}`,r.setAttribute(`role`,t===`error`?`alert`:`status`);let i=n?O(n,14):``;if(i){let e=document.createElement(`span`);e.className=`tcw-toast-icon`,e.innerHTML=i,r.appendChild(e)}r.appendChild(document.createTextNode(e));let a=e=>e.querySelector(`.tcw-modal-backdrop:not([hidden])`)!==null,o=a(this.portal)?this.portal:this.root;r.classList.toggle(`tcw-toast-over`,o===this.portal||a(this.root)),o.appendChild(r),requestAnimationFrame(()=>r.classList.add(`tcw-toast-in`)),setTimeout(()=>{r.classList.remove(`tcw-toast-in`),r.addEventListener(`transitionend`,()=>r.remove(),{once:!0}),setTimeout(()=>r.remove(),400)},3500)}say(e,t=`info`,n){(this.featureState.toasts||t===`error`)&&this.toast(e,t,n)}getLayoutSession(){return this.layoutSession}getSymbol(){return this.state.symbol}getTimeframe(){return this.state.timeframe}captureLayout(){let e=this.getSettings(),t=this.chart.saveState(),n=t?$c(t):null,r=n&&typeof n==`object`?Zc(n):null;return{v:1,symbol:this.state.symbol,timeframe:this.chosenTimeframe??this.state.timeframe,scaleMode:e.scaleMode,invertScale:e.invertScale,chart:r,settings:So(e,co)}}async restoreLayout(e){if(e.symbol!==this.state.symbol&&await this.setSymbol(e.symbol),e.timeframe!==this.state.timeframe&&await this.setTimeframe(e.timeframe),this.destroyed)return;if(e.chart){this.chart.loadState(JSON.stringify(Zc(e.chart)));let t=e.chart.chartType;typeof t==`string`&&(this.state={...this.state,chartType:t})}let t=this.allowedSettings({scaleMode:e.scaleMode,invertScale:e.invertScale,...G(e.settings,co)});this.claimSettings(Object.keys(t)),this.applySettings(t),this.syncIndicatorsFromChart(),this.updateUI(),this.settings?.refresh(this.shownSettings(),this.state.chartType)}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=Qc($c(e));return t?(await this.restoreLayout(t),!0):!1}getSettings(){return this.syncSettingsFromChart(),JSON.parse(JSON.stringify(this.settingsState))}setSettings(e){let t=this.allowedSettings(this.withoutEarlyFreeze(G(e)));this.claimSettings(Object.keys(t)),this.applySettings(t),this.settings?.refresh(this.shownSettings())}withoutEarlyFreeze(e){return e.autoScale!==!1||this.chart.getData().length>0?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==`autoScale`))}onSettingsChange(e){return this.settingsListeners.add(e),()=>{this.settingsListeners.delete(e)}}syncSettingsFromChart(){let e=this.chart,t=e.getTimeZone?.(),n=e.getMarketProfileConfig?.(),r=e.getPivotMarkersConfig?.(),i=this.allowedSettings(G({gridVisible:e.isGridVisible?.(),volumeVisible:e.isVolumeVisible?.(),legendVisible:e.isLegendVisible?.(),barCountdown:e.isBarCountdownVisible?.(),indicatorValueLabels:e.isIndicatorValueLabelsVisible?.(),alignAxisLabels:e.isAxisLabelsAligned?.(),leftPriceScale:e.isLeftPriceScaleVisible?.(),volumeProfileVisible:e.isVolumeProfileVisible?.(),marketProfileVisible:e.isMarketProfileVisible?.(),marketProfileSplit:n?.splitBySession,marketProfileLetters:n?.letters,marketProfileBuckets:n?.buckets,marketProfileOpacity:n?.opacity,depthHeatmapVisible:e.isDepthHeatmapVisible?.(),depthHeatmapOpacity:e.getDepthHeatmapConfig?.()?.opacity,pivotMarkersVisible:e.isPivotMarkersVisible?.(),pivotStrength:r?.left,pivotStructureLabels:r?.structureLabels,sessionShadingVisible:e.isSessionShadingVisible?.(),periodLevelsVisible:e.isPeriodLevelsVisible?.(),periodLevelsPeriod:e.getPeriodLevelsPeriod?.(),crosshairMode:e.getCrosshairMode?.(),scaleMode:this.userScaleMode(),autoScale:e.isAutoScale?.(),invertScale:e.isInvertScale?.(),timezone:t===void 0?void 0:d(t),numberLocale:e.getNumberLocale?.(),highLowLines:e.isHighLowLinesVisible?.(),extendedHours:e.isExtendedHoursVisible?.(),mainSeriesVisible:e.isMainSeriesVisible?.(),chartTypeOptions:e.getChartTypeOptions?.()})),a=i.scaleMode?{logScale:i.scaleMode===`logarithmic`}:{},o=i.chartTypeOptions?{chartTypeOptions:mo(i.chartTypeOptions)}:{};this.settingsState={...this.settingsState,...i,...a,...o}}allowedSettings(e){let t=this.settingsLocked,n=(e,n)=>e===`scaleMode`?n===`logarithmic`&&t.has(`logScale`):n===!0&&t.has(e);return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0&&!n(e,t)))}restoreKeptSettings(){let e=this.allowedSettings(this.settingsStore?.load()??{});Object.keys(e).length>0&&this.applySettings(e),this.settingsPublished=JSON.stringify(this.getSettings())}markSettingsTold(){this.settingsPublished!==null&&(this.settingsPublished=JSON.stringify(this.getSettings()))}publishSettings(){if(this.settingsPublished===null||this.destroyed)return;let e=this.getSettings(),t=JSON.stringify(e);if(t!==this.settingsPublished){this.settingsPublished=t,this.settingsStore?.save(this.ownSettings(e),this.settingsDefaults);for(let e of[...this.settingsListeners])try{e(JSON.parse(t))}catch(e){console.error(`[TradeCanvas] An onSettingsChange listener threw:`,e)}}}setupLayouts(t){let n=new e.t(t.storage??e.i(),{capture:()=>({content:this.getLayoutContent(),symbol:this.state.symbol,timeframe:this.chosenTimeframe??this.state.timeframe}),apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a widget layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,onChange:()=>this.toolbar?.setLayout(n.current()?.name??null,n.isDirty()),onError:()=>this.say(this.t(`layouts.saveFailed`),`error`)});this.layoutSession=n,this.layoutsUI=new Vc(n,{root:this.root,t:this.t,saveKeys:()=>this.keysShown(`hotkeys.save`,`${rr}+S`),toast:(e,t)=>this.say(e,t),formatTime:e=>{let{date:t,time:n}=Q(e,this.displayTimezone());return`${t} ${n}`}}),this.chart.on(`stateChange`,()=>n.changed()),t.openLast&&n.list().then(([e])=>e&&!this.destroyed?this.openLayout(e.id):void 0,()=>void 0)}async saveLayout(){await this.layoutsUI?.save()}async openLayout(e){return await this.layoutsUI?.open(e)??!1}clearSavedLayout(e){if(!this.layoutKeyPrefix)return;let t=e??this.state.symbol;try{localStorage.removeItem(this.layoutKeyPrefix+t)}catch{}}applySymbolLayout(e){if(!this.layoutKeyPrefix)return;let t=this.layoutKeyPrefix+e;this.activeLayoutKey=t;try{this.chart.loadStateFromStorage(t)&&this.syncIndicatorsFromChart()}catch{}this.chart.setAutoSave(t,this.layoutDebounceMs)}flushActiveLayout(){if(this.activeLayoutKey){try{this.chart.saveState(this.activeLayoutKey)}catch{}this.chart.disableAutoSave(),this.activeLayoutKey=null}}syncIndicatorsFromChart(){let e=new Map;for(let t of this.chart.getActiveIndicators())e.set(t.instanceId,{id:t.id,label:Ji(t,this.t)});this.state={...this.state,activeIndicators:e},this.updateUI(),this.indicatorPicker?.setCounts(this.indicatorCounts())}toggleIndicatorPicker(){if(this.indicatorPicker?.isOpen()){this.indicatorPicker.close();return}!this.indicatorPicker||!this.featureState[`toolbar.indicators`]||(this.indicatorPicker.open({items:this.indicatorPickerItems(),favorites:this.indicatorFavorites.list(),templates:this.featureState.indicatorTemplates?this.templateNames():null,counts:this.indicatorCounts()}),this.toolbar?.setIndicatorsOpen(!0))}indicatorPickerItems(){return(this.chart.getAvailableIndicators()??[]).filter(e=>!r.SYMBOL_INDICATOR_IDS.has(e.id)&&this.chart.isIndicatorAllowed(e.id)!==!1).map(e=>({id:e.id,name:e.name,shortName:e.shortName??e.id.toUpperCase(),placement:e.placement===`panel`?`panel`:`overlay`,category:(0,r.indicatorCategory)(e)}))}indicatorCounts(){let e=new Map;for(let{id:t}of this.state.activeIndicators.values())e.set(t,(e.get(t)??0)+1);return e}templateNames(){return this.templates.list().map(e=>e.name)}toggleReplay(){this.replayBar?.isMounted()?this.exitReplay():this.featureState.replay&&this.enterReplay()}enterReplay(){if(this.replayTotal()<2)return;let e=this.t;this.replayBar=new ii({onPlay:()=>{if(this.replayBar?.getMode()===`select`){this.seriesPending()||this.startReplayAt(Math.max(1,this.replayTotal()-100),!0);return}this.replayStartPending?this.replayPlayWanted=!0:this.chart.getReplayState()===`paused`&&this.chart.replayResume(),this.syncReplayBar()},onPause:()=>{this.replayPlayWanted=!1,this.chart.replayPause(),this.syncReplayBar()},onStepBack:()=>this.stepReplay(-1),onStepForward:()=>this.stepReplay(1),onSeek:e=>{this.seriesPending()||(this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(e),this.replayBar?.setState(`paused`))},onSpeedChange:e=>{this.replaySpeed=e,this.chart.setReplaySpeed(e)},onRandomStart:()=>{if(this.seriesPending())return;let e=this.replayBarCount(),t=Math.max(1,Math.floor(e*.1)),n=Math.max(t,Math.floor(e*.9));this.startReplayAt(t+Math.floor(Math.random()*(n-t+1)),!1,!0)},onClose:()=>this.exitReplay(),onSelectBar:()=>this.pickReplayBarAgain(),onCancelPick:()=>this.cancelReplayPick(),onStepChange:e=>{if(this.replayStep=e,this.replayBar?.getMode()!==`replay`)return;let t=this.chart.getReplayState()===`playing`;this.startReplayAt(Math.max(0,this.chart.getReplayBarIndex()-1),t)}},{selectHint:e(`replay.selectHint`),loading:e(`status.loading`),random:e(`replay.random`),realtime:e(`replay.realtime`),play:e(`replay.play`),pause:e(`replay.pause`),stepBack:e(`replay.stepBack`),stepForward:e(`replay.stepForward`),replay:e(`replay.label`),position:e(`replay.position`),speed:e(`replay.speed`),step:e(`replay.step`),selectBar:e(`replay.selectBar`),cancel:e(`common.cancel`),rate:e(`replay.rate`),rateHint:e(`replay.rateHint`),playingAt:e(`replay.playingAt`),pausedAt:e(`replay.pausedAt`),endedAt:e(`replay.endedAt`)});let n=this.replayStepMenu();this.replayBar.mount(this.chartContainer,{total:this.replayTotal(),rate:this.replaySpeed,mode:`select`,steps:n,step:this.replayStep,dir:this.root.dir===`rtl`?`rtl`:`ltr`,formatRate:n=>t.r(e(`replay.rate`),{rate:n.toLocaleString(this.intlLocale())})}),this.watchReplayBar(),this.toolbar?.setActive(`replay`,!0),this.root.setAttribute(`data-tcw-replay`,``),this.showReplayShade(),this.layoutReplayBar()}showReplayShade(){this.replayShade||(this.replayShade=document.createElement(`div`),this.replayShade.className=`tcw-replay-shade`,this.replayShade.hidden=!0,this.chartContainer.appendChild(this.replayShade),this.chartContainer.addEventListener(`mouseleave`,this.hideReplayShade))}removeReplayShade(){this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade)}pickReplayBarAgain(){let e=this.replayBar;!e?.isMounted()||this.seriesPending()||(this.replayPlayWanted=!1,this.chart.getReplayState()===`playing`&&this.chart.replayPause(),e.setState(`paused`),e.setMode(`select`),this.showReplayShade(),this.layoutReplayBar())}cancelReplayPick(){let e=this.replayBar;if(e?.isMounted()){if(!this.chart.isReplayActive()&&!this.replayStartPending){this.exitReplay();return}this.removeReplayShade(),e.setMode(`replay`),this.syncReplayBar(),this.layoutReplayBar()}}layoutReplayBar(){let e=this.replayBar?.element();if(!e||!this.replayBar)return;let t=this.chart.getPlotRect(),n=this.chartContainer,r=e=>`${Math.max(0,Math.round(e))}px`;e.style.setProperty(`--tcw-replay-foot`,r(n.clientHeight-(t.y+t.height))),e.style.setProperty(`--tcw-replay-plot-start`,r(t.x)),e.style.setProperty(`--tcw-replay-plot-end`,r(n.clientWidth-(t.x+t.width))),this.replayBar.setRoom(t.width-2*ed),this.liftOverReplayBar()}liftOverReplayBar(){let e=this.replayBar?.element();if(!e)return;let t=e.getBoundingClientRect().top,n=e=>{if(!e)return;let n=`${Math.max(0,Math.round(e.getBoundingClientRect().bottom-t))}px`;e.style.getPropertyValue(`--tcw-replay-lift`)!==n&&e.style.setProperty(`--tcw-replay-lift`,n)};n(this.root),n(this.bodyEl())}placeDrawingButton(){let e=this.bodyEl();if(!this.sidebar||!e)return;let t=this.chartContainer.getBoundingClientRect().left-e.getBoundingClientRect().left;this.sidebar.setPlotLeft(t+this.chart.getPlotRect().x)}bodyEl(){return this.root.querySelector(`:scope > .tcw-body`)}replayTimeText(){let e=this.chart.getReplayProgress(),t=(this.chart.getReplayBarIndex()>e.current?e.time:null)??this.replayStepTime;if(t===null)return;let r=this.textLocale(),i=this.chart.getTimeZone?.()??null,a=(0,n.timeframeToMs)(this.state.timeframe),o=(0,n.zonedDateFormatter)(r,{year:`numeric`},i),s={month:`short`,day:`numeric`};o(t)!==o(Date.now())&&(s.year=`numeric`);let c=(0,n.zonedDateFormatter)(r,s,i)(t);if(Number.isFinite(a)&&a>=Vu)return c;let l={hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`};return(!Number.isFinite(a)||a<td)&&(l.second=`2-digit`),`${c} · ${(0,n.zonedDateFormatter)(r,l,i)(t)}`}replayBarCount(){return this.chart.isReplayActive()&&this.replayBarsTotal!==null?this.replayBarsTotal:this.chart.getData().length}hideReplayShade=()=>this.positionReplayShade(null);replayFrom(e,t=!1){this.featureState.replay&&(this.replayBar?.isMounted()||this.enterReplay(),this.startReplayAt(e,t))}replayStepMenu(){let e=[{value:`auto`,label:this.t(`replay.step.auto`)},{value:`bar`,label:this.t(`replay.step.bar`)},...this.replayStepOptions().map(e=>({value:e,label:e}))];return e.some(e=>e.value===this.replayStep)||(this.replayStep=`auto`),e}refreshReplaySteps(){if(!this.replayBar?.isMounted())return;let e=this.replayStepMenu();this.replayBar.setSteps(e,this.replayStep)}afterReplayCarryOver(){let e=this.replayBar;!e?.isMounted()||e.getMode()!==`replay`||(this.syncReplayBar(),!(this.replayStep===`bar`||this.chartFetchesReplaySteps())&&this.replayStepsKey!==this.replayStepsKeyNow()&&this.startReplayAt(this.chart.getReplayBarIndex(),this.chart.getReplayState()===`playing`))}startPickedReplay(){let e=this.replayPickTime;if(e===null)return;if(this.loading.hasFailed()||this.replayBar?.getMode()!==`select`){this.replayPickTime=null;return}if(this.seriesPending())return;this.replayPickTime=null;let t=this.chart.getData();if(!wd(t,e))return;let n=0;for(;n+1<t.length&&t[n+1].time<=e;)n++;this.startReplayAt(n,!1,!0)}seriesPending(){return this.loading.isActive()&&!this.loading.hasFailed()}watchReplayBar(){this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayPollInterval=setInterval(()=>this.syncReplayBar(),Qu)}startReplayAt(e,t=!1,n=!1){let r=this.replayBar;if(!r)return;let i=n?this.replayBarCount():this.replayTotal(),a=Math.max(0,Math.min(Number.isFinite(e)?Math.floor(e):0,i-1)),o=this.chart.getData()[a]?.time;this.removeReplayShade(),r.setMode(`replay`),this.layoutReplayBar();let s=++this.replayStartSeq;this.replayPlayWanted=t;let c=this.options.replayAnimate!==!1,l=this.chartFetchesReplaySteps(),u=e=>{this.destroyed||this.replayBar!==r||!r.isMounted()||s!==this.replayStartSeq||(this.replayStartPending=!1,this.replayStepsKey=e?this.replayStepsKeyNow():null,this.chart.replayStart({speed:this.replaySpeed,interval:c?Hu:Hu/this.replayStepsPerBar(e?d:null),...o===void 0?{startIndex:a}:{startTime:o},paused:!0,revealMarks:this.options.replayRevealMarks!==!1,animate:c,...l?{step:this.replayStep}:{},...e?{steps:e}:{}}),this.replayPlayWanted&&this.chart.replayResume(),this.replayPlayWanted=!1,this.syncReplayBar(),this.watchReplayBar())},d=this.replayStepInterval();if(l||d===null){u(null);return}this.replayStartPending=!0,this.replayStepsFor(d).then(e=>{s===this.replayStartSeq&&(e||this.say(this.t(`replay.stepsFailed`),`error`),u(e))})}replayStepsKeyNow(){return`${this.state.symbol}|${this.state.timeframe}`}replayStepsPerBar(e){if(e===null)return 1;let t=(0,n.timeframeToMs)(this.state.timeframe)/(0,n.timeframeToMs)(e);return Number.isFinite(t)&&t>=1?Math.round(t):1}replayStepOptions(){return e.d(this.state.timeframe,e=>this.hasReplayStep(e))}hasReplayStep(e){if(this.adapter)return(0,r.servesTimeframe)(this.adapter,e);let t=(0,n.timeframeToMs)(e);return this.baseSeries!==null&&this.baseTimeframeMs>0&&t>=this.baseTimeframeMs&&t%this.baseTimeframeMs===0}replayStepInterval(){return this.replayStep===`bar`||this.replayStep===`auto`&&this.options.replayAnimate===!1?null:e.f(this.replayStep,this.state.timeframe,e=>this.hasReplayStep(e))}chartFetchesReplaySteps(){return this.options.replayAnimate===!1||!this.adapter||this.replayStep===`bar`?!1:(0,r.withResampling)(this.adapter).fetchHistoryBefore!==void 0}async replayStepsFor(e){let t=this.chart.getExchangeTimeZone()??null,{symbol:a,timeframe:o}=this.state,s=()=>`${a}|${o}|${e}|${t}|${this.builtStepsZone(a,e)}`;if(this.replayStepsCache?.key===s())return this.replayStepsCache.steps;let c=null;if(this.adapter){let t=Math.max(1,Math.round((0,n.timeframeToMs)(o)/(0,n.timeframeToMs)(e))),i=Math.min($u,Math.max(this.chart.getData().length,100)*t);try{c=await(0,r.withResampling)(this.adapter).fetchHistory(a,e,i)}catch{c=null}}else this.baseSeries&&(c=(0,n.timeframeToMs)(e)===this.baseTimeframeMs?this.baseSeries:i(this.baseSeries,e,this.resampleOptions(t)));return!c||c.length===0?null:(this.replayStepsCache={key:s(),steps:c},c)}builtStepsZone(e,t){let n=this.adapter?(0,r.withResampling)(this.adapter):null;if(!(n instanceof r.ResamplingAdapter))return``;let i=n.bucketFor(e,t);return i?String(i.timeZone??`UTC`):``}replayTotal(){return this.chart.isReplayActive()?this.chart.getReplayProgress().total:this.chart.getData().length}syncReplayBar(){let e=this.replayBar;if(!e?.isMounted()||(e.setPending(this.seriesPending()),this.startPickedReplay(),this.liftOverReplayBar(),e.getMode()!==`replay`))return;if(this.replayStartPending){e.setState(`paused`);return}if(!this.chart.isReplayActive()){this.teardownReplayUi();return}let t=this.chart.getReplayProgress(),n=this.chart.getReplayState();e.setProgress(t.current,t.total,this.replayTimeText()),e.setState(n===`stopped`?`paused`:n),e.setEnded(n!==`playing`&&t.total>0&&t.current>=t.total-1)}stepReplay(e){if(this.replayBar?.getMode()!==`replay`||this.seriesPending())return;let t=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause();let n=this.chart.getReplayBarIndex()>t.current?e>0?this.chart.getReplayBarIndex():t.current:t.current+e;this.chart.replaySeek(Math.max(0,Math.min(t.total-1,n))),this.replayBar.setState(`paused`),this.syncReplayBar()}handleReplayKey(e){if(e.defaultPrevented||e.isComposing||e.keyCode===rd||Z()||nd()||!X(this.root,!0))return!1;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t)||t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable))return!1;let n=this.replayBar?.getMode();return e.shiftKey&&(e.key===`ArrowRight`||e.key===`ArrowLeft`)&&n===`replay`?(e.preventDefault(),e.stopPropagation(),this.stepReplay(e.key===`ArrowRight`?1:-1),!0):e.key===` `&&n===`replay`&&this.onChartSurface(t)?(e.preventDefault(),e.stopPropagation(),this.toggleReplayPlay(),!0):e.key===`Escape`&&n===`select`?(this.cancelReplayPick(),!0):!1}onChartSurface(e){return!e||!this.chartContainer.contains(e)?!1:e===this.chartContainer||e.closest(`button, [role="button"], a, .tcw-replay-bar`)===null}toggleReplayPlay(){if(this.replayStartPending){this.replayPlayWanted=!this.replayPlayWanted;return}this.chart.getReplayState()===`playing`?this.chart.replayPause():this.replayBarAtEnd()||this.chart.replayResume(),this.syncReplayBar()}replayBarAtEnd(){let e=this.chart.getReplayProgress();return e.total>0&&e.current>=e.total-1}positionReplayShade(e){let t=this.replayShade;if(!t)return;let n=this.chart.getPlotRect();if(e===null||e<n.x||e>n.x+n.width){t.hidden=!0;return}t.hidden=!1,t.style.left=`${e}px`,t.style.top=`${n.y}px`,t.style.width=`${n.x+n.width-e}px`,t.style.height=`${n.height}px`}exitReplay(){this.teardownReplayUi(),this.chart.replayStop()}teardownReplayUi(){this.replayStartSeq++,this.replayPickTime=null,this.replayStartPending=!1,this.replayPlayWanted=!1,this.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.removeReplayShade();let e=!!this.replayBar?.element()?.contains(document.activeElement);this.replayBar?.unmount(),this.replayBar=null,this.replayBarsTotal=null,this.replayStepTime=null,this.toolbar?.setActive(`replay`,!1),this.root.removeAttribute(`data-tcw-replay`),this.root.style.removeProperty(`--tcw-replay-lift`),this.bodyEl()?.style.removeProperty(`--tcw-replay-lift`),e&&this.focusAfterReplay()}focusAfterReplay(){let e=e=>!!e&&!e.hidden&&!e.closest(`[hidden]`)&&getComputedStyle(e).display!==`none`,t=this.root.querySelector(`.tcw-toolbar [data-role="replay"]`),n=this.root.querySelector(`.tcw-toolbar .tcw-toolbar-more`);(e(t)?t:e(n)?n:this.chartContainer)?.focus()}applySettings(e,t=!0){this.settingsState={...this.settingsState,...e},Object.keys(e).some(e=>!ad.has(e))&&this.layoutSession?.changed(),this.scheduleLegend(),e.gridVisible!==void 0&&this.chart.setGridVisible(e.gridVisible),e.volumeVisible!==void 0&&this.chart.setVolumeVisible(e.volumeVisible),e.volumeProfileVisible!==void 0&&this.chart.setVolumeProfileVisible(e.volumeProfileVisible),e.marketProfileVisible!==void 0&&this.chart.setMarketProfileVisible(e.marketProfileVisible),e.marketProfileSplit!==void 0&&this.chart.setMarketProfileConfig({splitBySession:e.marketProfileSplit}),e.marketProfileLetters!==void 0&&this.chart.setMarketProfileConfig({letters:e.marketProfileLetters}),e.marketProfileBuckets!==void 0&&this.chart.setMarketProfileConfig({buckets:e.marketProfileBuckets}),e.marketProfileOpacity!==void 0&&this.chart.setMarketProfileConfig({opacity:e.marketProfileOpacity}),e.depthHeatmapVisible!==void 0&&this.chart.setDepthHeatmapVisible(e.depthHeatmapVisible),e.depthHeatmapOpacity!==void 0&&this.chart.setDepthHeatmapConfig({opacity:e.depthHeatmapOpacity}),e.sessionShadingVisible!==void 0&&this.chart.setSessionShadingVisible(e.sessionShadingVisible),e.pivotMarkersVisible!==void 0&&this.chart.setPivotMarkersVisible(e.pivotMarkersVisible),e.pivotStrength!==void 0&&this.chart.setPivotMarkersConfig({left:e.pivotStrength,right:e.pivotStrength}),e.pivotStructureLabels!==void 0&&this.chart.setPivotMarkersConfig({structureLabels:e.pivotStructureLabels}),e.periodLevelsVisible!==void 0&&this.chart.setPeriodLevelsVisible(e.periodLevelsVisible),e.periodLevelsPeriod!==void 0&&this.chart.setPeriodLevelsPeriod(e.periodLevelsPeriod),e.legendVisible!==void 0&&this.chart.setLegend({visible:e.legendVisible}),e.barCountdown!==void 0&&this.chart.setBarCountdownVisible(e.barCountdown),e.indicatorValueLabels!==void 0&&this.chart.setIndicatorValueLabelsVisible(e.indicatorValueLabels),e.alignAxisLabels!==void 0&&this.chart.setAxisLabelsAligned(e.alignAxisLabels),e.crosshairMode!==void 0&&this.chart.setCrosshairMode(e.crosshairMode),e.autoScale!==void 0&&this.chart.setAutoScale(e.autoScale),e.invertScale!==void 0&&this.chart.setInvertScale(e.invertScale),e.leftPriceScale!==void 0&&(this.chart.setLeftPriceScaleVisible(e.leftPriceScale),this.placeDrawingButton()),(e.scaleMode!==void 0||e.autoScale!==void 0)&&queueMicrotask(()=>this.refreshScaleSwitches()),e.timezone!==void 0&&queueMicrotask(()=>this.statusBar?.tick()),e.scaleMode===void 0?e.logScale!==void 0&&(this.settingsState={...this.settingsState,scaleMode:e.logScale?`logarithmic`:`regular`},this.showScaleMode()):(this.settingsState={...this.settingsState,logScale:e.scaleMode===`logarithmic`},this.showScaleMode()),e.numberLocale!==void 0&&(this.chart.setNumberLocale(e.numberLocale),this.watchlist?.setLocale(e.numberLocale||void 0)),e.timezone!==void 0&&this.chart.setTimeZone(u(e.timezone)),e.highLowLines!==void 0&&this.chart.setHighLowLines(e.highLowLines),e.extendedHours!==void 0&&this.chart.setExtendedHours(e.extendedHours),e.mainSeriesVisible!==void 0&&this.chart.setMainSeriesVisible(e.mainSeriesVisible),e.chartTypeOptions!==void 0&&this.chart.setChartTypeOptions({...ho(),...e.chartTypeOptions}),t&&!this.settingsEdit&&this.publishSettings()}resetSettings(){let e={...this.settingsState},t=this.settingsStyle(),n={...this.settingsDefaults};this.touchSettings(Object.keys(n),ke),this.applySettings(n),this.chart.resetOverrides([...ke],{layer:`user`});let r={...this.settingsState},i=this.settingsStyle();this.settings?.refresh(this.shownSettings()),!(this.settingsEdit||JSON.stringify([e,t])===JSON.stringify([r,i]))&&this.chart.recordUndo({undo:()=>this.restoreSettings(e,t),redo:()=>this.restoreSettings(r,i)})}changeStyle(e){let t=Object.keys(e);this.touchSettings([],t);let n=this.settingsStyle(t);this.chart.applyOverrides(e,{layer:`user`});let r=this.settingsStyle(t);this.settingsEdit||JSON.stringify(n)===JSON.stringify(r)||this.chart.recordUndo({subject:`style:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings({},n),redo:()=>this.restoreSettings({},r)})}changeSettings(e){let t=Object.keys(e);if(t.includes(`scaleMode`)||t.includes(`logScale`))for(let e of[`scaleMode`,`logScale`])t.includes(e)||t.push(e);let n=()=>Object.fromEntries(t.map(e=>[e,this.settingsState[e]]));this.touchSettings(t);let r=n(),i=t.includes(`scaleMode`),a=this.compareScaleHeld;i&&(this.compareScaleHeld=!1),this.applySettings(e);let o=n();this.settingsEdit||JSON.stringify(r)===JSON.stringify(o)&&a===this.compareScaleHeld||this.chart.recordUndo({subject:`settings:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings(r,null,i?a:void 0),redo:()=>this.restoreSettings(o,null,i?!1:void 0)})}settingsStyle(e=ke){let t=this.chart.getOverrides?.({layer:`user`})??{},n=Object.fromEntries(e.map(e=>{let n=t[e];return[e,typeof n==`string`||typeof n==`boolean`||typeof n==`number`?n:null]}));return{theme:this.chart.getTheme()?.name??``,overrides:n}}restoreSettings(e,t=null,n){n!==void 0&&(this.compareScaleHeld=n&&this.compares.length>0),this.applySettings(e),t&&t.theme===(this.chart.getTheme()?.name??``)&&this.chart.applyOverrides(t.overrides,{layer:`user`}),this.settings?.refresh(this.shownSettings())}async connectStream(){if(!this.adapter)return;let e=++this.connectSeq;this.state={...this.state,connectionState:`connecting`,connectionMessage:this.t(`status.connecting`)},this.updateUI(),this.loading.begin(this.chart.getData().length>0);try{if(this.chart.disconnectStream(),await this.chart.connect({adapter:this.adapter,symbol:this.state.symbol,timeframe:this.state.timeframe,historyLimit:this.options.historyLimit??500,historyPageSize:this.options.historyPageSize}),e!==this.connectSeq||this.destroyed)return;this.chart.setWatermark(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:48,color:this.state.isDark?`rgba(255,255,255,0.03)`:`rgba(0,0,0,0.03)`}),this.applySymbolLayout(this.state.symbol),this.loading.hasFailed()?this.state={...this.state,connectionState:`error`}:(this.loading.end(),this.state={...this.state,connectionState:`connected`,connectionMessage:this.t(`status.live`)}),this.refetchCompares()}catch(t){if(e!==this.connectSeq||this.destroyed)return;this.loading.fail(this.t(`status.connectionFailed`)),this.state={...this.state,connectionState:`error`,connectionMessage:t instanceof Error?t.message:this.t(`status.connectionFailed`)}}this.updateUI()}scheduleLegend(){!this.indicatorLegend||this.legendFrame||!this.featureState.indicatorLegend||(this.legendFrame=requestAnimationFrame(()=>{this.legendFrame=0,this.renderLegend()}))}renderLegend(){if(!this.indicatorLegend||this.destroyed)return;let e=this.chart.getData().length-1,t=this.chart.isTimeAligned(),n=this.legendHoverIndex,r=n===null?e:Math.min(Math.max(n,0),e),i=new Map;for(let e of this.chart.getIndicatorPanes())(e.instanceIds??[e.instanceId]).forEach((t,n)=>i.set(t,{...e.rect,row:n}));let a=this.settingsState.numberLocale||`en-US`,o=Jl(r>=0?this.chart.getCompareValues?.(n===null||!t?void 0:r)??[]:[],a,t),s=this.chart.getActiveIndicators().map(e=>{let t=i.get(e.instanceId)??null,r=zl(this.chart.getIndicatorOutput(e.instanceId)?.series,n),o=this.chart.getIndicatorStyle(e.instanceId),s=e.visible&&e.offChartType===!0,c=e.visible&&e.shown===!1&&!s,l=c||s?[]:Bl(e.descriptor,r,o?.colors??[],o?.plots);return{instanceId:e.instanceId,label:Ji(e,this.t),visible:e.visible,offInterval:c,offChartType:s,values:l.map(n=>({text:this.indicatorValueText(n.value,t===null&&Td(e),a),color:n.color})),pane:t?{x:t.x+qu,y:t.y+Math.min(Yu+t.row*Xu,Math.max(Yu,t.height-Xu)),width:t.width-2*qu}:null}}),c=[...o,...s],l=this.chart.getPlotRect(),u=this.chart.getMaximizedPane(),d=e=>c.find(t=>t.instanceId===e)?.label??``,f=this.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-qu,y:e.rect.y+Zu,label:d(e.instanceId),collapsed:this.chart.isPaneCollapsed(e.instanceId),maximized:u===e.instanceId,canMoveUp:this.chart.canMovePane(e.instanceId,-1),canMoveDown:this.chart.canMovePane(e.instanceId,1)}));this.indicatorLegend.update(c,{left:l.x+qu,top:this.chart.getLegendBottom()+Ju},f)}runPaneAction(e,t){t===`up`||t===`down`?this.chart.movePane(e,t===`up`?-1:1):t===`collapse`||t===`expand`?this.chart.setPaneCollapsed(e,t===`collapse`):this.chart.setMaximizedPane(t===`maximize`?e:null),this.scheduleLegend()}openLegendMenu(e,t){let n=this.legendMenu;if(!n)return;if(n.isOpen()){n.close();return}let r=[`price`,...this.chart.getIndicatorPanes().map(e=>e.instanceId)],i=1+this.chart.getIndicatorPanes().findIndex(t=>t.instanceIds.includes(e)),a=r[i-1],o=r[i+1],s=t=>t!==void 0&&this.chart.canMoveIndicatorToPane(e,t),c=[];s(a)&&c.push({id:`move:${a}`,label:this.t(a===`price`?`legend.movePrice`:`legend.moveUp`),icon:`arrowUp`}),s(o)&&c.push({id:`move:${o}`,label:this.t(`legend.moveDown`),icon:`arrowDown`}),s(`new`)&&c.push({id:`move:new`,label:this.t(`legend.moveNew`),icon:`plus`}),a!==`price`&&s(`price`)&&c.push({id:`move:price`,label:this.t(`legend.movePrice`),icon:`trendingUp`});let l=[];this.featureState.indicatorSettings&&this.featureState[`indicatorLegend.settings`]&&l.push({id:`settings`,label:this.t(`legend.settings`),icon:`settings`}),this.featureState[`indicatorLegend.remove`]&&l.push({id:`remove`,label:this.t(`legend.remove`),icon:`trash`,danger:!0}),c.length>0&&l.length>0&&c.push(`separator`),c.push(...l);let u=this.chart.getActiveIndicators().find(t=>t.instanceId===e)?.id??``,d=this.options.indicatorMenuItems?.({instanceId:e,indicatorId:u})??[],f=Su(c,d);if(f.length===0)return;let p=t.getBoundingClientRect(),m=this.root.getBoundingClientRect();n.open(f,p.left-m.left,p.bottom-m.top+2,t=>{Cu(t,d)||(t===`settings`?this.openIndicatorSettings(e):t===`remove`?this.handleRemoveIndicator(e):t.startsWith(`move:`)&&this.chart.moveIndicatorToPane(e,t.slice(5)),this.scheduleLegend())},t)}updateUI(){this.refreshDrawingsState(),this.scheduleLegend(),this.toolbar?.update(this.state),this.sidebar?.update(this.state),this.statusBar?.update({connectionState:this.state.connectionState,message:this.state.connectionMessage,symbol:this.state.symbol,timeframe:this.state.timeframe})}resolveIsDark(e){return e===void 0||e===`dark`?!0:e===`light`?!1:typeof e==`object`&&e.background?this.isColorDark(e.background):!0}resolveTheme(e){return e===void 0||e===`dark`?n.DARK_THEME:e===`light`?n.LIGHT_THEME:typeof e==`object`?e:n.DARK_THEME}isColorDark(e){if(e.startsWith(`#`)&&e.length>=7){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return t+n+r<384}return!0}};function pd(e,t,i){let a=e=>{let t=(0,r.sourceParam)(e.descriptor);return t&&(0,n.parseIndicatorSource)(e.params[t])?.instanceId||null},o=new Set([e]);for(let e=!0;e;){e=!1;for(let n of t){let t=a(n);t&&o.has(t)&&!o.has(n.instanceId)&&(o.add(n.instanceId),e=!0)}}let s=[];for(let e of t){if(o.has(e.instanceId))continue;let t=Ji(e,i);for(let r of e.descriptor.plots??[])s.push({value:(0,n.indicatorSource)(e.instanceId,r.key),label:`${t}: ${r.title}`})}return s}var md=`tcw:recentCommands`,hd=10;function gd(){try{let e=JSON.parse(xd()?.getItem(md)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`).slice(0,hd):[]}catch{return[]}}function _d(e){try{xd()?.setItem(md,JSON.stringify(e.slice(0,hd)))}catch{}}var vd=`tcw:dockWidth`;function yd(){try{let e=Number(xd()?.getItem(vd)??NaN);return Number.isFinite(e)&&e>0?e:null}catch{return null}}function bd(e){try{xd()?.setItem(vd,String(e))}catch{}}function xd(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}function Sd(e){let t=e.filter(e=>e!==null);if(t.length===0)return null;let n=Math.min(...t.map(e=>e.x)),r=Math.min(...t.map(e=>e.y)),i=Math.max(...t.map(e=>e.x+e.width)),a=Math.max(...t.map(e=>e.y+e.height));return{x:n,y:r,width:i-n,height:a-r}}function Cd(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}function wd(e,t){let n=e.length;if(n===0||t<e[0].time)return!1;let r=e[n-1].time;return t<r+(n>1?r-e[n-2].time:0)||t===r}function Td(e){return!r.SYMBOL_INDICATOR_IDS.has(e.id)&&e.scale!==`left`}var Ed={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},Dd=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],Od={"1x1":{cols:1,rows:1},"1x2":{cols:2,rows:1},"2x1":{cols:1,rows:2},"2x2":{cols:2,rows:2},"1x3":{cols:3,rows:1},"3x1":{cols:1,rows:3},"2x3":{cols:3,rows:2},"3x2":{cols:2,rows:3}};function kd(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(Od,e)}function Ad(e){return JSON.parse(JSON.stringify(e))}function jd(e,t,n=16){let r=(20-2*(e-1))/e,i=(20-2*(t-1))/t,a=``;for(let n=0;n<t;n++)for(let t=0;t<e;t++)a+=`<rect x="${2+t*(r+2)}" y="${2+n*(i+2)}" width="${r}" height="${i}" rx="1"/>`;return`<svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" aria-hidden="true">${a}</svg>`}function Md(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!kd(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map(Qc);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...Ed};for(let e of Dd)typeof r[e]==`boolean`&&(i[e]=r[e]);let a=typeof t.active==`number`&&Number.isInteger(t.active)?t.active:0;return{v:1,kind:`grid`,layout:t.layout,sync:i,active:a,cells:n}}var Nd=class{root;cellsEl;cells=[];layout;sync;active=0;hovered=null;relayDepth=0;uiTheme=null;styleOverrides={};featureSwitches={};parked=new Map;drawingFrame=0;drawingSource=null;layoutButtons=new Map;syncButtons=new Map;layoutsButton=null;tabsEl=null;stopNarrow=()=>{};session=null;layoutsUI=null;t;destroyed=!1;unregisterKeys=()=>{};onKeyDown=e=>{!(e.ctrlKey||e.metaKey)||e.altKey||e.shiftKey||e.key!==`s`&&e.key!==`S`||!this.layoutsUI||Z()||!X(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,n={}){this.options=n,this.layout=kd(n.layout)?n.layout:`1x2`,this.sync={...Ed,...n.sync},this.t=t.n(t.o(n.widget?.locale,n.widget?.messages)),Qe(),this.root=document.createElement(`div`),this.root.className=`tcw-root tcw-grid`,this.root.dataset.tcwTheme=n.widget?.theme===`light`?`light`:`dark`,xa(this.root,W(n.widget?.ui),{variables:n.widget?.ui!==void 0}),n.bar!==!1&&this.root.appendChild(this.buildBar()),this.cellsEl=document.createElement(`div`),this.cellsEl.className=`tcw-grid-cells`,this.root.appendChild(this.cellsEl),e.appendChild(this.root),this.stopNarrow=rl(this.root),this.applyShape();for(let e=0;e<this.shapeCount();e++)this.cells.push(this.createCell(e));this.markActive();let r=this.cells[0]?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;r&&(this.root.dataset.tcwTheme=r),n.layouts!==!1&&this.setupLayouts(n.layouts===!0||n.layouts===void 0?{}:n.layouts),this.unregisterKeys=Jc(this.root),document.addEventListener(`keydown`,this.onKeyDown)}get relaying(){return this.relayDepth>0}quietly(e){this.relayDepth++;try{return e()}finally{this.relayDepth--}}getWidget(e){return this.cells[e]?.widget??null}getWidgets(){return this.cells.map(e=>e.widget)}getActiveIndex(){return this.active}getActiveWidget(){return this.cells[this.active].widget}setActive(e){e<0||e>=this.cells.length||e===this.active||(this.active=e,this.markActive(),this.options.onActiveChange?.(e,this.cells[e].widget),this.session?.changed())}getLayout(){return this.layout}setLayout(e){if(e===this.layout||!kd(e))return;this.layout=e;let t=this.shapeCount();for(;this.cells.length>t;){let e=this.cells.length-1,t=this.cells.pop();this.parked.set(e,t.widget.captureLayout()),this.destroyCell(t)}this.applyShape();for(let e=this.cells.length;e<t;e++){let t=this.createCell(e);this.cells.push(t),this.unpark(e,t)}this.active>=t&&(this.active=0,this.options.onActiveChange?.(0,this.cells[0].widget)),this.markActive(),this.renderBar(),this.session?.changed()}getSync(){return{...this.sync}}setUI(e){let t=W(e);xa(this.root,t);for(let e of this.cells)e.widget.setUI(t);this.uiTheme=t}getUI(){return W(this.uiTheme??this.options.widget?.ui)}setSync(e){let t=this.sync;if(this.sync={...this.sync,...e},t.crosshair&&!this.sync.crosshair)for(let e of this.cells)e.widget.getChart().setCrosshairTime(null);let n=this.cells[this.active];if(n&&!this.relaying){let e=n.widget.getSymbol(),r=n.widget.getTimeframe();!t.symbol&&this.sync.symbol&&this.relay(n,t=>void t.setSymbol(e)),!t.interval&&this.sync.interval&&this.relay(n,e=>void e.setTimeframe(r)),!t.drawings&&this.sync.drawings&&this.mergeDrawings()}this.renderBar(),this.session?.changed()}applyOverrides(e){for(let t of this.cells)t.widget.getChart().applyOverrides(e);let t={...this.styleOverrides};for(let[n,r]of Object.entries(e))r==null?delete t[n]:t[n]=r;this.styleOverrides=t}setFeatures(e){let t=Be(e);for(let e of this.cells)e.widget.setFeatures(t);this.featureSwitches={...this.featureSwitches,...t}}setTheme(e){for(let t of this.cells)t.widget.setTheme(e);this.followTheme()}getLayoutSession(){return this.session}captureLayout(){let e=[...this.parked.entries()].sort(([e],[t])=>e-t).map(([,e])=>e);return{v:1,kind:`grid`,layout:this.layout,sync:{...this.sync},active:this.active,cells:[...this.cells.map(e=>e.widget.captureLayout()),...e]}}async restoreLayout(e){this.relayDepth++;let t;try{this.parked.clear(),this.setLayout(e.layout),this.sync={...e.sync},this.renderBar();let n=this.cells.length;e.cells.slice(n).forEach((e,t)=>this.parked.set(n+t,e)),t=await Promise.allSettled(this.cells.map((t,n)=>e.cells[n]?t.widget.restoreLayout(e.cells[n]):Promise.resolve()))}finally{this.relayDepth--}if(this.destroyed)return;this.setActive(Math.min(Math.max(0,e.active),this.cells.length-1)),this.renderTabs();let n=t.find(e=>e.status===`rejected`);if(n)throw n.reason}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=Md($c(e));return t?(await this.restoreLayout(t),!0):!1}destroy(){if(!this.destroyed){this.destroyed=!0,document.removeEventListener(`keydown`,this.onKeyDown),this.unregisterKeys(),this.stopNarrow(),this.drawingFrame&&cancelAnimationFrame(this.drawingFrame),this.session?.destroy(),this.layoutsUI?.destroy();for(let e of this.cells)this.destroyCell(e);this.cells=[],this.root.remove(),$e()}}shapeCount(){let{cols:e,rows:t}=Od[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=Od[this.layout];this.cellsEl.style.gridTemplateColumns=`repeat(${e}, minmax(0, 1fr))`,this.cellsEl.style.gridTemplateRows=`repeat(${t}, minmax(0, 1fr))`}createCell(e){let n=document.createElement(`div`);n.className=`tcw-grid-cell`,n.setAttribute(`role`,`region`),n.setAttribute(`aria-label`,t.r(this.t(`grid.chart`),{n:e+1})),this.cellsEl.appendChild(n);let r=this.options.widget??{},i=this.options.cells?.[e]??{},a=this.cells[this.active]?.widget,o={},s=new fd(n,{...r,...i,...i.adapter?{feed:void 0}:{},...i.feed?{adapter:void 0}:{},...a&&this.sync.symbol?{symbol:a.getSymbol()}:{},...a&&this.sync.interval?{timeframe:a.getTimeframe()}:{},...this.options.adapter&&!i.adapter&&!i.feed&&!r.feed?{adapter:this.options.adapter(e)}:{},...this.uiTheme?{ui:this.uiTheme}:{},layouts:!1,...i.persistSettings===void 0&&r.persistSettings?{persistSettings:{key:`${To(r.persistSettings)}:${e}`}}:{},features:{dock:!1,...r.features,...i.features},onSymbolChange:e=>{i.onSymbolChange?.(e),r.onSymbolChange?.(e),this.sync.symbol&&this.relay(o,t=>void t.setSymbol(e)),this.renderTabs(),this.session?.changed()},onTimeframeChange:e=>{i.onTimeframeChange?.(e),r.onTimeframeChange?.(e),this.sync.interval&&this.relay(o,t=>void t.setTimeframe(e)),this.renderTabs(),this.session?.changed()}});return o.el=n,o.widget=s,Object.keys(this.styleOverrides).length>0&&s.getChart().applyOverrides(this.styleOverrides),Object.keys(this.featureSwitches).length>0&&s.setFeatures(this.featureSwitches),this.wireCell(o),n.addEventListener(`pointerdown`,()=>this.setActive(this.cells.indexOf(o)),!0),n.addEventListener(`pointerenter`,()=>{this.hovered=o}),n.addEventListener(`pointerleave`,()=>{this.hovered===o&&(this.hovered=null)}),this.options.onChartAdd?.(s,e),o}wireCell(e){let t=e.widget.getChart(),n=()=>this.cells.filter(t=>t!==e);t.on(`crosshairMove`,e=>{let t=e.payload.bar?.time;if(!(!this.sync.crosshair||t===void 0))for(let e of n())e.widget.getChart().setCrosshairTime(t)}),t.on(`crosshairLeave`,()=>{if(this.sync.crosshair)for(let e of n())e.widget.getChart().setCrosshairTime(null)}),t.on(`visibleRangeChange`,n=>{if(!this.sync.time||this.relaying||(this.hovered??this.cells[this.active])!==e)return;let{from:r,to:i}=n.payload,a=t.getData(),o=a[r]?.time,s=a[i]?.time;o===void 0||s===void 0||this.relay(e,e=>e.getChart().setVisibleRange(o,s))});for(let n of[`drawingCreate`,`drawingUpdate`,`drawingRemove`])t.on(n,()=>{this.sync.drawings&&!this.relaying&&this.copyDrawingsSoon(e)});t.on(`replayStep`,t=>{if(!this.sync.replay||this.relaying||t.payload.cause===`series`)return;let{until:n}=t.payload;this.relay(e,e=>{let t=e.getChart();if(t.isReplayActive()){t.replaySeekToTime(n);return}let r=Pd(t.getData(),n);r>=0&&t.replayStart({startIndex:r,paused:!0})})}),t.on(`replayState`,t=>{!this.sync.replay||this.relaying||t.payload.state!==`stopped`||this.relay(e,e=>{e.getChart().isReplayActive()&&e.getChart().replayStop()})}),t.on(`stateChange`,()=>this.session?.changed()),e.widget.onSettingsChange(()=>this.session?.changed()),t.on(`themeChange`,()=>{this.relaying||this.followTheme(e)})}destroyCell(e){this.hovered===e&&(this.hovered=null),this.drawingSource===e&&(this.drawingSource=null),this.quietly(()=>e.widget.destroy()),e.el.remove()}relay(e,t){this.relaying||this.quietly(()=>{for(let n of this.cells)n!==e&&t(n.widget)})}unpark(e,t){let n=this.parked.get(e);if(!n)return;this.parked.delete(e);let r=this.cells[this.active]?.widget,i={...n,...r&&this.sync.symbol?{symbol:r.getSymbol()}:{},...r&&this.sync.interval?{timeframe:r.getTimeframe()}:{}};this.relayDepth++,t.widget.restoreLayout(i).catch(()=>t.widget.toast(this.t(`layouts.openFailed`),`error`)).finally(()=>{this.relayDepth--})}copyDrawingsSoon(e){this.drawingSource=e,!this.drawingFrame&&(this.drawingFrame=requestAnimationFrame(()=>{this.drawingFrame=0;let e=this.drawingSource;this.drawingSource=null,e&&!this.destroyed&&!this.relaying&&this.copyDrawings(e)}))}copyDrawings(e){let t=e.widget.getSymbol(),n=e.widget.getChart().getDrawings();this.quietly(()=>{for(let r of this.cells)r!==e&&r.widget.getSymbol()===t&&r.widget.getChart().setDrawings(Ad(n))})}mergeDrawings(){let e=new Map;for(let t of this.cells)e.set(t.widget.getSymbol(),[...e.get(t.widget.getSymbol())??[],t]);this.quietly(()=>{for(let t of e.values()){if(t.length<2)continue;let e=new Map;for(let n of t)for(let t of n.widget.getChart().getDrawings())e.has(t.id)||e.set(t.id,t);let n=[...e.values()];for(let e of t)e.widget.getChart().setDrawings(Ad(n))}})}followTheme(e=this.cells[this.active]){let t=e?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;t&&(this.root.dataset.tcwTheme=t,this.quietly(()=>{for(let n of this.cells)n!==e&&n.el.querySelector(`.tcw-root`)?.dataset.tcwTheme!==t&&n.widget.setTheme(t)}))}markActive(){this.cells.forEach((e,t)=>{e.el.classList.toggle(`tcw-grid-cell-active`,t===this.active&&this.cells.length>1),e.el.classList.toggle(`tcw-grid-cell-current`,t===this.active)}),this.renderTabs()}renderTabs(){let e=this.tabsEl;if(!e)return;let t=this.cells.map(e=>`${e.widget.getSymbol()} · ${e.widget.getTimeframe()}`);for(;e.children.length>t.length;)e.lastElementChild?.remove();for(;e.children.length<t.length;){let t=e.children.length,n=document.createElement(`button`);n.type=`button`,n.className=`tcw-btn tcw-grid-tab`,n.addEventListener(`click`,()=>this.setActive(t)),e.appendChild(n)}t.forEach((t,n)=>{let r=e.children[n];r.textContent!==t&&(r.textContent=t);let i=n===this.active;r.classList.toggle(`tcw-active`,i),r.setAttribute(`aria-pressed`,String(i))})}buildBar(){let e=document.createElement(`div`);e.className=`tcw-grid-bar`,e.setAttribute(`role`,`toolbar`),e.setAttribute(`aria-label`,this.t(`grid.bar`)),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-grid-group tcw-grid-tabs`,this.root.classList.add(`tcw-grid-has-tabs`),this.tabsEl.setAttribute(`role`,`group`),this.tabsEl.setAttribute(`aria-label`,this.t(`grid.charts`)),e.appendChild(this.tabsEl);let n=document.createElement(`div`);n.className=`tcw-grid-group`,n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,this.t(`grid.layout`));let r=this.options.layoutChoices?.filter(kd)??Object.keys(Od);for(let e of r){let{cols:r,rows:i}=Od[e],a=r*i===1?this.t(`grid.single`):t.r(this.t(`grid.layoutOption`),{count:r*i,cols:r,rows:i}),o=document.createElement(`button`);o.type=`button`,o.className=`tcw-btn-icon`,o.title=a,o.setAttribute(`aria-label`,a),o.innerHTML=jd(r,i),o.addEventListener(`click`,()=>this.setLayout(e)),this.layoutButtons.set(e,o),n.appendChild(o)}let i=document.createElement(`div`);i.className=`tcw-grid-group`,i.setAttribute(`role`,`group`),i.setAttribute(`aria-label`,this.t(`grid.sync`));let a=document.createElement(`span`);a.className=`tcw-grid-label`,a.innerHTML=`${O(`link`,13)}<span>${k(this.t(`grid.sync`))}</span>`,i.appendChild(a);for(let e of Dd){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-btn tcw-grid-sync`,t.textContent=this.t(`grid.sync.${e}`),t.title=this.t(`grid.sync.${e}.hint`),t.addEventListener(`click`,()=>this.setSync({[e]:!this.sync[e]})),this.syncButtons.set(e,t),i.appendChild(t)}let o=document.createElement(`span`);return o.className=`tcw-toolbar-spacer`,e.append(n,this.sep(),i,o),this.options.layouts!==!1&&(this.layoutsButton=document.createElement(`button`),this.layoutsButton.type=`button`,this.layoutsButton.className=`tcw-dropdown-trigger tcw-layouts-btn`,this.layoutsButton.setAttribute(`aria-haspopup`,`menu`),this.layoutsButton.addEventListener(`click`,()=>{this.layoutsButton&&this.layoutsUI?.openMenu(this.layoutsButton)}),e.appendChild(this.layoutsButton)),this.renderBar(),e}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}renderBar(){for(let[e,t]of this.layoutButtons){let n=e===this.layout;t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n))}for(let[e,t]of this.syncButtons)t.classList.toggle(`tcw-active`,this.sync[e]),t.setAttribute(`aria-pressed`,String(this.sync[e]));this.renderLayoutsButton()}renderLayoutsButton(){let e=this.layoutsButton;if(!e)return;let t=this.session?.current()?.name??this.t(`layouts.unnamed`),n=this.session?.isDirty()??!1,r=`${this.t(`toolbar.layouts`)}: ${t}${n?` (${this.t(`layouts.unsavedChanges`)})`:``}`;e.innerHTML=`${O(`save`,14)}<span class="tcw-layouts-label">${k(t)}</span>`+(n?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+O(`chevronDown`,12),e.title=r,e.setAttribute(`aria-label`,r)}setupLayouts(t){let n=new e.t(t.storage??e.i(`tcw:grid-layouts:`),{capture:()=>{let e=this.cells[this.active].widget;return{content:this.getLayoutContent(),symbol:e.getSymbol(),timeframe:e.getTimeframe()}},apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a grid layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,kind:`grid`,onChange:()=>this.renderLayoutsButton(),onError:()=>this.toast(this.t(`layouts.saveFailed`),`error`)});this.session=n,this.layoutsUI=new Vc(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=Q(e,null);return`${t} ${n}`}}),this.renderLayoutsButton(),t.openLast&&n.list().then(([e])=>e&&!this.destroyed?this.layoutsUI?.open(e.id):void 0,()=>void 0)}toast(e,t=`info`){this.cells[this.active]?.widget.toast(e,t)}};function Pd(e,t){let n=-1;for(let r=0;r<e.length&&e[r].time<t;r++)n=r;return n}Object.defineProperty(exports,`CHART_TYPE_ICONS`,{enumerable:!0,get:function(){return n.CHART_TYPE_ICONS}}),exports.ChartWidget=fd,exports.ChartWidgetGrid=Nd,exports.DEFAULT_GRID_SYNC=Ed,Object.defineProperty(exports,`DRAWING_TOOL_ICONS`,{enumerable:!0,get:function(){return n.DRAWING_TOOL_ICONS}}),exports.EN_MESSAGES=t.c,exports.GRID_SHAPES=Od,exports.LayoutSession=e.t,exports.MAX_LAYOUT_NAME=e.n,Object.defineProperty(exports,`UI_ICONS`,{enumerable:!0,get:function(){return n.UI_ICONS}}),exports.VI_MESSAGES=t.s,exports.WIDGET_FEATURES=Pe,exports.WIDGET_UI_PRESETS=fa,exports.applyWidgetUI=xa,exports.cleanLayoutName=e.r,exports.createChartTypeIcon=nt,exports.createIcon=O,exports.createToolIcon=tt,exports.findWidgetLocale=t.i,Object.defineProperty(exports,`iconSvg`,{enumerable:!0,get:function(){return n.iconSvg}}),exports.localStorageLayouts=e.i,exports.memoryLayouts=e.a,exports.readGridLayout=Md,exports.readWatchlists=mi,exports.readWidgetLayout=Qc,exports.registerWidgetLocale=t.a,exports.resolveWidgetUI=W,exports.widgetUIVariables=ba;
|
|
7735
7735
|
//# sourceMappingURL=index.cjs.map
|