diff --git a/NAMESPACE b/NAMESPACE index 13df419..8b3a545 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -11,6 +11,7 @@ export(install_duckdb_wasm) export(linkCharts) export(myIO) export(myIOOutput) +export(myIOProxy) export(myIO_last_error) export(myio_chart_schema) export(myio_function_signature) @@ -42,6 +43,7 @@ export(setTransitionSpeed) export(stop_duckdb_wasm_missing) export(suppressAxis) export(suppressLegend) +export(updateMyIOData) importFrom(htmlwidgets,createWidget) importFrom(htmlwidgets,shinyRenderWidget) importFrom(htmlwidgets,shinyWidgetOutput) diff --git a/NEWS.md b/NEWS.md index 4b746cb..acd0797 100644 --- a/NEWS.md +++ b/NEWS.md @@ -19,6 +19,12 @@ `addIoLayer(type = "line", transform = "lttb", options = list(threshold = 1000))`. Off by default (`identity`); runs on the in-memory/SVG path and is independent of the DuckDB-WASM engine's own SQL-side LTTB, so it never double-downsamples. +* New `myIOProxy()` + `updateMyIOData()` update a rendered chart's layer data in + place from the Shiny server without re-running `renderMyIO()`. Layers are + matched by label and swapped through the existing data-join path, so only the + changed marks transition and brush/zoom/toggle state is preserved (the full + re-render destroyed and recreated the chart, flickering and dropping state): + `myIOProxy("chart") |> updateMyIOData(series = new_df)`. ## Performance and tooling diff --git a/R/myIOProxy.R b/R/myIOProxy.R new file mode 100644 index 0000000..a42f5d3 --- /dev/null +++ b/R/myIOProxy.R @@ -0,0 +1,88 @@ +#' Update a myIO chart in place from the Shiny server +#' +#' `myIOProxy()` creates a lightweight handle to an already-rendered myIO widget, +#' and `updateMyIOData()` swaps the data of one or more existing layers without +#' re-rendering the whole widget. Unlike re-executing `renderMyIO()` (which +#' destroys and recreates the chart on every reactive invalidation, dropping +#' brush/zoom/toggle state and flickering), a proxy update reuses the existing +#' data-join path: only the changed marks transition, and interaction state is +#' preserved. +#' +#' Layers are matched by their `label`. Unknown labels are ignored client-side. +#' The supplied data frame replaces the layer's data as-is (the identity data +#' path); statistical transforms attached at `addIoLayer()` time are not +#' re-applied, so pass already-transformed data for transformed layers. +#' +#' @param outputId The output id of the `myIOOutput()` whose chart to update. +#' @param session The Shiny session object. Defaults to the current reactive +#' domain. +#' @param proxy A `myIO_proxy` object from `myIOProxy()`. +#' @param ... One or more `label = data.frame` updates, where `label` is an +#' existing layer label and the data frame carries that layer's mapped columns. +#' +#' @return `myIOProxy()` returns a `myIO_proxy` object; `updateMyIOData()` +#' returns the proxy invisibly. +#' +#' @examples +#' \dontrun{ +#' library(shiny) +#' ui <- fluidPage(myIOOutput("chart"), actionButton("go", "Resample")) +#' server <- function(input, output, session) { +#' output$chart <- renderMyIO({ +#' myIO(data = data.frame(x = 1:50, y = rnorm(50))) |> +#' addIoLayer("line", label = "series", mapping = list(x_var = "x", y_var = "y")) +#' }) +#' observeEvent(input$go, { +#' myIOProxy("chart") |> +#' updateMyIOData(series = data.frame(x = 1:50, y = rnorm(50))) +#' }) +#' } +#' shinyApp(ui, server) +#' } +#' +#' @export +myIOProxy <- function(outputId, session = NULL) { + if (!requireNamespace("shiny", quietly = TRUE)) { + stop("myIOProxy() requires the 'shiny' package.", call. = FALSE) + } + check_string(outputId, "outputId", "myIOProxy") + if (is.null(session)) { + session <- shiny::getDefaultReactiveDomain() + } + if (is.null(session)) { + stop("myIOProxy() must be called from within a Shiny session.", call. = FALSE) + } + structure( + list(id = session$ns(outputId), session = session), + class = "myIO_proxy" + ) +} + +#' @rdname myIOProxy +#' @export +updateMyIOData <- function(proxy, ...) { + if (!inherits(proxy, "myIO_proxy")) { + stop("updateMyIOData(): `proxy` must be a myIOProxy() object.", call. = FALSE) + } + updates <- list(...) + labels <- names(updates) + if (length(updates) == 0L || is.null(labels) || any(labels == "")) { + stop("updateMyIOData(): supply one or more named `label = data.frame` updates.", + call. = FALSE) + } + + layers <- lapply(labels, function(label) { + data <- updates[[label]] + if (!is.data.frame(data)) { + stop("updateMyIOData(): update for layer '", label, + "' must be a data frame.", call. = FALSE) + } + list(label = label, data = as_layer_rows(ensure_source_key(data))) + }) + + proxy$session$sendCustomMessage( + "myio:proxy-update", + list(id = proxy$id, layers = layers) + ) + invisible(proxy) +} diff --git a/_pkgdown.yml b/_pkgdown.yml index 263e22e..4c152a5 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -126,6 +126,7 @@ reference: desc: Use myIO widgets in Shiny applications contents: - starts_with("myIO-shiny") + - myIOProxy - title: LLM Tool Calling desc: Machine-readable schema and validators for agent-built chart specs contents: diff --git a/inst/htmlwidgets/myIO.js b/inst/htmlwidgets/myIO.js index 838dcca..35bcf6e 100644 --- a/inst/htmlwidgets/myIO.js +++ b/inst/htmlwidgets/myIO.js @@ -25,7 +25,8 @@ HTMLWidgets.widget({ var coordinatorMarkSpec = null; var coordinatorQueryTemplate = ""; if (this.myIOchart) { - // Destroy and recreate to handle layer count/type changes cleanly + // Destroy and recreate to handle layer count/type changes cleanly. + // The chart's "destroy" event unregisters it from the proxy registry. this.myIOchart.destroy(); d3.select(el).selectAll("*").remove(); this.myIOchart = null; @@ -115,6 +116,21 @@ HTMLWidgets.widget({ height: height }); var id = el.id; + // Register for myIOProxy() partial updates immediately after + // construction (before any async coordinator work) so the registry + // never has an empty window across a re-render where an in-flight + // proxy message could be dropped. The chart's "destroy" event reaps + // the entry on re-render and on teardown. + if (HTMLWidgets.shinyMode && window.myIO && + typeof window.myIO.registerInstance === "function") { + window.myIO.registerInstance(id, this.myIOchart); + window.myIO.installProxyHandler(); + this.myIOchart.on("destroy", function() { + if (window.myIO && typeof window.myIO.unregisterInstance === "function") { + window.myIO.unregisterInstance(id); + } + }); + } this.myIOchart.on("error", function(e) { el._myIO_lastError = { message: e.message, diff --git a/inst/htmlwidgets/myIO/myIOapi.js b/inst/htmlwidgets/myIO/myIOapi.js index f6cac3a..4c37da6 100644 --- a/inst/htmlwidgets/myIO/myIOapi.js +++ b/inst/htmlwidgets/myIO/myIOapi.js @@ -730,7 +730,7 @@ void main() { `}return A}var s=i(r),o=new Blob([s],{type:"text/csv;charset=utf-8;"}),h=document.createElement("a");if(h.download!==void 0){var g=URL.createObjectURL(o);h.setAttribute("href",g),h.setAttribute("download",t),h.style.visibility="hidden",document.body.appendChild(h),h.click(),document.body.removeChild(h)}}var xg=["--chart-text-color","--chart-font","--chart-annotation-font-size","--chart-grid-color","--chart-grid-opacity","--chart-bg","--chart-ref-line-color","--chart-ref-line-width","--chart-cursor-rule-color","--chart-cursor-rule-width","--chart-annotation-ring","--chart-primary-color","--chart-brush-fill","--chart-brush-stroke","--chart-brush-dim-opacity","--chart-legend-inactive-opacity","--chart-status-bar-color"];function _g(t,e){for(var r=getComputedStyle(e),i={},s=0;s-1&&i.indexOf(o)===-1,kind:s.type}})}}function m9(t){var e=t.colorContinuous||t.derived&&t.derived.colorContinuous;return{type:"continuous",items:[],colorScale:e||null,domain:e&&typeof e.domain=="function"?e.domain():null}}var Nu=16,id=12,Sg=6,g9=18,y9=6,Dh=12,Eg=14,Xm=180;function v2(t){var e=t.svg&&t.svg.node?t.svg.node():null;if(e&&e.querySelector&&e.querySelector(".myIO-inline-legend"))return{extraHeight:0,cleanup:function(){}};var r=nd(t,t.runtime&&t.runtime._legendState);if(!r||!r.type)return{extraHeight:0,cleanup:function(){}};var i=r.items?r.items.filter(function(O){return O.visible!==!1}):[];if(r.type!=="continuous"&&i.length===0)return{extraHeight:0,cleanup:function(){}};var s=t.svg.node(),o=parseFloat(s.getAttribute("width"))||t.totalWidth||t.width,h=parseFloat(s.getAttribute("height"))||t.height,g=s.getAttribute("viewBox"),v=_9(t),x=document.createElementNS("http://www.w3.org/2000/svg","g");x.setAttribute("class","myIO-export-legend");var _;r.type==="continuous"?_=v9(x,r,o,v):_=b9(x,i,o,v),x.setAttribute("transform","translate(0,"+h+")");var A=h+_;return s.appendChild(x),s.setAttribute("height",A),s.setAttribute("viewBox","0 0 "+o+" "+A),{extraHeight:_,cleanup:function(){s.removeChild(x),s.setAttribute("height",h),s.setAttribute("viewBox",g)}}}function b9(t,e,r,i){var s=r-Nu*2,o=Nu,h=Nu,g=Math.max(id,Dh);return e.forEach(function(v){var x=x9(v.label,Dh),_=id+Sg+x;o+_>Nu+s&&o>Nu&&(o=Nu,h+=g+y9);var A=document.createElementNS("http://www.w3.org/2000/svg","rect");A.setAttribute("x",o),A.setAttribute("y",h),A.setAttribute("width",id),A.setAttribute("height",id),A.setAttribute("rx",2),A.setAttribute("fill",v.color||"#6b7280"),t.appendChild(A);var O=document.createElementNS("http://www.w3.org/2000/svg","text");O.setAttribute("x",o+id+Sg),O.setAttribute("y",h+id-1),O.setAttribute("font-family","Roboto, Arial, sans-serif"),O.setAttribute("font-size",Dh),O.setAttribute("fill",i),O.textContent=v.label,t.appendChild(O),o+=_+g9}),h+g+Nu}function v9(t,e,r,i){var s=e.colorScale;if(!s)return 0;var o=e.domain||s.domain(),h=Nu,g=(r-Xm)/2,v=document.createElementNS("http://www.w3.org/2000/svg","defs"),x=document.createElementNS("http://www.w3.org/2000/svg","linearGradient"),_="export-legend-grad-"+Date.now();x.setAttribute("id",_);for(var A=8,O=o[0],I=o[o.length-1],Y=0;Y"u"||!/MSIE [1-9]\./.test(navigator.userAgent)){var e=t.document,r=function(){return t.URL||t.webkitURL||t},i=e.createElementNS("http://www.w3.org/1999/xhtml","a"),s="download"in i,o=function(re){var q=new MouseEvent("click");re.dispatchEvent(q)},h=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),g=t.webkitRequestFileSystem,v=t.requestFileSystem||g||t.mozRequestFileSystem,x=function(re){(t.setImmediate||t.setTimeout)(function(){throw re},0)},_="application/octet-stream",A=0,O=4e4,I=function(re){var q=function(){typeof re=="string"?r().revokeObjectURL(re):re.remove()};setTimeout(q,O)},Y=function(re,q,ue){q=[].concat(q);for(var J=q.length;J--;){var k=re["on"+q[J]];if(typeof k=="function")try{k.call(re,ue||re)}catch(de){x(de)}}},K=function(re){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(re.type)?new Blob(["\uFEFF",re],{type:re.type}):re},ee=function(re,q,ue){ue||(re=K(re));var J,k,de,ze=this,er=re.type,Er=!1,Ht=function(){Y(ze,"writestart progress write writeend".split(" "))},xn=function(){if(k&&h&&typeof FileReader<"u"){var In=new FileReader;return In.onloadend=function(){var bn=In.result;k.location.href="data:attachment/file"+bn.slice(bn.search(/[,;]/)),ze.readyState=ze.DONE,Ht()},In.readAsDataURL(re),void(ze.readyState=ze.INIT)}if((Er||!J)&&(J=r().createObjectURL(re)),k)k.location.href=J;else{var cr=t.open(J,"_blank");cr===void 0&&h&&(t.location.href=J)}ze.readyState=ze.DONE,Ht(),I(J)},$r=function(In){return function(){return ze.readyState!==ze.DONE?In.apply(this,arguments):void 0}},Tn={create:!0,exclusive:!1};return ze.readyState=ze.INIT,q||(q="download"),s?(J=r().createObjectURL(re),void setTimeout(function(){i.href=J,i.download=q,o(i),Ht(),I(J),ze.readyState=ze.DONE})):(t.chrome&&er&&er!==_&&(de=re.slice||re.webkitSlice,re=de.call(re,0,re.size,_),Er=!0),g&&q!=="download"&&(q+=".download"),(er===_||g)&&(k=t),v?(A+=re.size,void v(t.TEMPORARY,A,$r(function(In){In.root.getDirectory("saved",Tn,$r(function(cr){var bn=function(){cr.getFile(q,Tn,$r(function(mn){mn.createWriter($r(function(qn){qn.onwriteend=function(Wt){k.location.href=mn.toURL(),ze.readyState=ze.DONE,Y(ze,"writeend",Wt),I(mn)},qn.onerror=function(){var Wt=qn.error;Wt.code!==Wt.ABORT_ERR&&xn()},"writestart progress write abort".split(" ").forEach(function(Wt){qn["on"+Wt]=ze["on"+Wt]}),qn.write(re),ze.abort=function(){qn.abort(),ze.readyState=ze.DONE},ze.readyState=ze.WRITING}),xn)}),xn)};cr.getFile(q,{create:!1},$r(function(mn){mn.remove(),bn()}),$r(function(mn){mn.code===mn.NOT_FOUND_ERR?bn():xn()}))}),xn)}),xn)):void xn())},oe=ee.prototype,se=function(re,q,ue){return new ee(re,q,ue)};return typeof navigator<"u"&&navigator.msSaveOrOpenBlob?function(re,q,ue){return ue||(re=K(re)),navigator.msSaveOrOpenBlob(re,q||"download")}:(oe.abort=function(){var re=this;re.readyState=re.DONE,Y(re,"abort")},oe.readyState=oe.INIT=0,oe.WRITING=1,oe.DONE=2,oe.error=oe.onwritestart=oe.onprogress=oe.onwrite=oe.onabort=oe.onerror=oe.onwriteend=null,se)}})(typeof self<"u"&&self||typeof window<"u"&&window||(void 0).content);var sd=null;function wg(){return window.jspdf&&window.jspdf.jsPDF?Promise.resolve(window.jspdf.jsPDF):sd||(sd=new Promise(function(t,e){for(var r=document.querySelectorAll("script[src]"),i=null,s=0;sh?"landscape":"portrait",I=O==="landscape"?842:595,Y=O==="landscape"?595:842,K=36,ee=I-2*K,oe=Y-2*K,se=Math.min(ee/o,oe/h),re=o*se,q=h*se,ue=new e({orientation:O,unit:"pt",format:[I,Y]}),J=t.config.export&&t.config.export.title||t.config.axes&&t.config.axes.xAxisLabel||"myIO Chart";ue.setProperties({title:J,creator:"myIO"});var k=(I-re)/2,de=(Y-q)/2;ue.addImage(A,"PNG",k,de,re,q),ue.save(t.element.id+".pdf"),v(!0)},_.readAsDataURL(x)})})})}async function Tg(t){var e=v2(t),r=b2(t.svg.node());e.cleanup();try{if(navigator.clipboard&&navigator.clipboard.write&&typeof ClipboardItem<"u"){var i=new Blob([r],{type:"image/svg+xml"}),s=new Blob([r],{type:"text/html"});await navigator.clipboard.write([new ClipboardItem({"text/html":s,"image/svg+xml":i})])}else await navigator.clipboard.writeText(r);return!0}catch(o){return console.warn("[myIO] Clipboard copy failed",o),!1}}async function Ig(t){var e=v2(t),r=t.height+e.extraHeight,i=b2(t.svg.node());e.cleanup();var s=(t.totalWidth||t.width)*2,o=r*2;return new Promise(function(h){rd(i,s,o,"png",function(g){navigator.clipboard&&navigator.clipboard.write&&typeof ClipboardItem<"u"?navigator.clipboard.write([new ClipboardItem({"image/png":g})]).then(function(){h(!0)}).catch(function(){h(!1)}):h(!1)})})}var Du={chart:"Download data",image:"Save image",svg:"Save as SVG",pdf:"Export as PDF",clipboard:"Copy to clipboard","clipboard-png":"Copy as PNG","clipboard-svg":"Copy as SVG",percent:"Toggle percent",group2stack:"Toggle layout"};function Jm(t,e,r){if(r==="image"){var i=v2(t),s=t.height+i.extraHeight,o=b2(t.svg.node());i.cleanup(),rd(o,2*t.width,2*s,"png",function(O){w0(O,t.element.id+".png")});return}if(r==="svg"){var h=v2(t),g=b2(t.svg.node());h.cleanup();var v=new Blob([g],{type:"image/svg+xml;charset=utf-8"});w0(v,t.element.id+".svg");return}if(r==="chart"){var x=[],_=t.runtime._brushed;_&&_.data.length>0&&t.config.interactions.brush&&t.config.interactions.brush.onSelect==="export"?x.push(_.data):t.plotLayers.forEach(function(O){x.push(O.data)}),E0(t.element.id+"_data.csv",[].concat.apply([],x));return}if(r==="pdf"){Ag(t);return}if(r==="clipboard"||r==="clipboard-png"){Ig(t);return}if(r==="clipboard-svg"){Tg(t);return}if(r==="percent"){var A=t.runtime.activeY===t.options.toggleY[0]?[t.plotLayers[0].mapping.y_var,t.options.yAxisFormat]:t.options.toggleY;t.toggleVarY(A);return}r==="group2stack"&&t.toggleGroupedLayout(e)}function Vf(t){return'"}function Og(){return Vf('')}function Cg(){return Vf('')}function Lg(){return Vf('')}function Km(){return Vf('')}function Ng(){return Vf('PDF')}function Qm(){return Vf('')}function Zm(){return Vf('')}var kg="myIO-panel--open",Mg="myIO-sheet-backdrop--open",S9="myIO-panel--bottom",E9="myIO-panel--side";function e6(t){if(!t||!t.element||(d3.select(t.element).select(".myIO-fab").remove(),R9(t)))return null;t.dom=t.dom||{};var e=d3.select(t.element).append("button").attr("type","button").attr("class","myIO-fab").attr("aria-label","Legend and actions").attr("aria-expanded","false").html(Km());return e.on("click",function(){A0(t)}),e.on("keydown",function(r){(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),A0(t))}),t.dom.fab=e,T0(t),e}function A0(t){if(!t||!t.element)return null;if(t.dom=t.dom||{},t.runtime=t.runtime||{},t.runtime._sheetCloseTimer&&(clearTimeout(t.runtime._sheetCloseTimer),t.runtime._sheetCloseTimer=null),t.runtime._sheetOpen)return t.dom.panel||null;$g(t);var e=d3.select(t.element).append("div").attr("class","myIO-sheet-backdrop").attr("aria-hidden","true").on("click",function(){Ru(t)}),r=d3.select(t.element).append("div").attr("class","myIO-panel "+(Y3(t)?S9:E9)).attr("role","dialog").attr("aria-modal","true").attr("aria-label",k9(t)).attr("tabindex","-1"),i=r.append("div").attr("class","myIO-sheet-header");if(i.append("div").attr("class","myIO-sheet-handle"),i.append("button").attr("type","button").attr("class","myIO-sheet-close").attr("aria-label","Close").html(Ug()).on("click",function(){Ru(t)}).on("keydown",function(o){(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),Ru(t))}),t.dom.backdrop=e,t.dom.panel=r,t.dom.sheetLegendSection=null,t.dom.sheetLegendBody=null,t.dom.sheetActionsBody=null,!t.options||t.options.suppressLegend!==!0){var s=r.append("div").attr("class","myIO-sheet-legend-section").attr("data-sheet-section","legend");t.dom.sheetLegendSection=s,t.dom.sheetLegendBody=s.append("div").attr("class","myIO-sheet-legend"),s.append("hr").attr("class","myIO-sheet-divider")}return t.dom.sheetActionsBody=r.append("div").attr("class","myIO-sheet-actions").attr("data-sheet-section","actions"),ad(t),w9(t),t.runtime._sheetOpen=!0,D9(t),T0(t),window.requestAnimationFrame(function(){e.classed(Mg,!0),r.classed(kg,!0),M9(r.node())}),L9(t),r}function Ru(t,e){if(!(!t||!t.dom)){var r=e||{};t.runtime||(t.runtime={}),t.runtime._sheetCloseTimer&&(clearTimeout(t.runtime._sheetCloseTimer),t.runtime._sheetCloseTimer=null),t.dom.backdrop&&t.dom.backdrop.classed(Mg,!1),t.dom.panel&&t.dom.panel.classed(kg,!1),Fg(t),t.runtime._sheetOpen=!1,T0(t);var i=function(){$g(t),t.runtime._sheetCloseTimer=null,T0(t),r.returnFocus!==!1&&t.dom.fab&&typeof t.dom.fab.node=="function"&&t.dom.fab.node()&&t.dom.fab.node().focus()};if(window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches){i();return}var s=t.dom.panel&&t.dom.panel.node?t.dom.panel.node():null,o=t.dom.backdrop&&t.dom.backdrop.node?t.dom.backdrop.node():null;if(!s||!o){i();return}var h=!1,g=function(){h||(h=!0,i())};s.addEventListener("transitionend",g,{once:!0}),o.addEventListener("transitionend",g,{once:!0}),t.runtime._sheetCloseTimer=window.setTimeout(g,350)}}function ad(t){if(!(!t||!t.dom||!t.dom.panel)){var e=t.dom.sheetLegendBody,r=t.dom.sheetLegendSection;if(e){var i=t.dom.panel.node(),s=i?i.scrollTop:0,o=N9(t);if(e.selectAll("*").remove(),r&&r.selectAll(".myIO-sheet-legend-reset").remove(),!o||!o.type){r&&r.style("display","none"),i&&(i.scrollTop=s);return}r&&r.style("display",null),o.type==="continuous"?I9(t,e,o):o.type==="ordinal"?T9(t,e,o):A9(t,e,o),i&&(i.scrollTop=s)}}}function w9(t){if(!(!t.dom||!t.dom.sheetActionsBody)){var e=O9(t),r=t.dom.sheetActionsBody;r.selectAll("*").remove(),e.forEach(function(i){var s=r.append("button").attr("type","button").attr("class","myIO-sheet-action").attr("data-action",i.name).on("click",function(){Jm(t,t.currentLayers||t.derived&&t.derived.currentLayers||t.plotLayers||[],i.name)}).on("keydown",function(o){(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),Jm(t,t.currentLayers||t.derived&&t.derived.currentLayers||t.plotLayers||[],i.name))});s.append("span").attr("class","myIO-sheet-action-icon").attr("aria-hidden","true").html(i.icon),s.append("span").attr("class","myIO-sheet-action-label").text(i.label)})}}function A9(t,e,r){var i=Y3(t)&&r.items.length>4;e.classed("myIO-sheet-legend--grid",i),r.items.forEach(function(s){var o=e.append("button").attr("type","button").attr("class","myIO-sheet-legend-item").attr("role","switch").attr("aria-checked",s.visible?"true":"false").attr("data-key",s.key).on("click",function(){Dg(t,s)}).on("keydown",function(h){(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),Dg(t,s))});o.append("span").attr("class","myIO-sheet-swatch").style("background-color",s.color),o.append("span").attr("class","myIO-sheet-legend-label").text(s.label)}),Bg(t,r)}function T9(t,e,r){var i=Y3(t)&&r.items.length>4;e.classed("myIO-sheet-legend--grid",i),r.items.forEach(function(s){var o=e.append("button").attr("type","button").attr("class","myIO-sheet-legend-item").attr("role","switch").attr("aria-checked",s.visible?"true":"false").attr("data-key",s.key).on("click",function(){Rg(t,s)}).on("keydown",function(h){(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),Rg(t,s))});o.append("span").attr("class","myIO-sheet-swatch").style("background-color",s.color),o.append("span").attr("class","myIO-sheet-legend-label").text(s.label)}),Bg(t,r)}function I9(t,e,r){var i=r.colorScale||t.colorContinuous;if(i){var s=r.domain||i.domain(),o=B9(i,s),h=F9(i,s);e.append("div").attr("class","myIO-sheet-gradient").style("background","linear-gradient(90deg, "+o+")");var g=e.append("div").attr("class","myIO-sheet-gradient-ticks");h.forEach(function(v){g.append("span").text(v)})}}function O9(t){var e=t.currentLayers||t.derived&&t.derived.currentLayers||t.plotLayers||[],r=e[0]?e[0].type:null,i=t.config&&t.config.export,s=[];return(!i||i.csv!==!1)&&s.push({name:"chart",label:Du.chart,icon:Zm()}),(!i||i.png!==!1)&&s.push({name:"image",label:Du.image,icon:Og()}),(!i||i.svg!==!1)&&s.push({name:"svg",label:Du.svg,icon:Zm()}),(!i||i.pdf!==!1)&&s.push({name:"pdf",label:Du.pdf,icon:Ng()}),(!i||i.clipboard!==!1)&&(s.push({name:"clipboard-png",label:Du["clipboard-png"],icon:Qm()}),s.push({name:"clipboard-svg",label:Du["clipboard-svg"],icon:Qm()})),t.options&&t.options.toggleY&&s.push({name:"percent",label:Du.percent,icon:Cg()}),t.options&&t.options.toggleY&&r==="groupedBar"&&s.push({name:"group2stack",label:Du.group2stack,icon:Lg()}),s}function Dg(t,e){t.runtime||(t.runtime={});var r=Array.isArray(t.runtime._hiddenLayerKeys)?t.runtime._hiddenLayerKeys.slice():[],i=r.indexOf(e.key);i===-1?r.push(e.key):r.splice(i,1),t.runtime._hiddenLayerKeys=r,t.derived=t.derived||{},t.derived.currentLayers=(t.plotLayers||[]).filter(function(s){return r.indexOf(s._composite||s.label)===-1}),t.syncLegacyAliases(),t.renderCurrentLayers()}function Rg(t,e){t.runtime||(t.runtime={}),Array.isArray(t.runtime._hiddenOrdinalSegments)||(t.runtime._hiddenOrdinalSegments=[]);var r=t.runtime._hiddenOrdinalSegments,i=r.indexOf(e.key);i===-1?r.push(e.key):r.splice(i,1),t.runtime._suppressOrdinalLegendRebuild=!0;try{t.routeLayers(t.currentLayers||t.derived&&t.derived.currentLayers||[])}finally{t.runtime._suppressOrdinalLegendRebuild=!1}ad(t)}function Bg(t,e){var r=e.items.some(function(i){return!i.visible});r&&t.dom.sheetLegendSection&&(t.dom.sheetLegendSection.selectAll(".myIO-sheet-legend-reset").remove(),t.dom.sheetLegendSection.append("button").attr("type","button").attr("class","myIO-sheet-legend-reset").text("Show All").on("click",function(){C9(t,e.type)}))}function C9(t,e){if(t.runtime=t.runtime||{},e==="ordinal"){t.runtime._hiddenOrdinalSegments=[],t.runtime._suppressOrdinalLegendRebuild=!0;try{t.routeLayers(t.currentLayers||t.derived&&t.derived.currentLayers||[])}finally{t.runtime._suppressOrdinalLegendRebuild=!1}ad(t)}else t.runtime._hiddenLayerKeys=[],t.derived=t.derived||{},t.derived.currentLayers=(t.plotLayers||[]).slice(),t.syncLegacyAliases(),t.renderCurrentLayers()}function L9(t){var e=t.dom.panel;if(!(!e||!Y3(t))){var r=e.node(),i=0,s=0,o=!1;r.addEventListener("touchstart",function(h){var g=r.getBoundingClientRect(),v=h.touches[0];v.clientY-g.top>40||(i=v.clientY,s=v.clientY,o=!0,r.style.transition="none")},{passive:!0}),r.addEventListener("touchmove",function(h){if(o){s=h.touches[0].clientY;var g=Math.max(0,s-i);r.style.transform="translateY("+g+"px)"}},{passive:!0}),r.addEventListener("touchend",function(){if(o){o=!1,r.style.transition="";var h=s-i;h>80?Ru(t):r.style.transform=""}})}}function N9(t){return t.runtime&&t.runtime._legendData?t.runtime._legendData:nd(t,t.runtime&&t.runtime._legendState)}function T0(t){if(!(!t||!t.dom||!t.dom.fab)){var e=t.runtime&&t.runtime._sheetOpen===!0;t.dom.fab.attr("aria-expanded",e?"true":"false").attr("aria-label",e?"Close legend and actions":"Legend and actions").html(e?Ug():Km())}}function D9(t){Fg(t);var e=function(r){if(!(!t.runtime||!t.runtime._sheetOpen||!t.dom||!t.dom.panel)){if(r.key==="Escape"){r.preventDefault(),Ru(t);return}if(r.key==="Tab"){var i=Pg(t.dom.panel.node());if(i.length===0){r.preventDefault(),t.dom.panel.node().focus();return}var s=i[0],o=i[i.length-1],h=document.activeElement;r.shiftKey&&h===s?(r.preventDefault(),o.focus()):!r.shiftKey&&h===o&&(r.preventDefault(),s.focus())}}};t.runtime._sheetEscHandler=e,document.addEventListener("keydown",e)}function Fg(t){!t||!t.runtime||!t.runtime._sheetEscHandler||(document.removeEventListener("keydown",t.runtime._sheetEscHandler),t.runtime._sheetEscHandler=null)}function $g(t){t.dom&&t.dom.panel&&typeof t.dom.panel.remove=="function"&&t.dom.panel.remove(),t.dom&&t.dom.backdrop&&typeof t.dom.backdrop.remove=="function"&&t.dom.backdrop.remove(),t.dom&&(t.dom.panel=null,t.dom.backdrop=null,t.dom.sheetLegendSection=null,t.dom.sheetLegendBody=null,t.dom.sheetActionsBody=null)}function R9(t){var e=t&&(t.currentLayers||t.derived&&t.derived.currentLayers||t.plotLayers||[]);return!e||e.length===0}function k9(t){if(t&&t.svg&&typeof t.svg.attr=="function"){var e=t.svg.attr("aria-label");if(e)return e+" controls"}return"Chart controls"}function M9(t){if(t){var e=Pg(t);if(e.length>0){e[0].focus();return}t.focus()}}function Pg(t){return t?Array.from(t.querySelectorAll(["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(","))):[]}function B9(t,e){var r=e[0],i=e[e.length-1],s=8;return Array.from({length:s},function(o,h){var g=s===1?0:h/(s-1),v=r+(i-r)*g;return t(v)+" "+Math.round(g*100)+"%"}).join(", ")}function F9(t,e){return typeof t.ticks=="function"?t.ticks(5).map(function(r){return String(r)}):[String(e[0]),String(e[e.length-1])]}function $9(t){return'"}function Ug(){return $9('')}function Vg(t,e){!t||!t.runtime||t.options&&t.options.suppressLegend===!0||(t.runtime._legendState=e||null,t.runtime._legendData=nd(t,e),Gg(t,t.runtime._legendData),t.runtime._sheetOpen&&ad(t))}function od(t,e){!t||!t.runtime||t.runtime._suppressOrdinalLegendRebuild||(t.runtime._legendState={ordinalLegend:!0},t.runtime._legendData=Ym(t,e),Gg(t,t.runtime._legendData),t.runtime._sheetOpen&&ad(t))}function Gg(t,e){if(!(!t||!t.svg)&&(t.svg.selectAll(".myIO-inline-legend").remove(),!(!e||!Array.isArray(e.items)||e.items.length<2||e.type==="continuous"))){var r=P9(e.items).slice(0,10);if(!(r.length<2)){var i=r.length>5?2:1,s=Math.max(34,t.height-8-(i-1)*16),o=t.svg.append("g").attr("class","myIO-inline-legend").attr("transform","translate("+t.margin.left+","+s+")"),h=[0,0];r.forEach(function(g,v){var x=String(g.label||g.key||""),_=v<5?0:1,A=o.append("g").attr("class","myIO-inline-legend-item").attr("transform","translate("+h[_]+","+_*16+")");A.append("rect").attr("width",10).attr("height",10).attr("rx",2).attr("y",-9).attr("fill",Array.isArray(g.color)?g.color[0]:g.color||"#6b7280").style("opacity",g.visible===!1?.35:1),A.append("text").attr("class","myIO-inline-legend-label").attr("x",15).attr("y",0).text(x.length>24?x.substring(0,21)+"...":x),h[_]+=Math.min(190,46+x.length*7)})}}}function P9(t){var e={};return t.filter(function(r){var i=r.key||r.label;return e[i]?!1:(e[i]=!0,!0)})}var ld=class{static type="treemap";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"none",scaleCapabilities:{invertX:!1}};static scaleHints=null;static dataContract={level_1:{required:!0},level_2:{required:!0},y_var:{required:!1,numeric:!0}};render(e,r){var i=e.margin,s=d3.format(",d"),o=r.label;if(Nh(e))e.colorDiscrete=d3.scaleOrdinal().range(e.options.colorScheme[0]).domain(e.options.colorScheme[1]),e.colorContinuous=d3.scaleLinear().range(e.options.colorScheme[0]).domain(e.options.colorScheme[1]);else{var h=r.data.children.map(function(I){return I.name});e.colorDiscrete=d3.scaleOrdinal().range(r.color).domain(h)}var g=d3.hierarchy(r.data).eachBefore(function(I){I.data.id=(I.parent?I.parent.data.id+".":"")+I.data.name}).sum(function(I){return I[r.mapping.y_var]}).sort(function(I,Y){return Y.height-I.height||Y.value-I.value});d3.treemap().tile(d3.treemapResquarify).size([e.width-(i.left+i.right),n1(e)-(i.top+i.bottom)]).round(!0).paddingInner(1)(g);var v=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0,x=e.chart.selectAll(".root").data(g.leaves(),function(I){return I.data.id});x.exit().transition().duration(v).style("opacity",0).remove();var _=x.enter().append("g").attr("class","root").attr("transform",function(I){return"translate("+I.x0+","+I.y0+")"}).style("opacity",0);_.append("rect").attr("class",xr("tree",e.element.id,o)).attr("id",function(I){return I.data.id}).attr("width",function(I){return I.x1-I.x0}).attr("height",function(I){return I.y1-I.y0}).attr("fill",function(I){for(;I.depth>1;)I=I.parent;return e.colorDiscrete(I.data.id)}),_.append("text").attr("class","inner-text").attr("fill","black"),_.append("title");var A=_.merge(x);A.transition().duration(v).ease(Mn(e,d3.easeQuad)).style("opacity",1).attr("transform",function(I){return"translate("+I.x0+","+I.y0+")"}),A.select("rect").transition().duration(v).ease(Mn(e,d3.easeQuad)).attr("width",function(I){return I.x1-I.x0}).attr("height",function(I){return I.y1-I.y0}).attr("fill",function(I){for(;I.depth>1;)I=I.parent;return e.colorDiscrete(I.data.id)});var O=A.select("text.inner-text").selectAll("tspan").data(function(I){return U9(I,r,s)});O.exit().remove(),O.enter().append("tspan").attr("fill","black").merge(O).attr("x",3).attr("y",function(I,Y,K){return(Y===K.length-1)*3+16+(Y-.5)*9}).attr("fill-opacity",function(){return V9(this.parentNode.parentNode)?1:0}).text(function(I){return I}),A.select("title").text(function(I){return I.data[r.mapping.level_1]+` `+I.data[r.mapping.level_2]+` `+I.data[r.mapping.x_var]+` -`+s(I.value)}),od(e,r)}remove(e){e.dom.chartArea.selectAll(".root").transition().duration(500).style("opacity",0).remove()}};function U9(t,e,r){var i=String(t.data[e.mapping.x_var]||t.data[e.mapping.level_2]||t.data.name||""),s=Math.max(0,t.x1-t.x0),o=s<70&&i.length>10?i.substring(0,9)+"...":i;return o.split(/\s+/).concat(r(t.value))}function V9(t){return!t||typeof t.getBBox!="function"?!0:t.getBBox().width>40}var cd=class{static type="donut";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"none",scaleCapabilities:{invertX:!1}};static scaleHints=null;static dataContract={x_var:{required:!0},y_var:{required:!0,numeric:!0}};render(e,r){var i=e.margin,s=e.options.transition.speed,o=Math.min(e.width-(i.right+i.left),e.height-(i.top+i.bottom))/2,h=r.mapping.x_var,g=r.mapping.y_var;Nh(e)?(e.colorDiscrete=d3.scaleOrdinal().range(e.options.colorScheme[0]).domain(e.options.colorScheme[1]),e.colorContinuous=d3.scaleLinear().range(e.options.colorScheme[0]).domain(e.options.colorScheme[1])):e.colorDiscrete=d3.scaleOrdinal().range(r.color).domain(r.data.map(function(q){return q[h]}));var v=e.runtime._hiddenOrdinalSegments||[],x=r.data.filter(function(q){return v.indexOf(q[h])===-1}),_=d3.pie().sort(null).value(function(q){return q[g]}),A=d3.arc().innerRadius(o*.8).outerRadius(o*.4),O=d3.arc().innerRadius(o*.9).outerRadius(o*.9),I=e.chart.selectAll(".donut").data(_(x),function(q){return q.data[h]});I.exit().transition().duration(s).ease(Mn(e,d3.easeQuad)).attrTween("d",function(q){var ue={startAngle:q.endAngle,endAngle:q.endAngle},J=d3.interpolate(q,ue);return function(k){return A(J(k))}}).remove();var Y=I.enter().append("path").attr("class","donut").attr("fill",function(q){return e.colorDiscrete(q.data[h])}).attr("d",A).each(function(q){this._current=q});I.merge(Y).transition().duration(s).ease(Mn(e,d3.easeQuad)).attr("fill",function(q){return e.colorDiscrete(q.data[h])}).attrTween("d",function(q){this._current=this._current||q;var ue=d3.interpolate(this._current,q);return this._current=ue(1),function(J){return A(ue(J))}});function K(q){return q.startAngle+(q.endAngle-q.startAngle)/2}var ee=e.chart.selectAll(".inner-text").data(_(x),function(q){return q.data[h]});ee.exit().transition().duration(s).style("opacity",0).remove();var oe=ee.enter().append("text").attr("class","inner-text").style("font-size","12px").style("opacity",0).attr("dy",".35em").text(function(q){return q.data[h]});ee.merge(oe).transition().duration(s).ease(Mn(e,d3.easeQuad)).text(function(q){return q.data[h]}).style("opacity",function(q){return Math.abs(q.endAngle-q.startAngle)>.3?1:0}).attrTween("transform",function(q){this._current=this._current||q;var ue=d3.interpolate(this._current,q);return this._current=ue(1),function(J){var k=ue(J),de=O.centroid(k);return de[0]=o*(K(k).3?1:0}).attrTween("points",function(q){this._current=this._current||q;var ue=d3.interpolate(this._current,q);return this._current=ue(1),function(J){var k=ue(J),de=O.centroid(k);return de[0]=o*.95*(K(k)0?r.data[0]:{},v=r.mapping.value,x=typeof v=="string"?+g[v]:+v;Number.isFinite(x)||(x=0),x=Math.max(0,Math.min(1,x));var _=[x,1-x],A=d3.arc().innerRadius(o-h).outerRadius(o).cornerRadius(10),O=d3.arc().innerRadius(o-h).outerRadius(o),I=d3.pie().sort(null).value(function(k){return k}).startAngle(s*-.5).endAngle(s*.5),Y=d3.format(".1%"),K=r.options&&Array.isArray(r.options.thresholds)?r.options.thresholds:[{min:0,max:.6,color:"#3CA951"},{min:.6,max:.85,color:"#FFB000"},{min:.85,max:1,color:"#EF603B"}];function ee(k){return O({startAngle:s*-.5+s*Math.max(0,Math.min(1,+k.min||0)),endAngle:s*-.5+s*Math.max(0,Math.min(1,+k.max||0))})}var oe=e.chart.selectAll(".myIO-gauge-threshold").data(K);oe.exit().transition().duration(i).style("opacity",0).remove();var se=oe.enter().append("path").attr("class","myIO-gauge-threshold").attr("fill",function(k){return k.color}).attr("opacity",0).attr("d",ee);se.merge(oe).transition().duration(i).ease(Mn(e,d3.easeQuad)).attr("fill",function(k){return k.color}).attr("opacity",.24).attr("d",ee);var re=e.chart.selectAll(".myIO-gauge-background").data(I([1]));re.exit().transition().duration(i).style("opacity",0).remove();var q=re.enter().append("path").attr("class","myIO-gauge-background").attr("fill","rgba(107, 114, 128, 0.22)").attr("d",A).each(function(k){this._current=k});q.merge(re).transition().duration(i).ease(Mn(e,d3.easeBack)).attr("fill","rgba(107, 114, 128, 0.22)").attrTween("d",function(k){this._current=this._current||k;var de=d3.interpolate(this._current,k);return this._current=de(1),function(ze){return A(de(ze))}});var ue=e.chart.selectAll(".myIO-gauge-value").data(I(_));ue.exit().transition().duration(i).style("opacity",0).remove();var J=ue.enter().append("path").attr("class","myIO-gauge-value").attr("fill",function(k,de){return[r.color||jg(x,K),"transparent"][de]}).attr("d",A).each(function(k){this._current=k});J.merge(ue).transition().duration(i).ease(Mn(e,d3.easeBack)).attr("fill",function(k,de){return[r.color||jg(x,K),"transparent"][de]}).attrTween("d",function(k){this._current=this._current||k;var de=d3.interpolate(this._current,k);return this._current=de(1),function(ze){return A(de(ze))}}),e.chart.selectAll(".gauge-text").data([_[0]]).join("text").attr("class","gauge-text").text(function(k){return Y(k)}).attr("text-anchor","middle").attr("font-size",20).attr("dy","-0.45em"),e.chart.selectAll(".gauge-label").data([r.options&&r.options.metric?r.options.metric:r.label]).join("text").attr("class","gauge-label").text(function(k){return k}).attr("text-anchor","middle").attr("font-size",12).attr("dy","1.1em"),e.chart.selectAll(".gauge-min-label").data(["0%"]).join("text").attr("class","gauge-min-label").text(function(k){return k}).attr("text-anchor","middle").attr("font-size",11).attr("x",-o+h/2).attr("y",12),e.chart.selectAll(".gauge-max-label").data(["100%"]).join("text").attr("class","gauge-max-label").text(function(k){return k}).attr("text-anchor","middle").attr("font-size",11).attr("x",o-h/2).attr("y",12)}remove(e){e.dom.chartArea.selectAll(".myIO-gauge-threshold, .myIO-gauge-background, .myIO-gauge-value, .gauge-text, .gauge-label, .gauge-min-label, .gauge-max-label").transition().duration(500).style("opacity",0).remove()}};function jg(t,e){var r=e.find(function(i){return t>=+i.min&&t<=+i.max});return r&&r.color?r.color:"#4269D0"}var fd=class{static type="heatmap";static traits={hasAxes:!0,referenceLines:!1,legendType:"continuous",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"band",yScaleType:"band",yExtentFields:["value"],domainMerge:"union"};static dataContract={x_var:{required:!0},y_var:{required:!0},value:{required:!0,numeric:!0}};render(e,r){var i=e.options.transition.speed,s=r.mapping.x_var,o=r.mapping.y_var,h=r.mapping.value,g=r.data.map(function(I){return+I[h]}),v=d3.extent(g.filter(function(I){return Number.isFinite(I)}));(!v||v[0]===void 0||v[1]===void 0)&&(v=[0,1]),e.derived.colorContinuous=d3.scaleSequential(d3.interpolateBlues).domain(v),e.colorContinuous=e.derived.colorContinuous;var x=e.chart.selectAll("."+xr("heatmap",e.element.id,r.label)).data(r.data);x.exit().transition().duration(i).style("opacity",0).remove();var _=e.xScale.bandwidth?e.xScale.bandwidth():0,A=e.yScale.bandwidth?e.yScale.bandwidth():0,O=x.enter().append("rect").attr("class",xr("heatmap",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").attr("x",function(I){return e.xScale(I[s])}).attr("y",function(I){return e.yScale(I[o])}).attr("width",_).attr("height",A).attr("fill",function(I){return e.colorContinuous(+I[h])}).style("opacity",0);x.merge(O).transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x",function(I){return e.xScale(I[s])}).attr("y",function(I){return e.yScale(I[o])}).attr("width",_).attr("height",A).attr("fill",function(I){return e.colorContinuous(+I[h])}).style("opacity",1)}getHoverSelector(e,r){return"."+xr("heatmap",e.dom.element.id,r.label)}formatTooltip(e,r,i){return{title:i.mapping.x_var+": "+r[i.mapping.x_var]+", "+i.mapping.y_var+": "+r[i.mapping.y_var],body:i.mapping.value+": "+r[i.mapping.value],color:e.colorContinuous?e.colorContinuous(+r[i.mapping.value]):i.color,label:i.label,value:r[i.mapping.value],raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("heatmap",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};var dd=class{static type="calendarHeatmap";static traits={hasAxes:!1,referenceLines:!1,legendType:"continuous",binning:!1,rolloverStyle:"element"};static dataContract={date:{required:!0},value:{required:!0,numeric:!0}};static scaleHints=null;getHoverSelector(){return".myIO-calendar-cell"}formatTooltip(e,r,i){var s=d3.utcFormat("%b %-d, %Y"),o=r.date instanceof Date?r.date:new Date((r[i.mapping.date]||"")+"T00:00:00Z"),h=r.value!=null?r.value:+r[i.mapping.value];return{title:s(o),body:i.label+": "+h,color:r.color||i.color,label:i.label,value:h,raw:r}}render(e,r){var i=r.options||{},s=i.weekStart==="monday"?1:0,o=i.showWeekdayLabels!==!1,h=r.mapping.date,g=r.mapping.value,v=(r.data||[]).map(function(ar){return{date:new Date(ar[h]+"T00:00:00Z"),value:+ar[g],raw:ar}}).filter(function(ar){return!isNaN(ar.date.getTime())}).sort(function(ar,Wi){return ar.date-Wi.date});if(v.length!==0){var x=v[0].date.getUTCFullYear(),_=new Date(Date.UTC(x,0,1)),A=new Date(Date.UTC(x,11,31)),O=function(ar){var Wi=ar.getUTCDay();return(Wi-s+7)%7},I=O(_),Y=function(ar){var Wi=Math.floor((ar-_)/864e5);return Math.floor((Wi+I)/7)},K=Y(A)+1,ee=e.margin||{top:0,right:0,bottom:0,left:0},oe=(e.width||0)-(ee.left||0)-(ee.right||0),se=(e.height||0)-(ee.top||0)-(ee.bottom||0),re=o?24:0,q=18,ue=Math.max(1,oe-re),J=Math.max(1,se-q),k=Math.max(4,Math.min(Math.floor(ue/K),Math.floor(J/7))),de=e.element&&typeof getComputedStyle=="function"?getComputedStyle(e.element):null,ze=de?de.getPropertyValue("--chart-calendar-cell-gap"):"",er=parseFloat(ze);isFinite(er)||(er=2);var Er=e.config&&e.config.axis&&e.config.axis.vlim,Ht=d3.max(v,function(ar){return ar.value});Ht>0||(Ht=1);var xn=Er&&Er.max!==void 0&&Er.max!==null?[Er.min||0,Er.max]:[0,Ht],$r=d3.interpolateRgb("#ffffff",r.color||"#4E79A7"),Tn=d3.scaleSequential($r).domain(xn);e.colorContinuous=Tn,e.derived&&(e.derived.colorContinuous=Tn);var In=function(ar){var Wi=ar instanceof Date?ar:new Date(ar);return re+Y(Wi)*(k+er)};In.domain=function(){return[_,A]},In.range=function(){return[re,re+(K-1)*(k+er)]},In.invert=function(ar){var Wi=Math.round((ar-re)/(k+er)),Gs=Wi*7-I;return new Date(_.getTime()+Gs*864e5)},e.xScale=In;var cr=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0,bn=e.chart.selectAll(".myIO-calendar-root").data([null]).join("g").attr("class","myIO-calendar-root");if(o){var mn=s===0?["","Mon","","Wed","","Fri",""]:["","Tue","","Thu","","Sat",""],qn=mn.map(function(ar,Wi){return{t:ar,i:Wi}}).filter(function(ar){return ar.t}),Wt=bn.selectAll("text.myIO-calendar-dow").data(qn,function(ar){return ar.i});Wt.exit().remove(),Wt.enter().append("text").attr("class","myIO-calendar-dow").attr("x",0).merge(Wt).attr("y",function(ar){return q+ar.i*(k+er)+k*.75}).text(function(ar){return ar.t})}else bn.selectAll("text.myIO-calendar-dow").remove();var Pr=d3.utcFormat("%b"),hi=d3.range(12).map(function(ar){var Wi=new Date(Date.UTC(x,ar,1));return{m:ar,text:Pr(Wi),col:Y(Wi)}}),Ai=bn.selectAll("text.myIO-calendar-month").data(hi,function(ar){return ar.m});Ai.exit().remove(),Ai.enter().append("text").attr("class","myIO-calendar-month").attr("y",q-4).merge(Ai).attr("x",function(ar){return re+ar.col*(k+er)}).text(function(ar){return ar.text});var pi=function(ar){return ar.date.toISOString().slice(0,10)},ss=bn.selectAll("rect.myIO-calendar-cell").data(v,function(ar){return pi(ar)});ss.exit().transition().duration(cr).style("opacity",0).remove();var Va=ss.enter().append("rect").attr("class","myIO-calendar-cell").attr("data-date",pi).attr("data-row",function(ar){return String(O(ar.date))}).attr("data-col",function(ar){return String(Y(ar.date))}).attr("x",function(ar){return re+Y(ar.date)*(k+er)}).attr("y",function(ar){return q+O(ar.date)*(k+er)}).attr("width",k).attr("height",k).attr("fill",function(ar){return ar.value==null||isNaN(ar.value)||ar.value===0?"var(--chart-calendar-empty-fill, #ebedf0)":Tn(ar.value)}).style("opacity",0);Va.merge(ss).each(function(ar){ar.label=r.label,ar.color=ar.value==null||isNaN(ar.value)||ar.value===0?"var(--chart-calendar-empty-fill, #ebedf0)":Tn(ar.value),ar[h]=pi({date:ar.date}),ar[g]=ar.value}).transition().duration(cr).style("opacity",1).attr("x",function(ar){return re+Y(ar.date)*(k+er)}).attr("y",function(ar){return q+O(ar.date)*(k+er)}).attr("width",k).attr("height",k).attr("fill",function(ar){return ar.value==null||isNaN(ar.value)||ar.value===0?"var(--chart-calendar-empty-fill, #ebedf0)":Tn(ar.value)})}}remove(e){e&&e.chart&&typeof e.chart.selectAll=="function"&&e.chart.selectAll(".myIO-calendar-root").remove()}};var hd=class{static type="candlestick";static traits={hasAxes:!0,referenceLines:!0,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"linear",yScaleType:"linear",yExtentFields:["open","high","low","close"],domainMerge:"union"};static dataContract={x_var:{required:!0,numeric:!0},open:{required:!0,numeric:!0},high:{required:!0,numeric:!0},low:{required:!0,numeric:!0},close:{required:!0,numeric:!0}};render(e,r){var i=e.options.transition.speed,s=r.mapping.x_var,o=r.mapping.open,h=r.mapping.high,g=r.mapping.low,v=r.mapping.close,x=e.width-(e.margin.left+e.margin.right),_=Math.max(6,Math.min(40,x/Math.max(r.data.length*2.5,1))),A=this;function O(q){return e.xScale(q[s])}function I(q){return+q[v]>=+q[o]?"#4CAF50":"#F44336"}function Y(q){return e.yScale(Math.max(+q[o],+q[v]))}function K(q){return Math.max(Math.abs(e.yScale(+q[o])-e.yScale(+q[v])),1)}function ee(q){return e.yScale((+q[o]+ +q[v])/2)}var oe=e.chart.selectAll("."+xr("candlestick",e.element.id,r.label)).data(r.data);oe.exit().transition().duration(i).style("opacity",0).remove();var se=oe.enter().append("g").attr("class",xr("candlestick",e.element.id,r.label)).style("opacity",0);se.append("line").attr("class","wick").attr("stroke","#666").attr("stroke-width",1.5).attr("x1",O).attr("x2",O).attr("y1",ee).attr("y2",ee),se.append("rect").attr("class","body").attr("stroke-width",.5).attr("x",function(q){return O(q)-_/2}).attr("y",ee).attr("width",_).attr("height",0).attr("fill",I).attr("stroke",I);var re=oe.merge(se);re.transition().ease(Mn(e,d3.easeQuad)).duration(i).style("opacity",1),re.select("line.wick").transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x1",O).attr("x2",O).attr("y1",function(q){return e.yScale(+q[g])}).attr("y2",function(q){return e.yScale(+q[h])}),re.select("rect.body").transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x",function(q){return O(q)-_/2}).attr("y",Y).attr("width",_).attr("height",K).attr("fill",I).attr("stroke",I)}getHoverSelector(e,r){return"."+xr("candlestick",e.dom.element.id,r.label)}formatTooltip(e,r,i){return{title:i.mapping.x_var+": "+r[i.mapping.x_var],body:"O: "+r[i.mapping.open]+", H: "+r[i.mapping.high]+", L: "+r[i.mapping.low]+", C: "+r[i.mapping.close],color:r[i.mapping.close]>=r[i.mapping.open]?"#4CAF50":"#F44336",label:i.label,value:r[i.mapping.close],raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("candlestick",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};var pd=class{static type="waterfall";static traits={hasAxes:!0,referenceLines:!0,legendType:"none",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"band",yScaleType:"linear",yExtentFields:["_base_y","_cumulative_y"],domainMerge:"union"};static dataContract={x_var:{required:!0},y_var:{required:!0,numeric:!0}};render(e,r){var i=e.options.transition.speed,s=r.mapping.x_var,o=r.mapping.y_var,h=e.xScale.bandwidth?e.xScale.bandwidth():0,g=h*.82,v=(h-g)/2,x=Array.isArray(r.color),_=e.chart.selectAll("."+xr("waterfall",e.element.id,r.label)).data(r.data);_.exit().transition().duration(i).style("opacity",0).remove();var A=_.enter().append("rect").attr("class",xr("waterfall",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").attr("x",function(K){return e.xScale(K[s])+v}).attr("width",g).attr("y",function(K){return e.yScale(+K._base_y)}).attr("height",0).attr("fill",function(K,ee){return x?r.color[ee%r.color.length]:K._is_total?"#888":+K._cumulative_y>=+K._base_y?"#4CAF50":"#F44336"});_.merge(A).transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x",function(K){return e.xScale(K[s])+v}).attr("width",g).attr("y",function(K){return e.yScale(Math.max(+K._base_y,+K._cumulative_y))}).attr("height",function(K){return Math.abs(e.yScale(+K._base_y)-e.yScale(+K._cumulative_y))}).attr("fill",function(K,ee){return x?r.color[ee%r.color.length]:K._is_total?"#888":+K._cumulative_y>=+K._base_y?"#4CAF50":"#F44336"});var O=r.data.slice(0,Math.max(r.data.length-1,0)),I=e.chart.selectAll("."+xr("waterfall-connector",e.element.id,r.label)).data(O);I.exit().transition().duration(i).style("opacity",0).remove();var Y=I.enter().append("line").attr("class",xr("waterfall-connector",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").style("stroke","#374151").style("stroke-width",1.5).style("stroke-dasharray","4 2").attr("x1",function(K,ee){return e.xScale(r.data[ee][s])+v+g}).attr("x2",function(K,ee){return e.xScale(r.data[ee+1][s])+v}).attr("y1",function(K){return e.yScale(+K._cumulative_y)}).attr("y2",function(K){return e.yScale(+K._cumulative_y)}).style("opacity",0);I.merge(Y).transition().ease(Mn(e,d3.easeQuad)).duration(i).style("opacity",1).attr("x1",function(K,ee){return e.xScale(r.data[ee][s])+v+g}).attr("x2",function(K,ee){return e.xScale(r.data[ee+1][s])+v}).attr("y1",function(K){return e.yScale(+K._cumulative_y)}).attr("y2",function(K){return e.yScale(+K._cumulative_y)})}formatTooltip(e,r,i){return{title:i.mapping.x_var+": "+r[i.mapping.x_var],body:"Delta: "+r[i.mapping.y_var]+", Total: "+r._cumulative_y,color:r._is_total?"#888":+r._cumulative_y>=+r._base_y?"#4CAF50":"#F44336",label:i.label,value:r._cumulative_y,raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("waterfall",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove(),e.dom.chartArea.selectAll("."+xr("waterfall-connector",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};var md=class{static type="sankey";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints=null;static dataContract={source:{required:!0},target:{required:!0},value:{required:!0,numeric:!0}};render(e,r){var i=e.margin,s=e.width-(i.left+i.right),o=n1(e)-(i.top+i.bottom),h=18,g=d3.sankey().nodeId(function(se){return se.name}).nodeWidth(h).nodePadding(12).extent([[0,0],[s,o]]),v=new Map,x=r.data.map(function(se){var re=se[r.mapping.source],q=se[r.mapping.target];return v.has(re)||v.set(re,{name:re}),v.has(q)||v.set(q,{name:q}),{source:re,target:q,value:+se[r.mapping.value]}}),_=g({nodes:Array.from(v.values()),links:x});e.derived.colorDiscrete=d3.scaleOrdinal().domain(_.nodes.map(function(se){return se.name})).range(r.color||d3.schemeTableau10),e.colorDiscrete=e.derived.colorDiscrete;var A=e.chart.selectAll("."+xr("sankey",e.element.id,r.label)).data(_.links);A.exit().transition().duration(e.options.transition.speed).style("opacity",0).remove();var O=A.enter().append("path").attr("class",xr("sankey",e.element.id,r.label)).attr("fill","none").attr("stroke-opacity",.4).attr("clip-path","url(#"+e.element.id+"clip)").attr("d",d3.sankeyLinkHorizontal()).attr("stroke-width",function(se){return Math.max(1,se.width)}).attr("stroke",function(se){return e.colorDiscrete(se.source.name)}).style("opacity",0);A.merge(O).transition().ease(Mn(e,d3.easeQuad)).duration(e.options.transition.speed).style("opacity",1).attr("d",d3.sankeyLinkHorizontal()).attr("stroke-width",function(se){return Math.max(1,se.width)}).attr("stroke",function(se){return e.colorDiscrete(se.source.name)});var I=e.chart.selectAll("."+xr("sankey-node",e.element.id,r.label)).data(_.nodes);I.exit().transition().duration(e.options.transition.speed).style("opacity",0).remove();var Y=I.enter().append("rect").attr("class",xr("sankey-node",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").attr("x",function(se){return se.x0}).attr("y",function(se){return se.y0}).attr("width",function(se){return se.x1-se.x0}).attr("height",function(se){return Math.max(1,se.y1-se.y0)}).attr("fill",function(se){return e.colorDiscrete(se.name)}).style("opacity",0);I.merge(Y).transition().ease(Mn(e,d3.easeQuad)).duration(e.options.transition.speed).style("opacity",1).attr("x",function(se){return se.x0}).attr("y",function(se){return se.y0}).attr("width",function(se){return se.x1-se.x0}).attr("height",function(se){return Math.max(1,se.y1-se.y0)}).attr("fill",function(se){return e.colorDiscrete(se.name)});var K=xr("sankey-label",e.element.id,r.label),ee=e.chart.selectAll("."+K).data(_.nodes,function(se){return se.name});ee.exit().transition().duration(e.options.transition.speed).style("opacity",0).remove();var oe=ee.enter().append("text").attr("class",K).attr("x",function(se){return se.x0 "+r.target.name,body:"Value: "+r.value,color:e.colorDiscrete?e.colorDiscrete(r.source.name):i.color,label:i.label,value:r.value,raw:r}:{title:r.name,body:"Value: "+r.value,color:e.colorDiscrete?e.colorDiscrete(r.name):i.color,label:i.label,value:r.value,raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("sankey",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove(),e.dom.chartArea.selectAll("."+xr("sankey-node",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove(),e.dom.chartArea.selectAll("."+xr("sankey-label",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};var gd=class{static type="rangeBar";static traits={hasAxes:!0,referenceLines:!1,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"linear",yScaleType:"linear",yExtentFields:["low_y","high_y"],domainMerge:"union"};static dataContract={x_var:{required:!0},low_y:{required:!0,numeric:!0},high_y:{required:!0,numeric:!0}};render(e,r){if(r.options&&r.options.style==="errorbar"){G9(e,r);return}var i=e.options.transition.speed,s=r.mapping.x_var,o=r.mapping.low_y,h=r.mapping.high_y,g=r.options&&r.options.rangeBarWidth?r.options.rangeBarWidth:Math.max(6,Math.min(60,(e.width-(e.margin.left+e.margin.right))/Math.max(r.data.length*3,1))),v=e.chart.selectAll("."+xr("rangeBar",e.element.id,r.label)).data(r.data);v.exit().transition().duration(i).style("opacity",0).remove();function x(Y){return e.yScale((+Y[o]+ +Y[h])/2)}function _(Y){return e.yScale(Math.max(+Y[o],+Y[h]))}function A(Y){return Math.abs(e.yScale(+Y[o])-e.yScale(+Y[h]))}function O(Y){return typeof e.colorDiscrete=="function"&&Y[r.mapping.group]?e.colorDiscrete(Y[r.mapping.group]):r.color||"#6b7280"}var I=v.enter().append("rect").attr("class",xr("rangeBar",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").attr("x",function(Y){return e.xScale(Y[s])-g/2}).attr("y",x).attr("width",g).attr("height",0).attr("fill",O);v.merge(I).transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x",function(Y){return e.xScale(Y[s])-g/2}).attr("y",_).attr("width",g).attr("height",A).attr("fill",O)}getHoverSelector(e,r){return"."+xr("rangeBar",e.dom.element.id,r.label)}formatTooltip(e,r,i){return{title:i.mapping.x_var+": "+r[i.mapping.x_var],body:i.mapping.low_y+": "+r[i.mapping.low_y]+", "+i.mapping.high_y+": "+r[i.mapping.high_y],color:i.color,label:i.label,value:r[i.mapping.high_y],raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("rangeBar",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove(),e.dom.chartArea.selectAll("."+xr("rangeBar-error",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};function G9(t,e){var r=t.options.transition.speed,i=e.mapping.x_var,s=e.mapping.low_y,o=e.mapping.high_y,h=e.mapping.y_var;if(!h){typeof console<"u"&&console.warn&&console.warn("myIO RangeBarRenderer: style='errorbar' requires a y_var mapping for the mean point. Skipping render for layer '"+(e.label||"(unnamed)")+"'.");return}var g=e.color||"#4269D0",v=e.options&&e.options.capWidth?e.options.capWidth:18,x=e.options&&e.options.pointRadius?e.options.pointRadius:4;function _(oe){var se=t.xScale(oe[i]);return t.xScale.bandwidth&&(se+=t.xScale.bandwidth()/2),se}function A(oe){return t.yScale(+oe[s])}function O(oe){return t.yScale(+oe[o])}function I(oe){return t.yScale(+oe[h])}var Y=t.chart.selectAll("."+xr("rangeBar-error",t.element.id,e.label)).data(e.data);Y.exit().transition().duration(r).style("opacity",0).remove();var K=Y.enter().append("g").attr("class",xr("rangeBar-error",t.element.id,e.label)).attr("clip-path","url(#"+t.element.id+"clip)").style("opacity",0);K.append("line").attr("class","mean-ci-whisker").attr("x1",_).attr("x2",_).attr("y1",I).attr("y2",I).attr("stroke",g).attr("stroke-width",2),K.append("line").attr("class","mean-ci-cap mean-ci-cap-low").attr("x1",_).attr("x2",_).attr("y1",I).attr("y2",I).attr("stroke",g).attr("stroke-width",2),K.append("line").attr("class","mean-ci-cap mean-ci-cap-high").attr("x1",_).attr("x2",_).attr("y1",I).attr("y2",I).attr("stroke",g).attr("stroke-width",2),K.append("circle").attr("class","mean-ci-point").attr("cx",_).attr("cy",I).attr("r",0).attr("fill",g).attr("stroke","var(--chart-bg, #ffffff)").attr("stroke-width",1.5);var ee=Y.merge(K);ee.transition().ease(Mn(t,d3.easeQuad)).duration(r).style("opacity",1),ee.select(".mean-ci-whisker").transition().ease(Mn(t,d3.easeQuad)).duration(r).attr("x1",_).attr("x2",_).attr("y1",A).attr("y2",O).attr("stroke",g),ee.select(".mean-ci-cap-low").transition().ease(Mn(t,d3.easeQuad)).duration(r).attr("x1",function(oe){return _(oe)-v/2}).attr("x2",function(oe){return _(oe)+v/2}).attr("y1",A).attr("y2",A).attr("stroke",g),ee.select(".mean-ci-cap-high").transition().ease(Mn(t,d3.easeQuad)).duration(r).attr("x1",function(oe){return _(oe)-v/2}).attr("x2",function(oe){return _(oe)+v/2}).attr("y1",O).attr("y2",O).attr("stroke",g),ee.select(".mean-ci-point").transition().ease(Mn(t,d3.easeQuad)).duration(r).attr("cx",_).attr("cy",I).attr("r",x).attr("fill",g)}var yd=class{static type="text";static traits={hasAxes:!1,referenceLines:!1,legendType:"none",binning:!1,rolloverStyle:"none",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"linear",yScaleType:"linear",xExtentFields:[],yExtentFields:[],domainMerge:"union"};static dataContract={};render(e,r){var i=r.options&&r.options.position||"top-right",s=r.label,o=xr("text-annotation",e.element.id,s);e.chart.selectAll("."+o).remove();var h=r.data.map(function(K){return K.text}),g=i.indexOf("top")!==-1,v=i.indexOf("right")!==-1,x=e.width-(e.margin.left+e.margin.right),_=e.height-(e.margin.top+e.margin.bottom),A=v?x-58:10,O=g?20:_-10,I=v?"end":"start",Y=e.chart.append("g").attr("class",o).attr("transform","translate("+A+","+O+")");h.forEach(function(K,ee){Y.append("text").attr("y",(g?1:-1)*ee*16).attr("text-anchor",I).style("font-size","12px").style("font-family","var(--font-family, sans-serif)").style("fill","var(--text-color, #333)").style("opacity",.8).text(K)})}formatTooltip(){return null}remove(e,r){var i=xr("text-annotation",e.dom.element.id,r.label);e.dom.chartArea.selectAll("."+i).remove()}};var bd=class{static type="bracket";static traits={hasAxes:!0,referenceLines:!1,legendType:"none",binning:!1,rolloverStyle:"none",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"linear",yScaleType:"linear",xExtentFields:[],yExtentFields:["y"],domainMerge:"union"};static dataContract={x1:{required:!0,numeric:!0},x2:{required:!0,numeric:!0},y:{required:!0,numeric:!0}};render(e,r){var i=xr("bracket",e.element.id,r.label),s=6,o=4,h=e.options.transition.speed,g=r.color||"var(--text-color, #333)",v=e.chart.selectAll("g."+i+"-root").data([null]).join("g").attr("class",i+"-root").attr("clip-path","url(#"+e.element.id+"clip)"),x=function(I,Y){return I.label!=null?String(I.label)+"_"+Y:String(Y)},_=v.selectAll("g."+i).data(r.data,x);_.exit().transition().duration(h).style("opacity",0).remove();var A=_.enter().append("g").attr("class",i).style("opacity",0);A.append("line").attr("class","bracket-bar").attr("stroke",g).attr("stroke-width",1.5),A.append("line").attr("class","bracket-tick-left").attr("stroke",g).attr("stroke-width",1.5),A.append("line").attr("class","bracket-tick-right").attr("stroke",g).attr("stroke-width",1.5),A.append("text").attr("class","bracket-label").attr("text-anchor","middle").style("font-size","11px").style("font-family","var(--font-family, sans-serif)").style("fill",g);var O=A.merge(_);O.transition().duration(h).style("opacity",1),O.select(".bracket-bar").transition().duration(h).attr("x1",function(I){return e.xScale(+I.x1)}).attr("y1",function(I){return e.yScale(+I.y)}).attr("x2",function(I){return e.xScale(+I.x2)}).attr("y2",function(I){return e.yScale(+I.y)}),O.select(".bracket-tick-left").transition().duration(h).attr("x1",function(I){return e.xScale(+I.x1)}).attr("y1",function(I){return e.yScale(+I.y)}).attr("x2",function(I){return e.xScale(+I.x1)}).attr("y2",function(I){return e.yScale(+I.y)+s}),O.select(".bracket-tick-right").transition().duration(h).attr("x1",function(I){return e.xScale(+I.x2)}).attr("y1",function(I){return e.yScale(+I.y)}).attr("x2",function(I){return e.xScale(+I.x2)}).attr("y2",function(I){return e.yScale(+I.y)+s}),O.select(".bracket-label").text(function(I){return I.label}).transition().duration(h).attr("x",function(I){return(e.xScale(+I.x1)+e.xScale(+I.x2))/2}).attr("y",function(I){return e.yScale(+I.y)-o})}formatTooltip(){return null}remove(e,r){var i=xr("bracket",e.element.id,r.label);e.chart.selectAll("."+i).remove()}};var vd=class{static type="lollipop";static traits={hasAxes:!0,referenceLines:!0,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"band",yScaleType:"linear",xExtentFields:[],yExtentFields:["y_var"],domainMerge:"union"};static dataContract={x_var:{required:!0,numeric:!1},y_var:{required:!0,numeric:!0}};render(e,r,i){var s=e.derived.xScale,o=e.derived.yScale,h=e.config.scales.flipAxis,g=e.options.transition.speed,v=e.dom.chartArea.selectAll(".tag-lollipop-"+r.id).data([null]).join("g").attr("class","tag-lollipop-"+r.id),x=r.options&&r.options.headRadius||5,_=r.options&&r.options.stemWidth||2,A=r.mapping.x_var,O=r.mapping.y_var,I=s.bandwidth?s.bandwidth()/2:0,Y=typeof o(0)=="number"?o(0):o.range()[0],K=typeof s(0)=="number"?s(0):s.range()[0];function ee(J){if(h){var k=o(J[A]);return o.bandwidth&&(k+=I),{x1:K,x2:s(J[O]),y1:k,y2:k}}var de=s(J[A])+I;return{x1:de,x2:de,y1:Y,y2:o(J[O])}}function oe(J){var k=ee(J);return{cx:k.x2,cy:k.y2}}var se=v.selectAll(".lollipop-stem").data(r.data,function(J){return J._source_key});se.exit().transition().duration(g).style("opacity",0).attr("x2",h?K:function(J){return s(J[A])+I}).attr("y2",h?function(J){var k=o(J[A]);return o.bandwidth?k+I:k}:Y).remove();var re=se.enter().append("line").attr("class","lollipop-stem").attr("x1",function(J){return ee(J).x1}).attr("x2",function(J){return h?ee(J).x1:ee(J).x2}).attr("y1",function(J){return ee(J).y1}).attr("y2",function(J){return ee(J).y1}).attr("stroke",r.color).attr("stroke-width",_).style("opacity",0);re.merge(se).transition().duration(g).style("opacity",1).attr("x1",function(J){return ee(J).x1}).attr("x2",function(J){return ee(J).x2}).attr("y1",function(J){return ee(J).y1}).attr("y2",function(J){return ee(J).y2}).attr("stroke",r.color).attr("stroke-width",_);var q=v.selectAll(".lollipop-head").data(r.data,function(J){return J._source_key});q.exit().transition().duration(g).style("opacity",0).attr("cx",function(J){return ee(J).x1}).attr("cy",function(J){return ee(J).y1}).remove();var ue=q.enter().append("circle").attr("class","lollipop-head").attr("cx",function(J){return ee(J).x1}).attr("cy",function(J){return ee(J).y1}).attr("r",x).attr("fill",r.color).style("opacity",0);ue.merge(q).transition().duration(g).style("opacity",1).attr("cx",function(J){return oe(J).cx}).attr("cy",function(J){return oe(J).cy}).attr("r",x).attr("fill",r.color)}getHoverSelector(e,r){return".tag-lollipop-"+r.id+" .lollipop-head"}formatTooltip(e,r,i){var s=e.runtime.activeYFormat||d3.format("s");return{title:{text:String(r[i.mapping.x_var])},items:[{color:i.color,label:i.label,value:s(r[i.mapping.y_var])}]}}remove(e,r){e.dom.chartArea.selectAll(".tag-lollipop-"+r.id).remove()}};var xd=class{static type="dumbbell";static traits={hasAxes:!0,referenceLines:!0,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"band",yScaleType:"linear",xExtentFields:[],yExtentFields:["low_y","high_y"],domainMerge:"union"};static dataContract={x_var:{required:!0,numeric:!1},low_y:{required:!0,numeric:!0},high_y:{required:!0,numeric:!0}};render(e,r,i){var s=e.derived.xScale,o=e.derived.yScale,h=e.config.scales.flipAxis,g=e.options.transition.speed,v=e.dom.chartArea.selectAll(".tag-dumbbell-"+r.id).data([null]).join("g").attr("class","tag-dumbbell-"+r.id),x=r.options&&r.options.dotRadius||5,_=r.options&&r.options.lineWidth||2,A=r.mapping.x_var,O=r.mapping.low_y,I=r.mapping.high_y,Y=s.bandwidth?s.bandwidth()/2:0,K=o.bandwidth?o.bandwidth()/2:0;function ee(k){if(h){var de=o(k[A])+K,ze=s(k[O]),er=s(k[I]);return{lowX:ze,lowY:de,highX:er,highY:de,midX:(ze+er)/2,midY:de}}var Er=s(k[A])+Y,Ht=o(k[O]),xn=o(k[I]);return{lowX:Er,lowY:Ht,highX:Er,highY:xn,midX:Er,midY:(Ht+xn)/2}}var oe=v.selectAll(".dumbbell-line").data(r.data,function(k){return k._source_key});oe.exit().transition().duration(g).style("opacity",0).attr("x1",function(k){return ee(k).midX}).attr("x2",function(k){return ee(k).midX}).attr("y1",function(k){return ee(k).midY}).attr("y2",function(k){return ee(k).midY}).remove();var se=oe.enter().append("line").attr("class","dumbbell-line").attr("x1",function(k){return ee(k).midX}).attr("x2",function(k){return ee(k).midX}).attr("y1",function(k){return ee(k).midY}).attr("y2",function(k){return ee(k).midY}).attr("stroke","var(--chart-grid-color, #ccc)").attr("stroke-width",_).style("opacity",0);se.merge(oe).transition().duration(g).style("opacity",1).attr("x1",function(k){return ee(k).lowX}).attr("x2",function(k){return ee(k).highX}).attr("y1",function(k){return ee(k).lowY}).attr("y2",function(k){return ee(k).highY}).attr("stroke","var(--chart-grid-color, #ccc)").attr("stroke-width",_);var re=v.selectAll(".dumbbell-low").data(r.data,function(k){return k._source_key});re.exit().transition().duration(g).style("opacity",0).attr("cx",function(k){return ee(k).midX}).attr("cy",function(k){return ee(k).midY}).remove();var q=re.enter().append("circle").attr("class","dumbbell-low").attr("cx",function(k){return ee(k).midX}).attr("cy",function(k){return ee(k).midY}).attr("r",x).attr("fill",r.color).attr("opacity",0);q.merge(re).transition().duration(g).attr("cx",function(k){return ee(k).lowX}).attr("cy",function(k){return ee(k).lowY}).attr("r",x).attr("fill",r.color).attr("opacity",.6);var ue=v.selectAll(".dumbbell-high").data(r.data,function(k){return k._source_key});ue.exit().transition().duration(g).style("opacity",0).attr("cx",function(k){return ee(k).midX}).attr("cy",function(k){return ee(k).midY}).remove();var J=ue.enter().append("circle").attr("class","dumbbell-high").attr("cx",function(k){return ee(k).midX}).attr("cy",function(k){return ee(k).midY}).attr("r",x).attr("fill",r.color).attr("opacity",0);J.merge(ue).transition().duration(g).attr("cx",function(k){return ee(k).highX}).attr("cy",function(k){return ee(k).highY}).attr("r",x).attr("fill",r.color).attr("opacity",1)}getHoverSelector(e,r){return".tag-dumbbell-"+r.id+" .dumbbell-high, .tag-dumbbell-"+r.id+" .dumbbell-low"}formatTooltip(e,r,i){var s=e.runtime.activeYFormat||d3.format("s");return{title:{text:String(r[i.mapping.x_var])},items:[{color:i.color,label:"Low",value:s(r[i.mapping.low_y])},{color:i.color,label:"High",value:s(r[i.mapping.high_y])}]}}remove(e,r){e.dom.chartArea.selectAll(".tag-dumbbell-"+r.id).remove()}};var _d=class{static type="waffle";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints=null;static dataContract={category:{required:!0},value:{required:!0,numeric:!0}};render(e,r){for(var i=r.options&&r.options.rows||10,s=r.options&&r.options.cols||10,o=i*s,h=r.options&&r.options.cellGap||2,g=r.options&&r.options.cellRadius||2,v=e.config.layout.margin,x=e.runtime.width-v.left-v.right,_=e.runtime.height-v.top-v.bottom,A=Math.min((x-(s-1)*h)/s,(_-(i-1)*h)/i),O=0,I=0;I=de)&&(J=Er,k=!0)}se._quantile_dot_cx=J,se._quantile_dot_cy=ue,oe.push({cx:J,cy:ue})})});var O=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0,I=e.dom.chartArea.selectAll(".tag-quantile_dots-"+r.id).data([null]).join("g").attr("class","tag-quantile_dots-"+r.id),Y=I.selectAll(".quantile-dots-point").data(r.data,function(ee){return ee._source_key});Y.exit().transition().duration(O).attr("fill-opacity",0).remove();var K=Y.enter().append("circle").attr("class","quantile-dots-point").attr("clip-path","url(#"+e.element.id+"clip)").attr("cx",function(ee){return ee._quantile_dot_cx}).attr("cy",function(ee){return ee._quantile_dot_cy}).attr("r",o).attr("fill",r.color).attr("fill-opacity",0).attr("role","graphics-symbol");K.merge(Y).transition().duration(O).attr("cx",function(ee){return ee._quantile_dot_cx}).attr("cy",function(ee){return ee._quantile_dot_cy}).attr("r",o).attr("fill",r.color).attr("fill-opacity",.75)}getHoverSelector(e,r){return".tag-quantile_dots-"+r.id+" .quantile-dots-point"}formatTooltip(e,r,i){var s=e.runtime.activeYFormat||d3.format("s"),o=i.options&&i.options.source?" ("+i.options.source+")":"";return{title:String(r[i.mapping.x_var]),items:[{color:i.color,label:i.label+o,value:"Q"+r[i.mapping.quantile_rank]+": "+s(r[i.mapping.y_var])}],value:r[i.mapping.y_var],raw:r}}remove(e,r){e.dom.chartArea.selectAll(".tag-quantile_dots-"+r.id).remove()}};var wd=class{static type="bump";static traits={hasAxes:!0,referenceLines:!1,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints={xScaleType:"point",yScaleType:"linear",xExtentFields:[],yExtentFields:["y_var"],domainMerge:"union"};static dataContract={x_var:{required:!0},y_var:{required:!0,numeric:!0},group:{required:!0}};render(e,r){var i=e.derived.xScale,s=e.derived.yScale,o=r.mapping.x_var,h=r.mapping.y_var,g=r.mapping.group,v=r.options&&r.options.dotRadius||5,x=e.derived.colorDiscrete||d3.scaleOrdinal(d3.schemeCategory10),_=d3.group(r.data,function(K){return K[g]}),A=e.dom.chartArea.selectAll(".tag-bump-"+r.id).data([null]).join("g").attr("class","tag-bump-"+r.id),O=d3.line().x(function(K){return i(K[o])}).y(function(K){return s(K[h])}).curve(d3.curveBumpX),I=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0,Y=0;_.forEach(function(K,ee){var oe=x(ee),se=K.slice().sort(function(k,de){return String(k[o]).localeCompare(String(de[o]))}),re=A.selectAll(".bump-line-"+Y).data([se]),q=re.enter().append("path").attr("class","bump-line bump-line-"+Y).attr("fill","none").attr("stroke",oe).attr("stroke-width",2.5).attr("stroke-opacity",0).attr("d",O);q.merge(re).transition().duration(I).attr("stroke",oe).attr("stroke-opacity",.8).attr("d",O);var ue=A.selectAll(".bump-dot-"+Y).data(se,function(k){return k._source_key||k[o]});ue.exit().transition().duration(I).style("opacity",0).remove();var J=ue.enter().append("circle").attr("class","bump-dot bump-dot-"+Y).attr("cx",function(k){return i(k[o])}).attr("cy",function(k){return s(k[h])}).attr("r",v).attr("fill",oe).attr("stroke","#fff").attr("stroke-width",1.5).style("opacity",0);J.merge(ue).transition().duration(I).style("opacity",1).attr("cx",function(k){return i(k[o])}).attr("cy",function(k){return s(k[h])}).attr("r",v).attr("fill",oe),Y++})}getHoverSelector(e,r){return".tag-bump-"+r.id+" .bump-dot"}formatTooltip(e,r,i){return{title:{text:String(r[i.mapping.group])},items:[{color:i.color,label:String(r[i.mapping.x_var]),value:String(r[i.mapping.y_var])}]}}remove(e,r){e.dom.chartArea.selectAll(".tag-bump-"+r.id).remove()}};var Ad=class{static type="radar";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints=null;static dataContract={axis:{required:!0},value:{required:!0,numeric:!0}};render(e,r){var i=e.margin||(e.config&&e.config.layout?e.config.layout.margin:{top:0,right:0,bottom:0,left:0}),s=(e.width||e.runtime&&e.runtime.width||0)-i.left-i.right,o=(e.height||e.runtime&&e.runtime.height||0)-i.top-i.bottom,h=r.mapping.axis,g=r.mapping.value,v=r.mapping.group,x=r.options&&r.options.labelOffset||16,_=s/2,A=o/2,O=Math.max(0,Math.min(s,o)/2-x-8),I=[],Y=new Set,K=d3.max(r.data,function(cr){return+cr[g]})||0,ee=d3.scaleLinear().domain([0,K>0?K:1]).range([0,O]),oe=[],se=v?d3.group(r.data,function(cr){return cr[v]}):new Map([[r.label||"Series",r.data]]),re=e.derived.colorDiscrete||d3.scaleOrdinal(d3.schemeCategory10),q,ue,J,k,de;if(r.data.forEach(function(cr){var bn=cr[h];Y.has(bn)||(Y.add(bn),I.push(bn))}),q=I.length,q===0)return;ue=e.dom.chartArea.selectAll(".tag-radar-"+r.id).data([null]).join("g").attr("class","tag-radar-"+r.id),J=ue.selectAll(".radar-axis-layer").data([null]).join("g").attr("class","radar-axis-layer"),k=ue.selectAll(".radar-polygon-layer").data([null]).join("g").attr("class","radar-polygon-layer");var ze=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0;function er(cr){var bn=2*Math.PI*cr/q,mn=Math.sin(bn),qn=Math.cos(bn),Wt="middle";return mn>.25?Wt="start":mn<-.25&&(Wt="end"),{lineX:_+O*mn,lineY:A-O*qn,labelX:_+(O+x)*mn,labelY:A-(O+x)*qn,textAnchor:Wt}}var Er=J.selectAll(".radar-axis").data(I,function(cr){return cr});Er.exit().transition().duration(ze).style("opacity",0).remove();var Ht=Er.enter().append("g").attr("class","radar-axis").style("opacity",0);Ht.append("line").attr("class","radar-axis-line").attr("stroke","var(--chart-grid, #cbd5e1)").attr("stroke-width",1).attr("x1",_).attr("y1",A).attr("x2",_).attr("y2",A),Ht.append("text").attr("class","radar-axis-label").attr("fill","var(--chart-fg, #1f2937)").attr("x",_).attr("y",A).attr("dy","0.35em").attr("text-anchor","middle");var xn=Ht.merge(Er);xn.transition().duration(ze).style("opacity",1),xn.each(function(cr,bn){var mn=er(bn),qn=d3.select(this);qn.select(".radar-axis-line").attr("stroke","var(--chart-grid, #cbd5e1)").attr("stroke-width",1).transition().duration(ze).attr("x1",_).attr("y1",A).attr("x2",mn.lineX).attr("y2",mn.lineY),qn.select(".radar-axis-label").text(cr).transition().duration(ze).attr("x",mn.labelX).attr("y",mn.labelY).attr("text-anchor",mn.textAnchor)}),se.forEach(function(cr,bn){var mn=new Map,qn=[];cr.forEach(function(Wt){mn.set(Wt[h],Wt)}),I.forEach(function(Wt,Pr){var hi=2*Math.PI*Pr/q,Ai=mn.get(Wt),pi=Ai?+Ai[g]:0,ss=ee(Number.isFinite(pi)?pi:0);qn.push({axis:Wt,angle:hi,value:Number.isFinite(pi)?pi:0,x:_+ss*Math.sin(hi),y:A-ss*Math.cos(hi),datum:Ai||null})}),oe.push({key:bn,color:re(bn),points:qn,rows:cr})}),e.derived.colorDiscrete=re.domain(oe.map(function(cr){return cr.key})),e.colorDiscrete=e.derived.colorDiscrete,de=d3.line().x(function(cr){return cr.x}).y(function(cr){return cr.y}).curve(d3.curveLinearClosed);function $r(cr){return de(cr.map(function(bn){return{x:_,y:A}}))}var Tn=k.selectAll(".radar-polygon").data(oe,function(cr){return cr.key});Tn.exit().transition().duration(ze).style("opacity",0).remove();var In=Tn.enter().append("path").attr("class","radar-polygon").attr("d",function(cr){return $r(cr.points)}).attr("fill",function(cr){return cr.color}).attr("fill-opacity",0).attr("stroke",function(cr){return cr.color}).attr("stroke-width",2).attr("stroke-opacity",0);In.merge(Tn).transition().duration(ze).attrTween("d",function(cr){var bn=this,mn=bn._radarPoints||cr.points.map(function(){return{x:_,y:A}}),qn=cr.points,Wt=mn.map(function(Pr,hi){var Ai=qn[hi]||Pr;return{x:d3.interpolateNumber(Pr.x,Ai.x),y:d3.interpolateNumber(Pr.y,Ai.y)}});return function(Pr){var hi=Wt.map(function(Ai){return{x:Ai.x(Pr),y:Ai.y(Pr)}});return bn._radarPoints=qn,de(hi)}}).attr("fill",function(cr){return cr.color}).attr("fill-opacity",.2).attr("stroke",function(cr){return cr.color}).attr("stroke-opacity",1)}getHoverSelector(e,r){return".tag-radar-"+r.id+" .radar-polygon"}formatTooltip(e,r){return{title:{text:String(r.key)},items:r.points.map(function(i){return{color:r.color,label:i.axis,value:String(i.value)}})}}remove(e,r){e.dom.chartArea.selectAll(".tag-radar-"+r.id).remove()}};var Td=class{static type="funnel";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints=null;static dataContract={stage:{required:!0},value:{required:!0,numeric:!0}};render(e,r){var i=e.margin||(e.config&&e.config.layout?e.config.layout.margin:{top:0,right:0,bottom:0,left:0}),s=(e.width||e.runtime&&e.runtime.width||0)-i.left-i.right,o=(e.height||e.runtime&&e.runtime.height||0)-i.top-i.bottom,h=r.mapping.stage,g=r.mapping.value,v=r.options&&r.options.stageGap||6,x=d3.max(r.data,function(ue){return+ue[g]})||0,_=d3.scaleLinear().domain([0,x>0?x:1]).range([0,s*.95]),A=e.derived.colorDiscrete||d3.scaleOrdinal(d3.schemeTableau10),O=r.data.length>0?o/r.data.length:0,I,Y,K;I=r.data.map(function(ue,J){var k=r.data[J+1]||null,de=_(+ue[g]||0),ze=k?_(+k[g]||0):de*.55,er=J*O,Er=Math.max(er,er+O-v),Ht=s/2,xn=Ht-de/2,$r=Ht+de/2,Tn=Ht-ze/2,In=Ht+ze/2;return{stage:ue[h],value:+ue[g],color:A(ue[h]),datum:ue,points:[[xn,er],[$r,er],[In,Er],[Tn,Er]],labelX:Ht,labelY:(er+Er)/2}}),e.derived.colorDiscrete=A.domain(I.map(function(ue){return ue.stage})),e.colorDiscrete=e.derived.colorDiscrete;var ee=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0;function oe(ue){return"M"+ue[0][0]+","+ue[0][1]+"L"+ue[1][0]+","+ue[1][1]+"L"+ue[2][0]+","+ue[2][1]+"L"+ue[3][0]+","+ue[3][1]+"Z"}function se(ue){var J=(ue.points[0][0]+ue.points[1][0])/2,k=(ue.points[0][1]+ue.points[3][1])/2;return[[J,k],[J,k],[J,k],[J,k]]}Y=e.dom.chartArea.selectAll(".tag-funnel-"+r.id).data([null]).join("g").attr("class","tag-funnel-"+r.id),K=Y.selectAll(".funnel-stage-group").data(I,function(ue){return ue.stage}),K.exit().transition().duration(ee).style("opacity",0).remove();var re=K.enter().append("g").attr("class","funnel-stage-group").style("opacity",0);re.append("path").attr("class","funnel-stage").attr("d",function(ue){return oe(se(ue))}).attr("fill",function(ue){return ue.color}),re.append("text").attr("class","funnel-label").attr("x",function(ue){return ue.labelX}).attr("y",function(ue){return ue.labelY}).attr("dy","0.35em").attr("text-anchor","middle").text(function(ue){return ue.stage});var q=re.merge(K);q.transition().duration(ee).style("opacity",1),q.select(".funnel-stage").transition().duration(ee).attr("d",function(ue){return oe(ue.points)}).attr("fill",function(ue){return ue.color}),q.select(".funnel-label").text(function(ue){return ue.stage}).transition().duration(ee).attr("x",function(ue){return ue.labelX}).attr("y",function(ue){return ue.labelY})}getHoverSelector(e,r){return".tag-funnel-"+r.id+" .funnel-stage"}formatTooltip(e,r){return{title:{text:String(r.stage)},items:[{color:r.color,label:String(r.stage),value:String(r.value)}]}}remove(e,r){e.dom.chartArea.selectAll(".tag-funnel-"+r.id).remove()}};var Id=class{static type="parallel";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints=null;static dataContract={dimensions:{required:!0}};render(e,r){var i=e.margin||(e.config&&e.config.layout?e.config.layout.margin:{top:0,right:0,bottom:0,left:0}),s=(e.width||e.runtime&&e.runtime.width||0)-i.left-i.right,o=(e.height||e.runtime&&e.runtime.height||0)-i.top-i.bottom,h=r.mapping.dimensions,g=Array.isArray(h)?h.slice():[h],v=r.mapping.group,x=d3.scalePoint().domain(g).range([0,s]).padding(.5),_={},A=e.derived.colorDiscrete||d3.scaleOrdinal(d3.schemeCategory10),O,I,Y;g.forEach(function(q){var ue=d3.extent(r.data,function(J){var k=+J[q];return Number.isFinite(k)?k:null});(!ue||ue[0]===void 0||ue[1]===void 0)&&(ue=[0,1]),ue[0]===ue[1]&&(ue=[ue[0]-1,ue[1]+1]),_[q]=d3.scaleLinear().domain(ue).range([o,0])}),e.derived.colorDiscrete=A.domain(Array.from(new Set(r.data.map(function(q){return v?q[v]:r.label})))),e.colorDiscrete=e.derived.colorDiscrete,O=e.dom.chartArea.selectAll(".tag-parallel-"+r.id).data([null]).join("g").attr("class","tag-parallel-"+r.id),I=O.selectAll(".parallel-axis").data(g).join(function(q){var ue=q.append("g").attr("class","parallel-axis");return ue.append("text").attr("class","parallel-axis-label"),ue}).attr("transform",function(q){return"translate("+x(q)+",0)"}).each(function(q){d3.select(this).call(d3.axisLeft(_[q]).ticks(5))}),I.select(".parallel-axis-label").attr("x",0).attr("y",-10).attr("text-anchor","middle").text(function(q){return q}),Y=d3.line().defined(function(q){return q&&q[1]!==null}).x(function(q){return q[0]}).y(function(q){return q[1]});var K=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0;function ee(q){var ue=g.map(function(J){var k=+q[J];return Number.isFinite(k)?[x(J),_[J](k)]:[x(J),null]});return Y(ue)}function oe(q){var ue=v?q[v]:r.label;return A(ue)}var se=O.selectAll(".parallel-line").data(r.data,function(q,ue){return q._source_key!=null?q._source_key:ue});se.exit().transition().duration(K).attr("stroke-opacity",0).remove();var re=se.enter().append("path").attr("class","parallel-line").attr("fill","none").attr("d",ee).attr("stroke",oe).attr("stroke-opacity",0);re.merge(se).transition().duration(K).attr("d",ee).attr("stroke",oe).attr("stroke-opacity",.6)}getHoverSelector(e,r){return".tag-parallel-"+r.id+" .parallel-line"}formatTooltip(e,r,i){var s=Array.isArray(i.mapping.dimensions)?i.mapping.dimensions:[i.mapping.dimensions],o=i.mapping.group?String(r[i.mapping.group]):String(i.label||"Series");return{title:{text:o},items:s.map(function(h){return{color:e.colorDiscrete?e.colorDiscrete(i.mapping.group?r[i.mapping.group]:i.label):i.color,label:h,value:String(r[h])}})}}remove(e,r){e.dom.chartArea.selectAll(".tag-parallel-"+r.id).remove()}};var ns=new Map;function Ts(t,e){if(ns.has(t))throw new Error("Renderer already registered for type: "+t);var r=e&&e.constructor?e.constructor.traits:null,i=["hasAxes","referenceLines","legendType","binning","rolloverStyle"];if(!r)throw new Error("Renderer missing static traits: "+t);i.forEach(function(s){if(!(s in r))throw new Error("Renderer trait missing '"+s+"': "+t)}),ns.set(t,e)}function t6(t){if(!ns.has(t))throw new Error("Unknown renderer type: "+t);return ns.get(t)}function fl(t){return t6(t.type)}function qg(){return ns.has(X3.type)||Ts(X3.type,new X3),ns.has(J3.type)||Ts(J3.type,new J3),ns.has(K3.type)||Ts(K3.type,new K3),ns.has(Q3.type)||Ts(Q3.type,new Q3),ns.has(Z3.type)||Ts(Z3.type,new Z3),ns.has(ed.type)||Ts(ed.type,new ed),ns.has(td.type)||Ts(td.type,new td),ns.has(ld.type)||Ts(ld.type,new ld),ns.has(cd.type)||Ts(cd.type,new cd),ns.has(ud.type)||Ts(ud.type,new ud),ns.has(fd.type)||Ts(fd.type,new fd),ns.has(dd.type)||Ts(dd.type,new dd),ns.has(hd.type)||Ts(hd.type,new hd),ns.has(pd.type)||Ts(pd.type,new pd),ns.has(md.type)||Ts(md.type,new md),ns.has(gd.type)||Ts(gd.type,new gd),ns.has(vd.type)||Ts(vd.type,new vd),ns.has(xd.type)||Ts(xd.type,new xd),ns.has(_d.type)||Ts(_d.type,new _d),ns.has(Sd.type)||Ts(Sd.type,new Sd),ns.has(Ed.type)||Ts(Ed.type,new Ed),ns.has(wd.type)||Ts(wd.type,new wd),ns.has(Ad.type)||Ts(Ad.type,new Ad),ns.has(Td.type)||Ts(Td.type,new Td),ns.has(Id.type)||Ts(Id.type,new Id),ns.has(yd.type)||Ts(yd.type,new yd),ns.has(bd.type)||Ts(bd.type,new bd),ns}function zg(){return Array.from(ns.values())}function Hg(t,e){var r=Vs(t,e.label,e.color),i=d3.drag().on("start",function(){d3.select(this).raise().classed("active",!0).style("cursor","grabbing")}).on("drag",function(s,o){o[e.mapping.x_var]=t.xScale.invert(s.x),o[e.mapping.y_var]=t.yScale.invert(s.y),d3.select(this).attr("cx",t.xScale(o[e.mapping.x_var])).attr("cy",t.yScale(o[e.mapping.y_var]))}).on("end",function(s,o){d3.select(this).classed("active",!1).style("cursor","grab"),t.updateRegression(r,e.label),t.emit("dragEnd",{point:o,layerLabel:e.label})});t.chart.selectAll("."+xr("point",t.element.id,e.label)).style("cursor","grab").call(i)}function I0(t,e,r){Od(t);var i=d3.select(t.dom.element),s=i.append("div").attr("class","myIO-status-bar").attr("role","status").attr("aria-live","polite");s.append("span").attr("class","myIO-status-bar-text").text(e);var o=s.append("span").attr("class","myIO-status-bar-actions");(r||[]).forEach(function(h){o.append("button").attr("class","myIO-status-bar-btn").attr("type","button").text(h.label).on("click",h.handler)})}function Od(t){d3.select(t.dom.element).selectAll(".myIO-status-bar").remove()}var Wg=["point","bar","histogram","hexbin","groupedBar"];function Yg(t){var e=t.config.interactions.brush;if(!(!e||!e.enabled)){var r=(t.derived.currentLayers||[]).filter(function(g){return Wg.indexOf(g.type)>-1});if(r.length!==0){C0(t);var i=e.direction==="x"?d3.brushX():e.direction==="y"?d3.brushY():d3.brush(),s=t.config.layout.margin,o=t.runtime.width-(s.left+s.right),h=t.runtime.height-(s.top+s.bottom);i.extent([[0,0],[o,h]]),i.on("brush",function(g){j9(t,g,r,e)}).on("end",function(g){q9(t,g,r,e)}),t.dom.chartArea.insert("g",":first-child").attr("class","myIO-brush").call(i),t.dom.chartArea.select(".myIO-brush .overlay").style("cursor","crosshair"),t.runtime._brushFn=i,d3.select(t.dom.element).on("keydown.brush",function(g){g.key==="Escape"&&t.runtime._brushed&&r6(t)})}}}function j9(t,e,r,i){if(e.selection){var s=e.selection,o=i.direction;r.forEach(function(h){var g=Jg(t,h);t.dom.chartArea.selectAll(g).each(function(v){var x=Xg(t,v,h,s,o);d3.select(this).style("opacity",x?1:"var(--chart-brush-dim-opacity)")})})}}function q9(t,e,r,i){if(!e.selection){r6(t);return}var s=e.selection,o=i.direction,h=z9(t,s,o),g=[],v=[];r.forEach(function(_){_.data.forEach(function(A){Xg(t,A,_,s,o)&&(g.push(A),A._source_key&&v.push(A._source_key))})}),t.runtime._brushed={data:g,extent:h,keys:v};var x=r.reduce(function(_,A){return _+A.data.length},0);I0(t,g.length+" of "+x+" points selected",[{label:"Clear",handler:function(){r6(t)}}]),t.emit("brushed",{data:g,extent:h,keys:v,layerLabel:r.length===1?r[0].label:null})}function r6(t){(t.derived.currentLayers||[]).forEach(function(e){if(Wg.indexOf(e.type)>-1){var r=Jg(t,e);t.dom.chartArea.selectAll(r).style("opacity",1)}}),t.runtime._brushFn&&t.dom.chartArea.select(".myIO-brush").call(t.runtime._brushFn.move,null),t.runtime._brushed=null,Od(t),t.emit("brushed",{data:[],extent:null,keys:[],layerLabel:null})}function Xg(t,e,r,i,s){var o=r.mapping.x_var,h=r.mapping.y_var,g=t.xScale(e[o]),v=t.yScale(e[h]);return isNaN(g)||isNaN(v)?!1:s==="x"?g>=i[0]&&g<=i[1]:s==="y"?v>=i[0]&&v<=i[1]:g>=i[0][0]&&g<=i[1][0]&&v>=i[0][1]&&v<=i[1][1]}function O0(t,e,r){return typeof t.invert=="function"?[t.invert(e),t.invert(r)]:null}function z9(t,e,r){return r==="x"?{x:O0(t.xScale,e[0],e[1]),y:null}:r==="y"?{x:null,y:O0(t.yScale,e[1],e[0])}:{x:O0(t.xScale,e[0][0],e[1][0]),y:O0(t.yScale,e[1][1],e[0][1])}}function Jg(t,e){return e.type==="groupedBar"?".tag-grouped-bar-g rect":"."+xr(e.type,t.dom.element.id,e.label)}function C0(t){t.dom&&t.dom.chartArea&&t.dom.chartArea.selectAll(".myIO-brush").remove(),t.dom&&t.dom.element&&d3.select(t.dom.element).on("keydown.brush",null),t.runtime._brushed=null}var n6=30;function Kg(t,e,r){x2(t);var i=d3.select(t.dom.element),s=i.append("div").attr("class","myIO-popover").attr("role","dialog").attr("aria-label","Annotate data point"),o=s.append("div").attr("class","myIO-popover-field");o.append("label").text("Label:");var h;r.presetLabels&&r.presetLabels.length>0?(h=o.append("select").attr("class","myIO-popover-input"),r.presetLabels.forEach(function(A){h.append("option").attr("value",A).text(A)}),r.existingLabel&&h.property("value",r.existingLabel)):(h=o.append("input").attr("class","myIO-popover-input").attr("type","text").attr("maxlength",n6).attr("placeholder","Enter label..."),r.existingLabel&&h.property("value",r.existingLabel));var g=null;if(r.categoryColors){var v=s.append("div").attr("class","myIO-popover-field");v.append("label").text("Category:");var x=v.append("div").attr("class","myIO-popover-colors");Object.keys(r.categoryColors).forEach(function(A){var O=r.categoryColors[A];x.append("button").attr("class","myIO-popover-color-btn").attr("type","button").attr("title",A).attr("aria-label",A).style("background-color",O).on("click",function(){x.selectAll(".myIO-popover-color-btn").classed("selected",!1),d3.select(this).classed("selected",!0),g=O})})}var _=s.append("div").attr("class","myIO-popover-buttons");r.existingLabel&&r.onRemove&&_.append("button").attr("class","myIO-popover-btn myIO-popover-btn--danger").attr("type","button").text("Remove").on("click",function(){x2(t),r.onRemove()}),_.append("button").attr("class","myIO-popover-btn").attr("type","button").text("Cancel").on("click",function(){x2(t),r.onCancel&&r.onCancel()}),_.append("button").attr("class","myIO-popover-btn myIO-popover-btn--primary").attr("type","button").text("Apply").on("click",function(){var A=h.property("value").trim().substring(0,n6);A&&(x2(t),r.onApply(A,g))}),H9(t,s,e),h.node().focus(),s.on("keydown",function(A){if(A.key==="Enter"){var O=h.property("value").trim().substring(0,n6);O&&(x2(t),r.onApply(O,g))}A.key==="Escape"&&(x2(t),r.onCancel&&r.onCancel())})}function H9(t,e,r){var i=t.config.layout.margin,s=r.px+i.left,o=r.py+i.top-10;e.style("left",Math.max(4,Math.min(s-80,t.runtime.totalWidth-180))+"px").style("bottom",t.runtime.height-o+8+"px")}function x2(t){d3.select(t.dom.element).selectAll(".myIO-popover").remove()}var W9=["point","bar","histogram","hexbin","groupedBar"];function Qg(t){var e=t.config.interactions.annotation;if(!(!e||!e.enabled)){t.runtime._annotations||(t.runtime._annotations=[]);var r=(t.derived.currentLayers||[]).filter(function(i){return W9.indexOf(i.type)>-1});r.forEach(function(i){var s="."+xr(i.type,t.dom.element.id,i.label);t.dom.chartArea.selectAll(s).on("click.annotate",function(o,h){o.stopPropagation();var g=K9(t,h._source_key);Kg(t,{px:t.xScale(h[i.mapping.x_var]),py:t.yScale(h[i.mapping.y_var])},{presetLabels:e.presetLabels,categoryColors:e.categoryColors,existingLabel:g?g.label:null,onApply:function(v,x){Y9(t,h,i,v,x)},onRemove:function(){X9(t,h._source_key)},onCancel:function(){}})})}),L0(t),i6(t)}}function Y9(t,e,r,i,s){t.runtime._annotations=t.runtime._annotations.filter(function(h){return h._source_key!==e._source_key});var o={_source_key:e._source_key,x:e[r.mapping.x_var],y:e[r.mapping.y_var],x_var:r.mapping.x_var,y_var:r.mapping.y_var,label:i,category:s||null,layerLabel:r.label,timestamp:new Date().toISOString()};t.runtime._annotations.push(o),L0(t),i6(t),t.emit("annotated",{annotations:t.runtime._annotations,action:"add",latest:o})}function X9(t,e){var r=t.runtime._annotations.find(function(i){return i._source_key===e});t.runtime._annotations=t.runtime._annotations.filter(function(i){return i._source_key!==e}),L0(t),i6(t),t.emit("annotated",{annotations:t.runtime._annotations,action:"remove",latest:r||null})}function J9(t){t.runtime._annotations=[],L0(t),Od(t),t.emit("annotated",{annotations:[],action:"clear",latest:null})}function L0(t){var e=t.dom.chartArea.selectAll(".myIO-annotations").data([0]);e=e.enter().append("g").attr("class","myIO-annotations").merge(e);var r=e.selectAll(".myIO-annotation-mark").data(t.runtime._annotations||[],function(o){return o._source_key});r.exit().remove();var i=r.enter().append("g").attr("class","myIO-annotation-mark");i.append("circle").attr("r",8).attr("fill","none").attr("stroke-width",2),i.append("text").attr("dy",-12).attr("text-anchor","middle").attr("class","myIO-annotation-label");var s=i.merge(r);s.attr("transform",function(o){return"translate("+t.xScale(o.x)+","+t.yScale(o.y)+")"}),s.select("circle").style("stroke",function(o){return o.category||"var(--chart-annotation-ring)"}),s.select("text").text(function(o){return o.label.length>30?o.label.substring(0,27)+"\u2026":o.label}).style("font-size","var(--chart-annotation-font-size)").style("fill","var(--chart-text-color)")}function i6(t){var e=(t.runtime._annotations||[]).length;if(e===0){Od(t);return}I0(t,e+" annotation"+(e===1?"":"s"),[{label:"Export",handler:function(){var r=t.runtime._annotations||[];r.length>0&&E0(t.dom.element.id+"_annotations.csv",r)}},{label:"Clear",handler:function(){J9(t)}}])}function K9(t,e){return(t.runtime._annotations||[]).find(function(r){return r._source_key===e})}function Zg(t){x2(t)}var Rh=new Map;function s6(t){return t&&t.config&&t.config.interactions&&t.config.interactions.linked}function a6(t){var e=s6(t);return e&&e.cursor===!0&&e.group?e.group:null}function ty(t){var e=a6(t);if(e){var r=Rh.get(e);r||(r=new Set,Rh.set(e,r)),r.add(t),t.runtime=t.runtime||{},t.runtime._linkedCursor||(t.runtime._linkedCursor={lastTs:0})}}function ry(t){Rh.forEach(function(e,r){e.delete(t)&&e.size===0&&Rh.delete(r)})}function ny(t,e){var r=a6(t);if(r){var i=Rh.get(r);i&&i.forEach(function(s){s!==t&&Z9(s,e)})}}function Q9(t){var e=a6(t);e&&ny(t,{sourceId:t.element&&t.element.id,group:e,ts:typeof performance<"u"?performance.now():Date.now(),clear:!0})}function N0(t,e,r,i){var s=s6(t);if(!(!s||s.cursor!==!0)){var o=s.keyColumn,h=e&&o&&e[o]!==void 0?e[o]:null;ny(t,{sourceId:t.element&&t.element.id,group:s.group,keyValue:h,xValue:r,tooltip:i||null,ts:typeof performance<"u"?performance.now():Date.now()})}}function D0(t){var e=s6(t);!e||e.cursor!==!0||Q9(t)}function Z9(t,e){var r=t.runtime&&t.runtime._linkedCursor;if(r&&!(typeof e.ts=="number"&&e.ts+o)return null;var v=r(h);return Number.isFinite(v)?v:null}var x=typeof r.domain=="function"?r.domain():[];if(x.indexOf(e)===-1)return null;var _=r(e);return Number.isFinite(_)?_:null}function tx(t,e){var r=t.plot||t.svg;if(!(!r||typeof r.select!="function")){var i=r.select("line.myIO-hover-rule");i.empty()&&(i=r.append("line").attr("class","myIO-hover-rule"));var s=t.margin||{},o=(t.height||0)-((+s.top||0)+(+s.bottom||0));i.attr("x1",e).attr("x2",e).attr("y1",0).attr("y2",o).style("display",null)}}function ey(t){var e=t.plot||t.svg;!e||typeof e.select!="function"||e.select("line.myIO-hover-rule").remove()}var iy=["point","bar","histogram","hexbin","groupedBar","waffle","beeswarm","lollipop","dumbbell"];function sy(t){var e=t.config.interactions.linked;if(!(!e||!e.enabled)&&!(typeof crosstalk>"u")){o6(t);var r=new crosstalk.SelectionHandle(e.group),i=e.filter?new crosstalk.FilterHandle(e.group):null;t.runtime._crosstalkSel=r,t.runtime._crosstalkFil=i,(e.mode==="source"||e.mode==="both")&&(t.runtime._linkedBrushHandler=function(s){s.keys&&s.keys.length>0?r.set(s.keys):r.clear()},t.on("brushed",t.runtime._linkedBrushHandler)),(e.mode==="target"||e.mode==="both")&&(r.on("change.myIO",function(s){rx(t,s.value)}),i&&i.on("change.myIO",function(s){nx(t,s.value)}))}}function rx(t,e){var r=(t.derived.currentLayers||[]).filter(function(i){return iy.indexOf(i.type)>-1});r.forEach(function(i){var s="."+xr(i.type,t.dom.element.id,i.label);t.dom.chartArea.selectAll(s).each(function(o){if(!e)d3.select(this).style("opacity",1);else{var h=e.indexOf(o._source_key)>-1;d3.select(this).style("opacity",h?1:"var(--chart-brush-dim-opacity)")}})})}function nx(t,e){var r=(t.derived.currentLayers||[]).filter(function(i){return iy.indexOf(i.type)>-1});r.forEach(function(i){var s="."+xr(i.type,t.dom.element.id,i.label);t.dom.chartArea.selectAll(s).each(function(o){if(!e)d3.select(this).style("display",null);else{var h=e.indexOf(o._source_key)>-1;d3.select(this).style("display",h?null:"none")}})})}function o6(t){t.runtime._linkedBrushHandler&&(t.off("brushed",t.runtime._linkedBrushHandler),t.runtime._linkedBrushHandler=null),t.runtime._crosstalkSel&&(t.runtime._crosstalkSel.close(),t.runtime._crosstalkSel=null),t.runtime._crosstalkFil&&(t.runtime._crosstalkFil.close(),t.runtime._crosstalkFil=null),ry(t)}function oy(t){var e=t.config.interactions.sliders;if(!(!e||e.length===0)){l6(t),t.runtime._sliderTimers=[];var r=d3.select(t.dom.element),i=r.append("div").attr("class","myIO-slider-wrapper");e.forEach(function(s){var o=i.append("div").attr("class","myIO-slider-row");o.append("label").attr("class","myIO-slider-label").attr("for",t.dom.element.id+"-slider-"+s.param).text(s.label);var h=o.append("input").attr("type","range").attr("class","myIO-slider-input").attr("id",t.dom.element.id+"-slider-"+s.param).attr("min",s.min).attr("max",s.max).attr("step",s.step||"any").attr("aria-label",s.label).attr("aria-valuemin",s.min).attr("aria-valuemax",s.max).attr("aria-valuenow",s.value).property("value",s.value),g=o.append("span").attr("class","myIO-slider-value").text(ay(s.value,s.step));if(!HTMLWidgets.shinyMode){h.attr("disabled",!0).attr("title","Parameter sliders require Shiny"),o.style("opacity","0.5");return}var v=t.runtime._sliderTimers.length;t.runtime._sliderTimers.push(null);var x=s.debounce||200;h.on("input",function(){var _=+this.value;g.text(ay(_,s.step)),d3.select(this).attr("aria-valuenow",_),clearTimeout(t.runtime._sliderTimers[v]),t.runtime._sliderTimers[v]=setTimeout(function(){Shiny.onInputChange("myIO-"+t.dom.element.id+"-slider-"+s.param,_),t.emit("sliderChanged",{param:s.param,value:_})},x)})})}}function ay(t,e){if(e&&e<1){var r=String(e).split(".")[1];return t.toFixed(r?r.length:2)}return String(t)}function l6(t){t.runtime._sliderTimers&&(t.runtime._sliderTimers.forEach(clearTimeout),t.runtime._sliderTimers=null),d3.select(t.dom.element).selectAll(".myIO-slider-wrapper").remove()}function ix(t){let e=document.createElement("div");return e.textContent=String(t),e.innerHTML}function cy(t){t.dom.tooltip=d3.select(t.dom.element).append("div").attr("class","toolTip").attr("role","status").attr("aria-live","polite").attr("aria-hidden","true"),t.dom.tooltipTitle=t.dom.tooltip.append("div").attr("class","toolTipTitle"),t.dom.tooltipBody=t.dom.tooltip.append("div").attr("class","toolTipBody"),t.runtime.tooltipHideTimer=null,t.captureLegacyAliases()}function Cd(t){d3.select(t.dom.element).select(".toolTipBox").remove(),d3.select(t.dom.element).select(".toolLine").remove(),d3.select(t.dom.element).select(".toolPointLayer").remove(),t.runtime.toolTipBox=null,t.runtime.toolLine=null,t.runtime.toolPointLayer=null,t.syncLegacyAliases()}function uy(t,e,r){Cd(t),t.runtime.toolLine=t.dom.chartArea.append("line").attr("class","toolLine"),t.runtime.toolPointLayer=t.dom.chartArea.append("g").attr("class","toolPointLayer"),t.runtime.toolTipBox=t.dom.svg.append("rect").attr("class","toolTipBox").attr("opacity",0).attr("width",t.width-(t.margin.left+t.margin.right)).attr("height",t.height-(t.margin.top+t.margin.bottom)).attr("transform","translate("+t.margin.left+","+t.margin.top+")").on("mouseover",function(i){e(i)}).on("mousemove",function(i){e(i)}).on("mouseout",function(){typeof r=="function"&&r()}).on("touchstart",function(i){i.preventDefault(),e(i)}).on("touchmove",function(i){i.preventDefault(),e(i)}).on("touchend",function(){typeof r=="function"&&r()}),t.syncLegacyAliases()}function _2(t,e){if(!t.dom.tooltip)return;clearTimeout(t.runtime.tooltipHideTimer);let r=e.pointer||[0,0],i=e.title||{},s=e.items||[],o=s.length===1&&s[0].color?s[0].color:null;t.dom.tooltipTitle.style("border-left-color",o||null).html(""+ix(ly(i))+"");let h=t.dom.tooltipBody.selectAll(".toolTipItem").data(s);h.exit().remove();let g=h.enter().append("div").attr("class","toolTipItem");g.append("span").attr("class","dot"),g.append("span").attr("class","toolTipLabel"),g.append("span").attr("class","toolTipValue"),g.merge(h).select(".dot").style("background-color",function(v){return v.color||"transparent"}),g.merge(h).select(".toolTipLabel").text(function(v){return v.label||""}),g.merge(h).select(".toolTipValue").text(function(v){return ly(v)}),t.dom.tooltip.style("display","inline-block").style("opacity",1).attr("aria-hidden","false"),sx(t,r)}function ku(t){t.dom.tooltip&&(clearTimeout(t.runtime.tooltipHideTimer),t.runtime.tooltipHideTimer=window.setTimeout(function(){t.dom.tooltip.style("display","none").style("opacity",0).attr("aria-hidden","true")},300))}function ly(t){if(t==null)return"";if(typeof t=="string")return t;let e=typeof t.format=="function"?t.format:function(i){return i},r=t.text!=null?t.text:t.value;return r==null?"":e(r)}function sx(t,e){let r=t.dom.element.getBoundingClientRect(),i=t.dom.tooltip.node();t.dom.tooltip.style("left",e[0]+12+"px").style("top",e[1]+12+"px");let s=i.getBoundingClientRect(),o=e[0]+12,h=e[1]+12;o+s.width>r.width&&(o=Math.max(8,e[0]-s.width-12)),h+s.height>r.height&&(h=Math.max(8,e[1]-s.height-12)),t.dom.tooltip.style("left",o+"px").style("top",h+"px")}var Ld=300;function fy(t,e){var r=e||t.currentLayers||[],i=t,s=["text","yearMon"],o=s.indexOf(t.options.xAxisFormat)>-1?function(J){return J}:d3.format(t.options.xAxisFormat||""),h=d3.format(t.options.yAxisFormat||""),g=t.newScaleY?d3.format(t.newScaleY):h;Cd(t),r.forEach(function(J){["bar","point","hexbin","histogram","calendarHeatmap"].indexOf(J.type)>-1&&v(J)}),r.some(function(J){return J.type==="groupedBar"})&&t.chart.selectAll(".tag-grouped-bar-g rect").on("mouseout",K).on("mouseover",Y).on("mousemove",Y).on("touchstart",function(J){J.preventDefault(),Y.call(this,J)}).on("touchmove",function(J){J.preventDefault(),Y.call(this,J)}).on("touchend",K),r.length>0&&r.every(function(J){return["line","area"].indexOf(J.type)>-1})&&uy(t,ee,oe),r.some(function(J){return J.type==="donut"})&&se(".donut","donut",function(J,k){return{title:{text:k.mapping.x_var+": "+J.data[k.mapping.x_var]},items:[{color:t.colorDiscrete(J.index),label:k.mapping.y_var,value:J.data[k.mapping.y_var]}]}}),r.some(function(J){return J.type==="treemap"})&&t.chart.selectAll(".root").on("mouseout",q).on("mouseover",re).on("mousemove",re).on("touchstart",function(J){J.preventDefault(),re.call(this,J)}).on("touchmove",function(J){J.preventDefault(),re.call(this,J)}).on("touchend",q);function v(J){var k=fl(J),de=k.getHoverSelector?k.getHoverSelector(t,J):"."+xr(J.type,t.element.id,J.label);t.chart.selectAll(de).on("mouseout",function(){_.call(this,J)}).on("mouseover",function(ze){x.call(this,ze,J)}).on("mousemove",function(ze){x.call(this,ze,J)}).on("touchstart",function(ze){ze.preventDefault(),x.call(this,ze,J)}).on("touchmove",function(ze){ze.preventDefault(),x.call(this,ze,J)}).on("touchend",function(){_.call(this,J)})}function x(J,k){var de=d3.select(this).data()[0],ze=fl(k),er=A(k,ze,de,this);HTMLWidgets.shinyMode&&Shiny.onInputChange("myIO-"+i.element.id+"-rollover",JSON.stringify(de)),O(this,k,de),_2(i,{pointer:ue(J),title:er.title,items:er.items});var Er=k.type==="hexbin"?i.xScale?i.xScale.invert(de.x):null:k.type==="histogram"?de.x0:k.type==="calendarHeatmap"?de.date instanceof Date?de.date:new Date(de[k.mapping.date]+"T00:00:00Z"):de[k.mapping.x_var];N0(i,de,Er,er)}function _(J){I(this,J),ku(i),D0(i)}function A(J,k,de,ze){if(J.type==="hexbin"){var er=d3.format(",.2f");return{title:{text:"x: "+er(i.xScale.invert(de.x))+", y: "+er(i.yScale.invert(de.y))},items:[{color:d3.select(ze).attr("fill"),label:"Count",value:de.length}]}}if(J.type==="histogram")return{title:{text:"Bin: "+de.x0+" to "+de.x1},items:[{color:d3.select(ze).attr("fill"),label:"Count",value:de.length}]};if(J.type==="calendarHeatmap"){var Er=k.formatTooltip(i,de,J);return{title:{text:typeof Er.title=="string"?Er.title:Er.title.text},items:[{color:Er.color||d3.select(ze).attr("fill"),label:Er.label||J.label,value:Er.value}]}}var Ht=J.mapping.x_var+": "+o(de[J.mapping.x_var]),xn=i.newY?i.newY:J.mapping.y_var,$r=J.type==="point"||J.type==="bar"?J.mapping.y_var:J.label,Tn=Vs(i,J.label,J.color);if(k&&typeof k.formatTooltip=="function"){var In=k.formatTooltip(i,de,J);Ht=In.title||Ht,$r=In.label||$r,Tn=In.color||Tn}return{title:{text:Ht},items:[{color:Tn,label:$r,value:g(de[xn])}]}}function O(J,k){var de=d3.select(J),ze=k.type==="hexbin"?"#333":de.attr("fill")||de.style("fill")||Vs(i,k.label,k.color);if(k.type==="hexbin"){de.style("stroke",ze).style("stroke-width","2px");return}de.interrupt().style("stroke",ze).style("stroke-width","2px").style("stroke-opacity",.8),k.type==="point"&&de.attr("r",Math.max(+de.attr("r")||0,6))}function I(J,k){var de=d3.select(J);de.interrupt().transition().duration(Ld).style("stroke-width","0px").style("stroke","transparent").style("stroke-opacity",null),k.type==="point"&&de.transition().duration(Ld).attr("r",y2(i))}function Y(J){var k=d3.select(this).data()[0],de=r[k.idx],ze=Vs(i,de.label,de.color);HTMLWidgets.shinyMode&&Shiny.onInputChange("myIO-"+i.element.id+"-rollover",JSON.stringify(k.data.values)),d3.select(this).interrupt().style("stroke",ze).style("stroke-width","2px").style("stroke-opacity",.8);var er={title:{text:de.mapping.x_var+": "+o(k.data[0])},items:[{color:ze,label:de.mapping.y_var,value:g(k[1]-k[0])}]};_2(i,{pointer:ue(J),title:er.title,items:er.items}),N0(i,k.data,k.data[0],er)}function K(){d3.select(this).interrupt().transition().duration(Ld).style("stroke-width","0px").style("stroke","transparent").style("stroke-opacity",null),ku(i),D0(i)}function ee(J){var k=d3.pointer(J,this),de=i.xScale.invert(k[0]),ze=[],er=d3.bisector(function($r){return+$r[0]}).left;if(r.forEach(function($r){var Tn=$r.data,In=$r.mapping.x_var,cr=i.newY?i.newY:$r.mapping.y_var||$r.mapping.high_y,bn=Tn.map(function(hi){return hi[In]}),mn=er(bn,de),qn=Tn[mn-1],Wt=Tn[mn],Pr=qn?Wt&&de-qn[In]>Wt[In]-de?Wt:qn:Wt;Pr&&ze.push({color:$r.color,label:$r.label,xVar:In,yVar:cr,displayValue:Pr.density!=null?Pr.density:Pr[cr],value:Pr})}),ze.length===0){oe();return}HTMLWidgets.shinyMode&&Shiny.onInputChange("myIO-"+i.element.id+"-rollover",JSON.stringify(ze.map(function($r){return $r.value})));var Er=ze[0].value[ze[0].xVar];i.toolLine.style("stroke","var(--chart-ref-line-color)").style("stroke-width","1px").style("stroke-dasharray","4,4").attr("x1",i.xScale(Er)).attr("x2",i.xScale(Er)).attr("y1",0).attr("y2",i.height-(i.margin.top+i.margin.bottom));var Ht=i.toolPointLayer.selectAll("circle").data(ze);Ht.exit().remove(),Ht.enter().append("circle").attr("r",4).merge(Ht).attr("cx",function($r){return i.xScale($r.value[$r.xVar])}).attr("cy",function($r){return i.yScale($r.value[$r.yVar])}).attr("fill","#ffffff").attr("stroke",function($r){return $r.color}).attr("stroke-width",2);var xn={title:{text:ze[0].xVar+": "+o(Er)},items:ze.map(function($r){return{color:$r.color,label:$r.label,value:g($r.displayValue)}})};_2(i,{pointer:ue(J),title:xn.title,items:xn.items}),N0(i,ze[0].value,Er,xn)}function oe(){i.toolLine&&i.toolLine.style("stroke","none"),i.toolPointLayer&&i.toolPointLayer.selectAll("*").remove(),ku(i),D0(i)}function se(J,k,de){var ze=r.filter(function(er){return er.type===k})[0];t.chart.selectAll(J).on("mouseout",function(){t.chart.selectAll(J).transition().duration(Ld).style("opacity",1),ku(i)}).on("mouseover",function(er,Er){t.chart.selectAll(J).style("opacity",.4),d3.select(this).style("opacity",.85);var Ht=de(Er,ze);_2(i,{pointer:ue(er),title:Ht.title,items:Ht.items})}).on("mousemove",function(er,Er){var Ht=de(Er,ze);_2(i,{pointer:ue(er),title:Ht.title,items:Ht.items})}).on("touchstart",function(er,Er){er.preventDefault(),t.chart.selectAll(J).style("opacity",.4),d3.select(this).style("opacity",.85);var Ht=de(Er,ze);_2(i,{pointer:ue(er),title:Ht.title,items:Ht.items})}).on("touchend",function(){t.chart.selectAll(J).transition().duration(Ld).style("opacity",1),ku(i)})}function re(J,k){for(var de=r.filter(function(er){return er.type==="treemap"})[0],ze=k;ze.depth>1;)ze=ze.parent;t.chart.selectAll(".root").style("opacity",.4),d3.select(this).style("opacity",.85),_2(i,{pointer:ue(J),title:{text:de.mapping.level_1+": "+k.data[de.mapping.level_1]},items:[{color:t.colorDiscrete(ze.data.id),label:k.data[de.mapping.level_2],value:k.value}]})}function q(){t.chart.selectAll(".root").transition().duration(Ld).style("opacity",1),ku(i)}function ue(J){return d3.pointer(J,i.dom.element)}}var ax=.05,ox=.15;function hy(t,e){var r=t.margin,i=n1(t),s=[];e.forEach(function(v){var x=d3.extent(v.data,function(_){return+_[v.mapping.value]});s.push(x)});var o=d3.min(s,function(v){return v[0]}),h=d3.max(s,function(v){return v[1]}),g=d3.scaleLinear().domain([o,h]).nice().range([0,t.width-(r.left+r.right)]);e.forEach(function(v){var x=v.data.map(function(_){return _[v.mapping.value]});v.bins=d3.bin().domain(g.domain()).thresholds(g.ticks(v.mapping.bins))(x),v.max_value=d3.max(v.bins,function(_){return _.length})}),t.derived.xScale=g,t.derived.yScale=d3.scaleLinear().domain([0,d3.max(e,function(v){return v.max_value})]).nice().range([i-(r.top+r.bottom),0])}function py(t,e,r){var i=t.margin,s=[],o=[],h=[],g=[],v=r||{},x=v.xExtentFields||["x_var"],_=v.yExtentFields||["y_var"],A=e.filter(function(k){var de=k.scaleHints;return!(de&&Array.isArray(de.xExtentFields)&&de.xExtentFields.length===0&&Array.isArray(de.yExtentFields)&&de.yExtentFields.length===0)});A.forEach(function(k){var de=k.scaleHints&&Array.isArray(k.scaleHints.xExtentFields)?k.scaleHints.xExtentFields:x,ze=[];de.forEach(function(Tn){var In=k.mapping[Tn]||Tn,cr=k.data.map(function(bn){return+bn[In]});ze=ze.concat(cr)});var er=d3.extent(ze.length>0?ze:[0]),Er=k.scaleHints&&Array.isArray(k.scaleHints.yExtentFields)?k.scaleHints.yExtentFields:_,Ht=[];Er.forEach(function(Tn){var In=k.mapping[Tn]||Tn,cr=k.data.map(function(bn){return+bn[In]});Ht=Ht.concat(cr)});var xn=d3.extent(Ht.length>0?Ht:[0],function(Tn){return Tn});s.push(er),o.push([xn[0],xn[1]]);var $r=k.mapping.x_var;h.push(k.data.map(function(Tn){return Tn[$r]})),g.push(k.data.map(function(Tn){var In=k.mapping.y_var||"y_var";return Tn[In]}))});var O=d3.min(s,function(k){return k[0]}),I=d3.max(s,function(k){return k[1]}),Y=d3.min(s,function(k){return k[0]}),K=d3.max(s,function(k){return k[1]});t.derived.xCheck=Y===0&&K===0,O==I&&(O=O-1,I=I+1);var ee=Math.max(Math.abs(I-O)*ax,.5),oe=[t.config.scales.xlim.min?+t.config.scales.xlim.min:O-ee,t.config.scales.xlim.max?+t.config.scales.xlim.max:I+ee];t.derived.xBanded=[].concat.apply([],h).map(function(k){try{return Array.isArray(k)?k[0]:k}catch{return}}).filter(dy);var se=d3.min(o,function(k){return k[0]}),re=d3.max(o,function(k){return k[1]});se==re&&(se=se-1,re=re+1);var q=Math.abs(re-se)*ox,ue=[t.config.scales.ylim.min?+t.config.scales.ylim.min:se-q,t.config.scales.ylim.max?+t.config.scales.ylim.max:re+q];t.derived.yBanded=[].concat.apply([],g).map(function(k){try{return Array.isArray(k)?k[0]:k}catch{return}}).filter(dy);var J=n1(t);v.xScaleType==="band"?t.derived.xScale=d3.scaleBand().range([0,t.width-(i.left+i.right)]).domain(t.config.scales.flipAxis===!0?t.derived.yBanded:t.derived.xBanded):t.derived.xScale=d3.scaleLinear().range([0,t.width-(i.right+i.left)]).domain(t.config.scales.flipAxis===!0?ue:oe),v.yScaleType==="band"?t.derived.yScale=d3.scaleBand().range([J-(i.top+i.bottom),0]).domain(t.config.scales.flipAxis===!0?t.derived.xBanded:t.derived.yBanded):t.derived.yScale=d3.scaleLinear().range([J-(i.top+i.bottom),0]).domain(t.config.scales.flipAxis===!0?oe:ue),t.config.scales.colorScheme&&t.config.scales.colorScheme.enabled&&(t.derived.colorDiscrete=d3.scaleOrdinal().range(t.config.scales.colorScheme.colors).domain(t.config.scales.colorScheme.domain),t.derived.colorContinuous=d3.scaleLinear().range(t.config.scales.colorScheme.colors).domain(t.config.scales.colorScheme.domain)),t.syncLegacyAliases()}function dy(t,e,r){return r.indexOf(t)===e}var kh={xScaleType:"linear",yScaleType:"linear",xExtentFields:["x_var"],yExtentFields:["y_var"],domainMerge:"union"};function my(t){return t?Object.assign({},kh,t):null}function lx(t){if(t&&t.scaleHints)return my(t.scaleHints);try{var e=fl(t);return my(e.constructor.scaleHints)}catch{return null}}function R0(t,e){var r=t&&t.config&&t.config.scales&&t.config.scales.categoricalScale;return r&&r[e+"Axis"]===!0?"band":"linear"}function gy(t,e){var r=!!(t&&t.config&&t.config.scales&&t.config.scales.flipAxis),i=new Set,s=new Set,o=new Set,h=new Set,g="union";if((e||[]).forEach(function(v){var x=lx(v),_=R0(t,"x"),A=R0(t,"y"),O=x?x.xScaleType:_,I=x?x.yScaleType:A,Y=r?I:O,K=r?O:I;r||(_==="band"&&(Y="band"),A==="band"&&(K="band")),i.add(Y),s.add(K);var ee=x&&Array.isArray(x.xExtentFields)?x.xExtentFields:kh.xExtentFields;ee.forEach(function(se){o.add(se)});var oe=x&&Array.isArray(x.yExtentFields)?x.yExtentFields:kh.yExtentFields;oe.forEach(function(se){h.add(se)}),x&&x.domainMerge==="independent"&&(g="independent")}),i.size>1||s.size>1)throw new Error("Mismatched scaleTypes across layers: x="+Array.from(i).join(", ")+", y="+Array.from(s).join(", ")+".");return{xScaleType:i.size>0?Array.from(i)[0]:R0(t,"x"),yScaleType:s.size>0?Array.from(s)[0]:R0(t,"y"),xExtentFields:Array.from(o).length>0?Array.from(o):kh.xExtentFields,yExtentFields:Array.from(h).length>0?Array.from(h):kh.yExtentFields,domainMerge:g}}function Nd(t){var e=t.derived.currentLayers||[],r=e.map(function(o){return fl(o).constructor.traits}),i=e[0]?e[0].type:null,s=Array.from(new Set(r.map(function(o){return o.legendType})));return{type:i,axesChart:r.some(function(o){return o.hasAxes}),histogram:r.length>0&&r.every(function(o){return o.binning}),continuousLegend:s.length===1&&s[0]==="continuous",ordinalLegend:s.length===1&&s[0]==="ordinal",referenceLines:r.some(function(o){return o.referenceLines})}}function Dd(t,e){if(e.axesChart)if(e.histogram)hy(t,t.derived.currentLayers);else{var r=gy(t,t.derived.currentLayers);py(t,t.derived.currentLayers,r)}}var cx={line:"axes-continuous",point:"axes-continuous",area:"axes-continuous",bar:"axes-categorical",groupedBar:"axes-categorical",boxplot:"axes-categorical",violin:"axes-categorical",histogram:"axes-binned",heatmap:"axes-matrix",candlestick:"axes-continuous",waterfall:"axes-categorical",ridgeline:"axes-binned",rangeBar:"axes-continuous",sankey:"standalone-flow",hexbin:"axes-hex",treemap:"standalone-treemap",donut:"standalone-donut",gauge:"standalone-gauge",text:"axes-continuous",regression:"axes-continuous",bracket:"axes-continuous",comparison:"axes-categorical",qq:"axes-continuous",lollipop:"axes-categorical",dumbbell:"axes-categorical",waffle:"standalone-waffle",beeswarm:"axes-continuous",bump:"axes-continuous",survfit:"axes-continuous",histogram_fit:"axes-binned",quantile_dots:"axes-categorical",radar:"standalone-radar",funnel:"standalone-funnel",parallel:"standalone-parallel",calendarHeatmap:"standalone-calendar",fan:"axes-continuous"},ux=new Set(["axes-continuous:axes-categorical","axes-categorical:axes-continuous","axes-binned:axes-continuous","axes-continuous:axes-binned"]);function fx(t){if(t.length<=1)return{valid:!0,errors:[]};let e=[],r=t.map(function(o){return cx[o.type]||"unknown"}),i=r.filter(function(o){return o.startsWith("standalone")});i.length>0&&t.length>1&&e.push("Cannot mix standalone chart types with other layers."),i.length>1&&e.push("Standalone chart types must be used alone.");let s=Array.from(new Set(r));return s.length>1&&s.forEach(function(o,h){s.slice(h+1).forEach(function(g){ux.has(o+":"+g)||e.push("Cannot mix layer groups '"+o+"' and '"+g+"'.")})}),{valid:e.length===0,errors:e}}function dx(t,e){let r=[],i=[];return e?(Object.entries(e).forEach(function(s){let o=s[0],h=s[1],g=t.mapping?t.mapping[o]:null;if(h.required&&!g){r.push("Layer '"+t.label+"' is missing required mapping '"+o+"'.");return}if(!g)return;let v=Array.isArray(t.data)?typeof g=="string"?t.data.map(function(_){return _[g]}):t.data.map(function(){return g}):[];if(h.numeric&&v.find(function(A){return Number.isNaN(+A)})!==void 0&&r.push("Layer '"+t.label+"' field '"+g+"' must be numeric."),h.positive&&v.find(function(A){return+A<=0})!==void 0&&r.push("Layer '"+t.label+"' field '"+g+"' must be positive."),h.sorted){for(let _=1;_0&&i.push("Layer '"+t.label+"' field '"+g+"' contains "+x+" null/NaN values.")}),{errors:r,warnings:i}):{errors:r,warnings:i}}function k0(t){let e=t.derived.currentLayers||t.config.layers||[],r=fx(e);return r.valid?e.filter(function(i){let o=fl(i).constructor.dataContract,h=dx(i,o);return h.warnings.forEach(function(g){console.warn("[myIO]",g)}),h.errors.length>0?(h.errors.forEach(function(g){console.warn("[myIO] Layer '"+i.label+"' removed:",g),t.emit("error",{message:g,layer:i})}),!1):!0}):(r.errors.forEach(function(i){console.warn("[myIO] Composition error:",i),t.emit("error",{message:i})}),[])}function M0(t,e){e.referenceLines&&hx(t)}function hx(t){var e=t.margin,r=t.options.transition.speed,i=[t.options.referenceLine.x],s=[t.options.referenceLine.y];if(t.options.referenceLine.x){var o=t.plot.selectAll(".ref-x-line").data(i);o.exit().transition().duration(100).style("opacity",0).attr("y2",t.height-(e.top+e.bottom)).remove();var h=o.enter().append("line").attr("class","ref-x-line").attr("fill","none").style("stroke","gray").style("stroke-width",3).attr("x1",function(x){return t.xScale(x)}).attr("x2",function(x){return t.xScale(x)}).attr("y1",t.height-(e.top+e.bottom)).attr("y2",t.height-(e.top+e.bottom)).transition().ease(d3.easeQuad).duration(r).attr("y2",0);o.merge(h).transition().ease(d3.easeQuad).duration(r).attr("x1",function(x){return t.xScale(x)}).attr("x2",function(x){return t.xScale(x)}).attr("y1",t.height-(e.top+e.bottom)).attr("y2",0)}else t.plot.selectAll(".ref-x-line").remove();if(t.options.referenceLine.y){var g=t.plot.selectAll(".ref-y-line").data(s);g.exit().transition().duration(100).attr("y2",t.width-(e.left+e.right)).style("opacity",0).remove();var v=g.enter().append("line").attr("class","ref-y-line").attr("fill","none").style("stroke","gray").style("stroke-width",3).attr("x1",0).attr("x2",0).attr("y1",function(x){return t.yScale(x)}).attr("y2",function(x){return t.yScale(x)}).transition().ease(d3.easeQuad).duration(r).attr("x2",t.width-(e.left+e.right));g.merge(v).transition().ease(d3.easeQuad).duration(r).attr("x1",0).attr("x2",t.width-(e.left+e.right)).attr("y1",function(x){return t.yScale(x)}).attr("y2",function(x){return t.yScale(x)})}else t.plot.selectAll(".ref-y-line").remove()}function yy(t,e,r){let i=t.map(function(O){return O[r]}),s=t.map(function(O){return O[e]}),o={},h=s.length,g=0,v=0,x=0,_=0,A=0;for(let O=0;O0)return s.length}var o=r?r.clientWidth:this.controller.chart.runtime.totalWidth;return Math.max(Math.floor(o/(this.controller.config.minWidth||200)),1)}hasPanelData(){for(var e=0;e0)return!0;return!1}addLabel(){d3.select(this.element).append("div").attr("class","myIO-facet-label").text(this.facetValue)}renderPanel(){var e=this.buildPanelChart(),r=Nd(e);r.axesChart&&(Dd(e,r),this.applySharedDomains(e)),g0(e),e.dom.svg=e.svg,e.dom.plot=e.plot,e.dom.chartArea=e.chart,r.axesChart&&this.requiresClipPath(r.type)&&(this.setClipPath(e),b0(e,r,{isInitialRender:!0}),this.applyAxisSuppression(e),M0(e,r,{isInitialRender:!0})),this.renderLayers(e,this.layers),this.panelChart=e}buildPanelChart(){var e=this.controller.chart,r=Math.max(this.element.clientWidth||this.controller.config.minWidth||200,1),i=this.buildMargin(),s=Object.assign({},e.config,{layers:this.layers}),o={margin:i,suppressLegend:!0,suppressAxis:{xAxis:this.suppressX,yAxis:this.suppressY},xlim:s.scales.xlim,ylim:s.scales.ylim,categoricalScale:s.scales.categoricalScale,flipAxis:s.scales.flipAxis,colorScheme:s.scales.colorScheme?s.scales.colorScheme.enabled?[s.scales.colorScheme.colors,s.scales.colorScheme.domain,"on"]:[s.scales.colorScheme.colors,s.scales.colorScheme.domain,"off"]:null,xAxisFormat:s.axes.xAxisFormat,yAxisFormat:s.axes.yAxisFormat,toolTipFormat:s.axes.toolTipFormat,xTickLabels:s.axes.xTickLabels,xAxisLabel:s.axes.xAxisLabel,yAxisLabel:s.axes.yAxisLabel,dragPoints:!1,toggleY:null,toolTipOptions:s.interactions.toolTipOptions,transition:{speed:0},referenceLine:s.referenceLines};return{element:this.element,dom:{element:this.element},config:s,derived:{currentLayers:this.layers.slice()},runtime:{totalWidth:r,width:r,height:Mh,layout:e.runtime.layout,activeY:e.runtime.activeY,activeYFormat:e.runtime.activeYFormat},options:o,margin:i,width:r,height:Mh,totalWidth:r,layout:e.runtime.layout,newY:e.runtime.activeY,newScaleY:e.runtime.activeYFormat,plotLayers:this.layers,emit:function(){},dragPoints:function(){},updateRegression:function(){},syncLegacyAliases:function(){this.xScale=this.derived?this.derived.xScale:null,this.yScale=this.derived?this.derived.yScale:null,this.colorDiscrete=this.derived?this.derived.colorDiscrete:null,this.colorContinuous=this.derived?this.derived.colorContinuous:null,this.x_banded=this.derived?this.derived.xBanded:null,this.y_banded=this.derived?this.derived.yBanded:null,this.x_check=this.derived?this.derived.xCheck:null,this.currentLayers=this.derived?this.derived.currentLayers:null},captureLegacyAliases:function(){}}}buildMargin(){var e=this.controller.chart.config.layout.margin||{},r={top:e.top!=null?e.top:30,right:e.right!=null?e.right:5,bottom:e.bottom!=null?e.bottom:60,left:e.left!=null?e.left:50};return this.suppressX&&(r.bottom=Math.min(r.bottom,12)),this.suppressY&&(r.left=Math.min(r.left,12)),r}applySharedDomains(e){var r=this.controller.globalScaleSnapshot;!r||!e.derived||!e.derived.xScale||!e.derived.yScale||(r.xDomain&&e.derived.xScale.domain(r.xDomain.slice()),r.yDomain&&e.derived.yScale.domain(r.yDomain.slice()),r.xBanded&&(e.derived.xBanded=r.xBanded.slice()),r.yBanded&&(e.derived.yBanded=r.yBanded.slice()),typeof r.xCheck<"u"&&(e.derived.xCheck=r.xCheck),r.colorDiscrete&&(e.derived.colorDiscrete=r.colorDiscrete),r.colorContinuous&&(e.derived.colorContinuous=r.colorContinuous),e.syncLegacyAliases())}requiresClipPath(e){return e!=="donut"&&e!=="gauge"}setClipPath(e){var r=e.height-(e.margin.top+e.margin.bottom);e.dom.clipPath=e.dom.chartArea.append("defs").append("svg:clipPath").attr("id",e.dom.element.id+"clip").append("svg:rect").attr("x",0).attr("y",0).attr("width",e.width-(e.margin.left+e.margin.right)).attr("height",r),e.dom.chartArea.attr("clip-path","url(#"+e.dom.element.id+"clip)"),e.clipPath=e.dom.clipPath}applyAxisSuppression(e){this.suppressX&&e.plot.selectAll(".x-axis").remove(),this.suppressY&&e.plot.selectAll(".y-axis").remove()}renderLayers(e,r){for(var i=0;i1?_+": ":"";e.push(O+x.below+" of "+A+" dots below threshold of "+i+".")})}}}),e}function xy(t){return String(t).replace(/[^a-zA-Z0-9_-]/g,"")}function bx(t,e){if(!t.dom||!t.dom.chartArea||!e)return null;for(var r=t.dom.chartArea,i=[".tag-"+e.type+"-"+e.id,".tag-"+e.type+"-"+t.dom.element.id+"-"+xy(e.label)],s=0;s0&&e.visibility!==!1})}destroy(){this.chart.dom.svg.on("keydown.a11y",null),this.liveRegion&&this.liveRegion.remove(),clearTimeout(this.debounceTimer)}};var j0=class{constructor(e){this.chart=e,this.tableContainer=null,this.visible=!1}initialize(){this.tableContainer=d3.select(this.chart.dom.element).append("div").attr("class","myIO-data-table myIO-sr-only").attr("role","region").attr("aria-label","Chart data table")}generate(){if(this.tableContainer){this.tableContainer.selectAll("*").remove();for(var e=this.chart.config.layers,r=500,i=new Map,s=[],o=0;or&&this.tableContainer.append("p").text("Showing first "+r+" of "+A.length+" rows")}}}renderFanTable(e,r){if(!(!e||e.length===0)){var i=e[0],s=i.mapping&&i.mapping.x_var?i.mapping.x_var:"x_var",o=new Map,h=[];e.forEach(function(I){var Y=I.options&&I.options.interval_pct;if(Y!=null){var K=_y(Y);h.push(+Y),(Array.isArray(I.data)?I.data:[]).forEach(function(ee){var oe=String(ee[s]);o.has(oe)||o.set(oe,{x_var:ee[s]});var se=o.get(oe);se["low_"+K]=ee[I.mapping.low_y],se["high_"+K]=ee[I.mapping.high_y]})}}),h=Array.from(new Set(h)).sort(function(I,Y){return I-Y});var g=["x_var"];h.forEach(function(I){var Y=_y(I);g.push("low_"+Y),g.push("high_"+Y)});var v=Array.from(o.values()),x=v.slice(0,r),_=this.tableContainer.append("table").attr("aria-label","Data for "+(i._composite||"fan")),A=_.append("thead").append("tr");g.forEach(function(I){A.append("th").attr("scope","col").text(I)});var O=_.append("tbody");x.forEach(function(I){var Y=O.append("tr");g.forEach(function(K){var ee=I[K];Y.append("td").text(ee!=null?String(ee):"")})}),v.length>r&&this.tableContainer.append("p").text("Showing first "+r+" of "+v.length+" rows")}}toggle(){this.visible=!this.visible,this.visible?(this.generate(),this.tableContainer.classed("myIO-sr-only",!1),this.chart.dom.svg.attr("aria-hidden","true")):(this.tableContainer.classed("myIO-sr-only",!0),this.chart.dom.svg.attr("aria-hidden",null))}destroy(){this.tableContainer&&this.tableContainer.remove()}};function _y(t){return String(t).replace(/\.0+$/,"").replace(/(\.\d*?)0+$/,"$1")}var d6=280,Sx=100,Ex={on(t,e){return this._listeners=this._listeners||{},this._listeners[t]=this._listeners[t]||[],this._listeners[t].push(e),this},off(t,e){return!this._listeners||!this._listeners[t]?this:(this._listeners[t]=e?this._listeners[t].filter(function(r){return r!==e}):[],this)},emit(t,e){return!this._listeners||!this._listeners[t]?this:(this._listeners[t].forEach(function(r){r(e)}),this)}},q0=class{constructor(e){Object.assign(this,Ex),this._listeners={},this.config=e.config,this.dom={element:e.element},this.derived={},this.runtime={renderGen:0,resizeTimer:null,width:Math.max(e.width,d6),height:e.height,totalWidth:Math.max(e.width,d6),layout:"grouped",activeY:null,activeYFormat:null,tooltipHideTimer:null},this.config.sparkline&&this.applySparklineOverrides(),window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches&&(this.config.transitions.speed=0),this.runtime.width=this.runtime.totalWidth,this.syncLegacyAliases(),this.draw()}syncLegacyAliases(){this.element=this.dom?this.dom.element:null,this.svg=this.dom?this.dom.svg:null,this.plot=this.dom?this.dom.plot:null,this.chart=this.dom?this.dom.chartArea:null,this.legendArea=this.dom?this.dom.legendArea:null,this.clipPath=this.dom?this.dom.clipPath:null,this.tooltip=this.dom?this.dom.tooltip:null,this.toolTipTitle=this.dom?this.dom.tooltipTitle:null,this.toolTipBody=this.dom?this.dom.tooltipBody:null,this.plotLayers=this.config?this.config.layers:null,this.options=this.config?{margin:this.config.layout.margin,suppressLegend:this.config.layout.suppressLegend,suppressAxis:this.config.layout.suppressAxis,xlim:this.config.scales.xlim,ylim:this.config.scales.ylim,categoricalScale:this.config.scales.categoricalScale,flipAxis:this.config.scales.flipAxis,colorScheme:this.config.scales.colorScheme?this.config.scales.colorScheme.enabled?[this.config.scales.colorScheme.colors,this.config.scales.colorScheme.domain,"on"]:[this.config.scales.colorScheme.colors,this.config.scales.colorScheme.domain,"off"]:null,xAxisFormat:this.config.axes.xAxisFormat,yAxisFormat:this.config.axes.yAxisFormat,toolTipFormat:this.config.axes.toolTipFormat,xTickLabels:this.config.axes.xTickLabels,xAxisLabel:this.config.axes.xAxisLabel,yAxisLabel:this.config.axes.yAxisLabel,dragPoints:this.config.interactions.dragPoints,toggleY:this.config.interactions.toggleY&&this.config.interactions.toggleY.variable?[this.config.interactions.toggleY.variable,this.config.interactions.toggleY.format]:null,toolTipOptions:this.config.interactions.toolTipOptions,transition:this.config.transitions,referenceLine:this.config.referenceLines}:null,this.margin=this.config?this.config.layout.margin:null,this.width=this.runtime?this.runtime.width:null,this.height=this.runtime?this.runtime.height:null,this.totalWidth=this.runtime?this.runtime.totalWidth:null,this.layout=this.runtime?this.runtime.layout:null,this.newY=this.runtime?this.runtime.activeY:null,this.newScaleY=this.runtime?this.runtime.activeYFormat:null,this.toolLine=this.runtime?this.runtime.toolLine:null,this.toolTipBox=this.runtime?this.runtime.toolTipBox:null,this.toolPointLayer=this.runtime?this.runtime.toolPointLayer:null,this.xScale=this.derived?this.derived.xScale:null,this.yScale=this.derived?this.derived.yScale:null,this.colorDiscrete=this.derived?this.derived.colorDiscrete:null,this.colorContinuous=this.derived?this.derived.colorContinuous:null,this.x_banded=this.derived?this.derived.xBanded:null,this.y_banded=this.derived?this.derived.yBanded:null,this.x_check=this.derived?this.derived.xCheck:null,this.currentLayers=this.derived?this.derived.currentLayers:null,this.layerIndex=this.derived?this.derived.layerIndex:null}captureLegacyAliases(){!this.dom||!this.runtime||!this.derived||(this.dom.svg=this.svg||this.dom.svg,this.dom.plot=this.plot||this.dom.plot,this.dom.chartArea=this.chart||this.dom.chartArea,this.dom.legendArea=this.legendArea||this.dom.legendArea,this.dom.clipPath=this.clipPath||this.dom.clipPath,this.dom.tooltip=this.tooltip||this.dom.tooltip,this.dom.tooltipTitle=this.toolTipTitle||this.dom.tooltipTitle,this.dom.tooltipBody=this.toolTipBody||this.dom.tooltipBody,this.runtime.layout=this.layout||this.runtime.layout,this.runtime.activeY=this.newY||this.runtime.activeY,this.runtime.activeYFormat=this.newScaleY||this.runtime.activeYFormat,this.runtime.toolLine=this.toolLine||this.runtime.toolLine,this.runtime.toolTipBox=this.toolTipBox||this.runtime.toolTipBox,this.runtime.toolPointLayer=this.toolPointLayer||this.runtime.toolPointLayer,this.derived.xScale=this.xScale||this.derived.xScale,this.derived.yScale=this.yScale||this.derived.yScale,this.derived.colorDiscrete=this.colorDiscrete||this.derived.colorDiscrete,this.derived.colorContinuous=this.colorContinuous||this.derived.colorContinuous,this.derived.xBanded=this.x_banded||this.derived.xBanded,this.derived.yBanded=this.y_banded||this.derived.yBanded,this.derived.xCheck=this.x_check||this.derived.xCheck,this.derived.currentLayers=this.currentLayers||this.derived.currentLayers,this.derived.layerIndex=this.layerIndex||this.derived.layerIndex,this.syncLegacyAliases())}draw(){g0(this),this.captureLegacyAliases(),this.initialize()}initialize(){this.derived.currentLayers=this.config.layers,this.syncLegacyAliases(),this.themeManager=new B0(this.dom.element,this.config),this.themeManager.initialize(),cy(this),this.config.sparkline||(this.keyboardNav=new G0(this),this.keyboardNav.initialize(),this.dataTable=new j0(this),this.dataTable.initialize(),V0(this)),this.captureLegacyAliases(),this.derived.currentLayers.length>0&&this.setClipPath(this.derived.currentLayers[0].type),this.renderCurrentLayers({isInitialRender:!0})}applySparklineOverrides(){this.config.layout.margin={top:1,right:1,bottom:1,left:1},this.config.layout.suppressLegend=!0,this.config.layout.suppressAxis={xAxis:!0,yAxis:!0},this.config.interactions.brush&&(this.config.interactions.brush.enabled=!1),this.config.interactions.annotation&&(this.config.interactions.annotation.enabled=!1),this.config.interactions.linked&&(this.config.interactions.linked.enabled=!1),this.config.interactions.sliders=[],this.config.interactions.dragPoints=!1,this.config.referenceLines={x:null,y:null},this.dom.element.dataset.sparkline="true"}renderCurrentLayers(e){let r=e||{},i=++this.runtime.renderGen,s=()=>this.runtime&&this.runtime.renderGen===i;if(this.config.facet&&this.config.facet.enabled){this.facetController||(this.facetController=new $0(this)),this.facetController.initialize();return}else this.facetController&&(this.facetController.destroy(),this.facetController=null);try{if(this.dom.chartArea){this.dom.chartArea.selectAll("*").interrupt();var o=this.derived.currentLayers.map(function(x){return x.label}),h=this.config.layers.map(function(x){return x.label}),g=this.dom.chartArea;h.forEach(function(x){if(o.indexOf(x)===-1){var _=String(x).replace(/\s+/g,"");g.selectAll("[class*='tag-'][class*='-"+_+"']").remove()}})}if(this.emit("beforeRender",{options:r}),y0(this),this.derived.currentLayers=k0(this),this.syncLegacyAliases(),this.clearEmptyState(),!s())return;if(this.derived.currentLayers.length===0){this.renderEmptyState(),this.config.sparkline||V0(this);return}let v=Nd(this);if(Dd(this,v),this.syncLegacyAliases(),!s())return;e6(this),this.emit("afterScales",{state:v}),b0(this,v,r),this.routeLayers(this.derived.currentLayers),M0(this,v,r),Vg(this,v),fy(this),C0(this),this.config.interactions.brush&&this.config.interactions.brush.enabled&&Yg(this),this.config.interactions.annotation&&this.config.interactions.annotation.enabled&&Qg(this),this.config.interactions.linked&&this.config.interactions.linked.enabled&&sy(this),this.config.interactions.linked&&this.config.interactions.linked.cursor===!0&&ty(this),this.config.interactions.sliders&&this.config.interactions.sliders.length>0&&oy(this),this.emit("afterRender",{state:v}),this.config.sparkline||V0(this)}catch(v){throw console.warn("[myIO] Render error:",v.message),this.emit("error",{message:v.message,error:v}),v}}clearEmptyState(){this.dom&&this.dom.svg&&this.dom.svg.selectAll(".myIO-empty-state").remove(),this.dom&&this.dom.element&&d3.select(this.dom.element).select(".myIO-fab").style("display",null)}renderEmptyState(){this.dom.chartArea&&this.dom.chartArea.selectAll("*").interrupt().remove(),this.dom.plot&&(this.dom.plot.selectAll(".x-axis, .y-axis").interrupt().remove(),this.dom.plot.selectAll(".ref-x-line, .ref-y-line").remove()),Cd(this),ku(this),this.runtime&&this.runtime._sheetOpen&&Ru(this,{returnFocus:!1}),this.dom.element&&d3.select(this.dom.element).select(".myIO-fab").style("display","none"),this.dom.svg&&(this.dom.svg.selectAll(".myIO-empty-state").remove(),this.dom.svg.append("text").attr("class","myIO-empty-state").attr("x",this.runtime.totalWidth/2).attr("y",this.runtime.height/2).text("No data to display"))}addButtons(){e6(this)}toggleVarY(e){this.runtime.activeY=e[0],this.runtime.activeYFormat=e[1],this.syncLegacyAliases(),this.renderCurrentLayers()}toggleGroupedLayout(e){var r=S0(e,this),i=e.map(function(o){return o.color}),s=(this.runtime.width-(this.config.layout.margin.right+this.config.layout.margin.left))/(r[0].length+1)/i.length;this.runtime.layout==="stacked"?(x0(this,r,i,s),this.runtime.layout="grouped"):(_0(this,r,i,s),this.runtime.layout="stacked"),this.syncLegacyAliases()}setClipPath(e){switch(e){case"donut":case"gauge":break;default:var r=n1(this);this.dom.clipPath=this.dom.chartArea.append("defs").append("svg:clipPath").attr("id",this.dom.element.id+"clip").append("svg:rect").attr("x",0).attr("y",0).attr("width",this.runtime.width-(this.config.layout.margin.left+this.config.layout.margin.right)).attr("height",r-(this.config.layout.margin.top+this.config.layout.margin.bottom)),this.dom.chartArea.attr("clip-path","url(#"+this.dom.element.id+"clip)"),this.syncLegacyAliases()}}routeLayers(e){var r=this;this.derived.layerIndex=this.config.layers.map(function(i){return i.label}),this.syncLegacyAliases(),e.forEach(function(i){var s=fl(i);if(s&&typeof s.render=="function"){s.render(r,i,e),r.captureLegacyAliases();var o=i.options&&i.options.opacity!=null?i.options.opacity:1;if(o<1){var h=String(i.label).replace(/\s+/g,"");r.dom.chartArea.selectAll("[class*='tag-'][class*='-"+h+"']").style("opacity",o)}}})}removeLayers(e){e.forEach(r=>{zg().forEach(function(i){typeof i.remove=="function"?i.remove(this,{label:r}):["line","bar","point","regression-line","hexbin","area","crosshairY","crosshairX"].forEach(function(s){d3.selectAll("."+xr(s,this.dom.element.id,r)).transition().duration(500).style("opacity",0).remove()},this)},this)})}dragPoints(e){Hg(this,e)}updateOrdinalColorLegend(e){od(this,e)}updateRegression(e,r){let i=(this.config.layers||[]).find(function(s){return s.label===r&&s.type==="point"});i&&(this.config.layers||[]).forEach(function(s){if(s.type!=="line"||s.transform!=="lm"||!s.mapping||!i.mapping||s.mapping.x_var!==i.mapping.x_var||s.mapping.y_var!==i.mapping.y_var)return;let o=yy(i.data,i.mapping.y_var,i.mapping.x_var),h=i.data.map(function(g){return{...g,[s.mapping.y_var]:o.fn(g[s.mapping.x_var])}}).sort(function(g,v){return g[s.mapping.x_var]-v[s.mapping.x_var]});s.data=h,t6("line").render(this,{...s,color:e||s.color},this.config.layers)},this)}updateChart(e){let r=this.derived.layerIndex||[];this.config=e,this.derived.currentLayers=this.config.layers,this.syncLegacyAliases();let i=this.config.layers.map(function(o){return o.label}),s=r.filter(function(o){return!i.includes(o)});this.removeLayers(s),this.renderCurrentLayers()}resize(e,r){if(!e||!r||e<2||r<2)return;let i=this.runtime&&this.runtime._sheetOpen===!0;i&&Ru(this,{returnFocus:!1}),this.runtime.totalWidth=Math.max(e,d6),this.runtime.width=this.runtime.totalWidth,this.runtime.height=r,this.syncLegacyAliases(),clearTimeout(this.runtime.resizeTimer),this.runtime.resizeTimer=setTimeout(()=>{gg(this),this.captureLegacyAliases(),this.renderCurrentLayers(),i&&this.derived&&this.derived.currentLayers&&this.derived.currentLayers.length>0&&A0(this),this.emit("resize",{width:this.runtime.width,height:this.runtime.height})},Sx)}destroy(){this.emit("destroy",{}),clearTimeout(this.runtime&&this.runtime.resizeTimer),clearTimeout(this.runtime&&this.runtime.tooltipHideTimer),this.facetController&&(this.facetController.destroy(),this.facetController=null),this.keyboardNav&&this.keyboardNav.destroy(),this.dataTable&&this.dataTable.destroy(),this.themeManager&&this.themeManager.destroy(),this.runtime&&this.runtime._sheetOpen&&Ru(this,{returnFocus:!1}),clearTimeout(this.runtime&&this.runtime._sheetCloseTimer),C0(this),Zg(this),o6(this),l6(this),this.dom&&this.dom.element&&d3.select(this.dom.element).on("keydown.brush",null),this.dom&&this.dom.chartArea&&this.dom.chartArea.selectAll("*").interrupt(),this.dom&&this.dom.svg&&this.dom.svg.remove(),this.dom&&this.dom.tooltip&&this.dom.tooltip.remove(),this.dom&&this.dom.element&&d3.select(this.dom.element).selectAll(".myIO-fab, .myIO-panel, .myIO-sheet-backdrop").remove(),Cd(this),this._listeners={},this.config=null,this.derived=null,this.dom=null,this.runtime=null}};var z0=class{constructor({max:e=128}={}){this.max=e,this.lru=new Map,this.inflight=new Map}get(e){if(!this.lru.has(e))return;let r=this.lru.get(e);return this.lru.delete(e),this.lru.set(e,r),r}set(e,r){for(this.lru.has(e)&&this.lru.delete(e),this.lru.set(e,r);this.lru.size>this.max;){let i=this.lru.keys().next().value;this.lru.delete(i)}}delete(e){this.lru.delete(e)}clear(){this.lru.clear(),this.inflight.clear()}size(){return this.lru.size}inflightOrStore(e,r){if(this.inflight.has(e))return this.inflight.get(e);let i=r();return this.inflight.set(e,i),i}resolveInflight(e,r){this.set(e,r),this.inflight.delete(e)}rejectInflight(e){this.inflight.delete(e)}};var H0=class{constructor(){this.sources=new Map}register(e){if(!e||typeof e.sourceId!="string")throw new Error("SourceRegistry.register: entry must have sourceId");e.mode!=="none"&&this.sources.set(e.sourceId,e)}unregister(e){this.sources.delete(e)}get(e){return this.sources.get(e)}has(e){return this.sources.has(e)}all(){return Array.from(this.sources.values())}clear(){this.sources.clear()}};var W0=class{constructor(e={}){}async init(e={}){}async cancel(e){}async close(){}async applyPredicateCache(e,r){}async*query({queryId:e}){yield{__trailer:!0,queryId:e,rowCount:0,elapsedMs:0}}};function Y0(t){if(typeof Uint8Array.fromBase64=="function")return Uint8Array.fromBase64(t);let e=atob(t),r=e.length,i=new Uint8Array(r);for(let s=0;s(Kb(),Jb)),Promise.resolve().then(()=>m0(Qb()))]),s=i.default||i;for(let o of e.all()){if(o.mode!=="inline_ipc"||!o.ipcB64)continue;let h=Y0(o.ipcB64),g=r.tableFromIPC(h),v=g.toArray().map(x=>Object.assign({},x));s.tables[o.sourceId]={data:v},this.sources.set(o.sourceId,{table:g,rows:v})}this._alasql=s}async*query({sql:e,params:r=[],queryId:i,signal:s}){if(this._closed)throw Object.assign(new Error("engine-gone"),{queryId:i,code:"engine-gone"});if(s&&s.aborted)throw Object.assign(new Error("cancelled"),{queryId:i,code:"cancelled"});let o=Date.now(),h;try{h=this._alasql.exec(e,r)}catch(g){throw Object.assign(new Error(g.message||String(g)),{queryId:i,code:"syntax"})}yield{rows:h,queryId:i},yield{__trailer:!0,queryId:i,rowCount:Array.isArray(h)?h.length:0,elapsedMs:Date.now()-o}}async cancel(e){}async applyPredicateCache(e,r){}async close(){if(this._alasql)for(let e of this.sources.keys())delete this._alasql.tables[e];this.sources.clear(),this._closed=!0}};var vm=class{constructor(e={}){this.config=e,this.pending=new Map,this.batchWindow=e&&e.shiny_batch_window||4,this._handlersRegistered=!1}async init({sourceRegistry:e}={}){if(typeof Shiny>"u")throw Object.assign(new Error("Shiny is not available in this context"),{code:"engine-gone"});if(this._handlersRegistered)return;let r=o=>this._route("batch",o),i=o=>this._route("end",o),s=o=>this._route("error",o);Shiny.addCustomMessageHandler("myio:batch",r),Shiny.addCustomMessageHandler("myio:end",i),Shiny.addCustomMessageHandler("myio:error",s),this._handlersRegistered=!0}_route(e,r){let i=this.pending.get(r.queryId);i&&(e==="batch"?(i.push(r),Shiny.setInputValue("myio_ack",{v:1,queryId:r.queryId,seq:r.seq},{priority:"event"})):e==="end"?(i.push({__trailer:!0,queryId:r.queryId,rowCount:r.rowCount,elapsedMs:r.elapsedMs}),i.end()):e==="error"&&i.error(Object.assign(new Error(r.message||"engine error"),{queryId:r.queryId,code:r.code||"engine-gone"})))}query({sql:e,params:r=[],queryId:i,signal:s,templateId:o,sourceId:h,bindings:g,predicateHash:v,limit:x}){if(typeof Shiny>"u")throw Object.assign(new Error("Shiny not available"),{queryId:i,code:"engine-gone"});let _=[],A=[],O=!1,I=null,Y=re=>{A.length?A.shift()({value:re,done:!1}):_.push(re)},K=()=>{for(O=!0;A.length;)A.shift()({value:void 0,done:!0})},ee=re=>{for(I=re;A.length;)A.shift()({value:void 0,done:!0})};this.pending.set(i,{push:Y,end:K,error:ee,seqBudget:this.batchWindow});let oe=null;s&&(oe=()=>{Shiny.setInputValue("myio_cancel",{v:1,queryId:i},{priority:"event"}),ee(Object.assign(new Error("cancelled"),{queryId:i,code:"cancelled"}))},s.aborted?oe():s.addEventListener("abort",oe)),I||Shiny.setInputValue("myio_query",{v:1,queryId:i,templateId:o||null,sourceId:h||null,predicateHash:v||null,bindings:g||{},limit:x||null,_debugSql:e},{priority:"event"});let se=this.pending;return(async function*(){try{for(;;){if(I)throw I;if(_.length){yield _.shift();continue}if(O)return;let re=await new Promise(q=>A.push(q));if(re.done){if(I)throw I;return}yield re.value}}finally{s&&oe&&s.removeEventListener("abort",oe),se.delete(i)}})()}async cancel(e){typeof Shiny<"u"&&Shiny.setInputValue("myio_cancel",{v:1,queryId:e},{priority:"event"});let r=this.pending.get(e);r&&r.error(Object.assign(new Error("cancelled"),{queryId:e,code:"cancelled"}))}async applyPredicateCache(e,r){}async close(){for(let[,e]of this.pending)e.error(Object.assign(new Error("engine closed"),{code:"engine-gone"}));this.pending.clear()}};var xm=class{constructor(e={}){this.config=e,this.cacheUrl=e.duckdb_wasm&&e.duckdb_wasm.cache_url||null,this.workerUrl=e.duckdb_wasm&&e.duckdb_wasm.worker_url||null,this.db=null,this.conn=null,this._duckdb=null,this._closed=!1}async init({sourceRegistry:e}={}){if(this._closed)throw Object.assign(new Error("engine-gone"),{code:"engine-gone"});if(!this.cacheUrl||!this.workerUrl)throw Object.assign(new Error("WasmEngineAdapter: duckdb_wasm cache_url / worker_url not set. Ensure myIO::install_duckdb_wasm() has run."),{code:"engine-gone"});let r=this.cacheUrl.replace(/\/?$/,"/")+"duckdb-browser.mjs",i;try{i=await import(r)}catch(g){throw Object.assign(new Error("WasmEngineAdapter: failed to import duckdb-wasm loader from "+r+": "+(g?.message||g)),{code:"engine-gone"})}this._duckdb=i;let s=new Worker(this.workerUrl),o=this.cacheUrl.replace(/\/?$/,"/")+"duckdb-mvp.wasm",h=new i.ConsoleLogger;if(this.db=new i.AsyncDuckDB(h,s),await this.db.instantiate(o),this.conn=await this.db.connect(),e)for(let g of e.all())await this._registerSource(g)}async _registerSource(e){if(!this._duckdb)return;let r=this._duckdb.DuckDBDataProtocol;if(e.mode==="inline_ipc"&&e.ipcB64){let i=Y0(e.ipcB64),s=e.sourceId+".arrow";await this.db.registerFileBuffer(s,i),await this.conn.query('CREATE OR REPLACE VIEW "'+e.sourceId.replace(/"/g,'""')+`" AS SELECT * FROM read_arrow('`+s+"');")}else if(e.mode==="url"&&e.url){let i=e.sourceId+(/\.parquet$/i.test(e.url)?".parquet":/\.arrow$/i.test(e.url)?".arrow":/\.feather$/i.test(e.url)?".feather":".csv");await this.db.registerFileURL(i,e.url,r.HTTP,!1);let s=/\.parquet$/i.test(e.url)?"read_parquet":/\.arrow$/i.test(e.url)||/\.feather$/i.test(e.url)?"read_arrow":"read_csv_auto";await this.conn.query('CREATE OR REPLACE VIEW "'+e.sourceId.replace(/"/g,'""')+'" AS SELECT * FROM '+s+"('"+i+"');")}}async*query({sql:e,params:r=[],queryId:i,signal:s}){if(this._closed)throw Object.assign(new Error("engine-gone"),{queryId:i,code:"engine-gone"});if(s&&s.aborted)throw Object.assign(new Error("cancelled"),{queryId:i,code:"cancelled"});let o=Date.now(),h,g=null;try{h=await this.conn.send(e)}catch(x){throw Object.assign(new Error(x?.message||String(x)),{queryId:i,code:"syntax"})}s&&(g=()=>{this.conn&&this.conn.cancelSent().catch(()=>{})},s.addEventListener("abort",g));let v=0;try{for(;;){if(s&&s.aborted){try{await this.conn.cancelSent()}catch{}throw Object.assign(new Error("cancelled"),{queryId:i,code:"cancelled"})}let{done:x,value:_}=await h.next();if(x)break;_&&(v+=_.numRows||0,yield{batch:_,queryId:i})}}finally{s&&g&&s.removeEventListener("abort",g);try{await h.return()}catch{}}yield{__trailer:!0,queryId:i,rowCount:v,elapsedMs:Date.now()-o}}async cancel(e){if(this.conn)try{await this.conn.cancelSent()}catch{}}async applyPredicateCache(e,r){}async close(){if(this._closed=!0,this.conn){try{await this.conn.close()}catch{}this.conn=null}if(this.db){try{await this.db.terminate()}catch{}this.db=null}}};function _m(t,e={}){switch(t){case"svg":return new W0(e);case"memory":return new bm(e);case"wasm":return new xm(e);case"server":return new vm(e);default:throw new Error("createEngine: unknown engine '"+t+"'")}}var Fp=class{constructor({config:e}){this.config=e||{},this.cache=new z0({max:128}),this.sourceRegistry=new H0,this.charts=new Map,this.selectionStore=new Map,this.adapters=new Map,this._adapterInits=new Map,this._inflightControllers=new Map,this._debouncers=new Map}ensureAdapterFor(e,r,i){if(this.adapters.has(e))return Promise.resolve(this.adapters.get(e));if(this._adapterInits.has(e))return this._adapterInits.get(e);let s=_m(r,i),o=s.init({sourceRegistry:this.sourceRegistry}).then(()=>(this.adapters.set(e,s),this._adapterInits.delete(e),s)).catch(h=>{throw this._adapterInits.delete(e),h});return this._adapterInits.set(e,o),o}registerSource(e){this.sourceRegistry.register(e)}register({chartId:e,queryTemplate:r,markSpec:i,sourceHandle:s,predicateFn:o,onResult:h}){this.charts.set(e,{chartId:e,queryTemplate:r,markSpec:i,sourceHandle:s,predicateFn:o,currentPredicate:null,onResult:h}),this.selectionStore.has(s.sourceId)||this.selectionStore.set(s.sourceId,new Map),r&&String(r).trim()&&h&&setTimeout(()=>this._dispatch(e,{preview:!1}),0)}unregister(e){let r=this.charts.get(e);if(!r)return;this.charts.delete(e);let i=this._inflightControllers.get(e);i&&(i.abort(),this._inflightControllers.delete(e));let s=r.sourceHandle.sourceId,o=this.selectionStore.get(s);o&&o.delete(e);let h=this._debouncers.get(e);if(h&&(h.preview&&clearTimeout(h.preview),h.final&&clearTimeout(h.final),this._debouncers.delete(e)),[...this.charts.values()].filter(v=>v.sourceHandle.sourceId===s).length===0){let v=this.adapters.get(s);v&&(v.close().catch(()=>{}),this.adapters.delete(s)),this._adapterInits.delete(s),this.selectionStore.delete(s)}}setSelection({chartId:e,predicate:r}){let i=this.charts.get(e);if(!i)return;let s=i.sourceHandle.sourceId,o=this.selectionStore.get(s);o||(o=new Map,this.selectionStore.set(s,o)),r==null?o.delete(e):o.set(e,r),i.currentPredicate=r;for(let h of this.charts.values())h.chartId!==e&&h.sourceHandle.sourceId===s&&this._scheduleDispatch(h.chartId);if(this._subscribers){let h=this._subscribers.get(i.sourceHandle.sourceId);if(h)for(let g of h)try{g({chartId:e,predicate:r})}catch(v){console.error("[myIO coordinator] subscriber error:",v)}}}subscribe(e,r){return this._subscribers||(this._subscribers=new Map),this._subscribers.has(e)||this._subscribers.set(e,new Set),this._subscribers.get(e).add(r),()=>{let i=this._subscribers.get(e);i&&i.delete(r)}}_scheduleDispatch(e){let r=this._debouncers.get(e);r||(r={preview:null,final:null},this._debouncers.set(e,r)),r.preview&&clearTimeout(r.preview),r.final&&clearTimeout(r.final),r.preview=setTimeout(()=>this._dispatch(e,{preview:!0}),50),r.final=setTimeout(()=>this._dispatch(e,{preview:!1}),200)}async _dispatch(e,{preview:r=!1}={}){let i=this.charts.get(e);if(!i||!i.onResult||!i.queryTemplate||!String(i.queryTemplate).trim())return;let s=i.sourceHandle.sourceId,o=this._composeOthersPredicate(e,s),h=this._substituteTemplate(i.queryTemplate,{where:o,limit:r?1e3:1e5}),g=await this._hash(o),v=i.sourceHandle.engine||this.config.engine,x=await this._hash(h+""+g+""+v),_=this.cache.get(x);if(_){this._deliverToRenderer(e,_);return}let A=this.adapters.get(s);try{if(!A&&v&&(A=await this.ensureAdapterFor(s,v,this.config)),!this.charts.has(e)||!A)return;typeof A.applyPredicateCache=="function"&&await A.applyPredicateCache(g,o)}catch(K){if(!this.charts.has(e))return;console.error("[myIO coordinator]",e,K?.code,K?.message||K),this._deliverToRenderer(e,{batches:[],trailer:{error:K?.message||String(K),code:K?.code||"engine_error"}});return}let O="q_"+Math.random().toString(36).slice(2,10),I=null;if(!this.cache.inflight.has(x)){let K=this._inflightControllers.get(e);K&&K.abort(),I=new AbortController,this._inflightControllers.set(e,I)}let Y=this.cache.inflightOrStore(x,()=>(async()=>{let K=[],ee=null;for await(let oe of A.query({sql:h,params:[],queryId:O,sourceId:s,limit:r?1e3:1e5,signal:I.signal}))oe.__trailer?ee=oe:K.push(oe);return{batches:K,trailer:ee}})());try{let K=await Y,ee=this._inflightControllers.get(e);if(I&&ee===I&&this._inflightControllers.delete(e),I&&I.signal.aborted){this.cache.rejectInflight(x);return}if(this.cache.resolveInflight(x,K),!this.charts.has(e))return;this._deliverToRenderer(e,K)}catch(K){this.cache.rejectInflight(x);let ee=this._inflightControllers.get(e);if(I&&ee===I&&this._inflightControllers.delete(e),I&&I.signal.aborted)return;console.error("[myIO coordinator]",e,K?.code,K?.message||K),this._deliverToRenderer(e,{batches:[],trailer:{error:K?.message||String(K),code:K?.code||"query_error"}})}}_composeOthersPredicate(e,r){let s=[...(this.selectionStore.get(r)||new Map).entries()].filter(([o])=>o!==e).map(([,o])=>o).filter(Boolean);return s.length?"("+s.join(") AND (")+")":"TRUE"}_substituteTemplate(e,{where:r,limit:i}){return e.replace(/\{\{\s*where\s*\}\}/g,r).replace(/\{\{\s*limit\s*\}\}/g,String(i)).replace(/\$where\b/g,r).replace(/\$limit\b/g,String(i))}async _hash(e){if(typeof crypto<"u"&&crypto.subtle){let i=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-1",i);return Array.from(new Uint8Array(s,0,8)).map(o=>o.toString(16).padStart(2,"0")).join("")}let r=2166136261;for(let i=0;i>>0).toString(16).padStart(8,"0")}_deliverToRenderer(e,{batches:r,trailer:i}){let s=this.charts.get(e);if(!(!s||!s.onResult))try{s.onResult({batches:r,trailer:i,markSpec:s.markSpec})}catch(o){console.error("[myIO coordinator] renderer error for",e,o)}}onChartResult(e,r){let i=this.charts.get(e);i&&(i.onResult=r)}async close(){for(let e of this._debouncers.values())e.preview&&clearTimeout(e.preview),e.final&&clearTimeout(e.final);for(let[,e]of this.adapters)await e.close().catch(()=>{});this.adapters.clear();for(let e of this._inflightControllers.values())e.abort();this._adapterInits.clear(),this._inflightControllers.clear(),this.charts.clear(),this.selectionStore.clear(),this.sourceRegistry.clear(),this.cache.clear(),this._debouncers.clear()}};function Zb(t){return globalThis.__myioCoordinator||(globalThis.__myioCoordinator=new Fp({config:t})),globalThis.__myioCoordinator}var VS=new Set(["scatter","line","area"]),GS=150;function $p(t){let e=Number(t);return Number.isFinite(e)?e:null}function jS(t){if(t==="Inf"||t==="Infinity"||t===1/0)return 1/0;let e=Number(t);return Number.isFinite(e)&&e>0?e:5e4}function A8({markSpec:t,rowCount:e,threshold:r}){let i=t&&t.kind;if(!VS.has(i))return!1;let s=jS(r);if(!Number.isFinite(s))return!1;let o=Number(e);return Number.isFinite(o)&&o>=s}function qS(t,e){let r={};return["x","y","category","color","value","baseline"].forEach(i=>{let s=t.getChild?t.getChild(i):null;s&&(r[i]=s.get(e))}),r}function ev(t){if(!t)return[];if(typeof t.toArray=="function")return t.toArray().map(e=>Object.assign({},e));if(typeof t.getChild=="function"){let e=t.getChild("x"),r=t.numRows||t.length||(e?e.length:0),i=new Array(r);for(let s=0;s{r&&(Array.isArray(r)?e.push(...r):Array.isArray(r.rows)?e.push(...r.rows):r.batch?e.push(...ev(r.batch)):(typeof r.getChild=="function"||typeof r.toArray=="function")&&e.push(...ev(r)))}),e.map(r=>({...r,x:$p(r.x),y:$p(r.y),category:r.category==null?void 0:$p(r.category),color:r.color==null?void 0:r.color,value:r.value==null?void 0:$p(r.value),baseline:r.baseline==null?void 0:$p(r.baseline)})).filter(r=>r.x!=null&&r.y!=null)}function zS(t){let e=t.margin||t.config&&t.config.layout&&t.config.layout.margin||{top:0,right:0,bottom:0,left:0},r=Math.max(0,(t.width||t.runtime?.width||0)-e.left-e.right),i=Math.max(0,(t.height||t.runtime?.height||0)-e.top-e.bottom);return{left:e.left,top:e.top,width:r,height:i}}function HS(t){let e=t.dom?.element||t.element,r=t.dom?.svg?.node?t.dom.svg.node():e.querySelector("svg"),i=document.createElement("div");i.className="myIO-webgl-overlay",i.style.position="absolute",i.style.pointerEvents="none",i.style.overflow="hidden",i.style.zIndex="0";let s=document.createElement("div");return s.className="myIO-webgl-loading",s.textContent="Loading data...",s.style.position="absolute",s.style.left="50%",s.style.top="50%",s.style.transform="translate(-50%, -50%)",s.style.font="12px sans-serif",s.style.color="#666",s.style.background="rgba(255,255,255,0.85)",s.style.padding="6px 8px",s.style.border="1px solid rgba(0,0,0,0.12)",i.appendChild(s),r&&r.parentNode===e?e.insertBefore(i,r):e.appendChild(i),w8(t,i),i}function w8(t,e){let r=zS(t);return e.style.left=r.left+"px",e.style.top=r.top+"px",e.style.width=r.width+"px",e.style.height=r.height+"px",r}function Pp(t,e,r){t&&typeof t.emit=="function"&&t.emit(e,r)}function WS(t,e,r){let i=t.querySelector(".myIO-webgl-loading,.myIO-webgl-empty");if(!r){i&&i.remove();return}let s=i||document.createElement("div");s.className=e,s.textContent=r,s.style.position="absolute",s.style.left="50%",s.style.top="50%",s.style.transform="translate(-50%, -50%)",s.style.font="12px sans-serif",s.style.color="#666",s.style.background="rgba(255,255,255,0.85)",s.style.padding="6px 8px",s.style.border="1px solid rgba(0,0,0,0.12)",s.parentNode||t.appendChild(s)}function YS(t,e){return t.map(r=>{if(r.category!=null||r.color==null)return r;let i=String(r.color);return e.has(i)||e.set(i,e.size),{...r,category:e.get(i)}})}function XS(t,e){let r=t.xScale,i=t.yScale;if(typeof r!="function"||typeof i!="function")return null;let s=globalThis.window&&window.d3;return s&&typeof s.quadtree=="function"?s.quadtree().x(o=>o.__px).y(o=>o.__py).addAll(e.map(o=>({row:o,__px:r(o.x),__py:i(o.y)}))):e.map(o=>({row:o,__px:r(o.x),__py:i(o.y)}))}function JS(t,e,r){if(!t)return null;if(typeof t.find=="function")return t.find(e,r,16)?.row||null;let i=null,s=1/0;return t.forEach(o=>{let h=Math.hypot(o.__px-e,o.__py-r);h{s=!1,i||h();let x=r.getBoundingClientRect(),_=JS(i,o.clientX-x.left,o.clientY-x.top);_&&Pp(t,"rollover",{data:_,source:"webgl-bridge"})}))}return r.addEventListener("mousemove",g),{rebuild:h,destroy(){r.removeEventListener("mousemove",g)}}}function T8({chart:t,coordinator:e,chartId:r,markSpec:i,createRenderer:s,layerIndex:o=0}){let h=HS(t),g=Em({chart:t,layerIndex:o}),v=s||globalThis.window&&window.myIO&&window.myIO.webglRenderers&&window.myIO.webglRenderers.createWebGLRenderer,x=new Map,_=null,A=[],O=null,I=!1,Y=!1,K=null,ee=KS(t,()=>A);function oe(de,ze){if(!(Y||I)){if(Y=!0,console.warn("[myIO webgl bridge] falling back to SVG:",de,ze||""),_&&typeof _.destroy=="function")try{_.destroy()}catch{}_=null,h.remove(),O&&g.onResult(O)}}function se(){if(_||I||Y)return _;if(typeof v!="function")return oe("renderer unavailable"),null;let de=w8(t,h);try{_=v({kind:i.kind,el:h,width:de.width,height:de.height,xScale:t.xScale,yScale:t.yScale})}catch(er){return oe("renderer creation failed",er),null}let ze=h.querySelector("canvas");if(!_)return oe("renderer unavailable"),null;if(ze){let er=null;try{er=ze.getContext("webgl2")||ze.getContext("webgl")}catch{er=null}if(!er)return oe("WebGL context unavailable"),null;ze.addEventListener("webglcontextlost",Er=>{Er.preventDefault(),oe("WebGL context lost")},{once:!0})}return _}function re(de){let ze=de&&de.trailer,er=ze&&(ze.error||ze.message);return er?(_&&typeof _.update=="function"&&Promise.resolve(_.update([])).catch(()=>{}),Pp(t,"error",{message:String(er),trailer:ze,chartId:r}),!0):!1}function q(de){if(I)return;if(O=de,Y){g.onResult(de);return}if(re(de))return;A=YS(Sm(de&&de.batches),x),ee.rebuild();let ze=se();!ze||typeof ze.update!="function"||(WS(h,A.length?null:"myIO-webgl-empty",A.length?"":"No data in selection"),A.length||Pp(t,"emptySelection",{chartId:r}),Promise.resolve(ze.update(A)).catch(er=>{oe("render failed",er)}))}function ue(){if(I||Y)return;let de=w8(t,h);_&&typeof _.resize=="function"&&_.resize(de.width,de.height),_&&typeof _.update=="function"&&Promise.resolve(_.update(A)).catch(ze=>{oe("resize render failed",ze)})}function J(){I||(K&&clearTimeout(K),K=setTimeout(ue,GS))}function k(){I||(I=!0,K&&clearTimeout(K),e&&typeof e.onChartResult=="function"&&e.onChartResult(r,null),ee.destroy(),g.destroy(),_&&typeof _.destroy=="function"&&_.destroy(),h.remove())}return t&&typeof t.on=="function"&&(t.on("resize",J),t.on("destroy",k)),{onResult:q,resize:J,destroy:k,get pointCount(){return A.length},get overlay(){return Y?void 0:h},get fallbackActive(){return Y}}}function Em({chart:t,layerIndex:e=0}){let r=[],i=!1;function s(h){if(i)return;let g=h&&h.trailer,v=g&&(g.error||g.message);if(v){Pp(t,"error",{message:String(v),trailer:g});return}r=Sm(h&&h.batches),t.config&&t.config.layers&&t.config.layers[e]&&(t.config.layers[e].data=r),r.length||Pp(t,"emptySelection",{}),typeof t.renderCurrentLayers=="function"&&t.renderCurrentLayers()}function o(){i=!0}return t&&typeof t.on=="function"&&t.on("destroy",o),{onResult:s,destroy:o,get pointCount(){return r.length}}}function tv(t){return A8(t)?T8(t):t&&t.unifyDataPath?Em(t):null}var wm=class{constructor({coordinator:e,sourceId:r,group:i,rowkeyCol:s,threshold:o=1e5}){if(!e)throw new Error("CrosstalkAdapter: coordinator is required");if(!r)throw new Error("CrosstalkAdapter: sourceId is required");this.coordinator=e,this.sourceId=r,this.group=i||null,this.rowkeyCol=s||"__myio_rowkey__",this.threshold=Number(o)||1e5,this._selectionHandle=null,this._filterHandle=null,this._suppressedOnce=!1,this._badgeEl=null,this._mode="row-level"}attach(e){if(this.group=e||this.group,!this.group||typeof window>"u"||!window.crosstalk)return;let r=window.crosstalk.SelectionHandle,i=window.crosstalk.FilterHandle;r&&(this._selectionHandle=new r(this.group),this._selectionHandle.on("change",s=>this._onIncoming(s)),i&&(this._filterHandle=new i(this.group),this._filterHandle.on("change",s=>this._onIncoming(s))))}setBadge(e){this._badgeEl=e,this._renderBadge()}_renderBadge(){this._badgeEl&&(this._badgeEl.textContent="linked: "+this._mode)}_onIncoming(e){let r=e&&(e.value||e.keys)||null;if(!r||!Array.isArray(r)||r.length===0){this.coordinator.setSelection({chartId:"__crosstalk__:"+this.sourceId,predicate:null});return}let i=r.map(h=>h==null?"NULL":"'"+String(h).replace(/'/g,"''")+"'"),o='"'+this.rowkeyCol.replace(/"/g,'""')+'"'+" IN ("+i.join(",")+")";this.coordinator.setSelection({chartId:"__crosstalk__:"+this.sourceId,predicate:o})}async broadcast({predicate:e}){if(!this._selectionHandle)return;if(e==null){try{this._selectionHandle.set(null)}catch{}return}let r=this._countSql(e),i=this.coordinator.adapters&&this.coordinator.adapters.get(this.sourceId);if(!i)return;let s=0;try{for await(let h of i.query({sql:r,params:[],queryId:"__xcount__"+Date.now()})){if(!h||h.__trailer)continue;let g=h.rows||h.batch&&h.batch.toArray&&h.batch.toArray()||[];g[0]&&(s=Number(g[0].n??g[0][0]??g[0]["count(*)"]??0))}}catch(h){console.warn("[myIO crosstalk] count query failed:",h?.message||h);return}if(s>this.threshold){this._suppressedOnce||(console.info("myIO: selection above crosstalk_threshold ("+s+" > "+this.threshold+"); downstream row-indexed widgets will not react to this selection. myIO-to-myIO linking still works."),this._suppressedOnce=!0),this._mode="predicate-only",this._renderBadge();return}let o=await this._fetchKeys(e);if(o&&o.length>0)try{this._selectionHandle.set(o)}catch{}this._mode="row-level",this._renderBadge()}_countSql(e){return"SELECT count(*) AS n FROM "+('"'+this.sourceId.replace(/"/g,'""')+'"')+" WHERE "+e}async _fetchKeys(e){let r=this.coordinator.adapters&&this.coordinator.adapters.get(this.sourceId);if(!r)return[];let i='"'+this.sourceId.replace(/"/g,'""')+'"',o="SELECT "+('"'+this.rowkeyCol.replace(/"/g,'""')+'"')+" AS rowkey FROM "+i+" WHERE "+e,h=[];try{for await(let g of r.query({sql:o,params:[],queryId:"__xkeys__"+Date.now()})){if(!g||g.__trailer)continue;let v=g.rows||g.batch&&g.batch.toArray&&g.batch.toArray()||[];for(let x of v){let _=x&&(x.rowkey??x[0]);_!=null&&h.push(String(_))}}}catch(g){console.warn("[myIO crosstalk] key fetch failed:",g?.message||g)}return h}destroy(){try{this._selectionHandle&&this._selectionHandle.close()}catch{}try{this._filterHandle&&this._filterHandle.close()}catch{}this._selectionHandle=null,this._filterHandle=null}};var fh=class{constructor({el:e,width:r,height:i,xScale:s,yScale:o,palette:h,captureHoverEvents:g=!1}){this.el=e,this.width=r,this.height=i,this.xScale=s,this.yScale=o,this.captureHoverEvents=g!==!1,this.palette=h||["#440154","#414487","#2a788e","#22a884","#7ad151","#fde725"],this._scatterplot=null,this._destroyed=!1}_scaleCopy(e){return e&&typeof e.copy=="function"?e.copy():e}async _ensure(){if(this._scatterplot)return this._scatterplot;let e=await Promise.resolve().then(()=>(Yv(),Wv)),r=e.default||e.createScatterplot,i=document.createElement("canvas");return i.width=this.width,i.height=this.height,i.style.position="absolute",i.style.top="0",i.style.left="0",i.style.pointerEvents=this.captureHoverEvents?"auto":"none",this.el.appendChild(i),this._scatterplot=r({canvas:i,width:this.width,height:this.height,pointSize:3,backgroundColor:[1,1,1,0],colorBy:"category",pointColor:this.palette,xScale:this._scaleCopy(this.xScale),yScale:this._scaleCopy(this.yScale)}),this._applyScales(),this._scatterplot}_applyScales(){!this._scatterplot||!this.xScale||!this.yScale||(typeof this._scatterplot.setXScale=="function"&&this._scatterplot.setXScale(this._scaleCopy(this.xScale)),typeof this._scatterplot.setYScale=="function"&&this._scatterplot.setYScale(this._scaleCopy(this.yScale)),typeof this._scatterplot.set=="function"&&(typeof this._scatterplot.setXScale!="function"||typeof this._scatterplot.setYScale!="function")&&this._scatterplot.set({xScale:this._scaleCopy(this.xScale),yScale:this._scaleCopy(this.yScale)}))}async update(e){if(this._destroyed)return;let r=await this._ensure();if(!e||e.length===0){r.clear();return}let i={x:new Float32Array(e.length),y:new Float32Array(e.length),category:new Float32Array(e.length),value:new Float32Array(e.length)};for(let s=0;sm0(Am())),r=e.default||e,i=document.createElement("canvas");i.width=this.width,i.height=this.height,i.style.position="absolute",i.style.top="0",i.style.left="0",i.style.pointerEvents="none",this.el.appendChild(i),this._regl=r({canvas:i,attributes:{antialias:!0,preserveDrawingBuffer:!1}}),this._drawLine=this._regl({vert:` +`+s(I.value)}),od(e,r)}remove(e){e.dom.chartArea.selectAll(".root").transition().duration(500).style("opacity",0).remove()}};function U9(t,e,r){var i=String(t.data[e.mapping.x_var]||t.data[e.mapping.level_2]||t.data.name||""),s=Math.max(0,t.x1-t.x0),o=s<70&&i.length>10?i.substring(0,9)+"...":i;return o.split(/\s+/).concat(r(t.value))}function V9(t){return!t||typeof t.getBBox!="function"?!0:t.getBBox().width>40}var cd=class{static type="donut";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"none",scaleCapabilities:{invertX:!1}};static scaleHints=null;static dataContract={x_var:{required:!0},y_var:{required:!0,numeric:!0}};render(e,r){var i=e.margin,s=e.options.transition.speed,o=Math.min(e.width-(i.right+i.left),e.height-(i.top+i.bottom))/2,h=r.mapping.x_var,g=r.mapping.y_var;Nh(e)?(e.colorDiscrete=d3.scaleOrdinal().range(e.options.colorScheme[0]).domain(e.options.colorScheme[1]),e.colorContinuous=d3.scaleLinear().range(e.options.colorScheme[0]).domain(e.options.colorScheme[1])):e.colorDiscrete=d3.scaleOrdinal().range(r.color).domain(r.data.map(function(q){return q[h]}));var v=e.runtime._hiddenOrdinalSegments||[],x=r.data.filter(function(q){return v.indexOf(q[h])===-1}),_=d3.pie().sort(null).value(function(q){return q[g]}),A=d3.arc().innerRadius(o*.8).outerRadius(o*.4),O=d3.arc().innerRadius(o*.9).outerRadius(o*.9),I=e.chart.selectAll(".donut").data(_(x),function(q){return q.data[h]});I.exit().transition().duration(s).ease(Mn(e,d3.easeQuad)).attrTween("d",function(q){var ue={startAngle:q.endAngle,endAngle:q.endAngle},J=d3.interpolate(q,ue);return function(k){return A(J(k))}}).remove();var Y=I.enter().append("path").attr("class","donut").attr("fill",function(q){return e.colorDiscrete(q.data[h])}).attr("d",A).each(function(q){this._current=q});I.merge(Y).transition().duration(s).ease(Mn(e,d3.easeQuad)).attr("fill",function(q){return e.colorDiscrete(q.data[h])}).attrTween("d",function(q){this._current=this._current||q;var ue=d3.interpolate(this._current,q);return this._current=ue(1),function(J){return A(ue(J))}});function K(q){return q.startAngle+(q.endAngle-q.startAngle)/2}var ee=e.chart.selectAll(".inner-text").data(_(x),function(q){return q.data[h]});ee.exit().transition().duration(s).style("opacity",0).remove();var oe=ee.enter().append("text").attr("class","inner-text").style("font-size","12px").style("opacity",0).attr("dy",".35em").text(function(q){return q.data[h]});ee.merge(oe).transition().duration(s).ease(Mn(e,d3.easeQuad)).text(function(q){return q.data[h]}).style("opacity",function(q){return Math.abs(q.endAngle-q.startAngle)>.3?1:0}).attrTween("transform",function(q){this._current=this._current||q;var ue=d3.interpolate(this._current,q);return this._current=ue(1),function(J){var k=ue(J),de=O.centroid(k);return de[0]=o*(K(k).3?1:0}).attrTween("points",function(q){this._current=this._current||q;var ue=d3.interpolate(this._current,q);return this._current=ue(1),function(J){var k=ue(J),de=O.centroid(k);return de[0]=o*.95*(K(k)0?r.data[0]:{},v=r.mapping.value,x=typeof v=="string"?+g[v]:+v;Number.isFinite(x)||(x=0),x=Math.max(0,Math.min(1,x));var _=[x,1-x],A=d3.arc().innerRadius(o-h).outerRadius(o).cornerRadius(10),O=d3.arc().innerRadius(o-h).outerRadius(o),I=d3.pie().sort(null).value(function(k){return k}).startAngle(s*-.5).endAngle(s*.5),Y=d3.format(".1%"),K=r.options&&Array.isArray(r.options.thresholds)?r.options.thresholds:[{min:0,max:.6,color:"#3CA951"},{min:.6,max:.85,color:"#FFB000"},{min:.85,max:1,color:"#EF603B"}];function ee(k){return O({startAngle:s*-.5+s*Math.max(0,Math.min(1,+k.min||0)),endAngle:s*-.5+s*Math.max(0,Math.min(1,+k.max||0))})}var oe=e.chart.selectAll(".myIO-gauge-threshold").data(K);oe.exit().transition().duration(i).style("opacity",0).remove();var se=oe.enter().append("path").attr("class","myIO-gauge-threshold").attr("fill",function(k){return k.color}).attr("opacity",0).attr("d",ee);se.merge(oe).transition().duration(i).ease(Mn(e,d3.easeQuad)).attr("fill",function(k){return k.color}).attr("opacity",.24).attr("d",ee);var re=e.chart.selectAll(".myIO-gauge-background").data(I([1]));re.exit().transition().duration(i).style("opacity",0).remove();var q=re.enter().append("path").attr("class","myIO-gauge-background").attr("fill","rgba(107, 114, 128, 0.22)").attr("d",A).each(function(k){this._current=k});q.merge(re).transition().duration(i).ease(Mn(e,d3.easeBack)).attr("fill","rgba(107, 114, 128, 0.22)").attrTween("d",function(k){this._current=this._current||k;var de=d3.interpolate(this._current,k);return this._current=de(1),function(ze){return A(de(ze))}});var ue=e.chart.selectAll(".myIO-gauge-value").data(I(_));ue.exit().transition().duration(i).style("opacity",0).remove();var J=ue.enter().append("path").attr("class","myIO-gauge-value").attr("fill",function(k,de){return[r.color||jg(x,K),"transparent"][de]}).attr("d",A).each(function(k){this._current=k});J.merge(ue).transition().duration(i).ease(Mn(e,d3.easeBack)).attr("fill",function(k,de){return[r.color||jg(x,K),"transparent"][de]}).attrTween("d",function(k){this._current=this._current||k;var de=d3.interpolate(this._current,k);return this._current=de(1),function(ze){return A(de(ze))}}),e.chart.selectAll(".gauge-text").data([_[0]]).join("text").attr("class","gauge-text").text(function(k){return Y(k)}).attr("text-anchor","middle").attr("font-size",20).attr("dy","-0.45em"),e.chart.selectAll(".gauge-label").data([r.options&&r.options.metric?r.options.metric:r.label]).join("text").attr("class","gauge-label").text(function(k){return k}).attr("text-anchor","middle").attr("font-size",12).attr("dy","1.1em"),e.chart.selectAll(".gauge-min-label").data(["0%"]).join("text").attr("class","gauge-min-label").text(function(k){return k}).attr("text-anchor","middle").attr("font-size",11).attr("x",-o+h/2).attr("y",12),e.chart.selectAll(".gauge-max-label").data(["100%"]).join("text").attr("class","gauge-max-label").text(function(k){return k}).attr("text-anchor","middle").attr("font-size",11).attr("x",o-h/2).attr("y",12)}remove(e){e.dom.chartArea.selectAll(".myIO-gauge-threshold, .myIO-gauge-background, .myIO-gauge-value, .gauge-text, .gauge-label, .gauge-min-label, .gauge-max-label").transition().duration(500).style("opacity",0).remove()}};function jg(t,e){var r=e.find(function(i){return t>=+i.min&&t<=+i.max});return r&&r.color?r.color:"#4269D0"}var fd=class{static type="heatmap";static traits={hasAxes:!0,referenceLines:!1,legendType:"continuous",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"band",yScaleType:"band",yExtentFields:["value"],domainMerge:"union"};static dataContract={x_var:{required:!0},y_var:{required:!0},value:{required:!0,numeric:!0}};render(e,r){var i=e.options.transition.speed,s=r.mapping.x_var,o=r.mapping.y_var,h=r.mapping.value,g=r.data.map(function(I){return+I[h]}),v=d3.extent(g.filter(function(I){return Number.isFinite(I)}));(!v||v[0]===void 0||v[1]===void 0)&&(v=[0,1]),e.derived.colorContinuous=d3.scaleSequential(d3.interpolateBlues).domain(v),e.colorContinuous=e.derived.colorContinuous;var x=e.chart.selectAll("."+xr("heatmap",e.element.id,r.label)).data(r.data);x.exit().transition().duration(i).style("opacity",0).remove();var _=e.xScale.bandwidth?e.xScale.bandwidth():0,A=e.yScale.bandwidth?e.yScale.bandwidth():0,O=x.enter().append("rect").attr("class",xr("heatmap",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").attr("x",function(I){return e.xScale(I[s])}).attr("y",function(I){return e.yScale(I[o])}).attr("width",_).attr("height",A).attr("fill",function(I){return e.colorContinuous(+I[h])}).style("opacity",0);x.merge(O).transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x",function(I){return e.xScale(I[s])}).attr("y",function(I){return e.yScale(I[o])}).attr("width",_).attr("height",A).attr("fill",function(I){return e.colorContinuous(+I[h])}).style("opacity",1)}getHoverSelector(e,r){return"."+xr("heatmap",e.dom.element.id,r.label)}formatTooltip(e,r,i){return{title:i.mapping.x_var+": "+r[i.mapping.x_var]+", "+i.mapping.y_var+": "+r[i.mapping.y_var],body:i.mapping.value+": "+r[i.mapping.value],color:e.colorContinuous?e.colorContinuous(+r[i.mapping.value]):i.color,label:i.label,value:r[i.mapping.value],raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("heatmap",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};var dd=class{static type="calendarHeatmap";static traits={hasAxes:!1,referenceLines:!1,legendType:"continuous",binning:!1,rolloverStyle:"element"};static dataContract={date:{required:!0},value:{required:!0,numeric:!0}};static scaleHints=null;getHoverSelector(){return".myIO-calendar-cell"}formatTooltip(e,r,i){var s=d3.utcFormat("%b %-d, %Y"),o=r.date instanceof Date?r.date:new Date((r[i.mapping.date]||"")+"T00:00:00Z"),h=r.value!=null?r.value:+r[i.mapping.value];return{title:s(o),body:i.label+": "+h,color:r.color||i.color,label:i.label,value:h,raw:r}}render(e,r){var i=r.options||{},s=i.weekStart==="monday"?1:0,o=i.showWeekdayLabels!==!1,h=r.mapping.date,g=r.mapping.value,v=(r.data||[]).map(function(ar){return{date:new Date(ar[h]+"T00:00:00Z"),value:+ar[g],raw:ar}}).filter(function(ar){return!isNaN(ar.date.getTime())}).sort(function(ar,Wi){return ar.date-Wi.date});if(v.length!==0){var x=v[0].date.getUTCFullYear(),_=new Date(Date.UTC(x,0,1)),A=new Date(Date.UTC(x,11,31)),O=function(ar){var Wi=ar.getUTCDay();return(Wi-s+7)%7},I=O(_),Y=function(ar){var Wi=Math.floor((ar-_)/864e5);return Math.floor((Wi+I)/7)},K=Y(A)+1,ee=e.margin||{top:0,right:0,bottom:0,left:0},oe=(e.width||0)-(ee.left||0)-(ee.right||0),se=(e.height||0)-(ee.top||0)-(ee.bottom||0),re=o?24:0,q=18,ue=Math.max(1,oe-re),J=Math.max(1,se-q),k=Math.max(4,Math.min(Math.floor(ue/K),Math.floor(J/7))),de=e.element&&typeof getComputedStyle=="function"?getComputedStyle(e.element):null,ze=de?de.getPropertyValue("--chart-calendar-cell-gap"):"",er=parseFloat(ze);isFinite(er)||(er=2);var Er=e.config&&e.config.axis&&e.config.axis.vlim,Ht=d3.max(v,function(ar){return ar.value});Ht>0||(Ht=1);var xn=Er&&Er.max!==void 0&&Er.max!==null?[Er.min||0,Er.max]:[0,Ht],$r=d3.interpolateRgb("#ffffff",r.color||"#4E79A7"),Tn=d3.scaleSequential($r).domain(xn);e.colorContinuous=Tn,e.derived&&(e.derived.colorContinuous=Tn);var In=function(ar){var Wi=ar instanceof Date?ar:new Date(ar);return re+Y(Wi)*(k+er)};In.domain=function(){return[_,A]},In.range=function(){return[re,re+(K-1)*(k+er)]},In.invert=function(ar){var Wi=Math.round((ar-re)/(k+er)),Gs=Wi*7-I;return new Date(_.getTime()+Gs*864e5)},e.xScale=In;var cr=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0,bn=e.chart.selectAll(".myIO-calendar-root").data([null]).join("g").attr("class","myIO-calendar-root");if(o){var mn=s===0?["","Mon","","Wed","","Fri",""]:["","Tue","","Thu","","Sat",""],qn=mn.map(function(ar,Wi){return{t:ar,i:Wi}}).filter(function(ar){return ar.t}),Wt=bn.selectAll("text.myIO-calendar-dow").data(qn,function(ar){return ar.i});Wt.exit().remove(),Wt.enter().append("text").attr("class","myIO-calendar-dow").attr("x",0).merge(Wt).attr("y",function(ar){return q+ar.i*(k+er)+k*.75}).text(function(ar){return ar.t})}else bn.selectAll("text.myIO-calendar-dow").remove();var Pr=d3.utcFormat("%b"),hi=d3.range(12).map(function(ar){var Wi=new Date(Date.UTC(x,ar,1));return{m:ar,text:Pr(Wi),col:Y(Wi)}}),Ai=bn.selectAll("text.myIO-calendar-month").data(hi,function(ar){return ar.m});Ai.exit().remove(),Ai.enter().append("text").attr("class","myIO-calendar-month").attr("y",q-4).merge(Ai).attr("x",function(ar){return re+ar.col*(k+er)}).text(function(ar){return ar.text});var pi=function(ar){return ar.date.toISOString().slice(0,10)},ss=bn.selectAll("rect.myIO-calendar-cell").data(v,function(ar){return pi(ar)});ss.exit().transition().duration(cr).style("opacity",0).remove();var Va=ss.enter().append("rect").attr("class","myIO-calendar-cell").attr("data-date",pi).attr("data-row",function(ar){return String(O(ar.date))}).attr("data-col",function(ar){return String(Y(ar.date))}).attr("x",function(ar){return re+Y(ar.date)*(k+er)}).attr("y",function(ar){return q+O(ar.date)*(k+er)}).attr("width",k).attr("height",k).attr("fill",function(ar){return ar.value==null||isNaN(ar.value)||ar.value===0?"var(--chart-calendar-empty-fill, #ebedf0)":Tn(ar.value)}).style("opacity",0);Va.merge(ss).each(function(ar){ar.label=r.label,ar.color=ar.value==null||isNaN(ar.value)||ar.value===0?"var(--chart-calendar-empty-fill, #ebedf0)":Tn(ar.value),ar[h]=pi({date:ar.date}),ar[g]=ar.value}).transition().duration(cr).style("opacity",1).attr("x",function(ar){return re+Y(ar.date)*(k+er)}).attr("y",function(ar){return q+O(ar.date)*(k+er)}).attr("width",k).attr("height",k).attr("fill",function(ar){return ar.value==null||isNaN(ar.value)||ar.value===0?"var(--chart-calendar-empty-fill, #ebedf0)":Tn(ar.value)})}}remove(e){e&&e.chart&&typeof e.chart.selectAll=="function"&&e.chart.selectAll(".myIO-calendar-root").remove()}};var hd=class{static type="candlestick";static traits={hasAxes:!0,referenceLines:!0,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"linear",yScaleType:"linear",yExtentFields:["open","high","low","close"],domainMerge:"union"};static dataContract={x_var:{required:!0,numeric:!0},open:{required:!0,numeric:!0},high:{required:!0,numeric:!0},low:{required:!0,numeric:!0},close:{required:!0,numeric:!0}};render(e,r){var i=e.options.transition.speed,s=r.mapping.x_var,o=r.mapping.open,h=r.mapping.high,g=r.mapping.low,v=r.mapping.close,x=e.width-(e.margin.left+e.margin.right),_=Math.max(6,Math.min(40,x/Math.max(r.data.length*2.5,1))),A=this;function O(q){return e.xScale(q[s])}function I(q){return+q[v]>=+q[o]?"#4CAF50":"#F44336"}function Y(q){return e.yScale(Math.max(+q[o],+q[v]))}function K(q){return Math.max(Math.abs(e.yScale(+q[o])-e.yScale(+q[v])),1)}function ee(q){return e.yScale((+q[o]+ +q[v])/2)}var oe=e.chart.selectAll("."+xr("candlestick",e.element.id,r.label)).data(r.data);oe.exit().transition().duration(i).style("opacity",0).remove();var se=oe.enter().append("g").attr("class",xr("candlestick",e.element.id,r.label)).style("opacity",0);se.append("line").attr("class","wick").attr("stroke","#666").attr("stroke-width",1.5).attr("x1",O).attr("x2",O).attr("y1",ee).attr("y2",ee),se.append("rect").attr("class","body").attr("stroke-width",.5).attr("x",function(q){return O(q)-_/2}).attr("y",ee).attr("width",_).attr("height",0).attr("fill",I).attr("stroke",I);var re=oe.merge(se);re.transition().ease(Mn(e,d3.easeQuad)).duration(i).style("opacity",1),re.select("line.wick").transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x1",O).attr("x2",O).attr("y1",function(q){return e.yScale(+q[g])}).attr("y2",function(q){return e.yScale(+q[h])}),re.select("rect.body").transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x",function(q){return O(q)-_/2}).attr("y",Y).attr("width",_).attr("height",K).attr("fill",I).attr("stroke",I)}getHoverSelector(e,r){return"."+xr("candlestick",e.dom.element.id,r.label)}formatTooltip(e,r,i){return{title:i.mapping.x_var+": "+r[i.mapping.x_var],body:"O: "+r[i.mapping.open]+", H: "+r[i.mapping.high]+", L: "+r[i.mapping.low]+", C: "+r[i.mapping.close],color:r[i.mapping.close]>=r[i.mapping.open]?"#4CAF50":"#F44336",label:i.label,value:r[i.mapping.close],raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("candlestick",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};var pd=class{static type="waterfall";static traits={hasAxes:!0,referenceLines:!0,legendType:"none",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"band",yScaleType:"linear",yExtentFields:["_base_y","_cumulative_y"],domainMerge:"union"};static dataContract={x_var:{required:!0},y_var:{required:!0,numeric:!0}};render(e,r){var i=e.options.transition.speed,s=r.mapping.x_var,o=r.mapping.y_var,h=e.xScale.bandwidth?e.xScale.bandwidth():0,g=h*.82,v=(h-g)/2,x=Array.isArray(r.color),_=e.chart.selectAll("."+xr("waterfall",e.element.id,r.label)).data(r.data);_.exit().transition().duration(i).style("opacity",0).remove();var A=_.enter().append("rect").attr("class",xr("waterfall",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").attr("x",function(K){return e.xScale(K[s])+v}).attr("width",g).attr("y",function(K){return e.yScale(+K._base_y)}).attr("height",0).attr("fill",function(K,ee){return x?r.color[ee%r.color.length]:K._is_total?"#888":+K._cumulative_y>=+K._base_y?"#4CAF50":"#F44336"});_.merge(A).transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x",function(K){return e.xScale(K[s])+v}).attr("width",g).attr("y",function(K){return e.yScale(Math.max(+K._base_y,+K._cumulative_y))}).attr("height",function(K){return Math.abs(e.yScale(+K._base_y)-e.yScale(+K._cumulative_y))}).attr("fill",function(K,ee){return x?r.color[ee%r.color.length]:K._is_total?"#888":+K._cumulative_y>=+K._base_y?"#4CAF50":"#F44336"});var O=r.data.slice(0,Math.max(r.data.length-1,0)),I=e.chart.selectAll("."+xr("waterfall-connector",e.element.id,r.label)).data(O);I.exit().transition().duration(i).style("opacity",0).remove();var Y=I.enter().append("line").attr("class",xr("waterfall-connector",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").style("stroke","#374151").style("stroke-width",1.5).style("stroke-dasharray","4 2").attr("x1",function(K,ee){return e.xScale(r.data[ee][s])+v+g}).attr("x2",function(K,ee){return e.xScale(r.data[ee+1][s])+v}).attr("y1",function(K){return e.yScale(+K._cumulative_y)}).attr("y2",function(K){return e.yScale(+K._cumulative_y)}).style("opacity",0);I.merge(Y).transition().ease(Mn(e,d3.easeQuad)).duration(i).style("opacity",1).attr("x1",function(K,ee){return e.xScale(r.data[ee][s])+v+g}).attr("x2",function(K,ee){return e.xScale(r.data[ee+1][s])+v}).attr("y1",function(K){return e.yScale(+K._cumulative_y)}).attr("y2",function(K){return e.yScale(+K._cumulative_y)})}formatTooltip(e,r,i){return{title:i.mapping.x_var+": "+r[i.mapping.x_var],body:"Delta: "+r[i.mapping.y_var]+", Total: "+r._cumulative_y,color:r._is_total?"#888":+r._cumulative_y>=+r._base_y?"#4CAF50":"#F44336",label:i.label,value:r._cumulative_y,raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("waterfall",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove(),e.dom.chartArea.selectAll("."+xr("waterfall-connector",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};var md=class{static type="sankey";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints=null;static dataContract={source:{required:!0},target:{required:!0},value:{required:!0,numeric:!0}};render(e,r){var i=e.margin,s=e.width-(i.left+i.right),o=n1(e)-(i.top+i.bottom),h=18,g=d3.sankey().nodeId(function(se){return se.name}).nodeWidth(h).nodePadding(12).extent([[0,0],[s,o]]),v=new Map,x=r.data.map(function(se){var re=se[r.mapping.source],q=se[r.mapping.target];return v.has(re)||v.set(re,{name:re}),v.has(q)||v.set(q,{name:q}),{source:re,target:q,value:+se[r.mapping.value]}}),_=g({nodes:Array.from(v.values()),links:x});e.derived.colorDiscrete=d3.scaleOrdinal().domain(_.nodes.map(function(se){return se.name})).range(r.color||d3.schemeTableau10),e.colorDiscrete=e.derived.colorDiscrete;var A=e.chart.selectAll("."+xr("sankey",e.element.id,r.label)).data(_.links);A.exit().transition().duration(e.options.transition.speed).style("opacity",0).remove();var O=A.enter().append("path").attr("class",xr("sankey",e.element.id,r.label)).attr("fill","none").attr("stroke-opacity",.4).attr("clip-path","url(#"+e.element.id+"clip)").attr("d",d3.sankeyLinkHorizontal()).attr("stroke-width",function(se){return Math.max(1,se.width)}).attr("stroke",function(se){return e.colorDiscrete(se.source.name)}).style("opacity",0);A.merge(O).transition().ease(Mn(e,d3.easeQuad)).duration(e.options.transition.speed).style("opacity",1).attr("d",d3.sankeyLinkHorizontal()).attr("stroke-width",function(se){return Math.max(1,se.width)}).attr("stroke",function(se){return e.colorDiscrete(se.source.name)});var I=e.chart.selectAll("."+xr("sankey-node",e.element.id,r.label)).data(_.nodes);I.exit().transition().duration(e.options.transition.speed).style("opacity",0).remove();var Y=I.enter().append("rect").attr("class",xr("sankey-node",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").attr("x",function(se){return se.x0}).attr("y",function(se){return se.y0}).attr("width",function(se){return se.x1-se.x0}).attr("height",function(se){return Math.max(1,se.y1-se.y0)}).attr("fill",function(se){return e.colorDiscrete(se.name)}).style("opacity",0);I.merge(Y).transition().ease(Mn(e,d3.easeQuad)).duration(e.options.transition.speed).style("opacity",1).attr("x",function(se){return se.x0}).attr("y",function(se){return se.y0}).attr("width",function(se){return se.x1-se.x0}).attr("height",function(se){return Math.max(1,se.y1-se.y0)}).attr("fill",function(se){return e.colorDiscrete(se.name)});var K=xr("sankey-label",e.element.id,r.label),ee=e.chart.selectAll("."+K).data(_.nodes,function(se){return se.name});ee.exit().transition().duration(e.options.transition.speed).style("opacity",0).remove();var oe=ee.enter().append("text").attr("class",K).attr("x",function(se){return se.x0 "+r.target.name,body:"Value: "+r.value,color:e.colorDiscrete?e.colorDiscrete(r.source.name):i.color,label:i.label,value:r.value,raw:r}:{title:r.name,body:"Value: "+r.value,color:e.colorDiscrete?e.colorDiscrete(r.name):i.color,label:i.label,value:r.value,raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("sankey",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove(),e.dom.chartArea.selectAll("."+xr("sankey-node",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove(),e.dom.chartArea.selectAll("."+xr("sankey-label",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};var gd=class{static type="rangeBar";static traits={hasAxes:!0,referenceLines:!1,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"linear",yScaleType:"linear",yExtentFields:["low_y","high_y"],domainMerge:"union"};static dataContract={x_var:{required:!0},low_y:{required:!0,numeric:!0},high_y:{required:!0,numeric:!0}};render(e,r){if(r.options&&r.options.style==="errorbar"){G9(e,r);return}var i=e.options.transition.speed,s=r.mapping.x_var,o=r.mapping.low_y,h=r.mapping.high_y,g=r.options&&r.options.rangeBarWidth?r.options.rangeBarWidth:Math.max(6,Math.min(60,(e.width-(e.margin.left+e.margin.right))/Math.max(r.data.length*3,1))),v=e.chart.selectAll("."+xr("rangeBar",e.element.id,r.label)).data(r.data);v.exit().transition().duration(i).style("opacity",0).remove();function x(Y){return e.yScale((+Y[o]+ +Y[h])/2)}function _(Y){return e.yScale(Math.max(+Y[o],+Y[h]))}function A(Y){return Math.abs(e.yScale(+Y[o])-e.yScale(+Y[h]))}function O(Y){return typeof e.colorDiscrete=="function"&&Y[r.mapping.group]?e.colorDiscrete(Y[r.mapping.group]):r.color||"#6b7280"}var I=v.enter().append("rect").attr("class",xr("rangeBar",e.element.id,r.label)).attr("clip-path","url(#"+e.element.id+"clip)").attr("x",function(Y){return e.xScale(Y[s])-g/2}).attr("y",x).attr("width",g).attr("height",0).attr("fill",O);v.merge(I).transition().ease(Mn(e,d3.easeQuad)).duration(i).attr("x",function(Y){return e.xScale(Y[s])-g/2}).attr("y",_).attr("width",g).attr("height",A).attr("fill",O)}getHoverSelector(e,r){return"."+xr("rangeBar",e.dom.element.id,r.label)}formatTooltip(e,r,i){return{title:i.mapping.x_var+": "+r[i.mapping.x_var],body:i.mapping.low_y+": "+r[i.mapping.low_y]+", "+i.mapping.high_y+": "+r[i.mapping.high_y],color:i.color,label:i.label,value:r[i.mapping.high_y],raw:r}}remove(e,r){e.dom.chartArea.selectAll("."+xr("rangeBar",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove(),e.dom.chartArea.selectAll("."+xr("rangeBar-error",e.dom.element.id,r.label)).transition().duration(500).style("opacity",0).remove()}};function G9(t,e){var r=t.options.transition.speed,i=e.mapping.x_var,s=e.mapping.low_y,o=e.mapping.high_y,h=e.mapping.y_var;if(!h){typeof console<"u"&&console.warn&&console.warn("myIO RangeBarRenderer: style='errorbar' requires a y_var mapping for the mean point. Skipping render for layer '"+(e.label||"(unnamed)")+"'.");return}var g=e.color||"#4269D0",v=e.options&&e.options.capWidth?e.options.capWidth:18,x=e.options&&e.options.pointRadius?e.options.pointRadius:4;function _(oe){var se=t.xScale(oe[i]);return t.xScale.bandwidth&&(se+=t.xScale.bandwidth()/2),se}function A(oe){return t.yScale(+oe[s])}function O(oe){return t.yScale(+oe[o])}function I(oe){return t.yScale(+oe[h])}var Y=t.chart.selectAll("."+xr("rangeBar-error",t.element.id,e.label)).data(e.data);Y.exit().transition().duration(r).style("opacity",0).remove();var K=Y.enter().append("g").attr("class",xr("rangeBar-error",t.element.id,e.label)).attr("clip-path","url(#"+t.element.id+"clip)").style("opacity",0);K.append("line").attr("class","mean-ci-whisker").attr("x1",_).attr("x2",_).attr("y1",I).attr("y2",I).attr("stroke",g).attr("stroke-width",2),K.append("line").attr("class","mean-ci-cap mean-ci-cap-low").attr("x1",_).attr("x2",_).attr("y1",I).attr("y2",I).attr("stroke",g).attr("stroke-width",2),K.append("line").attr("class","mean-ci-cap mean-ci-cap-high").attr("x1",_).attr("x2",_).attr("y1",I).attr("y2",I).attr("stroke",g).attr("stroke-width",2),K.append("circle").attr("class","mean-ci-point").attr("cx",_).attr("cy",I).attr("r",0).attr("fill",g).attr("stroke","var(--chart-bg, #ffffff)").attr("stroke-width",1.5);var ee=Y.merge(K);ee.transition().ease(Mn(t,d3.easeQuad)).duration(r).style("opacity",1),ee.select(".mean-ci-whisker").transition().ease(Mn(t,d3.easeQuad)).duration(r).attr("x1",_).attr("x2",_).attr("y1",A).attr("y2",O).attr("stroke",g),ee.select(".mean-ci-cap-low").transition().ease(Mn(t,d3.easeQuad)).duration(r).attr("x1",function(oe){return _(oe)-v/2}).attr("x2",function(oe){return _(oe)+v/2}).attr("y1",A).attr("y2",A).attr("stroke",g),ee.select(".mean-ci-cap-high").transition().ease(Mn(t,d3.easeQuad)).duration(r).attr("x1",function(oe){return _(oe)-v/2}).attr("x2",function(oe){return _(oe)+v/2}).attr("y1",O).attr("y2",O).attr("stroke",g),ee.select(".mean-ci-point").transition().ease(Mn(t,d3.easeQuad)).duration(r).attr("cx",_).attr("cy",I).attr("r",x).attr("fill",g)}var yd=class{static type="text";static traits={hasAxes:!1,referenceLines:!1,legendType:"none",binning:!1,rolloverStyle:"none",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"linear",yScaleType:"linear",xExtentFields:[],yExtentFields:[],domainMerge:"union"};static dataContract={};render(e,r){var i=r.options&&r.options.position||"top-right",s=r.label,o=xr("text-annotation",e.element.id,s);e.chart.selectAll("."+o).remove();var h=r.data.map(function(K){return K.text}),g=i.indexOf("top")!==-1,v=i.indexOf("right")!==-1,x=e.width-(e.margin.left+e.margin.right),_=e.height-(e.margin.top+e.margin.bottom),A=v?x-58:10,O=g?20:_-10,I=v?"end":"start",Y=e.chart.append("g").attr("class",o).attr("transform","translate("+A+","+O+")");h.forEach(function(K,ee){Y.append("text").attr("y",(g?1:-1)*ee*16).attr("text-anchor",I).style("font-size","12px").style("font-family","var(--font-family, sans-serif)").style("fill","var(--text-color, #333)").style("opacity",.8).text(K)})}formatTooltip(){return null}remove(e,r){var i=xr("text-annotation",e.dom.element.id,r.label);e.dom.chartArea.selectAll("."+i).remove()}};var bd=class{static type="bracket";static traits={hasAxes:!0,referenceLines:!1,legendType:"none",binning:!1,rolloverStyle:"none",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"linear",yScaleType:"linear",xExtentFields:[],yExtentFields:["y"],domainMerge:"union"};static dataContract={x1:{required:!0,numeric:!0},x2:{required:!0,numeric:!0},y:{required:!0,numeric:!0}};render(e,r){var i=xr("bracket",e.element.id,r.label),s=6,o=4,h=e.options.transition.speed,g=r.color||"var(--text-color, #333)",v=e.chart.selectAll("g."+i+"-root").data([null]).join("g").attr("class",i+"-root").attr("clip-path","url(#"+e.element.id+"clip)"),x=function(I,Y){return I.label!=null?String(I.label)+"_"+Y:String(Y)},_=v.selectAll("g."+i).data(r.data,x);_.exit().transition().duration(h).style("opacity",0).remove();var A=_.enter().append("g").attr("class",i).style("opacity",0);A.append("line").attr("class","bracket-bar").attr("stroke",g).attr("stroke-width",1.5),A.append("line").attr("class","bracket-tick-left").attr("stroke",g).attr("stroke-width",1.5),A.append("line").attr("class","bracket-tick-right").attr("stroke",g).attr("stroke-width",1.5),A.append("text").attr("class","bracket-label").attr("text-anchor","middle").style("font-size","11px").style("font-family","var(--font-family, sans-serif)").style("fill",g);var O=A.merge(_);O.transition().duration(h).style("opacity",1),O.select(".bracket-bar").transition().duration(h).attr("x1",function(I){return e.xScale(+I.x1)}).attr("y1",function(I){return e.yScale(+I.y)}).attr("x2",function(I){return e.xScale(+I.x2)}).attr("y2",function(I){return e.yScale(+I.y)}),O.select(".bracket-tick-left").transition().duration(h).attr("x1",function(I){return e.xScale(+I.x1)}).attr("y1",function(I){return e.yScale(+I.y)}).attr("x2",function(I){return e.xScale(+I.x1)}).attr("y2",function(I){return e.yScale(+I.y)+s}),O.select(".bracket-tick-right").transition().duration(h).attr("x1",function(I){return e.xScale(+I.x2)}).attr("y1",function(I){return e.yScale(+I.y)}).attr("x2",function(I){return e.xScale(+I.x2)}).attr("y2",function(I){return e.yScale(+I.y)+s}),O.select(".bracket-label").text(function(I){return I.label}).transition().duration(h).attr("x",function(I){return(e.xScale(+I.x1)+e.xScale(+I.x2))/2}).attr("y",function(I){return e.yScale(+I.y)-o})}formatTooltip(){return null}remove(e,r){var i=xr("bracket",e.element.id,r.label);e.chart.selectAll("."+i).remove()}};var vd=class{static type="lollipop";static traits={hasAxes:!0,referenceLines:!0,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"band",yScaleType:"linear",xExtentFields:[],yExtentFields:["y_var"],domainMerge:"union"};static dataContract={x_var:{required:!0,numeric:!1},y_var:{required:!0,numeric:!0}};render(e,r,i){var s=e.derived.xScale,o=e.derived.yScale,h=e.config.scales.flipAxis,g=e.options.transition.speed,v=e.dom.chartArea.selectAll(".tag-lollipop-"+r.id).data([null]).join("g").attr("class","tag-lollipop-"+r.id),x=r.options&&r.options.headRadius||5,_=r.options&&r.options.stemWidth||2,A=r.mapping.x_var,O=r.mapping.y_var,I=s.bandwidth?s.bandwidth()/2:0,Y=typeof o(0)=="number"?o(0):o.range()[0],K=typeof s(0)=="number"?s(0):s.range()[0];function ee(J){if(h){var k=o(J[A]);return o.bandwidth&&(k+=I),{x1:K,x2:s(J[O]),y1:k,y2:k}}var de=s(J[A])+I;return{x1:de,x2:de,y1:Y,y2:o(J[O])}}function oe(J){var k=ee(J);return{cx:k.x2,cy:k.y2}}var se=v.selectAll(".lollipop-stem").data(r.data,function(J){return J._source_key});se.exit().transition().duration(g).style("opacity",0).attr("x2",h?K:function(J){return s(J[A])+I}).attr("y2",h?function(J){var k=o(J[A]);return o.bandwidth?k+I:k}:Y).remove();var re=se.enter().append("line").attr("class","lollipop-stem").attr("x1",function(J){return ee(J).x1}).attr("x2",function(J){return h?ee(J).x1:ee(J).x2}).attr("y1",function(J){return ee(J).y1}).attr("y2",function(J){return ee(J).y1}).attr("stroke",r.color).attr("stroke-width",_).style("opacity",0);re.merge(se).transition().duration(g).style("opacity",1).attr("x1",function(J){return ee(J).x1}).attr("x2",function(J){return ee(J).x2}).attr("y1",function(J){return ee(J).y1}).attr("y2",function(J){return ee(J).y2}).attr("stroke",r.color).attr("stroke-width",_);var q=v.selectAll(".lollipop-head").data(r.data,function(J){return J._source_key});q.exit().transition().duration(g).style("opacity",0).attr("cx",function(J){return ee(J).x1}).attr("cy",function(J){return ee(J).y1}).remove();var ue=q.enter().append("circle").attr("class","lollipop-head").attr("cx",function(J){return ee(J).x1}).attr("cy",function(J){return ee(J).y1}).attr("r",x).attr("fill",r.color).style("opacity",0);ue.merge(q).transition().duration(g).style("opacity",1).attr("cx",function(J){return oe(J).cx}).attr("cy",function(J){return oe(J).cy}).attr("r",x).attr("fill",r.color)}getHoverSelector(e,r){return".tag-lollipop-"+r.id+" .lollipop-head"}formatTooltip(e,r,i){var s=e.runtime.activeYFormat||d3.format("s");return{title:{text:String(r[i.mapping.x_var])},items:[{color:i.color,label:i.label,value:s(r[i.mapping.y_var])}]}}remove(e,r){e.dom.chartArea.selectAll(".tag-lollipop-"+r.id).remove()}};var xd=class{static type="dumbbell";static traits={hasAxes:!0,referenceLines:!0,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{invertX:!1}};static scaleHints={xScaleType:"band",yScaleType:"linear",xExtentFields:[],yExtentFields:["low_y","high_y"],domainMerge:"union"};static dataContract={x_var:{required:!0,numeric:!1},low_y:{required:!0,numeric:!0},high_y:{required:!0,numeric:!0}};render(e,r,i){var s=e.derived.xScale,o=e.derived.yScale,h=e.config.scales.flipAxis,g=e.options.transition.speed,v=e.dom.chartArea.selectAll(".tag-dumbbell-"+r.id).data([null]).join("g").attr("class","tag-dumbbell-"+r.id),x=r.options&&r.options.dotRadius||5,_=r.options&&r.options.lineWidth||2,A=r.mapping.x_var,O=r.mapping.low_y,I=r.mapping.high_y,Y=s.bandwidth?s.bandwidth()/2:0,K=o.bandwidth?o.bandwidth()/2:0;function ee(k){if(h){var de=o(k[A])+K,ze=s(k[O]),er=s(k[I]);return{lowX:ze,lowY:de,highX:er,highY:de,midX:(ze+er)/2,midY:de}}var Er=s(k[A])+Y,Ht=o(k[O]),xn=o(k[I]);return{lowX:Er,lowY:Ht,highX:Er,highY:xn,midX:Er,midY:(Ht+xn)/2}}var oe=v.selectAll(".dumbbell-line").data(r.data,function(k){return k._source_key});oe.exit().transition().duration(g).style("opacity",0).attr("x1",function(k){return ee(k).midX}).attr("x2",function(k){return ee(k).midX}).attr("y1",function(k){return ee(k).midY}).attr("y2",function(k){return ee(k).midY}).remove();var se=oe.enter().append("line").attr("class","dumbbell-line").attr("x1",function(k){return ee(k).midX}).attr("x2",function(k){return ee(k).midX}).attr("y1",function(k){return ee(k).midY}).attr("y2",function(k){return ee(k).midY}).attr("stroke","var(--chart-grid-color, #ccc)").attr("stroke-width",_).style("opacity",0);se.merge(oe).transition().duration(g).style("opacity",1).attr("x1",function(k){return ee(k).lowX}).attr("x2",function(k){return ee(k).highX}).attr("y1",function(k){return ee(k).lowY}).attr("y2",function(k){return ee(k).highY}).attr("stroke","var(--chart-grid-color, #ccc)").attr("stroke-width",_);var re=v.selectAll(".dumbbell-low").data(r.data,function(k){return k._source_key});re.exit().transition().duration(g).style("opacity",0).attr("cx",function(k){return ee(k).midX}).attr("cy",function(k){return ee(k).midY}).remove();var q=re.enter().append("circle").attr("class","dumbbell-low").attr("cx",function(k){return ee(k).midX}).attr("cy",function(k){return ee(k).midY}).attr("r",x).attr("fill",r.color).attr("opacity",0);q.merge(re).transition().duration(g).attr("cx",function(k){return ee(k).lowX}).attr("cy",function(k){return ee(k).lowY}).attr("r",x).attr("fill",r.color).attr("opacity",.6);var ue=v.selectAll(".dumbbell-high").data(r.data,function(k){return k._source_key});ue.exit().transition().duration(g).style("opacity",0).attr("cx",function(k){return ee(k).midX}).attr("cy",function(k){return ee(k).midY}).remove();var J=ue.enter().append("circle").attr("class","dumbbell-high").attr("cx",function(k){return ee(k).midX}).attr("cy",function(k){return ee(k).midY}).attr("r",x).attr("fill",r.color).attr("opacity",0);J.merge(ue).transition().duration(g).attr("cx",function(k){return ee(k).highX}).attr("cy",function(k){return ee(k).highY}).attr("r",x).attr("fill",r.color).attr("opacity",1)}getHoverSelector(e,r){return".tag-dumbbell-"+r.id+" .dumbbell-high, .tag-dumbbell-"+r.id+" .dumbbell-low"}formatTooltip(e,r,i){var s=e.runtime.activeYFormat||d3.format("s");return{title:{text:String(r[i.mapping.x_var])},items:[{color:i.color,label:"Low",value:s(r[i.mapping.low_y])},{color:i.color,label:"High",value:s(r[i.mapping.high_y])}]}}remove(e,r){e.dom.chartArea.selectAll(".tag-dumbbell-"+r.id).remove()}};var _d=class{static type="waffle";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints=null;static dataContract={category:{required:!0},value:{required:!0,numeric:!0}};render(e,r){for(var i=r.options&&r.options.rows||10,s=r.options&&r.options.cols||10,o=i*s,h=r.options&&r.options.cellGap||2,g=r.options&&r.options.cellRadius||2,v=e.config.layout.margin,x=e.runtime.width-v.left-v.right,_=e.runtime.height-v.top-v.bottom,A=Math.min((x-(s-1)*h)/s,(_-(i-1)*h)/i),O=0,I=0;I=de)&&(J=Er,k=!0)}se._quantile_dot_cx=J,se._quantile_dot_cy=ue,oe.push({cx:J,cy:ue})})});var O=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0,I=e.dom.chartArea.selectAll(".tag-quantile_dots-"+r.id).data([null]).join("g").attr("class","tag-quantile_dots-"+r.id),Y=I.selectAll(".quantile-dots-point").data(r.data,function(ee){return ee._source_key});Y.exit().transition().duration(O).attr("fill-opacity",0).remove();var K=Y.enter().append("circle").attr("class","quantile-dots-point").attr("clip-path","url(#"+e.element.id+"clip)").attr("cx",function(ee){return ee._quantile_dot_cx}).attr("cy",function(ee){return ee._quantile_dot_cy}).attr("r",o).attr("fill",r.color).attr("fill-opacity",0).attr("role","graphics-symbol");K.merge(Y).transition().duration(O).attr("cx",function(ee){return ee._quantile_dot_cx}).attr("cy",function(ee){return ee._quantile_dot_cy}).attr("r",o).attr("fill",r.color).attr("fill-opacity",.75)}getHoverSelector(e,r){return".tag-quantile_dots-"+r.id+" .quantile-dots-point"}formatTooltip(e,r,i){var s=e.runtime.activeYFormat||d3.format("s"),o=i.options&&i.options.source?" ("+i.options.source+")":"";return{title:String(r[i.mapping.x_var]),items:[{color:i.color,label:i.label+o,value:"Q"+r[i.mapping.quantile_rank]+": "+s(r[i.mapping.y_var])}],value:r[i.mapping.y_var],raw:r}}remove(e,r){e.dom.chartArea.selectAll(".tag-quantile_dots-"+r.id).remove()}};var wd=class{static type="bump";static traits={hasAxes:!0,referenceLines:!1,legendType:"layer",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints={xScaleType:"point",yScaleType:"linear",xExtentFields:[],yExtentFields:["y_var"],domainMerge:"union"};static dataContract={x_var:{required:!0},y_var:{required:!0,numeric:!0},group:{required:!0}};render(e,r){var i=e.derived.xScale,s=e.derived.yScale,o=r.mapping.x_var,h=r.mapping.y_var,g=r.mapping.group,v=r.options&&r.options.dotRadius||5,x=e.derived.colorDiscrete||d3.scaleOrdinal(d3.schemeCategory10),_=d3.group(r.data,function(K){return K[g]}),A=e.dom.chartArea.selectAll(".tag-bump-"+r.id).data([null]).join("g").attr("class","tag-bump-"+r.id),O=d3.line().x(function(K){return i(K[o])}).y(function(K){return s(K[h])}).curve(d3.curveBumpX),I=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0,Y=0;_.forEach(function(K,ee){var oe=x(ee),se=K.slice().sort(function(k,de){return String(k[o]).localeCompare(String(de[o]))}),re=A.selectAll(".bump-line-"+Y).data([se]),q=re.enter().append("path").attr("class","bump-line bump-line-"+Y).attr("fill","none").attr("stroke",oe).attr("stroke-width",2.5).attr("stroke-opacity",0).attr("d",O);q.merge(re).transition().duration(I).attr("stroke",oe).attr("stroke-opacity",.8).attr("d",O);var ue=A.selectAll(".bump-dot-"+Y).data(se,function(k){return k._source_key||k[o]});ue.exit().transition().duration(I).style("opacity",0).remove();var J=ue.enter().append("circle").attr("class","bump-dot bump-dot-"+Y).attr("cx",function(k){return i(k[o])}).attr("cy",function(k){return s(k[h])}).attr("r",v).attr("fill",oe).attr("stroke","#fff").attr("stroke-width",1.5).style("opacity",0);J.merge(ue).transition().duration(I).style("opacity",1).attr("cx",function(k){return i(k[o])}).attr("cy",function(k){return s(k[h])}).attr("r",v).attr("fill",oe),Y++})}getHoverSelector(e,r){return".tag-bump-"+r.id+" .bump-dot"}formatTooltip(e,r,i){return{title:{text:String(r[i.mapping.group])},items:[{color:i.color,label:String(r[i.mapping.x_var]),value:String(r[i.mapping.y_var])}]}}remove(e,r){e.dom.chartArea.selectAll(".tag-bump-"+r.id).remove()}};var Ad=class{static type="radar";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints=null;static dataContract={axis:{required:!0},value:{required:!0,numeric:!0}};render(e,r){var i=e.margin||(e.config&&e.config.layout?e.config.layout.margin:{top:0,right:0,bottom:0,left:0}),s=(e.width||e.runtime&&e.runtime.width||0)-i.left-i.right,o=(e.height||e.runtime&&e.runtime.height||0)-i.top-i.bottom,h=r.mapping.axis,g=r.mapping.value,v=r.mapping.group,x=r.options&&r.options.labelOffset||16,_=s/2,A=o/2,O=Math.max(0,Math.min(s,o)/2-x-8),I=[],Y=new Set,K=d3.max(r.data,function(cr){return+cr[g]})||0,ee=d3.scaleLinear().domain([0,K>0?K:1]).range([0,O]),oe=[],se=v?d3.group(r.data,function(cr){return cr[v]}):new Map([[r.label||"Series",r.data]]),re=e.derived.colorDiscrete||d3.scaleOrdinal(d3.schemeCategory10),q,ue,J,k,de;if(r.data.forEach(function(cr){var bn=cr[h];Y.has(bn)||(Y.add(bn),I.push(bn))}),q=I.length,q===0)return;ue=e.dom.chartArea.selectAll(".tag-radar-"+r.id).data([null]).join("g").attr("class","tag-radar-"+r.id),J=ue.selectAll(".radar-axis-layer").data([null]).join("g").attr("class","radar-axis-layer"),k=ue.selectAll(".radar-polygon-layer").data([null]).join("g").attr("class","radar-polygon-layer");var ze=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0;function er(cr){var bn=2*Math.PI*cr/q,mn=Math.sin(bn),qn=Math.cos(bn),Wt="middle";return mn>.25?Wt="start":mn<-.25&&(Wt="end"),{lineX:_+O*mn,lineY:A-O*qn,labelX:_+(O+x)*mn,labelY:A-(O+x)*qn,textAnchor:Wt}}var Er=J.selectAll(".radar-axis").data(I,function(cr){return cr});Er.exit().transition().duration(ze).style("opacity",0).remove();var Ht=Er.enter().append("g").attr("class","radar-axis").style("opacity",0);Ht.append("line").attr("class","radar-axis-line").attr("stroke","var(--chart-grid, #cbd5e1)").attr("stroke-width",1).attr("x1",_).attr("y1",A).attr("x2",_).attr("y2",A),Ht.append("text").attr("class","radar-axis-label").attr("fill","var(--chart-fg, #1f2937)").attr("x",_).attr("y",A).attr("dy","0.35em").attr("text-anchor","middle");var xn=Ht.merge(Er);xn.transition().duration(ze).style("opacity",1),xn.each(function(cr,bn){var mn=er(bn),qn=d3.select(this);qn.select(".radar-axis-line").attr("stroke","var(--chart-grid, #cbd5e1)").attr("stroke-width",1).transition().duration(ze).attr("x1",_).attr("y1",A).attr("x2",mn.lineX).attr("y2",mn.lineY),qn.select(".radar-axis-label").text(cr).transition().duration(ze).attr("x",mn.labelX).attr("y",mn.labelY).attr("text-anchor",mn.textAnchor)}),se.forEach(function(cr,bn){var mn=new Map,qn=[];cr.forEach(function(Wt){mn.set(Wt[h],Wt)}),I.forEach(function(Wt,Pr){var hi=2*Math.PI*Pr/q,Ai=mn.get(Wt),pi=Ai?+Ai[g]:0,ss=ee(Number.isFinite(pi)?pi:0);qn.push({axis:Wt,angle:hi,value:Number.isFinite(pi)?pi:0,x:_+ss*Math.sin(hi),y:A-ss*Math.cos(hi),datum:Ai||null})}),oe.push({key:bn,color:re(bn),points:qn,rows:cr})}),e.derived.colorDiscrete=re.domain(oe.map(function(cr){return cr.key})),e.colorDiscrete=e.derived.colorDiscrete,de=d3.line().x(function(cr){return cr.x}).y(function(cr){return cr.y}).curve(d3.curveLinearClosed);function $r(cr){return de(cr.map(function(bn){return{x:_,y:A}}))}var Tn=k.selectAll(".radar-polygon").data(oe,function(cr){return cr.key});Tn.exit().transition().duration(ze).style("opacity",0).remove();var In=Tn.enter().append("path").attr("class","radar-polygon").attr("d",function(cr){return $r(cr.points)}).attr("fill",function(cr){return cr.color}).attr("fill-opacity",0).attr("stroke",function(cr){return cr.color}).attr("stroke-width",2).attr("stroke-opacity",0);In.merge(Tn).transition().duration(ze).attrTween("d",function(cr){var bn=this,mn=bn._radarPoints||cr.points.map(function(){return{x:_,y:A}}),qn=cr.points,Wt=mn.map(function(Pr,hi){var Ai=qn[hi]||Pr;return{x:d3.interpolateNumber(Pr.x,Ai.x),y:d3.interpolateNumber(Pr.y,Ai.y)}});return function(Pr){var hi=Wt.map(function(Ai){return{x:Ai.x(Pr),y:Ai.y(Pr)}});return bn._radarPoints=qn,de(hi)}}).attr("fill",function(cr){return cr.color}).attr("fill-opacity",.2).attr("stroke",function(cr){return cr.color}).attr("stroke-opacity",1)}getHoverSelector(e,r){return".tag-radar-"+r.id+" .radar-polygon"}formatTooltip(e,r){return{title:{text:String(r.key)},items:r.points.map(function(i){return{color:r.color,label:i.axis,value:String(i.value)}})}}remove(e,r){e.dom.chartArea.selectAll(".tag-radar-"+r.id).remove()}};var Td=class{static type="funnel";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints=null;static dataContract={stage:{required:!0},value:{required:!0,numeric:!0}};render(e,r){var i=e.margin||(e.config&&e.config.layout?e.config.layout.margin:{top:0,right:0,bottom:0,left:0}),s=(e.width||e.runtime&&e.runtime.width||0)-i.left-i.right,o=(e.height||e.runtime&&e.runtime.height||0)-i.top-i.bottom,h=r.mapping.stage,g=r.mapping.value,v=r.options&&r.options.stageGap||6,x=d3.max(r.data,function(ue){return+ue[g]})||0,_=d3.scaleLinear().domain([0,x>0?x:1]).range([0,s*.95]),A=e.derived.colorDiscrete||d3.scaleOrdinal(d3.schemeTableau10),O=r.data.length>0?o/r.data.length:0,I,Y,K;I=r.data.map(function(ue,J){var k=r.data[J+1]||null,de=_(+ue[g]||0),ze=k?_(+k[g]||0):de*.55,er=J*O,Er=Math.max(er,er+O-v),Ht=s/2,xn=Ht-de/2,$r=Ht+de/2,Tn=Ht-ze/2,In=Ht+ze/2;return{stage:ue[h],value:+ue[g],color:A(ue[h]),datum:ue,points:[[xn,er],[$r,er],[In,Er],[Tn,Er]],labelX:Ht,labelY:(er+Er)/2}}),e.derived.colorDiscrete=A.domain(I.map(function(ue){return ue.stage})),e.colorDiscrete=e.derived.colorDiscrete;var ee=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0;function oe(ue){return"M"+ue[0][0]+","+ue[0][1]+"L"+ue[1][0]+","+ue[1][1]+"L"+ue[2][0]+","+ue[2][1]+"L"+ue[3][0]+","+ue[3][1]+"Z"}function se(ue){var J=(ue.points[0][0]+ue.points[1][0])/2,k=(ue.points[0][1]+ue.points[3][1])/2;return[[J,k],[J,k],[J,k],[J,k]]}Y=e.dom.chartArea.selectAll(".tag-funnel-"+r.id).data([null]).join("g").attr("class","tag-funnel-"+r.id),K=Y.selectAll(".funnel-stage-group").data(I,function(ue){return ue.stage}),K.exit().transition().duration(ee).style("opacity",0).remove();var re=K.enter().append("g").attr("class","funnel-stage-group").style("opacity",0);re.append("path").attr("class","funnel-stage").attr("d",function(ue){return oe(se(ue))}).attr("fill",function(ue){return ue.color}),re.append("text").attr("class","funnel-label").attr("x",function(ue){return ue.labelX}).attr("y",function(ue){return ue.labelY}).attr("dy","0.35em").attr("text-anchor","middle").text(function(ue){return ue.stage});var q=re.merge(K);q.transition().duration(ee).style("opacity",1),q.select(".funnel-stage").transition().duration(ee).attr("d",function(ue){return oe(ue.points)}).attr("fill",function(ue){return ue.color}),q.select(".funnel-label").text(function(ue){return ue.stage}).transition().duration(ee).attr("x",function(ue){return ue.labelX}).attr("y",function(ue){return ue.labelY})}getHoverSelector(e,r){return".tag-funnel-"+r.id+" .funnel-stage"}formatTooltip(e,r){return{title:{text:String(r.stage)},items:[{color:r.color,label:String(r.stage),value:String(r.value)}]}}remove(e,r){e.dom.chartArea.selectAll(".tag-funnel-"+r.id).remove()}};var Id=class{static type="parallel";static traits={hasAxes:!1,referenceLines:!1,legendType:"ordinal",binning:!1,rolloverStyle:"element",scaleCapabilities:{}};static scaleHints=null;static dataContract={dimensions:{required:!0}};render(e,r){var i=e.margin||(e.config&&e.config.layout?e.config.layout.margin:{top:0,right:0,bottom:0,left:0}),s=(e.width||e.runtime&&e.runtime.width||0)-i.left-i.right,o=(e.height||e.runtime&&e.runtime.height||0)-i.top-i.bottom,h=r.mapping.dimensions,g=Array.isArray(h)?h.slice():[h],v=r.mapping.group,x=d3.scalePoint().domain(g).range([0,s]).padding(.5),_={},A=e.derived.colorDiscrete||d3.scaleOrdinal(d3.schemeCategory10),O,I,Y;g.forEach(function(q){var ue=d3.extent(r.data,function(J){var k=+J[q];return Number.isFinite(k)?k:null});(!ue||ue[0]===void 0||ue[1]===void 0)&&(ue=[0,1]),ue[0]===ue[1]&&(ue=[ue[0]-1,ue[1]+1]),_[q]=d3.scaleLinear().domain(ue).range([o,0])}),e.derived.colorDiscrete=A.domain(Array.from(new Set(r.data.map(function(q){return v?q[v]:r.label})))),e.colorDiscrete=e.derived.colorDiscrete,O=e.dom.chartArea.selectAll(".tag-parallel-"+r.id).data([null]).join("g").attr("class","tag-parallel-"+r.id),I=O.selectAll(".parallel-axis").data(g).join(function(q){var ue=q.append("g").attr("class","parallel-axis");return ue.append("text").attr("class","parallel-axis-label"),ue}).attr("transform",function(q){return"translate("+x(q)+",0)"}).each(function(q){d3.select(this).call(d3.axisLeft(_[q]).ticks(5))}),I.select(".parallel-axis-label").attr("x",0).attr("y",-10).attr("text-anchor","middle").text(function(q){return q}),Y=d3.line().defined(function(q){return q&&q[1]!==null}).x(function(q){return q[0]}).y(function(q){return q[1]});var K=e.options&&e.options.transition&&typeof e.options.transition.speed=="number"?e.options.transition.speed:0;function ee(q){var ue=g.map(function(J){var k=+q[J];return Number.isFinite(k)?[x(J),_[J](k)]:[x(J),null]});return Y(ue)}function oe(q){var ue=v?q[v]:r.label;return A(ue)}var se=O.selectAll(".parallel-line").data(r.data,function(q,ue){return q._source_key!=null?q._source_key:ue});se.exit().transition().duration(K).attr("stroke-opacity",0).remove();var re=se.enter().append("path").attr("class","parallel-line").attr("fill","none").attr("d",ee).attr("stroke",oe).attr("stroke-opacity",0);re.merge(se).transition().duration(K).attr("d",ee).attr("stroke",oe).attr("stroke-opacity",.6)}getHoverSelector(e,r){return".tag-parallel-"+r.id+" .parallel-line"}formatTooltip(e,r,i){var s=Array.isArray(i.mapping.dimensions)?i.mapping.dimensions:[i.mapping.dimensions],o=i.mapping.group?String(r[i.mapping.group]):String(i.label||"Series");return{title:{text:o},items:s.map(function(h){return{color:e.colorDiscrete?e.colorDiscrete(i.mapping.group?r[i.mapping.group]:i.label):i.color,label:h,value:String(r[h])}})}}remove(e,r){e.dom.chartArea.selectAll(".tag-parallel-"+r.id).remove()}};var ns=new Map;function Ts(t,e){if(ns.has(t))throw new Error("Renderer already registered for type: "+t);var r=e&&e.constructor?e.constructor.traits:null,i=["hasAxes","referenceLines","legendType","binning","rolloverStyle"];if(!r)throw new Error("Renderer missing static traits: "+t);i.forEach(function(s){if(!(s in r))throw new Error("Renderer trait missing '"+s+"': "+t)}),ns.set(t,e)}function t6(t){if(!ns.has(t))throw new Error("Unknown renderer type: "+t);return ns.get(t)}function fl(t){return t6(t.type)}function qg(){return ns.has(X3.type)||Ts(X3.type,new X3),ns.has(J3.type)||Ts(J3.type,new J3),ns.has(K3.type)||Ts(K3.type,new K3),ns.has(Q3.type)||Ts(Q3.type,new Q3),ns.has(Z3.type)||Ts(Z3.type,new Z3),ns.has(ed.type)||Ts(ed.type,new ed),ns.has(td.type)||Ts(td.type,new td),ns.has(ld.type)||Ts(ld.type,new ld),ns.has(cd.type)||Ts(cd.type,new cd),ns.has(ud.type)||Ts(ud.type,new ud),ns.has(fd.type)||Ts(fd.type,new fd),ns.has(dd.type)||Ts(dd.type,new dd),ns.has(hd.type)||Ts(hd.type,new hd),ns.has(pd.type)||Ts(pd.type,new pd),ns.has(md.type)||Ts(md.type,new md),ns.has(gd.type)||Ts(gd.type,new gd),ns.has(vd.type)||Ts(vd.type,new vd),ns.has(xd.type)||Ts(xd.type,new xd),ns.has(_d.type)||Ts(_d.type,new _d),ns.has(Sd.type)||Ts(Sd.type,new Sd),ns.has(Ed.type)||Ts(Ed.type,new Ed),ns.has(wd.type)||Ts(wd.type,new wd),ns.has(Ad.type)||Ts(Ad.type,new Ad),ns.has(Td.type)||Ts(Td.type,new Td),ns.has(Id.type)||Ts(Id.type,new Id),ns.has(yd.type)||Ts(yd.type,new yd),ns.has(bd.type)||Ts(bd.type,new bd),ns}function zg(){return Array.from(ns.values())}function Hg(t,e){var r=Vs(t,e.label,e.color),i=d3.drag().on("start",function(){d3.select(this).raise().classed("active",!0).style("cursor","grabbing")}).on("drag",function(s,o){o[e.mapping.x_var]=t.xScale.invert(s.x),o[e.mapping.y_var]=t.yScale.invert(s.y),d3.select(this).attr("cx",t.xScale(o[e.mapping.x_var])).attr("cy",t.yScale(o[e.mapping.y_var]))}).on("end",function(s,o){d3.select(this).classed("active",!1).style("cursor","grab"),t.updateRegression(r,e.label),t.emit("dragEnd",{point:o,layerLabel:e.label})});t.chart.selectAll("."+xr("point",t.element.id,e.label)).style("cursor","grab").call(i)}function I0(t,e,r){Od(t);var i=d3.select(t.dom.element),s=i.append("div").attr("class","myIO-status-bar").attr("role","status").attr("aria-live","polite");s.append("span").attr("class","myIO-status-bar-text").text(e);var o=s.append("span").attr("class","myIO-status-bar-actions");(r||[]).forEach(function(h){o.append("button").attr("class","myIO-status-bar-btn").attr("type","button").text(h.label).on("click",h.handler)})}function Od(t){d3.select(t.dom.element).selectAll(".myIO-status-bar").remove()}var Wg=["point","bar","histogram","hexbin","groupedBar"];function Yg(t){var e=t.config.interactions.brush;if(!(!e||!e.enabled)){var r=(t.derived.currentLayers||[]).filter(function(g){return Wg.indexOf(g.type)>-1});if(r.length!==0){C0(t);var i=e.direction==="x"?d3.brushX():e.direction==="y"?d3.brushY():d3.brush(),s=t.config.layout.margin,o=t.runtime.width-(s.left+s.right),h=t.runtime.height-(s.top+s.bottom);i.extent([[0,0],[o,h]]),i.on("brush",function(g){j9(t,g,r,e)}).on("end",function(g){q9(t,g,r,e)}),t.dom.chartArea.insert("g",":first-child").attr("class","myIO-brush").call(i),t.dom.chartArea.select(".myIO-brush .overlay").style("cursor","crosshair"),t.runtime._brushFn=i,d3.select(t.dom.element).on("keydown.brush",function(g){g.key==="Escape"&&t.runtime._brushed&&r6(t)})}}}function j9(t,e,r,i){if(e.selection){var s=e.selection,o=i.direction;r.forEach(function(h){var g=Jg(t,h);t.dom.chartArea.selectAll(g).each(function(v){var x=Xg(t,v,h,s,o);d3.select(this).style("opacity",x?1:"var(--chart-brush-dim-opacity)")})})}}function q9(t,e,r,i){if(!e.selection){r6(t);return}var s=e.selection,o=i.direction,h=z9(t,s,o),g=[],v=[];r.forEach(function(_){_.data.forEach(function(A){Xg(t,A,_,s,o)&&(g.push(A),A._source_key&&v.push(A._source_key))})}),t.runtime._brushed={data:g,extent:h,keys:v};var x=r.reduce(function(_,A){return _+A.data.length},0);I0(t,g.length+" of "+x+" points selected",[{label:"Clear",handler:function(){r6(t)}}]),t.emit("brushed",{data:g,extent:h,keys:v,layerLabel:r.length===1?r[0].label:null})}function r6(t){(t.derived.currentLayers||[]).forEach(function(e){if(Wg.indexOf(e.type)>-1){var r=Jg(t,e);t.dom.chartArea.selectAll(r).style("opacity",1)}}),t.runtime._brushFn&&t.dom.chartArea.select(".myIO-brush").call(t.runtime._brushFn.move,null),t.runtime._brushed=null,Od(t),t.emit("brushed",{data:[],extent:null,keys:[],layerLabel:null})}function Xg(t,e,r,i,s){var o=r.mapping.x_var,h=r.mapping.y_var,g=t.xScale(e[o]),v=t.yScale(e[h]);return isNaN(g)||isNaN(v)?!1:s==="x"?g>=i[0]&&g<=i[1]:s==="y"?v>=i[0]&&v<=i[1]:g>=i[0][0]&&g<=i[1][0]&&v>=i[0][1]&&v<=i[1][1]}function O0(t,e,r){return typeof t.invert=="function"?[t.invert(e),t.invert(r)]:null}function z9(t,e,r){return r==="x"?{x:O0(t.xScale,e[0],e[1]),y:null}:r==="y"?{x:null,y:O0(t.yScale,e[1],e[0])}:{x:O0(t.xScale,e[0][0],e[1][0]),y:O0(t.yScale,e[1][1],e[0][1])}}function Jg(t,e){return e.type==="groupedBar"?".tag-grouped-bar-g rect":"."+xr(e.type,t.dom.element.id,e.label)}function C0(t){t.dom&&t.dom.chartArea&&t.dom.chartArea.selectAll(".myIO-brush").remove(),t.dom&&t.dom.element&&d3.select(t.dom.element).on("keydown.brush",null),t.runtime._brushed=null}var n6=30;function Kg(t,e,r){x2(t);var i=d3.select(t.dom.element),s=i.append("div").attr("class","myIO-popover").attr("role","dialog").attr("aria-label","Annotate data point"),o=s.append("div").attr("class","myIO-popover-field");o.append("label").text("Label:");var h;r.presetLabels&&r.presetLabels.length>0?(h=o.append("select").attr("class","myIO-popover-input"),r.presetLabels.forEach(function(A){h.append("option").attr("value",A).text(A)}),r.existingLabel&&h.property("value",r.existingLabel)):(h=o.append("input").attr("class","myIO-popover-input").attr("type","text").attr("maxlength",n6).attr("placeholder","Enter label..."),r.existingLabel&&h.property("value",r.existingLabel));var g=null;if(r.categoryColors){var v=s.append("div").attr("class","myIO-popover-field");v.append("label").text("Category:");var x=v.append("div").attr("class","myIO-popover-colors");Object.keys(r.categoryColors).forEach(function(A){var O=r.categoryColors[A];x.append("button").attr("class","myIO-popover-color-btn").attr("type","button").attr("title",A).attr("aria-label",A).style("background-color",O).on("click",function(){x.selectAll(".myIO-popover-color-btn").classed("selected",!1),d3.select(this).classed("selected",!0),g=O})})}var _=s.append("div").attr("class","myIO-popover-buttons");r.existingLabel&&r.onRemove&&_.append("button").attr("class","myIO-popover-btn myIO-popover-btn--danger").attr("type","button").text("Remove").on("click",function(){x2(t),r.onRemove()}),_.append("button").attr("class","myIO-popover-btn").attr("type","button").text("Cancel").on("click",function(){x2(t),r.onCancel&&r.onCancel()}),_.append("button").attr("class","myIO-popover-btn myIO-popover-btn--primary").attr("type","button").text("Apply").on("click",function(){var A=h.property("value").trim().substring(0,n6);A&&(x2(t),r.onApply(A,g))}),H9(t,s,e),h.node().focus(),s.on("keydown",function(A){if(A.key==="Enter"){var O=h.property("value").trim().substring(0,n6);O&&(x2(t),r.onApply(O,g))}A.key==="Escape"&&(x2(t),r.onCancel&&r.onCancel())})}function H9(t,e,r){var i=t.config.layout.margin,s=r.px+i.left,o=r.py+i.top-10;e.style("left",Math.max(4,Math.min(s-80,t.runtime.totalWidth-180))+"px").style("bottom",t.runtime.height-o+8+"px")}function x2(t){d3.select(t.dom.element).selectAll(".myIO-popover").remove()}var W9=["point","bar","histogram","hexbin","groupedBar"];function Qg(t){var e=t.config.interactions.annotation;if(!(!e||!e.enabled)){t.runtime._annotations||(t.runtime._annotations=[]);var r=(t.derived.currentLayers||[]).filter(function(i){return W9.indexOf(i.type)>-1});r.forEach(function(i){var s="."+xr(i.type,t.dom.element.id,i.label);t.dom.chartArea.selectAll(s).on("click.annotate",function(o,h){o.stopPropagation();var g=K9(t,h._source_key);Kg(t,{px:t.xScale(h[i.mapping.x_var]),py:t.yScale(h[i.mapping.y_var])},{presetLabels:e.presetLabels,categoryColors:e.categoryColors,existingLabel:g?g.label:null,onApply:function(v,x){Y9(t,h,i,v,x)},onRemove:function(){X9(t,h._source_key)},onCancel:function(){}})})}),L0(t),i6(t)}}function Y9(t,e,r,i,s){t.runtime._annotations=t.runtime._annotations.filter(function(h){return h._source_key!==e._source_key});var o={_source_key:e._source_key,x:e[r.mapping.x_var],y:e[r.mapping.y_var],x_var:r.mapping.x_var,y_var:r.mapping.y_var,label:i,category:s||null,layerLabel:r.label,timestamp:new Date().toISOString()};t.runtime._annotations.push(o),L0(t),i6(t),t.emit("annotated",{annotations:t.runtime._annotations,action:"add",latest:o})}function X9(t,e){var r=t.runtime._annotations.find(function(i){return i._source_key===e});t.runtime._annotations=t.runtime._annotations.filter(function(i){return i._source_key!==e}),L0(t),i6(t),t.emit("annotated",{annotations:t.runtime._annotations,action:"remove",latest:r||null})}function J9(t){t.runtime._annotations=[],L0(t),Od(t),t.emit("annotated",{annotations:[],action:"clear",latest:null})}function L0(t){var e=t.dom.chartArea.selectAll(".myIO-annotations").data([0]);e=e.enter().append("g").attr("class","myIO-annotations").merge(e);var r=e.selectAll(".myIO-annotation-mark").data(t.runtime._annotations||[],function(o){return o._source_key});r.exit().remove();var i=r.enter().append("g").attr("class","myIO-annotation-mark");i.append("circle").attr("r",8).attr("fill","none").attr("stroke-width",2),i.append("text").attr("dy",-12).attr("text-anchor","middle").attr("class","myIO-annotation-label");var s=i.merge(r);s.attr("transform",function(o){return"translate("+t.xScale(o.x)+","+t.yScale(o.y)+")"}),s.select("circle").style("stroke",function(o){return o.category||"var(--chart-annotation-ring)"}),s.select("text").text(function(o){return o.label.length>30?o.label.substring(0,27)+"\u2026":o.label}).style("font-size","var(--chart-annotation-font-size)").style("fill","var(--chart-text-color)")}function i6(t){var e=(t.runtime._annotations||[]).length;if(e===0){Od(t);return}I0(t,e+" annotation"+(e===1?"":"s"),[{label:"Export",handler:function(){var r=t.runtime._annotations||[];r.length>0&&E0(t.dom.element.id+"_annotations.csv",r)}},{label:"Clear",handler:function(){J9(t)}}])}function K9(t,e){return(t.runtime._annotations||[]).find(function(r){return r._source_key===e})}function Zg(t){x2(t)}var Rh=new Map;function s6(t){return t&&t.config&&t.config.interactions&&t.config.interactions.linked}function a6(t){var e=s6(t);return e&&e.cursor===!0&&e.group?e.group:null}function ty(t){var e=a6(t);if(e){var r=Rh.get(e);r||(r=new Set,Rh.set(e,r)),r.add(t),t.runtime=t.runtime||{},t.runtime._linkedCursor||(t.runtime._linkedCursor={lastTs:0})}}function ry(t){Rh.forEach(function(e,r){e.delete(t)&&e.size===0&&Rh.delete(r)})}function ny(t,e){var r=a6(t);if(r){var i=Rh.get(r);i&&i.forEach(function(s){s!==t&&Z9(s,e)})}}function Q9(t){var e=a6(t);e&&ny(t,{sourceId:t.element&&t.element.id,group:e,ts:typeof performance<"u"?performance.now():Date.now(),clear:!0})}function N0(t,e,r,i){var s=s6(t);if(!(!s||s.cursor!==!0)){var o=s.keyColumn,h=e&&o&&e[o]!==void 0?e[o]:null;ny(t,{sourceId:t.element&&t.element.id,group:s.group,keyValue:h,xValue:r,tooltip:i||null,ts:typeof performance<"u"?performance.now():Date.now()})}}function D0(t){var e=s6(t);!e||e.cursor!==!0||Q9(t)}function Z9(t,e){var r=t.runtime&&t.runtime._linkedCursor;if(r&&!(typeof e.ts=="number"&&e.ts+o)return null;var v=r(h);return Number.isFinite(v)?v:null}var x=typeof r.domain=="function"?r.domain():[];if(x.indexOf(e)===-1)return null;var _=r(e);return Number.isFinite(_)?_:null}function tx(t,e){var r=t.plot||t.svg;if(!(!r||typeof r.select!="function")){var i=r.select("line.myIO-hover-rule");i.empty()&&(i=r.append("line").attr("class","myIO-hover-rule"));var s=t.margin||{},o=(t.height||0)-((+s.top||0)+(+s.bottom||0));i.attr("x1",e).attr("x2",e).attr("y1",0).attr("y2",o).style("display",null)}}function ey(t){var e=t.plot||t.svg;!e||typeof e.select!="function"||e.select("line.myIO-hover-rule").remove()}var iy=["point","bar","histogram","hexbin","groupedBar","waffle","beeswarm","lollipop","dumbbell"];function sy(t){var e=t.config.interactions.linked;if(!(!e||!e.enabled)&&!(typeof crosstalk>"u")){o6(t);var r=new crosstalk.SelectionHandle(e.group),i=e.filter?new crosstalk.FilterHandle(e.group):null;t.runtime._crosstalkSel=r,t.runtime._crosstalkFil=i,(e.mode==="source"||e.mode==="both")&&(t.runtime._linkedBrushHandler=function(s){s.keys&&s.keys.length>0?r.set(s.keys):r.clear()},t.on("brushed",t.runtime._linkedBrushHandler)),(e.mode==="target"||e.mode==="both")&&(r.on("change.myIO",function(s){rx(t,s.value)}),i&&i.on("change.myIO",function(s){nx(t,s.value)}))}}function rx(t,e){var r=(t.derived.currentLayers||[]).filter(function(i){return iy.indexOf(i.type)>-1});r.forEach(function(i){var s="."+xr(i.type,t.dom.element.id,i.label);t.dom.chartArea.selectAll(s).each(function(o){if(!e)d3.select(this).style("opacity",1);else{var h=e.indexOf(o._source_key)>-1;d3.select(this).style("opacity",h?1:"var(--chart-brush-dim-opacity)")}})})}function nx(t,e){var r=(t.derived.currentLayers||[]).filter(function(i){return iy.indexOf(i.type)>-1});r.forEach(function(i){var s="."+xr(i.type,t.dom.element.id,i.label);t.dom.chartArea.selectAll(s).each(function(o){if(!e)d3.select(this).style("display",null);else{var h=e.indexOf(o._source_key)>-1;d3.select(this).style("display",h?null:"none")}})})}function o6(t){t.runtime._linkedBrushHandler&&(t.off("brushed",t.runtime._linkedBrushHandler),t.runtime._linkedBrushHandler=null),t.runtime._crosstalkSel&&(t.runtime._crosstalkSel.close(),t.runtime._crosstalkSel=null),t.runtime._crosstalkFil&&(t.runtime._crosstalkFil.close(),t.runtime._crosstalkFil=null),ry(t)}function oy(t){var e=t.config.interactions.sliders;if(!(!e||e.length===0)){l6(t),t.runtime._sliderTimers=[];var r=d3.select(t.dom.element),i=r.append("div").attr("class","myIO-slider-wrapper");e.forEach(function(s){var o=i.append("div").attr("class","myIO-slider-row");o.append("label").attr("class","myIO-slider-label").attr("for",t.dom.element.id+"-slider-"+s.param).text(s.label);var h=o.append("input").attr("type","range").attr("class","myIO-slider-input").attr("id",t.dom.element.id+"-slider-"+s.param).attr("min",s.min).attr("max",s.max).attr("step",s.step||"any").attr("aria-label",s.label).attr("aria-valuemin",s.min).attr("aria-valuemax",s.max).attr("aria-valuenow",s.value).property("value",s.value),g=o.append("span").attr("class","myIO-slider-value").text(ay(s.value,s.step));if(!HTMLWidgets.shinyMode){h.attr("disabled",!0).attr("title","Parameter sliders require Shiny"),o.style("opacity","0.5");return}var v=t.runtime._sliderTimers.length;t.runtime._sliderTimers.push(null);var x=s.debounce||200;h.on("input",function(){var _=+this.value;g.text(ay(_,s.step)),d3.select(this).attr("aria-valuenow",_),clearTimeout(t.runtime._sliderTimers[v]),t.runtime._sliderTimers[v]=setTimeout(function(){Shiny.onInputChange("myIO-"+t.dom.element.id+"-slider-"+s.param,_),t.emit("sliderChanged",{param:s.param,value:_})},x)})})}}function ay(t,e){if(e&&e<1){var r=String(e).split(".")[1];return t.toFixed(r?r.length:2)}return String(t)}function l6(t){t.runtime._sliderTimers&&(t.runtime._sliderTimers.forEach(clearTimeout),t.runtime._sliderTimers=null),d3.select(t.dom.element).selectAll(".myIO-slider-wrapper").remove()}function ix(t){let e=document.createElement("div");return e.textContent=String(t),e.innerHTML}function cy(t){t.dom.tooltip=d3.select(t.dom.element).append("div").attr("class","toolTip").attr("role","status").attr("aria-live","polite").attr("aria-hidden","true"),t.dom.tooltipTitle=t.dom.tooltip.append("div").attr("class","toolTipTitle"),t.dom.tooltipBody=t.dom.tooltip.append("div").attr("class","toolTipBody"),t.runtime.tooltipHideTimer=null,t.captureLegacyAliases()}function Cd(t){d3.select(t.dom.element).select(".toolTipBox").remove(),d3.select(t.dom.element).select(".toolLine").remove(),d3.select(t.dom.element).select(".toolPointLayer").remove(),t.runtime.toolTipBox=null,t.runtime.toolLine=null,t.runtime.toolPointLayer=null,t.syncLegacyAliases()}function uy(t,e,r){Cd(t),t.runtime.toolLine=t.dom.chartArea.append("line").attr("class","toolLine"),t.runtime.toolPointLayer=t.dom.chartArea.append("g").attr("class","toolPointLayer"),t.runtime.toolTipBox=t.dom.svg.append("rect").attr("class","toolTipBox").attr("opacity",0).attr("width",t.width-(t.margin.left+t.margin.right)).attr("height",t.height-(t.margin.top+t.margin.bottom)).attr("transform","translate("+t.margin.left+","+t.margin.top+")").on("mouseover",function(i){e(i)}).on("mousemove",function(i){e(i)}).on("mouseout",function(){typeof r=="function"&&r()}).on("touchstart",function(i){i.preventDefault(),e(i)}).on("touchmove",function(i){i.preventDefault(),e(i)}).on("touchend",function(){typeof r=="function"&&r()}),t.syncLegacyAliases()}function _2(t,e){if(!t.dom.tooltip)return;clearTimeout(t.runtime.tooltipHideTimer);let r=e.pointer||[0,0],i=e.title||{},s=e.items||[],o=s.length===1&&s[0].color?s[0].color:null;t.dom.tooltipTitle.style("border-left-color",o||null).html(""+ix(ly(i))+"");let h=t.dom.tooltipBody.selectAll(".toolTipItem").data(s);h.exit().remove();let g=h.enter().append("div").attr("class","toolTipItem");g.append("span").attr("class","dot"),g.append("span").attr("class","toolTipLabel"),g.append("span").attr("class","toolTipValue"),g.merge(h).select(".dot").style("background-color",function(v){return v.color||"transparent"}),g.merge(h).select(".toolTipLabel").text(function(v){return v.label||""}),g.merge(h).select(".toolTipValue").text(function(v){return ly(v)}),t.dom.tooltip.style("display","inline-block").style("opacity",1).attr("aria-hidden","false"),sx(t,r)}function ku(t){t.dom.tooltip&&(clearTimeout(t.runtime.tooltipHideTimer),t.runtime.tooltipHideTimer=window.setTimeout(function(){t.dom.tooltip.style("display","none").style("opacity",0).attr("aria-hidden","true")},300))}function ly(t){if(t==null)return"";if(typeof t=="string")return t;let e=typeof t.format=="function"?t.format:function(i){return i},r=t.text!=null?t.text:t.value;return r==null?"":e(r)}function sx(t,e){let r=t.dom.element.getBoundingClientRect(),i=t.dom.tooltip.node();t.dom.tooltip.style("left",e[0]+12+"px").style("top",e[1]+12+"px");let s=i.getBoundingClientRect(),o=e[0]+12,h=e[1]+12;o+s.width>r.width&&(o=Math.max(8,e[0]-s.width-12)),h+s.height>r.height&&(h=Math.max(8,e[1]-s.height-12)),t.dom.tooltip.style("left",o+"px").style("top",h+"px")}var Ld=300;function fy(t,e){var r=e||t.currentLayers||[],i=t,s=["text","yearMon"],o=s.indexOf(t.options.xAxisFormat)>-1?function(J){return J}:d3.format(t.options.xAxisFormat||""),h=d3.format(t.options.yAxisFormat||""),g=t.newScaleY?d3.format(t.newScaleY):h;Cd(t),r.forEach(function(J){["bar","point","hexbin","histogram","calendarHeatmap"].indexOf(J.type)>-1&&v(J)}),r.some(function(J){return J.type==="groupedBar"})&&t.chart.selectAll(".tag-grouped-bar-g rect").on("mouseout",K).on("mouseover",Y).on("mousemove",Y).on("touchstart",function(J){J.preventDefault(),Y.call(this,J)}).on("touchmove",function(J){J.preventDefault(),Y.call(this,J)}).on("touchend",K),r.length>0&&r.every(function(J){return["line","area"].indexOf(J.type)>-1})&&uy(t,ee,oe),r.some(function(J){return J.type==="donut"})&&se(".donut","donut",function(J,k){return{title:{text:k.mapping.x_var+": "+J.data[k.mapping.x_var]},items:[{color:t.colorDiscrete(J.index),label:k.mapping.y_var,value:J.data[k.mapping.y_var]}]}}),r.some(function(J){return J.type==="treemap"})&&t.chart.selectAll(".root").on("mouseout",q).on("mouseover",re).on("mousemove",re).on("touchstart",function(J){J.preventDefault(),re.call(this,J)}).on("touchmove",function(J){J.preventDefault(),re.call(this,J)}).on("touchend",q);function v(J){var k=fl(J),de=k.getHoverSelector?k.getHoverSelector(t,J):"."+xr(J.type,t.element.id,J.label);t.chart.selectAll(de).on("mouseout",function(){_.call(this,J)}).on("mouseover",function(ze){x.call(this,ze,J)}).on("mousemove",function(ze){x.call(this,ze,J)}).on("touchstart",function(ze){ze.preventDefault(),x.call(this,ze,J)}).on("touchmove",function(ze){ze.preventDefault(),x.call(this,ze,J)}).on("touchend",function(){_.call(this,J)})}function x(J,k){var de=d3.select(this).data()[0],ze=fl(k),er=A(k,ze,de,this);HTMLWidgets.shinyMode&&Shiny.onInputChange("myIO-"+i.element.id+"-rollover",JSON.stringify(de)),O(this,k,de),_2(i,{pointer:ue(J),title:er.title,items:er.items});var Er=k.type==="hexbin"?i.xScale?i.xScale.invert(de.x):null:k.type==="histogram"?de.x0:k.type==="calendarHeatmap"?de.date instanceof Date?de.date:new Date(de[k.mapping.date]+"T00:00:00Z"):de[k.mapping.x_var];N0(i,de,Er,er)}function _(J){I(this,J),ku(i),D0(i)}function A(J,k,de,ze){if(J.type==="hexbin"){var er=d3.format(",.2f");return{title:{text:"x: "+er(i.xScale.invert(de.x))+", y: "+er(i.yScale.invert(de.y))},items:[{color:d3.select(ze).attr("fill"),label:"Count",value:de.length}]}}if(J.type==="histogram")return{title:{text:"Bin: "+de.x0+" to "+de.x1},items:[{color:d3.select(ze).attr("fill"),label:"Count",value:de.length}]};if(J.type==="calendarHeatmap"){var Er=k.formatTooltip(i,de,J);return{title:{text:typeof Er.title=="string"?Er.title:Er.title.text},items:[{color:Er.color||d3.select(ze).attr("fill"),label:Er.label||J.label,value:Er.value}]}}var Ht=J.mapping.x_var+": "+o(de[J.mapping.x_var]),xn=i.newY?i.newY:J.mapping.y_var,$r=J.type==="point"||J.type==="bar"?J.mapping.y_var:J.label,Tn=Vs(i,J.label,J.color);if(k&&typeof k.formatTooltip=="function"){var In=k.formatTooltip(i,de,J);Ht=In.title||Ht,$r=In.label||$r,Tn=In.color||Tn}return{title:{text:Ht},items:[{color:Tn,label:$r,value:g(de[xn])}]}}function O(J,k){var de=d3.select(J),ze=k.type==="hexbin"?"#333":de.attr("fill")||de.style("fill")||Vs(i,k.label,k.color);if(k.type==="hexbin"){de.style("stroke",ze).style("stroke-width","2px");return}de.interrupt().style("stroke",ze).style("stroke-width","2px").style("stroke-opacity",.8),k.type==="point"&&de.attr("r",Math.max(+de.attr("r")||0,6))}function I(J,k){var de=d3.select(J);de.interrupt().transition().duration(Ld).style("stroke-width","0px").style("stroke","transparent").style("stroke-opacity",null),k.type==="point"&&de.transition().duration(Ld).attr("r",y2(i))}function Y(J){var k=d3.select(this).data()[0],de=r[k.idx],ze=Vs(i,de.label,de.color);HTMLWidgets.shinyMode&&Shiny.onInputChange("myIO-"+i.element.id+"-rollover",JSON.stringify(k.data.values)),d3.select(this).interrupt().style("stroke",ze).style("stroke-width","2px").style("stroke-opacity",.8);var er={title:{text:de.mapping.x_var+": "+o(k.data[0])},items:[{color:ze,label:de.mapping.y_var,value:g(k[1]-k[0])}]};_2(i,{pointer:ue(J),title:er.title,items:er.items}),N0(i,k.data,k.data[0],er)}function K(){d3.select(this).interrupt().transition().duration(Ld).style("stroke-width","0px").style("stroke","transparent").style("stroke-opacity",null),ku(i),D0(i)}function ee(J){var k=d3.pointer(J,this),de=i.xScale.invert(k[0]),ze=[],er=d3.bisector(function($r){return+$r[0]}).left;if(r.forEach(function($r){var Tn=$r.data,In=$r.mapping.x_var,cr=i.newY?i.newY:$r.mapping.y_var||$r.mapping.high_y,bn=Tn.map(function(hi){return hi[In]}),mn=er(bn,de),qn=Tn[mn-1],Wt=Tn[mn],Pr=qn?Wt&&de-qn[In]>Wt[In]-de?Wt:qn:Wt;Pr&&ze.push({color:$r.color,label:$r.label,xVar:In,yVar:cr,displayValue:Pr.density!=null?Pr.density:Pr[cr],value:Pr})}),ze.length===0){oe();return}HTMLWidgets.shinyMode&&Shiny.onInputChange("myIO-"+i.element.id+"-rollover",JSON.stringify(ze.map(function($r){return $r.value})));var Er=ze[0].value[ze[0].xVar];i.toolLine.style("stroke","var(--chart-ref-line-color)").style("stroke-width","1px").style("stroke-dasharray","4,4").attr("x1",i.xScale(Er)).attr("x2",i.xScale(Er)).attr("y1",0).attr("y2",i.height-(i.margin.top+i.margin.bottom));var Ht=i.toolPointLayer.selectAll("circle").data(ze);Ht.exit().remove(),Ht.enter().append("circle").attr("r",4).merge(Ht).attr("cx",function($r){return i.xScale($r.value[$r.xVar])}).attr("cy",function($r){return i.yScale($r.value[$r.yVar])}).attr("fill","#ffffff").attr("stroke",function($r){return $r.color}).attr("stroke-width",2);var xn={title:{text:ze[0].xVar+": "+o(Er)},items:ze.map(function($r){return{color:$r.color,label:$r.label,value:g($r.displayValue)}})};_2(i,{pointer:ue(J),title:xn.title,items:xn.items}),N0(i,ze[0].value,Er,xn)}function oe(){i.toolLine&&i.toolLine.style("stroke","none"),i.toolPointLayer&&i.toolPointLayer.selectAll("*").remove(),ku(i),D0(i)}function se(J,k,de){var ze=r.filter(function(er){return er.type===k})[0];t.chart.selectAll(J).on("mouseout",function(){t.chart.selectAll(J).transition().duration(Ld).style("opacity",1),ku(i)}).on("mouseover",function(er,Er){t.chart.selectAll(J).style("opacity",.4),d3.select(this).style("opacity",.85);var Ht=de(Er,ze);_2(i,{pointer:ue(er),title:Ht.title,items:Ht.items})}).on("mousemove",function(er,Er){var Ht=de(Er,ze);_2(i,{pointer:ue(er),title:Ht.title,items:Ht.items})}).on("touchstart",function(er,Er){er.preventDefault(),t.chart.selectAll(J).style("opacity",.4),d3.select(this).style("opacity",.85);var Ht=de(Er,ze);_2(i,{pointer:ue(er),title:Ht.title,items:Ht.items})}).on("touchend",function(){t.chart.selectAll(J).transition().duration(Ld).style("opacity",1),ku(i)})}function re(J,k){for(var de=r.filter(function(er){return er.type==="treemap"})[0],ze=k;ze.depth>1;)ze=ze.parent;t.chart.selectAll(".root").style("opacity",.4),d3.select(this).style("opacity",.85),_2(i,{pointer:ue(J),title:{text:de.mapping.level_1+": "+k.data[de.mapping.level_1]},items:[{color:t.colorDiscrete(ze.data.id),label:k.data[de.mapping.level_2],value:k.value}]})}function q(){t.chart.selectAll(".root").transition().duration(Ld).style("opacity",1),ku(i)}function ue(J){return d3.pointer(J,i.dom.element)}}var ax=.05,ox=.15;function hy(t,e){var r=t.margin,i=n1(t),s=[];e.forEach(function(v){var x=d3.extent(v.data,function(_){return+_[v.mapping.value]});s.push(x)});var o=d3.min(s,function(v){return v[0]}),h=d3.max(s,function(v){return v[1]}),g=d3.scaleLinear().domain([o,h]).nice().range([0,t.width-(r.left+r.right)]);e.forEach(function(v){var x=v.data.map(function(_){return _[v.mapping.value]});v.bins=d3.bin().domain(g.domain()).thresholds(g.ticks(v.mapping.bins))(x),v.max_value=d3.max(v.bins,function(_){return _.length})}),t.derived.xScale=g,t.derived.yScale=d3.scaleLinear().domain([0,d3.max(e,function(v){return v.max_value})]).nice().range([i-(r.top+r.bottom),0])}function py(t,e,r){var i=t.margin,s=[],o=[],h=[],g=[],v=r||{},x=v.xExtentFields||["x_var"],_=v.yExtentFields||["y_var"],A=e.filter(function(k){var de=k.scaleHints;return!(de&&Array.isArray(de.xExtentFields)&&de.xExtentFields.length===0&&Array.isArray(de.yExtentFields)&&de.yExtentFields.length===0)});A.forEach(function(k){var de=k.scaleHints&&Array.isArray(k.scaleHints.xExtentFields)?k.scaleHints.xExtentFields:x,ze=[];de.forEach(function(Tn){var In=k.mapping[Tn]||Tn,cr=k.data.map(function(bn){return+bn[In]});ze=ze.concat(cr)});var er=d3.extent(ze.length>0?ze:[0]),Er=k.scaleHints&&Array.isArray(k.scaleHints.yExtentFields)?k.scaleHints.yExtentFields:_,Ht=[];Er.forEach(function(Tn){var In=k.mapping[Tn]||Tn,cr=k.data.map(function(bn){return+bn[In]});Ht=Ht.concat(cr)});var xn=d3.extent(Ht.length>0?Ht:[0],function(Tn){return Tn});s.push(er),o.push([xn[0],xn[1]]);var $r=k.mapping.x_var;h.push(k.data.map(function(Tn){return Tn[$r]})),g.push(k.data.map(function(Tn){var In=k.mapping.y_var||"y_var";return Tn[In]}))});var O=d3.min(s,function(k){return k[0]}),I=d3.max(s,function(k){return k[1]}),Y=d3.min(s,function(k){return k[0]}),K=d3.max(s,function(k){return k[1]});t.derived.xCheck=Y===0&&K===0,O==I&&(O=O-1,I=I+1);var ee=Math.max(Math.abs(I-O)*ax,.5),oe=[t.config.scales.xlim.min?+t.config.scales.xlim.min:O-ee,t.config.scales.xlim.max?+t.config.scales.xlim.max:I+ee];t.derived.xBanded=[].concat.apply([],h).map(function(k){try{return Array.isArray(k)?k[0]:k}catch{return}}).filter(dy);var se=d3.min(o,function(k){return k[0]}),re=d3.max(o,function(k){return k[1]});se==re&&(se=se-1,re=re+1);var q=Math.abs(re-se)*ox,ue=[t.config.scales.ylim.min?+t.config.scales.ylim.min:se-q,t.config.scales.ylim.max?+t.config.scales.ylim.max:re+q];t.derived.yBanded=[].concat.apply([],g).map(function(k){try{return Array.isArray(k)?k[0]:k}catch{return}}).filter(dy);var J=n1(t);v.xScaleType==="band"?t.derived.xScale=d3.scaleBand().range([0,t.width-(i.left+i.right)]).domain(t.config.scales.flipAxis===!0?t.derived.yBanded:t.derived.xBanded):t.derived.xScale=d3.scaleLinear().range([0,t.width-(i.right+i.left)]).domain(t.config.scales.flipAxis===!0?ue:oe),v.yScaleType==="band"?t.derived.yScale=d3.scaleBand().range([J-(i.top+i.bottom),0]).domain(t.config.scales.flipAxis===!0?t.derived.xBanded:t.derived.yBanded):t.derived.yScale=d3.scaleLinear().range([J-(i.top+i.bottom),0]).domain(t.config.scales.flipAxis===!0?oe:ue),t.config.scales.colorScheme&&t.config.scales.colorScheme.enabled&&(t.derived.colorDiscrete=d3.scaleOrdinal().range(t.config.scales.colorScheme.colors).domain(t.config.scales.colorScheme.domain),t.derived.colorContinuous=d3.scaleLinear().range(t.config.scales.colorScheme.colors).domain(t.config.scales.colorScheme.domain)),t.syncLegacyAliases()}function dy(t,e,r){return r.indexOf(t)===e}var kh={xScaleType:"linear",yScaleType:"linear",xExtentFields:["x_var"],yExtentFields:["y_var"],domainMerge:"union"};function my(t){return t?Object.assign({},kh,t):null}function lx(t){if(t&&t.scaleHints)return my(t.scaleHints);try{var e=fl(t);return my(e.constructor.scaleHints)}catch{return null}}function R0(t,e){var r=t&&t.config&&t.config.scales&&t.config.scales.categoricalScale;return r&&r[e+"Axis"]===!0?"band":"linear"}function gy(t,e){var r=!!(t&&t.config&&t.config.scales&&t.config.scales.flipAxis),i=new Set,s=new Set,o=new Set,h=new Set,g="union";if((e||[]).forEach(function(v){var x=lx(v),_=R0(t,"x"),A=R0(t,"y"),O=x?x.xScaleType:_,I=x?x.yScaleType:A,Y=r?I:O,K=r?O:I;r||(_==="band"&&(Y="band"),A==="band"&&(K="band")),i.add(Y),s.add(K);var ee=x&&Array.isArray(x.xExtentFields)?x.xExtentFields:kh.xExtentFields;ee.forEach(function(se){o.add(se)});var oe=x&&Array.isArray(x.yExtentFields)?x.yExtentFields:kh.yExtentFields;oe.forEach(function(se){h.add(se)}),x&&x.domainMerge==="independent"&&(g="independent")}),i.size>1||s.size>1)throw new Error("Mismatched scaleTypes across layers: x="+Array.from(i).join(", ")+", y="+Array.from(s).join(", ")+".");return{xScaleType:i.size>0?Array.from(i)[0]:R0(t,"x"),yScaleType:s.size>0?Array.from(s)[0]:R0(t,"y"),xExtentFields:Array.from(o).length>0?Array.from(o):kh.xExtentFields,yExtentFields:Array.from(h).length>0?Array.from(h):kh.yExtentFields,domainMerge:g}}function Nd(t){var e=t.derived.currentLayers||[],r=e.map(function(o){return fl(o).constructor.traits}),i=e[0]?e[0].type:null,s=Array.from(new Set(r.map(function(o){return o.legendType})));return{type:i,axesChart:r.some(function(o){return o.hasAxes}),histogram:r.length>0&&r.every(function(o){return o.binning}),continuousLegend:s.length===1&&s[0]==="continuous",ordinalLegend:s.length===1&&s[0]==="ordinal",referenceLines:r.some(function(o){return o.referenceLines})}}function Dd(t,e){if(e.axesChart)if(e.histogram)hy(t,t.derived.currentLayers);else{var r=gy(t,t.derived.currentLayers);py(t,t.derived.currentLayers,r)}}var cx={line:"axes-continuous",point:"axes-continuous",area:"axes-continuous",bar:"axes-categorical",groupedBar:"axes-categorical",boxplot:"axes-categorical",violin:"axes-categorical",histogram:"axes-binned",heatmap:"axes-matrix",candlestick:"axes-continuous",waterfall:"axes-categorical",ridgeline:"axes-binned",rangeBar:"axes-continuous",sankey:"standalone-flow",hexbin:"axes-hex",treemap:"standalone-treemap",donut:"standalone-donut",gauge:"standalone-gauge",text:"axes-continuous",regression:"axes-continuous",bracket:"axes-continuous",comparison:"axes-categorical",qq:"axes-continuous",lollipop:"axes-categorical",dumbbell:"axes-categorical",waffle:"standalone-waffle",beeswarm:"axes-continuous",bump:"axes-continuous",survfit:"axes-continuous",histogram_fit:"axes-binned",quantile_dots:"axes-categorical",radar:"standalone-radar",funnel:"standalone-funnel",parallel:"standalone-parallel",calendarHeatmap:"standalone-calendar",fan:"axes-continuous"},ux=new Set(["axes-continuous:axes-categorical","axes-categorical:axes-continuous","axes-binned:axes-continuous","axes-continuous:axes-binned"]);function fx(t){if(t.length<=1)return{valid:!0,errors:[]};let e=[],r=t.map(function(o){return cx[o.type]||"unknown"}),i=r.filter(function(o){return o.startsWith("standalone")});i.length>0&&t.length>1&&e.push("Cannot mix standalone chart types with other layers."),i.length>1&&e.push("Standalone chart types must be used alone.");let s=Array.from(new Set(r));return s.length>1&&s.forEach(function(o,h){s.slice(h+1).forEach(function(g){ux.has(o+":"+g)||e.push("Cannot mix layer groups '"+o+"' and '"+g+"'.")})}),{valid:e.length===0,errors:e}}function dx(t,e){let r=[],i=[];return e?(Object.entries(e).forEach(function(s){let o=s[0],h=s[1],g=t.mapping?t.mapping[o]:null;if(h.required&&!g){r.push("Layer '"+t.label+"' is missing required mapping '"+o+"'.");return}if(!g)return;let v=Array.isArray(t.data)?typeof g=="string"?t.data.map(function(_){return _[g]}):t.data.map(function(){return g}):[];if(h.numeric&&v.find(function(A){return Number.isNaN(+A)})!==void 0&&r.push("Layer '"+t.label+"' field '"+g+"' must be numeric."),h.positive&&v.find(function(A){return+A<=0})!==void 0&&r.push("Layer '"+t.label+"' field '"+g+"' must be positive."),h.sorted){for(let _=1;_0&&i.push("Layer '"+t.label+"' field '"+g+"' contains "+x+" null/NaN values.")}),{errors:r,warnings:i}):{errors:r,warnings:i}}function k0(t){let e=t.derived.currentLayers||t.config.layers||[],r=fx(e);return r.valid?e.filter(function(i){let o=fl(i).constructor.dataContract,h=dx(i,o);return h.warnings.forEach(function(g){console.warn("[myIO]",g)}),h.errors.length>0?(h.errors.forEach(function(g){console.warn("[myIO] Layer '"+i.label+"' removed:",g),t.emit("error",{message:g,layer:i})}),!1):!0}):(r.errors.forEach(function(i){console.warn("[myIO] Composition error:",i),t.emit("error",{message:i})}),[])}function M0(t,e){e.referenceLines&&hx(t)}function hx(t){var e=t.margin,r=t.options.transition.speed,i=[t.options.referenceLine.x],s=[t.options.referenceLine.y];if(t.options.referenceLine.x){var o=t.plot.selectAll(".ref-x-line").data(i);o.exit().transition().duration(100).style("opacity",0).attr("y2",t.height-(e.top+e.bottom)).remove();var h=o.enter().append("line").attr("class","ref-x-line").attr("fill","none").style("stroke","gray").style("stroke-width",3).attr("x1",function(x){return t.xScale(x)}).attr("x2",function(x){return t.xScale(x)}).attr("y1",t.height-(e.top+e.bottom)).attr("y2",t.height-(e.top+e.bottom)).transition().ease(d3.easeQuad).duration(r).attr("y2",0);o.merge(h).transition().ease(d3.easeQuad).duration(r).attr("x1",function(x){return t.xScale(x)}).attr("x2",function(x){return t.xScale(x)}).attr("y1",t.height-(e.top+e.bottom)).attr("y2",0)}else t.plot.selectAll(".ref-x-line").remove();if(t.options.referenceLine.y){var g=t.plot.selectAll(".ref-y-line").data(s);g.exit().transition().duration(100).attr("y2",t.width-(e.left+e.right)).style("opacity",0).remove();var v=g.enter().append("line").attr("class","ref-y-line").attr("fill","none").style("stroke","gray").style("stroke-width",3).attr("x1",0).attr("x2",0).attr("y1",function(x){return t.yScale(x)}).attr("y2",function(x){return t.yScale(x)}).transition().ease(d3.easeQuad).duration(r).attr("x2",t.width-(e.left+e.right));g.merge(v).transition().ease(d3.easeQuad).duration(r).attr("x1",0).attr("x2",t.width-(e.left+e.right)).attr("y1",function(x){return t.yScale(x)}).attr("y2",function(x){return t.yScale(x)})}else t.plot.selectAll(".ref-y-line").remove()}function yy(t,e,r){let i=t.map(function(O){return O[r]}),s=t.map(function(O){return O[e]}),o={},h=s.length,g=0,v=0,x=0,_=0,A=0;for(let O=0;O0)return s.length}var o=r?r.clientWidth:this.controller.chart.runtime.totalWidth;return Math.max(Math.floor(o/(this.controller.config.minWidth||200)),1)}hasPanelData(){for(var e=0;e0)return!0;return!1}addLabel(){d3.select(this.element).append("div").attr("class","myIO-facet-label").text(this.facetValue)}renderPanel(){var e=this.buildPanelChart(),r=Nd(e);r.axesChart&&(Dd(e,r),this.applySharedDomains(e)),g0(e),e.dom.svg=e.svg,e.dom.plot=e.plot,e.dom.chartArea=e.chart,r.axesChart&&this.requiresClipPath(r.type)&&(this.setClipPath(e),b0(e,r,{isInitialRender:!0}),this.applyAxisSuppression(e),M0(e,r,{isInitialRender:!0})),this.renderLayers(e,this.layers),this.panelChart=e}buildPanelChart(){var e=this.controller.chart,r=Math.max(this.element.clientWidth||this.controller.config.minWidth||200,1),i=this.buildMargin(),s=Object.assign({},e.config,{layers:this.layers}),o={margin:i,suppressLegend:!0,suppressAxis:{xAxis:this.suppressX,yAxis:this.suppressY},xlim:s.scales.xlim,ylim:s.scales.ylim,categoricalScale:s.scales.categoricalScale,flipAxis:s.scales.flipAxis,colorScheme:s.scales.colorScheme?s.scales.colorScheme.enabled?[s.scales.colorScheme.colors,s.scales.colorScheme.domain,"on"]:[s.scales.colorScheme.colors,s.scales.colorScheme.domain,"off"]:null,xAxisFormat:s.axes.xAxisFormat,yAxisFormat:s.axes.yAxisFormat,toolTipFormat:s.axes.toolTipFormat,xTickLabels:s.axes.xTickLabels,xAxisLabel:s.axes.xAxisLabel,yAxisLabel:s.axes.yAxisLabel,dragPoints:!1,toggleY:null,toolTipOptions:s.interactions.toolTipOptions,transition:{speed:0},referenceLine:s.referenceLines};return{element:this.element,dom:{element:this.element},config:s,derived:{currentLayers:this.layers.slice()},runtime:{totalWidth:r,width:r,height:Mh,layout:e.runtime.layout,activeY:e.runtime.activeY,activeYFormat:e.runtime.activeYFormat},options:o,margin:i,width:r,height:Mh,totalWidth:r,layout:e.runtime.layout,newY:e.runtime.activeY,newScaleY:e.runtime.activeYFormat,plotLayers:this.layers,emit:function(){},dragPoints:function(){},updateRegression:function(){},syncLegacyAliases:function(){this.xScale=this.derived?this.derived.xScale:null,this.yScale=this.derived?this.derived.yScale:null,this.colorDiscrete=this.derived?this.derived.colorDiscrete:null,this.colorContinuous=this.derived?this.derived.colorContinuous:null,this.x_banded=this.derived?this.derived.xBanded:null,this.y_banded=this.derived?this.derived.yBanded:null,this.x_check=this.derived?this.derived.xCheck:null,this.currentLayers=this.derived?this.derived.currentLayers:null},captureLegacyAliases:function(){}}}buildMargin(){var e=this.controller.chart.config.layout.margin||{},r={top:e.top!=null?e.top:30,right:e.right!=null?e.right:5,bottom:e.bottom!=null?e.bottom:60,left:e.left!=null?e.left:50};return this.suppressX&&(r.bottom=Math.min(r.bottom,12)),this.suppressY&&(r.left=Math.min(r.left,12)),r}applySharedDomains(e){var r=this.controller.globalScaleSnapshot;!r||!e.derived||!e.derived.xScale||!e.derived.yScale||(r.xDomain&&e.derived.xScale.domain(r.xDomain.slice()),r.yDomain&&e.derived.yScale.domain(r.yDomain.slice()),r.xBanded&&(e.derived.xBanded=r.xBanded.slice()),r.yBanded&&(e.derived.yBanded=r.yBanded.slice()),typeof r.xCheck<"u"&&(e.derived.xCheck=r.xCheck),r.colorDiscrete&&(e.derived.colorDiscrete=r.colorDiscrete),r.colorContinuous&&(e.derived.colorContinuous=r.colorContinuous),e.syncLegacyAliases())}requiresClipPath(e){return e!=="donut"&&e!=="gauge"}setClipPath(e){var r=e.height-(e.margin.top+e.margin.bottom);e.dom.clipPath=e.dom.chartArea.append("defs").append("svg:clipPath").attr("id",e.dom.element.id+"clip").append("svg:rect").attr("x",0).attr("y",0).attr("width",e.width-(e.margin.left+e.margin.right)).attr("height",r),e.dom.chartArea.attr("clip-path","url(#"+e.dom.element.id+"clip)"),e.clipPath=e.dom.clipPath}applyAxisSuppression(e){this.suppressX&&e.plot.selectAll(".x-axis").remove(),this.suppressY&&e.plot.selectAll(".y-axis").remove()}renderLayers(e,r){for(var i=0;i1?_+": ":"";e.push(O+x.below+" of "+A+" dots below threshold of "+i+".")})}}}),e}function xy(t){return String(t).replace(/[^a-zA-Z0-9_-]/g,"")}function bx(t,e){if(!t.dom||!t.dom.chartArea||!e)return null;for(var r=t.dom.chartArea,i=[".tag-"+e.type+"-"+e.id,".tag-"+e.type+"-"+t.dom.element.id+"-"+xy(e.label)],s=0;s0&&e.visibility!==!1})}destroy(){this.chart.dom.svg.on("keydown.a11y",null),this.liveRegion&&this.liveRegion.remove(),clearTimeout(this.debounceTimer)}};var j0=class{constructor(e){this.chart=e,this.tableContainer=null,this.visible=!1}initialize(){this.tableContainer=d3.select(this.chart.dom.element).append("div").attr("class","myIO-data-table myIO-sr-only").attr("role","region").attr("aria-label","Chart data table")}generate(){if(this.tableContainer){this.tableContainer.selectAll("*").remove();for(var e=this.chart.config.layers,r=500,i=new Map,s=[],o=0;or&&this.tableContainer.append("p").text("Showing first "+r+" of "+A.length+" rows")}}}renderFanTable(e,r){if(!(!e||e.length===0)){var i=e[0],s=i.mapping&&i.mapping.x_var?i.mapping.x_var:"x_var",o=new Map,h=[];e.forEach(function(I){var Y=I.options&&I.options.interval_pct;if(Y!=null){var K=_y(Y);h.push(+Y),(Array.isArray(I.data)?I.data:[]).forEach(function(ee){var oe=String(ee[s]);o.has(oe)||o.set(oe,{x_var:ee[s]});var se=o.get(oe);se["low_"+K]=ee[I.mapping.low_y],se["high_"+K]=ee[I.mapping.high_y]})}}),h=Array.from(new Set(h)).sort(function(I,Y){return I-Y});var g=["x_var"];h.forEach(function(I){var Y=_y(I);g.push("low_"+Y),g.push("high_"+Y)});var v=Array.from(o.values()),x=v.slice(0,r),_=this.tableContainer.append("table").attr("aria-label","Data for "+(i._composite||"fan")),A=_.append("thead").append("tr");g.forEach(function(I){A.append("th").attr("scope","col").text(I)});var O=_.append("tbody");x.forEach(function(I){var Y=O.append("tr");g.forEach(function(K){var ee=I[K];Y.append("td").text(ee!=null?String(ee):"")})}),v.length>r&&this.tableContainer.append("p").text("Showing first "+r+" of "+v.length+" rows")}}toggle(){this.visible=!this.visible,this.visible?(this.generate(),this.tableContainer.classed("myIO-sr-only",!1),this.chart.dom.svg.attr("aria-hidden","true")):(this.tableContainer.classed("myIO-sr-only",!0),this.chart.dom.svg.attr("aria-hidden",null))}destroy(){this.tableContainer&&this.tableContainer.remove()}};function _y(t){return String(t).replace(/\.0+$/,"").replace(/(\.\d*?)0+$/,"$1")}var d6=280,Sx=100,Ex={on(t,e){return this._listeners=this._listeners||{},this._listeners[t]=this._listeners[t]||[],this._listeners[t].push(e),this},off(t,e){return!this._listeners||!this._listeners[t]?this:(this._listeners[t]=e?this._listeners[t].filter(function(r){return r!==e}):[],this)},emit(t,e){return!this._listeners||!this._listeners[t]?this:(this._listeners[t].forEach(function(r){r(e)}),this)}},q0=class{constructor(e){Object.assign(this,Ex),this._listeners={},this.config=e.config,this.dom={element:e.element},this.derived={},this.runtime={renderGen:0,resizeTimer:null,width:Math.max(e.width,d6),height:e.height,totalWidth:Math.max(e.width,d6),layout:"grouped",activeY:null,activeYFormat:null,tooltipHideTimer:null},this.config.sparkline&&this.applySparklineOverrides(),window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches&&(this.config.transitions.speed=0),this.runtime.width=this.runtime.totalWidth,this.syncLegacyAliases(),this.draw()}syncLegacyAliases(){this.element=this.dom?this.dom.element:null,this.svg=this.dom?this.dom.svg:null,this.plot=this.dom?this.dom.plot:null,this.chart=this.dom?this.dom.chartArea:null,this.legendArea=this.dom?this.dom.legendArea:null,this.clipPath=this.dom?this.dom.clipPath:null,this.tooltip=this.dom?this.dom.tooltip:null,this.toolTipTitle=this.dom?this.dom.tooltipTitle:null,this.toolTipBody=this.dom?this.dom.tooltipBody:null,this.plotLayers=this.config?this.config.layers:null,this.options=this.config?{margin:this.config.layout.margin,suppressLegend:this.config.layout.suppressLegend,suppressAxis:this.config.layout.suppressAxis,xlim:this.config.scales.xlim,ylim:this.config.scales.ylim,categoricalScale:this.config.scales.categoricalScale,flipAxis:this.config.scales.flipAxis,colorScheme:this.config.scales.colorScheme?this.config.scales.colorScheme.enabled?[this.config.scales.colorScheme.colors,this.config.scales.colorScheme.domain,"on"]:[this.config.scales.colorScheme.colors,this.config.scales.colorScheme.domain,"off"]:null,xAxisFormat:this.config.axes.xAxisFormat,yAxisFormat:this.config.axes.yAxisFormat,toolTipFormat:this.config.axes.toolTipFormat,xTickLabels:this.config.axes.xTickLabels,xAxisLabel:this.config.axes.xAxisLabel,yAxisLabel:this.config.axes.yAxisLabel,dragPoints:this.config.interactions.dragPoints,toggleY:this.config.interactions.toggleY&&this.config.interactions.toggleY.variable?[this.config.interactions.toggleY.variable,this.config.interactions.toggleY.format]:null,toolTipOptions:this.config.interactions.toolTipOptions,transition:this.config.transitions,referenceLine:this.config.referenceLines}:null,this.margin=this.config?this.config.layout.margin:null,this.width=this.runtime?this.runtime.width:null,this.height=this.runtime?this.runtime.height:null,this.totalWidth=this.runtime?this.runtime.totalWidth:null,this.layout=this.runtime?this.runtime.layout:null,this.newY=this.runtime?this.runtime.activeY:null,this.newScaleY=this.runtime?this.runtime.activeYFormat:null,this.toolLine=this.runtime?this.runtime.toolLine:null,this.toolTipBox=this.runtime?this.runtime.toolTipBox:null,this.toolPointLayer=this.runtime?this.runtime.toolPointLayer:null,this.xScale=this.derived?this.derived.xScale:null,this.yScale=this.derived?this.derived.yScale:null,this.colorDiscrete=this.derived?this.derived.colorDiscrete:null,this.colorContinuous=this.derived?this.derived.colorContinuous:null,this.x_banded=this.derived?this.derived.xBanded:null,this.y_banded=this.derived?this.derived.yBanded:null,this.x_check=this.derived?this.derived.xCheck:null,this.currentLayers=this.derived?this.derived.currentLayers:null,this.layerIndex=this.derived?this.derived.layerIndex:null}captureLegacyAliases(){!this.dom||!this.runtime||!this.derived||(this.dom.svg=this.svg||this.dom.svg,this.dom.plot=this.plot||this.dom.plot,this.dom.chartArea=this.chart||this.dom.chartArea,this.dom.legendArea=this.legendArea||this.dom.legendArea,this.dom.clipPath=this.clipPath||this.dom.clipPath,this.dom.tooltip=this.tooltip||this.dom.tooltip,this.dom.tooltipTitle=this.toolTipTitle||this.dom.tooltipTitle,this.dom.tooltipBody=this.toolTipBody||this.dom.tooltipBody,this.runtime.layout=this.layout||this.runtime.layout,this.runtime.activeY=this.newY||this.runtime.activeY,this.runtime.activeYFormat=this.newScaleY||this.runtime.activeYFormat,this.runtime.toolLine=this.toolLine||this.runtime.toolLine,this.runtime.toolTipBox=this.toolTipBox||this.runtime.toolTipBox,this.runtime.toolPointLayer=this.toolPointLayer||this.runtime.toolPointLayer,this.derived.xScale=this.xScale||this.derived.xScale,this.derived.yScale=this.yScale||this.derived.yScale,this.derived.colorDiscrete=this.colorDiscrete||this.derived.colorDiscrete,this.derived.colorContinuous=this.colorContinuous||this.derived.colorContinuous,this.derived.xBanded=this.x_banded||this.derived.xBanded,this.derived.yBanded=this.y_banded||this.derived.yBanded,this.derived.xCheck=this.x_check||this.derived.xCheck,this.derived.currentLayers=this.currentLayers||this.derived.currentLayers,this.derived.layerIndex=this.layerIndex||this.derived.layerIndex,this.syncLegacyAliases())}draw(){g0(this),this.captureLegacyAliases(),this.initialize()}initialize(){this.derived.currentLayers=this.config.layers,this.syncLegacyAliases(),this.themeManager=new B0(this.dom.element,this.config),this.themeManager.initialize(),cy(this),this.config.sparkline||(this.keyboardNav=new G0(this),this.keyboardNav.initialize(),this.dataTable=new j0(this),this.dataTable.initialize(),V0(this)),this.captureLegacyAliases(),this.derived.currentLayers.length>0&&this.setClipPath(this.derived.currentLayers[0].type),this.renderCurrentLayers({isInitialRender:!0})}applySparklineOverrides(){this.config.layout.margin={top:1,right:1,bottom:1,left:1},this.config.layout.suppressLegend=!0,this.config.layout.suppressAxis={xAxis:!0,yAxis:!0},this.config.interactions.brush&&(this.config.interactions.brush.enabled=!1),this.config.interactions.annotation&&(this.config.interactions.annotation.enabled=!1),this.config.interactions.linked&&(this.config.interactions.linked.enabled=!1),this.config.interactions.sliders=[],this.config.interactions.dragPoints=!1,this.config.referenceLines={x:null,y:null},this.dom.element.dataset.sparkline="true"}renderCurrentLayers(e){let r=e||{},i=++this.runtime.renderGen,s=()=>this.runtime&&this.runtime.renderGen===i;if(this.config.facet&&this.config.facet.enabled){this.facetController||(this.facetController=new $0(this)),this.facetController.initialize();return}else this.facetController&&(this.facetController.destroy(),this.facetController=null);try{if(this.dom.chartArea){this.dom.chartArea.selectAll("*").interrupt();var o=this.derived.currentLayers.map(function(x){return x.label}),h=this.config.layers.map(function(x){return x.label}),g=this.dom.chartArea;h.forEach(function(x){if(o.indexOf(x)===-1){var _=String(x).replace(/\s+/g,"");g.selectAll("[class*='tag-'][class*='-"+_+"']").remove()}})}if(this.emit("beforeRender",{options:r}),y0(this),this.derived.currentLayers=k0(this),this.syncLegacyAliases(),this.clearEmptyState(),!s())return;if(this.derived.currentLayers.length===0){this.renderEmptyState(),this.config.sparkline||V0(this);return}let v=Nd(this);if(Dd(this,v),this.syncLegacyAliases(),!s())return;e6(this),this.emit("afterScales",{state:v}),b0(this,v,r),this.routeLayers(this.derived.currentLayers),M0(this,v,r),Vg(this,v),fy(this),C0(this),this.config.interactions.brush&&this.config.interactions.brush.enabled&&Yg(this),this.config.interactions.annotation&&this.config.interactions.annotation.enabled&&Qg(this),this.config.interactions.linked&&this.config.interactions.linked.enabled&&sy(this),this.config.interactions.linked&&this.config.interactions.linked.cursor===!0&&ty(this),this.config.interactions.sliders&&this.config.interactions.sliders.length>0&&oy(this),this.emit("afterRender",{state:v}),this.config.sparkline||V0(this)}catch(v){throw console.warn("[myIO] Render error:",v.message),this.emit("error",{message:v.message,error:v}),v}}clearEmptyState(){this.dom&&this.dom.svg&&this.dom.svg.selectAll(".myIO-empty-state").remove(),this.dom&&this.dom.element&&d3.select(this.dom.element).select(".myIO-fab").style("display",null)}renderEmptyState(){this.dom.chartArea&&this.dom.chartArea.selectAll("*").interrupt().remove(),this.dom.plot&&(this.dom.plot.selectAll(".x-axis, .y-axis").interrupt().remove(),this.dom.plot.selectAll(".ref-x-line, .ref-y-line").remove()),Cd(this),ku(this),this.runtime&&this.runtime._sheetOpen&&Ru(this,{returnFocus:!1}),this.dom.element&&d3.select(this.dom.element).select(".myIO-fab").style("display","none"),this.dom.svg&&(this.dom.svg.selectAll(".myIO-empty-state").remove(),this.dom.svg.append("text").attr("class","myIO-empty-state").attr("x",this.runtime.totalWidth/2).attr("y",this.runtime.height/2).text("No data to display"))}addButtons(){e6(this)}toggleVarY(e){this.runtime.activeY=e[0],this.runtime.activeYFormat=e[1],this.syncLegacyAliases(),this.renderCurrentLayers()}toggleGroupedLayout(e){var r=S0(e,this),i=e.map(function(o){return o.color}),s=(this.runtime.width-(this.config.layout.margin.right+this.config.layout.margin.left))/(r[0].length+1)/i.length;this.runtime.layout==="stacked"?(x0(this,r,i,s),this.runtime.layout="grouped"):(_0(this,r,i,s),this.runtime.layout="stacked"),this.syncLegacyAliases()}setClipPath(e){switch(e){case"donut":case"gauge":break;default:var r=n1(this);this.dom.clipPath=this.dom.chartArea.append("defs").append("svg:clipPath").attr("id",this.dom.element.id+"clip").append("svg:rect").attr("x",0).attr("y",0).attr("width",this.runtime.width-(this.config.layout.margin.left+this.config.layout.margin.right)).attr("height",r-(this.config.layout.margin.top+this.config.layout.margin.bottom)),this.dom.chartArea.attr("clip-path","url(#"+this.dom.element.id+"clip)"),this.syncLegacyAliases()}}routeLayers(e){var r=this;this.derived.layerIndex=this.config.layers.map(function(i){return i.label}),this.syncLegacyAliases(),e.forEach(function(i){var s=fl(i);if(s&&typeof s.render=="function"){s.render(r,i,e),r.captureLegacyAliases();var o=i.options&&i.options.opacity!=null?i.options.opacity:1;if(o<1){var h=String(i.label).replace(/\s+/g,"");r.dom.chartArea.selectAll("[class*='tag-'][class*='-"+h+"']").style("opacity",o)}}})}removeLayers(e){e.forEach(r=>{zg().forEach(function(i){typeof i.remove=="function"?i.remove(this,{label:r}):["line","bar","point","regression-line","hexbin","area","crosshairY","crosshairX"].forEach(function(s){d3.selectAll("."+xr(s,this.dom.element.id,r)).transition().duration(500).style("opacity",0).remove()},this)},this)})}dragPoints(e){Hg(this,e)}updateOrdinalColorLegend(e){od(this,e)}updateRegression(e,r){let i=(this.config.layers||[]).find(function(s){return s.label===r&&s.type==="point"});i&&(this.config.layers||[]).forEach(function(s){if(s.type!=="line"||s.transform!=="lm"||!s.mapping||!i.mapping||s.mapping.x_var!==i.mapping.x_var||s.mapping.y_var!==i.mapping.y_var)return;let o=yy(i.data,i.mapping.y_var,i.mapping.x_var),h=i.data.map(function(g){return{...g,[s.mapping.y_var]:o.fn(g[s.mapping.x_var])}}).sort(function(g,v){return g[s.mapping.x_var]-v[s.mapping.x_var]});s.data=h,t6("line").render(this,{...s,color:e||s.color},this.config.layers)},this)}updateChart(e){let r=this.derived.layerIndex||[];this.config=e,this.derived.currentLayers=this.config.layers,this.syncLegacyAliases();let i=this.config.layers.map(function(o){return o.label}),s=r.filter(function(o){return!i.includes(o)});this.removeLayers(s),this.renderCurrentLayers()}updateData(e){if(!Array.isArray(e)||!this.config||!Array.isArray(this.config.layers))return;let r=Object.create(null);this.config.layers.forEach(function(i){r[i.label]=i}),e.forEach(function(i){i&&Object.prototype.hasOwnProperty.call(r,i.label)&&Array.isArray(i.data)&&(r[i.label].data=i.data)}),this.syncLegacyAliases(),this.renderCurrentLayers()}resize(e,r){if(!e||!r||e<2||r<2)return;let i=this.runtime&&this.runtime._sheetOpen===!0;i&&Ru(this,{returnFocus:!1}),this.runtime.totalWidth=Math.max(e,d6),this.runtime.width=this.runtime.totalWidth,this.runtime.height=r,this.syncLegacyAliases(),clearTimeout(this.runtime.resizeTimer),this.runtime.resizeTimer=setTimeout(()=>{gg(this),this.captureLegacyAliases(),this.renderCurrentLayers(),i&&this.derived&&this.derived.currentLayers&&this.derived.currentLayers.length>0&&A0(this),this.emit("resize",{width:this.runtime.width,height:this.runtime.height})},Sx)}destroy(){this.emit("destroy",{}),clearTimeout(this.runtime&&this.runtime.resizeTimer),clearTimeout(this.runtime&&this.runtime.tooltipHideTimer),this.facetController&&(this.facetController.destroy(),this.facetController=null),this.keyboardNav&&this.keyboardNav.destroy(),this.dataTable&&this.dataTable.destroy(),this.themeManager&&this.themeManager.destroy(),this.runtime&&this.runtime._sheetOpen&&Ru(this,{returnFocus:!1}),clearTimeout(this.runtime&&this.runtime._sheetCloseTimer),C0(this),Zg(this),o6(this),l6(this),this.dom&&this.dom.element&&d3.select(this.dom.element).on("keydown.brush",null),this.dom&&this.dom.chartArea&&this.dom.chartArea.selectAll("*").interrupt(),this.dom&&this.dom.svg&&this.dom.svg.remove(),this.dom&&this.dom.tooltip&&this.dom.tooltip.remove(),this.dom&&this.dom.element&&d3.select(this.dom.element).selectAll(".myIO-fab, .myIO-panel, .myIO-sheet-backdrop").remove(),Cd(this),this._listeners={},this.config=null,this.derived=null,this.dom=null,this.runtime=null}};var z0=class{constructor({max:e=128}={}){this.max=e,this.lru=new Map,this.inflight=new Map}get(e){if(!this.lru.has(e))return;let r=this.lru.get(e);return this.lru.delete(e),this.lru.set(e,r),r}set(e,r){for(this.lru.has(e)&&this.lru.delete(e),this.lru.set(e,r);this.lru.size>this.max;){let i=this.lru.keys().next().value;this.lru.delete(i)}}delete(e){this.lru.delete(e)}clear(){this.lru.clear(),this.inflight.clear()}size(){return this.lru.size}inflightOrStore(e,r){if(this.inflight.has(e))return this.inflight.get(e);let i=r();return this.inflight.set(e,i),i}resolveInflight(e,r){this.set(e,r),this.inflight.delete(e)}rejectInflight(e){this.inflight.delete(e)}};var H0=class{constructor(){this.sources=new Map}register(e){if(!e||typeof e.sourceId!="string")throw new Error("SourceRegistry.register: entry must have sourceId");e.mode!=="none"&&this.sources.set(e.sourceId,e)}unregister(e){this.sources.delete(e)}get(e){return this.sources.get(e)}has(e){return this.sources.has(e)}all(){return Array.from(this.sources.values())}clear(){this.sources.clear()}};var W0=class{constructor(e={}){}async init(e={}){}async cancel(e){}async close(){}async applyPredicateCache(e,r){}async*query({queryId:e}){yield{__trailer:!0,queryId:e,rowCount:0,elapsedMs:0}}};function Y0(t){if(typeof Uint8Array.fromBase64=="function")return Uint8Array.fromBase64(t);let e=atob(t),r=e.length,i=new Uint8Array(r);for(let s=0;s(Kb(),Jb)),Promise.resolve().then(()=>m0(Qb()))]),s=i.default||i;for(let o of e.all()){if(o.mode!=="inline_ipc"||!o.ipcB64)continue;let h=Y0(o.ipcB64),g=r.tableFromIPC(h),v=g.toArray().map(x=>Object.assign({},x));s.tables[o.sourceId]={data:v},this.sources.set(o.sourceId,{table:g,rows:v})}this._alasql=s}async*query({sql:e,params:r=[],queryId:i,signal:s}){if(this._closed)throw Object.assign(new Error("engine-gone"),{queryId:i,code:"engine-gone"});if(s&&s.aborted)throw Object.assign(new Error("cancelled"),{queryId:i,code:"cancelled"});let o=Date.now(),h;try{h=this._alasql.exec(e,r)}catch(g){throw Object.assign(new Error(g.message||String(g)),{queryId:i,code:"syntax"})}yield{rows:h,queryId:i},yield{__trailer:!0,queryId:i,rowCount:Array.isArray(h)?h.length:0,elapsedMs:Date.now()-o}}async cancel(e){}async applyPredicateCache(e,r){}async close(){if(this._alasql)for(let e of this.sources.keys())delete this._alasql.tables[e];this.sources.clear(),this._closed=!0}};var vm=class{constructor(e={}){this.config=e,this.pending=new Map,this.batchWindow=e&&e.shiny_batch_window||4,this._handlersRegistered=!1}async init({sourceRegistry:e}={}){if(typeof Shiny>"u")throw Object.assign(new Error("Shiny is not available in this context"),{code:"engine-gone"});if(this._handlersRegistered)return;let r=o=>this._route("batch",o),i=o=>this._route("end",o),s=o=>this._route("error",o);Shiny.addCustomMessageHandler("myio:batch",r),Shiny.addCustomMessageHandler("myio:end",i),Shiny.addCustomMessageHandler("myio:error",s),this._handlersRegistered=!0}_route(e,r){let i=this.pending.get(r.queryId);i&&(e==="batch"?(i.push(r),Shiny.setInputValue("myio_ack",{v:1,queryId:r.queryId,seq:r.seq},{priority:"event"})):e==="end"?(i.push({__trailer:!0,queryId:r.queryId,rowCount:r.rowCount,elapsedMs:r.elapsedMs}),i.end()):e==="error"&&i.error(Object.assign(new Error(r.message||"engine error"),{queryId:r.queryId,code:r.code||"engine-gone"})))}query({sql:e,params:r=[],queryId:i,signal:s,templateId:o,sourceId:h,bindings:g,predicateHash:v,limit:x}){if(typeof Shiny>"u")throw Object.assign(new Error("Shiny not available"),{queryId:i,code:"engine-gone"});let _=[],A=[],O=!1,I=null,Y=re=>{A.length?A.shift()({value:re,done:!1}):_.push(re)},K=()=>{for(O=!0;A.length;)A.shift()({value:void 0,done:!0})},ee=re=>{for(I=re;A.length;)A.shift()({value:void 0,done:!0})};this.pending.set(i,{push:Y,end:K,error:ee,seqBudget:this.batchWindow});let oe=null;s&&(oe=()=>{Shiny.setInputValue("myio_cancel",{v:1,queryId:i},{priority:"event"}),ee(Object.assign(new Error("cancelled"),{queryId:i,code:"cancelled"}))},s.aborted?oe():s.addEventListener("abort",oe)),I||Shiny.setInputValue("myio_query",{v:1,queryId:i,templateId:o||null,sourceId:h||null,predicateHash:v||null,bindings:g||{},limit:x||null,_debugSql:e},{priority:"event"});let se=this.pending;return(async function*(){try{for(;;){if(I)throw I;if(_.length){yield _.shift();continue}if(O)return;let re=await new Promise(q=>A.push(q));if(re.done){if(I)throw I;return}yield re.value}}finally{s&&oe&&s.removeEventListener("abort",oe),se.delete(i)}})()}async cancel(e){typeof Shiny<"u"&&Shiny.setInputValue("myio_cancel",{v:1,queryId:e},{priority:"event"});let r=this.pending.get(e);r&&r.error(Object.assign(new Error("cancelled"),{queryId:e,code:"cancelled"}))}async applyPredicateCache(e,r){}async close(){for(let[,e]of this.pending)e.error(Object.assign(new Error("engine closed"),{code:"engine-gone"}));this.pending.clear()}};var xm=class{constructor(e={}){this.config=e,this.cacheUrl=e.duckdb_wasm&&e.duckdb_wasm.cache_url||null,this.workerUrl=e.duckdb_wasm&&e.duckdb_wasm.worker_url||null,this.db=null,this.conn=null,this._duckdb=null,this._closed=!1}async init({sourceRegistry:e}={}){if(this._closed)throw Object.assign(new Error("engine-gone"),{code:"engine-gone"});if(!this.cacheUrl||!this.workerUrl)throw Object.assign(new Error("WasmEngineAdapter: duckdb_wasm cache_url / worker_url not set. Ensure myIO::install_duckdb_wasm() has run."),{code:"engine-gone"});let r=this.cacheUrl.replace(/\/?$/,"/")+"duckdb-browser.mjs",i;try{i=await import(r)}catch(g){throw Object.assign(new Error("WasmEngineAdapter: failed to import duckdb-wasm loader from "+r+": "+(g?.message||g)),{code:"engine-gone"})}this._duckdb=i;let s=new Worker(this.workerUrl),o=this.cacheUrl.replace(/\/?$/,"/")+"duckdb-mvp.wasm",h=new i.ConsoleLogger;if(this.db=new i.AsyncDuckDB(h,s),await this.db.instantiate(o),this.conn=await this.db.connect(),e)for(let g of e.all())await this._registerSource(g)}async _registerSource(e){if(!this._duckdb)return;let r=this._duckdb.DuckDBDataProtocol;if(e.mode==="inline_ipc"&&e.ipcB64){let i=Y0(e.ipcB64),s=e.sourceId+".arrow";await this.db.registerFileBuffer(s,i),await this.conn.query('CREATE OR REPLACE VIEW "'+e.sourceId.replace(/"/g,'""')+`" AS SELECT * FROM read_arrow('`+s+"');")}else if(e.mode==="url"&&e.url){let i=e.sourceId+(/\.parquet$/i.test(e.url)?".parquet":/\.arrow$/i.test(e.url)?".arrow":/\.feather$/i.test(e.url)?".feather":".csv");await this.db.registerFileURL(i,e.url,r.HTTP,!1);let s=/\.parquet$/i.test(e.url)?"read_parquet":/\.arrow$/i.test(e.url)||/\.feather$/i.test(e.url)?"read_arrow":"read_csv_auto";await this.conn.query('CREATE OR REPLACE VIEW "'+e.sourceId.replace(/"/g,'""')+'" AS SELECT * FROM '+s+"('"+i+"');")}}async*query({sql:e,params:r=[],queryId:i,signal:s}){if(this._closed)throw Object.assign(new Error("engine-gone"),{queryId:i,code:"engine-gone"});if(s&&s.aborted)throw Object.assign(new Error("cancelled"),{queryId:i,code:"cancelled"});let o=Date.now(),h,g=null;try{h=await this.conn.send(e)}catch(x){throw Object.assign(new Error(x?.message||String(x)),{queryId:i,code:"syntax"})}s&&(g=()=>{this.conn&&this.conn.cancelSent().catch(()=>{})},s.addEventListener("abort",g));let v=0;try{for(;;){if(s&&s.aborted){try{await this.conn.cancelSent()}catch{}throw Object.assign(new Error("cancelled"),{queryId:i,code:"cancelled"})}let{done:x,value:_}=await h.next();if(x)break;_&&(v+=_.numRows||0,yield{batch:_,queryId:i})}}finally{s&&g&&s.removeEventListener("abort",g);try{await h.return()}catch{}}yield{__trailer:!0,queryId:i,rowCount:v,elapsedMs:Date.now()-o}}async cancel(e){if(this.conn)try{await this.conn.cancelSent()}catch{}}async applyPredicateCache(e,r){}async close(){if(this._closed=!0,this.conn){try{await this.conn.close()}catch{}this.conn=null}if(this.db){try{await this.db.terminate()}catch{}this.db=null}}};function _m(t,e={}){switch(t){case"svg":return new W0(e);case"memory":return new bm(e);case"wasm":return new xm(e);case"server":return new vm(e);default:throw new Error("createEngine: unknown engine '"+t+"'")}}var Fp=class{constructor({config:e}){this.config=e||{},this.cache=new z0({max:128}),this.sourceRegistry=new H0,this.charts=new Map,this.selectionStore=new Map,this.adapters=new Map,this._adapterInits=new Map,this._inflightControllers=new Map,this._debouncers=new Map}ensureAdapterFor(e,r,i){if(this.adapters.has(e))return Promise.resolve(this.adapters.get(e));if(this._adapterInits.has(e))return this._adapterInits.get(e);let s=_m(r,i),o=s.init({sourceRegistry:this.sourceRegistry}).then(()=>(this.adapters.set(e,s),this._adapterInits.delete(e),s)).catch(h=>{throw this._adapterInits.delete(e),h});return this._adapterInits.set(e,o),o}registerSource(e){this.sourceRegistry.register(e)}register({chartId:e,queryTemplate:r,markSpec:i,sourceHandle:s,predicateFn:o,onResult:h}){this.charts.set(e,{chartId:e,queryTemplate:r,markSpec:i,sourceHandle:s,predicateFn:o,currentPredicate:null,onResult:h}),this.selectionStore.has(s.sourceId)||this.selectionStore.set(s.sourceId,new Map),r&&String(r).trim()&&h&&setTimeout(()=>this._dispatch(e,{preview:!1}),0)}unregister(e){let r=this.charts.get(e);if(!r)return;this.charts.delete(e);let i=this._inflightControllers.get(e);i&&(i.abort(),this._inflightControllers.delete(e));let s=r.sourceHandle.sourceId,o=this.selectionStore.get(s);o&&o.delete(e);let h=this._debouncers.get(e);if(h&&(h.preview&&clearTimeout(h.preview),h.final&&clearTimeout(h.final),this._debouncers.delete(e)),[...this.charts.values()].filter(v=>v.sourceHandle.sourceId===s).length===0){let v=this.adapters.get(s);v&&(v.close().catch(()=>{}),this.adapters.delete(s)),this._adapterInits.delete(s),this.selectionStore.delete(s)}}setSelection({chartId:e,predicate:r}){let i=this.charts.get(e);if(!i)return;let s=i.sourceHandle.sourceId,o=this.selectionStore.get(s);o||(o=new Map,this.selectionStore.set(s,o)),r==null?o.delete(e):o.set(e,r),i.currentPredicate=r;for(let h of this.charts.values())h.chartId!==e&&h.sourceHandle.sourceId===s&&this._scheduleDispatch(h.chartId);if(this._subscribers){let h=this._subscribers.get(i.sourceHandle.sourceId);if(h)for(let g of h)try{g({chartId:e,predicate:r})}catch(v){console.error("[myIO coordinator] subscriber error:",v)}}}subscribe(e,r){return this._subscribers||(this._subscribers=new Map),this._subscribers.has(e)||this._subscribers.set(e,new Set),this._subscribers.get(e).add(r),()=>{let i=this._subscribers.get(e);i&&i.delete(r)}}_scheduleDispatch(e){let r=this._debouncers.get(e);r||(r={preview:null,final:null},this._debouncers.set(e,r)),r.preview&&clearTimeout(r.preview),r.final&&clearTimeout(r.final),r.preview=setTimeout(()=>this._dispatch(e,{preview:!0}),50),r.final=setTimeout(()=>this._dispatch(e,{preview:!1}),200)}async _dispatch(e,{preview:r=!1}={}){let i=this.charts.get(e);if(!i||!i.onResult||!i.queryTemplate||!String(i.queryTemplate).trim())return;let s=i.sourceHandle.sourceId,o=this._composeOthersPredicate(e,s),h=this._substituteTemplate(i.queryTemplate,{where:o,limit:r?1e3:1e5}),g=await this._hash(o),v=i.sourceHandle.engine||this.config.engine,x=await this._hash(h+""+g+""+v),_=this.cache.get(x);if(_){this._deliverToRenderer(e,_);return}let A=this.adapters.get(s);try{if(!A&&v&&(A=await this.ensureAdapterFor(s,v,this.config)),!this.charts.has(e)||!A)return;typeof A.applyPredicateCache=="function"&&await A.applyPredicateCache(g,o)}catch(K){if(!this.charts.has(e))return;console.error("[myIO coordinator]",e,K?.code,K?.message||K),this._deliverToRenderer(e,{batches:[],trailer:{error:K?.message||String(K),code:K?.code||"engine_error"}});return}let O="q_"+Math.random().toString(36).slice(2,10),I=null;if(!this.cache.inflight.has(x)){let K=this._inflightControllers.get(e);K&&K.abort(),I=new AbortController,this._inflightControllers.set(e,I)}let Y=this.cache.inflightOrStore(x,()=>(async()=>{let K=[],ee=null;for await(let oe of A.query({sql:h,params:[],queryId:O,sourceId:s,limit:r?1e3:1e5,signal:I.signal}))oe.__trailer?ee=oe:K.push(oe);return{batches:K,trailer:ee}})());try{let K=await Y,ee=this._inflightControllers.get(e);if(I&&ee===I&&this._inflightControllers.delete(e),I&&I.signal.aborted){this.cache.rejectInflight(x);return}if(this.cache.resolveInflight(x,K),!this.charts.has(e))return;this._deliverToRenderer(e,K)}catch(K){this.cache.rejectInflight(x);let ee=this._inflightControllers.get(e);if(I&&ee===I&&this._inflightControllers.delete(e),I&&I.signal.aborted)return;console.error("[myIO coordinator]",e,K?.code,K?.message||K),this._deliverToRenderer(e,{batches:[],trailer:{error:K?.message||String(K),code:K?.code||"query_error"}})}}_composeOthersPredicate(e,r){let s=[...(this.selectionStore.get(r)||new Map).entries()].filter(([o])=>o!==e).map(([,o])=>o).filter(Boolean);return s.length?"("+s.join(") AND (")+")":"TRUE"}_substituteTemplate(e,{where:r,limit:i}){return e.replace(/\{\{\s*where\s*\}\}/g,r).replace(/\{\{\s*limit\s*\}\}/g,String(i)).replace(/\$where\b/g,r).replace(/\$limit\b/g,String(i))}async _hash(e){if(typeof crypto<"u"&&crypto.subtle){let i=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-1",i);return Array.from(new Uint8Array(s,0,8)).map(o=>o.toString(16).padStart(2,"0")).join("")}let r=2166136261;for(let i=0;i>>0).toString(16).padStart(8,"0")}_deliverToRenderer(e,{batches:r,trailer:i}){let s=this.charts.get(e);if(!(!s||!s.onResult))try{s.onResult({batches:r,trailer:i,markSpec:s.markSpec})}catch(o){console.error("[myIO coordinator] renderer error for",e,o)}}onChartResult(e,r){let i=this.charts.get(e);i&&(i.onResult=r)}async close(){for(let e of this._debouncers.values())e.preview&&clearTimeout(e.preview),e.final&&clearTimeout(e.final);for(let[,e]of this.adapters)await e.close().catch(()=>{});this.adapters.clear();for(let e of this._inflightControllers.values())e.abort();this._adapterInits.clear(),this._inflightControllers.clear(),this.charts.clear(),this.selectionStore.clear(),this.sourceRegistry.clear(),this.cache.clear(),this._debouncers.clear()}};function Zb(t){return globalThis.__myioCoordinator||(globalThis.__myioCoordinator=new Fp({config:t})),globalThis.__myioCoordinator}var VS=new Set(["scatter","line","area"]),GS=150;function $p(t){let e=Number(t);return Number.isFinite(e)?e:null}function jS(t){if(t==="Inf"||t==="Infinity"||t===1/0)return 1/0;let e=Number(t);return Number.isFinite(e)&&e>0?e:5e4}function A8({markSpec:t,rowCount:e,threshold:r}){let i=t&&t.kind;if(!VS.has(i))return!1;let s=jS(r);if(!Number.isFinite(s))return!1;let o=Number(e);return Number.isFinite(o)&&o>=s}function qS(t,e){let r={};return["x","y","category","color","value","baseline"].forEach(i=>{let s=t.getChild?t.getChild(i):null;s&&(r[i]=s.get(e))}),r}function ev(t){if(!t)return[];if(typeof t.toArray=="function")return t.toArray().map(e=>Object.assign({},e));if(typeof t.getChild=="function"){let e=t.getChild("x"),r=t.numRows||t.length||(e?e.length:0),i=new Array(r);for(let s=0;s{r&&(Array.isArray(r)?e.push(...r):Array.isArray(r.rows)?e.push(...r.rows):r.batch?e.push(...ev(r.batch)):(typeof r.getChild=="function"||typeof r.toArray=="function")&&e.push(...ev(r)))}),e.map(r=>({...r,x:$p(r.x),y:$p(r.y),category:r.category==null?void 0:$p(r.category),color:r.color==null?void 0:r.color,value:r.value==null?void 0:$p(r.value),baseline:r.baseline==null?void 0:$p(r.baseline)})).filter(r=>r.x!=null&&r.y!=null)}function zS(t){let e=t.margin||t.config&&t.config.layout&&t.config.layout.margin||{top:0,right:0,bottom:0,left:0},r=Math.max(0,(t.width||t.runtime?.width||0)-e.left-e.right),i=Math.max(0,(t.height||t.runtime?.height||0)-e.top-e.bottom);return{left:e.left,top:e.top,width:r,height:i}}function HS(t){let e=t.dom?.element||t.element,r=t.dom?.svg?.node?t.dom.svg.node():e.querySelector("svg"),i=document.createElement("div");i.className="myIO-webgl-overlay",i.style.position="absolute",i.style.pointerEvents="none",i.style.overflow="hidden",i.style.zIndex="0";let s=document.createElement("div");return s.className="myIO-webgl-loading",s.textContent="Loading data...",s.style.position="absolute",s.style.left="50%",s.style.top="50%",s.style.transform="translate(-50%, -50%)",s.style.font="12px sans-serif",s.style.color="#666",s.style.background="rgba(255,255,255,0.85)",s.style.padding="6px 8px",s.style.border="1px solid rgba(0,0,0,0.12)",i.appendChild(s),r&&r.parentNode===e?e.insertBefore(i,r):e.appendChild(i),w8(t,i),i}function w8(t,e){let r=zS(t);return e.style.left=r.left+"px",e.style.top=r.top+"px",e.style.width=r.width+"px",e.style.height=r.height+"px",r}function Pp(t,e,r){t&&typeof t.emit=="function"&&t.emit(e,r)}function WS(t,e,r){let i=t.querySelector(".myIO-webgl-loading,.myIO-webgl-empty");if(!r){i&&i.remove();return}let s=i||document.createElement("div");s.className=e,s.textContent=r,s.style.position="absolute",s.style.left="50%",s.style.top="50%",s.style.transform="translate(-50%, -50%)",s.style.font="12px sans-serif",s.style.color="#666",s.style.background="rgba(255,255,255,0.85)",s.style.padding="6px 8px",s.style.border="1px solid rgba(0,0,0,0.12)",s.parentNode||t.appendChild(s)}function YS(t,e){return t.map(r=>{if(r.category!=null||r.color==null)return r;let i=String(r.color);return e.has(i)||e.set(i,e.size),{...r,category:e.get(i)}})}function XS(t,e){let r=t.xScale,i=t.yScale;if(typeof r!="function"||typeof i!="function")return null;let s=globalThis.window&&window.d3;return s&&typeof s.quadtree=="function"?s.quadtree().x(o=>o.__px).y(o=>o.__py).addAll(e.map(o=>({row:o,__px:r(o.x),__py:i(o.y)}))):e.map(o=>({row:o,__px:r(o.x),__py:i(o.y)}))}function JS(t,e,r){if(!t)return null;if(typeof t.find=="function")return t.find(e,r,16)?.row||null;let i=null,s=1/0;return t.forEach(o=>{let h=Math.hypot(o.__px-e,o.__py-r);h{s=!1,i||h();let x=r.getBoundingClientRect(),_=JS(i,o.clientX-x.left,o.clientY-x.top);_&&Pp(t,"rollover",{data:_,source:"webgl-bridge"})}))}return r.addEventListener("mousemove",g),{rebuild:h,destroy(){r.removeEventListener("mousemove",g)}}}function T8({chart:t,coordinator:e,chartId:r,markSpec:i,createRenderer:s,layerIndex:o=0}){let h=HS(t),g=Em({chart:t,layerIndex:o}),v=s||globalThis.window&&window.myIO&&window.myIO.webglRenderers&&window.myIO.webglRenderers.createWebGLRenderer,x=new Map,_=null,A=[],O=null,I=!1,Y=!1,K=null,ee=KS(t,()=>A);function oe(de,ze){if(!(Y||I)){if(Y=!0,console.warn("[myIO webgl bridge] falling back to SVG:",de,ze||""),_&&typeof _.destroy=="function")try{_.destroy()}catch{}_=null,h.remove(),O&&g.onResult(O)}}function se(){if(_||I||Y)return _;if(typeof v!="function")return oe("renderer unavailable"),null;let de=w8(t,h);try{_=v({kind:i.kind,el:h,width:de.width,height:de.height,xScale:t.xScale,yScale:t.yScale})}catch(er){return oe("renderer creation failed",er),null}let ze=h.querySelector("canvas");if(!_)return oe("renderer unavailable"),null;if(ze){let er=null;try{er=ze.getContext("webgl2")||ze.getContext("webgl")}catch{er=null}if(!er)return oe("WebGL context unavailable"),null;ze.addEventListener("webglcontextlost",Er=>{Er.preventDefault(),oe("WebGL context lost")},{once:!0})}return _}function re(de){let ze=de&&de.trailer,er=ze&&(ze.error||ze.message);return er?(_&&typeof _.update=="function"&&Promise.resolve(_.update([])).catch(()=>{}),Pp(t,"error",{message:String(er),trailer:ze,chartId:r}),!0):!1}function q(de){if(I)return;if(O=de,Y){g.onResult(de);return}if(re(de))return;A=YS(Sm(de&&de.batches),x),ee.rebuild();let ze=se();!ze||typeof ze.update!="function"||(WS(h,A.length?null:"myIO-webgl-empty",A.length?"":"No data in selection"),A.length||Pp(t,"emptySelection",{chartId:r}),Promise.resolve(ze.update(A)).catch(er=>{oe("render failed",er)}))}function ue(){if(I||Y)return;let de=w8(t,h);_&&typeof _.resize=="function"&&_.resize(de.width,de.height),_&&typeof _.update=="function"&&Promise.resolve(_.update(A)).catch(ze=>{oe("resize render failed",ze)})}function J(){I||(K&&clearTimeout(K),K=setTimeout(ue,GS))}function k(){I||(I=!0,K&&clearTimeout(K),e&&typeof e.onChartResult=="function"&&e.onChartResult(r,null),ee.destroy(),g.destroy(),_&&typeof _.destroy=="function"&&_.destroy(),h.remove())}return t&&typeof t.on=="function"&&(t.on("resize",J),t.on("destroy",k)),{onResult:q,resize:J,destroy:k,get pointCount(){return A.length},get overlay(){return Y?void 0:h},get fallbackActive(){return Y}}}function Em({chart:t,layerIndex:e=0}){let r=[],i=!1;function s(h){if(i)return;let g=h&&h.trailer,v=g&&(g.error||g.message);if(v){Pp(t,"error",{message:String(v),trailer:g});return}r=Sm(h&&h.batches),t.config&&t.config.layers&&t.config.layers[e]&&(t.config.layers[e].data=r),r.length||Pp(t,"emptySelection",{}),typeof t.renderCurrentLayers=="function"&&t.renderCurrentLayers()}function o(){i=!0}return t&&typeof t.on=="function"&&t.on("destroy",o),{onResult:s,destroy:o,get pointCount(){return r.length}}}function tv(t){return A8(t)?T8(t):t&&t.unifyDataPath?Em(t):null}var wm=class{constructor({coordinator:e,sourceId:r,group:i,rowkeyCol:s,threshold:o=1e5}){if(!e)throw new Error("CrosstalkAdapter: coordinator is required");if(!r)throw new Error("CrosstalkAdapter: sourceId is required");this.coordinator=e,this.sourceId=r,this.group=i||null,this.rowkeyCol=s||"__myio_rowkey__",this.threshold=Number(o)||1e5,this._selectionHandle=null,this._filterHandle=null,this._suppressedOnce=!1,this._badgeEl=null,this._mode="row-level"}attach(e){if(this.group=e||this.group,!this.group||typeof window>"u"||!window.crosstalk)return;let r=window.crosstalk.SelectionHandle,i=window.crosstalk.FilterHandle;r&&(this._selectionHandle=new r(this.group),this._selectionHandle.on("change",s=>this._onIncoming(s)),i&&(this._filterHandle=new i(this.group),this._filterHandle.on("change",s=>this._onIncoming(s))))}setBadge(e){this._badgeEl=e,this._renderBadge()}_renderBadge(){this._badgeEl&&(this._badgeEl.textContent="linked: "+this._mode)}_onIncoming(e){let r=e&&(e.value||e.keys)||null;if(!r||!Array.isArray(r)||r.length===0){this.coordinator.setSelection({chartId:"__crosstalk__:"+this.sourceId,predicate:null});return}let i=r.map(h=>h==null?"NULL":"'"+String(h).replace(/'/g,"''")+"'"),o='"'+this.rowkeyCol.replace(/"/g,'""')+'"'+" IN ("+i.join(",")+")";this.coordinator.setSelection({chartId:"__crosstalk__:"+this.sourceId,predicate:o})}async broadcast({predicate:e}){if(!this._selectionHandle)return;if(e==null){try{this._selectionHandle.set(null)}catch{}return}let r=this._countSql(e),i=this.coordinator.adapters&&this.coordinator.adapters.get(this.sourceId);if(!i)return;let s=0;try{for await(let h of i.query({sql:r,params:[],queryId:"__xcount__"+Date.now()})){if(!h||h.__trailer)continue;let g=h.rows||h.batch&&h.batch.toArray&&h.batch.toArray()||[];g[0]&&(s=Number(g[0].n??g[0][0]??g[0]["count(*)"]??0))}}catch(h){console.warn("[myIO crosstalk] count query failed:",h?.message||h);return}if(s>this.threshold){this._suppressedOnce||(console.info("myIO: selection above crosstalk_threshold ("+s+" > "+this.threshold+"); downstream row-indexed widgets will not react to this selection. myIO-to-myIO linking still works."),this._suppressedOnce=!0),this._mode="predicate-only",this._renderBadge();return}let o=await this._fetchKeys(e);if(o&&o.length>0)try{this._selectionHandle.set(o)}catch{}this._mode="row-level",this._renderBadge()}_countSql(e){return"SELECT count(*) AS n FROM "+('"'+this.sourceId.replace(/"/g,'""')+'"')+" WHERE "+e}async _fetchKeys(e){let r=this.coordinator.adapters&&this.coordinator.adapters.get(this.sourceId);if(!r)return[];let i='"'+this.sourceId.replace(/"/g,'""')+'"',o="SELECT "+('"'+this.rowkeyCol.replace(/"/g,'""')+'"')+" AS rowkey FROM "+i+" WHERE "+e,h=[];try{for await(let g of r.query({sql:o,params:[],queryId:"__xkeys__"+Date.now()})){if(!g||g.__trailer)continue;let v=g.rows||g.batch&&g.batch.toArray&&g.batch.toArray()||[];for(let x of v){let _=x&&(x.rowkey??x[0]);_!=null&&h.push(String(_))}}}catch(g){console.warn("[myIO crosstalk] key fetch failed:",g?.message||g)}return h}destroy(){try{this._selectionHandle&&this._selectionHandle.close()}catch{}try{this._filterHandle&&this._filterHandle.close()}catch{}this._selectionHandle=null,this._filterHandle=null}};var fh=class{constructor({el:e,width:r,height:i,xScale:s,yScale:o,palette:h,captureHoverEvents:g=!1}){this.el=e,this.width=r,this.height=i,this.xScale=s,this.yScale=o,this.captureHoverEvents=g!==!1,this.palette=h||["#440154","#414487","#2a788e","#22a884","#7ad151","#fde725"],this._scatterplot=null,this._destroyed=!1}_scaleCopy(e){return e&&typeof e.copy=="function"?e.copy():e}async _ensure(){if(this._scatterplot)return this._scatterplot;let e=await Promise.resolve().then(()=>(Yv(),Wv)),r=e.default||e.createScatterplot,i=document.createElement("canvas");return i.width=this.width,i.height=this.height,i.style.position="absolute",i.style.top="0",i.style.left="0",i.style.pointerEvents=this.captureHoverEvents?"auto":"none",this.el.appendChild(i),this._scatterplot=r({canvas:i,width:this.width,height:this.height,pointSize:3,backgroundColor:[1,1,1,0],colorBy:"category",pointColor:this.palette,xScale:this._scaleCopy(this.xScale),yScale:this._scaleCopy(this.yScale)}),this._applyScales(),this._scatterplot}_applyScales(){!this._scatterplot||!this.xScale||!this.yScale||(typeof this._scatterplot.setXScale=="function"&&this._scatterplot.setXScale(this._scaleCopy(this.xScale)),typeof this._scatterplot.setYScale=="function"&&this._scatterplot.setYScale(this._scaleCopy(this.yScale)),typeof this._scatterplot.set=="function"&&(typeof this._scatterplot.setXScale!="function"||typeof this._scatterplot.setYScale!="function")&&this._scatterplot.set({xScale:this._scaleCopy(this.xScale),yScale:this._scaleCopy(this.yScale)}))}async update(e){if(this._destroyed)return;let r=await this._ensure();if(!e||e.length===0){r.clear();return}let i={x:new Float32Array(e.length),y:new Float32Array(e.length),category:new Float32Array(e.length),value:new Float32Array(e.length)};for(let s=0;sm0(Am())),r=e.default||e,i=document.createElement("canvas");i.width=this.width,i.height=this.height,i.style.position="absolute",i.style.top="0",i.style.left="0",i.style.pointerEvents="none",this.el.appendChild(i),this._regl=r({canvas:i,attributes:{antialias:!0,preserveDrawingBuffer:!1}}),this._drawLine=this._regl({vert:` precision mediump float; attribute vec2 position; uniform vec2 xDomain; @@ -759,7 +759,7 @@ void main() { precision mediump float; uniform vec4 color; void main() { gl_FragColor = color; } - `,attributes:{position:this._regl.prop("position")},uniforms:{xDomain:this._regl.prop("xDomain"),yDomain:this._regl.prop("yDomain"),color:this._regl.prop("color")},count:this._regl.prop("count"),primitive:"triangle strip"}),this._buffer=this._regl.buffer({type:"float32",usage:"dynamic",length:0})}async update(e){if(this._destroyed)return;if(await this._ensure(),!e||e.length===0){this._regl.clear({color:[0,0,0,0]});return}let r=new Float32Array(e.length*4);for(let o=0;o NULL); destroy() + // nulls config. + if (!chart.config) { + window.myIO.unregisterInstance(msg.id); + return; + } + if (typeof chart.updateData === "function") { + chart.updateData(msg.layers || []); + } + }); + window.myIO._proxyHandlerInstalled = true; + }; window.myIO.webglRenderers = { createWebGLRenderer, WebGLScatter, diff --git a/inst/myio-schema.json b/inst/myio-schema.json index d747f3d..64ae30b 100644 --- a/inst/myio-schema.json +++ b/inst/myio-schema.json @@ -1315,6 +1315,10 @@ "width", "height" ], + "myIOProxy": [ + "outputId", + "session" + ], "print.myIO_duckdb_wasm_status": [ "x", "..." @@ -1463,6 +1467,10 @@ "suppressLegend": [ "myIO", "suppressLegend" + ], + "updateMyIOData": [ + "proxy", + "..." ] } } diff --git a/man/myIOProxy.Rd b/man/myIOProxy.Rd new file mode 100644 index 0000000..a580114 --- /dev/null +++ b/man/myIOProxy.Rd @@ -0,0 +1,59 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/myIOProxy.R +\name{myIOProxy} +\alias{myIOProxy} +\alias{updateMyIOData} +\title{Update a myIO chart in place from the Shiny server} +\usage{ +myIOProxy(outputId, session = NULL) + +updateMyIOData(proxy, ...) +} +\arguments{ +\item{outputId}{The output id of the `myIOOutput()` whose chart to update.} + +\item{session}{The Shiny session object. Defaults to the current reactive +domain.} + +\item{proxy}{A `myIO_proxy` object from `myIOProxy()`.} + +\item{...}{One or more `label = data.frame` updates, where `label` is an +existing layer label and the data frame carries that layer's mapped columns.} +} +\value{ +`myIOProxy()` returns a `myIO_proxy` object; `updateMyIOData()` + returns the proxy invisibly. +} +\description{ +`myIOProxy()` creates a lightweight handle to an already-rendered myIO widget, +and `updateMyIOData()` swaps the data of one or more existing layers without +re-rendering the whole widget. Unlike re-executing `renderMyIO()` (which +destroys and recreates the chart on every reactive invalidation, dropping +brush/zoom/toggle state and flickering), a proxy update reuses the existing +data-join path: only the changed marks transition, and interaction state is +preserved. +} +\details{ +Layers are matched by their `label`. Unknown labels are ignored client-side. +The supplied data frame replaces the layer's data as-is (the identity data +path); statistical transforms attached at `addIoLayer()` time are not +re-applied, so pass already-transformed data for transformed layers. +} +\examples{ +\dontrun{ +library(shiny) +ui <- fluidPage(myIOOutput("chart"), actionButton("go", "Resample")) +server <- function(input, output, session) { + output$chart <- renderMyIO({ + myIO(data = data.frame(x = 1:50, y = rnorm(50))) |> + addIoLayer("line", label = "series", mapping = list(x_var = "x", y_var = "y")) + }) + observeEvent(input$go, { + myIOProxy("chart") |> + updateMyIOData(series = data.frame(x = 1:50, y = rnorm(50))) + }) +} +shinyApp(ui, server) +} + +} diff --git a/mcp/myio-schema.json b/mcp/myio-schema.json index d747f3d..64ae30b 100644 --- a/mcp/myio-schema.json +++ b/mcp/myio-schema.json @@ -1315,6 +1315,10 @@ "width", "height" ], + "myIOProxy": [ + "outputId", + "session" + ], "print.myIO_duckdb_wasm_status": [ "x", "..." @@ -1463,6 +1467,10 @@ "suppressLegend": [ "myIO", "suppressLegend" + ], + "updateMyIOData": [ + "proxy", + "..." ] } } diff --git a/tests/js/myio-proxy.test.js b/tests/js/myio-proxy.test.js new file mode 100644 index 0000000..40f2c01 --- /dev/null +++ b/tests/js/myio-proxy.test.js @@ -0,0 +1,116 @@ +import * as d3 from "d3"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { myIOchart } from "../../inst/htmlwidgets/myIO/src/Chart.js"; +import { registerBuiltInRenderers } from "../../inst/htmlwidgets/myIO/src/registry.js"; + +globalThis.d3 = d3; +globalThis.HTMLWidgets = { shinyMode: false }; + +function pointLayer(data) { + return { + id: "layer_001", type: "point", label: "pts", data: data, + mapping: { x_var: "x", y_var: "y" }, options: { barSize: "large" }, + transform: "identity", transformMeta: {}, encoding: {}, sourceKey: "_source_key", + derivedFrom: null, order: 1, visibility: true, color: "#4E79A7" + }; +} + +function makeChart(data) { + return new myIOchart({ + element: document.getElementById("chart"), + width: 600, height: 400, + config: { + specVersion: 1, layers: [pointLayer(data)], + layout: { margin: { top: 30, bottom: 60, left: 50, right: 5 }, suppressLegend: false, suppressAxis: { xAxis: false, yAxis: false } }, + scales: { xlim: { min: 0, max: 10 }, ylim: { min: 0, max: 100 }, categoricalScale: { xAxis: false, yAxis: false }, flipAxis: false, colorScheme: { colors: ["#4E79A7"], domain: ["none"], enabled: false } }, + axes: { xAxisFormat: "s", yAxisFormat: "s", xAxisLabel: null, yAxisLabel: null, toolTipFormat: "s" }, + interactions: { dragPoints: false, toggleY: { variable: null, format: null }, toolTipOptions: { suppressY: false } }, + theme: {}, transitions: { speed: 0 }, referenceLines: { x: null, y: null } + } + }); +} + +describe("Chart.updateData (myIOProxy partial update)", () => { + beforeEach(() => { + document.body.innerHTML = "
"; + registerBuiltInRenderers(); + }); + + // Real DOM re-render is asserted in Playwright (transition.spec.ts-style) since + // jsdom lacks SVG transform.baseVal for d3's axis-update interpolation. Here we + // pin the data-swap contract by spying on the re-render call. + test("swaps an existing layer's data and triggers a re-render (not a destroy)", () => { + const chart = makeChart([{ x: 1, y: 10 }, { x: 2, y: 20 }]); + chart.renderCurrentLayers = vi.fn(); + chart.updateData([{ label: "pts", data: [{ x: 1, y: 10 }, { x: 2, y: 20 }, { x: 3, y: 30 }] }]); + expect(chart.config.layers[0].data.length).toBe(3); + expect(chart.renderCurrentLayers).toHaveBeenCalledTimes(1); + }); + + test("ignores unknown labels and malformed input", () => { + const chart = makeChart([{ x: 1, y: 10 }]); + chart.renderCurrentLayers = vi.fn(); + expect(() => chart.updateData([{ label: "nope", data: [{ x: 9, y: 9 }] }])).not.toThrow(); + expect(chart.config.layers[0].data.length).toBe(1); + expect(() => chart.updateData(null)).not.toThrow(); + expect(() => chart.updateData([{ label: "pts", data: "bad" }])).not.toThrow(); + expect(chart.config.layers[0].data.length).toBe(1); + }); + + test("does not reset visibility (preserves legend-toggled subset)", () => { + const chart = makeChart([{ x: 1, y: 10 }]); + chart.renderCurrentLayers = vi.fn(); + // Simulate a legend toggle leaving an empty visible subset. + chart.derived.currentLayers = []; + chart.updateData([{ label: "pts", data: [{ x: 1, y: 10 }, { x: 2, y: 20 }] }]); + expect(chart.derived.currentLayers).toEqual([]); // not reset to all layers + expect(chart.config.layers[0].data.length).toBe(2); // data still swapped + }); + + test("does not pollute Object.prototype via a __proto__ label", () => { + const chart = makeChart([{ x: 1, y: 10 }]); + chart.renderCurrentLayers = vi.fn(); + chart.updateData([{ label: "__proto__", data: [{ x: 9, y: 9 }] }]); + expect(({}).data).toBeUndefined(); + expect(chart.config.layers[0].data.length).toBe(1); + }); +}); + +describe("proxy message handler wiring", () => { + test("installProxyHandler routes myio:proxy-update to the registered chart", async () => { + const handlers = {}; + window.Shiny = { + addCustomMessageHandler: (name, fn) => { handlers[name] = fn; } + }; + delete window.myIO; // fresh namespace for this test + vi.resetModules(); // force index.js top-level to re-run and re-populate window.myIO + await import("../../inst/htmlwidgets/myIO/src/index.js"); + + window.myIO.installProxyHandler(); + expect(typeof handlers["myio:proxy-update"]).toBe("function"); + + const fakeChart = { config: {}, updateData: vi.fn() }; + window.myIO.registerInstance("chartA", fakeChart); + + const payload = { id: "chartA", layers: [{ label: "pts", data: [{ x: 1, y: 2 }] }] }; + handlers["myio:proxy-update"](payload); + expect(fakeChart.updateData).toHaveBeenCalledWith(payload.layers); + + // unknown id is a no-op + expect(() => handlers["myio:proxy-update"]({ id: "missing", layers: [] })).not.toThrow(); + + // a __proto__ id must not resolve to Object.prototype + expect(() => handlers["myio:proxy-update"]({ id: "__proto__", layers: [] })).not.toThrow(); + + // a destroyed chart (config nulled) is lazily reaped, not called + const deadChart = { config: null, updateData: vi.fn() }; + window.myIO.registerInstance("chartDead", deadChart); + handlers["myio:proxy-update"]({ id: "chartDead", layers: [] }); + expect(deadChart.updateData).not.toHaveBeenCalled(); + expect(window.myIO._instances["chartDead"]).toBeUndefined(); + + // unregister removes it + window.myIO.unregisterInstance("chartA"); + expect(window.myIO._instances["chartA"]).toBeUndefined(); + }); +}); diff --git a/tests/playwright/fixtures/transition.html b/tests/playwright/fixtures/transition.html index 2a85e17..683949f 100644 --- a/tests/playwright/fixtures/transition.html +++ b/tests/playwright/fixtures/transition.html @@ -57,6 +57,11 @@ return circles.map(function (c) { return +c.getAttribute("cy"); }); }; + // myIOProxy partial-update path: swap layer "L" data in place (no destroy). + window.__proxyUpdate = function (rows) { + window.__chart.updateData([{ label: "L", data: rows }]); + }; + // Grouped/stacked bar path: guards that transitionGrouped/transitionStacked // (groupedBarHelpers.js) resolve their easingFor/staggerDelay imports — a // missing import there throws only when toggleGroupedLayout fires, which the diff --git a/tests/playwright/proxy.spec.ts b/tests/playwright/proxy.spec.ts new file mode 100644 index 0000000..0ae0caf --- /dev/null +++ b/tests/playwright/proxy.spec.ts @@ -0,0 +1,83 @@ +import { test, expect, type Page } from "@playwright/test"; +import { createServer, type Server } from "node:http"; +import { readFile } from "node:fs/promises"; +import { extname, join, normalize } from "node:path"; + +// B5 myIOProxy partial-update e2e against the PRODUCTION bundle. chart.updateData +// (the path the Shiny "myio:proxy-update" handler drives) must swap an existing +// layer's data and re-render IN PLACE — same element, no destroy — adding +// the new marks. Verified in Chromium (jsdom lacks SVG transform.baseVal for the +// d3 axis-update interpolation this exercises). + +let server: Server; +let baseUrl: string; + +test.beforeAll(async () => { + server = createServer(async (req, res) => { + const pathname = decodeURIComponent(new URL(req.url || "/", "http://localhost").pathname); + const relative = normalize(pathname).replace(/^(\.\.[/\\])+/, "").replace(/^[/\\]/, ""); + const filePath = join(process.cwd(), relative || "tests/playwright/fixtures/transition.html"); + try { + const body = await readFile(filePath); + const type = extname(filePath) === ".js" ? "text/javascript" : "text/html"; + res.writeHead(200, { "content-type": type }); + res.end(body); + } catch (_) { + res.writeHead(404); + res.end("not found"); + } + }); + await new Promise((resolve) => server.listen(0, resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("test server did not bind"); + baseUrl = `http://127.0.0.1:${address.port}`; +}); + +test.afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); +}); + +async function ready(page: Page) { + await page.goto(`${baseUrl}/tests/playwright/fixtures/transition.html`); + await page.waitForFunction(() => (window as any).__myioTestReady === true, null, { timeout: 10000 }); +} + +test("updateData swaps layer data in place and re-renders (same svg, no destroy)", async ({ page }) => { + const errors: string[] = []; + page.on("pageerror", (e) => errors.push(String(e))); + await ready(page); + + await page.evaluate(() => (window as any).__mount({ speed: 0 })); + expect(await page.locator("circle[class^='tag-point']").count()).toBe(2); + + // Capture the svg node identity to prove the chart was NOT destroyed/recreated. + const svgBefore = await page.evaluate(() => { + (window as any).__svgRef = document.querySelector("svg"); + return !!(window as any).__svgRef; + }); + expect(svgBefore).toBe(true); + + await page.evaluate(() => + (window as any).__proxyUpdate([ + { x: 2, y: 10 }, { x: 4, y: 40 }, { x: 6, y: 60 }, { x: 8, y: 90 } + ]) + ); + await page.waitForTimeout(50); + + expect(await page.locator("circle[class^='tag-point']").count()).toBe(4); + const sameSvg = await page.evaluate(() => (window as any).__svgRef === document.querySelector("svg")); + expect(sameSvg).toBe(true); + expect(errors, errors.join("\n")).toHaveLength(0); +}); + +test("a proxy update immediately after a re-mount is not lost", async ({ page }) => { + // Guards the destroy->reconstruct registry window: a Shiny reactive re-render + // followed at once by a proxy update must still reach the new chart. + await ready(page); + await page.evaluate(() => { + (window as any).__mount({ speed: 0 }); // re-render in place + (window as any).__proxyUpdate([{ x: 2, y: 10 }, { x: 5, y: 50 }, { x: 8, y: 90 }]); + }); + await page.waitForTimeout(50); + expect(await page.locator("circle[class^='tag-point']").count()).toBe(3); +}); diff --git a/tests/testthat/test_myIOProxy.R b/tests/testthat/test_myIOProxy.R new file mode 100644 index 0000000..d90a9b8 --- /dev/null +++ b/tests/testthat/test_myIOProxy.R @@ -0,0 +1,61 @@ +# B5: myIOProxy()/updateMyIOData() Shiny partial-update payload contract. + +fake_session <- function() { + env <- new.env() + list( + ns = function(id) paste0("ns-", id), + sendCustomMessage = function(type, message) { + env$type <- type + env$message <- message + }, + .captured = env + ) +} + +test_that("myIOProxy namespaces the outputId and carries the session", { + s <- fake_session() + p <- myIOProxy("chart", session = s) + expect_s3_class(p, "myIO_proxy") + expect_equal(p$id, "ns-chart") +}) + +test_that("myIOProxy errors without a session / reactive domain", { + expect_error(myIOProxy("chart"), "Shiny session") +}) + +test_that("updateMyIOData sends the row-rectangled payload to the right id", { + s <- fake_session() + p <- myIOProxy("chart", session = s) + df <- data.frame(x = 1:3, y = c(10, 20, 30)) + updateMyIOData(p, series = df) + + expect_equal(s$.captured$type, "myio:proxy-update") + msg <- s$.captured$message + expect_equal(msg$id, "ns-chart") + expect_length(msg$layers, 1L) + expect_equal(msg$layers[[1]]$label, "series") + # data is the as_layer_rows shape: a list of per-row named lists. + rows <- msg$layers[[1]]$data + expect_length(rows, 3L) + expect_equal(rows[[1]]$x, 1L) + expect_equal(rows[[3]]$y, 30) + expect_true("_source_key" %in% names(rows[[1]])) +}) + +test_that("updateMyIOData accepts multiple layer updates", { + s <- fake_session() + p <- myIOProxy("chart", session = s) + updateMyIOData(p, + a = data.frame(x = 1, y = 2), + b = data.frame(x = 3:4, y = 5:6)) + labels <- vapply(s$.captured$message$layers, function(l) l$label, character(1)) + expect_equal(labels, c("a", "b")) +}) + +test_that("updateMyIOData validates its inputs", { + s <- fake_session() + p <- myIOProxy("chart", session = s) + expect_error(updateMyIOData(list()), "myIOProxy") + expect_error(updateMyIOData(p), "named") + expect_error(updateMyIOData(p, series = 1:3), "data frame") +})