@tradecanvas/chart 1.37.0 → 1.38.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.
Files changed (70) hide show
  1. package/dist/Chart.d.ts +13 -5
  2. package/dist/Chart.d.ts.map +1 -1
  3. package/dist/LayoutSession-CQuy66RZ.cjs +2 -0
  4. package/dist/LayoutSession-CQuy66RZ.cjs.map +1 -0
  5. package/dist/{LayoutSession-DCTwvtwp.js → LayoutSession-DFL2W819.js} +7 -4
  6. package/dist/LayoutSession-DFL2W819.js.map +1 -0
  7. package/dist/i18n-3mW6rmUi.cjs +2 -0
  8. package/dist/i18n-3mW6rmUi.cjs.map +1 -0
  9. package/dist/{i18n-CCRcUMIR.js → i18n-EHdUj7jZ.js} +39 -3
  10. package/dist/i18n-EHdUj7jZ.js.map +1 -0
  11. package/dist/index.cjs +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/widget/ChartWidget.d.ts +4 -0
  14. package/dist/widget/ChartWidget.d.ts.map +1 -1
  15. package/dist/widget/WidgetDrawingSettings.d.ts +33 -32
  16. package/dist/widget/WidgetDrawingSettings.d.ts.map +1 -1
  17. package/dist/widget/WidgetIndicatorSettings.d.ts +1 -1
  18. package/dist/widget/WidgetIndicatorSettings.d.ts.map +1 -1
  19. package/dist/widget/WidgetObjectTree.d.ts +2 -0
  20. package/dist/widget/WidgetObjectTree.d.ts.map +1 -1
  21. package/dist/widget/drawingSettingsTabs.d.ts +42 -0
  22. package/dist/widget/drawingSettingsTabs.d.ts.map +1 -0
  23. package/dist/widget/index.cjs +102 -30
  24. package/dist/widget/index.cjs.map +1 -1
  25. package/dist/widget/index.js +1320 -1190
  26. package/dist/widget/index.js.map +1 -1
  27. package/dist/widget/locales/ar.d.ts.map +1 -1
  28. package/dist/widget/locales/cs.d.ts.map +1 -1
  29. package/dist/widget/locales/da.d.ts.map +1 -1
  30. package/dist/widget/locales/de.d.ts.map +1 -1
  31. package/dist/widget/locales/el.d.ts.map +1 -1
  32. package/dist/widget/locales/en.d.ts +19 -1
  33. package/dist/widget/locales/en.d.ts.map +1 -1
  34. package/dist/widget/locales/es.d.ts.map +1 -1
  35. package/dist/widget/locales/et.d.ts.map +1 -1
  36. package/dist/widget/locales/fa.d.ts.map +1 -1
  37. package/dist/widget/locales/fr.d.ts.map +1 -1
  38. package/dist/widget/locales/he.d.ts.map +1 -1
  39. package/dist/widget/locales/hu.d.ts.map +1 -1
  40. package/dist/widget/locales/id.d.ts.map +1 -1
  41. package/dist/widget/locales/index.cjs +1 -1
  42. package/dist/widget/locales/index.cjs.map +1 -1
  43. package/dist/widget/locales/index.js +533 -29
  44. package/dist/widget/locales/index.js.map +1 -1
  45. package/dist/widget/locales/it.d.ts.map +1 -1
  46. package/dist/widget/locales/ja.d.ts.map +1 -1
  47. package/dist/widget/locales/ko.d.ts.map +1 -1
  48. package/dist/widget/locales/ms.d.ts.map +1 -1
  49. package/dist/widget/locales/nb.d.ts.map +1 -1
  50. package/dist/widget/locales/nl.d.ts.map +1 -1
  51. package/dist/widget/locales/pl.d.ts.map +1 -1
  52. package/dist/widget/locales/pt.d.ts.map +1 -1
  53. package/dist/widget/locales/ro.d.ts.map +1 -1
  54. package/dist/widget/locales/ru.d.ts.map +1 -1
  55. package/dist/widget/locales/sk.d.ts.map +1 -1
  56. package/dist/widget/locales/sv.d.ts.map +1 -1
  57. package/dist/widget/locales/th.d.ts.map +1 -1
  58. package/dist/widget/locales/tr.d.ts.map +1 -1
  59. package/dist/widget/locales/vi.d.ts.map +1 -1
  60. package/dist/widget/locales/zh.d.ts.map +1 -1
  61. package/dist/widget/locales/zhHant.d.ts.map +1 -1
  62. package/dist/widget/settingsControls.d.ts +5 -2
  63. package/dist/widget/settingsControls.d.ts.map +1 -1
  64. package/package.json +3 -3
  65. package/dist/LayoutSession-CHx7F_fj.cjs +0 -2
  66. package/dist/LayoutSession-CHx7F_fj.cjs.map +0 -1
  67. package/dist/LayoutSession-DCTwvtwp.js.map +0 -1
  68. package/dist/i18n-BXzSqL8c.cjs +0 -2
  69. package/dist/i18n-BXzSqL8c.cjs.map +0 -1
  70. package/dist/i18n-CCRcUMIR.js.map +0 -1
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-CHx7F_fj.cjs`),t=require(`../i18n-BXzSqL8c.cjs`);let n=require(`@tradecanvas/commons`),r=require(`@tradecanvas/core`);function i(e,t,r={}){if(e.length===0)return[];let i=r.weekStartsOn??1,a=[],o=null,s=NaN;for(let r of e){let e=(0,n.timeframeBucketStart)(r.time,t,i);o===null||e!==s?(o!==null&&a.push(o),o={time:e,open:r.open,high:r.high,low:r.low,close:r.close,volume:r.volume},s=e):o={time:o.time,open:o.open,high:Math.max(o.high,r.high),low:Math.min(o.low,r.low),close:r.close,volume:o.volume+r.volume}}return o!==null&&a.push(o),a}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`}];function s(e){return!e||e===`local`?null:e===`exchange`?`exchange`:/^-?\d+$/.test(e)?Number(e):(0,n.isValidTimeZone)(e)?e:null}function c(e){return e===null?`local`:String(e)}function l(e,t,r,i){let a=(0,n.offsetAt)(null,t),c=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}}),l=s(e);typeof l==`number`&&c.push({value:e,label:(0,n.tzLabel)(l),offset:l}),c.sort((e,t)=>e.offset-t.offset);let u=[{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);u.push({value:`exchange`,label:`${i.label} (${(0,n.tzLabel)(e)})`,offset:e})}return[...u,...c]}var u=6,d=8,f=120;function p(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-u-d,o=i.top-u-d;e.scrollHeight<=a||a>=o?(r.top=`${i.bottom+u}px`,r.bottom=`auto`,r.maxHeight=`${Math.max(f,a)}px`):(r.top=`auto`,r.bottom=`${window.innerHeight-i.top+u}px`,r.maxHeight=`${Math.max(f,o)}px`);let s=getComputedStyle(t).direction===`rtl`,c=n===`right`!==s,l=e.offsetWidth,p=c?i.right-l:i.left;r.left=`${Math.max(d,Math.min(p,window.innerWidth-l-d))}px`}var m=700,h=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,p(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<=m?(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||``;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>m?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})))}},ee=42,g=7,_=new Set([`US`,`CA`,`MX`,`BR`,`JP`,`KR`,`TW`,`HK`,`IL`,`PH`,`IN`,`ZA`,`AU`,`TH`,`SA`,`PE`,`CO`]);function v(e){try{let t=new Intl.Locale(e),n=t.getWeekInfo?.()??t.weekInfo;return n?n.firstDay===7?0:1:+!_.has(t.maximize().region??``)}catch{return 1}}function te(e,t,n){let r=(new Date(Date.UTC(e,t,1)).getUTCDay()-n+g)%g,i=[];for(let n=0;n<ee;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 y=e=>String(e).padStart(2,`0`),b=e=>`${String(e.year).padStart(4,`0`)}-${y(e.month+1)}-${y(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{input=null;panel=null;grid=null;titleEl=null;view={year:0,month:0};focusDay=re();onOutside=e=>{let t=e.target;this.panel?.contains(t)||this.input?.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.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.panel?.contains(e)===!0)}open(e){this.close(!1),this.input=e;let t=this.clamp(ne(e.value)??re());this.focusDay=t,this.view={year:t.year,month:t.month};let n=this.labels(),r=document.createElement(`div`);r.className=`tcw-calendar`,r.setAttribute(`role`,`dialog`);let i=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;i&&r.setAttribute(`aria-label`,i.trim());let a=document.createElement(`div`);a.className=`tcw-calendar-head`;let o=this.navButton(n.prevMonth,-1),s=this.navButton(n.nextMonth,1),c=document.createElement(`div`);c.className=`tcw-calendar-title`,c.setAttribute(`aria-live`,`polite`),a.append(o,c,s);let l=document.createElement(`div`);l.className=`tcw-calendar-weekdays`,l.setAttribute(`aria-hidden`,`true`);let u=v(this.locale()),d=new Intl.DateTimeFormat(this.locale(),{weekday:`narrow`,timeZone:`UTC`});for(let e=0;e<g;e++){let t=document.createElement(`span`);t.className=`tcw-calendar-weekday`,t.textContent=d.format(new Date(Date.UTC(2023,0,1+(u+e)%g))),l.appendChild(t)}let f=document.createElement(`div`);f.className=`tcw-calendar-grid`,f.setAttribute(`role`,`grid`),f.addEventListener(`keydown`,e=>this.onKey(e)),f.addEventListener(`click`,e=>{let t=e.target.closest(`.tcw-calendar-day`);t&&!t.disabled&&t.dataset.date&&this.pick(t.dataset.date)});let m=document.createElement(`div`);m.className=`tcw-calendar-foot`;let h=document.createElement(`button`);h.type=`button`,h.className=`tcw-calendar-today`,h.textContent=n.today,h.addEventListener(`click`,()=>{let e=b(re());this.allowed(e)&&this.pick(e)}),m.appendChild(h),r.append(a,l,f,m),r.addEventListener(`mousedown`,e=>{e.target.closest(`button`)||e.preventDefault()}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&(e.preventDefault(),this.close(!0))}),this.panel=r,this.grid=f,this.titleEl=c,this.render(),this.layer().appendChild(r),p(r,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.panel?.remove(),this.panel=this.grid=this.titleEl=null,this.input=null,e&&t.isConnected&&t.focus())}focusGrid(){this.grid?.querySelector(`[tabindex="0"]`)?.focus()}destroy(){this.close(!1)}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=b(e),n=this.input?.min?ne(this.input.min):null,r=this.input?.max?ne(this.input.max):null;return n&&t<b(n)?n:r&&t>b(r)?r:e}allowed(e){let t=this.input;return t?!(t.min&&e<t.min)&&!(t.max&&e>t.max):!1}render(){let e=this.grid,t=this.input;if(!e||!t||!this.titleEl)return;let n=this.locale();this.titleEl.textContent=new Intl.DateTimeFormat(n,{month:`long`,year:`numeric`,timeZone:`UTC`}).format(new Date(Date.UTC(this.view.year,this.view.month,1)));let r=t.value,i=b(re()),a=b(this.focusDay),o=new Intl.DateTimeFormat(n,{dateStyle:`full`,timeZone:`UTC`});e.textContent=``;let s=null;for(let[t,c]of te(this.view.year,this.view.month,v(n)).entries()){t%g===0&&(s=document.createElement(`div`),s.className=`tcw-calendar-week`,s.setAttribute(`role`,`row`),e.appendChild(s));let n=b(c),l=document.createElement(`button`);l.type=`button`,l.className=`tcw-calendar-day`,l.dataset.date=n,l.setAttribute(`role`,`gridcell`),l.textContent=String(c.day),l.setAttribute(`aria-label`,o.format(new Date(Date.UTC(c.year,c.month,c.day)))),l.setAttribute(`aria-selected`,String(n===r)),l.tabIndex=n===a?0:-1,c.month!==this.view.month&&l.classList.add(`tcw-outside`),n===i&&l.classList.add(`tcw-today`),this.allowed(n)||(l.disabled=!0),s?.appendChild(l)}}onKey(e){let t={ArrowLeft:-1,ArrowRight:1,ArrowUp:-g,ArrowDown:g},n=this.panel?getComputedStyle(this.panel).direction===`rtl`:!1;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===` `){let e=b(this.focusDay);this.allowed(e)&&this.pick(e)}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){let t=this.input;if(!t||!this.allowed(e))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})))}},oe=()=>typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches,se=()=>typeof CSS>`u`||typeof CSS.supports!=`function`||CSS.supports(`selector(::-webkit-calendar-picker-indicator)`);function ce(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 le(e){return!(e instanceof HTMLInputElement)||e.type!==`date`||e.matches(`:disabled`)||e.readOnly?null:e}function ue(e,t){let n=new h(t.layer),r=new ae(t.layer,t.labels,t.locale),i=t.native??oe,a=t.calendar??se,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=ce(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=le(e.target);t&&(e.preventDefault(),r.isOpenFor(t)||r.open(t))},u=e=>{if(i()||!s(e))return;let t=ce(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=le(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 de=[{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`}],fe=[{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`}]}],pe=[`BTCUSDT`,`ETHUSDT`,`SOLUSDT`,`BNBUSDT`],me={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,logScale:!1,scaleMode:`regular`,autoScale:!0,invertScale:!1,leftPriceScale:!1,crosshairMode:`magnet`,numberLocale:`en-US`,timezone:`local`,highLowLines:!1,mainSeriesVisible:!0,extendedHours:!0,chartTypeOptions:{}},x=(e,...t)=>({label:e,keys:t}),S=(e,t,n={})=>({label:e,keys:[t],auto:n}),C=e=>({hint:e}),he={from:`panes.titleColor`},ge={title:`settings.section.lastPrice`,rows:[x(`settings.priceLine`,`lastPrice.visible`),x(`settings.up`,`lastPrice.upColor`),x(`settings.down`,`lastPrice.downColor`),x(`drawingSettings.lineStyle`,`lastPrice.style`),x(`drawingSettings.lineWidth`,`lastPrice.width`)]},_e={title:`settings.volume`,rows:[x(`settings.up`,`volume.upColor`),x(`settings.down`,`volume.downColor`)]},ve={title:`settings.highLowLines`,rows:[S(`drawingSettings.color`,`highLow.color`,he)]},ye=[ge,_e,ve],be=[x(`settings.legendText`,`legend.textColor`),x(`settings.legendLabels`,`legend.labelColor`),x(`settings.paneTitles`,`panes.titleColor`)],xe=[x(`drawingSettings.text`,`axis.price.textColor`,`axis.time.textColor`),x(`settings.scaleLines`,`axis.price.lineColor`,`axis.time.lineColor`)],Se=[{title:`settings.section.background`,rows:[x(`settings.background`,`background.color`),x(`settings.paneBackground`,`panes.background`),x(`settings.paneSeparator`,`panes.separatorColor`),S(`settings.watermark`,`watermark.color`,he)]},{title:`settings.gridLines`,rows:[x(`settings.horizontal`,`grid.horizontal.visible`),x(`settings.vertical`,`grid.vertical.visible`),x(`drawingSettings.color`,`grid.horizontal.color`,`grid.vertical.color`),x(`drawingSettings.lineStyle`,`grid.horizontal.style`,`grid.vertical.style`),x(`drawingSettings.lineWidth`,`grid.horizontal.width`,`grid.vertical.width`)]},{title:`settings.crosshairMode`,rows:[x(`settings.horizontal`,`crosshair.horizontal.visible`),x(`settings.vertical`,`crosshair.vertical.visible`),x(`drawingSettings.color`,`crosshair.horizontal.color`,`crosshair.vertical.color`),x(`drawingSettings.lineStyle`,`crosshair.horizontal.style`,`crosshair.vertical.style`),x(`drawingSettings.lineWidth`,`crosshair.horizontal.width`,`crosshair.vertical.width`),x(`settings.labelBackground`,`crosshair.labelBackground`),x(`settings.labelText`,`crosshair.labelTextColor`)]},{title:`settings.sessionBreaks`,rows:[S(`drawingSettings.color`,`sessionBreaks.color`,{from:`axis.price.lineColor`}),S(`drawingSettings.lineStyle`,`sessionBreaks.style`),S(`drawingSettings.lineWidth`,`sessionBreaks.width`)]},{title:`objects.drawings`,rows:[S(`settings.handles`,`drawings.handleColor`,C(`#ffffff`))]}],Ce=[{title:`settings.section.orders`,trading:!0,rows:[S(`ticket.buy`,`trading.buyColor`,C(n.DEFAULT_TRADING_CONFIG.orderColors?.buy)),S(`ticket.sell`,`trading.sellColor`,C(n.DEFAULT_TRADING_CONFIG.orderColors?.sell)),S(`settings.profit`,`trading.profitColor`,C(n.DEFAULT_TRADING_CONFIG.positionColors?.profit)),S(`settings.loss`,`trading.lossColor`,C(n.DEFAULT_TRADING_CONFIG.positionColors?.loss)),S(`account.entry`,`trading.entryColor`,C(n.DEFAULT_TRADING_CONFIG.positionColors?.entry))]},{title:`settings.section.signals`,rows:[S(`account.long`,`markers.longColor`,C(n.DEFAULT_SIGNAL_STYLE.longColor)),S(`account.short`,`markers.shortColor`,C(n.DEFAULT_SIGNAL_STYLE.shortColor)),S(`markers.neutral`,`markers.neutralColor`,C(n.DEFAULT_SIGNAL_STYLE.neutralColor))]},{title:`settings.section.tradeZones`,rows:[S(`settings.profit`,`tradeZones.profitColor`,C(n.DEFAULT_TRADE_ZONE_STYLE.profitColor)),S(`settings.loss`,`tradeZones.lossColor`,C(n.DEFAULT_TRADE_ZONE_STYLE.lossColor)),S(`settings.openTrade`,`tradeZones.activeColor`,C(n.DEFAULT_TRADE_ZONE_STYLE.activeColor))]}],we={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`},Te=new Set([`candlestick`,`heikinAshi`,`volumeCandles`,`equivolume`]);function Ee(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=we[r]??`drawingSettings.color`;return Te.has(e)&&r===`upColor`&&(i=`settings.upBody`),Te.has(e)&&r===`downColor`&&(i=`settings.downBody`),e===`baseline`&&r===`upColor`&&(i=`settings.aboveBase`),e===`baseline`&&r===`downColor`&&(i=`settings.belowBase`),x(i,n)})}var w=[...new Set([...Object.keys(n.CHART_STYLE_KEYS).filter(e=>e.startsWith(`series.`)),...[...ye,...Se,...Ce].flatMap(e=>e.rows.flatMap(e=>e.keys)),...[...be,...xe].flatMap(e=>e.keys)])],De=`/* === TradeCanvas Widget — Premium Styles === */
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-CQuy66RZ.cjs`),t=require(`../i18n-3mW6rmUi.cjs`);let n=require(`@tradecanvas/commons`),r=require(`@tradecanvas/core`);function i(e,t,r={}){if(e.length===0)return[];let i=r.weekStartsOn??1,a=[],o=null,s=NaN;for(let r of e){let e=(0,n.timeframeBucketStart)(r.time,t,i);o===null||e!==s?(o!==null&&a.push(o),o={time:e,open:r.open,high:r.high,low:r.low,close:r.close,volume:r.volume},s=e):o={time:o.time,open:o.open,high:Math.max(o.high,r.high),low:Math.min(o.low,r.low),close:r.close,volume:o.volume+r.volume}}return o!==null&&a.push(o),a}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`}];function s(e){return!e||e===`local`?null:e===`exchange`?`exchange`:/^-?\d+$/.test(e)?Number(e):(0,n.isValidTimeZone)(e)?e:null}function c(e){return e===null?`local`:String(e)}function l(e,t,r,i){let a=(0,n.offsetAt)(null,t),c=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}}),l=s(e);typeof l==`number`&&c.push({value:e,label:(0,n.tzLabel)(l),offset:l}),c.sort((e,t)=>e.offset-t.offset);let u=[{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);u.push({value:`exchange`,label:`${i.label} (${(0,n.tzLabel)(e)})`,offset:e})}return[...u,...c]}var u=6,d=8,f=120;function p(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-u-d,o=i.top-u-d;e.scrollHeight<=a||a>=o?(r.top=`${i.bottom+u}px`,r.bottom=`auto`,r.maxHeight=`${Math.max(f,a)}px`):(r.top=`auto`,r.bottom=`${window.innerHeight-i.top+u}px`,r.maxHeight=`${Math.max(f,o)}px`);let s=getComputedStyle(t).direction===`rtl`,c=n===`right`!==s,l=e.offsetWidth,p=c?i.right-l:i.left;r.left=`${Math.max(d,Math.min(p,window.innerWidth-l-d))}px`}var m=700,h=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,p(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<=m?(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||``;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>m?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})))}},ee=42,g=7,_=new Set([`US`,`CA`,`MX`,`BR`,`JP`,`KR`,`TW`,`HK`,`IL`,`PH`,`IN`,`ZA`,`AU`,`TH`,`SA`,`PE`,`CO`]);function v(e){try{let t=new Intl.Locale(e),n=t.getWeekInfo?.()??t.weekInfo;return n?n.firstDay===7?0:1:+!_.has(t.maximize().region??``)}catch{return 1}}function te(e,t,n){let r=(new Date(Date.UTC(e,t,1)).getUTCDay()-n+g)%g,i=[];for(let n=0;n<ee;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 y=e=>String(e).padStart(2,`0`),b=e=>`${String(e.year).padStart(4,`0`)}-${y(e.month+1)}-${y(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{input=null;panel=null;grid=null;titleEl=null;view={year:0,month:0};focusDay=re();onOutside=e=>{let t=e.target;this.panel?.contains(t)||this.input?.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.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.panel?.contains(e)===!0)}open(e){this.close(!1),this.input=e;let t=this.clamp(ne(e.value)??re());this.focusDay=t,this.view={year:t.year,month:t.month};let n=this.labels(),r=document.createElement(`div`);r.className=`tcw-calendar`,r.setAttribute(`role`,`dialog`);let i=e.getAttribute(`aria-label`)??e.labels?.[0]?.textContent??``;i&&r.setAttribute(`aria-label`,i.trim());let a=document.createElement(`div`);a.className=`tcw-calendar-head`;let o=this.navButton(n.prevMonth,-1),s=this.navButton(n.nextMonth,1),c=document.createElement(`div`);c.className=`tcw-calendar-title`,c.setAttribute(`aria-live`,`polite`),a.append(o,c,s);let l=document.createElement(`div`);l.className=`tcw-calendar-weekdays`,l.setAttribute(`aria-hidden`,`true`);let u=v(this.locale()),d=new Intl.DateTimeFormat(this.locale(),{weekday:`narrow`,timeZone:`UTC`});for(let e=0;e<g;e++){let t=document.createElement(`span`);t.className=`tcw-calendar-weekday`,t.textContent=d.format(new Date(Date.UTC(2023,0,1+(u+e)%g))),l.appendChild(t)}let f=document.createElement(`div`);f.className=`tcw-calendar-grid`,f.setAttribute(`role`,`grid`),f.addEventListener(`keydown`,e=>this.onKey(e)),f.addEventListener(`click`,e=>{let t=e.target.closest(`.tcw-calendar-day`);t&&!t.disabled&&t.dataset.date&&this.pick(t.dataset.date)});let m=document.createElement(`div`);m.className=`tcw-calendar-foot`;let h=document.createElement(`button`);h.type=`button`,h.className=`tcw-calendar-today`,h.textContent=n.today,h.addEventListener(`click`,()=>{let e=b(re());this.allowed(e)&&this.pick(e)}),m.appendChild(h),r.append(a,l,f,m),r.addEventListener(`mousedown`,e=>{e.target.closest(`button`)||e.preventDefault()}),r.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&(e.preventDefault(),this.close(!0))}),this.panel=r,this.grid=f,this.titleEl=c,this.render(),this.layer().appendChild(r),p(r,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.panel?.remove(),this.panel=this.grid=this.titleEl=null,this.input=null,e&&t.isConnected&&t.focus())}focusGrid(){this.grid?.querySelector(`[tabindex="0"]`)?.focus()}destroy(){this.close(!1)}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=b(e),n=this.input?.min?ne(this.input.min):null,r=this.input?.max?ne(this.input.max):null;return n&&t<b(n)?n:r&&t>b(r)?r:e}allowed(e){let t=this.input;return t?!(t.min&&e<t.min)&&!(t.max&&e>t.max):!1}render(){let e=this.grid,t=this.input;if(!e||!t||!this.titleEl)return;let n=this.locale();this.titleEl.textContent=new Intl.DateTimeFormat(n,{month:`long`,year:`numeric`,timeZone:`UTC`}).format(new Date(Date.UTC(this.view.year,this.view.month,1)));let r=t.value,i=b(re()),a=b(this.focusDay),o=new Intl.DateTimeFormat(n,{dateStyle:`full`,timeZone:`UTC`});e.textContent=``;let s=null;for(let[t,c]of te(this.view.year,this.view.month,v(n)).entries()){t%g===0&&(s=document.createElement(`div`),s.className=`tcw-calendar-week`,s.setAttribute(`role`,`row`),e.appendChild(s));let n=b(c),l=document.createElement(`button`);l.type=`button`,l.className=`tcw-calendar-day`,l.dataset.date=n,l.setAttribute(`role`,`gridcell`),l.textContent=String(c.day),l.setAttribute(`aria-label`,o.format(new Date(Date.UTC(c.year,c.month,c.day)))),l.setAttribute(`aria-selected`,String(n===r)),l.tabIndex=n===a?0:-1,c.month!==this.view.month&&l.classList.add(`tcw-outside`),n===i&&l.classList.add(`tcw-today`),this.allowed(n)||(l.disabled=!0),s?.appendChild(l)}}onKey(e){let t={ArrowLeft:-1,ArrowRight:1,ArrowUp:-g,ArrowDown:g},n=this.panel?getComputedStyle(this.panel).direction===`rtl`:!1;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===` `){let e=b(this.focusDay);this.allowed(e)&&this.pick(e)}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){let t=this.input;if(!t||!this.allowed(e))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})))}},oe=()=>typeof matchMedia==`function`&&matchMedia(`(pointer: coarse)`).matches,se=()=>typeof CSS>`u`||typeof CSS.supports!=`function`||CSS.supports(`selector(::-webkit-calendar-picker-indicator)`);function ce(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 le(e){return!(e instanceof HTMLInputElement)||e.type!==`date`||e.matches(`:disabled`)||e.readOnly?null:e}function ue(e,t){let n=new h(t.layer),r=new ae(t.layer,t.labels,t.locale),i=t.native??oe,a=t.calendar??se,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=ce(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=le(e.target);t&&(e.preventDefault(),r.isOpenFor(t)||r.open(t))},u=e=>{if(i()||!s(e))return;let t=ce(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=le(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 de=[{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`}],fe=[{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`}]}],pe=[`BTCUSDT`,`ETHUSDT`,`SOLUSDT`,`BNBUSDT`],me={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,logScale:!1,scaleMode:`regular`,autoScale:!0,invertScale:!1,leftPriceScale:!1,crosshairMode:`magnet`,numberLocale:`en-US`,timezone:`local`,highLowLines:!1,mainSeriesVisible:!0,extendedHours:!0,chartTypeOptions:{}},x=(e,...t)=>({label:e,keys:t}),S=(e,t,n={})=>({label:e,keys:[t],auto:n}),C=e=>({hint:e}),he={from:`panes.titleColor`},ge={title:`settings.section.lastPrice`,rows:[x(`settings.priceLine`,`lastPrice.visible`),x(`settings.up`,`lastPrice.upColor`),x(`settings.down`,`lastPrice.downColor`),x(`drawingSettings.lineStyle`,`lastPrice.style`),x(`drawingSettings.lineWidth`,`lastPrice.width`)]},_e={title:`settings.volume`,rows:[x(`settings.up`,`volume.upColor`),x(`settings.down`,`volume.downColor`)]},ve={title:`settings.highLowLines`,rows:[S(`drawingSettings.color`,`highLow.color`,he)]},ye=[ge,_e,ve],be=[x(`settings.legendText`,`legend.textColor`),x(`settings.legendLabels`,`legend.labelColor`),x(`settings.paneTitles`,`panes.titleColor`)],xe=[x(`drawingSettings.text`,`axis.price.textColor`,`axis.time.textColor`),x(`settings.scaleLines`,`axis.price.lineColor`,`axis.time.lineColor`)],Se=[{title:`settings.section.background`,rows:[x(`settings.background`,`background.color`),x(`settings.paneBackground`,`panes.background`),x(`settings.paneSeparator`,`panes.separatorColor`),S(`settings.watermark`,`watermark.color`,he)]},{title:`settings.gridLines`,rows:[x(`settings.horizontal`,`grid.horizontal.visible`),x(`settings.vertical`,`grid.vertical.visible`),x(`drawingSettings.color`,`grid.horizontal.color`,`grid.vertical.color`),x(`drawingSettings.lineStyle`,`grid.horizontal.style`,`grid.vertical.style`),x(`drawingSettings.lineWidth`,`grid.horizontal.width`,`grid.vertical.width`)]},{title:`settings.crosshairMode`,rows:[x(`settings.horizontal`,`crosshair.horizontal.visible`),x(`settings.vertical`,`crosshair.vertical.visible`),x(`drawingSettings.color`,`crosshair.horizontal.color`,`crosshair.vertical.color`),x(`drawingSettings.lineStyle`,`crosshair.horizontal.style`,`crosshair.vertical.style`),x(`drawingSettings.lineWidth`,`crosshair.horizontal.width`,`crosshair.vertical.width`),x(`settings.labelBackground`,`crosshair.labelBackground`),x(`settings.labelText`,`crosshair.labelTextColor`)]},{title:`settings.sessionBreaks`,rows:[S(`drawingSettings.color`,`sessionBreaks.color`,{from:`axis.price.lineColor`}),S(`drawingSettings.lineStyle`,`sessionBreaks.style`),S(`drawingSettings.lineWidth`,`sessionBreaks.width`)]},{title:`objects.drawings`,rows:[S(`settings.handles`,`drawings.handleColor`,C(`#ffffff`))]}],Ce=[{title:`settings.section.orders`,trading:!0,rows:[S(`ticket.buy`,`trading.buyColor`,C(n.DEFAULT_TRADING_CONFIG.orderColors?.buy)),S(`ticket.sell`,`trading.sellColor`,C(n.DEFAULT_TRADING_CONFIG.orderColors?.sell)),S(`settings.profit`,`trading.profitColor`,C(n.DEFAULT_TRADING_CONFIG.positionColors?.profit)),S(`settings.loss`,`trading.lossColor`,C(n.DEFAULT_TRADING_CONFIG.positionColors?.loss)),S(`account.entry`,`trading.entryColor`,C(n.DEFAULT_TRADING_CONFIG.positionColors?.entry))]},{title:`settings.section.signals`,rows:[S(`account.long`,`markers.longColor`,C(n.DEFAULT_SIGNAL_STYLE.longColor)),S(`account.short`,`markers.shortColor`,C(n.DEFAULT_SIGNAL_STYLE.shortColor)),S(`markers.neutral`,`markers.neutralColor`,C(n.DEFAULT_SIGNAL_STYLE.neutralColor))]},{title:`settings.section.tradeZones`,rows:[S(`settings.profit`,`tradeZones.profitColor`,C(n.DEFAULT_TRADE_ZONE_STYLE.profitColor)),S(`settings.loss`,`tradeZones.lossColor`,C(n.DEFAULT_TRADE_ZONE_STYLE.lossColor)),S(`settings.openTrade`,`tradeZones.activeColor`,C(n.DEFAULT_TRADE_ZONE_STYLE.activeColor))]}],we={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`},Te=new Set([`candlestick`,`heikinAshi`,`volumeCandles`,`equivolume`]);function Ee(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=we[r]??`drawingSettings.color`;return Te.has(e)&&r===`upColor`&&(i=`settings.upBody`),Te.has(e)&&r===`downColor`&&(i=`settings.downBody`),e===`baseline`&&r===`upColor`&&(i=`settings.aboveBase`),e===`baseline`&&r===`downColor`&&(i=`settings.belowBase`),x(i,n)})}var w=[...new Set([...Object.keys(n.CHART_STYLE_KEYS).filter(e=>e.startsWith(`series.`)),...[...ye,...Se,...Ce].flatMap(e=>e.rows.flatMap(e=>e.keys)),...[...be,...xe].flatMap(e=>e.keys)])],De=`/* === TradeCanvas Widget — Premium Styles === */
2
2
 
3
3
  /*
4
4
  * The HTML \`hidden\` attribute only sets \`display: none\` via the UA stylesheet,
@@ -3539,31 +3539,38 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
3539
3539
  }
3540
3540
 
3541
3541
  /* --- Drawing settings dialog --- */
3542
- .tcw-drawing-settings .tcw-modal-footer { gap: 12px; }
3543
- .tcw-drawing-settings-tools {
3544
- display: flex;
3545
- gap: 14px;
3546
- margin-inline-end: auto;
3547
- }
3548
3542
  .tcw-drawing-text {
3549
3543
  min-height: 56px;
3550
3544
  resize: vertical;
3551
3545
  font-family: inherit;
3552
3546
  }
3553
- .tcw-levels-editor { display: grid; gap: 6px; margin-bottom: 10px; }
3547
+ /* The text a drawing writes takes the dialog's width, under its name. */
3548
+ .tcw-text-row {
3549
+ flex-direction: column;
3550
+ align-items: stretch;
3551
+ gap: var(--tcw-space-3);
3552
+ }
3553
+ .tcw-text-row .tcw-drawing-text { box-sizing: border-box; width: 100%; }
3554
+ .tcw-levels-editor { display: grid; gap: var(--tcw-space-3); }
3555
+ /* Two columns of levels on a desktop, as a Fibonacci tool has a dozen. */
3554
3556
  .tcw-levels-grid {
3555
3557
  display: grid;
3556
- gap: 4px;
3558
+ grid-template-columns: repeat(2, minmax(0, 1fr));
3559
+ gap: var(--tcw-space-3) var(--tcw-space-6);
3557
3560
  max-height: 260px;
3558
3561
  overflow-y: auto;
3559
- padding-right: 2px;
3562
+ padding-inline-end: var(--tcw-space-1);
3563
+ }
3564
+ @media (max-width: 640px) {
3565
+ .tcw-levels-grid { grid-template-columns: minmax(0, 1fr); }
3560
3566
  }
3561
3567
  .tcw-level-row {
3562
3568
  display: grid;
3563
- grid-template-columns: auto minmax(0, 1fr) 32px 24px;
3569
+ grid-template-columns: auto minmax(0, 1fr) auto auto;
3564
3570
  align-items: center;
3565
- gap: 8px;
3571
+ gap: var(--tcw-space-3);
3566
3572
  }
3573
+ .tcw-level-row .tcw-indi-input { box-sizing: border-box; width: 100%; min-width: 0; }
3567
3574
  .tcw-level-row input[type='checkbox'] { accent-color: var(--tcw-accent); }
3568
3575
  .tcw-level-remove {
3569
3576
  display: inline-flex;
@@ -3580,8 +3587,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
3580
3587
  .tcw-level-remove:hover { color: var(--tcw-text); background: var(--tcw-bg-elevated); }
3581
3588
  .tcw-level-remove:focus-visible { outline: 2px solid var(--tcw-accent); outline-offset: 1px; }
3582
3589
  .tcw-level-add { justify-self: start; }
3583
- .tcw-drawing-templates { display: grid; gap: 2px; margin-bottom: 8px; }
3584
- .tcw-drawing-alert { display: inline-flex; align-items: center; gap: 6px; }
3585
3590
 
3586
3591
  /* --- Context menu (right-click on a drawing) --- */
3587
3592
  .tcw-context-menu {
@@ -5803,11 +5808,12 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5803
5808
  }
5804
5809
  }
5805
5810
 
5806
- /* === The indicator settings === */
5811
+ /* === The indicator settings, and a drawing's === */
5807
5812
 
5808
5813
  /* One half step of phi under the indicators dialog: 610 / sqrt(phi) = 480. */
5809
5814
  @media (min-width: 641px) {
5810
- .tcw-modal.tcw-modal-narrow.tcw-indi {
5815
+ .tcw-modal.tcw-modal-narrow.tcw-indi,
5816
+ .tcw-modal.tcw-modal-narrow.tcw-drawing-settings {
5811
5817
  width: 480px;
5812
5818
  max-width: 92vw;
5813
5819
  }
@@ -5861,7 +5867,8 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5861
5867
 
5862
5868
  /* Defaults on the left; Cancel and Ok on the right, one height for all three. */
5863
5869
  .tcw-indi .tcw-modal-footer,
5864
- .tcw-set .tcw-modal-footer {
5870
+ .tcw-set .tcw-modal-footer,
5871
+ .tcw-drawing-settings .tcw-modal-footer {
5865
5872
  gap: var(--tcw-space-4);
5866
5873
  }
5867
5874
 
@@ -5872,7 +5879,8 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5872
5879
  }
5873
5880
 
5874
5881
  .tcw-indi .tcw-modal-footer button,
5875
- .tcw-set .tcw-modal-footer button {
5882
+ .tcw-set .tcw-modal-footer button,
5883
+ .tcw-drawing-settings .tcw-modal-footer button {
5876
5884
  height: var(--tcw-menu-item-h);
5877
5885
  padding-block: 0;
5878
5886
  }
@@ -5908,11 +5916,75 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5908
5916
  .tcw-footer-menu:focus-visible,
5909
5917
  .tcw-footer-cancel:focus-visible,
5910
5918
  .tcw-indi .tcw-done-btn:focus-visible,
5911
- .tcw-set .tcw-done-btn:focus-visible {
5919
+ .tcw-set .tcw-done-btn:focus-visible,
5920
+ .tcw-drawing-settings .tcw-done-btn:focus-visible {
5912
5921
  outline: none;
5913
5922
  box-shadow: var(--tcw-ring);
5914
5923
  }
5915
5924
 
5925
+ /* A drawing's switches: the box, then its name, a list without rules between. */
5926
+ .tcw-check-row {
5927
+ justify-content: flex-start;
5928
+ gap: var(--tcw-space-4);
5929
+ padding-block: var(--tcw-space-3);
5930
+ cursor: pointer;
5931
+ }
5932
+
5933
+ .tcw-settings-row + .tcw-check-row,
5934
+ .tcw-check-row + .tcw-settings-row {
5935
+ border-top: 0;
5936
+ }
5937
+
5938
+ /* A point: its name, then its price, date and time in columns; on a phone the price over the date and time. */
5939
+ .tcw-draw-point {
5940
+ display: grid;
5941
+ grid-template-columns: auto minmax(0, 1fr) minmax(0, 1.3fr) minmax(0, 1fr);
5942
+ gap: var(--tcw-space-4);
5943
+ }
5944
+
5945
+ .tcw-draw-point > .tcw-settings-label {
5946
+ white-space: nowrap;
5947
+ }
5948
+
5949
+ .tcw-draw-point .tcw-indi-plot-controls {
5950
+ display: contents;
5951
+ }
5952
+
5953
+ .tcw-draw-point input {
5954
+ box-sizing: border-box;
5955
+ width: 100%;
5956
+ min-width: 0;
5957
+ }
5958
+
5959
+ .tcw-draw-point input[type='number'] {
5960
+ text-align: end;
5961
+ }
5962
+
5963
+ @media (max-width: 640px) {
5964
+ .tcw-draw-point {
5965
+ grid-template-columns: auto minmax(0, 1fr) minmax(0, 1fr);
5966
+ }
5967
+
5968
+ .tcw-draw-point > .tcw-settings-label {
5969
+ grid-row: span 2;
5970
+ }
5971
+
5972
+ .tcw-draw-point input[type='number'] {
5973
+ grid-column: span 2;
5974
+ }
5975
+ }
5976
+
5977
+ .tcw-drawing-settings .tcw-indi-plot-controls input[type='number']:not(.tcw-draw-point *) {
5978
+ width: 68px;
5979
+ text-align: end;
5980
+ }
5981
+
5982
+ /* The unit after a number (the fill's opacity in %). */
5983
+ .tcw-unit {
5984
+ margin-inline-start: calc(-1 * var(--tcw-space-2));
5985
+ color: var(--tcw-text-muted);
5986
+ }
5987
+
5916
5988
  /* === The chart settings === */
5917
5989
 
5918
5990
  /* 776 x 610: half a step of phi wider than the indicators dialog (610 x sqrt(phi) = 776), as tall as it,
@@ -5954,20 +6026,20 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
5954
6026
  `)}function E(e,...t){e.dataset.tcwPart=t.join(` `)}function Ve(...e){return`data-tcw-part="${e.join(` `)}"`}function He(e){return Object.prototype.hasOwnProperty.call(Pe,e)?Pe[e]:void 0}function Ue(e,t,n){let r=[...e.children],i=e=>e.classList.contains(t);for(let e of r)i(e)&&e.classList.remove(Re);let a=e=>!e.hidden&&getComputedStyle(e).display!==`none`,o=e=>a(e)&&(e instanceof HTMLButtonElement||e.childElementCount>0||e.textContent!==``),s=!1,c=null;for(let e of r)if(n!==void 0&&e.classList.contains(n))c?.classList.add(Re),c=null,s=!1;else if(i(e)){if(!a(e))continue;s?(c=e,s=!1):e.classList.add(Re)}else o(e)&&(s=!0,c=null);c?.classList.add(Re)}function We(e,t,n){let r=e.flatMap(e=>{if(e===`separator`)return[e];if(!(t[e.id]??[]).every(e=>n[e]))return[];if(!e.submenu)return[e];let r=We(e.submenu,t,n);return r.length>0?[{...e,submenu:r}]:[]});return r.filter((e,t)=>{if(e!==`separator`)return!0;let n=r.slice(0,t).some(e=>e!==`separator`),i=r[t+1];return n&&i!==void 0&&i!==`separator`})}var Ge=0,Ke=`tcw-styles`;function qe(){if(Ge++,Ge>1||document.getElementById(Ke))return;let e=document.createElement(`style`);e.id=Ke,e.textContent=`${De}
5955
6027
  ${Oe}
5956
6028
  ${ke}
5957
- ${Be()}`,document.head.insertBefore(e,document.head.firstChild)}function Je(){if(Ge--,Ge>0)return;let e=document.getElementById(Ke);e&&e.remove()}var Ye=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function D(e,t=14){let r=Ye(n.UI_ICONS,e);return r?(0,n.iconSvg)(r,t):``}function O(e,t=16){return(0,n.iconSvg)(Ye(n.DRAWING_TOOL_ICONS,e)??n.UI_ICONS.penLine,t)}function Xe(e,t=14){return(0,n.iconSvg)(Ye(n.CHART_TYPE_ICONS,e)??n.UI_ICONS.barChart,t)}function k(e){return e.replace(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`})[e])}var Ze=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(){p(this.panel,this.trigger,this.align)}},Qe=4,$e=150,et=`[role=menuitem], [role=menuitemcheckbox], [role=menuitemradio]`,tt=`(max-width: 640px)`,nt=`tcw:back`;function rt(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 it(e){return e.radio?`menuitemradio`:e.checked===void 0?`menuitem`:`menuitemcheckbox`}function at(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===void 0?e.icon&&D(e.icon,14)||t:e.checked?D(`check`,14):t}var A=class e{el;onPick=null;onRemove=null;returnFocus=null;anchor=null;child=null;parent=null;hoverTimer=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){this.show(e,{x:t,y:n,xBack:t,yBack:n},r,i,a,!0)}close(){if(this.clearHover(),this.child?.close(),this.el.hidden)return;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}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;let o=this.host.getBoundingClientRect(),s=Math.min(this.host.clientWidth,window.innerWidth-o.left)-Qe,c=Math.min(this.host.clientHeight,window.innerHeight-o.top)-Qe;this.el.style.maxHeight=`${Math.max(0,c)}px`,this.el.style.left=`${rt(t.x,this.el.offsetWidth,s,t.xBack,t.before)}px`,this.el.style.top=`${rt(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})}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`,it(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=at(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(`pointerenter`,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.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`,D(`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=D(`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?.(tt).matches??!1,l=c?[{id:nt,label:t,icon:`chevronLeft`},`separator`,...n]:n;i.show(l,s,e=>{e!==nt&&this.pick(e)},e,e=>this.onRemove?.(e),r);let u=c?i.el.querySelector(`[data-id="${nt}"]`):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){this.clearHover();let r=this.child?.isOpen()?this.child.anchor:null;(n?r===e:r===null)||(this.hoverTimer=setTimeout(()=>{this.hoverTimer=null,n?this.openSubmenu(e,t,n,!1):this.child?.close()},$e))}clearHover(){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(et)]}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})}},ot=[`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`],st=65234;function ct(e){return(e&&!ot.includes(e)?[e,...ot]:ot).map(e=>{let t;try{t=new Intl.NumberFormat(e,{minimumFractionDigits:2,maximumFractionDigits:2}).format(st)}catch{t=``}return{value:e,label:t?`${e} (${t})`:e}})}var lt={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 ut(e,t){let n=`chartType.${e.value}`,r=t(n);return r===n?e.label:r}function dt(e,t){return e.map(e=>({...e,label:lt[e.label]?t(lt[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 ft=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`,`1w`,`1M`],pt=[`1m`,`5m`,`15m`,`1h`,`4h`,`1d`],mt=6;function ht(e){let t=e.slice(-1);return t===`h`||t===`d`||t===`w`?e.slice(0,-1)+t.toUpperCase():e}var gt=e=>Number.isFinite((0,n.timeframeToMs)(e))||(0,n.tickBarCount)(e)!==null,_t=(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 vt(e,t){let n=t?.length?t:null,r=e?.length?e:n??ft;return[...new Set(r)].filter(e=>gt(e)&&(!n||n.includes(e))).sort(_t)}function yt(e,t,n=!1){if(t?.length)return e.filter(e=>t.includes(e));if(n)return[...e];let r=e.filter(e=>pt.includes(e));return r.length>0?r:e.slice(0,mt)}var bt=9999,xt={"":`m`,s:`s`,S:`s`,m:`m`,h:`h`,H:`h`,d:`d`,D:`d`,w:`w`,W:`w`,M:`M`},St={s:[`m`,60],m:[`h`,60],h:[`d`,24]};function Ct(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])<=bt&&(0,n.tickBarCount)(e)!==null?e:null}let r=Number(t[1]),i=xt[t[2]];if(!i||!Number.isSafeInteger(r)||r<1)return null;for(let e=St[i];e&&r%e[1]===0;e=St[i])r/=e[1],i=e[0];if(r>bt)return null;let a=`${r}${i}`;return(0,n.isTimeFrame)(a)?a:null}function wt(e,t,n){let r=n?.length?n:null,i=t.filter(e=>gt(e)&&(!r||r.includes(e)));return[...new Set([...e,...i])].sort(_t)}var Tt=[`T`,`s`,`m`,`h`,`d`,`w`,`M`];function Et(e){let t=e=>{let t=e.slice(-1);return Tt.includes(t)?t:`m`};return Tt.map(n=>({unit:n,timeframes:e.filter(e=>t(e.value)===n)})).filter(e=>e.timeframes.length>0)}var Dt=864e5,Ot=5/7;function kt(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<Dt)return e.barsInSpan*t/n;let r=e.spanMs/n;return n===Dt?r*(e.dayShare??Ot):r},a=[...new Set([...e.available,e.current])].filter(e=>{let t=(0,n.timeframeToMs)(e);return Number.isFinite(t)&&t>=r}).sort(_t);for(let t of a)if(i((0,n.timeframeToMs)(t))*2<=e.width)return t;return a[a.length-1]??e.current}var At={ticket:`receipt`,long:`trendingUp`,short:`trendingDown`,ladder:`ladder`,account:`layers`},jt=[`ladder`,`account`],Mt=2;function Nt(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 Pt=class e{button;menu=null;open=new Set;static create(t,n,r,i){let a=Nt(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`),E(i,`toolbar.trade`),i.innerHTML=`${D(`trendingUp`,14)} <span class="tcw-trigger-label">${k(t(`toolbar.trade`))}</span> ${D(`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=jt.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.map(e=>jt.includes(e.id)?{id:e.id,label:e.label,checked:this.open.has(e.id)}:{id:e.id,label:e.label,icon:At[e.id]}),r=this.root();this.menu??=new A(r,this.t(`toolbar.trade`));let i=e.getBoundingClientRect(),a=r.getBoundingClientRect();this.menu.open(n,i.left-a.left,i.bottom-a.top+Mt,e=>{t.find(t=>t.id===e)?.run()},e)}},Ft=0,It={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 Lt(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 Rt=class{config;callbacks;t;el;chartTypeDropdown=null;tfGroup=null;tfDropdown=null;tfFavorites=[];uid=(Ft++).toString(36);tfRendered=``;themeBtn=null;fullscreenBtn=null;hostLeft=null;hostRight=null;moreMenu=null;tfCurrent=null;resizeObserver=null;moreBtn=null;fitFrame=0;undoBtn=null;redoBtn=null;trade=null;constructor(e,t,n,r,i){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`,E(this.el,`toolbar`),this.build(),e.appendChild(this.el),typeof ResizeObserver<`u`&&(this.resizeObserver=new ResizeObserver(()=>this.fit()),this.resizeObserver.observe(this.el)),document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.fit()}))}anchorOf(e){return(e.hasAttribute(`data-tcw-folded`)||this.el.closest(`[data-tcw-narrow]`)!==null)&&this.moreBtn?this.moreBtn:e}fit(){let{el:e}=this,t=()=>e.scrollWidth<=e.clientWidth+1,n=[...e.querySelectorAll(`.tcw-toolbar-overflow`)];for(let e of n)e.removeAttribute(`data-tcw-folded`);if(e.classList.remove(`tcw-toolbar--collapsed`,`tcw-toolbar--icons`),!(e.clientWidth===0||t())){e.classList.add(`tcw-toolbar--collapsed`);for(let e=n.length-1;e>=0;e--)if(n[e].setAttribute(`data-tcw-folded`,``),t())return;e.classList.add(`tcw-toolbar--icons`);for(let e of n)if(e.removeAttribute(`data-tcw-folded`),!t()){e.setAttribute(`data-tcw-folded`,``);break}}}build(){let{config:e,callbacks:t,el:n}=this,r=document.createElement(`button`);if(r.className=`tcw-toolbar-symbol`,r.dataset.role=`symbol`,E(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`,E(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`,E(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`,E(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`,D(`chevronDown`,12)),e.appendChild(t),n.appendChild(e),this.tfDropdown=new Ze(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`,E(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 Ze(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`),E(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`,E(e,`compare`,`toolbar.compare`);let r=this.t(`objects.compare`);e.setAttribute(`aria-label`,r),e.title=r,e.innerHTML=`${D(`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`,E(this.undoBtn,`toolbar.undo`,`sidebar.undo`),this.redoBtn=this.iconBtn(`redo`,this.t(`drawing.redo`),t.onRedo),this.redoBtn.dataset.role=`redo`,E(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`,E(r,`layouts`,`toolbar.layouts`),r.setAttribute(`aria-haspopup`,`menu`),r.addEventListener(`click`,()=>e(this.anchorOf(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`,E(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(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(e,`alerts`,`toolbar.alerts`),n.appendChild(e)}this.trade=Pt.create(t,this.t,()=>this.rootEl(),e=>this.anchorOf(e)),this.trade&&n.appendChild(this.trade.button),n.appendChild(this.sep());let s=this.iconBtn(`camera`,this.t(`toolbar.screenshot`),t.onScreenshot);E(s,`screenshot`,`toolbar.screenshot`),n.appendChild(s);let c=this.iconBtn(`settings`,this.t(`toolbar.settings`),t.onSettings);E(c,`settings`,`toolbar.settings`),n.appendChild(c),this.themeBtn=this.iconBtn(`moon`,this.t(`toolbar.toggleTheme`),t.onToggleTheme),this.themeBtn.dataset.role=`theme`,E(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`,E(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=D(`more`,16),l.addEventListener(`click`,()=>this.toggleMore(l)),n.appendChild(l),this.moreBtn=l}toggleMore(e){if(this.moreMenu?.isOpen()){this.moreMenu.close();return}let t=this.rootEl(),n=new Set((t.getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean)),r=e=>(e.dataset.tcwPart??``).split(/\s+/).some(e=>n.has(e)),i=this.el.closest(`[data-tcw-narrow]`)!==null,a=[];for(let e of this.el.querySelectorAll(`.tcw-toolbar-overflow`)){if(r(e)||!i&&!e.hasAttribute(`data-tcw-folded`))continue;let t=e instanceof HTMLButtonElement?[e]:[...e.querySelectorAll(`button`)];a.push(...t.filter(e=>!e.hidden&&!e.disabled&&!r(e)))}if(a.length===0)return;let o=a.map((e,t)=>{let n=e.title||e.getAttribute(`aria-label`)||e.textContent?.trim()||``;return e.getAttribute(`aria-pressed`)===`true`?{id:String(t),label:n,checked:!0}:{id:String(t),label:n,icon:e.dataset.icon}});this.moreMenu??=new A(t,this.t(`toolbar.more`));let s=e.getBoundingClientRect(),c=t.getBoundingClientRect();this.moreMenu.open(o,s.right-c.left,s.bottom-c.top+2,e=>a[Number(e)]?.click(),e)}addHostButton(e){let t=document.createElement(`button`);t.type=`button`,t.className=e.text||!e.icon?`tcw-btn tcw-host-btn`:`tcw-btn-icon tcw-host-btn`,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=D(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 Lt(t,e.label),t.addEventListener(`click`,()=>e.onClick(t)),e.side!==`left`&&t.classList.add(`tcw-toolbar-overflow`),(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(),Ue(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)))}setLayout(e,t){let n=this.el.querySelector(`[data-role="layouts"]`);if(!n)return;let r=e??this.t(`layouts.unnamed`),i=`${this.t(`toolbar.layouts`)}: ${r}${t?` (${this.t(`layouts.unsavedChanges`)})`:``}`;n.innerHTML=`${D(`save`,14)}<span class="tcw-layouts-label">${k(r)}</span>`+(t?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+D(`chevronDown`,12),n.title=i,n.setAttribute(`aria-label`,i)}setFullscreen(e){if(!this.fullscreenBtn)return;let t=this.t(e?`toolbar.exitFullscreen`:`toolbar.fullscreen`);this.fullscreenBtn.innerHTML=D(e?`minimize`:`maximize`,14),this.fullscreenBtn.title=t,this.fullscreenBtn.setAttribute(`aria-pressed`,String(e))}chartTypeLabel(e){return ut(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)}">${Xe(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 Et(this.config.timeframes)){n+=`<div class="tcw-tf-section" data-tf-section="${r}" role="group" aria-label="${k(this.t(It[r]))}"><div class="tcw-dropdown-label">${k(this.t(It[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}">${D(`x`,12)}</button>`:``)+`<button class="tcw-tf-star${i?` tcw-active`:``}" data-tf-star="${a}" aria-pressed="${i}" title="${e}" aria-label="${e}: ${o}">${D(`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" ${Ve(`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}">${D(`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))}update(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(t.textContent=e.symbol),this.renderTimeframes(e.timeframe);let n=this.el.querySelector(`[data-role="charttype"]`);if(n){let t=this.config.chartTypes.find(t=>t.value===e.chartType),r=t?this.chartTypeLabel(t):e.chartType;n.innerHTML=Xe(e.chartType,16),n.title=r,n.setAttribute(`aria-label`,r)}let r=this.el.querySelector(`[data-role="indicators"]`);if(r){let t=e.activeIndicators.size,n=`${D(`trendingUp`,14)} <span class="tcw-trigger-label">${k(this.t(`toolbar.indicators`))}</span>`;r.setAttribute(`aria-label`,this.t(`toolbar.indicators`)),t>0&&(n+=` <span class="tcw-badge-count">${t}</span>`),r.innerHTML=n}if(this.themeBtn){let t=e.isDark?`moon`:`sun`;this.themeBtn.innerHTML=D(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=D(e,14),r.addEventListener(`click`,n),r}destroy(){this.resizeObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.chartTypeDropdown?.destroy(),this.tfDropdown?.destroy(),this.moreMenu?.destroy(),this.trade?.destroy(),this.el.remove()}};function zt(e,t,n){e.classList.toggle(`tcw-active`,t),n&&e.setAttribute(`aria-pressed`,String(t))}function Bt(e,t,n){let r=e.querySelector(`.tcw-host-btn-text`);r||(r=document.createElement(`span`),r.className=`tcw-host-btn-text`,e.appendChild(r)),r.textContent=n,Lt(e,t)}var Vt=16,Ht=150,Ut=4;function Wt(e){let t=`sidebar.${e}`;return T.includes(t)?t:null}function Gt(e,t){for(let n of e){let e=n.tools.find(e=>e.value===t);if(e)return e.label}return t}var Kt=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`,E(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=D(`penLine`,18),E(this.fab,`sidebar`),this.fab.addEventListener(`click`,()=>this.setOpen(!this.isOpen())),e.appendChild(this.fab)}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=D(`cursor`,14),this.cursorBtn.addEventListener(`click`,()=>{t.onCancelDrawing(),this.closeForChart()}),E(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`,E(this.favoritesEl,`sidebar.favorites`),n.appendChild(this.favoritesEl),this.favoritesDivider=this.divider(),E(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=Wt(e.section);a&&E(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=O(s,Vt),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`,E(e,`sidebar.style`),e.innerHTML=D(`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=D(`magnet`,14),this.magnetBtn.addEventListener(`click`,t.onToggleMagnet),E(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()}),E(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()}),E(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=D(`repeat`,14),this.stayBtn.addEventListener(`click`,t.onToggleStayInDrawing),E(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`,E(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`,E(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=D(`trash`,14),a.addEventListener(`click`,t.onClearDrawings),E(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:Gt(this.config.drawingToolGroups,e)}),n.dataset.toolValue=e,n.innerHTML=O(e,Vt),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=O(e.value,Vt);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,E(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=D(`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-Ut*2)}px`;let i=this.host.clientHeight-e.offsetHeight-Ut;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()},Ht)}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?O(e.activeTool,18):D(`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=O(e.activeTool,Vt),n[t].tools.length>1&&this.groupButtons[t].setAttribute(`aria-label`,`${n[t].label}: ${Gt(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=D(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=D(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(){Ue(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=D(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()}},qt=`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function j(e,t){if(e.key!==`Tab`)return;let n=document.activeElement,r=[...t.querySelectorAll(qt)].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 M(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 Jt(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 N(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 Yt(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=Xt(e),n.addEventListener(`input`,()=>t(n.value)),n}function P(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 Xt(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=Zt(t);return r!==null&&r!==t?Xt(r):`#000000`}var F;function Zt(e){if(F===void 0)try{F=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):null}catch{F=null}if(!F)return null;F.fillStyle=`#010203`,F.fillStyle=e;let t=String(F.fillStyle);return t===`#010203`?null:t}function Qt(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 $t(e,t){let n=Xt(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=0;function tn(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 nn(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 rn(e,t,n,r,i){let a=nn(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-${++en}`,s.setAttribute(`aria-describedby`,c.id);let l=null,u=t=>{s.value=Xt(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 I(e,t,n){let r=nn(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 L(e,t,n,r){let i=nn(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 an(e,t,n,r,i=e=>String(e)){let a=nn(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 on(e,t,n,r,i){let a=document.createElement(`div`);a.className=`tcw-settings-row`;let o=document.createElement(`label`);o.className=`tcw-settings-label`,o.textContent=e,a.appendChild(o);let s=document.createElement(`input`);return s.type=`number`,s.className=`tcw-settings-number`,s.min=`0`,s.step=n.step,Number.isFinite(n.max)&&(s.max=String(n.max)),s.placeholder=i(`settings.auto`),s.value=t===null?``:String(t),s.setAttribute(`aria-label`,e),s.addEventListener(`change`,()=>{if(s.value.trim()===``){s.removeAttribute(`aria-invalid`),r(null);return}let e=Number(s.value),t=Number.isFinite(e)&&e>0&&e<=n.max&&(n.step!==`1`||Number.isInteger(e));s.toggleAttribute(`aria-invalid`,!t),t&&r(e)}),a.appendChild(s),a}var R=[{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`}],sn=[1,2,3,4],cn=`t:`,ln=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=ln++;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){this.modal&&(this.currentSettings={...e},t!==void 0&&(this.chartType=t),this.renderTabContent())}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}j(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=D(`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=R.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:`)?Xe(t.slice(10),16):D(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>${D(`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=R.findIndex(e=>e.id===this.currentTab),n=e.key===`ArrowDown`||e.key===`ArrowRight`?(t+1)%R.length:e.key===`ArrowUp`||e.key===`ArrowLeft`?(t-1+R.length)%R.length:e.key===`Home`?0:e.key===`End`?R.length-1:-1;n<0||(e.preventDefault(),this.selectTab(R[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:`${cn}${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(cn)&&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 Ce)(!e.trading||this.available.trading!==!1)&&this.renderLookSection(e);break}}renderSymbolTab(e){this.renderChartTypeSection(),this.addSection(void 0,[I(this.t(`settings.mainSeries`),e.mainSeriesVisible,e=>this.patch({mainSeriesVisible:e})),I(this.t(`settings.extendedHours`),e.extendedHours,e=>this.patch({extendedHours:e}))]);let t=this.t(`common.show`);this.renderLookSection(ge),this.renderLookSection(_e,[I(t,e.volumeVisible,e=>this.patch({volumeVisible:e}))]),this.renderLookSection(ve,[I(t,e.highLowLines,e=>this.patch({highLowLines:e}))])}renderStatusLineTab(e){this.addSection(void 0,[I(this.t(`settings.ohlcLegend`),e.legendVisible,e=>this.patch({legendVisible:e})),...be.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=l(e.timezone,Date.now(),this.t(`settings.timezone.local`),this.available.exchangeZone?{label:this.t(`settings.timezone.exchange`),zone:this.available.exchangeZone()}:void 0);this.addSection(void 0,[L(this.t(`settings.priceScale`),e.scaleMode,t,e=>this.patch({scaleMode:e})),I(this.t(`settings.autoScale`),e.autoScale,e=>this.patch({autoScale:e})),I(this.t(`settings.invertScale`),e.invertScale,e=>this.patch({invertScale:e})),I(this.t(`settings.leftScale`),e.leftPriceScale,e=>this.patch({leftPriceScale:e})),I(this.t(`settings.indicatorValues`),e.indicatorValueLabels,e=>this.patch({indicatorValueLabels:e})),...this.available.barCountdown===!1?[]:[I(this.t(`settings.barCountdown`),e.barCountdown,e=>this.patch({barCountdown:e}))],L(this.t(`settings.timezone`),e.timezone,n,e=>this.patch({timezone:e})),L(this.t(`settings.numberLocale`),e.numberLocale,ct(e.numberLocale),e=>this.patch({numberLocale:e}))]),this.addSection(this.t(`settings.section.axes`),xe.map(e=>this.lookRow(e)))}renderAppearanceTab(e){let[t,n,r,...i]=Se;this.renderLookSection(t),this.renderLookSection(n,[I(this.t(`common.show`),e.gridVisible,e=>this.patch({gridVisible:e}))]),this.renderLookSection(r,[L(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,[I(n(`settings.volumeProfile`),e.volumeProfileVisible,e=>this.patch({volumeProfileVisible:e}))]),this.addSection(void 0,[I(n(`settings.marketProfile`),e.marketProfileVisible,e=>this.patch({marketProfileVisible:e})),I(n(`settings.marketProfileSplit`),e.marketProfileSplit,e=>this.patch({marketProfileSplit:e})),I(n(`settings.marketProfileLetters`),e.marketProfileLetters,e=>this.patch({marketProfileLetters:e})),an(n(`settings.marketProfileBuckets`),e.marketProfileBuckets,{min:8,max:200,step:1},e=>this.patch({marketProfileBuckets:e})),an(n(`settings.marketProfileOpacity`),e.marketProfileOpacity,{min:.05,max:1,step:.05},e=>this.patch({marketProfileOpacity:e}),t)]),this.addSection(void 0,[I(n(`settings.depthHeatmap`),e.depthHeatmapVisible,e=>this.patch({depthHeatmapVisible:e})),an(n(`settings.depthHeatmapOpacity`),e.depthHeatmapOpacity,{min:.1,max:1,step:.05},e=>this.patch({depthHeatmapOpacity:e}),t)]),this.addSection(void 0,[I(n(`settings.swingMarkers`),e.pivotMarkersVisible,e=>this.patch({pivotMarkersVisible:e})),an(n(`settings.swingStrength`),e.pivotStrength,{min:2,max:20,step:1},e=>this.patch({pivotStrength:e})),I(n(`settings.swingStructure`),e.pivotStructureLabels,e=>this.patch({pivotStructureLabels:e}))]),this.addSection(void 0,[I(n(`settings.sessionShading`),e.sessionShadingVisible,e=>this.patch({sessionShadingVisible:e})),I(n(`settings.periodLevels`),e.periodLevelsVisible,e=>this.patch({periodLevelsVisible:e})),L(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=tn(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=I(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=L(t,i(),[...s,...this.lineStyles()],e=>o(e===``?null:fn(e))),c=()=>{a.querySelector(`select`).value=i()};break;case`width`:{let e=r(),n=typeof e==`number`&&!sn.includes(e)?[...sn,e].sort((e,t)=>e-t):sn;a=L(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=rn(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=de.find(t=>t.value===e),r=tn(n?ut(n,this.t):e),i=()=>this.currentSettings?.chartTypeOptions??{},a=(e,t)=>this.patch({chartTypeOptions:{...i(),[e]:t}}),o=(e,t,n,i,a)=>r.appendChild(on(this.t(e),t,{step:n,max:i},a,this.t));switch(e){case`renko`:{let e=t.renko??{};o(`settings.boxSize`,typeof e.boxSize==`number`?e.boxSize:null,`any`,1/0,e=>a(`renko`,{...i().renko??{},boxSize:e??`atr`})),o(`settings.atrPeriod`,e.atrPeriod??null,`1`,500,e=>a(`renko`,dn(i().renko,`atrPeriod`,e)));break}case`lineBreak`:o(`settings.lineBreakLines`,t.lineBreak?.lines??null,`1`,10,e=>a(`lineBreak`,dn(i().lineBreak,`lines`,e)));break;case`kagi`:o(`settings.reversal`,t.kagi?.reversal??null,`any`,1/0,e=>a(`kagi`,dn(i().kagi,`reversal`,e))),r.appendChild(L(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,`any`,1/0,e=>a(`pointAndFigure`,{...i().pointAndFigure??{},boxSize:e??`auto`})),o(`settings.reversalBoxes`,t.pointAndFigure?.reversal??null,`1`,10,e=>a(`pointAndFigure`,dn(i().pointAndFigure,`reversal`,e)));break;case`rangeBars`:o(`settings.barRange`,typeof t.rangeBars?.range==`number`?t.rangeBars.range:null,`any`,1/0,e=>a(`rangeBars`,{range:e??`auto`}));break;default:break}for(let t of Ee(e))r.appendChild(this.lookRow(t));this.bodyEl.appendChild(r)}patch(e){this.currentSettings&&Object.assign(this.currentSettings,e),this.callbacks.onChange(e)}};function dn(e,t,n){let r={...e??{}};return n===null?delete r[t]:r[t]=n,r}function fn(e){return e===`dashed`||e===`dotted`?e:`solid`}var pn=class{el;dotEl;messageEl;marketEl;hostLeft;hostRight;clockBtn=null;clockMenu=null;scaleBtns=null;scaleShown=``;constructor(e,t,n={}){this.host=e,this.extras=n,this.el=document.createElement(`div`),this.el.className=`tcw-statusbar`,E(this.el,`statusBar`),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.hostRight=this.hostGroup(),r.appendChild(this.hostRight);let i=document.createElement(`div`);i.className=`tcw-status-indicator`,E(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,E(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)}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){this.marketEl.hidden=e===`always`,this.marketEl.dataset.state=e,this.marketEl.textContent=e===`always`?``:t}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.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.clockMenu?.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.title=e.label,t.setAttribute(`aria-haspopup`,`menu`),E(t,`statusBar.clock`),t.addEventListener(`click`,()=>this.toggleZones(t,e)),this.clockBtn=t,this.tick(),t}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)}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),E(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,E(r,`statusBar.range`),r.textContent=e.presetLabels?.[n]??n,r.addEventListener(`click`,()=>e.onPreset(n)),t.appendChild(r)}let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-range-btn tcw-range-goto`,n.dataset.role=`goto`,E(n,`goToDate`,`statusBar.goToDate`),n.title=`${e.goToLabel} (Alt+G)`,n.setAttribute(`aria-label`,e.goToLabel),n.innerHTML=D(`calendar`,13),n.addEventListener(`click`,e.onGoTo),t.appendChild(n),t}};function mn(e,t,n){let r=(...e)=>e.map(e=>`<kbd class="tcw-cmd-kbd tcw-cmd-key">${e}</kbd>`).join(``),i=(e,t)=>`<span class="tcw-cmd-help">${e}<span class="tcw-cmd-help-text">${k(t)}</span></span>`;return i(r(D(`arrowUp`,11),D(`arrowDown`,11)),e)+i(r(D(`enter`,11)),t)+i(r(`Esc`),n)}var hn=class{backdrop=null;modal=null;input=null;list=null;items=[];filtered=[];selectedIndex=0;callbacks;boundKeydown;constructor(e,n=()=>document.body,r=t.t){this.host=n,this.t=r,this.callbacks=e,this.boundKeydown=this.handleKeydown.bind(this)}open(e){if(this.backdrop)return;this.items=e,this.filtered=e,this.selectedIndex=0,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.addEventListener(`click`,()=>this.close()),this.modal=document.createElement(`div`),this.modal.className=`tcw-cmd-palette`;let t=document.createElement(`div`);t.className=`tcw-cmd-header`;let n=document.createElement(`span`);n.className=`tcw-cmd-icon`,n.innerHTML=D(`search`,16),t.appendChild(n),this.input=document.createElement(`input`),this.input.className=`tcw-cmd-input`,this.input.type=`text`,this.input.placeholder=this.t(`palette.placeholder`),this.input.addEventListener(`input`,()=>this.filter()),t.appendChild(this.input);let r=document.createElement(`span`);r.className=`tcw-cmd-hint`,r.textContent=`ESC`,t.appendChild(r),this.modal.appendChild(t),this.list=document.createElement(`div`),this.list.className=`tcw-cmd-list`,this.modal.appendChild(this.list);let i=document.createElement(`div`);i.className=`tcw-cmd-footer`,i.innerHTML=mn(this.t(`common.navigate`),this.t(`common.select`),this.t(`common.close`)),this.modal.appendChild(i),this.host().append(this.backdrop,this.modal),this.renderList(),this.input.focus(),document.addEventListener(`keydown`,this.boundKeydown)}close(){document.removeEventListener(`keydown`,this.boundKeydown),this.backdrop?.remove(),this.modal?.remove(),this.backdrop=null,this.modal=null,this.input=null,this.list=null,this.callbacks.onClose()}isOpen(){return this.backdrop!==null}filter(){let e=this.input?.value.toLowerCase().trim()??``;e?this.filtered=this.items.filter(t=>t.label.toLowerCase().includes(e)||t.category.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)):this.filtered=this.items,this.selectedIndex=0,this.renderList()}renderList(){if(!this.list)return;if(this.list.innerHTML=``,this.filtered.length===0){let e=document.createElement(`div`);e.className=`tcw-cmd-empty`,e.textContent=this.t(`palette.empty`),this.list.appendChild(e);return}let e=``;for(let t=0;t<this.filtered.length;t++){let n=this.filtered[t];if(n.category!==e){e=n.category;let t=document.createElement(`div`);t.className=`tcw-cmd-category`,t.textContent=this.categoryLabel(e),this.list.appendChild(t)}let r=document.createElement(`button`);r.className=`tcw-cmd-item`,t===this.selectedIndex&&r.classList.add(`tcw-selected`),n.active&&r.classList.add(`tcw-active`),r.dataset.index=String(t);let i=document.createElement(`span`);if(i.className=`tcw-cmd-item-label`,i.textContent=n.label,r.appendChild(i),n.active){let e=document.createElement(`span`);e.className=`tcw-cmd-check`,e.innerHTML=D(`check`,14),r.appendChild(e)}if(n.shortcut){let e=document.createElement(`kbd`);e.className=`tcw-cmd-kbd`,e.textContent=n.shortcut,r.appendChild(e)}r.addEventListener(`click`,()=>this.select(t)),r.addEventListener(`mouseenter`,()=>{this.selectedIndex=t,this.updateSelection()}),this.list.appendChild(r)}}updateSelection(){if(!this.list)return;let e=this.list.querySelectorAll(`.tcw-cmd-item`);e.forEach((e,t)=>{e.classList.toggle(`tcw-selected`,t===this.selectedIndex)}),e[this.selectedIndex]?.scrollIntoView({block:`nearest`})}select(e){let t=this.filtered[e];if(t){switch(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}this.close()}}handleKeydown(e){switch(e.key){case`Escape`:e.preventDefault(),this.close();break;case`ArrowDown`:e.preventDefault(),this.filtered.length>0&&(this.selectedIndex=(this.selectedIndex+1)%this.filtered.length,this.updateSelection());break;case`ArrowUp`:e.preventDefault(),this.filtered.length>0&&(this.selectedIndex=(this.selectedIndex-1+this.filtered.length)%this.filtered.length,this.updateSelection());break;case`Enter`:e.preventDefault(),this.select(this.selectedIndex);break}}categoryLabel(e){switch(e){case`indicator`:return this.t(`palette.group.indicator`);case`chartType`:return this.t(`palette.group.chartType`);case`drawing`:return this.t(`palette.group.drawing`);case`timeframe`:return this.t(`palette.group.timeframe`);case`action`:return this.t(`palette.group.action`);default:return e}}destroy(){this.close()}},gn=class{backdrop=null;modal=null;input=null;list=null;symbols=[];current=``;filtered=[];selectedIndex=0;callbacks;boundKeydown;pickOverride=null;searchFn=null;searchTimer=null;searchAbort=null;status=`idle`;pickOnResults=!1;constructor(e,n=()=>document.body,r=t.t){this.host=n,this.t=r,this.callbacks=e,this.boundKeydown=this.handleKeydown.bind(this)}open(e,t,n,r){if(this.backdrop)return;this.pickOverride=n??null,this.searchFn=r??null,this.status=`idle`,this.symbols=e,this.current=t,this.filtered=e.map(e=>({symbol:e,score:0})),this.selectedIndex=Math.max(0,e.indexOf(t)),this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.addEventListener(`click`,()=>this.close()),this.modal=document.createElement(`div`),this.modal.className=`tcw-cmd-palette`;let i=document.createElement(`div`);i.className=`tcw-cmd-header`;let a=document.createElement(`span`);a.className=`tcw-cmd-icon`,a.innerHTML=D(`search`,16),i.appendChild(a),this.input=document.createElement(`input`),this.input.className=`tcw-cmd-input`,this.input.type=`text`,this.input.placeholder=this.t(`symbolSearch.placeholder`),this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.addEventListener(`input`,()=>this.filter()),i.appendChild(this.input);let o=document.createElement(`span`);o.className=`tcw-cmd-hint`,o.textContent=`ESC`,i.appendChild(o),this.modal.appendChild(i),this.list=document.createElement(`div`),this.list.className=`tcw-cmd-list`,this.modal.appendChild(this.list);let s=document.createElement(`div`);s.className=`tcw-cmd-footer`,s.innerHTML=mn(this.t(`common.navigate`),this.t(`common.open`),this.t(`common.close`)),this.modal.appendChild(s),this.host().append(this.backdrop,this.modal),this.renderList(),this.input.focus(),document.addEventListener(`keydown`,this.boundKeydown)}close(){document.removeEventListener(`keydown`,this.boundKeydown),this.cancelSearch(),this.pickOnResults=!1,this.searchFn=null,this.backdrop?.remove(),this.modal?.remove(),this.backdrop=null,this.modal=null,this.input=null,this.list=null,this.pickOverride=null,this.callbacks.onClose()}isOpen(){return this.backdrop!==null}destroy(){this.close()}filter(){this.pickOnResults=!1;let e=(this.input?.value??``).toUpperCase().trim();if(this.searchFn&&e){this.scheduleSearch(this.input?.value.trim()??``);return}this.cancelSearch(),this.status=`idle`,e?this.filtered=this.symbols.map(t=>({symbol:t,score:_n(t.toUpperCase(),e)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score):this.filtered=this.symbols.map(e=>({symbol:e,score:0})),this.selectedIndex=0,this.renderList()}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.filtered=[],this.renderList();try{let r=await t(e,n.signal);if(n.signal.aborted)return;this.filtered=r.map(e=>({symbol:e.symbol,score:0,description:e.description,meta:[e.exchange,e.type].filter(Boolean).join(` · `)||void 0})),this.status=`idle`}catch{if(n.signal.aborted)return;this.filtered=[],this.status=`failed`}this.selectedIndex=0,this.renderList(),this.pickOnResults&&(this.pickOnResults=!1,this.pick(0))}cancelSearch(){this.searchTimer!==null&&clearTimeout(this.searchTimer),this.searchTimer=null,this.searchAbort?.abort(),this.searchAbort=null}renderList(){if(!this.list)return;if(this.list.innerHTML=``,this.filtered.length===0){let e=document.createElement(`div`);e.className=`tcw-cmd-empty`,e.setAttribute(`role`,`status`),e.textContent=this.status===`searching`?this.t(`symbolSearch.searching`):this.status===`failed`?this.t(`symbolSearch.failed`):this.t(`symbolSearch.empty`),this.list.appendChild(e);return}let e=(this.input?.value??``).toUpperCase().trim();for(let t=0;t<this.filtered.length;t++){let{symbol:n,description:r,meta:i}=this.filtered[t],a=document.createElement(`button`);a.className=`tcw-cmd-item`,t===this.selectedIndex&&a.classList.add(`tcw-selected`),n===this.current&&a.classList.add(`tcw-active`);let o=document.createElement(`span`);if(o.className=`tcw-cmd-item-label`,o.innerHTML=vn(n,e),a.appendChild(o),r&&r!==n){let e=document.createElement(`span`);e.className=`tcw-cmd-item-desc`,e.textContent=r,a.appendChild(e)}if(i){let e=document.createElement(`span`);e.className=`tcw-cmd-item-meta`,e.textContent=i,a.appendChild(e)}if(n===this.current){let e=document.createElement(`span`);e.className=`tcw-cmd-check`,e.innerHTML=D(`check`,14),a.appendChild(e)}a.addEventListener(`click`,()=>this.pick(t)),a.addEventListener(`mouseenter`,()=>{this.selectedIndex=t,this.updateSelection()}),this.list.appendChild(a)}}updateSelection(){if(!this.list)return;let e=this.list.querySelectorAll(`.tcw-cmd-item`);e.forEach((e,t)=>e.classList.toggle(`tcw-selected`,t===this.selectedIndex)),e[this.selectedIndex]?.scrollIntoView?.({block:`nearest`})}pick(e){let t=this.filtered[e];if(!t)return;let n=this.pickOverride;n?n(t.symbol):this.callbacks.onPick(t.symbol),this.close()}handleKeydown(e){switch(e.key){case`Escape`:e.preventDefault(),this.close();break;case`ArrowDown`:e.preventDefault(),this.filtered.length>0&&(this.selectedIndex=(this.selectedIndex+1)%this.filtered.length,this.updateSelection());break;case`ArrowUp`:e.preventDefault(),this.filtered.length>0&&(this.selectedIndex=(this.selectedIndex-1+this.filtered.length)%this.filtered.length,this.updateSelection());break;case`Enter`:if(e.preventDefault(),this.searchTimer!==null||this.status===`searching`){this.pickOnResults=!0,this.searchTimer!==null&&this.searchNow();break}this.pick(this.selectedIndex);break}}};function _n(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 vn(e,t){if(!t)return k(e);let n=e.toUpperCase(),r=``,i=0;for(let a=0;a<e.length;a++)i<t.length&&n[a]===t[i]?(r+=`<mark style="background:transparent;color:var(--tcw-accent);font-weight:700">${k(e[a])}</mark>`,i++):r+=k(e[a]);return r}var yn={"Search & navigation":`hotkeys.group.searchNavigation`,"Chart manipulation":`hotkeys.group.chartManipulation`,"Touch (mobile / tablet)":`hotkeys.group.touch`,Keyboard:`hotkeys.group.keyboard`,Drawing:`hotkeys.group.drawing`,More:`hotkeys.group.more`},z=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent)?`⌘`:`Ctrl`,bn=[{title:`Search & navigation`,entries:[{keys:[z,`K`],label:`hotkeys.commandPalette`,feature:`hotkeys.commandPalette`},{keys:[z,`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:[z,`S`],label:`hotkeys.saveLayout`,feature:`hotkeys.save`},{keys:[`0–9`],label:`hotkeys.typeInterval`,feature:`intervalTyping`},{keys:[`?`],label:`hotkeys.showSheet`,feature:`hotkeys.help`}]},{title:`Chart manipulation`,entries:[{keys:[`key.drag`],label:`hotkeys.pan`},{keys:[z,`key.drag`],label:`hotkeys.boxSelect`},{keys:[z,`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:[`F`],label:`hotkeys.fit`}]},{title:`Drawing`,entries:[{keys:[z,`Z`],label:`hotkeys.undo`},{keys:[z,`Shift`,`Z`],label:`hotkeys.redo`},{keys:[`Esc`],label:`hotkeys.cancelDrawing`},{keys:[z,`C`],label:`hotkeys.copy`},{keys:[z,`V`],label:`hotkeys.paste`},{keys:[`key.rightClick`],label:`hotkeys.drawingMenu`},{keys:[`key.doubleClick`],label:`hotkeys.drawingSettings`},{keys:[z,`G`],label:`hotkeys.group`},{keys:[z,`Shift`,`G`],label:`hotkeys.ungroup`},{keys:[z,`]`,`[`],label:`hotkeys.orderStep`},{keys:[z,`Shift`,`]`,`[`],label:`hotkeys.orderEnd`},{keys:[`Enter`],label:`hotkeys.finishPath`},{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`}]}],xn=class{backdrop=null;modal=null;callbacks;t;boundKeydown;constructor(e,t,n=()=>document.body){this.host=n,this.callbacks=e,this.t=t,this.boundKeydown=e=>{e.key===`Escape`&&(e.preventDefault(),this.close())}}open(e={}){if(this.backdrop)return;let t=e.isOn??(()=>!0),n=new Set((e.extra??[]).map(e=>e.keys.join(`+`).toLowerCase())),r=bn.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&&r.push({title:`More`,entries:[...e.extra]}),this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.addEventListener(`click`,()=>this.close()),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-hotkey-sheet`,this.modal.style.width=`640px`;let i=document.createElement(`div`);i.className=`tcw-modal-header`;let a=document.createElement(`h3`);a.textContent=this.t(`hotkeys.title`),i.appendChild(a);let o=document.createElement(`button`);o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`hotkeys.close`)),o.innerHTML=D(`x`,14),o.addEventListener(`click`,()=>this.close()),i.appendChild(o),this.modal.appendChild(i);let s=document.createElement(`div`);s.className=`tcw-modal-body`;let c=document.createElement(`div`);c.className=`tcw-hotkey-grid`;for(let e of r){let t=document.createElement(`section`);t.className=`tcw-hotkey-section`;let n=document.createElement(`div`);n.className=`tcw-settings-section-title`;let r=yn[e.title];n.textContent=r?this.t(r):e.title,t.appendChild(n);for(let n of e.entries){let e=document.createElement(`div`);e.className=`tcw-hotkey-row`;let r=document.createElement(`div`);r.className=`tcw-hotkey-keys`;for(let e=0;e<n.keys.length;e++){if(e>0){let e=document.createElement(`span`);e.className=`tcw-hotkey-sep`,e.textContent=`+`,r.appendChild(e)}let t=document.createElement(`kbd`);t.className=`tcw-cmd-kbd`;let i=n.keys[e];t.textContent=i.startsWith(`key.`)?this.t(i):i,r.appendChild(t)}e.appendChild(r);let i=document.createElement(`span`);i.className=`tcw-hotkey-label`,i.textContent=`text`in n?n.text:this.t(n.label),e.appendChild(i),t.appendChild(e)}c.appendChild(t)}s.appendChild(c),this.modal.appendChild(s);let l=document.createElement(`div`);l.className=`tcw-modal-footer`;let u=document.createElement(`span`);u.style.cssText=`font-size:11px;color:var(--tcw-text-muted)`,u.textContent=this.t(`hotkeys.footer`),l.appendChild(u);let d=document.createElement(`button`);d.className=`tcw-done-btn`,d.textContent=this.t(`hotkeys.gotIt`),d.addEventListener(`click`,()=>this.close()),l.appendChild(d),this.modal.appendChild(l),this.host().append(this.backdrop,this.modal),document.addEventListener(`keydown`,this.boundKeydown)}close(){document.removeEventListener(`keydown`,this.boundKeydown),this.backdrop?.remove(),this.modal?.remove(),this.backdrop=null,this.modal=null,this.callbacks.onClose()}isOpen(){return this.backdrop!==null}destroy(){this.close()}},Sn={selectHint:`Click a bar to start the replay`,random:`Random bar`,realtime:`Back to realtime`,barsPerSecond:`bars/s`,play:`Play`,pause:`Pause`,stepBack:`Step back (Shift+←)`,stepForward:`Step forward (Shift+→)`,replay:`Replay`,position:`Replay position`,speed:`Speed`,step:`Step`},Cn=[1,2,3,5,10,25,50],wn=class{root=null;scrubber=null;progressLabel=null;playBtn=null;realtimeBtn=null;state=`stopped`;mode=`select`;ended=!1;total=0;speed=5;steps=[];step=`bar`;labels;constructor(e,t={}){this.callbacks=e,this.labels={...Sn,...t}}mount(e,t){this.root||(this.total=Math.max(0,t.total),this.speed=t.speed??5,this.steps=t.steps??[],this.step=t.step??`bar`,this.state=`paused`,this.mode=t.mode??`select`,this.root=document.createElement(`div`),this.root.className=`tcw-replay-bar`,E(this.root,`replay`),this.root.setAttribute(`role`,`toolbar`),this.root.setAttribute(`aria-label`,this.labels.replay),this.root.innerHTML=this.markup(),e.appendChild(this.root),this.wireEvents(),this.syncUi())}unmount(){this.root?.remove(),this.root=null,this.scrubber=null,this.progressLabel=null,this.playBtn=null,this.realtimeBtn=null,this.state=`stopped`,this.ended=!1}isMounted(){return this.root!==null}getMode(){return this.mode}setMode(e){let t=!!this.root?.contains(document.activeElement);this.mode=e,this.syncUi(),t&&e===`replay`&&this.playBtn?.focus()}setState(e){this.state=e,this.syncUi()}setEnded(e){this.ended!==e&&(this.ended=e,this.syncUi())}setProgress(e,t){this.total=t,this.scrubber&&(this.scrubber.max=String(Math.max(0,t-1)),this.scrubber.value=String(e)),this.progressLabel&&(this.progressLabel.textContent=`${Math.min(e+1,t)} / ${t}`)}destroy(){this.unmount()}markup(){let e=this.labels,t=Cn.map(t=>`<option value="${t}"${t===this.speed?` selected`:``}>${t} ${k(e.barsPerSecond)}</option>`).join(``);return`
6029
+ ${Be()}`,document.head.insertBefore(e,document.head.firstChild)}function Je(){if(Ge--,Ge>0)return;let e=document.getElementById(Ke);e&&e.remove()}var Ye=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function D(e,t=14){let r=Ye(n.UI_ICONS,e);return r?(0,n.iconSvg)(r,t):``}function Xe(e,t=16){return(0,n.iconSvg)(Ye(n.DRAWING_TOOL_ICONS,e)??n.UI_ICONS.penLine,t)}function Ze(e,t=14){return(0,n.iconSvg)(Ye(n.CHART_TYPE_ICONS,e)??n.UI_ICONS.barChart,t)}function O(e){return e.replace(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`})[e])}var Qe=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(){p(this.panel,this.trigger,this.align)}},$e=4,et=150,tt=`[role=menuitem], [role=menuitemcheckbox], [role=menuitemradio]`,nt=`(max-width: 640px)`,rt=`tcw:back`;function it(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 at(e){return e.radio?`menuitemradio`:e.checked===void 0?`menuitem`:`menuitemcheckbox`}function ot(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===void 0?e.icon&&D(e.icon,14)||t:e.checked?D(`check`,14):t}var k=class e{el;onPick=null;onRemove=null;returnFocus=null;anchor=null;child=null;parent=null;hoverTimer=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){this.show(e,{x:t,y:n,xBack:t,yBack:n},r,i,a,!0)}close(){if(this.clearHover(),this.child?.close(),this.el.hidden)return;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}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;let o=this.host.getBoundingClientRect(),s=Math.min(this.host.clientWidth,window.innerWidth-o.left)-$e,c=Math.min(this.host.clientHeight,window.innerHeight-o.top)-$e;this.el.style.maxHeight=`${Math.max(0,c)}px`,this.el.style.left=`${it(t.x,this.el.offsetWidth,s,t.xBack,t.before)}px`,this.el.style.top=`${it(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})}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`,at(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=ot(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(`pointerenter`,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.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`,D(`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=D(`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?.(nt).matches??!1,l=c?[{id:rt,label:t,icon:`chevronLeft`},`separator`,...n]:n;i.show(l,s,e=>{e!==rt&&this.pick(e)},e,e=>this.onRemove?.(e),r);let u=c?i.el.querySelector(`[data-id="${rt}"]`):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){this.clearHover();let r=this.child?.isOpen()?this.child.anchor:null;(n?r===e:r===null)||(this.hoverTimer=setTimeout(()=>{this.hoverTimer=null,n?this.openSubmenu(e,t,n,!1):this.child?.close()},et))}clearHover(){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(tt)]}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})}},st=[`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`],ct=65234;function lt(e){return(e&&!st.includes(e)?[e,...st]:st).map(e=>{let t;try{t=new Intl.NumberFormat(e,{minimumFractionDigits:2,maximumFractionDigits:2}).format(ct)}catch{t=``}return{value:e,label:t?`${e} (${t})`:e}})}var ut={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 dt(e,t){let n=`chartType.${e.value}`,r=t(n);return r===n?e.label:r}function ft(e,t){return e.map(e=>({...e,label:ut[e.label]?t(ut[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 pt=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`,`1w`,`1M`],mt=[`1m`,`5m`,`15m`,`1h`,`4h`,`1d`],ht=6;function gt(e){let t=e.slice(-1);return t===`h`||t===`d`||t===`w`?e.slice(0,-1)+t.toUpperCase():e}var _t=e=>Number.isFinite((0,n.timeframeToMs)(e))||(0,n.tickBarCount)(e)!==null,vt=(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 yt(e,t){let n=t?.length?t:null,r=e?.length?e:n??pt;return[...new Set(r)].filter(e=>_t(e)&&(!n||n.includes(e))).sort(vt)}function bt(e,t,n=!1){if(t?.length)return e.filter(e=>t.includes(e));if(n)return[...e];let r=e.filter(e=>mt.includes(e));return r.length>0?r:e.slice(0,ht)}var xt=9999,St={"":`m`,s:`s`,S:`s`,m:`m`,h:`h`,H:`h`,d:`d`,D:`d`,w:`w`,W:`w`,M:`M`},Ct={s:[`m`,60],m:[`h`,60],h:[`d`,24]};function wt(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])<=xt&&(0,n.tickBarCount)(e)!==null?e:null}let r=Number(t[1]),i=St[t[2]];if(!i||!Number.isSafeInteger(r)||r<1)return null;for(let e=Ct[i];e&&r%e[1]===0;e=Ct[i])r/=e[1],i=e[0];if(r>xt)return null;let a=`${r}${i}`;return(0,n.isTimeFrame)(a)?a:null}function Tt(e,t,n){let r=n?.length?n:null,i=t.filter(e=>_t(e)&&(!r||r.includes(e)));return[...new Set([...e,...i])].sort(vt)}var Et=[`T`,`s`,`m`,`h`,`d`,`w`,`M`];function Dt(e){let t=e=>{let t=e.slice(-1);return Et.includes(t)?t:`m`};return Et.map(n=>({unit:n,timeframes:e.filter(e=>t(e.value)===n)})).filter(e=>e.timeframes.length>0)}var Ot=864e5,kt=5/7;function At(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<Ot)return e.barsInSpan*t/n;let r=e.spanMs/n;return n===Ot?r*(e.dayShare??kt):r},a=[...new Set([...e.available,e.current])].filter(e=>{let t=(0,n.timeframeToMs)(e);return Number.isFinite(t)&&t>=r}).sort(vt);for(let t of a)if(i((0,n.timeframeToMs)(t))*2<=e.width)return t;return a[a.length-1]??e.current}var jt={ticket:`receipt`,long:`trendingUp`,short:`trendingDown`,ladder:`ladder`,account:`layers`},Mt=[`ladder`,`account`],Nt=2;function Pt(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 Ft=class e{button;menu=null;open=new Set;static create(t,n,r,i){let a=Pt(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`),E(i,`toolbar.trade`),i.innerHTML=`${D(`trendingUp`,14)} <span class="tcw-trigger-label">${O(t(`toolbar.trade`))}</span> ${D(`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=Mt.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.map(e=>Mt.includes(e.id)?{id:e.id,label:e.label,checked:this.open.has(e.id)}:{id:e.id,label:e.label,icon:jt[e.id]}),r=this.root();this.menu??=new k(r,this.t(`toolbar.trade`));let i=e.getBoundingClientRect(),a=r.getBoundingClientRect();this.menu.open(n,i.left-a.left,i.bottom-a.top+Nt,e=>{t.find(t=>t.id===e)?.run()},e)}},It=0,Lt={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 Rt(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 zt=class{config;callbacks;t;el;chartTypeDropdown=null;tfGroup=null;tfDropdown=null;tfFavorites=[];uid=(It++).toString(36);tfRendered=``;themeBtn=null;fullscreenBtn=null;hostLeft=null;hostRight=null;moreMenu=null;tfCurrent=null;resizeObserver=null;moreBtn=null;fitFrame=0;undoBtn=null;redoBtn=null;trade=null;constructor(e,t,n,r,i){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`,E(this.el,`toolbar`),this.build(),e.appendChild(this.el),typeof ResizeObserver<`u`&&(this.resizeObserver=new ResizeObserver(()=>this.fit()),this.resizeObserver.observe(this.el)),document.fonts?.ready.then(()=>this.scheduleFit())}scheduleFit(){this.fitFrame||typeof requestAnimationFrame>`u`||(this.fitFrame=requestAnimationFrame(()=>{this.fitFrame=0,this.fit()}))}anchorOf(e){return(e.hasAttribute(`data-tcw-folded`)||this.el.closest(`[data-tcw-narrow]`)!==null)&&this.moreBtn?this.moreBtn:e}fit(){let{el:e}=this,t=()=>e.scrollWidth<=e.clientWidth+1,n=[...e.querySelectorAll(`.tcw-toolbar-overflow`)];for(let e of n)e.removeAttribute(`data-tcw-folded`);if(e.classList.remove(`tcw-toolbar--collapsed`,`tcw-toolbar--icons`),!(e.clientWidth===0||t())){e.classList.add(`tcw-toolbar--collapsed`);for(let e=n.length-1;e>=0;e--)if(n[e].setAttribute(`data-tcw-folded`,``),t())return;e.classList.add(`tcw-toolbar--icons`);for(let e of n)if(e.removeAttribute(`data-tcw-folded`),!t()){e.setAttribute(`data-tcw-folded`,``);break}}}build(){let{config:e,callbacks:t,el:n}=this,r=document.createElement(`button`);if(r.className=`tcw-toolbar-symbol`,r.dataset.role=`symbol`,E(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`,E(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`,E(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`,E(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`,D(`chevronDown`,12)),e.appendChild(t),n.appendChild(e),this.tfDropdown=new Qe(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`,E(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 Qe(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`),E(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`,E(e,`compare`,`toolbar.compare`);let r=this.t(`objects.compare`);e.setAttribute(`aria-label`,r),e.title=r,e.innerHTML=`${D(`plus`,14)} <span class="tcw-trigger-label">${O(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`,E(this.undoBtn,`toolbar.undo`,`sidebar.undo`),this.redoBtn=this.iconBtn(`redo`,this.t(`drawing.redo`),t.onRedo),this.redoBtn.dataset.role=`redo`,E(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`,E(r,`layouts`,`toolbar.layouts`),r.setAttribute(`aria-haspopup`,`menu`),r.addEventListener(`click`,()=>e(this.anchorOf(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`,E(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(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(e,`alerts`,`toolbar.alerts`),n.appendChild(e)}this.trade=Ft.create(t,this.t,()=>this.rootEl(),e=>this.anchorOf(e)),this.trade&&n.appendChild(this.trade.button),n.appendChild(this.sep());let s=this.iconBtn(`camera`,this.t(`toolbar.screenshot`),t.onScreenshot);E(s,`screenshot`,`toolbar.screenshot`),n.appendChild(s);let c=this.iconBtn(`settings`,this.t(`toolbar.settings`),t.onSettings);E(c,`settings`,`toolbar.settings`),n.appendChild(c),this.themeBtn=this.iconBtn(`moon`,this.t(`toolbar.toggleTheme`),t.onToggleTheme),this.themeBtn.dataset.role=`theme`,E(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`,E(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=D(`more`,16),l.addEventListener(`click`,()=>this.toggleMore(l)),n.appendChild(l),this.moreBtn=l}toggleMore(e){if(this.moreMenu?.isOpen()){this.moreMenu.close();return}let t=this.rootEl(),n=new Set((t.getAttribute(`data-tcw-off`)??``).split(/\s+/).filter(Boolean)),r=e=>(e.dataset.tcwPart??``).split(/\s+/).some(e=>n.has(e)),i=this.el.closest(`[data-tcw-narrow]`)!==null,a=[];for(let e of this.el.querySelectorAll(`.tcw-toolbar-overflow`)){if(r(e)||!i&&!e.hasAttribute(`data-tcw-folded`))continue;let t=e instanceof HTMLButtonElement?[e]:[...e.querySelectorAll(`button`)];a.push(...t.filter(e=>!e.hidden&&!e.disabled&&!r(e)))}if(a.length===0)return;let o=a.map((e,t)=>{let n=e.title||e.getAttribute(`aria-label`)||e.textContent?.trim()||``;return e.getAttribute(`aria-pressed`)===`true`?{id:String(t),label:n,checked:!0}:{id:String(t),label:n,icon:e.dataset.icon}});this.moreMenu??=new k(t,this.t(`toolbar.more`));let s=e.getBoundingClientRect(),c=t.getBoundingClientRect();this.moreMenu.open(o,s.right-c.left,s.bottom-c.top+2,e=>a[Number(e)]?.click(),e)}addHostButton(e){let t=document.createElement(`button`);t.type=`button`,t.className=e.text||!e.icon?`tcw-btn tcw-host-btn`:`tcw-btn-icon tcw-host-btn`,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=D(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 Rt(t,e.label),t.addEventListener(`click`,()=>e.onClick(t)),e.side!==`left`&&t.classList.add(`tcw-toolbar-overflow`),(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(),Ue(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)))}setLayout(e,t){let n=this.el.querySelector(`[data-role="layouts"]`);if(!n)return;let r=e??this.t(`layouts.unnamed`),i=`${this.t(`toolbar.layouts`)}: ${r}${t?` (${this.t(`layouts.unsavedChanges`)})`:``}`;n.innerHTML=`${D(`save`,14)}<span class="tcw-layouts-label">${O(r)}</span>`+(t?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+D(`chevronDown`,12),n.title=i,n.setAttribute(`aria-label`,i)}setFullscreen(e){if(!this.fullscreenBtn)return;let t=this.t(e?`toolbar.exitFullscreen`:`toolbar.fullscreen`);this.fullscreenBtn.innerHTML=D(e?`minimize`:`maximize`,14),this.fullscreenBtn.title=t,this.fullscreenBtn.setAttribute(`aria-pressed`,String(e))}chartTypeLabel(e){return dt(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="${O(e.value)}">${Ze(e.value,16)}<span>${O(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=O(this.t(`toolbar.timeframes.pin`)),t=O(this.t(`toolbar.timeframes.remove`)),n=``;for(let{unit:r,timeframes:i}of Dt(this.config.timeframes)){n+=`<div class="tcw-tf-section" data-tf-section="${r}" role="group" aria-label="${O(this.t(Lt[r]))}"><div class="tcw-dropdown-label">${O(this.t(Lt[r]))}</div>`;for(let r of i){let i=this.tfFavorites.includes(r.value),[a,o]=[O(r.value),O(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}">${D(`x`,12)}</button>`:``)+`<button class="tcw-tf-star${i?` tcw-active`:``}" data-tf-star="${a}" aria-pressed="${i}" title="${e}" aria-label="${e}: ${o}">${D(`star`,12)}</button></div>`}n+=`</div>`}if(this.callbacks.onAddTimeframe){let e=O(this.t(`toolbar.timeframes.custom`)),t=O(this.t(`toolbar.timeframes.add`));n+=`<form class="tcw-tf-custom" ${Ve(`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}">${D(`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))}update(e){let t=this.el.querySelector(`[data-role="symbol"]`);t&&(t.textContent=e.symbol),this.renderTimeframes(e.timeframe);let n=this.el.querySelector(`[data-role="charttype"]`);if(n){let t=this.config.chartTypes.find(t=>t.value===e.chartType),r=t?this.chartTypeLabel(t):e.chartType;n.innerHTML=Ze(e.chartType,16),n.title=r,n.setAttribute(`aria-label`,r)}let r=this.el.querySelector(`[data-role="indicators"]`);if(r){let t=e.activeIndicators.size,n=`${D(`trendingUp`,14)} <span class="tcw-trigger-label">${O(this.t(`toolbar.indicators`))}</span>`;r.setAttribute(`aria-label`,this.t(`toolbar.indicators`)),t>0&&(n+=` <span class="tcw-badge-count">${t}</span>`),r.innerHTML=n}if(this.themeBtn){let t=e.isDark?`moon`:`sun`;this.themeBtn.innerHTML=D(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=D(e,14),r.addEventListener(`click`,n),r}destroy(){this.resizeObserver?.disconnect(),this.fitFrame&&cancelAnimationFrame(this.fitFrame),this.chartTypeDropdown?.destroy(),this.tfDropdown?.destroy(),this.moreMenu?.destroy(),this.trade?.destroy(),this.el.remove()}};function Bt(e,t,n){e.classList.toggle(`tcw-active`,t),n&&e.setAttribute(`aria-pressed`,String(t))}function Vt(e,t,n){let r=e.querySelector(`.tcw-host-btn-text`);r||(r=document.createElement(`span`),r.className=`tcw-host-btn-text`,e.appendChild(r)),r.textContent=n,Rt(e,t)}var Ht=16,Ut=150,Wt=4;function Gt(e){let t=`sidebar.${e}`;return T.includes(t)?t:null}function Kt(e,t){for(let n of e){let e=n.tools.find(e=>e.value===t);if(e)return e.label}return t}var qt=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`,E(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=D(`penLine`,18),E(this.fab,`sidebar`),this.fab.addEventListener(`click`,()=>this.setOpen(!this.isOpen())),e.appendChild(this.fab)}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=D(`cursor`,14),this.cursorBtn.addEventListener(`click`,()=>{t.onCancelDrawing(),this.closeForChart()}),E(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`,E(this.favoritesEl,`sidebar.favorites`),n.appendChild(this.favoritesEl),this.favoritesDivider=this.divider(),E(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=Gt(e.section);a&&E(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=Xe(s,Ht),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`,E(e,`sidebar.style`),e.innerHTML=D(`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=D(`magnet`,14),this.magnetBtn.addEventListener(`click`,t.onToggleMagnet),E(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()}),E(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()}),E(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=D(`repeat`,14),this.stayBtn.addEventListener(`click`,t.onToggleStayInDrawing),E(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`,E(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`,E(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=D(`trash`,14),a.addEventListener(`click`,t.onClearDrawings),E(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:Kt(this.config.drawingToolGroups,e)}),n.dataset.toolValue=e,n.innerHTML=Xe(e,Ht),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=Xe(e.value,Ht);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,E(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=D(`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-Wt*2)}px`;let i=this.host.clientHeight-e.offsetHeight-Wt;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()},Ut)}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?Xe(e.activeTool,18):D(`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=Xe(e.activeTool,Ht),n[t].tools.length>1&&this.groupButtons[t].setAttribute(`aria-label`,`${n[t].label}: ${Kt(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=D(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=D(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(){Ue(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=D(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()}},Jt=`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function A(e,t){if(e.key!==`Tab`)return;let n=document.activeElement,r=[...t.querySelectorAll(Jt)].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 j(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 Yt(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 Xt(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 M(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 Zt(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=P(e),n.addEventListener(`input`,()=>t(n.value)),n}function N(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 P(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=Qt(t);return r!==null&&r!==t?P(r):`#000000`}var F;function Qt(e){if(F===void 0)try{F=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):null}catch{F=null}if(!F)return null;F.fillStyle=`#010203`,F.fillStyle=e;let t=String(F.fillStyle);return t===`#010203`?null:t}function $t(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=P(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 tn=0;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 rn(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 an(e,t,n,r,i){let a=rn(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-${++tn}`,s.setAttribute(`aria-describedby`,c.id);let l=null,u=t=>{s.value=P(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 I(e,t,n){let r=rn(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 L(e,t,n,r){let i=rn(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 on(e,t,n,r,i=e=>String(e)){let a=rn(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 sn(e,t,n,r,i){let a=document.createElement(`div`);a.className=`tcw-settings-row`;let o=document.createElement(`label`);o.className=`tcw-settings-label`,o.textContent=e,a.appendChild(o);let s=document.createElement(`input`);return s.type=`number`,s.className=`tcw-settings-number`,s.min=`0`,s.step=n.step,Number.isFinite(n.max)&&(s.max=String(n.max)),s.placeholder=i(`settings.auto`),s.value=t===null?``:String(t),s.setAttribute(`aria-label`,e),s.addEventListener(`change`,()=>{if(s.value.trim()===``){s.removeAttribute(`aria-invalid`),r(null);return}let e=Number(s.value),t=Number.isFinite(e)&&e>0&&e<=n.max&&(n.step!==`1`||Number.isInteger(e));s.toggleAttribute(`aria-invalid`,!t),t&&r(e)}),a.appendChild(s),a}var R=[{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`}],cn=[1,2,3,4],ln=`t:`,un=1,dn=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){this.modal&&(this.currentSettings={...e},t!==void 0&&(this.chartType=t),this.renderTabContent())}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}A(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=D(`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=R.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:`)?Ze(t.slice(10),16):D(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>${D(`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=R.findIndex(e=>e.id===this.currentTab),n=e.key===`ArrowDown`||e.key===`ArrowRight`?(t+1)%R.length:e.key===`ArrowUp`||e.key===`ArrowLeft`?(t-1+R.length)%R.length:e.key===`Home`?0:e.key===`End`?R.length-1:-1;n<0||(e.preventDefault(),this.selectTab(R[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:`${ln}${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 k(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(ln)&&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 Ce)(!e.trading||this.available.trading!==!1)&&this.renderLookSection(e);break}}renderSymbolTab(e){this.renderChartTypeSection(),this.addSection(void 0,[I(this.t(`settings.mainSeries`),e.mainSeriesVisible,e=>this.patch({mainSeriesVisible:e})),I(this.t(`settings.extendedHours`),e.extendedHours,e=>this.patch({extendedHours:e}))]);let t=this.t(`common.show`);this.renderLookSection(ge),this.renderLookSection(_e,[I(t,e.volumeVisible,e=>this.patch({volumeVisible:e}))]),this.renderLookSection(ve,[I(t,e.highLowLines,e=>this.patch({highLowLines:e}))])}renderStatusLineTab(e){this.addSection(void 0,[I(this.t(`settings.ohlcLegend`),e.legendVisible,e=>this.patch({legendVisible:e})),...be.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=l(e.timezone,Date.now(),this.t(`settings.timezone.local`),this.available.exchangeZone?{label:this.t(`settings.timezone.exchange`),zone:this.available.exchangeZone()}:void 0);this.addSection(void 0,[L(this.t(`settings.priceScale`),e.scaleMode,t,e=>this.patch({scaleMode:e})),I(this.t(`settings.autoScale`),e.autoScale,e=>this.patch({autoScale:e})),I(this.t(`settings.invertScale`),e.invertScale,e=>this.patch({invertScale:e})),I(this.t(`settings.leftScale`),e.leftPriceScale,e=>this.patch({leftPriceScale:e})),I(this.t(`settings.indicatorValues`),e.indicatorValueLabels,e=>this.patch({indicatorValueLabels:e})),...this.available.barCountdown===!1?[]:[I(this.t(`settings.barCountdown`),e.barCountdown,e=>this.patch({barCountdown:e}))],L(this.t(`settings.timezone`),e.timezone,n,e=>this.patch({timezone:e})),L(this.t(`settings.numberLocale`),e.numberLocale,lt(e.numberLocale),e=>this.patch({numberLocale:e}))]),this.addSection(this.t(`settings.section.axes`),xe.map(e=>this.lookRow(e)))}renderAppearanceTab(e){let[t,n,r,...i]=Se;this.renderLookSection(t),this.renderLookSection(n,[I(this.t(`common.show`),e.gridVisible,e=>this.patch({gridVisible:e}))]),this.renderLookSection(r,[L(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,[I(n(`settings.volumeProfile`),e.volumeProfileVisible,e=>this.patch({volumeProfileVisible:e}))]),this.addSection(void 0,[I(n(`settings.marketProfile`),e.marketProfileVisible,e=>this.patch({marketProfileVisible:e})),I(n(`settings.marketProfileSplit`),e.marketProfileSplit,e=>this.patch({marketProfileSplit:e})),I(n(`settings.marketProfileLetters`),e.marketProfileLetters,e=>this.patch({marketProfileLetters:e})),on(n(`settings.marketProfileBuckets`),e.marketProfileBuckets,{min:8,max:200,step:1},e=>this.patch({marketProfileBuckets:e})),on(n(`settings.marketProfileOpacity`),e.marketProfileOpacity,{min:.05,max:1,step:.05},e=>this.patch({marketProfileOpacity:e}),t)]),this.addSection(void 0,[I(n(`settings.depthHeatmap`),e.depthHeatmapVisible,e=>this.patch({depthHeatmapVisible:e})),on(n(`settings.depthHeatmapOpacity`),e.depthHeatmapOpacity,{min:.1,max:1,step:.05},e=>this.patch({depthHeatmapOpacity:e}),t)]),this.addSection(void 0,[I(n(`settings.swingMarkers`),e.pivotMarkersVisible,e=>this.patch({pivotMarkersVisible:e})),on(n(`settings.swingStrength`),e.pivotStrength,{min:2,max:20,step:1},e=>this.patch({pivotStrength:e})),I(n(`settings.swingStructure`),e.pivotStructureLabels,e=>this.patch({pivotStructureLabels:e}))]),this.addSection(void 0,[I(n(`settings.sessionShading`),e.sessionShadingVisible,e=>this.patch({sessionShadingVisible:e})),I(n(`settings.periodLevels`),e.periodLevelsVisible,e=>this.patch({periodLevelsVisible:e})),L(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=I(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=L(t,i(),[...s,...this.lineStyles()],e=>o(e===``?null:pn(e))),c=()=>{a.querySelector(`select`).value=i()};break;case`width`:{let e=r(),n=typeof e==`number`&&!cn.includes(e)?[...cn,e].sort((e,t)=>e-t):cn;a=L(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=an(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=de.find(t=>t.value===e),r=nn(n?dt(n,this.t):e),i=()=>this.currentSettings?.chartTypeOptions??{},a=(e,t)=>this.patch({chartTypeOptions:{...i(),[e]:t}}),o=(e,t,n,i,a)=>r.appendChild(sn(this.t(e),t,{step:n,max:i},a,this.t));switch(e){case`renko`:{let e=t.renko??{};o(`settings.boxSize`,typeof e.boxSize==`number`?e.boxSize:null,`any`,1/0,e=>a(`renko`,{...i().renko??{},boxSize:e??`atr`})),o(`settings.atrPeriod`,e.atrPeriod??null,`1`,500,e=>a(`renko`,fn(i().renko,`atrPeriod`,e)));break}case`lineBreak`:o(`settings.lineBreakLines`,t.lineBreak?.lines??null,`1`,10,e=>a(`lineBreak`,fn(i().lineBreak,`lines`,e)));break;case`kagi`:o(`settings.reversal`,t.kagi?.reversal??null,`any`,1/0,e=>a(`kagi`,fn(i().kagi,`reversal`,e))),r.appendChild(L(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,`any`,1/0,e=>a(`pointAndFigure`,{...i().pointAndFigure??{},boxSize:e??`auto`})),o(`settings.reversalBoxes`,t.pointAndFigure?.reversal??null,`1`,10,e=>a(`pointAndFigure`,fn(i().pointAndFigure,`reversal`,e)));break;case`rangeBars`:o(`settings.barRange`,typeof t.rangeBars?.range==`number`?t.rangeBars.range:null,`any`,1/0,e=>a(`rangeBars`,{range:e??`auto`}));break;default:break}for(let t of Ee(e))r.appendChild(this.lookRow(t));this.bodyEl.appendChild(r)}patch(e){this.currentSettings&&Object.assign(this.currentSettings,e),this.callbacks.onChange(e)}};function fn(e,t,n){let r={...e??{}};return n===null?delete r[t]:r[t]=n,r}function pn(e){return e===`dashed`||e===`dotted`?e:`solid`}var mn=class{el;dotEl;messageEl;marketEl;hostLeft;hostRight;clockBtn=null;clockMenu=null;scaleBtns=null;scaleShown=``;constructor(e,t,n={}){this.host=e,this.extras=n,this.el=document.createElement(`div`),this.el.className=`tcw-statusbar`,E(this.el,`statusBar`),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.hostRight=this.hostGroup(),r.appendChild(this.hostRight);let i=document.createElement(`div`);i.className=`tcw-status-indicator`,E(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,E(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)}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){this.marketEl.hidden=e===`always`,this.marketEl.dataset.state=e,this.marketEl.textContent=e===`always`?``:t}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.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.clockMenu?.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.title=e.label,t.setAttribute(`aria-haspopup`,`menu`),E(t,`statusBar.clock`),t.addEventListener(`click`,()=>this.toggleZones(t,e)),this.clockBtn=t,this.tick(),t}toggleZones(e,t){if(this.clockMenu?.isOpen()){this.clockMenu.close();return}let{current:n,list:r}=t.options();this.clockMenu??=new k(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)}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),E(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,E(r,`statusBar.range`),r.textContent=e.presetLabels?.[n]??n,r.addEventListener(`click`,()=>e.onPreset(n)),t.appendChild(r)}let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-range-btn tcw-range-goto`,n.dataset.role=`goto`,E(n,`goToDate`,`statusBar.goToDate`),n.title=`${e.goToLabel} (Alt+G)`,n.setAttribute(`aria-label`,e.goToLabel),n.innerHTML=D(`calendar`,13),n.addEventListener(`click`,e.onGoTo),t.appendChild(n),t}};function hn(e,t,n){let r=(...e)=>e.map(e=>`<kbd class="tcw-cmd-kbd tcw-cmd-key">${e}</kbd>`).join(``),i=(e,t)=>`<span class="tcw-cmd-help">${e}<span class="tcw-cmd-help-text">${O(t)}</span></span>`;return i(r(D(`arrowUp`,11),D(`arrowDown`,11)),e)+i(r(D(`enter`,11)),t)+i(r(`Esc`),n)}var gn=class{backdrop=null;modal=null;input=null;list=null;items=[];filtered=[];selectedIndex=0;callbacks;boundKeydown;constructor(e,n=()=>document.body,r=t.t){this.host=n,this.t=r,this.callbacks=e,this.boundKeydown=this.handleKeydown.bind(this)}open(e){if(this.backdrop)return;this.items=e,this.filtered=e,this.selectedIndex=0,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.addEventListener(`click`,()=>this.close()),this.modal=document.createElement(`div`),this.modal.className=`tcw-cmd-palette`;let t=document.createElement(`div`);t.className=`tcw-cmd-header`;let n=document.createElement(`span`);n.className=`tcw-cmd-icon`,n.innerHTML=D(`search`,16),t.appendChild(n),this.input=document.createElement(`input`),this.input.className=`tcw-cmd-input`,this.input.type=`text`,this.input.placeholder=this.t(`palette.placeholder`),this.input.addEventListener(`input`,()=>this.filter()),t.appendChild(this.input);let r=document.createElement(`span`);r.className=`tcw-cmd-hint`,r.textContent=`ESC`,t.appendChild(r),this.modal.appendChild(t),this.list=document.createElement(`div`),this.list.className=`tcw-cmd-list`,this.modal.appendChild(this.list);let i=document.createElement(`div`);i.className=`tcw-cmd-footer`,i.innerHTML=hn(this.t(`common.navigate`),this.t(`common.select`),this.t(`common.close`)),this.modal.appendChild(i),this.host().append(this.backdrop,this.modal),this.renderList(),this.input.focus(),document.addEventListener(`keydown`,this.boundKeydown)}close(){document.removeEventListener(`keydown`,this.boundKeydown),this.backdrop?.remove(),this.modal?.remove(),this.backdrop=null,this.modal=null,this.input=null,this.list=null,this.callbacks.onClose()}isOpen(){return this.backdrop!==null}filter(){let e=this.input?.value.toLowerCase().trim()??``;e?this.filtered=this.items.filter(t=>t.label.toLowerCase().includes(e)||t.category.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)):this.filtered=this.items,this.selectedIndex=0,this.renderList()}renderList(){if(!this.list)return;if(this.list.innerHTML=``,this.filtered.length===0){let e=document.createElement(`div`);e.className=`tcw-cmd-empty`,e.textContent=this.t(`palette.empty`),this.list.appendChild(e);return}let e=``;for(let t=0;t<this.filtered.length;t++){let n=this.filtered[t];if(n.category!==e){e=n.category;let t=document.createElement(`div`);t.className=`tcw-cmd-category`,t.textContent=this.categoryLabel(e),this.list.appendChild(t)}let r=document.createElement(`button`);r.className=`tcw-cmd-item`,t===this.selectedIndex&&r.classList.add(`tcw-selected`),n.active&&r.classList.add(`tcw-active`),r.dataset.index=String(t);let i=document.createElement(`span`);if(i.className=`tcw-cmd-item-label`,i.textContent=n.label,r.appendChild(i),n.active){let e=document.createElement(`span`);e.className=`tcw-cmd-check`,e.innerHTML=D(`check`,14),r.appendChild(e)}if(n.shortcut){let e=document.createElement(`kbd`);e.className=`tcw-cmd-kbd`,e.textContent=n.shortcut,r.appendChild(e)}r.addEventListener(`click`,()=>this.select(t)),r.addEventListener(`mouseenter`,()=>{this.selectedIndex=t,this.updateSelection()}),this.list.appendChild(r)}}updateSelection(){if(!this.list)return;let e=this.list.querySelectorAll(`.tcw-cmd-item`);e.forEach((e,t)=>{e.classList.toggle(`tcw-selected`,t===this.selectedIndex)}),e[this.selectedIndex]?.scrollIntoView({block:`nearest`})}select(e){let t=this.filtered[e];if(t){switch(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}this.close()}}handleKeydown(e){switch(e.key){case`Escape`:e.preventDefault(),this.close();break;case`ArrowDown`:e.preventDefault(),this.filtered.length>0&&(this.selectedIndex=(this.selectedIndex+1)%this.filtered.length,this.updateSelection());break;case`ArrowUp`:e.preventDefault(),this.filtered.length>0&&(this.selectedIndex=(this.selectedIndex-1+this.filtered.length)%this.filtered.length,this.updateSelection());break;case`Enter`:e.preventDefault(),this.select(this.selectedIndex);break}}categoryLabel(e){switch(e){case`indicator`:return this.t(`palette.group.indicator`);case`chartType`:return this.t(`palette.group.chartType`);case`drawing`:return this.t(`palette.group.drawing`);case`timeframe`:return this.t(`palette.group.timeframe`);case`action`:return this.t(`palette.group.action`);default:return e}}destroy(){this.close()}},_n=class{backdrop=null;modal=null;input=null;list=null;symbols=[];current=``;filtered=[];selectedIndex=0;callbacks;boundKeydown;pickOverride=null;searchFn=null;searchTimer=null;searchAbort=null;status=`idle`;pickOnResults=!1;constructor(e,n=()=>document.body,r=t.t){this.host=n,this.t=r,this.callbacks=e,this.boundKeydown=this.handleKeydown.bind(this)}open(e,t,n,r){if(this.backdrop)return;this.pickOverride=n??null,this.searchFn=r??null,this.status=`idle`,this.symbols=e,this.current=t,this.filtered=e.map(e=>({symbol:e,score:0})),this.selectedIndex=Math.max(0,e.indexOf(t)),this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.addEventListener(`click`,()=>this.close()),this.modal=document.createElement(`div`),this.modal.className=`tcw-cmd-palette`;let i=document.createElement(`div`);i.className=`tcw-cmd-header`;let a=document.createElement(`span`);a.className=`tcw-cmd-icon`,a.innerHTML=D(`search`,16),i.appendChild(a),this.input=document.createElement(`input`),this.input.className=`tcw-cmd-input`,this.input.type=`text`,this.input.placeholder=this.t(`symbolSearch.placeholder`),this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.addEventListener(`input`,()=>this.filter()),i.appendChild(this.input);let o=document.createElement(`span`);o.className=`tcw-cmd-hint`,o.textContent=`ESC`,i.appendChild(o),this.modal.appendChild(i),this.list=document.createElement(`div`),this.list.className=`tcw-cmd-list`,this.modal.appendChild(this.list);let s=document.createElement(`div`);s.className=`tcw-cmd-footer`,s.innerHTML=hn(this.t(`common.navigate`),this.t(`common.open`),this.t(`common.close`)),this.modal.appendChild(s),this.host().append(this.backdrop,this.modal),this.renderList(),this.input.focus(),document.addEventListener(`keydown`,this.boundKeydown)}close(){document.removeEventListener(`keydown`,this.boundKeydown),this.cancelSearch(),this.pickOnResults=!1,this.searchFn=null,this.backdrop?.remove(),this.modal?.remove(),this.backdrop=null,this.modal=null,this.input=null,this.list=null,this.pickOverride=null,this.callbacks.onClose()}isOpen(){return this.backdrop!==null}destroy(){this.close()}filter(){this.pickOnResults=!1;let e=(this.input?.value??``).toUpperCase().trim();if(this.searchFn&&e){this.scheduleSearch(this.input?.value.trim()??``);return}this.cancelSearch(),this.status=`idle`,e?this.filtered=this.symbols.map(t=>({symbol:t,score:vn(t.toUpperCase(),e)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score):this.filtered=this.symbols.map(e=>({symbol:e,score:0})),this.selectedIndex=0,this.renderList()}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.filtered=[],this.renderList();try{let r=await t(e,n.signal);if(n.signal.aborted)return;this.filtered=r.map(e=>({symbol:e.symbol,score:0,description:e.description,meta:[e.exchange,e.type].filter(Boolean).join(` · `)||void 0})),this.status=`idle`}catch{if(n.signal.aborted)return;this.filtered=[],this.status=`failed`}this.selectedIndex=0,this.renderList(),this.pickOnResults&&(this.pickOnResults=!1,this.pick(0))}cancelSearch(){this.searchTimer!==null&&clearTimeout(this.searchTimer),this.searchTimer=null,this.searchAbort?.abort(),this.searchAbort=null}renderList(){if(!this.list)return;if(this.list.innerHTML=``,this.filtered.length===0){let e=document.createElement(`div`);e.className=`tcw-cmd-empty`,e.setAttribute(`role`,`status`),e.textContent=this.status===`searching`?this.t(`symbolSearch.searching`):this.status===`failed`?this.t(`symbolSearch.failed`):this.t(`symbolSearch.empty`),this.list.appendChild(e);return}let e=(this.input?.value??``).toUpperCase().trim();for(let t=0;t<this.filtered.length;t++){let{symbol:n,description:r,meta:i}=this.filtered[t],a=document.createElement(`button`);a.className=`tcw-cmd-item`,t===this.selectedIndex&&a.classList.add(`tcw-selected`),n===this.current&&a.classList.add(`tcw-active`);let o=document.createElement(`span`);if(o.className=`tcw-cmd-item-label`,o.innerHTML=yn(n,e),a.appendChild(o),r&&r!==n){let e=document.createElement(`span`);e.className=`tcw-cmd-item-desc`,e.textContent=r,a.appendChild(e)}if(i){let e=document.createElement(`span`);e.className=`tcw-cmd-item-meta`,e.textContent=i,a.appendChild(e)}if(n===this.current){let e=document.createElement(`span`);e.className=`tcw-cmd-check`,e.innerHTML=D(`check`,14),a.appendChild(e)}a.addEventListener(`click`,()=>this.pick(t)),a.addEventListener(`mouseenter`,()=>{this.selectedIndex=t,this.updateSelection()}),this.list.appendChild(a)}}updateSelection(){if(!this.list)return;let e=this.list.querySelectorAll(`.tcw-cmd-item`);e.forEach((e,t)=>e.classList.toggle(`tcw-selected`,t===this.selectedIndex)),e[this.selectedIndex]?.scrollIntoView?.({block:`nearest`})}pick(e){let t=this.filtered[e];if(!t)return;let n=this.pickOverride;n?n(t.symbol):this.callbacks.onPick(t.symbol),this.close()}handleKeydown(e){switch(e.key){case`Escape`:e.preventDefault(),this.close();break;case`ArrowDown`:e.preventDefault(),this.filtered.length>0&&(this.selectedIndex=(this.selectedIndex+1)%this.filtered.length,this.updateSelection());break;case`ArrowUp`:e.preventDefault(),this.filtered.length>0&&(this.selectedIndex=(this.selectedIndex-1+this.filtered.length)%this.filtered.length,this.updateSelection());break;case`Enter`:if(e.preventDefault(),this.searchTimer!==null||this.status===`searching`){this.pickOnResults=!0,this.searchTimer!==null&&this.searchNow();break}this.pick(this.selectedIndex);break}}};function vn(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 yn(e,t){if(!t)return O(e);let n=e.toUpperCase(),r=``,i=0;for(let a=0;a<e.length;a++)i<t.length&&n[a]===t[i]?(r+=`<mark style="background:transparent;color:var(--tcw-accent);font-weight:700">${O(e[a])}</mark>`,i++):r+=O(e[a]);return r}var bn={"Search & navigation":`hotkeys.group.searchNavigation`,"Chart manipulation":`hotkeys.group.chartManipulation`,"Touch (mobile / tablet)":`hotkeys.group.touch`,Keyboard:`hotkeys.group.keyboard`,Drawing:`hotkeys.group.drawing`,More:`hotkeys.group.more`},z=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent)?`⌘`:`Ctrl`,xn=[{title:`Search & navigation`,entries:[{keys:[z,`K`],label:`hotkeys.commandPalette`,feature:`hotkeys.commandPalette`},{keys:[z,`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:[z,`S`],label:`hotkeys.saveLayout`,feature:`hotkeys.save`},{keys:[`0–9`],label:`hotkeys.typeInterval`,feature:`intervalTyping`},{keys:[`?`],label:`hotkeys.showSheet`,feature:`hotkeys.help`}]},{title:`Chart manipulation`,entries:[{keys:[`key.drag`],label:`hotkeys.pan`},{keys:[z,`key.drag`],label:`hotkeys.boxSelect`},{keys:[z,`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:[`F`],label:`hotkeys.fit`}]},{title:`Drawing`,entries:[{keys:[z,`Z`],label:`hotkeys.undo`},{keys:[z,`Shift`,`Z`],label:`hotkeys.redo`},{keys:[`Esc`],label:`hotkeys.cancelDrawing`},{keys:[z,`C`],label:`hotkeys.copy`},{keys:[z,`V`],label:`hotkeys.paste`},{keys:[`key.rightClick`],label:`hotkeys.drawingMenu`},{keys:[`key.doubleClick`],label:`hotkeys.drawingSettings`},{keys:[z,`G`],label:`hotkeys.group`},{keys:[z,`Shift`,`G`],label:`hotkeys.ungroup`},{keys:[z,`]`,`[`],label:`hotkeys.orderStep`},{keys:[z,`Shift`,`]`,`[`],label:`hotkeys.orderEnd`},{keys:[`Enter`],label:`hotkeys.finishPath`},{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`}]}],Sn=class{backdrop=null;modal=null;callbacks;t;boundKeydown;constructor(e,t,n=()=>document.body){this.host=n,this.callbacks=e,this.t=t,this.boundKeydown=e=>{e.key===`Escape`&&(e.preventDefault(),this.close())}}open(e={}){if(this.backdrop)return;let t=e.isOn??(()=>!0),n=new Set((e.extra??[]).map(e=>e.keys.join(`+`).toLowerCase())),r=xn.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&&r.push({title:`More`,entries:[...e.extra]}),this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.addEventListener(`click`,()=>this.close()),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-hotkey-sheet`,this.modal.style.width=`640px`;let i=document.createElement(`div`);i.className=`tcw-modal-header`;let a=document.createElement(`h3`);a.textContent=this.t(`hotkeys.title`),i.appendChild(a);let o=document.createElement(`button`);o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`hotkeys.close`)),o.innerHTML=D(`x`,14),o.addEventListener(`click`,()=>this.close()),i.appendChild(o),this.modal.appendChild(i);let s=document.createElement(`div`);s.className=`tcw-modal-body`;let c=document.createElement(`div`);c.className=`tcw-hotkey-grid`;for(let e of r){let t=document.createElement(`section`);t.className=`tcw-hotkey-section`;let n=document.createElement(`div`);n.className=`tcw-settings-section-title`;let r=bn[e.title];n.textContent=r?this.t(r):e.title,t.appendChild(n);for(let n of e.entries){let e=document.createElement(`div`);e.className=`tcw-hotkey-row`;let r=document.createElement(`div`);r.className=`tcw-hotkey-keys`;for(let e=0;e<n.keys.length;e++){if(e>0){let e=document.createElement(`span`);e.className=`tcw-hotkey-sep`,e.textContent=`+`,r.appendChild(e)}let t=document.createElement(`kbd`);t.className=`tcw-cmd-kbd`;let i=n.keys[e];t.textContent=i.startsWith(`key.`)?this.t(i):i,r.appendChild(t)}e.appendChild(r);let i=document.createElement(`span`);i.className=`tcw-hotkey-label`,i.textContent=`text`in n?n.text:this.t(n.label),e.appendChild(i),t.appendChild(e)}c.appendChild(t)}s.appendChild(c),this.modal.appendChild(s);let l=document.createElement(`div`);l.className=`tcw-modal-footer`;let u=document.createElement(`span`);u.style.cssText=`font-size:11px;color:var(--tcw-text-muted)`,u.textContent=this.t(`hotkeys.footer`),l.appendChild(u);let d=document.createElement(`button`);d.className=`tcw-done-btn`,d.textContent=this.t(`hotkeys.gotIt`),d.addEventListener(`click`,()=>this.close()),l.appendChild(d),this.modal.appendChild(l),this.host().append(this.backdrop,this.modal),document.addEventListener(`keydown`,this.boundKeydown)}close(){document.removeEventListener(`keydown`,this.boundKeydown),this.backdrop?.remove(),this.modal?.remove(),this.backdrop=null,this.modal=null,this.callbacks.onClose()}isOpen(){return this.backdrop!==null}destroy(){this.close()}},Cn={selectHint:`Click a bar to start the replay`,random:`Random bar`,realtime:`Back to realtime`,barsPerSecond:`bars/s`,play:`Play`,pause:`Pause`,stepBack:`Step back (Shift+←)`,stepForward:`Step forward (Shift+→)`,replay:`Replay`,position:`Replay position`,speed:`Speed`,step:`Step`},wn=[1,2,3,5,10,25,50],Tn=class{root=null;scrubber=null;progressLabel=null;playBtn=null;realtimeBtn=null;state=`stopped`;mode=`select`;ended=!1;total=0;speed=5;steps=[];step=`bar`;labels;constructor(e,t={}){this.callbacks=e,this.labels={...Cn,...t}}mount(e,t){this.root||(this.total=Math.max(0,t.total),this.speed=t.speed??5,this.steps=t.steps??[],this.step=t.step??`bar`,this.state=`paused`,this.mode=t.mode??`select`,this.root=document.createElement(`div`),this.root.className=`tcw-replay-bar`,E(this.root,`replay`),this.root.setAttribute(`role`,`toolbar`),this.root.setAttribute(`aria-label`,this.labels.replay),this.root.innerHTML=this.markup(),e.appendChild(this.root),this.wireEvents(),this.syncUi())}unmount(){this.root?.remove(),this.root=null,this.scrubber=null,this.progressLabel=null,this.playBtn=null,this.realtimeBtn=null,this.state=`stopped`,this.ended=!1}isMounted(){return this.root!==null}getMode(){return this.mode}setMode(e){let t=!!this.root?.contains(document.activeElement);this.mode=e,this.syncUi(),t&&e===`replay`&&this.playBtn?.focus()}setState(e){this.state=e,this.syncUi()}setEnded(e){this.ended!==e&&(this.ended=e,this.syncUi())}setProgress(e,t){this.total=t,this.scrubber&&(this.scrubber.max=String(Math.max(0,t-1)),this.scrubber.value=String(e)),this.progressLabel&&(this.progressLabel.textContent=`${Math.min(e+1,t)} / ${t}`)}destroy(){this.unmount()}markup(){let e=this.labels,t=wn.map(t=>`<option value="${t}"${t===this.speed?` selected`:``}>${t} ${O(e.barsPerSecond)}</option>`).join(``);return`
5958
6030
  <span class="tcw-replay-group" data-mode="select">
5959
- <span class="tcw-replay-hint" role="status">${kn()}${k(e.selectHint)}</span>
5960
- <button class="tcw-replay-text-btn" data-act="random">${k(e.random)}</button>
6031
+ <span class="tcw-replay-hint" role="status">${An()}${O(e.selectHint)}</span>
6032
+ <button class="tcw-replay-text-btn" data-act="random">${O(e.random)}</button>
5961
6033
  </span>
5962
6034
  <span class="tcw-replay-group" data-mode="replay">
5963
- <button class="tcw-replay-btn" data-act="stepBack" title="${k(e.stepBack)}" aria-label="${k(e.stepBack)}">${Dn()}</button>
5964
- <button class="tcw-replay-btn tcw-replay-play" data-act="play" title="${k(e.play)}" aria-label="${k(e.play)}">${Tn()}</button>
5965
- <button class="tcw-replay-btn" data-act="stepForward" title="${k(e.stepForward)}" aria-label="${k(e.stepForward)}">${On()}</button>
5966
- <input type="range" class="tcw-replay-scrubber" data-act="seek" min="0" max="${Math.max(0,this.total-1)}" value="0" step="1" aria-label="${k(this.labels.position)}" />
6035
+ <button class="tcw-replay-btn" data-act="stepBack" title="${O(e.stepBack)}" aria-label="${O(e.stepBack)}">${On()}</button>
6036
+ <button class="tcw-replay-btn tcw-replay-play" data-act="play" title="${O(e.play)}" aria-label="${O(e.play)}">${En()}</button>
6037
+ <button class="tcw-replay-btn" data-act="stepForward" title="${O(e.stepForward)}" aria-label="${O(e.stepForward)}">${kn()}</button>
6038
+ <input type="range" class="tcw-replay-scrubber" data-act="seek" min="0" max="${Math.max(0,this.total-1)}" value="0" step="1" aria-label="${O(this.labels.position)}" />
5967
6039
  <span class="tcw-replay-progress" data-tcw="progress">1 / ${this.total}</span>
5968
- <select class="tcw-replay-speed" data-act="speed" aria-label="${k(this.labels.speed)}">${t}</select>
6040
+ <select class="tcw-replay-speed" data-act="speed" aria-label="${O(this.labels.speed)}">${t}</select>
5969
6041
  </span>
5970
- ${this.steps.length>1?`<select class="tcw-replay-speed tcw-replay-step" data-act="step" aria-label="${k(e.step)}" title="${k(e.step)}">${this.steps.map(e=>`<option value="${k(e.value)}"${e.value===this.step?` selected`:``}>${k(e.label)}</option>`).join(``)}</select>`:``}
5971
- <button class="tcw-replay-text-btn tcw-replay-realtime" data-act="realtime">${k(e.realtime)}</button>
5972
- `}wireEvents(){let e=this.root;e&&(this.scrubber=e.querySelector(`input[data-act="seek"]`),this.progressLabel=e.querySelector(`[data-tcw="progress"]`),this.playBtn=e.querySelector(`button[data-act="play"]`),this.realtimeBtn=e.querySelector(`button[data-act="realtime"]`),this.realtimeBtn?.addEventListener(`click`,()=>this.callbacks.onClose()),e.querySelector(`[data-act="random"]`)?.addEventListener(`click`,()=>this.callbacks.onRandomStart()),e.querySelector(`[data-act="stepBack"]`)?.addEventListener(`click`,()=>this.callbacks.onStepBack()),e.querySelector(`[data-act="stepForward"]`)?.addEventListener(`click`,()=>this.callbacks.onStepForward()),this.playBtn?.addEventListener(`click`,()=>{this.state===`playing`?this.callbacks.onPause():this.callbacks.onPlay()}),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.speed=t,this.callbacks.onSpeedChange(t)}),e.querySelector(`[data-act="step"]`)?.addEventListener(`change`,e=>{this.step=e.target.value,this.callbacks.onStepChange?.(this.step)}))}syncUi(){let e=this.root;if(e){for(let t of e.querySelectorAll(`.tcw-replay-group`))t.hidden=t.dataset.mode!==this.mode;if(e.classList.toggle(`tcw-replay-bar--ended`,this.ended),this.playBtn){let e=this.state===`playing`;this.playBtn.innerHTML=e?En():Tn(),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}}}},Tn=()=>D(`play`,14),En=()=>D(`pause`,14),Dn=()=>D(`stepBack`,14),On=()=>D(`stepForward`,14),kn=()=>D(`cursor`,14),An=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.textContent=`+`,r.title=n.add,r.setAttribute(`aria-label`,n.add),r.hidden=!t.onAdd,r.addEventListener(`click`,()=>t.onAdd?.()),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,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)}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()}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=jn(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){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-remove`,r.innerHTML=D(`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=Mn(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&&Nn(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 jn(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 Mn(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 Nn(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 Pn=50,Fn=500,In=60,Ln=64,Rn=e=>typeof e==`string`&&e.trim().slice(0,In)||null,zn=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t&&t.length<=Ln?t:null};function Bn(e){let t=[];for(let n of e){let e=zn(n);if(e&&!t.includes(e)&&t.push(e),t.length===Fn)break}return t}function Vn(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===Pn)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=Ln?t.id:null,i=Rn(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?Bn(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 Hn=e=>({...e,symbols:[...e.symbols]}),Un=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?Vn({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:Rn(e.defaultName)??`Watchlist`,symbols:Bn(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map(Hn)}getActive(){return Hn(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=Vn({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=Rn(e);if(!t||this.lists.length>=Pn)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(),Hn(r)}rename(e,t){let n=Rn(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=zn(e),r=this.lists.find(e=>e.id===t);return!n||!r||r.symbols.includes(n)||r.symbols.length>=Fn?!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?Vn(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{}}},Wn=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`,E(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=D(`x`,14),o.addEventListener(`click`,()=>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)}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(B(`div`,`tcw-syminfo-symbol`,e.symbol)),e.description&&t.append(B(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(B(`div`,`tcw-syminfo-meta`,e.meta));let n=document.createElement(`div`);if(n.className=`tcw-syminfo-quote`,e.price&&n.append(B(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=B(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),n.append(t)}let r=B(`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(B(`dt`,``,t.label),B(`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=B(`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(B(`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(B(`span`,``,t.title));t.meta&&e.append(B(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function B(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var Gn=10,Kn=5*6e4,qn=864e5;function Jn(e){let{info:r,quote:i,t:a,textLocale:o}=e,s=Xn(e.bars,r?.timezone),c=e.formatPrice,l=i?.last??s?.close,u=i?.prevClose??s?.prevClose,d=i?.change??(l!==void 0&&u!==void 0?l-u:void 0),f=l!==void 0&&d!==void 0?l-d:void 0,p=i?.changePercent??(d!==void 0&&f?d/f*100:void 0),m=(0,n.marketStatus)(r,e.now),h=a(m.state===`open`?`symbolInfo.open`:m.state===`closed`?`symbolInfo.closed`:`symbolInfo.always`);if(m.state!==`always`&&m.next!==null){let n=Zn(m.next-e.now,o);h+=` · ${t.r(a(m.state===`open`?`symbolInfo.closesIn`:`symbolInfo.opensIn`),{when:n})}`}let ee=[],g=(e,t)=>{t&&ee.push({label:e,value:t})},_=e=>e===void 0?void 0:c(e);g(a(`dataWindow.open`),_(i?.open??s?.open)),g(a(`dataWindow.high`),_(i?.high??s?.high)),g(a(`dataWindow.low`),_(i?.low??s?.low)),g(a(`symbolInfo.prevClose`),_(u));let v=i?.volume??s?.volume;g(a(`dataWindow.volume`),v===void 0?void 0:Qn(v,e.numberLocale)),g(a(`symbolInfo.bid`),_(i?.bid)),g(a(`symbolInfo.ask`),_(i?.ask)),g(a(`symbolInfo.tick`),r?.minTick===void 0?void 0:String(r.minTick)),g(a(`symbolInfo.currency`),r?.currency),g(a(`symbolInfo.timezone`),r?.timezone),g(a(`symbolInfo.hours`),$n(r,o));let te=(d??0)>=0?`+`:`-`;return{symbol:e.symbol,description:r?.description,meta:[r?.exchange,r?.type].filter(Boolean).join(` · `)||void 0,price:l===void 0?void 0:c(l),change:d===void 0?void 0:{text:`${te}${c(Math.abs(d))}${p===void 0?``:` (${te}${Math.abs(p).toFixed(2)}%)`}`,up:d>=0},status:{state:m.state,text:h},stats:ee}}var Yn=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,Zn(e.time-t,i)].filter(Boolean).join(` · `)}))})},c=this.cache.get(e);if(c&&Date.now()-c.at<Kn){s(c.items);return}r({kind:`loading`}),Promise.resolve().then(()=>t(e,Gn)).then(t=>{if(o!==this.request||a())return;let r=(0,n.readNews)(t,Gn);this.cache.set(e,{at:Date.now(),items:r}),s(r)}).catch(()=>{o===this.request&&!a()&&r({kind:`failed`})})}};function Xn(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))/qn)},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 Zn(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 Qn(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function $n(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 er={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function tr(){let e={};for(let[t,n]of Object.entries(er))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var nr=300,rr=80,ir=n.PHI**-3,ar=80,or=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`,E(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,E(i,a),i.title=r,i.setAttribute(`aria-label`,r),i.innerHTML=D(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(ar,t.height*ir);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),rr)},nr)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function sr(e,n,r,i=!1){let a=e.label??n(`alerts.source.price`),o=fr.get(e.condition),s=o?n(o):e.condition;if(lr.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?mr(e.price):r(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:i?`${a} `:``}${s} ${l}`}var cr=[{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`}],lr=[`movesUp`,`movesDown`],ur={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},dr=``,fr=new Map(cr.map(e=>[e.value,e.key]));function pr(e){return Math.round(e*1e6)/1e6}function mr(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var hr=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`,E(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=D(`x`,14),s.addEventListener(`click`,()=>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 cr){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=`${D(`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=lr.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==dr}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=dr,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:dr,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()}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(pr(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(lr.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!==dr)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=ur[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 sr(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=D(`trash`,14),o.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),n.appendChild(r),n.appendChild(o),this.listEl.appendChild(n)}}},gr=`print`,_r=3,vr=10;function V(e,t){return Math.max(vr,(0,n.phiStep)(e,t,_r))}var yr=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,br=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,xr={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:`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`,mono:`'Cascadia Mono', 'SF Mono', ui-monospace, Menlo, Consolas, monospace`,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', ${yr}`,mono:br,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', ${yr}`,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', ${yr}`,mono:br,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}},Sr={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 Cr(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 wr=Object.freeze(Object.fromEntries(Object.keys(xr).map(e=>[e,Er(Tr(e))])));function Tr(e){let{density:t,...n}=xr[e];return{...n,preset:e,radius:{...n.radius},components:Cr(n.radius,n.components),sizes:{...n.sizes},font:{...n.font},borders:{...n.borders},shadows:{...n.shadows}}}function Er(e){for(let t of Object.values(e))t&&typeof t==`object`&&Er(t);return Object.freeze(e)}var Dr=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(xr,e),H=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,Or=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&kr(e);function kr(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 Ar=(e,t)=>typeof e==`string`&&t.includes(e);function U(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=Dr(t.preset)?t.preset:gr,r=xr[n],i=U(r.radius,t.radius,(e,t)=>H(t,0,999)),a=U(t.density===`compact`||t.density===`spacious`?(r.density??Sr)[t.density]:r.sizes,t.sizes,(e,t)=>e===`icon`?H(t,10,32):H(t,16,80)),o=U(r.font,t.font,(e,t)=>e===`family`||e===`mono`?Or(t):e===`size`?H(t,11,20):e===`weight`||e===`strongWeight`?H(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:H(t,0,.5));return{preset:n,radius:i,components:U(Cr(i,r.components),t.components,(e,t)=>H(t,0,999)),sizes:a,font:o,borders:U(r.borders,t.borders,(e,t)=>e===`width`?H(t,0,4):typeof t==`boolean`),shadows:U(r.shadows,t.shadows,(e,t)=>Or(t)),blur:H(t.blur,0,40)?t.blur:r.blur,active:Ar(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:Ar(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:Ar(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:Ar(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:H(t.tagRadius,0,999)?t.tagRadius:r.tagRadius}}function jr(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(V(a.size,-1)),"--tcw-font-size-xs":t(V(a.size,-2)),"--tcw-font-size-lg":t(V(a.size,1)),"--tcw-font-size-xl":t(V(a.size,2)),"--tcw-font-size-display":t(V(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 G(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(jr(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 Mr=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,E(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=D(`x`,14),o.addEventListener(`click`,()=>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&&E(e,`compare`)}e.appendChild(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()}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=D(`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.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));E(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.drawingsEl.replaceChildren(),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=D(`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){if(!e.isConnected)return;let r=document.createElement(`input`);r.type=`text`,r.className=`tcw-tree-rename`,r.value=n,r.maxLength=80,r.setAttribute(`aria-label`,this.t(`objects.renameGroup`));let i=!1,a=a=>{if(i)return;i=!0;let o=r.value.trim();r.isConnected&&r.replaceWith(e),a&&o&&o!==n&&this.callbacks.onRenameGroup?.(t,o)};r.addEventListener(`keydown`,e=>{e.key===`Enter`?a(!0):e.key===`Escape`&&(e.stopPropagation(),a(!1))}),r.addEventListener(`blur`,()=>a(!0)),e.replaceWith(r),r.focus(),r.select()}drawingRow(e){let t=this.row(e.label);e.visible||t.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);if(n.className=`tcw-tree-actions`,n.appendChild(this.iconButton(e.visible?`eye`:`eyeOff`,e.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleDrawingVisible(e.id,!e.visible))),n.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.onConfigureDrawing){let t=this.iconButton(`settings`,this.t(`objects.drawingSettings`),``,()=>this.callbacks.onConfigureDrawing?.(e.id));E(t,`drawingSettings`),n.appendChild(t)}return n.appendChild(this.iconButton(`trash`,this.t(`objects.removeDrawing`),`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(e.id))),t.appendChild(n),t}renderCompares(e){if(this.compareEl){if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(this.t(`objects.noComparisons`)));return}for(let t of e){let e=this.row(t.label),n=document.createElement(`span`);n.className=`tcw-tree-dot`,n.style.background=t.color,e.insertBefore(n,e.firstChild),this.callbacks.onRemoveCompare&&e.appendChild(this.iconButton(`trash`,this.t(`objects.removeComparison`),`tcw-tree-del`,()=>this.callbacks.onRemoveCompare?.(t.id))),this.compareEl.appendChild(e)}}}row(e){let t=document.createElement(`div`);t.className=`tcw-tree-row`;let n=document.createElement(`span`);return n.className=`tcw-tree-name`,n.textContent=e,n.title=e,t.appendChild(n),t}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=D(e,14),i.addEventListener(`click`,r),i}},Nr={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`};function Pr(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:Nr[e]??e}var Fr=[1,1.5,2,3,4],Ir=[`solid`,`dashed`,`dotted`],Lr=`#4c8dff`,Rr=10,zr={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 Br(e,t,n,r,i){let a=Gr();for(let e of[...t.plots].sort((e,t)=>e.color-t.color))a.appendChild(Vr(e,t,n,r));let o=P(Fr.map(e=>({value:String(e),label:`${e} px`})),String(t.lineWidth),e=>n.lineWidth(Number(e)));if(o.dataset.role=`line-width`,a.appendChild(M(r(`indicatorSettings.lineWidth`),o)),t.scale&&n.scale){let e=P([{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(M(r(`indicatorSettings.scale`),e))}e.appendChild(a),t.levels&&n.levels&&e.appendChild(Hr([...t.levels],n.levels,r,i))}function Vr(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=Yt(t.colors[e]??t.colors[0]??Lr,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=P(Ir.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 Hr(e,t,n,r){let i=Gr(),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+Rr]);let t=i.querySelectorAll(`.tcw-indi-level input`);t[t.length-1]?.focus()}),i.replaceChildren(e,...a.length===0?[Kr(n(`indicatorSettings.noLevels`))]:t,r)},s=e=>{a=e,t([...e]),o()},c=(e,o)=>{let c=N(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=D(`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 Ur(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=Gr();for(let e of r.INTERVAL_UNITS)s.appendChild(Wr(e,a.get(e),o,i));e.appendChild(s)}function Wr(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(zr[e]),o.append(s,c),a.appendChild(o);let l=[];if(e!==`ticks`){let o=(a,o)=>{let s=N(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(zr[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 Gr(){let e=document.createElement(`div`);return e.className=`tcw-settings-section`,e}function Kr(e){let t=document.createElement(`div`);return t.className=`tcw-settings-label`,t.textContent=e,t}var qr=1,Jr=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Yr=1.5,Xr={visible:!0,lineStyle:`solid`},K=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Zr=e=>JSON.parse(JSON.stringify(e));function Qr(e){return e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase())}function $r(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].map(e=>[e,{...Xr,...t[e]}]))}var ei=class{backdrop;modal;bodyEl;titleEl;tabsEl;defaultsBtn;menu=null;callbacks;target=null;draft={};initial=null;look={colors:[],lineWidth:Yr,plots:{},levels:[],intervals:null};tab=`inputs`;tabButtons=[];returnFocus=null;uid=qr++;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=D(`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>${D(`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??Yr,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:Zr(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;K(this.currentParams(),t.params)||this.callbacks.onApply(n,{...t.params});let r=t.look,i={};K(this.look.colors,r.colors)||(i.colors=[...r.colors]),this.look.lineWidth!==r.lineWidth&&(i.lineWidths=[r.lineWidth]),K(this.look.plots,r.plots)||(i.plots=$r(this.look.plots,r.plots)),Object.keys(i).length>0&&this.callbacks.onStyle?.(n,i),K(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),K(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=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||t.length===0||(e.preventDefault(),this.selectTab(t[r],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.finish(!1);return}j(e,this.modal)}renderBody(){this.bodyEl.replaceChildren();let e=this.target;e&&(this.tab===`style`?this.renderStyle(e):this.tab===`visibility`?Ur(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=Jt(!!n,t=>this.setValue(e,t));else if(r===`number`){let r=Number(n);i=N(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`&&Jr.test(n)?Yt(n,t=>this.setValue(e,t)):this.textControl(e,String(n??``));return M(t?.label??Qr(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 e of t)r.appendChild(this.option(String(e),String(e)));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);Br(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:$r(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])=>!K(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!==Yr&&(i.lineWidths=[this.look.lineWidth]),Object.keys(this.look.plots).length>0&&(i.plots=Zr(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 ti(e){return e.normalize(`NFD`).replace(/[̀-ͯ]/g,``).toLowerCase()}var ni=/[\s/()%-]+/;function ri(e,t){let n=ti(e.shortName),r=ti(e.name);return n===t||ti(e.id)===t?0:n.startsWith(t)||r.startsWith(t)?1:[...r.split(ni),...n.split(ni)].some(e=>e.startsWith(t))?2:r.includes(t)||n.includes(t)?3:null}function ii(e,t){let n=ti(t.trim());return n?e.map(e=>({item:e,rank:ri(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 ai=1,oi=(e,t)=>e.name.localeCompare(t.name),si=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=ai++;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=D(`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=D(`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`?D(`star`,14):e===`templates`?D(`layers`,14):``}<span></span>`,t.querySelector(`span`).textContent=this.viewLabel(e),e===`templates`&&E(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=ii(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(oi);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(oi);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(oi).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=D(`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=`${D(`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=`${D(`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=D(`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}j(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 ci(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var li=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function ui(e){return li(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 di(e){if(!li(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 fi=class{constructor(e=`tcw:indicator-defaults`,t=ci()){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(!li(t))return e;for(let[n,r]of Object.entries(t))li(r)&&e.set(n,{params:ui(r.params),style:di(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:ui(t.params),style:di(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},pi=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),mi=80,hi={crosshairMode:[`normal`,`magnet`,`hidden`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},gi=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function _i(e){if(!gi(e))return{};let t={};for(let[n,r]of Object.entries(me)){if(pi.has(n)||!(n in e))continue;let i=e[n];if(typeof i!=typeof r||typeof i==`number`&&!Number.isFinite(i))continue;let a=hi[n];a&&!a.includes(i)||(t[n]=i)}return t}function vi(e){let{overrides:t}=(0,n.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(t).filter(([e,t])=>t!==null&&w.includes(e)))}function yi(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var bi=class{constructor(e=`tcw:chart-templates`,t=yi()){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)!gi(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,mi).trim(),settings:_i(n.settings),style:vi(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,mi).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:_i(t),style:vi(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 xi(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Si=80;function Ci(e){let{text:t,...r}=(0,n.sanitizeDrawingStyle)(e);return r}function wi(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 Ti=class{templates=[];constructor(e=`tcw:draw-templates`,t=xi()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(wi)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?wi(n):null}save(e,t,n){let r=e.trim().slice(0,Si);if(!r)return;let i={name:r,style:Ci(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,Si),style:Ci(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{}}},Ei=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=xi()){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{}}},Di=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],Oi=[1,2,3,4],ki=[`solid`,`dashed`,`dotted`],Ai=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=D(`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=`${D(`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 Di){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 Oi){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 ki){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=D(`trash`,13),a.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(a),this.templatesEl.appendChild(e)}}},ji=10,q=4,Mi=4,Ni=20,Pi=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function Fi(e){return typeof e==`string`&&Pi.test(e.trim())?e.trim():`#7d8696`}function Ii(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,Ni):1}function Li(e){return ki.includes(e)?e:`solid`}var Ri=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=[Fi(t.color),Ii(t.lineWidth),Li(t.lineStyle),e.locked,e.canDelete,e.canSettings,e.canAlert].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=Fi(e.style.color),r=Ii(e.style.lineWidth),i=Li(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`),zi(i)),`<span class="tcw-sel-sep" aria-hidden="true"></span>`,e.canSettings?s(`settings`,t(`legend.settings`),D(`settings`,15)):``,e.canAlert?s(`alert`,t(`drawingSettings.addAlert`),D(`bell`,15)):``,s(`lock`,t(a?`common.unlock`:`common.lock`),D(a?`lock`:`unlock`,15),a?` tcw-sel-on`:``).replace(`<button `,`<button aria-pressed="${a}" `),s(`more`,t(`legend.more`),D(`more`,15)),e.canDelete?s(`delete`,t(`drawingMenu.delete`),D(`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-ji;o<n.y+q&&(o=Math.min(t.y+t.height+ji,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`){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=Fi(n.color).toLowerCase(),i=Ii(n.lineWidth),a=Li(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`?this.pop.innerHTML=Di.map(e=>o(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=Oi.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=ki.map(e=>o(`tcw-sel-option`,e===a,`data-style="${e}"`,zi(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`?Mi: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`);t&&(t.dataset.color?this.callbacks.onStyle({color:t.dataset.color}):t.dataset.width?this.callbacks.onStyle({lineWidth:Number(t.dataset.width)}):t.dataset.style&&this.callbacks.onStyle({lineStyle:Li(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 zi(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 Bi=12,Vi=[1,2,3,4],Hi=[`solid`,`dashed`,`dotted`],Ui=[10,11,12,14,16,18,20,24,28,32],Wi=48,Gi=1,Ki=class{backdrop;modal;titleEl;tabsEl;bodyEl;footerLeft;tabButtons=[];target=null;style;options={};anchors=[];tab=`style`;returnFocus=null;uid=Gi++;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=D(`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`);let s=document.createElement(`div`);s.className=`tcw-modal-footer`,this.footerLeft=document.createElement(`div`),this.footerLeft.className=`tcw-drawing-settings-tools`;let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-reset-link`,c.textContent=this.t(`common.cancel`),c.addEventListener(`click`,()=>this.close(!0));let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-done-btn`,l.textContent=this.t(`drawingSettings.ok`),l.addEventListener(`click`,()=>this.close(!1)),s.append(this.footerLeft,c,l),this.modal.append(a,this.tabsEl,this.bodyEl,s),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){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.titleEl.textContent=e.name,this.tab=`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,(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.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.backdrop.remove()}tabs(){let e=[`style`];return this.target&&Object.keys(this.target.defs).length>0&&e.push(`options`),this.target&&this.target.anchors.length<=Bi&&e.push(`coordinates`),e}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=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.selectTab(t[r],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.close(!0);return}j(e,this.modal)}renderBody(){if(this.bodyEl.replaceChildren(),this.footerLeft.replaceChildren(),!this.target)return;if(this.target.alertable&&this.callbacks.onAddAlert){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-reset-link tcw-drawing-alert`,E(e,`alerts`),e.innerHTML=`${D(`bell`,13)}<span></span>`,e.querySelector(`span`).textContent=this.t(`drawingSettings.addAlert`),e.addEventListener(`click`,()=>this.callbacks.onAddAlert?.(this.target.id)),this.footerLeft.appendChild(e)}let e=document.createElement(`div`);e.className=`tcw-settings-section`,this.tab===`options`?this.renderOptions(e):this.tab===`coordinates`?this.renderCoordinates(e):this.renderStyle(e),this.bodyEl.appendChild(e)}change(e){this.target&&this.callbacks.onChange(this.target.id,e)}setStyle(e){this.style={...this.style,...e},this.change({style:e})}setOptions(e){this.options={...this.options,...structuredClone(e)},this.change({options:e})}renderStyle(e){let t=this.target;e.appendChild(M(this.t(`drawingSettings.color`),Yt(this.style.color,e=>this.setStyle({color:e})))),e.appendChild(M(this.t(`drawingSettings.lineWidth`),P(Vi.map(e=>({value:String(e),label:`${e} px`})),String(this.style.lineWidth),e=>this.setStyle({lineWidth:Number(e)})))),e.appendChild(M(this.t(`drawingSettings.lineStyle`),P(Hi.map(e=>({value:e,label:this.t(`drawingSettings.lineStyle.${e}`)})),this.style.lineStyle,e=>this.setStyle({lineStyle:e})))),t.fill&&this.renderFill(e),t.text&&this.renderText(e),this.callbacks.templates&&this.renderTemplates(e)}renderFill(e){let t=this.style.fillColor??$t(this.style.color,.1),n=Xt(t),r=Qt(t),i=()=>this.setStyle({fillColor:$t(n,r),fillOpacity:r});e.appendChild(M(this.t(`drawingSettings.fill`),Yt(n,e=>{n=e,i()}))),e.appendChild(M(this.t(`drawingSettings.opacity`),N(Math.round(r*100),{min:0,max:100,step:5},e=>{r=e/100,i()})))}renderText(e){let t=document.createElement(`textarea`);t.className=`tcw-indi-input tcw-drawing-text`,t.rows=3,t.value=this.style.text??``,t.addEventListener(`input`,()=>this.setStyle({text:t.value})),e.appendChild(M(this.t(`drawingSettings.text`),t)),e.appendChild(M(this.t(`drawingSettings.fontSize`),P(Ui.map(e=>({value:String(e),label:`${e} px`})),String(this.style.fontSize??12),e=>this.setStyle({fontSize:Number(e)}))))}renderTemplates(e){let t=this.callbacks.templates,r=this.target,i=document.createElement(`div`);i.className=`tcw-style-subhead`,i.textContent=this.t(`drawingStyle.templates`),e.appendChild(i);let a=document.createElement(`div`);a.className=`tcw-drawing-templates`;let o=t.list(r.type);if(o.length===0){let e=document.createElement(`div`);e.className=`tcw-settings-label`,e.textContent=this.t(`drawingStyle.noTemplates`),a.appendChild(e)}for(let e of o){let i=document.createElement(`div`);i.className=`tcw-style-tmpl`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-style-tmpl-apply`,o.textContent=e.name,o.addEventListener(`click`,()=>{this.setStyle(e.style),e.options&&this.setOptions((0,n.sanitizeDrawingOptions)(r.defs,e.options)),this.renderBody()});let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-style-tmpl-del`,s.setAttribute(`aria-label`,this.t(`drawingStyle.deleteTemplate`)),s.innerHTML=D(`x`,12),s.addEventListener(`click`,()=>{t.remove(e.name,e.type),this.renderBody()}),i.append(o,s),a.appendChild(i)}e.appendChild(a);let s=document.createElement(`div`);s.className=`tcw-style-save`;let c=document.createElement(`input`);c.type=`text`,c.className=`tcw-style-name`,c.placeholder=this.t(`drawingStyle.templateName`),c.setAttribute(`aria-label`,this.t(`drawingStyle.templateName`));let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-style-savebtn`,l.textContent=this.t(`common.save`),l.addEventListener(`click`,()=>{c.value.trim()&&(t.save(c.value,this.style,{type:r.type,options:this.options}),this.renderBody())}),s.append(c,l),e.appendChild(s)}label(e,t){let n=`drawingOption.${e}`,r=this.t(n);return r===n?t:r}renderOptions(e){let t=this.target;for(let[n,r]of Object.entries(t.defs))r.kind===`levels`?e.appendChild(this.levelsEditor(n,r)):e.appendChild(M(this.label(n,r.label),this.optionControl(n,r)));let n=document.createElement(`button`);if(n.type=`button`,n.className=`tcw-reset-link`,n.textContent=this.t(`settings.resetToDefaults`),n.addEventListener(`click`,()=>{let e={};for(let[n,r]of Object.entries(t.defs))e[n]=structuredClone(r.default);this.setOptions(e),this.renderBody()}),this.footerLeft.appendChild(n),this.callbacks.onSaveDefault){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-reset-link`,e.textContent=this.t(`drawingSettings.saveDefault`),e.addEventListener(`click`,()=>this.callbacks.onSaveDefault?.(t.type,structuredClone(this.options))),this.footerLeft.appendChild(e)}}optionControl(e,t){let n=this.options[e];switch(t.kind){case`boolean`:return Jt(!!n,t=>this.setOptions({[e]:t}));case`number`:return N(Number(n),{min:t.min,max:t.max,step:t.step},t=>this.setOptions({[e]:t}));case`choice`:return P(t.choices.map(t=>({value:t.value,label:this.label(`${e}.${t.value}`,t.label)})),String(n),t=>this.setOptions({[e]:t}));case`text`:{let t=document.createElement(`input`);return t.type=`text`,t.className=`tcw-indi-input`,t.value=String(n??``),t.addEventListener(`change`,()=>this.setOptions({[e]:t.value})),t}}}levelsEditor(e,t){let n=document.createElement(`div`);n.className=`tcw-levels-editor`;let r=document.createElement(`div`);r.className=`tcw-style-subhead`,r.textContent=this.label(e,t.label),n.appendChild(r);let i=()=>{let t=this.options[e];return Array.isArray(t)?t:[]},a=t=>this.setOptions({[e]:t}),o=document.createElement(`div`);o.className=`tcw-levels-grid`,i().forEach((e,t)=>{let n=document.createElement(`div`);n.className=`tcw-level-row`;let r=document.createElement(`input`);r.type=`checkbox`,r.checked=e.visible;let s=` ${t+1}`;r.setAttribute(`aria-label`,this.t(`drawingSettings.levelVisible`)+s),r.addEventListener(`change`,()=>a(i().map((e,n)=>n===t?{...e,visible:r.checked}:e)));let c=N(e.value,{step:.001},e=>a(i().map((n,r)=>r===t?{...n,value:e}:n)));c.setAttribute(`aria-label`,this.t(`drawingSettings.levelValue`)+s);let l=Yt(e.color??this.style.color,e=>a(i().map((n,r)=>r===t?{...n,color:e}:n)));l.setAttribute(`aria-label`,this.t(`drawingSettings.levelColor`)+s);let u=document.createElement(`button`);u.type=`button`,u.className=`tcw-level-remove`,u.setAttribute(`aria-label`,this.t(`drawingSettings.removeLevel`)+s),u.innerHTML=D(`x`,12),u.addEventListener(`click`,()=>{a(i().filter((e,n)=>n!==t)),this.renderBody()}),n.append(r,c,l,u),o.appendChild(n)}),n.appendChild(o);let s=document.createElement(`button`);return s.type=`button`,s.className=`tcw-reset-link tcw-level-add`,s.textContent=this.t(`drawingSettings.addLevel`),s.disabled=i().length>=Wi,s.addEventListener(`click`,()=>{let e=i().at(-1)?.value??0;a([...i(),{value:Math.round((e+.5)*1e3)/1e3,visible:!0}]),this.renderBody()}),n.appendChild(s),n}renderCoordinates(e){this.anchors.forEach((n,r)=>{let i=document.createElement(`div`);i.className=`tcw-style-subhead`,i.textContent=t.r(this.t(`drawingSettings.point`),{n:r+1}),e.appendChild(i);let a=this.callbacks.toWallTime(n.time),o=document.createElement(`input`);o.type=`date`,o.className=`tcw-indi-input`,o.value=a.date;let s=document.createElement(`input`);s.type=`time`,s.className=`tcw-indi-input`,s.value=a.time;let c=()=>{let e=this.callbacks.fromWallTime(o.value,s.value);e!==null&&this.setAnchor(r,{time:e})};o.addEventListener(`change`,c),s.addEventListener(`change`,c),e.appendChild(M(this.t(`drawingSettings.date`),o)),e.appendChild(M(this.t(`drawingSettings.time`),s)),e.appendChild(M(this.t(`drawingSettings.price`),this.priceInput(n.price,e=>this.setAnchor(r,{price:e}))))})}priceInput(e,t){let n=this.callbacks.roundPrice??(e=>e),r=this.callbacks.priceStep?.(),i=N(n(e),{step:r!==void 0&&r>0?r:`any`},e=>{let r=n(e);i.value=String(r),t(r)});return i}setAnchor(e,t){this.anchors=this.anchors.map((n,r)=>r===e?{...n,...t}:n),this.change({anchors:this.anchors.map(e=>({...e}))})}};function qi(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 Ji=[{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`}],Yi=[{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 Xi(e){return Ji.find(t=>t.id===e)?.mode}function Zi(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function Qi(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function $i(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 ea=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function ta(e,t){let n=[Qi({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 Zi($i(e,t),n,r,[...i,ea(t)])}function na(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},Qi({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=Ji.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}];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 Zi(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],$i({...e,canTrade:!1,canDraw:!1},t),[ea(t)])}function ra(e,t){let n=[Qi({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(Qi({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 Zi(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function ia(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 Zi([Qi({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[ea(t)])}function aa(e,t,n){switch(e){case`priceAxis`:return na(t,n);case`timeAxis`:return ra(t,n);case`pane`:return ia(t,n);default:return ta(t,n)}}var oa=[`positions`,`orders`,`history`],sa=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],ca=[`market`,`limit`,`stop`],la=[`gtc`,`day`];function ua(e,t,n){return e.includes(t??``)?t:n}function da(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function fa(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 pa(e,t=2){return`${e>0?`+`:``}${e.toFixed(t)}`}var ma=class{el;tabButtons=new Map;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 oa){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-account-tab`,t.setAttribute(`role`,`tab`),t.id=`tcw-account-tab-${e}`,t.addEventListener(`click`,()=>this.selectTab(e)),this.tabButtons.set(e,t),a.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-account-new`,E(o,`orderTicket`),o.innerHTML=D(`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=D(`x`,14),s.addEventListener(`click`,()=>this.closePanel()),i.append(a,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,da(t.positions,e.positions)&&da(t.orders,e.orders)&&da(t.fills,e.fills)&&t.realisedPnl===e.realisedPnl){this.open&&this.tab===`positions`&&t.price!==e.price&&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=oa.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=oa[(n+oa.length)%oa.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;n.textContent=`${this.t(`account.${t}`)} (${e[t]})`,n.setAttribute(`aria-selected`,String(r)),n.tabIndex=r?0:-1,r&&this.content.setAttribute(`aria-labelledby`,n.id)}}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?`—`:this.callbacks.formatPrice(e),this.writePnl(t.pnl,fa(t.position,e))}writePnl(e,t){e.className=t===null?``:t.pnl>=0?`tcw-account-up`:`tcw-account-down`,e.textContent=t===null?`—`:`${pa(t.pnl)} (${pa(t.pct)}%)`}table(e,t,n){if(t.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(n),this.content.replaceChildren(e);return}let r=document.createElement(`table`);r.className=`tcw-account-table`;let i=r.createTHead().insertRow();for(let t of e){let e=document.createElement(`th`);e.scope=`col`,e.textContent=t?this.t(t):``,i.appendChild(e)}r.createTBody().append(...t),this.content.replaceChildren(r)}row(e,t=``){let n=document.createElement(`tr`);t&&(n.className=t);for(let t of e){let e=n.insertCell();typeof t==`string`?e.textContent=t:e.appendChild(t)}return n}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=D(n.icon,14),e.addEventListener(`click`,n.run),t.appendChild(e)}return t}renderPositions(){let{formatPrice:e}=this.callbacks,{price:t}=this.snapshot,n=this.snapshot.positions.map(n=>{let r=n.quantity-(n.closedQuantity??0),i=document.createElement(`span`);this.writePnl(i,fa(n,t));let a=`${this.sideText(n.side,`position`)} ${r} @ ${e(n.entryPrice)}`,o=this.row([this.sideCell(n.side),String(r),e(n.entryPrice),t===null?`—`:e(t),i,n.stopLoss===void 0?`—`:e(n.stopLoss),n.takeProfit===void 0?`—`:e(n.takeProfit),this.actions({icon:`repeat`,label:`${this.t(`account.reverse`)}: ${a}`,key:`reverse:${n.id}`,run:()=>this.callbacks.onReversePosition(n.id)},{icon:`x`,label:`${this.t(`account.closePosition`)}: ${a}`,key:`close:${n.id}`,run:()=>this.callbacks.onClosePosition(n.id),danger:!0})]);return this.live.push({position:n,price:o.cells[3],pnl:i}),o});this.table([`account.side`,`account.quantity`,`account.entry`,`account.price`,`account.pnl`,`account.stopLoss`,`account.takeProfit`,`account.actions`],n,`account.noPositions`)}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=ua(ca,t.type===`stopLimit`?`stop`:t.type,`limit`),r=`${this.sideText(t.side,`trade`)} ${t.quantity} @ ${e(t.price)}`;return this.row([this.sideCell(t.side,`trade`),this.t(`ticket.type.${n}`),String(t.quantity),e(t.price),t.stopLoss===void 0?`—`:e(t.stopLoss),t.takeProfit===void 0?`—`:e(t.takeProfit),t.timeInForce?this.t(`ticket.tif.${ua(la,t.timeInForce,`gtc`)}`):`—`,this.actions({icon:`x`,label:`${this.t(`account.cancelOrder`)}: ${r}`,key:`cancel:${t.id}`,run:()=>this.callbacks.onCancelOrder(t.id),danger:!0})])});this.table([`account.side`,`ticket.type`,`account.quantity`,`account.price`,`account.stopLoss`,`account.takeProfit`,`ticket.timeInForce`,`account.actions`],t,`account.noOrders`)}renderHistory(){let{formatPrice:e,formatTime:n}=this.callbacks,r=[...this.snapshot.fills].reverse().map(t=>{let r=document.createElement(`span`);return t.pnl===void 0?r.textContent=`—`:(r.className=t.pnl>=0?`tcw-account-up`:`tcw-account-down`,r.textContent=pa(t.pnl)),this.row([n(t.time),this.sideCell(t.side,`trade`),String(t.quantity),e(t.price),this.t(`account.reason.${ua(sa,t.reason,`order`)}`),r])});this.table([`account.time`,`account.side`,`account.quantity`,`account.price`,`account.reason`,`account.pnl`],r,`account.noFills`);let i=this.snapshot.realisedPnl??this.snapshot.fills.reduce((e,t)=>e+(t.pnl??0),0);if(r.length>0){let e=document.createElement(`p`);e.className=`tcw-account-summary`,e.textContent=t.r(this.t(`account.realised`),{pnl:pa(i)}),this.content.appendChild(e)}}},ha=1e-9;function ga(e,t){return e.type===`market`?t:e.price}function _a(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=ga(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,...va(e,n)]}function va(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)>ha)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+ha||r<o.floor-ha)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function ya(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 ba(e,t){let n=ga(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}var xa=0,Sa=class{backdrop;modal;body;problemsEl;submit;draft=null;lastPrice=null;rules={};returnFocus=null;uid=++xa;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-modal-narrow 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.stopPropagation(),this.close();return}j(e,this.modal)});let a=document.createElement(`div`);a.className=`tcw-modal-header`;let o=document.createElement(`h3`);o.id=`tcw-ticket-title-${this.uid}`,o.textContent=this.t(`ticket.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-modal-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=D(`x`,16),s.addEventListener(`click`,()=>this.close()),a.append(o,s),this.body=document.createElement(`div`),this.body.className=`tcw-modal-body`,this.problemsEl=document.createElement(`div`),this.problemsEl.className=`tcw-ticket-problems`,this.problemsEl.setAttribute(`aria-live`,`polite`);let c=document.createElement(`div`);c.className=`tcw-modal-footer`;let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-reset-link`,l.textContent=this.t(`common.cancel`),l.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`button`,this.submit.className=`tcw-done-btn`,this.submit.addEventListener(`click`,()=>this.place()),c.append(l,this.submit),this.modal.append(a,this.body,this.problemsEl,c),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??{};let t=e.price??e.lastPrice??0,n=e.side??`buy`,r=`market`;e.price!==void 0&&e.lastPrice!==null&&e.price!==e.lastPrice&&(r=e.price<e.lastPrice==(n===`buy`)?`limit`:`stop`);let i=this.rules.lot!==void 0&&this.rules.lot>1?this.rules.lot:1;this.draft={side:n,type:r,quantity:i,price:t,stopLoss:null,takeProfit:null,timeInForce:`gtc`},this.render(),this.backdrop.hidden=!1,this.body.querySelector(`button, input, select`)?.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){!this.draft||e===this.lastPrice||(this.lastPrice=e,this.check())}destroy(){this.close(),this.backdrop.remove()}place(){let e=this.draft;!e||_a(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(ya(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=document.activeElement,n=t instanceof HTMLElement&&this.body.contains(t)?t.dataset.ticketField:void 0;this.body.replaceChildren(this.sideToggle(e.side),M(this.t(`ticket.type`),Ca(`type`,P([`market`,`limit`,`stop`].map(e=>({value:e,label:this.t(`ticket.type.${e}`)})),e.type,e=>this.set({type:e},!0)))),M(this.t(`ticket.quantity`),Ca(`quantity`,this.number(e.quantity,e=>this.set({quantity:e}))))),e.type!==`market`&&this.body.append(M(this.t(`ticket.price`),Ca(`price`,this.number(e.price,e=>this.set({price:e})))),M(this.t(`ticket.timeInForce`),Ca(`timeInForce`,P([`gtc`,`day`].map(e=>({value:e,label:this.t(`ticket.tif.${e}`)})),e.timeInForce,e=>this.set({timeInForce:e})))));let r=e.type===`market`?this.lastPrice??e.price:e.price,i=t=>wa(r*(1+(e.side===`buy`?t:-t)/100),r);this.body.append(this.optionalPrice(`ticket.stopLoss`,e.stopLoss,i(-1),t=>this.set({stopLoss:t},t===null||e.stopLoss===null)),this.optionalPrice(`ticket.takeProfit`,e.takeProfit,i(2),t=>this.set({takeProfit:t},t===null||e.takeProfit===null))),n&&this.body.querySelector(`[data-ticket-field="${n}"]`)?.focus(),this.check()}sideToggle(e){let t=document.createElement(`div`);t.className=`tcw-ticket-side`,t.setAttribute(`role`,`group`);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`,()=>this.set({side:n},!0)),t.appendChild(r)}return t}number(e,t){let n=document.createElement(`input`);return n.type=`number`,n.className=`tcw-indi-input`,n.step=`any`,n.min=`0`,n.value=String(e),n.addEventListener(`input`,()=>t(n.value.trim()===``?NaN:Number(n.value))),n}optionalPrice(e,t,n,r){let i=document.createElement(`div`);i.className=`tcw-settings-row tcw-ticket-optional`;let a=document.createElement(`span`);a.textContent=this.t(e);let o=Jt(t!==null,e=>r(e?n:null));if(o.setAttribute(`aria-label`,this.t(e)),o.dataset.ticketField=`${e}-switch`,i.append(a,o),t!==null){let n=this.number(t,e=>r(Number.isFinite(e)?e:NaN));n.setAttribute(`aria-label`,this.t(e)),n.dataset.ticketField=e,i.appendChild(n)}return i}check(){let e=this.draft;if(!e)return;let n=_a(e,this.lastPrice,this.rules),r=n.map(e=>this.problemText(e)),i=ba(e,this.lastPrice);n.length===0&&i!==null&&r.push(t.r(this.t(`ticket.riskReward`),{rr:i.toFixed(2)})),this.problemsEl.replaceChildren(...r.map(e=>{let t=document.createElement(`p`);return t.textContent=e,t})),this.problemsEl.classList.toggle(`tcw-ticket-bad`,n.length>0),this.submit.disabled=n.length>0,this.submit.classList.toggle(`tcw-ticket-sell`,e.side===`sell`),this.submit.textContent=this.t(e.side===`buy`?`ticket.placeBuy`:`ticket.placeSell`)}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 Ca(e,t){return t.dataset.ticketField=e,t}function wa(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 Ta=0,Ea=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++Ta;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}j(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=D(`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()}}}},Da=0,Oa=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++Da;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-modal-narrow 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`){j(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=D(`x`,16),c.addEventListener(`click`,()=>this.close()),o.append(s,c),this.search=document.createElement(`input`),this.search.type=`search`,this.search.className=`tcw-indi-input tcw-layouts-search`,this.search.placeholder=this.t(`layouts.search`),this.search.setAttribute(`aria-label`,this.t(`layouts.search`)),this.search.addEventListener(`input`,()=>this.render()),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-layouts-list`,this.listEl.setAttribute(`role`,`list`);let l=document.createElement(`div`);l.className=`tcw-modal-body tcw-layouts-body`,l.append(this.search,this.listEl),a.append(o,l),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-tag`,e.textContent=this.t(`layouts.current`),a.appendChild(e)}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=D(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()}}},ka=5,Aa=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 Ea(n,r),this.dialog=new Oa(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,root:r}=this.host,i=[];try{i=(await t.list()).slice(0,ka)}catch{}if(this.destroyed)return;let a=t.current(),o=[{id:`save`,label:n(`layouts.save`),icon:`save`},{id:`saveAs`,label:n(`layouts.saveAs`),icon:`plus`}];a&&o.push({id:`rename`,label:n(`layouts.rename`),icon:`penLine`}),o.push({id:`autoSave`,label:n(`layouts.autoSave`),checked:t.isAutoSave()}),i.length>0&&o.push(`separator`,...i.map(e=>({id:`open:${e.id}`,label:e.name,checked:e.id===a?.id}))),o.push(`separator`,{id:`manage`,label:n(`layouts.open`),icon:`folder`});let s=e.getBoundingClientRect(),c=r.getBoundingClientRect();this.menu.open(o,s.left-c.left,s.bottom-c.top+2,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))},e)}destroy(){this.destroyed=!0,this.menu.destroy(),this.prompt.destroy(),this.dialog.destroy()}},ja=0,Ma=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-${++ja}`,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=Ct(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=Ct(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},Na=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{}}},Pa=[],Fa=null;function Ia(e){let t=()=>{Fa=e};return e.addEventListener(`pointerdown`,t,!0),Pa.push(e),()=>{e.removeEventListener(`pointerdown`,t,!0);let n=Pa.indexOf(e);n>=0&&Pa.splice(n,1),Fa===e&&(Fa=null)}}function J(e,t=!1){let n=Fa?.isConnected?Fa:null;if(!n){let e=document.activeElement;n=e?Pa.find(t=>t.contains(e))??null:null}return!n&&!t&&(n=Pa.find(e=>e.isConnected)??null),n!==null&&e.contains(n)}function Y(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable)}var La=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],Ra=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function za(e){let{theme:t,timestamp:n,...r}=e;return r}function Ba(e){return!Ra(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:La.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:Ra(e.chart)?za(e.chart):null}}function Va(e){try{return JSON.parse(e)}catch{return null}}function Ha(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Ua=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=Ha()){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 Wa(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 Ga(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 Ka=/^(\d{4})-(\d{2})-(\d{2})$/,qa=/^(\d{2}):(\d{2})$/;function Ja(e,t,r){let i=Ka.exec(e),a=t?qa.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 X(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 Ya=class{form=null;returnFocus=null;opener=null;onOutside=e=>{let t=e.target;this.form&&!this.form.contains(t)&&!this.opener?.contains(t)&&this.close()};constructor(e,t,n){this.host=e,this.labels=t,this.onSubmit=n}isOpen(){return this.form!==null}open(e,t=null){this.close(),this.opener=t,this.returnFocus=document.activeElement;let n=document.createElement(`form`);n.className=`tcw-goto`,E(n,`goToDate`),n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-label`,this.labels.title);let r=document.createElement(`div`);r.className=`tcw-goto-title`,r.textContent=this.labels.title;let i=this.field(n,this.labels.date,`date`,e.date);i.required=!0;let a=this.field(n,this.labels.time,`time`,e.time),o=document.createElement(`div`);o.className=`tcw-goto-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-btn`,s.textContent=this.labels.cancel,s.addEventListener(`click`,()=>this.close());let c=document.createElement(`button`);c.type=`submit`,c.className=`tcw-btn tcw-goto-submit`,c.textContent=this.labels.submit,o.append(s,c),n.prepend(r),n.append(o),n.addEventListener(`submit`,e=>{if(e.preventDefault(),!i.value)return;let t={date:i.value,time:a.value};this.close(),this.onSubmit(t)}),n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&this.close()}),this.host.appendChild(n),this.form=n,document.addEventListener(`mousedown`,this.onOutside),i.focus()}close(){if(!this.form)return;document.removeEventListener(`mousedown`,this.onOutside),this.form.remove(),this.form=null;let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}destroy(){this.close()}field(e,t,n,r){let i=document.createElement(`label`);i.className=`tcw-goto-field`;let a=document.createElement(`span`);a.textContent=t;let o=document.createElement(`input`);return o.type=n,o.value=r,o.className=`tcw-goto-input`,i.append(a,o),e.appendChild(i),o}},Z=8,Xa=4,Za=3,Qa=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,$a=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`)&&eo(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(eo(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&to(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`||(eo(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)&&(to(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&&to(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!io(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`&&to(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(Qa);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`&&to(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(!ro(e)){this.hide();return}this.el.textContent=no(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&&(ro(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=ao(e);s===`bottom`&&o+n.height+Z+i>t.height?s=`top`:s===`top`&&o-Z-i<0?s=`bottom`:s===`right`&&a+n.width+Z+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+Z:o-Z-i):(c=s===`right`?a+n.width+Z:a-Z-r,l=o+n.height/2-i/2),c=Math.max(Xa,Math.min(t.width-r-Xa,c)),l=Math.max(Xa,Math.min(t.height-i-Xa,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,Za],bottom:[0,-Za],left:[Za,0],right:[-Za,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 eo(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function to(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function no(e){return e.dataset.tip??e.getAttribute(`title`)??``}function ro(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function io(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function ao(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var oo=2,so=class{stack;toggle;rows=new Map;panes=new Map;collapsed=!1;toggleKey=``;stackKey=``;constructor(e,t,n){this.host=e,this.callbacks=t,this.labels=n,this.stack=document.createElement(`div`),this.stack.className=`tcw-ind-legend`,E(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)}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,a=!1;for(let t of e){i.add(t.instanceId);let e=this.rows.get(t.instanceId)??this.createRow(t.instanceId);this.fill(e,t),t.pane?e.el.parentElement!==this.host&&this.host.appendChild(e.el):e.el.parentElement!==this.stack&&(this.stack.insertBefore(e.el,this.toggle),a=!0),this.place(e,t.pane)}for(let[e,t]of this.rows)i.has(e)||(t.el.remove(),this.rows.delete(e));a&&this.collapsed&&this.setCollapsed(!1),this.renderToggle(e.filter(e=>!e.pane).length)}destroy(){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()}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=D(i,12),Q(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`,E(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,E(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){let t=document.createElement(`div`);t.className=`tcw-ind-legend-row`,E(t,`indicatorLegend`),t.dataset.instance=e;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-ind-legend-name`,n.addEventListener(`click`,()=>this.callbacks.onSettings(e));let r=document.createElement(`span`);r.className=`tcw-ind-legend-values`,E(r,`indicatorLegend.values`);let i=document.createElement(`span`);i.className=`tcw-ind-legend-actions`;let a=(e,t,n,...r)=>{let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-ind-legend-act`,a.dataset.act=e,E(a,...r),a.innerHTML=D(t,13),a.addEventListener(`click`,n),i.appendChild(a),a},o=a(`visible`,`eye`,()=>{this.callbacks.onToggleVisible(e,!u.visible)},`indicatorLegend.visibility`),s=a(`settings`,`settings`,()=>this.callbacks.onSettings(e),`indicatorSettings`,`indicatorLegend.settings`),c=this.callbacks.onMore?a(`more`,`more`,()=>this.callbacks.onMore?.(e,c),`indicatorLegend.more`):null,l=a(`remove`,`x`,()=>this.callbacks.onRemove(e),`indicatorLegend.remove`);t.append(n,r,i);let u={el:t,name:n,values:r,eye:o,settings:s,more:c,remove:l,visible:!0,valuesKey:``,state:``,placeKey:``};return this.rows.set(e,u),u}fill(e,t){let n=`${t.label}|${t.visible}|${!!t.offInterval}`;n!==e.state&&(e.state=n,e.visible=t.visible,e.name.textContent=t.label,e.name.title=this.labels.settings,e.el.classList.toggle(`tcw-ind-legend-row--hidden`,!t.visible||!!t.offInterval),t.offInterval&&this.labels.offInterval?e.el.title=this.labels.offInterval:e.el.removeAttribute(`title`),e.eye.innerHTML=D(t.visible?`eye`:`eyeOff`,13),Q(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),Q(e.settings,this.labels.settings,t.label),e.more&&(Q(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),Q(e.remove,this.labels.remove,t.label));let r=t.values.map(e=>`${e.text}${e.color??``}`).join(``);r!==e.valuesKey&&(e.valuesKey=r,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})))}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>=oo;!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;Q(this.toggle,r,this.collapsed?`(${e})`:void 0),this.toggle.setAttribute(`aria-expanded`,String(!this.collapsed));let i=D(this.collapsed?`chevronDown`:`chevronUp`,12);this.toggle.innerHTML=this.collapsed?`${i}<span>${e}</span>`:i}};function Q(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function co(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 lo=new Map;function uo(e){let t=lo.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),lo.set(e,t)),t}function fo(e,t=`en-US`){return Math.abs(e)>=1e6?uo(t).format(e):(0,n.formatPrice)(e,(0,r.indicatorValuePrecision)(e),t)}var po=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.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=`${D(`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=`${D(`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,this.labelEl.textContent=e===`buy`?this.t(`toolbar.longBracket`):this.t(`toolbar.shortBracket`),this.labelEl.dataset.side=e,this.el.hidden=!1}hide(){this.visible=!1,this.el.hidden=!0}isVisible(){return this.visible}destroy(){this.el.remove()}},mo=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 ho(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}}var go=class{el;bodyEl;callbacks;open=!1;levels;constructor(e,n,r=12,i=t.t){this.t=i,this.callbacks=n,this.levels=r,this.el=document.createElement(`div`),this.el.className=`tcw-ladder`,E(this.el,`depthLadder`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-ladder-header`;let o=document.createElement(`span`);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=D(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a);let c=document.createElement(`div`);c.className=`tcw-ladder-cols`,c.innerHTML=[this.t(`ladder.bid`),this.t(`ladder.price`),this.t(`ladder.ask`)].map(e=>`<span>${k(e)}</span>`).join(``),this.el.appendChild(c),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-ladder-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.callbacks.onToggle?.(!0)}close(){this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1)}setData(e){if(!e){this.renderEmpty();return}this.render(ho(e,this.levels))}destroy(){this.el.remove()}renderEmpty(){this.bodyEl.replaceChildren();let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=this.t(`ladder.empty`),this.bodyEl.appendChild(e)}render(e){if(this.bodyEl.replaceChildren(),e.rows.length===0){this.renderEmpty();return}let n=e.maxVolume>0?1/e.maxVolume:0;for(let r of e.rows){let e=r.askVolume>0,i=document.createElement(`div`);i.className=`tcw-ladder-row`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-ladder-cell tcw-ladder-bid`,r.bidVolume>0?(a.textContent=_o(r.bidVolume),a.style.setProperty(`--w`,`${(r.bidVolume*n*100).toFixed(1)}%`),a.title=t.r(this.t(`ladder.sellAt`),{price:this.callbacks.formatPrice(r.price)}),a.addEventListener(`click`,()=>this.callbacks.onTrade(`sell`,r.price))):a.disabled=!0;let o=document.createElement(`div`);o.className=`tcw-ladder-price ${e?`tcw-ask`:`tcw-bid`}`,o.textContent=this.callbacks.formatPrice(r.price);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-ladder-cell tcw-ladder-ask`,r.askVolume>0?(s.textContent=_o(r.askVolume),s.style.setProperty(`--w`,`${(r.askVolume*n*100).toFixed(1)}%`),s.title=t.r(this.t(`ladder.buyAt`),{price:this.callbacks.formatPrice(r.price)}),s.addEventListener(`click`,()=>this.callbacks.onTrade(`buy`,r.price))):s.disabled=!0,i.appendChild(a),i.appendChild(o),i.appendChild(s),this.bodyEl.appendChild(i)}}};function _o(e){return e>=1e3?(e/1e3).toFixed(1)+`k`:e>=1?e.toFixed(2).replace(/\.00$/,``):e.toPrecision(2)}var vo=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`,E(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=D(`x`,14),o.addEventListener(`click`,()=>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)}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(`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?`+`:``;this.bodyEl.appendChild(this.row(this.t(`dataWindow.change`),`${i}${t(e.change)} (${i}${e.changePct.toFixed(2)}%)`,r)),this.bodyEl.appendChild(this.row(this.t(`dataWindow.volume`),bo(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,yo(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 yo(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 bo(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 xo=globalThis.Buffer;function So(e){if(xo)return xo.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 Co(e){if(xo)return xo.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 wo(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function To(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function Eo(e){return wo(So(JSON.stringify(e)))}function Do(e){if(!e)return null;try{let t=Co(To(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:n.scaleMode??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[]}}catch{return null}}var Oo=`tcw`;function ko(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)===Oo)return decodeURIComponent(e.slice(t+1))}return null}function Ao(e,t){let[n]=e.split(`#`);return`${n}#${Oo}=${t}`}var jo=[[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]],Mo=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`),jo.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)}},No=4e3,Po=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(),No)):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}},Fo=`host:`;function Io(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${Fo}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function Lo(e,t){return e.startsWith(Fo)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var Ro=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),zo={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},Bo={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function Vo(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=zo[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(zo[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=Bo[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[Ro?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function Ho(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 Uo=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 Wo(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return Uo.has(t)}function Go(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 Ko=48,qo=5e4,Jo=100;function Yo(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,Jo);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var Xo=[`#4c8dff`,`#a57cff`,`#1398a8`,`#e25592`,`#8a93a3`,`#62c895`],Zo=4,Qo=7,$o=17,es=3,ts=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`],ns=5e3,rs=()=>{let e=document.activeElement;return e instanceof Element&&e.closest(`[role="dialog"], [aria-modal="true"], [role="menu"]`)!==null},is=229,as=1e3,os=w.filter(e=>n.CHART_STYLE_KEYS[e]!==`color`),ss=()=>typeof document<`u`&&document.hidden,cs=200,ls=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.toolbar?.setFullscreen(document.fullscreenElement===this.root),this.portal.isConnected&&this.overlayHost()};commandPalette=null;symbolSearch=null;hotkeySheet=null;replayBar=null;dragDrop=null;alertsPanel=null;objectTree=null;indicatorSettings=null;indicatorPicker=null;drawingStyle=null;drawingSettings=null;drawingMenu=null;selectionToolbar=null;selectionToolbarFrame=null;chartMenu=null;menuPane=null;canExport=!0;symbolLoads=new Map;ui;legendMenu=null;templates=new Na;templatePrompt=null;chartTemplates=new bi;chartTemplatePrompt=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;legendHoverIndex=null;favoritesStore=new Ua;indicatorFavorites=new Ua(`tcw:indicator-favorites`);indicatorDefaults=new fi;timeframeFavorites=new Ua(`tcw:tf-favorites`);customTimeframes=new Ua(`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 Yn;marketTimer=null;clockTimer=null;onPageShown=null;chartNav=null;visibleBarCount=50;replayPollInterval=null;replaySpeed=5;replayStep=`bar`;replayStartSeq=0;replayStepsCache=null;replayShade=null;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;root;chartContainer;loading;historyPill;connectSeq=0;localSeq=0;lastLocalSwitchMs=0;destroyed=!1;options;symbols;settingsState;settingsDefaults;t;adapter=null;boundGlobalKeydown=null;baseSeries=null;baseTimeframeMs=0;chosenTimeframe=null;rangeSeq=0;rangeQueue=Promise.resolve();compares=[];featureState;hostHotkeys=[];hostMenus=new Set;hostLayer=null;priceAxisAddDefault=!1;constructor(i,a={}){this.options=a,this.symbols=a.symbols??pe;let o=a.chartOptions;if(this.settingsState={...me,...o?.numberLocale?{numberLocale:o.numberLocale}:{},...o?.timeZone==null?{}:{timezone:c(o.timeZone)},...o?.leftPriceScale===void 0?{}:{leftPriceScale:o.leftPriceScale},...o?.highLowLines===void 0?{}:{highLowLines:o.highLowLines},...o?.extendedHours===void 0?{}:{extendedHours:o.extendedHours},...o?.chartTypeOptions?{chartTypeOptions:(0,n.readChartTypeOptions)(o.chartTypeOptions)}:{}},this.t=t.n(t.o(a.locale,a.messages)),this.featureState=Ie(a),a.persistLayouts){let e=a.persistLayouts===!0?{}:a.persistLayouts;this.layoutKeyPrefix=e.keyPrefix??`tcw:layout:`,this.layoutDebounceMs=e.debounceMs??1500}let s=this.resolveIsDark(a.theme),u=this.resolveTheme(a.theme);this.themeOf={...this.themeOf,[s?`dark`:`light`]:u};let d={drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:a.trading!==!1,tradingContextMenu:!1,priceAxisAddButton:this.featureState.alerts||a.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,...a.chartOptions?.features};this.priceAxisAddDefault=d.priceAxisAddButton===!0;let f={...d,priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]};if(this.canExport=d.dataExport!==!1,this.settingsDefaults={...this.settingsState,legendVisible:d.legend!==!1,barCountdown:d.barCountdown!==!1,indicatorValueLabels:d.indicatorValueLabels===!0},this.settingsState={...this.settingsDefaults},this.timeframes=wt(vt(a.timeframes,d.timeframes),this.customTimeframes.list(),d.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let e=yt(this.timeframes,d.defaultTimeframeFavorites,!!a.timeframes?.length);for(let t of e)this.timeframeFavorites.add(t)}let p=a.timeframe??`5m`,m=!d.timeframes?.length||d.timeframes.includes(p)?p:this.timeframes[0]??p;this.state={symbol:a.symbol??this.symbols[0]??`BTCUSDT`,timeframe:m,chartType:a.chartOptions?.chartType??`candlestick`,isDark:s,activeIndicators:new Map,activeTool:null,magnetEnabled:d.drawingMagnet!==!1,magnetStrong:!1,eraser:!1,zoomArea:!1,stayInDrawing:!1,connectionState:a.adapter?`connecting`:`disconnected`,connectionMessage:a.adapter?this.t(`status.connecting`):``},qe(),this.root=document.createElement(`div`),this.root.className=`tcw-root`,this.root.dataset.tcwTheme=s?`dark`:`light`;let h=a.dir===`ltr`||a.dir===`rtl`?a.dir:ps(a.locale)?`rtl`:`ltr`;this.root.dir=h,this.portal.dir=h,i.appendChild(this.root),this.tooltip=new $a(this.root),this.portal.className=`tcw-root tcw-portal`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.stopKeyboardInset=Wa([this.root,this.portal]),this.stopNarrow=Ga(this.root,e=>{this.toolbar?.fit(),e||this.sidebar?.closeOverlay()}),this.ui=W(a.ui);let ee=a.ui!==void 0;G(this.root,this.ui,{variables:ee}),G(this.portal,this.ui,{variables:ee}),this.markSwitchedOff(),this.stopFormControls=ue([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 Rt(this.root,{symbols:this.symbols,timeframes:this.timeframeMenu(),timeframeFavorites:this.pinnedTimeframes(),chartTypes:a.chartTypes?de.filter(e=>a.chartTypes.includes(e.value)):de},{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:a.trading===!1?void 0:()=>this.toggleAccountPanel(),onLayouts:a.layouts===!1?void 0:e=>void this.layoutsUI?.openMenu(e),onBracket:a.trading===!1?void 0:e=>this.startBracket(e),onToggleLadder:a.trading!==!1&&a.depthLadder?()=>this.depthLadder?.toggle():void 0,onOrderTicket:a.trading===!1?void 0:()=>this.openOrderTicket(),onCompare:a.adapter&&d.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 g=document.createElement(`div`);g.className=`tcw-body`,a.drawingFavorites&&this.favoritesStore.seedDefaults(a.drawingFavorites),this.sidebar=new Kt(g,{drawingToolGroups:dt(fe,this.t),favorites:this.favoritesStore.list(),shortcuts:tr()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onToggleMagnet:d.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),onClearDrawings:()=>{this.chart.clearDrawings(),this.state={...this.state,activeTool:null},this.updateUI()},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`,g.appendChild(this.chartContainer),this.loading=new Mo(this.chartContainer,this.t(`status.loading`)),this.historyPill=new Po(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),a.watchlist&&this.createWatchlist(g,a.watchlist===!0?{}:a.watchlist),this.root.appendChild(g);let _=document.createElement(`div`);_.className=`tcw-account-dock`,E(_,`accountPanel`),this.root.appendChild(_),this.chart=new e.c(this.chartContainer,{chartType:this.state.chartType,theme:u,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}}},...a.chartOptions,features:f}),a.chartOptions?.shapes||this.applyChartShapes(),this.applyLegendFont();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 or(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=>this.historyPill.update(e.payload)),this.chart.on(`symbolInfoChange`,e=>{let t=e.payload.info,n=t?[t.description,t.exchange].filter(Boolean).join(` · `):``;this.toolbar?.setSymbolDescription(n||null),this.refreshMarket()}),this.symbolInfoPanel=new Wn(this.root,this.t,{onToggle:e=>{this.toolbar?.setActive(`symbolInfo`,e),e&&(this.refreshSymbolInfo(),this.loadNews())}}),this.marketTimer=setInterval(()=>this.refreshMarket(),3e4),this.onPageShown=()=>{ss()||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(),this.statusBar=new pn(this.root,{presets:r.RANGE_PRESETS,presetLabels:{All:this.t(`range.all`)},groupLabel:this.t(`range.presets`),goToLabel:this.t(`range.goTo`),onPreset:e=>void this.applyRangePreset(e),onGoTo:()=>this.toggleGoToDate()},{clock:{label:this.t(`settings.timezone`),now:()=>this.clockNow(),options:()=>({current:this.settingsState.timezone,list:l(this.settingsState.timezone,Date.now(),this.t(`settings.timezone.local`),this.adapter?.resolveSymbol?{label:this.t(`settings.timezone.exchange`),zone:this.chart.getSymbolInfo()?.timezone??null}:void 0)}),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:d.logScale===!1?void 0:()=>this.toggleScaleMode(`logarithmic`),onAuto:()=>this.changeSettings({autoScale:!this.chart.isAutoScale()})}}),this.clockTimer=setInterval(()=>{!ss()&&this.featureState.statusBar&&this.featureState[`statusBar.clock`]&&this.statusBar?.tick()},as),this.chart.on(`priceRangeChange`,()=>this.refreshScaleSwitches()),this.refreshScaleSwitches(),this.goToDate=new Ya(this.root,{title:this.t(`range.goTo`),date:this.t(`range.date`),time:this.t(`range.time`),submit:this.t(`range.goToSubmit`),cancel:this.t(`range.cancel`)},({date:e,time:t})=>this.goToWallTime(e,t)),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:d.barCountdown,logScale:d.logScale,trading:d.trading!==!1,exchangeZone:this.adapter?.resolveSymbol?()=>this.chart.getSymbolInfo()?.timezone??null:void 0},this.overlayHost),this.symbolSearch=new gn({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t),this.hotkeySheet=new xn({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.setPaneTitlesVisible(!this.featureState.indicatorLegend),this.indicatorLegend=new so(this.chartContainer,{onToggleVisible:(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=>this.handleRemoveIndicator(e),onMore:(e,t)=>this.openLegendMenu(e,t),onPaneAction:(e,t)=>this.runPaneAction(e,t)},{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`)}),this.legendMenu=new A(this.root,this.t(`legend.more`)),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.legendHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.scheduleLegend()}),this.chart.on(`crosshairLeave`,()=>{this.legendHoverIndex=null,this.scheduleLegend()});for(let e of[`indicatorUpdate`,`indicatorChange`,`dataUpdate`,`resize`,`paneResize`,`paneChange`,`themeChange`,`timeframeChange`])this.chart.on(e,()=>this.scheduleLegend());this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let t=e.payload.barIndex;if(typeof t==`number`){if(this.replayBar.getMode()===`select`){this.startReplayAt(t);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(t?.x??null)}),this.dataWindow=new vo(this.root,{formatPrice:e=>this.formatAlertPrice(e)},this.t),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.lastHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())});let v=new Ti,te=new Ei;for(let[e,t]of Object.entries(te.all()))this.chart.setDrawingToolDefaults(e,t??null);this.drawingSettings=new Ki(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}),this.refreshObjects()},toWallTime:e=>X(e*(0,n.barTimeUnit)(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let r=Ja(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(),onAddAlert:e=>this.addDrawingAlert(e),onSaveDefault:(e,n)=>{this.chart.setDrawingToolDefaults(e,n),te.set(e,this.chart.getDrawingToolDefaults(e)),this.say(t.r(this.t(`drawingSettings.defaultSaved`),{name:this.drawingToolName(e)}))},templates:v},this.t),this.chart.on(`drawingDoubleClick`,e=>this.openDrawingSettings(e.payload.id)),this.drawingStyle=new Ai(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},v,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 Ri(this.root,{onStyle:e=>{for(let t of this.chart.getSelectedDrawingIds())this.chart.setSelectedDrawingStyle(e,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(We(aa(t,c,this.t),Me,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=We($i(this.chartMenuContext(i),this.t),Me,this.featureState);this.openChartMenu(a,n,r,{area:`priceAxisAdd`,price:i})}),this.chart.on(`signalMarkerHover`,e=>this.showMarkerTip(e.payload)),this.intervalInput=new Ma(this.chartContainer,{title:this.t(`interval.title`),hint:this.t(`interval.hint`),invalid:this.t(`interval.invalid`)},e=>this.selectTypedTimeframe(e)),a.layouts!==!1&&this.setupLayouts(a.layouts===!0||a.layouts===void 0?{}:a.layouts),a.trading!==!1){this.orderTicket=new Sa(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)},this.t),this.accountPanel=new ma(_,{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}=X(e,this.displayTimezone());return`${t} ${n}`},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())}a.trading!==!1&&(this.bracketBar=new po(this.root,{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)}))}),a.depthLadder&&(this.depthLadder=new go(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),onToggle:e=>this.toolbar?.setActive(`ladder`,e)},void 0,this.t)),this.chart.on(`dataUpdate`,e=>{let t=e.payload;t&&t.bracket===`cancelled`&&this.bracketBar?.hide()})),this.alertsPanel=new hr(this.root,{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}=X(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)}))}),a.alertNotifications&&(this.alertNotifier=new mo(a.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 si(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 ei(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 Mr(this.root,{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()},onAddCompare:d.compareSymbols===!1?void 0:()=>this.handleAddCompare(),onRemoveCompare:e=>this.handleRemoveCompare(e)},this.t);let y=()=>{this.objectTree?.isOpen()&&this.refreshObjects()},b=0;if(this.chart.on(`drawingCreate`,y),this.chart.on(`drawingRemove`,y),this.chart.on(`drawingUpdate`,()=>{b||!this.objectTree?.isOpen()||(b=requestAnimationFrame(()=>{b=0,this.destroyed||y()}))}),this.chart.on(`indicatorAdd`,y),this.chart.on(`indicatorRemove`,y),this.chart.on(`indicatorChange`,y),this.commandPalette=new hn({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),this.boundGlobalKeydown=e=>{if(this.featureState.hotkeys&&this.replayBar?.isMounted()&&this.handleReplayKey(e)||this.handleHostHotkey(e))return;let t=J(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.symbolSearch?.open(this.symbols,this.state.symbol,void 0,this.symbolSearchFn())}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||Y()||!J(this.root,!0))return;e.preventDefault(),this.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&er[e.code]){if(e.defaultPrevented||Y()||!t||rs()||!n(`hotkeys.tools`))return;e.preventDefault(),this.handleDrawingTool(er[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervalInput||!n(`intervalTyping`)||Y()||rs()||!J(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(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`||e.code===`KeyR`)){if(Y()||!t)return;if(e.code===`KeyI`){if(!n(`hotkeys.invertScale`))return;e.preventDefault(),this.changeSettings({invertScale:!this.settingsState.invertScale}),this.settings?.refresh(this.settingsState)}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(Y()||!t||!n(`hotkeys.help`)||!this.featureState.hotkeySheet)return;e.preventDefault(),this.hotkeySheet?.open({isOn:e=>this.sheetKeyOn(e),extra:this.hostHotkeys.map(e=>({keys:e.parsed.display,text:e.spec.label}))})}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=Ia(this.root),a.adapter?(this.adapter=a.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(),a.onReady?.(this.chart),a.shareUrl&&typeof location<`u`){let e=ko(location.hash);e&&this.importState(e)}}setSymbols(e){this.symbols=e;let t=this.watchlistStore;t&&this.watchlistFromSymbols&&t.replace(t.getLists().map(t=>t.id===`default`?{...t,symbols:e}:t))}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}toggleSymbolInfo(e){let t=this.symbolInfoPanel;if(!t)return;let n=e??!t.isOpen();n&&!this.featureState.symbolInfo||(n?t.open():t.close())}refreshMarket(){if(ss())return;let e=(0,n.marketStatus)(this.chart.getSymbolInfo(),Date.now());this.statusBar?.setMarket(e.state,this.t(e.state===`open`?`symbolInfo.open`:`symbolInfo.closed`)),this.refreshSymbolInfo()}refreshSymbolInfo(){let e=this.symbolInfoPanel;!e?.isOpen()||this.destroyed||e.render(this.symbolInfoView())}symbolInfoView(){let e=this.state.symbol;return Jn({symbol:e,info:this.chart.getSymbolInfo(),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?ds():null,r=new Un({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 An(e,{onSelect:e=>{this.setSymbol(e)},onAdd:()=>this.symbolSearch?.open(this.symbols,this.state.symbol,e=>r.add(e),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)},{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.state={...this.state,symbol:e},this.sessionRefPrice=null,this.options.onSymbolChange?.(e),this.updateUI(),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)||ss())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),G(this.root,this.ui),G(this.portal,this.ui),this.applyChartShapes(),this.applyLegendFont()}getUI(){return W({...this.ui})}applyLegendFont(){this.chart.setLegend({fontFamily:this.ui.font.mono,fontSize:V(this.ui.font.size,-1)})}applyChartShapes(){this.chart.setShapes({tagRadius:this.ui.tagRadius})}destroy(){if(!this.destroyed){this.destroyed=!0,this.stopKeyboardInset?.(),this.stopKeyboardInset=null,this.stopNarrow?.(),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.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.intervalInput?.destroy(),this.markerTip?.remove(),this.layoutSession?.destroy(),this.layoutsUI?.destroy(),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.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(),Je()}}handleSymbolClick(){this.featureState.symbolSearch&&this.symbolSearch?.open(this.symbols,this.state.symbol,void 0,this.symbolSearchFn())}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 kt({dayShare:i.slice(-cs).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)&&e.visible);if(this.chart.getDrawingTool()!==null||this.chart.isEraserMode()||this.chart.isZoomAreaMode()||r.length===0){e.hide();return}let i=this.chartOffset(),a=this.chart.getPlotRect(),o=fs(r.map(e=>this.chart.getDrawingRect(e.id)))??{x:a.x+a.width/2,y:a.y,width:0,height:0},s=r[0];e.show({rect:{x:o.x+i.x,y:o.y+i.y,width:o.width,height:o.height},bounds:{x:a.x+i.x,y:a.y+i.y,width:a.width,height:a.height},style:s.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(s.id)})}openDrawingSettings(e){let t=this.chart.getDrawings().find(t=>t.id===e),n=t?this.chart.getDrawingToolDescriptor(t.type):null;!t||!n||!this.drawingSettings||!this.featureState.drawingSettings||this.drawingSettings.open({id:e,type:t.type,name:this.drawingToolName(t.type),style:{...t.style},options:this.chart.getDrawingOptions(e),defs:n.options??{},anchors:t.anchors.map(e=>({...e})),fill:n.fill===!0,text:n.text===!0,alertable:this.chart.canAddDrawingAlert(e)})}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=We(qi({selected:i,canConfigure:this.drawingSettings!==null,canAlert:this.chart.canAddDrawingAlert(e)},this.t),Ne,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=Io(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=>{Lo(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:r.scaleMode,canLog:i.logScale!==!1,inverted:this.chart.isInvertScale(),leftScale:r.leftPriceScale,labels:{values:r.indicatorValueLabels,...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(Yi.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)}timezoneChoices(){let e=this.adapter?.resolveSymbol?{label:this.t(`settings.timezone.exchange`),zone:this.chart.getSymbolInfo()?.timezone??null}:void 0;return l(this.settingsState.timezone,Date.now(),this.t(`settings.timezone.local`),e).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=Io(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=>{Lo(e,i)||(e.startsWith(`tz:`)?this.changeSettings({timezone:e.slice(3)}):this.runChartMenuAction(e,r))})}setFeatures(e){let t=this.featureState;this.featureState={...t,...Fe(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.alertsPanel?.close()],[`objectTree`,()=>this.objectTree?.close()],[`symbolInfo`,()=>this.symbolInfoPanel?.close()],[`dataWindow`,()=>this.dataWindow?.close()],[`accountPanel`,()=>this.toggleAccountPanel(!1)],[`orderTicket`,()=>this.orderTicket?.close()],[`depthLadder`,()=>this.depthLadder?.close()],[`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()],[`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=Vo(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;Wo(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===is||e.getModifierState?.(`AltGraph`)||e.defaultPrevented||Y()||Go(e)||rs())return!1;let t=this.hostHotkeys.find(t=>Ho(e,t.parsed));if(!t)return!1;let n=!t.parsed.ctrl&&!t.parsed.alt;if(!J(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(os.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;default:return!0}}markSwitchedOff(){let e=Le(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()}addToolbarButton(e){if(!this.toolbar)return null;let t=this.toolbar,n=t.addHostButton(e);return t.tidy(),{element:n,setActive:t=>zt(n,t,e.toggle===!0),setText:t=>Bt(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:t=>{if(n.isOpen()){n.close();return}let r=e.items();if(r.length===0)return;let i=t.getBoundingClientRect(),a=this.root.getBoundingClientRect();n.open(Io([],r),i.left-a.left,i.bottom-a.top+2,e=>Lo(e,r),t)}});return r.setAttribute(`aria-haspopup`,`menu`),r.setAttribute(`aria-expanded`,`false`),t.tidy(),{element:r,setText:t=>Bt(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=>zt(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=Xi(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`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()})}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}:{}}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}=X(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=s(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();e.length!==0&&this.goToDate.open(X(e[e.length-1].time*(0,n.barTimeUnit)(e),this.displayTimezone()),this.root.querySelector(`[data-role="goto"]`))}goToWallTime(e,t){let r=Ja(e,t,this.displayTimezone()),i=this.chart.getData();if(r===null||i.length===0)return;let a=r/(0,n.barTimeUnit)(i);this.chart.goToTime(a),a<i[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:ht(e),custom:this.customTimeframes.has(e)}))}handleAddTimeframe(e){if(!this.featureState.customTimeframes)return!1;let t=Ct(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=wt(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}=X(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=wt(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 Ea(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>=Ko||this.baseSeries.length>=qo;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await Yo(),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.options.weekStartsOn??1;this.chart.setData(i(this.baseSeries,this.state.timeframe,{weekStartsOn:e}))}else this.chart.setData(this.baseSeries);this.lastLocalSwitchMs=performance.now()-e}handleDataUpdate(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.length==`number`){t.length>0&&this.loading.isActive()&&(this.loading.end(),this.state.connectionState===`error`&&this.setConnectionState(`connected`,this.t(`status.live`)));return}if(t.error!==void 0){this.loading.isActive()&&(this.loading.fail(this.t(`status.connectionFailed`)),this.setConnectionState(`error`,t.error||this.t(`status.connectionFailed`)));return}switch(t.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()}toggleAlerts(){!this.alertsPanel||!this.featureState.alerts||(this.alertsPanel.toggle(),this.alertsPanel.isOpen()&&this.refreshAlerts())}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}));return Eo({v:1,symbol:this.state.symbol,timeframe:this.state.timeframe,chartType:this.state.chartType,scaleMode:this.chart.getScaleMode(),indicators:e,drawings:this.chart.getDrawings()})}async importState(e){let t=Do(e);return t?(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),this.chart.setScaleMode(t.scaleMode),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):!1}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=Ao(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)}buildDataWindowModel(){let e=this.chart.getData(),t=this.lastHoverIndex;if(t===null||t<0||t>=e.length)return{ohlc:null,change:0,changePct:0,indicators:[]};let n=e[t],r=t>0?e[t-1].close:n.open,i=n.close-r,a=r===0?0:i/r*100,o=this.chart.getActiveIndicators().map(e=>{let n=this.chart.getIndicatorOutput(e.instanceId)?.series?.[t]??null,r=e.descriptor.plots?.map(e=>[e.key,e.title])??Object.keys(n??{}).map(e=>[e,e]),i=n?r.filter(([e])=>typeof n[e]==`number`&&Number.isFinite(n[e])).map(([e,t])=>({key:t,value:n[e]})):[];return{name:e.descriptor.name,values:i}}).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,changePct:a,indicators:o}}toggleDataWindow(){!this.dataWindow||!this.featureState.dataWindow||(this.dataWindow.toggle(),this.dataWindow.isOpen()&&this.dataWindow.render(this.buildDataWindowModel()))}toggleObjects(){!this.objectTree||!this.featureState.objectTree||(this.objectTree.toggle(),this.objectTree.isOpen()&&this.refreshObjects())}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:us(e,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:e.descriptor.name,visible:e.visible})),t=this.chart.getDrawings().map(e=>({id:e.id,label:Pr(e.type,this.t),visible:e.visible,locked:e.locked,group:e.group})),n=this.compares.map(e=>({id:e.id,label:e.symbol,color:e.color}));this.objectTree.setObjects(e,t,n)}async handleAddCompare(){if(!this.featureState.compare)return;if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}let e=new Set([this.state.symbol,...this.compares.map(e=>e.symbol)]),t=this.symbols.filter(t=>!e.has(t));this.symbolSearch?.open(t.length?t:this.symbols,this.state.symbol,e=>{this.pickCompareWay(e)},this.symbolSearchFn())}pickCompareWay(e){let n=this.state.symbol,r=[{id:`percent`,label:this.t(`compare.percent`)},{id:`scale`,label:this.t(`compare.ownScale`)},{id:`pane`,label:this.t(`compare.ownPane`)},{id:`spread`,label:t.r(this.t(`compare.spread`),{main:n,other:e})},{id:`ratio`,label:t.r(this.t(`compare.ratio`),{main:n,other:e})},{id:`correlation`,label:t.r(this.t(`compare.correlation`),{main:n,other:e})},{id:`correlationLog`,label:t.r(this.t(`compare.correlationLog`),{main:n,other:e})}],i=this.chart.getPlotRect();this.chartMenu?.open(r,i.x+24,i.y+24,t=>void this.addCompareSymbol(e,t))}async addCompareSymbol(e,n=`percent`){if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}if(n!==`percent`){let t=n===`scale`?this.chart.addIndicator(`compareSymbol`,{symbol:e},`bottom`,{scale:`left`}):n===`pane`?this.chart.addIndicator(`compareSymbol`,{symbol:e}):n===`correlation`?this.chart.addIndicator(`correlation`,{symbol:e}):n===`correlationLog`?this.chart.addIndicator(`correlationlog`,{symbol:e}):this.chart.addIndicator(`spread`,{symbol:e,mode:n});t&&n===`pane`&&this.chart.moveIndicatorToPane(t,`new`);return}if(this.compares.some(t=>t.symbol===e))return;let i=Xo[this.compares.length%Xo.length],a=`cmp_${e}`;try{let n=await(0,r.withResampling)(this.adapter).fetchHistory(e,this.state.timeframe,this.options.historyLimit??500);this.compares.length===0&&this.chart.setCompareMode(`percent`),this.chart.addCompareSymbol(a,e,n,i),this.compares=[...this.compares,{id:a,symbol:e,color:i}],this.refreshObjects(),this.say(t.r(this.t(`toast.comparing`),{symbol:e}))}catch(t){this.say(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}}handleRemoveCompare(e){this.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.refreshObjects()}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=Math.max(this.chart.getData().length,this.options.historyLimit??500),a=await(0,r.withResampling)(this.adapter).fetchHistory(e,t,n);if(i())return;this.chart.setSymbolSeries(e,a)}catch(t){if(i())return;this.chart.setSymbolSeries(e,this.chart.getSymbolSeries(e)),this.say(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}}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);for(let e of this.compares)try{let t=await(0,r.withResampling)(this.adapter).fetchHistory(e.symbol,this.state.timeframe,this.options.historyLimit??500);this.chart.updateCompareData(e.id,t)}catch{}}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)))}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 sr(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=this.chart.getIndicatorOutput(r)?.series?.[t.length-1]?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}formatAlertPrice(e){let t=this.chart.getPriceFormatter?.();if(t)return t(e);let n=Math.abs(e),r=n>=1e3?2:n>=1?4:6,i=this.settingsState.numberLocale||void 0;return e.toLocaleString(i,{minimumFractionDigits:2,maximumFractionDigits:r})}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.settingsState,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 de)e.push({id:t.value,label:ut(t,this.t),category:`chartType`,active:this.state.chartType===t.value});for(let t of dt(fe,this.t))for(let n of t.tools)e.push({id:n.value,label:n.label,category:`drawing`,active:this.state.activeTool===n.value});for(let t of this.timeframes)e.push({id:t,label:ht(t),category:`timeframe`,active:this.state.timeframe===t});return e.push({id:`screenshot`,label:this.t(`action.screenshot`),category:`action`,shortcut:``},{id:`copyImage`,label:this.t(`action.copyImage`),category:`action`},{id:`toggleTheme`,label:this.t(`action.toggleTheme`),category:`action`},{id:`settings`,label:this.t(`action.settings`),category:`action`},{id:`shareView`,label:this.t(`action.shareView`),category:`action`},{id:`autoFib`,label:this.t(`action.autoFib`),category:`action`},{id:`dataWindow`,label:this.t(`action.dataWindow`),category:`action`},{id:`symbolInfo`,label:this.t(`action.symbolInfo`),category:`action`},{id:`clearDrawings`,label:this.t(`action.clearDrawings`),category:`action`}),e.filter(e=>e.category!==`action`||this.commandOn(e.id))}commandOn(e){let t=He(e);return t===void 0||this.featureState[t]}handleAction(e){if(this.commandOn(e))switch(e){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.chart.clearDrawings(),this.state={...this.state,activeTool:null},this.updateUI();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.settingsState={...this.settingsState,chartTypeOptions:this.chart.getChartTypeOptions?.()??{},autoScale:this.chart.isAutoScale?.()??this.settingsState.autoScale},this.settingsEdit={settings:{...this.settingsState},style:this.settingsStyle(),keys:new Set,styleKeys:new Set},this.settings?.open(this.settingsState,this.state.chartType,e))}resetView(){this.chart.fitContent(),this.changeSettings({autoScale:!0}),this.settings?.refresh(this.settingsState)}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;if(!e){this.restoreSettings(a,o);return}let s=r(this.settingsState),c=i.length>0?this.settingsStyle(i):null;JSON.stringify([a,o])!==JSON.stringify([s,c])&&this.chart.recordUndo({undo:()=>this.restoreSettings(a,o),redo:()=>this.restoreSettings(s,c)})}touchSettings(e,t=[]){if(this.settingsEdit){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);n&&(this.touchSettings(Object.keys(n.settings),w),this.applySettings(n.settings),this.chart.resetOverrides([...w],{layer:`user`}),this.chart.applyOverrides(n.style,{layer:`user`}),this.settings?.refresh(this.settingsState),this.say(t.r(this.t(`templates.applied`),{name:e})))}promptSaveChartTemplate(){this.chartTemplatePrompt??=new Ea(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?D(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.chart.saveState(),t=e?Va(e):null,n=t&&typeof t==`object`?za(t):null;return{v:1,symbol:this.state.symbol,timeframe:this.chosenTimeframe??this.state.timeframe,scaleMode:this.settingsState.scaleMode,invertScale:this.settingsState.invertScale,chart:n}}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){if(e.chart){this.chart.loadState(JSON.stringify(za(e.chart)));let t=e.chart.chartType;typeof t==`string`&&(this.state={...this.state,chartType:t})}this.applySettings({scaleMode:e.scaleMode,invertScale:e.invertScale}),this.syncIndicatorsFromChart(),this.updateUI(),this.settings?.refresh(this.settingsState,this.state.chartType)}}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=Ba(Va(e));return t?(await this.restoreLayout(t),!0):!1}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 Aa(n,{root:this.root,t:this.t,toast:(e,t)=>this.say(e,t),formatTime:e=>{let{date:t,time:n}=X(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 t=new Map;for(let n of this.chart.getActiveIndicators())t.set(n.instanceId,{id:n.id,label:e.C(n.id,n.params,n.descriptor.defaultConfig,n.descriptor.shortName)});this.state={...this.state,activeIndicators:t},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 wn({onPlay:()=>{if(this.replayBar?.getMode()===`select`){this.startReplayAt(Math.max(1,this.replayTotal()-100),!0);return}this.chart.getReplayState()===`paused`&&this.chart.replayResume(),this.replayBar?.setState(`playing`)},onPause:()=>{this.chart.replayPause(),this.replayBar?.setState(`paused`)},onStepBack:()=>this.stepReplay(-1),onStepForward:()=>this.stepReplay(1),onSeek:e=>{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:()=>{let e=this.replayTotal(),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)))},onClose:()=>this.exitReplay(),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`),random:e(`replay.random`),realtime:e(`replay.realtime`),barsPerSecond:e(`replay.barsPerSecond`),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`)});let t=[{value:`bar`,label:e(`replay.step.bar`)},...this.replayStepOptions().map(e=>({value:e,label:e}))];t.some(e=>e.value===this.replayStep)||(this.replayStep=`bar`),this.replayBar.mount(this.chartContainer,{total:this.replayTotal(),speed:this.replaySpeed,mode:`select`,steps:t,step:this.replayStep}),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)}hideReplayShade=()=>this.positionReplayShade(null);replayFrom(e,t=!1){this.featureState.replay&&(this.replayBar?.isMounted()||this.enterReplay(),this.startReplayAt(e,t))}startReplayAt(e,t=!1){let n=this.replayBar;if(!n)return;let r=this.replayTotal(),i=Math.max(0,Math.min(Number.isFinite(e)?Math.floor(e):0,r-1));this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade),n.setMode(`replay`);let a=++this.replayStartSeq,o=e=>{this.destroyed||this.replayBar!==n||!n.isMounted()||a!==this.replayStartSeq||(this.chart.replayStart({speed:this.replaySpeed,interval:1e3,startIndex:i,paused:!0,revealMarks:this.options.replayRevealMarks!==!1,...e?{steps:e}:{}}),t&&this.chart.replayResume(),n.setState(t?`playing`:`paused`),this.syncReplayBar(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayPollInterval=setInterval(()=>this.syncReplayBar(),150))};if(this.replayStep===`bar`){o(null);return}this.replayStepsFor(this.replayStep).then(e=>{a===this.replayStartSeq&&(e||this.say(this.t(`replay.stepsFailed`),`error`),o(e))})}replayStepOptions(){let e=(0,n.timeframeToMs)(this.state.timeframe);return ts.filter(t=>{let i=(0,n.timeframeToMs)(t);return!(i<e)||e%i!==0?!1:this.adapter?(0,r.servesTimeframe)(this.adapter,t):this.baseSeries!==null&&this.baseTimeframeMs>0&&i>=this.baseTimeframeMs&&i%this.baseTimeframeMs===0})}async replayStepsFor(e){let t=`${this.state.symbol}|${this.state.timeframe}|${e}`;if(this.replayStepsCache?.key===t)return this.replayStepsCache.steps;let a=null;if(this.adapter){let t=Math.max(1,Math.round((0,n.timeframeToMs)(this.state.timeframe)/(0,n.timeframeToMs)(e))),i=Math.min(ns,Math.max(this.chart.getData().length,100)*t);try{a=await(0,r.withResampling)(this.adapter).fetchHistory(this.state.symbol,e,i)}catch{a=null}}else this.baseSeries&&(a=(0,n.timeframeToMs)(e)===this.baseTimeframeMs?this.baseSeries:i(this.baseSeries,e));return!a||a.length===0?null:(this.replayStepsCache={key:t,steps:a},a)}replayTotal(){return this.chart.isReplayActive()?this.chart.getReplayProgress().total:this.chart.getData().length}syncReplayBar(){let e=this.replayBar;if(!e?.isMounted()||e.getMode()!==`replay`)return;if(!this.chart.isReplayActive()){this.teardownReplayUi();return}let t=this.chart.getReplayProgress(),n=this.chart.getReplayState();e.setProgress(t.current,t.total),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`)return;let t=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(Math.max(0,Math.min(t.total-1,t.current+e))),this.replayBar.setState(`paused`),this.syncReplayBar()}handleReplayKey(e){if(e.defaultPrevented)return!1;let t=document.activeElement;return t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable)?!1:e.shiftKey&&(e.key===`ArrowRight`||e.key===`ArrowLeft`)&&this.replayBar?.getMode()===`replay`?(e.preventDefault(),e.stopPropagation(),this.stepReplay(e.key===`ArrowRight`?1:-1),!0):e.key===`Escape`&&this.replayBar?.getMode()===`select`?(this.exitReplay(),!0):!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.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade),this.replayBar?.unmount(),this.replayBar=null}applySettings(e){this.settingsState={...this.settingsState,...e},(e.scaleMode!==void 0||e.logScale!==void 0||e.invertScale!==void 0)&&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.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),(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.chart.setLogScale(e.logScale),this.settingsState={...this.settingsState,scaleMode:e.logScale?`logarithmic`:`regular`}):(this.chart.setScaleMode(e.scaleMode),this.settingsState={...this.settingsState,logScale:e.scaleMode===`logarithmic`}),e.numberLocale!==void 0&&(this.chart.setNumberLocale(e.numberLocale),this.watchlist?.setLocale(e.numberLocale||void 0)),e.timezone!==void 0&&this.chart.setTimezone(s(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({renko:{},lineBreak:{},kagi:{},pointAndFigure:{},rangeBars:{},...e.chartTypeOptions})}resetSettings(){let e={...this.settingsState},t=this.settingsStyle(),n={...this.settingsDefaults};this.touchSettings(Object.keys(n),w),this.applySettings(n),this.chart.resetOverrides([...w],{layer:`user`});let r={...this.settingsState},i=this.settingsStyle();this.settings?.refresh(this.settingsState),!(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();this.applySettings(e);let i=n();this.settingsEdit||JSON.stringify(r)===JSON.stringify(i)||this.chart.recordUndo({subject:`settings:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings(r),redo:()=>this.restoreSettings(i)})}settingsStyle(e=w){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){this.applySettings(e),t&&t.theme===(this.chart.getTheme()?.name??``)&&this.chart.applyOverrides(t.overrides,{layer:`user`}),this.settings?.refresh(this.settingsState)}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 t=this.chart.getData().length-1,n=this.chart.isTimeAligned()?this.legendHoverIndex:null,r=n===null?t:Math.min(Math.max(n,0),t),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=this.chart.getActiveIndicators().map(t=>{let n=i.get(t.instanceId)??null,o=r>=0?this.chart.getIndicatorOutput(t.instanceId)?.series?.[r]:null,s=this.chart.getIndicatorStyle(t.instanceId),c=t.visible&&t.shown===!1,l=c?[]:co(t.descriptor,o,s?.colors??[],s?.plots);return{instanceId:t.instanceId,label:e.C(t.id,t.params,t.descriptor.defaultConfig,t.descriptor.shortName),visible:t.visible,offInterval:c,values:l.map(e=>({text:n?fo(e.value,a):this.chart.formatPrice(e.value),color:e.color})),pane:n?{x:n.x+Zo,y:n.y+Math.min(Qo+n.row*$o,Math.max(Qo,n.height-$o)),width:n.width-2*Zo}:null}}),s=this.chart.getPlotRect(),c=this.chart.getMaximizedPane(),l=e=>o.find(t=>t.instanceId===e)?.label??``,u=this.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-Zo,y:e.rect.y+es,label:l(e.instanceId),collapsed:this.chart.isPaneCollapsed(e.instanceId),maximized:c===e.instanceId,canMoveUp:this.chart.canMovePane(e.instanceId,-1),canMoveDown:this.chart.canMovePane(e.instanceId,1)}));this.indicatorLegend.update(o,{left:s.x+Zo,top:this.chart.getLegendBottom()+1},u)}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=Io(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=>{Lo(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 us(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([t]);for(let e=!0;e;){e=!1;for(let t of i){let n=a(t);n&&o.has(n)&&!o.has(t.instanceId)&&(o.add(t.instanceId),e=!0)}}let s=[];for(let t of i){if(o.has(t.instanceId))continue;let r=e.C(t.id,t.params,t.descriptor.defaultConfig,t.descriptor.shortName);for(let e of t.descriptor.plots??[])s.push({value:(0,n.indicatorSource)(t.instanceId,e.key),label:`${r}: ${e.title}`})}return s}function ds(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}function fs(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 ps(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}var ms={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},hs=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],$={"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 gs(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call($,e)}function _s(e){return JSON.parse(JSON.stringify(e))}function vs(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 ys(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!gs(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map(Ba);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...ms};for(let e of hs)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 bs=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||Y()||!J(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,n={}){this.options=n,this.layout=gs(n.layout)?n.layout:`1x2`,this.sync={...ms,...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`,G(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=Ga(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=Ia(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||!gs(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);G(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=Fe(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=ys(Va(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(),Je()}}shapeCount(){let{cols:e,rows:t}=$[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=$[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 ls(n,{...r,...i,...a&&this.sync.symbol?{symbol:a.getSymbol()}:{},...a&&this.sync.interval?{timeframe:a.getTimeframe()}:{},...this.options.adapter&&!i.adapter?{adapter:this.options.adapter(e)}:{},...this.uiTheme?{ui:this.uiTheme}:{},layouts:!1,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)return;let{until:n}=t.payload;this.relay(e,e=>{let t=e.getChart();if(t.isReplayActive()){t.replaySeekToTime(n);return}let r=xs(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()),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(_s(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(_s(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(gs)??Object.keys($);for(let e of r){let{cols:r,rows:i}=$[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=vs(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=`${D(`link`,13)}<span>${k(this.t(`grid.sync`))}</span>`,i.appendChild(a);for(let e of hs){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=`${D(`save`,14)}<span class="tcw-layouts-label">${k(t)}</span>`+(n?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+D(`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 Aa(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=X(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 xs(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=ls,exports.ChartWidgetGrid=bs,exports.DEFAULT_GRID_SYNC=ms,Object.defineProperty(exports,`DRAWING_TOOL_ICONS`,{enumerable:!0,get:function(){return n.DRAWING_TOOL_ICONS}}),exports.EN_MESSAGES=t.c,exports.GRID_SHAPES=$,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=T,exports.WIDGET_UI_PRESETS=wr,exports.applyWidgetUI=G,exports.cleanLayoutName=e.r,exports.createChartTypeIcon=Xe,exports.createIcon=D,exports.createToolIcon=O,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=ys,exports.readWatchlists=Vn,exports.readWidgetLayout=Ba,exports.registerWidgetLocale=t.a,exports.resolveWidgetUI=W,exports.widgetUIVariables=jr;
6042
+ ${this.steps.length>1?`<select class="tcw-replay-speed tcw-replay-step" data-act="step" aria-label="${O(e.step)}" title="${O(e.step)}">${this.steps.map(e=>`<option value="${O(e.value)}"${e.value===this.step?` selected`:``}>${O(e.label)}</option>`).join(``)}</select>`:``}
6043
+ <button class="tcw-replay-text-btn tcw-replay-realtime" data-act="realtime">${O(e.realtime)}</button>
6044
+ `}wireEvents(){let e=this.root;e&&(this.scrubber=e.querySelector(`input[data-act="seek"]`),this.progressLabel=e.querySelector(`[data-tcw="progress"]`),this.playBtn=e.querySelector(`button[data-act="play"]`),this.realtimeBtn=e.querySelector(`button[data-act="realtime"]`),this.realtimeBtn?.addEventListener(`click`,()=>this.callbacks.onClose()),e.querySelector(`[data-act="random"]`)?.addEventListener(`click`,()=>this.callbacks.onRandomStart()),e.querySelector(`[data-act="stepBack"]`)?.addEventListener(`click`,()=>this.callbacks.onStepBack()),e.querySelector(`[data-act="stepForward"]`)?.addEventListener(`click`,()=>this.callbacks.onStepForward()),this.playBtn?.addEventListener(`click`,()=>{this.state===`playing`?this.callbacks.onPause():this.callbacks.onPlay()}),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.speed=t,this.callbacks.onSpeedChange(t)}),e.querySelector(`[data-act="step"]`)?.addEventListener(`change`,e=>{this.step=e.target.value,this.callbacks.onStepChange?.(this.step)}))}syncUi(){let e=this.root;if(e){for(let t of e.querySelectorAll(`.tcw-replay-group`))t.hidden=t.dataset.mode!==this.mode;if(e.classList.toggle(`tcw-replay-bar--ended`,this.ended),this.playBtn){let e=this.state===`playing`;this.playBtn.innerHTML=e?Dn():En(),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}}}},En=()=>D(`play`,14),Dn=()=>D(`pause`,14),On=()=>D(`stepBack`,14),kn=()=>D(`stepForward`,14),An=()=>D(`cursor`,14),jn=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.textContent=`+`,r.title=n.add,r.setAttribute(`aria-label`,n.add),r.hidden=!t.onAdd,r.addEventListener(`click`,()=>t.onAdd?.()),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,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)}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()}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=Mn(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){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-remove`,r.innerHTML=D(`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=Nn(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&&Pn(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 Mn(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 Nn(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 Pn(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 Fn=50,In=500,Ln=60,Rn=64,zn=e=>typeof e==`string`&&e.trim().slice(0,Ln)||null,Bn=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t&&t.length<=Rn?t:null};function Vn(e){let t=[];for(let n of e){let e=Bn(n);if(e&&!t.includes(e)&&t.push(e),t.length===In)break}return t}function Hn(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===Fn)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=Rn?t.id:null,i=zn(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?Vn(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 Un=e=>({...e,symbols:[...e.symbols]}),Wn=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?Hn({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:zn(e.defaultName)??`Watchlist`,symbols:Vn(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map(Un)}getActive(){return Un(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=Hn({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=zn(e);if(!t||this.lists.length>=Fn)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(),Un(r)}rename(e,t){let n=zn(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=Bn(e),r=this.lists.find(e=>e.id===t);return!n||!r||r.symbols.includes(n)||r.symbols.length>=In?!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?Hn(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{}}},Gn=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`,E(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=D(`x`,14),o.addEventListener(`click`,()=>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)}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(B(`div`,`tcw-syminfo-symbol`,e.symbol)),e.description&&t.append(B(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(B(`div`,`tcw-syminfo-meta`,e.meta));let n=document.createElement(`div`);if(n.className=`tcw-syminfo-quote`,e.price&&n.append(B(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=B(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),n.append(t)}let r=B(`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(B(`dt`,``,t.label),B(`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=B(`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(B(`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(B(`span`,``,t.title));t.meta&&e.append(B(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function B(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var Kn=10,qn=5*6e4,Jn=864e5;function Yn(e){let{info:r,quote:i,t:a,textLocale:o}=e,s=Zn(e.bars,r?.timezone),c=e.formatPrice,l=i?.last??s?.close,u=i?.prevClose??s?.prevClose,d=i?.change??(l!==void 0&&u!==void 0?l-u:void 0),f=l!==void 0&&d!==void 0?l-d:void 0,p=i?.changePercent??(d!==void 0&&f?d/f*100:void 0),m=(0,n.marketStatus)(r,e.now),h=a(m.state===`open`?`symbolInfo.open`:m.state===`closed`?`symbolInfo.closed`:`symbolInfo.always`);if(m.state!==`always`&&m.next!==null){let n=Qn(m.next-e.now,o);h+=` · ${t.r(a(m.state===`open`?`symbolInfo.closesIn`:`symbolInfo.opensIn`),{when:n})}`}let ee=[],g=(e,t)=>{t&&ee.push({label:e,value:t})},_=e=>e===void 0?void 0:c(e);g(a(`dataWindow.open`),_(i?.open??s?.open)),g(a(`dataWindow.high`),_(i?.high??s?.high)),g(a(`dataWindow.low`),_(i?.low??s?.low)),g(a(`symbolInfo.prevClose`),_(u));let v=i?.volume??s?.volume;g(a(`dataWindow.volume`),v===void 0?void 0:$n(v,e.numberLocale)),g(a(`symbolInfo.bid`),_(i?.bid)),g(a(`symbolInfo.ask`),_(i?.ask)),g(a(`symbolInfo.tick`),r?.minTick===void 0?void 0:String(r.minTick)),g(a(`symbolInfo.currency`),r?.currency),g(a(`symbolInfo.timezone`),r?.timezone),g(a(`symbolInfo.hours`),er(r,o));let te=(d??0)>=0?`+`:`-`;return{symbol:e.symbol,description:r?.description,meta:[r?.exchange,r?.type].filter(Boolean).join(` · `)||void 0,price:l===void 0?void 0:c(l),change:d===void 0?void 0:{text:`${te}${c(Math.abs(d))}${p===void 0?``:` (${te}${Math.abs(p).toFixed(2)}%)`}`,up:d>=0},status:{state:m.state,text:h},stats:ee}}var Xn=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,Qn(e.time-t,i)].filter(Boolean).join(` · `)}))})},c=this.cache.get(e);if(c&&Date.now()-c.at<qn){s(c.items);return}r({kind:`loading`}),Promise.resolve().then(()=>t(e,Kn)).then(t=>{if(o!==this.request||a())return;let r=(0,n.readNews)(t,Kn);this.cache.set(e,{at:Date.now(),items:r}),s(r)}).catch(()=>{o===this.request&&!a()&&r({kind:`failed`})})}};function Zn(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))/Jn)},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 Qn(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 $n(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function er(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 tr={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`};function nr(){let e={};for(let[t,n]of Object.entries(tr))e[n]=`Alt+${t.replace(/^Key/,``)}`;return e}var rr=300,ir=80,ar=n.PHI**-3,or=80,sr=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`,E(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,E(i,a),i.title=r,i.setAttribute(`aria-label`,r),i.innerHTML=D(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(or,t.height*ar);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),ir)},rr)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function cr(e,n,r,i=!1){let a=e.label??n(`alerts.source.price`),o=pr.get(e.condition),s=o?n(o):e.condition;if(ur.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?hr(e.price):r(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:i?`${a} `:``}${s} ${l}`}var lr=[{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`}],ur=[`movesUp`,`movesDown`],dr={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},fr=``,pr=new Map(lr.map(e=>[e.value,e.key]));function mr(e){return Math.round(e*1e6)/1e6}function hr(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var gr=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`,E(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=D(`x`,14),s.addEventListener(`click`,()=>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 lr){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=`${D(`plus`,14)}<span>${O(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=ur.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==fr}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=fr,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:fr,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()}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(mr(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(ur.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!==fr)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=dr[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 cr(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=D(`trash`,14),o.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),n.appendChild(r),n.appendChild(o),this.listEl.appendChild(n)}}},_r=`print`,vr=3,yr=10;function V(e,t){return Math.max(yr,(0,n.phiStep)(e,t,vr))}var br=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,xr=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,Sr={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:`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`,mono:`'Cascadia Mono', 'SF Mono', ui-monospace, Menlo, Consolas, monospace`,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', ${br}`,mono:xr,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', ${br}`,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', ${br}`,mono:xr,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}},Cr={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 wr(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 Tr=Object.freeze(Object.fromEntries(Object.keys(Sr).map(e=>[e,Dr(Er(e))])));function Er(e){let{density:t,...n}=Sr[e];return{...n,preset:e,radius:{...n.radius},components:wr(n.radius,n.components),sizes:{...n.sizes},font:{...n.font},borders:{...n.borders},shadows:{...n.shadows}}}function Dr(e){for(let t of Object.values(e))t&&typeof t==`object`&&Dr(t);return Object.freeze(e)}var Or=e=>typeof e==`string`&&Object.prototype.hasOwnProperty.call(Sr,e),H=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,kr=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&Ar(e);function Ar(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 jr=(e,t)=>typeof e==`string`&&t.includes(e);function U(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=Or(t.preset)?t.preset:_r,r=Sr[n],i=U(r.radius,t.radius,(e,t)=>H(t,0,999)),a=U(t.density===`compact`||t.density===`spacious`?(r.density??Cr)[t.density]:r.sizes,t.sizes,(e,t)=>e===`icon`?H(t,10,32):H(t,16,80)),o=U(r.font,t.font,(e,t)=>e===`family`||e===`mono`?kr(t):e===`size`?H(t,11,20):e===`weight`||e===`strongWeight`?H(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:H(t,0,.5));return{preset:n,radius:i,components:U(wr(i,r.components),t.components,(e,t)=>H(t,0,999)),sizes:a,font:o,borders:U(r.borders,t.borders,(e,t)=>e===`width`?H(t,0,4):typeof t==`boolean`),shadows:U(r.shadows,t.shadows,(e,t)=>kr(t)),blur:H(t.blur,0,40)?t.blur:r.blur,active:jr(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:jr(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:jr(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:jr(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:H(t.tagRadius,0,999)?t.tagRadius:r.tagRadius}}function Mr(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(V(a.size,-1)),"--tcw-font-size-xs":t(V(a.size,-2)),"--tcw-font-size-lg":t(V(a.size,1)),"--tcw-font-size-xl":t(V(a.size,2)),"--tcw-font-size-display":t(V(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 G(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(Mr(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 Nr=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,E(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=D(`x`,14),o.addEventListener(`click`,()=>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&&E(e,`compare`)}e.appendChild(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()}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=D(`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.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));E(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.drawingsEl.replaceChildren(),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=D(`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){if(!e.isConnected)return;let r=document.createElement(`input`);r.type=`text`,r.className=`tcw-tree-rename`,r.value=n,r.maxLength=80,r.setAttribute(`aria-label`,this.t(`objects.renameGroup`));let i=!1,a=a=>{if(i)return;i=!0;let o=r.value.trim();r.isConnected&&r.replaceWith(e),a&&o&&o!==n&&this.callbacks.onRenameGroup?.(t,o)};r.addEventListener(`keydown`,e=>{e.key===`Enter`?a(!0):e.key===`Escape`&&(e.stopPropagation(),a(!1))}),r.addEventListener(`blur`,()=>a(!0)),e.replaceWith(r),r.focus(),r.select()}drawingRow(e){let t=this.row(e.label);(!e.visible||e.offInterval)&&t.classList.add(`tcw-tree-hidden`),e.offInterval&&(t.title=this.t(`indicatorSettings.offInterval`));let n=document.createElement(`div`);if(n.className=`tcw-tree-actions`,n.appendChild(this.iconButton(e.visible?`eye`:`eyeOff`,e.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleDrawingVisible(e.id,!e.visible))),n.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.onConfigureDrawing){let t=this.iconButton(`settings`,this.t(`objects.drawingSettings`),``,()=>this.callbacks.onConfigureDrawing?.(e.id));E(t,`drawingSettings`),n.appendChild(t)}return n.appendChild(this.iconButton(`trash`,this.t(`objects.removeDrawing`),`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(e.id))),t.appendChild(n),t}renderCompares(e){if(this.compareEl){if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(this.t(`objects.noComparisons`)));return}for(let t of e){let e=this.row(t.label),n=document.createElement(`span`);n.className=`tcw-tree-dot`,n.style.background=t.color,e.insertBefore(n,e.firstChild),this.callbacks.onRemoveCompare&&e.appendChild(this.iconButton(`trash`,this.t(`objects.removeComparison`),`tcw-tree-del`,()=>this.callbacks.onRemoveCompare?.(t.id))),this.compareEl.appendChild(e)}}}row(e){let t=document.createElement(`div`);t.className=`tcw-tree-row`;let n=document.createElement(`span`);return n.className=`tcw-tree-name`,n.textContent=e,n.title=e,t.appendChild(n),t}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=D(e,14),i.addEventListener(`click`,r),i}},Pr={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`};function Fr(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:Pr[e]??e}var Ir=[1,1.5,2,3,4],Lr=[`solid`,`dashed`,`dotted`],Rr=`#4c8dff`,zr=10,Br={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 Vr(e,t,n,r,i){let a=Kr();for(let e of[...t.plots].sort((e,t)=>e.color-t.color))a.appendChild(Hr(e,t,n,r));let o=N(Ir.map(e=>({value:String(e),label:`${e} px`})),String(t.lineWidth),e=>n.lineWidth(Number(e)));if(o.dataset.role=`line-width`,a.appendChild(j(r(`indicatorSettings.lineWidth`),o)),t.scale&&n.scale){let e=N([{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(j(r(`indicatorSettings.scale`),e))}e.appendChild(a),t.levels&&n.levels&&e.appendChild(Ur([...t.levels],n.levels,r,i))}function Hr(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=Zt(t.colors[e]??t.colors[0]??Rr,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=N(Lr.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 Ur(e,t,n,r){let i=Kr(),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+zr]);let t=i.querySelectorAll(`.tcw-indi-level input`);t[t.length-1]?.focus()}),i.replaceChildren(e,...a.length===0?[qr(n(`indicatorSettings.noLevels`))]:t,r)},s=e=>{a=e,t([...e]),o()},c=(e,o)=>{let c=M(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=D(`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 Wr(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=Kr();for(let e of r.INTERVAL_UNITS)s.appendChild(Gr(e,a.get(e),o,i));e.appendChild(s)}function Gr(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(Br[e]),o.append(s,c),a.appendChild(o);let l=[];if(e!==`ticks`){let o=(a,o)=>{let s=M(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(Br[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 Kr(){let e=document.createElement(`div`);return e.className=`tcw-settings-section`,e}function qr(e){let t=document.createElement(`div`);return t.className=`tcw-settings-label`,t.textContent=e,t}var Jr=1,Yr=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Xr=1.5,Zr={visible:!0,lineStyle:`solid`},K=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Qr=e=>JSON.parse(JSON.stringify(e));function $r(e){return e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase())}function ei(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].map(e=>[e,{...Zr,...t[e]}]))}var ti=class{backdrop;modal;bodyEl;titleEl;tabsEl;defaultsBtn;menu=null;callbacks;target=null;draft={};initial=null;look={colors:[],lineWidth:Xr,plots:{},levels:[],intervals:null};tab=`inputs`;tabButtons=[];returnFocus=null;uid=Jr++;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=D(`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>${D(`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??Xr,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:Qr(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;K(this.currentParams(),t.params)||this.callbacks.onApply(n,{...t.params});let r=t.look,i={};K(this.look.colors,r.colors)||(i.colors=[...r.colors]),this.look.lineWidth!==r.lineWidth&&(i.lineWidths=[r.lineWidth]),K(this.look.plots,r.plots)||(i.plots=ei(this.look.plots,r.plots)),Object.keys(i).length>0&&this.callbacks.onStyle?.(n,i),K(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),K(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}A(e,this.modal)}renderBody(){this.bodyEl.replaceChildren();let e=this.target;e&&(this.tab===`style`?this.renderStyle(e):this.tab===`visibility`?Wr(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=Xt(!!n,t=>this.setValue(e,t));else if(r===`number`){let r=Number(n);i=M(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`&&Yr.test(n)?Zt(n,t=>this.setValue(e,t)):this.textControl(e,String(n??``));return j(t?.label??$r(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 e of t)r.appendChild(this.option(String(e),String(e)));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);Vr(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 k(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:ei(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])=>!K(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!==Xr&&(i.lineWidths=[this.look.lineWidth]),Object.keys(this.look.plots).length>0&&(i.plots=Qr(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 ni(e){return e.normalize(`NFD`).replace(/[̀-ͯ]/g,``).toLowerCase()}var ri=/[\s/()%-]+/;function ii(e,t){let n=ni(e.shortName),r=ni(e.name);return n===t||ni(e.id)===t?0:n.startsWith(t)||r.startsWith(t)?1:[...r.split(ri),...n.split(ri)].some(e=>e.startsWith(t))?2:r.includes(t)||n.includes(t)?3:null}function ai(e,t){let n=ni(t.trim());return n?e.map(e=>({item:e,rank:ii(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 oi=1,si=(e,t)=>e.name.localeCompare(t.name),ci=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=oi++;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=D(`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=D(`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`?D(`star`,14):e===`templates`?D(`layers`,14):``}<span></span>`,t.querySelector(`span`).textContent=this.viewLabel(e),e===`templates`&&E(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=ai(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(si);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(si);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(si).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=D(`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=`${D(`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=`${D(`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=D(`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}A(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 li(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ui=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function di(e){return ui(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 fi(e){if(!ui(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 pi=class{constructor(e=`tcw:indicator-defaults`,t=li()){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(!ui(t))return e;for(let[n,r]of Object.entries(t))ui(r)&&e.set(n,{params:di(r.params),style:fi(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:di(t.params),style:fi(t.style)}]]);try{return this.storage.setItem(this.key,JSON.stringify(n)),!0}catch{return!1}}},mi=new Set([`timezone`,`numberLocale`,`chartTypeOptions`,`logScale`,`autoScale`]),hi=80,gi={crosshairMode:[`normal`,`magnet`,`hidden`],scaleMode:[`regular`,`logarithmic`,`percentage`,`indexedTo100`],periodLevelsPeriod:[`day`,`week`]},_i=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function vi(e){if(!_i(e))return{};let t={};for(let[n,r]of Object.entries(me)){if(mi.has(n)||!(n in e))continue;let i=e[n];if(typeof i!=typeof r||typeof i==`number`&&!Number.isFinite(i))continue;let a=gi[n];a&&!a.includes(i)||(t[n]=i)}return t}function yi(e){let{overrides:t}=(0,n.readChartStyleOverrides)(e);return Object.fromEntries(Object.entries(t).filter(([e,t])=>t!==null&&w.includes(e)))}function bi(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var xi=class{constructor(e=`tcw:chart-templates`,t=bi()){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)!_i(n)||typeof n.name!=`string`||!n.name.trim()||t.push({name:n.name.slice(0,hi).trim(),settings:vi(n.settings),style:yi(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,hi).trim();if(!r||!this.storage)return!1;let i=[...this.list().filter(e=>e.name!==r),{name:r,settings:vi(t),style:yi(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 Si(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Ci=80;function wi(e){let{text:t,...r}=(0,n.sanitizeDrawingStyle)(e);return r}function Ti(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 Ei=class{templates=[];constructor(e=`tcw:draw-templates`,t=Si()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(Ti)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?Ti(n):null}save(e,t,n){let r=e.trim().slice(0,Ci);if(!r)return;let i={name:r,style:wi(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,Ci),style:wi(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{}}},Di=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=Si()){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{}}},Oi=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],ki=[1,2,3,4],Ai=[`solid`,`dashed`,`dotted`],ji=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=D(`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=`${D(`plus`,13)}<span>${O(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 Oi){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 ki){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 Ai){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=D(`trash`,13),a.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(a),this.templatesEl.appendChild(e)}}},Mi=10,q=4,Ni=4,Pi=20,Fi=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d\s.,%/+-]+\)|[a-z]+)$/i;function Ii(e){return typeof e==`string`&&Fi.test(e.trim())?e.trim():`#7d8696`}function Li(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.min(t,Pi):1}function Ri(e){return Ai.includes(e)?e:`solid`}var zi=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=[Ii(t.color),Li(t.lineWidth),Ri(t.lineStyle),e.locked,e.canDelete,e.canSettings,e.canAlert].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=Ii(e.style.color),r=Li(e.style.lineWidth),i=Ri(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="${O(t)}" title="${O(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:${O(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`),Bi(i)),`<span class="tcw-sel-sep" aria-hidden="true"></span>`,e.canSettings?s(`settings`,t(`legend.settings`),D(`settings`,15)):``,e.canAlert?s(`alert`,t(`drawingSettings.addAlert`),D(`bell`,15)):``,s(`lock`,t(a?`common.unlock`:`common.lock`),D(a?`lock`:`unlock`,15),a?` tcw-sel-on`:``).replace(`<button `,`<button aria-pressed="${a}" `),s(`more`,t(`legend.more`),D(`more`,15)),e.canDelete?s(`delete`,t(`drawingMenu.delete`),D(`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-Mi;o<n.y+q&&(o=Math.min(t.y+t.height+Mi,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`){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=Ii(n.color).toLowerCase(),i=Li(n.lineWidth),a=Ri(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`?this.pop.innerHTML=Oi.map(e=>o(`tcw-sel-swatch`,e.toLowerCase()===r,`data-color="${e}" style="background:${e}" aria-label="${e}"`)).join(``):e===`width`?this.pop.innerHTML=ki.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=Ai.map(e=>o(`tcw-sel-option`,e===a,`data-style="${e}"`,Bi(e)+O(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`?Ni: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`);t&&(t.dataset.color?this.callbacks.onStyle({color:t.dataset.color}):t.dataset.width?this.callbacks.onStyle({lineWidth:Number(t.dataset.width)}):t.dataset.style&&this.callbacks.onStyle({lineStyle:Ri(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 Bi(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 Vi=[1,2,3,4],Hi=[`solid`,`dashed`,`dotted`],Ui=[10,11,12,14,16,18,20,24,28,32],Wi=48,Gi=.5,Ki=.1,qi=[`leftEnd`,`rightEnd`];function Ji(e,t,n){let r=`drawingOption.${t}`,i=e(r);return i===r?n:i}function Yi(){let e=document.createElement(`div`);return e.className=`tcw-settings-section`,e}function Xi(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 Zi(e,t,n,r){let i=[],a=Yi();a.appendChild(Qi(t.style(),n,i,r));let o=qi.filter(e=>t.defs[e]?.kind===`choice`);o.length>0&&a.appendChild(Xi(r(`drawingSettings.lineEnds`),...o.map(e=>J(N([{value:`normal`,label:r(`drawingSettings.lineEnd.normal`)},{value:`arrow`,label:r(`drawingSettings.lineEnd.arrow`)}],String(t.options()[e]??`normal`),t=>n.options({[e]:t})),Ji(r,e,t.defs[e].label))))),t.fill&&a.appendChild($i(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=Yi();for(let[e,a]of s)i.appendChild(ea(e,a,t.options(),n,r));e.appendChild(i)}for(let[a,o]of Object.entries(t.defs))o.kind===`levels`&&e.appendChild(ta(a,o,t,n,i,r))}function Qi(e,t,n,r){let i=J(Zt(e.color,e=>{t.style({color:e});for(let t of n)t(e)}),r(`drawingSettings.color`)),a=J(N(Vi.map(e=>({value:String(e),label:`${e} px`})),String(e.lineWidth),e=>t.style({lineWidth:Number(e)})),r(`drawingSettings.lineWidth`)),o=J(N(Hi.map(e=>({value:e,label:r(`drawingSettings.lineStyle.${e}`)})),e.lineStyle,e=>t.style({lineStyle:e})),r(`drawingSettings.lineStyle`));return Xi(r(`drawingSettings.line`),i,a,o)}function $i(e,t,n,r){let i=e.fillColor??en(e.color,Ki),a=P(i),o=$t(i),s=e.fillColor!==void 0,c=()=>{s=!0,t.style({fillColor:en(a,o),fillOpacity:o})},l=J(Zt(a,e=>{a=e,c()}),r(`drawingSettings.fill`));n.push(e=>{s||(a=P(e),l.value=a)});let u=J(M(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=`%`,Xi(r(`drawingSettings.fill`),l,u,d)}function ea(e,t,n,r,i){let a=Ji(i,e,t.label),o=n[e];switch(t.kind){case`boolean`:return Yt(a,!!o,t=>r.options({[e]:t}));case`number`:return j(a,M(Number(o),{min:t.min,max:t.max,step:t.step},t=>r.options({[e]:t})));case`choice`:return j(a,N(t.choices.map(t=>({value:t.value,label:Ji(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})),j(a,t)}}}function ta(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=Ji(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(M(e.value,{step:.001},e=>l(c().map((n,r)=>r===t?{...n,value:e}:n))),a(`drawingSettings.levelValue`)+s),p=J(Zt(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=P(e))});let m=document.createElement(`button`);m.type=`button`,m.className=`tcw-level-remove`,m.setAttribute(`aria-label`,a(`drawingSettings.removeLevel`)+s),m.innerHTML=D(`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>=Wi,d.addEventListener(`click`,()=>{let e=c().at(-1)?.value??0;l([...c(),{value:Math.round((e+Gi)*1e3)/1e3,visible:!0}]),r.redraw([`.tcw-level-row:last-child input[type="number"]`])}),o.appendChild(d),o}function na(e,t,n,r){let i=Yi(),a=document.createElement(`textarea`);a.className=`tcw-indi-input tcw-drawing-text`,a.rows=3,a.value=t.text??``,a.addEventListener(`input`,()=>n({text:a.value}));let o=j(r(`drawingSettings.text`),a);o.classList.add(`tcw-text-row`),i.appendChild(o),i.appendChild(j(r(`drawingSettings.fontSize`),N(Ui.map(e=>({value:String(e),label:`${e} px`})),String(t.fontSize??12),e=>n({fontSize:Number(e)})))),e.appendChild(i)}function ra(e,n,r,i){let a=Yi();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=Xi(o,J(ia(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 ia(e,t,n){let r=t.roundPrice??(e=>e),i=t.priceStep?.(),a=M(r(e),{step:i!==void 0&&i>0?i:`any`},e=>{let t=r(e);a.value=String(t),n(t)});return a}var aa=12,oa=`t:`,sa=1,ca=class{backdrop;modal;titleEl;tabsEl;bodyEl;templateBtn;menu=null;tabButtons=[];target=null;style;options={};anchors=[];intervals=null;tab=`style`;returnFocus=null;uid=sa++;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=D(`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>${D(`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){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=`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,(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.anchors.length<=aa?[`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}A(e,this.modal)}renderBody(){this.bodyEl.replaceChildren();let e=this.target;if(e)switch(this.tab){case`text`:na(this.bodyEl,this.style,e=>this.setStyle(e),this.t);break;case`coordinates`:ra(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`:Wr(this.bodyEl,this.intervals,e=>this.setIntervals(e),this.t);break;default:Zi(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:`${oa}${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 k(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(oa)&&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}};function la(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 ua=[{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`}],da=[{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 fa(e){return ua.find(t=>t.id===e)?.mode}function pa(...e){return e.filter(e=>e.length>0).flatMap((e,t)=>t===0?[...e]:[`separator`,...e])}function ma(e,t){let n=t.keys[e.id];return n?{...e,shortcut:n}:e}function ha(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 ga=e=>({id:`settings`,label:e(`chartMenu.settings`),icon:`settings`});function _a(e,t){let n=[ma({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 pa(ha(e,t),n,r,[...i,ga(t)])}function va(e,t){let n=[{id:`resetPriceScale`,label:t(`chartMenu.resetPriceScale`)},{id:`autoScale`,label:t(`settings.autoScale`),checked:e.autoScale},ma({id:`invertScale`,label:t(`chartMenu.invertScale`),checked:e.inverted},e),{id:`leftScale`,label:t(`settings.leftScale`),checked:e.leftScale}],r=ua.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}];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 pa(n,r,[{id:`labels`,label:t(`chartMenu.labels`),submenu:i},{id:`lines`,label:t(`chartMenu.lines`),submenu:a}],ha({...e,canTrade:!1,canDraw:!1},t),[ga(t)])}function ya(e,t){let n=[ma({id:`resetView`,label:t(`chartMenu.resetTimeScale`)},e)];e.canGoToDate&&n.push(ma({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 pa(n,r.length>0?[{id:`timezone`,label:t(`settings.timezone`),submenu:r}]:[])}function ba(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 pa([ma({id:`resetView`,label:t(`chartMenu.resetView`)},e)],n,[ga(t)])}function xa(e,t,n){switch(e){case`priceAxis`:return va(t,n);case`timeAxis`:return ya(t,n);case`pane`:return ba(t,n);default:return _a(t,n)}}var Sa=[`positions`,`orders`,`history`],Ca=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],wa=[`market`,`limit`,`stop`],Ta=[`gtc`,`day`];function Ea(e,t,n){return e.includes(t??``)?t:n}function Da(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Oa(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 ka(e,t=2){return`${e>0?`+`:``}${e.toFixed(t)}`}var Aa=class{el;tabButtons=new Map;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 Sa){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-account-tab`,t.setAttribute(`role`,`tab`),t.id=`tcw-account-tab-${e}`,t.addEventListener(`click`,()=>this.selectTab(e)),this.tabButtons.set(e,t),a.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-account-new`,E(o,`orderTicket`),o.innerHTML=D(`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=D(`x`,14),s.addEventListener(`click`,()=>this.closePanel()),i.append(a,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,Da(t.positions,e.positions)&&Da(t.orders,e.orders)&&Da(t.fills,e.fills)&&t.realisedPnl===e.realisedPnl){this.open&&this.tab===`positions`&&t.price!==e.price&&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=Sa.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=Sa[(n+Sa.length)%Sa.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;n.textContent=`${this.t(`account.${t}`)} (${e[t]})`,n.setAttribute(`aria-selected`,String(r)),n.tabIndex=r?0:-1,r&&this.content.setAttribute(`aria-labelledby`,n.id)}}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?`—`:this.callbacks.formatPrice(e),this.writePnl(t.pnl,Oa(t.position,e))}writePnl(e,t){e.className=t===null?``:t.pnl>=0?`tcw-account-up`:`tcw-account-down`,e.textContent=t===null?`—`:`${ka(t.pnl)} (${ka(t.pct)}%)`}table(e,t,n){if(t.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(n),this.content.replaceChildren(e);return}let r=document.createElement(`table`);r.className=`tcw-account-table`;let i=r.createTHead().insertRow();for(let t of e){let e=document.createElement(`th`);e.scope=`col`,e.textContent=t?this.t(t):``,i.appendChild(e)}r.createTBody().append(...t),this.content.replaceChildren(r)}row(e,t=``){let n=document.createElement(`tr`);t&&(n.className=t);for(let t of e){let e=n.insertCell();typeof t==`string`?e.textContent=t:e.appendChild(t)}return n}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=D(n.icon,14),e.addEventListener(`click`,n.run),t.appendChild(e)}return t}renderPositions(){let{formatPrice:e}=this.callbacks,{price:t}=this.snapshot,n=this.snapshot.positions.map(n=>{let r=n.quantity-(n.closedQuantity??0),i=document.createElement(`span`);this.writePnl(i,Oa(n,t));let a=`${this.sideText(n.side,`position`)} ${r} @ ${e(n.entryPrice)}`,o=this.row([this.sideCell(n.side),String(r),e(n.entryPrice),t===null?`—`:e(t),i,n.stopLoss===void 0?`—`:e(n.stopLoss),n.takeProfit===void 0?`—`:e(n.takeProfit),this.actions({icon:`repeat`,label:`${this.t(`account.reverse`)}: ${a}`,key:`reverse:${n.id}`,run:()=>this.callbacks.onReversePosition(n.id)},{icon:`x`,label:`${this.t(`account.closePosition`)}: ${a}`,key:`close:${n.id}`,run:()=>this.callbacks.onClosePosition(n.id),danger:!0})]);return this.live.push({position:n,price:o.cells[3],pnl:i}),o});this.table([`account.side`,`account.quantity`,`account.entry`,`account.price`,`account.pnl`,`account.stopLoss`,`account.takeProfit`,`account.actions`],n,`account.noPositions`)}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=Ea(wa,t.type===`stopLimit`?`stop`:t.type,`limit`),r=`${this.sideText(t.side,`trade`)} ${t.quantity} @ ${e(t.price)}`;return this.row([this.sideCell(t.side,`trade`),this.t(`ticket.type.${n}`),String(t.quantity),e(t.price),t.stopLoss===void 0?`—`:e(t.stopLoss),t.takeProfit===void 0?`—`:e(t.takeProfit),t.timeInForce?this.t(`ticket.tif.${Ea(Ta,t.timeInForce,`gtc`)}`):`—`,this.actions({icon:`x`,label:`${this.t(`account.cancelOrder`)}: ${r}`,key:`cancel:${t.id}`,run:()=>this.callbacks.onCancelOrder(t.id),danger:!0})])});this.table([`account.side`,`ticket.type`,`account.quantity`,`account.price`,`account.stopLoss`,`account.takeProfit`,`ticket.timeInForce`,`account.actions`],t,`account.noOrders`)}renderHistory(){let{formatPrice:e,formatTime:n}=this.callbacks,r=[...this.snapshot.fills].reverse().map(t=>{let r=document.createElement(`span`);return t.pnl===void 0?r.textContent=`—`:(r.className=t.pnl>=0?`tcw-account-up`:`tcw-account-down`,r.textContent=ka(t.pnl)),this.row([n(t.time),this.sideCell(t.side,`trade`),String(t.quantity),e(t.price),this.t(`account.reason.${Ea(Ca,t.reason,`order`)}`),r])});this.table([`account.time`,`account.side`,`account.quantity`,`account.price`,`account.reason`,`account.pnl`],r,`account.noFills`);let i=this.snapshot.realisedPnl??this.snapshot.fills.reduce((e,t)=>e+(t.pnl??0),0);if(r.length>0){let e=document.createElement(`p`);e.className=`tcw-account-summary`,e.textContent=t.r(this.t(`account.realised`),{pnl:ka(i)}),this.content.appendChild(e)}}},ja=1e-9;function Ma(e,t){return e.type===`market`?t:e.price}function Na(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=Ma(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,...Pa(e,n)]}function Pa(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)>ja)&&n.push(`priceStep`),o&&r!==null&&r>0&&(r>o.ceiling+ja||r<o.floor-ja)&&n.push(`priceLimits`),s!==void 0&&s>1&&e.quantity>s&&e.quantity%s!==0&&n.push(`lot`),n}function Fa(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 Ia(e,t){let n=Ma(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}var La=0,Ra=class{backdrop;modal;body;problemsEl;submit;draft=null;lastPrice=null;rules={};returnFocus=null;uid=++La;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-modal-narrow 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.stopPropagation(),this.close();return}A(e,this.modal)});let a=document.createElement(`div`);a.className=`tcw-modal-header`;let o=document.createElement(`h3`);o.id=`tcw-ticket-title-${this.uid}`,o.textContent=this.t(`ticket.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-modal-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=D(`x`,16),s.addEventListener(`click`,()=>this.close()),a.append(o,s),this.body=document.createElement(`div`),this.body.className=`tcw-modal-body`,this.problemsEl=document.createElement(`div`),this.problemsEl.className=`tcw-ticket-problems`,this.problemsEl.setAttribute(`aria-live`,`polite`);let c=document.createElement(`div`);c.className=`tcw-modal-footer`;let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-reset-link`,l.textContent=this.t(`common.cancel`),l.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`button`,this.submit.className=`tcw-done-btn`,this.submit.addEventListener(`click`,()=>this.place()),c.append(l,this.submit),this.modal.append(a,this.body,this.problemsEl,c),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??{};let t=e.price??e.lastPrice??0,n=e.side??`buy`,r=`market`;e.price!==void 0&&e.lastPrice!==null&&e.price!==e.lastPrice&&(r=e.price<e.lastPrice==(n===`buy`)?`limit`:`stop`);let i=this.rules.lot!==void 0&&this.rules.lot>1?this.rules.lot:1;this.draft={side:n,type:r,quantity:i,price:t,stopLoss:null,takeProfit:null,timeInForce:`gtc`},this.render(),this.backdrop.hidden=!1,this.body.querySelector(`button, input, select`)?.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){!this.draft||e===this.lastPrice||(this.lastPrice=e,this.check())}destroy(){this.close(),this.backdrop.remove()}place(){let e=this.draft;!e||Na(e,this.lastPrice,this.rules).length>0||(this.callbacks.onSubmit(Fa(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=document.activeElement,n=t instanceof HTMLElement&&this.body.contains(t)?t.dataset.ticketField:void 0;this.body.replaceChildren(this.sideToggle(e.side),j(this.t(`ticket.type`),za(`type`,N([`market`,`limit`,`stop`].map(e=>({value:e,label:this.t(`ticket.type.${e}`)})),e.type,e=>this.set({type:e},!0)))),j(this.t(`ticket.quantity`),za(`quantity`,this.number(e.quantity,e=>this.set({quantity:e}))))),e.type!==`market`&&this.body.append(j(this.t(`ticket.price`),za(`price`,this.number(e.price,e=>this.set({price:e})))),j(this.t(`ticket.timeInForce`),za(`timeInForce`,N([`gtc`,`day`].map(e=>({value:e,label:this.t(`ticket.tif.${e}`)})),e.timeInForce,e=>this.set({timeInForce:e})))));let r=e.type===`market`?this.lastPrice??e.price:e.price,i=t=>Ba(r*(1+(e.side===`buy`?t:-t)/100),r);this.body.append(this.optionalPrice(`ticket.stopLoss`,e.stopLoss,i(-1),t=>this.set({stopLoss:t},t===null||e.stopLoss===null)),this.optionalPrice(`ticket.takeProfit`,e.takeProfit,i(2),t=>this.set({takeProfit:t},t===null||e.takeProfit===null))),n&&this.body.querySelector(`[data-ticket-field="${n}"]`)?.focus(),this.check()}sideToggle(e){let t=document.createElement(`div`);t.className=`tcw-ticket-side`,t.setAttribute(`role`,`group`);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`,()=>this.set({side:n},!0)),t.appendChild(r)}return t}number(e,t){let n=document.createElement(`input`);return n.type=`number`,n.className=`tcw-indi-input`,n.step=`any`,n.min=`0`,n.value=String(e),n.addEventListener(`input`,()=>t(n.value.trim()===``?NaN:Number(n.value))),n}optionalPrice(e,t,n,r){let i=document.createElement(`div`);i.className=`tcw-settings-row tcw-ticket-optional`;let a=document.createElement(`span`);a.textContent=this.t(e);let o=Xt(t!==null,e=>r(e?n:null));if(o.setAttribute(`aria-label`,this.t(e)),o.dataset.ticketField=`${e}-switch`,i.append(a,o),t!==null){let n=this.number(t,e=>r(Number.isFinite(e)?e:NaN));n.setAttribute(`aria-label`,this.t(e)),n.dataset.ticketField=e,i.appendChild(n)}return i}check(){let e=this.draft;if(!e)return;let n=Na(e,this.lastPrice,this.rules),r=n.map(e=>this.problemText(e)),i=Ia(e,this.lastPrice);n.length===0&&i!==null&&r.push(t.r(this.t(`ticket.riskReward`),{rr:i.toFixed(2)})),this.problemsEl.replaceChildren(...r.map(e=>{let t=document.createElement(`p`);return t.textContent=e,t})),this.problemsEl.classList.toggle(`tcw-ticket-bad`,n.length>0),this.submit.disabled=n.length>0,this.submit.classList.toggle(`tcw-ticket-sell`,e.side===`sell`),this.submit.textContent=this.t(e.side===`buy`?`ticket.placeBuy`:`ticket.placeSell`)}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 za(e,t){return t.dataset.ticketField=e,t}function Ba(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 Va=0,Ha=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++Va;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}A(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=D(`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()}}}},Ua=0,Wa=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++Ua;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-modal-narrow 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`){A(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=D(`x`,16),c.addEventListener(`click`,()=>this.close()),o.append(s,c),this.search=document.createElement(`input`),this.search.type=`search`,this.search.className=`tcw-indi-input tcw-layouts-search`,this.search.placeholder=this.t(`layouts.search`),this.search.setAttribute(`aria-label`,this.t(`layouts.search`)),this.search.addEventListener(`input`,()=>this.render()),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-layouts-list`,this.listEl.setAttribute(`role`,`list`);let l=document.createElement(`div`);l.className=`tcw-modal-body tcw-layouts-body`,l.append(this.search,this.listEl),a.append(o,l),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-tag`,e.textContent=this.t(`layouts.current`),a.appendChild(e)}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=D(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()}}},Ga=5,Ka=class{menu;prompt;dialog;destroyed=!1;constructor(e,t){this.session=e,this.host=t;let{root:n,t:r}=t;this.menu=new k(n,r(`toolbar.layouts`)),this.prompt=new Ha(n,r),this.dialog=new Wa(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,root:r}=this.host,i=[];try{i=(await t.list()).slice(0,Ga)}catch{}if(this.destroyed)return;let a=t.current(),o=[{id:`save`,label:n(`layouts.save`),icon:`save`},{id:`saveAs`,label:n(`layouts.saveAs`),icon:`plus`}];a&&o.push({id:`rename`,label:n(`layouts.rename`),icon:`penLine`}),o.push({id:`autoSave`,label:n(`layouts.autoSave`),checked:t.isAutoSave()}),i.length>0&&o.push(`separator`,...i.map(e=>({id:`open:${e.id}`,label:e.name,checked:e.id===a?.id}))),o.push(`separator`,{id:`manage`,label:n(`layouts.open`),icon:`folder`});let s=e.getBoundingClientRect(),c=r.getBoundingClientRect();this.menu.open(o,s.left-c.left,s.bottom-c.top+2,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))},e)}destroy(){this.destroyed=!0,this.menu.destroy(),this.prompt.destroy(),this.dialog.destroy()}},qa=0,Ja=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-${++qa}`,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=wt(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=wt(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},Ya=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{}}},Xa=[],Za=null;function Qa(e){let t=()=>{Za=e};return e.addEventListener(`pointerdown`,t,!0),Xa.push(e),()=>{e.removeEventListener(`pointerdown`,t,!0);let n=Xa.indexOf(e);n>=0&&Xa.splice(n,1),Za===e&&(Za=null)}}function $a(e,t=!1){let n=Za?.isConnected?Za:null;if(!n){let e=document.activeElement;n=e?Xa.find(t=>t.contains(e))??null:null}return!n&&!t&&(n=Xa.find(e=>e.isConnected)??null),n!==null&&e.contains(n)}function Y(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable)}var eo=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],to=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function no(e){let{theme:t,timestamp:n,...r}=e;return r}function ro(e){return!to(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:eo.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:to(e.chart)?no(e.chart):null}}function io(e){try{return JSON.parse(e)}catch{return null}}function ao(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var oo=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=ao()){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 so(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 co(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 lo=/^(\d{4})-(\d{2})-(\d{2})$/,uo=/^(\d{2}):(\d{2})$/;function fo(e,t,r){let i=lo.exec(e),a=t?uo.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 X(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 po=class{form=null;returnFocus=null;opener=null;onOutside=e=>{let t=e.target;this.form&&!this.form.contains(t)&&!this.opener?.contains(t)&&this.close()};constructor(e,t,n){this.host=e,this.labels=t,this.onSubmit=n}isOpen(){return this.form!==null}open(e,t=null){this.close(),this.opener=t,this.returnFocus=document.activeElement;let n=document.createElement(`form`);n.className=`tcw-goto`,E(n,`goToDate`),n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-label`,this.labels.title);let r=document.createElement(`div`);r.className=`tcw-goto-title`,r.textContent=this.labels.title;let i=this.field(n,this.labels.date,`date`,e.date);i.required=!0;let a=this.field(n,this.labels.time,`time`,e.time),o=document.createElement(`div`);o.className=`tcw-goto-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-btn`,s.textContent=this.labels.cancel,s.addEventListener(`click`,()=>this.close());let c=document.createElement(`button`);c.type=`submit`,c.className=`tcw-btn tcw-goto-submit`,c.textContent=this.labels.submit,o.append(s,c),n.prepend(r),n.append(o),n.addEventListener(`submit`,e=>{if(e.preventDefault(),!i.value)return;let t={date:i.value,time:a.value};this.close(),this.onSubmit(t)}),n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&this.close()}),this.host.appendChild(n),this.form=n,document.addEventListener(`mousedown`,this.onOutside),i.focus()}close(){if(!this.form)return;document.removeEventListener(`mousedown`,this.onOutside),this.form.remove(),this.form=null;let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}destroy(){this.close()}field(e,t,n,r){let i=document.createElement(`label`);i.className=`tcw-goto-field`;let a=document.createElement(`span`);a.textContent=t;let o=document.createElement(`input`);return o.type=n,o.value=r,o.className=`tcw-goto-input`,i.append(a,o),e.appendChild(i),o}},Z=8,mo=4,ho=3,go=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,_o=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`)&&vo(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(vo(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&yo(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`||(vo(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)&&(yo(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&&yo(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!So(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`&&yo(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(go);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`&&yo(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(!xo(e)){this.hide();return}this.el.textContent=bo(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&&(xo(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=Co(e);s===`bottom`&&o+n.height+Z+i>t.height?s=`top`:s===`top`&&o-Z-i<0?s=`bottom`:s===`right`&&a+n.width+Z+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+Z:o-Z-i):(c=s===`right`?a+n.width+Z:a-Z-r,l=o+n.height/2-i/2),c=Math.max(mo,Math.min(t.width-r-mo,c)),l=Math.max(mo,Math.min(t.height-i-mo,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,ho],bottom:[0,-ho],left:[ho,0],right:[-ho,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 vo(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function yo(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function bo(e){return e.dataset.tip??e.getAttribute(`title`)??``}function xo(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function So(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function Co(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var wo=2,To=class{stack;toggle;rows=new Map;panes=new Map;collapsed=!1;toggleKey=``;stackKey=``;constructor(e,t,n){this.host=e,this.callbacks=t,this.labels=n,this.stack=document.createElement(`div`),this.stack.className=`tcw-ind-legend`,E(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)}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,a=!1;for(let t of e){i.add(t.instanceId);let e=this.rows.get(t.instanceId)??this.createRow(t.instanceId);this.fill(e,t),t.pane?e.el.parentElement!==this.host&&this.host.appendChild(e.el):e.el.parentElement!==this.stack&&(this.stack.insertBefore(e.el,this.toggle),a=!0),this.place(e,t.pane)}for(let[e,t]of this.rows)i.has(e)||(t.el.remove(),this.rows.delete(e));a&&this.collapsed&&this.setCollapsed(!1),this.renderToggle(e.filter(e=>!e.pane).length)}destroy(){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()}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=D(i,12),Q(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`,E(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,E(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){let t=document.createElement(`div`);t.className=`tcw-ind-legend-row`,E(t,`indicatorLegend`),t.dataset.instance=e;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-ind-legend-name`,n.addEventListener(`click`,()=>this.callbacks.onSettings(e));let r=document.createElement(`span`);r.className=`tcw-ind-legend-values`,E(r,`indicatorLegend.values`);let i=document.createElement(`span`);i.className=`tcw-ind-legend-actions`;let a=(e,t,n,...r)=>{let a=document.createElement(`button`);return a.type=`button`,a.className=`tcw-ind-legend-act`,a.dataset.act=e,E(a,...r),a.innerHTML=D(t,13),a.addEventListener(`click`,n),i.appendChild(a),a},o=a(`visible`,`eye`,()=>{this.callbacks.onToggleVisible(e,!u.visible)},`indicatorLegend.visibility`),s=a(`settings`,`settings`,()=>this.callbacks.onSettings(e),`indicatorSettings`,`indicatorLegend.settings`),c=this.callbacks.onMore?a(`more`,`more`,()=>this.callbacks.onMore?.(e,c),`indicatorLegend.more`):null,l=a(`remove`,`x`,()=>this.callbacks.onRemove(e),`indicatorLegend.remove`);t.append(n,r,i);let u={el:t,name:n,values:r,eye:o,settings:s,more:c,remove:l,visible:!0,valuesKey:``,state:``,placeKey:``};return this.rows.set(e,u),u}fill(e,t){let n=`${t.label}|${t.visible}|${!!t.offInterval}`;n!==e.state&&(e.state=n,e.visible=t.visible,e.name.textContent=t.label,e.name.title=this.labels.settings,e.el.classList.toggle(`tcw-ind-legend-row--hidden`,!t.visible||!!t.offInterval),t.offInterval&&this.labels.offInterval?e.el.title=this.labels.offInterval:e.el.removeAttribute(`title`),e.eye.innerHTML=D(t.visible?`eye`:`eyeOff`,13),Q(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),Q(e.settings,this.labels.settings,t.label),e.more&&(Q(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),Q(e.remove,this.labels.remove,t.label));let r=t.values.map(e=>`${e.text}${e.color??``}`).join(``);r!==e.valuesKey&&(e.valuesKey=r,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})))}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>=wo;!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;Q(this.toggle,r,this.collapsed?`(${e})`:void 0),this.toggle.setAttribute(`aria-expanded`,String(!this.collapsed));let i=D(this.collapsed?`chevronDown`:`chevronUp`,12);this.toggle.innerHTML=this.collapsed?`${i}<span>${e}</span>`:i}};function Q(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function Eo(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 Do=new Map;function Oo(e){let t=Do.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),Do.set(e,t)),t}function ko(e,t=`en-US`){return Math.abs(e)>=1e6?Oo(t).format(e):(0,n.formatPrice)(e,(0,r.indicatorValuePrecision)(e),t)}var Ao=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.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=`${D(`x`,14)}<span>${O(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=`${D(`check`,14)}<span>${O(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,this.labelEl.textContent=e===`buy`?this.t(`toolbar.longBracket`):this.t(`toolbar.shortBracket`),this.labelEl.dataset.side=e,this.el.hidden=!1}hide(){this.visible=!1,this.el.hidden=!0}isVisible(){return this.visible}destroy(){this.el.remove()}},jo=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 Mo(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}}var No=class{el;bodyEl;callbacks;open=!1;levels;constructor(e,n,r=12,i=t.t){this.t=i,this.callbacks=n,this.levels=r,this.el=document.createElement(`div`),this.el.className=`tcw-ladder`,E(this.el,`depthLadder`),this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-ladder-header`;let o=document.createElement(`span`);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=D(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a);let c=document.createElement(`div`);c.className=`tcw-ladder-cols`,c.innerHTML=[this.t(`ladder.bid`),this.t(`ladder.price`),this.t(`ladder.ask`)].map(e=>`<span>${O(e)}</span>`).join(``),this.el.appendChild(c),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-ladder-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.callbacks.onToggle?.(!0)}close(){this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1)}setData(e){if(!e){this.renderEmpty();return}this.render(Mo(e,this.levels))}destroy(){this.el.remove()}renderEmpty(){this.bodyEl.replaceChildren();let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=this.t(`ladder.empty`),this.bodyEl.appendChild(e)}render(e){if(this.bodyEl.replaceChildren(),e.rows.length===0){this.renderEmpty();return}let n=e.maxVolume>0?1/e.maxVolume:0;for(let r of e.rows){let e=r.askVolume>0,i=document.createElement(`div`);i.className=`tcw-ladder-row`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-ladder-cell tcw-ladder-bid`,r.bidVolume>0?(a.textContent=Po(r.bidVolume),a.style.setProperty(`--w`,`${(r.bidVolume*n*100).toFixed(1)}%`),a.title=t.r(this.t(`ladder.sellAt`),{price:this.callbacks.formatPrice(r.price)}),a.addEventListener(`click`,()=>this.callbacks.onTrade(`sell`,r.price))):a.disabled=!0;let o=document.createElement(`div`);o.className=`tcw-ladder-price ${e?`tcw-ask`:`tcw-bid`}`,o.textContent=this.callbacks.formatPrice(r.price);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-ladder-cell tcw-ladder-ask`,r.askVolume>0?(s.textContent=Po(r.askVolume),s.style.setProperty(`--w`,`${(r.askVolume*n*100).toFixed(1)}%`),s.title=t.r(this.t(`ladder.buyAt`),{price:this.callbacks.formatPrice(r.price)}),s.addEventListener(`click`,()=>this.callbacks.onTrade(`buy`,r.price))):s.disabled=!0,i.appendChild(a),i.appendChild(o),i.appendChild(s),this.bodyEl.appendChild(i)}}};function Po(e){return e>=1e3?(e/1e3).toFixed(1)+`k`:e>=1?e.toFixed(2).replace(/\.00$/,``):e.toPrecision(2)}var Fo=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`,E(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=D(`x`,14),o.addEventListener(`click`,()=>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)}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(`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?`+`:``;this.bodyEl.appendChild(this.row(this.t(`dataWindow.change`),`${i}${t(e.change)} (${i}${e.changePct.toFixed(2)}%)`,r)),this.bodyEl.appendChild(this.row(this.t(`dataWindow.volume`),Lo(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,Io(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 Io(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 Lo(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 Ro=globalThis.Buffer;function zo(e){if(Ro)return Ro.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 Bo(e){if(Ro)return Ro.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 Vo(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ho(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function Uo(e){return Vo(zo(JSON.stringify(e)))}function Wo(e){if(!e)return null;try{let t=Bo(Ho(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:n.scaleMode??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[]}}catch{return null}}var Go=`tcw`;function Ko(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)===Go)return decodeURIComponent(e.slice(t+1))}return null}function qo(e,t){let[n]=e.split(`#`);return`${n}#${Go}=${t}`}var Jo=[[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]],Yo=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`),Jo.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)}},Xo=4e3,Zo=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(),Xo)):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}},Qo=`host:`;function $o(e,t){return[...e,...e.length>0&&t.length>0?[`separator`]:[],...t.map((e,t)=>({id:`${Qo}${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))]}function es(e,t){return e.startsWith(Qo)?(t[Number(e.slice(5))]?.onSelect(),!0):!1}var ts=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),ns={ctrl:`ctrl`,control:`ctrl`,cmd:`ctrl`,command:`ctrl`,meta:`ctrl`,mod:`ctrl`,alt:`alt`,option:`alt`,opt:`alt`,shift:`shift`},rs={esc:`escape`,space:` `,spacebar:` `,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`,del:`delete`,return:`enter`,plus:`+`};function is(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=ns[e.toLowerCase()];if(!t)return null;r[t]=!0}let i=n.toLowerCase();if(ns[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=rs[i]??i,r.shift&&r.key.length===1)return null;return r.display=[...r.ctrl?[ts?`⌘`:`Ctrl`]:[],...r.alt?[`Alt`]:[],...r.shift?[`Shift`]:[],r.key===` `?`Space`:n.length===1?n.toUpperCase():n],r}function as(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 os=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 ss(e){let t=`${e.ctrl?`ctrl+`:``}${e.alt?`alt+`:``}${e.shift?`shift+`:``}${e.char??e.key}`;return os.has(t)}function cs(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 ls=48,us=5e4,ds=100;function fs(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,ds);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var ps=[`#4c8dff`,`#a57cff`,`#1398a8`,`#e25592`,`#8a93a3`,`#62c895`],ms=4,hs=7,gs=17,_s=3,vs=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`],ys=5e3,bs=()=>{let e=document.activeElement;return e instanceof Element&&e.closest(`[role="dialog"], [aria-modal="true"], [role="menu"]`)!==null},xs=229,Ss=1e3,Cs=w.filter(e=>n.CHART_STYLE_KEYS[e]!==`color`),ws=()=>typeof document<`u`&&document.hidden,Ts=200,Es=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.toolbar?.setFullscreen(document.fullscreenElement===this.root),this.portal.isConnected&&this.overlayHost()};commandPalette=null;symbolSearch=null;hotkeySheet=null;replayBar=null;dragDrop=null;alertsPanel=null;objectTree=null;indicatorSettings=null;indicatorPicker=null;drawingStyle=null;drawingSettings=null;drawingMenu=null;selectionToolbar=null;selectionToolbarFrame=null;chartMenu=null;menuPane=null;canExport=!0;symbolLoads=new Map;ui;legendMenu=null;templates=new Ya;templatePrompt=null;chartTemplates=new xi;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;legendHoverIndex=null;favoritesStore=new oo;indicatorFavorites=new oo(`tcw:indicator-favorites`);indicatorDefaults=new pi;timeframeFavorites=new oo(`tcw:tf-favorites`);customTimeframes=new oo(`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 Xn;marketTimer=null;clockTimer=null;onPageShown=null;chartNav=null;visibleBarCount=50;replayPollInterval=null;replaySpeed=5;replayStep=`bar`;replayStartSeq=0;replayStepsCache=null;replayShade=null;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;root;chartContainer;loading;historyPill;connectSeq=0;localSeq=0;lastLocalSwitchMs=0;destroyed=!1;options;symbols;settingsState;settingsDefaults;t;adapter=null;boundGlobalKeydown=null;baseSeries=null;baseTimeframeMs=0;chosenTimeframe=null;rangeSeq=0;rangeQueue=Promise.resolve();compares=[];featureState;hostHotkeys=[];hostMenus=new Set;hostLayer=null;priceAxisAddDefault=!1;constructor(i,a={}){this.options=a,this.symbols=a.symbols??pe;let o=a.chartOptions;if(this.settingsState={...me,...o?.numberLocale?{numberLocale:o.numberLocale}:{},...o?.timeZone==null?{}:{timezone:c(o.timeZone)},...o?.leftPriceScale===void 0?{}:{leftPriceScale:o.leftPriceScale},...o?.highLowLines===void 0?{}:{highLowLines:o.highLowLines},...o?.extendedHours===void 0?{}:{extendedHours:o.extendedHours},...o?.chartTypeOptions?{chartTypeOptions:(0,n.readChartTypeOptions)(o.chartTypeOptions)}:{}},this.t=t.n(t.o(a.locale,a.messages)),this.featureState=Ie(a),a.persistLayouts){let e=a.persistLayouts===!0?{}:a.persistLayouts;this.layoutKeyPrefix=e.keyPrefix??`tcw:layout:`,this.layoutDebounceMs=e.debounceMs??1500}let s=this.resolveIsDark(a.theme),u=this.resolveTheme(a.theme);this.themeOf={...this.themeOf,[s?`dark`:`light`]:u};let d={drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:a.trading!==!1,tradingContextMenu:!1,priceAxisAddButton:this.featureState.alerts||a.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,...a.chartOptions?.features};this.priceAxisAddDefault=d.priceAxisAddButton===!0;let f={...d,priceAxisAddButton:this.priceAxisAddDefault&&this.featureState[`menu.priceAxisAdd`]};if(this.canExport=d.dataExport!==!1,this.settingsDefaults={...this.settingsState,legendVisible:d.legend!==!1,barCountdown:d.barCountdown!==!1,indicatorValueLabels:d.indicatorValueLabels===!0},this.settingsState={...this.settingsDefaults},this.timeframes=Tt(yt(a.timeframes,d.timeframes),this.customTimeframes.list(),d.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let e=bt(this.timeframes,d.defaultTimeframeFavorites,!!a.timeframes?.length);for(let t of e)this.timeframeFavorites.add(t)}let p=a.timeframe??`5m`,m=!d.timeframes?.length||d.timeframes.includes(p)?p:this.timeframes[0]??p;this.state={symbol:a.symbol??this.symbols[0]??`BTCUSDT`,timeframe:m,chartType:a.chartOptions?.chartType??`candlestick`,isDark:s,activeIndicators:new Map,activeTool:null,magnetEnabled:d.drawingMagnet!==!1,magnetStrong:!1,eraser:!1,zoomArea:!1,stayInDrawing:!1,connectionState:a.adapter?`connecting`:`disconnected`,connectionMessage:a.adapter?this.t(`status.connecting`):``},qe(),this.root=document.createElement(`div`),this.root.className=`tcw-root`,this.root.dataset.tcwTheme=s?`dark`:`light`;let h=a.dir===`ltr`||a.dir===`rtl`?a.dir:As(a.locale)?`rtl`:`ltr`;this.root.dir=h,this.portal.dir=h,i.appendChild(this.root),this.tooltip=new _o(this.root),this.portal.className=`tcw-root tcw-portal`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.stopKeyboardInset=so([this.root,this.portal]),this.stopNarrow=co(this.root,e=>{this.toolbar?.fit(),e||this.sidebar?.closeOverlay()}),this.ui=W(a.ui);let ee=a.ui!==void 0;G(this.root,this.ui,{variables:ee}),G(this.portal,this.ui,{variables:ee}),this.markSwitchedOff(),this.stopFormControls=ue([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 zt(this.root,{symbols:this.symbols,timeframes:this.timeframeMenu(),timeframeFavorites:this.pinnedTimeframes(),chartTypes:a.chartTypes?de.filter(e=>a.chartTypes.includes(e.value)):de},{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:a.trading===!1?void 0:()=>this.toggleAccountPanel(),onLayouts:a.layouts===!1?void 0:e=>void this.layoutsUI?.openMenu(e),onBracket:a.trading===!1?void 0:e=>this.startBracket(e),onToggleLadder:a.trading!==!1&&a.depthLadder?()=>this.depthLadder?.toggle():void 0,onOrderTicket:a.trading===!1?void 0:()=>this.openOrderTicket(),onCompare:a.adapter&&d.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 g=document.createElement(`div`);g.className=`tcw-body`,a.drawingFavorites&&this.favoritesStore.seedDefaults(a.drawingFavorites),this.sidebar=new qt(g,{drawingToolGroups:ft(fe,this.t),favorites:this.favoritesStore.list(),shortcuts:nr()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onToggleMagnet:d.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),onClearDrawings:()=>{this.chart.clearDrawings(),this.state={...this.state,activeTool:null},this.updateUI()},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`,g.appendChild(this.chartContainer),this.loading=new Yo(this.chartContainer,this.t(`status.loading`)),this.historyPill=new Zo(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),a.watchlist&&this.createWatchlist(g,a.watchlist===!0?{}:a.watchlist),this.root.appendChild(g);let _=document.createElement(`div`);_.className=`tcw-account-dock`,E(_,`accountPanel`),this.root.appendChild(_),this.chart=new e.c(this.chartContainer,{chartType:this.state.chartType,theme:u,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}}},...a.chartOptions,features:f}),a.chartOptions?.shapes||this.applyChartShapes(),this.applyLegendFont();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 sr(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=>this.historyPill.update(e.payload)),this.chart.on(`symbolInfoChange`,e=>{let t=e.payload.info,n=t?[t.description,t.exchange].filter(Boolean).join(` · `):``;this.toolbar?.setSymbolDescription(n||null),this.refreshMarket()}),this.symbolInfoPanel=new Gn(this.root,this.t,{onToggle:e=>{this.toolbar?.setActive(`symbolInfo`,e),e&&(this.refreshSymbolInfo(),this.loadNews())}}),this.marketTimer=setInterval(()=>this.refreshMarket(),3e4),this.onPageShown=()=>{ws()||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(),this.statusBar=new mn(this.root,{presets:r.RANGE_PRESETS,presetLabels:{All:this.t(`range.all`)},groupLabel:this.t(`range.presets`),goToLabel:this.t(`range.goTo`),onPreset:e=>void this.applyRangePreset(e),onGoTo:()=>this.toggleGoToDate()},{clock:{label:this.t(`settings.timezone`),now:()=>this.clockNow(),options:()=>({current:this.settingsState.timezone,list:l(this.settingsState.timezone,Date.now(),this.t(`settings.timezone.local`),this.adapter?.resolveSymbol?{label:this.t(`settings.timezone.exchange`),zone:this.chart.getSymbolInfo()?.timezone??null}:void 0)}),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:d.logScale===!1?void 0:()=>this.toggleScaleMode(`logarithmic`),onAuto:()=>this.changeSettings({autoScale:!this.chart.isAutoScale()})}}),this.clockTimer=setInterval(()=>{!ws()&&this.featureState.statusBar&&this.featureState[`statusBar.clock`]&&this.statusBar?.tick()},Ss),this.chart.on(`priceRangeChange`,()=>this.refreshScaleSwitches()),this.refreshScaleSwitches(),this.goToDate=new po(this.root,{title:this.t(`range.goTo`),date:this.t(`range.date`),time:this.t(`range.time`),submit:this.t(`range.goToSubmit`),cancel:this.t(`range.cancel`)},({date:e,time:t})=>this.goToWallTime(e,t)),this.settings=new dn({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:d.barCountdown,logScale:d.logScale,trading:d.trading!==!1,exchangeZone:this.adapter?.resolveSymbol?()=>this.chart.getSymbolInfo()?.timezone??null:void 0},this.overlayHost),this.symbolSearch=new _n({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t),this.hotkeySheet=new Sn({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.setPaneTitlesVisible(!this.featureState.indicatorLegend),this.indicatorLegend=new To(this.chartContainer,{onToggleVisible:(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=>this.handleRemoveIndicator(e),onMore:(e,t)=>this.openLegendMenu(e,t),onPaneAction:(e,t)=>this.runPaneAction(e,t)},{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`)}),this.legendMenu=new k(this.root,this.t(`legend.more`)),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.legendHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.scheduleLegend()}),this.chart.on(`crosshairLeave`,()=>{this.legendHoverIndex=null,this.scheduleLegend()});for(let e of[`indicatorUpdate`,`indicatorChange`,`dataUpdate`,`resize`,`paneResize`,`paneChange`,`themeChange`,`timeframeChange`])this.chart.on(e,()=>this.scheduleLegend());this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let t=e.payload.barIndex;if(typeof t==`number`){if(this.replayBar.getMode()===`select`){this.startReplayAt(t);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(t?.x??null)}),this.dataWindow=new Fo(this.root,{formatPrice:e=>this.formatAlertPrice(e)},this.t),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.lastHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())});let v=new Ei,te=new Di;for(let[e,t]of Object.entries(te.all()))this.chart.setDrawingToolDefaults(e,t??null);this.drawingSettings=new ca(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}),this.refreshObjects()},toWallTime:e=>X(e*(0,n.barTimeUnit)(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let r=fo(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),te.set(e,this.chart.getDrawingToolDefaults(e)),this.say(t.r(this.t(`drawingSettings.defaultSaved`),{name:this.drawingToolName(e)}))},templates:{list:e=>v.list(e),save:e=>this.promptSaveDrawingTemplate(v,e),remove:(e,t)=>v.remove(e,t)}},this.t),this.chart.on(`drawingDoubleClick`,e=>this.openDrawingSettings(e.payload.id)),this.drawingStyle=new ji(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},v,this.t),this.drawingMenu=new k(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 zi(this.root,{onStyle:e=>{for(let t of this.chart.getSelectedDrawingIds())this.chart.setSelectedDrawingStyle(e,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 k(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(We(xa(t,c,this.t),Me,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=We(ha(this.chartMenuContext(i),this.t),Me,this.featureState);this.openChartMenu(a,n,r,{area:`priceAxisAdd`,price:i})}),this.chart.on(`signalMarkerHover`,e=>this.showMarkerTip(e.payload)),this.intervalInput=new Ja(this.chartContainer,{title:this.t(`interval.title`),hint:this.t(`interval.hint`),invalid:this.t(`interval.invalid`)},e=>this.selectTypedTimeframe(e)),a.layouts!==!1&&this.setupLayouts(a.layouts===!0||a.layouts===void 0?{}:a.layouts),a.trading!==!1){this.orderTicket=new Ra(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)},this.t),this.accountPanel=new Aa(_,{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}=X(e,this.displayTimezone());return`${t} ${n}`},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())}a.trading!==!1&&(this.bracketBar=new Ao(this.root,{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)}))}),a.depthLadder&&(this.depthLadder=new No(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),onToggle:e=>this.toolbar?.setActive(`ladder`,e)},void 0,this.t)),this.chart.on(`dataUpdate`,e=>{let t=e.payload;t&&t.bracket===`cancelled`&&this.bracketBar?.hide()})),this.alertsPanel=new gr(this.root,{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}=X(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)}))}),a.alertNotifications&&(this.alertNotifier=new jo(a.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 ci(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 ti(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 Nr(this.root,{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()},onAddCompare:d.compareSymbols===!1?void 0:()=>this.handleAddCompare(),onRemoveCompare:e=>this.handleRemoveCompare(e)},this.t);let y=()=>{this.objectTree?.isOpen()&&this.refreshObjects()},b=0,ne=()=>{b||!this.objectTree?.isOpen()||(b=requestAnimationFrame(()=>{b=0,this.destroyed||y()}))};if(this.chart.on(`drawingCreate`,y),this.chart.on(`drawingRemove`,y),this.chart.on(`drawingUpdate`,ne),this.chart.on(`timeframeChange`,ne),this.chart.on(`indicatorAdd`,y),this.chart.on(`indicatorRemove`,y),this.chart.on(`indicatorChange`,y),this.commandPalette=new gn({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),this.boundGlobalKeydown=e=>{if(this.featureState.hotkeys&&this.replayBar?.isMounted()&&this.handleReplayKey(e)||this.handleHostHotkey(e))return;let t=$a(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.symbolSearch?.open(this.symbols,this.state.symbol,void 0,this.symbolSearchFn())}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||Y()||!$a(this.root,!0))return;e.preventDefault(),this.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&tr[e.code]){if(e.defaultPrevented||Y()||!t||bs()||!n(`hotkeys.tools`))return;e.preventDefault(),this.handleDrawingTool(tr[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervalInput||!n(`intervalTyping`)||Y()||bs()||!$a(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(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`||e.code===`KeyR`)){if(Y()||!t)return;if(e.code===`KeyI`){if(!n(`hotkeys.invertScale`))return;e.preventDefault(),this.changeSettings({invertScale:!this.settingsState.invertScale}),this.settings?.refresh(this.settingsState)}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(Y()||!t||!n(`hotkeys.help`)||!this.featureState.hotkeySheet)return;e.preventDefault(),this.hotkeySheet?.open({isOn:e=>this.sheetKeyOn(e),extra:this.hostHotkeys.map(e=>({keys:e.parsed.display,text:e.spec.label}))})}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=Qa(this.root),a.adapter?(this.adapter=a.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(),a.onReady?.(this.chart),a.shareUrl&&typeof location<`u`){let e=Ko(location.hash);e&&this.importState(e)}}setSymbols(e){this.symbols=e;let t=this.watchlistStore;t&&this.watchlistFromSymbols&&t.replace(t.getLists().map(t=>t.id===`default`?{...t,symbols:e}:t))}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}toggleSymbolInfo(e){let t=this.symbolInfoPanel;if(!t)return;let n=e??!t.isOpen();n&&!this.featureState.symbolInfo||(n?t.open():t.close())}refreshMarket(){if(ws())return;let e=(0,n.marketStatus)(this.chart.getSymbolInfo(),Date.now());this.statusBar?.setMarket(e.state,this.t(e.state===`open`?`symbolInfo.open`:`symbolInfo.closed`)),this.refreshSymbolInfo()}refreshSymbolInfo(){let e=this.symbolInfoPanel;!e?.isOpen()||this.destroyed||e.render(this.symbolInfoView())}symbolInfoView(){let e=this.state.symbol;return Yn({symbol:e,info:this.chart.getSymbolInfo(),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?Os():null,r=new Wn({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 jn(e,{onSelect:e=>{this.setSymbol(e)},onAdd:()=>this.symbolSearch?.open(this.symbols,this.state.symbol,e=>r.add(e),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)},{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.state={...this.state,symbol:e},this.sessionRefPrice=null,this.options.onSymbolChange?.(e),this.updateUI(),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)||ws())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),G(this.root,this.ui),G(this.portal,this.ui),this.applyChartShapes(),this.applyLegendFont()}getUI(){return W({...this.ui})}applyLegendFont(){this.chart.setLegend({fontFamily:this.ui.font.mono,fontSize:V(this.ui.font.size,-1)})}applyChartShapes(){this.chart.setShapes({tagRadius:this.ui.tagRadius})}destroy(){if(!this.destroyed){this.destroyed=!0,this.stopKeyboardInset?.(),this.stopKeyboardInset=null,this.stopNarrow?.(),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.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.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.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(),Je()}}handleSymbolClick(){this.featureState.symbolSearch&&this.symbolSearch?.open(this.symbols,this.state.symbol,void 0,this.symbolSearchFn())}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 At({dayShare:i.slice(-Ts).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=this.chart.getPlotRect(),o=ks(r.map(e=>this.chart.getDrawingRect(e.id)))??{x:a.x+a.width/2,y:a.y,width:0,height:0},s=r[0];e.show({rect:{x:o.x+i.x,y:o.y+i.y,width:o.width,height:o.height},bounds:{x:a.x+i.x,y:a.y+i.y,width:a.width,height:a.height},style:s.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(s.id)})}openDrawingSettings(e){let t=this.chart.getDrawings().find(t=>t.id===e),n=t?this.chart.getDrawingToolDescriptor(t.type):null;!t||!n||!this.drawingSettings||!this.featureState.drawingSettings||this.drawingSettings.open({id:e,type:t.type,name:this.drawingToolName(t.type),style:{...t.style},options:this.chart.getDrawingOptions(e),defs:n.options??{},anchors:t.anchors.map(e=>({...e})),fill:n.fill===!0,text:n.text===!0,intervals:t.intervals??null})}promptSaveDrawingTemplate(e,n){this.drawingTemplatePrompt??=new Ha(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=We(la({selected:i,canConfigure:this.drawingSettings!==null,canAlert:this.chart.canAddDrawingAlert(e)},this.t),Ne,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=$o(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=>{es(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:r.scaleMode,canLog:i.logScale!==!1,inverted:this.chart.isInvertScale(),leftScale:r.leftPriceScale,labels:{values:r.indicatorValueLabels,...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(da.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)}timezoneChoices(){let e=this.adapter?.resolveSymbol?{label:this.t(`settings.timezone.exchange`),zone:this.chart.getSymbolInfo()?.timezone??null}:void 0;return l(this.settingsState.timezone,Date.now(),this.t(`settings.timezone.local`),e).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=$o(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=>{es(e,i)||(e.startsWith(`tz:`)?this.changeSettings({timezone:e.slice(3)}):this.runChartMenuAction(e,r))})}setFeatures(e){let t=this.featureState;this.featureState={...t,...Fe(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.alertsPanel?.close()],[`objectTree`,()=>this.objectTree?.close()],[`symbolInfo`,()=>this.symbolInfoPanel?.close()],[`dataWindow`,()=>this.dataWindow?.close()],[`accountPanel`,()=>this.toggleAccountPanel(!1)],[`orderTicket`,()=>this.orderTicket?.close()],[`depthLadder`,()=>this.depthLadder?.close()],[`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()],[`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=is(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;ss(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===xs||e.getModifierState?.(`AltGraph`)||e.defaultPrevented||Y()||cs(e)||bs())return!1;let t=this.hostHotkeys.find(t=>as(e,t.parsed));if(!t)return!1;let n=!t.parsed.ctrl&&!t.parsed.alt;if(!$a(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(Cs.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;default:return!0}}markSwitchedOff(){let e=Le(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()}addToolbarButton(e){if(!this.toolbar)return null;let t=this.toolbar,n=t.addHostButton(e);return t.tidy(),{element:n,setActive:t=>Bt(n,t,e.toggle===!0),setText:t=>Vt(n,e.label,t),remove:()=>{n.remove(),t.tidy()}}}addToolbarDropdown(e){let t=this.toolbar;if(!t)return null;let n=new k(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:t=>{if(n.isOpen()){n.close();return}let r=e.items();if(r.length===0)return;let i=t.getBoundingClientRect(),a=this.root.getBoundingClientRect();n.open($o([],r),i.left-a.left,i.bottom-a.top+2,e=>es(e,r),t)}});return r.setAttribute(`aria-haspopup`,`menu`),r.setAttribute(`aria-expanded`,`false`),t.tidy(),{element:r,setText:t=>Vt(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=>Bt(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=fa(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`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()})}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}:{}}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}=X(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=s(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();e.length!==0&&this.goToDate.open(X(e[e.length-1].time*(0,n.barTimeUnit)(e),this.displayTimezone()),this.root.querySelector(`[data-role="goto"]`))}goToWallTime(e,t){let r=fo(e,t,this.displayTimezone()),i=this.chart.getData();if(r===null||i.length===0)return;let a=r/(0,n.barTimeUnit)(i);this.chart.goToTime(a),a<i[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:gt(e),custom:this.customTimeframes.has(e)}))}handleAddTimeframe(e){if(!this.featureState.customTimeframes)return!1;let t=wt(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=Tt(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}=X(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=Tt(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 Ha(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>=ls||this.baseSeries.length>=us;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await fs(),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.options.weekStartsOn??1;this.chart.setData(i(this.baseSeries,this.state.timeframe,{weekStartsOn:e}))}else this.chart.setData(this.baseSeries);this.lastLocalSwitchMs=performance.now()-e}handleDataUpdate(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.length==`number`){t.length>0&&this.loading.isActive()&&(this.loading.end(),this.state.connectionState===`error`&&this.setConnectionState(`connected`,this.t(`status.live`)));return}if(t.error!==void 0){this.loading.isActive()&&(this.loading.fail(this.t(`status.connectionFailed`)),this.setConnectionState(`error`,t.error||this.t(`status.connectionFailed`)));return}switch(t.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()}toggleAlerts(){!this.alertsPanel||!this.featureState.alerts||(this.alertsPanel.toggle(),this.alertsPanel.isOpen()&&this.refreshAlerts())}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}));return Uo({v:1,symbol:this.state.symbol,timeframe:this.state.timeframe,chartType:this.state.chartType,scaleMode:this.chart.getScaleMode(),indicators:e,drawings:this.chart.getDrawings()})}async importState(e){let t=Wo(e);return t?(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),this.chart.setScaleMode(t.scaleMode),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):!1}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=qo(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)}buildDataWindowModel(){let e=this.chart.getData(),t=this.lastHoverIndex;if(t===null||t<0||t>=e.length)return{ohlc:null,change:0,changePct:0,indicators:[]};let n=e[t],r=t>0?e[t-1].close:n.open,i=n.close-r,a=r===0?0:i/r*100,o=this.chart.getActiveIndicators().map(e=>{let n=this.chart.getIndicatorOutput(e.instanceId)?.series?.[t]??null,r=e.descriptor.plots?.map(e=>[e.key,e.title])??Object.keys(n??{}).map(e=>[e,e]),i=n?r.filter(([e])=>typeof n[e]==`number`&&Number.isFinite(n[e])).map(([e,t])=>({key:t,value:n[e]})):[];return{name:e.descriptor.name,values:i}}).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,changePct:a,indicators:o}}toggleDataWindow(){!this.dataWindow||!this.featureState.dataWindow||(this.dataWindow.toggle(),this.dataWindow.isOpen()&&this.dataWindow.render(this.buildDataWindowModel()))}toggleObjects(){!this.objectTree||!this.featureState.objectTree||(this.objectTree.toggle(),this.objectTree.isOpen()&&this.refreshObjects())}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:Ds(e,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:e.descriptor.name,visible:e.visible})),t=this.chart.getDrawings().map(e=>({id:e.id,label:Fr(e.type,this.t),visible:e.visible,offInterval:e.visible&&!this.chart.isDrawingShown(e.id),locked:e.locked,group:e.group})),n=this.compares.map(e=>({id:e.id,label:e.symbol,color:e.color}));this.objectTree.setObjects(e,t,n)}async handleAddCompare(){if(!this.featureState.compare)return;if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}let e=new Set([this.state.symbol,...this.compares.map(e=>e.symbol)]),t=this.symbols.filter(t=>!e.has(t));this.symbolSearch?.open(t.length?t:this.symbols,this.state.symbol,e=>{this.pickCompareWay(e)},this.symbolSearchFn())}pickCompareWay(e){let n=this.state.symbol,r=[{id:`percent`,label:this.t(`compare.percent`)},{id:`scale`,label:this.t(`compare.ownScale`)},{id:`pane`,label:this.t(`compare.ownPane`)},{id:`spread`,label:t.r(this.t(`compare.spread`),{main:n,other:e})},{id:`ratio`,label:t.r(this.t(`compare.ratio`),{main:n,other:e})},{id:`correlation`,label:t.r(this.t(`compare.correlation`),{main:n,other:e})},{id:`correlationLog`,label:t.r(this.t(`compare.correlationLog`),{main:n,other:e})}],i=this.chart.getPlotRect();this.chartMenu?.open(r,i.x+24,i.y+24,t=>void this.addCompareSymbol(e,t))}async addCompareSymbol(e,n=`percent`){if(!this.adapter){this.say(this.t(`toast.compareNeedsAdapter`),`error`);return}if(n!==`percent`){let t=n===`scale`?this.chart.addIndicator(`compareSymbol`,{symbol:e},`bottom`,{scale:`left`}):n===`pane`?this.chart.addIndicator(`compareSymbol`,{symbol:e}):n===`correlation`?this.chart.addIndicator(`correlation`,{symbol:e}):n===`correlationLog`?this.chart.addIndicator(`correlationlog`,{symbol:e}):this.chart.addIndicator(`spread`,{symbol:e,mode:n});t&&n===`pane`&&this.chart.moveIndicatorToPane(t,`new`);return}if(this.compares.some(t=>t.symbol===e))return;let i=ps[this.compares.length%ps.length],a=`cmp_${e}`;try{let n=await(0,r.withResampling)(this.adapter).fetchHistory(e,this.state.timeframe,this.options.historyLimit??500);this.compares.length===0&&this.chart.setCompareMode(`percent`),this.chart.addCompareSymbol(a,e,n,i),this.compares=[...this.compares,{id:a,symbol:e,color:i}],this.refreshObjects(),this.say(t.r(this.t(`toast.comparing`),{symbol:e}))}catch(t){this.say(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}}handleRemoveCompare(e){this.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.refreshObjects()}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=Math.max(this.chart.getData().length,this.options.historyLimit??500),a=await(0,r.withResampling)(this.adapter).fetchHistory(e,t,n);if(i())return;this.chart.setSymbolSeries(e,a)}catch(t){if(i())return;this.chart.setSymbolSeries(e,this.chart.getSymbolSeries(e)),this.say(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}}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);for(let e of this.compares)try{let t=await(0,r.withResampling)(this.adapter).fetchHistory(e.symbol,this.state.timeframe,this.options.historyLimit??500);this.chart.updateCompareData(e.id,t)}catch{}}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)))}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 cr(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=this.chart.getIndicatorOutput(r)?.series?.[t.length-1]?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}formatAlertPrice(e){let t=this.chart.getPriceFormatter?.();if(t)return t(e);let n=Math.abs(e),r=n>=1e3?2:n>=1?4:6,i=this.settingsState.numberLocale||void 0;return e.toLocaleString(i,{minimumFractionDigits:2,maximumFractionDigits:r})}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.settingsState,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 de)e.push({id:t.value,label:dt(t,this.t),category:`chartType`,active:this.state.chartType===t.value});for(let t of ft(fe,this.t))for(let n of t.tools)e.push({id:n.value,label:n.label,category:`drawing`,active:this.state.activeTool===n.value});for(let t of this.timeframes)e.push({id:t,label:gt(t),category:`timeframe`,active:this.state.timeframe===t});return e.push({id:`screenshot`,label:this.t(`action.screenshot`),category:`action`,shortcut:``},{id:`copyImage`,label:this.t(`action.copyImage`),category:`action`},{id:`toggleTheme`,label:this.t(`action.toggleTheme`),category:`action`},{id:`settings`,label:this.t(`action.settings`),category:`action`},{id:`shareView`,label:this.t(`action.shareView`),category:`action`},{id:`autoFib`,label:this.t(`action.autoFib`),category:`action`},{id:`dataWindow`,label:this.t(`action.dataWindow`),category:`action`},{id:`symbolInfo`,label:this.t(`action.symbolInfo`),category:`action`},{id:`clearDrawings`,label:this.t(`action.clearDrawings`),category:`action`}),e.filter(e=>e.category!==`action`||this.commandOn(e.id))}commandOn(e){let t=He(e);return t===void 0||this.featureState[t]}handleAction(e){if(this.commandOn(e))switch(e){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.chart.clearDrawings(),this.state={...this.state,activeTool:null},this.updateUI();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.settingsState={...this.settingsState,chartTypeOptions:this.chart.getChartTypeOptions?.()??{},autoScale:this.chart.isAutoScale?.()??this.settingsState.autoScale},this.settingsEdit={settings:{...this.settingsState},style:this.settingsStyle(),keys:new Set,styleKeys:new Set},this.settings?.open(this.settingsState,this.state.chartType,e))}resetView(){this.chart.fitContent(),this.changeSettings({autoScale:!0}),this.settings?.refresh(this.settingsState)}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;if(!e){this.restoreSettings(a,o);return}let s=r(this.settingsState),c=i.length>0?this.settingsStyle(i):null;JSON.stringify([a,o])!==JSON.stringify([s,c])&&this.chart.recordUndo({undo:()=>this.restoreSettings(a,o),redo:()=>this.restoreSettings(s,c)})}touchSettings(e,t=[]){if(this.settingsEdit){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);n&&(this.touchSettings(Object.keys(n.settings),w),this.applySettings(n.settings),this.chart.resetOverrides([...w],{layer:`user`}),this.chart.applyOverrides(n.style,{layer:`user`}),this.settings?.refresh(this.settingsState),this.say(t.r(this.t(`templates.applied`),{name:e})))}promptSaveChartTemplate(){this.chartTemplatePrompt??=new Ha(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?D(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.chart.saveState(),t=e?io(e):null,n=t&&typeof t==`object`?no(t):null;return{v:1,symbol:this.state.symbol,timeframe:this.chosenTimeframe??this.state.timeframe,scaleMode:this.settingsState.scaleMode,invertScale:this.settingsState.invertScale,chart:n}}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){if(e.chart){this.chart.loadState(JSON.stringify(no(e.chart)));let t=e.chart.chartType;typeof t==`string`&&(this.state={...this.state,chartType:t})}this.applySettings({scaleMode:e.scaleMode,invertScale:e.invertScale}),this.syncIndicatorsFromChart(),this.updateUI(),this.settings?.refresh(this.settingsState,this.state.chartType)}}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=ro(io(e));return t?(await this.restoreLayout(t),!0):!1}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 Ka(n,{root:this.root,t:this.t,toast:(e,t)=>this.say(e,t),formatTime:e=>{let{date:t,time:n}=X(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 t=new Map;for(let n of this.chart.getActiveIndicators())t.set(n.instanceId,{id:n.id,label:e.C(n.id,n.params,n.descriptor.defaultConfig,n.descriptor.shortName)});this.state={...this.state,activeIndicators:t},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 Tn({onPlay:()=>{if(this.replayBar?.getMode()===`select`){this.startReplayAt(Math.max(1,this.replayTotal()-100),!0);return}this.chart.getReplayState()===`paused`&&this.chart.replayResume(),this.replayBar?.setState(`playing`)},onPause:()=>{this.chart.replayPause(),this.replayBar?.setState(`paused`)},onStepBack:()=>this.stepReplay(-1),onStepForward:()=>this.stepReplay(1),onSeek:e=>{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:()=>{let e=this.replayTotal(),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)))},onClose:()=>this.exitReplay(),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`),random:e(`replay.random`),realtime:e(`replay.realtime`),barsPerSecond:e(`replay.barsPerSecond`),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`)});let t=[{value:`bar`,label:e(`replay.step.bar`)},...this.replayStepOptions().map(e=>({value:e,label:e}))];t.some(e=>e.value===this.replayStep)||(this.replayStep=`bar`),this.replayBar.mount(this.chartContainer,{total:this.replayTotal(),speed:this.replaySpeed,mode:`select`,steps:t,step:this.replayStep}),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)}hideReplayShade=()=>this.positionReplayShade(null);replayFrom(e,t=!1){this.featureState.replay&&(this.replayBar?.isMounted()||this.enterReplay(),this.startReplayAt(e,t))}startReplayAt(e,t=!1){let n=this.replayBar;if(!n)return;let r=this.replayTotal(),i=Math.max(0,Math.min(Number.isFinite(e)?Math.floor(e):0,r-1));this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade),n.setMode(`replay`);let a=++this.replayStartSeq,o=e=>{this.destroyed||this.replayBar!==n||!n.isMounted()||a!==this.replayStartSeq||(this.chart.replayStart({speed:this.replaySpeed,interval:1e3,startIndex:i,paused:!0,revealMarks:this.options.replayRevealMarks!==!1,...e?{steps:e}:{}}),t&&this.chart.replayResume(),n.setState(t?`playing`:`paused`),this.syncReplayBar(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayPollInterval=setInterval(()=>this.syncReplayBar(),150))};if(this.replayStep===`bar`){o(null);return}this.replayStepsFor(this.replayStep).then(e=>{a===this.replayStartSeq&&(e||this.say(this.t(`replay.stepsFailed`),`error`),o(e))})}replayStepOptions(){let e=(0,n.timeframeToMs)(this.state.timeframe);return vs.filter(t=>{let i=(0,n.timeframeToMs)(t);return!(i<e)||e%i!==0?!1:this.adapter?(0,r.servesTimeframe)(this.adapter,t):this.baseSeries!==null&&this.baseTimeframeMs>0&&i>=this.baseTimeframeMs&&i%this.baseTimeframeMs===0})}async replayStepsFor(e){let t=`${this.state.symbol}|${this.state.timeframe}|${e}`;if(this.replayStepsCache?.key===t)return this.replayStepsCache.steps;let a=null;if(this.adapter){let t=Math.max(1,Math.round((0,n.timeframeToMs)(this.state.timeframe)/(0,n.timeframeToMs)(e))),i=Math.min(ys,Math.max(this.chart.getData().length,100)*t);try{a=await(0,r.withResampling)(this.adapter).fetchHistory(this.state.symbol,e,i)}catch{a=null}}else this.baseSeries&&(a=(0,n.timeframeToMs)(e)===this.baseTimeframeMs?this.baseSeries:i(this.baseSeries,e));return!a||a.length===0?null:(this.replayStepsCache={key:t,steps:a},a)}replayTotal(){return this.chart.isReplayActive()?this.chart.getReplayProgress().total:this.chart.getData().length}syncReplayBar(){let e=this.replayBar;if(!e?.isMounted()||e.getMode()!==`replay`)return;if(!this.chart.isReplayActive()){this.teardownReplayUi();return}let t=this.chart.getReplayProgress(),n=this.chart.getReplayState();e.setProgress(t.current,t.total),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`)return;let t=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(Math.max(0,Math.min(t.total-1,t.current+e))),this.replayBar.setState(`paused`),this.syncReplayBar()}handleReplayKey(e){if(e.defaultPrevented)return!1;let t=document.activeElement;return t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable)?!1:e.shiftKey&&(e.key===`ArrowRight`||e.key===`ArrowLeft`)&&this.replayBar?.getMode()===`replay`?(e.preventDefault(),e.stopPropagation(),this.stepReplay(e.key===`ArrowRight`?1:-1),!0):e.key===`Escape`&&this.replayBar?.getMode()===`select`?(this.exitReplay(),!0):!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.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade),this.replayBar?.unmount(),this.replayBar=null}applySettings(e){this.settingsState={...this.settingsState,...e},(e.scaleMode!==void 0||e.logScale!==void 0||e.invertScale!==void 0)&&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.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),(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.chart.setLogScale(e.logScale),this.settingsState={...this.settingsState,scaleMode:e.logScale?`logarithmic`:`regular`}):(this.chart.setScaleMode(e.scaleMode),this.settingsState={...this.settingsState,logScale:e.scaleMode===`logarithmic`}),e.numberLocale!==void 0&&(this.chart.setNumberLocale(e.numberLocale),this.watchlist?.setLocale(e.numberLocale||void 0)),e.timezone!==void 0&&this.chart.setTimezone(s(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({renko:{},lineBreak:{},kagi:{},pointAndFigure:{},rangeBars:{},...e.chartTypeOptions})}resetSettings(){let e={...this.settingsState},t=this.settingsStyle(),n={...this.settingsDefaults};this.touchSettings(Object.keys(n),w),this.applySettings(n),this.chart.resetOverrides([...w],{layer:`user`});let r={...this.settingsState},i=this.settingsStyle();this.settings?.refresh(this.settingsState),!(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();this.applySettings(e);let i=n();this.settingsEdit||JSON.stringify(r)===JSON.stringify(i)||this.chart.recordUndo({subject:`settings:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings(r),redo:()=>this.restoreSettings(i)})}settingsStyle(e=w){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){this.applySettings(e),t&&t.theme===(this.chart.getTheme()?.name??``)&&this.chart.applyOverrides(t.overrides,{layer:`user`}),this.settings?.refresh(this.settingsState)}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 t=this.chart.getData().length-1,n=this.chart.isTimeAligned()?this.legendHoverIndex:null,r=n===null?t:Math.min(Math.max(n,0),t),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=this.chart.getActiveIndicators().map(t=>{let n=i.get(t.instanceId)??null,o=r>=0?this.chart.getIndicatorOutput(t.instanceId)?.series?.[r]:null,s=this.chart.getIndicatorStyle(t.instanceId),c=t.visible&&t.shown===!1,l=c?[]:Eo(t.descriptor,o,s?.colors??[],s?.plots);return{instanceId:t.instanceId,label:e.C(t.id,t.params,t.descriptor.defaultConfig,t.descriptor.shortName),visible:t.visible,offInterval:c,values:l.map(e=>({text:n?ko(e.value,a):this.chart.formatPrice(e.value),color:e.color})),pane:n?{x:n.x+ms,y:n.y+Math.min(hs+n.row*gs,Math.max(hs,n.height-gs)),width:n.width-2*ms}:null}}),s=this.chart.getPlotRect(),c=this.chart.getMaximizedPane(),l=e=>o.find(t=>t.instanceId===e)?.label??``,u=this.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-ms,y:e.rect.y+_s,label:l(e.instanceId),collapsed:this.chart.isPaneCollapsed(e.instanceId),maximized:c===e.instanceId,canMoveUp:this.chart.canMovePane(e.instanceId,-1),canMoveDown:this.chart.canMovePane(e.instanceId,1)}));this.indicatorLegend.update(o,{left:s.x+ms,top:this.chart.getLegendBottom()+1},u)}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=$o(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=>{es(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 Ds(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([t]);for(let e=!0;e;){e=!1;for(let t of i){let n=a(t);n&&o.has(n)&&!o.has(t.instanceId)&&(o.add(t.instanceId),e=!0)}}let s=[];for(let t of i){if(o.has(t.instanceId))continue;let r=e.C(t.id,t.params,t.descriptor.defaultConfig,t.descriptor.shortName);for(let e of t.descriptor.plots??[])s.push({value:(0,n.indicatorSource)(t.instanceId,e.key),label:`${r}: ${e.title}`})}return s}function Os(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}function ks(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 As(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}var js={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},Ms=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],$={"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 Ns(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call($,e)}function Ps(e){return JSON.parse(JSON.stringify(e))}function Fs(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 Is(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!Ns(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map(ro);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...js};for(let e of Ms)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 Ls=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||Y()||!$a(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,n={}){this.options=n,this.layout=Ns(n.layout)?n.layout:`1x2`,this.sync={...js,...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`,G(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=co(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=Qa(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||!Ns(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);G(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=Fe(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=Is(io(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(),Je()}}shapeCount(){let{cols:e,rows:t}=$[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=$[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 Es(n,{...r,...i,...a&&this.sync.symbol?{symbol:a.getSymbol()}:{},...a&&this.sync.interval?{timeframe:a.getTimeframe()}:{},...this.options.adapter&&!i.adapter?{adapter:this.options.adapter(e)}:{},...this.uiTheme?{ui:this.uiTheme}:{},layouts:!1,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)return;let{until:n}=t.payload;this.relay(e,e=>{let t=e.getChart();if(t.isReplayActive()){t.replaySeekToTime(n);return}let r=Rs(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()),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(Ps(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(Ps(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(Ns)??Object.keys($);for(let e of r){let{cols:r,rows:i}=$[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=Fs(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=`${D(`link`,13)}<span>${O(this.t(`grid.sync`))}</span>`,i.appendChild(a);for(let e of Ms){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=`${D(`save`,14)}<span class="tcw-layouts-label">${O(t)}</span>`+(n?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+D(`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 Ka(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=X(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 Rs(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=Es,exports.ChartWidgetGrid=Ls,exports.DEFAULT_GRID_SYNC=js,Object.defineProperty(exports,`DRAWING_TOOL_ICONS`,{enumerable:!0,get:function(){return n.DRAWING_TOOL_ICONS}}),exports.EN_MESSAGES=t.c,exports.GRID_SHAPES=$,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=T,exports.WIDGET_UI_PRESETS=Tr,exports.applyWidgetUI=G,exports.cleanLayoutName=e.r,exports.createChartTypeIcon=Ze,exports.createIcon=D,exports.createToolIcon=Xe,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=Is,exports.readWatchlists=Hn,exports.readWidgetLayout=ro,exports.registerWidgetLocale=t.a,exports.resolveWidgetUI=W,exports.widgetUIVariables=Mr;
5973
6045
  //# sourceMappingURL=index.cjs.map