@tabler/charts-bootstrap 0.0.1-alpha.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -6
- package/dist/bootstrap.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/tabler-charts-bootstrap.min.js +2 -2
- package/dist/tabler-charts-bootstrap.min.js.map +1 -1
- package/dist/tabler.css +1 -1
- package/package.json +3 -3
- package/scss/_charts.scss +7 -3
- package/scss/_tabler.scss +12 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tabler-charts-bootstrap.min.js","names":["round","SVG_NS","TEXT","SHAPES","round","round","round","cleanData","EDGE","toMs","HOVER_SLOP","toMs","round","toMs","SVG_NS","pending","Chart","round","toMs","round","round","emit","round","pending","CoreChart","round","cleanData","cleanData","to2","cleanData","round","cleanData","HALF_PI","cleanData","sweepArcs","round","cleanData","cleanData","LABEL_GAP","HOVER_SLOP","truncate","round","cleanData","round","cleanData","round","cleanData","round","cleanData","exports","insets","side","v","value","key","fallback","innerRect","margins","width","height","isWide","code","charWidth","char","estimateTextWidth","em","i","text","point","ASCII","fontSize","round$1","LINE_HEIGHT","SVG_NS$2","SHAPE","TEXT$1","STOP","GROUP","SHAPES$1","rootOf","el","target","svg","transformOf","style","ox","oy","inline","live","tag","props","declarations","name","copy","transform","liveChildren","copies","twin","child","legendLayer","legend","container","items","doc","patterned","box","g","item","swatch","s","n","color","slot","fill","hidden","dot","label","bottom","margin","exportSVG","animation","chartStyle","options","total","wrap","title","background","rect","exportImage","markup","type","image","canvas","scale","context","blob","resolve","reject","quality","downloadChart","format","link","features","register","added","steps","addPost","step","each","config","content","interaction","ctx","feature","found","h","children","attrs","cls","normalizeClass","normalizeStyle","out","flattenChildren","result","UNSAFE","prop","input","last","numberCache","dateCache","cached","cache","create","cacheKey","locale","getNumberFormat","getDateFormat","unsignedZero","formatNumber","compactSymbols","formatCompact","SYMBOLS","nf","own","digitsOf","small","large","exp","scaled","parts","digits","part","symbols","compactOf","o","formatDetail","stepPrecision","abs","hasPrecision","formatTicks","fmt","epsilon","formatDate","df","E10","E5","E2","tickSpec","stop","start","count","power","error","factor","i1","i2","inc","ticks","reverse","index","tickIncrement","tickStep","niceDomain","lo","hi","prev","linearTicks","d0","d1","bandTicks","isHorizontal","position","thinTicks","sizes","tick","fitsBetween","j","gap","span","sum","size","first","fits","kept","tail","axisSize","labels","max","tickSize","tickPadding","axis","horizontal","sign","offset","edge","area","tickLine","line","grid","direction","p","band","inner","paddingInner","domain","r0","r1","range","paddingOuter","align","bandwidth","at","px","raw","pixel","padding","extent","min","values","linear","k","mid","rMin","rMax","dMin","dMax","clamp","finite","optional","isRecord","list","numbers","x","records","fix","named","r","cleanSeries","d","data","cleanData$1","cleanItems","keyOf","legendItems","entry","groupAttrs","labelKey","seriesKey","seriesLegend","resolveLabels","plottable","isTimeAxis","toMs$1","l","labelFormatter","valueScale","valueTicks","markerShape","shapes","patterns","tickCount","auto","valueDomain","override","domainOf","extra","zeroDefault","pad","nlo","nhi","notesFeature","valueAxis","layout","of","finishLayout","flip","plot","xOptions","notes","y","yTicks","categories","xTicks","present","plotClip","overhang","cartesianLayout","yOptions","showY","showX","timed","probeY","countX","keys","labelAt","xAxis","edgeLabels","halfLine","firstLabel","lastLabel","edgeX","valueWidth","overflow","halfStep","sides","clipId","bleed","seriesAttrs","series","dash","categoryInteraction","formatLabel","formatValue","hitAt","center","empty","anchor","seriesIndex","hit","py","mark","markAt","seriesTable","all","limit","categorySpan","scales","f","pair","cleanAnnotations","a","isPair","annotationValues","annotations","annotationLayers","bands","lines","x0","x1","y0","y1","inside","vertical","from","to","placed","obstacles","apart","t","b","clearOfLabels","clear","end","shape","w","a1","a0","spots","after","before","top","near","far","spot","dateLabels","utc","log","base","safe","ln","logBase","untransform","t0","t1","decades","m","keep","logDomain","niced","logTicks","hitKey","toChartPoint","sx","sy","clientX","clientY","legendContent","off","defaultHidden","NAME_RE","EVENT_RE","isValidTag","isValidAttr","SVG_NS$1","HTML_NS","rendered","roots","render","replace","vnode","canPatch","patchElement","namespaceFor","createElement","parent","childNamespace","createNode","ns","setAttr","childNs","node","next","patchNode","patchAttrs","patchChildren","update","oldNodes","keyed","unkeyed","matched","used","cursor","candidate","HTML_ROOTS","VOID","renderToString","escapeText","renderNode","inSvg","parentInSvg","escapeAttr","childInSvg","TEXT_RE","ATTR_RE","TEXT_RE_G","ATTR_RE_G","ENTITIES","replaceEntity","listeners","seen","observer","getObserver","entries","contentRect","observeResize","ro","listener","queue","pending$2","requestFrame","callback","run","task","schedule","flush","flushHooks","cancel","ran","later","uid","nextId","resolveSize","measuredWidth","measured","ratio","renderContent","renderContext","id","onHitTest","measuredFontSize","cleanData","assertType","resolveLegend","option","chartLabel","names","shown","countNodes","c","isStatic","composeChart","descId","fills","still","extraAttrs","underlay","overlay","buildChart","chartToString","chartEvents","mounted","Chart$1","followsHeight","#cfg","changed","#measured","#font","#markResizing","#schedule","element","#adopt","#measure","#unobserve","#onResize","plugin","defaultPlugins","#plugins","reserved","#cache","#current","#hit","source","#source","#setHover","event","#hiddenSet","#toggled","#destroyed","cfg","#content","stale","#refreshHighlight","adopted","#compose","hiddenKey","#measureFontSize","under","over","layer","set","#handlers","handler","#resizeTimer","force","#hovered","rerender","TILES","SLOTS","patternDefs","patternVars","vars","patternFills","SHAPES","markerPath","reshape","group","shapesStep","SECOND","MINUTE","HOUR","DAY","MONTH","YEAR","INTERVALS","calendar","get","unit","make","mo","mi","weekday","date","chooseInterval","years","toMs","FORMATS","time","cal","interval","primary","above","tz","main","upper","timePointScale","stamps","valid","positions","ms","timeAxis","points","probe","overlaps","contains","outer","valueLabels","spec","pie","cell","stacked","marks","share","candidates","down","reach","along","room","sliceFits","other","slim","radius","depth","labelsStep","matches","hydrateElement","current","texts","created","hydrate","running","tween","state","origin","begin","duration","draw","NUMBER","native","morph","now","lttbIndices","threshold","runs","sampleRun","budget","bucketSize","bucket","nextStart","nextEnd","avgX","avgY","rangeStart","rangeEnd","ax","ay","best","bestArea","lttb","PathBuilder","#k","precision","rounded","#n","#xy","x2","y2","emit$1","curve","dedupe","move","path","monotone","xm","tangents","h0","h1","s0","s1","endTangent","dx","isValid","linePath","areaPath","baseAt","baseline","NAMES","DEFAULT_FORMATS","download","host","chart","addedClass","toggle","menu","setOpen","open","onOutside","isOpen","onClick","onKey","onBlur","remove","formats","seriesGroup","hoverUnderlay","crosshair","hoverOverlay","listening","listenPointer","local","onMove","onLeave","pointer","highlight","tableContent","corner","headers","table","caption","head","cells","describeHit","enabled","keyboard","region","announce","go","handle","focused","isChart","onFocus","adopt","bound","place","marginTop","marginBottom","groups","indexes","passing","indexOf","sync","self","joined","leave","join","ref","idle","pending$1","drain","tasks","scheduleIdle","cancelIdle","dataTable","maxRows","visible","rows","note","same","hitAnchor","tooltipContent","placeTooltip","left","bounds","fitsRight","fitsLeft","rawX","right","waiting","placeAll","measure","tooltip","tip","turns","turn","clip","Chart","fadeMask","stackSeries","percent","up","lastUp","lastDown","nullAsZero","row","segment","stackBounds","stacks","seriesPoints","connectNulls","renderLines","filled","fillStyle","pointRadius","gradient","fadeId","stack","seg","decimate","pts","drawn","bottoms","areas","dots","cx","cy","round","barPath","sweep","rr","hbarPath","hgt","length","horizontalLayout","probeValues","showValues","showCategories","probeCategories","edgeLabel","bar","orientation","isLine","lineKeys","stackHidden","layoutOptions","groupPadding","slots","order","columns","barWidth","maxBarWidth","groupWidth","barLeft","across","negative","away","paths","bodyPath","asCartesian","pick","candlestick","cartesian","maxCandleWidth","paint","candle","candles","EPSILON","PI","HALF_PI$1","TAU","DEG","asin","acos","intersect","x10","y10","x32","x3","y32","y3","cornerTangents","x01","y01","cw","rc","x11","y11","x00","y00","dy","d2","D","cx0","cy0","cx1","cy1","dx0","dy0","dx1","dy1","sector","a01","a11","a00","a10","da0","da","da1","ap","rp","rc0","rc1","p0","p1","oc","bx","by","cos","kc","lc","arcCentroid","padAngleForGap","innerRadius","outerRadius","angleOf","arcPathStable","arc","ring","delta","ccw","outerSweep","ix","iy","ex","ey","arcNode","startAngle","endAngle","padAngle","cornerRadius","HALF_PI","ringsOf","layoutRings","fitGauge","textTop","textBottom","renderGauge","thickness","rings","showCenter","centerLabel","radii","grow","fraction","geometry","hitFor","centerValue","gaugeTable","gauge","EMPTY","shade","rangeKey","rangeOf","ranges","slotColor","ringPath","renderHeatmap","dataMin","dataMax","stops","bySeries","u","pct","rowTicks","halfColumn","cellW","cellH","cellX","cellY","valueAt","painted","heatmapLegend","heatmap","layoutSlices","slice","angle","renderPie","defaults","slices","strokeGap","pieTable","pieType","donut","truncate$1","word","sin","fitRadius","angles","blockHeight","renderRadar","labelWidth","wrapped","polygon","radiusOf","spokeLabels","rest","radar","truncate","colorOf","graph","byName","nodes","declared","isHidden","legendKey","links","pass","justify","ia","ib","nodeWidth","nodePadding","widest","match","cap","byColumn","col","showValue","linkPath","ty","cubic","inLink","renderSankey","nodeMark","linkItem","hitNode","flows","linkIndex","hitLink","sankeyLegend","sankeyTable","sankey","circlePath","sizeOf","renderScatter","maxSize","bubble","countY","usable","xDomain","yDomain","ticksOf","probeX","half","fx","fy","fs","sz","bestDistance","distance","dotsPath","scatterTable","withSize","withLabel","take","scatter","renderSparkline","markers","tristate","variant","zero","bars","xAt","labelOf","yOf","dotAt","extremes","sparkline","types","SELECTOR","RESERVED","TEXT","charts","pending","getChart","dispose","parseValue","parseJson","what","optionsOf","json","inlineData","attr","emit","detail","setup","existing","known","src","response","init","elements","root","made","observe","record","owner","script","observing"],"sources":["../../core/src/layout.ts","../../core/src/export-chart.ts","../../core/src/features.ts","../../core/src/export.ts","../../core/src/vnode.ts","../../core/src/format.ts","../../core/src/scales/ticks.ts","../../core/src/components/axis.ts","../../core/src/components/grid.ts","../../core/src/scales/band.ts","../../core/src/scales/extent.ts","../../core/src/scales/linear.ts","../../core/src/charts/clean.ts","../../core/src/charts/named.ts","../../core/src/charts/cartesian.ts","../../core/src/charts/annotations.ts","../../core/src/charts/dates.ts","../../core/src/scales/log.ts","../../core/src/charts/log-axis.ts","../../core/src/interaction.ts","../../core/src/legend.ts","../../core/src/render/attrs.ts","../../core/src/render/dom.ts","../../core/src/render/string.ts","../../core/src/resize.ts","../../core/src/scheduler.ts","../../core/src/chart.ts","../../core/src/charts/patterns.ts","../../core/src/charts/point-shapes.ts","../../core/src/scales/time.ts","../../core/src/charts/time-axis.ts","../../core/src/charts/value-labels.ts","../../core/src/render/hydrate.ts","../../core/src/render/tween.ts","../../core/src/render/morph.ts","../../core/src/shapes/decimate.ts","../../core/src/shapes/path.ts","../../core/src/plugins/download.ts","../../core/src/components/hover.ts","../../core/src/plugins/pointer.ts","../../core/src/plugins/highlight.ts","../../core/src/a11y.ts","../../core/src/plugins/keyboard.ts","../../core/src/plugins/legend.ts","../../core/src/plugins/sync.ts","../../core/src/idle.ts","../../core/src/plugins/table.ts","../../core/src/tooltip.ts","../../core/src/plugins/tooltip.ts","../../core/src/plugins/index.ts","../../core/src/chart-default.ts","../../core/src/components/fade.ts","../../core/src/charts/stack.ts","../../core/src/charts/line.ts","../../core/src/charts/area.ts","../../core/src/shapes/bar.ts","../../core/src/charts/horizontal.ts","../../core/src/charts/bar.ts","../../core/src/charts/candlestick.ts","../../core/src/shapes/arc.ts","../../core/src/render/sweep.ts","../../core/src/charts/gauge.ts","../../core/src/charts/heatmap.ts","../../core/src/charts/pie.ts","../../core/src/charts/radar.ts","../../core/src/charts/sankey.ts","../../core/src/shapes/circle.ts","../../core/src/charts/scatter.ts","../../core/src/charts/sparkline.ts","../../core/src/chart-types.ts","../../core/package.json","../../core/src/core.ts","../../core/src/index.ts","../src/index.ts","../src/cdn.ts"],"sourcesContent":["/** Axis-aligned rectangle in pixels. */\nexport interface Rect {\n x: number\n y: number\n width: number\n height: number\n}\n\n/** Space around a box, in pixels. */\nexport interface Insets {\n top: number\n right: number\n bottom: number\n left: number\n}\n\n/** Insets given as one number for all sides or per side. */\nexport type InsetsInput = number | Partial<Insets>\n\n/** Normalize an {@link InsetsInput}; missing sides fall back to `fallback`. */\nexport function insets(value: InsetsInput | undefined, fallback = 0): Insets {\n // A side that is not a finite number (left out, or junk from outside) takes the fallback.\n const side = (key: keyof Insets): number => {\n const v = typeof value === 'number' ? value : value?.[key]\n return Number.isFinite(v) ? (v as number) : fallback\n }\n return { top: side('top'), right: side('right'), bottom: side('bottom'), left: side('left') }\n}\n\n/** Rectangle left inside `width × height` after `margins`; never negative. */\nexport function innerRect(width: number, height: number, margins: Insets): Rect {\n return {\n x: margins.left,\n y: margins.top,\n width: Math.max(0, width - margins.left - margins.right),\n height: Math.max(0, height - margins.top - margins.bottom),\n }\n}\n\n// Approximate advance widths in em for common UI sans-serif fonts\n// (system-ui / SF, Segoe UI, Roboto), measured in the browser.\nconst THIN = \" !'.,:;|ijlI`\"\nconst NARROW = '()[]{}-/frt'\nconst ROUND = 'CDGHNOQU'\nconst WIDE = '%@MWmw'\n\n/**\n * Full-width characters, a whole em each: Hangul, CJK and kana, compatibility\n * ideographs, fullwidth forms and pictographs (emoji).\n */\nconst isWide = (code: number): boolean =>\n code >= 0x1100 &&\n (code <= 0x115f ||\n (code >= 0x2e80 && code <= 0xa4cf) ||\n (code >= 0xac00 && code <= 0xd7a3) ||\n (code >= 0xf900 && code <= 0xfaff) ||\n (code >= 0xff00 && code <= 0xff60) ||\n code >= 0x1f300)\n\n/** The width of an ASCII character, in em. */\nfunction charWidth(char: string): number {\n if (char >= '0' && char <= '9') return char === '1' ? 0.45 : 0.63\n if (THIN.includes(char)) return 0.27\n if (NARROW.includes(char)) return 0.38\n if (WIDE.includes(char)) return 0.88\n if (ROUND.includes(char)) return 0.76\n if (char >= 'A' && char <= 'Z') return 0.66\n return 0.57\n}\n\n/**\n * Estimate the rendered width of `text` without a DOM, for layout on the\n * server and in workers. Tuned for common UI sans-serif fonts; deterministic,\n * so SSR and client layouts agree.\n */\nexport function estimateTextWidth(text: string, fontSize: number): number {\n let em = 0\n for (let i = 0; i < text.length; i++) {\n const point = text.codePointAt(i) as number\n // Beyond ASCII a character is a whole em or an average one; a pair of surrogates is one.\n em += ASCII[point] ?? (isWide(point) ? 1 : 0.57)\n if (point > 0xffff) i++\n }\n return em * fontSize\n}\n\n/**\n * The width of every ASCII character, looked up instead of worked out: an\n * axis of 100,000 long labels estimates millions of characters per render.\n */\nconst ASCII = /* @__PURE__ */ Array.from({ length: 128 }, (_, code) =>\n charWidth(String.fromCharCode(code)),\n)\n\n/** A pixel value rounded to two decimals, as written into attributes and path data. */\nexport const round = (value: number): number => Math.round(value * 100) / 100\n\n/** Line height used for single-line labels, relative to the font size. */\nexport const LINE_HEIGHT = 1.25\n","/**\n * Export a rendered chart as a standalone SVG or an image\n * (`exportSVG()`, `exportImage()`, `downloadChart()` of `@tabler/charts/export`).\n *\n * Charts are styled by CSS, so the export copies the computed styles of\n * every mark into the SVG: the file looks the same anywhere, without the\n * stylesheet or the page's custom properties. Browser only.\n *\n * Kept free of side effects, so `@tabler/charts` can re-export the functions\n * without carrying them into every bundle: the `/export` entry registers the\n * `download` menu's saver on top.\n */\nimport type { Chart } from './chart.ts'\nimport { round } from './layout.ts'\n\nconst SVG_NS = 'http://www.w3.org/2000/svg'\n\nexport interface ExportOptions {\n /**\n * Background color, `'auto'` for the chart's surface (`--tc-surface`), or\n * `false` for none (transparent). Defaults to `'auto'`.\n */\n background?: string | false\n /** Draw the legend into the image, as the page shows it. Defaults to `true`. */\n legend?: boolean\n}\n\nexport interface ImageOptions extends ExportOptions {\n /** Image type. Defaults to `'image/png'`. */\n type?: 'image/png' | 'image/jpeg' | 'image/webp'\n /** Pixels per chart pixel. Defaults to `2`. */\n scale?: number\n /** Quality of lossy types, `0…1`. */\n quality?: number\n}\n\nexport interface DownloadOptions extends ImageOptions {\n /** File name without the extension. Defaults to the chart's title, or `chart`. */\n filename?: string\n /** File format. Defaults to `'png'`. */\n format?: 'svg' | 'png' | 'jpeg' | 'webp'\n}\n\n/** A chart, its container, or its root `<svg>`. */\nexport type ExportTarget = Chart<object> | Element\n\n/** Properties copied from the computed style, with the values they can be left out at. */\nconst SHAPE: Record<string, string> = {\n fill: 'rgb(0, 0, 0)',\n 'fill-opacity': '1',\n stroke: 'none',\n 'stroke-width': '1px',\n 'stroke-opacity': '1',\n 'stroke-dasharray': 'none',\n 'stroke-dashoffset': '0px',\n 'stroke-linecap': 'butt',\n 'stroke-linejoin': 'miter',\n 'paint-order': 'normal',\n 'shape-rendering': 'auto',\n 'vector-effect': 'none',\n opacity: '1',\n visibility: 'visible',\n}\nconst TEXT: Record<string, string> = {\n ...SHAPE,\n 'font-family': '',\n 'font-size': '',\n 'font-weight': '400',\n 'font-style': 'normal',\n 'font-variant-numeric': 'normal',\n 'letter-spacing': 'normal',\n}\nconst STOP: Record<string, string> = { 'stop-color': '', 'stop-opacity': '1' }\nconst GROUP: Record<string, string> = { opacity: '1' }\nconst SHAPES = new Set(['path', 'line', 'rect', 'circle', 'ellipse', 'polygon', 'polyline'])\n\nfunction rootOf(target: ExportTarget): SVGSVGElement {\n const el = 'element' in target && !(target instanceof Element) ? target.element : target\n const svg = el.localName === 'svg' ? el : el.querySelector(':scope > svg.tc-chart')\n if (!svg) throw new Error('@tabler/charts: no rendered chart to export.')\n return svg as SVGSVGElement\n}\n\n/** A computed transform as an SVG `transform` attribute, around its origin. */\nfunction transformOf(style: CSSStyleDeclaration): string | undefined {\n const value = style.transform\n if (!value || value === 'none') return undefined\n // Browsers report a matrix; SVG takes the same functions without units.\n const svg = value.replace(/px/g, '')\n if (svg.startsWith('translate')) return svg\n const [ox = 0, oy = 0] = (style.transformOrigin || '0 0').split(' ').map(Number.parseFloat)\n return ox || oy ? `translate(${ox} ${oy}) ${svg} translate(${-ox} ${-oy})` : svg\n}\n\n/** Copy the computed look of `live` onto its clone, recursively. */\nfunction inline(live: Element, copy: Element): boolean {\n const style = getComputedStyle(live)\n if (style.display === 'none') return false\n const tag = live.localName\n const props = tag === 'text' ? TEXT : tag === 'stop' ? STOP : SHAPES.has(tag) ? SHAPE : GROUP\n const declarations: string[] = []\n for (const name in props) {\n const value = style.getPropertyValue(name)\n if (value && value !== props[name]) declarations.push(`${name}:${value}`)\n }\n copy.removeAttribute('style')\n if (declarations.length) copy.setAttribute('style', declarations.join(';'))\n const transform = transformOf(style)\n if (transform) copy.setAttribute('transform', transform)\n\n const liveChildren = Array.from(live.children)\n const copies = Array.from(copy.children)\n liveChildren.forEach((child, i) => {\n const twin = copies[i] as Element\n if (child.classList.contains('tc-hover-layer') || !inline(child, twin)) twin.remove()\n })\n return true\n}\n\n/**\n * The legend as the page lays it out: every entry at its place relative to\n * the legend box, with a swatch (hollow when hidden) and its name.\n */\nfunction legendLayer(\n container: Element,\n): { svg: Element; height: number; margin: number; bottom: boolean } | undefined {\n const legend = container.querySelector(':scope > .tc-legend')\n const items = legend ? Array.from(legend.querySelectorAll('.tc-legend-item')) : []\n if (!legend || !items.length) return undefined\n const doc = container.ownerDocument\n const patterned = container.querySelector(':scope > svg.tc-patterned')\n const box = legend.getBoundingClientRect()\n const g = doc.createElementNS(SVG_NS, 'g')\n for (const item of items) {\n const swatch = item.querySelector('.tc-legend-swatch')\n const name = item.querySelector('.tc-legend-name')\n if (!swatch || !name) continue\n const s = swatch.getBoundingClientRect()\n const n = name.getBoundingClientRect()\n const color = getComputedStyle(swatch).getPropertyValue('--tc-series-color').trim()\n // A chart that wears its patterns has them in the copied svg: the swatch takes its slot's.\n const slot = /\\btc-series-([1-8])\\b/.exec(item.getAttribute('class') ?? '')?.[1] ?? 'other'\n const fill = patterned\n ? getComputedStyle(patterned).getPropertyValue(`--tc-pattern-${slot}`).trim()\n : ''\n const hidden = item.classList.contains('tc-legend-item-hidden')\n const dot = doc.createElementNS(SVG_NS, 'circle')\n dot.setAttribute('cx', String(round(s.left - box.left + s.width / 2)))\n dot.setAttribute('cy', String(round(s.top - box.top + s.height / 2)))\n dot.setAttribute('r', String(round(s.width / 2 - (hidden ? 0.75 : 0))))\n dot.setAttribute(\n 'style',\n hidden\n ? `fill:none;stroke:${color};stroke-width:1.5px`\n : `fill:${fill.startsWith('url(') ? fill : color}`,\n )\n const text = getComputedStyle(name)\n const label = doc.createElementNS(SVG_NS, 'text')\n label.setAttribute('x', String(round(n.left - box.left)))\n label.setAttribute('y', String(round(n.top - box.top + n.height / 2)))\n label.setAttribute('dy', '0.35em')\n label.setAttribute(\n 'style',\n `fill:${text.color};font-family:${text.fontFamily};font-size:${text.fontSize};font-weight:${text.fontWeight}`,\n )\n label.textContent = name.textContent\n g.append(dot, label)\n }\n const bottom = legend.getAttribute('data-position') === 'bottom'\n const margin =\n Number.parseFloat(getComputedStyle(legend)[bottom ? 'marginTop' : 'marginBottom']) || 0\n return { svg: g, height: round(box.height + margin), margin, bottom }\n}\n\n/**\n * The chart as a standalone SVG document: the computed styles are inlined,\n * hover marks left out and running animations finished first.\n *\n * ```ts\n * const svg = exportSVG(chart)\n * ```\n */\nexport function exportSVG(target: ExportTarget, options: ExportOptions = {}): string {\n const svg = rootOf(target)\n // Read the resting state, not a frame in the middle of an entrance or update.\n for (const animation of svg.getAnimations?.({ subtree: true }) ?? []) animation.finish()\n const copy = svg.cloneNode(true) as SVGSVGElement\n inline(svg, copy)\n const doc = svg.ownerDocument\n const width = Number(svg.getAttribute('width'))\n const height = Number(svg.getAttribute('height'))\n copy.setAttribute('xmlns', SVG_NS)\n copy.removeAttribute('class')\n copy.removeAttribute('tabindex')\n copy.removeAttribute('data-resizing')\n copy.removeAttribute('aria-describedby')\n copy.removeAttribute('aria-activedescendant')\n\n const chartStyle = getComputedStyle(svg)\n const container = svg.parentElement\n const legend = options.legend !== false && container ? legendLayer(container) : undefined\n let total = height\n if (legend) {\n // The chart moves down below a top legend; a bottom one goes under it.\n const wrap = doc.createElementNS(SVG_NS, 'g')\n wrap.append(...Array.from(copy.childNodes))\n if (legend.bottom) {\n legend.svg.setAttribute('transform', `translate(0 ${height + legend.margin})`)\n } else {\n wrap.setAttribute('transform', `translate(0 ${legend.height})`)\n }\n copy.append(wrap, legend.svg)\n total = height + legend.height\n }\n copy.setAttribute('width', String(width))\n copy.setAttribute('height', String(total))\n copy.setAttribute('viewBox', `0 0 ${width} ${total}`)\n\n // A name for the file itself, besides the aria-label.\n const name = svg.getAttribute('aria-label')\n if (name) {\n const title = doc.createElementNS(SVG_NS, 'title')\n title.textContent = name\n copy.prepend(title)\n }\n\n const background =\n options.background === undefined || options.background === 'auto'\n ? chartStyle.getPropertyValue('--tc-surface').trim() || undefined\n : options.background || undefined\n if (background) {\n const rect = doc.createElementNS(SVG_NS, 'rect')\n rect.setAttribute('width', '100%')\n rect.setAttribute('height', '100%')\n rect.setAttribute('fill', background)\n copy.insertBefore(rect, copy.querySelector(':scope > title')?.nextSibling ?? copy.firstChild)\n }\n return new XMLSerializer().serializeToString(copy)\n}\n\n/**\n * The chart as an image (PNG by default), drawn from `exportSVG()` at\n * `scale` pixels per chart pixel.\n *\n * ```ts\n * const blob = await exportImage(chart, { scale: 3 })\n * ```\n */\nexport async function exportImage(target: ExportTarget, options: ImageOptions = {}): Promise<Blob> {\n const { type = 'image/png', scale = 2, quality } = options\n const markup = exportSVG(target, {\n ...options,\n // JPEG has no transparency: without a background it would turn black.\n ...(type === 'image/jpeg' && options.background === false ? { background: '#fff' } : {}),\n })\n const doc = rootOf(target).ownerDocument\n const image = new Image()\n image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`\n await image.decode()\n const canvas = doc.createElement('canvas')\n canvas.width = Math.round(image.width * scale)\n canvas.height = Math.round(image.height * scale)\n const context = canvas.getContext('2d')\n if (!context) throw new Error('@tabler/charts: no 2d canvas to draw the image.')\n context.drawImage(image, 0, 0, canvas.width, canvas.height)\n return new Promise((resolve, reject) => {\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error('@tabler/charts: could not encode.'))),\n type,\n quality,\n )\n })\n}\n\n/**\n * Save the chart as a file: PNG by default, or SVG, JPEG or WebP.\n *\n * ```ts\n * button.onclick = () => downloadChart(chart, { format: 'svg', filename: 'sales' })\n * ```\n */\nexport async function downloadChart(\n target: ExportTarget,\n options: DownloadOptions = {},\n): Promise<void> {\n const { format = 'png' } = options\n const svg = rootOf(target)\n const blob =\n format === 'svg'\n ? new Blob([exportSVG(target, options)], { type: 'image/svg+xml' })\n : await exportImage(target, { ...options, type: `image/${format}` })\n const name = (options.filename ?? svg.getAttribute('aria-label') ?? 'chart')\n .replace(/[\\\\/:*?\"<>|]+/g, '')\n .trim()\n const link = svg.ownerDocument.createElement('a')\n link.href = URL.createObjectURL(blob)\n link.download = `${name || 'chart'}.${format === 'jpeg' ? 'jpg' : format}`\n link.click()\n // Give the browser a moment to start the download before the URL goes.\n setTimeout(() => URL.revokeObjectURL(link.href), 1000)\n}\n","import type { ChartConfig, RenderContext } from './chart.ts'\nimport type { annotationLayers, annotationValues } from './charts/annotations.ts'\nimport type { dateLabels } from './charts/dates.ts'\nimport type { logDomain, logTicks } from './charts/log-axis.ts'\nimport type { patternFills } from './charts/patterns.ts'\nimport type { markerPath } from './charts/point-shapes.ts'\nimport type { timeAxis } from './charts/time-axis.ts'\nimport type { downloadChart } from './export-chart.ts'\nimport type { Interaction } from './interaction.ts'\nimport type { hydrate } from './render/hydrate.ts'\nimport type { morph } from './render/morph.ts'\nimport type { sweep } from './render/sweep.ts'\nimport type { log } from './scales/log.ts'\nimport type { time, timePointScale } from './scales/time.ts'\nimport type { areaPath, linePath, Point } from './shapes/path.ts'\nimport type { ChildInput } from './vnode.ts'\n\n/**\n * Optional features that chart types look up at render time. Each lives in\n * its own module (`@tabler/charts/time`, `/log`, `/decimate`, `/line`, `/annotations`) and registers\n * itself when imported; `@tabler/charts` registers all of them, while\n * `@tabler/charts/core` starts empty so unused code never ships.\n */\nexport interface Features {\n /** Time scale (and the point scale over it) behind `x: { type: 'time' }`. */\n time?: { scale: typeof time; points: typeof timePointScale; axis: typeof timeAxis }\n /** Date labels behind `x: { type: 'time' }` (also registered by `@tabler/charts/candlestick`). */\n dates?: typeof dateLabels\n /** Log scale and axis behind `scale: 'log'`. */\n log?: { scale: typeof log; domain: typeof logDomain; ticks: typeof logTicks }\n /** Downsampling behind `decimate: N`: indices of the points to keep. */\n decimate?: (points: readonly Point[], threshold: number) => number[]\n /**\n * Taking over server-rendered markup node by node (without it, the server\n * svg is replaced on the first render).\n */\n hydrate?: typeof hydrate\n /** Path morphing on data updates where CSS cannot transition `d` (Safari). */\n morph?: typeof morph\n /** Arcs turning to their new angles on data updates (set by pie, donut and gauge). */\n sweep?: typeof sweep\n /** Line and area paths behind `series.type: 'line' | 'area'` in bar charts. */\n line?: { linePath: typeof linePath; areaPath: typeof areaPath }\n /** Reference lines and bands behind `annotations` in cartesian charts. */\n annotations?: { layers: typeof annotationLayers; values: typeof annotationValues }\n /** Pattern fills behind `patterns` (and forced colors, with `'auto'`). */\n patterns?: typeof patternFills\n /**\n * Steps that finish a chart's rendered content (see `addPost`): point\n * shapes, value labels.\n */\n post?: PostStep\n /** Point shapes by color slot, behind `shapes`. */\n 'point-shapes'?: typeof markerPath\n /** Saving a chart as a file, behind the `download` menu. */\n export?: typeof downloadChart\n}\n\nexport const features: Features = {}\n\n/** Register optional features (idempotent). */\nexport function register(added: Features): void {\n Object.assign(features, added)\n}\n\n/** A step that finishes rendered chart content, e.g. by adding value labels. */\nexport type PostStep = (\n config: ChartConfig<object>,\n content: ChildInput,\n interaction: Interaction | undefined,\n ctx: RenderContext,\n) => ChildInput\n\nconst steps = /* @__PURE__ */ new Set<PostStep>()\n\n/** Add a step that finishes rendered content, once, in the order added. */\nexport function addPost(step: PostStep): void {\n steps.add(step)\n features.post = (config, content, interaction, ctx) => {\n for (const each of steps) content = each(config, content, interaction, ctx)\n return content\n }\n}\n\n/** The registered feature, or a helpful error naming the import that provides it. */\nexport function feature<K extends keyof Features>(name: K): NonNullable<Features[K]> {\n const found = features[name]\n if (!found) {\n throw new Error(\n `@tabler/charts: Import \"@tabler/charts/${name === 'dates' ? 'time' : name}\" for ${name}.`,\n )\n }\n return found\n}\n","/**\n * Standalone entry: `import { exportSVG, exportImage, downloadChart } from '@tabler/charts/export'`\n * saves a rendered chart as a standalone SVG or an image. Importing it also\n * enables the `download` option (a menu on the chart that saves it): with the\n * `Chart` of `@tabler/charts`, which has the `download()` plugin, or with the\n * plugin installed on the core.\n */\nimport { downloadChart, exportImage, exportSVG } from './export-chart.ts'\nimport { register } from './features.ts'\n\n// Registered here, in the entry itself, so no bundler can shake it away.\nregister({ export: downloadChart })\n\nexport type {\n DownloadOptions,\n ExportOptions,\n ExportTarget,\n ImageOptions,\n} from './export-chart.ts'\nexport { downloadChart, exportImage, exportSVG }\n","/**\n * Minimal virtual node tree shared by the string (SSR) and DOM renderers.\n *\n * VNodes are plain, serializable data: no event handlers, no component\n * functions. Interaction is handled by event delegation on the root element,\n * so the same tree can be rendered on the server, in a worker or in tests.\n */\n\n/** Value accepted for a single attribute. `false`, `null`, `undefined` and non-finite numbers omit it. */\nexport type AttrValue = string | number | boolean | null | undefined\n\n/** Normalized attributes stored on a {@link VNode}. */\nexport type Attrs = Record<string, string | number>\n\n/** Identity used by the DOM renderer to match nodes between renders. */\nexport type Key = string | number\n\n/** Class list: strings, falsy values (skipped) and nested arrays. */\nexport type ClassValue = string | false | null | undefined | ClassValue[]\n\n/** Inline styles: a raw string or a map of properties (custom properties included). */\nexport type StyleValue = string | Record<string, string | number | null | undefined>\n\n/** Props accepted by {@link h}. */\nexport interface Props {\n [name: string]: AttrValue | ClassValue | StyleValue\n key?: Key | null | undefined\n class?: ClassValue\n style?: StyleValue | null | undefined\n}\n\n/** A normalized child: an element node or a text node. */\nexport type Child = VNode | string\n\n/** Anything that can be passed as a child to {@link h}; falsy values are skipped. */\nexport type ChildInput = Child | number | boolean | null | undefined | ChildInput[]\n\nexport interface VNode {\n /** Element name, e.g. `svg`, `g`, `path`. */\n tag: string\n /** Normalized attributes, without `key`. */\n attrs: Attrs\n /** Flattened children with adjacent text merged. */\n children: Child[]\n /** Optional identity used by the keyed DOM patcher. */\n key: Key | undefined\n /**\n * The arc a path draws (radii, angles, pad angle, corner radius), kept out\n * of the markup: the DOM patcher sweeps from the arc of the last render to\n * this one (see `sweep`).\n */\n arc?: readonly number[]\n}\n\n/**\n * Create a virtual node.\n *\n * ```ts\n * h('g', { class: ['tc-series', `tc-series-${i}`], key: series.id },\n * h('path', { class: 'tc-line', d }),\n * )\n * ```\n */\nexport function h(tag: string, props?: Props | null, ...children: ChildInput[]): VNode {\n const attrs: Attrs = {}\n let key: Key | undefined\n\n if (props) {\n for (const name in props) {\n const value = props[name]\n if (name === 'key') {\n if (value != null) key = value as Key\n } else if (name === 'class') {\n const cls = normalizeClass(value as ClassValue)\n if (cls) attrs.class = cls\n } else if (name === 'style') {\n const style = normalizeStyle(value as StyleValue | null | undefined)\n if (style) attrs.style = style\n } else if (value === true) {\n attrs[name] = ''\n } else if (typeof value === 'string') {\n attrs[name] = value\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n attrs[name] = value\n }\n }\n }\n\n const out: Child[] = []\n flattenChildren(children, out)\n\n return { tag, attrs, children: out, key }\n}\n\n/** Join a class value into a space separated string. */\nexport function normalizeClass(value: ClassValue): string {\n if (!value) return ''\n if (typeof value === 'string') return value\n let result = ''\n for (const item of value) {\n const cls = normalizeClass(item)\n if (cls) result = result ? `${result} ${cls}` : cls\n }\n return result\n}\n\n/**\n * Values that could leave their declaration (`;`, braces, quotes, escapes,\n * comments) or load something (`url()` and friends). Colors and dashes often\n * come from user data, and `red;position:fixed` would restyle the chart's\n * elements, `url(…)` would make the browser request it. A reference to an\n * element of the page, `url(#id)` (pattern fills), loads nothing and passes.\n */\nconst UNSAFE =\n /[;{}<>\"'\\\\]|\\/\\*|\\b(?:url(?!\\(#[\\w-]+\\))|src|attr|image|image-set|cross-fade|element|expression)\\s*\\(/i\n\n/**\n * Serialize a style value into a CSS declaration list. In a map, values that\n * could inject CSS (see {@link UNSAFE}) are left out, so use one for values\n * from data; a raw string is taken as it is.\n */\nexport function normalizeStyle(value: StyleValue | null | undefined): string {\n if (!value) return ''\n if (typeof value === 'string') return value\n let result = ''\n for (const prop in value) {\n const v = value[prop]\n if (v == null || v === '' || UNSAFE.test(String(v))) continue\n result += `${result ? ';' : ''}${prop}:${v}`\n }\n return result\n}\n\nfunction flattenChildren(input: ChildInput[], out: Child[]): void {\n for (const child of input) {\n if (child == null || typeof child === 'boolean') continue\n if (Array.isArray(child)) {\n flattenChildren(child, out)\n continue\n }\n if (typeof child === 'object') {\n out.push(child)\n continue\n }\n const text = String(child)\n if (text === '') continue\n const last = out.length - 1\n if (last >= 0 && typeof out[last] === 'string') {\n out[last] += text\n } else {\n out.push(text)\n }\n }\n}\n","/**\n * Number and date formatting built on `Intl` — locale aware, zero bytes of\n * locale data shipped.\n *\n * Formats are plain data (`Intl` options) or functions, so chart configs stay\n * serializable (JSON attributes, SSR). Pass an explicit `locale` when\n * rendering on the server, otherwise server and browser may disagree.\n */\n\n/** Locale(s) passed to `Intl`; `undefined` uses the runtime default. */\nexport type Locale = string | readonly string[] | undefined\n\n/** `Intl.NumberFormat` options, plus suffixes of our own for compact notation. */\nexport interface NumberFormatOptions extends Intl.NumberFormatOptions {\n /**\n * Compact notation with these suffixes for thousands, millions, billions…\n * instead of the locale's words: `['k', 'M', 'G']` writes 1500 as \"1.5k\",\n * or \"1,5k\" in Polish, where the locale itself writes \"1,5 tys.\". `true`\n * stands for `['K', 'M', 'B', 'T']`. Larger numbers keep the last suffix.\n */\n compactSymbols?: boolean | readonly string[]\n}\n\n/** Number format options or a custom formatter. */\nexport type NumberFormat = NumberFormatOptions | ((value: number) => string)\n\n/** `Intl.DateTimeFormat` options or a custom formatter. */\nexport type DateFormat = Intl.DateTimeFormatOptions | ((value: Date) => string)\n\nconst MAX_CACHE = 64\nconst numberCache = /* @__PURE__ */ new Map<string, Intl.NumberFormat>()\nconst dateCache = /* @__PURE__ */ new Map<string, Intl.DateTimeFormat>()\n\nfunction cached<T>(cache: Map<string, T>, key: string, create: () => T): T {\n let value = cache.get(key)\n if (value === undefined) {\n if (cache.size >= MAX_CACHE) cache.clear()\n value = create()\n cache.set(key, value)\n }\n return value\n}\n\nfunction cacheKey(locale: Locale, options: object): string {\n return `${JSON.stringify(locale ?? null)}|${JSON.stringify(options)}`\n}\n\n/** Shared, cached `Intl.NumberFormat` instance. */\nexport function getNumberFormat(\n locale?: Locale,\n options: Intl.NumberFormatOptions = {},\n): Intl.NumberFormat {\n return cached(\n numberCache,\n cacheKey(locale, options),\n () => new Intl.NumberFormat(locale as string | string[] | undefined, options),\n )\n}\n\n/** Shared, cached `Intl.DateTimeFormat` instance. */\nexport function getDateFormat(\n locale?: Locale,\n options: Intl.DateTimeFormatOptions = {},\n): Intl.DateTimeFormat {\n return cached(\n dateCache,\n cacheKey(locale, options),\n () => new Intl.DateTimeFormat(locale as string | string[] | undefined, options),\n )\n}\n\n/** Avoid `-0` rendering as \"-0\". */\nconst unsignedZero = (value: number): number => (value === 0 ? 0 : value)\n\n/**\n * Create a number formatter.\n *\n * ```ts\n * formatNumber({ style: 'currency', currency: 'PLN' }, 'pl-PL')(1234.5) // \"1234,50 zł\"\n * ```\n */\nexport function formatNumber(format?: NumberFormat, locale?: Locale): (value: number) => string {\n if (typeof format === 'function') return format\n const { compactSymbols, ...options } = format ?? {}\n if (compactSymbols) {\n return formatCompact(compactSymbols === true ? SYMBOLS : compactSymbols, options, locale)\n }\n const nf = getNumberFormat(locale, options)\n return (value) => nf.format(unsignedZero(value))\n}\n\nconst SYMBOLS = ['K', 'M', 'B', 'T']\n\n/**\n * Compact notation with the given suffixes: the value divided by its power\n * of a thousand, formatted by `Intl` (separators, currency, sign) with the\n * suffix after the digits. Without digits of its own it rounds like `Intl`'s\n * compact notation: two significant digits below 10, whole numbers above.\n */\nfunction formatCompact(\n symbols: readonly string[],\n // `notation` and `compactDisplay` are taken out: the suffixes replace them.\n { notation, compactDisplay, ...options }: Intl.NumberFormatOptions,\n locale: Locale,\n): (value: number) => string {\n const own = digitsOf(options)\n const small = getNumberFormat(locale, own ? options : { ...options, maximumSignificantDigits: 2 })\n const large = own ? small : getNumberFormat(locale, { ...options, maximumFractionDigits: 0 })\n return (value) => {\n for (let exp = 0; ; exp++) {\n const scaled = unsignedZero(value / 1000 ** exp)\n const parts = (Math.abs(scaled) < 10 ? small : large).formatToParts(scaled)\n let digits = ''\n let last: Intl.NumberFormatPart | undefined\n for (const part of parts) {\n if (part.type === 'integer') digits += part.value\n if (part.type === 'integer' || part.type === 'fraction') last = part\n }\n // Four digits or more: a thousand times smaller, with the next suffix\n // (so 999 950 rounds up to \"1M\", not \"1000K\").\n if (digits.length < 4 || exp >= symbols.length) {\n if (exp && last) last.value += symbols[exp - 1]\n return parts.map((part) => part.value).join('')\n }\n }\n }\n}\n\n/** Whether number options write compact numbers (\"25K\"). */\nconst compactOf = (o: NumberFormatOptions): boolean =>\n o.notation === 'compact' || !!o.compactSymbols\n\n/** Whether number options set their digits (fraction or significant). */\nconst digitsOf = (o: Intl.NumberFormatOptions): boolean =>\n (o.minimumFractionDigits ??\n o.maximumFractionDigits ??\n o.minimumSignificantDigits ??\n o.maximumSignificantDigits) !== undefined\n\n/**\n * A formatter for values read one at a time (tooltips, data tables) in an\n * axis format. Compact notation suits ticks (\"$25K\") but hides the\n * difference between values: unless the format sets its own precision, it\n * keeps three significant digits (\"$24.8K\").\n */\nexport function formatDetail(format?: NumberFormat, locale?: Locale): (value: number) => string {\n return formatNumber(\n typeof format === 'object' && compactOf(format) && !digitsOf(format)\n ? { ...format, maximumSignificantDigits: 3 }\n : format,\n locale,\n )\n}\n/**\n * Number of fraction digits needed to tell apart ticks `step` apart,\n * e.g. `1 → 0`, `0.2 → 1`, `0.05 → 2`.\n */\nexport function stepPrecision(step: number): number {\n const abs = Math.abs(step)\n if (!Number.isFinite(abs) || abs === 0) return 0\n return Math.max(0, -Math.floor(Math.log10(abs) + 1e-9))\n}\n\nfunction hasPrecision(options: NumberFormatOptions): boolean {\n return (\n digitsOf(options) || !!options.compactSymbols || (options.notation ?? 'standard') !== 'standard'\n )\n}\n/**\n * Create a formatter for axis ticks `step` apart. Unless `format` sets its\n * own precision, every tick gets the same number of fraction digits, derived\n * from the step (`0, 0.5, 1` → `0.0, 0.5, 1.0`).\n */\nexport function formatTicks(\n step: number,\n format?: NumberFormat,\n locale?: Locale,\n): (value: number) => string {\n if (typeof format === 'function') return format\n const options = format ?? {}\n if (hasPrecision(options)) return formatNumber(options, locale)\n\n let digits = stepPrecision(step)\n if (options.style === 'percent') digits = Math.max(0, digits - 2)\n const fmt = formatNumber(\n { ...options, minimumFractionDigits: digits, maximumFractionDigits: digits },\n locale,\n )\n // Values within floating point noise of zero (e.g. 1e-17) print as zero.\n const epsilon = Math.abs(step) * 1e-9\n return (value) => fmt(Math.abs(value) < epsilon ? 0 : value)\n}\n\n/**\n * Create a date formatter accepting `Date` objects or timestamps.\n *\n * ```ts\n * formatDate({ month: 'short', day: 'numeric' }, 'en-US')(new Date(2026, 0, 5)) // \"Jan 5\"\n * ```\n */\nexport function formatDate(format?: DateFormat, locale?: Locale): (value: Date | number) => string {\n if (typeof format === 'function') {\n return (value) => format(typeof value === 'number' ? new Date(value) : value)\n }\n const df = getDateFormat(locale, format)\n return (value) => df.format(value)\n}\n","const E10 = Math.sqrt(50)\nconst E5 = Math.sqrt(10)\nconst E2 = Math.sqrt(2)\n\n/**\n * Integer tick indices `[i1, i2]` and an increment `inc`. A negative `inc`\n * means \"divide by -inc\", which keeps decimal ticks exact (0.3, not\n * 0.30000000000000004).\n */\nfunction tickSpec(start: number, stop: number, count: number): [number, number, number] {\n const step = (stop - start) / Math.max(0, count)\n const power = Math.floor(Math.log10(step))\n const error = step / 10 ** power\n const factor = error >= E10 ? 10 : error >= E5 ? 5 : error >= E2 ? 2 : 1\n let i1: number\n let i2: number\n let inc: number\n if (power < 0) {\n inc = 10 ** -power / factor\n i1 = Math.round(start * inc)\n i2 = Math.round(stop * inc)\n if (i1 / inc < start) ++i1\n if (i2 / inc > stop) --i2\n inc = -inc\n } else {\n inc = 10 ** power * factor\n i1 = Math.round(start / inc)\n i2 = Math.round(stop / inc)\n if (i1 * inc < start) ++i1\n if (i2 * inc > stop) --i2\n }\n if (i2 < i1 && count >= 0.5 && count < 2) return tickSpec(start, stop, count * 2)\n return [i1, i2, inc]\n}\n\n/**\n * Roughly `count` evenly spaced, \"nice\" values (multiples of 1, 2 or 5 × 10ⁿ)\n * between `start` and `stop`, inclusive. Order follows `start → stop`.\n */\nexport function ticks(start: number, stop: number, count = 5): number[] {\n if (!(count > 0) || !Number.isFinite(start) || !Number.isFinite(stop)) return []\n if (start === stop) return [start]\n const reverse = stop < start\n const [i1, i2, inc] = reverse ? tickSpec(stop, start, count) : tickSpec(start, stop, count)\n if (!(i2 >= i1)) return []\n const n = i2 - i1 + 1\n const out = new Array<number>(n)\n for (let i = 0; i < n; i++) {\n const index = reverse ? i2 - i : i1 + i\n out[i] = inc < 0 ? index / -inc : index * inc\n }\n return out\n}\n\n/**\n * Signed tick increment: positive values are the step, negative values `-k`\n * mean a step of `1 / k`.\n */\nexport function tickIncrement(start: number, stop: number, count: number): number {\n return tickSpec(start, stop, count)[2]\n}\n\n/** Distance between ticks produced by {@link ticks} for the same arguments. */\nexport function tickStep(start: number, stop: number, count = 5): number {\n const reverse = stop < start\n const inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count)\n return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc)\n}\n\n/**\n * Extend `[start, stop]` to round tick values, e.g. `[0.2, 9.7] → [0, 10]`.\n * Iterates because rounding can change the ideal step; if the step does not\n * settle (e.g. very low `count` around zero keeps doubling the domain), the\n * domain is returned unchanged, matching d3.\n */\nexport function niceDomain(start: number, stop: number, count = 5): [number, number] {\n if (!Number.isFinite(start) || !Number.isFinite(stop) || start === stop || !(count > 0)) {\n return [start, stop]\n }\n const reverse = stop < start\n let lo = reverse ? stop : start\n let hi = reverse ? start : stop\n let prev: number | undefined\n for (let i = 0; i < 10; i++) {\n const step = tickIncrement(lo, hi, count)\n if (step === prev) return reverse ? [hi, lo] : [lo, hi]\n if (step > 0) {\n lo = Math.floor(lo / step) * step\n hi = Math.ceil(hi / step) * step\n } else if (step < 0) {\n lo = Math.ceil(lo * step) / step\n hi = Math.floor(hi * step) / step\n } else {\n break\n }\n prev = step\n }\n return [start, stop]\n}\n","import { formatTicks, type Locale, type NumberFormat } from '../format.ts'\nimport { estimateTextWidth, LINE_HEIGHT, type Rect, round } from '../layout.ts'\nimport type { BandKey, BandScale } from '../scales/band.ts'\nimport type { LinearScale } from '../scales/linear.ts'\nimport { tickStep } from '../scales/ticks.ts'\nimport { h, type VNode } from '../vnode.ts'\n\nexport type AxisPosition = 'top' | 'right' | 'bottom' | 'left'\n\n/** A single axis tick: its data value, pixel position along the axis and label. */\nexport interface Tick {\n value: number | BandKey\n position: number\n label: string\n}\n\nexport interface LinearTicksOptions {\n /** Approximate number of ticks. Defaults to `5`. */\n count?: number\n format?: NumberFormat\n locale?: Locale\n}\n\n/** Ticks for a linear scale, labelled with a shared precision. */\nexport function linearTicks(scale: LinearScale, options: LinearTicksOptions = {}): Tick[] {\n const { count = 5, format, locale } = options\n const [d0, d1] = scale.domain\n const fmt = formatTicks(tickStep(d0, d1, count), format, locale)\n return scale.ticks(count).map((value) => ({ value, position: scale(value), label: fmt(value) }))\n}\n\n/** Ticks at the center of every band. */\nexport function bandTicks(\n scale: BandScale,\n format: (key: BandKey, index: number) => string = String,\n): Tick[] {\n return scale.domain.map((key, i) => ({\n value: key,\n position: scale.at(i) + scale.bandwidth / 2,\n label: format(key, i),\n }))\n}\n\n/** Whether labels are laid out along x (horizontal axes). */\nconst isHorizontal = (position: AxisPosition): boolean =>\n position === 'top' || position === 'bottom'\n\n/**\n * Keep every n-th tick (smallest n) so labels do not overlap along the axis.\n * The first and the last tick are always kept: when the last one does not\n * land on the step, it replaces the last kept tick if they would collide.\n */\nexport function thinTicks(\n ticks: readonly Tick[],\n position: AxisPosition,\n fontSize: number,\n gap = 8,\n): Tick[] {\n if (ticks.length < 2) return ticks.slice()\n const size = (tick: Tick) =>\n isHorizontal(position) ? estimateTextWidth(tick.label, fontSize) : fontSize * LINE_HEIGHT\n const sizes = ticks.map(size)\n const fitsBetween = (i: number, j: number) =>\n Math.abs((ticks[j] as Tick).position - (ticks[i] as Tick).position) >=\n ((sizes[i] as number) + (sizes[j] as number)) / 2 + gap\n\n const last = ticks.length - 1\n // Start from the step the total label size demands, instead of trying every one.\n const span = Math.abs((ticks[last] as Tick).position - (ticks[0] as Tick).position)\n const total = sizes.reduce((sum, size) => sum + size + gap, 0)\n const first = span > 0 ? Math.max(1, Math.floor(total / span)) : last\n for (let step = first; step <= last; step++) {\n let fits = true\n for (let i = step; i <= last && fits; i += step) fits = fitsBetween(i - step, i)\n if (!fits) continue\n\n const kept: number[] = []\n for (let i = 0; i <= last; i += step) kept.push(i)\n const tail = kept[kept.length - 1] as number\n if (tail !== last) {\n if (fitsBetween(tail, last)) kept.push(last)\n else if (kept.length > 1 && fitsBetween(kept[kept.length - 2] as number, last))\n kept[kept.length - 1] = last\n }\n return kept.map((i) => ticks[i] as Tick)\n }\n return ticks.slice(0, 1)\n}\n\nexport interface AxisOptions {\n position: AxisPosition\n ticks: readonly Tick[]\n /** Plot area the axis is attached to. */\n area: Rect\n /** Length of tick marks. Defaults to `0` (labels only). */\n tickSize?: number\n /** Distance between tick marks and labels. Defaults to `8`. */\n tickPadding?: number\n /** Draw the axis line along the plot edge. Defaults to `false`. */\n line?: boolean\n}\n\n/** Pixels an axis occupies perpendicular to the plot edge (for margins). */\nexport function axisSize(\n position: AxisPosition,\n ticks: readonly Tick[],\n fontSize: number,\n options: { tickSize?: number; tickPadding?: number } = {},\n): number {\n const { tickSize = 0, tickPadding = 8 } = options\n if (ticks.length === 0) return 0\n // Beside the plot, labels are as wide as their text: a little slack covers\n // fonts wider than the estimate, so they do not touch the chart's edge.\n const labels = isHorizontal(position)\n ? fontSize * LINE_HEIGHT\n : ticks.reduce((max, t) => Math.max(max, estimateTextWidth(t.label, fontSize)), 0) + 3\n return Math.ceil(labels + tickSize + tickPadding)\n}\n\n/**\n * Render an axis as `<g class=\"tc-axis tc-axis-{x|y} tc-axis-{position}\">`\n * with one `<g class=\"tc-tick\">` per tick, keyed by value so ticks can\n * transition when the scale changes.\n */\nexport function axis(options: AxisOptions): VNode {\n const { position, ticks, area, tickSize = 0, tickPadding = 8, line = false } = options\n const horizontal = isHorizontal(position)\n const sign = position === 'top' || position === 'left' ? -1 : 1\n const offset = sign * (tickSize + tickPadding)\n\n // Edge of the plot the axis sits on.\n const edge =\n position === 'top'\n ? area.y\n : position === 'bottom'\n ? area.y + area.height\n : position === 'left'\n ? area.x\n : area.x + area.width\n\n const label = horizontal\n ? { y: offset, dy: position === 'top' ? '0em' : '0.71em', 'text-anchor': 'middle' }\n : { x: offset, dy: '0.32em', 'text-anchor': position === 'left' ? 'end' : 'start' }\n\n const tickLine = horizontal ? { y2: sign * tickSize } : { x2: sign * tickSize }\n\n return h(\n 'g',\n {\n // Keyed, so an axis keeps its nodes when layers around it come and go.\n key: `axis-${position}`,\n class: ['tc-axis', horizontal ? 'tc-axis-x' : 'tc-axis-y', `tc-axis-${position}`],\n 'aria-hidden': 'true',\n },\n line &&\n h(\n 'line',\n horizontal\n ? { class: 'tc-axis-line', x1: area.x, x2: area.x + area.width, y1: edge, y2: edge }\n : { class: 'tc-axis-line', x1: edge, x2: edge, y1: area.y, y2: area.y + area.height },\n ),\n ticks.map((tick) =>\n h(\n 'g',\n {\n key: tick.value,\n class: 'tc-tick',\n // An inline style (not the transform attribute) so CSS can transition it.\n style: horizontal\n ? `transform:translate(${round(tick.position)}px,${round(edge)}px)`\n : `transform:translate(${round(edge)}px,${round(tick.position)}px)`,\n },\n tickSize > 0 && h('line', { class: 'tc-tick-line', ...tickLine }),\n h('text', { class: 'tc-tick-label', ...label }, tick.label),\n ),\n ),\n )\n}\n","import type { Rect } from '../layout.ts'\nimport { round } from '../layout.ts'\nimport { h, type VNode } from '../vnode.ts'\nimport type { Tick } from './axis.ts'\n\nexport interface GridOptions {\n /** `'y'` draws horizontal lines at y ticks, `'x'` vertical lines at x ticks. */\n direction: 'x' | 'y'\n ticks: readonly Tick[]\n area: Rect\n}\n\n/**\n * Render grid lines as `<g class=\"tc-grid tc-grid-{x|y}\">`. The line at\n * value `0` also gets `tc-grid-line-zero`, so the baseline can be emphasized.\n */\nexport function grid(options: GridOptions): VNode {\n const { direction, ticks, area } = options\n return h(\n 'g',\n { key: `grid-${direction}`, class: ['tc-grid', `tc-grid-${direction}`], 'aria-hidden': 'true' },\n ticks.map((tick) => {\n const p = round(tick.position)\n return h('line', {\n key: tick.value,\n class: ['tc-grid-line', tick.value === 0 && 'tc-grid-line-zero'],\n // Positioned with a transitionable transform, so lines glide when the scale changes.\n ...(direction === 'y'\n ? {\n x1: area.x,\n x2: area.x + area.width,\n y1: 0,\n y2: 0,\n style: `transform:translateY(${p}px)`,\n }\n : {\n x1: 0,\n x2: 0,\n y1: area.y,\n y2: area.y + area.height,\n style: `transform:translateX(${p}px)`,\n }),\n })\n }),\n )\n}\n","/** Category identifier used by band and point scales. */\nexport type BandKey = string | number\n\nexport interface BandScaleOptions {\n /** Share of each step left empty between bands, `0…1`. Defaults to `0`. */\n paddingInner?: number\n /** Space before the first and after the last band, in steps. Defaults to `0`. */\n paddingOuter?: number\n /** Where leftover space goes: `0` start, `0.5` center, `1` end. Defaults to `0.5`. */\n align?: number\n}\n\n/** Discrete scale splitting a range into equal bands, one per category. */\nexport interface BandScale {\n /** Start of the band for `key`, or `undefined` for unknown keys. */\n (key: BandKey): number | undefined\n readonly domain: readonly BandKey[]\n readonly range: readonly [number, number]\n /** Width of a single band. */\n readonly bandwidth: number\n /** Distance between the starts of adjacent bands. */\n readonly step: number\n /** Start of the band at `index`. */\n at(index: number): number\n /** Center of the band for `key`. */\n center(key: BandKey): number | undefined\n /** Index of the band nearest to `pixel` (for hit testing), or `-1` when empty. */\n indexAt(pixel: number): number\n}\n\n/**\n * Create a band scale, e.g. for bar charts.\n *\n * ```ts\n * const x = band(['Jan', 'Feb', 'Mar'], [0, 300], { paddingInner: 0.2 })\n * x('Feb') // start of the \"Feb\" band\n * x.bandwidth // bar width\n * ```\n */\nexport function band(\n domain: readonly BandKey[],\n range: readonly [number, number],\n options: BandScaleOptions = {},\n): BandScale {\n const { paddingInner = 0, paddingOuter = 0, align = 0.5 } = options\n const inner = Math.min(1, Math.max(0, paddingInner))\n const n = domain.length\n const [r0, r1] = range\n const reverse = r1 < r0\n const lo = reverse ? r1 : r0\n const hi = reverse ? r0 : r1\n\n const step = (hi - lo) / Math.max(1, n - inner + paddingOuter * 2)\n const start = lo + (hi - lo - step * (n - inner)) * align\n const bandwidth = step * (1 - inner)\n\n const index = new Map<BandKey, number>()\n for (let i = 0; i < n; i++) {\n const key = domain[i] as BandKey\n if (!index.has(key)) index.set(key, i)\n }\n\n const at = (i: number): number => start + step * (reverse ? n - 1 - i : i)\n\n const scale = (key: BandKey): number | undefined => {\n const i = index.get(key)\n return i === undefined ? undefined : at(i)\n }\n\n return Object.assign(scale, {\n domain: domain.slice(),\n range: [r0, r1] as const,\n bandwidth,\n step,\n at,\n center(key: BandKey): number | undefined {\n const px = scale(key)\n return px === undefined ? undefined : px + bandwidth / 2\n },\n indexAt(pixel: number): number {\n if (n === 0) return -1\n const raw = step === 0 ? 0 : Math.round((pixel - start - bandwidth / 2) / step)\n const i = Math.min(n - 1, Math.max(0, raw))\n return reverse ? n - 1 - i : i\n },\n })\n}\n\n/**\n * Create a point scale: a band scale with zero-width bands, placing each\n * category on a single point (e.g. line charts over labels).\n * `padding` is the space before the first and after the last point, in steps.\n */\nexport function point(\n domain: readonly BandKey[],\n range: readonly [number, number],\n options: { padding?: number; align?: number } = {},\n): BandScale {\n const { padding = 0, align } = options\n return band(domain, range, {\n paddingInner: 1,\n paddingOuter: padding,\n ...(align === undefined ? {} : { align }),\n })\n}\n","/**\n * Minimum and maximum of `values`, skipping `null`, `undefined` and\n * non-finite numbers. Returns `undefined` when nothing is left.\n */\nexport function extent(values: Iterable<number | null | undefined>): [number, number] | undefined {\n let min = Number.POSITIVE_INFINITY\n let max = Number.NEGATIVE_INFINITY\n for (const value of values) {\n if (value == null || !Number.isFinite(value)) continue\n if (value < min) min = value\n if (value > max) max = value\n }\n return min <= max ? [min, max] : undefined\n}\n","import { niceDomain, ticks } from './ticks.ts'\n\nexport interface LinearScaleOptions {\n /** Clamp output to the range (and `invert()` output to the domain). */\n clamp?: boolean\n}\n\n/** Continuous scale mapping a numeric domain to a pixel range. */\nexport interface LinearScale {\n (value: number): number\n readonly domain: readonly [number, number]\n readonly range: readonly [number, number]\n /** Map a pixel back to a domain value. */\n invert(pixel: number): number\n /** Nice tick values inside the domain. */\n ticks(count?: number): number[]\n /** A copy of the scale with its domain extended to round values. */\n nice(count?: number): LinearScale\n}\n\n/**\n * Create a linear scale.\n *\n * ```ts\n * const y = linear([0, 120], [300, 0]).nice()\n * y(60) // 150\n * ```\n *\n * A zero-width domain (e.g. a single data point) maps to the middle of the range.\n */\nexport function linear(\n domain: readonly [number, number],\n range: readonly [number, number],\n options: LinearScaleOptions = {},\n): LinearScale {\n const [d0, d1] = domain\n const [r0, r1] = range\n const span = d1 - d0\n const k = span === 0 ? 0 : (r1 - r0) / span\n const mid = (r0 + r1) / 2\n const { clamp = false } = options\n const rMin = Math.min(r0, r1)\n const rMax = Math.max(r0, r1)\n const dMin = Math.min(d0, d1)\n const dMax = Math.max(d0, d1)\n\n const scale = (value: number): number => {\n if (span === 0) return mid\n const px = r0 + (value - d0) * k\n return clamp ? Math.min(rMax, Math.max(rMin, px)) : px\n }\n\n return Object.assign(scale, {\n domain: [d0, d1] as const,\n range: [r0, r1] as const,\n invert(pixel: number): number {\n if (span === 0 || r1 === r0) return d0\n const value = d0 + (pixel - r0) / k\n return clamp ? Math.min(dMax, Math.max(dMin, value)) : value\n },\n ticks(count?: number): number[] {\n return ticks(d0, d1, count)\n },\n nice(count?: number): LinearScale {\n return linear(niceDomain(d0, d1, count), range, options)\n },\n })\n}\n","/**\n * Data from users, APIs and JSON is often not what the types say. Each chart\n * type cleans its data as it comes in, annotations as they render, axis bounds where read\n * (`ChartType.clean`): numbers\n * that are not finite become gaps, names become text, colors that are not\n * strings are dropped, and lists or records of the wrong kind are left out.\n * What is already clean keeps its identity, so large arrays are not copied.\n */\nimport type { Label } from './cartesian.ts'\n\ntype Rec = Record<string, unknown>\n\n/**\n * A number the chart can draw, or `null`: finite and at most 1e300 in size, so\n * spans stay finite; below 1e-300 it is 0, so tick steps do not underflow.\n */\nexport const finite = (v: unknown): number | null =>\n typeof v === 'number' && Math.abs(v) <= 1e300 ? (Math.abs(v) < 1e-300 ? 0 : v) : null\n\n/** A finite number, or `undefined` (an option left out). */\nconst optional = (v: unknown): number | undefined => finite(v) ?? undefined\n\nexport const isRecord = (v: unknown): v is Rec => !!v && typeof v === 'object' && !Array.isArray(v)\n\n/** The array, or an empty one. */\nexport const list = (v: unknown): readonly unknown[] => (Array.isArray(v) ? v : [])\n\n/** Strings as they are, finite numbers as digits, anything else as ''. */\nexport const text = (v: unknown): string =>\n typeof v === 'string' ? v : finite(v) === null ? '' : String(v)\n\n/** A category label: a string, a finite number or a valid date; else ''. */\nexport const label = (v: unknown): Label =>\n typeof v === 'string' || finite(v instanceof Date ? +v : v) !== null ? (v as Label) : ''\n\n/** Values with gaps for anything that is not a finite number (the same array when clean). */\nexport const numbers = (v: unknown): readonly (number | null)[] => {\n const values = list(v)\n return (\n values.every((x) => x == null || finite(x) === x) ? values : values.map(finite)\n ) as readonly (number | null)[]\n}\n\n/** The records of a list, each fixed by `fix`; other items are left out. */\nexport const records = <T>(v: unknown, fix: (r: Rec) => T): T[] => list(v).filter(isRecord).map(fix)\n\n/** What every named item has: text for its name, a string id and color. */\nexport const named = (r: Rec): Rec => ({\n ...r,\n name: text(r.name),\n id: typeof r.id === 'string' ? r.id : undefined,\n color: typeof r.color === 'string' ? r.color : undefined,\n})\n\n/** Labels and series of the cartesian types (line, area, bar, heatmap, radar). */\nexport const cleanSeries = (data: unknown): unknown => {\n const d = isRecord(data) ? data : {}\n return {\n ...d,\n labels: Array.isArray(d.labels) ? d.labels.map(label) : undefined,\n series: records(d.series, (s) => ({\n ...named(s),\n values: numbers(s.values),\n })),\n }\n}\n\n/** Options with their data cleaned by `data` (axis bounds are checked where they are read). */\nexport const cleanData =\n (data: (v: unknown) => unknown) =>\n <O>(options: O): O => ({ ...options, data: data((options as Rec).data) })\n\n/** Slices or rings: records with a finite value (0 when it is not). */\nexport const cleanItems = (data: unknown): unknown =>\n records(data, (r) => ({ ...named(r), value: finite(r.value) ?? 0, max: optional(r.max) }))\n","import type { LegendItem } from '../legend.ts'\nimport type { ClassValue, Props } from '../vnode.ts'\n\n/** What series, slices and rings have in common: a name, and how they look in a legend. */\nexport interface Named {\n name: string\n id?: string\n color?: string\n class?: ClassValue\n hidden?: boolean\n}\n\n/** Stable key of a series, slice or ring: its `id`, or its name. */\nexport const keyOf = (item: Named): string => item.id ?? item.name\n\n/** Legend entries for series, slices or rings, in their order (which is their color slot). */\nexport function legendItems(list: readonly Named[]): LegendItem[] {\n return list.map((entry, index) => {\n const item: LegendItem = { key: keyOf(entry), name: entry.name, index }\n if (entry.color) item.color = entry.color\n if (entry.hidden) item.hidden = true\n return item\n })\n}\n\n/** Attributes of the group of a series, slice or ring in color slot `index`. */\nexport function groupAttrs(item: Named, index: number): Props {\n return {\n key: keyOf(item),\n class: ['tc-series', `tc-series-${index + 1}`, item.class],\n 'data-series': item.name,\n // A map, so values from data cannot inject CSS (see normalizeStyle).\n style: { '--tc-series-color': item.color },\n }\n}\n","import type { DataTable, LegendItem, RenderContext } from '../chart.ts'\nimport { axis, axisSize, bandTicks, linearTicks, type Tick, thinTicks } from '../components/axis.ts'\nimport { grid } from '../components/grid.ts'\nimport { type Features, feature, features } from '../features.ts'\nimport { formatDetail, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n type Rect,\n} from '../layout.ts'\nimport { type BandKey, type BandScale, band, point } from '../scales/band.ts'\nimport { extent } from '../scales/extent.ts'\nimport { type LinearScale, linear } from '../scales/linear.ts'\nimport { niceDomain } from '../scales/ticks.ts'\nimport { type ClassValue, h, type Props, type VNode } from '../vnode.ts'\nimport type { Annotation } from './annotations.ts'\nimport { finite } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** Category label on the x axis. */\nexport type Label = string | number | Date\n\n/** A label as a `key` for keyed rendering (dates by their timestamp). */\nexport const labelKey = (label: Label): string | number =>\n label instanceof Date ? label.getTime() : label\n\n/** One data series. `null` values are gaps. */\nexport interface Series {\n /** Display name (legend, tooltip, accessibility). */\n name: string\n /** One value per label; `null`/`undefined` leaves a gap. */\n values: readonly (number | null | undefined)[]\n /** Stable identity for keyed updates. Defaults to `name`. */\n id?: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /**\n * Dashed line: dash and gap length in pixels, or a full `stroke-dasharray`\n * such as `'6 3'`. Sets `--tc-series-dash` on the series group; values\n * that could inject CSS are ignored, as for `color`.\n */\n dash?: number | string\n /** Line width in pixels; overrides `--tc-stroke-width` via `--tc-series-width`. */\n width?: number\n /**\n * In a `bar` chart, draw this series as a line or a filled area over the\n * bars instead (it is left out of stacks). Needs the line module\n * (`@tabler/charts/line`, or `@tabler/charts`). Defaults to `'bar'`.\n */\n type?: 'bar' | 'line' | 'area'\n /** Extra classes on the series group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface CartesianData {\n /** Categories along x. Defaults to `1…n` for the longest series. */\n labels?: readonly Label[]\n series: readonly Series[]\n}\n\n/** Options for the value (y) axis. */\nexport interface ValueAxisOptions {\n /** Render the axis labels. Defaults to `true`. */\n show?: boolean\n /** Render horizontal grid lines. Defaults to `true`. */\n grid?: boolean\n /** Fixed lower bound; overrides data and `zero`. */\n min?: number\n /** Fixed upper bound. */\n max?: number\n /** Include zero in the domain. */\n zero?: boolean\n /** Extend the domain to round tick values. Defaults to `true`. */\n nice?: boolean\n /** Approximate tick count. Defaults to one per ~60px of height. */\n ticks?: number\n format?: NumberFormat\n /** `'log'` for a logarithmic axis (positive values only). Defaults to `'linear'`. */\n scale?: 'linear' | 'log'\n}\n\n/** Options for the category (x) axis. */\nexport interface CategoryAxisOptions {\n /** Render the axis labels. Defaults to `true`. */\n show?: boolean\n /** Render vertical grid lines. Defaults to `false`. */\n grid?: boolean\n /** Draw the axis line along the bottom edge. Defaults to `false`. */\n line?: boolean\n /** Format a label for display (axis ticks for categories, tooltips and the table). */\n format?: (label: Label, index: number) => string\n /**\n * `'time'` treats labels as dates or timestamps: line and area charts place\n * points at their real distance in time, with calendar-aware ticks.\n * Labels must be in ascending order. Needs `@tabler/charts/time` (included\n * in `@tabler/charts`; candlesticks label dates without it). Defaults to `'category'`.\n */\n type?: 'category' | 'time'\n /** Align time ticks to UTC instead of local time (use it for SSR). */\n utc?: boolean\n}\n\nexport interface CartesianOptions {\n data: CartesianData\n y?: ValueAxisOptions\n x?: CategoryAxisOptions\n /** Reference lines and bands: targets, normal ranges, events and periods. */\n annotations?: readonly Annotation[]\n /** Extra space around the plot area, in pixels. */\n padding?: InsetsInput\n}\n\nexport interface CartesianLayoutOptions {\n /** `point` places categories on points (lines), `band` on bands (bars). */\n scale: 'point' | 'band'\n /** Values spanning the y domain, when they differ from the raw data (stacks). */\n values?: readonly (number | null | undefined)[]\n /** Format of the value axis ticks, when it differs from `y.format` (percent stacks). */\n tickFormat?: NumberFormat\n /** Default for `y.zero`. */\n zero: boolean\n /** Space marks need beyond the plot edge (point radius, stroke). */\n overhang?: number\n /** Band padding for `scale: 'band'`. */\n paddingInner?: number\n paddingOuter?: number\n}\n\nexport interface CartesianLayout {\n area: Rect\n labels: readonly Label[]\n /** Category scale (along x, or along y when `horizontal`). */\n x: BandScale\n /** Value scale (along y, or along x when `horizontal`). */\n y: LinearScale\n /** Whether categories run along y. */\n horizontal: boolean\n xTicks: Tick[]\n yTicks: Tick[]\n /** Grid lines, drawn below the marks. */\n background: VNode[]\n /** Axes, drawn above the marks. */\n foreground: VNode[]\n /** Clip path definition and its url, for the marks group. */\n clip: { def: VNode; url: string }\n}\n\nexport const TICK_SPACING = 60\n/** Horizontal value axes need more room per label. */\nexport const TICK_SPACING_X = 80\n/** Minimal margin around the plot, in pixels. */\nexport const EDGE = 8\n\n/** Stable key of a series: its `id`, or its name. */\nexport const seriesKey: (series: Series) => string = keyOf\n\n/** Legend entries for series-based charts. */\nexport const seriesLegend = (data: CartesianData): LegendItem[] => legendItems(data.series)\n\n/** Categories from `data.labels`, or `1…n` for the longest series. */\nexport function resolveLabels(data: CartesianData): Label[] {\n if (data.labels) return data.labels.slice()\n const n = Math.max(0, ...data.series.map((s) => s.values.length))\n return Array.from({ length: n }, (_, i) => i + 1)\n}\n\n/**\n * Whether a value can be plotted on the axis: finite, and positive on a log\n * scale (zero and negatives become gaps there).\n */\nexport function plottable(\n value: number | null | undefined,\n axis: ValueAxisOptions | undefined,\n): value is number {\n if (value == null || !Number.isFinite(value)) return false\n return axis?.scale !== 'log' || value > 0\n}\n\n/**\n * Whether the category axis carries time: `x.type === 'time'` and every label\n * is a date, a timestamp or a parseable string. Otherwise the axis falls back\n * to categories instead of producing NaN positions.\n */\nexport const isTimeAxis = (options: CartesianOptions): boolean =>\n options.x?.type === 'time' && resolveLabels(options.data).every((l) => Number.isFinite(toMs(l)))\n\n/** Formatter for category labels in tooltips and tables. */\nexport function labelFormatter(\n options: CartesianOptions,\n ctx: RenderContext,\n): (label: Label, index: number) => string {\n if (options.x?.format) return options.x.format\n if (!isTimeAxis(options)) return (label) => String(label)\n return feature('dates')(resolveLabels(options.data), options.x?.utc, ctx.locale)\n}\n\n/** A label as a timestamp: dates, numbers, or parseable strings (ISO); `NaN` otherwise. */\n// Through Date, so timestamps out of its range are NaN too.\nexport const toMs = (label: Label): number => new Date(label).getTime()\n\n/** Value scale for a domain: linear, or logarithmic with positive-only ticks. */\nexport function valueScale(\n domain: [number, number],\n range: [number, number],\n options: ValueAxisOptions,\n): LinearScale {\n return options.scale === 'log' ? feature('log').scale(domain, range) : linear(domain, range)\n}\n\n/** Ticks of a value scale with labels; log scales format each power as is. */\nexport function valueTicks(\n scale: LinearScale,\n options: ValueAxisOptions,\n count: number,\n format: NumberFormat | undefined,\n locale: RenderContext['locale'],\n): Tick[] {\n return options.scale === 'log'\n ? feature('log').ticks(scale, count, format, locale)\n : linearTicks(scale, { count, format, locale })\n}\n\n/** The point shapes of a chart (`shapes`, or with `patterns: true`), if it has them. */\nexport const markerShape = (options: object): NonNullable<Features['point-shapes']> | undefined => {\n const { shapes, patterns } = options as { shapes?: boolean; patterns?: unknown }\n // On the core, the shapes come with their module (like the points of line charts).\n return (shapes ?? patterns === true) ? features['point-shapes'] : undefined\n}\n\n/** The tick count asked for on an axis (a number up to 100), or `auto`. */\nexport const tickCount = (axis: { ticks?: number } | undefined, auto: number): number =>\n Math.min(finite(axis?.ticks) ?? auto, 100)\n\n/** Y domain from the data and axis options. */\nexport function valueDomain(\n data: CartesianData,\n options: ValueAxisOptions,\n zeroDefault: boolean,\n count: number,\n hidden: ReadonlySet<string> = new Set(),\n override?: readonly (number | null | undefined)[],\n extra: readonly number[] = [],\n): [number, number] {\n // (extra: values to include besides the data, e.g. annotation targets)\n const values =\n override ?? data.series.filter((s) => !hidden.has(seriesKey(s))).flatMap((s) => s.values)\n return domainOf(extra.length ? [...values, ...extra] : values, options, zeroDefault, count)\n}\n\n/** A niced numeric domain for `values`, honouring zero, min, max and nice. */\nexport function domainOf(\n values: readonly (number | null | undefined)[],\n options: ValueAxisOptions,\n zeroDefault: boolean,\n count: number,\n): [number, number] {\n if (options.scale === 'log') return feature('log').domain(values, options)\n // Bounds may come from outside: only numbers count.\n const min = finite(options.min)\n const max = finite(options.max)\n let [lo, hi] = extent(values) ?? [0, 1]\n if (options.zero ?? zeroDefault) {\n lo = Math.min(lo, 0)\n hi = Math.max(hi, 0)\n }\n if (lo === hi) {\n // A flat series still needs a visible range.\n if (lo === 0) {\n hi = 1\n } else {\n const pad = Math.abs(lo) * 0.1\n lo -= pad\n hi += pad\n }\n }\n if (min !== null) lo = min\n if (max !== null) hi = max\n if (options.nice !== false) {\n const [nlo, nhi] = niceDomain(lo, hi, count)\n if (min === null) lo = nlo\n if (max === null) hi = nhi\n }\n return [lo, hi]\n}\n\n/** The annotations feature, when the chart has annotations (it then must be registered). */\nexport function notesFeature(\n options: CartesianOptions,\n): NonNullable<Features['annotations']> | undefined {\n return options.annotations?.length ? feature('annotations') : undefined\n}\n\n/**\n * The category axis of a cartesian layout: the labels at its edges (for the\n * margins), its scale over a pixel range, and its ticks on that scale.\n */\nexport interface CategoryAxis {\n edges: readonly string[]\n scale(range: [number, number]): BandScale\n ticks(scale: BandScale): Tick[]\n /** Pixel position of a date, on time axes (after `scale()`). */\n readonly time?: ((date: Date) => number) | undefined\n}\n\n/**\n * The value axis of a cartesian layout, before the plot area is known: its\n * scale over a pixel range, the ticks of that scale, and `probe`, ticks to\n * measure the labels with (their positions mean nothing). `auto` is the\n * tick count the plot has room for, unless the axis asks for its own.\n */\nexport function valueAxis(\n options: CartesianOptions,\n ctx: RenderContext,\n layout: CartesianLayoutOptions,\n auto: number,\n): {\n scale(range: [number, number]): LinearScale\n ticks(scale: LinearScale): Tick[]\n probe: Tick[]\n} {\n const axis = options.y ?? {}\n const count = tickCount(axis, Math.max(2, auto))\n const domain = valueDomain(\n options.data,\n axis,\n layout.zero,\n count,\n ctx.hidden,\n layout.values,\n notesFeature(options)?.values(options.annotations),\n )\n const format = layout.tickFormat ?? axis.format\n const scale = (range: [number, number]) => valueScale(domain, range, axis)\n const ticks = (of: LinearScale) => valueTicks(of, axis, count, format, ctx.locale)\n return { scale, ticks, probe: ticks(scale([0, 1])) }\n}\n\n/**\n * Finish a layout that has its plot area, scales and ticks with what is\n * drawn around the marks: grid lines and annotation bands below them,\n * annotation lines and the axes above. Values run along y and categories\n * along x, or the other way round when `horizontal`.\n */\nexport function finishLayout(\n options: CartesianOptions,\n ctx: RenderContext,\n overhang: number,\n plot: Omit<CartesianLayout, 'background' | 'foreground' | 'clip'>,\n keys: readonly BandKey[],\n time?: (date: Date) => number,\n): CartesianLayout {\n const { area, x, y, xTicks, yTicks, horizontal: flip } = plot\n const xOptions = options.x ?? {}\n // Annotations: bands under the series, lines above them (and below the axes).\n const notes = notesFeature(options)?.layers(options.annotations, {\n area,\n horizontal: flip,\n fontSize: ctx.fontSize,\n value: y,\n band: x,\n keys,\n time,\n })\n const values = options.y?.show !== false && [\n axis({ position: flip ? 'bottom' : 'left', ticks: yTicks, area }),\n ]\n const categories = ((xOptions.show !== false && plot.labels.length > 0) || xOptions.line) && [\n axis({ position: flip ? 'left' : 'bottom', ticks: xTicks, area, line: xOptions.line === true }),\n ]\n const present = (parts: (VNode | VNode[] | null | false | undefined)[]): VNode[] =>\n parts.flatMap((part) => part || [])\n return {\n ...plot,\n background: present([\n options.y?.grid !== false && grid({ direction: flip ? 'x' : 'y', ticks: yTicks, area }),\n xOptions.grid && grid({ direction: flip ? 'y' : 'x', ticks: xTicks, area }),\n notes?.under,\n ]),\n // The axis on the left first, then the one at the bottom.\n foreground: present([notes?.over, flip ? categories : values, flip ? values : categories]),\n clip: plotClip(ctx, area, overhang),\n }\n}\n\n/** Compute scales, ticks, grid and axes shared by line, area and bar charts. */\nexport function cartesianLayout(\n options: CartesianOptions,\n ctx: RenderContext,\n layout: CartesianLayoutOptions,\n): CartesianLayout {\n const { data } = options\n const yOptions = options.y ?? {}\n const xOptions = options.x ?? {}\n const { fontSize, locale, width, height } = ctx\n const overhang = layout.overhang ?? 0\n const pad = insets(options.padding)\n const labels = resolveLabels(data)\n const format = labelFormatter(options, ctx)\n const showY = yOptions.show !== false\n const showX = xOptions.show !== false && labels.length > 0\n const timed = isTimeAxis(options) && layout.scale === 'point'\n\n const value = valueAxis(options, ctx, layout, Math.round(height / TICK_SPACING))\n const probeY = value.probe\n const countX = Math.max(2, Math.round(width / TICK_SPACING_X))\n const keys = labels.map(labelKey)\n const labelAt = (i: number) => format(labels[i] as Label, i)\n // Time axes (from the time module) place points by date, with calendar ticks.\n const xAxis: CategoryAxis = timed\n ? feature('time').axis(labels, keys, xOptions, countX, locale)\n : {\n // No labels, no edges: a custom format is not asked about a label that is not there.\n edges: labels.length ? [labelAt(0), labelAt(labels.length - 1)] : [],\n scale: (range) =>\n layout.scale === 'point'\n ? point(keys, range)\n : band(keys, range, {\n paddingInner: layout.paddingInner ?? 0.3,\n paddingOuter: layout.paddingOuter ?? 0.15,\n }),\n ticks: (scale) => bandTicks(scale, (_: BandKey, i) => labelAt(i)),\n }\n const edgeLabels = xAxis.edges\n\n // Margins: labels outside the plot, half a line above the top tick,\n // half of the first/last x label for point scales.\n const halfLine = Math.ceil((fontSize * LINE_HEIGHT) / 2)\n const firstLabel = showX ? estimateTextWidth(edgeLabels[0] ?? '', fontSize) : 0\n const lastLabel = showX ? estimateTextWidth(edgeLabels[edgeLabels.length - 1] ?? '', fontSize) : 0\n const edgeX = layout.scale === 'point'\n // On bands a label is centered half a step from the edge: only what is wider\n // than that needs margin (long labels on narrow bands, e.g. dates on candles).\n // The step depends on the margins, so they are worked out twice.\n const valueWidth = showY ? axisSize('left', probeY, fontSize) : 0\n const side = (halfStep: number) => {\n const overflow = (label: number) =>\n edgeX ? Math.ceil(label / 2) : Math.max(0, Math.ceil(label / 2 - halfStep))\n return {\n right: pad.right + Math.max(overflow(lastLabel), overhang, EDGE),\n left: pad.left + Math.max(valueWidth, overflow(firstLabel), overhang, showY ? 0 : EDGE),\n }\n }\n const steps = Math.max(1, labels.length) * 2\n let sides = side((width - pad.left - pad.right - valueWidth) / steps)\n if (!edgeX) sides = side((width - sides.left - sides.right) / steps)\n const margins = {\n top: pad.top + Math.max(showY ? halfLine : 0, overhang, EDGE / 2),\n bottom:\n pad.bottom +\n Math.max(\n // Without an x axis, the lowest value label still needs half a line.\n showX ? axisSize('bottom', [probeY[0] as Tick], fontSize) : showY ? halfLine : 0,\n overhang,\n EDGE / 2,\n ),\n ...sides,\n }\n const area = innerRect(width, height, margins)\n\n const x = xAxis.scale([area.x, area.x + area.width])\n const y = value.scale([area.y + area.height, area.y])\n\n // Nice ticks can outnumber the count asked for: on a short plot, thin them\n // like category labels so none overlap (the grid follows the ticks kept).\n const yTicks = thinTicks(value.ticks(y), 'left', fontSize, 4)\n const xTicks = showX ? thinTicks(xAxis.ticks(x), 'bottom', fontSize) : []\n\n return finishLayout(\n options,\n ctx,\n overhang,\n { area, labels, x, y, horizontal: false, xTicks, yTicks },\n keys,\n xAxis.time,\n )\n}\n\n/** Clip path around the plot area, a little larger so strokes and dots are not cut. */\nexport function plotClip(\n ctx: RenderContext,\n area: Rect,\n overhang: number,\n): CartesianLayout['clip'] {\n const clipId = `${ctx.id}-clip`\n const bleed = overhang + 1\n return {\n def: h(\n 'clipPath',\n { id: clipId },\n h('rect', {\n x: area.x - bleed,\n y: area.y - bleed,\n width: area.width + bleed * 2,\n height: area.height + bleed * 2,\n }),\n ),\n url: `url(#${clipId})`,\n }\n}\n\n/** Attributes shared by every series group. */\nexport function seriesAttrs(series: Series, index: number): Props {\n const { dash, width } = series\n return {\n ...groupAttrs(series, index),\n // A map, so values from data cannot inject CSS (see normalizeStyle).\n style: {\n '--tc-series-color': series.color,\n '--tc-series-dash': Number.isFinite(dash) ? `${dash}px` : dash,\n '--tc-series-width': Number.isFinite(width) ? `${width}px` : undefined,\n },\n }\n}\n\n/** Pixels around the plot area that still count as hovering it. */\nconst HOVER_SLOP = 8\n\n/**\n * Interaction by category: the nearest category to the pointer while it is\n * over the plot area, with every visible series' value there. `anchor`\n * places each value (line point, bar end, and the bar's box); `markAt` names the series of the\n * mark directly under the pointer, if the chart has distinct marks (bars).\n * Labels and values are formatted with `x.format` / `y.format` and the locale.\n */\nexport function categoryInteraction(\n layout: CartesianLayout,\n options: CartesianOptions,\n ctx: RenderContext,\n anchor: (\n seriesIndex: number,\n index: number,\n value: number,\n ) => { x: number; y: number; box?: Rect },\n markAt?: (x: number, y: number, index: number) => number | undefined,\n): Interaction {\n const { area, x, labels, horizontal } = layout\n const { data } = options\n const formatLabel = labelFormatter(options, ctx)\n const formatValue = formatDetail(options.y?.format, ctx.locale)\n\n const hitAt = (index: number): Hit => {\n const start = x.at(index)\n const center = start + x.bandwidth / 2\n const label = labels[index] as Label\n // Where a missing value is anchored: the category center on its axis.\n const empty = horizontal ? { x: area.x, y: center } : { x: center, y: null }\n const items: HitItem[] = []\n data.series.forEach((series, seriesIndex) => {\n if (ctx.hidden.has(seriesKey(series))) return\n const raw = series.values[index]\n const value = plottable(raw, options.y) ? raw : null\n const point = value === null ? empty : anchor(seriesIndex, index, value)\n const item: HitItem = {\n name: series.name,\n seriesIndex,\n value,\n text: value === null ? '–' : formatValue(value),\n ...point,\n }\n if (series.color) item.color = series.color\n items.push(item)\n })\n // Horizontal bars run the categories along y: the hit sits at the plot center on x.\n const hit: Hit = {\n index,\n label: labelKey(label),\n title: formatLabel(label, index),\n x: horizontal ? area.x + area.width / 2 : center,\n area,\n items,\n }\n if (horizontal) {\n hit.y = center\n hit.axis = 'y'\n }\n if (x.bandwidth > 0) {\n hit.band = horizontal\n ? { x: area.x, y: start, width: area.width, height: x.bandwidth }\n : { x: start, y: area.y, width: x.bandwidth, height: area.height }\n }\n return hit\n }\n\n return {\n count: labels.length,\n hitTest(px, py) {\n if (labels.length === 0) return null\n if (\n px < area.x - HOVER_SLOP ||\n px > area.x + area.width + HOVER_SLOP ||\n py < area.y - HOVER_SLOP ||\n py > area.y + area.height + HOVER_SLOP\n ) {\n return null\n }\n const index = x.indexAt(horizontal ? py : px)\n const hit = hitAt(index)\n const mark = markAt?.(px, py, index)\n if (mark !== undefined) hit.seriesIndex = mark\n return hit\n },\n hitIndex(index, seriesIndex) {\n if (index < 0 || index >= labels.length) return null\n const hit = hitAt(index)\n if (seriesIndex !== undefined && hit.items.some((item) => item.seriesIndex === seriesIndex)) {\n hit.seriesIndex = seriesIndex\n }\n return hit\n },\n }\n}\n\n/** Accessible table of series values: one row per category, one column per visible series. */\nexport function seriesTable(\n options: CartesianOptions,\n ctx: RenderContext,\n limit: number = Number.POSITIVE_INFINITY,\n): DataTable {\n const all = resolveLabels(options.data)\n const labels = all.length > limit ? all.slice(0, limit) : all\n const formatLabel = labelFormatter(options, ctx)\n const formatValue = formatDetail(options.y?.format, ctx.locale)\n const series = options.data.series.filter((s) => !ctx.hidden.has(seriesKey(s)))\n return {\n columns: ['', ...series.map((s) => s.name)],\n total: all.length,\n rows: labels.map((label, i) => [\n formatLabel(label, i),\n ...series.map((s) => {\n const v = s.values[i]\n return v == null || !Number.isFinite(v) ? '–' : formatValue(v)\n }),\n ]),\n }\n}\n","import { estimateTextWidth, type Rect, round } from '../layout.ts'\nimport type { BandKey, BandScale } from '../scales/band.ts'\nimport { type ClassValue, h, type VNode } from '../vnode.ts'\nimport { labelKey, toMs } from './cartesian.ts'\nimport { finite, label, records, text } from './clean.ts'\n\n/** A category label, a number, or a date (on a time axis). */\ntype AnnotationLabel = string | number | Date\n\n/**\n * A reference line or band drawn with the series: a target on the value\n * axis (`y: 99.9`), a normal range (`y: [40, 60]`), an event on the category\n * axis (`x: 'Jun'`, or a date on a time axis) or a period (`x: [from, to]`).\n */\nexport interface Annotation {\n /** A line at a value, or a band between two values, on the value axis. */\n y?: number | readonly [number, number]\n /** A line at a category (or a date on a time axis), or a band between two, on the category axis. */\n x?: AnnotationLabel | readonly [AnnotationLabel, AnnotationLabel]\n /** Short text next to the line or inside the band. */\n label?: string\n /** Where the label sits along the line or band. Defaults to `'end'` (right, or top). */\n position?: 'start' | 'end'\n /**\n * Any CSS color; sets `--tc-annotation-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the annotation group. */\n class?: ClassValue\n /** Stable identity for keyed updates. Defaults to the position in the list. */\n id?: string\n}\n\n/** How the layout maps data to pixels for annotations. */\nexport interface AnnotationScales {\n area: Rect\n /** Whether categories run along y (horizontal bars). */\n horizontal: boolean\n fontSize: number\n /** Pixel position of a value along the value axis. */\n value: (v: number) => number\n /** The category scale, and the keys of its categories in order. */\n band: BandScale\n keys: readonly BandKey[]\n /** Pixel position of a date, when the category axis is a time axis. */\n time?: ((date: Date) => number) | undefined\n}\n\n/** Pixel span of a category (or a date on a time axis), or `undefined` if it is not on the axis. */\nfunction categorySpan(\n scales: AnnotationScales,\n label: AnnotationLabel,\n): readonly [number, number] | undefined {\n if (scales.time) {\n const p = scales.time(new Date(toMs(label)))\n return Number.isFinite(p) ? [p, p] : undefined\n }\n const i = scales.keys.indexOf(labelKey(label))\n return i < 0 ? undefined : [scales.band.at(i), scales.band.at(i) + scales.band.bandwidth]\n}\n\n/** A value or a [from, to] pair, cleaned by `f`; `null` when anything is off. */\nconst span = <T>(v: unknown, f: (x: unknown) => T | null): T | readonly T[] | null => {\n if (!Array.isArray(v)) return f(v)\n const pair = v.map(f)\n return pair.length === 2 && !pair.includes(null) ? (pair as T[]) : null\n}\n\n/** Annotations from outside: lines or bands at finite values or labels, with text labels. */\nexport const cleanAnnotations = (v: unknown): Annotation[] | undefined =>\n v === undefined\n ? v\n : (records(v, (a) => ({\n ...a,\n y: a.y === undefined ? a.y : span(a.y, finite),\n x: a.x === undefined ? a.x : span(a.x, label),\n label: a.label == null ? undefined : text(a.label),\n color: typeof a.color === 'string' ? a.color : undefined,\n })).filter((a) => a.y !== null && a.x !== null && (a.x ?? a.y) !== undefined) as Annotation[])\n\nconst isPair = <T>(v: T | readonly [T, T]): v is readonly [T, T] => Array.isArray(v)\n\n/** Values the value axis should include so every annotation shows. */\nexport function annotationValues(annotations: readonly Annotation[] | undefined): number[] {\n const out: number[] = []\n for (const a of cleanAnnotations(annotations) ?? []) {\n if (a.y === undefined) continue\n for (const v of isPair(a.y) ? a.y : [a.y]) if (Number.isFinite(v)) out.push(v)\n }\n return out\n}\n\n/**\n * Annotation layers: bands go below the series, lines and labels above\n * them. Annotations outside the plot area are skipped.\n */\nexport function annotationLayers(\n annotations: readonly Annotation[] | undefined,\n scales: AnnotationScales,\n): { under: VNode | null; over: VNode | null } {\n // Annotations may come from outside (thresholds from an API).\n annotations = cleanAnnotations(annotations)\n if (!annotations?.length) return { under: null, over: null }\n const { area, horizontal, fontSize } = scales\n const bands: VNode[] = []\n const lines: VNode[] = []\n // Plot edges: \"across\" is the axis the annotation spans, \"along\" the one it marks.\n const x0 = area.x\n const x1 = area.x + area.width\n const y0 = area.y\n const y1 = area.y + area.height\n const inside = (p: number, lo: number, hi: number) => p >= lo - 0.5 && p <= hi + 0.5\n const pad = 4\n /**\n * Where an annotation lands: the pixel span it covers within the plot, and\n * whether it runs across x (a vertical line); `undefined` when it is off\n * the plot or names nothing on the axes.\n */\n const geometry = (a: Annotation): { a0: number; a1: number; vertical: boolean } | undefined => {\n let span: readonly [number, number]\n let vertical: boolean\n if (a.y !== undefined) {\n const [from, to] = isPair(a.y) ? a.y : [a.y, a.y]\n if (!Number.isFinite(from) || !Number.isFinite(to)) return undefined\n span = [scales.value(from), scales.value(to)]\n vertical = horizontal\n } else if (a.x !== undefined) {\n const [from, to] = isPair(a.x) ? a.x : [a.x, a.x]\n const start = categorySpan(scales, from)\n const stop = categorySpan(scales, to)\n if (!start || !stop) return undefined\n // A single category: its center; a range: from the start of one to the end of the other.\n span = isPair(a.x)\n ? [Math.min(start[0], stop[0]), Math.max(start[1], stop[1])]\n : [(start[0] + start[1]) / 2, (start[0] + start[1]) / 2]\n vertical = !horizontal\n } else {\n return undefined\n }\n const lo = Math.min(span[0], span[1])\n const hi = Math.max(span[0], span[1])\n const [min, max] = vertical ? [x0, x1] : [y0, y1]\n if (!inside(lo, min, max) && !inside(hi, min, max) && !(lo < min && hi > max)) return undefined\n return { a0: Math.max(lo, min), a1: Math.min(hi, max), vertical }\n }\n const shapes = annotations.map(geometry)\n\n type Box = [number, number, number, number]\n /** Boxes labels keep clear of: the labels placed so far, and every line. */\n const placed: Box[] = []\n const obstacles: [number, Box][] = []\n shapes.forEach((g, i) => {\n if (!g || g.a1 - g.a0 > 0.5) return\n const at = g.a0\n obstacles.push([i, g.vertical ? [at - 1.5, y0, at + 1.5, y1] : [x0, at - 1.5, x1, at + 1.5]])\n })\n const apart = (box: Box, [l, t, r, b]: Box) =>\n box[2] <= l || box[0] >= r || box[3] <= t || box[1] >= b\n const clearOfLabels = (box: Box) => placed.every((p) => apart(box, p))\n const clear = (box: Box, own: number) =>\n clearOfLabels(box) && obstacles.every(([i, l]) => i === own || apart(box, l))\n\n annotations.forEach((a, index) => {\n const key = a.id ?? index\n // Groups are named by axis; the line, band and label inside by what they are.\n const attrs = (part?: string) => ({\n key: part ? `${key}-${part}` : key,\n class: ['tc-annotation', a.y !== undefined ? 'tc-annotation-y' : 'tc-annotation-x', a.class],\n style: { '--tc-annotation-color': a.color },\n })\n const end = a.position !== 'start'\n\n const shape = shapes[index]\n if (!shape) return\n const { a0, a1, vertical } = shape\n\n // Label: candidate spots in order of preference, inside the plot area; the\n // first that covers neither an earlier label nor another line wins (or the first one).\n let label: VNode | false | undefined\n if (a.label) {\n const w = estimateTextWidth(a.label, fontSize * 0.92)\n const line = a1 - a0 <= 0.5\n // [left edge, baseline] of each spot.\n const spots: [number, number][] = []\n if (vertical) {\n // Beside a line or at the start of a band; on the other side if it would\n // run out, and then on the other side anyway, stepping along the line.\n const after = a0 + pad\n const before = line ? a0 - pad - w : Math.max(x0, a1 - pad - w)\n const sides = after + w <= x1 ? [after, before] : [before, after]\n const top = end ? y0 + fontSize : y1 - pad\n const step = (end ? 1 : -1) * fontSize * 1.2\n for (const x of sides) {\n if (x < x0 || x + w > x1) continue\n for (let k = 0; k < 3; k++) spots.push([x, top + k * step])\n }\n if (!spots.length) spots.push([Math.max(x0 + pad, sides[0] as number), top])\n } else {\n // At the preferred end above or below, then at the other end.\n const near = end ? x1 - pad - w : x0 + pad\n const far = end ? x0 + pad : x1 - pad - w\n for (const x of [near, far]) {\n if (line) spots.push([x, a0 - pad], [x, a0 + fontSize])\n else spots.push([x, a0 + fontSize], [x, a1 - pad])\n }\n }\n const box = ([x, y]: [number, number]): Box => [x, y - fontSize, x + w, y + fontSize * 0.25]\n // Nothing free: at least keep off the other labels; a line through text reads better than text on text.\n const spot =\n spots.find((s) => clear(box(s), index)) ??\n spots.find((s) => clearOfLabels(box(s))) ??\n (spots[0] as [number, number])\n placed.push(box(spot))\n label = h(\n 'text',\n { class: 'tc-annotation-label', x: round(spot[0]), y: round(spot[1]) },\n a.label,\n )\n }\n\n if (a1 - a0 > 0.5) {\n // A band below the series; its label goes with the lines, above them.\n const d = vertical\n ? `M${round(a0)},${round(y0)}H${round(a1)}V${round(y1)}H${round(a0)}Z`\n : `M${round(x0)},${round(a0)}H${round(x1)}V${round(a1)}H${round(x0)}Z`\n bands.push(h('g', attrs(), h('path', { class: 'tc-annotation-band', d })))\n if (label) lines.push(h('g', attrs('label'), label))\n return\n }\n // A line across the plot area.\n const at = round(a0)\n lines.push(\n h(\n 'g',\n attrs(),\n h(\n 'line',\n vertical\n ? { class: 'tc-annotation-line', x1: at, x2: at, y1: round(y0), y2: round(y1) }\n : { class: 'tc-annotation-line', x1: round(x0), x2: round(x1), y1: at, y2: at },\n ),\n label,\n ),\n )\n })\n\n return {\n under: bands.length\n ? h('g', { key: 'annotations-under', class: 'tc-annotations', 'aria-hidden': 'true' }, bands)\n : null,\n over: lines.length\n ? h('g', { key: 'annotations-over', class: 'tc-annotations', 'aria-hidden': 'true' }, lines)\n : null,\n }\n}\n","import type { Locale } from '../format.ts'\nimport { formatDate } from '../format.ts'\nimport { type Label, toMs } from './cartesian.ts'\n\n/**\n * Formatter for date labels on a time axis (tooltips, tables, band axes):\n * the date, with the time of day when the labels span less than a few days.\n */\nexport function dateLabels(\n labels: readonly Label[],\n utc: boolean | undefined,\n locale: Locale,\n): (label: Label) => string {\n const first = labels[0]\n const last = labels[labels.length - 1]\n const span = first !== undefined && last !== undefined ? Math.abs(toMs(last) - toMs(first)) : 0\n const withTime = span > 0 && span < 3 * 24 * 60 * 60 * 1000\n const fmt = formatDate(\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n ...(withTime ? { hour: 'numeric', minute: '2-digit' } : {}),\n ...(utc ? { timeZone: 'UTC' } : {}),\n },\n locale,\n )\n return (label) => (Number.isFinite(toMs(label)) ? fmt(toMs(label)) : String(label))\n}\n","import type { LinearScale, LinearScaleOptions } from './linear.ts'\n\nexport interface LogScaleOptions extends LinearScaleOptions {\n /** Logarithm base. Defaults to `10`. */\n base?: number\n}\n\n/**\n * Create a logarithmic scale. The domain must not cross zero: both ends\n * positive (or both negative, mirrored). Same interface as {@link linear},\n * so layouts can use either.\n *\n * ```ts\n * const y = log([1, 10000], [300, 0])\n * y.ticks() // 1, 10, 100, 1000, 10000\n * ```\n */\nexport function log(\n domain: readonly [number, number],\n range: readonly [number, number],\n options: LogScaleOptions = {},\n): LinearScale {\n const base = options.base && options.base > 1 ? options.base : 10\n const clamp = options.clamp === true\n const negative = domain[0] < 0 || domain[1] < 0\n const sign = negative ? -1 : 1\n // Values at or below zero cannot be shown; treat them as the smallest positive step.\n const safe = (v: number): number => Math.max(Number.MIN_VALUE, v * sign)\n const ln = Math.log(base)\n // Exact for the common bases, so powers map to whole numbers.\n const logBase =\n base === 10 ? Math.log10 : base === 2 ? Math.log2 : (v: number) => Math.log(v) / ln\n const transform = (v: number): number => logBase(safe(v))\n const untransform = (t: number): number => sign * base ** t\n const t0 = transform(domain[0])\n const t1 = transform(domain[1])\n const [r0, r1] = range\n const span = t1 - t0\n const k = span === 0 ? 0 : (r1 - r0) / span\n const rMin = Math.min(r0, r1)\n const rMax = Math.max(r0, r1)\n\n const scale = (value: number): number => {\n if (span === 0) return (r0 + r1) / 2\n const px = r0 + (transform(value) - t0) * k\n return clamp ? Math.min(rMax, Math.max(rMin, px)) : px\n }\n\n return Object.assign(scale, {\n domain: [domain[0], domain[1]] as const,\n range: [r0, r1] as const,\n invert(pixel: number): number {\n if (span === 0 || r1 === r0) return domain[0]\n return untransform(t0 + (pixel - r0) / k)\n },\n ticks(count = 5): number[] {\n const lo = Math.min(t0, t1)\n const hi = Math.max(t0, t1)\n if (!Number.isFinite(lo) || !Number.isFinite(hi)) return []\n const first = Math.floor(lo)\n const last = Math.ceil(hi)\n const decades = last - first\n const inside = (v: number) => {\n const t = transform(v)\n return t >= lo - 1e-9 && t <= hi + 1e-9\n }\n let out: number[] = []\n if (decades <= count && Number.isInteger(base)) {\n // Few decades: integer multiples inside each (1, 2, 3 … 9 × 10ⁿ), thinned when crowded.\n const at = (keep: (m: number) => boolean) => {\n const ticks: number[] = []\n for (let p = first; p <= last; p++) {\n for (let m = 1; m < base; m++) {\n const v = sign * m * base ** p\n if (keep(m) && inside(v)) ticks.push(v)\n }\n }\n return ticks\n }\n out = at(() => true)\n if (out.length > count * 2) out = at((m) => m === 1 || m === 2 || m === 5)\n if (out.length > count * 2) out = at((m) => m === 1)\n } else {\n // Many decades: one tick per power (or per few powers).\n const step = Math.max(1, Math.ceil(decades / Math.max(1, count)))\n for (let p = Math.ceil(lo / step) * step; p <= hi + 1e-9; p += step) {\n const v = sign * base ** p\n if (inside(v)) out.push(v)\n }\n }\n return t1 < t0 ? out.reverse() : out\n },\n nice(): LinearScale {\n const lo = untransform(Math.floor(Math.min(t0, t1)))\n const hi = untransform(Math.ceil(Math.max(t0, t1)))\n return log(t1 < t0 ? [hi, lo] : [lo, hi], range, options)\n },\n })\n}\n","import type { Tick } from '../components/axis.ts'\nimport { formatNumber, type Locale, type NumberFormat } from '../format.ts'\nimport { extent } from '../scales/extent.ts'\nimport type { LinearScale } from '../scales/linear.ts'\nimport { log } from '../scales/log.ts'\nimport type { ValueAxisOptions } from './cartesian.ts'\nimport { finite } from './clean.ts'\n\n/** Domain of a log axis: positive values only, niced to whole powers of ten. */\nexport function logDomain(\n values: readonly (number | null | undefined)[],\n options: ValueAxisOptions,\n): [number, number] {\n const positive = values.filter((v): v is number => v != null && v > 0 && Number.isFinite(v))\n let [lo, hi] = extent(positive) ?? [1, 10]\n // Bounds may come from outside: only positive numbers count.\n const min = finite(options.min)\n const max = finite(options.max)\n if (min !== null && min > 0) lo = min\n if (max !== null && max > 0) hi = max\n if (lo === hi) hi = lo * 10\n if (options.nice !== false) {\n const niced = log([lo, hi], [0, 1]).nice().domain\n if (min === null) lo = niced[0]\n if (max === null) hi = niced[1]\n }\n return [lo, hi]\n}\n\n/** Ticks of a log axis, each power formatted as is. */\nexport function logTicks(\n scale: LinearScale,\n count: number,\n format: NumberFormat | undefined,\n locale: Locale,\n): Tick[] {\n const fmt = formatNumber(format, locale)\n return scale.ticks(count).map((value) => ({ value, position: scale(value), label: fmt(value) }))\n}\n","import type { Rect } from './layout.ts'\n\n/** One series' value at a hovered position. */\nexport interface HitItem {\n /** Series name. */\n name: string\n /** Position of the series in `data.series`. */\n seriesIndex: number\n /** Custom series color, if one was set. */\n color?: string\n value: number | null\n /** Value formatted for display (tooltips). */\n text: string\n /** Anchor of the value in chart pixels (point, bar end); `y` is `null` for gaps. */\n x: number\n y: number | null\n /** The mark's rectangle (bar, segment, cell), for value labels inside it. */\n box?: Rect\n}\n\n/** What lies under the pointer. */\nexport interface Hit {\n /** Category index. */\n index: number\n /** Category label. */\n label: string | number\n /** Label formatted for display (tooltips). */\n title: string\n /** Anchor x of the category in chart pixels (for crosshairs and tooltips); the plot center for horizontal bars. */\n x: number\n /** Plot area, in chart pixels. */\n area: Rect\n /** Axis the categories run along; `'y'` for horizontal bars. Defaults to `'x'`. */\n axis?: 'x' | 'y'\n /** Center of the category along y, when categories run along y. */\n y?: number\n /** The category's band in chart pixels, for band scales (bars). */\n band?: { x: number; y: number; width: number; height: number }\n /** Every series' value at this category. */\n items: HitItem[]\n /** Series of the mark directly under the pointer (e.g. a bar), if any. */\n seriesIndex?: number\n /**\n * The crosshair segment, when it is not vertical across the plot (a radar\n * spoke). Tooltips from the keyboard then anchor on the value itself.\n */\n guide?: { x1: number; y1: number; x2: number; y2: number }\n /**\n * A shape to highlight instead of a crosshair or band (e.g. a halo around a\n * pie slice): path data `d`, drawn translated by `x` / `y`.\n */\n mark?: { d: string; x: number; y: number }\n}\n\n/** Maps a point in chart pixels to what lies there. */\nexport type HitTester = (x: number, y: number) => Hit | null\n\n/** How a rendered chart answers pointer and keyboard interaction. */\nexport interface Interaction {\n /** What lies at a point in chart pixels. */\n hitTest: HitTester\n /** The hit for a category by index (keyboard navigation), optionally focused on a series. */\n hitIndex(index: number, seriesIndex?: number): Hit | null\n /** Number of categories. */\n count: number\n}\n\n/** Identity of a hit, used to emit hover changes only when it changes. */\nexport function hitKey(hit: Hit | null): string {\n return hit ? `${hit.index}:${hit.seriesIndex ?? ''}` : ''\n}\n\n/**\n * Convert a pointer position to chart pixels, accounting for the SVG being\n * scaled by CSS (e.g. `max-width: 100%`).\n */\nexport function toChartPoint(\n svg: Element,\n clientX: number,\n clientY: number,\n width: number,\n height: number,\n): { x: number; y: number } {\n const rect = svg.getBoundingClientRect()\n const sx = rect.width > 0 ? width / rect.width : 1\n const sy = rect.height > 0 ? height / rect.height : 1\n return { x: (clientX - rect.left) * sx, y: (clientY - rect.top) * sy }\n}\n","import { h, type VNode } from './vnode.ts'\n\n/** One legend entry: a series (or a slice, for part-to-whole charts). */\nexport interface LegendItem {\n /** Stable identity, used to toggle it. */\n key: string\n name: string\n /** Color slot: the entry wears `.tc-series-{index + 1}`. */\n index: number\n /** Custom color overriding the slot. */\n color?: string\n /** Hidden by default (e.g. `series.hidden`). */\n hidden?: boolean\n}\n\nexport interface LegendOptions {\n /** Place the legend above or below the chart. Defaults to `'top'`. */\n position?: 'top' | 'bottom'\n}\n\n/**\n * Legend content: one toggle button per entry. Buttons are native, so they\n * are focusable and work with Enter/Space; `aria-pressed` reflects visibility.\n */\nexport function legendContent(items: readonly LegendItem[], hidden: ReadonlySet<string>): VNode {\n return h(\n 'div',\n { class: 'tc-legend-items' },\n items.map((item) => {\n const off = hidden.has(item.key)\n return h(\n 'button',\n {\n key: item.key,\n type: 'button',\n class: [\n 'tc-legend-item',\n 'tc-series',\n `tc-series-${item.index + 1}`,\n off && 'tc-legend-item-hidden',\n ],\n style: { '--tc-series-color': item.color },\n 'aria-pressed': off ? 'false' : 'true',\n 'data-key': item.key,\n },\n h('span', { class: 'tc-legend-swatch', 'aria-hidden': 'true' }),\n h('span', { class: 'tc-legend-name' }, item.name),\n )\n }),\n )\n}\n\n/** Keys hidden by default, from the entries' own `hidden` flags. */\nexport function defaultHidden(items: readonly LegendItem[]): Set<string> {\n return new Set(items.filter((item) => item.hidden).map((item) => item.key))\n}\n","/** Valid XML-ish tag and attribute names; anything else is skipped by renderers. */\nconst NAME_RE = /^[a-zA-Z_][\\w:.-]*$/\n\n/** Inline event handler attributes (`onclick`, `onLoad`…) are never rendered. */\nconst EVENT_RE = /^on/i\n\n/** Whether a tag name is safe to render. */\nexport function isValidTag(name: string): boolean {\n return NAME_RE.test(name)\n}\n\n/** Whether an attribute name is safe to render. */\nexport function isValidAttr(name: string): boolean {\n return NAME_RE.test(name) && !EVENT_RE.test(name)\n}\n","import { features } from '../features.ts'\nimport type { Attrs, Child, VNode } from '../vnode.ts'\nimport { isValidAttr, isValidTag } from './attrs.ts'\n\nexport const SVG_NS = 'http://www.w3.org/2000/svg'\nconst HTML_NS = 'http://www.w3.org/1999/xhtml'\n\n/** VNode each rendered DOM node was last patched with. */\nexport const rendered: WeakMap<Node, Child> = /* @__PURE__ */ new WeakMap<Node, Child>()\n\n/** Root element rendered into each container. */\nconst roots = /* @__PURE__ */ new WeakMap<Element, Element>()\n\n/**\n * Render a VNode tree into `container`.\n *\n * The first call mounts the tree; later calls patch the existing DOM in place,\n * reusing nodes matched by `key` (or by position for unkeyed children), so CSS\n * transitions on changed attributes keep working. Passing `null` unmounts.\n *\n * The rendered root is appended to `container`; other content of the\n * container is left untouched. On the first call, `replace` names an element\n * already in the container (e.g. server-rendered markup) for the root: when\n * it has the root's tag and `@tabler/charts/hydrate` is loaded (it is part\n * of `@tabler/charts`), its nodes are hydrated: reused and patched to the\n * tree, so nothing is re-created and entrance animations do not run again.\n * Otherwise the root takes its place.\n */\nexport function render(\n container: Element,\n vnode: VNode | null,\n replace?: Element | null,\n): Element | null {\n const prev = roots.get(container) ?? (replace?.parentNode === container ? replace : undefined)\n\n if (vnode === null || !isValidTag(vnode.tag)) {\n if (prev) {\n prev.remove()\n roots.delete(container)\n }\n return null\n }\n\n if (prev && canPatch(prev, vnode)) {\n patchElement(prev, vnode)\n roots.set(container, prev)\n return prev\n }\n\n if (prev && features.hydrate?.(prev, vnode, namespaceFor(container, vnode.tag))) {\n roots.set(container, prev)\n return prev\n }\n\n const el = createElement(vnode, namespaceFor(container, vnode.tag), container.ownerDocument)\n if (prev) prev.replaceWith(el)\n else container.appendChild(el)\n roots.set(container, el)\n return el\n}\n\nfunction namespaceFor(parent: Element, tag: string): string {\n if (tag === 'svg') return SVG_NS\n if (parent.namespaceURI === SVG_NS && parent.localName !== 'foreignObject') return SVG_NS\n return HTML_NS\n}\n\nexport function childNamespace(el: Element): string {\n return el.namespaceURI === SVG_NS && el.localName !== 'foreignObject' ? SVG_NS : HTML_NS\n}\n\nexport function createNode(child: Child, ns: string, doc: Document): Node | null {\n if (typeof child === 'string') {\n const text = doc.createTextNode(child)\n rendered.set(text, child)\n return text\n }\n if (!isValidTag(child.tag)) return null\n return createElement(child, child.tag === 'svg' ? SVG_NS : ns, doc)\n}\n\n/**\n * Styles go through the CSSOM: a strict CSP (`style-src` without\n * 'unsafe-inline') blocks style attributes set with setAttribute, not these.\n */\nfunction setAttr(el: Element, name: string, value: string): void {\n if (name === 'style') (el as HTMLElement).style.cssText = value\n else el.setAttribute(name, value)\n}\n\nfunction createElement(vnode: VNode, ns: string, doc: Document): Element {\n const el = doc.createElementNS(ns, vnode.tag)\n const { attrs } = vnode\n for (const name in attrs) {\n if (isValidAttr(name)) setAttr(el, name, String(attrs[name]))\n }\n const childNs = childNamespace(el)\n for (const child of vnode.children) {\n const node = createNode(child, childNs, doc)\n if (node) el.appendChild(node)\n }\n rendered.set(el, vnode)\n return el\n}\n\nfunction canPatch(node: Node, next: Child): boolean {\n const prev = rendered.get(node)\n if (prev === undefined) return false\n if (typeof next === 'string') return typeof prev === 'string'\n return typeof prev !== 'string' && prev.tag === next.tag && prev.key === next.key\n}\n\nfunction patchNode(node: Node, next: Child): void {\n if (typeof next === 'string') {\n if (rendered.get(node) !== next) {\n ;(node as Text).data = next\n rendered.set(node, next)\n }\n return\n }\n patchElement(node as Element, next)\n}\n\nfunction patchElement(el: Element, next: VNode): void {\n const prev = rendered.get(el) as VNode\n if (prev === next) return\n // An arc sweeps to its new angles, setting its `d` itself on the way: the\n // sweep feature then says what is left to patch.\n patchAttrs(el, prev.attrs, features.sweep?.(el, prev, next) ?? next.attrs, true)\n patchChildren(el, next.children)\n rendered.set(el, next)\n}\n\nexport function patchAttrs(el: Element, prev: Attrs, next: Attrs, update = false): void {\n for (const name in next) {\n const value = next[name] as string | number\n if (prev[name] === value || !isValidAttr(name)) continue\n // Where CSS cannot transition `d` (Safari), the morph feature animates it.\n if (update && name === 'd' && features.morph?.(el, String(prev[name] ?? ''), String(value))) {\n continue\n }\n setAttr(el, name, String(value))\n }\n for (const name in prev) {\n if (!(name in next) && isValidAttr(name)) el.removeAttribute(name)\n }\n}\n\nfunction patchChildren(parent: Element, next: Child[]): void {\n if (next.length === 0 && parent.firstChild === null) return\n\n const oldNodes = Array.from(parent.childNodes)\n const keyed = new Map<unknown, Node>()\n const unkeyed: Node[] = []\n\n for (const node of oldNodes) {\n const vnode = rendered.get(node)\n if (vnode === undefined) continue\n if (typeof vnode !== 'string' && vnode.key !== undefined) keyed.set(vnode.key, node)\n else unkeyed.push(node)\n }\n\n // Match new children against existing nodes.\n const matched = new Array<Node | undefined>(next.length)\n const used = new Set<Node>()\n let cursor = 0\n for (let i = 0; i < next.length; i++) {\n const child = next[i] as Child\n let candidate: Node | undefined\n if (typeof child !== 'string' && child.key !== undefined) {\n candidate = keyed.get(child.key)\n } else if (cursor < unkeyed.length) {\n candidate = unkeyed[cursor]\n }\n if (candidate && !used.has(candidate) && canPatch(candidate, child)) {\n matched[i] = candidate\n used.add(candidate)\n if (candidate === unkeyed[cursor]) cursor++\n }\n }\n\n // Remove unmatched nodes first, so placing the rest needs as few moves as possible.\n for (const node of oldNodes) {\n if (!used.has(node)) parent.removeChild(node)\n }\n\n // Patch or create, then place from the end using the next sibling as anchor.\n const ns = childNamespace(parent)\n const doc = parent.ownerDocument\n let anchor: Node | null = null\n for (let i = next.length - 1; i >= 0; i--) {\n const child = next[i] as Child\n let node = matched[i]\n if (node) {\n patchNode(node, child)\n } else {\n node = createNode(child, ns, doc) ?? undefined\n if (!node) continue\n }\n if (node.parentNode !== parent || node.nextSibling !== anchor) {\n parent.insertBefore(node, anchor)\n }\n anchor = node\n }\n}\n","import type { Child, VNode } from '../vnode.ts'\nimport { isValidAttr, isValidTag } from './attrs.ts'\n\nconst SVG_NS = 'http://www.w3.org/2000/svg'\n\nexport interface RenderToStringOptions {\n /**\n * Add `xmlns` to a root `<svg>` that has none, so the output is a valid\n * standalone `.svg` file. Defaults to `true`.\n */\n xmlns?: boolean\n /**\n * Markup context of the root. By default common HTML elements (`div`,\n * `table`, `button`…) render as HTML and everything else as SVG.\n */\n namespace?: 'svg' | 'html'\n}\n\n/** Root tags treated as HTML when no namespace is given. */\nconst HTML_ROOTS = /* @__PURE__ */ new Set([\n 'a',\n 'b',\n 'button',\n 'caption',\n 'div',\n 'em',\n 'i',\n 'label',\n 'li',\n 'ol',\n 'p',\n 'section',\n 'small',\n 'span',\n 'strong',\n 'table',\n 'tbody',\n 'td',\n 'th',\n 'thead',\n 'tr',\n 'ul',\n])\n\n/** HTML elements that never have content and must not get a closing tag. */\nconst VOID = /* @__PURE__ */ new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n])\n\n/**\n * Serialize a VNode tree to markup (SSR, static export): SVG trees as\n * XML-compatible SVG, HTML trees (legend, table, tooltip) as HTML.\n *\n * Empty elements self-close only inside SVG; in HTML they get an explicit\n * closing tag (`<th></th>`), since `<th/>` would open an element there.\n * Text and attribute values are escaped. Invalid tag or attribute names and\n * inline event handlers (`on*`) are dropped, so data coming from chart\n * options can never inject markup or scripts.\n */\nexport function renderToString(node: Child, options: RenderToStringOptions = {}): string {\n if (typeof node === 'string') return escapeText(node)\n const root =\n options.xmlns !== false && node.tag === 'svg' && node.attrs.xmlns === undefined\n ? { ...node, attrs: { xmlns: SVG_NS, ...node.attrs } }\n : node\n const svg = options.namespace ? options.namespace === 'svg' : !HTML_ROOTS.has(node.tag)\n return renderNode(root, svg)\n}\n\nfunction renderNode(node: VNode, parentInSvg: boolean): string {\n const { tag, attrs, children } = node\n if (!isValidTag(tag)) return ''\n const inSvg = parentInSvg || tag === 'svg'\n\n let out = `<${tag}`\n for (const name in attrs) {\n if (!isValidAttr(name)) continue\n out += ` ${name}=\"${escapeAttr(String(attrs[name]))}\"`\n }\n\n if (children.length === 0) {\n if (inSvg) return `${out}/>`\n if (VOID.has(tag.toLowerCase())) return `${out}>`\n }\n\n out += '>'\n // Content of foreignObject is HTML again.\n const childInSvg = inSvg && tag !== 'foreignObject'\n for (const child of children) {\n out += typeof child === 'string' ? escapeText(child) : renderNode(child, childInSvg)\n }\n return `${out}</${tag}>`\n}\n\nconst TEXT_RE = /[&<>]/\nconst ATTR_RE = /[&\"<>]/\nconst TEXT_RE_G = /[&<>]/g\nconst ATTR_RE_G = /[&\"<>]/g\nconst ENTITIES: Record<string, string> = { '&': '&', '<': '<', '>': '>', '\"': '"' }\nconst replaceEntity = (char: string): string => ENTITIES[char] as string\n\n/** Escape text content. */\nexport function escapeText(value: string): string {\n return TEXT_RE.test(value) ? value.replace(TEXT_RE_G, replaceEntity) : value\n}\n\n/** Escape a double-quoted attribute value. */\nexport function escapeAttr(value: string): string {\n return ATTR_RE.test(value) ? value.replace(ATTR_RE_G, replaceEntity) : value\n}\n","/** One `ResizeObserver` shared by every chart on the page. */\n\ntype Listener = (width: number, height: number) => void\n\nconst listeners = /* @__PURE__ */ new WeakMap<Element, Listener>()\n/** Elements observed while in the document. */\nconst seen = /* @__PURE__ */ new WeakSet<Element>()\nlet observer: ResizeObserver | undefined\n\nfunction getObserver(): ResizeObserver | undefined {\n if (observer || typeof ResizeObserver !== 'function') return observer\n observer = new ResizeObserver((entries) => {\n for (const { target, contentRect } of entries) {\n if (target.isConnected) {\n seen.add(target)\n listeners.get(target)?.(contentRect.width, contentRect.height)\n } else if (seen.has(target)) {\n // Taken out of the page without destroy(): stop observing, or the\n // observer would keep the element and its chart in memory for good.\n // `chart.resize()` observes it again if it comes back.\n seen.delete(target)\n observer?.unobserve(target)\n }\n }\n })\n return observer\n}\n\n/**\n * Call `listener` with the content size of `el` whenever it changes.\n * Returns a function that stops observing. No-op where `ResizeObserver`\n * is unavailable (SSR, old browsers). Observing again is harmless.\n */\nexport function observeResize(el: Element, listener: Listener): () => void {\n const ro = getObserver()\n if (!ro) return () => {}\n listeners.set(el, listener)\n ro.observe(el)\n return () => {\n if (listeners.get(el) !== listener) return\n listeners.delete(el)\n ro.unobserve(el)\n }\n}\n","/**\n * Batches work from all charts into a single animation frame. Scheduling the\n * same key twice before the flush runs its latest task once.\n */\n\nconst queue = /* @__PURE__ */ new Map<object, () => void>()\nlet pending = false\n\nconst requestFrame = (callback: () => void): void => {\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(callback)\n else queueMicrotask(callback)\n}\n\n/**\n * Run a task; an error it throws is reported on its own (as an uncaught\n * error, in the console and to `window.onerror`) instead of stopping the\n * tasks of other charts in the same frame.\n */\nexport function run(task: () => void): void {\n try {\n task()\n } catch (error) {\n setTimeout(() => {\n throw error\n })\n }\n}\n\n/** Run `task` in the next frame, replacing any task already queued for `key`. */\nexport function schedule(key: object, task: () => void): void {\n queue.set(key, task)\n if (!pending) {\n pending = true\n requestFrame(flush)\n }\n}\n\n/** Work `flush()` also runs: the idle queue (`idle.ts`), once something uses it. */\nexport const flushHooks: { idle?: () => number } = {}\n\n/** Drop the task queued for `key`, if any. */\nexport function cancel(key: object): void {\n queue.delete(key)\n}\n\n/**\n * Run queued tasks now, idle ones too; returns how many ran. Tasks queued\n * meanwhile run too, but each key only once: a task queued again after it\n * ran (a chart updated from its own `render` handler) waits for the next\n * frame, instead of looping in this one and freezing the page.\n */\nexport function flush(): number {\n pending = false\n let count = 0\n const ran = new Set<object>()\n const later = new Map<object, () => void>()\n // Idle work can schedule frame work in turn.\n do {\n // (A Map also visits what is added while it is walked: tasks queued meanwhile.)\n for (const [key, task] of queue) {\n queue.delete(key)\n if (ran.has(key)) later.set(key, task)\n else {\n ran.add(key)\n run(task)\n count++\n }\n }\n count += flushHooks.idle?.() ?? 0\n } while (queue.size > 0)\n for (const [key, task] of later) schedule(key, task)\n return count\n}\n","import type { DataTable } from './a11y.ts'\nimport type { ValueLabelOptions } from './charts/value-labels.ts'\nimport { feature, features } from './features.ts'\nimport type { Locale, NumberFormat } from './format.ts'\nimport { type Hit, hitKey, type Interaction } from './interaction.ts'\nimport { defaultHidden, type LegendItem, type LegendOptions } from './legend.ts'\nimport type { ChartPlugin, PluginInstance } from './plugin.ts'\nimport type { DownloadOption } from './plugins/download.ts'\nimport { render } from './render/dom.ts'\nimport { renderToString } from './render/string.ts'\nimport { observeResize } from './resize.ts'\nimport { cancel, schedule } from './scheduler.ts'\nimport type { TooltipOptions } from './tooltip.ts'\nimport { type ChildInput, type ClassValue, h, type Props, type VNode } from './vnode.ts'\n\n/** Size and environment a chart type renders into. */\nexport interface RenderContext {\n width: number\n height: number\n /** Font size used to estimate label sizes. */\n fontSize: number\n locale: Locale\n /** Unique, stable prefix for ids inside this chart. */\n id: string\n /** Register how pointer and keyboard map to data (ignored in SSR). */\n onHitTest(interaction: Interaction): void\n /** Keys of legend entries (series) currently hidden. */\n hidden: ReadonlySet<string>\n}\n\n/**\n * A chart type plugin (`line`, `bar`, …). Receives the chart options and\n * returns the content of the root `<svg>`.\n */\nexport interface ChartType<O extends object = object> {\n readonly name: string\n /**\n * Clean options that may come from outside (data, annotations, axis\n * bounds from users, APIs, JSON) into the shape `render()` expects; called\n * as the config comes in, before anything reads it.\n */\n clean?(options: O): unknown\n render(options: O, context: RenderContext): ChildInput\n /** Entries for the legend (series, slices); charts without it get no legend. */\n legend?(options: O): LegendItem[]\n /**\n * The data as a text table, for screen readers and the visible table\n * option. `limit` is the most rows wanted; report the real count in `total`.\n */\n table?(options: O, context: RenderContext, limit: number): DataTable\n /**\n * Whether the chart should be focusable and keyboard-navigable by default\n * (`keyboard` in the config overrides it). Decorative types such as\n * sparklines opt out so a page of stat tiles does not multiply tab stops.\n */\n readonly keyboard?: boolean\n /**\n * How value labels (`valueLabels`) read this chart type, when not as bars\n * or points: `marks: 'slice'` writes each value as its share, inside its\n * slice; `marks: 'cell'` writes it in the middle of its mark. `format`\n * names the number format of the values in the options (by default a label\n * shows the text of the tooltip).\n */\n readonly valueLabels?: {\n marks?: 'slice' | 'cell'\n format?(options: O): NumberFormat | undefined\n }\n}\n\nexport type { DataTable, LegendItem }\n\n/** Options shared by every chart type. */\nexport interface BaseOptions {\n /** Fixed width in pixels. Defaults to the container width. */\n width?: number\n /**\n * Height in pixels, or `'container'` to follow the container's height (the\n * container then needs a height of its own). Defaults to width / aspectRatio.\n */\n height?: number | 'container'\n /** Width to height ratio used when `height` is not set. Defaults to `2`. */\n aspectRatio?: number\n /** Accessible name of the chart. */\n title?: string\n /** Longer accessible description. */\n description?: string\n /** Extra classes on the root `<svg>`. */\n class?: ClassValue\n /** Locale for number and date formatting. Set it explicitly for SSR. */\n locale?: Locale\n /**\n * Font size used to lay out labels. In the browser it is read from the\n * `--tc-font-size` custom property of the container when not set; set it\n * explicitly for SSR so server and client layouts match. Defaults to `12`.\n */\n fontSize?: number\n /** Id prefix; set it explicitly for SSR so server and client ids match. */\n id?: string\n /** Show a tooltip on hover, optionally with custom content. Defaults to `true`. */\n tooltip?: boolean | TooltipOptions\n /** Show a vertical crosshair on hover (point charts). Defaults to `true`. */\n crosshair?: boolean\n /** Show a legend with toggles. Defaults to showing it for two or more entries. */\n legend?: boolean | LegendOptions\n /**\n * Animate entrances and data updates (reduced motion always wins). By\n * default charts animate unless they draw more than 1000 elements (e.g. a\n * scatter of a thousand points), where transitions cost far more frame\n * time than they show; `true` animates those too.\n */\n animate?: boolean\n /**\n * Fill bars, areas, slices, rings and bubbles with patterns (and dash\n * lines), so series do not depend on color alone: `true` always, `'auto'`\n * (the default) only in forced colors (Windows High Contrast), where the\n * colors are gone, `false` never. Needs `@tabler/charts/patterns` on the\n * core (`@tabler/charts` includes it).\n */\n patterns?: boolean | 'auto'\n /**\n * Write the values on the marks: bars at their end, stacked segments,\n * cells and slices inside (slices show their share), lines and points\n * above their last point (`points: 'all'` for every one). Labels that do\n * not fit are left out. Needs `@tabler/charts/value-labels` on the core\n * (`@tabler/charts` includes it).\n */\n valueLabels?: boolean | ValueLabelOptions\n /**\n * Share the hover with the other charts of this group: the category under\n * the pointer is highlighted in all of them (matched by label), with its\n * tooltip. Needs the `sync()` plugin (the `Chart` of `@tabler/charts` has it).\n */\n sync?: string\n /**\n * Give the points of each series a shape of their own (circle, square,\n * triangle, diamond…) in line, radar and scatter charts, so they do not\n * depend on color alone. Defaults to `patterns === true`. Needs\n * `@tabler/charts/point-shapes` on the core (`@tabler/charts` includes it).\n */\n shapes?: boolean\n /**\n * Render the data as an HTML table: visually hidden for screen readers\n * (`true`, the default), shown below the chart (`'visible'`), or not at all.\n * An object sets `visible` and `maxRows` (default 1000; longer data is cut\n * and the caption says so).\n */\n table?: boolean | 'visible' | { visible?: boolean; maxRows?: number }\n /** Make the chart focusable and navigable with arrow keys. Defaults to `true`. */\n keyboard?: boolean\n /**\n * A download menu in the chart's corner: `true` offers PNG and SVG, a list\n * picks the formats (`['png', 'svg', 'jpeg', 'webp']`), an object also\n * sets the file name and the export options. Needs `@tabler/charts/export`\n * imported, and on the core the `download()` plugin (the `Chart` of\n * `@tabler/charts` has it).\n */\n download?: DownloadOption\n /**\n * Extra plugins, installed when the chart is created. The default `Chart`\n * from `@tabler/charts` already includes the built-in ones; the bare `Chart`\n * from `@tabler/charts/core` only runs these.\n */\n plugins?: readonly ChartPlugin[]\n}\n\n/** Full chart configuration: base options, the chart type and its options. */\nexport type ChartConfig<O extends object = object> = BaseOptions & O & { type: ChartType<O> }\n\nexport interface Size {\n width: number\n height: number\n}\n\nconst DEFAULT_WIDTH = 600\nconst DEFAULT_ASPECT_RATIO = 2\nconst DEFAULT_FONT_SIZE = 12\n\nlet uid = 0\nconst nextId = (): string => `tc-${++uid}`\n\n/** Resolve the final pixel size from options and the measured container size. */\nexport function resolveSize(options: BaseOptions, measured?: Partial<Size>): Size {\n const measuredWidth = measured?.width ?? 0\n // (Sizes that are not finite numbers count as not set.)\n const width = Math.max(\n 0,\n Math.round(\n Number.isFinite(options.width)\n ? (options.width as number)\n : measuredWidth > 0\n ? measuredWidth\n : DEFAULT_WIDTH,\n ),\n )\n const ratio =\n options.aspectRatio && options.aspectRatio > 0 ? options.aspectRatio : DEFAULT_ASPECT_RATIO\n const height = Number.isFinite(options.height)\n ? (options.height as number)\n : options.height === 'container' && (measured?.height ?? 0) > 0\n ? (measured?.height as number)\n : width / ratio\n return { width, height: Math.max(0, Math.round(height)) }\n}\n\n/** Run the chart type's `render()` for a config and size. */\nfunction renderContent<O extends object>(\n config: ChartConfig<O>,\n size: Size,\n id: string,\n onHitTest: (interaction: Interaction) => void,\n hidden: ReadonlySet<string>,\n fontSize?: number,\n): ChildInput {\n let found: Interaction | undefined\n const ctx = renderContext(\n config,\n size,\n id,\n (interaction) => {\n found = interaction\n onHitTest(interaction)\n },\n hidden,\n fontSize,\n )\n const content = config.type.render(config, ctx)\n // Optional features finish the content (point shapes, value labels).\n return features.post ? features.post(config as ChartConfig<object>, content, found, ctx) : content\n}\n\n/** Render context for a config and size (also used by plugins such as the data table). */\nexport function renderContext<O extends object>(\n config: ChartConfig<O>,\n size: Size,\n id: string,\n onHitTest: (interaction: Interaction) => void,\n hidden: ReadonlySet<string>,\n measuredFontSize?: number,\n): RenderContext {\n return {\n width: size.width,\n height: size.height,\n fontSize: config.fontSize ?? measuredFontSize ?? DEFAULT_FONT_SIZE,\n locale: config.locale,\n id,\n onHitTest,\n hidden,\n }\n}\n\n/**\n * The config as cleaned by its chart type, without the options that are\n * numbers nothing can be drawn with (NaN, ±Infinity, from a division or a\n * parse gone wrong outside): their defaults apply, as if they were left out.\n */\nfunction cleanData<O extends object>(config: ChartConfig<O>): ChartConfig<O> {\n const out = {\n ...(config.type?.clean ? (config.type.clean(config) as object) : config),\n } as Record<string, unknown>\n for (const key in out) {\n if (typeof out[key] === 'number' && !Number.isFinite(out[key])) delete out[key]\n }\n return out as ChartConfig<O>\n}\n\nfunction assertType(config: ChartConfig<object>): void {\n if (!config.type || typeof config.type.render !== 'function') {\n throw new TypeError('@tabler/charts: `type` must be a chart type such as line.')\n }\n}\n\n/** Legend entries of a config, whether a legend is shown and where. */\nexport interface ResolvedLegend {\n items: LegendItem[]\n show: boolean\n position: 'top' | 'bottom'\n}\n\n/** Legend entries of a config, and whether the legend is shown. */\nexport function resolveLegend<O extends object>(config: ChartConfig<O>): ResolvedLegend {\n const items = config.type.legend?.(config) ?? []\n const option = config.legend\n const show = option === undefined ? items.length >= 2 : option !== false && items.length > 0\n const position = typeof option === 'object' && option.position === 'bottom' ? 'bottom' : 'top'\n return { items, show, position }\n}\n\n/**\n * The chart's accessible name: its `title`, or else the chart type and its\n * legend entries (\"line chart: Visitors, Sign-ups\"), since an image without\n * a name is announced as nothing at all. Set `title` for a name in the\n * page's language.\n */\nexport function chartLabel(config: ChartConfig<object>): string {\n if (config.title) return config.title\n const names = (config.type.legend?.(config) ?? []).map((item) => item.name).filter(Boolean)\n const shown = names.slice(0, 6).join(', ')\n // Screen readers do not care for capitals; a long list of names is cut short.\n return `${config.type.name} chart${names.length ? `: ${shown}${names.length > 6 ? ', …' : ''}` : ''}`\n}\n\n/** Elements beyond which charts skip transitions unless `animate: true`. */\nconst ANIMATION_LIMIT = 1000\n\n/** Number of elements in chart content. */\nconst countNodes = (child: ChildInput): number =>\n Array.isArray(child)\n ? child.reduce((n: number, c: ChildInput) => n + countNodes(c), 0)\n : child && typeof child === 'object'\n ? 1 + countNodes((child as VNode).children)\n : 0\n\n/** Whether a chart renders without transitions: asked to, or too big to animate cheaply. */\nconst isStatic = (config: ChartConfig<object>, content: ChildInput): boolean =>\n config.animate === false || (config.animate !== true && countNodes(content) > ANIMATION_LIMIT)\n\n/** Wrap chart content (and hover layers) in the accessible root `<svg>`. */\nfunction composeChart(\n config: ChartConfig<object>,\n size: Size,\n id: string,\n still: boolean,\n content: ChildInput,\n underlay?: ChildInput,\n overlay?: ChildInput,\n extraAttrs?: Props,\n): VNode {\n const { width, height } = size\n const descId = config.description ? `${id}-desc` : undefined\n const { patterns } = config\n // [class, root style, defs] of the pattern fills, when the chart has them.\n const fills =\n patterns === false\n ? undefined\n : (patterns === true ? feature('patterns') : features.patterns)?.(config, id)\n return h(\n 'svg',\n {\n class: [\n 'tc-chart',\n `tc-chart-${config.type.name}`,\n still && 'tc-static',\n fills?.[0],\n config.class,\n ],\n style: fills?.[1],\n viewBox: `0 0 ${width} ${height}`,\n width,\n height,\n role: 'img',\n // An svg <title> would also show as a native tooltip, so the name is an attribute.\n 'aria-label': chartLabel(config),\n 'aria-describedby': descId,\n ...extraAttrs,\n },\n // Keyed, so their coming and going never shifts the (unkeyed) chart\n // content in the DOM patcher: that would recreate it and restart animations.\n descId && h('desc', { key: 'desc', id: descId }, config.description),\n fills?.[2],\n underlay && h('g', { key: 'hover-under', class: 'tc-hover-layer' }, underlay),\n content,\n overlay && h('g', { key: 'hover-over', class: 'tc-hover-layer' }, overlay),\n )\n}\n\n/**\n * Build the VNode tree of a chart: a pure function of the config and size,\n * shared by the DOM chart and server-side rendering.\n */\nexport function buildChart<O extends object>(\n config: ChartConfig<O>,\n size: Size,\n id: string = config.id ?? 'tc',\n onHitTest: (interaction: Interaction) => void = () => {},\n): VNode {\n assertType(config as ChartConfig<object>)\n config = cleanData(config)\n const hidden = defaultHidden(resolveLegend(config).items)\n const content = renderContent(config, size, id, onHitTest, hidden)\n const base = config as ChartConfig<object>\n return composeChart(base, size, id, isStatic(base, content), content)\n}\n\n/**\n * Render a chart to an SVG string, e.g. on the server.\n *\n * ```ts\n * chartToString({ type: line, data, id: 'sales', locale: 'en-US' }, { width: 600, height: 300 })\n * ```\n */\nexport function chartToString<O extends object>(config: ChartConfig<O>, size: Size): string {\n return renderToString(buildChart(config, size))\n}\n\nexport interface ChartEvents {\n /** A legend entry was toggled (by the user or `toggleSeries()`). */\n 'legend-toggle': { key: string; name: string; index: number; hidden: boolean }\n /** After the chart content rendered into the DOM (not on hover-only updates). */\n render: { size: Size }\n /**\n * The highlighted category (or mark) changed, or its data changed while\n * highlighted. `hit` is `null` when the pointer left the plot.\n */\n hover: { hit: Hit | null; event?: PointerEvent }\n /** A click on the plot. */\n click: { hit: Hit; event: MouseEvent }\n}\n\n/** The name of every chart event, for adapters that pass them all on. */\nexport const chartEvents: readonly (keyof ChartEvents)[] = [\n 'hover',\n 'click',\n 'legend-toggle',\n 'render',\n]\n\ntype Handler<T> = (event: T) => void\n\n/** Where the current highlight came from. */\ntype Source =\n | { kind: 'pointer'; x: number; y: number }\n | { kind: 'index'; index: number; seriesIndex?: number }\n\n/** The output of a chart type, with what it was built for. */\ninterface Content<O extends object> {\n cfg: ChartConfig<O>\n width: number\n height: number\n hidden: string\n fontSize: number | undefined\n content: ChildInput\n /** Whether the content renders without transitions. */\n still: boolean\n}\n\n/** The chart on each element. */\nconst mounted = /* @__PURE__ */ new WeakMap<Element, Chart<object>>()\n\n/**\n * A chart bound to a DOM element: measures its container, renders SVG into\n * it and re-renders on `update()` and resize (batched per animation frame).\n * Features such as the tooltip, the legend and pointer input (`hover` /\n * `click` events, from `pointer()`, which the highlight and tooltip plugins\n * turn on themselves) are plugins; the `Chart` exported by `@tabler/charts`\n * installs the built-in ones.\n *\n * ```ts\n * const chart = new Chart('#sales', { type: line, data })\n * chart.update({ data: next })\n * ```\n */\nexport class Chart<O extends object = object> {\n /** Element the chart renders into. */\n readonly element: Element\n /** Id prefix used for elements inside the chart. */\n readonly id: string\n #cfg: ChartConfig<O>\n /** Container size changes, from the shared ResizeObserver. */\n #onResize = (width: number, height: number): void => {\n // Our own SVG sets the container height unless it follows the container.\n const followsHeight = this.#cfg.height === 'container'\n const changed =\n width !== this.#measured.width || (followsHeight && height !== this.#measured.height)\n this.#measured = { width, height }\n // A hidden container (display: none) measures 0×0: nothing to draw until it shows again.\n if (changed && (width || height)) {\n this.#font = undefined\n this.#markResizing()\n this.#schedule()\n }\n }\n #measured: Partial<Size> = {}\n readonly #handlers = new Map<keyof ChartEvents, Set<Handler<never>>>()\n #unobserve: () => void\n readonly #plugins: PluginInstance[] = []\n #destroyed = false\n #current: Interaction | undefined\n #source: Source | undefined\n #hovered = ''\n #hit: Hit | null = null\n /** Chart type output of the last render, reused while only the highlight changes. */\n #cache: Content<O> | undefined\n #resizeTimer: ReturnType<typeof setTimeout> | undefined\n /** Visibility set by the user, overriding each entry's default. */\n readonly #toggled = new Map<string, boolean>()\n /** Server-rendered svg to take over on the first render, if any. */\n #adopt: Element | null\n /**\n * The measured `--tc-font-size` (`undefined` reads it again). Reading it\n * forces the browser to restyle the page, so new data alone reuses it.\n */\n #font: number | undefined\n\n constructor(\n target: Element | string,\n config: ChartConfig<O>,\n defaultPlugins: readonly ChartPlugin[] = [],\n ) {\n const element = typeof target === 'string' ? document.querySelector(target) : target\n if (!element) throw new Error(`@tabler/charts: element \"${String(target)}\" not found.`)\n // One chart per element: a new one replaces the chart already there.\n mounted.get(element)?.destroy()\n mounted.set(element, this as unknown as Chart<object>)\n this.element = element\n this.#cfg = cleanData(config)\n this.id = config.id ?? nextId()\n this.#adopt = element.querySelector(':scope > svg.tc-chart')\n this.#measure()\n this.#unobserve = observeResize(element, this.#onResize)\n try {\n for (const plugin of [...defaultPlugins, ...(config.plugins ?? [])]) {\n this.#plugins.push(plugin.install(this as unknown as Chart<object>))\n }\n this.render()\n } catch (error) {\n // Nobody gets this chart to destroy it: leave the element as it was found.\n this.destroy()\n throw error\n }\n }\n\n /** Current configuration. */\n get config(): ChartConfig<O> {\n return this.#cfg\n }\n\n /** Size of the last render. */\n get size(): Size {\n // In 'container' height mode, plugins such as the legend take part of the\n // container. Only then: measuring them forces a layout of the page.\n let measured = this.#measured\n if (this.#cfg.height === 'container' && measured.height) {\n let reserved = 0\n for (const plugin of this.#plugins) reserved += plugin.reservedHeight?.() ?? 0\n if (reserved) measured = { ...measured, height: measured.height - reserved }\n }\n return resolveSize(this.#cfg, measured)\n }\n\n /** Font size used by the last render (explicit, measured, or the default). */\n get fontSize(): number {\n return this.#cache?.fontSize ?? this.#cfg.fontSize ?? DEFAULT_FONT_SIZE\n }\n\n /** How pointer and keyboard map to data for the current render. */\n get interaction(): Interaction | undefined {\n return this.#current\n }\n\n /** The highlighted category (hover or keyboard), or `null`. */\n get active(): Hit | null {\n return this.#hit\n }\n\n /**\n * The pointer in chart pixels while it drives the highlight (`undefined`\n * for keyboard highlights). `hitAnchor(chart.active, chart.pointer)` gives\n * where a tooltip belongs either way.\n */\n get pointer(): { x: number; y: number } | undefined {\n const source = this.#source\n return this.#hit && source?.kind === 'pointer' ? { x: source.x, y: source.y } : undefined\n }\n\n /** Whether the highlight comes from the pointer or from `highlightIndex()` (keyboard). */\n get highlightSource(): 'pointer' | 'index' | undefined {\n return this.#hit ? this.#source?.kind : undefined\n }\n\n /**\n * Highlight a category by index (and optionally one series in it), as\n * keyboard navigation does. Returns the hit, or `null` for an invalid index.\n */\n highlightIndex(index: number, seriesIndex?: number): Hit | null {\n const hit = this.#current?.hitIndex(index, seriesIndex) ?? null\n if (!hit) return null\n this.#source = { kind: 'index', index, seriesIndex }\n this.#setHover(hit)\n return hit\n }\n\n /**\n * Highlight what lies at a point in chart pixels, as the pointer does (the\n * `pointer()` plugin calls it). Returns the hit, or `null` for none.\n */\n highlightAt(x: number, y: number, event?: PointerEvent): Hit | null {\n const hit = this.hitTest(x, y)\n this.#source = { kind: 'pointer', x, y }\n this.#setHover(hit, event)\n return hit\n }\n\n /** Remove any highlight. */\n clearHighlight(event?: PointerEvent): void {\n this.#source = undefined\n this.#setHover(null, event)\n }\n\n /**\n * Show or hide a legend entry (series) by key, name or index; toggles when\n * `hidden` is omitted. Re-renders in the next frame.\n */\n toggleSeries(target: string | number, hidden?: boolean): this {\n const { items } = resolveLegend(this.#cfg)\n const item =\n typeof target === 'number'\n ? items.find((entry) => entry.index === target)\n : (items.find((entry) => entry.key === target) ??\n items.find((entry) => entry.name === target))\n if (!item) return this\n const next = hidden ?? !this.#hiddenSet(items).has(item.key)\n this.#toggled.set(item.key, next)\n this.emit('legend-toggle', { key: item.key, name: item.name, index: item.index, hidden: next })\n this.#schedule()\n return this\n }\n\n /** Whether a legend entry is hidden. */\n isHidden(key: string): boolean {\n return this.#hiddenSet(resolveLegend(this.#cfg).items).has(key)\n }\n\n /** Merge `options` into the configuration and re-render in the next frame. */\n update(options: Partial<ChartConfig<O>>): this {\n this.#cfg = cleanData({ ...this.#cfg, ...options })\n // Options such as `class` may change the font size; new data does not.\n for (const key in options) if (key !== 'data') this.#font = undefined\n this.#schedule()\n return this\n }\n\n /**\n * Replace the whole configuration and re-render in the next frame: options\n * left out go back to their defaults (`update()` would keep them).\n */\n setConfig(config: ChartConfig<O>): this {\n this.#cfg = cleanData(config)\n this.#font = undefined\n this.#schedule()\n return this\n }\n\n /** Replace the data and re-render in the next frame. */\n setData(data: O extends { data: infer D } ? D : never): this {\n return this.update({ data } as unknown as Partial<ChartConfig<O>>)\n }\n\n /**\n * Re-measure the container and re-render in the next frame. Call it when a\n * container taken out of the page without `destroy()` comes back.\n */\n resize(): this {\n // A container taken out of the page and put back is observed again.\n if (!this.#destroyed) this.#unobserve = observeResize(this.element, this.#onResize)\n this.#measure()\n this.#font = undefined\n this.#schedule()\n return this\n }\n\n /** Render synchronously now. */\n render(): this {\n if (this.#destroyed) return this\n cancel(this)\n const cfg = this.#cfg\n const config = cfg as ChartConfig<object>\n assertType(config)\n const legend = resolveLegend(cfg)\n const hidden = this.#hiddenSet(legend.items)\n for (const plugin of this.#plugins) plugin.beforeRender?.({ config, legend, hidden })\n const size = this.size\n const { content, stale, changed } = this.#content(size, hidden)\n if (stale) this.#refreshHighlight()\n\n const adopted = this.#adopt\n render(this.element, this.#compose(content, size), adopted)\n this.#adopt = null\n // The server markup was hydrated in place: snap it to the real size and\n // data instead of morphing (the server could not measure the container).\n if (adopted) this.#markResizing()\n\n for (const plugin of this.#plugins)\n plugin.afterRender?.({ config, legend, hidden, size, stale, changed })\n if (stale) this.emit('render', { size })\n return this\n }\n\n /**\n * The chart type's output for the current config, size, hidden series and\n * font size: built again when one of them changed (`stale`; `changed` when\n * it is what the chart shows, not only its size), else the one of the last render.\n */\n #content(\n size: Size,\n hidden: ReadonlySet<string>,\n ): { content: Content<O>; stale: boolean; changed: boolean } {\n const cfg = this.#cfg\n const hiddenKey = [...hidden].sort().join('\\u0000')\n this.#font ??= cfg.fontSize ?? this.#measureFontSize()\n const fontSize = cfg.fontSize ?? this.#font\n\n let cache = this.#cache\n const changed = !cache || cache.cfg !== cfg || cache.hidden !== hiddenKey\n const stale =\n changed ||\n cache?.width !== size.width ||\n cache.height !== size.height ||\n cache.fontSize !== fontSize\n if (!cache || stale) {\n this.#current = undefined\n const content = renderContent(\n cfg,\n size,\n this.id,\n (interaction) => {\n this.#current = interaction\n },\n hidden,\n fontSize,\n )\n cache = {\n cfg,\n width: size.width,\n height: size.height,\n hidden: hiddenKey,\n fontSize,\n content,\n still: isStatic(cfg as ChartConfig<object>, content),\n }\n this.#cache = cache\n }\n return { content: cache, stale, changed }\n }\n\n /** Keep the highlight (and its consumers, like tooltips) in sync with new data or layout. */\n #refreshHighlight(): void {\n const source = this.#source\n if (!source) return\n const next =\n source.kind === 'pointer'\n ? this.hitTest(source.x, source.y)\n : (this.#current?.hitIndex(source.index, source.seriesIndex) ?? null)\n this.#setHover(next, undefined, true, false)\n }\n\n /** The root svg: the content, with the plugins' hover layers and attributes. */\n #compose(content: Content<O>, size: Size): VNode {\n const config = this.#cfg as ChartConfig<object>\n const hit = this.#hit\n const under: ChildInput[] = []\n const over: ChildInput[] = []\n let attrs: Props | undefined\n for (const plugin of this.#plugins) {\n if (hit && plugin.layers) {\n const layer = plugin.layers(hit, config)\n under.push(layer.under)\n over.push(layer.over)\n }\n const extra = plugin.svgAttrs?.(config)\n if (extra) attrs = { ...attrs, ...extra }\n }\n // Hover layers only while something is highlighted (an empty list would still render).\n return composeChart(\n config,\n size,\n this.id,\n content.still,\n content.content,\n under.length ? under : undefined,\n over.length ? over : undefined,\n attrs,\n )\n }\n\n /** What lies at a point in chart pixels, or `null`. */\n hitTest(x: number, y: number): Hit | null {\n return this.#current?.hitTest(x, y) ?? null\n }\n\n /** Subscribe to an event; returns a function that unsubscribes. */\n on<K extends keyof ChartEvents>(name: K, handler: Handler<ChartEvents[K]>): () => void {\n let set = this.#handlers.get(name)\n if (!set) {\n set = new Set()\n this.#handlers.set(name, set)\n }\n set.add(handler as Handler<never>)\n return () => {\n set.delete(handler as Handler<never>)\n }\n }\n\n /** Remove the chart from the DOM and stop observing its container. */\n destroy(): void {\n if (this.#destroyed) return\n this.#destroyed = true\n if (mounted.get(this.element) === (this as never)) mounted.delete(this.element)\n cancel(this)\n clearTimeout(this.#resizeTimer)\n this.#unobserve()\n for (const plugin of this.#plugins) plugin.destroy?.()\n this.#handlers.clear()\n render(this.element, null)\n }\n\n /**\n * Update the highlighted hit: emit `hover` when it changed (or when\n * `force`d after new data) and re-render the hover layers in the next frame.\n */\n #setHover(hit: Hit | null, event?: PointerEvent, force = false, rerender = true): void {\n const key = hitKey(hit)\n if (!force && key === this.#hovered) return\n // After a re-render, only a highlight that is still active is worth repeating.\n if (force && key === '' && this.#hovered === '') return\n this.#hovered = key\n this.#hit = hit\n this.emit('hover', event ? { hit, event } : { hit })\n if (rerender) this.#schedule()\n }\n\n #hiddenSet(items: readonly LegendItem[]): Set<string> {\n const hidden = new Set<string>()\n for (const item of items) {\n if (this.#toggled.get(item.key) ?? item.hidden) hidden.add(item.key)\n }\n return hidden\n }\n\n /** Suspend transitions while the container keeps resizing (see `[data-resizing]` in CSS). */\n #markResizing(): void {\n const svg = this.element.querySelector(':scope > svg.tc-chart')\n if (!svg) return\n svg.setAttribute('data-resizing', '')\n clearTimeout(this.#resizeTimer)\n this.#resizeTimer = setTimeout(() => svg.removeAttribute('data-resizing'), 200)\n }\n\n #schedule(): void {\n if (!this.#destroyed) schedule(this, () => this.render())\n }\n\n /** The `--tc-font-size` in effect on the container, in pixels (browser only). */\n #measureFontSize(): number | undefined {\n if (typeof getComputedStyle !== 'function') return undefined\n const value = Number.parseFloat(\n getComputedStyle(this.element).getPropertyValue('--tc-font-size'),\n )\n return Number.isFinite(value) && value > 0 ? value : undefined\n }\n\n /** Measure the content box, matching what `ResizeObserver` reports. */\n #measure(): void {\n const el = this.element as HTMLElement\n const style = typeof getComputedStyle === 'function' ? getComputedStyle(el) : undefined\n const px = (value: string | undefined) => Number.parseFloat(value ?? '') || 0\n this.#measured = {\n width: el.clientWidth - px(style?.paddingLeft) - px(style?.paddingRight),\n height: el.clientHeight - px(style?.paddingTop) - px(style?.paddingBottom),\n }\n }\n\n /** Call the handlers of an event (plugins emit `click`, for instance). */\n emit<K extends keyof ChartEvents>(name: K, event: ChartEvents[K]): void {\n const set = this.#handlers.get(name)\n if (set) for (const handler of set) (handler as Handler<ChartEvents[K]>)(event)\n }\n}\n","/**\n * Pattern fills, so series do not depend on color alone (color vision\n * deficiency, grayscale print, forced colors). Every legend entry gets an\n * 8×8 tile: its series color with lines or dots in `--tc-pattern-color` (the\n * surface by default) over it, one shape per color slot. The chart root\n * carries `--tc-pattern-{n}: url(#…)` and the slot classes map it to\n * `--tc-series-pattern`, which the stylesheet uses as the fill of bars,\n * areas, slices, rings and bubbles (lines get dashes instead) when\n * `patterns` is `true`, or with `'auto'` (the default) in forced colors.\n */\nimport { type ChartConfig, resolveLegend } from '../chart.ts'\nimport type { LegendItem } from '../legend.ts'\nimport { h, type VNode } from '../vnode.ts'\n\n/** Tile shapes by color slot: lines as strokes, dots as round-capped stubs. */\nconst TILES = [\n // Diagonal /, with the corners filled in so tiles join up.\n 'M-2,2L2,-2M0,8L8,0M6,10L10,6',\n // Dots.\n 'M2,2h.01M6,6h.01',\n // Diagonal \.\n 'M-2,6L2,10M0,0L8,8M6,-2L10,2',\n // Horizontal.\n 'M0,4H8',\n // Cross-hatch.\n 'M0,8L8,0M0,0L8,8',\n // Vertical.\n 'M4,0V8',\n // Grid.\n 'M0,4H8M4,0V8',\n // Dashes.\n 'M1,2H4M5,6H8',\n]\n\n/** Slots with a pattern of their own; series 9+ share the one of the \"other\" color. */\nconst SLOTS = TILES.length\n\n/** The pattern of a slot (0-based): its id suffix and slot class. */\nconst slot = (index: number): [string, string] =>\n index < SLOTS ? [`${index + 1}`, `tc-series-${index + 1}`] : ['other', '']\n\n/** `<pattern>` elements for the legend entries of a chart. */\nexport function patternDefs(items: readonly LegendItem[], id: string): VNode[] {\n const out = new Map<string, VNode>()\n for (const item of items) {\n const [n, cls] = slot(item.index)\n if (out.has(n)) continue\n out.set(\n n,\n h(\n 'pattern',\n {\n key: n,\n id: `${id}-pattern-${n}`,\n class: ['tc-pattern', 'tc-series', cls],\n width: 8,\n height: 8,\n patternUnits: 'userSpaceOnUse',\n // A map, so a color from data cannot inject CSS (see normalizeStyle).\n style: { '--tc-series-color': item.color },\n },\n h('rect', { class: 'tc-pattern-bg', width: 8, height: 8 }),\n h('path', { class: 'tc-pattern-ink', d: TILES[item.index % SLOTS] as string }),\n ),\n )\n }\n return [...out.values()]\n}\n\n/** The `--tc-pattern-{n}` references for the chart root. */\nexport function patternVars(items: readonly LegendItem[], id: string): Record<string, string> {\n const vars: Record<string, string> = {}\n for (const item of items) {\n const [n] = slot(item.index)\n vars[`--tc-pattern-${n}`] = `url(#${id}-pattern-${n})`\n }\n return vars\n}\n\n/**\n * The pattern fills of a chart: its root class (`tc-patterned` with\n * `patterns: true`, `tc-patterns-auto` for forced colors), the root's\n * `--tc-pattern-{n}` references and the `<defs>` with the patterns;\n * `undefined` for a chart without legend entries.\n */\nexport function patternFills(\n config: ChartConfig<object>,\n id: string,\n): [string, Record<string, string>, VNode] | undefined {\n const { items } = resolveLegend(config)\n if (!items.length) return undefined\n return [\n config.patterns === true ? 'tc-patterned' : 'tc-patterns-auto',\n patternVars(items, id),\n h('defs', { key: 'patterns' }, patternDefs(items, id)),\n ]\n}\n","/**\n * Marker shapes, so the points of series do not depend on color alone\n * (color vision deficiency, grayscale print): one shape per color slot,\n * for line, radar and scatter points and the active points of the hover.\n * On with `shapes: true`, and with `patterns: true` unless `shapes` says\n * otherwise. Legend and tooltip swatches take the same shapes in CSS.\n */\nimport type { PostStep } from '../features.ts'\nimport { round } from '../layout.ts'\nimport type { Child, ChildInput, VNode } from '../vnode.ts'\n\n/**\n * Outlines by color slot (0-based), as x, y pairs in units of the radius,\n * sized so the shapes weigh about the same as the circle of slot 0 (and of\n * slots 9 and up).\n */\nconst SHAPES: readonly (readonly number[])[] = [\n [],\n // Square.\n [-0.9, -0.9, 0.9, -0.9, 0.9, 0.9, -0.9, 0.9],\n // Triangle.\n [0, -1.3, 1.2, 0.9, -1.2, 0.9],\n // Diamond.\n [0, -1.3, 1.3, 0, 0, 1.3, -1.3, 0],\n // Triangle, pointing down.\n [-1.2, -0.9, 1.2, -0.9, 0, 1.3],\n // Plus.\n [\n -0.4, -1.2, 0.4, -1.2, 0.4, -0.4, 1.2, -0.4, 1.2, 0.4, 0.4, 0.4, 0.4, 1.2, -0.4, 1.2, -0.4, 0.4,\n -1.2, 0.4, -1.2, -0.4, -0.4, -0.4,\n ],\n // Cross.\n [\n -0.7, -1.2, 0, -0.5, 0.7, -1.2, 1.2, -0.7, 0.5, 0, 1.2, 0.7, 0.7, 1.2, 0, 0.5, -0.7, 1.2, -1.2,\n 0.7, -0.5, 0, -1.2, -0.7,\n ],\n // Star.\n [\n 0, -1.4, 0.32, -0.44, 1.33, -0.43, 0.52, 0.17, 0.82, 1.13, 0, 0.55, -0.82, 1.13, -0.52, 0.17,\n -1.33, -0.43, -0.32, -0.44,\n ],\n]\n\n/** The path of slot `slot`'s marker of radius `r` around (`x`, `y`). */\nexport function markerPath(slot: number, x: number, y: number, r: number): string {\n const shape = SHAPES[slot] ?? []\n if (!shape.length) {\n return `M${round(x - r)},${round(y)}a${r},${r},0,1,0,${2 * r},0a${r},${r},0,1,0,${-2 * r},0Z`\n }\n let d = ''\n for (let i = 0; i < shape.length; i += 2) {\n d += `${i ? 'L' : 'M'}${round(x + (shape[i] as number) * r)},${round(y + (shape[i + 1] as number) * r)}`\n }\n return `${d}Z`\n}\n\n/** The content with the point circles of each series group (`.tc-series-N`) in its slot's shape. */\nfunction reshape(child: ChildInput, slot: number): ChildInput {\n if (Array.isArray(child)) return child.map((c) => reshape(c, slot))\n if (!child || typeof child !== 'object') return child\n const { attrs } = child\n const cls = String(attrs.class ?? '')\n const group = /\\btc-series-(\\d+)\\b/.exec(cls)\n if (\n child.tag === 'circle' &&\n slot >= 0 &&\n /\\btc-point\\b/.test(cls) &&\n !/\\btc-bubble\\b/.test(cls)\n ) {\n const shaped: VNode = {\n tag: 'path',\n attrs: {\n class: `${cls} tc-marker`,\n d: markerPath(slot, +(attrs.cx ?? 0), +(attrs.cy ?? 0), +(attrs.r ?? 0)),\n },\n children: [],\n key: child.key,\n }\n return shaped\n }\n return {\n ...child,\n children: child.children.map((c) => reshape(c, group ? Number(group[1]) - 1 : slot) as Child),\n }\n}\n\n/** The step that gives the points of charts with `shapes` (or `patterns: true`) their shapes. */\nexport const shapesStep: PostStep = (config, content) =>\n (config.shapes ?? config.patterns === true) ? reshape(content, -1) : content\n","import { getDateFormat, type Locale } from '../format.ts'\nimport type { BandKey, BandScale } from './band.ts'\nimport { extent } from './extent.ts'\nimport { tickStep } from './ticks.ts'\n\n/** A point in time: a `Date` or a timestamp in milliseconds. */\nexport type TimeValue = Date | number\n\nexport interface TimeScaleOptions {\n /** Align ticks to UTC instead of local time (use it for SSR). Defaults to `false`. */\n utc?: boolean\n /** Clamp output to the range. */\n clamp?: boolean\n}\n\n/** Continuous scale mapping time to a pixel range, with calendar-aware ticks. */\nexport interface TimeScale {\n (value: TimeValue): number\n readonly domain: readonly [number, number]\n readonly range: readonly [number, number]\n readonly utc: boolean\n /** Map a pixel back to a time. */\n invert(pixel: number): Date\n /** Tick dates at calendar boundaries, roughly `count` of them. */\n ticks(count?: number): Date[]\n /** A formatter suited to the tick interval chosen for `count`. */\n tickFormat(count?: number, locale?: Locale): (date: Date) => string\n /** A copy with the domain extended to tick boundaries. */\n nice(count?: number): TimeScale\n}\n\ntype Unit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'\n\ninterface Interval {\n unit: Unit\n step: number\n /** Approximate duration, for choosing an interval. */\n ms: number\n}\n\nconst SECOND = 1000\nconst MINUTE = 60 * SECOND\nconst HOUR = 60 * MINUTE\nconst DAY = 24 * HOUR\nconst WEEK = 7 * DAY\nconst MONTH = 30 * DAY\nconst YEAR = 365 * DAY\n\nconst INTERVALS: Interval[] = [\n { unit: 'second', step: 1, ms: SECOND },\n { unit: 'second', step: 5, ms: 5 * SECOND },\n { unit: 'second', step: 15, ms: 15 * SECOND },\n { unit: 'second', step: 30, ms: 30 * SECOND },\n { unit: 'minute', step: 1, ms: MINUTE },\n { unit: 'minute', step: 5, ms: 5 * MINUTE },\n { unit: 'minute', step: 15, ms: 15 * MINUTE },\n { unit: 'minute', step: 30, ms: 30 * MINUTE },\n { unit: 'hour', step: 1, ms: HOUR },\n { unit: 'hour', step: 3, ms: 3 * HOUR },\n { unit: 'hour', step: 6, ms: 6 * HOUR },\n { unit: 'hour', step: 12, ms: 12 * HOUR },\n { unit: 'day', step: 1, ms: DAY },\n { unit: 'day', step: 2, ms: 2 * DAY },\n { unit: 'week', step: 1, ms: WEEK },\n { unit: 'month', step: 1, ms: MONTH },\n { unit: 'month', step: 3, ms: 3 * MONTH },\n { unit: 'year', step: 1, ms: YEAR },\n]\n\n/** Calendar arithmetic in local time or UTC. */\nfunction calendar(utc: boolean) {\n const get = (d: Date, unit: Unit): number => {\n switch (unit) {\n case 'year':\n return utc ? d.getUTCFullYear() : d.getFullYear()\n case 'month':\n return utc ? d.getUTCMonth() : d.getMonth()\n case 'day':\n case 'week':\n return utc ? d.getUTCDate() : d.getDate()\n case 'hour':\n return utc ? d.getUTCHours() : d.getHours()\n case 'minute':\n return utc ? d.getUTCMinutes() : d.getMinutes()\n default:\n return utc ? d.getUTCSeconds() : d.getSeconds()\n }\n }\n const make = (y: number, mo: number, d: number, h = 0, mi = 0, s = 0): Date =>\n utc ? new Date(Date.UTC(y, mo, d, h, mi, s)) : new Date(y, mo, d, h, mi, s)\n const weekday = (d: Date): number => (utc ? d.getUTCDay() : d.getDay())\n\n /** Start of the interval containing `date` (weeks start on Monday). */\n const floor = (date: Date, { unit, step }: Interval): Date => {\n const y = get(date, 'year')\n const mo = get(date, 'month')\n const d = get(date, 'day')\n switch (unit) {\n case 'year':\n return make(Math.floor(y / step) * step, 0, 1)\n case 'month':\n return make(y, Math.floor(mo / step) * step, 1)\n case 'week':\n return make(y, mo, d - ((weekday(date) + 6) % 7))\n case 'day':\n return make(y, mo, Math.floor((d - 1) / step) * step + 1)\n case 'hour':\n return make(y, mo, d, Math.floor(get(date, 'hour') / step) * step)\n case 'minute':\n return make(y, mo, d, get(date, 'hour'), Math.floor(get(date, 'minute') / step) * step)\n default:\n return make(\n y,\n mo,\n d,\n get(date, 'hour'),\n get(date, 'minute'),\n Math.floor(get(date, 'second') / step) * step,\n )\n }\n }\n\n /** `date` moved forward by one interval. */\n const next = (date: Date, { unit, step }: Interval): Date => {\n const y = get(date, 'year')\n const mo = get(date, 'month')\n const d = get(date, 'day')\n switch (unit) {\n case 'year':\n return make(y + step, 0, 1)\n case 'month':\n return make(y, mo + step, 1)\n case 'week':\n return make(y, mo, d + 7 * step)\n case 'day': {\n // Day steps restart at the first of each month, so ticks land on the 1st.\n const n = make(y, mo, d + step)\n return get(n, 'month') === mo ? n : make(y, mo + 1, 1)\n }\n case 'hour':\n return make(y, mo, d, get(date, 'hour') + step)\n case 'minute':\n return make(y, mo, d, get(date, 'hour'), get(date, 'minute') + step)\n default:\n return make(y, mo, d, get(date, 'hour'), get(date, 'minute'), get(date, 'second') + step)\n }\n }\n\n /** Whether `date` sits on the boundary of the unit above `unit`. */\n const boundary = (date: Date, unit: Unit): boolean => {\n switch (unit) {\n case 'second':\n return get(date, 'second') === 0\n case 'minute':\n return get(date, 'minute') === 0 && get(date, 'second') === 0\n case 'hour':\n return get(date, 'hour') === 0 && get(date, 'minute') === 0\n case 'day':\n case 'week':\n return get(date, 'day') === 1\n case 'month':\n return get(date, 'month') === 0\n default:\n return false\n }\n }\n\n return { floor, next, boundary }\n}\n\n/** Pick the interval whose duration is closest to `span / count`. */\nfunction chooseInterval(span: number, count: number): Interval {\n const target = Math.abs(span) / Math.max(1, count)\n let i = 0\n while (i < INTERVALS.length && (INTERVALS[i] as Interval).ms < target) i++\n if (i === INTERVALS.length) {\n // Beyond one year: multiples of years.\n const years = Math.max(1, tickStep(0, target / YEAR, 1))\n return { unit: 'year', step: years, ms: years * YEAR }\n }\n if (i === 0) return INTERVALS[0] as Interval\n const lo = INTERVALS[i - 1] as Interval\n const hi = INTERVALS[i] as Interval\n return target / lo.ms < hi.ms / target ? lo : hi\n}\n\nconst toMs = (value: TimeValue): number => (value instanceof Date ? value.getTime() : value)\n\n/** Intl options for each tick unit, and for the boundary of the unit above it. */\nconst FORMATS: Record<Unit, [Intl.DateTimeFormatOptions, Intl.DateTimeFormatOptions | null]> = {\n second: [\n { hour: 'numeric', minute: '2-digit', second: '2-digit' },\n { hour: 'numeric', minute: '2-digit' },\n ],\n minute: [\n { hour: 'numeric', minute: '2-digit' },\n { hour: 'numeric', minute: '2-digit' },\n ],\n hour: [\n { hour: 'numeric', minute: '2-digit' },\n { month: 'short', day: 'numeric' },\n ],\n day: [{ month: 'short', day: 'numeric' }, null],\n week: [{ month: 'short', day: 'numeric' }, null],\n month: [{ month: 'short' }, { year: 'numeric' }],\n year: [{ year: 'numeric' }, null],\n}\n\n/**\n * Create a time scale over `[start, end]`.\n *\n * ```ts\n * const x = time([new Date(2026, 0, 1), new Date(2026, 2, 31)], [0, 600])\n * x.ticks() // first of each month, or every week, depending on the range\n * x.tickFormat() // e.g. \"Jan\", \"Feb\"\n * ```\n */\nexport function time(\n domain: readonly [TimeValue, TimeValue],\n range: readonly [number, number],\n options: TimeScaleOptions = {},\n): TimeScale {\n const utc = options.utc === true\n const d0 = toMs(domain[0])\n const d1 = toMs(domain[1])\n const [r0, r1] = range\n const span = d1 - d0\n const k = span === 0 ? 0 : (r1 - r0) / span\n const cal = calendar(utc)\n const clamp = options.clamp === true\n const rMin = Math.min(r0, r1)\n const rMax = Math.max(r0, r1)\n\n const scale = (value: TimeValue): number => {\n if (span === 0) return (r0 + r1) / 2\n const px = r0 + (toMs(value) - d0) * k\n return clamp ? Math.min(rMax, Math.max(rMin, px)) : px\n }\n\n const interval = (count = 5): Interval => chooseInterval(span, count)\n\n return Object.assign(scale, {\n domain: [d0, d1] as const,\n range: [r0, r1] as const,\n utc,\n invert(pixel: number): Date {\n return new Date(span === 0 || r1 === r0 ? d0 : d0 + (pixel - r0) / k)\n },\n ticks(count = 5): Date[] {\n if (!Number.isFinite(d0) || !Number.isFinite(d1)) return []\n const lo = Math.min(d0, d1)\n const hi = Math.max(d0, d1)\n if (lo === hi) return [new Date(lo)]\n const step = interval(count)\n const out: Date[] = []\n let t = cal.floor(new Date(lo), step)\n if (t.getTime() < lo) t = cal.next(t, step)\n while (t.getTime() <= hi && out.length < 1000) {\n out.push(t)\n t = cal.next(t, step)\n }\n return d1 < d0 ? out.reverse() : out\n },\n tickFormat(count = 5, locale?: Locale): (date: Date) => string {\n const { unit } = interval(count)\n const [primary, above] = FORMATS[unit]\n const tz = utc ? { timeZone: 'UTC' } : {}\n const main = getDateFormat(locale, { ...primary, ...tz })\n const upper = above ? getDateFormat(locale, { ...above, ...tz }) : null\n return (date) => (upper && cal.boundary(date, unit) ? upper : main).format(date)\n },\n nice(count = 5): TimeScale {\n if (span === 0 || !Number.isFinite(span)) return time(domain, range, options)\n const step = interval(count)\n const lo = cal.floor(new Date(Math.min(d0, d1)), step)\n let hi = cal.floor(new Date(Math.max(d0, d1)), step)\n if (hi.getTime() < Math.max(d0, d1)) hi = cal.next(hi, step)\n return time(d1 < d0 ? [hi, lo] : [lo, hi], range, options)\n },\n })\n}\n\n/**\n * A point scale over time for category charts: each category sits at its\n * real distance in time. Conforms to `BandScale` (zero bandwidth), so line\n * and area charts and their hit testing work unchanged. `stamps` must be\n * ascending; `keys` are the categories' keys.\n */\nexport function timePointScale(\n stamps: readonly number[],\n keys: readonly BandKey[],\n range: readonly [number, number],\n utc: boolean,\n): { scale: BandScale; time: TimeScale } {\n // Spreading large arrays into Math.min/max overflows the stack, so scan.\n const [lo, hi] = extent(stamps) ?? [0, 1]\n const valid = stamps.filter((t) => Number.isFinite(t))\n const t = time([lo, hi], range, { utc })\n const positions = stamps.map((ms) => t(ms))\n const at = (i: number): number => positions[i] ?? range[0]\n const scale = Object.assign((key: BandKey) => positions[keys.indexOf(key)], {\n domain: keys.slice(),\n range,\n bandwidth: 0,\n step: valid.length > 1 ? (range[1] - range[0]) / (valid.length - 1) : 0,\n at,\n center: (key: BandKey) => positions[keys.indexOf(key)],\n indexAt(pixel: number): number {\n // Stamps are sorted, so the nearest position is found by binary search.\n if (positions.length === 0) return -1\n let a = 0\n let b = positions.length - 1\n while (a < b) {\n const mid = (a + b) >> 1\n if ((positions[mid] as number) < pixel) a = mid + 1\n else b = mid\n }\n const prev = a - 1\n return prev >= 0 && pixel - (positions[prev] as number) < (positions[a] as number) - pixel\n ? prev\n : a\n },\n })\n return { scale: scale as BandScale, time: t }\n}\n","import type { Tick } from '../components/axis.ts'\nimport type { Locale } from '../format.ts'\nimport type { BandKey } from '../scales/band.ts'\nimport { type TimeScale, timePointScale } from '../scales/time.ts'\nimport { type CategoryAxis, type CategoryAxisOptions, type Label, toMs } from './cartesian.ts'\n\n/**\n * A time category axis: points at their real distance in time, ticks on\n * calendar boundaries labelled for the span (or with `x.format`).\n */\nexport function timeAxis(\n labels: readonly Label[],\n keys: readonly BandKey[],\n options: CategoryAxisOptions,\n count: number,\n locale: Locale,\n): CategoryAxis {\n const stamps = labels.map(toMs)\n const points = (range: readonly [number, number]) =>\n timePointScale(stamps, keys, range, options.utc === true)\n const probe = points([0, 1]).time\n const { format } = options\n const label = format ? (d: Date) => format(d, -1) : probe.tickFormat(count, locale)\n let time: TimeScale = probe\n return {\n // Time ticks come from the scale; their labels are what sits at the edges.\n edges: probe.ticks(count).map(label),\n scale(range) {\n const scaled = points(range)\n time = scaled.time\n return scaled.scale\n },\n ticks: (): Tick[] =>\n time.ticks(count).map((d) => ({ value: d.getTime(), position: time(d), label: label(d) })),\n get time() {\n return time\n },\n }\n}\n","/**\n * Value labels: the value written on each mark, for charts read at a\n * glance. They are worked out from the chart's interaction, so every type\n * gets them the same way: bars at their end (inside when there is no room\n * outside), stacked segments and heatmap cells in their middle, lines and\n * points above their point (the last one by default), slices in their\n * middle with their share. A label that does not fit its mark or the plot,\n * or that would cover another one, is left out: labels never overlap.\n */\nimport type { ChartConfig, RenderContext } from '../chart.ts'\nimport type { PostStep } from '../features.ts'\nimport { formatNumber, getNumberFormat, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { estimateTextWidth, type Rect, round } from '../layout.ts'\nimport { h, type VNode } from '../vnode.ts'\n\nexport interface ValueLabelOptions {\n /** Format of the values. Defaults to the value axis format (slices: their share in percent). */\n format?: NumberFormat\n /** Which points of lines, areas and scatters get a label. Defaults to `'last'`. */\n points?: 'last' | 'all'\n}\n\n/** Space between a mark and its label, and around labels. */\nconst GAP = 4\n\ninterface Placed {\n key: string\n text: string\n x: number\n y: number\n inside: boolean\n box: Rect\n}\n\nconst overlaps = (a: Rect, b: Rect): boolean =>\n a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height\n\nconst contains = (outer: Rect, inner: Rect): boolean =>\n inner.x >= outer.x - 1 &&\n inner.y >= outer.y - 1 &&\n inner.x + inner.width <= outer.x + outer.width + 1 &&\n inner.y + inner.height <= outer.y + outer.height + 1\n\n/** The labels layer of a chart, or `null` when nothing gets one. */\nexport function valueLabels(\n config: ChartConfig<object>,\n interaction: Interaction,\n ctx: RenderContext,\n): VNode | null {\n const option = config.valueLabels\n const options: ValueLabelOptions = typeof option === 'object' ? option : {}\n const { fontSize, locale } = ctx\n // What the chart type says about its marks (slices, cells) and its number format.\n const spec = config.type.valueLabels\n const pie = spec?.marks === 'slice'\n const cell = spec?.marks === 'cell'\n const stacked = !!(config as { stacked?: unknown }).stacked\n const format = options.format\n ? formatNumber(options.format, locale)\n : pie\n ? (v: number) =>\n getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 }).format(v)\n : spec?.format\n ? formatNumber(spec.format(config), locale)\n : undefined\n // Numbers have no descenders: one em is their height, with room to spare.\n const height = fontSize\n\n // Candidates in order of priority: every hit's items, and for points only the\n // last one of each series unless all are asked for.\n const items: [string, HitItem, Hit][] = []\n const last = new Map<number, number>()\n let total = 0\n for (let i = 0; i < interaction.count; i++) {\n const hit = interaction.hitIndex(i)\n for (const item of hit?.items ?? []) {\n if (item.value === null || item.y === null || !hit) continue\n total += Math.abs(item.value)\n if (!pie && !item.box && options.points !== 'all') last.set(item.seriesIndex, items.length)\n items.push([`${i}-${item.seriesIndex}`, item, hit])\n }\n }\n\n // Marks a label must not cover: every bar and cell but its own.\n const marks = items.flatMap(([, item]) => (item.box ? [item.box] : []))\n const placed: Placed[] = []\n items.forEach(([key, item, hit], n) => {\n const { area } = hit\n if (!pie && !item.box && options.points !== 'all' && last.get(item.seriesIndex) !== n) return\n const value = item.value as number\n const share = value / (total || 1)\n const text = format ? format(pie ? share : value) : item.text\n const width = estimateTextWidth(text, fontSize)\n const at = (x: number, y: number, inside: boolean): Placed => {\n // A point's label at the plot's edge (the last point) moves in.\n if (!item.box && !pie) {\n x = Math.max(area.x + width / 2 + 2, Math.min(x, area.x + area.width - width / 2 - 2))\n }\n return {\n key,\n text,\n x,\n y,\n inside,\n box: { x: x - width / 2 - 2, y: y - height / 2, width: width + 4, height },\n }\n }\n const y = item.y as number\n const candidates: Placed[] = []\n const { box } = item\n if (pie) {\n candidates.push(at(item.x, y, true))\n } else if (box) {\n const horizontal = hit.axis === 'y'\n const down = value < 0\n if (!stacked && !cell) {\n // Beyond the bar's end, then just inside it.\n const reach = (horizontal ? width / 2 : height / 2) + GAP\n const sign = down ? 1 : -1\n const along = y + sign * reach\n candidates.push(\n horizontal ? at(item.x - sign * reach, y, false) : at(item.x, along, false),\n // A label wider than its bar may lean off a taller neighbour.\n ...(horizontal\n ? []\n : [\n at(box.x + width / 2 - 3, along, false),\n at(box.x + box.width - width / 2 + 3, along, false),\n ]),\n horizontal ? at(item.x + sign * reach, y, true) : at(item.x, y - sign * reach, true),\n )\n } else {\n candidates.push(at(box.x + box.width / 2, box.y + box.height / 2, true))\n }\n } else {\n // Above the point, below it, or beside it (the end of a line, at the plot's edge).\n const side = width / 2 + GAP + 4\n candidates.push(\n at(item.x, y - height / 2 - GAP - 2, false),\n at(item.x, y + height / 2 + GAP + 2, false),\n at(item.x - side, y, false),\n at(item.x + side, y, false),\n )\n }\n // Labels may rise into the margin above the plot, not over the axes.\n const room = { ...area, y: 0, height: area.y + area.height }\n // Glyphs leave a little room at their sides (`slim`): a label may brush a neighbour.\n const fits = (p: Placed, slim = { ...p.box, x: p.box.x + 5, width: p.box.width - 10 }) =>\n contains(pie ? area : room, p.box) &&\n (!p.inside || !box || contains(box, p.box)) &&\n (!pie || sliceFits(item, area, share, p.box)) &&\n !placed.some((other) => overlaps(other.box, p.box)) &&\n !marks.some((mark) => mark !== box && overlaps(mark, slim))\n const spot = candidates.find((p) => fits(p))\n if (spot) placed.push(spot)\n })\n\n if (!placed.length) return null\n return h(\n 'g',\n { key: 'value-labels', class: 'tc-value-labels', 'aria-hidden': 'true' },\n placed.map((p) =>\n h(\n 'text',\n {\n key: p.key,\n class: ['tc-value-label', p.inside && 'tc-value-label-inside'],\n style: `transform:translate(${round(p.x)}px,${round(p.y)}px)`,\n 'text-anchor': 'middle',\n dy: '0.35em',\n },\n p.text,\n ),\n ),\n )\n}\n\n/**\n * Whether a label fits its slice: it sits at the slice's centroid, where the\n * slice is about its share of the circle wide and twice the distance to the\n * outer edge deep.\n */\nfunction sliceFits(item: HitItem, area: Rect, share: number, label: Rect): boolean {\n const outer = area.width / 2\n const radius = Math.hypot(item.x - area.x - outer, (item.y as number) - area.y - outer)\n const depth = 2 * (outer - radius)\n return label.width <= share * 2 * Math.PI * radius && label.height <= depth\n}\n\n/** The step that adds the labels over the content of charts with `valueLabels`. */\nexport const labelsStep: PostStep = (config, content, interaction, ctx) =>\n config.valueLabels && interaction ? [content, valueLabels(config, interaction, ctx)] : content\n","import type { Attrs, VNode } from '../vnode.ts'\nimport { childNamespace, createNode, patchAttrs, rendered, SVG_NS } from './dom.ts'\n\n/** Whether existing DOM `node` can stand for `vnode` in namespace `ns`. */\nfunction matches(node: Node, vnode: VNode, ns: string): node is Element {\n return (\n node.nodeType === 1 &&\n (node as Element).localName === vnode.tag &&\n (node as Element).namespaceURI === ns\n )\n}\n\n/**\n * Claim server-rendered DOM for a tree: the element takes the vnode's\n * attributes (extra ones are removed), and its children are matched by\n * position: text with text, elements with the same tag (hydrated in turn).\n * Anything that does not match is created in place, leftovers are removed.\n * Afterwards the nodes are tracked like freshly rendered ones.\n */\nexport function hydrateElement(el: Element, vnode: VNode): void {\n // The server attributes are the previous state to patch from.\n const current: Attrs = {}\n for (const name of el.getAttributeNames()) current[name] = el.getAttribute(name) as string\n // A strict CSP ignores style attributes in markup: set them again, through the CSSOM.\n if (current.style) current.style = ''\n patchAttrs(el, current, vnode.attrs)\n\n // Comments never stand for anything, and neither does text where the tree has none\n // (whitespace between elements). Text only ever sits in leaf elements here.\n const texts = vnode.children.some((child) => typeof child === 'string')\n for (const node of Array.from(el.childNodes)) {\n if (node.nodeType === 8 || (!texts && node.nodeType === 3)) el.removeChild(node)\n }\n\n const ns = childNamespace(el)\n let node: Node | null = el.firstChild\n for (const child of vnode.children) {\n const next: Node | null = node ? node.nextSibling : null\n if (\n typeof child === 'string'\n ? node?.nodeType === 3\n : node && matches(node, child, child.tag === 'svg' ? SVG_NS : ns)\n ) {\n if (typeof child === 'string') {\n if ((node as Text).data !== child) (node as Text).data = child\n rendered.set(node as Node, child)\n } else {\n hydrateElement(node as Element, child)\n }\n node = next\n } else {\n const created = createNode(child, ns, el.ownerDocument)\n if (created) el.insertBefore(created, node)\n }\n }\n while (node) {\n const extra: Node = node\n node = node.nextSibling\n el.removeChild(extra)\n }\n rendered.set(el, vnode)\n}\n\n/**\n * Hydrate `el` for the root `vnode` when it is foreign markup (not rendered\n * here) with the root's tag in namespace `ns`. Returns whether it did.\n */\nexport function hydrate(el: Element, vnode: VNode, ns: string): boolean {\n if (rendered.has(el) || !matches(el, vnode, ns)) return false\n hydrateElement(el, vnode)\n return true\n}\n","/**\n * Paths redrawn frame by frame, shared by `morph` and `sweep`: numbers go\n * from where they are to where they end with an ease-out curve, and each\n * frame draws the `d` of the numbers in between.\n */\n\n/** The running tween of each path: its frame request and the numbers drawn now. */\nconst running = /* @__PURE__ */ new WeakMap<Element, { frame: number; now: number[] }>()\n\n/** Stop the tween of `el`, if any; returns the numbers it had reached. */\nexport function stop(el: Element): number[] | undefined {\n const current = running.get(el)\n if (current) cancelAnimationFrame(current.frame)\n running.delete(el)\n return current?.now\n}\n\n/**\n * Take the numbers from `origin` to `end` over `duration` ms, setting the\n * `d` of `el` to `draw(numbers)` on each frame and to `to` on the last.\n */\nexport function tween(\n el: Element,\n origin: readonly number[],\n end: readonly number[],\n duration: number,\n draw: (now: number[]) => string,\n to: string,\n): void {\n const state = { frame: 0, now: origin.slice() }\n const begin = performance.now()\n const step = (time: number) => {\n const t = Math.min(1, Math.max(0, (time - begin) / duration))\n // Ease out, close to the default --tc-easing (a custom easing is approximated).\n const k = 1 - (1 - t) ** 3\n state.now = end.map((value, i) => (origin[i] as number) + (value - (origin[i] as number)) * k)\n el.setAttribute('d', t < 1 ? draw(state.now) : to)\n if (t < 1) state.frame = requestAnimationFrame(step)\n else running.delete(el)\n }\n running.set(el, state)\n state.frame = requestAnimationFrame(step)\n}\n","/**\n * Path morphing for browsers that cannot transition `d` in CSS (Safari):\n * when a patch changes the `d` of a path whose style asks for a `d`\n * transition, the numbers in the path are interpolated frame by frame\n * instead, over the transition's duration with an ease-out curve. Chart\n * paths keep their commands between renders, so only the numbers move; a\n * path whose commands changed jumps, as it would in CSS too.\n */\n\nimport { round } from '../layout.ts'\nimport { stop, tween } from './tween.ts'\n\nconst NUMBER = /-?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[-+]?\\d+)?/gi\n\nlet native: boolean | undefined\n\n/**\n * Change `el`'s `d` from `from` to `to` over its CSS transition, frame by\n * frame. Returns `false` when the browser transitions `d` itself, or the\n * path is not meant to move (the caller then just sets the attribute).\n */\nexport function morph(el: Element, from: string, to: string): boolean {\n native ??= typeof CSS === 'undefined' || CSS.supports('d', 'path(\"M0 0\")')\n const current = stop(el)\n // A chart without transitions (too big to animate, or resizing) has nothing to\n // morph: said here, before asking for the style of each of its paths.\n if (native || el.closest('.tc-static,[data-resizing]')) return false\n\n const style = getComputedStyle(el)\n const index = style.transitionProperty.split(', ').findIndex((p) => p === 'd' || p === 'all')\n const duration =\n index < 0 ? 0 : Number.parseFloat(style.transitionDuration.split(', ')[index] ?? '') * 1000\n const text = to.split(NUMBER)\n const end = to.match(NUMBER)?.map(Number) ?? []\n const start = from.match(NUMBER)?.map(Number) ?? []\n if (!(duration > 0) || start.length !== end.length || from.split(NUMBER).join() !== text.join()) {\n return false\n }\n\n // An interrupted morph continues from where the path is now.\n tween(\n el,\n current?.length === end.length ? current : start,\n end,\n duration,\n (now) =>\n now.reduce((d, value, i) => d + round(value) + (text[i + 1] as string), text[0] as string),\n to,\n )\n return true\n}\n","import type { Point } from './path.ts'\n\n/**\n * Largest-Triangle-Three-Buckets downsampling (Sveinn Steinarsson, 2013):\n * keep roughly `threshold` points that preserve the visual shape of a line,\n * including its peaks and valleys.\n *\n * Returns the indices to keep, in order. Gaps (`null` points) are kept as\n * gap markers and every run between gaps is sampled on its own, so the\n * result lines up with any per-index data (e.g. stacked baselines).\n */\nexport function lttbIndices(points: readonly Point[], threshold: number): number[] {\n const n = points.length\n if (!(threshold >= 3) || n <= threshold) return points.map((_, i) => i)\n\n // Split into runs of valid points.\n const runs: [number, number][] = []\n let start = -1\n for (let i = 0; i < n; i++) {\n const valid = points[i] != null\n if (valid && start === -1) start = i\n if (!valid && start !== -1) {\n runs.push([start, i])\n start = -1\n }\n }\n if (start !== -1) runs.push([start, n])\n const valid = runs.reduce((sum, [a, b]) => sum + (b - a), 0)\n\n const out: number[] = []\n let last = 0\n for (const [a, b] of runs) {\n // One gap marker between runs; everything else in the gap is dropped.\n if (a > last) out.push(last)\n // Each run gets a share of the budget (at least its two ends).\n const budget = Math.max(2, Math.round((threshold * (b - a)) / valid))\n sampleRun(points, a, b, budget, out)\n last = b\n }\n if (last < n) out.push(last)\n return out\n}\n\n/** LTTB over `points[from, to)`, pushing kept indices to `out`. */\nfunction sampleRun(\n points: readonly Point[],\n from: number,\n to: number,\n budget: number,\n out: number[],\n): void {\n const n = to - from\n if (n <= budget) {\n for (let i = from; i < to; i++) out.push(i)\n return\n }\n const at = (i: number) => points[i] as readonly [number, number]\n const bucketSize = (n - 2) / (budget - 2)\n let a = from\n out.push(a)\n\n for (let bucket = 0; bucket < budget - 2; bucket++) {\n // Average of the next bucket is the third corner of every candidate triangle.\n const nextStart = from + 1 + Math.floor((bucket + 1) * bucketSize)\n const nextEnd = Math.min(to, from + 1 + Math.floor((bucket + 2) * bucketSize))\n let avgX = 0\n let avgY = 0\n for (let i = nextStart; i < nextEnd; i++) {\n avgX += at(i)[0]\n avgY += at(i)[1]\n }\n const count = Math.max(1, nextEnd - nextStart)\n avgX /= count\n avgY /= count\n\n // The point of this bucket forming the largest triangle with `a` and the average.\n const rangeStart = from + 1 + Math.floor(bucket * bucketSize)\n const rangeEnd = Math.min(to - 1, from + 1 + Math.floor((bucket + 1) * bucketSize))\n const [ax, ay] = at(a)\n let best = rangeStart\n let bestArea = -1\n for (let i = rangeStart; i < rangeEnd; i++) {\n const [x, y] = at(i)\n const area = Math.abs((ax - avgX) * (y - ay) - (ax - x) * (avgY - ay))\n if (area > bestArea) {\n bestArea = area\n best = i\n }\n }\n out.push(best)\n a = best\n }\n out.push(to - 1)\n}\n\n/** The points kept by {@link lttbIndices}, gaps included. */\nexport function lttb(points: readonly Point[], threshold: number): Point[] {\n return lttbIndices(points, threshold).map((i) => points[i])\n}\n","/** A point in pixels; `null` (or a non-finite coordinate) marks a gap. */\nexport type Point = readonly [x: number, y: number] | null | undefined\n\n/** Curve used to connect consecutive points. */\nexport type Curve = 'linear' | 'monotone' | 'step' | 'step-before' | 'step-after'\n\nexport interface PathOptions {\n /** Interpolation between points. Defaults to `'linear'`. */\n curve?: Curve\n /** Decimal places kept in the path data. Defaults to `2`. */\n precision?: number\n}\n\ntype Pt = readonly [number, number]\n\n/** Accumulates SVG path commands with rounded coordinates. */\nclass PathBuilder {\n d = ''\n readonly #k: number\n\n constructor(precision: number) {\n this.#k = 10 ** Math.max(0, Math.min(12, Math.floor(precision)))\n }\n\n #n(value: number): string {\n const rounded = Math.round(value * this.#k) / this.#k\n return String(rounded === 0 ? 0 : rounded)\n }\n\n #xy(x: number, y: number): string {\n return `${this.#n(x)},${this.#n(y)}`\n }\n\n moveTo(x: number, y: number): void {\n this.d += `M${this.#xy(x, y)}`\n }\n\n lineTo(x: number, y: number): void {\n this.d += `L${this.#xy(x, y)}`\n }\n\n curveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void {\n this.d += `C${this.#xy(x1, y1)},${this.#xy(x2, y2)},${this.#xy(x, y)}`\n }\n\n close(): void {\n this.d += 'Z'\n }\n}\n\n/**\n * Emit `points` with a curve. The first point is a `moveTo` when `move` is\n * true, otherwise a `lineTo` (continuing an existing subpath). Returns the\n * number of points drawn.\n */\nfunction emit(path: PathBuilder, input: readonly Pt[], curve: Curve, move: boolean): number {\n // Monotone tangents break on zero-length segments, so drop coincident points.\n const points = curve === 'monotone' ? dedupe(input) : input\n const first = points[0]\n if (!first) return 0\n if (move) path.moveTo(first[0], first[1])\n else path.lineTo(first[0], first[1])\n\n switch (curve) {\n case 'monotone':\n monotone(path, points)\n break\n case 'step':\n step(path, points, 0.5)\n break\n case 'step-before':\n step(path, points, 0)\n break\n case 'step-after':\n step(path, points, 1)\n break\n default:\n for (let i = 1; i < points.length; i++) {\n const p = points[i] as Pt\n path.lineTo(p[0], p[1])\n }\n }\n return points.length\n}\n\nfunction dedupe(points: readonly Pt[]): readonly Pt[] {\n return points.filter((p, i) => {\n const prev = points[i - 1]\n return !prev || p[0] !== prev[0] || p[1] !== prev[1]\n })\n}\n\nfunction step(path: PathBuilder, points: readonly Pt[], t: number): void {\n for (let i = 1; i < points.length; i++) {\n const [x0, y0] = points[i - 1] as Pt\n const [x1, y1] = points[i] as Pt\n if (t <= 0) {\n path.lineTo(x0, y1)\n path.lineTo(x1, y1)\n } else if (t >= 1) {\n path.lineTo(x1, y0)\n path.lineTo(x1, y1)\n } else {\n const xm = x0 * (1 - t) + x1 * t\n path.lineTo(xm, y0)\n path.lineTo(xm, y1)\n // The next horizontal run continues from here, so only the last point is needed.\n if (i === points.length - 1) path.lineTo(x1, y1)\n }\n }\n}\n\nconst sign = (x: number): number => (x < 0 ? -1 : 1)\n\n/**\n * Monotone cubic interpolation in x (Steffen, 1990), as in d3's\n * `curveMonotoneX`: smooth, but never overshoots the data.\n */\nfunction monotone(path: PathBuilder, points: readonly Pt[]): void {\n const n = points.length\n if (n < 2) return\n if (n === 2) {\n const p = points[1] as Pt\n path.lineTo(p[0], p[1])\n return\n }\n\n const tangents = new Array<number>(n)\n for (let i = 1; i < n - 1; i++) {\n const [x0, y0] = points[i - 1] as Pt\n const [x1, y1] = points[i] as Pt\n const [x2, y2] = points[i + 1] as Pt\n const h0 = x1 - x0\n const h1 = x2 - x1\n const s0 = (y1 - y0) / (h0 || (h1 < 0 ? -0 : 0))\n const s1 = (y2 - y1) / (h1 || (h0 < 0 ? -0 : 0))\n const p = (s0 * h1 + s1 * h0) / (h0 + h1)\n tangents[i] =\n (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0\n }\n tangents[0] = endTangent(points[0] as Pt, points[1] as Pt, tangents[1] as number)\n tangents[n - 1] = endTangent(points[n - 2] as Pt, points[n - 1] as Pt, tangents[n - 2] as number)\n\n for (let i = 1; i < n; i++) {\n const [x0, y0] = points[i - 1] as Pt\n const [x1, y1] = points[i] as Pt\n const dx = (x1 - x0) / 3\n path.curveTo(\n x0 + dx,\n y0 + dx * (tangents[i - 1] as number),\n x1 - dx,\n y1 - dx * (tangents[i] as number),\n x1,\n y1,\n )\n }\n}\n\n/** One-sided tangent for the first/last point from the neighbour's tangent. */\nfunction endTangent(a: Pt, b: Pt, t: number): number {\n const h = b[0] - a[0]\n return h ? (3 * (b[1] - a[1])) / h / 2 - t / 2 : t\n}\n\nconst isValid = (p: Point): p is Pt => p != null && Number.isFinite(p[0]) && Number.isFinite(p[1])\n\n/** Split points into runs of consecutive valid points, keeping their indices. */\nfunction runs(points: readonly Point[], valid: (i: number) => boolean = () => true): number[][] {\n const out: number[][] = []\n let current: number[] | undefined\n for (let i = 0; i < points.length; i++) {\n if (isValid(points[i]) && valid(i)) {\n if (!current) {\n current = []\n out.push(current)\n }\n current.push(i)\n } else {\n current = undefined\n }\n }\n return out\n}\n\n/**\n * Build the `d` attribute of a line through `points`. Gaps (`null`/`NaN`)\n * start a new subpath; a lone point renders as `M x,y Z`.\n *\n * ```ts\n * linePath([[0, 10], [50, 40], null, [100, 20]], { curve: 'monotone' })\n * ```\n */\nexport function linePath(points: readonly Point[], options: PathOptions = {}): string {\n const { curve = 'linear', precision = 2 } = options\n const path = new PathBuilder(precision)\n for (const run of runs(points)) {\n const drawn = emit(\n path,\n run.map((i) => points[i] as Pt),\n curve,\n true,\n )\n if (drawn === 1) path.close()\n }\n return path.d\n}\n\n/**\n * Build the `d` attribute of an area between `points` and a `baseline`:\n * a constant y (e.g. the zero line) or one y per point (stacked areas).\n * Each run of valid points becomes a closed subpath.\n */\nexport function areaPath(\n points: readonly Point[],\n baseline: number | readonly (number | null | undefined)[],\n options: PathOptions = {},\n): string {\n const { curve = 'linear', precision = 2 } = options\n const path = new PathBuilder(precision)\n const baseAt = (i: number): number =>\n typeof baseline === 'number' ? baseline : (baseline[i] ?? Number.NaN)\n\n for (const run of runs(points, (i) => Number.isFinite(baseAt(i)))) {\n emit(\n path,\n run.map((i) => points[i] as Pt),\n curve,\n true,\n )\n\n const bottom = run.map((i) => [(points[i] as Pt)[0], baseAt(i)] as const).reverse()\n // Walking backwards mirrors step curves, so stacked steps line up. A flat\n // baseline takes the same curve (it stays straight) so that the path keeps\n // its commands between flat and stacked, and CSS can morph one into the other.\n const back =\n curve === 'step-before' ? 'step-after' : curve === 'step-after' ? 'step-before' : curve\n emit(path, bottom, back, false)\n path.close()\n }\n return path.d\n}\n","import { feature } from '../features.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { render } from '../render/dom.ts'\nimport { h } from '../vnode.ts'\n\n/** A file format of the download menu. */\nexport type DownloadFormat = 'png' | 'svg' | 'jpeg' | 'webp'\n\n/** The `download` option as an object. */\nexport interface DownloadMenuOptions {\n /** Formats offered, in this order. Defaults to `['png', 'svg']`. */\n formats?: readonly DownloadFormat[]\n /** File name without the extension. Defaults to the chart's title, or `chart`. */\n filename?: string\n /** Accessible name of the menu button. Defaults to `'Download'`. */\n label?: string\n /**\n * Background color, `'auto'` for the chart's surface (`--tc-surface`), or\n * `false` for none (transparent). Defaults to `'auto'`.\n */\n background?: string | false\n /** Draw the legend into the file. Defaults to `true`. */\n legend?: boolean\n /** Pixels per chart pixel in images. Defaults to `2`. */\n scale?: number\n}\n\n/** The `download` option: on, a list of formats, or the options. */\nexport type DownloadOption = boolean | readonly DownloadFormat[] | DownloadMenuOptions\n\nconst NAMES: Record<DownloadFormat, string> = { png: 'PNG', svg: 'SVG', jpeg: 'JPEG', webp: 'WebP' }\nconst DEFAULT_FORMATS: readonly DownloadFormat[] = ['png', 'svg']\n\nfunction resolve(option: DownloadOption): DownloadMenuOptions {\n return option === true\n ? {}\n : Array.isArray(option)\n ? { formats: option }\n : (option as DownloadMenuOptions)\n}\n\n/**\n * A download menu in the chart's corner (`.tc-download`): a button that opens\n * a list of file formats, PNG and SVG by default. Shown with the `download`\n * option. The files come from `@tabler/charts/export`, which must be imported\n * (the chart says so otherwise): that way charts without a download never\n * carry the export code.\n */\nexport function download(): ChartPlugin {\n return {\n name: 'download',\n install(chart) {\n const host = chart.element\n const doc = host.ownerDocument\n let el: HTMLElement | undefined\n let options: DownloadMenuOptions = {}\n // The menu overlays the chart: the container is the positioning context.\n const addedClass = !host.classList.contains('tc-container')\n\n const toggle = () => el?.querySelector<HTMLElement>('.tc-download-toggle')\n const menu = () => el?.querySelector<HTMLElement>('.tc-download-menu')\n const items = () => Array.from(el?.querySelectorAll<HTMLElement>('.tc-download-item') ?? [])\n\n const setOpen = (open: boolean) => {\n const list = menu()\n if (!list) return\n list.hidden = !open\n toggle()?.setAttribute('aria-expanded', String(open))\n if (open) doc.addEventListener('pointerdown', onOutside, true)\n else doc.removeEventListener('pointerdown', onOutside, true)\n }\n const isOpen = () => menu()?.hidden === false\n\n const onOutside = (event: Event) => {\n if (!el?.contains(event.target as Node)) setOpen(false)\n }\n\n const onClick = (event: Event) => {\n const target = event.target as Element\n if (target.closest('.tc-download-toggle')) {\n setOpen(!isOpen())\n if (isOpen()) items()[0]?.focus()\n return\n }\n const format = target.closest('.tc-download-item')?.getAttribute('data-format')\n if (!format) return\n setOpen(false)\n toggle()?.focus()\n void feature('export')(chart, { ...options, format: format as DownloadFormat })\n }\n\n const onKey = (event: KeyboardEvent) => {\n if (event.key === 'Escape' && isOpen()) {\n event.preventDefault()\n setOpen(false)\n toggle()?.focus()\n return\n }\n if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return\n const list = items()\n if (!list.length) return\n event.preventDefault()\n if (!isOpen()) setOpen(true)\n const at = list.indexOf(doc.activeElement as HTMLElement)\n const step = event.key === 'ArrowDown' ? 1 : -1\n list[(at + step + list.length) % list.length]?.focus()\n }\n\n // Tabbing out of the menu closes it.\n const onBlur = (event: FocusEvent) => {\n if (!el?.contains(event.relatedTarget as Node)) setOpen(false)\n }\n\n const remove = () => {\n if (!el) return\n setOpen(false)\n render(el, null)\n el.remove()\n el = undefined\n if (addedClass) host.classList.remove('tc-container')\n }\n\n return {\n afterRender({ config, changed }) {\n const option = config.download\n if (!option || typeof document === 'undefined') {\n remove()\n return\n }\n // Resizing and hovering change nothing in the menu.\n if (!changed && el?.isConnected) return\n // Fail early, at render, when the export entry is not imported.\n feature('export')\n options = resolve(option)\n const formats = options.formats?.length ? options.formats : DEFAULT_FORMATS\n if (!el) {\n el = doc.createElement('div')\n el.className = 'tc-download'\n el.addEventListener('click', onClick)\n el.addEventListener('keydown', onKey)\n el.addEventListener('focusout', onBlur)\n }\n render(\n el,\n h(\n 'div',\n { class: 'tc-download-box' },\n h(\n 'button',\n {\n type: 'button',\n class: 'tc-download-toggle',\n 'aria-label': options.label ?? 'Download',\n 'aria-haspopup': 'menu',\n 'aria-expanded': 'false',\n },\n h(\n 'svg',\n {\n viewBox: '0 0 24 24',\n width: '16',\n height: '16',\n 'aria-hidden': 'true',\n fill: 'none',\n stroke: 'currentColor',\n 'stroke-width': '2',\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round',\n },\n h('path', {\n d: 'M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2M7 11l5 5 5-5M12 4v12',\n }),\n ),\n ),\n h(\n 'div',\n { class: 'tc-download-menu', role: 'menu', hidden: '' },\n formats.map((format) =>\n h(\n 'button',\n {\n key: format,\n type: 'button',\n role: 'menuitem',\n class: 'tc-download-item',\n 'data-format': format,\n },\n NAMES[format] ?? format,\n ),\n ),\n ),\n ),\n )\n host.classList.add('tc-container')\n if (!el.isConnected) host.appendChild(el)\n },\n destroy: remove,\n }\n },\n }\n}\n","import type { Hit } from '../interaction.ts'\nimport { round } from '../layout.ts'\nimport { h, type VNode } from '../vnode.ts'\n\n/** Series wrapper so hover marks pick up the series color from CSS. */\nfunction seriesGroup(seriesIndex: number, color: string | undefined, child: VNode): VNode {\n return h(\n 'g',\n {\n key: seriesIndex,\n class: ['tc-series', `tc-series-${seriesIndex + 1}`],\n style: { '--tc-series-color': color },\n },\n child,\n )\n}\n\n/**\n * Hover marks drawn below the series: a band behind the hovered category of\n * band charts (bars), or a vertical crosshair for point charts (lines).\n */\nexport function hoverUnderlay(hit: Hit, crosshair = true): VNode {\n const { area } = hit\n return h(\n 'g',\n { class: 'tc-hover', 'aria-hidden': 'true' },\n hit.mark\n ? null\n : hit.band\n ? h('rect', {\n class: 'tc-hover-band',\n x: round(hit.band.x),\n y: round(hit.band.y),\n width: round(hit.band.width),\n height: round(hit.band.height),\n })\n : crosshair &&\n h(\n 'line',\n hit.guide\n ? {\n class: 'tc-crosshair',\n x1: round(hit.guide.x1),\n x2: round(hit.guide.x2),\n y1: round(hit.guide.y1),\n y2: round(hit.guide.y2),\n }\n : {\n class: 'tc-crosshair',\n x1: round(hit.x),\n x2: round(hit.x),\n y1: round(area.y),\n y2: round(area.y + area.height),\n },\n ),\n )\n}\n\n/**\n * Hover marks drawn above the series: the hit's own mark (pie slices), or\n * an active dot on every point of point charts (of the series' `shape`, if given).\n */\nexport function hoverOverlay(\n hit: Hit,\n radius = 4,\n shape?: (slot: number, x: number, y: number, r: number) => string,\n): VNode {\n const { mark } = hit\n if (mark) {\n const item = hit.items.find((i) => i.seriesIndex === hit.seriesIndex) ?? hit.items[0]\n return h(\n 'g',\n { class: 'tc-hover', 'aria-hidden': 'true' },\n item &&\n seriesGroup(\n item.seriesIndex,\n item.color,\n h('path', {\n class: 'tc-hover-mark',\n d: mark.d,\n style: `transform:translate(${round(mark.x)}px,${round(mark.y)}px)`,\n }),\n ),\n )\n }\n return h(\n 'g',\n { class: 'tc-hover', 'aria-hidden': 'true' },\n !hit.band &&\n hit.items.map(\n (item) =>\n item.y !== null &&\n seriesGroup(\n item.seriesIndex,\n item.color,\n shape\n ? h('path', {\n class: 'tc-point tc-point-active tc-marker',\n d: shape(item.seriesIndex, item.x, item.y, radius),\n })\n : h('circle', {\n class: 'tc-point tc-point-active',\n cx: round(item.x),\n cy: round(item.y),\n r: radius,\n }),\n ),\n ),\n )\n}\n","import type { Chart } from '../chart.ts'\nimport { toChartPoint } from '../interaction.ts'\nimport type { ChartPlugin } from '../plugin.ts'\n\nconst listening = /* @__PURE__ */ new WeakSet<object>()\n\n/**\n * Turn pointer input on the chart's element into highlights and `hover` /\n * `click` events (once per chart, however many plugins ask). Returns the\n * function that stops listening, or nothing when already listening.\n */\nexport function listenPointer(chart: Chart<object>): (() => void) | undefined {\n const el = chart.element\n if (listening.has(chart) || typeof el.addEventListener !== 'function') return undefined\n listening.add(chart)\n const local = (event: MouseEvent) => {\n const svg = el.querySelector('svg.tc-chart')\n if (!svg) return undefined\n const { width, height } = chart.size\n return toChartPoint(svg, event.clientX, event.clientY, width, height)\n }\n const onMove = (event: PointerEvent) => {\n const point = local(event)\n if (point) chart.highlightAt(point.x, point.y, event)\n }\n const onLeave = (event: PointerEvent) => {\n // On touch, keep the last highlight after the finger lifts.\n if (event.pointerType !== 'touch' && chart.highlightSource === 'pointer') {\n chart.clearHighlight(event)\n }\n }\n const onClick = (event: MouseEvent) => {\n const point = local(event)\n const hit = point ? chart.hitTest(point.x, point.y) : null\n if (hit) chart.emit('click', { hit, event })\n }\n el.addEventListener('pointermove', onMove as EventListener)\n el.addEventListener('pointerdown', onMove as EventListener)\n el.addEventListener('pointerleave', onLeave as EventListener)\n el.addEventListener('click', onClick as EventListener)\n return () => {\n listening.delete(chart)\n el.removeEventListener('pointermove', onMove as EventListener)\n el.removeEventListener('pointerdown', onMove as EventListener)\n el.removeEventListener('pointerleave', onLeave as EventListener)\n el.removeEventListener('click', onClick as EventListener)\n }\n}\n\n/**\n * Pointer input: hovering highlights what is under the pointer and emits\n * `hover`, clicking emits `click`. The highlight and tooltip plugins turn it\n * on themselves; add it to a bare `Chart` that only needs the events.\n */\nexport function pointer(): ChartPlugin {\n return {\n name: 'pointer',\n install(chart) {\n const stop = listenPointer(chart)\n return stop ? { destroy: stop } : {}\n },\n }\n}\n","import { markerShape } from '../charts/cartesian.ts'\nimport { hoverOverlay, hoverUnderlay } from '../components/hover.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { listenPointer } from './pointer.ts'\n\n/**\n * Draws the highlighted category: a crosshair (or a band behind bars) under\n * the series and active dots above them. `crosshair: false` keeps the dots.\n */\nexport function highlight(): ChartPlugin {\n return {\n name: 'highlight',\n install(chart) {\n const stop = listenPointer(chart)\n return {\n layers: (hit, config) => ({\n under: hoverUnderlay(hit, config.crosshair !== false),\n over: hoverOverlay(hit, 4, markerShape(config)),\n }),\n ...(stop ? { destroy: stop } : {}),\n }\n },\n }\n}\n","import type { Hit } from './interaction.ts'\nimport { h, type VNode } from './vnode.ts'\n\n/** The data behind a chart as text: header cells and one row per category. */\nexport interface DataTable {\n /** Column headers; the first one labels the row headers (may be empty). */\n columns: string[]\n /** Rows of display text; the first cell of each row is its header. */\n rows: string[][]\n /** Total number of rows when `rows` was cut to a limit. */\n total?: number\n}\n\n/**\n * An HTML table of the chart data, for screen readers (visually hidden by\n * default) or as a visible fallback. Every cell is text, escaped by the renderer.\n */\nexport function tableContent(table: DataTable, caption?: string): VNode {\n const [corner = '', ...headers] = table.columns\n return h(\n 'table',\n { class: 'tc-table' },\n caption && h('caption', null, caption),\n h(\n 'thead',\n null,\n h(\n 'tr',\n null,\n h('th', { scope: 'col' }, corner),\n headers.map((name, i) => h('th', { key: i, scope: 'col' }, name)),\n ),\n ),\n h(\n 'tbody',\n null,\n table.rows.map(([head = '', ...cells], i) =>\n h(\n 'tr',\n { key: i },\n h('th', { scope: 'row' }, head),\n cells.map((cell, j) => h('td', { key: j }, cell)),\n ),\n ),\n ),\n )\n}\n\n/** Short sentence describing a hit, announced during keyboard navigation. */\nexport function describeHit(hit: Hit): string {\n const items =\n hit.seriesIndex === undefined\n ? hit.items\n : hit.items.filter((item) => item.seriesIndex === hit.seriesIndex)\n const values = items.map((item) => `${item.name} ${item.text}`).join(', ')\n return hit.title ? `${hit.title}: ${values}` : values\n}\n","import { describeHit } from '../a11y.ts'\nimport type { ChartPlugin } from '../plugin.ts'\n\n/**\n * Keyboard navigation: the SVG becomes focusable; arrow keys walk\n * categories, Up/Down walk series, Home/End jump, Escape (or leaving)\n * clears. Every step is announced through a polite live region.\n */\n/** The config's `keyboard` option, else the chart type's default, else on. */\nconst enabled = (config: { keyboard?: boolean; type: { keyboard?: boolean } }): boolean =>\n config.keyboard ?? config.type.keyboard ?? true\n\nexport function keyboard(): ChartPlugin {\n return {\n name: 'keyboard',\n install(chart) {\n const host = chart.element\n let live: HTMLElement | undefined\n\n /**\n * The live region, added when the chart takes focus: screen readers only\n * announce changes of a region that was already there, so one created\n * with its first message would stay silent for that message.\n */\n const region = (): HTMLElement => {\n if (!live) {\n live = host.ownerDocument.createElement('div')\n live.className = 'tc-sr-only'\n live.setAttribute('aria-live', 'polite')\n live.setAttribute('aria-atomic', 'true')\n host.appendChild(live)\n }\n return live\n }\n const announce = (text: string) => {\n region().textContent = text\n }\n\n const go = (index: number, seriesIndex?: number) => {\n const hit = chart.highlightIndex(index, seriesIndex)\n if (hit) announce(describeHit(hit))\n }\n\n /** Returns whether the key was handled. */\n const handle = (key: string): boolean => {\n const interaction = chart.interaction\n if (!interaction || interaction.count === 0) return false\n const current = chart.highlightSource === 'index' ? chart.active : null\n const last = interaction.count - 1\n const index = current?.index\n const focused = current?.seriesIndex\n const series = current?.items.map((item) => item.seriesIndex) ?? []\n const at = focused === undefined ? -1 : series.indexOf(focused)\n\n switch (key) {\n case 'ArrowRight':\n go(index === undefined ? 0 : Math.min(last, index + 1), focused)\n return true\n case 'ArrowLeft':\n go(index === undefined ? last : Math.max(0, index - 1), focused)\n return true\n case 'Home':\n go(0, focused)\n return true\n case 'End':\n go(last, focused)\n return true\n case 'ArrowDown':\n case 'ArrowUp': {\n if (index === undefined || series.length === 0) {\n go(0)\n return true\n }\n const step = key === 'ArrowDown' ? 1 : -1\n const next = at === -1 ? (step > 0 ? 0 : series.length - 1) : at + step\n go(index, next < 0 || next >= series.length ? undefined : series[next])\n return true\n }\n case 'Escape':\n if (!current) return false\n chart.clearHighlight()\n return true\n default:\n return false\n }\n }\n\n const isChart = (target: EventTarget | null) =>\n (target as Element | null)?.matches?.('svg.tc-chart') === true\n const onKey = (event: Event) => {\n const { key } = event as KeyboardEvent\n if (!enabled(chart.config) || !isChart(event.target)) return\n if (handle(key)) event.preventDefault()\n }\n const onBlur = (event: Event) => {\n if (isChart(event.target) && chart.highlightSource === 'index') chart.clearHighlight()\n }\n const onFocus = (event: Event) => {\n if (enabled(chart.config) && isChart(event.target)) region()\n }\n host.addEventListener('keydown', onKey)\n host.addEventListener('focusin', onFocus)\n host.addEventListener('focusout', onBlur)\n\n return {\n svgAttrs: (config) => (enabled(config) ? { tabindex: 0 } : undefined),\n destroy() {\n host.removeEventListener('keydown', onKey)\n host.removeEventListener('focusin', onFocus)\n host.removeEventListener('focusout', onBlur)\n live?.remove()\n },\n }\n },\n }\n}\n","import { legendContent } from '../legend.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { render } from '../render/dom.ts'\n\n/**\n * An HTML legend (`.tc-legend`) with toggle buttons, above or below the SVG.\n * Shown for two or more entries unless the `legend` option says otherwise.\n */\nexport function legend(): ChartPlugin {\n return {\n name: 'legend',\n install(chart) {\n const host = chart.element\n // Take over a server-rendered legend instead of adding a second one.\n let el = host.querySelector<HTMLElement>(':scope > .tc-legend') ?? undefined\n let adopt = el?.firstElementChild ?? null\n let bound = false\n const onClick = (event: Event) => {\n const button = (event.target as Element).closest?.('.tc-legend-item')\n const key = button?.getAttribute('data-key')\n if (key != null) chart.toggleSeries(key)\n }\n\n const remove = () => {\n if (!el) return\n render(el, null)\n el.removeEventListener('click', onClick)\n bound = false\n el.remove()\n el = undefined\n }\n\n /** Keep the legend right before or after the SVG, whatever else lives in the container. */\n const place = () => {\n if (!el) return\n const svg = host.querySelector(':scope > svg.tc-chart')\n if (el.dataset.position === 'bottom') {\n if (!svg) {\n if (!el.isConnected) host.appendChild(el)\n } else if (svg.nextElementSibling !== el) {\n svg.after(el)\n }\n } else if (!el.isConnected || el.nextElementSibling !== svg) {\n host.insertBefore(el, svg ?? host.firstChild)\n }\n }\n\n return {\n beforeRender({ legend, hidden }) {\n if (!legend.show || typeof document === 'undefined') {\n remove()\n return\n }\n if (!el) {\n el = host.ownerDocument.createElement('div')\n el.className = 'tc-legend'\n }\n if (!bound) {\n el.addEventListener('click', onClick)\n bound = true\n }\n el.dataset.position = legend.position\n render(el, legendContent(legend.items, hidden), adopt)\n adopt = null\n place()\n },\n // With its margin: the gap to the chart is taken from the container too.\n reservedHeight() {\n if (!el?.isConnected) return 0\n const { marginTop, marginBottom } = getComputedStyle(el)\n return (\n el.offsetHeight +\n (Number.parseFloat(marginTop) || 0) +\n (Number.parseFloat(marginBottom) || 0)\n )\n },\n afterRender: place,\n destroy: remove,\n }\n },\n }\n}\n","import type { Chart } from '../chart.ts'\nimport type { Interaction } from '../interaction.ts'\nimport type { ChartPlugin } from '../plugin.ts'\n\n/** Charts by `sync` group, held weakly: a chart taken out without destroy() is let go. */\nconst groups = /* @__PURE__ */ new Map<string, Set<WeakRef<Chart<object>>>>()\n\n/** The index of each category label, per render of a chart. */\nconst indexes = /* @__PURE__ */ new WeakMap<Interaction, Map<string | number, number>>()\n\n/** Set while a highlight is passed on, so the charts it reaches do not pass it on again. */\nlet passing = false\n\n/** The index of the category with `label` in a chart's current render, if it has one. */\nfunction indexOf(interaction: Interaction, label: string | number): number | undefined {\n let index = indexes.get(interaction)\n if (!index) {\n index = new Map()\n for (let i = 0; i < interaction.count; i++) {\n const hit = interaction.hitIndex(i)\n if (hit && !index.has(hit.label)) index.set(hit.label, i)\n }\n indexes.set(interaction, index)\n }\n return index.get(label)\n}\n\n/**\n * Shared hover across charts: charts with the same `sync` group highlight\n * the category under the pointer in any of them (with its crosshair and\n * tooltip), matched by label, and clear together when it leaves. Keyboard\n * highlights stay in their own chart.\n */\nexport function sync(): ChartPlugin {\n return {\n name: 'sync',\n install(chart) {\n const self = new WeakRef(chart)\n let group: Set<WeakRef<Chart<object>>> | undefined\n /** The name of the group joined: the config may have moved on before the next render. */\n let joined: string | undefined\n /** Leave the group, and take it off the list when it is empty. */\n const leave = () => {\n group?.delete(self)\n if (joined && group?.size === 0 && groups.get(joined) === group) groups.delete(joined)\n }\n /** Join the group of the current config, leaving the one before. */\n const join = () => {\n const name = chart.config.sync\n const next = name ? (groups.get(name) ?? new Set()) : undefined\n if (next === group) return\n leave()\n if (name && next) {\n next.add(self)\n groups.set(name, next)\n }\n group = next\n joined = name\n }\n join()\n const off = chart.on('hover', ({ hit }) => {\n // Only the pointer leads; keyboard highlights and highlights passed on do not.\n if (passing || !group || (hit && chart.highlightSource !== 'pointer')) return\n passing = true\n try {\n for (const ref of group) {\n const other = ref.deref()\n if (!other) group.delete(ref)\n if (!other || other === chart) continue\n const index = hit && other.interaction && indexOf(other.interaction, hit.label)\n if (index === undefined || index === null) other.clearHighlight()\n else other.highlightIndex(index)\n }\n } finally {\n passing = false\n }\n })\n return {\n afterRender: join,\n destroy() {\n off()\n leave()\n },\n }\n },\n }\n}\n","/**\n * Work that can wait until the browser is idle, such as hidden data tables:\n * it runs in an idle callback (within a second at the latest), or with\n * `flush()`. A module of its own, so charts without such work do not ship it.\n */\nimport { flushHooks, run } from './scheduler.ts'\n\nconst idle = /* @__PURE__ */ new Map<object, () => void>()\nlet pending = false\n\nfunction drain(): number {\n pending = false\n let count = 0\n while (idle.size > 0) {\n const tasks = Array.from(idle.values())\n idle.clear()\n for (const task of tasks) {\n run(task)\n count++\n }\n }\n return count\n}\n\n/** Run `task` once the browser is idle, replacing any idle task already queued for `key`. */\nexport function scheduleIdle(key: object, task: () => void): void {\n flushHooks.idle = drain\n idle.set(key, task)\n if (pending) return\n pending = true\n if (typeof requestIdleCallback === 'function') requestIdleCallback(drain, { timeout: 1000 })\n else setTimeout(drain, 100)\n}\n\n/** Drop the idle task queued for `key`, if any. */\nexport function cancelIdle(key: object): void {\n idle.delete(key)\n}\n","import { tableContent } from '../a11y.ts'\nimport { type ChartConfig, renderContext, type Size } from '../chart.ts'\nimport { getNumberFormat } from '../format.ts'\nimport { cancelIdle, scheduleIdle } from '../idle.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { render } from '../render/dom.ts'\n\n/**\n * The chart data as an HTML table next to the SVG: visually hidden for\n * screen readers by default, visible with `table: 'visible'`.\n */\nconst DEFAULT_MAX_ROWS = 1000\n\nexport function dataTable(): ChartPlugin {\n return {\n name: 'table',\n install(chart) {\n const host = chart.element\n // Take over a server-rendered table instead of adding a second one.\n let el = host.querySelector<HTMLElement>(':scope > .tc-table-wrap') ?? undefined\n let adopt = el?.firstElementChild ?? null\n\n /** The table option of the last table, to tell its changes from new data. */\n let shown: unknown\n const key = {}\n\n const remove = () => {\n cancelIdle(key)\n if (!el) return\n render(el, null)\n el.remove()\n el = undefined\n }\n\n const update = (config: ChartConfig<object>, size: Size, hidden: ReadonlySet<string>) => {\n const option = config.table ?? true\n const maxRows =\n typeof option === 'object' && option.maxRows ? option.maxRows : DEFAULT_MAX_ROWS\n const table =\n option !== false && typeof document !== 'undefined'\n ? config.type.table?.(\n config,\n renderContext(config, size, chart.id, () => {}, hidden, chart.fontSize),\n maxRows,\n )\n : undefined\n if (!table) {\n remove()\n return\n }\n const visible =\n option === 'visible' || (typeof option === 'object' && option.visible === true)\n // Huge tables help nobody and cost real time to build; keep the first rows.\n let caption = config.title\n const total = table.total ?? table.rows.length\n const rows =\n table.rows.length > maxRows\n ? { columns: table.columns, rows: table.rows.slice(0, maxRows) }\n : table\n if (total > rows.rows.length) {\n const n = getNumberFormat(config.locale)\n const note = `${n.format(rows.rows.length)} of ${n.format(total)} rows`\n caption = caption ? `${caption} (${note})` : note\n }\n if (!el) el = host.ownerDocument.createElement('div')\n el.className = visible ? 'tc-table-wrap' : 'tc-table-wrap tc-sr-only'\n render(el, tableContent(rows, caption), adopt)\n adopt = null\n const svg = host.querySelector(':scope > svg.tc-chart')\n const bottomLegend = host.querySelector(':scope > .tc-legend[data-position=\"bottom\"]')\n const after = bottomLegend ?? svg\n if (after && after.nextElementSibling !== el) after.after(el)\n else if (!el.isConnected) host.appendChild(el)\n }\n\n return {\n afterRender({ config, size, hidden, changed }) {\n // Resizing changes nothing in the table.\n if (!changed && el?.isConnected) return\n const option = config.table ?? true\n const same = shown === option\n shown = option\n // A hidden table only serves screen readers: rebuilding thousands of\n // cells for new data can wait until the browser is idle instead of\n // delaying the frame that animates the chart. The first table, visible\n // ones and changes of the table option itself are built right away.\n if (same && el?.isConnected && el.classList.contains('tc-sr-only')) {\n scheduleIdle(key, () => update(config, size, hidden))\n } else {\n cancelIdle(key)\n update(config, size, hidden)\n }\n },\n destroy: remove,\n }\n },\n }\n}\n","import type { Hit } from './interaction.ts'\nimport { type ChildInput, h, type VNode } from './vnode.ts'\n\n/**\n * Where a tooltip for `hit` belongs, in chart pixels: the pointer when it\n * drives the highlight, otherwise the focused value (keyboard).\n */\nexport function hitAnchor(hit: Hit, pointer?: { x: number; y: number }): { x: number; y: number } {\n if (pointer) return pointer\n const item = hit.items.find((i) => i.seriesIndex === hit.seriesIndex) ?? hit.items[0]\n if (hit.guide && item?.y != null) return { x: item.x, y: item.y }\n if (hit.axis === 'y') return { x: item?.x ?? hit.x, y: hit.y ?? hit.area.y }\n return { x: hit.x, y: item?.y ?? hit.area.y + hit.area.height / 2 }\n}\n\nexport interface TooltipOptions {\n /**\n * Custom content for a hit: VNodes built with `h()` or plain text.\n * Rendered safely (no HTML parsing), inside `.tc-tooltip`.\n */\n format?: (hit: Hit) => ChildInput\n /** Extra content below the default rows (e.g. a total), in `.tc-tooltip-footer`. */\n footer?: (hit: Hit) => ChildInput\n}\n\n/** Default tooltip content: the category title and one row per series. */\nexport function tooltipContent(hit: Hit, options: TooltipOptions = {}): VNode {\n const body: ChildInput = options.format\n ? options.format(hit)\n : [\n hit.title && h('div', { class: 'tc-tooltip-title' }, hit.title),\n hit.items.map((item) =>\n h(\n 'div',\n {\n key: item.seriesIndex,\n class: [\n 'tc-tooltip-item',\n 'tc-series',\n `tc-series-${item.seriesIndex + 1}`,\n hit.seriesIndex === item.seriesIndex && 'tc-tooltip-item-active',\n ],\n style: { '--tc-series-color': item.color },\n },\n h('span', { class: 'tc-tooltip-swatch' }),\n h('span', { class: 'tc-tooltip-name' }, item.name),\n h('span', { class: 'tc-tooltip-value' }, item.text),\n ),\n ),\n options.footer && h('div', { class: 'tc-tooltip-footer' }, options.footer(hit)),\n ]\n return h('div', { class: 'tc-tooltip-content' }, body)\n}\n\nexport interface TooltipPlacement {\n x: number\n y: number\n side: 'left' | 'right'\n}\n\n/**\n * Place a `width × height` tooltip next to an anchor within `bounds` (from\n * `bounds.x`, `bounds.y`, 0 by default): right of the anchor, or left when it\n * would overflow, vertically centered on the pointer and clamped.\n */\nexport function placeTooltip(\n anchor: { x: number; y: number },\n size: { width: number; height: number },\n bounds: { x?: number; y?: number; width: number; height: number },\n offset = 12,\n): TooltipPlacement {\n const { x: left = 0, y: top = 0 } = bounds\n const fitsRight = anchor.x + offset + size.width <= left + bounds.width\n const fitsLeft = anchor.x - offset - size.width >= left\n const side = fitsRight || !fitsLeft ? 'right' : 'left'\n const rawX = side === 'right' ? anchor.x + offset : anchor.x - offset - size.width\n const x = Math.max(left, Math.min(rawX, left + bounds.width - size.width))\n const y = Math.max(top, Math.min(anchor.y - size.height / 2, top + bounds.height - size.height))\n return { x: Math.round(x), y: Math.round(y), side }\n}\n","import type { ChartPlugin } from '../plugin.ts'\nimport { render } from '../render/dom.ts'\nimport { schedule } from '../scheduler.ts'\nimport { hitAnchor, placeTooltip, tooltipContent } from '../tooltip.ts'\nimport { listenPointer } from './pointer.ts'\n\n/**\n * Where a tooltip in `el` can show without being cut off: the box of the\n * nearest element that clips its overflow (`el` itself, an ancestor, across\n * shadow roots), within the viewport.\n */\nfunction room(el: Element): { left: number; top: number; right: number; bottom: number } {\n let left = 0\n let top = 0\n let right = innerWidth\n let bottom = innerHeight\n for (let node: Element | null = el; node; ) {\n const style = getComputedStyle(node)\n if (style.overflowX !== 'visible' || style.overflowY !== 'visible') {\n const box = node.getBoundingClientRect()\n left = Math.max(left, box.left)\n top = Math.max(top, box.top)\n right = Math.min(right, box.right)\n bottom = Math.min(bottom, box.bottom)\n break\n }\n node = node.parentElement ?? ((node.getRootNode() as ShadowRoot).host || null)\n }\n return { left, top, right, bottom }\n}\n\n/** Tooltips to place: each measures where it goes, and returns what moves it there. */\nconst waiting: (() => (() => void) | undefined)[] = []\n\n/**\n * Place the waiting tooltips, in the frame that rendered their charts: all\n * are measured before any is moved, so the page is laid out once for the\n * frame. Measured and moved one by one, twelve charts sharing a hover laid\n * the page out twelve times.\n */\nfunction placeAll(): void {\n for (const move of waiting.splice(0).map((measure) => measure())) move?.()\n}\n\n/**\n * An HTML tooltip (`.tc-tooltip`) for the highlighted category, placed next\n * to it inside the chart element. Configure it with the `tooltip` option.\n */\nexport function tooltip(): ChartPlugin {\n return {\n name: 'tooltip',\n install(chart) {\n const stop = listenPointer(chart)\n const el = chart.element as HTMLElement\n // Positioning context for the tooltip (zero specificity in CSS, so page styles win).\n const addedClass = !el.classList.contains('tc-container')\n el.classList.add('tc-container')\n let tip: HTMLElement | undefined\n /** Counts the renders, so a placement still waiting knows when it is out of date. */\n let turns = 0\n\n return {\n afterRender() {\n const option = chart.config.tooltip\n const hit = chart.active\n const anchor = hit && hitAnchor(hit, chart.pointer)\n if (\n option === false ||\n typeof document === 'undefined' ||\n !hit ||\n !anchor ||\n !Number.isFinite(anchor.x) ||\n !Number.isFinite(anchor.y)\n ) {\n turns++\n tip?.removeAttribute('data-visible')\n return\n }\n if (!tip) {\n tip = el.ownerDocument.createElement('div')\n tip.className = 'tc-tooltip'\n tip.setAttribute('aria-hidden', 'true')\n el.appendChild(tip)\n }\n render(tip, tooltipContent(hit, typeof option === 'object' ? option : undefined))\n\n // Placed with the tooltips of the other charts of this frame (see placeAll).\n const shown = tip\n const turn = ++turns\n waiting.push(() => {\n const svg = el.querySelector('svg.tc-chart')\n // A later render of this chart, or its end, overtook this one.\n if (!svg || turn !== turns) return undefined\n const { width, height } = chart.size\n const box = el.getBoundingClientRect()\n const rect = svg.getBoundingClientRect()\n // Screen pixels per pixel of the container (transformed or zoomed ancestors).\n const k = box.width > 0 && el.offsetWidth > 0 ? box.width / el.offsetWidth : 1\n const sx = rect.width > 0 ? rect.width / width / k : 1\n const sy = rect.height > 0 ? rect.height / height / k : 1\n const origin = {\n x: (rect.left - box.left) / k - el.clientLeft,\n y: (rect.top - box.top) / k - el.clientTop,\n }\n // Snap to the category, follow the pointer along the values\n // (a radar spoke runs both ways, so there it follows the pointer).\n const ax = hit.axis === 'y' || hit.guide ? anchor.x : hit.x\n const ay = hit.axis === 'y' ? (hit.y ?? anchor.y) : anchor.y\n // The tooltip may leave the container, up to what would cut it off.\n const clip = room(el)\n const place = placeTooltip(\n { x: origin.x + ax * sx, y: origin.y + ay * sy },\n { width: shown.offsetWidth, height: shown.offsetHeight },\n {\n x: (clip.left - box.left) / k - el.clientLeft,\n y: (clip.top - box.top) / k - el.clientTop,\n width: (clip.right - clip.left) / k,\n height: (clip.bottom - clip.top) / k,\n },\n )\n return () => {\n shown.style.transform = `translate(${place.x}px, ${place.y}px)`\n shown.dataset.side = place.side\n if (!shown.hasAttribute('data-visible')) {\n // Commit the position before becoming visible, so it does not glide in from the old spot.\n void getComputedStyle(shown).transform\n shown.setAttribute('data-visible', '')\n }\n }\n })\n schedule(waiting, placeAll)\n },\n destroy() {\n turns++\n if (tip) {\n render(tip, null)\n tip.remove()\n }\n if (addedClass) el.classList.remove('tc-container')\n stop?.()\n },\n }\n },\n }\n}\n","import type { ChartPlugin } from '../plugin.ts'\nimport { download } from './download.ts'\nimport { highlight } from './highlight.ts'\nimport { keyboard } from './keyboard.ts'\nimport { legend } from './legend.ts'\nimport { pointer } from './pointer.ts'\nimport { sync } from './sync.ts'\nimport { dataTable } from './table.ts'\nimport { tooltip } from './tooltip.ts'\n\nexport { dataTable, download, highlight, keyboard, legend, pointer, sync, tooltip }\n\n/** The built-in plugins installed by the default `Chart` from `@tabler/charts`. */\nexport function defaultPlugins(): ChartPlugin[] {\n return [highlight(), legend(), tooltip(), dataTable(), keyboard(), sync(), download()]\n}\n","import { type ChartConfig, Chart as CoreChart } from './chart.ts'\nimport { defaultPlugins } from './plugins/index.ts'\n\n/**\n * A chart with every built-in plugin installed: hover highlight, legend,\n * tooltip, data table and keyboard navigation. Each can be switched off in\n * the config (`tooltip: false`, …). For the smallest bundle, use the bare\n * `Chart` from `@tabler/charts/core` and pick plugins explicitly.\n *\n * ```ts\n * const chart = new Chart('#sales', { type: line, data })\n * ```\n */\nexport class Chart<O extends object = object> extends CoreChart<O> {\n constructor(target: Element | string, config: ChartConfig<O>) {\n super(target, config, defaultPlugins())\n }\n}\n","import { h, type VNode } from '../vnode.ts'\n\n/**\n * A vertical luminance mask shared by all gradient areas of a chart (line, area, sparkline). Areas keep their\n * series color from CSS; the mask only fades them, with stop opacities read\n * from `--tc-area-gradient-start` / `--tc-area-gradient-end`.\n */\nexport function fadeMask(id: string): VNode {\n return h(\n 'mask',\n { id, maskContentUnits: 'objectBoundingBox' },\n h(\n 'linearGradient',\n { id: `${id}-gradient`, x1: 0, y1: 0, x2: 0, y2: 1 },\n h('stop', { class: 'tc-fade-start', offset: 0 }),\n h('stop', { class: 'tc-fade-end', offset: 1 }),\n ),\n h('rect', { width: 1, height: 1, fill: `url(#${id}-gradient)` }),\n )\n}\n","import { type Series, seriesKey } from './cartesian.ts'\n\n/** Stack series on top of each other; `'percent'` normalizes every category to 100%. */\nexport type StackMode = boolean | 'percent'\n\n/** A stacked segment from `y0` to `y1` (in data units). */\nexport interface Segment {\n y0: number\n y1: number\n}\n\nexport interface StackOptions {\n /** Normalize each category by the sum of absolute values. */\n percent?: boolean\n /** Count missing values as zero (areas) instead of leaving no segment (bars). */\n nullAsZero?: boolean\n /** Keys of hidden series, which get no segment and do not stack. */\n hidden?: ReadonlySet<string>\n}\n\n/**\n * Stack series per category: positive values grow up from zero and\n * negative values down from zero, each on their own running total (like\n * d3's diverging offset), so gains and losses never interleave. Returns one\n * array per series with a segment per category, or `null` for no segment.\n */\nexport function stackSeries(\n series: readonly Series[],\n count: number,\n options: StackOptions = {},\n): (Segment | null)[][] {\n const { percent = false, nullAsZero = false, hidden } = options\n const visible = series.map((s) => !hidden?.has(seriesKey(s)))\n const out = series.map(() => new Array<Segment | null>(count).fill(null))\n\n for (let i = 0; i < count; i++) {\n let total = 0\n if (percent) {\n series.forEach((s, j) => {\n const v = s.values[i]\n if (visible[j] && v != null) total += Math.abs(v)\n })\n }\n let up = 0\n let down = 0\n let lastUp: Segment | undefined\n let lastDown: Segment | undefined\n for (let j = 0; j < series.length; j++) {\n const s = series[j] as Series\n if (!visible[j]) continue\n const raw = s.values[i]\n const valid = raw != null\n if (!valid && !nullAsZero) continue\n let v = valid ? (raw as number) : 0\n if (percent) v = total === 0 ? 0 : v / total\n const row = out[j] as (Segment | null)[]\n if (v < 0) {\n const segment: Segment = { y0: down, y1: down + v }\n row[i] = segment\n down += v\n lastDown = segment\n } else {\n const segment: Segment = { y0: up, y1: up + v }\n row[i] = segment\n up += v\n lastUp = segment\n }\n }\n // Shares must end exactly at ±100%: floating point drift (1.0000000000000002)\n // would otherwise make nice() stretch the axis to 120%, or leave a hairline gap.\n if (percent) {\n if (lastUp && Math.abs(up - 1) < 1e-9) lastUp.y1 = 1\n if (lastDown && Math.abs(down + 1) < 1e-9) lastDown.y1 = -1\n }\n }\n return out\n}\n\n/** Every segment boundary, for the value domain. */\nexport function stackBounds(stacks: readonly (Segment | null)[][]): number[] {\n const values: number[] = []\n for (const row of stacks) {\n for (const segment of row) if (segment) values.push(segment.y0, segment.y1)\n }\n return values\n}\n","import type { ChartType, RenderContext } from '../chart.ts'\nimport { fadeMask } from '../components/fade.ts'\nimport { feature } from '../features.ts'\nimport { round } from '../layout.ts'\nimport { areaPath, type Curve, linePath, type Point } from '../shapes/path.ts'\nimport { type ChildInput, h } from '../vnode.ts'\nimport {\n type CartesianOptions,\n cartesianLayout,\n categoryInteraction,\n plottable,\n resolveLabels,\n type Series,\n seriesAttrs,\n seriesKey,\n seriesLegend,\n seriesTable,\n} from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\nimport { type StackMode, stackBounds, stackSeries } from './stack.ts'\n\nexport interface LineOptions extends CartesianOptions {\n /** Interpolation between points. Defaults to `'monotone'`. */\n curve?: Curve\n /** Draw dots on every point, only on the last one, or none. Defaults to `'none'`. */\n points?: 'none' | 'last' | 'all'\n /** Dot radius in pixels. Defaults to `4`. */\n pointRadius?: number\n /** Bridge `null` values instead of leaving gaps. Defaults to `false`. */\n connectNulls?: boolean\n /** Fill the area under each line. Defaults to `false` (`true` for `area`). */\n area?: boolean\n /**\n * Area fill style: a vertical fade (strength set by `--tc-area-gradient-start`\n * / `--tc-area-gradient-end`) or a flat wash (`--tc-area-opacity`).\n * Defaults to `'gradient'`, or `'solid'` for stacked areas.\n */\n fill?: 'gradient' | 'solid'\n /**\n * Stack series on top of each other (each line draws the running total);\n * `'percent'` shows every category as 100%. Missing values count as zero.\n */\n stacked?: StackMode\n /**\n * Draw long series with at most this many points, chosen by LTTB\n * downsampling so peaks and valleys survive. Tooltips and keyboard\n * navigation still use every value. Off by default.\n */\n decimate?: number\n}\n\n/** Points in pixels for a series; `null` for missing values. */\nfunction seriesPoints(\n series: Series,\n count: number,\n x: (i: number) => number,\n y: (v: number) => number,\n connectNulls: boolean,\n valid: (v: number | null | undefined) => v is number,\n): Point[] {\n const points: Point[] = []\n for (let i = 0; i < count; i++) {\n const v = series.values[i]\n if (!valid(v)) {\n if (!connectNulls) points.push(null)\n } else {\n points.push([x(i), y(v)])\n }\n }\n return points\n}\n\n/** Render line (and optionally area) series; shared by `line` and `area`. */\nexport function renderLines(options: LineOptions, ctx: RenderContext, fill: boolean): ChildInput {\n const {\n curve = 'monotone',\n points = 'none',\n pointRadius = 4,\n connectNulls = false,\n area: filled = fill,\n stacked = false,\n decimate,\n // Faded layers would show light seams between stacked areas, so stacks default to solid.\n fill: fillStyle = stacked ? 'solid' : 'gradient',\n } = options\n const overhang = points === 'none' ? 2 : pointRadius + 2\n const { series } = options.data\n const count = resolveLabels(options.data).length\n const stacks = stacked\n ? stackSeries(series, count, {\n percent: stacked === 'percent',\n nullAsZero: true,\n hidden: ctx.hidden,\n })\n : null\n const layout = cartesianLayout(options, ctx, {\n scale: 'point',\n zero: filled || stacks !== null,\n overhang,\n ...(stacks ? { values: stackBounds(stacks) } : {}),\n ...(stacked === 'percent' ? { tickFormat: { style: 'percent' } } : {}),\n })\n const { x, y, labels } = layout\n const baseline = y(Math.min(Math.max(0, y.domain[0]), y.domain[1]))\n ctx.onHitTest(\n categoryInteraction(layout, options, ctx, (seriesIndex, i, v) => ({\n x: x.at(i),\n y: y(stacks ? (stacks[seriesIndex]?.[i]?.y1 ?? 0) : v),\n })),\n )\n const gradient = filled && fillStyle === 'gradient'\n const fadeId = `${ctx.id}-fade`\n\n // Hidden series keep their index (and color slot) but draw nothing.\n const visible = (s: Series) => !ctx.hidden.has(seriesKey(s))\n const all = series.map((s, index) => {\n if (!visible(s)) return []\n // Stacked series draw their running total.\n const stack = stacks?.[index]\n if (stack) return stack.map((seg, i): Point => (seg ? [x.at(i), y(seg.y1)] : null))\n return seriesPoints(\n s,\n labels.length,\n (i) => x.at(i),\n y,\n connectNulls,\n (v) => plottable(v, options.y),\n )\n })\n /** Indices drawn per series: a downsampled subset when `decimate` is set. */\n const kept = all.map((pts) =>\n decimate !== undefined && pts.length > decimate ? feature('decimate')(pts, decimate) : null,\n )\n const drawn = (index: number): Point[] => {\n const pts = all[index] as Point[]\n const keep = kept[index]\n return keep ? keep.map((i) => pts[i] as Point) : pts\n }\n /** Area bottom: zero, or the top of the layer below for stacks (downsampled alike). */\n const bottom = (index: number): number | (number | null)[] => {\n const stack = stacks?.[index]\n if (!stack) return baseline\n const bottoms = stack.map((seg) => (seg ? y(seg.y0) : null))\n const keep = kept[index]\n return keep ? keep.map((i) => bottoms[i] ?? null) : bottoms\n }\n\n // All areas go below all lines, so a filled series never covers another line.\n const areas =\n filled &&\n h(\n 'g',\n { class: 'tc-areas' },\n options.data.series.map(\n (s, index) =>\n visible(s) &&\n h(\n 'g',\n seriesAttrs(s, index),\n h('path', {\n class: ['tc-area', gradient && 'tc-area-gradient'],\n d: areaPath(drawn(index), bottom(index), { curve }),\n mask: gradient ? `url(#${fadeId})` : undefined,\n }),\n ),\n ),\n )\n\n const lines = options.data.series.map((s, index) => {\n if (!visible(s)) return null\n const pts = drawn(index)\n const valid = pts.filter((p): p is readonly [number, number] => p != null)\n const dots = points === 'all' ? valid : points === 'last' ? valid.slice(-1) : []\n return h(\n 'g',\n seriesAttrs(s, index),\n h('path', { class: 'tc-line', d: linePath(pts, { curve }) }),\n dots.length > 0 &&\n h(\n 'g',\n { class: 'tc-points' },\n dots.map(([cx, cy]) =>\n h('circle', {\n key: cx,\n class: 'tc-point',\n cx: round(cx),\n cy: round(cy),\n r: pointRadius,\n }),\n ),\n ),\n )\n })\n\n return [\n h('defs', { key: 'defs' }, layout.clip.def, gradient && fadeMask(fadeId)),\n layout.background,\n // Layers are keyed: an annotation band or a grid that comes and goes must not\n // shift the series list onto another node (that would recreate every series).\n h('g', { key: 'series', class: 'tc-series-list', 'clip-path': layout.clip.url }, areas, lines),\n layout.foreground,\n ]\n}\n\n/**\n * Line chart: one line per series over category labels.\n *\n * ```ts\n * new Chart('#el', {\n * type: line,\n * data: { labels: ['Jan', 'Feb', 'Mar'], series: [{ name: 'Sales', values: [3, 5, 4] }] },\n * })\n * ```\n */\nexport const line: ChartType<LineOptions> = {\n name: 'line',\n clean: cleanData(cleanSeries),\n render: (options, ctx) => renderLines(options, ctx, false),\n legend: (options) => seriesLegend(options.data),\n table: (options, ctx, limit) => seriesTable(options, ctx, limit),\n}\n","import type { ChartType } from '../chart.ts'\nimport { seriesLegend, seriesTable } from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\nimport { type LineOptions, renderLines } from './line.ts'\n\n/** Options of the area chart: line options with the fill always on. */\nexport type AreaOptions = Omit<LineOptions, 'area'>\n\n/**\n * Area chart: filled lines over category labels, with zero in the y domain\n * by default and a vertical fade (`fill: 'gradient'`).\n *\n * ```ts\n * new Chart('#el', {\n * type: area,\n * data: { labels: ['Jan', 'Feb', 'Mar'], series: [{ name: 'Sales', values: [3, 5, 4] }] },\n * })\n * ```\n */\nexport const area: ChartType<AreaOptions> = {\n name: 'area',\n clean: cleanData(cleanSeries),\n render: (options, ctx) => renderLines(options, ctx, true),\n legend: (options) => seriesLegend(options.data),\n table: (options, ctx, limit) => seriesTable(options, ctx, limit),\n}\n","import { round as to2 } from '../layout.ts'\n\n/** Rounded for path data, without a `-0`. */\nconst round = (value: number): number => {\n const rounded = to2(value)\n return rounded === 0 ? 0 : rounded\n}\n\n/**\n * Path of a vertical bar from `baseline` to `value` (both y in pixels),\n * `x`…`x + width` wide. Only the data end is rounded, with `radius` clamped\n * to half the width and to the bar height; the baseline end stays square.\n * Works for bars growing up (value above baseline) and down (negative values).\n * Square corners are zero-radius arcs and every side is an `L`, so every\n * bar path, vertical or horizontal, has the same commands and CSS can\n * transition `d` between rounded and square (stacking) and between\n * orientations.\n */\nexport function barPath(\n x: number,\n width: number,\n baseline: number,\n value: number,\n radius = 0,\n): string {\n const w = Math.max(0, width)\n const height = Math.abs(baseline - value)\n const r = Math.max(0, Math.min(radius, w / 2, height))\n const x0 = round(x)\n const x1 = round(x + w)\n const b = round(baseline)\n const v = round(value)\n\n const up = value <= baseline\n const edge = round(up ? value + r : value - r)\n const sweep = up ? 1 : 0\n const rr = round(r)\n return (\n `M${x0},${b}L${x0},${edge}` +\n `A${rr},${rr},0,0,${sweep},${round(x + r)},${v}` +\n `L${round(x + w - r)},${v}` +\n `A${rr},${rr},0,0,${sweep},${x1},${edge}` +\n `L${x1},${b}Z`\n )\n}\n\n/**\n * Path of a horizontal bar from `baseline` to `value` (both x in pixels),\n * `y`…`y + height` tall. Only the data end is rounded, with `radius` clamped\n * to half the height and to the bar length; the baseline end stays square.\n * Works for bars growing right (positive values) and left (negative values).\n * Same commands as `barPath`, so a chart can morph between orientations.\n */\nexport function hbarPath(\n y: number,\n height: number,\n baseline: number,\n value: number,\n radius = 0,\n): string {\n const hgt = Math.max(0, height)\n const length = Math.abs(value - baseline)\n const r = Math.max(0, Math.min(radius, hgt / 2, length))\n const y0 = round(y)\n const y1 = round(y + hgt)\n const b = round(baseline)\n const v = round(value)\n\n const right = value >= baseline\n const edge = round(right ? value - r : value + r)\n const sweep = right ? 1 : 0\n const rr = round(r)\n return (\n `M${b},${y0}L${edge},${y0}` +\n `A${rr},${rr},0,0,${sweep},${v},${round(y + r)}` +\n `L${v},${round(y + hgt - r)}` +\n `A${rr},${rr},0,0,${sweep},${edge},${y1}` +\n `L${b},${y1}Z`\n )\n}\n","import type { RenderContext } from '../chart.ts'\nimport { axisSize, bandTicks, type Tick, thinTicks } from '../components/axis.ts'\nimport { estimateTextWidth, innerRect, insets } from '../layout.ts'\nimport { type BandKey, band } from '../scales/band.ts'\nimport {\n type CartesianLayout,\n type CartesianLayoutOptions,\n type CartesianOptions,\n EDGE,\n finishLayout,\n type Label,\n labelFormatter,\n labelKey,\n resolveLabels,\n TICK_SPACING_X,\n valueAxis,\n} from './cartesian.ts'\n\n/**\n * Cartesian layout with categories along y (labels on the left) and values\n * along x (labels at the bottom), for horizontal bars. Only bar charts use\n * it, so it lives outside `cartesianLayout()` and stays out of other bundles.\n */\nexport function horizontalLayout(\n options: CartesianOptions,\n ctx: RenderContext,\n layout: CartesianLayoutOptions,\n): CartesianLayout {\n const yOptions = options.y ?? {}\n const xOptions = options.x ?? {}\n const { fontSize, width, height } = ctx\n const overhang = layout.overhang ?? 0\n const pad = insets(options.padding)\n const labels = resolveLabels(options.data)\n const format = labelFormatter(options, ctx)\n const value = valueAxis(options, ctx, layout, Math.round(width / TICK_SPACING_X))\n const probeValues = value.probe\n const showValues = yOptions.show !== false\n const showCategories = xOptions.show !== false && labels.length > 0\n\n const probeCategories: Tick[] = labels.map((label, i) => ({\n value: labelKey(label),\n position: 0,\n label: format(label, i),\n }))\n const edgeLabel = (tick: Tick | undefined) =>\n showValues && tick ? Math.ceil(estimateTextWidth(tick.label, fontSize) / 2) : 0\n\n const margins = {\n top: pad.top + Math.max(overhang, EDGE / 2),\n right: pad.right + Math.max(edgeLabel(probeValues[probeValues.length - 1]), overhang, EDGE),\n bottom:\n pad.bottom +\n Math.max(showValues ? axisSize('bottom', probeValues, fontSize) : 0, overhang, EDGE / 2),\n left:\n pad.left +\n Math.max(\n showCategories ? axisSize('left', probeCategories, fontSize) : 0,\n edgeLabel(probeValues[0]),\n overhang,\n EDGE,\n ),\n }\n const area = innerRect(width, height, margins)\n\n const keys = labels.map(labelKey)\n const x = band(keys, [area.y, area.y + area.height], {\n paddingInner: layout.paddingInner ?? 0.3,\n paddingOuter: layout.paddingOuter ?? 0.15,\n })\n const y = value.scale([area.x, area.x + area.width])\n const yTicks = thinTicks(value.ticks(y), 'bottom', fontSize)\n const xTicks = showCategories\n ? thinTicks(\n bandTicks(x, (_: BandKey, i) => format(labels[i] as Label, i)),\n 'left',\n fontSize,\n )\n : []\n\n // The value axis runs along x here, categories along y.\n return finishLayout(\n options,\n ctx,\n overhang,\n { area, labels, x, y, horizontal: true, xTicks, yTicks },\n keys,\n )\n}\n","import type { ChartType } from '../chart.ts'\nimport { feature } from '../features.ts'\nimport { barPath, hbarPath } from '../shapes/bar.ts'\nimport type { Curve, Point } from '../shapes/path.ts'\nimport { h } from '../vnode.ts'\nimport {\n type CartesianLayoutOptions,\n type CartesianOptions,\n cartesianLayout,\n categoryInteraction,\n labelKey,\n plottable,\n resolveLabels,\n seriesAttrs,\n seriesKey,\n seriesLegend,\n seriesTable,\n} from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\nimport { horizontalLayout } from './horizontal.ts'\nimport { type Segment, type StackMode, stackBounds, stackSeries } from './stack.ts'\n\nexport interface BarOptions extends CartesianOptions {\n /** Corner radius of the data end of each bar (or stack). Defaults to `4`. */\n radius?: number\n /** Maximum bar thickness in pixels; leftover band space stays empty. Defaults to `24`. */\n maxBarWidth?: number\n /** Gap between bars of a group, or between stacked segments, in pixels. Defaults to `2`. */\n gap?: number\n /** Share of each category left empty between groups, `0…1`. Defaults to `0.3`. */\n groupPadding?: number\n /**\n * Stack series in one bar per category instead of side by side; `'percent'`\n * shows each category as 100%. Negative values stack down from zero.\n */\n stacked?: StackMode\n /**\n * `'horizontal'` lays categories out along y with bars growing right\n * (left for negative values). The `x` / `y` options keep describing the\n * category / value axis. Defaults to `'vertical'`.\n */\n orientation?: 'vertical' | 'horizontal'\n /** Interpolation of series drawn as lines (`series.type`). Defaults to `'monotone'`. */\n curve?: Curve\n}\n\n/**\n * Bar chart: vertical bars per category, grouped side by side or stacked,\n * growing from zero (negative values grow down).\n *\n * ```ts\n * new Chart('#el', {\n * type: bar,\n * data: { labels: ['Q1', 'Q2'], series: [{ name: '2025', values: [3, 5] }] },\n * stacked: true,\n * })\n * ```\n */\nexport const bar: ChartType<BarOptions> = {\n name: 'bar',\n clean: cleanData(cleanSeries),\n render(options, ctx) {\n const {\n radius = 4,\n maxBarWidth = 24,\n gap = 2,\n groupPadding = 0.3,\n stacked = false,\n orientation = 'vertical',\n curve = 'monotone',\n } = options\n const horizontal = orientation === 'horizontal'\n const { series } = options.data\n const count = resolveLabels(options.data).length\n // Series drawn as lines sit on top of the bars and stay out of the stacks.\n const isLine = (index: number) => (series[index]?.type ?? 'bar') !== 'bar'\n const lineKeys = series.filter((_, index) => isLine(index)).map(seriesKey)\n const stackHidden = lineKeys.length ? new Set([...ctx.hidden, ...lineKeys]) : ctx.hidden\n const stacks = stacked\n ? stackSeries(series, count, { percent: stacked === 'percent', hidden: stackHidden })\n : null\n\n const layoutOptions: CartesianLayoutOptions = {\n scale: 'band',\n zero: true,\n paddingInner: groupPadding,\n paddingOuter: groupPadding / 2,\n ...(stacks\n ? {\n values: [\n ...stackBounds(stacks),\n ...series.flatMap((s, index) => (isLine(index) ? s.values : [])),\n ],\n }\n : {}),\n ...(stacked === 'percent' ? { tickFormat: { style: 'percent' } } : {}),\n }\n const layout = horizontal\n ? horizontalLayout(options, ctx, layoutOptions)\n : cartesianLayout(options, ctx, layoutOptions)\n const { x, y, labels } = layout\n\n // Hidden series keep their color slot but give up their place in the group.\n const slots = new Map<number, number>()\n series.forEach((s, index) => {\n if (!ctx.hidden.has(seriesKey(s)) && !isLine(index)) slots.set(index, slots.size)\n })\n const order = [...slots.keys()]\n const columns = stacks ? 1 : Math.max(1, slots.size)\n\n const barWidth = Math.max(\n 0,\n Math.min(maxBarWidth, (x.bandwidth - (stacks ? 0 : gap * (columns - 1))) / columns),\n )\n const groupWidth = barWidth * columns + (stacks ? 0 : gap * (columns - 1))\n const offset = (x.bandwidth - groupWidth) / 2\n const barLeft = (seriesIndex: number, i: number) =>\n x.at(i) + offset + (stacks ? 0 : (slots.get(seriesIndex) ?? 0) * (barWidth + gap))\n\n /** Data extent of a bar: from zero to the value, or its stacked segment. */\n const segment = (seriesIndex: number, i: number): Segment | null => {\n if (stacks) return stacks[seriesIndex]?.[i] ?? null\n const v = series[seriesIndex]?.values[i]\n return plottable(v, options.y) ? { y0: 0, y1: v } : null\n }\n\n // In a stack only the outermost segment of each sign gets rounded.\n const outer = labels.map((_, i) => {\n let up = -1\n let down = -1\n for (const index of order) {\n const seg = segment(index, i)\n if (!seg) continue\n if (seg.y1 > seg.y0) up = index\n else if (seg.y1 < seg.y0) down = index\n }\n return { up, down }\n })\n\n ctx.onHitTest(\n categoryInteraction(\n layout,\n options,\n ctx,\n (seriesIndex, i, v) => {\n if (isLine(seriesIndex)) {\n const across = x.at(i) + x.bandwidth / 2\n return horizontal ? { x: y(v), y: across } : { x: across, y: y(v) }\n }\n const left = barLeft(seriesIndex, i)\n const seg = segment(seriesIndex, i)\n const end = y(seg?.y1 ?? 0)\n const base = y(seg?.y0 ?? 0)\n // The bar's box, for value labels inside it.\n const lo = Math.min(end, base)\n const length = Math.abs(end - base)\n return horizontal\n ? {\n x: end,\n y: left + barWidth / 2,\n box: { x: lo, y: left, width: length, height: barWidth },\n }\n : {\n x: left + barWidth / 2,\n y: end,\n box: { x: left, y: lo, width: barWidth, height: length },\n }\n },\n (px, py, i) => {\n // Pointer position across the categories and along the values.\n const across = horizontal ? py : px\n const along = horizontal ? px : py\n if (stacks) {\n // The segment under the pointer, within the column (gaps included).\n const left = barLeft(0, i)\n if (across < left - gap / 2 || across > left + barWidth + gap / 2) return undefined\n return order.find((index) => {\n const seg = segment(index, i)\n if (!seg) return false\n const a = y(seg.y0)\n const b = y(seg.y1)\n return along >= Math.min(a, b) - gap / 2 && along <= Math.max(a, b) + gap / 2\n })\n }\n // The bar under the pointer, gaps included, so thin bars are easy to hit.\n const slot = Math.floor((across - (x.at(i) + offset) + gap / 2) / (barWidth + gap))\n const seriesIndex = order[slot]\n return seriesIndex !== undefined && segment(seriesIndex, i) ? seriesIndex : undefined\n },\n ),\n )\n\n const groups = series.map(\n (s, index) =>\n slots.has(index) &&\n h(\n 'g',\n seriesAttrs(s, index),\n labels.map((label, i) => {\n const seg = segment(index, i)\n if (!seg) return null\n const negative = seg.y1 < seg.y0\n // Leave a surface-colored gap where this segment sits on another one;\n // positive values grow toward smaller y, but toward larger x.\n const away = (negative ? 1 : -1) * (horizontal ? -1 : 1)\n const inner = seg.y0 === 0 ? 0 : away * gap\n const rounded = !stacks || (negative ? outer[i]?.down : outer[i]?.up) === index\n const draw = horizontal ? hbarPath : barPath\n return h('path', {\n key: labelKey(label),\n class: ['tc-bar', negative && 'tc-bar-negative', horizontal && 'tc-bar-horizontal'],\n d: draw(\n barLeft(index, i),\n barWidth,\n y(seg.y0) + inner,\n y(seg.y1),\n rounded ? radius : 0,\n ),\n })\n }),\n ),\n )\n\n // Lines through the band centers, drawn after (over) every bar. The path\n // generators come with the line module, so plain bar charts do not ship them.\n const paths = lineKeys.length ? feature('line') : null\n const baseline = y(Math.min(Math.max(0, y.domain[0]), y.domain[1]))\n const lines = series.map((s, index) => {\n if (!paths) return null\n if (!isLine(index) || ctx.hidden.has(seriesKey(s))) return null\n const points = labels.map((_, i): Point => {\n const v = s.values[i]\n if (!plottable(v, options.y)) return null\n const center = x.at(i) + x.bandwidth / 2\n return horizontal ? [y(v), center] : [center, y(v)]\n })\n // Areas need a vertical baseline; sideways they fall back to a line.\n const filled = s.type === 'area' && !horizontal\n return h(\n 'g',\n seriesAttrs(s, index),\n filled && h('path', { class: 'tc-area', d: paths.areaPath(points, baseline, { curve }) }),\n h('path', { class: 'tc-line', d: paths.linePath(points, { curve }) }),\n )\n })\n\n return [\n h('defs', { key: 'defs' }, layout.clip.def),\n layout.background,\n // Layers are keyed: an annotation band or a grid that comes and goes must not\n // shift the series list onto another node (that would recreate every series).\n h(\n 'g',\n { key: 'series', class: 'tc-series-list', 'clip-path': layout.clip.url },\n groups,\n lines,\n ),\n layout.foreground,\n ]\n },\n legend: (options) => seriesLegend(options.data),\n table: (options, ctx, limit) => seriesTable(options, ctx, limit),\n}\n","import type { ChartType } from '../chart.ts'\nimport type { Hit, Interaction } from '../interaction.ts'\nimport type { InsetsInput } from '../layout.ts'\nimport { round } from '../layout.ts'\nimport { h } from '../vnode.ts'\nimport type { Annotation } from './annotations.ts'\nimport {\n type CartesianData,\n type CartesianOptions,\n type CategoryAxisOptions,\n cartesianLayout,\n categoryInteraction,\n type Label,\n labelKey,\n plottable,\n seriesTable,\n type ValueAxisOptions,\n} from './cartesian.ts'\nimport { cleanData, finite, label, records } from './clean.ts'\n\n/** One period: where the price opened, its range and where it closed. */\nexport interface Candle {\n /** The period (a date for `x: { type: 'time' }`, or any label). */\n x: Label\n open: number\n high: number\n low: number\n close: number\n}\n\n/**\n * A rounded rectangle with the same commands whatever its size and radius\n * (a zero radius draws square corners), so CSS can morph one into another.\n */\nconst bodyPath = (x: number, y: number, w: number, h: number, r: number): string => {\n const a = `A${r},${r},0,0,1,`\n return `M${round(x + r)},${y}H${round(x + w - r)}${a}${round(x + w)},${round(y + r)}V${round(y + h - r)}${a}${round(x + w - r)},${round(y + h)}H${round(x + r)}${a}${x},${round(y + h - r)}V${round(y + r)}${a}${round(x + r)},${y}Z`\n}\n\nexport interface CandlestickOptions {\n data: readonly Candle[]\n /** Maximum candle body width in pixels. Defaults to `16`. */\n maxCandleWidth?: number\n /** Share of each period left empty between candles, `0…1`. Defaults to `0.3`. */\n groupPadding?: number\n /** Extra space around the plot area, in pixels. */\n padding?: InsetsInput\n /** Corner radius of the bodies. Defaults to `1`. */\n radius?: number\n x?: CategoryAxisOptions\n y?: ValueAxisOptions\n /** Reference lines and bands, e.g. a price target or a trading halt. */\n annotations?: readonly Annotation[]\n}\n\nconst UP = 'var(--tc-up-color,var(--tc-color-6))'\nconst DOWN = 'var(--tc-negative-color,var(--tc-color-8))'\n\n/** Whether every price can be placed on the value axis (positive ones only on a log axis). */\nconst valid = (c: Candle, axis: ValueAxisOptions | undefined): boolean =>\n [c.open, c.high, c.low, c.close].every((v) => plottable(v, axis))\n\n/** The candles as four series, for the shared axes, tooltip and table. */\nfunction asCartesian(options: CandlestickOptions): CartesianOptions {\n const pick = (key: 'open' | 'high' | 'low' | 'close') =>\n options.data.map((c) => (valid(c, options.y) ? c[key] : null))\n const data: CartesianData = {\n labels: options.data.map((c) => c.x),\n series: [\n { name: 'Open', values: pick('open') },\n { name: 'High', values: pick('high') },\n { name: 'Low', values: pick('low') },\n { name: 'Close', values: pick('close') },\n ],\n }\n const out: CartesianOptions = { data }\n if (options.x) out.x = options.x\n if (options.y) out.y = options.y\n if (options.padding !== undefined) out.padding = options.padding\n if (options.annotations) out.annotations = options.annotations\n return out\n}\n\n/**\n * Candlestick (OHLC) chart: per period a wick from low to high and a body\n * from open to close, green when it closed higher (`--tc-up-color`) and red\n * when lower (`--tc-negative-color`).\n *\n * ```ts\n * new Chart('#el', {\n * type: candlestick,\n * data: [{ x: '2026-01-01', open: 98, high: 102, low: 89, close: 94 }],\n * x: { type: 'time' },\n * })\n * ```\n */\nexport const candlestick: ChartType<CandlestickOptions> = {\n name: 'candlestick',\n clean: cleanData((data) =>\n records(data, (c) => ({\n ...c,\n x: label(c.x),\n open: finite(c.open),\n high: finite(c.high),\n low: finite(c.low),\n close: finite(c.close),\n })),\n ),\n render(options, ctx) {\n const { maxCandleWidth = 16, groupPadding = 0.3, radius = 1 } = options\n const cartesian = asCartesian(options)\n const layout = cartesianLayout(cartesian, ctx, {\n scale: 'band',\n zero: false,\n paddingInner: groupPadding,\n paddingOuter: groupPadding / 2,\n })\n const { x, y, labels } = layout\n const width = Math.max(1, Math.min(maxCandleWidth, x.bandwidth))\n const center = (i: number) => x.at(i) + x.bandwidth / 2\n const up = (c: Candle) => c.close >= c.open\n\n const base = categoryInteraction(layout, cartesian, ctx, (_, i, v) => ({\n x: center(i),\n y: y(v),\n }))\n // Tooltip swatches take the color of the candle, not four palette slots.\n const paint = (hit: Hit | null): Hit | null => {\n const candle = hit ? options.data[hit.index] : undefined\n if (!hit || !candle) return hit\n const color = up(candle) ? UP : DOWN\n return { ...hit, items: hit.items.map((item) => ({ ...item, color })) }\n }\n const interaction: Interaction = {\n count: base.count,\n hitIndex: (i, s) => paint(base.hitIndex(i, s)),\n hitTest: (px, py) => paint(base.hitTest(px, py)),\n }\n ctx.onHitTest(interaction)\n\n const candles = options.data.map((c, i) => {\n if (!valid(c, options.y)) return null\n const cx = round(center(i))\n const top = y(Math.max(c.open, c.close))\n // A flat period still shows a 1px body.\n const bottom = Math.max(y(Math.min(c.open, c.close)), top + 1)\n const left = round(center(i) - width / 2)\n const r = round(Math.min(radius, width / 2, (bottom - top) / 2))\n return h(\n 'g',\n {\n key: labelKey(labels[i] as Label),\n class: ['tc-candle', up(c) ? 'tc-candle-up' : 'tc-candle-down'],\n },\n h('path', {\n class: 'tc-candle-wick',\n d: `M${cx},${round(y(c.high))}V${round(y(c.low))}`,\n }),\n // A path, not a rect, so it morphs between updates (d), in Safari too.\n h('path', {\n class: 'tc-candle-body',\n d: bodyPath(left, round(top), round(width), round(bottom - top), r),\n }),\n )\n })\n\n return [\n h('defs', { key: 'defs' }, layout.clip.def),\n layout.background,\n h(\n 'g',\n { key: 'series', class: 'tc-series-list tc-candles', 'clip-path': layout.clip.url },\n candles,\n ),\n layout.foreground,\n ]\n },\n table: (options, ctx, limit) => seriesTable(asCartesian(options), ctx, limit),\n}\n","/**\n * Annular sector paths with padding and rounded corners, ported from\n * d3-shape's `arc()` (ISC license, Mike Bostock) so geometry matches d3.\n *\n * Angles are in radians, clockwise from 12 o'clock; paths are centered on\n * the origin (translate the group to place them).\n */\n\nconst EPSILON = 1e-12\nconst PI = Math.PI\nconst HALF_PI = PI / 2\nconst TAU = 2 * PI\n\n/** Degrees to radians. */\nexport const DEG: number = Math.PI / 180\n\n/** Room kept around pies and gauges for the halo of the hovered arc, in pixels. */\nexport const HALO = 8\n\n// Clamped like d3-shape's math helpers, so out-of-range inputs saturate instead of NaN.\nconst asin = (x: number): number => (x >= 1 ? HALF_PI : x <= -1 ? -HALF_PI : Math.asin(x))\nconst acos = (x: number): number => (x > 1 ? 0 : x < -1 ? PI : Math.acos(x))\n\nexport interface ArcOptions {\n innerRadius: number\n outerRadius: number\n startAngle: number\n endAngle: number\n /** Angle removed between adjacent arcs, split between both ends. Defaults to `0`. */\n padAngle?: number\n /** Radius the pad angle is measured at. Defaults to `sqrt(inner² + outer²)` like d3. */\n padRadius?: number\n /** Radius of the rounded corners, clamped to half the ring thickness. Defaults to `0`. */\n cornerRadius?: number\n /** Decimal places kept in the path data. Defaults to `2`. */\n precision?: number\n}\n\n/** Canvas-like path builder emitting SVG path data (after d3-path). */\nclass ArcPath {\n d = ''\n #x0: number | null = null\n #y0: number | null = null\n #x1: number | null = null\n #y1: number | null = null\n readonly #k: number\n\n constructor(precision: number) {\n this.#k = 10 ** Math.max(0, Math.min(12, Math.floor(precision)))\n }\n\n #n(value: number): string {\n const rounded = Math.round(value * this.#k) / this.#k\n return String(rounded === 0 ? 0 : rounded)\n }\n\n moveTo(x: number, y: number): void {\n this.#x0 = this.#x1 = x\n this.#y0 = this.#y1 = y\n this.d += `M${this.#n(x)},${this.#n(y)}`\n }\n\n lineTo(x: number, y: number): void {\n this.#x1 = x\n this.#y1 = y\n this.d += `L${this.#n(x)},${this.#n(y)}`\n }\n\n closePath(): void {\n if (this.#x1 !== null) {\n this.#x1 = this.#x0\n this.#y1 = this.#y0\n this.d += 'Z'\n }\n }\n\n arc(x: number, y: number, r: number, a0: number, a1: number, ccw: boolean): void {\n const dx = r * Math.cos(a0)\n const dy = r * Math.sin(a0)\n const x0 = x + dx\n const y0 = y + dy\n const cw = ccw ? 0 : 1\n let da = ccw ? a0 - a1 : a1 - a0\n\n if (this.#x1 === null || this.#y1 === null) {\n this.d += `M${this.#n(x0)},${this.#n(y0)}`\n this.#x0 = x0\n this.#y0 = y0\n } else if (Math.abs(this.#x1 - x0) > EPSILON || Math.abs(this.#y1 - y0) > EPSILON) {\n this.d += `L${this.#n(x0)},${this.#n(y0)}`\n }\n this.#x1 = x0\n this.#y1 = y0\n if (!r) return\n\n if (da < 0) da = (da % TAU) + TAU\n const rr = this.#n(r)\n if (da > TAU - EPSILON) {\n // A complete circle: two half arcs.\n this.d += `A${rr},${rr},0,1,${cw},${this.#n(x - dx)},${this.#n(y - dy)}`\n this.d += `A${rr},${rr},0,1,${cw},${this.#n(x0)},${this.#n(y0)}`\n } else if (da > EPSILON) {\n this.#x1 = x + r * Math.cos(a1)\n this.#y1 = y + r * Math.sin(a1)\n this.d += `A${rr},${rr},0,${da >= PI ? 1 : 0},${cw},${this.#n(this.#x1)},${this.#n(this.#y1)}`\n }\n }\n}\n\nfunction intersect(\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n x3: number,\n y3: number,\n): [number, number] | undefined {\n const x10 = x1 - x0\n const y10 = y1 - y0\n const x32 = x3 - x2\n const y32 = y3 - y2\n let t = y32 * x10 - x32 * y10\n if (t * t < EPSILON) return undefined\n t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t\n return [x0 + t * x10, y0 + t * y10]\n}\n\n/** Center and tangent points of a rounded corner between a radial edge and an arc. */\nfunction cornerTangents(\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n r1: number,\n rc: number,\n cw: boolean,\n) {\n const x01 = x0 - x1\n const y01 = y0 - y1\n const lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01)\n const ox = lo * y01\n const oy = -lo * x01\n const x11 = x0 + ox\n const y11 = y0 + oy\n const x10 = x1 + ox\n const y10 = y1 + oy\n const x00 = (x11 + x10) / 2\n const y00 = (y11 + y10) / 2\n const dx = x10 - x11\n const dy = y10 - y11\n const d2 = dx * dx + dy * dy\n const r = r1 - rc\n const D = x11 * y10 - x10 * y11\n const d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D))\n let cx0 = (D * dy - dx * d) / d2\n let cy0 = (-D * dx - dy * d) / d2\n const cx1 = (D * dy + dx * d) / d2\n const cy1 = (-D * dx + dy * d) / d2\n const dx0 = cx0 - x00\n const dy0 = cy0 - y00\n const dx1 = cx1 - x00\n const dy1 = cy1 - y00\n // Pick the intersection closest to the edge midpoint.\n if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {\n cx0 = cx1\n cy0 = cy1\n }\n return {\n cx: cx0,\n cy: cy0,\n x01: -ox,\n y01: -oy,\n x11: cx0 * (r1 / r - 1),\n y11: cy0 * (r1 / r - 1),\n }\n}\n\n/**\n * Padded angles, clamped corner radii and edge points of a partial sector,\n * shared by both path generators so they agree exactly.\n */\nfunction sector(\n options: ArcOptions,\n r0: number,\n r1: number,\n a0: number,\n a1: number,\n da: number,\n cw: boolean,\n) {\n let a01 = a0\n let a11 = a1\n let a00 = a0\n let a10 = a1\n let da0 = da\n let da1 = da\n const ap = (options.padAngle ?? 0) / 2\n const rp = ap > EPSILON ? (options.padRadius ?? Math.sqrt(r0 * r0 + r1 * r1)) : 0\n const rc = Math.min(Math.abs(r1 - r0) / 2, options.cornerRadius ?? 0)\n let rc0 = rc\n let rc1 = rc\n\n // Apply padding: equal linear offsets at both radii keep the gap parallel.\n if (rp > EPSILON) {\n let p0 = asin((rp / r0) * Math.sin(ap))\n let p1 = asin((rp / r1) * Math.sin(ap))\n da0 -= p0 * 2\n if (da0 > EPSILON) {\n p0 *= cw ? 1 : -1\n a00 += p0\n a10 -= p0\n } else {\n da0 = 0\n a00 = a10 = (a0 + a1) / 2\n }\n da1 -= p1 * 2\n if (da1 > EPSILON) {\n p1 *= cw ? 1 : -1\n a01 += p1\n a11 -= p1\n } else {\n da1 = 0\n a01 = a11 = (a0 + a1) / 2\n }\n }\n\n const x01 = r1 * Math.cos(a01)\n const y01 = r1 * Math.sin(a01)\n const x10 = r0 * Math.cos(a10)\n const y10 = r0 * Math.sin(a10)\n const x11 = r1 * Math.cos(a11)\n const y11 = r1 * Math.sin(a11)\n const x00 = r0 * Math.cos(a00)\n const y00 = r0 * Math.sin(a00)\n\n // Restrict the corner radius for narrow sectors, where corners would overlap.\n if (rc > EPSILON && da < PI) {\n const oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10)\n if (oc) {\n const ax = x01 - oc[0]\n const ay = y01 - oc[1]\n const bx = x11 - oc[0]\n const by = y11 - oc[1]\n const cos =\n (ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))\n const kc = 1 / Math.sin(acos(cos) / 2)\n const lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1])\n rc0 = Math.min(rc, (r0 - lc) / (kc - 1))\n rc1 = Math.min(rc, (r1 - lc) / (kc + 1))\n } else {\n rc0 = rc1 = 0\n }\n }\n return { a00, a01, a10, a11, da0, da1, rc, rc0, rc1, x01, y01, x10, y10, x11, y11, x00, y00 }\n}\n\n/** SVG path data of an annular sector (a pie slice when `innerRadius` is 0). */\nexport function arcPath(options: ArcOptions): string {\n const path = new ArcPath(options.precision ?? 2)\n let r0 = Math.max(0, options.innerRadius)\n let r1 = Math.max(0, options.outerRadius)\n if (r1 < r0) [r0, r1] = [r1, r0]\n const a0 = options.startAngle - HALF_PI\n const a1 = options.endAngle - HALF_PI\n const da = Math.abs(a1 - a0)\n const cw = a1 > a0\n\n if (!(r1 > EPSILON)) {\n path.moveTo(0, 0)\n } else if (da > TAU - EPSILON) {\n // A full ring (or disc).\n path.moveTo(r1 * Math.cos(a0), r1 * Math.sin(a0))\n path.arc(0, 0, r1, a0, a1, !cw)\n if (r0 > EPSILON) {\n path.moveTo(r0 * Math.cos(a1), r0 * Math.sin(a1))\n path.arc(0, 0, r0, a1, a0, cw)\n }\n } else {\n const g = sector(options, r0, r1, a0, a1, da, cw)\n const { a00, a01, a10, a11, da0, da1, rc, rc0, rc1, x01, y01, x10, y10 } = g\n\n // Outer ring.\n if (!(da1 > EPSILON)) {\n path.moveTo(x01, y01)\n } else if (rc1 > EPSILON) {\n const { x00, y00, x11, y11 } = g\n const t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw)\n const t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw)\n path.moveTo(t0.cx + t0.x01, t0.cy + t0.y01)\n if (rc1 < rc) {\n path.arc(t0.cx, t0.cy, rc1, Math.atan2(t0.y01, t0.x01), Math.atan2(t1.y01, t1.x01), !cw)\n } else {\n path.arc(t0.cx, t0.cy, rc1, Math.atan2(t0.y01, t0.x01), Math.atan2(t0.y11, t0.x11), !cw)\n path.arc(\n 0,\n 0,\n r1,\n Math.atan2(t0.cy + t0.y11, t0.cx + t0.x11),\n Math.atan2(t1.cy + t1.y11, t1.cx + t1.x11),\n !cw,\n )\n path.arc(t1.cx, t1.cy, rc1, Math.atan2(t1.y11, t1.x11), Math.atan2(t1.y01, t1.x01), !cw)\n }\n } else {\n path.moveTo(x01, y01)\n path.arc(0, 0, r1, a01, a11, !cw)\n }\n\n // Inner ring (or the center of a pie slice).\n if (!(r0 > EPSILON) || !(da0 > EPSILON)) {\n path.lineTo(x10, y10)\n } else if (rc0 > EPSILON) {\n const { x00, y00, x11, y11 } = g\n const t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw)\n const t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw)\n path.lineTo(t0.cx + t0.x01, t0.cy + t0.y01)\n if (rc0 < rc) {\n path.arc(t0.cx, t0.cy, rc0, Math.atan2(t0.y01, t0.x01), Math.atan2(t1.y01, t1.x01), !cw)\n } else {\n path.arc(t0.cx, t0.cy, rc0, Math.atan2(t0.y01, t0.x01), Math.atan2(t0.y11, t0.x11), !cw)\n path.arc(\n 0,\n 0,\n r0,\n Math.atan2(t0.cy + t0.y11, t0.cx + t0.x11),\n Math.atan2(t1.cy + t1.y11, t1.cx + t1.x11),\n cw,\n )\n path.arc(t1.cx, t1.cy, rc0, Math.atan2(t1.y11, t1.x11), Math.atan2(t1.y01, t1.x01), !cw)\n }\n } else {\n path.arc(0, 0, r0, a10, a00, cw)\n }\n }\n\n path.closePath()\n return path.d\n}\n\n/** Midpoint of an arc, e.g. to anchor a tooltip or label (like d3's `arc.centroid`). */\nexport function arcCentroid(options: ArcOptions): [number, number] {\n const r = (options.innerRadius + options.outerRadius) / 2\n const a = (options.startAngle + options.endAngle) / 2 - HALF_PI\n return [Math.cos(a) * r, Math.sin(a) * r]\n}\n\n/** Pad angle giving a constant `gap` (in pixels) between arcs of a ring. */\nexport function padAngleForGap(gap: number, innerRadius: number, outerRadius: number): number {\n const rp = Math.sqrt(innerRadius * innerRadius + outerRadius * outerRadius)\n return rp > 0 ? 2 * Math.asin(Math.min(1, gap / 2 / rp)) : 0\n}\n\n/** Angle of a point around the origin. */\nconst angleOf = (x: number, y: number): number => Math.atan2(y, x)\n\n/**\n * The same sector as {@link arcPath}, drawn with a fixed command structure:\n * every corner is always present (zero length when there is none) and each\n * ring is split into two half arcs, so the large-arc flag never flips.\n * Paths of different angles therefore keep their commands while an arc is\n * redrawn frame by frame, turning to its new angles (see `sweep`).\n */\nexport function arcPathStable(options: ArcOptions): string {\n const k = 10 ** Math.max(0, Math.min(12, Math.floor(options.precision ?? 2)))\n const n = (v: number): string => {\n const r = Math.round(v * k) / k\n return String(r === 0 ? 0 : r)\n }\n let d = ''\n const move = (x: number, y: number) => {\n d += `M${n(x)},${n(y)}`\n }\n const line = (x: number, y: number) => {\n d += `L${n(x)},${n(y)}`\n }\n const arc = (r: number, sweep: 0 | 1, x: number, y: number) => {\n d += `A${n(r)},${n(r)},0,0,${sweep},${n(x)},${n(y)}`\n }\n /** Two half arcs of radius `r` around the origin from angle `a0` to `a1`. */\n const ring = (r: number, a0: number, a1: number, ccw: boolean) => {\n let delta = ccw ? a0 - a1 : a1 - a0\n delta = ((delta % TAU) + TAU) % TAU\n if (delta < EPSILON && Math.abs(a1 - a0) > EPSILON) delta = TAU\n const mid = ccw ? a0 - delta / 2 : a0 + delta / 2\n const sweep: 0 | 1 = ccw ? 0 : 1\n arc(r, sweep, r * Math.cos(mid), r * Math.sin(mid))\n arc(r, sweep, r * Math.cos(a1), r * Math.sin(a1))\n }\n\n let r0 = Math.max(0, options.innerRadius)\n let r1 = Math.max(0, options.outerRadius)\n if (r1 < r0) [r0, r1] = [r1, r0]\n const a0 = options.startAngle - HALF_PI\n const a1 = options.endAngle - HALF_PI\n const da = Math.abs(a1 - a0)\n const cw = a1 > a0\n const outerSweep: 0 | 1 = cw ? 1 : 0\n\n if (!(r1 > EPSILON)) {\n // A point: eleven no-op commands at the origin.\n move(0, 0)\n for (let i = 0; i < 4; i++) arc(0, outerSweep, 0, 0)\n line(0, 0)\n for (let i = 0; i < 4; i++) arc(0, outerSweep, 0, 0)\n return `${d}Z`\n }\n\n if (da > TAU - EPSILON) {\n // A full ring (or disc): the seam between the two rings closes the path.\n const ox = r1 * Math.cos(a0)\n const oy = r1 * Math.sin(a0)\n move(ox, oy)\n arc(r1, outerSweep, ox, oy)\n ring(r1, a0, a0 + (cw ? TAU : -TAU) * (1 - 1e-9), !cw)\n arc(r1, outerSweep, ox, oy)\n const ix = r0 * Math.cos(a0)\n const iy = r0 * Math.sin(a0)\n line(ix, iy)\n arc(r0, outerSweep, ix, iy)\n if (r0 > EPSILON) ring(r0, a0, a0 + (cw ? -TAU : TAU) * (1 - 1e-9), cw)\n else for (let i = 0; i < 2; i++) arc(0, outerSweep, 0, 0)\n arc(r0, outerSweep, ix, iy)\n return `${d}Z`\n }\n\n const { a00, a01, a10, a11, da0, da1, rc, rc0, rc1, x01, y01, x10, y10, x11, y11, x00, y00 } =\n sector(options, r0, r1, a0, a1, da, cw)\n\n // Outer edge: corner, two ring halves, corner.\n if (da1 > EPSILON && rc1 > EPSILON) {\n const t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw)\n const t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw)\n move(t0.cx + t0.x01, t0.cy + t0.y01)\n if (rc1 < rc) {\n // Corners merged: one corner arc covers the edge, the rest is empty.\n const ex = t1.cx + t1.x01\n const ey = t1.cy + t1.y01\n arc(rc1, outerSweep, ex, ey)\n arc(r1, outerSweep, ex, ey)\n arc(r1, outerSweep, ex, ey)\n arc(rc1, outerSweep, ex, ey)\n } else {\n arc(rc1, outerSweep, t0.cx + t0.x11, t0.cy + t0.y11)\n ring(\n r1,\n angleOf(t0.cx + t0.x11, t0.cy + t0.y11),\n angleOf(t1.cx + t1.x11, t1.cy + t1.y11),\n !cw,\n )\n arc(rc1, outerSweep, t1.cx + t1.x01, t1.cy + t1.y01)\n }\n } else {\n move(x01, y01)\n arc(r1, outerSweep, x01, y01)\n if (da1 > EPSILON) ring(r1, a01, a11, !cw)\n else for (let i = 0; i < 2; i++) arc(r1, outerSweep, x01, y01)\n arc(r1, outerSweep, x11, y11)\n }\n\n // Inner edge (or the center of a pie slice): corner, two ring halves, corner.\n if (!(r0 > EPSILON) || !(da0 > EPSILON)) {\n line(x10, y10)\n for (let i = 0; i < 4; i++) arc(r0, outerSweep, x10, y10)\n } else if (rc0 > EPSILON) {\n const t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw)\n const t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw)\n line(t0.cx + t0.x01, t0.cy + t0.y01)\n if (rc0 < rc) {\n const ex = t1.cx + t1.x01\n const ey = t1.cy + t1.y01\n arc(rc0, outerSweep, ex, ey)\n arc(r0, outerSweep, ex, ey)\n arc(r0, outerSweep, ex, ey)\n arc(rc0, outerSweep, ex, ey)\n } else {\n arc(rc0, outerSweep, t0.cx + t0.x11, t0.cy + t0.y11)\n ring(r0, angleOf(t0.cx + t0.x11, t0.cy + t0.y11), angleOf(t1.cx + t1.x11, t1.cy + t1.y11), cw)\n arc(rc0, outerSweep, t1.cx + t1.x01, t1.cy + t1.y01)\n }\n } else {\n line(x10, y10)\n arc(r0, outerSweep, x10, y10)\n ring(r0, a10, a00, cw)\n arc(r0, outerSweep, x00, y00)\n }\n return `${d}Z`\n}\n","/**\n * Arcs that turn to their new angles: a transition of `d` moves each point\n * of a path along a straight line, which bends a slice out of its ring on\n * the way. A path that knows which arc it draws (the `arc` of its node, see\n * `arcNode`) is redrawn frame by frame instead, with the angles and radii\n * in between, so slices grow and shrink around the center. Timed by the\n * path's `transition-duration` (`--tc-duration`), with an ease-out curve.\n */\n\nimport { type ArcOptions, arcPathStable } from '../shapes/arc.ts'\nimport { type Attrs, h, type VNode } from '../vnode.ts'\nimport { stop, tween } from './tween.ts'\n\n/**\n * A path drawing this arc, which keeps the arc with it (radii, angles, pad\n * angle, corner radius): out of the markup, for the next render to sweep from.\n */\nexport function arcNode(name: string, arc: ArcOptions): VNode {\n const node = h('path', { class: name, d: arcPathStable(arc) })\n node.arc = [\n arc.innerRadius,\n arc.outerRadius,\n arc.startAngle,\n arc.endAngle,\n arc.padAngle ?? 0,\n arc.cornerRadius ?? 0,\n ]\n return node\n}\n\n/**\n * Take `el` from the arc of its last render, `prev`, to the arc of `next`.\n * Returns the attributes left for the caller to patch (all but `d`, set\n * here frame by frame), or nothing when there is no sweep: not an arc, the\n * same path, no arc to come from, or a chart without transitions.\n */\nexport function sweep(el: Element, prev: VNode, next: VNode): Attrs | undefined {\n const { arc, attrs } = next\n if (!arc || prev.attrs.d === attrs.d) return\n // An interrupted sweep continues from where the arc is now.\n const origin = stop(el) ?? prev.arc\n // Zero in a chart without transitions (static, resizing, reduced motion).\n const duration = Number.parseFloat(getComputedStyle(el).transitionDuration) * 1000\n if (!origin || !(duration > 0)) return\n tween(\n el,\n origin,\n arc,\n duration,\n ([innerRadius, outerRadius, startAngle, endAngle, padAngle, cornerRadius]) =>\n arcPathStable({\n innerRadius,\n outerRadius,\n startAngle,\n endAngle,\n padAngle,\n cornerRadius,\n } as ArcOptions),\n String(attrs.d),\n )\n return { ...attrs, d: prev.attrs.d as string }\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext } from '../chart.ts'\nimport { features } from '../features.ts'\nimport { formatNumber, getNumberFormat, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { type InsetsInput, innerRect, insets } from '../layout.ts'\nimport { arcNode, sweep as sweepArcs } from '../render/sweep.ts'\nimport { arcCentroid, arcPathStable, DEG, HALO } from '../shapes/arc.ts'\nimport { type ChildInput, type ClassValue, h } from '../vnode.ts'\nimport { cleanData, cleanItems, isRecord } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** One ring of a gauge. */\nexport interface GaugeRing {\n name: string\n /** Current value, clamped to `0…max`. */\n value: number\n /** Full-ring value of this ring; overrides `GaugeOptions.max`. */\n max?: number\n /** Stable identity for keyed updates and legend toggles. Defaults to `name`. */\n id?: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the ring group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface GaugeOptions {\n /** A single value, one ring, or concentric rings (outermost first). */\n data: number | GaugeRing | readonly GaugeRing[]\n /** Full-ring value. Defaults to `100`. */\n max?: number\n /** Where the arc starts, in degrees clockwise from 12 o'clock. Defaults to `0`. */\n startAngle?: number\n /** Degrees the full ring spans, `0…360`. Defaults to `360`; use e.g. `270` for a dial. */\n angle?: number\n /** Ring thickness in pixels. Defaults to `12`. */\n thickness?: number\n /** Space between rings in pixels. Defaults to `4`. */\n gap?: number\n /** Corner radius of the arcs. Defaults to half the thickness (round caps). */\n cornerRadius?: number\n /** Format of the values (tooltip, table). */\n format?: NumberFormat\n /**\n * Text in the middle: the first ring's share of `max` and its name by\n * default; `false` hides it, or give your own `value` / `label`.\n */\n center?: false | { value?: string; label?: string }\n /** Extra space around the gauge, in pixels. */\n padding?: InsetsInput\n}\n\n/** Space kept around the gauge for the hover halo. */\nconst HALF_PI = Math.PI / 2\n\ninterface Ring {\n data: GaugeRing\n index: number\n value: number\n max: number\n /** Slot among the visible rings, from the outside in. */\n position: number\n}\n\nfunction ringsOf(options: GaugeOptions): GaugeRing[] {\n const { data } = options\n if (typeof data === 'number') return [{ name: '', value: data }]\n return Array.isArray(data) ? (data as GaugeRing[]) : [data as GaugeRing]\n}\n\n/** The visible rings with clamped values. */\nfunction layoutRings(options: GaugeOptions, hidden: ReadonlySet<string>): Ring[] {\n const max = options.max ?? 100\n return ringsOf(options)\n .map((data, index) => ({ data, index, max: data.max ?? max }))\n .filter((ring) => !hidden.has(keyOf(ring.data)))\n .map((ring, position) => ({\n ...ring,\n position,\n value: Math.min(ring.max, Math.max(0, ring.data.value || 0)),\n }))\n}\n\n/**\n * Radius and center that fit the swept ring (plus the text in the middle)\n * into `area`: a dial or half ring is centered by its own outline, not by\n * the full circle it is cut from.\n */\nfunction fitGauge(\n area: { x: number; y: number; width: number; height: number },\n start: number,\n sweep: number,\n textTop: number,\n textBottom: number,\n): { outer: number; cx: number; cy: number } {\n // Points of the outline, in units of the outer radius: both ends of the arc\n // and every axis extreme it passes; the origin covers the inner edge.\n const unit: [number, number][] = [[0, 0]]\n const end = start + sweep\n unit.push([Math.sin(start), -Math.cos(start)], [Math.sin(end), -Math.cos(end)])\n // (At most a full turn of them: a huge start angle is beyond what adding a quarter turn changes.)\n for (let a = Math.ceil(start / HALF_PI) * HALF_PI, n = 0; n < 5 && a <= end + 1e-9; n++) {\n unit.push([Math.sin(a), -Math.cos(a)])\n a += HALF_PI\n }\n let outer = Math.min(area.width, area.height) / 2\n let box = { x0: 0, y0: 0, x1: 0, y1: 0 }\n // The text does not scale with the radius, so converge in a few rounds.\n for (let i = 0; i < 4; i++) {\n box = { x0: 0, y0: textTop, x1: 0, y1: textBottom }\n for (const [x, y] of unit) {\n box.x0 = Math.min(box.x0, x * outer)\n box.x1 = Math.max(box.x1, x * outer)\n box.y0 = Math.min(box.y0, y * outer)\n box.y1 = Math.max(box.y1, y * outer)\n }\n const scale = Math.min(area.width / (box.x1 - box.x0), area.height / (box.y1 - box.y0))\n if (Math.abs(scale - 1) < 1e-3) break\n outer = Math.max(0, outer * scale)\n }\n return {\n outer,\n cx: area.x + (area.width - (box.x1 - box.x0)) / 2 - box.x0,\n cy: area.y + (area.height - (box.y1 - box.y0)) / 2 - box.y0,\n }\n}\n\nfunction renderGauge(options: GaugeOptions, ctx: RenderContext): ChildInput {\n const { width, height, locale } = ctx\n const thickness = Math.max(1, options.thickness ?? 12)\n const gap = Math.max(0, options.gap ?? 4)\n const cornerRadius = options.cornerRadius ?? thickness / 2\n const pad = insets(options.padding, 0)\n const area = innerRect(width, height, {\n top: pad.top + HALO,\n right: pad.right + HALO,\n bottom: pad.bottom + HALO,\n left: pad.left + HALO,\n })\n const start = (options.startAngle ?? 0) * DEG\n const sweep = Math.min(360, Math.max(0, options.angle ?? 360)) * DEG\n const rings = layoutRings(options, ctx.hidden)\n const center = options.center\n const first = rings[0]\n const showCenter = center !== false && first !== undefined\n const centerLabel = showCenter ? (center?.label ?? (first.data.name || undefined)) : undefined\n const { outer, cx, cy } = fitGauge(\n area,\n start,\n sweep,\n showCenter ? -1.4 * ctx.fontSize : 0,\n showCenter ? (centerLabel ? 2 : 0.7) * ctx.fontSize : 0,\n )\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n\n const radii = (ring: Ring, grow = 0) => {\n const r1 = Math.max(0, outer - ring.position * (thickness + gap))\n return { innerRadius: Math.max(0, r1 - thickness - grow), outerRadius: r1 + grow }\n }\n const fraction = (ring: Ring) => (ring.max > 0 ? ring.value / ring.max : 0)\n const geometry = (ring: Ring, grow = 0) => ({\n ...radii(ring, grow),\n startAngle: start,\n endAngle: start + sweep * fraction(ring),\n cornerRadius,\n })\n\n const hitFor = (ring: Ring): Hit => {\n const [x, y] = arcCentroid(geometry(ring))\n const item: HitItem = {\n name: ring.data.name,\n seriesIndex: ring.index,\n value: ring.value,\n text: `${value(ring.value)} (${share.format(fraction(ring))})`,\n x: cx + x,\n y: cy + y,\n }\n if (ring.data.color) item.color = ring.data.color\n return {\n index: ring.position,\n label: ring.data.name,\n title: '',\n x: cx + x,\n area: { x: cx - outer, y: cy - outer, width: outer * 2, height: outer * 2 },\n items: [item],\n seriesIndex: ring.index,\n // The value arc, slightly enlarged.\n mark: { d: arcPathStable(geometry(ring, 2)), x: cx, y: cy },\n }\n }\n\n const interaction: Interaction = {\n count: rings.length,\n hitIndex: (position) => {\n const ring = rings[position]\n return ring ? hitFor(ring) : null\n },\n hitTest(px, py) {\n const r = Math.hypot(px - cx, py - cy)\n const ring = rings.find((ring) => {\n const { innerRadius, outerRadius } = radii(ring, 2)\n return r >= innerRadius && r <= outerRadius\n })\n return ring ? hitFor(ring) : null\n },\n }\n ctx.onHitTest(interaction)\n\n const groups = rings.map((ring) =>\n h(\n 'g',\n groupAttrs(ring.data, ring.index),\n // Each path keeps its arc, so a new value (or a new shape of the gauge)\n // sweeps it around the center (see `sweep`).\n arcNode('tc-gauge-track', { ...geometry(ring), endAngle: start + sweep }),\n arcNode('tc-gauge-arc', geometry(ring)),\n ),\n )\n\n const centerValue = showCenter ? (center?.value ?? share.format(fraction(first))) : ''\n\n return [\n // Rings sit in their own group: the entrance animation transforms it, not the translated parent.\n h(\n 'g',\n { class: 'tc-gauge', style: `transform:translate(${cx}px,${cy}px)` },\n h('g', { class: 'tc-gauge-rings' }, groups),\n ),\n showCenter &&\n h(\n 'g',\n { class: 'tc-gauge-center', 'aria-hidden': 'true' },\n h(\n 'text',\n {\n class: 'tc-gauge-value',\n x: cx,\n y: cy,\n dy: centerLabel ? '0' : '0.35em',\n 'text-anchor': 'middle',\n },\n centerValue,\n ),\n centerLabel &&\n h(\n 'text',\n { class: 'tc-gauge-label', x: cx, y: cy, dy: '1.6em', 'text-anchor': 'middle' },\n centerLabel,\n ),\n ),\n ]\n}\n\nfunction gaugeTable(options: GaugeOptions, ctx: RenderContext): DataTable {\n const value = formatNumber(options.format, ctx.locale)\n const share = getNumberFormat(ctx.locale, { style: 'percent', maximumFractionDigits: 1 })\n return {\n columns: ['', 'Value', 'Share'],\n rows: layoutRings(options, ctx.hidden).map((ring) => [\n ring.data.name,\n value(ring.value),\n share.format(ring.max > 0 ? ring.value / ring.max : 0),\n ]),\n }\n}\n\n/**\n * Gauge (radial bar): progress towards a maximum as an arc on a track, with\n * the share in the middle. Several rings nest from the outside in.\n *\n * ```ts\n * new Chart('#el', { type: gauge, data: 58 })\n * new Chart('#el', { type: gauge, data: { name: 'completed', value: 1392, max: 2400 } })\n * ```\n */\nexport const gauge: ChartType<GaugeOptions> = {\n name: 'gauge',\n clean: cleanData((data) =>\n cleanItems(\n typeof data === 'number' ? [{ name: '', value: data }] : isRecord(data) ? [data] : data,\n ),\n ),\n render: (options, ctx): ChildInput => {\n // Set here, not as the module loads (see pie).\n features.sweep = sweepArcs\n return renderGauge(options, ctx)\n },\n legend: (options) => legendItems(ringsOf(options)),\n table: gaugeTable,\n}\n","import type { ChartType, LegendItem, RenderContext } from '../chart.ts'\nimport { axis, axisSize, bandTicks, thinTicks } from '../components/axis.ts'\nimport { formatNumber, type Locale, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { estimateTextWidth, type InsetsInput, innerRect, insets, round } from '../layout.ts'\nimport { band } from '../scales/band.ts'\nimport { extent } from '../scales/extent.ts'\nimport { h, type StyleValue } from '../vnode.ts'\nimport {\n type CartesianData,\n type Label,\n labelKey,\n resolveLabels,\n type Series,\n seriesKey,\n seriesLegend,\n seriesTable,\n} from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\n\n/** A band of values drawn in one color, with its own legend entry. */\nexport interface HeatmapRange {\n /** Lowest value in the band (inclusive). Leave it out for \"everything below `to`\". */\n from?: number\n /** Value where the band ends (exclusive). Leave it out on the last band. */\n to?: number\n /**\n * Any CSS color, including `var(--tc-color-3)`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color: string\n /** Legend and tooltip name, e.g. `'High'`. Defaults to the range, e.g. `10–30`. */\n name?: string\n}\n\nexport interface HeatmapOptions {\n /** Columns are the labels, rows are the series (first series on top). */\n data: CartesianData\n /** Value shown with the lightest shade (or the first color). Defaults to the smaller of `0` and the data minimum. */\n min?: number\n /** Value shown with the full color (or the last color). Defaults to the data maximum. */\n max?: number\n /**\n * Discrete bands of values, each in its own color and legend entry (which\n * also hides the band's cells). Takes precedence over `colors` and `colorBy`.\n */\n ranges?: readonly HeatmapRange[]\n /**\n * A continuous scale through two or more colors (any CSS color, including\n * `var(--tc-…)`), from `min` to `max`. For values around a reference\n * point, use two hues with a neutral middle, e.g.\n * `['var(--tc-color-1)', 'var(--tc-grid-color)', 'var(--tc-color-8)']`.\n * Values that could inject CSS are ignored, as for series colors.\n */\n colors?: readonly string[]\n /** Value placed on the middle color of `colors` (e.g. `0` for changes). Defaults to halfway. */\n mid?: number\n /**\n * `'series'` shades every row in its own palette color (with a legend of\n * the rows); `'value'` (the default) uses one hue, `--tc-heat-color`.\n */\n colorBy?: 'value' | 'series'\n /** Space between cells in pixels, drawn as surface. Defaults to `2`. */\n gap?: number\n /** Corner radius of the cells. Defaults to `3`. */\n radius?: number\n /** Format of the values (tooltip, table). */\n format?: NumberFormat\n /** Column labels along the bottom. */\n x?: { show?: boolean; format?: (label: Label, index: number) => string }\n /** Row names on the left. */\n y?: { show?: boolean }\n /** Extra space around the grid, in pixels. */\n padding?: InsetsInput\n}\n\n/** Share of the full color at the minimum, so zero still reads as a value, not a gap. */\nconst FLOOR = 0.08\n\nconst EMPTY = 'var(--tc-heat-empty,var(--tc-grid-color))'\n\n/** Cell color at `share` (0…1) of the way from the empty shade to `color`. */\nconst shade = (share: number, color = 'var(--tc-heat-color,var(--tc-color-1))'): string =>\n `color-mix(in oklab,${color} ${round(share * 100)}%,${EMPTY})`\n\n/** Legend key of a range. */\nconst rangeKey = (range: HeatmapRange, index: number): string => range.name ?? `range-${index + 1}`\n\n/** The first range containing `v` (`from` inclusive, `to` exclusive). */\nconst rangeOf = (ranges: readonly HeatmapRange[], v: number): number =>\n ranges.findIndex((r) => (r.from === undefined || v >= r.from) && (r.to === undefined || v < r.to))\n\n/** Color of a palette slot by series index, as the CSS classes would pick it. */\nconst slotColor = (series: Series, index: number): string =>\n series.color ?? (index < 8 ? `var(--tc-color-${index + 1})` : 'var(--tc-color-other)')\n\n/** How one cell is painted: inline style, the tooltip swatch, and whether it is drawn empty. */\ninterface Paint {\n style?: StyleValue\n color: string\n empty?: boolean\n}\n\n/** A rounded rectangle as path data, for the hover ring. */\nfunction ringPath(x: number, y: number, w: number, hgt: number, r: number): string {\n const rr = Math.max(0, Math.min(r, w / 2, hgt / 2))\n const n = round\n return (\n `M${n(x + rr)},${n(y)}H${n(x + w - rr)}A${n(rr)},${n(rr)},0,0,1,${n(x + w)},${n(y + rr)}` +\n `V${n(y + hgt - rr)}A${n(rr)},${n(rr)},0,0,1,${n(x + w - rr)},${n(y + hgt)}` +\n `H${n(x + rr)}A${n(rr)},${n(rr)},0,0,1,${n(x)},${n(y + hgt - rr)}` +\n `V${n(y + rr)}A${n(rr)},${n(rr)},0,0,1,${n(x + rr)},${n(y)}Z`\n )\n}\n\nfunction renderHeatmap(options: HeatmapOptions, ctx: RenderContext) {\n const { width, height, fontSize, locale } = ctx\n const { gap = 2, radius = 3 } = options\n const labels = resolveLabels(options.data)\n const formatLabel = options.x?.format ?? ((label: Label) => String(label))\n const value = formatNumber(options.format, locale)\n\n // Color domain.\n const all = options.data.series.flatMap((s) => s.values)\n const [dataMin, dataMax] = extent(all) ?? [0, 1]\n const lo = options.min ?? Math.min(0, dataMin)\n const hi = options.max ?? dataMax\n /** Position of a value in the domain, 0…1 (through `mid` for a scale with a middle). */\n const position = (v: number) => {\n const { mid } = options\n let t: number\n if (mid !== undefined && options.colors && lo < mid && mid < hi) {\n t = v <= mid ? ((v - lo) / (mid - lo)) * 0.5 : 0.5 + ((v - mid) / (hi - mid)) * 0.5\n } else {\n t = hi > lo ? (v - lo) / (hi - lo) : v > lo ? 1 : 0\n }\n return Math.min(1, Math.max(0, t))\n }\n const share = (v: number) => FLOOR + (1 - FLOOR) * position(v)\n\n const ranges = options.ranges?.length ? options.ranges : undefined\n const stops = !ranges && options.colors && options.colors.length >= 2 ? options.colors : undefined\n const bySeries = !ranges && !stops && options.colorBy === 'series'\n // Rows hidden from the legend (rows are legend entries when colored by series).\n const rows = bySeries\n ? options.data.series.filter((s) => !ctx.hidden.has(seriesKey(s)))\n : options.data.series\n const slot = (row: Series) => options.data.series.indexOf(row)\n\n /** How the cell of `row` with value `v` is painted in the active color mode. */\n const paint = (v: number, row: Series): Paint => {\n if (ranges) {\n const index = rangeOf(ranges, v)\n const range = ranges[index]\n if (!range || ctx.hidden.has(rangeKey(range, index))) return { color: EMPTY, empty: true }\n return { style: { '--tc-cell-fill': range.color }, color: range.color }\n }\n if (stops) {\n const at = position(v) * (stops.length - 1)\n const k = Math.min(stops.length - 2, Math.floor(at))\n const u = round((at - k) * 100)\n const from = stops[k] as string\n const color =\n u <= 0\n ? from\n : u >= 100\n ? (stops[k + 1] as string)\n : `color-mix(in oklab,${stops[k + 1]} ${u}%,${from})`\n return { style: { '--tc-cell-fill': color }, color }\n }\n const pct = share(v)\n return {\n style: `--tc-heat:${round(pct * 100)}%`,\n color: bySeries ? shade(pct, slotColor(row, slot(row))) : shade(pct),\n }\n }\n\n // Margins for the labels, then one band per column and per row.\n const pad = insets(options.padding, 0)\n const showX = options.x?.show !== false && labels.length > 0\n const showY = options.y?.show !== false && rows.length > 0\n const rowTicks = rows.map((s, i) => ({ value: i, position: 0, label: s.name }))\n const left = showY ? axisSize('left', rowTicks, fontSize) : 0\n const bottom = showX ? axisSize('bottom', [{ value: 0, position: 0, label: 'M' }], fontSize) : 0\n // The last column label is centered on its column: what is wider than half a\n // column needs room on the right.\n const lastLabel = showX\n ? estimateTextWidth(\n formatLabel(labels[labels.length - 1] as Label, labels.length - 1),\n fontSize,\n )\n : 0\n const halfColumn = (width - pad.left - pad.right - left) / Math.max(1, labels.length) / 2\n const area = innerRect(width, height, {\n top: pad.top,\n right: pad.right + Math.max(0, Math.ceil(lastLabel / 2 - halfColumn)),\n bottom: pad.bottom + bottom,\n left: pad.left + left,\n })\n const x = band(\n labels.map((_, i) => i),\n [area.x, area.x + area.width],\n )\n const y = band(\n rows.map((_, i) => i),\n [area.y, area.y + area.height],\n )\n const cellW = Math.max(0, x.bandwidth - gap)\n const cellH = Math.max(0, y.bandwidth - gap)\n const cellX = (i: number) => x.at(i) + gap / 2\n const cellY = (j: number) => y.at(j) + gap / 2\n const valueAt = (i: number, j: number) => {\n const v = rows[j]?.values[i]\n return v != null && Number.isFinite(v) ? v : null\n }\n\n // One hit per column; every row is an item, the hovered row is active.\n const hitAt = (i: number, row = 0): Hit | null => {\n if (i < 0 || i >= labels.length || rows.length === 0) return null\n const j = Math.max(0, Math.min(rows.length - 1, row))\n const items: HitItem[] = rows.map((s, r) => {\n const v = valueAt(i, r)\n const range = ranges && v !== null ? ranges[rangeOf(ranges, v)] : undefined\n return {\n name: s.name,\n seriesIndex: r,\n value: v,\n // With ranges, the band's name says what the value means.\n text: v === null ? '–' : range?.name ? `${value(v)} · ${range.name}` : value(v),\n x: cellX(i) + cellW / 2,\n y: cellY(r) + cellH / 2,\n box: { x: cellX(i), y: cellY(r), width: cellW, height: cellH },\n color: v === null ? 'var(--tc-grid-color)' : paint(v, s).color,\n }\n })\n return {\n index: i,\n label: labelKey(labels[i] as Label),\n title: formatLabel(labels[i] as Label, i),\n x: cellX(i) + cellW / 2,\n area,\n items,\n seriesIndex: j,\n // A ring just outside the hovered cell.\n mark: {\n d: ringPath(cellX(i) - 2, cellY(j) - 2, cellW + 4, cellH + 4, radius + 2),\n x: 0,\n y: 0,\n },\n }\n }\n\n const interaction: Interaction = {\n count: labels.length,\n hitIndex: (i, row) => hitAt(i, row),\n hitTest(px, py) {\n if (px < area.x || px > area.x + area.width || py < area.y || py > area.y + area.height) {\n return null\n }\n const i = Math.min(labels.length - 1, Math.floor((px - area.x) / (x.step || 1)))\n const j = Math.min(rows.length - 1, Math.floor((py - area.y) / (y.step || 1)))\n return hitAt(i, j)\n },\n }\n ctx.onHitTest(interaction)\n\n const cells = rows.map((s, j) =>\n h(\n 'g',\n {\n key: seriesKey(s),\n // Colored by series, a row takes its palette slot like any series.\n class: ['tc-heatmap-row', bySeries && ['tc-series', `tc-series-${slot(s) + 1}`]],\n 'data-series': s.name,\n style: bySeries ? { '--tc-series-color': s.color } : undefined,\n },\n labels.map((label, i) => {\n const v = valueAt(i, j)\n const painted = v === null ? undefined : paint(v, s)\n return h('rect', {\n key: labelKey(label),\n class: ['tc-cell', (v === null || painted?.empty) && 'tc-cell-empty'],\n x: round(cellX(i)),\n y: round(cellY(j)),\n width: round(cellW),\n height: round(cellH),\n rx: round(Math.min(radius, cellW / 2, cellH / 2)),\n style: painted?.style,\n })\n }),\n ),\n )\n\n const xTicks = showX\n ? thinTicks(\n bandTicks(x, (_, i) => formatLabel(labels[i] as Label, i)),\n 'bottom',\n fontSize,\n )\n : []\n const yTicks = showY ? bandTicks(y, (_, j) => rows[j]?.name ?? '') : []\n\n return [\n h('g', { class: 'tc-heatmap-cells' }, cells),\n showX && axis({ position: 'bottom', ticks: xTicks, area }),\n showY && axis({ position: 'left', ticks: yTicks, area }),\n ]\n}\n\n/** Legend: the ranges, or the rows when colored by series; none for a single scale. */\nfunction heatmapLegend(options: HeatmapOptions): LegendItem[] {\n const { ranges } = options\n if (ranges?.length) {\n // The legend is asked with the whole config, so the names follow its locale.\n const value = formatNumber(options.format, (options as { locale?: Locale }).locale)\n return ranges.map((range, index) => ({\n key: rangeKey(range, index),\n name:\n range.name ??\n (range.from === undefined\n ? `< ${value(range.to ?? 0)}`\n : range.to === undefined\n ? `≥ ${value(range.from)}`\n : `${value(range.from)}–${value(range.to)}`),\n index,\n color: range.color,\n }))\n }\n if (options.colors && options.colors.length >= 2) return []\n return options.colorBy === 'series' ? seriesLegend(options.data) : []\n}\n\n/**\n * Heatmap: a grid of cells, one row per series and one column per label,\n * shaded from light to the full color by value (a single hue, so it reads\n * as magnitude). Set the hue with `--tc-heat-color`, or color the cells by\n * `ranges` of values, a `colors` scale (with a `mid` for diverging data),\n * or one palette color per row with `colorBy: 'series'`.\n *\n * ```ts\n * new Chart('#el', {\n * type: heatmap,\n * data: { labels: ['W1', 'W2', 'W3'], series: [{ name: 'Mon', values: [2, 4, 0] }] },\n * })\n * ```\n */\nexport const heatmap: ChartType<HeatmapOptions> = {\n name: 'heatmap',\n clean: cleanData(cleanSeries),\n render: renderHeatmap,\n legend: heatmapLegend,\n valueLabels: { marks: 'cell', format: (options) => options.format },\n // Cells are formatted as in the tooltip: `format` is the value format here, not `y.format`.\n table: (options, ctx, limit) =>\n seriesTable(\n { data: options.data, ...(options.x ? { x: options.x } : {}), y: { format: options.format } },\n ctx,\n limit,\n ),\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext } from '../chart.ts'\nimport { features } from '../features.ts'\nimport { formatNumber, getNumberFormat, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { type InsetsInput, innerRect, insets } from '../layout.ts'\nimport { arcNode, sweep } from '../render/sweep.ts'\nimport { arcCentroid, arcPathStable, DEG, HALO, padAngleForGap } from '../shapes/arc.ts'\nimport { type ChildInput, type ClassValue, h } from '../vnode.ts'\nimport { cleanData, cleanItems } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** One slice of a pie or donut. */\nexport interface PieSlice {\n name: string\n /** Non-negative value; negative values count as zero. */\n value: number\n /** Stable identity for keyed updates and legend toggles. Defaults to `name`. */\n id?: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the slice group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface PieOptions {\n data: readonly PieSlice[]\n /** Hole size relative to the radius, `0…0.95`. Defaults to `0` (`0.62` for `donut`). */\n innerRadius?: number\n /** Gap between slices in pixels, drawn as surface. Defaults to `2`. */\n gap?: number\n /** Corner radius of the slices. Defaults to `0` (`4` for `donut`). */\n cornerRadius?: number\n /** Where the first slice starts, in degrees clockwise from 12 o'clock. Defaults to `0`. */\n startAngle?: number\n /** Format of the values (tooltip, table, donut total). */\n format?: NumberFormat\n /**\n * Text in the donut hole: the total by default; `false` hides it, or give\n * your own `value` / `label`.\n */\n center?: false | { value?: string; label?: string }\n /** Extra space around the pie, in pixels. */\n padding?: InsetsInput\n}\n\ninterface Slice {\n data: PieSlice\n index: number\n value: number\n startAngle: number\n endAngle: number\n}\n\n/** Angles of the visible slices, clockwise from `startAngle`. */\nfunction layoutSlices(\n options: PieOptions,\n hidden: ReadonlySet<string>,\n): { slices: Slice[]; total: number } {\n const visible = options.data\n .map((data, index) => ({ data, index, value: Math.max(0, data.value || 0) }))\n .filter((slice) => !hidden.has(keyOf(slice.data)))\n const total = visible.reduce((sum, slice) => sum + slice.value, 0)\n let angle = (options.startAngle ?? 0) * DEG\n const slices = visible.map((slice) => {\n const sweep = total > 0 ? (slice.value / total) * Math.PI * 2 : 0\n const out: Slice = { ...slice, startAngle: angle, endAngle: angle + sweep }\n angle += sweep\n return out\n })\n return { slices, total }\n}\n\nfunction renderPie(\n options: PieOptions,\n ctx: RenderContext,\n defaults: { inner: number; corner: number },\n) {\n const { width, height, locale } = ctx\n const gap = options.gap ?? 2\n const area = innerRect(width, height, insets(options.padding, 0))\n const outer = Math.max(0, Math.min(area.width, area.height) / 2 - HALO)\n const ratio = Math.min(0.95, Math.max(0, options.innerRadius ?? defaults.inner))\n const inner = outer * ratio\n const cornerRadius = options.cornerRadius ?? defaults.corner\n const cx = area.x + area.width / 2\n const cy = area.y + area.height / 2\n const { slices, total } = layoutSlices(options, ctx.hidden)\n const drawn = slices.filter((slice) => slice.value > 0)\n // A single slice is a full ring: no gap to cut.\n // Rings get a pad angle, which keeps a constant gap width along the whole\n // edge. In a full pie every slice meets at the center, so a pad angle would\n // widen into a wedge: the gap is a surface-colored stroke instead.\n const strokeGap = inner === 0 && drawn.length > 1 ? gap : 0\n const padAngle = inner > 0 && drawn.length > 1 ? padAngleForGap(gap, inner, outer) : 0\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n\n const geometry = (slice: Slice, r0 = inner, r1 = outer) => ({\n innerRadius: r0,\n outerRadius: r1,\n startAngle: slice.startAngle,\n endAngle: slice.endAngle,\n padAngle,\n cornerRadius,\n })\n\n const hitFor = (slice: Slice, position: number): Hit => {\n const [x, y] = arcCentroid(geometry(slice))\n const item: HitItem = {\n name: slice.data.name,\n seriesIndex: slice.index,\n value: slice.value,\n text: `${value(slice.value)} (${share.format(total > 0 ? slice.value / total : 0)})`,\n x: cx + x,\n y: cy + y,\n }\n if (slice.data.color) item.color = slice.data.color\n return {\n index: position,\n label: slice.data.name,\n title: '',\n x: cx + x,\n area: { x: cx - outer, y: cy - outer, width: outer * 2, height: outer * 2 },\n items: [item],\n seriesIndex: slice.index,\n // A thin halo just outside the slice.\n mark: {\n d: arcPathStable({ ...geometry(slice, outer + 2, outer + 6), cornerRadius: 2 }),\n x: cx,\n y: cy,\n },\n }\n }\n\n const interaction: Interaction = {\n count: drawn.length,\n hitIndex: (position) => {\n const slice = drawn[position]\n return slice ? hitFor(slice, position) : null\n },\n hitTest(px, py) {\n const dx = px - cx\n const dy = py - cy\n const r = Math.hypot(dx, dy)\n if (r < inner - 2 || r > outer + HALO) return null\n const start = (options.startAngle ?? 0) * DEG\n const turn = Math.PI * 2\n // Clockwise angle from 12 o'clock, normalized into [start, start + turn).\n let angle = Math.atan2(dx, -dy)\n angle = start + ((((angle - start) % turn) + turn) % turn)\n const position = drawn.findIndex((s) => angle >= s.startAngle && angle < s.endAngle)\n return position === -1 ? null : hitFor(drawn[position] as Slice, position)\n },\n }\n ctx.onHitTest(interaction)\n\n const groups = slices.map((slice) =>\n h(\n 'g',\n groupAttrs(slice.data, slice.index),\n // The path keeps its arc, so new data sweeps slices around the center\n // (see `sweep`). An empty slice keeps its path, a line with no area in\n // the gap between its neighbors, to grow from there.\n arcNode('tc-slice', geometry(slice)),\n ),\n )\n\n const center = options.center\n const showCenter = inner > 0 && center !== false\n const centerValue = showCenter ? (center?.value ?? value(total)) : ''\n const centerLabel = showCenter ? center?.label : undefined\n\n return [\n h(\n 'g',\n { class: 'tc-pie', style: `transform:translate(${cx}px,${cy}px)` },\n total === 0 &&\n h('path', {\n class: 'tc-pie-track',\n d: arcPathStable({\n innerRadius: inner,\n outerRadius: outer,\n startAngle: 0,\n endAngle: Math.PI * 2,\n }),\n }),\n h(\n 'g',\n {\n class: 'tc-pie-slices',\n style: strokeGap > 0 ? `--tc-pie-gap:${strokeGap}px` : undefined,\n },\n groups,\n ),\n ),\n showCenter &&\n h(\n 'g',\n { class: 'tc-pie-center', 'aria-hidden': 'true' },\n h(\n 'text',\n {\n class: 'tc-pie-value',\n x: cx,\n y: cy,\n dy: centerLabel ? '0' : '0.35em',\n 'text-anchor': 'middle',\n },\n centerValue,\n ),\n centerLabel &&\n h(\n 'text',\n { class: 'tc-pie-label', x: cx, y: cy, dy: '1.6em', 'text-anchor': 'middle' },\n centerLabel,\n ),\n ),\n ]\n}\n\nfunction pieTable(options: PieOptions, ctx: RenderContext): DataTable {\n const { slices, total } = layoutSlices(options, ctx.hidden)\n const value = formatNumber(options.format, ctx.locale)\n const share = getNumberFormat(ctx.locale, { style: 'percent', maximumFractionDigits: 1 })\n return {\n columns: ['', 'Value', 'Share'],\n rows: slices.map((slice) => [\n slice.data.name,\n value(slice.value),\n share.format(total > 0 ? slice.value / total : 0),\n ]),\n }\n}\n\nfunction pieType(name: string, defaults: { inner: number; corner: number }): ChartType<PieOptions> {\n return {\n name,\n clean: cleanData(cleanItems),\n render: (options, ctx): ChildInput => {\n // Set here, not as the module loads: a module with side effects would\n // stay in every bundle that imports another chart type next to it.\n features.sweep = sweep\n return renderPie(options, ctx, defaults)\n },\n legend: (options) => legendItems(options.data),\n table: pieTable,\n valueLabels: { marks: 'slice' },\n }\n}\n\n/**\n * Pie chart: parts of a whole as slices, in data order, clockwise from the top.\n *\n * ```ts\n * new Chart('#el', { type: pie, data: [{ name: 'Direct', value: 42 }, { name: 'Search', value: 31 }] })\n * ```\n */\nexport const pie: ChartType<PieOptions> = pieType('pie', { inner: 0, corner: 0 })\n\n/** Donut chart: a pie with a hole showing the total (or your own `center`). */\nexport const donut: ChartType<PieOptions> = pieType('donut', { inner: 0.62, corner: 4 })\n","import type { ChartType, RenderContext } from '../chart.ts'\nimport { linearTicks } from '../components/axis.ts'\nimport { formatDetail, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n round,\n} from '../layout.ts'\nimport { linear } from '../scales/linear.ts'\nimport { type ChildInput, h } from '../vnode.ts'\nimport {\n type CartesianData,\n domainOf,\n type Label,\n labelKey,\n resolveLabels,\n seriesAttrs,\n seriesKey,\n seriesLegend,\n seriesTable,\n tickCount,\n} from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\n\n/** Options for the radial value axis. */\nexport interface RadialAxisOptions {\n /** Render the value labels along the first spoke. Defaults to `true`. */\n show?: boolean\n /** Value at the center. Defaults to `0` (or the data minimum when it is negative). */\n min?: number\n /** Value at the outer ring. Defaults to the niced data maximum. */\n max?: number\n /** Extend the domain to round values. Defaults to `true`. */\n nice?: boolean\n /** Approximate number of rings. Defaults to one per ~40px of radius. */\n ticks?: number\n format?: NumberFormat\n}\n\nexport interface RadarOptions {\n /** One spoke per label, one polygon per series. */\n data: CartesianData\n /** The radial value axis. */\n r?: RadialAxisOptions\n /** Format of the spoke labels (axis, tooltips and the table). */\n format?: (label: Label, index: number) => string\n /** Shape of the rings. Defaults to `'polygon'`. */\n grid?: 'polygon' | 'circle'\n /** Fill each polygon. Defaults to `true`. */\n fill?: boolean\n /** Draw a dot on every value. Defaults to `false`. */\n points?: boolean\n /** Dot radius in pixels. Defaults to `4`. */\n pointRadius?: number\n /**\n * Widest spoke label, in pixels: a longer one wraps at its spaces onto up\n * to three lines. Defaults to a quarter of the chart's width.\n */\n labelWidth?: number\n /** Extra space around the chart, in pixels. */\n padding?: InsetsInput\n}\n\n/** Space between the outer ring and the spoke labels. */\nconst LABEL_GAP = 8\n/** Pixels around the outer ring that still count as hovering it. */\nconst HOVER_SLOP = 8\n\n/** Smallest radius, as a share of the space, however long the labels. */\nconst MIN_RADIUS = 0.5\n/** Most lines a wrapped spoke label takes. */\nconst MAX_LINES = 3\n\n/** `text`, cut short with an ellipsis to fit `width` pixels. */\nfunction truncate(text: string, width: number, fontSize: number): string {\n if (estimateTextWidth(text, fontSize) <= width) return text\n let end = text.length\n while (end > 0 && estimateTextWidth(`${text.slice(0, end)}…`, fontSize) > width) end--\n return end > 0 ? `${text.slice(0, end).trimEnd()}…` : ''\n}\n\n/**\n * `text` split at its spaces into lines no wider than `width` pixels (a word\n * wider than that gets a line of its own), at most `MAX_LINES` of them: what\n * is left joins the last line.\n */\nfunction wrap(text: string, width: number, fontSize: number): string[] {\n const lines: string[] = []\n let line = ''\n for (const word of text.split(' ')) {\n const next = line ? `${line} ${word}` : word\n if (!line || estimateTextWidth(next, fontSize) <= width) line = next\n else {\n lines.push(line)\n line = word\n }\n }\n lines.push(line)\n if (lines.length > MAX_LINES)\n lines.splice(MAX_LINES - 1, lines.length, lines.slice(MAX_LINES - 1).join(' '))\n return lines\n}\n\n/** Text anchor of a spoke label on the side its spoke points to. */\nconst side = (sin: number): -1 | 0 | 1 => (sin > 0.1 ? 1 : sin < -0.1 ? -1 : 0)\n\n/**\n * The largest radius at which every spoke label still fits in `area`:\n * labels sit beyond the outer ring, on the side their spoke points to.\n */\nfunction fitRadius(\n area: { width: number; height: number },\n angles: readonly number[],\n labels: readonly (readonly string[])[],\n fontSize: number,\n): number {\n let radius = Math.min(area.width, area.height) / 2\n angles.forEach((angle, i) => {\n const sin = Math.sin(angle)\n const cos = Math.cos(angle)\n const lines = labels[i] ?? []\n const w = Math.max(0, ...lines.map((line) => estimateTextWidth(line, fontSize)))\n const height = blockHeight(lines.length, fontSize)\n const s = side(sin)\n // Horizontal: the label runs outwards from the spoke end (or is centered on it).\n const across = s === 0 ? w / 2 : w + LABEL_GAP\n if (Math.abs(sin) > 1e-6) radius = Math.min(radius, (area.width / 2 - across) / Math.abs(sin))\n // Vertical: the lines of text above the top spokes, below the bottom ones,\n // centered on the ones at the sides.\n if (Math.abs(cos) > 1e-6) {\n const along = (s === 0 ? height + LABEL_GAP : height / 2) / Math.abs(cos)\n radius = Math.min(radius, area.height / 2 / Math.abs(cos) - along)\n }\n })\n return Math.max(0, radius)\n}\n\n/** Height of `lines` lines of text, in pixels. */\nconst blockHeight = (lines: number, fontSize: number) =>\n fontSize * (1 + Math.max(0, lines - 1) * LINE_HEIGHT)\n\nfunction renderRadar(options: RadarOptions, ctx: RenderContext): ChildInput {\n const { width, height, fontSize, locale } = ctx\n const axis = options.r ?? {}\n const { fill = true, points = false, pointRadius = 4 } = options\n const series = options.data.series\n const labels = resolveLabels(options.data)\n const n = labels.length\n const visible = series.filter((s) => !ctx.hidden.has(seriesKey(s)))\n const formatLabel = options.format ?? ((label: Label) => String(label))\n const formatValue = formatDetail(axis.format, locale)\n\n const pad = insets(options.padding)\n const area = innerRect(width, height, {\n top: pad.top + LABEL_GAP,\n right: pad.right + LABEL_GAP,\n bottom: pad.bottom + LABEL_GAP,\n left: pad.left + LABEL_GAP,\n })\n const cx = area.x + area.width / 2\n const cy = area.y + area.height / 2\n const angles = labels.map((_, i) => (i / Math.max(1, n)) * Math.PI * 2)\n const texts = labels.map((label, i) => formatLabel(label, i))\n // Long labels wrap onto a few lines, then the radius fits them, but never\n // shrinks below a share of the space: lines that still do not fit are cut\n // short (the tooltip and the table keep the labels whole).\n const labelWidth = options.labelWidth ?? area.width / 4\n const wrapped = texts.map((text) => wrap(text, labelWidth, fontSize))\n const radius = Math.max(\n fitRadius(area, angles, wrapped, fontSize),\n (Math.min(area.width, area.height) / 2) * MIN_RADIUS,\n )\n const shown = wrapped.map((lines, i) => {\n const sin = Math.sin(angles[i] as number)\n const room = side(sin) === 0 ? area.width : area.width / 2 - radius * Math.abs(sin) - LABEL_GAP\n return lines.map((line) => truncate(line, room, fontSize))\n })\n\n const count = tickCount(axis, Math.max(2, Math.round(radius / 40)))\n const values = visible.flatMap((s) => s.values)\n const domain = domainOf(values, axis, true, count)\n const scale = linear(domain, [0, radius], { clamp: true })\n const ticks = linearTicks(scale, { count, format: axis.format, locale })\n\n /** Point at `r` pixels from the center along spoke `i`. */\n const at = (i: number, r: number): [number, number] => [\n cx + r * Math.sin(angles[i] as number),\n cy - r * Math.cos(angles[i] as number),\n ]\n /** A closed path through one radius per spoke (the same commands for any values). */\n const polygon = (radii: readonly number[]) =>\n `${radii.map((r, i) => `${i ? 'L' : 'M'}${at(i, r).map(round).join(',')}`).join('')}Z`\n const ring = (r: number) =>\n options.grid === 'circle'\n ? `M${round(cx)},${round(cy - r)}A${round(r)},${round(r)},0,1,1,${round(cx)},${round(cy + r)}A${round(r)},${round(r)},0,1,1,${round(cx)},${round(cy - r)}Z`\n : polygon(labels.map(() => r))\n /** Pixel radius of a value; missing values sit at the center. */\n const radiusOf = (v: number | null | undefined) =>\n v != null && Number.isFinite(v) ? scale(v) : 0\n\n const hitAt = (index: number): Hit => {\n const items: HitItem[] = []\n series.forEach((s, seriesIndex) => {\n if (ctx.hidden.has(seriesKey(s))) return\n const raw = s.values[index]\n const value = raw != null && Number.isFinite(raw) ? raw : null\n const [x, y] = at(index, radiusOf(value))\n const item: HitItem = {\n name: s.name,\n seriesIndex,\n value,\n text: value === null ? '–' : formatValue(value),\n x,\n y: value === null ? null : y,\n }\n if (s.color) item.color = s.color\n items.push(item)\n })\n const [x2, y2] = at(index, radius)\n return {\n index,\n label: labelKey(labels[index] as Label),\n title: texts[index] as string,\n x: x2,\n area: { x: cx - radius, y: cy - radius, width: radius * 2, height: radius * 2 },\n items,\n guide: { x1: cx, y1: cy, x2, y2 },\n }\n }\n\n const interaction: Interaction = {\n count: n,\n hitTest(px, py) {\n if (n === 0 || Math.hypot(px - cx, py - cy) > radius + HOVER_SLOP) return null\n // The nearest spoke by angle, clockwise from 12 o'clock.\n const angle = Math.atan2(px - cx, cy - py)\n const turn = (angle < 0 ? angle + Math.PI * 2 : angle) / (Math.PI * 2)\n return hitAt(Math.round(turn * n) % n)\n },\n hitIndex(index, seriesIndex) {\n if (index < 0 || index >= n) return null\n const hit = hitAt(index)\n if (seriesIndex !== undefined && hit.items.some((item) => item.seriesIndex === seriesIndex)) {\n hit.seriesIndex = seriesIndex\n }\n return hit\n },\n }\n ctx.onHitTest(interaction)\n\n const grid = h(\n 'g',\n { key: 'grid', class: 'tc-radar-grid', 'aria-hidden': 'true' },\n ticks\n .filter((tick) => tick.position > 0)\n .map((tick) =>\n h('path', { key: tick.value, class: 'tc-radar-ring', d: ring(tick.position) }),\n ),\n labels.map((label, i) => {\n const [x2, y2] = at(i, radius)\n return h('line', {\n key: labelKey(label),\n class: 'tc-radar-spoke',\n x1: round(cx),\n y1: round(cy),\n x2: round(x2),\n y2: round(y2),\n })\n }),\n )\n\n const groups = series.map((s, index) => {\n if (ctx.hidden.has(seriesKey(s))) return null\n const d = polygon(labels.map((_, i) => radiusOf(s.values[i])))\n return h(\n 'g',\n seriesAttrs(s, index),\n fill && h('path', { class: 'tc-area', d }),\n h('path', { class: 'tc-line', d }),\n points &&\n h(\n 'g',\n { class: 'tc-points' },\n labels.map((label, i) => {\n const v = s.values[i]\n if (v == null || !Number.isFinite(v)) return null\n const [x, y] = at(i, scale(v))\n return h('circle', {\n key: labelKey(label),\n class: 'tc-point',\n cx: round(x),\n cy: round(y),\n r: pointRadius,\n })\n }),\n ),\n )\n })\n\n const spokeLabels = h(\n 'g',\n { key: 'labels', class: 'tc-radar-labels', 'aria-hidden': 'true' },\n labels.map((label, i) => {\n const angle = angles[i] as number\n const s = side(Math.sin(angle))\n const cos = Math.cos(angle)\n const [x, y] = at(i, radius + LABEL_GAP)\n const [first = '', ...rest] = shown[i] ?? []\n // Above the top spokes, below the bottom ones, centered on the sides:\n // the first line moves up to leave room for the ones under it.\n const up = rest.length * LINE_HEIGHT\n const dy = s !== 0 ? `${round(0.35 - up / 2)}em` : cos > 0 ? `${round(-up)}em` : '0.71em'\n return h(\n 'text',\n {\n key: labelKey(label),\n class: 'tc-tick-label tc-radar-label',\n x: round(x),\n y: round(y),\n 'text-anchor': s > 0 ? 'start' : s < 0 ? 'end' : 'middle',\n dy,\n },\n first,\n rest.map((line, j) => h('tspan', { key: j, x: round(x), dy: `${LINE_HEIGHT}em` }, line)),\n )\n }),\n )\n\n const valueLabels =\n axis.show !== false &&\n h(\n 'g',\n { key: 'values', class: 'tc-radar-values', 'aria-hidden': 'true' },\n ticks\n .filter((tick) => tick.position > 0)\n .map((tick) =>\n h(\n 'text',\n {\n key: tick.value,\n class: 'tc-tick-label tc-radar-value',\n x: round(cx + 4),\n y: round(cy - tick.position),\n dy: '0.35em',\n },\n tick.label,\n ),\n ),\n )\n\n return [\n grid,\n // Series grow from the center: the transform origin is set here, in pixels.\n h(\n 'g',\n {\n key: 'series',\n class: 'tc-series-list tc-radar-series',\n style: `transform-origin:${round(cx)}px ${round(cy)}px`,\n },\n groups,\n ),\n spokeLabels,\n valueLabels,\n ]\n}\n\n/**\n * Radar (spider) chart: one spoke per label, the values of each series\n * joined into a polygon around the center. Good for comparing a few series\n * over the same handful of measures.\n *\n * ```ts\n * new Chart('#el', {\n * type: radar,\n * data: {\n * labels: ['Speed', 'Range', 'Comfort', 'Price', 'Safety'],\n * series: [{ name: 'Model A', values: [80, 60, 70, 40, 90] }],\n * },\n * })\n * ```\n */\nexport const radar: ChartType<RadarOptions> = {\n name: 'radar',\n clean: cleanData(cleanSeries),\n render: renderRadar,\n legend: (options) => seriesLegend(options.data),\n table: (options, ctx, limit) =>\n seriesTable(\n {\n data: options.data,\n ...(options.r?.format ? { y: { format: options.r.format } } : {}),\n ...(options.format ? { x: { format: options.format } } : {}),\n },\n ctx,\n limit,\n ),\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext } from '../chart.ts'\nimport { formatDetail, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n type Rect,\n round,\n} from '../layout.ts'\nimport type { LegendItem } from '../legend.ts'\nimport { type ChildInput, h } from '../vnode.ts'\nimport { cleanData, finite, isRecord, named, records, text } from './clean.ts'\n\n/** A node of the flow; nodes left out are made from the links. */\nexport interface SankeyNode {\n name: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`. Nodes\n * sharing a color form one legend entry, named after the first of them.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Start hidden (toggle it back from the legend, with every node of its color). */\n hidden?: boolean\n}\n\n/** A flow between two nodes, by name. */\nexport interface SankeyLink {\n from: string\n to: string\n /** Non-negative value; negative values count as zero. */\n value: number\n}\n\nexport interface SankeyData {\n /** Optional: sets the stacking order within a column, and colors. */\n nodes?: readonly SankeyNode[]\n links: readonly SankeyLink[]\n}\n\nexport interface SankeyOptions {\n data: SankeyData\n /** Width of the node bars in pixels. Defaults to `12`. */\n nodeWidth?: number\n /** Vertical gap between the nodes of a column in pixels. Defaults to `16`. */\n nodePadding?: number\n /** Format of the values (labels, tooltips and the table). */\n format?: NumberFormat\n /**\n * `'justify'` (default) puts every node without outgoing flows in the last\n * column; `'left'` leaves it in the column after its sources.\n */\n align?: 'justify' | 'left'\n /** Extra space around the diagram, in pixels. */\n padding?: InsetsInput\n}\n\ninterface Node {\n data: SankeyNode\n index: number\n /** Palette slot, 1-based: the node's position in its column. */\n slot: number\n column: number\n value: number\n x: number\n y: number\n height: number\n ins: Link[]\n outs: Link[]\n}\n\ninterface Link {\n data: SankeyLink\n index: number\n source: Node\n target: Node\n /** Top of the slice at the source and at the target. */\n sy: number\n ty: number\n width: number\n}\n\ninterface Layout {\n nodes: Node[]\n links: Link[]\n /** The columns' extent, between the label margins. */\n plot: Rect\n nodeWidth: number\n labels: NodeLabel[]\n}\n\n/** A node's label: the name and the value under it, cut to fit (empty when hidden). */\ninterface NodeLabel {\n side: 'left' | 'right'\n name: string\n value: string\n}\n\n/** Space between a node and its label. */\nconst LABEL_GAP = 8\n/** Largest share of the width one side's labels may take. */\nconst MAX_LABEL_SHARE = 0.3\n/** Pixels around a node that still count as hovering it. */\nconst HOVER_SLOP = 2\n\n/** `text`, cut short with an ellipsis to fit `width` pixels. */\nfunction truncate(text: string, width: number, fontSize: number): string {\n if (estimateTextWidth(text, fontSize) <= width) return text\n let end = text.length\n while (end > 0 && estimateTextWidth(`${text.slice(0, end)}…`, fontSize) > width) end--\n return end > 0 ? `${text.slice(0, end).trimEnd()}…` : ''\n}\n\n/** The color of a node for hover and tooltip swatches. */\nconst colorOf = (node: Node): string => node.data.color ?? `var(--tc-color-${node.slot})`\n\n/** The visible nodes and links, in data order, with their columns. */\nfunction graph(data: SankeyData, hidden: ReadonlySet<string>, justify: boolean) {\n const byName = new Map<string, Node>()\n const nodes: Node[] = []\n const node = (name: string, data?: SankeyNode): Node => {\n let found = byName.get(name)\n if (!found) {\n found = {\n data: data ?? { name },\n index: nodes.length,\n slot: 1,\n column: 0,\n value: 0,\n x: 0,\n y: 0,\n height: 0,\n ins: [],\n outs: [],\n }\n byName.set(name, found)\n nodes.push(found)\n }\n return found\n }\n const declared = new Map((data.nodes ?? []).map((n) => [n.name, n]))\n /** A legend key hides every node of its color, see `sankeyLegend`. */\n const isHidden = (name: string) => {\n const n = declared.get(name)\n return hidden.has(name) || (n?.color !== undefined && hidden.has(legendKey(data, n.color)))\n }\n const links: Link[] = []\n data.links.forEach((link, index) => {\n if (link.from === link.to || isHidden(link.from) || isHidden(link.to)) return\n const source = node(link.from, declared.get(link.from))\n const target = node(link.to, declared.get(link.to))\n const out: Link = { data: link, index, source, target, sy: 0, ty: 0, width: 0 }\n links.push(out)\n if (link.value <= 0) return\n source.outs.push(out)\n target.ins.push(out)\n })\n for (const n of nodes) {\n n.value = Math.max(\n n.outs.reduce((sum, l) => sum + l.data.value, 0),\n n.ins.reduce((sum, l) => sum + l.data.value, 0),\n )\n }\n // Column: the longest path from a source, passes bounded so cycles end.\n for (let pass = 0; pass < nodes.length; pass++) {\n let changed = false\n for (const link of links) {\n if (link.data.value > 0 && link.target.column <= link.source.column) {\n link.target.column = link.source.column + 1\n changed = true\n }\n }\n if (!changed) break\n }\n const last = nodes.reduce((max, n) => Math.max(max, n.column), 0)\n if (justify) for (const n of nodes) if (n.outs.length === 0) n.column = last\n // Stack order within a column: declared nodes first, then first appearance.\n const order = [...declared.keys()]\n nodes.sort((a, b) => {\n if (a.column !== b.column) return a.column - b.column\n const ia = order.indexOf(a.data.name)\n const ib = order.indexOf(b.data.name)\n if (ia !== -1 && ib !== -1) return ia - ib\n if (ia !== ib) return ia === -1 ? 1 : -1\n return a.index - b.index\n })\n const slots = new Map<number, number>()\n nodes.forEach((n, index) => {\n n.index = index\n const slot = (slots.get(n.column) ?? 0) + 1\n slots.set(n.column, slot)\n n.slot = ((slot - 1) % 8) + 1\n })\n return { nodes, links, columns: last + 1 }\n}\n\n/** Key of the legend entry of `color`: the first node that wears it. */\nconst legendKey = (data: SankeyData, color: string): string =>\n (data.nodes ?? []).find((n) => n.color === color)?.name ?? color\n\nfunction layout(options: SankeyOptions, ctx: RenderContext): Layout {\n const { width, height, fontSize, locale } = ctx\n const nodeWidth = Math.max(1, options.nodeWidth ?? 12)\n const nodePadding = Math.max(0, options.nodePadding ?? 16)\n const area = innerRect(width, height, insets(options.padding))\n const { nodes, links, columns } = graph(options.data, ctx.hidden, options.align !== 'left')\n const format = formatDetail(options.format, locale)\n\n // Labels take their room from the sides: the first column's to its left,\n // the last column's to its right, the rest to the right of their node.\n const texts = nodes.map((n) => [n.data.name, format(n.value)] as const)\n const widest = (match: (n: Node) => boolean) =>\n nodes.reduce((max, n, i) => {\n if (!match(n)) return max\n const [name, value] = texts[i] as readonly [string, string]\n return Math.max(max, estimateTextWidth(name, fontSize), estimateTextWidth(value, fontSize))\n }, 0)\n const cap = area.width * MAX_LABEL_SHARE\n const left =\n columns > 1\n ? Math.min(\n cap,\n widest((n) => n.column === 0),\n )\n : 0\n const right = Math.min(\n cap,\n widest((n) => n.column === columns - 1),\n )\n const plot: Rect = {\n x: area.x + (left ? left + LABEL_GAP : 0),\n y: area.y,\n width: Math.max(\n 0,\n area.width - (left ? left + LABEL_GAP : 0) - (right ? right + LABEL_GAP : 0),\n ),\n height: area.height,\n }\n const step = columns > 1 ? (plot.width - nodeWidth) / (columns - 1) : 0\n\n // Heights: one scale for every column, so values compare across them.\n const byColumn: Node[][] = Array.from({ length: columns }, () => [])\n for (const n of nodes) byColumn[n.column]?.push(n)\n const pad = byColumn.reduce(\n (min, col) => (col.length > 1 ? Math.min(min, plot.height / 2 / (col.length - 1)) : min),\n nodePadding,\n )\n let k = Number.POSITIVE_INFINITY\n for (const col of byColumn) {\n const sum = col.reduce((s, n) => s + n.value, 0)\n if (sum > 0) k = Math.min(k, (plot.height - (col.length - 1) * pad) / sum)\n }\n if (!Number.isFinite(k) || k < 0) k = 0\n byColumn.forEach((col, c) => {\n const total = col.reduce((s, n) => s + n.value * k, 0) + (col.length - 1) * pad\n let y = plot.y + (plot.height - total) / 2\n for (const n of col) {\n n.x = plot.x + (columns > 1 ? c * step : (plot.width - nodeWidth) / 2)\n n.y = y\n n.height = n.value * k\n y += n.height + pad\n }\n })\n // Slices: flows leave and enter in the order of the node at the other end.\n for (const n of nodes) {\n let y = n.y\n for (const link of [...n.outs].sort((a, b) => a.target.y - b.target.y)) {\n link.sy = y\n link.width = link.data.value * k\n y += link.width\n }\n y = n.y\n for (const link of [...n.ins].sort((a, b) => a.source.y - b.source.y)) {\n link.ty = y\n y += link.data.value * k\n }\n }\n\n const labels = nodes.map((n, i): NodeLabel => {\n const [name, value] = texts[i] as readonly [string, string]\n const side: 'left' | 'right' = n.column === 0 && columns > 1 ? 'left' : 'right'\n const room =\n side === 'left' ? left : n.column === columns - 1 ? right : step - nodeWidth - LABEL_GAP * 2\n // Crowded columns keep only the names: the value line would run into the next label.\n const col = byColumn[n.column] as Node[]\n const at = col.indexOf(n)\n const neighbours = [col[at - 1], col[at + 1]].filter((o): o is Node => !!o)\n const spacing = neighbours.reduce(\n (min, o) => Math.min(min, (n.height + o.height) / 2 + pad),\n Number.POSITIVE_INFINITY,\n )\n const showValue = spacing >= fontSize * (1 + LINE_HEIGHT)\n return {\n side,\n name: truncate(name, room, fontSize),\n value: showValue ? truncate(value, room, fontSize) : '',\n }\n })\n return { nodes, links, plot, nodeWidth, labels }\n}\n\n/** Path of a link: two cubic Béziers between the slices at its ends. */\nfunction linkPath(link: Link, nodeWidth: number): string {\n const x0 = link.source.x + nodeWidth\n const x1 = link.target.x\n const xm = (x0 + x1) / 2\n const { sy, ty, width } = link\n const p = (...v: number[]) => v.map(round).join(',')\n return `M${p(x0, sy)}C${p(xm, sy, xm, ty, x1, ty)}L${p(x1, ty + width)}C${p(xm, ty + width, xm, sy + width, x0, sy + width)}Z`\n}\n\n/** A point on a cubic Bézier with control points `a`, `b`, `c`, `d`. */\nconst cubic = (a: number, b: number, c: number, d: number, t: number): number => {\n const u = 1 - t\n return u * u * u * a + 3 * u * u * t * b + 3 * u * t * t * c + t * t * t * d\n}\n\n/** Whether `(px, py)` lies inside the ribbon of `link`. */\nfunction inLink(link: Link, nodeWidth: number, px: number, py: number): boolean {\n const x0 = link.source.x + nodeWidth\n const x1 = link.target.x\n if (px < Math.min(x0, x1) || px > Math.max(x0, x1) || x0 === x1) return false\n const xm = (x0 + x1) / 2\n // x(t) is monotone, so bisection finds the t under the pointer.\n let lo = 0\n let hi = 1\n for (let i = 0; i < 20; i++) {\n const mid = (lo + hi) / 2\n if (cubic(x0, xm, xm, x1, mid) < px === x1 > x0) lo = mid\n else hi = mid\n }\n const top = cubic(link.sy, link.sy, link.ty, link.ty, (lo + hi) / 2)\n return py >= top && py <= top + link.width\n}\n\nfunction renderSankey(options: SankeyOptions, ctx: RenderContext): ChildInput {\n const { nodes, links, plot, nodeWidth, labels } = layout(options, ctx)\n const drawn = links.filter((link) => link.data.value > 0)\n const formatValue = formatDetail(options.format, ctx.locale)\n\n const nodeMark = (n: Node) => ({\n d: `M0,0h${round(nodeWidth)}v${round(n.height)}h${round(-nodeWidth)}Z`,\n x: n.x,\n y: n.y,\n })\n const linkItem = (link: Link): HitItem => ({\n name: `${link.source.data.name} → ${link.target.data.name}`,\n seriesIndex: link.index,\n color: colorOf(link.source),\n value: link.data.value,\n text: formatValue(link.data.value),\n x: (link.source.x + nodeWidth + link.target.x) / 2,\n y: cubic(link.sy, link.sy, link.ty, link.ty, 0.5) + link.width / 2,\n })\n const hitNode = (n: Node, linkIndex?: number): Hit => {\n const own: HitItem = {\n name: n.data.name,\n seriesIndex: links.length + n.index,\n color: colorOf(n),\n value: n.value,\n text: formatValue(n.value),\n x: n.x + nodeWidth / 2,\n y: n.y + n.height / 2,\n }\n const flows = [...n.ins, ...n.outs].map(linkItem)\n const focused = flows.find((item) => item.seriesIndex === linkIndex)\n const link = focused && drawn.find((l) => l.index === linkIndex)\n return {\n index: n.index,\n label: n.data.name,\n title: '',\n x: own.x,\n area: plot,\n items: [own, ...flows],\n seriesIndex: focused ? linkIndex : own.seriesIndex,\n mark: link ? { d: linkPath(link, nodeWidth), x: 0, y: 0 } : nodeMark(n),\n }\n }\n const hitLink = (link: Link): Hit => {\n const item = linkItem(link)\n return {\n index: link.source.index,\n label: link.source.data.name,\n title: '',\n x: item.x,\n area: plot,\n items: [item],\n seriesIndex: link.index,\n mark: { d: linkPath(link, nodeWidth), x: 0, y: 0 },\n }\n }\n\n const interaction: Interaction = {\n count: nodes.length,\n hitTest(px, py) {\n const n = nodes.find(\n (n) =>\n px >= n.x - HOVER_SLOP &&\n px <= n.x + nodeWidth + HOVER_SLOP &&\n py >= n.y - HOVER_SLOP &&\n py <= n.y + n.height + HOVER_SLOP,\n )\n if (n) return hitNode(n)\n const link = drawn.find((l) => inLink(l, nodeWidth, px, py))\n return link ? hitLink(link) : null\n },\n hitIndex(index, seriesIndex) {\n const n = nodes[index]\n return n ? hitNode(n, seriesIndex) : null\n },\n }\n ctx.onHitTest(interaction)\n\n return [\n h(\n 'g',\n { key: 'links', class: 'tc-sankey-links' },\n drawn.map((link) =>\n h('path', {\n key: `${link.source.data.name}→${link.target.data.name}#${link.index}`,\n class: ['tc-series', `tc-series-${link.source.slot}`, 'tc-sankey-link'],\n style: { '--tc-series-color': link.source.data.color },\n d: linkPath(link, nodeWidth),\n }),\n ),\n ),\n h(\n 'g',\n { key: 'nodes', class: 'tc-sankey-nodes' },\n nodes.map((n) =>\n h(\n 'g',\n {\n key: n.data.name,\n class: ['tc-series', `tc-series-${n.slot}`],\n 'data-series': n.data.name,\n style: { '--tc-series-color': n.data.color },\n },\n h('rect', {\n class: 'tc-sankey-node',\n x: round(n.x),\n y: round(n.y),\n width: round(nodeWidth),\n height: round(n.height),\n }),\n ),\n ),\n ),\n h(\n 'g',\n { key: 'labels', class: 'tc-sankey-labels', 'aria-hidden': 'true' },\n nodes.map((n, i) => {\n const label = labels[i] as NodeLabel\n if (!label.name && !label.value) return null\n const x = round(label.side === 'left' ? n.x - LABEL_GAP : n.x + nodeWidth + LABEL_GAP)\n const y = round(n.y + n.height / 2)\n const anchor = label.side === 'left' ? 'end' : 'start'\n return h(\n 'g',\n { key: n.data.name, class: 'tc-sankey-label' },\n h(\n 'text',\n {\n class: 'tc-value-label tc-sankey-name',\n x,\n y,\n dy: label.value ? '-0.25em' : '0.35em',\n 'text-anchor': anchor,\n },\n label.name,\n ),\n label.value &&\n h(\n 'text',\n {\n class: 'tc-tick-label tc-sankey-value',\n x,\n y,\n dy: '0.95em',\n 'text-anchor': anchor,\n },\n label.value,\n ),\n )\n }),\n ),\n ]\n}\n\n/** One legend entry per custom color, named after the first node wearing it. */\nfunction sankeyLegend(options: SankeyOptions): LegendItem[] {\n const seen = new Map<string, LegendItem>()\n for (const n of options.data.nodes ?? []) {\n if (n.color && !seen.has(n.color)) {\n const item: LegendItem = { key: n.name, name: n.name, index: seen.size, color: n.color }\n if (n.hidden) item.hidden = true\n seen.set(n.color, item)\n }\n }\n return [...seen.values()]\n}\n\nfunction sankeyTable(options: SankeyOptions, ctx: RenderContext): DataTable {\n const { links } = graph(options.data, ctx.hidden, true)\n const value = formatDetail(options.format, ctx.locale)\n return {\n columns: ['From', 'To', 'Value'],\n rows: links.map((link) => [link.data.from, link.data.to, value(link.data.value)]),\n }\n}\n\n/** Nodes and links from users, APIs and JSON, in the shape the layout expects. */\nconst cleanSankey = (data: unknown): unknown => {\n const d = isRecord(data) ? data : {}\n return {\n ...d,\n nodes: Array.isArray(d.nodes) ? records(d.nodes, (r) => named(r)) : undefined,\n links: records(d.links, (r) => ({\n from: text(r.from),\n to: text(r.to),\n value: Math.max(0, finite(r.value) ?? 0),\n })),\n }\n}\n\n/**\n * Sankey diagram: flows between nodes, as ribbons whose width is their\n * value. Nodes are made from the links (or declared, to set their order and\n * colors) and placed in columns by the longest path from a source.\n *\n * ```ts\n * new Chart('#el', {\n * type: sankey,\n * data: {\n * links: [\n * { from: 'Wages', to: 'Income', value: 60 },\n * { from: 'Dividends', to: 'Income', value: 15 },\n * { from: 'Income', to: 'Rent', value: 30 },\n * { from: 'Income', to: 'Savings', value: 45 },\n * ],\n * },\n * })\n * ```\n */\nexport const sankey: ChartType<SankeyOptions> = {\n name: 'sankey',\n clean: cleanData(cleanSankey),\n render: renderSankey,\n legend: sankeyLegend,\n table: sankeyTable,\n}\n","/** SVG path of a circle of radius `r` around the origin (a path, so it can be a hover mark). */\nexport const circlePath = (r: number): string =>\n `M${r},0A${r},${r},0,1,1,${-r},0A${r},${r},0,1,1,${r},0Z`\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext } from '../chart.ts'\nimport { axis, axisSize, type Tick, thinTicks } from '../components/axis.ts'\nimport { grid } from '../components/grid.ts'\nimport { formatDetail, formatNumber } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n round,\n} from '../layout.ts'\nimport { extent } from '../scales/extent.ts'\nimport type { LinearScale } from '../scales/linear.ts'\nimport { circlePath } from '../shapes/circle.ts'\nimport { type ClassValue, h } from '../vnode.ts'\nimport {\n domainOf,\n markerShape,\n plotClip,\n plottable,\n tickCount,\n type ValueAxisOptions,\n valueScale,\n valueTicks,\n} from './cartesian.ts'\nimport { cleanData, finite, isRecord, named, records, text } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** A point of a scatter or bubble chart. */\nexport interface ScatterPoint {\n x: number\n y: number\n /** Bubble size; the circle area is proportional to it. */\n size?: number\n /** Name shown in the tooltip and table (e.g. a country). */\n label?: string\n}\n\nexport interface ScatterSeries {\n name: string\n points: readonly ScatterPoint[]\n /** Stable identity for keyed updates and legend toggles. Defaults to `name`. */\n id?: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the series group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface ScatterOptions {\n data: { series: readonly ScatterSeries[] }\n /** Horizontal value axis. */\n x?: ValueAxisOptions\n /** Vertical value axis. */\n y?: ValueAxisOptions\n /** Radius of points without a size, in pixels. Defaults to `4`. */\n radius?: number\n /** Radius range for bubbles (points with `size`). Defaults to `{ min: 4, max: 24 }`. */\n size?: { min?: number; max?: number }\n /** Extra space around the plot area, in pixels. */\n padding?: InsetsInput\n}\n\n/** Pointer distance (in pixels, beyond the radius) that still hits a point. */\nconst HIT_RADIUS = 24\nconst EDGE = 8\n\ninterface Placed {\n seriesIndex: number\n pointIndex: number\n point: ScatterPoint\n cx: number\n cy: number\n r: number\n}\n\n/** A point's bubble size, or `undefined` when it has none (or an invalid one). */\nconst sizeOf = (p: ScatterPoint): number | undefined =>\n p.size != null && Number.isFinite(p.size) && p.size > 0 ? p.size : undefined\n\nfunction renderScatter(options: ScatterOptions, ctx: RenderContext) {\n const { width, height, fontSize, locale } = ctx\n const xOptions = options.x ?? {}\n const yOptions = options.y ?? {}\n const radius = options.radius ?? 4\n const visible = options.data.series.filter((s) => !ctx.hidden.has(keyOf(s)))\n const points = visible.flatMap((s) => s.points)\n const sizes = points.map(sizeOf).filter((v): v is number => v !== undefined)\n const maxSize = extent(sizes)?.[1] ?? 0\n const rMin = options.size?.min ?? 4\n const rMax = options.size?.max ?? 24\n // Area-proportional bubbles: the radius grows with the square root of the size.\n const bubble = (size: number | undefined) =>\n size != null && size > 0 && maxSize > 0\n ? rMin + (rMax - rMin) * Math.sqrt(size / maxSize)\n : radius\n const overhang = Math.max(radius, sizes.length ? rMax : 0) + 2\n\n const countY = tickCount(yOptions, Math.max(2, Math.round(height / 60)))\n const countX = tickCount(xOptions, Math.max(2, Math.round(width / 80)))\n // Only points that can be plotted on both axes take part.\n const usable = (p: ScatterPoint) => plottable(p.x, xOptions) && plottable(p.y, yOptions)\n const shown = points.filter(usable)\n const xDomain = domainOf(\n shown.map((p) => p.x),\n xOptions,\n false,\n countX,\n )\n const yDomain = domainOf(\n shown.map((p) => p.y),\n yOptions,\n false,\n countY,\n )\n\n const showX = xOptions.show !== false\n const showY = yOptions.show !== false\n // Linear or logarithmic, as each axis asks (see valueScale).\n const ticksOf = (scale: LinearScale, axis: ValueAxisOptions, count: number) =>\n valueTicks(scale, axis, count, axis.format, locale)\n const probeY = ticksOf(valueScale(yDomain, [1, 0], yOptions), yOptions, countY)\n const probeX = ticksOf(valueScale(xDomain, [0, 1], xOptions), xOptions, countX)\n const half = (tick: Tick | undefined) =>\n showX && tick ? Math.ceil(estimateTextWidth(tick.label, fontSize) / 2) : 0\n const pad = insets(options.padding)\n const margins = {\n top:\n pad.top + Math.max(showY ? Math.ceil((fontSize * LINE_HEIGHT) / 2) : 0, overhang, EDGE / 2),\n right: pad.right + Math.max(half(probeX[probeX.length - 1]), overhang, EDGE),\n bottom:\n pad.bottom + Math.max(showX ? axisSize('bottom', probeX, fontSize) : 0, overhang, EDGE / 2),\n left:\n pad.left +\n Math.max(showY ? axisSize('left', probeY, fontSize) : 0, half(probeX[0]), overhang),\n }\n const area = innerRect(width, height, margins)\n const x = valueScale(xDomain, [area.x, area.x + area.width], xOptions)\n const y = valueScale(yDomain, [area.y + area.height, area.y], yOptions)\n // Thinned like the ticks of the other charts: on a log axis they crowd at the end of each decade.\n const xTicks = thinTicks(ticksOf(x, xOptions, countX), 'bottom', fontSize)\n const yTicks = thinTicks(ticksOf(y, yOptions, countY), 'left', fontSize, 4)\n\n // Every visible point in pixels, sorted by x for fast nearest-point lookups.\n const placed: Placed[] = []\n options.data.series.forEach((series, seriesIndex) => {\n if (ctx.hidden.has(keyOf(series))) return\n series.points.forEach((point, pointIndex) => {\n if (!usable(point)) return\n placed.push({\n seriesIndex,\n pointIndex,\n point,\n cx: x(point.x),\n cy: y(point.y),\n r: bubble(sizeOf(point)),\n })\n })\n })\n placed.sort((a, b) => a.cx - b.cx)\n\n const fx = formatDetail(xOptions.format, locale)\n const fy = formatDetail(yOptions.format, locale)\n const fs = formatNumber(undefined, locale)\n const hitFor = (p: Placed, index: number): Hit => {\n const series = options.data.series[p.seriesIndex] as ScatterSeries\n const sz = sizeOf(p.point)\n const size = sz === undefined ? '' : ` · ${fs(sz)}`\n const item: HitItem = {\n name: series.name,\n seriesIndex: p.seriesIndex,\n value: p.point.y,\n text: `${fx(p.point.x)}, ${fy(p.point.y)}${size}`,\n x: p.cx,\n y: p.cy,\n }\n if (series.color) item.color = series.color\n return {\n index,\n label: p.point.label ?? series.name,\n title: p.point.label ?? '',\n x: p.cx,\n area,\n items: [item],\n seriesIndex: p.seriesIndex,\n mark: { d: circlePath(round(p.r + 4)), x: p.cx, y: p.cy },\n }\n }\n\n const interaction: Interaction = {\n count: placed.length,\n hitIndex: (index) => {\n const p = placed[index]\n return p ? hitFor(p, index) : null\n },\n hitTest(px, py) {\n // Binary search the first point within reach on x, then scan the window.\n let lo = 0\n let hi = placed.length\n const reach = HIT_RADIUS + rMax\n while (lo < hi) {\n const mid = (lo + hi) >> 1\n if ((placed[mid] as Placed).cx < px - reach) lo = mid + 1\n else hi = mid\n }\n let best = -1\n let bestDistance = Number.POSITIVE_INFINITY\n for (let i = lo; i < placed.length; i++) {\n const p = placed[i] as Placed\n if (p.cx > px + reach) break\n const distance = Math.hypot(p.cx - px, p.cy - py) - p.r\n if (distance < bestDistance && distance <= HIT_RADIUS) {\n best = i\n bestDistance = distance\n }\n }\n return best === -1 ? null : hitFor(placed[best] as Placed, best)\n },\n }\n ctx.onHitTest(interaction)\n\n /** One path drawing a dot of `radius` at every point (two arcs each, or the series' shape). */\n const shape = markerShape(options)\n const dotsPath = (dots: readonly ScatterPoint[], slot: number) => {\n if (!dots.length) return null\n const r = round(radius)\n let d = ''\n for (const p of dots) {\n d += shape\n ? shape(slot, x(p.x), y(p.y), r)\n : `M${round(x(p.x) - radius)},${round(y(p.y))}a${r},${r},0,1,0,${2 * r},0a${r},${r},0,1,0,${-2 * r},0`\n }\n return h('path', { key: 'dots', class: ['tc-point tc-dots', shape && 'tc-marker'], d })\n }\n\n const background = []\n if (yOptions.grid !== false) background.push(grid({ direction: 'y', ticks: yTicks, area }))\n if (xOptions.grid) background.push(grid({ direction: 'x', ticks: xTicks, area }))\n\n // Dots may reach a little past the plot edges; bubbles are cut at them (like\n // Chart.js), as a big one there would cover the axis labels.\n const clip = plotClip(ctx, area, sizes.length ? 0 : overhang)\n const groups = options.data.series.map(\n (series, seriesIndex) =>\n !ctx.hidden.has(keyOf(series)) &&\n h(\n 'g',\n groupAttrs(series, seriesIndex),\n // Plain points share one path per series: thousands of circles would\n // each cost the browser style and layout work. The path keeps its\n // commands while the point count does, so new data morphs. Bubbles\n // stay circles: each is see-through over the others.\n dotsPath(\n series.points.filter((p) => usable(p) && sizeOf(p) === undefined),\n seriesIndex,\n ),\n series.points.map(\n (point, i) =>\n usable(point) &&\n sizeOf(point) !== undefined &&\n h('circle', {\n key: i,\n class: 'tc-point tc-bubble',\n cx: round(x(point.x)),\n cy: round(y(point.y)),\n r: round(bubble(sizeOf(point))),\n }),\n ),\n ),\n )\n\n return [\n h('defs', null, clip.def),\n background,\n h('g', { key: 'series', class: 'tc-series-list', 'clip-path': clip.url }, groups),\n showY && axis({ position: 'left', ticks: yTicks, area }),\n showX && axis({ position: 'bottom', ticks: xTicks, area }),\n ]\n}\n\nfunction scatterTable(\n options: ScatterOptions,\n ctx: RenderContext,\n limit: number = Number.POSITIVE_INFINITY,\n): DataTable {\n const fx = formatDetail(options.x?.format, ctx.locale)\n const fy = formatDetail(options.y?.format, ctx.locale)\n const fs = formatNumber(undefined, ctx.locale)\n const series = options.data.series.filter((s) => !ctx.hidden.has(keyOf(s)))\n const withSize = series.some((s) => s.points.some((p) => p.size != null))\n const withLabel = series.some((s) => s.points.some((p) => p.label != null))\n const total = series.reduce((sum, s) => sum + s.points.length, 0)\n let left = limit\n return {\n columns: ['', ...(withLabel ? ['Label'] : []), 'x', 'y', ...(withSize ? ['Size'] : [])],\n total,\n rows: series.flatMap((s) => {\n const take = s.points.slice(0, Math.max(0, left))\n left -= take.length\n return take.map((p) => [\n s.name,\n ...(withLabel ? [p.label ?? ''] : []),\n fx(p.x),\n fy(p.y),\n ...(withSize ? [sizeOf(p) === undefined ? '–' : fs(sizeOf(p) as number)] : []),\n ])\n }),\n }\n}\n\n/**\n * Scatter chart: points on two value axes; give points a `size` for a\n * bubble chart (area-proportional radii).\n *\n * ```ts\n * new Chart('#el', {\n * type: scatter,\n * data: { series: [{ name: 'Cities', points: [{ x: 12, y: 3.4 }, { x: 18, y: 5.1 }] }] },\n * })\n * ```\n */\nexport const scatter: ChartType<ScatterOptions> = {\n name: 'scatter',\n clean: cleanData((data) => ({\n ...(isRecord(data) ? data : {}),\n series: records(isRecord(data) && data.series, (s) => ({\n ...named(s),\n points: records(s.points, (p) => ({\n ...p,\n x: finite(p.x),\n y: finite(p.y),\n size: finite(p.size) ?? undefined,\n label: p.label == null ? undefined : text(p.label),\n })).filter((p) => p.x !== null && p.y !== null),\n })),\n })),\n render: renderScatter,\n legend: (options) => legendItems(options.data.series),\n table: scatterTable,\n valueLabels: { format: (options) => options.y?.format },\n}\n","import type { ChartType, RenderContext } from '../chart.ts'\nimport { fadeMask } from '../components/fade.ts'\nimport { formatNumber, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { type InsetsInput, innerRect, insets, round } from '../layout.ts'\nimport { linear } from '../scales/linear.ts'\nimport { barPath } from '../shapes/bar.ts'\nimport { circlePath } from '../shapes/circle.ts'\nimport { areaPath, type Curve, linePath, type Point } from '../shapes/path.ts'\nimport { h } from '../vnode.ts'\nimport { domainOf, type Label, labelKey } from './cartesian.ts'\nimport { cleanData, label, numbers } from './clean.ts'\n\nexport interface SparklineOptions {\n /** The values; `null` leaves a gap. */\n data: readonly (number | null | undefined)[]\n /** Labels for the tooltip, one per value (e.g. dates). */\n labels?: readonly Label[]\n /** Name shown in the tooltip. Defaults to `'Value'`. */\n name?: string\n /**\n * `'line'` (default), `'area'`, `'bar'`, or `'tristate'`: only the sign\n * counts, as a full bar up (win), down (loss) or a tick on the middle (draw).\n */\n variant?: 'line' | 'area' | 'bar' | 'tristate'\n /** Interpolation for lines and areas. Defaults to `'monotone'`. */\n curve?: Curve\n /** Dot on the last value. Defaults to `'last'`. */\n point?: 'last' | 'none'\n /** Mark the minimum and maximum values. */\n markers?: 'minmax' | 'none'\n /** Dot radius in pixels. Defaults to `3`. */\n pointRadius?: number\n /** Include zero in the value range. Defaults to `true` for areas and bars, `false` for lines. */\n zero?: boolean\n /** Format of values in the tooltip. */\n format?: NumberFormat\n /** Extra space around the plot, in pixels. */\n padding?: InsetsInput\n}\n\nfunction renderSparkline(options: SparklineOptions, ctx: RenderContext) {\n const {\n variant = 'line',\n curve = 'monotone',\n point = 'last',\n markers = 'none',\n pointRadius = 3,\n name = 'Value',\n } = options\n const values = options.data.map((v) => (v == null || !Number.isFinite(v) ? null : v))\n // (No log option on sparklines, so finite is all that matters here.)\n const count = values.length\n const dots = point === 'last' || markers === 'minmax'\n // Room for the stroke and dots so nothing is clipped at the edges.\n const overhang = dots ? pointRadius + 2 : 2\n const pad = insets(options.padding, 0)\n const area = innerRect(ctx.width, ctx.height, {\n top: pad.top + overhang,\n right: pad.right + overhang,\n bottom: pad.bottom + overhang,\n left: pad.left + overhang,\n })\n const tristate = variant === 'tristate'\n const zero = options.zero ?? variant !== 'line'\n // Tristate bars span half the height each way, whatever the magnitude.\n const domain: [number, number] = tristate ? [-1, 1] : domainOf(values, { nice: false }, zero, 2)\n\n const bars = variant === 'bar' || tristate\n const gap = 1\n const slot = count > 0 ? area.width / count : 0\n const xAt = (i: number) =>\n bars\n ? area.x + slot * i + slot / 2\n : area.x + (count > 1 ? (area.width * i) / (count - 1) : area.width / 2)\n const y = linear(domain, [area.y + area.height, area.y])\n const baseline = y(Math.min(Math.max(0, domain[0]), domain[1]))\n const points: Point[] = values.map((v, i) => (v === null ? null : [xAt(i), y(v)]))\n\n const format = formatNumber(options.format, ctx.locale)\n const labelOf = (i: number) => {\n const label = options.labels?.[i]\n return label === undefined ? '' : String(label)\n }\n // Where a value is drawn: a tristate bar ends at its sign, not its magnitude.\n const yOf = (v: number) => y(tristate ? Math.sign(v) : v)\n const hitFor = (i: number): Hit | null => {\n const value = values[i]\n if (value === undefined) return null\n const px = xAt(i)\n const item: HitItem = {\n name,\n seriesIndex: 0,\n value,\n text: value === null ? '–' : format(value),\n x: px,\n y: value === null ? null : yOf(value),\n }\n const hit: Hit = {\n index: i,\n label: labelKey(options.labels?.[i] ?? i + 1),\n title: labelOf(i),\n x: px,\n area,\n items: [item],\n }\n if (value !== null) hit.mark = { d: circlePath(pointRadius + 3), x: px, y: yOf(value) }\n return hit\n }\n const interaction: Interaction = {\n count,\n hitIndex: (i) => hitFor(i),\n hitTest(px, py) {\n if (count === 0 || py < area.y - overhang || py > area.y + area.height + overhang) return null\n const i = bars\n ? Math.floor((px - area.x) / slot)\n : Math.round(((px - area.x) / Math.max(1, area.width)) * (count - 1))\n return hitFor(Math.max(0, Math.min(count - 1, i)))\n },\n }\n ctx.onHitTest(interaction)\n\n const marks = []\n if (tristate) {\n const width = Math.max(1, slot - gap)\n marks.push(\n h('line', {\n class: 'tc-sparkline-zero',\n x1: area.x,\n x2: area.x + area.width,\n y1: round(baseline),\n y2: round(baseline),\n }),\n )\n values.forEach((v, i) => {\n if (v === null) return\n const sign = Math.sign(v)\n // A draw is a short tick centered on the middle line.\n const tick = Math.min(2, area.height / 2)\n const [from, to] =\n sign === 0 ? [baseline + tick / 2, baseline - tick / 2] : [baseline, y(sign)]\n marks.push(\n h('path', {\n key: i,\n class: [\n 'tc-bar',\n sign < 0 && 'tc-bar-negative',\n sign < 0 ? 'tc-tristate-loss' : sign > 0 ? 'tc-tristate-win' : 'tc-tristate-draw',\n ],\n d: barPath(xAt(i) - width / 2, width, from, to, sign === 0 ? 0 : Math.min(2, width / 2)),\n }),\n )\n })\n } else if (bars) {\n const width = Math.max(1, slot - gap)\n values.forEach((v, i) => {\n if (v === null) return\n marks.push(\n h('path', {\n key: i,\n class: ['tc-bar', v < 0 && 'tc-bar-negative'],\n d: barPath(xAt(i) - width / 2, width, baseline, y(v), Math.min(2, width / 2)),\n }),\n )\n })\n } else {\n if (variant === 'area') {\n marks.push(\n h('path', {\n class: 'tc-area tc-area-gradient',\n d: areaPath(points, baseline, { curve }),\n mask: `url(#${ctx.id}-fade)`,\n }),\n )\n }\n marks.push(h('path', { class: 'tc-line', d: linePath(points, { curve }) }))\n }\n\n const dotAt = (i: number, cls: string) => {\n const v = values[i]\n return v == null\n ? null\n : h('circle', {\n key: `${cls}-${i}`,\n class: ['tc-point', cls],\n cx: round(xAt(i)),\n cy: round(y(v)),\n r: pointRadius,\n })\n }\n const extremes = []\n if (markers === 'minmax') {\n let min = -1\n let max = -1\n values.forEach((v, i) => {\n if (v === null) return\n if (min === -1 || v < (values[min] as number)) min = i\n if (max === -1 || v > (values[max] as number)) max = i\n })\n if (min !== -1) extremes.push(dotAt(min, 'tc-point-min'))\n if (max !== -1 && max !== min) extremes.push(dotAt(max, 'tc-point-max'))\n }\n let last = -1\n if (point === 'last') {\n for (let i = count - 1; i >= 0; i--) {\n if (values[i] !== null) {\n last = i\n break\n }\n }\n }\n\n return [\n variant === 'area' && h('defs', null, fadeMask(`${ctx.id}-fade`)),\n h(\n 'g',\n { class: 'tc-series tc-series-1 tc-sparkline' },\n marks,\n extremes,\n last !== -1 && !bars && dotAt(last, 'tc-point-last'),\n ),\n ]\n}\n\n/**\n * Sparkline: a tiny line, area or bar chart without axes, for stat tiles.\n *\n * ```ts\n * new Chart('#el', { type: sparkline, data: [3, 5, 4, 7, 6], height: 40 })\n * ```\n */\nexport const sparkline: ChartType<SparklineOptions> = {\n name: 'sparkline',\n // The labels too: they come from outside like the values.\n clean: (options) => ({\n ...cleanData(numbers)(options),\n labels: Array.isArray(options.labels) ? options.labels.map(label) : undefined,\n }),\n render: renderSparkline,\n // Decorative by default: opt in with `keyboard: true`.\n keyboard: false,\n}\n","import type { ChartType } from './chart.ts'\nimport { area } from './charts/area.ts'\nimport { bar } from './charts/bar.ts'\nimport { candlestick } from './charts/candlestick.ts'\nimport { gauge } from './charts/gauge.ts'\nimport { heatmap } from './charts/heatmap.ts'\nimport { line } from './charts/line.ts'\nimport { donut, pie } from './charts/pie.ts'\nimport { radar } from './charts/radar.ts'\nimport { sankey } from './charts/sankey.ts'\nimport { scatter } from './charts/scatter.ts'\nimport { sparkline } from './charts/sparkline.ts'\n\n/**\n * Every built-in chart type by its name, for charts declared in markup\n * (`<tabler-chart type=\"line\">`, `data-tc-chart=\"line\"`). Importing it\n * brings every type along: code that knows its types imports them directly.\n */\nexport const types: Readonly<Record<string, ChartType<never>>> = {\n line,\n area,\n bar,\n pie,\n donut,\n scatter,\n sparkline,\n gauge,\n heatmap,\n candlestick,\n radar,\n sankey,\n} as Record<string, ChartType<never>>\n","","import { version } from '../package.json'\n\n/** Version of the `@tabler/charts` package. */\nexport const VERSION: string = version\n\nexport type { DataTable } from './a11y.ts'\nexport { describeHit, tableContent } from './a11y.ts'\nexport type {\n BaseOptions,\n ChartConfig,\n ChartEvents,\n ChartType,\n RenderContext,\n ResolvedLegend,\n Size,\n} from './chart.ts'\nexport {\n buildChart,\n Chart,\n chartEvents,\n chartLabel,\n chartToString,\n renderContext,\n resolveLegend,\n resolveSize,\n} from './chart.ts'\nexport type { Annotation } from './charts/annotations.ts'\nexport type { AreaOptions } from './charts/area.ts'\nexport { area } from './charts/area.ts'\nexport type { BarOptions } from './charts/bar.ts'\nexport { bar } from './charts/bar.ts'\nexport type { Candle, CandlestickOptions } from './charts/candlestick.ts'\nexport { candlestick } from './charts/candlestick.ts'\nexport type {\n CartesianData,\n CartesianOptions,\n CategoryAxisOptions,\n Label,\n Series,\n ValueAxisOptions,\n} from './charts/cartesian.ts'\nexport {\n categoryInteraction,\n domainOf,\n seriesKey,\n seriesLegend,\n seriesTable,\n} from './charts/cartesian.ts'\nexport type { GaugeOptions, GaugeRing } from './charts/gauge.ts'\nexport { gauge } from './charts/gauge.ts'\nexport type { HeatmapOptions, HeatmapRange } from './charts/heatmap.ts'\nexport { heatmap } from './charts/heatmap.ts'\nexport type { LineOptions } from './charts/line.ts'\nexport { line } from './charts/line.ts'\nexport type { PieOptions, PieSlice } from './charts/pie.ts'\nexport { donut, pie } from './charts/pie.ts'\nexport type { RadarOptions, RadialAxisOptions } from './charts/radar.ts'\nexport { radar } from './charts/radar.ts'\nexport type { SankeyData, SankeyLink, SankeyNode, SankeyOptions } from './charts/sankey.ts'\nexport { sankey } from './charts/sankey.ts'\nexport type { ScatterOptions, ScatterPoint, ScatterSeries } from './charts/scatter.ts'\nexport { scatter } from './charts/scatter.ts'\nexport type { SparklineOptions } from './charts/sparkline.ts'\nexport { sparkline } from './charts/sparkline.ts'\nexport type { AxisOptions, AxisPosition, LinearTicksOptions, Tick } from './components/axis.ts'\nexport { axis, axisSize, bandTicks, linearTicks, thinTicks } from './components/axis.ts'\nexport type { GridOptions } from './components/grid.ts'\nexport { grid } from './components/grid.ts'\nexport { hoverOverlay, hoverUnderlay } from './components/hover.ts'\nexport type { Features } from './features.ts'\nexport { feature, features, register } from './features.ts'\nexport type { DateFormat, Locale, NumberFormat, NumberFormatOptions } from './format.ts'\nexport {\n formatDate,\n formatDetail,\n formatNumber,\n formatTicks,\n getDateFormat,\n getNumberFormat,\n stepPrecision,\n} from './format.ts'\nexport type { Hit, HitItem, HitTester, Interaction } from './interaction.ts'\nexport type { Insets, InsetsInput, Rect } from './layout.ts'\nexport { estimateTextWidth, innerRect, insets, LINE_HEIGHT } from './layout.ts'\nexport type { LegendItem, LegendOptions } from './legend.ts'\nexport { defaultHidden, legendContent } from './legend.ts'\nexport type {\n AfterRenderState,\n BeforeRenderState,\n ChartPlugin,\n PluginInstance,\n} from './plugin.ts'\nexport type { DownloadFormat, DownloadMenuOptions, DownloadOption } from './plugins/download.ts'\nexport {\n dataTable,\n defaultPlugins,\n download,\n highlight,\n keyboard,\n legend,\n pointer,\n sync,\n tooltip,\n} from './plugins/index.ts'\nexport { render } from './render/dom.ts'\nexport type { RenderToStringOptions } from './render/string.ts'\nexport { escapeAttr, escapeText, renderToString } from './render/string.ts'\nexport type { BandKey, BandScale, BandScaleOptions } from './scales/band.ts'\nexport { band, point } from './scales/band.ts'\nexport { extent } from './scales/extent.ts'\nexport type { LinearScale, LinearScaleOptions } from './scales/linear.ts'\nexport { linear } from './scales/linear.ts'\nexport { niceDomain, tickIncrement, tickStep, ticks } from './scales/ticks.ts'\nexport { cancel, flush, schedule } from './scheduler.ts'\nexport type { ArcOptions } from './shapes/arc.ts'\nexport { arcCentroid, arcPathStable, padAngleForGap } from './shapes/arc.ts'\nexport { barPath, hbarPath } from './shapes/bar.ts'\nexport type { Curve, PathOptions, Point } from './shapes/path.ts'\nexport { areaPath, linePath } from './shapes/path.ts'\nexport type { TooltipOptions, TooltipPlacement } from './tooltip.ts'\nexport { hitAnchor, placeTooltip, tooltipContent } from './tooltip.ts'\nexport type {\n Attrs,\n AttrValue,\n Child,\n ChildInput,\n ClassValue,\n Key,\n Props,\n StyleValue,\n VNode,\n} from './vnode.ts'\nexport { h, normalizeClass, normalizeStyle } from './vnode.ts'\n","/**\n * `@tabler/charts`: everything from `@tabler/charts/core`, with a `Chart`\n * that installs the built-in plugins (tooltip, legend, keyboard, …) and\n * every optional feature registered (time and log axes, decimation,\n * annotations, pattern fills, value labels, point shapes). The one exception\n * is the `download` menu's saver: `import '@tabler/charts/export'` adds it,\n * so charts that never offer a download do not carry the export code.\n */\n\nimport { annotationLayers, annotationValues } from './charts/annotations.ts'\nimport { dateLabels } from './charts/dates.ts'\nimport { logDomain, logTicks } from './charts/log-axis.ts'\nimport { patternFills } from './charts/patterns.ts'\nimport { markerPath, shapesStep } from './charts/point-shapes.ts'\nimport { timeAxis } from './charts/time-axis.ts'\nimport { labelsStep } from './charts/value-labels.ts'\nimport { addPost, register } from './features.ts'\nimport { hydrate } from './render/hydrate.ts'\nimport { morph } from './render/morph.ts'\nimport { log } from './scales/log.ts'\nimport { time, timePointScale } from './scales/time.ts'\nimport { lttb, lttbIndices } from './shapes/decimate.ts'\nimport { areaPath, linePath } from './shapes/path.ts'\n\n// Registered here, in the entry itself, so no bundler can shake it away.\nregister({\n time: { scale: time, points: timePointScale, axis: timeAxis },\n dates: dateLabels,\n log: { scale: log, domain: logDomain, ticks: logTicks },\n decimate: lttbIndices,\n line: { linePath, areaPath },\n annotations: { layers: annotationLayers, values: annotationValues },\n patterns: patternFills,\n 'point-shapes': markerPath,\n hydrate,\n morph,\n})\n\n// Steps that finish the content: shapes first, then the labels over them.\naddPost(shapesStep)\naddPost(labelsStep)\n\nexport { Chart } from './chart-default.ts'\nexport { types } from './chart-types.ts'\nexport * from './core.ts'\nexport type { DownloadOptions, ExportOptions, ExportTarget, ImageOptions } from './export-chart.ts'\nexport { downloadChart, exportImage, exportSVG } from './export-chart.ts'\nexport type { LogScaleOptions } from './scales/log.ts'\nexport type { TimeScale, TimeScaleOptions, TimeValue } from './scales/time.ts'\nexport { log, lttb, lttbIndices, time, timePointScale }\n","/**\n * `@tabler/charts-bootstrap`: a data API in the Bootstrap style. Charts are\n * declared in HTML and `init()` (or the CDN script, on its own) turns them\n * into charts.\n *\n * ```html\n * <div data-tc-chart=\"line\" data-tc-src=\"/api/sales.json\" data-tc-aspect-ratio=\"3\"></div>\n * <div data-tc-chart=\"bar\" data-tc-stacked=\"true\">\n * <script type=\"application/json\">{ \"labels\": [...], \"series\": [...] }</script>\n * </div>\n * ```\n *\n * `data-tc-chart` names the type; data comes from `data-tc-src` (a JSON URL),\n * an inline `<script type=\"application/json\">` or `data-tc-data`; every other\n * `data-tc-*` attribute is an option (`data-tc-aspect-ratio=\"3\"`), and\n * `data-tc-options` takes a JSON object for the rest.\n */\nimport { Chart, type ChartConfig, type ChartType, chartEvents, types } from '@tabler/charts'\n\n/** Every built-in chart type, by its `data-tc-chart` name. */\nexport { types }\n\nexport interface InitOptions {\n /** Extra or replacement chart types, merged over the built-in ones. */\n types?: Readonly<Record<string, ChartType<never>>>\n}\n\nconst SELECTOR = '[data-tc-chart]'\n/** Attributes that are not chart options. */\nconst RESERVED = new Set(['chart', 'src', 'data', 'options'])\n/** Options that are text, whatever it spells: a title \"2024\" is not a number. */\nconst TEXT = new Set(['title', 'description', 'locale', 'sync', 'id', 'class'])\n\nconst charts = new WeakMap<Element, Chart<object>>()\n/** Elements whose data is still loading, so a second init() does not fetch twice. */\nconst pending = new WeakSet<Element>()\n\n/** The chart created for an element by `init()`, if any; `O` types its options (e.g. `LineOptions`). */\nexport function getChart<O extends object = object>(element: Element): Chart<O> | undefined {\n return charts.get(element) as Chart<O> | undefined\n}\n\n/** Destroy the chart of an element (it can be initialized again later). */\nexport function dispose(element: Element): void {\n charts.get(element)?.destroy()\n charts.delete(element)\n}\n\n/** `\"true\"`, `\"3\"`, `'{\"a\":1}'` or plain text, as the value it spells. */\nfunction parseValue(text: string): unknown {\n if (text === 'true' || text === '') return true\n if (text === 'false') return false\n if (text !== '' && Number.isFinite(Number(text))) return Number(text)\n if (/^\\s*[[{]/.test(text)) return parseJson(text, 'a data-tc-* attribute')\n return text\n}\n\nfunction parseJson(text: string, what: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error) {\n throw new SyntaxError(\n `@tabler/charts-bootstrap: invalid JSON in ${what}: ${(error as Error).message}`,\n )\n }\n}\n\n/** Options from the element's `data-tc-*` attributes. */\nfunction optionsOf(element: HTMLElement): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n const json = element.dataset.tcOptions\n if (json) Object.assign(out, parseJson(json, 'data-tc-options'))\n for (const [key, value] of Object.entries(element.dataset)) {\n if (!key.startsWith('tc') || value === undefined) continue\n // dataset turns data-tc-aspect-ratio into tcAspectRatio.\n const name = key.charAt(2).toLowerCase() + key.slice(3)\n if (RESERVED.has(name)) continue\n out[name] =\n name === 'legend' && value === 'bottom'\n ? { position: 'bottom' }\n : name === 'download' && /^[a-z]/i.test(value) && !/^(true|false)$/.test(value)\n ? value.split(/[\\s,]+/).filter(Boolean)\n : TEXT.has(name)\n ? value\n : parseValue(value)\n }\n return out\n}\n\n/** Inline data: `data-tc-data` or a `<script type=\"application/json\">` child. */\nfunction inlineData(element: HTMLElement): unknown {\n const attr = element.dataset.tcData\n if (attr) return parseJson(attr, 'data-tc-data')\n const script = element.querySelector(':scope > script[type=\"application/json\"]')\n const text = script?.textContent?.trim()\n return text ? parseJson(text, 'the inline <script type=\"application/json\">') : undefined\n}\n\nfunction emit(element: Element, name: string, detail: unknown): void {\n element.dispatchEvent(new CustomEvent(`tc-${name}`, { detail, bubbles: true }))\n}\n\nfunction create(element: HTMLElement, type: ChartType<object>, data: unknown): Chart<object> {\n const config = { ...optionsOf(element), type, data } as ChartConfig<object>\n const chart = new Chart(element, config)\n for (const name of chartEvents) chart.on(name, (detail) => emit(element, name, detail))\n charts.set(element, chart)\n // The first render ran in the constructor, before anyone could listen.\n emit(element, 'render', { size: chart.size })\n return chart\n}\n\n/** Set up one element; returns its chart, or a promise while `data-tc-src` loads. */\nfunction setup(\n element: HTMLElement,\n known: Readonly<Record<string, ChartType<never>>>,\n): Chart<object> | Promise<Chart<object> | undefined> | undefined {\n const existing = charts.get(element)\n if (existing || pending.has(element)) return existing\n const name = element.dataset.tcChart ?? ''\n const type = known[name] as ChartType<object> | undefined\n if (!type) {\n const list = Object.keys(known).join(', ')\n throw new Error(`@tabler/charts-bootstrap: unknown chart type \"${name}\". Known types: ${list}.`)\n }\n const src = element.dataset.tcSrc\n if (!src) return create(element, type, inlineData(element) ?? [])\n\n pending.add(element)\n element.setAttribute('aria-busy', 'true')\n return fetch(src)\n .then((response) => {\n if (!response.ok) throw new Error(`${response.status} ${response.statusText}`.trim())\n return response.json()\n })\n .then(\n (data) => (element.isConnected ? create(element, type, data) : undefined),\n (error: unknown) => {\n emit(element, 'error', { error, src })\n console.error(`@tabler/charts-bootstrap: could not load ${src}:`, error)\n return undefined\n },\n )\n .finally(() => {\n pending.delete(element)\n element.removeAttribute('aria-busy')\n })\n}\n\n/**\n * Create a chart for every `[data-tc-chart]` in `root` (and `root` itself)\n * that does not have one yet. Resolves once charts with `data-tc-src` have\n * loaded; the ones with inline data exist as soon as `init()` returns.\n */\nexport function init(\n root: ParentNode = document,\n options: InitOptions = {},\n): Promise<Chart<object>[]> {\n const known = { ...types, ...options.types }\n const elements = [...root.querySelectorAll<HTMLElement>(SELECTOR)]\n if (root instanceof Element && root.matches(SELECTOR)) elements.unshift(root as HTMLElement)\n const made = elements.map((element) => {\n // One broken declaration (unknown type, bad JSON) must not stop the others.\n try {\n return setup(element, known)\n } catch (error) {\n emit(element, 'error', { error })\n console.error(error)\n return undefined\n }\n })\n return Promise.all(made).then((list) => list.filter((c): c is Chart<object> => c !== undefined))\n}\n\n/**\n * Keep `root` in sync: charts added later are initialized, charts removed\n * are destroyed. Returns a function that stops observing.\n */\nexport function observe(root: Element = document.body, options: InitOptions = {}): () => void {\n void init(root, options)\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n // A chart changing its own content (every hover, every update) adds no charts.\n const owner = (record.target as Element).closest?.(SELECTOR)\n if (owner && charts.has(owner)) continue\n for (const node of record.removedNodes) {\n if (!(node instanceof Element)) continue\n if (charts.has(node)) dispose(node)\n for (const inner of node.querySelectorAll(SELECTOR)) dispose(inner)\n }\n for (const node of record.addedNodes) {\n if (node instanceof Element && !node.isConnected) continue\n if (node instanceof Element) void init(node, options)\n }\n }\n })\n observer.observe(root, { childList: true, subtree: true })\n return () => observer.disconnect()\n}\n","/**\n * The CDN build (`dist/tabler-charts-bootstrap.min.js`): the library, the\n * chart stylesheet with the Bootstrap mapping, and the data API in one\n * classic script. On load it injects the styles and initializes every\n * `[data-tc-chart]`; everything is also on the `TablerCharts` global.\n *\n * ```html\n * <script src=\"https://cdn.jsdelivr.net/npm/@tabler/charts-bootstrap/dist/tabler-charts-bootstrap.min.js\"></script>\n * ```\n *\n * On the script tag, `data-no-styles` skips the styles (load them yourself)\n * and `data-observe` also initializes charts added later and destroys\n * removed ones.\n */\n// A script tag cannot import an entry: the download menu's saver comes along.\nimport '@tabler/charts/export'\nimport { init, observe } from './index.ts'\n\nif (typeof document !== 'undefined') {\n const script = document.currentScript\n if (!script?.hasAttribute('data-no-styles') && !document.getElementById('tc-styles')) {\n const style = document.createElement('style')\n style.id = 'tc-styles'\n style.textContent = __TC_PAGE_STYLES__\n // Under a strict CSP, the nonce of this script lets its styles in too.\n style.nonce = (script as HTMLScriptElement | null)?.nonce ?? ''\n // First in <head>, so the page's own CSS overrides it.\n document.head.prepend(style)\n }\n const observing = script?.hasAttribute('data-observe') ?? false\n const start = () => (observing ? observe(document.body) : void init(document))\n if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)\n else start()\n}\n\nexport * from '@tabler/charts'\nexport { dispose, getChart, init, observe, types } from './index.ts'\n"],"mappings":"2FAoBA,SAAgBkD,EAAO,EAAgC,EAAW,EAAW,CAE3E,IAAMC,EAAQ,GAA8B,CAC1C,IAAMC,EAAI,OAAOC,GAAU,SAAWA,EAAQA,IAAQC,GACtD,OAAO,OAAO,SAASF,CAAC,EAAKA,EAAeG,CAC9C,EACA,MAAO,CAAE,IAAKJ,EAAK,KAAK,EAAG,MAAOA,EAAK,OAAO,EAAG,OAAQA,EAAK,QAAQ,EAAG,KAAMA,EAAK,MAAM,CAAE,CAC9F,CAGA,SAAgBK,EAAU,EAAe,EAAgB,EAAuB,CAC9E,MAAO,CACL,EAAGC,EAAQ,KACX,EAAGA,EAAQ,IACX,MAAO,KAAK,IAAI,EAAGC,EAAQD,EAAQ,KAAOA,EAAQ,KAAK,EACvD,OAAQ,KAAK,IAAI,EAAGE,EAASF,EAAQ,IAAMA,EAAQ,MAAM,CAC3D,CACF,CAIA,IASMG,EAAU,GACdC,GAAQ,OACPA,GAAQ,MACNA,GAAQ,OAAUA,GAAQ,OAC1BA,GAAQ,OAAUA,GAAQ,OAC1BA,GAAQ,OAAUA,GAAQ,OAC1BA,GAAQ,OAAUA,GAAQ,OAC3BA,GAAQ,QAGZ,SAASC,EAAU,EAAsB,CAOvC,OANIC,GAAQ,KAAOA,GAAQ,IAAYA,IAAS,IAAM,IAAO,I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-bootstrap.min.js","names":["round","SVG_NS","TEXT","SHAPES","round","round","round","cleanData","EDGE","toMs","HOVER_SLOP","toMs","round","toMs","SVG_NS","pending","Chart","round","toMs","round","round","emit","round","pending","CoreChart","round","cleanData","cleanData","to2","cleanData","round","cleanData","HALF_PI","cleanData","sweepArcs","round","cleanData","round","cleanData","cleanData","LABEL_GAP","HOVER_SLOP","truncate","round","cleanData","round","cleanData","round","cleanData","round","cleanData","exports","insets","side","v","value","key","fallback","innerRect","margins","width","height","isWide","code","charWidth","char","estimateTextWidth","em","i","text","point","ASCII","fontSize","round$1","LINE_HEIGHT","SVG_NS$2","SHAPE","TEXT$1","STOP","GROUP","SHAPES$1","rootOf","el","target","svg","transformOf","style","ox","oy","inline","live","tag","props","declarations","name","copy","transform","liveChildren","copies","twin","child","legendLayer","legend","container","items","doc","patterned","box","g","item","swatch","s","n","color","slot","fill","hidden","dot","label","bottom","margin","exportSVG","animation","chartStyle","options","total","wrap","title","background","rect","exportImage","markup","type","image","canvas","scale","context","blob","resolve","reject","quality","downloadChart","format","link","features","register","added","steps","addPost","step","each","config","content","interaction","ctx","feature","found","h","children","attrs","cls","normalizeClass","normalizeStyle","out","flattenChildren","result","UNSAFE","prop","input","last","numberCache","dateCache","cached","cache","create","cacheKey","locale","getNumberFormat","getDateFormat","unsignedZero","formatNumber","compactSymbols","formatCompact","SYMBOLS","nf","own","digitsOf","small","large","exp","scaled","parts","digits","part","symbols","compactOf","o","formatDetail","stepPrecision","abs","hasPrecision","formatTicks","fmt","epsilon","formatDate","df","E10","E5","E2","tickSpec","stop","start","count","power","error","factor","i1","i2","inc","ticks","reverse","index","tickIncrement","tickStep","niceDomain","lo","hi","prev","linearTicks","d0","d1","bandTicks","isHorizontal","position","thinTicks","sizes","tick","fitsBetween","j","gap","span","sum","size","first","fits","kept","tail","axisSize","labels","max","tickSize","tickPadding","axis","horizontal","sign","offset","edge","area","tickLine","line","grid","direction","p","band","inner","paddingInner","domain","r0","r1","range","paddingOuter","align","bandwidth","at","px","raw","pixel","padding","extent","min","values","linear","k","mid","rMin","rMax","dMin","dMax","clamp","finite","optional","isRecord","list","numbers","x","records","fix","named","r","cleanSeries","d","data","cleanData$1","cleanItems","keyOf","legendItems","entry","groupAttrs","labelKey","seriesKey","seriesLegend","resolveLabels","plottable","isTimeAxis","toMs$1","l","labelFormatter","valueScale","valueTicks","markerShape","shapes","patterns","tickCount","auto","valueDomain","override","domainOf","extra","zeroDefault","pad","nlo","nhi","notesFeature","valueAxis","layout","of","finishLayout","flip","plot","xOptions","notes","y","yTicks","categories","xTicks","present","plotClip","overhang","cartesianLayout","yOptions","showY","showX","timed","probeY","countX","keys","labelAt","xAxis","edgeLabels","halfLine","firstLabel","lastLabel","edgeX","valueWidth","overflow","halfStep","sides","clipId","bleed","seriesAttrs","series","dash","categoryInteraction","formatLabel","formatValue","hitAt","center","empty","anchor","seriesIndex","hit","py","mark","markAt","seriesTable","all","limit","categorySpan","scales","f","pair","cleanAnnotations","a","isPair","annotationValues","annotations","annotationLayers","bands","lines","x0","x1","y0","y1","inside","vertical","from","to","placed","obstacles","apart","t","b","clearOfLabels","clear","end","shape","w","a1","a0","spots","after","before","top","near","far","spot","dateLabels","utc","log","base","safe","ln","logBase","untransform","t0","t1","decades","m","keep","logDomain","niced","logTicks","hitKey","toChartPoint","sx","sy","clientX","clientY","legendContent","off","defaultHidden","NAME_RE","EVENT_RE","isValidTag","isValidAttr","SVG_NS$1","HTML_NS","rendered","roots","render","replace","vnode","canPatch","patchElement","namespaceFor","createElement","parent","childNamespace","createNode","ns","setAttr","childNs","node","next","patchNode","patchAttrs","patchChildren","update","oldNodes","keyed","unkeyed","matched","used","cursor","candidate","HTML_ROOTS","VOID","renderToString","escapeText","renderNode","inSvg","parentInSvg","escapeAttr","childInSvg","TEXT_RE","ATTR_RE","TEXT_RE_G","ATTR_RE_G","ENTITIES","replaceEntity","listeners","seen","observer","getObserver","entries","contentRect","observeResize","ro","listener","queue","pending$2","requestFrame","callback","run","task","schedule","flush","flushHooks","cancel","ran","later","uid","nextId","resolveSize","measuredWidth","measured","ratio","renderContent","renderContext","id","onHitTest","measuredFontSize","cleanData","assertType","resolveLegend","option","chartLabel","names","shown","countNodes","c","isStatic","composeChart","descId","fills","still","extraAttrs","underlay","overlay","buildChart","chartToString","chartEvents","mounted","Chart$1","followsHeight","#cfg","changed","#measured","#font","#markResizing","#schedule","element","#adopt","#measure","#unobserve","#onResize","plugin","defaultPlugins","#plugins","reserved","#cache","#current","#hit","source","#source","#setHover","event","#hiddenSet","#toggled","#destroyed","cfg","#content","stale","#refreshHighlight","adopted","#compose","hiddenKey","#measureFontSize","under","over","layer","set","#handlers","handler","#resizeTimer","force","#hovered","rerender","TILES","SLOTS","patternDefs","patternVars","vars","patternFills","SHAPES","markerPath","reshape","group","shapesStep","SECOND","MINUTE","HOUR","DAY","MONTH","YEAR","INTERVALS","calendar","get","unit","make","mo","mi","weekday","date","chooseInterval","years","toMs","FORMATS","time","cal","interval","primary","above","tz","main","upper","timePointScale","stamps","valid","positions","ms","timeAxis","points","probe","overlaps","contains","outer","valueLabels","spec","pie","cell","stacked","marks","share","candidates","down","reach","along","room","sliceFits","other","slim","radius","depth","labelsStep","matches","hydrateElement","current","texts","created","hydrate","running","tween","state","origin","begin","duration","draw","NUMBER","native","morph","now","lttbIndices","threshold","runs","sampleRun","budget","bucketSize","bucket","nextStart","nextEnd","avgX","avgY","rangeStart","rangeEnd","ax","ay","best","bestArea","lttb","PathBuilder","#k","precision","rounded","#n","#xy","x2","y2","emit$1","curve","dedupe","move","path","monotone","xm","tangents","h0","h1","s0","s1","endTangent","dx","isValid","linePath","areaPath","baseAt","baseline","NAMES","DEFAULT_FORMATS","download","host","chart","addedClass","toggle","menu","setOpen","open","onOutside","isOpen","onClick","onKey","onBlur","remove","formats","seriesGroup","hoverUnderlay","crosshair","hoverOverlay","listening","listenPointer","local","overControl","onLeave","onMove","pointer","highlight","tableContent","corner","headers","table","caption","head","cells","describeHit","enabled","keyboard","region","announce","go","handle","focused","isChart","onFocus","adopt","bound","place","marginTop","marginBottom","groups","indexes","passing","indexOf","sync","self","joined","leave","join","ref","idle","pending$1","drain","tasks","scheduleIdle","cancelIdle","dataTable","maxRows","visible","rows","note","same","hitAnchor","tooltipContent","placeTooltip","left","bounds","fitsRight","fitsLeft","rawX","right","waiting","placeAll","measure","tooltip","tip","turns","turn","clip","Chart","fadeMask","stackSeries","percent","up","lastUp","lastDown","nullAsZero","row","segment","stackBounds","stacks","seriesPoints","connectNulls","renderLines","filled","fillStyle","pointRadius","gradient","fadeId","stack","seg","decimate","pts","drawn","bottoms","areas","dots","cx","cy","round","barPath","sweep","rr","hbarPath","hgt","length","horizontalLayout","probeValues","showValues","showCategories","probeCategories","edgeLabel","bar","orientation","isLine","lineKeys","stackHidden","layoutOptions","groupPadding","slots","order","columns","barWidth","maxBarWidth","groupWidth","barLeft","across","negative","away","paths","bodyPath","asCartesian","pick","candlestick","cartesian","maxCandleWidth","paint","candle","candles","EPSILON","PI","HALF_PI$1","TAU","DEG","asin","acos","intersect","x10","y10","x32","x3","y32","y3","cornerTangents","x01","y01","cw","rc","x11","y11","x00","y00","dy","d2","D","cx0","cy0","cx1","cy1","dx0","dy0","dx1","dy1","sector","a01","a11","a00","a10","da0","da","da1","ap","rp","rc0","rc1","p0","p1","oc","bx","by","cos","kc","lc","arcCentroid","padAngleForGap","innerRadius","outerRadius","angleOf","arcPathStable","arc","ring","delta","ccw","outerSweep","ix","iy","ex","ey","arcNode","startAngle","endAngle","padAngle","cornerRadius","HALF_PI","ringsOf","layoutRings","fitGauge","textTop","textBottom","renderGauge","thickness","rings","showCenter","centerLabel","radii","grow","fraction","geometry","hitFor","centerValue","gaugeTable","gauge","EMPTY","shade","rangeKey","rangeOf","ranges","slotColor","ringPath","renderHeatmap","dataMin","dataMax","stops","bySeries","u","pct","rowTicks","halfColumn","cellW","cellH","cellX","cellY","valueAt","painted","heatmapLegend","heatmap","MAX_SEATS","partiesOf","party","seatCounts","taken","parties","wanted","distribute","counts","layoutSeats","closed","radiiOf","pitchOf","capacity","pitch","seats","spacing","angle","seat","renderParliament","seatsOf","vacant","circle","parliamentTable","parliament","layoutSlices","slice","renderPie","defaults","slices","strokeGap","pieTable","pieType","donut","truncate$1","word","sin","fitRadius","angles","blockHeight","renderRadar","labelWidth","wrapped","polygon","radiusOf","spokeLabels","rest","radar","truncate","colorOf","graph","byName","nodes","declared","isHidden","legendKey","links","pass","justify","ia","ib","nodeWidth","nodePadding","widest","match","cap","byColumn","col","showValue","linkPath","ty","cubic","inLink","renderSankey","nodeMark","linkItem","hitNode","flows","linkIndex","hitLink","sankeyLegend","sankeyTable","sankey","circlePath","sizeOf","renderScatter","maxSize","bubble","countY","usable","xDomain","yDomain","ticksOf","probeX","half","fx","fy","fs","sz","bestDistance","distance","dotsPath","scatterTable","withSize","withLabel","take","scatter","renderSparkline","markers","tristate","variant","zero","bars","xAt","labelOf","yOf","dotAt","extremes","sparkline","types","SELECTOR","RESERVED","TEXT","charts","pending","getChart","dispose","parseValue","parseJson","what","optionsOf","json","inlineData","attr","emit","detail","setup","existing","known","src","response","init","elements","root","made","observe","record","owner","script","observing"],"sources":["../../core/src/layout.ts","../../core/src/export-chart.ts","../../core/src/features.ts","../../core/src/export.ts","../../core/src/vnode.ts","../../core/src/format.ts","../../core/src/scales/ticks.ts","../../core/src/components/axis.ts","../../core/src/components/grid.ts","../../core/src/scales/band.ts","../../core/src/scales/extent.ts","../../core/src/scales/linear.ts","../../core/src/charts/clean.ts","../../core/src/charts/named.ts","../../core/src/charts/cartesian.ts","../../core/src/charts/annotations.ts","../../core/src/charts/dates.ts","../../core/src/scales/log.ts","../../core/src/charts/log-axis.ts","../../core/src/interaction.ts","../../core/src/legend.ts","../../core/src/render/attrs.ts","../../core/src/render/dom.ts","../../core/src/render/string.ts","../../core/src/resize.ts","../../core/src/scheduler.ts","../../core/src/chart.ts","../../core/src/charts/patterns.ts","../../core/src/charts/point-shapes.ts","../../core/src/scales/time.ts","../../core/src/charts/time-axis.ts","../../core/src/charts/value-labels.ts","../../core/src/render/hydrate.ts","../../core/src/render/tween.ts","../../core/src/render/morph.ts","../../core/src/shapes/decimate.ts","../../core/src/shapes/path.ts","../../core/src/plugins/download.ts","../../core/src/components/hover.ts","../../core/src/plugins/pointer.ts","../../core/src/plugins/highlight.ts","../../core/src/a11y.ts","../../core/src/plugins/keyboard.ts","../../core/src/plugins/legend.ts","../../core/src/plugins/sync.ts","../../core/src/idle.ts","../../core/src/plugins/table.ts","../../core/src/tooltip.ts","../../core/src/plugins/tooltip.ts","../../core/src/plugins/index.ts","../../core/src/chart-default.ts","../../core/src/components/fade.ts","../../core/src/charts/stack.ts","../../core/src/charts/line.ts","../../core/src/charts/area.ts","../../core/src/shapes/bar.ts","../../core/src/charts/horizontal.ts","../../core/src/charts/bar.ts","../../core/src/charts/candlestick.ts","../../core/src/shapes/arc.ts","../../core/src/render/sweep.ts","../../core/src/charts/gauge.ts","../../core/src/charts/heatmap.ts","../../core/src/charts/parliament.ts","../../core/src/charts/pie.ts","../../core/src/charts/radar.ts","../../core/src/charts/sankey.ts","../../core/src/shapes/circle.ts","../../core/src/charts/scatter.ts","../../core/src/charts/sparkline.ts","../../core/src/chart-types.ts","../../core/package.json","../../core/src/core.ts","../../core/src/index.ts","../src/index.ts","../src/cdn.ts"],"sourcesContent":["/** Axis-aligned rectangle in pixels. */\nexport interface Rect {\n x: number\n y: number\n width: number\n height: number\n}\n\n/** Space around a box, in pixels. */\nexport interface Insets {\n top: number\n right: number\n bottom: number\n left: number\n}\n\n/** Insets given as one number for all sides or per side. */\nexport type InsetsInput = number | Partial<Insets>\n\n/** Normalize an {@link InsetsInput}; missing sides fall back to `fallback`. */\nexport function insets(value: InsetsInput | undefined, fallback = 0): Insets {\n // A side that is not a finite number (left out, or junk from outside) takes the fallback.\n const side = (key: keyof Insets): number => {\n const v = typeof value === 'number' ? value : value?.[key]\n return Number.isFinite(v) ? (v as number) : fallback\n }\n return { top: side('top'), right: side('right'), bottom: side('bottom'), left: side('left') }\n}\n\n/** Rectangle left inside `width × height` after `margins`; never negative. */\nexport function innerRect(width: number, height: number, margins: Insets): Rect {\n return {\n x: margins.left,\n y: margins.top,\n width: Math.max(0, width - margins.left - margins.right),\n height: Math.max(0, height - margins.top - margins.bottom),\n }\n}\n\n// Approximate advance widths in em for common UI sans-serif fonts\n// (system-ui / SF, Segoe UI, Roboto), measured in the browser.\nconst THIN = \" !'.,:;|ijlI`\"\nconst NARROW = '()[]{}-/frt'\nconst ROUND = 'CDGHNOQU'\nconst WIDE = '%@MWmw'\n\n/**\n * Full-width characters, a whole em each: Hangul, CJK and kana, compatibility\n * ideographs, fullwidth forms and pictographs (emoji).\n */\nconst isWide = (code: number): boolean =>\n code >= 0x1100 &&\n (code <= 0x115f ||\n (code >= 0x2e80 && code <= 0xa4cf) ||\n (code >= 0xac00 && code <= 0xd7a3) ||\n (code >= 0xf900 && code <= 0xfaff) ||\n (code >= 0xff00 && code <= 0xff60) ||\n code >= 0x1f300)\n\n/** The width of an ASCII character, in em. */\nfunction charWidth(char: string): number {\n if (char >= '0' && char <= '9') return char === '1' ? 0.45 : 0.63\n if (THIN.includes(char)) return 0.27\n if (NARROW.includes(char)) return 0.38\n if (WIDE.includes(char)) return 0.88\n if (ROUND.includes(char)) return 0.76\n if (char >= 'A' && char <= 'Z') return 0.66\n return 0.57\n}\n\n/**\n * Estimate the rendered width of `text` without a DOM, for layout on the\n * server and in workers. Tuned for common UI sans-serif fonts; deterministic,\n * so SSR and client layouts agree.\n */\nexport function estimateTextWidth(text: string, fontSize: number): number {\n let em = 0\n for (let i = 0; i < text.length; i++) {\n const point = text.codePointAt(i) as number\n // Beyond ASCII a character is a whole em or an average one; a pair of surrogates is one.\n em += ASCII[point] ?? (isWide(point) ? 1 : 0.57)\n if (point > 0xffff) i++\n }\n return em * fontSize\n}\n\n/**\n * The width of every ASCII character, looked up instead of worked out: an\n * axis of 100,000 long labels estimates millions of characters per render.\n */\nconst ASCII = /* @__PURE__ */ Array.from({ length: 128 }, (_, code) =>\n charWidth(String.fromCharCode(code)),\n)\n\n/** A pixel value rounded to two decimals, as written into attributes and path data. */\nexport const round = (value: number): number => Math.round(value * 100) / 100\n\n/** Line height used for single-line labels, relative to the font size. */\nexport const LINE_HEIGHT = 1.25\n","/**\n * Export a rendered chart as a standalone SVG or an image\n * (`exportSVG()`, `exportImage()`, `downloadChart()` of `@tabler/charts/export`).\n *\n * Charts are styled by CSS, so the export copies the computed styles of\n * every mark into the SVG: the file looks the same anywhere, without the\n * stylesheet or the page's custom properties. Browser only.\n *\n * Kept free of side effects, so `@tabler/charts` can re-export the functions\n * without carrying them into every bundle: the `/export` entry registers the\n * `download` menu's saver on top.\n */\nimport type { Chart } from './chart.ts'\nimport { round } from './layout.ts'\n\nconst SVG_NS = 'http://www.w3.org/2000/svg'\n\nexport interface ExportOptions {\n /**\n * Background color, `'auto'` for the chart's surface (`--tc-surface`), or\n * `false` for none (transparent). Defaults to `'auto'`.\n */\n background?: string | false\n /** Draw the legend into the image, as the page shows it. Defaults to `true`. */\n legend?: boolean\n}\n\nexport interface ImageOptions extends ExportOptions {\n /** Image type. Defaults to `'image/png'`. */\n type?: 'image/png' | 'image/jpeg' | 'image/webp'\n /** Pixels per chart pixel. Defaults to `2`. */\n scale?: number\n /** Quality of lossy types, `0…1`. */\n quality?: number\n}\n\nexport interface DownloadOptions extends ImageOptions {\n /** File name without the extension. Defaults to the chart's title, or `chart`. */\n filename?: string\n /** File format. Defaults to `'png'`. */\n format?: 'svg' | 'png' | 'jpeg' | 'webp'\n}\n\n/** A chart, its container, or its root `<svg>`. */\nexport type ExportTarget = Chart<object> | Element\n\n/** Properties copied from the computed style, with the values they can be left out at. */\nconst SHAPE: Record<string, string> = {\n fill: 'rgb(0, 0, 0)',\n 'fill-opacity': '1',\n stroke: 'none',\n 'stroke-width': '1px',\n 'stroke-opacity': '1',\n 'stroke-dasharray': 'none',\n 'stroke-dashoffset': '0px',\n 'stroke-linecap': 'butt',\n 'stroke-linejoin': 'miter',\n 'paint-order': 'normal',\n 'shape-rendering': 'auto',\n 'vector-effect': 'none',\n opacity: '1',\n visibility: 'visible',\n}\nconst TEXT: Record<string, string> = {\n ...SHAPE,\n 'font-family': '',\n 'font-size': '',\n 'font-weight': '400',\n 'font-style': 'normal',\n 'font-variant-numeric': 'normal',\n 'letter-spacing': 'normal',\n}\nconst STOP: Record<string, string> = { 'stop-color': '', 'stop-opacity': '1' }\nconst GROUP: Record<string, string> = { opacity: '1' }\nconst SHAPES = new Set(['path', 'line', 'rect', 'circle', 'ellipse', 'polygon', 'polyline'])\n\nfunction rootOf(target: ExportTarget): SVGSVGElement {\n const el = 'element' in target && !(target instanceof Element) ? target.element : target\n const svg = el.localName === 'svg' ? el : el.querySelector(':scope > svg.tc-chart')\n if (!svg) throw new Error('@tabler/charts: no rendered chart to export.')\n return svg as SVGSVGElement\n}\n\n/** A computed transform as an SVG `transform` attribute, around its origin. */\nfunction transformOf(style: CSSStyleDeclaration): string | undefined {\n const value = style.transform\n if (!value || value === 'none') return undefined\n // Browsers report a matrix; SVG takes the same functions without units.\n const svg = value.replace(/px/g, '')\n if (svg.startsWith('translate')) return svg\n const [ox = 0, oy = 0] = (style.transformOrigin || '0 0').split(' ').map(Number.parseFloat)\n return ox || oy ? `translate(${ox} ${oy}) ${svg} translate(${-ox} ${-oy})` : svg\n}\n\n/** Copy the computed look of `live` onto its clone, recursively. */\nfunction inline(live: Element, copy: Element): boolean {\n const style = getComputedStyle(live)\n if (style.display === 'none') return false\n const tag = live.localName\n const props = tag === 'text' ? TEXT : tag === 'stop' ? STOP : SHAPES.has(tag) ? SHAPE : GROUP\n const declarations: string[] = []\n for (const name in props) {\n const value = style.getPropertyValue(name)\n if (value && value !== props[name]) declarations.push(`${name}:${value}`)\n }\n copy.removeAttribute('style')\n if (declarations.length) copy.setAttribute('style', declarations.join(';'))\n const transform = transformOf(style)\n if (transform) copy.setAttribute('transform', transform)\n\n const liveChildren = Array.from(live.children)\n const copies = Array.from(copy.children)\n liveChildren.forEach((child, i) => {\n const twin = copies[i] as Element\n if (child.classList.contains('tc-hover-layer') || !inline(child, twin)) twin.remove()\n })\n return true\n}\n\n/**\n * The legend as the page lays it out: every entry at its place relative to\n * the legend box, with a swatch (hollow when hidden) and its name.\n */\nfunction legendLayer(\n container: Element,\n): { svg: Element; height: number; margin: number; bottom: boolean } | undefined {\n const legend = container.querySelector(':scope > .tc-legend')\n const items = legend ? Array.from(legend.querySelectorAll('.tc-legend-item')) : []\n if (!legend || !items.length) return undefined\n const doc = container.ownerDocument\n const patterned = container.querySelector(':scope > svg.tc-patterned')\n const box = legend.getBoundingClientRect()\n const g = doc.createElementNS(SVG_NS, 'g')\n for (const item of items) {\n const swatch = item.querySelector('.tc-legend-swatch')\n const name = item.querySelector('.tc-legend-name')\n if (!swatch || !name) continue\n const s = swatch.getBoundingClientRect()\n const n = name.getBoundingClientRect()\n const color = getComputedStyle(swatch).getPropertyValue('--tc-series-color').trim()\n // A chart that wears its patterns has them in the copied svg: the swatch takes its slot's.\n const slot = /\\btc-series-([1-8])\\b/.exec(item.getAttribute('class') ?? '')?.[1] ?? 'other'\n const fill = patterned\n ? getComputedStyle(patterned).getPropertyValue(`--tc-pattern-${slot}`).trim()\n : ''\n const hidden = item.classList.contains('tc-legend-item-hidden')\n const dot = doc.createElementNS(SVG_NS, 'circle')\n dot.setAttribute('cx', String(round(s.left - box.left + s.width / 2)))\n dot.setAttribute('cy', String(round(s.top - box.top + s.height / 2)))\n dot.setAttribute('r', String(round(s.width / 2 - (hidden ? 0.75 : 0))))\n dot.setAttribute(\n 'style',\n hidden\n ? `fill:none;stroke:${color};stroke-width:1.5px`\n : `fill:${fill.startsWith('url(') ? fill : color}`,\n )\n const text = getComputedStyle(name)\n const label = doc.createElementNS(SVG_NS, 'text')\n label.setAttribute('x', String(round(n.left - box.left)))\n label.setAttribute('y', String(round(n.top - box.top + n.height / 2)))\n label.setAttribute('dy', '0.35em')\n label.setAttribute(\n 'style',\n `fill:${text.color};font-family:${text.fontFamily};font-size:${text.fontSize};font-weight:${text.fontWeight}`,\n )\n label.textContent = name.textContent\n g.append(dot, label)\n }\n const bottom = legend.getAttribute('data-position') === 'bottom'\n const margin =\n Number.parseFloat(getComputedStyle(legend)[bottom ? 'marginTop' : 'marginBottom']) || 0\n return { svg: g, height: round(box.height + margin), margin, bottom }\n}\n\n/**\n * The chart as a standalone SVG document: the computed styles are inlined,\n * hover marks left out and running animations finished first.\n *\n * ```ts\n * const svg = exportSVG(chart)\n * ```\n */\nexport function exportSVG(target: ExportTarget, options: ExportOptions = {}): string {\n const svg = rootOf(target)\n // Read the resting state, not a frame in the middle of an entrance or update.\n for (const animation of svg.getAnimations?.({ subtree: true }) ?? []) animation.finish()\n const copy = svg.cloneNode(true) as SVGSVGElement\n inline(svg, copy)\n const doc = svg.ownerDocument\n const width = Number(svg.getAttribute('width'))\n const height = Number(svg.getAttribute('height'))\n copy.setAttribute('xmlns', SVG_NS)\n copy.removeAttribute('class')\n copy.removeAttribute('tabindex')\n copy.removeAttribute('data-resizing')\n copy.removeAttribute('aria-describedby')\n copy.removeAttribute('aria-activedescendant')\n\n const chartStyle = getComputedStyle(svg)\n const container = svg.parentElement\n const legend = options.legend !== false && container ? legendLayer(container) : undefined\n let total = height\n if (legend) {\n // The chart moves down below a top legend; a bottom one goes under it.\n const wrap = doc.createElementNS(SVG_NS, 'g')\n wrap.append(...Array.from(copy.childNodes))\n if (legend.bottom) {\n legend.svg.setAttribute('transform', `translate(0 ${height + legend.margin})`)\n } else {\n wrap.setAttribute('transform', `translate(0 ${legend.height})`)\n }\n copy.append(wrap, legend.svg)\n total = height + legend.height\n }\n copy.setAttribute('width', String(width))\n copy.setAttribute('height', String(total))\n copy.setAttribute('viewBox', `0 0 ${width} ${total}`)\n\n // A name for the file itself, besides the aria-label.\n const name = svg.getAttribute('aria-label')\n if (name) {\n const title = doc.createElementNS(SVG_NS, 'title')\n title.textContent = name\n copy.prepend(title)\n }\n\n const background =\n options.background === undefined || options.background === 'auto'\n ? chartStyle.getPropertyValue('--tc-surface').trim() || undefined\n : options.background || undefined\n if (background) {\n const rect = doc.createElementNS(SVG_NS, 'rect')\n rect.setAttribute('width', '100%')\n rect.setAttribute('height', '100%')\n rect.setAttribute('fill', background)\n copy.insertBefore(rect, copy.querySelector(':scope > title')?.nextSibling ?? copy.firstChild)\n }\n return new XMLSerializer().serializeToString(copy)\n}\n\n/**\n * The chart as an image (PNG by default), drawn from `exportSVG()` at\n * `scale` pixels per chart pixel.\n *\n * ```ts\n * const blob = await exportImage(chart, { scale: 3 })\n * ```\n */\nexport async function exportImage(target: ExportTarget, options: ImageOptions = {}): Promise<Blob> {\n const { type = 'image/png', scale = 2, quality } = options\n const markup = exportSVG(target, {\n ...options,\n // JPEG has no transparency: without a background it would turn black.\n ...(type === 'image/jpeg' && options.background === false ? { background: '#fff' } : {}),\n })\n const doc = rootOf(target).ownerDocument\n const image = new Image()\n image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`\n await image.decode()\n const canvas = doc.createElement('canvas')\n canvas.width = Math.round(image.width * scale)\n canvas.height = Math.round(image.height * scale)\n const context = canvas.getContext('2d')\n if (!context) throw new Error('@tabler/charts: no 2d canvas to draw the image.')\n context.drawImage(image, 0, 0, canvas.width, canvas.height)\n return new Promise((resolve, reject) => {\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error('@tabler/charts: could not encode.'))),\n type,\n quality,\n )\n })\n}\n\n/**\n * Save the chart as a file: PNG by default, or SVG, JPEG or WebP.\n *\n * ```ts\n * button.onclick = () => downloadChart(chart, { format: 'svg', filename: 'sales' })\n * ```\n */\nexport async function downloadChart(\n target: ExportTarget,\n options: DownloadOptions = {},\n): Promise<void> {\n const { format = 'png' } = options\n const svg = rootOf(target)\n const blob =\n format === 'svg'\n ? new Blob([exportSVG(target, options)], { type: 'image/svg+xml' })\n : await exportImage(target, { ...options, type: `image/${format}` })\n const name = (options.filename ?? svg.getAttribute('aria-label') ?? 'chart')\n .replace(/[\\\\/:*?\"<>|]+/g, '')\n .trim()\n const link = svg.ownerDocument.createElement('a')\n link.href = URL.createObjectURL(blob)\n link.download = `${name || 'chart'}.${format === 'jpeg' ? 'jpg' : format}`\n link.click()\n // Give the browser a moment to start the download before the URL goes.\n setTimeout(() => URL.revokeObjectURL(link.href), 1000)\n}\n","import type { ChartConfig, RenderContext } from './chart.ts'\nimport type { annotationLayers, annotationValues } from './charts/annotations.ts'\nimport type { dateLabels } from './charts/dates.ts'\nimport type { logDomain, logTicks } from './charts/log-axis.ts'\nimport type { patternFills } from './charts/patterns.ts'\nimport type { markerPath } from './charts/point-shapes.ts'\nimport type { timeAxis } from './charts/time-axis.ts'\nimport type { downloadChart } from './export-chart.ts'\nimport type { Interaction } from './interaction.ts'\nimport type { hydrate } from './render/hydrate.ts'\nimport type { morph } from './render/morph.ts'\nimport type { sweep } from './render/sweep.ts'\nimport type { log } from './scales/log.ts'\nimport type { time, timePointScale } from './scales/time.ts'\nimport type { areaPath, linePath, Point } from './shapes/path.ts'\nimport type { ChildInput } from './vnode.ts'\n\n/**\n * Optional features that chart types look up at render time. Each lives in\n * its own module (`@tabler/charts/time`, `/log`, `/decimate`, `/line`, `/annotations`) and registers\n * itself when imported; `@tabler/charts` registers all of them, while\n * `@tabler/charts/core` starts empty so unused code never ships.\n */\nexport interface Features {\n /** Time scale (and the point scale over it) behind `x: { type: 'time' }`. */\n time?: { scale: typeof time; points: typeof timePointScale; axis: typeof timeAxis }\n /** Date labels behind `x: { type: 'time' }` (also registered by `@tabler/charts/candlestick`). */\n dates?: typeof dateLabels\n /** Log scale and axis behind `scale: 'log'`. */\n log?: { scale: typeof log; domain: typeof logDomain; ticks: typeof logTicks }\n /** Downsampling behind `decimate: N`: indices of the points to keep. */\n decimate?: (points: readonly Point[], threshold: number) => number[]\n /**\n * Taking over server-rendered markup node by node (without it, the server\n * svg is replaced on the first render).\n */\n hydrate?: typeof hydrate\n /** Path morphing on data updates where CSS cannot transition `d` (Safari). */\n morph?: typeof morph\n /** Arcs turning to their new angles on data updates (set by pie, donut and gauge). */\n sweep?: typeof sweep\n /** Line and area paths behind `series.type: 'line' | 'area'` in bar charts. */\n line?: { linePath: typeof linePath; areaPath: typeof areaPath }\n /** Reference lines and bands behind `annotations` in cartesian charts. */\n annotations?: { layers: typeof annotationLayers; values: typeof annotationValues }\n /** Pattern fills behind `patterns` (and forced colors, with `'auto'`). */\n patterns?: typeof patternFills\n /**\n * Steps that finish a chart's rendered content (see `addPost`): point\n * shapes, value labels.\n */\n post?: PostStep\n /** Point shapes by color slot, behind `shapes`. */\n 'point-shapes'?: typeof markerPath\n /** Saving a chart as a file, behind the `download` menu. */\n export?: typeof downloadChart\n}\n\nexport const features: Features = {}\n\n/** Register optional features (idempotent). */\nexport function register(added: Features): void {\n Object.assign(features, added)\n}\n\n/** A step that finishes rendered chart content, e.g. by adding value labels. */\nexport type PostStep = (\n config: ChartConfig<object>,\n content: ChildInput,\n interaction: Interaction | undefined,\n ctx: RenderContext,\n) => ChildInput\n\nconst steps = /* @__PURE__ */ new Set<PostStep>()\n\n/** Add a step that finishes rendered content, once, in the order added. */\nexport function addPost(step: PostStep): void {\n steps.add(step)\n features.post = (config, content, interaction, ctx) => {\n for (const each of steps) content = each(config, content, interaction, ctx)\n return content\n }\n}\n\n/** The registered feature, or a helpful error naming the import that provides it. */\nexport function feature<K extends keyof Features>(name: K): NonNullable<Features[K]> {\n const found = features[name]\n if (!found) {\n throw new Error(\n `@tabler/charts: Import \"@tabler/charts/${name === 'dates' ? 'time' : name}\" for ${name}.`,\n )\n }\n return found\n}\n","/**\n * Standalone entry: `import { exportSVG, exportImage, downloadChart } from '@tabler/charts/export'`\n * saves a rendered chart as a standalone SVG or an image. Importing it also\n * enables the `download` option (a menu on the chart that saves it): with the\n * `Chart` of `@tabler/charts`, which has the `download()` plugin, or with the\n * plugin installed on the core.\n */\nimport { downloadChart, exportImage, exportSVG } from './export-chart.ts'\nimport { register } from './features.ts'\n\n// Registered here, in the entry itself, so no bundler can shake it away.\nregister({ export: downloadChart })\n\nexport type {\n DownloadOptions,\n ExportOptions,\n ExportTarget,\n ImageOptions,\n} from './export-chart.ts'\nexport { downloadChart, exportImage, exportSVG }\n","/**\n * Minimal virtual node tree shared by the string (SSR) and DOM renderers.\n *\n * VNodes are plain, serializable data: no event handlers, no component\n * functions. Interaction is handled by event delegation on the root element,\n * so the same tree can be rendered on the server, in a worker or in tests.\n */\n\n/** Value accepted for a single attribute. `false`, `null`, `undefined` and non-finite numbers omit it. */\nexport type AttrValue = string | number | boolean | null | undefined\n\n/** Normalized attributes stored on a {@link VNode}. */\nexport type Attrs = Record<string, string | number>\n\n/** Identity used by the DOM renderer to match nodes between renders. */\nexport type Key = string | number\n\n/** Class list: strings, falsy values (skipped) and nested arrays. */\nexport type ClassValue = string | false | null | undefined | ClassValue[]\n\n/** Inline styles: a raw string or a map of properties (custom properties included). */\nexport type StyleValue = string | Record<string, string | number | null | undefined>\n\n/** Props accepted by {@link h}. */\nexport interface Props {\n [name: string]: AttrValue | ClassValue | StyleValue\n key?: Key | null | undefined\n class?: ClassValue\n style?: StyleValue | null | undefined\n}\n\n/** A normalized child: an element node or a text node. */\nexport type Child = VNode | string\n\n/** Anything that can be passed as a child to {@link h}; falsy values are skipped. */\nexport type ChildInput = Child | number | boolean | null | undefined | ChildInput[]\n\nexport interface VNode {\n /** Element name, e.g. `svg`, `g`, `path`. */\n tag: string\n /** Normalized attributes, without `key`. */\n attrs: Attrs\n /** Flattened children with adjacent text merged. */\n children: Child[]\n /** Optional identity used by the keyed DOM patcher. */\n key: Key | undefined\n /**\n * The arc a path draws (radii, angles, pad angle, corner radius), kept out\n * of the markup: the DOM patcher sweeps from the arc of the last render to\n * this one (see `sweep`).\n */\n arc?: readonly number[]\n}\n\n/**\n * Create a virtual node.\n *\n * ```ts\n * h('g', { class: ['tc-series', `tc-series-${i}`], key: series.id },\n * h('path', { class: 'tc-line', d }),\n * )\n * ```\n */\nexport function h(tag: string, props?: Props | null, ...children: ChildInput[]): VNode {\n const attrs: Attrs = {}\n let key: Key | undefined\n\n if (props) {\n for (const name in props) {\n const value = props[name]\n if (name === 'key') {\n if (value != null) key = value as Key\n } else if (name === 'class') {\n const cls = normalizeClass(value as ClassValue)\n if (cls) attrs.class = cls\n } else if (name === 'style') {\n const style = normalizeStyle(value as StyleValue | null | undefined)\n if (style) attrs.style = style\n } else if (value === true) {\n attrs[name] = ''\n } else if (typeof value === 'string') {\n attrs[name] = value\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n attrs[name] = value\n }\n }\n }\n\n const out: Child[] = []\n flattenChildren(children, out)\n\n return { tag, attrs, children: out, key }\n}\n\n/** Join a class value into a space separated string. */\nexport function normalizeClass(value: ClassValue): string {\n if (!value) return ''\n if (typeof value === 'string') return value\n let result = ''\n for (const item of value) {\n const cls = normalizeClass(item)\n if (cls) result = result ? `${result} ${cls}` : cls\n }\n return result\n}\n\n/**\n * Values that could leave their declaration (`;`, braces, quotes, escapes,\n * comments) or load something (`url()` and friends). Colors and dashes often\n * come from user data, and `red;position:fixed` would restyle the chart's\n * elements, `url(…)` would make the browser request it. A reference to an\n * element of the page, `url(#id)` (pattern fills), loads nothing and passes.\n */\nconst UNSAFE =\n /[;{}<>\"'\\\\]|\\/\\*|\\b(?:url(?!\\(#[\\w-]+\\))|src|attr|image|image-set|cross-fade|element|expression)\\s*\\(/i\n\n/**\n * Serialize a style value into a CSS declaration list. In a map, values that\n * could inject CSS (see {@link UNSAFE}) are left out, so use one for values\n * from data; a raw string is taken as it is.\n */\nexport function normalizeStyle(value: StyleValue | null | undefined): string {\n if (!value) return ''\n if (typeof value === 'string') return value\n let result = ''\n for (const prop in value) {\n const v = value[prop]\n if (v == null || v === '' || UNSAFE.test(String(v))) continue\n result += `${result ? ';' : ''}${prop}:${v}`\n }\n return result\n}\n\nfunction flattenChildren(input: ChildInput[], out: Child[]): void {\n for (const child of input) {\n if (child == null || typeof child === 'boolean') continue\n if (Array.isArray(child)) {\n flattenChildren(child, out)\n continue\n }\n if (typeof child === 'object') {\n out.push(child)\n continue\n }\n const text = String(child)\n if (text === '') continue\n const last = out.length - 1\n if (last >= 0 && typeof out[last] === 'string') {\n out[last] += text\n } else {\n out.push(text)\n }\n }\n}\n","/**\n * Number and date formatting built on `Intl` — locale aware, zero bytes of\n * locale data shipped.\n *\n * Formats are plain data (`Intl` options) or functions, so chart configs stay\n * serializable (JSON attributes, SSR). Pass an explicit `locale` when\n * rendering on the server, otherwise server and browser may disagree.\n */\n\n/** Locale(s) passed to `Intl`; `undefined` uses the runtime default. */\nexport type Locale = string | readonly string[] | undefined\n\n/** `Intl.NumberFormat` options, plus suffixes of our own for compact notation. */\nexport interface NumberFormatOptions extends Intl.NumberFormatOptions {\n /**\n * Compact notation with these suffixes for thousands, millions, billions…\n * instead of the locale's words: `['k', 'M', 'G']` writes 1500 as \"1.5k\",\n * or \"1,5k\" in Polish, where the locale itself writes \"1,5 tys.\". `true`\n * stands for `['K', 'M', 'B', 'T']`. Larger numbers keep the last suffix.\n */\n compactSymbols?: boolean | readonly string[]\n}\n\n/** Number format options or a custom formatter. */\nexport type NumberFormat = NumberFormatOptions | ((value: number) => string)\n\n/** `Intl.DateTimeFormat` options or a custom formatter. */\nexport type DateFormat = Intl.DateTimeFormatOptions | ((value: Date) => string)\n\nconst MAX_CACHE = 64\nconst numberCache = /* @__PURE__ */ new Map<string, Intl.NumberFormat>()\nconst dateCache = /* @__PURE__ */ new Map<string, Intl.DateTimeFormat>()\n\nfunction cached<T>(cache: Map<string, T>, key: string, create: () => T): T {\n let value = cache.get(key)\n if (value === undefined) {\n if (cache.size >= MAX_CACHE) cache.clear()\n value = create()\n cache.set(key, value)\n }\n return value\n}\n\nfunction cacheKey(locale: Locale, options: object): string {\n return `${JSON.stringify(locale ?? null)}|${JSON.stringify(options)}`\n}\n\n/** Shared, cached `Intl.NumberFormat` instance. */\nexport function getNumberFormat(\n locale?: Locale,\n options: Intl.NumberFormatOptions = {},\n): Intl.NumberFormat {\n return cached(\n numberCache,\n cacheKey(locale, options),\n () => new Intl.NumberFormat(locale as string | string[] | undefined, options),\n )\n}\n\n/** Shared, cached `Intl.DateTimeFormat` instance. */\nexport function getDateFormat(\n locale?: Locale,\n options: Intl.DateTimeFormatOptions = {},\n): Intl.DateTimeFormat {\n return cached(\n dateCache,\n cacheKey(locale, options),\n () => new Intl.DateTimeFormat(locale as string | string[] | undefined, options),\n )\n}\n\n/** Avoid `-0` rendering as \"-0\". */\nconst unsignedZero = (value: number): number => (value === 0 ? 0 : value)\n\n/**\n * Create a number formatter.\n *\n * ```ts\n * formatNumber({ style: 'currency', currency: 'PLN' }, 'pl-PL')(1234.5) // \"1234,50 zł\"\n * ```\n */\nexport function formatNumber(format?: NumberFormat, locale?: Locale): (value: number) => string {\n if (typeof format === 'function') return format\n const { compactSymbols, ...options } = format ?? {}\n if (compactSymbols) {\n return formatCompact(compactSymbols === true ? SYMBOLS : compactSymbols, options, locale)\n }\n const nf = getNumberFormat(locale, options)\n return (value) => nf.format(unsignedZero(value))\n}\n\nconst SYMBOLS = ['K', 'M', 'B', 'T']\n\n/**\n * Compact notation with the given suffixes: the value divided by its power\n * of a thousand, formatted by `Intl` (separators, currency, sign) with the\n * suffix after the digits. Without digits of its own it rounds like `Intl`'s\n * compact notation: two significant digits below 10, whole numbers above.\n */\nfunction formatCompact(\n symbols: readonly string[],\n // `notation` and `compactDisplay` are taken out: the suffixes replace them.\n { notation, compactDisplay, ...options }: Intl.NumberFormatOptions,\n locale: Locale,\n): (value: number) => string {\n const own = digitsOf(options)\n const small = getNumberFormat(locale, own ? options : { ...options, maximumSignificantDigits: 2 })\n const large = own ? small : getNumberFormat(locale, { ...options, maximumFractionDigits: 0 })\n return (value) => {\n for (let exp = 0; ; exp++) {\n const scaled = unsignedZero(value / 1000 ** exp)\n const parts = (Math.abs(scaled) < 10 ? small : large).formatToParts(scaled)\n let digits = ''\n let last: Intl.NumberFormatPart | undefined\n for (const part of parts) {\n if (part.type === 'integer') digits += part.value\n if (part.type === 'integer' || part.type === 'fraction') last = part\n }\n // Four digits or more: a thousand times smaller, with the next suffix\n // (so 999 950 rounds up to \"1M\", not \"1000K\").\n if (digits.length < 4 || exp >= symbols.length) {\n if (exp && last) last.value += symbols[exp - 1]\n return parts.map((part) => part.value).join('')\n }\n }\n }\n}\n\n/** Whether number options write compact numbers (\"25K\"). */\nconst compactOf = (o: NumberFormatOptions): boolean =>\n o.notation === 'compact' || !!o.compactSymbols\n\n/** Whether number options set their digits (fraction or significant). */\nconst digitsOf = (o: Intl.NumberFormatOptions): boolean =>\n (o.minimumFractionDigits ??\n o.maximumFractionDigits ??\n o.minimumSignificantDigits ??\n o.maximumSignificantDigits) !== undefined\n\n/**\n * A formatter for values read one at a time (tooltips, data tables) in an\n * axis format. Compact notation suits ticks (\"$25K\") but hides the\n * difference between values: unless the format sets its own precision, it\n * keeps three significant digits (\"$24.8K\").\n */\nexport function formatDetail(format?: NumberFormat, locale?: Locale): (value: number) => string {\n return formatNumber(\n typeof format === 'object' && compactOf(format) && !digitsOf(format)\n ? { ...format, maximumSignificantDigits: 3 }\n : format,\n locale,\n )\n}\n/**\n * Number of fraction digits needed to tell apart ticks `step` apart,\n * e.g. `1 → 0`, `0.2 → 1`, `0.05 → 2`.\n */\nexport function stepPrecision(step: number): number {\n const abs = Math.abs(step)\n if (!Number.isFinite(abs) || abs === 0) return 0\n return Math.max(0, -Math.floor(Math.log10(abs) + 1e-9))\n}\n\nfunction hasPrecision(options: NumberFormatOptions): boolean {\n return (\n digitsOf(options) || !!options.compactSymbols || (options.notation ?? 'standard') !== 'standard'\n )\n}\n/**\n * Create a formatter for axis ticks `step` apart. Unless `format` sets its\n * own precision, every tick gets the same number of fraction digits, derived\n * from the step (`0, 0.5, 1` → `0.0, 0.5, 1.0`).\n */\nexport function formatTicks(\n step: number,\n format?: NumberFormat,\n locale?: Locale,\n): (value: number) => string {\n if (typeof format === 'function') return format\n const options = format ?? {}\n if (hasPrecision(options)) return formatNumber(options, locale)\n\n let digits = stepPrecision(step)\n if (options.style === 'percent') digits = Math.max(0, digits - 2)\n const fmt = formatNumber(\n { ...options, minimumFractionDigits: digits, maximumFractionDigits: digits },\n locale,\n )\n // Values within floating point noise of zero (e.g. 1e-17) print as zero.\n const epsilon = Math.abs(step) * 1e-9\n return (value) => fmt(Math.abs(value) < epsilon ? 0 : value)\n}\n\n/**\n * Create a date formatter accepting `Date` objects or timestamps.\n *\n * ```ts\n * formatDate({ month: 'short', day: 'numeric' }, 'en-US')(new Date(2026, 0, 5)) // \"Jan 5\"\n * ```\n */\nexport function formatDate(format?: DateFormat, locale?: Locale): (value: Date | number) => string {\n if (typeof format === 'function') {\n return (value) => format(typeof value === 'number' ? new Date(value) : value)\n }\n const df = getDateFormat(locale, format)\n return (value) => df.format(value)\n}\n","const E10 = Math.sqrt(50)\nconst E5 = Math.sqrt(10)\nconst E2 = Math.sqrt(2)\n\n/**\n * Integer tick indices `[i1, i2]` and an increment `inc`. A negative `inc`\n * means \"divide by -inc\", which keeps decimal ticks exact (0.3, not\n * 0.30000000000000004).\n */\nfunction tickSpec(start: number, stop: number, count: number): [number, number, number] {\n const step = (stop - start) / Math.max(0, count)\n const power = Math.floor(Math.log10(step))\n const error = step / 10 ** power\n const factor = error >= E10 ? 10 : error >= E5 ? 5 : error >= E2 ? 2 : 1\n let i1: number\n let i2: number\n let inc: number\n if (power < 0) {\n inc = 10 ** -power / factor\n i1 = Math.round(start * inc)\n i2 = Math.round(stop * inc)\n if (i1 / inc < start) ++i1\n if (i2 / inc > stop) --i2\n inc = -inc\n } else {\n inc = 10 ** power * factor\n i1 = Math.round(start / inc)\n i2 = Math.round(stop / inc)\n if (i1 * inc < start) ++i1\n if (i2 * inc > stop) --i2\n }\n if (i2 < i1 && count >= 0.5 && count < 2) return tickSpec(start, stop, count * 2)\n return [i1, i2, inc]\n}\n\n/**\n * Roughly `count` evenly spaced, \"nice\" values (multiples of 1, 2 or 5 × 10ⁿ)\n * between `start` and `stop`, inclusive. Order follows `start → stop`.\n */\nexport function ticks(start: number, stop: number, count = 5): number[] {\n if (!(count > 0) || !Number.isFinite(start) || !Number.isFinite(stop)) return []\n if (start === stop) return [start]\n const reverse = stop < start\n const [i1, i2, inc] = reverse ? tickSpec(stop, start, count) : tickSpec(start, stop, count)\n if (!(i2 >= i1)) return []\n const n = i2 - i1 + 1\n const out = new Array<number>(n)\n for (let i = 0; i < n; i++) {\n const index = reverse ? i2 - i : i1 + i\n out[i] = inc < 0 ? index / -inc : index * inc\n }\n return out\n}\n\n/**\n * Signed tick increment: positive values are the step, negative values `-k`\n * mean a step of `1 / k`.\n */\nexport function tickIncrement(start: number, stop: number, count: number): number {\n return tickSpec(start, stop, count)[2]\n}\n\n/** Distance between ticks produced by {@link ticks} for the same arguments. */\nexport function tickStep(start: number, stop: number, count = 5): number {\n const reverse = stop < start\n const inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count)\n return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc)\n}\n\n/**\n * Extend `[start, stop]` to round tick values, e.g. `[0.2, 9.7] → [0, 10]`.\n * Iterates because rounding can change the ideal step; if the step does not\n * settle (e.g. very low `count` around zero keeps doubling the domain), the\n * domain is returned unchanged, matching d3.\n */\nexport function niceDomain(start: number, stop: number, count = 5): [number, number] {\n if (!Number.isFinite(start) || !Number.isFinite(stop) || start === stop || !(count > 0)) {\n return [start, stop]\n }\n const reverse = stop < start\n let lo = reverse ? stop : start\n let hi = reverse ? start : stop\n let prev: number | undefined\n for (let i = 0; i < 10; i++) {\n const step = tickIncrement(lo, hi, count)\n if (step === prev) return reverse ? [hi, lo] : [lo, hi]\n if (step > 0) {\n lo = Math.floor(lo / step) * step\n hi = Math.ceil(hi / step) * step\n } else if (step < 0) {\n lo = Math.ceil(lo * step) / step\n hi = Math.floor(hi * step) / step\n } else {\n break\n }\n prev = step\n }\n return [start, stop]\n}\n","import { formatTicks, type Locale, type NumberFormat } from '../format.ts'\nimport { estimateTextWidth, LINE_HEIGHT, type Rect, round } from '../layout.ts'\nimport type { BandKey, BandScale } from '../scales/band.ts'\nimport type { LinearScale } from '../scales/linear.ts'\nimport { tickStep } from '../scales/ticks.ts'\nimport { h, type VNode } from '../vnode.ts'\n\nexport type AxisPosition = 'top' | 'right' | 'bottom' | 'left'\n\n/** A single axis tick: its data value, pixel position along the axis and label. */\nexport interface Tick {\n value: number | BandKey\n position: number\n label: string\n}\n\nexport interface LinearTicksOptions {\n /** Approximate number of ticks. Defaults to `5`. */\n count?: number\n format?: NumberFormat\n locale?: Locale\n}\n\n/** Ticks for a linear scale, labelled with a shared precision. */\nexport function linearTicks(scale: LinearScale, options: LinearTicksOptions = {}): Tick[] {\n const { count = 5, format, locale } = options\n const [d0, d1] = scale.domain\n const fmt = formatTicks(tickStep(d0, d1, count), format, locale)\n return scale.ticks(count).map((value) => ({ value, position: scale(value), label: fmt(value) }))\n}\n\n/** Ticks at the center of every band. */\nexport function bandTicks(\n scale: BandScale,\n format: (key: BandKey, index: number) => string = String,\n): Tick[] {\n return scale.domain.map((key, i) => ({\n value: key,\n position: scale.at(i) + scale.bandwidth / 2,\n label: format(key, i),\n }))\n}\n\n/** Whether labels are laid out along x (horizontal axes). */\nconst isHorizontal = (position: AxisPosition): boolean =>\n position === 'top' || position === 'bottom'\n\n/**\n * Keep every n-th tick (smallest n) so labels do not overlap along the axis.\n * The first and the last tick are always kept: when the last one does not\n * land on the step, it replaces the last kept tick if they would collide.\n */\nexport function thinTicks(\n ticks: readonly Tick[],\n position: AxisPosition,\n fontSize: number,\n gap = 8,\n): Tick[] {\n if (ticks.length < 2) return ticks.slice()\n const size = (tick: Tick) =>\n isHorizontal(position) ? estimateTextWidth(tick.label, fontSize) : fontSize * LINE_HEIGHT\n const sizes = ticks.map(size)\n const fitsBetween = (i: number, j: number) =>\n Math.abs((ticks[j] as Tick).position - (ticks[i] as Tick).position) >=\n ((sizes[i] as number) + (sizes[j] as number)) / 2 + gap\n\n const last = ticks.length - 1\n // Start from the step the total label size demands, instead of trying every one.\n const span = Math.abs((ticks[last] as Tick).position - (ticks[0] as Tick).position)\n const total = sizes.reduce((sum, size) => sum + size + gap, 0)\n const first = span > 0 ? Math.max(1, Math.floor(total / span)) : last\n for (let step = first; step <= last; step++) {\n let fits = true\n for (let i = step; i <= last && fits; i += step) fits = fitsBetween(i - step, i)\n if (!fits) continue\n\n const kept: number[] = []\n for (let i = 0; i <= last; i += step) kept.push(i)\n const tail = kept[kept.length - 1] as number\n if (tail !== last) {\n if (fitsBetween(tail, last)) kept.push(last)\n else if (kept.length > 1 && fitsBetween(kept[kept.length - 2] as number, last))\n kept[kept.length - 1] = last\n }\n return kept.map((i) => ticks[i] as Tick)\n }\n return ticks.slice(0, 1)\n}\n\nexport interface AxisOptions {\n position: AxisPosition\n ticks: readonly Tick[]\n /** Plot area the axis is attached to. */\n area: Rect\n /** Length of tick marks. Defaults to `0` (labels only). */\n tickSize?: number\n /** Distance between tick marks and labels. Defaults to `8`. */\n tickPadding?: number\n /** Draw the axis line along the plot edge. Defaults to `false`. */\n line?: boolean\n}\n\n/** Pixels an axis occupies perpendicular to the plot edge (for margins). */\nexport function axisSize(\n position: AxisPosition,\n ticks: readonly Tick[],\n fontSize: number,\n options: { tickSize?: number; tickPadding?: number } = {},\n): number {\n const { tickSize = 0, tickPadding = 8 } = options\n if (ticks.length === 0) return 0\n // Beside the plot, labels are as wide as their text: a little slack covers\n // fonts wider than the estimate, so they do not touch the chart's edge.\n const labels = isHorizontal(position)\n ? fontSize * LINE_HEIGHT\n : ticks.reduce((max, t) => Math.max(max, estimateTextWidth(t.label, fontSize)), 0) + 3\n return Math.ceil(labels + tickSize + tickPadding)\n}\n\n/**\n * Render an axis as `<g class=\"tc-axis tc-axis-{x|y} tc-axis-{position}\">`\n * with one `<g class=\"tc-tick\">` per tick, keyed by value so ticks can\n * transition when the scale changes.\n */\nexport function axis(options: AxisOptions): VNode {\n const { position, ticks, area, tickSize = 0, tickPadding = 8, line = false } = options\n const horizontal = isHorizontal(position)\n const sign = position === 'top' || position === 'left' ? -1 : 1\n const offset = sign * (tickSize + tickPadding)\n\n // Edge of the plot the axis sits on.\n const edge =\n position === 'top'\n ? area.y\n : position === 'bottom'\n ? area.y + area.height\n : position === 'left'\n ? area.x\n : area.x + area.width\n\n const label = horizontal\n ? { y: offset, dy: position === 'top' ? '0em' : '0.71em', 'text-anchor': 'middle' }\n : { x: offset, dy: '0.32em', 'text-anchor': position === 'left' ? 'end' : 'start' }\n\n const tickLine = horizontal ? { y2: sign * tickSize } : { x2: sign * tickSize }\n\n return h(\n 'g',\n {\n // Keyed, so an axis keeps its nodes when layers around it come and go.\n key: `axis-${position}`,\n class: ['tc-axis', horizontal ? 'tc-axis-x' : 'tc-axis-y', `tc-axis-${position}`],\n 'aria-hidden': 'true',\n },\n line &&\n h(\n 'line',\n horizontal\n ? { class: 'tc-axis-line', x1: area.x, x2: area.x + area.width, y1: edge, y2: edge }\n : { class: 'tc-axis-line', x1: edge, x2: edge, y1: area.y, y2: area.y + area.height },\n ),\n ticks.map((tick) =>\n h(\n 'g',\n {\n key: tick.value,\n class: 'tc-tick',\n // An inline style (not the transform attribute) so CSS can transition it.\n style: horizontal\n ? `transform:translate(${round(tick.position)}px,${round(edge)}px)`\n : `transform:translate(${round(edge)}px,${round(tick.position)}px)`,\n },\n tickSize > 0 && h('line', { class: 'tc-tick-line', ...tickLine }),\n h('text', { class: 'tc-tick-label', ...label }, tick.label),\n ),\n ),\n )\n}\n","import type { Rect } from '../layout.ts'\nimport { round } from '../layout.ts'\nimport { h, type VNode } from '../vnode.ts'\nimport type { Tick } from './axis.ts'\n\nexport interface GridOptions {\n /** `'y'` draws horizontal lines at y ticks, `'x'` vertical lines at x ticks. */\n direction: 'x' | 'y'\n ticks: readonly Tick[]\n area: Rect\n}\n\n/**\n * Render grid lines as `<g class=\"tc-grid tc-grid-{x|y}\">`. The line at\n * value `0` also gets `tc-grid-line-zero`, so the baseline can be emphasized.\n */\nexport function grid(options: GridOptions): VNode {\n const { direction, ticks, area } = options\n return h(\n 'g',\n { key: `grid-${direction}`, class: ['tc-grid', `tc-grid-${direction}`], 'aria-hidden': 'true' },\n ticks.map((tick) => {\n const p = round(tick.position)\n return h('line', {\n key: tick.value,\n class: ['tc-grid-line', tick.value === 0 && 'tc-grid-line-zero'],\n // Positioned with a transitionable transform, so lines glide when the scale changes.\n ...(direction === 'y'\n ? {\n x1: area.x,\n x2: area.x + area.width,\n y1: 0,\n y2: 0,\n style: `transform:translateY(${p}px)`,\n }\n : {\n x1: 0,\n x2: 0,\n y1: area.y,\n y2: area.y + area.height,\n style: `transform:translateX(${p}px)`,\n }),\n })\n }),\n )\n}\n","/** Category identifier used by band and point scales. */\nexport type BandKey = string | number\n\nexport interface BandScaleOptions {\n /** Share of each step left empty between bands, `0…1`. Defaults to `0`. */\n paddingInner?: number\n /** Space before the first and after the last band, in steps. Defaults to `0`. */\n paddingOuter?: number\n /** Where leftover space goes: `0` start, `0.5` center, `1` end. Defaults to `0.5`. */\n align?: number\n}\n\n/** Discrete scale splitting a range into equal bands, one per category. */\nexport interface BandScale {\n /** Start of the band for `key`, or `undefined` for unknown keys. */\n (key: BandKey): number | undefined\n readonly domain: readonly BandKey[]\n readonly range: readonly [number, number]\n /** Width of a single band. */\n readonly bandwidth: number\n /** Distance between the starts of adjacent bands. */\n readonly step: number\n /** Start of the band at `index`. */\n at(index: number): number\n /** Center of the band for `key`. */\n center(key: BandKey): number | undefined\n /** Index of the band nearest to `pixel` (for hit testing), or `-1` when empty. */\n indexAt(pixel: number): number\n}\n\n/**\n * Create a band scale, e.g. for bar charts.\n *\n * ```ts\n * const x = band(['Jan', 'Feb', 'Mar'], [0, 300], { paddingInner: 0.2 })\n * x('Feb') // start of the \"Feb\" band\n * x.bandwidth // bar width\n * ```\n */\nexport function band(\n domain: readonly BandKey[],\n range: readonly [number, number],\n options: BandScaleOptions = {},\n): BandScale {\n const { paddingInner = 0, paddingOuter = 0, align = 0.5 } = options\n const inner = Math.min(1, Math.max(0, paddingInner))\n const n = domain.length\n const [r0, r1] = range\n const reverse = r1 < r0\n const lo = reverse ? r1 : r0\n const hi = reverse ? r0 : r1\n\n const step = (hi - lo) / Math.max(1, n - inner + paddingOuter * 2)\n const start = lo + (hi - lo - step * (n - inner)) * align\n const bandwidth = step * (1 - inner)\n\n const index = new Map<BandKey, number>()\n for (let i = 0; i < n; i++) {\n const key = domain[i] as BandKey\n if (!index.has(key)) index.set(key, i)\n }\n\n const at = (i: number): number => start + step * (reverse ? n - 1 - i : i)\n\n const scale = (key: BandKey): number | undefined => {\n const i = index.get(key)\n return i === undefined ? undefined : at(i)\n }\n\n return Object.assign(scale, {\n domain: domain.slice(),\n range: [r0, r1] as const,\n bandwidth,\n step,\n at,\n center(key: BandKey): number | undefined {\n const px = scale(key)\n return px === undefined ? undefined : px + bandwidth / 2\n },\n indexAt(pixel: number): number {\n if (n === 0) return -1\n const raw = step === 0 ? 0 : Math.round((pixel - start - bandwidth / 2) / step)\n const i = Math.min(n - 1, Math.max(0, raw))\n return reverse ? n - 1 - i : i\n },\n })\n}\n\n/**\n * Create a point scale: a band scale with zero-width bands, placing each\n * category on a single point (e.g. line charts over labels).\n * `padding` is the space before the first and after the last point, in steps.\n */\nexport function point(\n domain: readonly BandKey[],\n range: readonly [number, number],\n options: { padding?: number; align?: number } = {},\n): BandScale {\n const { padding = 0, align } = options\n return band(domain, range, {\n paddingInner: 1,\n paddingOuter: padding,\n ...(align === undefined ? {} : { align }),\n })\n}\n","/**\n * Minimum and maximum of `values`, skipping `null`, `undefined` and\n * non-finite numbers. Returns `undefined` when nothing is left.\n */\nexport function extent(values: Iterable<number | null | undefined>): [number, number] | undefined {\n let min = Number.POSITIVE_INFINITY\n let max = Number.NEGATIVE_INFINITY\n for (const value of values) {\n if (value == null || !Number.isFinite(value)) continue\n if (value < min) min = value\n if (value > max) max = value\n }\n return min <= max ? [min, max] : undefined\n}\n","import { niceDomain, ticks } from './ticks.ts'\n\nexport interface LinearScaleOptions {\n /** Clamp output to the range (and `invert()` output to the domain). */\n clamp?: boolean\n}\n\n/** Continuous scale mapping a numeric domain to a pixel range. */\nexport interface LinearScale {\n (value: number): number\n readonly domain: readonly [number, number]\n readonly range: readonly [number, number]\n /** Map a pixel back to a domain value. */\n invert(pixel: number): number\n /** Nice tick values inside the domain. */\n ticks(count?: number): number[]\n /** A copy of the scale with its domain extended to round values. */\n nice(count?: number): LinearScale\n}\n\n/**\n * Create a linear scale.\n *\n * ```ts\n * const y = linear([0, 120], [300, 0]).nice()\n * y(60) // 150\n * ```\n *\n * A zero-width domain (e.g. a single data point) maps to the middle of the range.\n */\nexport function linear(\n domain: readonly [number, number],\n range: readonly [number, number],\n options: LinearScaleOptions = {},\n): LinearScale {\n const [d0, d1] = domain\n const [r0, r1] = range\n const span = d1 - d0\n const k = span === 0 ? 0 : (r1 - r0) / span\n const mid = (r0 + r1) / 2\n const { clamp = false } = options\n const rMin = Math.min(r0, r1)\n const rMax = Math.max(r0, r1)\n const dMin = Math.min(d0, d1)\n const dMax = Math.max(d0, d1)\n\n const scale = (value: number): number => {\n if (span === 0) return mid\n const px = r0 + (value - d0) * k\n return clamp ? Math.min(rMax, Math.max(rMin, px)) : px\n }\n\n return Object.assign(scale, {\n domain: [d0, d1] as const,\n range: [r0, r1] as const,\n invert(pixel: number): number {\n if (span === 0 || r1 === r0) return d0\n const value = d0 + (pixel - r0) / k\n return clamp ? Math.min(dMax, Math.max(dMin, value)) : value\n },\n ticks(count?: number): number[] {\n return ticks(d0, d1, count)\n },\n nice(count?: number): LinearScale {\n return linear(niceDomain(d0, d1, count), range, options)\n },\n })\n}\n","/**\n * Data from users, APIs and JSON is often not what the types say. Each chart\n * type cleans its data as it comes in, annotations as they render, axis bounds where read\n * (`ChartType.clean`): numbers\n * that are not finite become gaps, names become text, colors that are not\n * strings are dropped, and lists or records of the wrong kind are left out.\n * What is already clean keeps its identity, so large arrays are not copied.\n */\nimport type { Label } from './cartesian.ts'\n\ntype Rec = Record<string, unknown>\n\n/**\n * A number the chart can draw, or `null`: finite and at most 1e300 in size, so\n * spans stay finite; below 1e-300 it is 0, so tick steps do not underflow.\n */\nexport const finite = (v: unknown): number | null =>\n typeof v === 'number' && Math.abs(v) <= 1e300 ? (Math.abs(v) < 1e-300 ? 0 : v) : null\n\n/** A finite number, or `undefined` (an option left out). */\nconst optional = (v: unknown): number | undefined => finite(v) ?? undefined\n\nexport const isRecord = (v: unknown): v is Rec => !!v && typeof v === 'object' && !Array.isArray(v)\n\n/** The array, or an empty one. */\nexport const list = (v: unknown): readonly unknown[] => (Array.isArray(v) ? v : [])\n\n/** Strings as they are, finite numbers as digits, anything else as ''. */\nexport const text = (v: unknown): string =>\n typeof v === 'string' ? v : finite(v) === null ? '' : String(v)\n\n/** A category label: a string, a finite number or a valid date; else ''. */\nexport const label = (v: unknown): Label =>\n typeof v === 'string' || finite(v instanceof Date ? +v : v) !== null ? (v as Label) : ''\n\n/** Values with gaps for anything that is not a finite number (the same array when clean). */\nexport const numbers = (v: unknown): readonly (number | null)[] => {\n const values = list(v)\n return (\n values.every((x) => x == null || finite(x) === x) ? values : values.map(finite)\n ) as readonly (number | null)[]\n}\n\n/** The records of a list, each fixed by `fix`; other items are left out. */\nexport const records = <T>(v: unknown, fix: (r: Rec) => T): T[] => list(v).filter(isRecord).map(fix)\n\n/** What every named item has: text for its name, a string id and color. */\nexport const named = (r: Rec): Rec => ({\n ...r,\n name: text(r.name),\n id: typeof r.id === 'string' ? r.id : undefined,\n color: typeof r.color === 'string' ? r.color : undefined,\n})\n\n/** Labels and series of the cartesian types (line, area, bar, heatmap, radar). */\nexport const cleanSeries = (data: unknown): unknown => {\n const d = isRecord(data) ? data : {}\n return {\n ...d,\n labels: Array.isArray(d.labels) ? d.labels.map(label) : undefined,\n series: records(d.series, (s) => ({\n ...named(s),\n values: numbers(s.values),\n })),\n }\n}\n\n/** Options with their data cleaned by `data` (axis bounds are checked where they are read). */\nexport const cleanData =\n (data: (v: unknown) => unknown) =>\n <O>(options: O): O => ({ ...options, data: data((options as Rec).data) })\n\n/** Slices or rings: records with a finite value (0 when it is not). */\nexport const cleanItems = (data: unknown): unknown =>\n records(data, (r) => ({ ...named(r), value: finite(r.value) ?? 0, max: optional(r.max) }))\n","import type { LegendItem } from '../legend.ts'\nimport type { ClassValue, Props } from '../vnode.ts'\n\n/** What series, slices and rings have in common: a name, and how they look in a legend. */\nexport interface Named {\n name: string\n id?: string\n color?: string\n class?: ClassValue\n hidden?: boolean\n}\n\n/** Stable key of a series, slice or ring: its `id`, or its name. */\nexport const keyOf = (item: Named): string => item.id ?? item.name\n\n/** Legend entries for series, slices or rings, in their order (which is their color slot). */\nexport function legendItems(list: readonly Named[]): LegendItem[] {\n return list.map((entry, index) => {\n const item: LegendItem = { key: keyOf(entry), name: entry.name, index }\n if (entry.color) item.color = entry.color\n if (entry.hidden) item.hidden = true\n return item\n })\n}\n\n/** Attributes of the group of a series, slice or ring in color slot `index`. */\nexport function groupAttrs(item: Named, index: number): Props {\n return {\n key: keyOf(item),\n class: ['tc-series', `tc-series-${index + 1}`, item.class],\n 'data-series': item.name,\n // A map, so values from data cannot inject CSS (see normalizeStyle).\n style: { '--tc-series-color': item.color },\n }\n}\n","import type { DataTable, LegendItem, RenderContext } from '../chart.ts'\nimport { axis, axisSize, bandTicks, linearTicks, type Tick, thinTicks } from '../components/axis.ts'\nimport { grid } from '../components/grid.ts'\nimport { type Features, feature, features } from '../features.ts'\nimport { formatDetail, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n type Rect,\n} from '../layout.ts'\nimport { type BandKey, type BandScale, band, point } from '../scales/band.ts'\nimport { extent } from '../scales/extent.ts'\nimport { type LinearScale, linear } from '../scales/linear.ts'\nimport { niceDomain } from '../scales/ticks.ts'\nimport { type ClassValue, h, type Props, type VNode } from '../vnode.ts'\nimport type { Annotation } from './annotations.ts'\nimport { finite } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** Category label on the x axis. */\nexport type Label = string | number | Date\n\n/** A label as a `key` for keyed rendering (dates by their timestamp). */\nexport const labelKey = (label: Label): string | number =>\n label instanceof Date ? label.getTime() : label\n\n/** One data series. `null` values are gaps. */\nexport interface Series {\n /** Display name (legend, tooltip, accessibility). */\n name: string\n /** One value per label; `null`/`undefined` leaves a gap. */\n values: readonly (number | null | undefined)[]\n /** Stable identity for keyed updates. Defaults to `name`. */\n id?: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /**\n * Dashed line: dash and gap length in pixels, or a full `stroke-dasharray`\n * such as `'6 3'`. Sets `--tc-series-dash` on the series group; values\n * that could inject CSS are ignored, as for `color`.\n */\n dash?: number | string\n /** Line width in pixels; overrides `--tc-stroke-width` via `--tc-series-width`. */\n width?: number\n /**\n * In a `bar` chart, draw this series as a line or a filled area over the\n * bars instead (it is left out of stacks). Needs the line module\n * (`@tabler/charts/line`, or `@tabler/charts`). Defaults to `'bar'`.\n */\n type?: 'bar' | 'line' | 'area'\n /** Extra classes on the series group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface CartesianData {\n /** Categories along x. Defaults to `1…n` for the longest series. */\n labels?: readonly Label[]\n series: readonly Series[]\n}\n\n/** Options for the value (y) axis. */\nexport interface ValueAxisOptions {\n /** Render the axis labels. Defaults to `true`. */\n show?: boolean\n /** Render horizontal grid lines. Defaults to `true`. */\n grid?: boolean\n /** Fixed lower bound; overrides data and `zero`. */\n min?: number\n /** Fixed upper bound. */\n max?: number\n /** Include zero in the domain. */\n zero?: boolean\n /** Extend the domain to round tick values. Defaults to `true`. */\n nice?: boolean\n /** Approximate tick count. Defaults to one per ~60px of height. */\n ticks?: number\n format?: NumberFormat\n /** `'log'` for a logarithmic axis (positive values only). Defaults to `'linear'`. */\n scale?: 'linear' | 'log'\n}\n\n/** Options for the category (x) axis. */\nexport interface CategoryAxisOptions {\n /** Render the axis labels. Defaults to `true`. */\n show?: boolean\n /** Render vertical grid lines. Defaults to `false`. */\n grid?: boolean\n /** Draw the axis line along the bottom edge. Defaults to `false`. */\n line?: boolean\n /** Format a label for display (axis ticks for categories, tooltips and the table). */\n format?: (label: Label, index: number) => string\n /**\n * `'time'` treats labels as dates or timestamps: line and area charts place\n * points at their real distance in time, with calendar-aware ticks.\n * Labels must be in ascending order. Needs `@tabler/charts/time` (included\n * in `@tabler/charts`; candlesticks label dates without it). Defaults to `'category'`.\n */\n type?: 'category' | 'time'\n /** Align time ticks to UTC instead of local time (use it for SSR). */\n utc?: boolean\n}\n\nexport interface CartesianOptions {\n data: CartesianData\n y?: ValueAxisOptions\n x?: CategoryAxisOptions\n /** Reference lines and bands: targets, normal ranges, events and periods. */\n annotations?: readonly Annotation[]\n /** Extra space around the plot area, in pixels. */\n padding?: InsetsInput\n}\n\nexport interface CartesianLayoutOptions {\n /** `point` places categories on points (lines), `band` on bands (bars). */\n scale: 'point' | 'band'\n /** Values spanning the y domain, when they differ from the raw data (stacks). */\n values?: readonly (number | null | undefined)[]\n /** Format of the value axis ticks, when it differs from `y.format` (percent stacks). */\n tickFormat?: NumberFormat\n /** Default for `y.zero`. */\n zero: boolean\n /** Space marks need beyond the plot edge (point radius, stroke). */\n overhang?: number\n /** Band padding for `scale: 'band'`. */\n paddingInner?: number\n paddingOuter?: number\n}\n\nexport interface CartesianLayout {\n area: Rect\n labels: readonly Label[]\n /** Category scale (along x, or along y when `horizontal`). */\n x: BandScale\n /** Value scale (along y, or along x when `horizontal`). */\n y: LinearScale\n /** Whether categories run along y. */\n horizontal: boolean\n xTicks: Tick[]\n yTicks: Tick[]\n /** Grid lines, drawn below the marks. */\n background: VNode[]\n /** Axes, drawn above the marks. */\n foreground: VNode[]\n /** Clip path definition and its url, for the marks group. */\n clip: { def: VNode; url: string }\n}\n\nexport const TICK_SPACING = 60\n/** Horizontal value axes need more room per label. */\nexport const TICK_SPACING_X = 80\n/** Minimal margin around the plot, in pixels. */\nexport const EDGE = 8\n\n/** Stable key of a series: its `id`, or its name. */\nexport const seriesKey: (series: Series) => string = keyOf\n\n/** Legend entries for series-based charts. */\nexport const seriesLegend = (data: CartesianData): LegendItem[] => legendItems(data.series)\n\n/** Categories from `data.labels`, or `1…n` for the longest series. */\nexport function resolveLabels(data: CartesianData): Label[] {\n if (data.labels) return data.labels.slice()\n const n = Math.max(0, ...data.series.map((s) => s.values.length))\n return Array.from({ length: n }, (_, i) => i + 1)\n}\n\n/**\n * Whether a value can be plotted on the axis: finite, and positive on a log\n * scale (zero and negatives become gaps there).\n */\nexport function plottable(\n value: number | null | undefined,\n axis: ValueAxisOptions | undefined,\n): value is number {\n if (value == null || !Number.isFinite(value)) return false\n return axis?.scale !== 'log' || value > 0\n}\n\n/**\n * Whether the category axis carries time: `x.type === 'time'` and every label\n * is a date, a timestamp or a parseable string. Otherwise the axis falls back\n * to categories instead of producing NaN positions.\n */\nexport const isTimeAxis = (options: CartesianOptions): boolean =>\n options.x?.type === 'time' && resolveLabels(options.data).every((l) => Number.isFinite(toMs(l)))\n\n/** Formatter for category labels in tooltips and tables. */\nexport function labelFormatter(\n options: CartesianOptions,\n ctx: RenderContext,\n): (label: Label, index: number) => string {\n if (options.x?.format) return options.x.format\n if (!isTimeAxis(options)) return (label) => String(label)\n return feature('dates')(resolveLabels(options.data), options.x?.utc, ctx.locale)\n}\n\n/** A label as a timestamp: dates, numbers, or parseable strings (ISO); `NaN` otherwise. */\n// Through Date, so timestamps out of its range are NaN too.\nexport const toMs = (label: Label): number => new Date(label).getTime()\n\n/** Value scale for a domain: linear, or logarithmic with positive-only ticks. */\nexport function valueScale(\n domain: [number, number],\n range: [number, number],\n options: ValueAxisOptions,\n): LinearScale {\n return options.scale === 'log' ? feature('log').scale(domain, range) : linear(domain, range)\n}\n\n/** Ticks of a value scale with labels; log scales format each power as is. */\nexport function valueTicks(\n scale: LinearScale,\n options: ValueAxisOptions,\n count: number,\n format: NumberFormat | undefined,\n locale: RenderContext['locale'],\n): Tick[] {\n return options.scale === 'log'\n ? feature('log').ticks(scale, count, format, locale)\n : linearTicks(scale, { count, format, locale })\n}\n\n/** The point shapes of a chart (`shapes`, or with `patterns: true`), if it has them. */\nexport const markerShape = (options: object): NonNullable<Features['point-shapes']> | undefined => {\n const { shapes, patterns } = options as { shapes?: boolean; patterns?: unknown }\n // On the core, the shapes come with their module (like the points of line charts).\n return (shapes ?? patterns === true) ? features['point-shapes'] : undefined\n}\n\n/** The tick count asked for on an axis (a number up to 100), or `auto`. */\nexport const tickCount = (axis: { ticks?: number } | undefined, auto: number): number =>\n Math.min(finite(axis?.ticks) ?? auto, 100)\n\n/** Y domain from the data and axis options. */\nexport function valueDomain(\n data: CartesianData,\n options: ValueAxisOptions,\n zeroDefault: boolean,\n count: number,\n hidden: ReadonlySet<string> = new Set(),\n override?: readonly (number | null | undefined)[],\n extra: readonly number[] = [],\n): [number, number] {\n // (extra: values to include besides the data, e.g. annotation targets)\n const values =\n override ?? data.series.filter((s) => !hidden.has(seriesKey(s))).flatMap((s) => s.values)\n return domainOf(extra.length ? [...values, ...extra] : values, options, zeroDefault, count)\n}\n\n/** A niced numeric domain for `values`, honouring zero, min, max and nice. */\nexport function domainOf(\n values: readonly (number | null | undefined)[],\n options: ValueAxisOptions,\n zeroDefault: boolean,\n count: number,\n): [number, number] {\n if (options.scale === 'log') return feature('log').domain(values, options)\n // Bounds may come from outside: only numbers count.\n const min = finite(options.min)\n const max = finite(options.max)\n let [lo, hi] = extent(values) ?? [0, 1]\n if (options.zero ?? zeroDefault) {\n lo = Math.min(lo, 0)\n hi = Math.max(hi, 0)\n }\n if (lo === hi) {\n // A flat series still needs a visible range.\n if (lo === 0) {\n hi = 1\n } else {\n const pad = Math.abs(lo) * 0.1\n lo -= pad\n hi += pad\n }\n }\n if (min !== null) lo = min\n if (max !== null) hi = max\n if (options.nice !== false) {\n const [nlo, nhi] = niceDomain(lo, hi, count)\n if (min === null) lo = nlo\n if (max === null) hi = nhi\n }\n return [lo, hi]\n}\n\n/** The annotations feature, when the chart has annotations (it then must be registered). */\nexport function notesFeature(\n options: CartesianOptions,\n): NonNullable<Features['annotations']> | undefined {\n return options.annotations?.length ? feature('annotations') : undefined\n}\n\n/**\n * The category axis of a cartesian layout: the labels at its edges (for the\n * margins), its scale over a pixel range, and its ticks on that scale.\n */\nexport interface CategoryAxis {\n edges: readonly string[]\n scale(range: [number, number]): BandScale\n ticks(scale: BandScale): Tick[]\n /** Pixel position of a date, on time axes (after `scale()`). */\n readonly time?: ((date: Date) => number) | undefined\n}\n\n/**\n * The value axis of a cartesian layout, before the plot area is known: its\n * scale over a pixel range, the ticks of that scale, and `probe`, ticks to\n * measure the labels with (their positions mean nothing). `auto` is the\n * tick count the plot has room for, unless the axis asks for its own.\n */\nexport function valueAxis(\n options: CartesianOptions,\n ctx: RenderContext,\n layout: CartesianLayoutOptions,\n auto: number,\n): {\n scale(range: [number, number]): LinearScale\n ticks(scale: LinearScale): Tick[]\n probe: Tick[]\n} {\n const axis = options.y ?? {}\n const count = tickCount(axis, Math.max(2, auto))\n const domain = valueDomain(\n options.data,\n axis,\n layout.zero,\n count,\n ctx.hidden,\n layout.values,\n notesFeature(options)?.values(options.annotations),\n )\n const format = layout.tickFormat ?? axis.format\n const scale = (range: [number, number]) => valueScale(domain, range, axis)\n const ticks = (of: LinearScale) => valueTicks(of, axis, count, format, ctx.locale)\n return { scale, ticks, probe: ticks(scale([0, 1])) }\n}\n\n/**\n * Finish a layout that has its plot area, scales and ticks with what is\n * drawn around the marks: grid lines and annotation bands below them,\n * annotation lines and the axes above. Values run along y and categories\n * along x, or the other way round when `horizontal`.\n */\nexport function finishLayout(\n options: CartesianOptions,\n ctx: RenderContext,\n overhang: number,\n plot: Omit<CartesianLayout, 'background' | 'foreground' | 'clip'>,\n keys: readonly BandKey[],\n time?: (date: Date) => number,\n): CartesianLayout {\n const { area, x, y, xTicks, yTicks, horizontal: flip } = plot\n const xOptions = options.x ?? {}\n // Annotations: bands under the series, lines above them (and below the axes).\n const notes = notesFeature(options)?.layers(options.annotations, {\n area,\n horizontal: flip,\n fontSize: ctx.fontSize,\n value: y,\n band: x,\n keys,\n time,\n })\n const values = options.y?.show !== false && [\n axis({ position: flip ? 'bottom' : 'left', ticks: yTicks, area }),\n ]\n const categories = ((xOptions.show !== false && plot.labels.length > 0) || xOptions.line) && [\n axis({ position: flip ? 'left' : 'bottom', ticks: xTicks, area, line: xOptions.line === true }),\n ]\n const present = (parts: (VNode | VNode[] | null | false | undefined)[]): VNode[] =>\n parts.flatMap((part) => part || [])\n return {\n ...plot,\n background: present([\n options.y?.grid !== false && grid({ direction: flip ? 'x' : 'y', ticks: yTicks, area }),\n xOptions.grid && grid({ direction: flip ? 'y' : 'x', ticks: xTicks, area }),\n notes?.under,\n ]),\n // The axis on the left first, then the one at the bottom.\n foreground: present([notes?.over, flip ? categories : values, flip ? values : categories]),\n clip: plotClip(ctx, area, overhang),\n }\n}\n\n/** Compute scales, ticks, grid and axes shared by line, area and bar charts. */\nexport function cartesianLayout(\n options: CartesianOptions,\n ctx: RenderContext,\n layout: CartesianLayoutOptions,\n): CartesianLayout {\n const { data } = options\n const yOptions = options.y ?? {}\n const xOptions = options.x ?? {}\n const { fontSize, locale, width, height } = ctx\n const overhang = layout.overhang ?? 0\n const pad = insets(options.padding)\n const labels = resolveLabels(data)\n const format = labelFormatter(options, ctx)\n const showY = yOptions.show !== false\n const showX = xOptions.show !== false && labels.length > 0\n const timed = isTimeAxis(options) && layout.scale === 'point'\n\n const value = valueAxis(options, ctx, layout, Math.round(height / TICK_SPACING))\n const probeY = value.probe\n const countX = Math.max(2, Math.round(width / TICK_SPACING_X))\n const keys = labels.map(labelKey)\n const labelAt = (i: number) => format(labels[i] as Label, i)\n // Time axes (from the time module) place points by date, with calendar ticks.\n const xAxis: CategoryAxis = timed\n ? feature('time').axis(labels, keys, xOptions, countX, locale)\n : {\n // No labels, no edges: a custom format is not asked about a label that is not there.\n edges: labels.length ? [labelAt(0), labelAt(labels.length - 1)] : [],\n scale: (range) =>\n layout.scale === 'point'\n ? point(keys, range)\n : band(keys, range, {\n paddingInner: layout.paddingInner ?? 0.3,\n paddingOuter: layout.paddingOuter ?? 0.15,\n }),\n ticks: (scale) => bandTicks(scale, (_: BandKey, i) => labelAt(i)),\n }\n const edgeLabels = xAxis.edges\n\n // Margins: labels outside the plot, half a line above the top tick,\n // half of the first/last x label for point scales.\n const halfLine = Math.ceil((fontSize * LINE_HEIGHT) / 2)\n const firstLabel = showX ? estimateTextWidth(edgeLabels[0] ?? '', fontSize) : 0\n const lastLabel = showX ? estimateTextWidth(edgeLabels[edgeLabels.length - 1] ?? '', fontSize) : 0\n const edgeX = layout.scale === 'point'\n // On bands a label is centered half a step from the edge: only what is wider\n // than that needs margin (long labels on narrow bands, e.g. dates on candles).\n // The step depends on the margins, so they are worked out twice.\n const valueWidth = showY ? axisSize('left', probeY, fontSize) : 0\n const side = (halfStep: number) => {\n const overflow = (label: number) =>\n edgeX ? Math.ceil(label / 2) : Math.max(0, Math.ceil(label / 2 - halfStep))\n return {\n right: pad.right + Math.max(overflow(lastLabel), overhang, EDGE),\n left: pad.left + Math.max(valueWidth, overflow(firstLabel), overhang, showY ? 0 : EDGE),\n }\n }\n const steps = Math.max(1, labels.length) * 2\n let sides = side((width - pad.left - pad.right - valueWidth) / steps)\n if (!edgeX) sides = side((width - sides.left - sides.right) / steps)\n const margins = {\n top: pad.top + Math.max(showY ? halfLine : 0, overhang, EDGE / 2),\n bottom:\n pad.bottom +\n Math.max(\n // Without an x axis, the lowest value label still needs half a line.\n showX ? axisSize('bottom', [probeY[0] as Tick], fontSize) : showY ? halfLine : 0,\n overhang,\n EDGE / 2,\n ),\n ...sides,\n }\n const area = innerRect(width, height, margins)\n\n const x = xAxis.scale([area.x, area.x + area.width])\n const y = value.scale([area.y + area.height, area.y])\n\n // Nice ticks can outnumber the count asked for: on a short plot, thin them\n // like category labels so none overlap (the grid follows the ticks kept).\n const yTicks = thinTicks(value.ticks(y), 'left', fontSize, 4)\n const xTicks = showX ? thinTicks(xAxis.ticks(x), 'bottom', fontSize) : []\n\n return finishLayout(\n options,\n ctx,\n overhang,\n { area, labels, x, y, horizontal: false, xTicks, yTicks },\n keys,\n xAxis.time,\n )\n}\n\n/** Clip path around the plot area, a little larger so strokes and dots are not cut. */\nexport function plotClip(\n ctx: RenderContext,\n area: Rect,\n overhang: number,\n): CartesianLayout['clip'] {\n const clipId = `${ctx.id}-clip`\n const bleed = overhang + 1\n return {\n def: h(\n 'clipPath',\n { id: clipId },\n h('rect', {\n x: area.x - bleed,\n y: area.y - bleed,\n width: area.width + bleed * 2,\n height: area.height + bleed * 2,\n }),\n ),\n url: `url(#${clipId})`,\n }\n}\n\n/** Attributes shared by every series group. */\nexport function seriesAttrs(series: Series, index: number): Props {\n const { dash, width } = series\n return {\n ...groupAttrs(series, index),\n // A map, so values from data cannot inject CSS (see normalizeStyle).\n style: {\n '--tc-series-color': series.color,\n '--tc-series-dash': Number.isFinite(dash) ? `${dash}px` : dash,\n '--tc-series-width': Number.isFinite(width) ? `${width}px` : undefined,\n },\n }\n}\n\n/** Pixels around the plot area that still count as hovering it. */\nconst HOVER_SLOP = 8\n\n/**\n * Interaction by category: the nearest category to the pointer while it is\n * over the plot area, with every visible series' value there. `anchor`\n * places each value (line point, bar end, and the bar's box); `markAt` names the series of the\n * mark directly under the pointer, if the chart has distinct marks (bars).\n * Labels and values are formatted with `x.format` / `y.format` and the locale.\n */\nexport function categoryInteraction(\n layout: CartesianLayout,\n options: CartesianOptions,\n ctx: RenderContext,\n anchor: (\n seriesIndex: number,\n index: number,\n value: number,\n ) => { x: number; y: number; box?: Rect },\n markAt?: (x: number, y: number, index: number) => number | undefined,\n): Interaction {\n const { area, x, labels, horizontal } = layout\n const { data } = options\n const formatLabel = labelFormatter(options, ctx)\n const formatValue = formatDetail(options.y?.format, ctx.locale)\n\n const hitAt = (index: number): Hit => {\n const start = x.at(index)\n const center = start + x.bandwidth / 2\n const label = labels[index] as Label\n // Where a missing value is anchored: the category center on its axis.\n const empty = horizontal ? { x: area.x, y: center } : { x: center, y: null }\n const items: HitItem[] = []\n data.series.forEach((series, seriesIndex) => {\n if (ctx.hidden.has(seriesKey(series))) return\n const raw = series.values[index]\n const value = plottable(raw, options.y) ? raw : null\n const point = value === null ? empty : anchor(seriesIndex, index, value)\n const item: HitItem = {\n name: series.name,\n seriesIndex,\n value,\n text: value === null ? '–' : formatValue(value),\n ...point,\n }\n if (series.color) item.color = series.color\n items.push(item)\n })\n // Horizontal bars run the categories along y: the hit sits at the plot center on x.\n const hit: Hit = {\n index,\n label: labelKey(label),\n title: formatLabel(label, index),\n x: horizontal ? area.x + area.width / 2 : center,\n area,\n items,\n }\n if (horizontal) {\n hit.y = center\n hit.axis = 'y'\n }\n if (x.bandwidth > 0) {\n hit.band = horizontal\n ? { x: area.x, y: start, width: area.width, height: x.bandwidth }\n : { x: start, y: area.y, width: x.bandwidth, height: area.height }\n }\n return hit\n }\n\n return {\n count: labels.length,\n hitTest(px, py) {\n if (labels.length === 0) return null\n if (\n px < area.x - HOVER_SLOP ||\n px > area.x + area.width + HOVER_SLOP ||\n py < area.y - HOVER_SLOP ||\n py > area.y + area.height + HOVER_SLOP\n ) {\n return null\n }\n const index = x.indexAt(horizontal ? py : px)\n const hit = hitAt(index)\n const mark = markAt?.(px, py, index)\n if (mark !== undefined) hit.seriesIndex = mark\n return hit\n },\n hitIndex(index, seriesIndex) {\n if (index < 0 || index >= labels.length) return null\n const hit = hitAt(index)\n if (seriesIndex !== undefined && hit.items.some((item) => item.seriesIndex === seriesIndex)) {\n hit.seriesIndex = seriesIndex\n }\n return hit\n },\n }\n}\n\n/** Accessible table of series values: one row per category, one column per visible series. */\nexport function seriesTable(\n options: CartesianOptions,\n ctx: RenderContext,\n limit: number = Number.POSITIVE_INFINITY,\n): DataTable {\n const all = resolveLabels(options.data)\n const labels = all.length > limit ? all.slice(0, limit) : all\n const formatLabel = labelFormatter(options, ctx)\n const formatValue = formatDetail(options.y?.format, ctx.locale)\n const series = options.data.series.filter((s) => !ctx.hidden.has(seriesKey(s)))\n return {\n columns: ['', ...series.map((s) => s.name)],\n total: all.length,\n rows: labels.map((label, i) => [\n formatLabel(label, i),\n ...series.map((s) => {\n const v = s.values[i]\n return v == null || !Number.isFinite(v) ? '–' : formatValue(v)\n }),\n ]),\n }\n}\n","import { estimateTextWidth, type Rect, round } from '../layout.ts'\nimport type { BandKey, BandScale } from '../scales/band.ts'\nimport { type ClassValue, h, type VNode } from '../vnode.ts'\nimport { labelKey, toMs } from './cartesian.ts'\nimport { finite, label, records, text } from './clean.ts'\n\n/** A category label, a number, or a date (on a time axis). */\ntype AnnotationLabel = string | number | Date\n\n/**\n * A reference line or band drawn with the series: a target on the value\n * axis (`y: 99.9`), a normal range (`y: [40, 60]`), an event on the category\n * axis (`x: 'Jun'`, or a date on a time axis) or a period (`x: [from, to]`).\n */\nexport interface Annotation {\n /** A line at a value, or a band between two values, on the value axis. */\n y?: number | readonly [number, number]\n /** A line at a category (or a date on a time axis), or a band between two, on the category axis. */\n x?: AnnotationLabel | readonly [AnnotationLabel, AnnotationLabel]\n /** Short text next to the line or inside the band. */\n label?: string\n /** Where the label sits along the line or band. Defaults to `'end'` (right, or top). */\n position?: 'start' | 'end'\n /**\n * Any CSS color; sets `--tc-annotation-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the annotation group. */\n class?: ClassValue\n /** Stable identity for keyed updates. Defaults to the position in the list. */\n id?: string\n}\n\n/** How the layout maps data to pixels for annotations. */\nexport interface AnnotationScales {\n area: Rect\n /** Whether categories run along y (horizontal bars). */\n horizontal: boolean\n fontSize: number\n /** Pixel position of a value along the value axis. */\n value: (v: number) => number\n /** The category scale, and the keys of its categories in order. */\n band: BandScale\n keys: readonly BandKey[]\n /** Pixel position of a date, when the category axis is a time axis. */\n time?: ((date: Date) => number) | undefined\n}\n\n/** Pixel span of a category (or a date on a time axis), or `undefined` if it is not on the axis. */\nfunction categorySpan(\n scales: AnnotationScales,\n label: AnnotationLabel,\n): readonly [number, number] | undefined {\n if (scales.time) {\n const p = scales.time(new Date(toMs(label)))\n return Number.isFinite(p) ? [p, p] : undefined\n }\n const i = scales.keys.indexOf(labelKey(label))\n return i < 0 ? undefined : [scales.band.at(i), scales.band.at(i) + scales.band.bandwidth]\n}\n\n/** A value or a [from, to] pair, cleaned by `f`; `null` when anything is off. */\nconst span = <T>(v: unknown, f: (x: unknown) => T | null): T | readonly T[] | null => {\n if (!Array.isArray(v)) return f(v)\n const pair = v.map(f)\n return pair.length === 2 && !pair.includes(null) ? (pair as T[]) : null\n}\n\n/** Annotations from outside: lines or bands at finite values or labels, with text labels. */\nexport const cleanAnnotations = (v: unknown): Annotation[] | undefined =>\n v === undefined\n ? v\n : (records(v, (a) => ({\n ...a,\n y: a.y === undefined ? a.y : span(a.y, finite),\n x: a.x === undefined ? a.x : span(a.x, label),\n label: a.label == null ? undefined : text(a.label),\n color: typeof a.color === 'string' ? a.color : undefined,\n })).filter((a) => a.y !== null && a.x !== null && (a.x ?? a.y) !== undefined) as Annotation[])\n\nconst isPair = <T>(v: T | readonly [T, T]): v is readonly [T, T] => Array.isArray(v)\n\n/** Values the value axis should include so every annotation shows. */\nexport function annotationValues(annotations: readonly Annotation[] | undefined): number[] {\n const out: number[] = []\n for (const a of cleanAnnotations(annotations) ?? []) {\n if (a.y === undefined) continue\n for (const v of isPair(a.y) ? a.y : [a.y]) if (Number.isFinite(v)) out.push(v)\n }\n return out\n}\n\n/**\n * Annotation layers: bands go below the series, lines and labels above\n * them. Annotations outside the plot area are skipped.\n */\nexport function annotationLayers(\n annotations: readonly Annotation[] | undefined,\n scales: AnnotationScales,\n): { under: VNode | null; over: VNode | null } {\n // Annotations may come from outside (thresholds from an API).\n annotations = cleanAnnotations(annotations)\n if (!annotations?.length) return { under: null, over: null }\n const { area, horizontal, fontSize } = scales\n const bands: VNode[] = []\n const lines: VNode[] = []\n // Plot edges: \"across\" is the axis the annotation spans, \"along\" the one it marks.\n const x0 = area.x\n const x1 = area.x + area.width\n const y0 = area.y\n const y1 = area.y + area.height\n const inside = (p: number, lo: number, hi: number) => p >= lo - 0.5 && p <= hi + 0.5\n const pad = 4\n /**\n * Where an annotation lands: the pixel span it covers within the plot, and\n * whether it runs across x (a vertical line); `undefined` when it is off\n * the plot or names nothing on the axes.\n */\n const geometry = (a: Annotation): { a0: number; a1: number; vertical: boolean } | undefined => {\n let span: readonly [number, number]\n let vertical: boolean\n if (a.y !== undefined) {\n const [from, to] = isPair(a.y) ? a.y : [a.y, a.y]\n if (!Number.isFinite(from) || !Number.isFinite(to)) return undefined\n span = [scales.value(from), scales.value(to)]\n vertical = horizontal\n } else if (a.x !== undefined) {\n const [from, to] = isPair(a.x) ? a.x : [a.x, a.x]\n const start = categorySpan(scales, from)\n const stop = categorySpan(scales, to)\n if (!start || !stop) return undefined\n // A single category: its center; a range: from the start of one to the end of the other.\n span = isPair(a.x)\n ? [Math.min(start[0], stop[0]), Math.max(start[1], stop[1])]\n : [(start[0] + start[1]) / 2, (start[0] + start[1]) / 2]\n vertical = !horizontal\n } else {\n return undefined\n }\n const lo = Math.min(span[0], span[1])\n const hi = Math.max(span[0], span[1])\n const [min, max] = vertical ? [x0, x1] : [y0, y1]\n if (!inside(lo, min, max) && !inside(hi, min, max) && !(lo < min && hi > max)) return undefined\n return { a0: Math.max(lo, min), a1: Math.min(hi, max), vertical }\n }\n const shapes = annotations.map(geometry)\n\n type Box = [number, number, number, number]\n /** Boxes labels keep clear of: the labels placed so far, and every line. */\n const placed: Box[] = []\n const obstacles: [number, Box][] = []\n shapes.forEach((g, i) => {\n if (!g || g.a1 - g.a0 > 0.5) return\n const at = g.a0\n obstacles.push([i, g.vertical ? [at - 1.5, y0, at + 1.5, y1] : [x0, at - 1.5, x1, at + 1.5]])\n })\n const apart = (box: Box, [l, t, r, b]: Box) =>\n box[2] <= l || box[0] >= r || box[3] <= t || box[1] >= b\n const clearOfLabels = (box: Box) => placed.every((p) => apart(box, p))\n const clear = (box: Box, own: number) =>\n clearOfLabels(box) && obstacles.every(([i, l]) => i === own || apart(box, l))\n\n annotations.forEach((a, index) => {\n const key = a.id ?? index\n // Groups are named by axis; the line, band and label inside by what they are.\n const attrs = (part?: string) => ({\n key: part ? `${key}-${part}` : key,\n class: ['tc-annotation', a.y !== undefined ? 'tc-annotation-y' : 'tc-annotation-x', a.class],\n style: { '--tc-annotation-color': a.color },\n })\n const end = a.position !== 'start'\n\n const shape = shapes[index]\n if (!shape) return\n const { a0, a1, vertical } = shape\n\n // Label: candidate spots in order of preference, inside the plot area; the\n // first that covers neither an earlier label nor another line wins (or the first one).\n let label: VNode | false | undefined\n if (a.label) {\n const w = estimateTextWidth(a.label, fontSize * 0.92)\n const line = a1 - a0 <= 0.5\n // [left edge, baseline] of each spot.\n const spots: [number, number][] = []\n if (vertical) {\n // Beside a line or at the start of a band; on the other side if it would\n // run out, and then on the other side anyway, stepping along the line.\n const after = a0 + pad\n const before = line ? a0 - pad - w : Math.max(x0, a1 - pad - w)\n const sides = after + w <= x1 ? [after, before] : [before, after]\n const top = end ? y0 + fontSize : y1 - pad\n const step = (end ? 1 : -1) * fontSize * 1.2\n for (const x of sides) {\n if (x < x0 || x + w > x1) continue\n for (let k = 0; k < 3; k++) spots.push([x, top + k * step])\n }\n if (!spots.length) spots.push([Math.max(x0 + pad, sides[0] as number), top])\n } else {\n // At the preferred end above or below, then at the other end.\n const near = end ? x1 - pad - w : x0 + pad\n const far = end ? x0 + pad : x1 - pad - w\n for (const x of [near, far]) {\n if (line) spots.push([x, a0 - pad], [x, a0 + fontSize])\n else spots.push([x, a0 + fontSize], [x, a1 - pad])\n }\n }\n const box = ([x, y]: [number, number]): Box => [x, y - fontSize, x + w, y + fontSize * 0.25]\n // Nothing free: at least keep off the other labels; a line through text reads better than text on text.\n const spot =\n spots.find((s) => clear(box(s), index)) ??\n spots.find((s) => clearOfLabels(box(s))) ??\n (spots[0] as [number, number])\n placed.push(box(spot))\n label = h(\n 'text',\n { class: 'tc-annotation-label', x: round(spot[0]), y: round(spot[1]) },\n a.label,\n )\n }\n\n if (a1 - a0 > 0.5) {\n // A band below the series; its label goes with the lines, above them.\n const d = vertical\n ? `M${round(a0)},${round(y0)}H${round(a1)}V${round(y1)}H${round(a0)}Z`\n : `M${round(x0)},${round(a0)}H${round(x1)}V${round(a1)}H${round(x0)}Z`\n bands.push(h('g', attrs(), h('path', { class: 'tc-annotation-band', d })))\n if (label) lines.push(h('g', attrs('label'), label))\n return\n }\n // A line across the plot area.\n const at = round(a0)\n lines.push(\n h(\n 'g',\n attrs(),\n h(\n 'line',\n vertical\n ? { class: 'tc-annotation-line', x1: at, x2: at, y1: round(y0), y2: round(y1) }\n : { class: 'tc-annotation-line', x1: round(x0), x2: round(x1), y1: at, y2: at },\n ),\n label,\n ),\n )\n })\n\n return {\n under: bands.length\n ? h('g', { key: 'annotations-under', class: 'tc-annotations', 'aria-hidden': 'true' }, bands)\n : null,\n over: lines.length\n ? h('g', { key: 'annotations-over', class: 'tc-annotations', 'aria-hidden': 'true' }, lines)\n : null,\n }\n}\n","import type { Locale } from '../format.ts'\nimport { formatDate } from '../format.ts'\nimport { type Label, toMs } from './cartesian.ts'\n\n/**\n * Formatter for date labels on a time axis (tooltips, tables, band axes):\n * the date, with the time of day when the labels span less than a few days.\n */\nexport function dateLabels(\n labels: readonly Label[],\n utc: boolean | undefined,\n locale: Locale,\n): (label: Label) => string {\n const first = labels[0]\n const last = labels[labels.length - 1]\n const span = first !== undefined && last !== undefined ? Math.abs(toMs(last) - toMs(first)) : 0\n const withTime = span > 0 && span < 3 * 24 * 60 * 60 * 1000\n const fmt = formatDate(\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n ...(withTime ? { hour: 'numeric', minute: '2-digit' } : {}),\n ...(utc ? { timeZone: 'UTC' } : {}),\n },\n locale,\n )\n return (label) => (Number.isFinite(toMs(label)) ? fmt(toMs(label)) : String(label))\n}\n","import type { LinearScale, LinearScaleOptions } from './linear.ts'\n\nexport interface LogScaleOptions extends LinearScaleOptions {\n /** Logarithm base. Defaults to `10`. */\n base?: number\n}\n\n/**\n * Create a logarithmic scale. The domain must not cross zero: both ends\n * positive (or both negative, mirrored). Same interface as {@link linear},\n * so layouts can use either.\n *\n * ```ts\n * const y = log([1, 10000], [300, 0])\n * y.ticks() // 1, 10, 100, 1000, 10000\n * ```\n */\nexport function log(\n domain: readonly [number, number],\n range: readonly [number, number],\n options: LogScaleOptions = {},\n): LinearScale {\n const base = options.base && options.base > 1 ? options.base : 10\n const clamp = options.clamp === true\n const negative = domain[0] < 0 || domain[1] < 0\n const sign = negative ? -1 : 1\n // Values at or below zero cannot be shown; treat them as the smallest positive step.\n const safe = (v: number): number => Math.max(Number.MIN_VALUE, v * sign)\n const ln = Math.log(base)\n // Exact for the common bases, so powers map to whole numbers.\n const logBase =\n base === 10 ? Math.log10 : base === 2 ? Math.log2 : (v: number) => Math.log(v) / ln\n const transform = (v: number): number => logBase(safe(v))\n const untransform = (t: number): number => sign * base ** t\n const t0 = transform(domain[0])\n const t1 = transform(domain[1])\n const [r0, r1] = range\n const span = t1 - t0\n const k = span === 0 ? 0 : (r1 - r0) / span\n const rMin = Math.min(r0, r1)\n const rMax = Math.max(r0, r1)\n\n const scale = (value: number): number => {\n if (span === 0) return (r0 + r1) / 2\n const px = r0 + (transform(value) - t0) * k\n return clamp ? Math.min(rMax, Math.max(rMin, px)) : px\n }\n\n return Object.assign(scale, {\n domain: [domain[0], domain[1]] as const,\n range: [r0, r1] as const,\n invert(pixel: number): number {\n if (span === 0 || r1 === r0) return domain[0]\n return untransform(t0 + (pixel - r0) / k)\n },\n ticks(count = 5): number[] {\n const lo = Math.min(t0, t1)\n const hi = Math.max(t0, t1)\n if (!Number.isFinite(lo) || !Number.isFinite(hi)) return []\n const first = Math.floor(lo)\n const last = Math.ceil(hi)\n const decades = last - first\n const inside = (v: number) => {\n const t = transform(v)\n return t >= lo - 1e-9 && t <= hi + 1e-9\n }\n let out: number[] = []\n if (decades <= count && Number.isInteger(base)) {\n // Few decades: integer multiples inside each (1, 2, 3 … 9 × 10ⁿ), thinned when crowded.\n const at = (keep: (m: number) => boolean) => {\n const ticks: number[] = []\n for (let p = first; p <= last; p++) {\n for (let m = 1; m < base; m++) {\n const v = sign * m * base ** p\n if (keep(m) && inside(v)) ticks.push(v)\n }\n }\n return ticks\n }\n out = at(() => true)\n if (out.length > count * 2) out = at((m) => m === 1 || m === 2 || m === 5)\n if (out.length > count * 2) out = at((m) => m === 1)\n } else {\n // Many decades: one tick per power (or per few powers).\n const step = Math.max(1, Math.ceil(decades / Math.max(1, count)))\n for (let p = Math.ceil(lo / step) * step; p <= hi + 1e-9; p += step) {\n const v = sign * base ** p\n if (inside(v)) out.push(v)\n }\n }\n return t1 < t0 ? out.reverse() : out\n },\n nice(): LinearScale {\n const lo = untransform(Math.floor(Math.min(t0, t1)))\n const hi = untransform(Math.ceil(Math.max(t0, t1)))\n return log(t1 < t0 ? [hi, lo] : [lo, hi], range, options)\n },\n })\n}\n","import type { Tick } from '../components/axis.ts'\nimport { formatNumber, type Locale, type NumberFormat } from '../format.ts'\nimport { extent } from '../scales/extent.ts'\nimport type { LinearScale } from '../scales/linear.ts'\nimport { log } from '../scales/log.ts'\nimport type { ValueAxisOptions } from './cartesian.ts'\nimport { finite } from './clean.ts'\n\n/** Domain of a log axis: positive values only, niced to whole powers of ten. */\nexport function logDomain(\n values: readonly (number | null | undefined)[],\n options: ValueAxisOptions,\n): [number, number] {\n const positive = values.filter((v): v is number => v != null && v > 0 && Number.isFinite(v))\n let [lo, hi] = extent(positive) ?? [1, 10]\n // Bounds may come from outside: only positive numbers count.\n const min = finite(options.min)\n const max = finite(options.max)\n if (min !== null && min > 0) lo = min\n if (max !== null && max > 0) hi = max\n if (lo === hi) hi = lo * 10\n if (options.nice !== false) {\n const niced = log([lo, hi], [0, 1]).nice().domain\n if (min === null) lo = niced[0]\n if (max === null) hi = niced[1]\n }\n return [lo, hi]\n}\n\n/** Ticks of a log axis, each power formatted as is. */\nexport function logTicks(\n scale: LinearScale,\n count: number,\n format: NumberFormat | undefined,\n locale: Locale,\n): Tick[] {\n const fmt = formatNumber(format, locale)\n return scale.ticks(count).map((value) => ({ value, position: scale(value), label: fmt(value) }))\n}\n","import type { Rect } from './layout.ts'\n\n/** One series' value at a hovered position. */\nexport interface HitItem {\n /** Series name. */\n name: string\n /** Position of the series in `data.series`. */\n seriesIndex: number\n /** Custom series color, if one was set. */\n color?: string\n value: number | null\n /** Value formatted for display (tooltips). */\n text: string\n /** Anchor of the value in chart pixels (point, bar end); `y` is `null` for gaps. */\n x: number\n y: number | null\n /** The mark's rectangle (bar, segment, cell), for value labels inside it. */\n box?: Rect\n}\n\n/** What lies under the pointer. */\nexport interface Hit {\n /** Category index. */\n index: number\n /** Category label. */\n label: string | number\n /** Label formatted for display (tooltips). */\n title: string\n /** Anchor x of the category in chart pixels (for crosshairs and tooltips); the plot center for horizontal bars. */\n x: number\n /** Plot area, in chart pixels. */\n area: Rect\n /** Axis the categories run along; `'y'` for horizontal bars. Defaults to `'x'`. */\n axis?: 'x' | 'y'\n /** Center of the category along y, when categories run along y. */\n y?: number\n /** The category's band in chart pixels, for band scales (bars). */\n band?: { x: number; y: number; width: number; height: number }\n /** Every series' value at this category. */\n items: HitItem[]\n /** Series of the mark directly under the pointer (e.g. a bar), if any. */\n seriesIndex?: number\n /**\n * The crosshair segment, when it is not vertical across the plot (a radar\n * spoke). Tooltips from the keyboard then anchor on the value itself.\n */\n guide?: { x1: number; y1: number; x2: number; y2: number }\n /**\n * A shape to highlight instead of a crosshair or band (e.g. a halo around a\n * pie slice): path data `d`, drawn translated by `x` / `y`.\n */\n mark?: { d: string; x: number; y: number }\n}\n\n/** Maps a point in chart pixels to what lies there. */\nexport type HitTester = (x: number, y: number) => Hit | null\n\n/** How a rendered chart answers pointer and keyboard interaction. */\nexport interface Interaction {\n /** What lies at a point in chart pixels. */\n hitTest: HitTester\n /** The hit for a category by index (keyboard navigation), optionally focused on a series. */\n hitIndex(index: number, seriesIndex?: number): Hit | null\n /** Number of categories. */\n count: number\n}\n\n/** Identity of a hit, used to emit hover changes only when it changes. */\nexport function hitKey(hit: Hit | null): string {\n return hit ? `${hit.index}:${hit.seriesIndex ?? ''}` : ''\n}\n\n/**\n * Convert a pointer position to chart pixels, accounting for the SVG being\n * scaled by CSS (e.g. `max-width: 100%`).\n */\nexport function toChartPoint(\n svg: Element,\n clientX: number,\n clientY: number,\n width: number,\n height: number,\n): { x: number; y: number } {\n const rect = svg.getBoundingClientRect()\n const sx = rect.width > 0 ? width / rect.width : 1\n const sy = rect.height > 0 ? height / rect.height : 1\n return { x: (clientX - rect.left) * sx, y: (clientY - rect.top) * sy }\n}\n","import { h, type VNode } from './vnode.ts'\n\n/** One legend entry: a series (or a slice, for part-to-whole charts). */\nexport interface LegendItem {\n /** Stable identity, used to toggle it. */\n key: string\n name: string\n /** Color slot: the entry wears `.tc-series-{index + 1}`. */\n index: number\n /** Custom color overriding the slot. */\n color?: string\n /** Hidden by default (e.g. `series.hidden`). */\n hidden?: boolean\n}\n\nexport interface LegendOptions {\n /** Place the legend above or below the chart. Defaults to `'top'`. */\n position?: 'top' | 'bottom'\n}\n\n/**\n * Legend content: one toggle button per entry. Buttons are native, so they\n * are focusable and work with Enter/Space; `aria-pressed` reflects visibility.\n */\nexport function legendContent(items: readonly LegendItem[], hidden: ReadonlySet<string>): VNode {\n return h(\n 'div',\n { class: 'tc-legend-items' },\n items.map((item) => {\n const off = hidden.has(item.key)\n return h(\n 'button',\n {\n key: item.key,\n type: 'button',\n class: [\n 'tc-legend-item',\n 'tc-series',\n `tc-series-${item.index + 1}`,\n off && 'tc-legend-item-hidden',\n ],\n style: { '--tc-series-color': item.color },\n 'aria-pressed': off ? 'false' : 'true',\n 'data-key': item.key,\n },\n h('span', { class: 'tc-legend-swatch', 'aria-hidden': 'true' }),\n h('span', { class: 'tc-legend-name' }, item.name),\n )\n }),\n )\n}\n\n/** Keys hidden by default, from the entries' own `hidden` flags. */\nexport function defaultHidden(items: readonly LegendItem[]): Set<string> {\n return new Set(items.filter((item) => item.hidden).map((item) => item.key))\n}\n","/** Valid XML-ish tag and attribute names; anything else is skipped by renderers. */\nconst NAME_RE = /^[a-zA-Z_][\\w:.-]*$/\n\n/** Inline event handler attributes (`onclick`, `onLoad`…) are never rendered. */\nconst EVENT_RE = /^on/i\n\n/** Whether a tag name is safe to render. */\nexport function isValidTag(name: string): boolean {\n return NAME_RE.test(name)\n}\n\n/** Whether an attribute name is safe to render. */\nexport function isValidAttr(name: string): boolean {\n return NAME_RE.test(name) && !EVENT_RE.test(name)\n}\n","import { features } from '../features.ts'\nimport type { Attrs, Child, VNode } from '../vnode.ts'\nimport { isValidAttr, isValidTag } from './attrs.ts'\n\nexport const SVG_NS = 'http://www.w3.org/2000/svg'\nconst HTML_NS = 'http://www.w3.org/1999/xhtml'\n\n/** VNode each rendered DOM node was last patched with. */\nexport const rendered: WeakMap<Node, Child> = /* @__PURE__ */ new WeakMap<Node, Child>()\n\n/** Root element rendered into each container. */\nconst roots = /* @__PURE__ */ new WeakMap<Element, Element>()\n\n/**\n * Render a VNode tree into `container`.\n *\n * The first call mounts the tree; later calls patch the existing DOM in place,\n * reusing nodes matched by `key` (or by position for unkeyed children), so CSS\n * transitions on changed attributes keep working. Passing `null` unmounts.\n *\n * The rendered root is appended to `container`; other content of the\n * container is left untouched. On the first call, `replace` names an element\n * already in the container (e.g. server-rendered markup) for the root: when\n * it has the root's tag and `@tabler/charts/hydrate` is loaded (it is part\n * of `@tabler/charts`), its nodes are hydrated: reused and patched to the\n * tree, so nothing is re-created and entrance animations do not run again.\n * Otherwise the root takes its place.\n */\nexport function render(\n container: Element,\n vnode: VNode | null,\n replace?: Element | null,\n): Element | null {\n const prev = roots.get(container) ?? (replace?.parentNode === container ? replace : undefined)\n\n if (vnode === null || !isValidTag(vnode.tag)) {\n if (prev) {\n prev.remove()\n roots.delete(container)\n }\n return null\n }\n\n if (prev && canPatch(prev, vnode)) {\n patchElement(prev, vnode)\n roots.set(container, prev)\n return prev\n }\n\n if (prev && features.hydrate?.(prev, vnode, namespaceFor(container, vnode.tag))) {\n roots.set(container, prev)\n return prev\n }\n\n const el = createElement(vnode, namespaceFor(container, vnode.tag), container.ownerDocument)\n if (prev) prev.replaceWith(el)\n else container.appendChild(el)\n roots.set(container, el)\n return el\n}\n\nfunction namespaceFor(parent: Element, tag: string): string {\n if (tag === 'svg') return SVG_NS\n if (parent.namespaceURI === SVG_NS && parent.localName !== 'foreignObject') return SVG_NS\n return HTML_NS\n}\n\nexport function childNamespace(el: Element): string {\n return el.namespaceURI === SVG_NS && el.localName !== 'foreignObject' ? SVG_NS : HTML_NS\n}\n\nexport function createNode(child: Child, ns: string, doc: Document): Node | null {\n if (typeof child === 'string') {\n const text = doc.createTextNode(child)\n rendered.set(text, child)\n return text\n }\n if (!isValidTag(child.tag)) return null\n return createElement(child, child.tag === 'svg' ? SVG_NS : ns, doc)\n}\n\n/**\n * Styles go through the CSSOM: a strict CSP (`style-src` without\n * 'unsafe-inline') blocks style attributes set with setAttribute, not these.\n */\nfunction setAttr(el: Element, name: string, value: string): void {\n if (name === 'style') (el as HTMLElement).style.cssText = value\n else el.setAttribute(name, value)\n}\n\nfunction createElement(vnode: VNode, ns: string, doc: Document): Element {\n const el = doc.createElementNS(ns, vnode.tag)\n const { attrs } = vnode\n for (const name in attrs) {\n if (isValidAttr(name)) setAttr(el, name, String(attrs[name]))\n }\n const childNs = childNamespace(el)\n for (const child of vnode.children) {\n const node = createNode(child, childNs, doc)\n if (node) el.appendChild(node)\n }\n rendered.set(el, vnode)\n return el\n}\n\nfunction canPatch(node: Node, next: Child): boolean {\n const prev = rendered.get(node)\n if (prev === undefined) return false\n if (typeof next === 'string') return typeof prev === 'string'\n return typeof prev !== 'string' && prev.tag === next.tag && prev.key === next.key\n}\n\nfunction patchNode(node: Node, next: Child): void {\n if (typeof next === 'string') {\n if (rendered.get(node) !== next) {\n ;(node as Text).data = next\n rendered.set(node, next)\n }\n return\n }\n patchElement(node as Element, next)\n}\n\nfunction patchElement(el: Element, next: VNode): void {\n const prev = rendered.get(el) as VNode\n if (prev === next) return\n // An arc sweeps to its new angles, setting its `d` itself on the way: the\n // sweep feature then says what is left to patch.\n patchAttrs(el, prev.attrs, features.sweep?.(el, prev, next) ?? next.attrs, true)\n patchChildren(el, next.children)\n rendered.set(el, next)\n}\n\nexport function patchAttrs(el: Element, prev: Attrs, next: Attrs, update = false): void {\n for (const name in next) {\n const value = next[name] as string | number\n if (prev[name] === value || !isValidAttr(name)) continue\n // Where CSS cannot transition `d` (Safari), the morph feature animates it.\n if (update && name === 'd' && features.morph?.(el, String(prev[name] ?? ''), String(value))) {\n continue\n }\n setAttr(el, name, String(value))\n }\n for (const name in prev) {\n if (!(name in next) && isValidAttr(name)) el.removeAttribute(name)\n }\n}\n\nfunction patchChildren(parent: Element, next: Child[]): void {\n if (next.length === 0 && parent.firstChild === null) return\n\n const oldNodes = Array.from(parent.childNodes)\n const keyed = new Map<unknown, Node>()\n const unkeyed: Node[] = []\n\n for (const node of oldNodes) {\n const vnode = rendered.get(node)\n if (vnode === undefined) continue\n if (typeof vnode !== 'string' && vnode.key !== undefined) keyed.set(vnode.key, node)\n else unkeyed.push(node)\n }\n\n // Match new children against existing nodes.\n const matched = new Array<Node | undefined>(next.length)\n const used = new Set<Node>()\n let cursor = 0\n for (let i = 0; i < next.length; i++) {\n const child = next[i] as Child\n let candidate: Node | undefined\n if (typeof child !== 'string' && child.key !== undefined) {\n candidate = keyed.get(child.key)\n } else if (cursor < unkeyed.length) {\n candidate = unkeyed[cursor]\n }\n if (candidate && !used.has(candidate) && canPatch(candidate, child)) {\n matched[i] = candidate\n used.add(candidate)\n if (candidate === unkeyed[cursor]) cursor++\n }\n }\n\n // Remove unmatched nodes first, so placing the rest needs as few moves as possible.\n for (const node of oldNodes) {\n if (!used.has(node)) parent.removeChild(node)\n }\n\n // Patch or create, then place from the end using the next sibling as anchor.\n const ns = childNamespace(parent)\n const doc = parent.ownerDocument\n let anchor: Node | null = null\n for (let i = next.length - 1; i >= 0; i--) {\n const child = next[i] as Child\n let node = matched[i]\n if (node) {\n patchNode(node, child)\n } else {\n node = createNode(child, ns, doc) ?? undefined\n if (!node) continue\n }\n if (node.parentNode !== parent || node.nextSibling !== anchor) {\n parent.insertBefore(node, anchor)\n }\n anchor = node\n }\n}\n","import type { Child, VNode } from '../vnode.ts'\nimport { isValidAttr, isValidTag } from './attrs.ts'\n\nconst SVG_NS = 'http://www.w3.org/2000/svg'\n\nexport interface RenderToStringOptions {\n /**\n * Add `xmlns` to a root `<svg>` that has none, so the output is a valid\n * standalone `.svg` file. Defaults to `true`.\n */\n xmlns?: boolean\n /**\n * Markup context of the root. By default common HTML elements (`div`,\n * `table`, `button`…) render as HTML and everything else as SVG.\n */\n namespace?: 'svg' | 'html'\n}\n\n/** Root tags treated as HTML when no namespace is given. */\nconst HTML_ROOTS = /* @__PURE__ */ new Set([\n 'a',\n 'b',\n 'button',\n 'caption',\n 'div',\n 'em',\n 'i',\n 'label',\n 'li',\n 'ol',\n 'p',\n 'section',\n 'small',\n 'span',\n 'strong',\n 'table',\n 'tbody',\n 'td',\n 'th',\n 'thead',\n 'tr',\n 'ul',\n])\n\n/** HTML elements that never have content and must not get a closing tag. */\nconst VOID = /* @__PURE__ */ new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n])\n\n/**\n * Serialize a VNode tree to markup (SSR, static export): SVG trees as\n * XML-compatible SVG, HTML trees (legend, table, tooltip) as HTML.\n *\n * Empty elements self-close only inside SVG; in HTML they get an explicit\n * closing tag (`<th></th>`), since `<th/>` would open an element there.\n * Text and attribute values are escaped. Invalid tag or attribute names and\n * inline event handlers (`on*`) are dropped, so data coming from chart\n * options can never inject markup or scripts.\n */\nexport function renderToString(node: Child, options: RenderToStringOptions = {}): string {\n if (typeof node === 'string') return escapeText(node)\n const root =\n options.xmlns !== false && node.tag === 'svg' && node.attrs.xmlns === undefined\n ? { ...node, attrs: { xmlns: SVG_NS, ...node.attrs } }\n : node\n const svg = options.namespace ? options.namespace === 'svg' : !HTML_ROOTS.has(node.tag)\n return renderNode(root, svg)\n}\n\nfunction renderNode(node: VNode, parentInSvg: boolean): string {\n const { tag, attrs, children } = node\n if (!isValidTag(tag)) return ''\n const inSvg = parentInSvg || tag === 'svg'\n\n let out = `<${tag}`\n for (const name in attrs) {\n if (!isValidAttr(name)) continue\n out += ` ${name}=\"${escapeAttr(String(attrs[name]))}\"`\n }\n\n if (children.length === 0) {\n if (inSvg) return `${out}/>`\n if (VOID.has(tag.toLowerCase())) return `${out}>`\n }\n\n out += '>'\n // Content of foreignObject is HTML again.\n const childInSvg = inSvg && tag !== 'foreignObject'\n for (const child of children) {\n out += typeof child === 'string' ? escapeText(child) : renderNode(child, childInSvg)\n }\n return `${out}</${tag}>`\n}\n\nconst TEXT_RE = /[&<>]/\nconst ATTR_RE = /[&\"<>]/\nconst TEXT_RE_G = /[&<>]/g\nconst ATTR_RE_G = /[&\"<>]/g\nconst ENTITIES: Record<string, string> = { '&': '&', '<': '<', '>': '>', '\"': '"' }\nconst replaceEntity = (char: string): string => ENTITIES[char] as string\n\n/** Escape text content. */\nexport function escapeText(value: string): string {\n return TEXT_RE.test(value) ? value.replace(TEXT_RE_G, replaceEntity) : value\n}\n\n/** Escape a double-quoted attribute value. */\nexport function escapeAttr(value: string): string {\n return ATTR_RE.test(value) ? value.replace(ATTR_RE_G, replaceEntity) : value\n}\n","/** One `ResizeObserver` shared by every chart on the page. */\n\ntype Listener = (width: number, height: number) => void\n\nconst listeners = /* @__PURE__ */ new WeakMap<Element, Listener>()\n/** Elements observed while in the document. */\nconst seen = /* @__PURE__ */ new WeakSet<Element>()\nlet observer: ResizeObserver | undefined\n\nfunction getObserver(): ResizeObserver | undefined {\n if (observer || typeof ResizeObserver !== 'function') return observer\n observer = new ResizeObserver((entries) => {\n for (const { target, contentRect } of entries) {\n if (target.isConnected) {\n seen.add(target)\n listeners.get(target)?.(contentRect.width, contentRect.height)\n } else if (seen.has(target)) {\n // Taken out of the page without destroy(): stop observing, or the\n // observer would keep the element and its chart in memory for good.\n // `chart.resize()` observes it again if it comes back.\n seen.delete(target)\n observer?.unobserve(target)\n }\n }\n })\n return observer\n}\n\n/**\n * Call `listener` with the content size of `el` whenever it changes.\n * Returns a function that stops observing. No-op where `ResizeObserver`\n * is unavailable (SSR, old browsers). Observing again is harmless.\n */\nexport function observeResize(el: Element, listener: Listener): () => void {\n const ro = getObserver()\n if (!ro) return () => {}\n listeners.set(el, listener)\n ro.observe(el)\n return () => {\n if (listeners.get(el) !== listener) return\n listeners.delete(el)\n ro.unobserve(el)\n }\n}\n","/**\n * Batches work from all charts into a single animation frame. Scheduling the\n * same key twice before the flush runs its latest task once.\n */\n\nconst queue = /* @__PURE__ */ new Map<object, () => void>()\nlet pending = false\n\nconst requestFrame = (callback: () => void): void => {\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(callback)\n else queueMicrotask(callback)\n}\n\n/**\n * Run a task; an error it throws is reported on its own (as an uncaught\n * error, in the console and to `window.onerror`) instead of stopping the\n * tasks of other charts in the same frame.\n */\nexport function run(task: () => void): void {\n try {\n task()\n } catch (error) {\n setTimeout(() => {\n throw error\n })\n }\n}\n\n/** Run `task` in the next frame, replacing any task already queued for `key`. */\nexport function schedule(key: object, task: () => void): void {\n queue.set(key, task)\n if (!pending) {\n pending = true\n requestFrame(flush)\n }\n}\n\n/** Work `flush()` also runs: the idle queue (`idle.ts`), once something uses it. */\nexport const flushHooks: { idle?: () => number } = {}\n\n/** Drop the task queued for `key`, if any. */\nexport function cancel(key: object): void {\n queue.delete(key)\n}\n\n/**\n * Run queued tasks now, idle ones too; returns how many ran. Tasks queued\n * meanwhile run too, but each key only once: a task queued again after it\n * ran (a chart updated from its own `render` handler) waits for the next\n * frame, instead of looping in this one and freezing the page.\n */\nexport function flush(): number {\n pending = false\n let count = 0\n const ran = new Set<object>()\n const later = new Map<object, () => void>()\n // Idle work can schedule frame work in turn.\n do {\n // (A Map also visits what is added while it is walked: tasks queued meanwhile.)\n for (const [key, task] of queue) {\n queue.delete(key)\n if (ran.has(key)) later.set(key, task)\n else {\n ran.add(key)\n run(task)\n count++\n }\n }\n count += flushHooks.idle?.() ?? 0\n } while (queue.size > 0)\n for (const [key, task] of later) schedule(key, task)\n return count\n}\n","import type { DataTable } from './a11y.ts'\nimport type { ValueLabelOptions } from './charts/value-labels.ts'\nimport { feature, features } from './features.ts'\nimport type { Locale, NumberFormat } from './format.ts'\nimport { type Hit, hitKey, type Interaction } from './interaction.ts'\nimport { defaultHidden, type LegendItem, type LegendOptions } from './legend.ts'\nimport type { ChartPlugin, PluginInstance } from './plugin.ts'\nimport type { DownloadOption } from './plugins/download.ts'\nimport { render } from './render/dom.ts'\nimport { renderToString } from './render/string.ts'\nimport { observeResize } from './resize.ts'\nimport { cancel, schedule } from './scheduler.ts'\nimport type { TooltipOptions } from './tooltip.ts'\nimport { type ChildInput, type ClassValue, h, type Props, type VNode } from './vnode.ts'\n\n/** Size and environment a chart type renders into. */\nexport interface RenderContext {\n width: number\n height: number\n /** Font size used to estimate label sizes. */\n fontSize: number\n locale: Locale\n /** Unique, stable prefix for ids inside this chart. */\n id: string\n /** Register how pointer and keyboard map to data (ignored in SSR). */\n onHitTest(interaction: Interaction): void\n /** Keys of legend entries (series) currently hidden. */\n hidden: ReadonlySet<string>\n}\n\n/**\n * A chart type plugin (`line`, `bar`, …). Receives the chart options and\n * returns the content of the root `<svg>`.\n */\nexport interface ChartType<O extends object = object> {\n readonly name: string\n /**\n * Clean options that may come from outside (data, annotations, axis\n * bounds from users, APIs, JSON) into the shape `render()` expects; called\n * as the config comes in, before anything reads it.\n */\n clean?(options: O): unknown\n render(options: O, context: RenderContext): ChildInput\n /** Entries for the legend (series, slices); charts without it get no legend. */\n legend?(options: O): LegendItem[]\n /**\n * The data as a text table, for screen readers and the visible table\n * option. `limit` is the most rows wanted; report the real count in `total`.\n */\n table?(options: O, context: RenderContext, limit: number): DataTable\n /**\n * Whether the chart should be focusable and keyboard-navigable by default\n * (`keyboard` in the config overrides it). Decorative types such as\n * sparklines opt out so a page of stat tiles does not multiply tab stops.\n */\n readonly keyboard?: boolean\n /**\n * How value labels (`valueLabels`) read this chart type, when not as bars\n * or points: `marks: 'slice'` writes each value as its share, inside its\n * slice; `marks: 'cell'` writes it in the middle of its mark. `format`\n * names the number format of the values in the options (by default a label\n * shows the text of the tooltip).\n */\n readonly valueLabels?: {\n marks?: 'slice' | 'cell'\n format?(options: O): NumberFormat | undefined\n }\n}\n\nexport type { DataTable, LegendItem }\n\n/** Options shared by every chart type. */\nexport interface BaseOptions {\n /** Fixed width in pixels. Defaults to the container width. */\n width?: number\n /**\n * Height in pixels, or `'container'` to follow the container's height (the\n * container then needs a height of its own). Defaults to width / aspectRatio.\n */\n height?: number | 'container'\n /** Width to height ratio used when `height` is not set. Defaults to `2`. */\n aspectRatio?: number\n /** Accessible name of the chart. */\n title?: string\n /** Longer accessible description. */\n description?: string\n /** Extra classes on the root `<svg>`. */\n class?: ClassValue\n /** Locale for number and date formatting. Set it explicitly for SSR. */\n locale?: Locale\n /**\n * Font size used to lay out labels. In the browser it is read from the\n * `--tc-font-size` custom property of the container when not set; set it\n * explicitly for SSR so server and client layouts match. Defaults to `12`.\n */\n fontSize?: number\n /** Id prefix; set it explicitly for SSR so server and client ids match. */\n id?: string\n /** Show a tooltip on hover, optionally with custom content. Defaults to `true`. */\n tooltip?: boolean | TooltipOptions\n /** Show a vertical crosshair on hover (point charts). Defaults to `true`. */\n crosshair?: boolean\n /** Show a legend with toggles. Defaults to showing it for two or more entries. */\n legend?: boolean | LegendOptions\n /**\n * Animate entrances and data updates (reduced motion always wins). By\n * default charts animate unless they draw more than 1000 elements (e.g. a\n * scatter of a thousand points), where transitions cost far more frame\n * time than they show; `true` animates those too.\n */\n animate?: boolean\n /**\n * Fill bars, areas, slices, rings and bubbles with patterns (and dash\n * lines), so series do not depend on color alone: `true` always, `'auto'`\n * (the default) only in forced colors (Windows High Contrast), where the\n * colors are gone, `false` never. Needs `@tabler/charts/patterns` on the\n * core (`@tabler/charts` includes it).\n */\n patterns?: boolean | 'auto'\n /**\n * Write the values on the marks: bars at their end, stacked segments,\n * cells and slices inside (slices show their share), lines and points\n * above their last point (`points: 'all'` for every one). Labels that do\n * not fit are left out. Needs `@tabler/charts/value-labels` on the core\n * (`@tabler/charts` includes it).\n */\n valueLabels?: boolean | ValueLabelOptions\n /**\n * Share the hover with the other charts of this group: the category under\n * the pointer is highlighted in all of them (matched by label), with its\n * tooltip. Needs the `sync()` plugin (the `Chart` of `@tabler/charts` has it).\n */\n sync?: string\n /**\n * Give the points of each series a shape of their own (circle, square,\n * triangle, diamond…) in line, radar and scatter charts, so they do not\n * depend on color alone. Defaults to `patterns === true`. Needs\n * `@tabler/charts/point-shapes` on the core (`@tabler/charts` includes it).\n */\n shapes?: boolean\n /**\n * Render the data as an HTML table: visually hidden for screen readers\n * (`true`, the default), shown below the chart (`'visible'`), or not at all.\n * An object sets `visible` and `maxRows` (default 1000; longer data is cut\n * and the caption says so).\n */\n table?: boolean | 'visible' | { visible?: boolean; maxRows?: number }\n /** Make the chart focusable and navigable with arrow keys. Defaults to `true`. */\n keyboard?: boolean\n /**\n * A download menu in the chart's corner: `true` offers PNG and SVG, a list\n * picks the formats (`['png', 'svg', 'jpeg', 'webp']`), an object also\n * sets the file name and the export options. Needs `@tabler/charts/export`\n * imported, and on the core the `download()` plugin (the `Chart` of\n * `@tabler/charts` has it).\n */\n download?: DownloadOption\n /**\n * Extra plugins, installed when the chart is created. The default `Chart`\n * from `@tabler/charts` already includes the built-in ones; the bare `Chart`\n * from `@tabler/charts/core` only runs these.\n */\n plugins?: readonly ChartPlugin[]\n}\n\n/** Full chart configuration: base options, the chart type and its options. */\nexport type ChartConfig<O extends object = object> = BaseOptions & O & { type: ChartType<O> }\n\nexport interface Size {\n width: number\n height: number\n}\n\nconst DEFAULT_WIDTH = 600\nconst DEFAULT_ASPECT_RATIO = 2\nconst DEFAULT_FONT_SIZE = 12\n\nlet uid = 0\nconst nextId = (): string => `tc-${++uid}`\n\n/** Resolve the final pixel size from options and the measured container size. */\nexport function resolveSize(options: BaseOptions, measured?: Partial<Size>): Size {\n const measuredWidth = measured?.width ?? 0\n // (Sizes that are not finite numbers count as not set.)\n const width = Math.max(\n 0,\n Math.round(\n Number.isFinite(options.width)\n ? (options.width as number)\n : measuredWidth > 0\n ? measuredWidth\n : DEFAULT_WIDTH,\n ),\n )\n const ratio =\n options.aspectRatio && options.aspectRatio > 0 ? options.aspectRatio : DEFAULT_ASPECT_RATIO\n const height = Number.isFinite(options.height)\n ? (options.height as number)\n : options.height === 'container' && (measured?.height ?? 0) > 0\n ? (measured?.height as number)\n : width / ratio\n return { width, height: Math.max(0, Math.round(height)) }\n}\n\n/** Run the chart type's `render()` for a config and size. */\nfunction renderContent<O extends object>(\n config: ChartConfig<O>,\n size: Size,\n id: string,\n onHitTest: (interaction: Interaction) => void,\n hidden: ReadonlySet<string>,\n fontSize?: number,\n): ChildInput {\n let found: Interaction | undefined\n const ctx = renderContext(\n config,\n size,\n id,\n (interaction) => {\n found = interaction\n onHitTest(interaction)\n },\n hidden,\n fontSize,\n )\n const content = config.type.render(config, ctx)\n // Optional features finish the content (point shapes, value labels).\n return features.post ? features.post(config as ChartConfig<object>, content, found, ctx) : content\n}\n\n/** Render context for a config and size (also used by plugins such as the data table). */\nexport function renderContext<O extends object>(\n config: ChartConfig<O>,\n size: Size,\n id: string,\n onHitTest: (interaction: Interaction) => void,\n hidden: ReadonlySet<string>,\n measuredFontSize?: number,\n): RenderContext {\n return {\n width: size.width,\n height: size.height,\n fontSize: config.fontSize ?? measuredFontSize ?? DEFAULT_FONT_SIZE,\n locale: config.locale,\n id,\n onHitTest,\n hidden,\n }\n}\n\n/**\n * The config as cleaned by its chart type, without the options that are\n * numbers nothing can be drawn with (NaN, ±Infinity, from a division or a\n * parse gone wrong outside): their defaults apply, as if they were left out.\n */\nfunction cleanData<O extends object>(config: ChartConfig<O>): ChartConfig<O> {\n const out = {\n ...(config.type?.clean ? (config.type.clean(config) as object) : config),\n } as Record<string, unknown>\n for (const key in out) {\n if (typeof out[key] === 'number' && !Number.isFinite(out[key])) delete out[key]\n }\n return out as ChartConfig<O>\n}\n\nfunction assertType(config: ChartConfig<object>): void {\n if (!config.type || typeof config.type.render !== 'function') {\n throw new TypeError('@tabler/charts: `type` must be a chart type such as line.')\n }\n}\n\n/** Legend entries of a config, whether a legend is shown and where. */\nexport interface ResolvedLegend {\n items: LegendItem[]\n show: boolean\n position: 'top' | 'bottom'\n}\n\n/** Legend entries of a config, and whether the legend is shown. */\nexport function resolveLegend<O extends object>(config: ChartConfig<O>): ResolvedLegend {\n const items = config.type.legend?.(config) ?? []\n const option = config.legend\n const show = option === undefined ? items.length >= 2 : option !== false && items.length > 0\n const position = typeof option === 'object' && option.position === 'bottom' ? 'bottom' : 'top'\n return { items, show, position }\n}\n\n/**\n * The chart's accessible name: its `title`, or else the chart type and its\n * legend entries (\"line chart: Visitors, Sign-ups\"), since an image without\n * a name is announced as nothing at all. Set `title` for a name in the\n * page's language.\n */\nexport function chartLabel(config: ChartConfig<object>): string {\n if (config.title) return config.title\n const names = (config.type.legend?.(config) ?? []).map((item) => item.name).filter(Boolean)\n const shown = names.slice(0, 6).join(', ')\n // Screen readers do not care for capitals; a long list of names is cut short.\n return `${config.type.name} chart${names.length ? `: ${shown}${names.length > 6 ? ', …' : ''}` : ''}`\n}\n\n/** Elements beyond which charts skip transitions unless `animate: true`. */\nconst ANIMATION_LIMIT = 1000\n\n/** Number of elements in chart content. */\nconst countNodes = (child: ChildInput): number =>\n Array.isArray(child)\n ? child.reduce((n: number, c: ChildInput) => n + countNodes(c), 0)\n : child && typeof child === 'object'\n ? 1 + countNodes((child as VNode).children)\n : 0\n\n/** Whether a chart renders without transitions: asked to, or too big to animate cheaply. */\nconst isStatic = (config: ChartConfig<object>, content: ChildInput): boolean =>\n config.animate === false || (config.animate !== true && countNodes(content) > ANIMATION_LIMIT)\n\n/** Wrap chart content (and hover layers) in the accessible root `<svg>`. */\nfunction composeChart(\n config: ChartConfig<object>,\n size: Size,\n id: string,\n still: boolean,\n content: ChildInput,\n underlay?: ChildInput,\n overlay?: ChildInput,\n extraAttrs?: Props,\n): VNode {\n const { width, height } = size\n const descId = config.description ? `${id}-desc` : undefined\n const { patterns } = config\n // [class, root style, defs] of the pattern fills, when the chart has them.\n const fills =\n patterns === false\n ? undefined\n : (patterns === true ? feature('patterns') : features.patterns)?.(config, id)\n return h(\n 'svg',\n {\n class: [\n 'tc-chart',\n `tc-chart-${config.type.name}`,\n still && 'tc-static',\n fills?.[0],\n config.class,\n ],\n style: fills?.[1],\n viewBox: `0 0 ${width} ${height}`,\n width,\n height,\n role: 'img',\n // An svg <title> would also show as a native tooltip, so the name is an attribute.\n 'aria-label': chartLabel(config),\n 'aria-describedby': descId,\n ...extraAttrs,\n },\n // Keyed, so their coming and going never shifts the (unkeyed) chart\n // content in the DOM patcher: that would recreate it and restart animations.\n descId && h('desc', { key: 'desc', id: descId }, config.description),\n fills?.[2],\n underlay && h('g', { key: 'hover-under', class: 'tc-hover-layer' }, underlay),\n content,\n overlay && h('g', { key: 'hover-over', class: 'tc-hover-layer' }, overlay),\n )\n}\n\n/**\n * Build the VNode tree of a chart: a pure function of the config and size,\n * shared by the DOM chart and server-side rendering.\n */\nexport function buildChart<O extends object>(\n config: ChartConfig<O>,\n size: Size,\n id: string = config.id ?? 'tc',\n onHitTest: (interaction: Interaction) => void = () => {},\n): VNode {\n assertType(config as ChartConfig<object>)\n config = cleanData(config)\n const hidden = defaultHidden(resolveLegend(config).items)\n const content = renderContent(config, size, id, onHitTest, hidden)\n const base = config as ChartConfig<object>\n return composeChart(base, size, id, isStatic(base, content), content)\n}\n\n/**\n * Render a chart to an SVG string, e.g. on the server.\n *\n * ```ts\n * chartToString({ type: line, data, id: 'sales', locale: 'en-US' }, { width: 600, height: 300 })\n * ```\n */\nexport function chartToString<O extends object>(config: ChartConfig<O>, size: Size): string {\n return renderToString(buildChart(config, size))\n}\n\nexport interface ChartEvents {\n /** A legend entry was toggled (by the user or `toggleSeries()`). */\n 'legend-toggle': { key: string; name: string; index: number; hidden: boolean }\n /** After the chart content rendered into the DOM (not on hover-only updates). */\n render: { size: Size }\n /**\n * The highlighted category (or mark) changed, or its data changed while\n * highlighted. `hit` is `null` when the pointer left the plot.\n */\n hover: { hit: Hit | null; event?: PointerEvent }\n /** A click on the plot. */\n click: { hit: Hit; event: MouseEvent }\n}\n\n/** The name of every chart event, for adapters that pass them all on. */\nexport const chartEvents: readonly (keyof ChartEvents)[] = [\n 'hover',\n 'click',\n 'legend-toggle',\n 'render',\n]\n\ntype Handler<T> = (event: T) => void\n\n/** Where the current highlight came from. */\ntype Source =\n | { kind: 'pointer'; x: number; y: number }\n | { kind: 'index'; index: number; seriesIndex?: number }\n\n/** The output of a chart type, with what it was built for. */\ninterface Content<O extends object> {\n cfg: ChartConfig<O>\n width: number\n height: number\n hidden: string\n fontSize: number | undefined\n content: ChildInput\n /** Whether the content renders without transitions. */\n still: boolean\n}\n\n/** The chart on each element. */\nconst mounted = /* @__PURE__ */ new WeakMap<Element, Chart<object>>()\n\n/**\n * A chart bound to a DOM element: measures its container, renders SVG into\n * it and re-renders on `update()` and resize (batched per animation frame).\n * Features such as the tooltip, the legend and pointer input (`hover` /\n * `click` events, from `pointer()`, which the highlight and tooltip plugins\n * turn on themselves) are plugins; the `Chart` exported by `@tabler/charts`\n * installs the built-in ones.\n *\n * ```ts\n * const chart = new Chart('#sales', { type: line, data })\n * chart.update({ data: next })\n * ```\n */\nexport class Chart<O extends object = object> {\n /** Element the chart renders into. */\n readonly element: Element\n /** Id prefix used for elements inside the chart. */\n readonly id: string\n #cfg: ChartConfig<O>\n /** Container size changes, from the shared ResizeObserver. */\n #onResize = (width: number, height: number): void => {\n // Our own SVG sets the container height unless it follows the container.\n const followsHeight = this.#cfg.height === 'container'\n const changed =\n width !== this.#measured.width || (followsHeight && height !== this.#measured.height)\n this.#measured = { width, height }\n // A hidden container (display: none) measures 0×0: nothing to draw until it shows again.\n if (changed && (width || height)) {\n this.#font = undefined\n this.#markResizing()\n this.#schedule()\n }\n }\n #measured: Partial<Size> = {}\n readonly #handlers = new Map<keyof ChartEvents, Set<Handler<never>>>()\n #unobserve: () => void\n readonly #plugins: PluginInstance[] = []\n #destroyed = false\n #current: Interaction | undefined\n #source: Source | undefined\n #hovered = ''\n #hit: Hit | null = null\n /** Chart type output of the last render, reused while only the highlight changes. */\n #cache: Content<O> | undefined\n #resizeTimer: ReturnType<typeof setTimeout> | undefined\n /** Visibility set by the user, overriding each entry's default. */\n readonly #toggled = new Map<string, boolean>()\n /** Server-rendered svg to take over on the first render, if any. */\n #adopt: Element | null\n /**\n * The measured `--tc-font-size` (`undefined` reads it again). Reading it\n * forces the browser to restyle the page, so new data alone reuses it.\n */\n #font: number | undefined\n\n constructor(\n target: Element | string,\n config: ChartConfig<O>,\n defaultPlugins: readonly ChartPlugin[] = [],\n ) {\n const element = typeof target === 'string' ? document.querySelector(target) : target\n if (!element) throw new Error(`@tabler/charts: element \"${String(target)}\" not found.`)\n // One chart per element: a new one replaces the chart already there.\n mounted.get(element)?.destroy()\n mounted.set(element, this as unknown as Chart<object>)\n this.element = element\n this.#cfg = cleanData(config)\n this.id = config.id ?? nextId()\n this.#adopt = element.querySelector(':scope > svg.tc-chart')\n this.#measure()\n this.#unobserve = observeResize(element, this.#onResize)\n try {\n for (const plugin of [...defaultPlugins, ...(config.plugins ?? [])]) {\n this.#plugins.push(plugin.install(this as unknown as Chart<object>))\n }\n this.render()\n } catch (error) {\n // Nobody gets this chart to destroy it: leave the element as it was found.\n this.destroy()\n throw error\n }\n }\n\n /** Current configuration. */\n get config(): ChartConfig<O> {\n return this.#cfg\n }\n\n /** Size of the last render. */\n get size(): Size {\n // In 'container' height mode, plugins such as the legend take part of the\n // container. Only then: measuring them forces a layout of the page.\n let measured = this.#measured\n if (this.#cfg.height === 'container' && measured.height) {\n let reserved = 0\n for (const plugin of this.#plugins) reserved += plugin.reservedHeight?.() ?? 0\n if (reserved) measured = { ...measured, height: measured.height - reserved }\n }\n return resolveSize(this.#cfg, measured)\n }\n\n /** Font size used by the last render (explicit, measured, or the default). */\n get fontSize(): number {\n return this.#cache?.fontSize ?? this.#cfg.fontSize ?? DEFAULT_FONT_SIZE\n }\n\n /** How pointer and keyboard map to data for the current render. */\n get interaction(): Interaction | undefined {\n return this.#current\n }\n\n /** The highlighted category (hover or keyboard), or `null`. */\n get active(): Hit | null {\n return this.#hit\n }\n\n /**\n * The pointer in chart pixels while it drives the highlight (`undefined`\n * for keyboard highlights). `hitAnchor(chart.active, chart.pointer)` gives\n * where a tooltip belongs either way.\n */\n get pointer(): { x: number; y: number } | undefined {\n const source = this.#source\n return this.#hit && source?.kind === 'pointer' ? { x: source.x, y: source.y } : undefined\n }\n\n /** Whether the highlight comes from the pointer or from `highlightIndex()` (keyboard). */\n get highlightSource(): 'pointer' | 'index' | undefined {\n return this.#hit ? this.#source?.kind : undefined\n }\n\n /**\n * Highlight a category by index (and optionally one series in it), as\n * keyboard navigation does. Returns the hit, or `null` for an invalid index.\n */\n highlightIndex(index: number, seriesIndex?: number): Hit | null {\n const hit = this.#current?.hitIndex(index, seriesIndex) ?? null\n if (!hit) return null\n this.#source = { kind: 'index', index, seriesIndex }\n this.#setHover(hit)\n return hit\n }\n\n /**\n * Highlight what lies at a point in chart pixels, as the pointer does (the\n * `pointer()` plugin calls it). Returns the hit, or `null` for none.\n */\n highlightAt(x: number, y: number, event?: PointerEvent): Hit | null {\n const hit = this.hitTest(x, y)\n this.#source = { kind: 'pointer', x, y }\n this.#setHover(hit, event)\n return hit\n }\n\n /** Remove any highlight. */\n clearHighlight(event?: PointerEvent): void {\n this.#source = undefined\n this.#setHover(null, event)\n }\n\n /**\n * Show or hide a legend entry (series) by key, name or index; toggles when\n * `hidden` is omitted. Re-renders in the next frame.\n */\n toggleSeries(target: string | number, hidden?: boolean): this {\n const { items } = resolveLegend(this.#cfg)\n const item =\n typeof target === 'number'\n ? items.find((entry) => entry.index === target)\n : (items.find((entry) => entry.key === target) ??\n items.find((entry) => entry.name === target))\n if (!item) return this\n const next = hidden ?? !this.#hiddenSet(items).has(item.key)\n this.#toggled.set(item.key, next)\n this.emit('legend-toggle', { key: item.key, name: item.name, index: item.index, hidden: next })\n this.#schedule()\n return this\n }\n\n /** Whether a legend entry is hidden. */\n isHidden(key: string): boolean {\n return this.#hiddenSet(resolveLegend(this.#cfg).items).has(key)\n }\n\n /** Merge `options` into the configuration and re-render in the next frame. */\n update(options: Partial<ChartConfig<O>>): this {\n this.#cfg = cleanData({ ...this.#cfg, ...options })\n // Options such as `class` may change the font size; new data does not.\n for (const key in options) if (key !== 'data') this.#font = undefined\n this.#schedule()\n return this\n }\n\n /**\n * Replace the whole configuration and re-render in the next frame: options\n * left out go back to their defaults (`update()` would keep them).\n */\n setConfig(config: ChartConfig<O>): this {\n this.#cfg = cleanData(config)\n this.#font = undefined\n this.#schedule()\n return this\n }\n\n /** Replace the data and re-render in the next frame. */\n setData(data: O extends { data: infer D } ? D : never): this {\n return this.update({ data } as unknown as Partial<ChartConfig<O>>)\n }\n\n /**\n * Re-measure the container and re-render in the next frame. Call it when a\n * container taken out of the page without `destroy()` comes back.\n */\n resize(): this {\n // A container taken out of the page and put back is observed again.\n if (!this.#destroyed) this.#unobserve = observeResize(this.element, this.#onResize)\n this.#measure()\n this.#font = undefined\n this.#schedule()\n return this\n }\n\n /** Render synchronously now. */\n render(): this {\n if (this.#destroyed) return this\n cancel(this)\n const cfg = this.#cfg\n const config = cfg as ChartConfig<object>\n assertType(config)\n const legend = resolveLegend(cfg)\n const hidden = this.#hiddenSet(legend.items)\n for (const plugin of this.#plugins) plugin.beforeRender?.({ config, legend, hidden })\n const size = this.size\n const { content, stale, changed } = this.#content(size, hidden)\n if (stale) this.#refreshHighlight()\n\n const adopted = this.#adopt\n render(this.element, this.#compose(content, size), adopted)\n this.#adopt = null\n // The server markup was hydrated in place: snap it to the real size and\n // data instead of morphing (the server could not measure the container).\n if (adopted) this.#markResizing()\n\n for (const plugin of this.#plugins)\n plugin.afterRender?.({ config, legend, hidden, size, stale, changed })\n if (stale) this.emit('render', { size })\n return this\n }\n\n /**\n * The chart type's output for the current config, size, hidden series and\n * font size: built again when one of them changed (`stale`; `changed` when\n * it is what the chart shows, not only its size), else the one of the last render.\n */\n #content(\n size: Size,\n hidden: ReadonlySet<string>,\n ): { content: Content<O>; stale: boolean; changed: boolean } {\n const cfg = this.#cfg\n const hiddenKey = [...hidden].sort().join('\\u0000')\n this.#font ??= cfg.fontSize ?? this.#measureFontSize()\n const fontSize = cfg.fontSize ?? this.#font\n\n let cache = this.#cache\n const changed = !cache || cache.cfg !== cfg || cache.hidden !== hiddenKey\n const stale =\n changed ||\n cache?.width !== size.width ||\n cache.height !== size.height ||\n cache.fontSize !== fontSize\n if (!cache || stale) {\n this.#current = undefined\n const content = renderContent(\n cfg,\n size,\n this.id,\n (interaction) => {\n this.#current = interaction\n },\n hidden,\n fontSize,\n )\n cache = {\n cfg,\n width: size.width,\n height: size.height,\n hidden: hiddenKey,\n fontSize,\n content,\n still: isStatic(cfg as ChartConfig<object>, content),\n }\n this.#cache = cache\n }\n return { content: cache, stale, changed }\n }\n\n /** Keep the highlight (and its consumers, like tooltips) in sync with new data or layout. */\n #refreshHighlight(): void {\n const source = this.#source\n if (!source) return\n const next =\n source.kind === 'pointer'\n ? this.hitTest(source.x, source.y)\n : (this.#current?.hitIndex(source.index, source.seriesIndex) ?? null)\n this.#setHover(next, undefined, true, false)\n }\n\n /** The root svg: the content, with the plugins' hover layers and attributes. */\n #compose(content: Content<O>, size: Size): VNode {\n const config = this.#cfg as ChartConfig<object>\n const hit = this.#hit\n const under: ChildInput[] = []\n const over: ChildInput[] = []\n let attrs: Props | undefined\n for (const plugin of this.#plugins) {\n if (hit && plugin.layers) {\n const layer = plugin.layers(hit, config)\n under.push(layer.under)\n over.push(layer.over)\n }\n const extra = plugin.svgAttrs?.(config)\n if (extra) attrs = { ...attrs, ...extra }\n }\n // Hover layers only while something is highlighted (an empty list would still render).\n return composeChart(\n config,\n size,\n this.id,\n content.still,\n content.content,\n under.length ? under : undefined,\n over.length ? over : undefined,\n attrs,\n )\n }\n\n /** What lies at a point in chart pixels, or `null`. */\n hitTest(x: number, y: number): Hit | null {\n return this.#current?.hitTest(x, y) ?? null\n }\n\n /** Subscribe to an event; returns a function that unsubscribes. */\n on<K extends keyof ChartEvents>(name: K, handler: Handler<ChartEvents[K]>): () => void {\n let set = this.#handlers.get(name)\n if (!set) {\n set = new Set()\n this.#handlers.set(name, set)\n }\n set.add(handler as Handler<never>)\n return () => {\n set.delete(handler as Handler<never>)\n }\n }\n\n /** Remove the chart from the DOM and stop observing its container. */\n destroy(): void {\n if (this.#destroyed) return\n this.#destroyed = true\n if (mounted.get(this.element) === (this as never)) mounted.delete(this.element)\n cancel(this)\n clearTimeout(this.#resizeTimer)\n this.#unobserve()\n for (const plugin of this.#plugins) plugin.destroy?.()\n this.#handlers.clear()\n render(this.element, null)\n }\n\n /**\n * Update the highlighted hit: emit `hover` when it changed (or when\n * `force`d after new data) and re-render the hover layers in the next frame.\n */\n #setHover(hit: Hit | null, event?: PointerEvent, force = false, rerender = true): void {\n const key = hitKey(hit)\n if (!force && key === this.#hovered) return\n // After a re-render, only a highlight that is still active is worth repeating.\n if (force && key === '' && this.#hovered === '') return\n this.#hovered = key\n this.#hit = hit\n this.emit('hover', event ? { hit, event } : { hit })\n if (rerender) this.#schedule()\n }\n\n #hiddenSet(items: readonly LegendItem[]): Set<string> {\n const hidden = new Set<string>()\n for (const item of items) {\n if (this.#toggled.get(item.key) ?? item.hidden) hidden.add(item.key)\n }\n return hidden\n }\n\n /** Suspend transitions while the container keeps resizing (see `[data-resizing]` in CSS). */\n #markResizing(): void {\n const svg = this.element.querySelector(':scope > svg.tc-chart')\n if (!svg) return\n svg.setAttribute('data-resizing', '')\n clearTimeout(this.#resizeTimer)\n this.#resizeTimer = setTimeout(() => svg.removeAttribute('data-resizing'), 200)\n }\n\n #schedule(): void {\n if (!this.#destroyed) schedule(this, () => this.render())\n }\n\n /** The `--tc-font-size` in effect on the container, in pixels (browser only). */\n #measureFontSize(): number | undefined {\n if (typeof getComputedStyle !== 'function') return undefined\n const value = Number.parseFloat(\n getComputedStyle(this.element).getPropertyValue('--tc-font-size'),\n )\n return Number.isFinite(value) && value > 0 ? value : undefined\n }\n\n /** Measure the content box, matching what `ResizeObserver` reports. */\n #measure(): void {\n const el = this.element as HTMLElement\n const style = typeof getComputedStyle === 'function' ? getComputedStyle(el) : undefined\n const px = (value: string | undefined) => Number.parseFloat(value ?? '') || 0\n this.#measured = {\n width: el.clientWidth - px(style?.paddingLeft) - px(style?.paddingRight),\n height: el.clientHeight - px(style?.paddingTop) - px(style?.paddingBottom),\n }\n }\n\n /** Call the handlers of an event (plugins emit `click`, for instance). */\n emit<K extends keyof ChartEvents>(name: K, event: ChartEvents[K]): void {\n const set = this.#handlers.get(name)\n if (set) for (const handler of set) (handler as Handler<ChartEvents[K]>)(event)\n }\n}\n","/**\n * Pattern fills, so series do not depend on color alone (color vision\n * deficiency, grayscale print, forced colors). Every legend entry gets an\n * 8×8 tile: its series color with lines or dots in `--tc-pattern-color` (the\n * surface by default) over it, one shape per color slot. The chart root\n * carries `--tc-pattern-{n}: url(#…)` and the slot classes map it to\n * `--tc-series-pattern`, which the stylesheet uses as the fill of bars,\n * areas, slices, rings and bubbles (lines get dashes instead) when\n * `patterns` is `true`, or with `'auto'` (the default) in forced colors.\n */\nimport { type ChartConfig, resolveLegend } from '../chart.ts'\nimport type { LegendItem } from '../legend.ts'\nimport { h, type VNode } from '../vnode.ts'\n\n/** Tile shapes by color slot: lines as strokes, dots as round-capped stubs. */\nconst TILES = [\n // Diagonal /, with the corners filled in so tiles join up.\n 'M-2,2L2,-2M0,8L8,0M6,10L10,6',\n // Dots.\n 'M2,2h.01M6,6h.01',\n // Diagonal \.\n 'M-2,6L2,10M0,0L8,8M6,-2L10,2',\n // Horizontal.\n 'M0,4H8',\n // Cross-hatch.\n 'M0,8L8,0M0,0L8,8',\n // Vertical.\n 'M4,0V8',\n // Grid.\n 'M0,4H8M4,0V8',\n // Dashes.\n 'M1,2H4M5,6H8',\n]\n\n/** Slots with a pattern of their own; series 9+ share the one of the \"other\" color. */\nconst SLOTS = TILES.length\n\n/** The pattern of a slot (0-based): its id suffix and slot class. */\nconst slot = (index: number): [string, string] =>\n index < SLOTS ? [`${index + 1}`, `tc-series-${index + 1}`] : ['other', '']\n\n/** `<pattern>` elements for the legend entries of a chart. */\nexport function patternDefs(items: readonly LegendItem[], id: string): VNode[] {\n const out = new Map<string, VNode>()\n for (const item of items) {\n const [n, cls] = slot(item.index)\n if (out.has(n)) continue\n out.set(\n n,\n h(\n 'pattern',\n {\n key: n,\n id: `${id}-pattern-${n}`,\n class: ['tc-pattern', 'tc-series', cls],\n width: 8,\n height: 8,\n patternUnits: 'userSpaceOnUse',\n // A map, so a color from data cannot inject CSS (see normalizeStyle).\n style: { '--tc-series-color': item.color },\n },\n h('rect', { class: 'tc-pattern-bg', width: 8, height: 8 }),\n h('path', { class: 'tc-pattern-ink', d: TILES[item.index % SLOTS] as string }),\n ),\n )\n }\n return [...out.values()]\n}\n\n/** The `--tc-pattern-{n}` references for the chart root. */\nexport function patternVars(items: readonly LegendItem[], id: string): Record<string, string> {\n const vars: Record<string, string> = {}\n for (const item of items) {\n const [n] = slot(item.index)\n vars[`--tc-pattern-${n}`] = `url(#${id}-pattern-${n})`\n }\n return vars\n}\n\n/**\n * The pattern fills of a chart: its root class (`tc-patterned` with\n * `patterns: true`, `tc-patterns-auto` for forced colors), the root's\n * `--tc-pattern-{n}` references and the `<defs>` with the patterns;\n * `undefined` for a chart without legend entries.\n */\nexport function patternFills(\n config: ChartConfig<object>,\n id: string,\n): [string, Record<string, string>, VNode] | undefined {\n const { items } = resolveLegend(config)\n if (!items.length) return undefined\n return [\n config.patterns === true ? 'tc-patterned' : 'tc-patterns-auto',\n patternVars(items, id),\n h('defs', { key: 'patterns' }, patternDefs(items, id)),\n ]\n}\n","/**\n * Marker shapes, so the points of series do not depend on color alone\n * (color vision deficiency, grayscale print): one shape per color slot,\n * for line, radar and scatter points and the active points of the hover.\n * On with `shapes: true`, and with `patterns: true` unless `shapes` says\n * otherwise. Legend and tooltip swatches take the same shapes in CSS.\n */\nimport type { PostStep } from '../features.ts'\nimport { round } from '../layout.ts'\nimport type { Child, ChildInput, VNode } from '../vnode.ts'\n\n/**\n * Outlines by color slot (0-based), as x, y pairs in units of the radius,\n * sized so the shapes weigh about the same as the circle of slot 0 (and of\n * slots 9 and up).\n */\nconst SHAPES: readonly (readonly number[])[] = [\n [],\n // Square.\n [-0.9, -0.9, 0.9, -0.9, 0.9, 0.9, -0.9, 0.9],\n // Triangle.\n [0, -1.3, 1.2, 0.9, -1.2, 0.9],\n // Diamond.\n [0, -1.3, 1.3, 0, 0, 1.3, -1.3, 0],\n // Triangle, pointing down.\n [-1.2, -0.9, 1.2, -0.9, 0, 1.3],\n // Plus.\n [\n -0.4, -1.2, 0.4, -1.2, 0.4, -0.4, 1.2, -0.4, 1.2, 0.4, 0.4, 0.4, 0.4, 1.2, -0.4, 1.2, -0.4, 0.4,\n -1.2, 0.4, -1.2, -0.4, -0.4, -0.4,\n ],\n // Cross.\n [\n -0.7, -1.2, 0, -0.5, 0.7, -1.2, 1.2, -0.7, 0.5, 0, 1.2, 0.7, 0.7, 1.2, 0, 0.5, -0.7, 1.2, -1.2,\n 0.7, -0.5, 0, -1.2, -0.7,\n ],\n // Star.\n [\n 0, -1.4, 0.32, -0.44, 1.33, -0.43, 0.52, 0.17, 0.82, 1.13, 0, 0.55, -0.82, 1.13, -0.52, 0.17,\n -1.33, -0.43, -0.32, -0.44,\n ],\n]\n\n/** The path of slot `slot`'s marker of radius `r` around (`x`, `y`). */\nexport function markerPath(slot: number, x: number, y: number, r: number): string {\n const shape = SHAPES[slot] ?? []\n if (!shape.length) {\n return `M${round(x - r)},${round(y)}a${r},${r},0,1,0,${2 * r},0a${r},${r},0,1,0,${-2 * r},0Z`\n }\n let d = ''\n for (let i = 0; i < shape.length; i += 2) {\n d += `${i ? 'L' : 'M'}${round(x + (shape[i] as number) * r)},${round(y + (shape[i + 1] as number) * r)}`\n }\n return `${d}Z`\n}\n\n/** The content with the point circles of each series group (`.tc-series-N`) in its slot's shape. */\nfunction reshape(child: ChildInput, slot: number): ChildInput {\n if (Array.isArray(child)) return child.map((c) => reshape(c, slot))\n if (!child || typeof child !== 'object') return child\n const { attrs } = child\n const cls = String(attrs.class ?? '')\n const group = /\\btc-series-(\\d+)\\b/.exec(cls)\n if (\n child.tag === 'circle' &&\n slot >= 0 &&\n /\\btc-point\\b/.test(cls) &&\n !/\\btc-bubble\\b/.test(cls)\n ) {\n const shaped: VNode = {\n tag: 'path',\n attrs: {\n class: `${cls} tc-marker`,\n d: markerPath(slot, +(attrs.cx ?? 0), +(attrs.cy ?? 0), +(attrs.r ?? 0)),\n },\n children: [],\n key: child.key,\n }\n return shaped\n }\n return {\n ...child,\n children: child.children.map((c) => reshape(c, group ? Number(group[1]) - 1 : slot) as Child),\n }\n}\n\n/** The step that gives the points of charts with `shapes` (or `patterns: true`) their shapes. */\nexport const shapesStep: PostStep = (config, content) =>\n (config.shapes ?? config.patterns === true) ? reshape(content, -1) : content\n","import { getDateFormat, type Locale } from '../format.ts'\nimport type { BandKey, BandScale } from './band.ts'\nimport { extent } from './extent.ts'\nimport { tickStep } from './ticks.ts'\n\n/** A point in time: a `Date` or a timestamp in milliseconds. */\nexport type TimeValue = Date | number\n\nexport interface TimeScaleOptions {\n /** Align ticks to UTC instead of local time (use it for SSR). Defaults to `false`. */\n utc?: boolean\n /** Clamp output to the range. */\n clamp?: boolean\n}\n\n/** Continuous scale mapping time to a pixel range, with calendar-aware ticks. */\nexport interface TimeScale {\n (value: TimeValue): number\n readonly domain: readonly [number, number]\n readonly range: readonly [number, number]\n readonly utc: boolean\n /** Map a pixel back to a time. */\n invert(pixel: number): Date\n /** Tick dates at calendar boundaries, roughly `count` of them. */\n ticks(count?: number): Date[]\n /** A formatter suited to the tick interval chosen for `count`. */\n tickFormat(count?: number, locale?: Locale): (date: Date) => string\n /** A copy with the domain extended to tick boundaries. */\n nice(count?: number): TimeScale\n}\n\ntype Unit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'\n\ninterface Interval {\n unit: Unit\n step: number\n /** Approximate duration, for choosing an interval. */\n ms: number\n}\n\nconst SECOND = 1000\nconst MINUTE = 60 * SECOND\nconst HOUR = 60 * MINUTE\nconst DAY = 24 * HOUR\nconst WEEK = 7 * DAY\nconst MONTH = 30 * DAY\nconst YEAR = 365 * DAY\n\nconst INTERVALS: Interval[] = [\n { unit: 'second', step: 1, ms: SECOND },\n { unit: 'second', step: 5, ms: 5 * SECOND },\n { unit: 'second', step: 15, ms: 15 * SECOND },\n { unit: 'second', step: 30, ms: 30 * SECOND },\n { unit: 'minute', step: 1, ms: MINUTE },\n { unit: 'minute', step: 5, ms: 5 * MINUTE },\n { unit: 'minute', step: 15, ms: 15 * MINUTE },\n { unit: 'minute', step: 30, ms: 30 * MINUTE },\n { unit: 'hour', step: 1, ms: HOUR },\n { unit: 'hour', step: 3, ms: 3 * HOUR },\n { unit: 'hour', step: 6, ms: 6 * HOUR },\n { unit: 'hour', step: 12, ms: 12 * HOUR },\n { unit: 'day', step: 1, ms: DAY },\n { unit: 'day', step: 2, ms: 2 * DAY },\n { unit: 'week', step: 1, ms: WEEK },\n { unit: 'month', step: 1, ms: MONTH },\n { unit: 'month', step: 3, ms: 3 * MONTH },\n { unit: 'year', step: 1, ms: YEAR },\n]\n\n/** Calendar arithmetic in local time or UTC. */\nfunction calendar(utc: boolean) {\n const get = (d: Date, unit: Unit): number => {\n switch (unit) {\n case 'year':\n return utc ? d.getUTCFullYear() : d.getFullYear()\n case 'month':\n return utc ? d.getUTCMonth() : d.getMonth()\n case 'day':\n case 'week':\n return utc ? d.getUTCDate() : d.getDate()\n case 'hour':\n return utc ? d.getUTCHours() : d.getHours()\n case 'minute':\n return utc ? d.getUTCMinutes() : d.getMinutes()\n default:\n return utc ? d.getUTCSeconds() : d.getSeconds()\n }\n }\n const make = (y: number, mo: number, d: number, h = 0, mi = 0, s = 0): Date =>\n utc ? new Date(Date.UTC(y, mo, d, h, mi, s)) : new Date(y, mo, d, h, mi, s)\n const weekday = (d: Date): number => (utc ? d.getUTCDay() : d.getDay())\n\n /** Start of the interval containing `date` (weeks start on Monday). */\n const floor = (date: Date, { unit, step }: Interval): Date => {\n const y = get(date, 'year')\n const mo = get(date, 'month')\n const d = get(date, 'day')\n switch (unit) {\n case 'year':\n return make(Math.floor(y / step) * step, 0, 1)\n case 'month':\n return make(y, Math.floor(mo / step) * step, 1)\n case 'week':\n return make(y, mo, d - ((weekday(date) + 6) % 7))\n case 'day':\n return make(y, mo, Math.floor((d - 1) / step) * step + 1)\n case 'hour':\n return make(y, mo, d, Math.floor(get(date, 'hour') / step) * step)\n case 'minute':\n return make(y, mo, d, get(date, 'hour'), Math.floor(get(date, 'minute') / step) * step)\n default:\n return make(\n y,\n mo,\n d,\n get(date, 'hour'),\n get(date, 'minute'),\n Math.floor(get(date, 'second') / step) * step,\n )\n }\n }\n\n /** `date` moved forward by one interval. */\n const next = (date: Date, { unit, step }: Interval): Date => {\n const y = get(date, 'year')\n const mo = get(date, 'month')\n const d = get(date, 'day')\n switch (unit) {\n case 'year':\n return make(y + step, 0, 1)\n case 'month':\n return make(y, mo + step, 1)\n case 'week':\n return make(y, mo, d + 7 * step)\n case 'day': {\n // Day steps restart at the first of each month, so ticks land on the 1st.\n const n = make(y, mo, d + step)\n return get(n, 'month') === mo ? n : make(y, mo + 1, 1)\n }\n case 'hour':\n return make(y, mo, d, get(date, 'hour') + step)\n case 'minute':\n return make(y, mo, d, get(date, 'hour'), get(date, 'minute') + step)\n default:\n return make(y, mo, d, get(date, 'hour'), get(date, 'minute'), get(date, 'second') + step)\n }\n }\n\n /** Whether `date` sits on the boundary of the unit above `unit`. */\n const boundary = (date: Date, unit: Unit): boolean => {\n switch (unit) {\n case 'second':\n return get(date, 'second') === 0\n case 'minute':\n return get(date, 'minute') === 0 && get(date, 'second') === 0\n case 'hour':\n return get(date, 'hour') === 0 && get(date, 'minute') === 0\n case 'day':\n case 'week':\n return get(date, 'day') === 1\n case 'month':\n return get(date, 'month') === 0\n default:\n return false\n }\n }\n\n return { floor, next, boundary }\n}\n\n/** Pick the interval whose duration is closest to `span / count`. */\nfunction chooseInterval(span: number, count: number): Interval {\n const target = Math.abs(span) / Math.max(1, count)\n let i = 0\n while (i < INTERVALS.length && (INTERVALS[i] as Interval).ms < target) i++\n if (i === INTERVALS.length) {\n // Beyond one year: multiples of years.\n const years = Math.max(1, tickStep(0, target / YEAR, 1))\n return { unit: 'year', step: years, ms: years * YEAR }\n }\n if (i === 0) return INTERVALS[0] as Interval\n const lo = INTERVALS[i - 1] as Interval\n const hi = INTERVALS[i] as Interval\n return target / lo.ms < hi.ms / target ? lo : hi\n}\n\nconst toMs = (value: TimeValue): number => (value instanceof Date ? value.getTime() : value)\n\n/** Intl options for each tick unit, and for the boundary of the unit above it. */\nconst FORMATS: Record<Unit, [Intl.DateTimeFormatOptions, Intl.DateTimeFormatOptions | null]> = {\n second: [\n { hour: 'numeric', minute: '2-digit', second: '2-digit' },\n { hour: 'numeric', minute: '2-digit' },\n ],\n minute: [\n { hour: 'numeric', minute: '2-digit' },\n { hour: 'numeric', minute: '2-digit' },\n ],\n hour: [\n { hour: 'numeric', minute: '2-digit' },\n { month: 'short', day: 'numeric' },\n ],\n day: [{ month: 'short', day: 'numeric' }, null],\n week: [{ month: 'short', day: 'numeric' }, null],\n month: [{ month: 'short' }, { year: 'numeric' }],\n year: [{ year: 'numeric' }, null],\n}\n\n/**\n * Create a time scale over `[start, end]`.\n *\n * ```ts\n * const x = time([new Date(2026, 0, 1), new Date(2026, 2, 31)], [0, 600])\n * x.ticks() // first of each month, or every week, depending on the range\n * x.tickFormat() // e.g. \"Jan\", \"Feb\"\n * ```\n */\nexport function time(\n domain: readonly [TimeValue, TimeValue],\n range: readonly [number, number],\n options: TimeScaleOptions = {},\n): TimeScale {\n const utc = options.utc === true\n const d0 = toMs(domain[0])\n const d1 = toMs(domain[1])\n const [r0, r1] = range\n const span = d1 - d0\n const k = span === 0 ? 0 : (r1 - r0) / span\n const cal = calendar(utc)\n const clamp = options.clamp === true\n const rMin = Math.min(r0, r1)\n const rMax = Math.max(r0, r1)\n\n const scale = (value: TimeValue): number => {\n if (span === 0) return (r0 + r1) / 2\n const px = r0 + (toMs(value) - d0) * k\n return clamp ? Math.min(rMax, Math.max(rMin, px)) : px\n }\n\n const interval = (count = 5): Interval => chooseInterval(span, count)\n\n return Object.assign(scale, {\n domain: [d0, d1] as const,\n range: [r0, r1] as const,\n utc,\n invert(pixel: number): Date {\n return new Date(span === 0 || r1 === r0 ? d0 : d0 + (pixel - r0) / k)\n },\n ticks(count = 5): Date[] {\n if (!Number.isFinite(d0) || !Number.isFinite(d1)) return []\n const lo = Math.min(d0, d1)\n const hi = Math.max(d0, d1)\n if (lo === hi) return [new Date(lo)]\n const step = interval(count)\n const out: Date[] = []\n let t = cal.floor(new Date(lo), step)\n if (t.getTime() < lo) t = cal.next(t, step)\n while (t.getTime() <= hi && out.length < 1000) {\n out.push(t)\n t = cal.next(t, step)\n }\n return d1 < d0 ? out.reverse() : out\n },\n tickFormat(count = 5, locale?: Locale): (date: Date) => string {\n const { unit } = interval(count)\n const [primary, above] = FORMATS[unit]\n const tz = utc ? { timeZone: 'UTC' } : {}\n const main = getDateFormat(locale, { ...primary, ...tz })\n const upper = above ? getDateFormat(locale, { ...above, ...tz }) : null\n return (date) => (upper && cal.boundary(date, unit) ? upper : main).format(date)\n },\n nice(count = 5): TimeScale {\n if (span === 0 || !Number.isFinite(span)) return time(domain, range, options)\n const step = interval(count)\n const lo = cal.floor(new Date(Math.min(d0, d1)), step)\n let hi = cal.floor(new Date(Math.max(d0, d1)), step)\n if (hi.getTime() < Math.max(d0, d1)) hi = cal.next(hi, step)\n return time(d1 < d0 ? [hi, lo] : [lo, hi], range, options)\n },\n })\n}\n\n/**\n * A point scale over time for category charts: each category sits at its\n * real distance in time. Conforms to `BandScale` (zero bandwidth), so line\n * and area charts and their hit testing work unchanged. `stamps` must be\n * ascending; `keys` are the categories' keys.\n */\nexport function timePointScale(\n stamps: readonly number[],\n keys: readonly BandKey[],\n range: readonly [number, number],\n utc: boolean,\n): { scale: BandScale; time: TimeScale } {\n // Spreading large arrays into Math.min/max overflows the stack, so scan.\n const [lo, hi] = extent(stamps) ?? [0, 1]\n const valid = stamps.filter((t) => Number.isFinite(t))\n const t = time([lo, hi], range, { utc })\n const positions = stamps.map((ms) => t(ms))\n const at = (i: number): number => positions[i] ?? range[0]\n const scale = Object.assign((key: BandKey) => positions[keys.indexOf(key)], {\n domain: keys.slice(),\n range,\n bandwidth: 0,\n step: valid.length > 1 ? (range[1] - range[0]) / (valid.length - 1) : 0,\n at,\n center: (key: BandKey) => positions[keys.indexOf(key)],\n indexAt(pixel: number): number {\n // Stamps are sorted, so the nearest position is found by binary search.\n if (positions.length === 0) return -1\n let a = 0\n let b = positions.length - 1\n while (a < b) {\n const mid = (a + b) >> 1\n if ((positions[mid] as number) < pixel) a = mid + 1\n else b = mid\n }\n const prev = a - 1\n return prev >= 0 && pixel - (positions[prev] as number) < (positions[a] as number) - pixel\n ? prev\n : a\n },\n })\n return { scale: scale as BandScale, time: t }\n}\n","import type { Tick } from '../components/axis.ts'\nimport type { Locale } from '../format.ts'\nimport type { BandKey } from '../scales/band.ts'\nimport { type TimeScale, timePointScale } from '../scales/time.ts'\nimport { type CategoryAxis, type CategoryAxisOptions, type Label, toMs } from './cartesian.ts'\n\n/**\n * A time category axis: points at their real distance in time, ticks on\n * calendar boundaries labelled for the span (or with `x.format`).\n */\nexport function timeAxis(\n labels: readonly Label[],\n keys: readonly BandKey[],\n options: CategoryAxisOptions,\n count: number,\n locale: Locale,\n): CategoryAxis {\n const stamps = labels.map(toMs)\n const points = (range: readonly [number, number]) =>\n timePointScale(stamps, keys, range, options.utc === true)\n const probe = points([0, 1]).time\n const { format } = options\n const label = format ? (d: Date) => format(d, -1) : probe.tickFormat(count, locale)\n let time: TimeScale = probe\n return {\n // Time ticks come from the scale; their labels are what sits at the edges.\n edges: probe.ticks(count).map(label),\n scale(range) {\n const scaled = points(range)\n time = scaled.time\n return scaled.scale\n },\n ticks: (): Tick[] =>\n time.ticks(count).map((d) => ({ value: d.getTime(), position: time(d), label: label(d) })),\n get time() {\n return time\n },\n }\n}\n","/**\n * Value labels: the value written on each mark, for charts read at a\n * glance. They are worked out from the chart's interaction, so every type\n * gets them the same way: bars at their end (inside when there is no room\n * outside), stacked segments and heatmap cells in their middle, lines and\n * points above their point (the last one by default), slices in their\n * middle with their share. A label that does not fit its mark or the plot,\n * or that would cover another one, is left out: labels never overlap.\n */\nimport type { ChartConfig, RenderContext } from '../chart.ts'\nimport type { PostStep } from '../features.ts'\nimport { formatNumber, getNumberFormat, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { estimateTextWidth, type Rect, round } from '../layout.ts'\nimport { h, type VNode } from '../vnode.ts'\n\nexport interface ValueLabelOptions {\n /** Format of the values. Defaults to the value axis format (slices: their share in percent). */\n format?: NumberFormat\n /** Which points of lines, areas and scatters get a label. Defaults to `'last'`. */\n points?: 'last' | 'all'\n}\n\n/** Space between a mark and its label, and around labels. */\nconst GAP = 4\n\ninterface Placed {\n key: string\n text: string\n x: number\n y: number\n inside: boolean\n box: Rect\n}\n\nconst overlaps = (a: Rect, b: Rect): boolean =>\n a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height\n\nconst contains = (outer: Rect, inner: Rect): boolean =>\n inner.x >= outer.x - 1 &&\n inner.y >= outer.y - 1 &&\n inner.x + inner.width <= outer.x + outer.width + 1 &&\n inner.y + inner.height <= outer.y + outer.height + 1\n\n/** The labels layer of a chart, or `null` when nothing gets one. */\nexport function valueLabels(\n config: ChartConfig<object>,\n interaction: Interaction,\n ctx: RenderContext,\n): VNode | null {\n const option = config.valueLabels\n const options: ValueLabelOptions = typeof option === 'object' ? option : {}\n const { fontSize, locale } = ctx\n // What the chart type says about its marks (slices, cells) and its number format.\n const spec = config.type.valueLabels\n const pie = spec?.marks === 'slice'\n const cell = spec?.marks === 'cell'\n const stacked = !!(config as { stacked?: unknown }).stacked\n const format = options.format\n ? formatNumber(options.format, locale)\n : pie\n ? (v: number) =>\n getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 }).format(v)\n : spec?.format\n ? formatNumber(spec.format(config), locale)\n : undefined\n // Numbers have no descenders: one em is their height, with room to spare.\n const height = fontSize\n\n // Candidates in order of priority: every hit's items, and for points only the\n // last one of each series unless all are asked for.\n const items: [string, HitItem, Hit][] = []\n const last = new Map<number, number>()\n let total = 0\n for (let i = 0; i < interaction.count; i++) {\n const hit = interaction.hitIndex(i)\n for (const item of hit?.items ?? []) {\n if (item.value === null || item.y === null || !hit) continue\n total += Math.abs(item.value)\n if (!pie && !item.box && options.points !== 'all') last.set(item.seriesIndex, items.length)\n items.push([`${i}-${item.seriesIndex}`, item, hit])\n }\n }\n\n // Marks a label must not cover: every bar and cell but its own.\n const marks = items.flatMap(([, item]) => (item.box ? [item.box] : []))\n const placed: Placed[] = []\n items.forEach(([key, item, hit], n) => {\n const { area } = hit\n if (!pie && !item.box && options.points !== 'all' && last.get(item.seriesIndex) !== n) return\n const value = item.value as number\n const share = value / (total || 1)\n const text = format ? format(pie ? share : value) : item.text\n const width = estimateTextWidth(text, fontSize)\n const at = (x: number, y: number, inside: boolean): Placed => {\n // A point's label at the plot's edge (the last point) moves in.\n if (!item.box && !pie) {\n x = Math.max(area.x + width / 2 + 2, Math.min(x, area.x + area.width - width / 2 - 2))\n }\n return {\n key,\n text,\n x,\n y,\n inside,\n box: { x: x - width / 2 - 2, y: y - height / 2, width: width + 4, height },\n }\n }\n const y = item.y as number\n const candidates: Placed[] = []\n const { box } = item\n if (pie) {\n candidates.push(at(item.x, y, true))\n } else if (box) {\n const horizontal = hit.axis === 'y'\n const down = value < 0\n if (!stacked && !cell) {\n // Beyond the bar's end, then just inside it.\n const reach = (horizontal ? width / 2 : height / 2) + GAP\n const sign = down ? 1 : -1\n const along = y + sign * reach\n candidates.push(\n horizontal ? at(item.x - sign * reach, y, false) : at(item.x, along, false),\n // A label wider than its bar may lean off a taller neighbour.\n ...(horizontal\n ? []\n : [\n at(box.x + width / 2 - 3, along, false),\n at(box.x + box.width - width / 2 + 3, along, false),\n ]),\n horizontal ? at(item.x + sign * reach, y, true) : at(item.x, y - sign * reach, true),\n )\n } else {\n candidates.push(at(box.x + box.width / 2, box.y + box.height / 2, true))\n }\n } else {\n // Above the point, below it, or beside it (the end of a line, at the plot's edge).\n const side = width / 2 + GAP + 4\n candidates.push(\n at(item.x, y - height / 2 - GAP - 2, false),\n at(item.x, y + height / 2 + GAP + 2, false),\n at(item.x - side, y, false),\n at(item.x + side, y, false),\n )\n }\n // Labels may rise into the margin above the plot, not over the axes.\n const room = { ...area, y: 0, height: area.y + area.height }\n // Glyphs leave a little room at their sides (`slim`): a label may brush a neighbour.\n const fits = (p: Placed, slim = { ...p.box, x: p.box.x + 5, width: p.box.width - 10 }) =>\n contains(pie ? area : room, p.box) &&\n (!p.inside || !box || contains(box, p.box)) &&\n (!pie || sliceFits(item, area, share, p.box)) &&\n !placed.some((other) => overlaps(other.box, p.box)) &&\n !marks.some((mark) => mark !== box && overlaps(mark, slim))\n const spot = candidates.find((p) => fits(p))\n if (spot) placed.push(spot)\n })\n\n if (!placed.length) return null\n return h(\n 'g',\n { key: 'value-labels', class: 'tc-value-labels', 'aria-hidden': 'true' },\n placed.map((p) =>\n h(\n 'text',\n {\n key: p.key,\n class: ['tc-value-label', p.inside && 'tc-value-label-inside'],\n style: `transform:translate(${round(p.x)}px,${round(p.y)}px)`,\n 'text-anchor': 'middle',\n dy: '0.35em',\n },\n p.text,\n ),\n ),\n )\n}\n\n/**\n * Whether a label fits its slice: it sits at the slice's centroid, where the\n * slice is about its share of the circle wide and twice the distance to the\n * outer edge deep.\n */\nfunction sliceFits(item: HitItem, area: Rect, share: number, label: Rect): boolean {\n const outer = area.width / 2\n const radius = Math.hypot(item.x - area.x - outer, (item.y as number) - area.y - outer)\n const depth = 2 * (outer - radius)\n return label.width <= share * 2 * Math.PI * radius && label.height <= depth\n}\n\n/** The step that adds the labels over the content of charts with `valueLabels`. */\nexport const labelsStep: PostStep = (config, content, interaction, ctx) =>\n config.valueLabels && interaction ? [content, valueLabels(config, interaction, ctx)] : content\n","import type { Attrs, VNode } from '../vnode.ts'\nimport { childNamespace, createNode, patchAttrs, rendered, SVG_NS } from './dom.ts'\n\n/** Whether existing DOM `node` can stand for `vnode` in namespace `ns`. */\nfunction matches(node: Node, vnode: VNode, ns: string): node is Element {\n return (\n node.nodeType === 1 &&\n (node as Element).localName === vnode.tag &&\n (node as Element).namespaceURI === ns\n )\n}\n\n/**\n * Claim server-rendered DOM for a tree: the element takes the vnode's\n * attributes (extra ones are removed), and its children are matched by\n * position: text with text, elements with the same tag (hydrated in turn).\n * Anything that does not match is created in place, leftovers are removed.\n * Afterwards the nodes are tracked like freshly rendered ones.\n */\nexport function hydrateElement(el: Element, vnode: VNode): void {\n // The server attributes are the previous state to patch from.\n const current: Attrs = {}\n for (const name of el.getAttributeNames()) current[name] = el.getAttribute(name) as string\n // A strict CSP ignores style attributes in markup: set them again, through the CSSOM.\n if (current.style) current.style = ''\n patchAttrs(el, current, vnode.attrs)\n\n // Comments never stand for anything, and neither does text where the tree has none\n // (whitespace between elements). Text only ever sits in leaf elements here.\n const texts = vnode.children.some((child) => typeof child === 'string')\n for (const node of Array.from(el.childNodes)) {\n if (node.nodeType === 8 || (!texts && node.nodeType === 3)) el.removeChild(node)\n }\n\n const ns = childNamespace(el)\n let node: Node | null = el.firstChild\n for (const child of vnode.children) {\n const next: Node | null = node ? node.nextSibling : null\n if (\n typeof child === 'string'\n ? node?.nodeType === 3\n : node && matches(node, child, child.tag === 'svg' ? SVG_NS : ns)\n ) {\n if (typeof child === 'string') {\n if ((node as Text).data !== child) (node as Text).data = child\n rendered.set(node as Node, child)\n } else {\n hydrateElement(node as Element, child)\n }\n node = next\n } else {\n const created = createNode(child, ns, el.ownerDocument)\n if (created) el.insertBefore(created, node)\n }\n }\n while (node) {\n const extra: Node = node\n node = node.nextSibling\n el.removeChild(extra)\n }\n rendered.set(el, vnode)\n}\n\n/**\n * Hydrate `el` for the root `vnode` when it is foreign markup (not rendered\n * here) with the root's tag in namespace `ns`. Returns whether it did.\n */\nexport function hydrate(el: Element, vnode: VNode, ns: string): boolean {\n if (rendered.has(el) || !matches(el, vnode, ns)) return false\n hydrateElement(el, vnode)\n return true\n}\n","/**\n * Paths redrawn frame by frame, shared by `morph` and `sweep`: numbers go\n * from where they are to where they end with an ease-out curve, and each\n * frame draws the `d` of the numbers in between.\n */\n\n/** The running tween of each path: its frame request and the numbers drawn now. */\nconst running = /* @__PURE__ */ new WeakMap<Element, { frame: number; now: number[] }>()\n\n/** Stop the tween of `el`, if any; returns the numbers it had reached. */\nexport function stop(el: Element): number[] | undefined {\n const current = running.get(el)\n if (current) cancelAnimationFrame(current.frame)\n running.delete(el)\n return current?.now\n}\n\n/**\n * Take the numbers from `origin` to `end` over `duration` ms, setting the\n * `d` of `el` to `draw(numbers)` on each frame and to `to` on the last.\n */\nexport function tween(\n el: Element,\n origin: readonly number[],\n end: readonly number[],\n duration: number,\n draw: (now: number[]) => string,\n to: string,\n): void {\n const state = { frame: 0, now: origin.slice() }\n const begin = performance.now()\n const step = (time: number) => {\n const t = Math.min(1, Math.max(0, (time - begin) / duration))\n // Ease out, close to the default --tc-easing (a custom easing is approximated).\n const k = 1 - (1 - t) ** 3\n state.now = end.map((value, i) => (origin[i] as number) + (value - (origin[i] as number)) * k)\n el.setAttribute('d', t < 1 ? draw(state.now) : to)\n if (t < 1) state.frame = requestAnimationFrame(step)\n else running.delete(el)\n }\n running.set(el, state)\n state.frame = requestAnimationFrame(step)\n}\n","/**\n * Path morphing for browsers that cannot transition `d` in CSS (Safari):\n * when a patch changes the `d` of a path whose style asks for a `d`\n * transition, the numbers in the path are interpolated frame by frame\n * instead, over the transition's duration with an ease-out curve. Chart\n * paths keep their commands between renders, so only the numbers move; a\n * path whose commands changed jumps, as it would in CSS too.\n */\n\nimport { round } from '../layout.ts'\nimport { stop, tween } from './tween.ts'\n\nconst NUMBER = /-?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[-+]?\\d+)?/gi\n\nlet native: boolean | undefined\n\n/**\n * Change `el`'s `d` from `from` to `to` over its CSS transition, frame by\n * frame. Returns `false` when the browser transitions `d` itself, or the\n * path is not meant to move (the caller then just sets the attribute).\n */\nexport function morph(el: Element, from: string, to: string): boolean {\n native ??= typeof CSS === 'undefined' || CSS.supports('d', 'path(\"M0 0\")')\n const current = stop(el)\n // A chart without transitions (too big to animate, or resizing) has nothing to\n // morph: said here, before asking for the style of each of its paths.\n if (native || el.closest('.tc-static,[data-resizing]')) return false\n\n const style = getComputedStyle(el)\n const index = style.transitionProperty.split(', ').findIndex((p) => p === 'd' || p === 'all')\n const duration =\n index < 0 ? 0 : Number.parseFloat(style.transitionDuration.split(', ')[index] ?? '') * 1000\n const text = to.split(NUMBER)\n const end = to.match(NUMBER)?.map(Number) ?? []\n const start = from.match(NUMBER)?.map(Number) ?? []\n if (!(duration > 0) || start.length !== end.length || from.split(NUMBER).join() !== text.join()) {\n return false\n }\n\n // An interrupted morph continues from where the path is now.\n tween(\n el,\n current?.length === end.length ? current : start,\n end,\n duration,\n (now) =>\n now.reduce((d, value, i) => d + round(value) + (text[i + 1] as string), text[0] as string),\n to,\n )\n return true\n}\n","import type { Point } from './path.ts'\n\n/**\n * Largest-Triangle-Three-Buckets downsampling (Sveinn Steinarsson, 2013):\n * keep roughly `threshold` points that preserve the visual shape of a line,\n * including its peaks and valleys.\n *\n * Returns the indices to keep, in order. Gaps (`null` points) are kept as\n * gap markers and every run between gaps is sampled on its own, so the\n * result lines up with any per-index data (e.g. stacked baselines).\n */\nexport function lttbIndices(points: readonly Point[], threshold: number): number[] {\n const n = points.length\n if (!(threshold >= 3) || n <= threshold) return points.map((_, i) => i)\n\n // Split into runs of valid points.\n const runs: [number, number][] = []\n let start = -1\n for (let i = 0; i < n; i++) {\n const valid = points[i] != null\n if (valid && start === -1) start = i\n if (!valid && start !== -1) {\n runs.push([start, i])\n start = -1\n }\n }\n if (start !== -1) runs.push([start, n])\n const valid = runs.reduce((sum, [a, b]) => sum + (b - a), 0)\n\n const out: number[] = []\n let last = 0\n for (const [a, b] of runs) {\n // One gap marker between runs; everything else in the gap is dropped.\n if (a > last) out.push(last)\n // Each run gets a share of the budget (at least its two ends).\n const budget = Math.max(2, Math.round((threshold * (b - a)) / valid))\n sampleRun(points, a, b, budget, out)\n last = b\n }\n if (last < n) out.push(last)\n return out\n}\n\n/** LTTB over `points[from, to)`, pushing kept indices to `out`. */\nfunction sampleRun(\n points: readonly Point[],\n from: number,\n to: number,\n budget: number,\n out: number[],\n): void {\n const n = to - from\n if (n <= budget) {\n for (let i = from; i < to; i++) out.push(i)\n return\n }\n const at = (i: number) => points[i] as readonly [number, number]\n const bucketSize = (n - 2) / (budget - 2)\n let a = from\n out.push(a)\n\n for (let bucket = 0; bucket < budget - 2; bucket++) {\n // Average of the next bucket is the third corner of every candidate triangle.\n const nextStart = from + 1 + Math.floor((bucket + 1) * bucketSize)\n const nextEnd = Math.min(to, from + 1 + Math.floor((bucket + 2) * bucketSize))\n let avgX = 0\n let avgY = 0\n for (let i = nextStart; i < nextEnd; i++) {\n avgX += at(i)[0]\n avgY += at(i)[1]\n }\n const count = Math.max(1, nextEnd - nextStart)\n avgX /= count\n avgY /= count\n\n // The point of this bucket forming the largest triangle with `a` and the average.\n const rangeStart = from + 1 + Math.floor(bucket * bucketSize)\n const rangeEnd = Math.min(to - 1, from + 1 + Math.floor((bucket + 1) * bucketSize))\n const [ax, ay] = at(a)\n let best = rangeStart\n let bestArea = -1\n for (let i = rangeStart; i < rangeEnd; i++) {\n const [x, y] = at(i)\n const area = Math.abs((ax - avgX) * (y - ay) - (ax - x) * (avgY - ay))\n if (area > bestArea) {\n bestArea = area\n best = i\n }\n }\n out.push(best)\n a = best\n }\n out.push(to - 1)\n}\n\n/** The points kept by {@link lttbIndices}, gaps included. */\nexport function lttb(points: readonly Point[], threshold: number): Point[] {\n return lttbIndices(points, threshold).map((i) => points[i])\n}\n","/** A point in pixels; `null` (or a non-finite coordinate) marks a gap. */\nexport type Point = readonly [x: number, y: number] | null | undefined\n\n/** Curve used to connect consecutive points. */\nexport type Curve = 'linear' | 'monotone' | 'step' | 'step-before' | 'step-after'\n\nexport interface PathOptions {\n /** Interpolation between points. Defaults to `'linear'`. */\n curve?: Curve\n /** Decimal places kept in the path data. Defaults to `2`. */\n precision?: number\n}\n\ntype Pt = readonly [number, number]\n\n/** Accumulates SVG path commands with rounded coordinates. */\nclass PathBuilder {\n d = ''\n readonly #k: number\n\n constructor(precision: number) {\n this.#k = 10 ** Math.max(0, Math.min(12, Math.floor(precision)))\n }\n\n #n(value: number): string {\n const rounded = Math.round(value * this.#k) / this.#k\n return String(rounded === 0 ? 0 : rounded)\n }\n\n #xy(x: number, y: number): string {\n return `${this.#n(x)},${this.#n(y)}`\n }\n\n moveTo(x: number, y: number): void {\n this.d += `M${this.#xy(x, y)}`\n }\n\n lineTo(x: number, y: number): void {\n this.d += `L${this.#xy(x, y)}`\n }\n\n curveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void {\n this.d += `C${this.#xy(x1, y1)},${this.#xy(x2, y2)},${this.#xy(x, y)}`\n }\n\n close(): void {\n this.d += 'Z'\n }\n}\n\n/**\n * Emit `points` with a curve. The first point is a `moveTo` when `move` is\n * true, otherwise a `lineTo` (continuing an existing subpath). Returns the\n * number of points drawn.\n */\nfunction emit(path: PathBuilder, input: readonly Pt[], curve: Curve, move: boolean): number {\n // Monotone tangents break on zero-length segments, so drop coincident points.\n const points = curve === 'monotone' ? dedupe(input) : input\n const first = points[0]\n if (!first) return 0\n if (move) path.moveTo(first[0], first[1])\n else path.lineTo(first[0], first[1])\n\n switch (curve) {\n case 'monotone':\n monotone(path, points)\n break\n case 'step':\n step(path, points, 0.5)\n break\n case 'step-before':\n step(path, points, 0)\n break\n case 'step-after':\n step(path, points, 1)\n break\n default:\n for (let i = 1; i < points.length; i++) {\n const p = points[i] as Pt\n path.lineTo(p[0], p[1])\n }\n }\n return points.length\n}\n\nfunction dedupe(points: readonly Pt[]): readonly Pt[] {\n return points.filter((p, i) => {\n const prev = points[i - 1]\n return !prev || p[0] !== prev[0] || p[1] !== prev[1]\n })\n}\n\nfunction step(path: PathBuilder, points: readonly Pt[], t: number): void {\n for (let i = 1; i < points.length; i++) {\n const [x0, y0] = points[i - 1] as Pt\n const [x1, y1] = points[i] as Pt\n if (t <= 0) {\n path.lineTo(x0, y1)\n path.lineTo(x1, y1)\n } else if (t >= 1) {\n path.lineTo(x1, y0)\n path.lineTo(x1, y1)\n } else {\n const xm = x0 * (1 - t) + x1 * t\n path.lineTo(xm, y0)\n path.lineTo(xm, y1)\n // The next horizontal run continues from here, so only the last point is needed.\n if (i === points.length - 1) path.lineTo(x1, y1)\n }\n }\n}\n\nconst sign = (x: number): number => (x < 0 ? -1 : 1)\n\n/**\n * Monotone cubic interpolation in x (Steffen, 1990), as in d3's\n * `curveMonotoneX`: smooth, but never overshoots the data.\n */\nfunction monotone(path: PathBuilder, points: readonly Pt[]): void {\n const n = points.length\n if (n < 2) return\n if (n === 2) {\n const p = points[1] as Pt\n path.lineTo(p[0], p[1])\n return\n }\n\n const tangents = new Array<number>(n)\n for (let i = 1; i < n - 1; i++) {\n const [x0, y0] = points[i - 1] as Pt\n const [x1, y1] = points[i] as Pt\n const [x2, y2] = points[i + 1] as Pt\n const h0 = x1 - x0\n const h1 = x2 - x1\n const s0 = (y1 - y0) / (h0 || (h1 < 0 ? -0 : 0))\n const s1 = (y2 - y1) / (h1 || (h0 < 0 ? -0 : 0))\n const p = (s0 * h1 + s1 * h0) / (h0 + h1)\n tangents[i] =\n (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0\n }\n tangents[0] = endTangent(points[0] as Pt, points[1] as Pt, tangents[1] as number)\n tangents[n - 1] = endTangent(points[n - 2] as Pt, points[n - 1] as Pt, tangents[n - 2] as number)\n\n for (let i = 1; i < n; i++) {\n const [x0, y0] = points[i - 1] as Pt\n const [x1, y1] = points[i] as Pt\n const dx = (x1 - x0) / 3\n path.curveTo(\n x0 + dx,\n y0 + dx * (tangents[i - 1] as number),\n x1 - dx,\n y1 - dx * (tangents[i] as number),\n x1,\n y1,\n )\n }\n}\n\n/** One-sided tangent for the first/last point from the neighbour's tangent. */\nfunction endTangent(a: Pt, b: Pt, t: number): number {\n const h = b[0] - a[0]\n return h ? (3 * (b[1] - a[1])) / h / 2 - t / 2 : t\n}\n\nconst isValid = (p: Point): p is Pt => p != null && Number.isFinite(p[0]) && Number.isFinite(p[1])\n\n/** Split points into runs of consecutive valid points, keeping their indices. */\nfunction runs(points: readonly Point[], valid: (i: number) => boolean = () => true): number[][] {\n const out: number[][] = []\n let current: number[] | undefined\n for (let i = 0; i < points.length; i++) {\n if (isValid(points[i]) && valid(i)) {\n if (!current) {\n current = []\n out.push(current)\n }\n current.push(i)\n } else {\n current = undefined\n }\n }\n return out\n}\n\n/**\n * Build the `d` attribute of a line through `points`. Gaps (`null`/`NaN`)\n * start a new subpath; a lone point renders as `M x,y Z`.\n *\n * ```ts\n * linePath([[0, 10], [50, 40], null, [100, 20]], { curve: 'monotone' })\n * ```\n */\nexport function linePath(points: readonly Point[], options: PathOptions = {}): string {\n const { curve = 'linear', precision = 2 } = options\n const path = new PathBuilder(precision)\n for (const run of runs(points)) {\n const drawn = emit(\n path,\n run.map((i) => points[i] as Pt),\n curve,\n true,\n )\n if (drawn === 1) path.close()\n }\n return path.d\n}\n\n/**\n * Build the `d` attribute of an area between `points` and a `baseline`:\n * a constant y (e.g. the zero line) or one y per point (stacked areas).\n * Each run of valid points becomes a closed subpath.\n */\nexport function areaPath(\n points: readonly Point[],\n baseline: number | readonly (number | null | undefined)[],\n options: PathOptions = {},\n): string {\n const { curve = 'linear', precision = 2 } = options\n const path = new PathBuilder(precision)\n const baseAt = (i: number): number =>\n typeof baseline === 'number' ? baseline : (baseline[i] ?? Number.NaN)\n\n for (const run of runs(points, (i) => Number.isFinite(baseAt(i)))) {\n emit(\n path,\n run.map((i) => points[i] as Pt),\n curve,\n true,\n )\n\n const bottom = run.map((i) => [(points[i] as Pt)[0], baseAt(i)] as const).reverse()\n // Walking backwards mirrors step curves, so stacked steps line up. A flat\n // baseline takes the same curve (it stays straight) so that the path keeps\n // its commands between flat and stacked, and CSS can morph one into the other.\n const back =\n curve === 'step-before' ? 'step-after' : curve === 'step-after' ? 'step-before' : curve\n emit(path, bottom, back, false)\n path.close()\n }\n return path.d\n}\n","import { feature } from '../features.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { render } from '../render/dom.ts'\nimport { h } from '../vnode.ts'\n\n/** A file format of the download menu. */\nexport type DownloadFormat = 'png' | 'svg' | 'jpeg' | 'webp'\n\n/** The `download` option as an object. */\nexport interface DownloadMenuOptions {\n /** Formats offered, in this order. Defaults to `['png', 'svg']`. */\n formats?: readonly DownloadFormat[]\n /** File name without the extension. Defaults to the chart's title, or `chart`. */\n filename?: string\n /** Accessible name of the menu button. Defaults to `'Download'`. */\n label?: string\n /**\n * Background color, `'auto'` for the chart's surface (`--tc-surface`), or\n * `false` for none (transparent). Defaults to `'auto'`.\n */\n background?: string | false\n /** Draw the legend into the file. Defaults to `true`. */\n legend?: boolean\n /** Pixels per chart pixel in images. Defaults to `2`. */\n scale?: number\n}\n\n/** The `download` option: on, a list of formats, or the options. */\nexport type DownloadOption = boolean | readonly DownloadFormat[] | DownloadMenuOptions\n\nconst NAMES: Record<DownloadFormat, string> = { png: 'PNG', svg: 'SVG', jpeg: 'JPEG', webp: 'WebP' }\nconst DEFAULT_FORMATS: readonly DownloadFormat[] = ['png', 'svg']\n\nfunction resolve(option: DownloadOption): DownloadMenuOptions {\n return option === true\n ? {}\n : Array.isArray(option)\n ? { formats: option }\n : (option as DownloadMenuOptions)\n}\n\n/**\n * A download menu in the chart's corner (`.tc-download`): a button that opens\n * a list of file formats, PNG and SVG by default. Shown with the `download`\n * option. The files come from `@tabler/charts/export`, which must be imported\n * (the chart says so otherwise): that way charts without a download never\n * carry the export code.\n */\nexport function download(): ChartPlugin {\n return {\n name: 'download',\n install(chart) {\n const host = chart.element\n const doc = host.ownerDocument\n let el: HTMLElement | undefined\n let options: DownloadMenuOptions = {}\n // The menu overlays the chart: the container is the positioning context.\n const addedClass = !host.classList.contains('tc-container')\n\n const toggle = () => el?.querySelector<HTMLElement>('.tc-download-toggle')\n const menu = () => el?.querySelector<HTMLElement>('.tc-download-menu')\n const items = () => Array.from(el?.querySelectorAll<HTMLElement>('.tc-download-item') ?? [])\n\n const setOpen = (open: boolean) => {\n const list = menu()\n if (!list) return\n list.hidden = !open\n toggle()?.setAttribute('aria-expanded', String(open))\n if (open) doc.addEventListener('pointerdown', onOutside, true)\n else doc.removeEventListener('pointerdown', onOutside, true)\n }\n const isOpen = () => menu()?.hidden === false\n\n const onOutside = (event: Event) => {\n if (!el?.contains(event.target as Node)) setOpen(false)\n }\n\n const onClick = (event: Event) => {\n const target = event.target as Element\n if (target.closest('.tc-download-toggle')) {\n setOpen(!isOpen())\n if (isOpen()) items()[0]?.focus()\n return\n }\n const format = target.closest('.tc-download-item')?.getAttribute('data-format')\n if (!format) return\n setOpen(false)\n toggle()?.focus()\n void feature('export')(chart, { ...options, format: format as DownloadFormat })\n }\n\n const onKey = (event: KeyboardEvent) => {\n if (event.key === 'Escape' && isOpen()) {\n event.preventDefault()\n setOpen(false)\n toggle()?.focus()\n return\n }\n if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return\n const list = items()\n if (!list.length) return\n event.preventDefault()\n if (!isOpen()) setOpen(true)\n const at = list.indexOf(doc.activeElement as HTMLElement)\n const step = event.key === 'ArrowDown' ? 1 : -1\n list[(at + step + list.length) % list.length]?.focus()\n }\n\n // Tabbing out of the menu closes it.\n const onBlur = (event: FocusEvent) => {\n if (!el?.contains(event.relatedTarget as Node)) setOpen(false)\n }\n\n const remove = () => {\n if (!el) return\n setOpen(false)\n render(el, null)\n el.remove()\n el = undefined\n if (addedClass) host.classList.remove('tc-container')\n }\n\n return {\n afterRender({ config, changed }) {\n const option = config.download\n if (!option || typeof document === 'undefined') {\n remove()\n return\n }\n // Resizing and hovering change nothing in the menu.\n if (!changed && el?.isConnected) return\n // Fail early, at render, when the export entry is not imported.\n feature('export')\n options = resolve(option)\n const formats = options.formats?.length ? options.formats : DEFAULT_FORMATS\n if (!el) {\n el = doc.createElement('div')\n el.className = 'tc-download'\n el.addEventListener('click', onClick)\n el.addEventListener('keydown', onKey)\n el.addEventListener('focusout', onBlur)\n }\n render(\n el,\n h(\n 'div',\n { class: 'tc-download-box' },\n h(\n 'button',\n {\n type: 'button',\n class: 'tc-download-toggle',\n 'aria-label': options.label ?? 'Download',\n 'aria-haspopup': 'menu',\n 'aria-expanded': 'false',\n },\n h(\n 'svg',\n {\n viewBox: '0 0 24 24',\n width: '16',\n height: '16',\n 'aria-hidden': 'true',\n fill: 'none',\n stroke: 'currentColor',\n 'stroke-width': '2',\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round',\n },\n h('path', {\n d: 'M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2M7 11l5 5 5-5M12 4v12',\n }),\n ),\n ),\n h(\n 'div',\n { class: 'tc-download-menu', role: 'menu', hidden: '' },\n formats.map((format) =>\n h(\n 'button',\n {\n key: format,\n type: 'button',\n role: 'menuitem',\n class: 'tc-download-item',\n 'data-format': format,\n },\n NAMES[format] ?? format,\n ),\n ),\n ),\n ),\n )\n host.classList.add('tc-container')\n if (!el.isConnected) host.appendChild(el)\n },\n destroy: remove,\n }\n },\n }\n}\n","import type { Hit } from '../interaction.ts'\nimport { round } from '../layout.ts'\nimport { h, type VNode } from '../vnode.ts'\n\n/** Series wrapper so hover marks pick up the series color from CSS. */\nfunction seriesGroup(seriesIndex: number, color: string | undefined, child: VNode): VNode {\n return h(\n 'g',\n {\n key: seriesIndex,\n class: ['tc-series', `tc-series-${seriesIndex + 1}`],\n style: { '--tc-series-color': color },\n },\n child,\n )\n}\n\n/**\n * Hover marks drawn below the series: a band behind the hovered category of\n * band charts (bars), or a vertical crosshair for point charts (lines).\n */\nexport function hoverUnderlay(hit: Hit, crosshair = true): VNode {\n const { area } = hit\n return h(\n 'g',\n { class: 'tc-hover', 'aria-hidden': 'true' },\n hit.mark\n ? null\n : hit.band\n ? h('rect', {\n class: 'tc-hover-band',\n x: round(hit.band.x),\n y: round(hit.band.y),\n width: round(hit.band.width),\n height: round(hit.band.height),\n })\n : crosshair &&\n h(\n 'line',\n hit.guide\n ? {\n class: 'tc-crosshair',\n x1: round(hit.guide.x1),\n x2: round(hit.guide.x2),\n y1: round(hit.guide.y1),\n y2: round(hit.guide.y2),\n }\n : {\n class: 'tc-crosshair',\n x1: round(hit.x),\n x2: round(hit.x),\n y1: round(area.y),\n y2: round(area.y + area.height),\n },\n ),\n )\n}\n\n/**\n * Hover marks drawn above the series: the hit's own mark (pie slices), or\n * an active dot on every point of point charts (of the series' `shape`, if given).\n */\nexport function hoverOverlay(\n hit: Hit,\n radius = 4,\n shape?: (slot: number, x: number, y: number, r: number) => string,\n): VNode {\n const { mark } = hit\n if (mark) {\n const item = hit.items.find((i) => i.seriesIndex === hit.seriesIndex) ?? hit.items[0]\n return h(\n 'g',\n { class: 'tc-hover', 'aria-hidden': 'true' },\n item &&\n seriesGroup(\n item.seriesIndex,\n item.color,\n h('path', {\n class: 'tc-hover-mark',\n d: mark.d,\n style: `transform:translate(${round(mark.x)}px,${round(mark.y)}px)`,\n }),\n ),\n )\n }\n return h(\n 'g',\n { class: 'tc-hover', 'aria-hidden': 'true' },\n !hit.band &&\n hit.items.map(\n (item) =>\n item.y !== null &&\n seriesGroup(\n item.seriesIndex,\n item.color,\n shape\n ? h('path', {\n class: 'tc-point tc-point-active tc-marker',\n d: shape(item.seriesIndex, item.x, item.y, radius),\n })\n : h('circle', {\n class: 'tc-point tc-point-active',\n cx: round(item.x),\n cy: round(item.y),\n r: radius,\n }),\n ),\n ),\n )\n}\n","import type { Chart } from '../chart.ts'\nimport { toChartPoint } from '../interaction.ts'\nimport type { ChartPlugin } from '../plugin.ts'\n\nconst listening = /* @__PURE__ */ new WeakSet<object>()\n\n/**\n * Turn pointer input on the chart's element into highlights and `hover` /\n * `click` events (once per chart, however many plugins ask). Returns the\n * function that stops listening, or nothing when already listening.\n */\nexport function listenPointer(chart: Chart<object>): (() => void) | undefined {\n const el = chart.element\n if (listening.has(chart) || typeof el.addEventListener !== 'function') return undefined\n listening.add(chart)\n const local = (event: MouseEvent) => {\n const svg = el.querySelector('svg.tc-chart')\n if (!svg) return undefined\n const { width, height } = chart.size\n return toChartPoint(svg, event.clientX, event.clientY, width, height)\n }\n // Controls laid over the chart (the download menu) are not the chart:\n // hovering them clears the highlight, so the tooltip never covers them.\n const overControl = (event: Event) =>\n !!(event.target as Element | null)?.closest?.('.tc-download')\n const onLeave = (event: PointerEvent) => {\n // On touch, keep the last highlight after the finger lifts.\n if (event.pointerType !== 'touch' && chart.highlightSource === 'pointer') {\n chart.clearHighlight(event)\n }\n }\n const onMove = (event: PointerEvent) => {\n if (overControl(event)) {\n onLeave(event)\n return\n }\n const point = local(event)\n if (point) chart.highlightAt(point.x, point.y, event)\n }\n const onClick = (event: MouseEvent) => {\n if (overControl(event)) return\n const point = local(event)\n const hit = point ? chart.hitTest(point.x, point.y) : null\n if (hit) chart.emit('click', { hit, event })\n }\n el.addEventListener('pointermove', onMove as EventListener)\n el.addEventListener('pointerdown', onMove as EventListener)\n el.addEventListener('pointerleave', onLeave as EventListener)\n el.addEventListener('click', onClick as EventListener)\n return () => {\n listening.delete(chart)\n el.removeEventListener('pointermove', onMove as EventListener)\n el.removeEventListener('pointerdown', onMove as EventListener)\n el.removeEventListener('pointerleave', onLeave as EventListener)\n el.removeEventListener('click', onClick as EventListener)\n }\n}\n\n/**\n * Pointer input: hovering highlights what is under the pointer and emits\n * `hover`, clicking emits `click`. The highlight and tooltip plugins turn it\n * on themselves; add it to a bare `Chart` that only needs the events.\n */\nexport function pointer(): ChartPlugin {\n return {\n name: 'pointer',\n install(chart) {\n const stop = listenPointer(chart)\n return stop ? { destroy: stop } : {}\n },\n }\n}\n","import { markerShape } from '../charts/cartesian.ts'\nimport { hoverOverlay, hoverUnderlay } from '../components/hover.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { listenPointer } from './pointer.ts'\n\n/**\n * Draws the highlighted category: a crosshair (or a band behind bars) under\n * the series and active dots above them. `crosshair: false` keeps the dots.\n */\nexport function highlight(): ChartPlugin {\n return {\n name: 'highlight',\n install(chart) {\n const stop = listenPointer(chart)\n return {\n layers: (hit, config) => ({\n under: hoverUnderlay(hit, config.crosshair !== false),\n over: hoverOverlay(hit, 4, markerShape(config)),\n }),\n ...(stop ? { destroy: stop } : {}),\n }\n },\n }\n}\n","import type { Hit } from './interaction.ts'\nimport { h, type VNode } from './vnode.ts'\n\n/** The data behind a chart as text: header cells and one row per category. */\nexport interface DataTable {\n /** Column headers; the first one labels the row headers (may be empty). */\n columns: string[]\n /** Rows of display text; the first cell of each row is its header. */\n rows: string[][]\n /** Total number of rows when `rows` was cut to a limit. */\n total?: number\n}\n\n/**\n * An HTML table of the chart data, for screen readers (visually hidden by\n * default) or as a visible fallback. Every cell is text, escaped by the renderer.\n */\nexport function tableContent(table: DataTable, caption?: string): VNode {\n const [corner = '', ...headers] = table.columns\n return h(\n 'table',\n { class: 'tc-table' },\n caption && h('caption', null, caption),\n h(\n 'thead',\n null,\n h(\n 'tr',\n null,\n h('th', { scope: 'col' }, corner),\n headers.map((name, i) => h('th', { key: i, scope: 'col' }, name)),\n ),\n ),\n h(\n 'tbody',\n null,\n table.rows.map(([head = '', ...cells], i) =>\n h(\n 'tr',\n { key: i },\n h('th', { scope: 'row' }, head),\n cells.map((cell, j) => h('td', { key: j }, cell)),\n ),\n ),\n ),\n )\n}\n\n/** Short sentence describing a hit, announced during keyboard navigation. */\nexport function describeHit(hit: Hit): string {\n const items =\n hit.seriesIndex === undefined\n ? hit.items\n : hit.items.filter((item) => item.seriesIndex === hit.seriesIndex)\n const values = items.map((item) => `${item.name} ${item.text}`).join(', ')\n return hit.title ? `${hit.title}: ${values}` : values\n}\n","import { describeHit } from '../a11y.ts'\nimport type { ChartPlugin } from '../plugin.ts'\n\n/**\n * Keyboard navigation: the SVG becomes focusable; arrow keys walk\n * categories, Up/Down walk series, Home/End jump, Escape (or leaving)\n * clears. Every step is announced through a polite live region.\n */\n/** The config's `keyboard` option, else the chart type's default, else on. */\nconst enabled = (config: { keyboard?: boolean; type: { keyboard?: boolean } }): boolean =>\n config.keyboard ?? config.type.keyboard ?? true\n\nexport function keyboard(): ChartPlugin {\n return {\n name: 'keyboard',\n install(chart) {\n const host = chart.element\n let live: HTMLElement | undefined\n\n /**\n * The live region, added when the chart takes focus: screen readers only\n * announce changes of a region that was already there, so one created\n * with its first message would stay silent for that message.\n */\n const region = (): HTMLElement => {\n if (!live) {\n live = host.ownerDocument.createElement('div')\n live.className = 'tc-sr-only'\n live.setAttribute('aria-live', 'polite')\n live.setAttribute('aria-atomic', 'true')\n host.appendChild(live)\n }\n return live\n }\n const announce = (text: string) => {\n region().textContent = text\n }\n\n const go = (index: number, seriesIndex?: number) => {\n const hit = chart.highlightIndex(index, seriesIndex)\n if (hit) announce(describeHit(hit))\n }\n\n /** Returns whether the key was handled. */\n const handle = (key: string): boolean => {\n const interaction = chart.interaction\n if (!interaction || interaction.count === 0) return false\n const current = chart.highlightSource === 'index' ? chart.active : null\n const last = interaction.count - 1\n const index = current?.index\n const focused = current?.seriesIndex\n const series = current?.items.map((item) => item.seriesIndex) ?? []\n const at = focused === undefined ? -1 : series.indexOf(focused)\n\n switch (key) {\n case 'ArrowRight':\n go(index === undefined ? 0 : Math.min(last, index + 1), focused)\n return true\n case 'ArrowLeft':\n go(index === undefined ? last : Math.max(0, index - 1), focused)\n return true\n case 'Home':\n go(0, focused)\n return true\n case 'End':\n go(last, focused)\n return true\n case 'ArrowDown':\n case 'ArrowUp': {\n if (index === undefined || series.length === 0) {\n go(0)\n return true\n }\n const step = key === 'ArrowDown' ? 1 : -1\n const next = at === -1 ? (step > 0 ? 0 : series.length - 1) : at + step\n go(index, next < 0 || next >= series.length ? undefined : series[next])\n return true\n }\n case 'Escape':\n if (!current) return false\n chart.clearHighlight()\n return true\n default:\n return false\n }\n }\n\n const isChart = (target: EventTarget | null) =>\n (target as Element | null)?.matches?.('svg.tc-chart') === true\n const onKey = (event: Event) => {\n const { key } = event as KeyboardEvent\n if (!enabled(chart.config) || !isChart(event.target)) return\n if (handle(key)) event.preventDefault()\n }\n const onBlur = (event: Event) => {\n if (isChart(event.target) && chart.highlightSource === 'index') chart.clearHighlight()\n }\n const onFocus = (event: Event) => {\n if (enabled(chart.config) && isChart(event.target)) region()\n }\n host.addEventListener('keydown', onKey)\n host.addEventListener('focusin', onFocus)\n host.addEventListener('focusout', onBlur)\n\n return {\n svgAttrs: (config) => (enabled(config) ? { tabindex: 0 } : undefined),\n destroy() {\n host.removeEventListener('keydown', onKey)\n host.removeEventListener('focusin', onFocus)\n host.removeEventListener('focusout', onBlur)\n live?.remove()\n },\n }\n },\n }\n}\n","import { legendContent } from '../legend.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { render } from '../render/dom.ts'\n\n/**\n * An HTML legend (`.tc-legend`) with toggle buttons, above or below the SVG.\n * Shown for two or more entries unless the `legend` option says otherwise.\n */\nexport function legend(): ChartPlugin {\n return {\n name: 'legend',\n install(chart) {\n const host = chart.element\n // Take over a server-rendered legend instead of adding a second one.\n let el = host.querySelector<HTMLElement>(':scope > .tc-legend') ?? undefined\n let adopt = el?.firstElementChild ?? null\n let bound = false\n const onClick = (event: Event) => {\n const button = (event.target as Element).closest?.('.tc-legend-item')\n const key = button?.getAttribute('data-key')\n if (key != null) chart.toggleSeries(key)\n }\n\n const remove = () => {\n if (!el) return\n render(el, null)\n el.removeEventListener('click', onClick)\n bound = false\n el.remove()\n el = undefined\n }\n\n /** Keep the legend right before or after the SVG, whatever else lives in the container. */\n const place = () => {\n if (!el) return\n const svg = host.querySelector(':scope > svg.tc-chart')\n if (el.dataset.position === 'bottom') {\n if (!svg) {\n if (!el.isConnected) host.appendChild(el)\n } else if (svg.nextElementSibling !== el) {\n svg.after(el)\n }\n } else if (!el.isConnected || el.nextElementSibling !== svg) {\n host.insertBefore(el, svg ?? host.firstChild)\n }\n }\n\n return {\n beforeRender({ legend, hidden }) {\n if (!legend.show || typeof document === 'undefined') {\n remove()\n return\n }\n if (!el) {\n el = host.ownerDocument.createElement('div')\n el.className = 'tc-legend'\n }\n if (!bound) {\n el.addEventListener('click', onClick)\n bound = true\n }\n el.dataset.position = legend.position\n render(el, legendContent(legend.items, hidden), adopt)\n adopt = null\n place()\n },\n // With its margin: the gap to the chart is taken from the container too.\n reservedHeight() {\n if (!el?.isConnected) return 0\n const { marginTop, marginBottom } = getComputedStyle(el)\n return (\n el.offsetHeight +\n (Number.parseFloat(marginTop) || 0) +\n (Number.parseFloat(marginBottom) || 0)\n )\n },\n afterRender: place,\n destroy: remove,\n }\n },\n }\n}\n","import type { Chart } from '../chart.ts'\nimport type { Interaction } from '../interaction.ts'\nimport type { ChartPlugin } from '../plugin.ts'\n\n/** Charts by `sync` group, held weakly: a chart taken out without destroy() is let go. */\nconst groups = /* @__PURE__ */ new Map<string, Set<WeakRef<Chart<object>>>>()\n\n/** The index of each category label, per render of a chart. */\nconst indexes = /* @__PURE__ */ new WeakMap<Interaction, Map<string | number, number>>()\n\n/** Set while a highlight is passed on, so the charts it reaches do not pass it on again. */\nlet passing = false\n\n/** The index of the category with `label` in a chart's current render, if it has one. */\nfunction indexOf(interaction: Interaction, label: string | number): number | undefined {\n let index = indexes.get(interaction)\n if (!index) {\n index = new Map()\n for (let i = 0; i < interaction.count; i++) {\n const hit = interaction.hitIndex(i)\n if (hit && !index.has(hit.label)) index.set(hit.label, i)\n }\n indexes.set(interaction, index)\n }\n return index.get(label)\n}\n\n/**\n * Shared hover across charts: charts with the same `sync` group highlight\n * the category under the pointer in any of them (with its crosshair and\n * tooltip), matched by label, and clear together when it leaves. Keyboard\n * highlights stay in their own chart.\n */\nexport function sync(): ChartPlugin {\n return {\n name: 'sync',\n install(chart) {\n const self = new WeakRef(chart)\n let group: Set<WeakRef<Chart<object>>> | undefined\n /** The name of the group joined: the config may have moved on before the next render. */\n let joined: string | undefined\n /** Leave the group, and take it off the list when it is empty. */\n const leave = () => {\n group?.delete(self)\n if (joined && group?.size === 0 && groups.get(joined) === group) groups.delete(joined)\n }\n /** Join the group of the current config, leaving the one before. */\n const join = () => {\n const name = chart.config.sync\n const next = name ? (groups.get(name) ?? new Set()) : undefined\n if (next === group) return\n leave()\n if (name && next) {\n next.add(self)\n groups.set(name, next)\n }\n group = next\n joined = name\n }\n join()\n const off = chart.on('hover', ({ hit }) => {\n // Only the pointer leads; keyboard highlights and highlights passed on do not.\n if (passing || !group || (hit && chart.highlightSource !== 'pointer')) return\n passing = true\n try {\n for (const ref of group) {\n const other = ref.deref()\n if (!other) group.delete(ref)\n if (!other || other === chart) continue\n const index = hit && other.interaction && indexOf(other.interaction, hit.label)\n if (index === undefined || index === null) other.clearHighlight()\n else other.highlightIndex(index)\n }\n } finally {\n passing = false\n }\n })\n return {\n afterRender: join,\n destroy() {\n off()\n leave()\n },\n }\n },\n }\n}\n","/**\n * Work that can wait until the browser is idle, such as hidden data tables:\n * it runs in an idle callback (within a second at the latest), or with\n * `flush()`. A module of its own, so charts without such work do not ship it.\n */\nimport { flushHooks, run } from './scheduler.ts'\n\nconst idle = /* @__PURE__ */ new Map<object, () => void>()\nlet pending = false\n\nfunction drain(): number {\n pending = false\n let count = 0\n while (idle.size > 0) {\n const tasks = Array.from(idle.values())\n idle.clear()\n for (const task of tasks) {\n run(task)\n count++\n }\n }\n return count\n}\n\n/** Run `task` once the browser is idle, replacing any idle task already queued for `key`. */\nexport function scheduleIdle(key: object, task: () => void): void {\n flushHooks.idle = drain\n idle.set(key, task)\n if (pending) return\n pending = true\n if (typeof requestIdleCallback === 'function') requestIdleCallback(drain, { timeout: 1000 })\n else setTimeout(drain, 100)\n}\n\n/** Drop the idle task queued for `key`, if any. */\nexport function cancelIdle(key: object): void {\n idle.delete(key)\n}\n","import { tableContent } from '../a11y.ts'\nimport { type ChartConfig, renderContext, type Size } from '../chart.ts'\nimport { getNumberFormat } from '../format.ts'\nimport { cancelIdle, scheduleIdle } from '../idle.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { render } from '../render/dom.ts'\n\n/**\n * The chart data as an HTML table next to the SVG: visually hidden for\n * screen readers by default, visible with `table: 'visible'`.\n */\nconst DEFAULT_MAX_ROWS = 1000\n\nexport function dataTable(): ChartPlugin {\n return {\n name: 'table',\n install(chart) {\n const host = chart.element\n // Take over a server-rendered table instead of adding a second one.\n let el = host.querySelector<HTMLElement>(':scope > .tc-table-wrap') ?? undefined\n let adopt = el?.firstElementChild ?? null\n\n /** The table option of the last table, to tell its changes from new data. */\n let shown: unknown\n const key = {}\n\n const remove = () => {\n cancelIdle(key)\n if (!el) return\n render(el, null)\n el.remove()\n el = undefined\n }\n\n const update = (config: ChartConfig<object>, size: Size, hidden: ReadonlySet<string>) => {\n const option = config.table ?? true\n const maxRows =\n typeof option === 'object' && option.maxRows ? option.maxRows : DEFAULT_MAX_ROWS\n const table =\n option !== false && typeof document !== 'undefined'\n ? config.type.table?.(\n config,\n renderContext(config, size, chart.id, () => {}, hidden, chart.fontSize),\n maxRows,\n )\n : undefined\n if (!table) {\n remove()\n return\n }\n const visible =\n option === 'visible' || (typeof option === 'object' && option.visible === true)\n // Huge tables help nobody and cost real time to build; keep the first rows.\n let caption = config.title\n const total = table.total ?? table.rows.length\n const rows =\n table.rows.length > maxRows\n ? { columns: table.columns, rows: table.rows.slice(0, maxRows) }\n : table\n if (total > rows.rows.length) {\n const n = getNumberFormat(config.locale)\n const note = `${n.format(rows.rows.length)} of ${n.format(total)} rows`\n caption = caption ? `${caption} (${note})` : note\n }\n if (!el) el = host.ownerDocument.createElement('div')\n el.className = visible ? 'tc-table-wrap' : 'tc-table-wrap tc-sr-only'\n render(el, tableContent(rows, caption), adopt)\n adopt = null\n const svg = host.querySelector(':scope > svg.tc-chart')\n const bottomLegend = host.querySelector(':scope > .tc-legend[data-position=\"bottom\"]')\n const after = bottomLegend ?? svg\n if (after && after.nextElementSibling !== el) after.after(el)\n else if (!el.isConnected) host.appendChild(el)\n }\n\n return {\n afterRender({ config, size, hidden, changed }) {\n // Resizing changes nothing in the table.\n if (!changed && el?.isConnected) return\n const option = config.table ?? true\n const same = shown === option\n shown = option\n // A hidden table only serves screen readers: rebuilding thousands of\n // cells for new data can wait until the browser is idle instead of\n // delaying the frame that animates the chart. The first table, visible\n // ones and changes of the table option itself are built right away.\n if (same && el?.isConnected && el.classList.contains('tc-sr-only')) {\n scheduleIdle(key, () => update(config, size, hidden))\n } else {\n cancelIdle(key)\n update(config, size, hidden)\n }\n },\n destroy: remove,\n }\n },\n }\n}\n","import type { Hit } from './interaction.ts'\nimport { type ChildInput, h, type VNode } from './vnode.ts'\n\n/**\n * Where a tooltip for `hit` belongs, in chart pixels: the pointer when it\n * drives the highlight, otherwise the focused value (keyboard).\n */\nexport function hitAnchor(hit: Hit, pointer?: { x: number; y: number }): { x: number; y: number } {\n if (pointer) return pointer\n const item = hit.items.find((i) => i.seriesIndex === hit.seriesIndex) ?? hit.items[0]\n if (hit.guide && item?.y != null) return { x: item.x, y: item.y }\n if (hit.axis === 'y') return { x: item?.x ?? hit.x, y: hit.y ?? hit.area.y }\n return { x: hit.x, y: item?.y ?? hit.area.y + hit.area.height / 2 }\n}\n\nexport interface TooltipOptions {\n /**\n * Colors of the tooltip: `'dark'` (the default) is a dark box with light\n * text, `'light'` a white one with dark text. Both keep their colors in\n * dark mode; the `--tc-tooltip-*` tokens tune them.\n */\n theme?: 'dark' | 'light'\n /**\n * Custom content for a hit: VNodes built with `h()` or plain text.\n * Rendered safely (no HTML parsing), inside `.tc-tooltip`.\n */\n format?: (hit: Hit) => ChildInput\n /** Extra content below the default rows (e.g. a total), in `.tc-tooltip-footer`. */\n footer?: (hit: Hit) => ChildInput\n}\n\n/** Default tooltip content: the category title and one row per series. */\nexport function tooltipContent(hit: Hit, options: TooltipOptions = {}): VNode {\n const body: ChildInput = options.format\n ? options.format(hit)\n : [\n hit.title && h('div', { class: 'tc-tooltip-title' }, hit.title),\n hit.items.map((item) =>\n h(\n 'div',\n {\n key: item.seriesIndex,\n class: [\n 'tc-tooltip-item',\n 'tc-series',\n `tc-series-${item.seriesIndex + 1}`,\n hit.seriesIndex === item.seriesIndex && 'tc-tooltip-item-active',\n ],\n style: { '--tc-series-color': item.color },\n },\n h('span', { class: 'tc-tooltip-swatch' }),\n h('span', { class: 'tc-tooltip-name' }, item.name),\n h('span', { class: 'tc-tooltip-value' }, item.text),\n ),\n ),\n options.footer && h('div', { class: 'tc-tooltip-footer' }, options.footer(hit)),\n ]\n return h('div', { class: 'tc-tooltip-content' }, body)\n}\n\nexport interface TooltipPlacement {\n x: number\n y: number\n side: 'left' | 'right'\n}\n\n/**\n * Place a `width × height` tooltip next to an anchor within `bounds` (from\n * `bounds.x`, `bounds.y`, 0 by default): right of the anchor, or left when it\n * would overflow, vertically centered on the pointer and clamped.\n */\nexport function placeTooltip(\n anchor: { x: number; y: number },\n size: { width: number; height: number },\n bounds: { x?: number; y?: number; width: number; height: number },\n offset = 12,\n): TooltipPlacement {\n const { x: left = 0, y: top = 0 } = bounds\n const fitsRight = anchor.x + offset + size.width <= left + bounds.width\n const fitsLeft = anchor.x - offset - size.width >= left\n const side = fitsRight || !fitsLeft ? 'right' : 'left'\n const rawX = side === 'right' ? anchor.x + offset : anchor.x - offset - size.width\n const x = Math.max(left, Math.min(rawX, left + bounds.width - size.width))\n const y = Math.max(top, Math.min(anchor.y - size.height / 2, top + bounds.height - size.height))\n return { x: Math.round(x), y: Math.round(y), side }\n}\n","import type { ChartPlugin } from '../plugin.ts'\nimport { render } from '../render/dom.ts'\nimport { schedule } from '../scheduler.ts'\nimport { hitAnchor, placeTooltip, tooltipContent } from '../tooltip.ts'\nimport { listenPointer } from './pointer.ts'\n\n/**\n * Where a tooltip in `el` can show without being cut off: the box of the\n * nearest element that clips its overflow (`el` itself, an ancestor, across\n * shadow roots), within the viewport.\n */\nfunction room(el: Element): { left: number; top: number; right: number; bottom: number } {\n let left = 0\n let top = 0\n let right = innerWidth\n let bottom = innerHeight\n for (let node: Element | null = el; node; ) {\n const style = getComputedStyle(node)\n if (style.overflowX !== 'visible' || style.overflowY !== 'visible') {\n const box = node.getBoundingClientRect()\n left = Math.max(left, box.left)\n top = Math.max(top, box.top)\n right = Math.min(right, box.right)\n bottom = Math.min(bottom, box.bottom)\n break\n }\n node = node.parentElement ?? ((node.getRootNode() as ShadowRoot).host || null)\n }\n return { left, top, right, bottom }\n}\n\n/** Tooltips to place: each measures where it goes, and returns what moves it there. */\nconst waiting: (() => (() => void) | undefined)[] = []\n\n/**\n * Place the waiting tooltips, in the frame that rendered their charts: all\n * are measured before any is moved, so the page is laid out once for the\n * frame. Measured and moved one by one, twelve charts sharing a hover laid\n * the page out twelve times.\n */\nfunction placeAll(): void {\n for (const move of waiting.splice(0).map((measure) => measure())) move?.()\n}\n\n/**\n * An HTML tooltip (`.tc-tooltip`) for the highlighted category, placed next\n * to it inside the chart element. Configure it with the `tooltip` option;\n * `theme: 'light'` adds `.tc-tooltip-light` for the white variant.\n */\nexport function tooltip(): ChartPlugin {\n return {\n name: 'tooltip',\n install(chart) {\n const stop = listenPointer(chart)\n const el = chart.element as HTMLElement\n // Positioning context for the tooltip (zero specificity in CSS, so page styles win).\n const addedClass = !el.classList.contains('tc-container')\n el.classList.add('tc-container')\n let tip: HTMLElement | undefined\n /** Counts the renders, so a placement still waiting knows when it is out of date. */\n let turns = 0\n\n return {\n afterRender() {\n const option = chart.config.tooltip\n const hit = chart.active\n const anchor = hit && hitAnchor(hit, chart.pointer)\n if (\n option === false ||\n typeof document === 'undefined' ||\n !hit ||\n !anchor ||\n !Number.isFinite(anchor.x) ||\n !Number.isFinite(anchor.y)\n ) {\n turns++\n tip?.removeAttribute('data-visible')\n return\n }\n if (!tip) {\n tip = el.ownerDocument.createElement('div')\n tip.className = 'tc-tooltip'\n tip.setAttribute('aria-hidden', 'true')\n el.appendChild(tip)\n }\n const options = typeof option === 'object' ? option : undefined\n tip.classList.toggle('tc-tooltip-light', options?.theme === 'light')\n render(tip, tooltipContent(hit, options))\n\n // Placed with the tooltips of the other charts of this frame (see placeAll).\n const shown = tip\n const turn = ++turns\n waiting.push(() => {\n const svg = el.querySelector('svg.tc-chart')\n // A later render of this chart, or its end, overtook this one.\n if (!svg || turn !== turns) return undefined\n const { width, height } = chart.size\n const box = el.getBoundingClientRect()\n const rect = svg.getBoundingClientRect()\n // Screen pixels per pixel of the container (transformed or zoomed ancestors).\n const k = box.width > 0 && el.offsetWidth > 0 ? box.width / el.offsetWidth : 1\n const sx = rect.width > 0 ? rect.width / width / k : 1\n const sy = rect.height > 0 ? rect.height / height / k : 1\n const origin = {\n x: (rect.left - box.left) / k - el.clientLeft,\n y: (rect.top - box.top) / k - el.clientTop,\n }\n // Snap to the category, follow the pointer along the values\n // (a radar spoke runs both ways, so there it follows the pointer).\n const ax = hit.axis === 'y' || hit.guide ? anchor.x : hit.x\n const ay = hit.axis === 'y' ? (hit.y ?? anchor.y) : anchor.y\n // The tooltip may leave the container, up to what would cut it off.\n const clip = room(el)\n const place = placeTooltip(\n { x: origin.x + ax * sx, y: origin.y + ay * sy },\n { width: shown.offsetWidth, height: shown.offsetHeight },\n {\n x: (clip.left - box.left) / k - el.clientLeft,\n y: (clip.top - box.top) / k - el.clientTop,\n width: (clip.right - clip.left) / k,\n height: (clip.bottom - clip.top) / k,\n },\n )\n return () => {\n shown.style.transform = `translate(${place.x}px, ${place.y}px)`\n shown.dataset.side = place.side\n if (!shown.hasAttribute('data-visible')) {\n // Commit the position before becoming visible, so it does not glide in from the old spot.\n void getComputedStyle(shown).transform\n shown.setAttribute('data-visible', '')\n }\n }\n })\n schedule(waiting, placeAll)\n },\n destroy() {\n turns++\n if (tip) {\n render(tip, null)\n tip.remove()\n }\n if (addedClass) el.classList.remove('tc-container')\n stop?.()\n },\n }\n },\n }\n}\n","import type { ChartPlugin } from '../plugin.ts'\nimport { download } from './download.ts'\nimport { highlight } from './highlight.ts'\nimport { keyboard } from './keyboard.ts'\nimport { legend } from './legend.ts'\nimport { pointer } from './pointer.ts'\nimport { sync } from './sync.ts'\nimport { dataTable } from './table.ts'\nimport { tooltip } from './tooltip.ts'\n\nexport { dataTable, download, highlight, keyboard, legend, pointer, sync, tooltip }\n\n/** The built-in plugins installed by the default `Chart` from `@tabler/charts`. */\nexport function defaultPlugins(): ChartPlugin[] {\n return [highlight(), legend(), tooltip(), dataTable(), keyboard(), sync(), download()]\n}\n","import { type ChartConfig, Chart as CoreChart } from './chart.ts'\nimport { defaultPlugins } from './plugins/index.ts'\n\n/**\n * A chart with every built-in plugin installed: hover highlight, legend,\n * tooltip, data table and keyboard navigation. Each can be switched off in\n * the config (`tooltip: false`, …). For the smallest bundle, use the bare\n * `Chart` from `@tabler/charts/core` and pick plugins explicitly.\n *\n * ```ts\n * const chart = new Chart('#sales', { type: line, data })\n * ```\n */\nexport class Chart<O extends object = object> extends CoreChart<O> {\n constructor(target: Element | string, config: ChartConfig<O>) {\n super(target, config, defaultPlugins())\n }\n}\n","import { h, type VNode } from '../vnode.ts'\n\n/**\n * A vertical luminance mask shared by all gradient areas of a chart (line, area, sparkline). Areas keep their\n * series color from CSS; the mask only fades them, with stop opacities read\n * from `--tc-area-gradient-start` / `--tc-area-gradient-end`.\n */\nexport function fadeMask(id: string): VNode {\n return h(\n 'mask',\n { id, maskContentUnits: 'objectBoundingBox' },\n h(\n 'linearGradient',\n { id: `${id}-gradient`, x1: 0, y1: 0, x2: 0, y2: 1 },\n h('stop', { class: 'tc-fade-start', offset: 0 }),\n h('stop', { class: 'tc-fade-end', offset: 1 }),\n ),\n h('rect', { width: 1, height: 1, fill: `url(#${id}-gradient)` }),\n )\n}\n","import { type Series, seriesKey } from './cartesian.ts'\n\n/** Stack series on top of each other; `'percent'` normalizes every category to 100%. */\nexport type StackMode = boolean | 'percent'\n\n/** A stacked segment from `y0` to `y1` (in data units). */\nexport interface Segment {\n y0: number\n y1: number\n}\n\nexport interface StackOptions {\n /** Normalize each category by the sum of absolute values. */\n percent?: boolean\n /** Count missing values as zero (areas) instead of leaving no segment (bars). */\n nullAsZero?: boolean\n /** Keys of hidden series, which get no segment and do not stack. */\n hidden?: ReadonlySet<string>\n}\n\n/**\n * Stack series per category: positive values grow up from zero and\n * negative values down from zero, each on their own running total (like\n * d3's diverging offset), so gains and losses never interleave. Returns one\n * array per series with a segment per category, or `null` for no segment.\n */\nexport function stackSeries(\n series: readonly Series[],\n count: number,\n options: StackOptions = {},\n): (Segment | null)[][] {\n const { percent = false, nullAsZero = false, hidden } = options\n const visible = series.map((s) => !hidden?.has(seriesKey(s)))\n const out = series.map(() => new Array<Segment | null>(count).fill(null))\n\n for (let i = 0; i < count; i++) {\n let total = 0\n if (percent) {\n series.forEach((s, j) => {\n const v = s.values[i]\n if (visible[j] && v != null) total += Math.abs(v)\n })\n }\n let up = 0\n let down = 0\n let lastUp: Segment | undefined\n let lastDown: Segment | undefined\n for (let j = 0; j < series.length; j++) {\n const s = series[j] as Series\n if (!visible[j]) continue\n const raw = s.values[i]\n const valid = raw != null\n if (!valid && !nullAsZero) continue\n let v = valid ? (raw as number) : 0\n if (percent) v = total === 0 ? 0 : v / total\n const row = out[j] as (Segment | null)[]\n if (v < 0) {\n const segment: Segment = { y0: down, y1: down + v }\n row[i] = segment\n down += v\n lastDown = segment\n } else {\n const segment: Segment = { y0: up, y1: up + v }\n row[i] = segment\n up += v\n lastUp = segment\n }\n }\n // Shares must end exactly at ±100%: floating point drift (1.0000000000000002)\n // would otherwise make nice() stretch the axis to 120%, or leave a hairline gap.\n if (percent) {\n if (lastUp && Math.abs(up - 1) < 1e-9) lastUp.y1 = 1\n if (lastDown && Math.abs(down + 1) < 1e-9) lastDown.y1 = -1\n }\n }\n return out\n}\n\n/** Every segment boundary, for the value domain. */\nexport function stackBounds(stacks: readonly (Segment | null)[][]): number[] {\n const values: number[] = []\n for (const row of stacks) {\n for (const segment of row) if (segment) values.push(segment.y0, segment.y1)\n }\n return values\n}\n","import type { ChartType, RenderContext } from '../chart.ts'\nimport { fadeMask } from '../components/fade.ts'\nimport { feature } from '../features.ts'\nimport { round } from '../layout.ts'\nimport { areaPath, type Curve, linePath, type Point } from '../shapes/path.ts'\nimport { type ChildInput, h } from '../vnode.ts'\nimport {\n type CartesianOptions,\n cartesianLayout,\n categoryInteraction,\n plottable,\n resolveLabels,\n type Series,\n seriesAttrs,\n seriesKey,\n seriesLegend,\n seriesTable,\n} from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\nimport { type StackMode, stackBounds, stackSeries } from './stack.ts'\n\nexport interface LineOptions extends CartesianOptions {\n /** Interpolation between points. Defaults to `'monotone'`. */\n curve?: Curve\n /** Draw dots on every point, only on the last one, or none. Defaults to `'none'`. */\n points?: 'none' | 'last' | 'all'\n /** Dot radius in pixels. Defaults to `4`. */\n pointRadius?: number\n /** Bridge `null` values instead of leaving gaps. Defaults to `false`. */\n connectNulls?: boolean\n /** Fill the area under each line. Defaults to `false` (`true` for `area`). */\n area?: boolean\n /**\n * Area fill style: a vertical fade (strength set by `--tc-area-gradient-start`\n * / `--tc-area-gradient-end`) or a flat wash (`--tc-area-opacity`).\n * Defaults to `'gradient'`, or `'solid'` for stacked areas.\n */\n fill?: 'gradient' | 'solid'\n /**\n * Stack series on top of each other (each line draws the running total);\n * `'percent'` shows every category as 100%. Missing values count as zero.\n */\n stacked?: StackMode\n /**\n * Draw long series with at most this many points, chosen by LTTB\n * downsampling so peaks and valleys survive. Tooltips and keyboard\n * navigation still use every value. Off by default.\n */\n decimate?: number\n}\n\n/** Points in pixels for a series; `null` for missing values. */\nfunction seriesPoints(\n series: Series,\n count: number,\n x: (i: number) => number,\n y: (v: number) => number,\n connectNulls: boolean,\n valid: (v: number | null | undefined) => v is number,\n): Point[] {\n const points: Point[] = []\n for (let i = 0; i < count; i++) {\n const v = series.values[i]\n if (!valid(v)) {\n if (!connectNulls) points.push(null)\n } else {\n points.push([x(i), y(v)])\n }\n }\n return points\n}\n\n/** Render line (and optionally area) series; shared by `line` and `area`. */\nexport function renderLines(options: LineOptions, ctx: RenderContext, fill: boolean): ChildInput {\n const {\n curve = 'monotone',\n points = 'none',\n pointRadius = 4,\n connectNulls = false,\n area: filled = fill,\n stacked = false,\n decimate,\n // Faded layers would show light seams between stacked areas, so stacks default to solid.\n fill: fillStyle = stacked ? 'solid' : 'gradient',\n } = options\n const overhang = points === 'none' ? 2 : pointRadius + 2\n const { series } = options.data\n const count = resolveLabels(options.data).length\n const stacks = stacked\n ? stackSeries(series, count, {\n percent: stacked === 'percent',\n nullAsZero: true,\n hidden: ctx.hidden,\n })\n : null\n const layout = cartesianLayout(options, ctx, {\n scale: 'point',\n zero: filled || stacks !== null,\n overhang,\n ...(stacks ? { values: stackBounds(stacks) } : {}),\n ...(stacked === 'percent' ? { tickFormat: { style: 'percent' } } : {}),\n })\n const { x, y, labels } = layout\n const baseline = y(Math.min(Math.max(0, y.domain[0]), y.domain[1]))\n ctx.onHitTest(\n categoryInteraction(layout, options, ctx, (seriesIndex, i, v) => ({\n x: x.at(i),\n y: y(stacks ? (stacks[seriesIndex]?.[i]?.y1 ?? 0) : v),\n })),\n )\n const gradient = filled && fillStyle === 'gradient'\n const fadeId = `${ctx.id}-fade`\n\n // Hidden series keep their index (and color slot) but draw nothing.\n const visible = (s: Series) => !ctx.hidden.has(seriesKey(s))\n const all = series.map((s, index) => {\n if (!visible(s)) return []\n // Stacked series draw their running total.\n const stack = stacks?.[index]\n if (stack) return stack.map((seg, i): Point => (seg ? [x.at(i), y(seg.y1)] : null))\n return seriesPoints(\n s,\n labels.length,\n (i) => x.at(i),\n y,\n connectNulls,\n (v) => plottable(v, options.y),\n )\n })\n /** Indices drawn per series: a downsampled subset when `decimate` is set. */\n const kept = all.map((pts) =>\n decimate !== undefined && pts.length > decimate ? feature('decimate')(pts, decimate) : null,\n )\n const drawn = (index: number): Point[] => {\n const pts = all[index] as Point[]\n const keep = kept[index]\n return keep ? keep.map((i) => pts[i] as Point) : pts\n }\n /** Area bottom: zero, or the top of the layer below for stacks (downsampled alike). */\n const bottom = (index: number): number | (number | null)[] => {\n const stack = stacks?.[index]\n if (!stack) return baseline\n const bottoms = stack.map((seg) => (seg ? y(seg.y0) : null))\n const keep = kept[index]\n return keep ? keep.map((i) => bottoms[i] ?? null) : bottoms\n }\n\n // All areas go below all lines, so a filled series never covers another line.\n const areas =\n filled &&\n h(\n 'g',\n { class: 'tc-areas' },\n options.data.series.map(\n (s, index) =>\n visible(s) &&\n h(\n 'g',\n seriesAttrs(s, index),\n h('path', {\n class: ['tc-area', gradient && 'tc-area-gradient'],\n d: areaPath(drawn(index), bottom(index), { curve }),\n mask: gradient ? `url(#${fadeId})` : undefined,\n }),\n ),\n ),\n )\n\n const lines = options.data.series.map((s, index) => {\n if (!visible(s)) return null\n const pts = drawn(index)\n const valid = pts.filter((p): p is readonly [number, number] => p != null)\n const dots = points === 'all' ? valid : points === 'last' ? valid.slice(-1) : []\n return h(\n 'g',\n seriesAttrs(s, index),\n h('path', { class: 'tc-line', d: linePath(pts, { curve }) }),\n dots.length > 0 &&\n h(\n 'g',\n { class: 'tc-points' },\n dots.map(([cx, cy]) =>\n h('circle', {\n key: cx,\n class: 'tc-point',\n cx: round(cx),\n cy: round(cy),\n r: pointRadius,\n }),\n ),\n ),\n )\n })\n\n return [\n h('defs', { key: 'defs' }, layout.clip.def, gradient && fadeMask(fadeId)),\n layout.background,\n // Layers are keyed: an annotation band or a grid that comes and goes must not\n // shift the series list onto another node (that would recreate every series).\n h('g', { key: 'series', class: 'tc-series-list', 'clip-path': layout.clip.url }, areas, lines),\n layout.foreground,\n ]\n}\n\n/**\n * Line chart: one line per series over category labels.\n *\n * ```ts\n * new Chart('#el', {\n * type: line,\n * data: { labels: ['Jan', 'Feb', 'Mar'], series: [{ name: 'Sales', values: [3, 5, 4] }] },\n * })\n * ```\n */\nexport const line: ChartType<LineOptions> = {\n name: 'line',\n clean: cleanData(cleanSeries),\n render: (options, ctx) => renderLines(options, ctx, false),\n legend: (options) => seriesLegend(options.data),\n table: (options, ctx, limit) => seriesTable(options, ctx, limit),\n}\n","import type { ChartType } from '../chart.ts'\nimport { seriesLegend, seriesTable } from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\nimport { type LineOptions, renderLines } from './line.ts'\n\n/** Options of the area chart: line options with the fill always on. */\nexport type AreaOptions = Omit<LineOptions, 'area'>\n\n/**\n * Area chart: filled lines over category labels, with zero in the y domain\n * by default and a vertical fade (`fill: 'gradient'`).\n *\n * ```ts\n * new Chart('#el', {\n * type: area,\n * data: { labels: ['Jan', 'Feb', 'Mar'], series: [{ name: 'Sales', values: [3, 5, 4] }] },\n * })\n * ```\n */\nexport const area: ChartType<AreaOptions> = {\n name: 'area',\n clean: cleanData(cleanSeries),\n render: (options, ctx) => renderLines(options, ctx, true),\n legend: (options) => seriesLegend(options.data),\n table: (options, ctx, limit) => seriesTable(options, ctx, limit),\n}\n","import { round as to2 } from '../layout.ts'\n\n/** Rounded for path data, without a `-0`. */\nconst round = (value: number): number => {\n const rounded = to2(value)\n return rounded === 0 ? 0 : rounded\n}\n\n/**\n * Path of a vertical bar from `baseline` to `value` (both y in pixels),\n * `x`…`x + width` wide. Only the data end is rounded, with `radius` clamped\n * to half the width and to the bar height; the baseline end stays square.\n * Works for bars growing up (value above baseline) and down (negative values).\n * Square corners are zero-radius arcs and every side is an `L`, so every\n * bar path, vertical or horizontal, has the same commands and CSS can\n * transition `d` between rounded and square (stacking) and between\n * orientations.\n */\nexport function barPath(\n x: number,\n width: number,\n baseline: number,\n value: number,\n radius = 0,\n): string {\n const w = Math.max(0, width)\n const height = Math.abs(baseline - value)\n const r = Math.max(0, Math.min(radius, w / 2, height))\n const x0 = round(x)\n const x1 = round(x + w)\n const b = round(baseline)\n const v = round(value)\n\n const up = value <= baseline\n const edge = round(up ? value + r : value - r)\n const sweep = up ? 1 : 0\n const rr = round(r)\n return (\n `M${x0},${b}L${x0},${edge}` +\n `A${rr},${rr},0,0,${sweep},${round(x + r)},${v}` +\n `L${round(x + w - r)},${v}` +\n `A${rr},${rr},0,0,${sweep},${x1},${edge}` +\n `L${x1},${b}Z`\n )\n}\n\n/**\n * Path of a horizontal bar from `baseline` to `value` (both x in pixels),\n * `y`…`y + height` tall. Only the data end is rounded, with `radius` clamped\n * to half the height and to the bar length; the baseline end stays square.\n * Works for bars growing right (positive values) and left (negative values).\n * Same commands as `barPath`, so a chart can morph between orientations.\n */\nexport function hbarPath(\n y: number,\n height: number,\n baseline: number,\n value: number,\n radius = 0,\n): string {\n const hgt = Math.max(0, height)\n const length = Math.abs(value - baseline)\n const r = Math.max(0, Math.min(radius, hgt / 2, length))\n const y0 = round(y)\n const y1 = round(y + hgt)\n const b = round(baseline)\n const v = round(value)\n\n const right = value >= baseline\n const edge = round(right ? value - r : value + r)\n const sweep = right ? 1 : 0\n const rr = round(r)\n return (\n `M${b},${y0}L${edge},${y0}` +\n `A${rr},${rr},0,0,${sweep},${v},${round(y + r)}` +\n `L${v},${round(y + hgt - r)}` +\n `A${rr},${rr},0,0,${sweep},${edge},${y1}` +\n `L${b},${y1}Z`\n )\n}\n","import type { RenderContext } from '../chart.ts'\nimport { axisSize, bandTicks, type Tick, thinTicks } from '../components/axis.ts'\nimport { estimateTextWidth, innerRect, insets } from '../layout.ts'\nimport { type BandKey, band } from '../scales/band.ts'\nimport {\n type CartesianLayout,\n type CartesianLayoutOptions,\n type CartesianOptions,\n EDGE,\n finishLayout,\n type Label,\n labelFormatter,\n labelKey,\n resolveLabels,\n TICK_SPACING_X,\n valueAxis,\n} from './cartesian.ts'\n\n/**\n * Cartesian layout with categories along y (labels on the left) and values\n * along x (labels at the bottom), for horizontal bars. Only bar charts use\n * it, so it lives outside `cartesianLayout()` and stays out of other bundles.\n */\nexport function horizontalLayout(\n options: CartesianOptions,\n ctx: RenderContext,\n layout: CartesianLayoutOptions,\n): CartesianLayout {\n const yOptions = options.y ?? {}\n const xOptions = options.x ?? {}\n const { fontSize, width, height } = ctx\n const overhang = layout.overhang ?? 0\n const pad = insets(options.padding)\n const labels = resolveLabels(options.data)\n const format = labelFormatter(options, ctx)\n const value = valueAxis(options, ctx, layout, Math.round(width / TICK_SPACING_X))\n const probeValues = value.probe\n const showValues = yOptions.show !== false\n const showCategories = xOptions.show !== false && labels.length > 0\n\n const probeCategories: Tick[] = labels.map((label, i) => ({\n value: labelKey(label),\n position: 0,\n label: format(label, i),\n }))\n const edgeLabel = (tick: Tick | undefined) =>\n showValues && tick ? Math.ceil(estimateTextWidth(tick.label, fontSize) / 2) : 0\n\n const margins = {\n top: pad.top + Math.max(overhang, EDGE / 2),\n right: pad.right + Math.max(edgeLabel(probeValues[probeValues.length - 1]), overhang, EDGE),\n bottom:\n pad.bottom +\n Math.max(showValues ? axisSize('bottom', probeValues, fontSize) : 0, overhang, EDGE / 2),\n left:\n pad.left +\n Math.max(\n showCategories ? axisSize('left', probeCategories, fontSize) : 0,\n edgeLabel(probeValues[0]),\n overhang,\n EDGE,\n ),\n }\n const area = innerRect(width, height, margins)\n\n const keys = labels.map(labelKey)\n const x = band(keys, [area.y, area.y + area.height], {\n paddingInner: layout.paddingInner ?? 0.3,\n paddingOuter: layout.paddingOuter ?? 0.15,\n })\n const y = value.scale([area.x, area.x + area.width])\n const yTicks = thinTicks(value.ticks(y), 'bottom', fontSize)\n const xTicks = showCategories\n ? thinTicks(\n bandTicks(x, (_: BandKey, i) => format(labels[i] as Label, i)),\n 'left',\n fontSize,\n )\n : []\n\n // The value axis runs along x here, categories along y.\n return finishLayout(\n options,\n ctx,\n overhang,\n { area, labels, x, y, horizontal: true, xTicks, yTicks },\n keys,\n )\n}\n","import type { ChartType } from '../chart.ts'\nimport { feature } from '../features.ts'\nimport { barPath, hbarPath } from '../shapes/bar.ts'\nimport type { Curve, Point } from '../shapes/path.ts'\nimport { h } from '../vnode.ts'\nimport {\n type CartesianLayoutOptions,\n type CartesianOptions,\n cartesianLayout,\n categoryInteraction,\n labelKey,\n plottable,\n resolveLabels,\n seriesAttrs,\n seriesKey,\n seriesLegend,\n seriesTable,\n} from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\nimport { horizontalLayout } from './horizontal.ts'\nimport { type Segment, type StackMode, stackBounds, stackSeries } from './stack.ts'\n\nexport interface BarOptions extends CartesianOptions {\n /** Corner radius of the data end of each bar (or stack). Defaults to `4`. */\n radius?: number\n /** Maximum bar thickness in pixels; leftover band space stays empty. Defaults to `24`. */\n maxBarWidth?: number\n /** Gap between bars of a group, or between stacked segments, in pixels. Defaults to `2`. */\n gap?: number\n /** Share of each category left empty between groups, `0…1`. Defaults to `0.3`. */\n groupPadding?: number\n /**\n * Stack series in one bar per category instead of side by side; `'percent'`\n * shows each category as 100%. Negative values stack down from zero.\n */\n stacked?: StackMode\n /**\n * `'horizontal'` lays categories out along y with bars growing right\n * (left for negative values). The `x` / `y` options keep describing the\n * category / value axis. Defaults to `'vertical'`.\n */\n orientation?: 'vertical' | 'horizontal'\n /** Interpolation of series drawn as lines (`series.type`). Defaults to `'monotone'`. */\n curve?: Curve\n}\n\n/**\n * Bar chart: vertical bars per category, grouped side by side or stacked,\n * growing from zero (negative values grow down).\n *\n * ```ts\n * new Chart('#el', {\n * type: bar,\n * data: { labels: ['Q1', 'Q2'], series: [{ name: '2025', values: [3, 5] }] },\n * stacked: true,\n * })\n * ```\n */\nexport const bar: ChartType<BarOptions> = {\n name: 'bar',\n clean: cleanData(cleanSeries),\n render(options, ctx) {\n const {\n radius = 4,\n maxBarWidth = 24,\n gap = 2,\n groupPadding = 0.3,\n stacked = false,\n orientation = 'vertical',\n curve = 'monotone',\n } = options\n const horizontal = orientation === 'horizontal'\n const { series } = options.data\n const count = resolveLabels(options.data).length\n // Series drawn as lines sit on top of the bars and stay out of the stacks.\n const isLine = (index: number) => (series[index]?.type ?? 'bar') !== 'bar'\n const lineKeys = series.filter((_, index) => isLine(index)).map(seriesKey)\n const stackHidden = lineKeys.length ? new Set([...ctx.hidden, ...lineKeys]) : ctx.hidden\n const stacks = stacked\n ? stackSeries(series, count, { percent: stacked === 'percent', hidden: stackHidden })\n : null\n\n const layoutOptions: CartesianLayoutOptions = {\n scale: 'band',\n zero: true,\n paddingInner: groupPadding,\n paddingOuter: groupPadding / 2,\n ...(stacks\n ? {\n values: [\n ...stackBounds(stacks),\n ...series.flatMap((s, index) => (isLine(index) ? s.values : [])),\n ],\n }\n : {}),\n ...(stacked === 'percent' ? { tickFormat: { style: 'percent' } } : {}),\n }\n const layout = horizontal\n ? horizontalLayout(options, ctx, layoutOptions)\n : cartesianLayout(options, ctx, layoutOptions)\n const { x, y, labels } = layout\n\n // Hidden series keep their color slot but give up their place in the group.\n const slots = new Map<number, number>()\n series.forEach((s, index) => {\n if (!ctx.hidden.has(seriesKey(s)) && !isLine(index)) slots.set(index, slots.size)\n })\n const order = [...slots.keys()]\n const columns = stacks ? 1 : Math.max(1, slots.size)\n\n const barWidth = Math.max(\n 0,\n Math.min(maxBarWidth, (x.bandwidth - (stacks ? 0 : gap * (columns - 1))) / columns),\n )\n const groupWidth = barWidth * columns + (stacks ? 0 : gap * (columns - 1))\n const offset = (x.bandwidth - groupWidth) / 2\n const barLeft = (seriesIndex: number, i: number) =>\n x.at(i) + offset + (stacks ? 0 : (slots.get(seriesIndex) ?? 0) * (barWidth + gap))\n\n /** Data extent of a bar: from zero to the value, or its stacked segment. */\n const segment = (seriesIndex: number, i: number): Segment | null => {\n if (stacks) return stacks[seriesIndex]?.[i] ?? null\n const v = series[seriesIndex]?.values[i]\n return plottable(v, options.y) ? { y0: 0, y1: v } : null\n }\n\n // In a stack only the outermost segment of each sign gets rounded.\n const outer = labels.map((_, i) => {\n let up = -1\n let down = -1\n for (const index of order) {\n const seg = segment(index, i)\n if (!seg) continue\n if (seg.y1 > seg.y0) up = index\n else if (seg.y1 < seg.y0) down = index\n }\n return { up, down }\n })\n\n ctx.onHitTest(\n categoryInteraction(\n layout,\n options,\n ctx,\n (seriesIndex, i, v) => {\n if (isLine(seriesIndex)) {\n const across = x.at(i) + x.bandwidth / 2\n return horizontal ? { x: y(v), y: across } : { x: across, y: y(v) }\n }\n const left = barLeft(seriesIndex, i)\n const seg = segment(seriesIndex, i)\n const end = y(seg?.y1 ?? 0)\n const base = y(seg?.y0 ?? 0)\n // The bar's box, for value labels inside it.\n const lo = Math.min(end, base)\n const length = Math.abs(end - base)\n return horizontal\n ? {\n x: end,\n y: left + barWidth / 2,\n box: { x: lo, y: left, width: length, height: barWidth },\n }\n : {\n x: left + barWidth / 2,\n y: end,\n box: { x: left, y: lo, width: barWidth, height: length },\n }\n },\n (px, py, i) => {\n // Pointer position across the categories and along the values.\n const across = horizontal ? py : px\n const along = horizontal ? px : py\n if (stacks) {\n // The segment under the pointer, within the column (gaps included).\n const left = barLeft(0, i)\n if (across < left - gap / 2 || across > left + barWidth + gap / 2) return undefined\n return order.find((index) => {\n const seg = segment(index, i)\n if (!seg) return false\n const a = y(seg.y0)\n const b = y(seg.y1)\n return along >= Math.min(a, b) - gap / 2 && along <= Math.max(a, b) + gap / 2\n })\n }\n // The bar under the pointer, gaps included, so thin bars are easy to hit.\n const slot = Math.floor((across - (x.at(i) + offset) + gap / 2) / (barWidth + gap))\n const seriesIndex = order[slot]\n return seriesIndex !== undefined && segment(seriesIndex, i) ? seriesIndex : undefined\n },\n ),\n )\n\n const groups = series.map(\n (s, index) =>\n slots.has(index) &&\n h(\n 'g',\n seriesAttrs(s, index),\n labels.map((label, i) => {\n const seg = segment(index, i)\n if (!seg) return null\n const negative = seg.y1 < seg.y0\n // Leave a surface-colored gap where this segment sits on another one;\n // positive values grow toward smaller y, but toward larger x.\n const away = (negative ? 1 : -1) * (horizontal ? -1 : 1)\n const inner = seg.y0 === 0 ? 0 : away * gap\n const rounded = !stacks || (negative ? outer[i]?.down : outer[i]?.up) === index\n const draw = horizontal ? hbarPath : barPath\n return h('path', {\n key: labelKey(label),\n class: ['tc-bar', negative && 'tc-bar-negative', horizontal && 'tc-bar-horizontal'],\n d: draw(\n barLeft(index, i),\n barWidth,\n y(seg.y0) + inner,\n y(seg.y1),\n rounded ? radius : 0,\n ),\n })\n }),\n ),\n )\n\n // Lines through the band centers, drawn after (over) every bar. The path\n // generators come with the line module, so plain bar charts do not ship them.\n const paths = lineKeys.length ? feature('line') : null\n const baseline = y(Math.min(Math.max(0, y.domain[0]), y.domain[1]))\n const lines = series.map((s, index) => {\n if (!paths) return null\n if (!isLine(index) || ctx.hidden.has(seriesKey(s))) return null\n const points = labels.map((_, i): Point => {\n const v = s.values[i]\n if (!plottable(v, options.y)) return null\n const center = x.at(i) + x.bandwidth / 2\n return horizontal ? [y(v), center] : [center, y(v)]\n })\n // Areas need a vertical baseline; sideways they fall back to a line.\n const filled = s.type === 'area' && !horizontal\n return h(\n 'g',\n seriesAttrs(s, index),\n filled && h('path', { class: 'tc-area', d: paths.areaPath(points, baseline, { curve }) }),\n h('path', { class: 'tc-line', d: paths.linePath(points, { curve }) }),\n )\n })\n\n return [\n h('defs', { key: 'defs' }, layout.clip.def),\n layout.background,\n // Layers are keyed: an annotation band or a grid that comes and goes must not\n // shift the series list onto another node (that would recreate every series).\n h(\n 'g',\n { key: 'series', class: 'tc-series-list', 'clip-path': layout.clip.url },\n groups,\n lines,\n ),\n layout.foreground,\n ]\n },\n legend: (options) => seriesLegend(options.data),\n table: (options, ctx, limit) => seriesTable(options, ctx, limit),\n}\n","import type { ChartType } from '../chart.ts'\nimport type { Hit, Interaction } from '../interaction.ts'\nimport type { InsetsInput } from '../layout.ts'\nimport { round } from '../layout.ts'\nimport { h } from '../vnode.ts'\nimport type { Annotation } from './annotations.ts'\nimport {\n type CartesianData,\n type CartesianOptions,\n type CategoryAxisOptions,\n cartesianLayout,\n categoryInteraction,\n type Label,\n labelKey,\n plottable,\n seriesTable,\n type ValueAxisOptions,\n} from './cartesian.ts'\nimport { cleanData, finite, label, records } from './clean.ts'\n\n/** One period: where the price opened, its range and where it closed. */\nexport interface Candle {\n /** The period (a date for `x: { type: 'time' }`, or any label). */\n x: Label\n open: number\n high: number\n low: number\n close: number\n}\n\n/**\n * A rounded rectangle with the same commands whatever its size and radius\n * (a zero radius draws square corners), so CSS can morph one into another.\n */\nconst bodyPath = (x: number, y: number, w: number, h: number, r: number): string => {\n const a = `A${r},${r},0,0,1,`\n return `M${round(x + r)},${y}H${round(x + w - r)}${a}${round(x + w)},${round(y + r)}V${round(y + h - r)}${a}${round(x + w - r)},${round(y + h)}H${round(x + r)}${a}${x},${round(y + h - r)}V${round(y + r)}${a}${round(x + r)},${y}Z`\n}\n\nexport interface CandlestickOptions {\n data: readonly Candle[]\n /** Maximum candle body width in pixels. Defaults to `16`. */\n maxCandleWidth?: number\n /** Share of each period left empty between candles, `0…1`. Defaults to `0.3`. */\n groupPadding?: number\n /** Extra space around the plot area, in pixels. */\n padding?: InsetsInput\n /** Corner radius of the bodies. Defaults to `1`. */\n radius?: number\n x?: CategoryAxisOptions\n y?: ValueAxisOptions\n /** Reference lines and bands, e.g. a price target or a trading halt. */\n annotations?: readonly Annotation[]\n}\n\nconst UP = 'var(--tc-up-color,var(--tc-color-6))'\nconst DOWN = 'var(--tc-negative-color,var(--tc-color-8))'\n\n/** Whether every price can be placed on the value axis (positive ones only on a log axis). */\nconst valid = (c: Candle, axis: ValueAxisOptions | undefined): boolean =>\n [c.open, c.high, c.low, c.close].every((v) => plottable(v, axis))\n\n/** The candles as four series, for the shared axes, tooltip and table. */\nfunction asCartesian(options: CandlestickOptions): CartesianOptions {\n const pick = (key: 'open' | 'high' | 'low' | 'close') =>\n options.data.map((c) => (valid(c, options.y) ? c[key] : null))\n const data: CartesianData = {\n labels: options.data.map((c) => c.x),\n series: [\n { name: 'Open', values: pick('open') },\n { name: 'High', values: pick('high') },\n { name: 'Low', values: pick('low') },\n { name: 'Close', values: pick('close') },\n ],\n }\n const out: CartesianOptions = { data }\n if (options.x) out.x = options.x\n if (options.y) out.y = options.y\n if (options.padding !== undefined) out.padding = options.padding\n if (options.annotations) out.annotations = options.annotations\n return out\n}\n\n/**\n * Candlestick (OHLC) chart: per period a wick from low to high and a body\n * from open to close, green when it closed higher (`--tc-up-color`) and red\n * when lower (`--tc-negative-color`).\n *\n * ```ts\n * new Chart('#el', {\n * type: candlestick,\n * data: [{ x: '2026-01-01', open: 98, high: 102, low: 89, close: 94 }],\n * x: { type: 'time' },\n * })\n * ```\n */\nexport const candlestick: ChartType<CandlestickOptions> = {\n name: 'candlestick',\n clean: cleanData((data) =>\n records(data, (c) => ({\n ...c,\n x: label(c.x),\n open: finite(c.open),\n high: finite(c.high),\n low: finite(c.low),\n close: finite(c.close),\n })),\n ),\n render(options, ctx) {\n const { maxCandleWidth = 16, groupPadding = 0.3, radius = 1 } = options\n const cartesian = asCartesian(options)\n const layout = cartesianLayout(cartesian, ctx, {\n scale: 'band',\n zero: false,\n paddingInner: groupPadding,\n paddingOuter: groupPadding / 2,\n })\n const { x, y, labels } = layout\n const width = Math.max(1, Math.min(maxCandleWidth, x.bandwidth))\n const center = (i: number) => x.at(i) + x.bandwidth / 2\n const up = (c: Candle) => c.close >= c.open\n\n const base = categoryInteraction(layout, cartesian, ctx, (_, i, v) => ({\n x: center(i),\n y: y(v),\n }))\n // Tooltip swatches take the color of the candle, not four palette slots.\n const paint = (hit: Hit | null): Hit | null => {\n const candle = hit ? options.data[hit.index] : undefined\n if (!hit || !candle) return hit\n const color = up(candle) ? UP : DOWN\n return { ...hit, items: hit.items.map((item) => ({ ...item, color })) }\n }\n const interaction: Interaction = {\n count: base.count,\n hitIndex: (i, s) => paint(base.hitIndex(i, s)),\n hitTest: (px, py) => paint(base.hitTest(px, py)),\n }\n ctx.onHitTest(interaction)\n\n const candles = options.data.map((c, i) => {\n if (!valid(c, options.y)) return null\n const cx = round(center(i))\n const top = y(Math.max(c.open, c.close))\n // A flat period still shows a 1px body.\n const bottom = Math.max(y(Math.min(c.open, c.close)), top + 1)\n const left = round(center(i) - width / 2)\n const r = round(Math.min(radius, width / 2, (bottom - top) / 2))\n return h(\n 'g',\n {\n key: labelKey(labels[i] as Label),\n class: ['tc-candle', up(c) ? 'tc-candle-up' : 'tc-candle-down'],\n },\n h('path', {\n class: 'tc-candle-wick',\n d: `M${cx},${round(y(c.high))}V${round(y(c.low))}`,\n }),\n // A path, not a rect, so it morphs between updates (d), in Safari too.\n h('path', {\n class: 'tc-candle-body',\n d: bodyPath(left, round(top), round(width), round(bottom - top), r),\n }),\n )\n })\n\n return [\n h('defs', { key: 'defs' }, layout.clip.def),\n layout.background,\n h(\n 'g',\n { key: 'series', class: 'tc-series-list tc-candles', 'clip-path': layout.clip.url },\n candles,\n ),\n layout.foreground,\n ]\n },\n table: (options, ctx, limit) => seriesTable(asCartesian(options), ctx, limit),\n}\n","/**\n * Annular sector paths with padding and rounded corners, ported from\n * d3-shape's `arc()` (ISC license, Mike Bostock) so geometry matches d3.\n *\n * Angles are in radians, clockwise from 12 o'clock; paths are centered on\n * the origin (translate the group to place them).\n */\n\nconst EPSILON = 1e-12\nconst PI = Math.PI\nconst HALF_PI = PI / 2\nconst TAU = 2 * PI\n\n/** Degrees to radians. */\nexport const DEG: number = Math.PI / 180\n\n/** Room kept around pies and gauges for the halo of the hovered arc, in pixels. */\nexport const HALO = 8\n\n// Clamped like d3-shape's math helpers, so out-of-range inputs saturate instead of NaN.\nconst asin = (x: number): number => (x >= 1 ? HALF_PI : x <= -1 ? -HALF_PI : Math.asin(x))\nconst acos = (x: number): number => (x > 1 ? 0 : x < -1 ? PI : Math.acos(x))\n\nexport interface ArcOptions {\n innerRadius: number\n outerRadius: number\n startAngle: number\n endAngle: number\n /** Angle removed between adjacent arcs, split between both ends. Defaults to `0`. */\n padAngle?: number\n /** Radius the pad angle is measured at. Defaults to `sqrt(inner² + outer²)` like d3. */\n padRadius?: number\n /** Radius of the rounded corners, clamped to half the ring thickness. Defaults to `0`. */\n cornerRadius?: number\n /** Decimal places kept in the path data. Defaults to `2`. */\n precision?: number\n}\n\n/** Canvas-like path builder emitting SVG path data (after d3-path). */\nclass ArcPath {\n d = ''\n #x0: number | null = null\n #y0: number | null = null\n #x1: number | null = null\n #y1: number | null = null\n readonly #k: number\n\n constructor(precision: number) {\n this.#k = 10 ** Math.max(0, Math.min(12, Math.floor(precision)))\n }\n\n #n(value: number): string {\n const rounded = Math.round(value * this.#k) / this.#k\n return String(rounded === 0 ? 0 : rounded)\n }\n\n moveTo(x: number, y: number): void {\n this.#x0 = this.#x1 = x\n this.#y0 = this.#y1 = y\n this.d += `M${this.#n(x)},${this.#n(y)}`\n }\n\n lineTo(x: number, y: number): void {\n this.#x1 = x\n this.#y1 = y\n this.d += `L${this.#n(x)},${this.#n(y)}`\n }\n\n closePath(): void {\n if (this.#x1 !== null) {\n this.#x1 = this.#x0\n this.#y1 = this.#y0\n this.d += 'Z'\n }\n }\n\n arc(x: number, y: number, r: number, a0: number, a1: number, ccw: boolean): void {\n const dx = r * Math.cos(a0)\n const dy = r * Math.sin(a0)\n const x0 = x + dx\n const y0 = y + dy\n const cw = ccw ? 0 : 1\n let da = ccw ? a0 - a1 : a1 - a0\n\n if (this.#x1 === null || this.#y1 === null) {\n this.d += `M${this.#n(x0)},${this.#n(y0)}`\n this.#x0 = x0\n this.#y0 = y0\n } else if (Math.abs(this.#x1 - x0) > EPSILON || Math.abs(this.#y1 - y0) > EPSILON) {\n this.d += `L${this.#n(x0)},${this.#n(y0)}`\n }\n this.#x1 = x0\n this.#y1 = y0\n if (!r) return\n\n if (da < 0) da = (da % TAU) + TAU\n const rr = this.#n(r)\n if (da > TAU - EPSILON) {\n // A complete circle: two half arcs.\n this.d += `A${rr},${rr},0,1,${cw},${this.#n(x - dx)},${this.#n(y - dy)}`\n this.d += `A${rr},${rr},0,1,${cw},${this.#n(x0)},${this.#n(y0)}`\n } else if (da > EPSILON) {\n this.#x1 = x + r * Math.cos(a1)\n this.#y1 = y + r * Math.sin(a1)\n this.d += `A${rr},${rr},0,${da >= PI ? 1 : 0},${cw},${this.#n(this.#x1)},${this.#n(this.#y1)}`\n }\n }\n}\n\nfunction intersect(\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n x3: number,\n y3: number,\n): [number, number] | undefined {\n const x10 = x1 - x0\n const y10 = y1 - y0\n const x32 = x3 - x2\n const y32 = y3 - y2\n let t = y32 * x10 - x32 * y10\n if (t * t < EPSILON) return undefined\n t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t\n return [x0 + t * x10, y0 + t * y10]\n}\n\n/** Center and tangent points of a rounded corner between a radial edge and an arc. */\nfunction cornerTangents(\n x0: number,\n y0: number,\n x1: number,\n y1: number,\n r1: number,\n rc: number,\n cw: boolean,\n) {\n const x01 = x0 - x1\n const y01 = y0 - y1\n const lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01)\n const ox = lo * y01\n const oy = -lo * x01\n const x11 = x0 + ox\n const y11 = y0 + oy\n const x10 = x1 + ox\n const y10 = y1 + oy\n const x00 = (x11 + x10) / 2\n const y00 = (y11 + y10) / 2\n const dx = x10 - x11\n const dy = y10 - y11\n const d2 = dx * dx + dy * dy\n const r = r1 - rc\n const D = x11 * y10 - x10 * y11\n const d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D))\n let cx0 = (D * dy - dx * d) / d2\n let cy0 = (-D * dx - dy * d) / d2\n const cx1 = (D * dy + dx * d) / d2\n const cy1 = (-D * dx + dy * d) / d2\n const dx0 = cx0 - x00\n const dy0 = cy0 - y00\n const dx1 = cx1 - x00\n const dy1 = cy1 - y00\n // Pick the intersection closest to the edge midpoint.\n if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {\n cx0 = cx1\n cy0 = cy1\n }\n return {\n cx: cx0,\n cy: cy0,\n x01: -ox,\n y01: -oy,\n x11: cx0 * (r1 / r - 1),\n y11: cy0 * (r1 / r - 1),\n }\n}\n\n/**\n * Padded angles, clamped corner radii and edge points of a partial sector,\n * shared by both path generators so they agree exactly.\n */\nfunction sector(\n options: ArcOptions,\n r0: number,\n r1: number,\n a0: number,\n a1: number,\n da: number,\n cw: boolean,\n) {\n let a01 = a0\n let a11 = a1\n let a00 = a0\n let a10 = a1\n let da0 = da\n let da1 = da\n const ap = (options.padAngle ?? 0) / 2\n const rp = ap > EPSILON ? (options.padRadius ?? Math.sqrt(r0 * r0 + r1 * r1)) : 0\n const rc = Math.min(Math.abs(r1 - r0) / 2, options.cornerRadius ?? 0)\n let rc0 = rc\n let rc1 = rc\n\n // Apply padding: equal linear offsets at both radii keep the gap parallel.\n if (rp > EPSILON) {\n let p0 = asin((rp / r0) * Math.sin(ap))\n let p1 = asin((rp / r1) * Math.sin(ap))\n da0 -= p0 * 2\n if (da0 > EPSILON) {\n p0 *= cw ? 1 : -1\n a00 += p0\n a10 -= p0\n } else {\n da0 = 0\n a00 = a10 = (a0 + a1) / 2\n }\n da1 -= p1 * 2\n if (da1 > EPSILON) {\n p1 *= cw ? 1 : -1\n a01 += p1\n a11 -= p1\n } else {\n da1 = 0\n a01 = a11 = (a0 + a1) / 2\n }\n }\n\n const x01 = r1 * Math.cos(a01)\n const y01 = r1 * Math.sin(a01)\n const x10 = r0 * Math.cos(a10)\n const y10 = r0 * Math.sin(a10)\n const x11 = r1 * Math.cos(a11)\n const y11 = r1 * Math.sin(a11)\n const x00 = r0 * Math.cos(a00)\n const y00 = r0 * Math.sin(a00)\n\n // Restrict the corner radius for narrow sectors, where corners would overlap.\n if (rc > EPSILON && da < PI) {\n const oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10)\n if (oc) {\n const ax = x01 - oc[0]\n const ay = y01 - oc[1]\n const bx = x11 - oc[0]\n const by = y11 - oc[1]\n const cos =\n (ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))\n const kc = 1 / Math.sin(acos(cos) / 2)\n const lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1])\n rc0 = Math.min(rc, (r0 - lc) / (kc - 1))\n rc1 = Math.min(rc, (r1 - lc) / (kc + 1))\n } else {\n rc0 = rc1 = 0\n }\n }\n return { a00, a01, a10, a11, da0, da1, rc, rc0, rc1, x01, y01, x10, y10, x11, y11, x00, y00 }\n}\n\n/** SVG path data of an annular sector (a pie slice when `innerRadius` is 0). */\nexport function arcPath(options: ArcOptions): string {\n const path = new ArcPath(options.precision ?? 2)\n let r0 = Math.max(0, options.innerRadius)\n let r1 = Math.max(0, options.outerRadius)\n if (r1 < r0) [r0, r1] = [r1, r0]\n const a0 = options.startAngle - HALF_PI\n const a1 = options.endAngle - HALF_PI\n const da = Math.abs(a1 - a0)\n const cw = a1 > a0\n\n if (!(r1 > EPSILON)) {\n path.moveTo(0, 0)\n } else if (da > TAU - EPSILON) {\n // A full ring (or disc).\n path.moveTo(r1 * Math.cos(a0), r1 * Math.sin(a0))\n path.arc(0, 0, r1, a0, a1, !cw)\n if (r0 > EPSILON) {\n path.moveTo(r0 * Math.cos(a1), r0 * Math.sin(a1))\n path.arc(0, 0, r0, a1, a0, cw)\n }\n } else {\n const g = sector(options, r0, r1, a0, a1, da, cw)\n const { a00, a01, a10, a11, da0, da1, rc, rc0, rc1, x01, y01, x10, y10 } = g\n\n // Outer ring.\n if (!(da1 > EPSILON)) {\n path.moveTo(x01, y01)\n } else if (rc1 > EPSILON) {\n const { x00, y00, x11, y11 } = g\n const t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw)\n const t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw)\n path.moveTo(t0.cx + t0.x01, t0.cy + t0.y01)\n if (rc1 < rc) {\n path.arc(t0.cx, t0.cy, rc1, Math.atan2(t0.y01, t0.x01), Math.atan2(t1.y01, t1.x01), !cw)\n } else {\n path.arc(t0.cx, t0.cy, rc1, Math.atan2(t0.y01, t0.x01), Math.atan2(t0.y11, t0.x11), !cw)\n path.arc(\n 0,\n 0,\n r1,\n Math.atan2(t0.cy + t0.y11, t0.cx + t0.x11),\n Math.atan2(t1.cy + t1.y11, t1.cx + t1.x11),\n !cw,\n )\n path.arc(t1.cx, t1.cy, rc1, Math.atan2(t1.y11, t1.x11), Math.atan2(t1.y01, t1.x01), !cw)\n }\n } else {\n path.moveTo(x01, y01)\n path.arc(0, 0, r1, a01, a11, !cw)\n }\n\n // Inner ring (or the center of a pie slice).\n if (!(r0 > EPSILON) || !(da0 > EPSILON)) {\n path.lineTo(x10, y10)\n } else if (rc0 > EPSILON) {\n const { x00, y00, x11, y11 } = g\n const t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw)\n const t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw)\n path.lineTo(t0.cx + t0.x01, t0.cy + t0.y01)\n if (rc0 < rc) {\n path.arc(t0.cx, t0.cy, rc0, Math.atan2(t0.y01, t0.x01), Math.atan2(t1.y01, t1.x01), !cw)\n } else {\n path.arc(t0.cx, t0.cy, rc0, Math.atan2(t0.y01, t0.x01), Math.atan2(t0.y11, t0.x11), !cw)\n path.arc(\n 0,\n 0,\n r0,\n Math.atan2(t0.cy + t0.y11, t0.cx + t0.x11),\n Math.atan2(t1.cy + t1.y11, t1.cx + t1.x11),\n cw,\n )\n path.arc(t1.cx, t1.cy, rc0, Math.atan2(t1.y11, t1.x11), Math.atan2(t1.y01, t1.x01), !cw)\n }\n } else {\n path.arc(0, 0, r0, a10, a00, cw)\n }\n }\n\n path.closePath()\n return path.d\n}\n\n/** Midpoint of an arc, e.g. to anchor a tooltip or label (like d3's `arc.centroid`). */\nexport function arcCentroid(options: ArcOptions): [number, number] {\n const r = (options.innerRadius + options.outerRadius) / 2\n const a = (options.startAngle + options.endAngle) / 2 - HALF_PI\n return [Math.cos(a) * r, Math.sin(a) * r]\n}\n\n/** Pad angle giving a constant `gap` (in pixels) between arcs of a ring. */\nexport function padAngleForGap(gap: number, innerRadius: number, outerRadius: number): number {\n const rp = Math.sqrt(innerRadius * innerRadius + outerRadius * outerRadius)\n return rp > 0 ? 2 * Math.asin(Math.min(1, gap / 2 / rp)) : 0\n}\n\n/** Angle of a point around the origin. */\nconst angleOf = (x: number, y: number): number => Math.atan2(y, x)\n\n/**\n * The same sector as {@link arcPath}, drawn with a fixed command structure:\n * every corner is always present (zero length when there is none) and each\n * ring is split into two half arcs, so the large-arc flag never flips.\n * Paths of different angles therefore keep their commands while an arc is\n * redrawn frame by frame, turning to its new angles (see `sweep`).\n */\nexport function arcPathStable(options: ArcOptions): string {\n const k = 10 ** Math.max(0, Math.min(12, Math.floor(options.precision ?? 2)))\n const n = (v: number): string => {\n const r = Math.round(v * k) / k\n return String(r === 0 ? 0 : r)\n }\n let d = ''\n const move = (x: number, y: number) => {\n d += `M${n(x)},${n(y)}`\n }\n const line = (x: number, y: number) => {\n d += `L${n(x)},${n(y)}`\n }\n const arc = (r: number, sweep: 0 | 1, x: number, y: number) => {\n d += `A${n(r)},${n(r)},0,0,${sweep},${n(x)},${n(y)}`\n }\n /** Two half arcs of radius `r` around the origin from angle `a0` to `a1`. */\n const ring = (r: number, a0: number, a1: number, ccw: boolean) => {\n let delta = ccw ? a0 - a1 : a1 - a0\n delta = ((delta % TAU) + TAU) % TAU\n if (delta < EPSILON && Math.abs(a1 - a0) > EPSILON) delta = TAU\n const mid = ccw ? a0 - delta / 2 : a0 + delta / 2\n const sweep: 0 | 1 = ccw ? 0 : 1\n arc(r, sweep, r * Math.cos(mid), r * Math.sin(mid))\n arc(r, sweep, r * Math.cos(a1), r * Math.sin(a1))\n }\n\n let r0 = Math.max(0, options.innerRadius)\n let r1 = Math.max(0, options.outerRadius)\n if (r1 < r0) [r0, r1] = [r1, r0]\n const a0 = options.startAngle - HALF_PI\n const a1 = options.endAngle - HALF_PI\n const da = Math.abs(a1 - a0)\n const cw = a1 > a0\n const outerSweep: 0 | 1 = cw ? 1 : 0\n\n if (!(r1 > EPSILON)) {\n // A point: eleven no-op commands at the origin.\n move(0, 0)\n for (let i = 0; i < 4; i++) arc(0, outerSweep, 0, 0)\n line(0, 0)\n for (let i = 0; i < 4; i++) arc(0, outerSweep, 0, 0)\n return `${d}Z`\n }\n\n if (da > TAU - EPSILON) {\n // A full ring (or disc): the seam between the two rings closes the path.\n const ox = r1 * Math.cos(a0)\n const oy = r1 * Math.sin(a0)\n move(ox, oy)\n arc(r1, outerSweep, ox, oy)\n ring(r1, a0, a0 + (cw ? TAU : -TAU) * (1 - 1e-9), !cw)\n arc(r1, outerSweep, ox, oy)\n const ix = r0 * Math.cos(a0)\n const iy = r0 * Math.sin(a0)\n line(ix, iy)\n arc(r0, outerSweep, ix, iy)\n if (r0 > EPSILON) ring(r0, a0, a0 + (cw ? -TAU : TAU) * (1 - 1e-9), cw)\n else for (let i = 0; i < 2; i++) arc(0, outerSweep, 0, 0)\n arc(r0, outerSweep, ix, iy)\n return `${d}Z`\n }\n\n const { a00, a01, a10, a11, da0, da1, rc, rc0, rc1, x01, y01, x10, y10, x11, y11, x00, y00 } =\n sector(options, r0, r1, a0, a1, da, cw)\n\n // Outer edge: corner, two ring halves, corner.\n if (da1 > EPSILON && rc1 > EPSILON) {\n const t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw)\n const t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw)\n move(t0.cx + t0.x01, t0.cy + t0.y01)\n if (rc1 < rc) {\n // Corners merged: one corner arc covers the edge, the rest is empty.\n const ex = t1.cx + t1.x01\n const ey = t1.cy + t1.y01\n arc(rc1, outerSweep, ex, ey)\n arc(r1, outerSweep, ex, ey)\n arc(r1, outerSweep, ex, ey)\n arc(rc1, outerSweep, ex, ey)\n } else {\n arc(rc1, outerSweep, t0.cx + t0.x11, t0.cy + t0.y11)\n ring(\n r1,\n angleOf(t0.cx + t0.x11, t0.cy + t0.y11),\n angleOf(t1.cx + t1.x11, t1.cy + t1.y11),\n !cw,\n )\n arc(rc1, outerSweep, t1.cx + t1.x01, t1.cy + t1.y01)\n }\n } else {\n move(x01, y01)\n arc(r1, outerSweep, x01, y01)\n if (da1 > EPSILON) ring(r1, a01, a11, !cw)\n else for (let i = 0; i < 2; i++) arc(r1, outerSweep, x01, y01)\n arc(r1, outerSweep, x11, y11)\n }\n\n // Inner edge (or the center of a pie slice): corner, two ring halves, corner.\n if (!(r0 > EPSILON) || !(da0 > EPSILON)) {\n line(x10, y10)\n for (let i = 0; i < 4; i++) arc(r0, outerSweep, x10, y10)\n } else if (rc0 > EPSILON) {\n const t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw)\n const t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw)\n line(t0.cx + t0.x01, t0.cy + t0.y01)\n if (rc0 < rc) {\n const ex = t1.cx + t1.x01\n const ey = t1.cy + t1.y01\n arc(rc0, outerSweep, ex, ey)\n arc(r0, outerSweep, ex, ey)\n arc(r0, outerSweep, ex, ey)\n arc(rc0, outerSweep, ex, ey)\n } else {\n arc(rc0, outerSweep, t0.cx + t0.x11, t0.cy + t0.y11)\n ring(r0, angleOf(t0.cx + t0.x11, t0.cy + t0.y11), angleOf(t1.cx + t1.x11, t1.cy + t1.y11), cw)\n arc(rc0, outerSweep, t1.cx + t1.x01, t1.cy + t1.y01)\n }\n } else {\n line(x10, y10)\n arc(r0, outerSweep, x10, y10)\n ring(r0, a10, a00, cw)\n arc(r0, outerSweep, x00, y00)\n }\n return `${d}Z`\n}\n","/**\n * Arcs that turn to their new angles: a transition of `d` moves each point\n * of a path along a straight line, which bends a slice out of its ring on\n * the way. A path that knows which arc it draws (the `arc` of its node, see\n * `arcNode`) is redrawn frame by frame instead, with the angles and radii\n * in between, so slices grow and shrink around the center. Timed by the\n * path's `transition-duration` (`--tc-duration`), with an ease-out curve.\n */\n\nimport { type ArcOptions, arcPathStable } from '../shapes/arc.ts'\nimport { type Attrs, h, type VNode } from '../vnode.ts'\nimport { stop, tween } from './tween.ts'\n\n/**\n * A path drawing this arc, which keeps the arc with it (radii, angles, pad\n * angle, corner radius): out of the markup, for the next render to sweep from.\n */\nexport function arcNode(name: string, arc: ArcOptions): VNode {\n const node = h('path', { class: name, d: arcPathStable(arc) })\n node.arc = [\n arc.innerRadius,\n arc.outerRadius,\n arc.startAngle,\n arc.endAngle,\n arc.padAngle ?? 0,\n arc.cornerRadius ?? 0,\n ]\n return node\n}\n\n/**\n * Take `el` from the arc of its last render, `prev`, to the arc of `next`.\n * Returns the attributes left for the caller to patch (all but `d`, set\n * here frame by frame), or nothing when there is no sweep: not an arc, the\n * same path, no arc to come from, or a chart without transitions.\n */\nexport function sweep(el: Element, prev: VNode, next: VNode): Attrs | undefined {\n const { arc, attrs } = next\n if (!arc || prev.attrs.d === attrs.d) return\n // An interrupted sweep continues from where the arc is now.\n const origin = stop(el) ?? prev.arc\n // Zero in a chart without transitions (static, resizing, reduced motion).\n const duration = Number.parseFloat(getComputedStyle(el).transitionDuration) * 1000\n if (!origin || !(duration > 0)) return\n tween(\n el,\n origin,\n arc,\n duration,\n ([innerRadius, outerRadius, startAngle, endAngle, padAngle, cornerRadius]) =>\n arcPathStable({\n innerRadius,\n outerRadius,\n startAngle,\n endAngle,\n padAngle,\n cornerRadius,\n } as ArcOptions),\n String(attrs.d),\n )\n return { ...attrs, d: prev.attrs.d as string }\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext } from '../chart.ts'\nimport { features } from '../features.ts'\nimport { formatNumber, getNumberFormat, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { type InsetsInput, innerRect, insets } from '../layout.ts'\nimport { arcNode, sweep as sweepArcs } from '../render/sweep.ts'\nimport { arcCentroid, arcPathStable, DEG, HALO } from '../shapes/arc.ts'\nimport { type ChildInput, type ClassValue, h } from '../vnode.ts'\nimport { cleanData, cleanItems, isRecord } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** One ring of a gauge. */\nexport interface GaugeRing {\n name: string\n /** Current value, clamped to `0…max`. */\n value: number\n /** Full-ring value of this ring; overrides `GaugeOptions.max`. */\n max?: number\n /** Stable identity for keyed updates and legend toggles. Defaults to `name`. */\n id?: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the ring group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface GaugeOptions {\n /** A single value, one ring, or concentric rings (outermost first). */\n data: number | GaugeRing | readonly GaugeRing[]\n /** Full-ring value. Defaults to `100`. */\n max?: number\n /** Where the arc starts, in degrees clockwise from 12 o'clock. Defaults to `0`. */\n startAngle?: number\n /** Degrees the full ring spans, `0…360`. Defaults to `360`; use e.g. `270` for a dial. */\n angle?: number\n /** Ring thickness in pixels. Defaults to `12`. */\n thickness?: number\n /** Space between rings in pixels. Defaults to `4`. */\n gap?: number\n /** Corner radius of the arcs. Defaults to half the thickness (round caps). */\n cornerRadius?: number\n /** Format of the values (tooltip, table). */\n format?: NumberFormat\n /**\n * Text in the middle: the first ring's share of `max` and its name by\n * default; `false` hides it, or give your own `value` / `label`.\n */\n center?: false | { value?: string; label?: string }\n /** Extra space around the gauge, in pixels. */\n padding?: InsetsInput\n}\n\n/** Space kept around the gauge for the hover halo. */\nconst HALF_PI = Math.PI / 2\n\ninterface Ring {\n data: GaugeRing\n index: number\n value: number\n max: number\n /** Slot among the visible rings, from the outside in. */\n position: number\n}\n\nfunction ringsOf(options: GaugeOptions): GaugeRing[] {\n const { data } = options\n if (typeof data === 'number') return [{ name: '', value: data }]\n return Array.isArray(data) ? (data as GaugeRing[]) : [data as GaugeRing]\n}\n\n/** The visible rings with clamped values. */\nfunction layoutRings(options: GaugeOptions, hidden: ReadonlySet<string>): Ring[] {\n const max = options.max ?? 100\n return ringsOf(options)\n .map((data, index) => ({ data, index, max: data.max ?? max }))\n .filter((ring) => !hidden.has(keyOf(ring.data)))\n .map((ring, position) => ({\n ...ring,\n position,\n value: Math.min(ring.max, Math.max(0, ring.data.value || 0)),\n }))\n}\n\n/**\n * Radius and center that fit the swept ring (plus the text in the middle)\n * into `area`: a dial or half ring is centered by its own outline, not by\n * the full circle it is cut from.\n */\nfunction fitGauge(\n area: { x: number; y: number; width: number; height: number },\n start: number,\n sweep: number,\n textTop: number,\n textBottom: number,\n): { outer: number; cx: number; cy: number } {\n // Points of the outline, in units of the outer radius: both ends of the arc\n // and every axis extreme it passes; the origin covers the inner edge.\n const unit: [number, number][] = [[0, 0]]\n const end = start + sweep\n unit.push([Math.sin(start), -Math.cos(start)], [Math.sin(end), -Math.cos(end)])\n // (At most a full turn of them: a huge start angle is beyond what adding a quarter turn changes.)\n for (let a = Math.ceil(start / HALF_PI) * HALF_PI, n = 0; n < 5 && a <= end + 1e-9; n++) {\n unit.push([Math.sin(a), -Math.cos(a)])\n a += HALF_PI\n }\n let outer = Math.min(area.width, area.height) / 2\n let box = { x0: 0, y0: 0, x1: 0, y1: 0 }\n // The text does not scale with the radius, so converge in a few rounds.\n for (let i = 0; i < 4; i++) {\n box = { x0: 0, y0: textTop, x1: 0, y1: textBottom }\n for (const [x, y] of unit) {\n box.x0 = Math.min(box.x0, x * outer)\n box.x1 = Math.max(box.x1, x * outer)\n box.y0 = Math.min(box.y0, y * outer)\n box.y1 = Math.max(box.y1, y * outer)\n }\n const scale = Math.min(area.width / (box.x1 - box.x0), area.height / (box.y1 - box.y0))\n if (Math.abs(scale - 1) < 1e-3) break\n outer = Math.max(0, outer * scale)\n }\n return {\n outer,\n cx: area.x + (area.width - (box.x1 - box.x0)) / 2 - box.x0,\n cy: area.y + (area.height - (box.y1 - box.y0)) / 2 - box.y0,\n }\n}\n\nfunction renderGauge(options: GaugeOptions, ctx: RenderContext): ChildInput {\n const { width, height, locale } = ctx\n const thickness = Math.max(1, options.thickness ?? 12)\n const gap = Math.max(0, options.gap ?? 4)\n const cornerRadius = options.cornerRadius ?? thickness / 2\n const pad = insets(options.padding, 0)\n const area = innerRect(width, height, {\n top: pad.top + HALO,\n right: pad.right + HALO,\n bottom: pad.bottom + HALO,\n left: pad.left + HALO,\n })\n const start = (options.startAngle ?? 0) * DEG\n const sweep = Math.min(360, Math.max(0, options.angle ?? 360)) * DEG\n const rings = layoutRings(options, ctx.hidden)\n const center = options.center\n const first = rings[0]\n const showCenter = center !== false && first !== undefined\n const centerLabel = showCenter ? (center?.label ?? (first.data.name || undefined)) : undefined\n const { outer, cx, cy } = fitGauge(\n area,\n start,\n sweep,\n showCenter ? -1.4 * ctx.fontSize : 0,\n showCenter ? (centerLabel ? 2 : 0.7) * ctx.fontSize : 0,\n )\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n\n const radii = (ring: Ring, grow = 0) => {\n const r1 = Math.max(0, outer - ring.position * (thickness + gap))\n return { innerRadius: Math.max(0, r1 - thickness - grow), outerRadius: r1 + grow }\n }\n const fraction = (ring: Ring) => (ring.max > 0 ? ring.value / ring.max : 0)\n const geometry = (ring: Ring, grow = 0) => ({\n ...radii(ring, grow),\n startAngle: start,\n endAngle: start + sweep * fraction(ring),\n cornerRadius,\n })\n\n const hitFor = (ring: Ring): Hit => {\n const [x, y] = arcCentroid(geometry(ring))\n const item: HitItem = {\n name: ring.data.name,\n seriesIndex: ring.index,\n value: ring.value,\n text: `${value(ring.value)} (${share.format(fraction(ring))})`,\n x: cx + x,\n y: cy + y,\n }\n if (ring.data.color) item.color = ring.data.color\n return {\n index: ring.position,\n label: ring.data.name,\n title: '',\n x: cx + x,\n area: { x: cx - outer, y: cy - outer, width: outer * 2, height: outer * 2 },\n items: [item],\n seriesIndex: ring.index,\n // The value arc, slightly enlarged.\n mark: { d: arcPathStable(geometry(ring, 2)), x: cx, y: cy },\n }\n }\n\n const interaction: Interaction = {\n count: rings.length,\n hitIndex: (position) => {\n const ring = rings[position]\n return ring ? hitFor(ring) : null\n },\n hitTest(px, py) {\n const r = Math.hypot(px - cx, py - cy)\n const ring = rings.find((ring) => {\n const { innerRadius, outerRadius } = radii(ring, 2)\n return r >= innerRadius && r <= outerRadius\n })\n return ring ? hitFor(ring) : null\n },\n }\n ctx.onHitTest(interaction)\n\n const groups = rings.map((ring) =>\n h(\n 'g',\n groupAttrs(ring.data, ring.index),\n // Each path keeps its arc, so a new value (or a new shape of the gauge)\n // sweeps it around the center (see `sweep`).\n arcNode('tc-gauge-track', { ...geometry(ring), endAngle: start + sweep }),\n arcNode('tc-gauge-arc', geometry(ring)),\n ),\n )\n\n const centerValue = showCenter ? (center?.value ?? share.format(fraction(first))) : ''\n\n return [\n // Rings sit in their own group: the entrance animation transforms it, not the translated parent.\n h(\n 'g',\n { class: 'tc-gauge', style: `transform:translate(${cx}px,${cy}px)` },\n h('g', { class: 'tc-gauge-rings' }, groups),\n ),\n showCenter &&\n h(\n 'g',\n { class: 'tc-gauge-center', 'aria-hidden': 'true' },\n h(\n 'text',\n {\n class: 'tc-gauge-value',\n x: cx,\n y: cy,\n dy: centerLabel ? '0' : '0.35em',\n 'text-anchor': 'middle',\n },\n centerValue,\n ),\n centerLabel &&\n h(\n 'text',\n { class: 'tc-gauge-label', x: cx, y: cy, dy: '1.6em', 'text-anchor': 'middle' },\n centerLabel,\n ),\n ),\n ]\n}\n\nfunction gaugeTable(options: GaugeOptions, ctx: RenderContext): DataTable {\n const value = formatNumber(options.format, ctx.locale)\n const share = getNumberFormat(ctx.locale, { style: 'percent', maximumFractionDigits: 1 })\n return {\n columns: ['', 'Value', 'Share'],\n rows: layoutRings(options, ctx.hidden).map((ring) => [\n ring.data.name,\n value(ring.value),\n share.format(ring.max > 0 ? ring.value / ring.max : 0),\n ]),\n }\n}\n\n/**\n * Gauge (radial bar): progress towards a maximum as an arc on a track, with\n * the share in the middle. Several rings nest from the outside in.\n *\n * ```ts\n * new Chart('#el', { type: gauge, data: 58 })\n * new Chart('#el', { type: gauge, data: { name: 'completed', value: 1392, max: 2400 } })\n * ```\n */\nexport const gauge: ChartType<GaugeOptions> = {\n name: 'gauge',\n clean: cleanData((data) =>\n cleanItems(\n typeof data === 'number' ? [{ name: '', value: data }] : isRecord(data) ? [data] : data,\n ),\n ),\n render: (options, ctx): ChildInput => {\n // Set here, not as the module loads (see pie).\n features.sweep = sweepArcs\n return renderGauge(options, ctx)\n },\n legend: (options) => legendItems(ringsOf(options)),\n table: gaugeTable,\n}\n","import type { ChartType, LegendItem, RenderContext } from '../chart.ts'\nimport { axis, axisSize, bandTicks, thinTicks } from '../components/axis.ts'\nimport { formatNumber, type Locale, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { estimateTextWidth, type InsetsInput, innerRect, insets, round } from '../layout.ts'\nimport { band } from '../scales/band.ts'\nimport { extent } from '../scales/extent.ts'\nimport { h, type StyleValue } from '../vnode.ts'\nimport {\n type CartesianData,\n type Label,\n labelKey,\n resolveLabels,\n type Series,\n seriesKey,\n seriesLegend,\n seriesTable,\n} from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\n\n/** A band of values drawn in one color, with its own legend entry. */\nexport interface HeatmapRange {\n /** Lowest value in the band (inclusive). Leave it out for \"everything below `to`\". */\n from?: number\n /** Value where the band ends (exclusive). Leave it out on the last band. */\n to?: number\n /**\n * Any CSS color, including `var(--tc-color-3)`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color: string\n /** Legend and tooltip name, e.g. `'High'`. Defaults to the range, e.g. `10–30`. */\n name?: string\n}\n\nexport interface HeatmapOptions {\n /** Columns are the labels, rows are the series (first series on top). */\n data: CartesianData\n /** Value shown with the lightest shade (or the first color). Defaults to the smaller of `0` and the data minimum. */\n min?: number\n /** Value shown with the full color (or the last color). Defaults to the data maximum. */\n max?: number\n /**\n * Discrete bands of values, each in its own color and legend entry (which\n * also hides the band's cells). Takes precedence over `colors` and `colorBy`.\n */\n ranges?: readonly HeatmapRange[]\n /**\n * A continuous scale through two or more colors (any CSS color, including\n * `var(--tc-…)`), from `min` to `max`. For values around a reference\n * point, use two hues with a neutral middle, e.g.\n * `['var(--tc-color-1)', 'var(--tc-grid-color)', 'var(--tc-color-8)']`.\n * Values that could inject CSS are ignored, as for series colors.\n */\n colors?: readonly string[]\n /** Value placed on the middle color of `colors` (e.g. `0` for changes). Defaults to halfway. */\n mid?: number\n /**\n * `'series'` shades every row in its own palette color (with a legend of\n * the rows); `'value'` (the default) uses one hue, `--tc-heat-color`.\n */\n colorBy?: 'value' | 'series'\n /** Space between cells in pixels, drawn as surface. Defaults to `2`. */\n gap?: number\n /** Corner radius of the cells. Defaults to `3`. */\n radius?: number\n /** Format of the values (tooltip, table). */\n format?: NumberFormat\n /** Column labels along the bottom. */\n x?: { show?: boolean; format?: (label: Label, index: number) => string }\n /** Row names on the left. */\n y?: { show?: boolean }\n /** Extra space around the grid, in pixels. */\n padding?: InsetsInput\n}\n\n/** Share of the full color at the minimum, so zero still reads as a value, not a gap. */\nconst FLOOR = 0.08\n\nconst EMPTY = 'var(--tc-heat-empty,var(--tc-grid-color))'\n\n/** Cell color at `share` (0…1) of the way from the empty shade to `color`. */\nconst shade = (share: number, color = 'var(--tc-heat-color,var(--tc-color-1))'): string =>\n `color-mix(in oklab,${color} ${round(share * 100)}%,${EMPTY})`\n\n/** Legend key of a range. */\nconst rangeKey = (range: HeatmapRange, index: number): string => range.name ?? `range-${index + 1}`\n\n/** The first range containing `v` (`from` inclusive, `to` exclusive). */\nconst rangeOf = (ranges: readonly HeatmapRange[], v: number): number =>\n ranges.findIndex((r) => (r.from === undefined || v >= r.from) && (r.to === undefined || v < r.to))\n\n/** Color of a palette slot by series index, as the CSS classes would pick it. */\nconst slotColor = (series: Series, index: number): string =>\n series.color ?? (index < 8 ? `var(--tc-color-${index + 1})` : 'var(--tc-color-other)')\n\n/** How one cell is painted: inline style, the tooltip swatch, and whether it is drawn empty. */\ninterface Paint {\n style?: StyleValue\n color: string\n empty?: boolean\n}\n\n/** A rounded rectangle as path data, for the hover ring. */\nfunction ringPath(x: number, y: number, w: number, hgt: number, r: number): string {\n const rr = Math.max(0, Math.min(r, w / 2, hgt / 2))\n const n = round\n return (\n `M${n(x + rr)},${n(y)}H${n(x + w - rr)}A${n(rr)},${n(rr)},0,0,1,${n(x + w)},${n(y + rr)}` +\n `V${n(y + hgt - rr)}A${n(rr)},${n(rr)},0,0,1,${n(x + w - rr)},${n(y + hgt)}` +\n `H${n(x + rr)}A${n(rr)},${n(rr)},0,0,1,${n(x)},${n(y + hgt - rr)}` +\n `V${n(y + rr)}A${n(rr)},${n(rr)},0,0,1,${n(x + rr)},${n(y)}Z`\n )\n}\n\nfunction renderHeatmap(options: HeatmapOptions, ctx: RenderContext) {\n const { width, height, fontSize, locale } = ctx\n const { gap = 2, radius = 3 } = options\n const labels = resolveLabels(options.data)\n const formatLabel = options.x?.format ?? ((label: Label) => String(label))\n const value = formatNumber(options.format, locale)\n\n // Color domain.\n const all = options.data.series.flatMap((s) => s.values)\n const [dataMin, dataMax] = extent(all) ?? [0, 1]\n const lo = options.min ?? Math.min(0, dataMin)\n const hi = options.max ?? dataMax\n /** Position of a value in the domain, 0…1 (through `mid` for a scale with a middle). */\n const position = (v: number) => {\n const { mid } = options\n let t: number\n if (mid !== undefined && options.colors && lo < mid && mid < hi) {\n t = v <= mid ? ((v - lo) / (mid - lo)) * 0.5 : 0.5 + ((v - mid) / (hi - mid)) * 0.5\n } else {\n t = hi > lo ? (v - lo) / (hi - lo) : v > lo ? 1 : 0\n }\n return Math.min(1, Math.max(0, t))\n }\n const share = (v: number) => FLOOR + (1 - FLOOR) * position(v)\n\n const ranges = options.ranges?.length ? options.ranges : undefined\n const stops = !ranges && options.colors && options.colors.length >= 2 ? options.colors : undefined\n const bySeries = !ranges && !stops && options.colorBy === 'series'\n // Rows hidden from the legend (rows are legend entries when colored by series).\n const rows = bySeries\n ? options.data.series.filter((s) => !ctx.hidden.has(seriesKey(s)))\n : options.data.series\n const slot = (row: Series) => options.data.series.indexOf(row)\n\n /** How the cell of `row` with value `v` is painted in the active color mode. */\n const paint = (v: number, row: Series): Paint => {\n if (ranges) {\n const index = rangeOf(ranges, v)\n const range = ranges[index]\n if (!range || ctx.hidden.has(rangeKey(range, index))) return { color: EMPTY, empty: true }\n return { style: { '--tc-cell-fill': range.color }, color: range.color }\n }\n if (stops) {\n const at = position(v) * (stops.length - 1)\n const k = Math.min(stops.length - 2, Math.floor(at))\n const u = round((at - k) * 100)\n const from = stops[k] as string\n const color =\n u <= 0\n ? from\n : u >= 100\n ? (stops[k + 1] as string)\n : `color-mix(in oklab,${stops[k + 1]} ${u}%,${from})`\n return { style: { '--tc-cell-fill': color }, color }\n }\n const pct = share(v)\n return {\n style: `--tc-heat:${round(pct * 100)}%`,\n color: bySeries ? shade(pct, slotColor(row, slot(row))) : shade(pct),\n }\n }\n\n // Margins for the labels, then one band per column and per row.\n const pad = insets(options.padding, 0)\n const showX = options.x?.show !== false && labels.length > 0\n const showY = options.y?.show !== false && rows.length > 0\n const rowTicks = rows.map((s, i) => ({ value: i, position: 0, label: s.name }))\n const left = showY ? axisSize('left', rowTicks, fontSize) : 0\n const bottom = showX ? axisSize('bottom', [{ value: 0, position: 0, label: 'M' }], fontSize) : 0\n // The last column label is centered on its column: what is wider than half a\n // column needs room on the right.\n const lastLabel = showX\n ? estimateTextWidth(\n formatLabel(labels[labels.length - 1] as Label, labels.length - 1),\n fontSize,\n )\n : 0\n const halfColumn = (width - pad.left - pad.right - left) / Math.max(1, labels.length) / 2\n const area = innerRect(width, height, {\n top: pad.top,\n right: pad.right + Math.max(0, Math.ceil(lastLabel / 2 - halfColumn)),\n bottom: pad.bottom + bottom,\n left: pad.left + left,\n })\n const x = band(\n labels.map((_, i) => i),\n [area.x, area.x + area.width],\n )\n const y = band(\n rows.map((_, i) => i),\n [area.y, area.y + area.height],\n )\n const cellW = Math.max(0, x.bandwidth - gap)\n const cellH = Math.max(0, y.bandwidth - gap)\n const cellX = (i: number) => x.at(i) + gap / 2\n const cellY = (j: number) => y.at(j) + gap / 2\n const valueAt = (i: number, j: number) => {\n const v = rows[j]?.values[i]\n return v != null && Number.isFinite(v) ? v : null\n }\n\n // One hit per column; every row is an item, the hovered row is active.\n const hitAt = (i: number, row = 0): Hit | null => {\n if (i < 0 || i >= labels.length || rows.length === 0) return null\n const j = Math.max(0, Math.min(rows.length - 1, row))\n const items: HitItem[] = rows.map((s, r) => {\n const v = valueAt(i, r)\n const range = ranges && v !== null ? ranges[rangeOf(ranges, v)] : undefined\n return {\n name: s.name,\n seriesIndex: r,\n value: v,\n // With ranges, the band's name says what the value means.\n text: v === null ? '–' : range?.name ? `${value(v)} · ${range.name}` : value(v),\n x: cellX(i) + cellW / 2,\n y: cellY(r) + cellH / 2,\n box: { x: cellX(i), y: cellY(r), width: cellW, height: cellH },\n color: v === null ? 'var(--tc-grid-color)' : paint(v, s).color,\n }\n })\n return {\n index: i,\n label: labelKey(labels[i] as Label),\n title: formatLabel(labels[i] as Label, i),\n x: cellX(i) + cellW / 2,\n area,\n items,\n seriesIndex: j,\n // A ring just outside the hovered cell.\n mark: {\n d: ringPath(cellX(i) - 2, cellY(j) - 2, cellW + 4, cellH + 4, radius + 2),\n x: 0,\n y: 0,\n },\n }\n }\n\n const interaction: Interaction = {\n count: labels.length,\n hitIndex: (i, row) => hitAt(i, row),\n hitTest(px, py) {\n if (px < area.x || px > area.x + area.width || py < area.y || py > area.y + area.height) {\n return null\n }\n const i = Math.min(labels.length - 1, Math.floor((px - area.x) / (x.step || 1)))\n const j = Math.min(rows.length - 1, Math.floor((py - area.y) / (y.step || 1)))\n return hitAt(i, j)\n },\n }\n ctx.onHitTest(interaction)\n\n const cells = rows.map((s, j) =>\n h(\n 'g',\n {\n key: seriesKey(s),\n // Colored by series, a row takes its palette slot like any series.\n class: ['tc-heatmap-row', bySeries && ['tc-series', `tc-series-${slot(s) + 1}`]],\n 'data-series': s.name,\n style: bySeries ? { '--tc-series-color': s.color } : undefined,\n },\n labels.map((label, i) => {\n const v = valueAt(i, j)\n const painted = v === null ? undefined : paint(v, s)\n return h('rect', {\n key: labelKey(label),\n class: ['tc-cell', (v === null || painted?.empty) && 'tc-cell-empty'],\n x: round(cellX(i)),\n y: round(cellY(j)),\n width: round(cellW),\n height: round(cellH),\n rx: round(Math.min(radius, cellW / 2, cellH / 2)),\n style: painted?.style,\n })\n }),\n ),\n )\n\n const xTicks = showX\n ? thinTicks(\n bandTicks(x, (_, i) => formatLabel(labels[i] as Label, i)),\n 'bottom',\n fontSize,\n )\n : []\n const yTicks = showY ? bandTicks(y, (_, j) => rows[j]?.name ?? '') : []\n\n return [\n h('g', { class: 'tc-heatmap-cells' }, cells),\n showX && axis({ position: 'bottom', ticks: xTicks, area }),\n showY && axis({ position: 'left', ticks: yTicks, area }),\n ]\n}\n\n/** Legend: the ranges, or the rows when colored by series; none for a single scale. */\nfunction heatmapLegend(options: HeatmapOptions): LegendItem[] {\n const { ranges } = options\n if (ranges?.length) {\n // The legend is asked with the whole config, so the names follow its locale.\n const value = formatNumber(options.format, (options as { locale?: Locale }).locale)\n return ranges.map((range, index) => ({\n key: rangeKey(range, index),\n name:\n range.name ??\n (range.from === undefined\n ? `< ${value(range.to ?? 0)}`\n : range.to === undefined\n ? `≥ ${value(range.from)}`\n : `${value(range.from)}–${value(range.to)}`),\n index,\n color: range.color,\n }))\n }\n if (options.colors && options.colors.length >= 2) return []\n return options.colorBy === 'series' ? seriesLegend(options.data) : []\n}\n\n/**\n * Heatmap: a grid of cells, one row per series and one column per label,\n * shaded from light to the full color by value (a single hue, so it reads\n * as magnitude). Set the hue with `--tc-heat-color`, or color the cells by\n * `ranges` of values, a `colors` scale (with a `mid` for diverging data),\n * or one palette color per row with `colorBy: 'series'`.\n *\n * ```ts\n * new Chart('#el', {\n * type: heatmap,\n * data: { labels: ['W1', 'W2', 'W3'], series: [{ name: 'Mon', values: [2, 4, 0] }] },\n * })\n * ```\n */\nexport const heatmap: ChartType<HeatmapOptions> = {\n name: 'heatmap',\n clean: cleanData(cleanSeries),\n render: renderHeatmap,\n legend: heatmapLegend,\n valueLabels: { marks: 'cell', format: (options) => options.format },\n // Cells are formatted as in the tooltip: `format` is the value format here, not `y.format`.\n table: (options, ctx, limit) =>\n seriesTable(\n { data: options.data, ...(options.x ? { x: options.x } : {}), y: { format: options.format } },\n ctx,\n limit,\n ),\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext } from '../chart.ts'\nimport { formatNumber, getNumberFormat, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { type InsetsInput, innerRect, insets, round } from '../layout.ts'\nimport { DEG } from '../shapes/arc.ts'\nimport { type ChildInput, type ClassValue, h } from '../vnode.ts'\nimport { cleanData, finite, named, records } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** One party (or group) of a parliament. */\nexport interface ParliamentParty {\n name: string\n /** Seats won; a fraction is rounded, a negative count is zero. */\n seats: number\n /** Stable identity for keyed updates and legend toggles. Defaults to `name`. */\n id?: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the party group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface ParliamentOptions {\n /** Parties in their order along the benches, from the left. */\n data: readonly ParliamentParty[]\n /**\n * Seats in the house. Defaults to the parties' sum; more than that leaves\n * vacant seats, drawn empty after the last party.\n */\n total?: number\n /** Rows of seats. Defaults to the fewest rows that seat everyone comfortably. */\n rows?: number\n /** Where the benches start, in degrees clockwise from 12 o'clock. Defaults to `-angle / 2`. */\n startAngle?: number\n /** Degrees the benches span, `0…360`. Defaults to `180` (a hemicycle). */\n angle?: number\n /** Radius of the innermost row relative to the outermost, `0…0.95`. Defaults to `0.45`. */\n innerRadius?: number\n /** Space between seats as a share of their pitch, `0…0.9`. Defaults to `0.35`. */\n gap?: number\n /** Format of the seat counts (tooltip, table, center). */\n format?: NumberFormat\n /**\n * Text in the middle: the number of seats by default; `false` hides it, or\n * give your own `value` / `label` (the label sits above the value).\n */\n center?: false | { value?: string; label?: string }\n /** Extra space around the chart, in pixels. */\n padding?: InsetsInput\n}\n\n/** The most seats a house can have: enough for any parliament, few enough to draw. */\nconst MAX_SEATS = 5000\n\ninterface Party {\n data: ParliamentParty\n index: number\n seats: number\n /** Slot among the visible parties, from the left. */\n position: number\n}\n\n/** A seat in units of the outer radius, before the chart is placed. */\ninterface Seat {\n x: number\n y: number\n angle: number\n row: number\n}\n\ninterface Layout {\n seats: Seat[]\n /** Radius of a seat, in units of the outer radius. */\n dot: number\n /** Outline of the benches, in units of the outer radius. */\n box: { x0: number; y0: number; x1: number; y1: number }\n}\n\nfunction partiesOf(options: ParliamentOptions, hidden: ReadonlySet<string>): Party[] {\n return options.data\n .map((data, index) => ({\n data,\n index,\n seats: Math.min(MAX_SEATS, Math.max(0, Math.round(data.seats || 0))),\n }))\n .filter((party) => !hidden.has(keyOf(party.data)))\n .map((party, position) => ({ ...party, position }))\n}\n\n/** Seats of the house: the visible parties', and the vacant ones up to `total`. */\nfunction seatCounts(\n options: ParliamentOptions,\n parties: readonly Party[],\n): { taken: number; total: number } {\n const taken = Math.min(\n MAX_SEATS,\n parties.reduce((sum, party) => sum + party.seats, 0),\n )\n const wanted = Math.min(MAX_SEATS, Math.round(options.total ?? 0))\n return { taken, total: Math.max(taken, wanted > 0 ? wanted : 0) }\n}\n\n/** Seats per row, proportional to each row's length so the angular pitch is the same everywhere. */\nfunction distribute(total: number, radii: readonly number[]): number[] {\n const sum = radii.reduce((a, r) => a + r, 0)\n const counts = radii.map((r) => Math.floor((total * r) / sum))\n let left = total - counts.reduce((a, n) => a + n, 0)\n // The remainder goes to the rows that lost most in rounding, outer rows first.\n const order = radii\n .map((r, i) => ({ i, lost: (total * r) / sum - (counts[i] as number) }))\n .sort((a, b) => b.lost - a.lost || b.i - a.i)\n for (const { i } of order) {\n if (left <= 0) break\n counts[i] = (counts[i] as number) + 1\n left--\n }\n return counts\n}\n\n/**\n * The seats of `total` places on `rows` concentric arcs (the fewest rows\n * that fit when not given), sorted by angle so parties take contiguous\n * wedges, in units of the outer radius.\n */\nfunction layoutSeats(\n total: number,\n rows: number | undefined,\n start: number,\n span: number,\n inner: number,\n gap: number,\n): Layout {\n const box = { x0: 0, y0: 0, x1: 0, y1: 0 }\n if (total <= 0) return { seats: [], dot: 0, box }\n const depth = 1 - inner\n // On a closed ring the last seat would land on the first: one step less.\n const closed = span >= Math.PI * 2 - 1e-9\n const radiiOf = (n: number) =>\n Array.from({ length: n }, (_, i) => (n > 1 ? inner + (i * depth) / (n - 1) : 1))\n // Pitch between rows; a single row is as deep as the ring is.\n const pitchOf = (n: number) => (n > 1 ? depth / (n - 1) : depth)\n // How many seats `n` rows hold at the row pitch along each arc.\n const capacity = (n: number) => {\n const pitch = pitchOf(n)\n return radiiOf(n).reduce((sum, r) => sum + Math.floor((r * span) / pitch) + (closed ? 0 : 1), 0)\n }\n let n = rows && rows > 0 ? Math.min(Math.round(rows), total) : 1\n if (!rows) while (n < total && capacity(n) < total) n++\n const radii = radiiOf(n)\n const pitch = pitchOf(n)\n const counts = distribute(total, radii)\n const seats: Seat[] = []\n // Seats are as far apart as the tightest row's neighbors, or the rows.\n let spacing = n > 1 ? pitch : Number.POSITIVE_INFINITY\n radii.forEach((r, row) => {\n const count = counts[row] as number\n const step = count > 1 ? span / (closed ? count : count - 1) : 0\n if (count > 1) spacing = Math.min(spacing, r * step)\n for (let k = 0; k < count; k++) {\n const angle = count > 1 ? start + k * step : start + span / 2\n seats.push({ x: r * Math.sin(angle), y: -r * Math.cos(angle), angle, row })\n }\n })\n seats.sort((a, b) => a.angle - b.angle || a.row - b.row)\n const dot = (Number.isFinite(spacing) ? spacing : depth) * (1 - gap) * 0.5\n for (const seat of seats) {\n box.x0 = Math.min(box.x0, seat.x - dot)\n box.x1 = Math.max(box.x1, seat.x + dot)\n box.y0 = Math.min(box.y0, seat.y - dot)\n box.y1 = Math.max(box.y1, seat.y + dot)\n }\n return { seats, dot, box }\n}\n\nfunction renderParliament(options: ParliamentOptions, ctx: RenderContext): ChildInput {\n const { width, height, locale } = ctx\n const area = innerRect(width, height, insets(options.padding, 0))\n const span = Math.min(360, Math.max(0, options.angle ?? 180)) * DEG\n const start = (options.startAngle ?? -(span / DEG) / 2) * DEG\n const inner = Math.min(0.95, Math.max(0, options.innerRadius ?? 0.45))\n const gap = Math.min(0.9, Math.max(0, options.gap ?? 0.35))\n const parties = partiesOf(options, ctx.hidden)\n const { taken, total } = seatCounts(options, parties)\n const layout = layoutSeats(total, options.rows, start, span, inner, gap)\n\n // The text in the middle: inside the open side of a hemicycle, else around the center.\n const center = options.center\n const showCenter = center !== false\n const centerLabel = showCenter ? center?.label : undefined\n const open = span <= Math.PI + 1e-9 && Math.abs(start + span / 2) < 1e-9\n const em = ctx.fontSize\n // (The value is 1.75em tall; on the open side its label sits above it.)\n const textTop = showCenter ? (open ? -(centerLabel ? 3.4 : 2.1) * em : -1.4 * em) : 0\n const textBottom = showCenter ? (open ? 0 : (centerLabel ? 2 : 0.7) * em) : 0\n\n // Radius that fits the benches and the text: the text does not scale, so converge.\n let outer = Math.min(area.width, area.height) / 2\n let box = { x0: 0, y0: 0, x1: 0, y1: 0 }\n for (let i = 0; i < 4 && outer > 0; i++) {\n box = {\n x0: Math.min(layout.box.x0 * outer, 0),\n y0: Math.min(layout.box.y0 * outer, textTop),\n x1: Math.max(layout.box.x1 * outer, 0),\n y1: Math.max(layout.box.y1 * outer, textBottom),\n }\n const scale = Math.min(area.width / (box.x1 - box.x0), area.height / (box.y1 - box.y0))\n if (Math.abs(scale - 1) < 1e-3) break\n outer = Math.max(0, outer * scale)\n }\n const cx = area.x + (area.width - (box.x1 - box.x0)) / 2 - box.x0\n const cy = area.y + (area.height - (box.y1 - box.y0)) / 2 - box.y0\n const dot = round(layout.dot * outer)\n const at = (seat: Seat) => [cx + seat.x * outer, cy + seat.y * outer] as const\n\n // Parties take the seats in order from the left; the vacant ones come last.\n let next = 0\n const seatsOf = parties.map((party) => {\n const from = next\n next += party.seats\n return layout.seats.slice(from, next)\n })\n const vacant = layout.seats.slice(taken, total)\n const drawn = parties.filter((party) => party.seats > 0)\n\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n const hitFor = (party: Party, seat?: Seat): Hit => {\n const seats = seatsOf[party.position] as Seat[]\n let x = 0\n let y = 0\n if (seat) [x, y] = at(seat)\n else {\n for (const s of seats) {\n const [sx, sy] = at(s)\n x += sx / seats.length\n y += sy / seats.length\n }\n }\n const item: HitItem = {\n name: party.data.name,\n seriesIndex: party.index,\n value: party.seats,\n text: `${value(party.seats)} (${share.format(total > 0 ? party.seats / total : 0)})`,\n x,\n y,\n }\n if (party.data.color) item.color = party.data.color\n // A halo around every seat of the party.\n const r = dot + 3\n const d = seats\n .map((s) => {\n const [sx, sy] = at(s)\n return `M${round(sx + r)},${round(sy)}A${r},${r},0,1,1,${round(sx - r)},${round(sy)}A${r},${r},0,1,1,${round(sx + r)},${round(sy)}Z`\n })\n .join('')\n return {\n index: drawn.indexOf(party),\n label: party.data.name,\n title: '',\n x,\n area: { x: cx - outer, y: cy - outer, width: outer * 2, height: outer * 2 },\n items: [item],\n seriesIndex: party.index,\n mark: { d, x: 0, y: 0 },\n }\n }\n\n const interaction: Interaction = {\n count: drawn.length,\n hitIndex: (position) => {\n const party = drawn[position]\n return party ? hitFor(party) : null\n },\n hitTest(px, py) {\n const reach = dot + 2\n let best: { party: Party; seat: Seat; d: number } | undefined\n for (const party of drawn) {\n for (const seat of seatsOf[party.position] as Seat[]) {\n const [x, y] = at(seat)\n const d = Math.hypot(px - x, py - y)\n if (d <= reach && (!best || d < best.d)) best = { party, seat, d }\n }\n }\n return best ? hitFor(best.party, best.seat) : null\n },\n }\n ctx.onHitTest(interaction)\n\n const circle = (seat: Seat, key: number, cls: string) => {\n const [x, y] = at(seat)\n return h('circle', {\n key,\n class: cls,\n r: dot,\n style: `transform:translate(${round(x - cx)}px,${round(y - cy)}px)`,\n })\n }\n const groups = parties.map((party) =>\n h(\n 'g',\n groupAttrs(party.data, party.index),\n (seatsOf[party.position] as Seat[]).map((seat, i) => circle(seat, i, 'tc-seat')),\n ),\n )\n\n const centerValue = showCenter ? (center?.value ?? value(total)) : ''\n\n return [\n // Seats sit in their own group: the entrance animation transforms it, not the translated parent.\n h(\n 'g',\n { class: 'tc-parliament', style: `transform:translate(${round(cx)}px,${round(cy)}px)` },\n h(\n 'g',\n { class: 'tc-parliament-seats' },\n groups,\n vacant.length > 0 &&\n h(\n 'g',\n { key: 'vacant', class: 'tc-parliament-vacant' },\n vacant.map((seat, i) => circle(seat, i, 'tc-seat tc-seat-vacant')),\n ),\n ),\n ),\n showCenter &&\n h(\n 'g',\n { class: 'tc-parliament-center', 'aria-hidden': 'true' },\n centerLabel &&\n h(\n 'text',\n {\n class: 'tc-parliament-label',\n x: round(cx),\n y: round(cy),\n dy: open ? '-2.5em' : '1.6em',\n 'text-anchor': 'middle',\n },\n centerLabel,\n ),\n h(\n 'text',\n {\n class: 'tc-parliament-value',\n x: round(cx),\n y: round(cy),\n dy: open ? '-0.4em' : centerLabel ? '0' : '0.35em',\n 'text-anchor': 'middle',\n },\n centerValue,\n ),\n ),\n ]\n}\n\nfunction parliamentTable(options: ParliamentOptions, ctx: RenderContext): DataTable {\n const parties = partiesOf(options, ctx.hidden)\n const { total } = seatCounts(options, parties)\n const value = formatNumber(options.format, ctx.locale)\n const share = getNumberFormat(ctx.locale, { style: 'percent', maximumFractionDigits: 1 })\n return {\n columns: ['', 'Seats', 'Share'],\n rows: parties.map((party) => [\n party.data.name,\n value(party.seats),\n share.format(total > 0 ? party.seats / total : 0),\n ]),\n }\n}\n\n/**\n * Parliament chart: the seats of a house as dots on concentric benches, a\n * hemicycle by default, each party a wedge of them in data order from the\n * left, with the number of seats in the middle.\n *\n * ```ts\n * new Chart('#el', {\n * type: parliament,\n * data: [{ name: 'Left', seats: 135 }, { name: 'Right', seats: 57 }, { name: 'Other', seats: 7 }],\n * })\n * ```\n */\nexport const parliament: ChartType<ParliamentOptions> = {\n name: 'parliament',\n clean: cleanData((data) => records(data, (r) => ({ ...named(r), seats: finite(r.seats) ?? 0 }))),\n render: renderParliament,\n legend: (options) => legendItems(options.data),\n table: parliamentTable,\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext } from '../chart.ts'\nimport { features } from '../features.ts'\nimport { formatNumber, getNumberFormat, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { type InsetsInput, innerRect, insets } from '../layout.ts'\nimport { arcNode, sweep } from '../render/sweep.ts'\nimport { arcCentroid, arcPathStable, DEG, HALO, padAngleForGap } from '../shapes/arc.ts'\nimport { type ChildInput, type ClassValue, h } from '../vnode.ts'\nimport { cleanData, cleanItems } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** One slice of a pie or donut. */\nexport interface PieSlice {\n name: string\n /** Non-negative value; negative values count as zero. */\n value: number\n /** Stable identity for keyed updates and legend toggles. Defaults to `name`. */\n id?: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the slice group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface PieOptions {\n data: readonly PieSlice[]\n /** Hole size relative to the radius, `0…0.95`. Defaults to `0` (`0.62` for `donut`). */\n innerRadius?: number\n /** Gap between slices in pixels, drawn as surface. Defaults to `2`. */\n gap?: number\n /** Corner radius of the slices. Defaults to `0` (`4` for `donut`). */\n cornerRadius?: number\n /** Where the first slice starts, in degrees clockwise from 12 o'clock. Defaults to `0`. */\n startAngle?: number\n /** Format of the values (tooltip, table, donut total). */\n format?: NumberFormat\n /**\n * Text in the donut hole: the total by default; `false` hides it, or give\n * your own `value` / `label`.\n */\n center?: false | { value?: string; label?: string }\n /** Extra space around the pie, in pixels. */\n padding?: InsetsInput\n}\n\ninterface Slice {\n data: PieSlice\n index: number\n value: number\n startAngle: number\n endAngle: number\n}\n\n/** Angles of the visible slices, clockwise from `startAngle`. */\nfunction layoutSlices(\n options: PieOptions,\n hidden: ReadonlySet<string>,\n): { slices: Slice[]; total: number } {\n const visible = options.data\n .map((data, index) => ({ data, index, value: Math.max(0, data.value || 0) }))\n .filter((slice) => !hidden.has(keyOf(slice.data)))\n const total = visible.reduce((sum, slice) => sum + slice.value, 0)\n let angle = (options.startAngle ?? 0) * DEG\n const slices = visible.map((slice) => {\n const sweep = total > 0 ? (slice.value / total) * Math.PI * 2 : 0\n const out: Slice = { ...slice, startAngle: angle, endAngle: angle + sweep }\n angle += sweep\n return out\n })\n return { slices, total }\n}\n\nfunction renderPie(\n options: PieOptions,\n ctx: RenderContext,\n defaults: { inner: number; corner: number },\n) {\n const { width, height, locale } = ctx\n const gap = options.gap ?? 2\n const area = innerRect(width, height, insets(options.padding, 0))\n const outer = Math.max(0, Math.min(area.width, area.height) / 2 - HALO)\n const ratio = Math.min(0.95, Math.max(0, options.innerRadius ?? defaults.inner))\n const inner = outer * ratio\n const cornerRadius = options.cornerRadius ?? defaults.corner\n const cx = area.x + area.width / 2\n const cy = area.y + area.height / 2\n const { slices, total } = layoutSlices(options, ctx.hidden)\n const drawn = slices.filter((slice) => slice.value > 0)\n // A single slice is a full ring: no gap to cut.\n // Rings get a pad angle, which keeps a constant gap width along the whole\n // edge. In a full pie every slice meets at the center, so a pad angle would\n // widen into a wedge: the gap is a surface-colored stroke instead.\n const strokeGap = inner === 0 && drawn.length > 1 ? gap : 0\n const padAngle = inner > 0 && drawn.length > 1 ? padAngleForGap(gap, inner, outer) : 0\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n\n const geometry = (slice: Slice, r0 = inner, r1 = outer) => ({\n innerRadius: r0,\n outerRadius: r1,\n startAngle: slice.startAngle,\n endAngle: slice.endAngle,\n padAngle,\n cornerRadius,\n })\n\n const hitFor = (slice: Slice, position: number): Hit => {\n const [x, y] = arcCentroid(geometry(slice))\n const item: HitItem = {\n name: slice.data.name,\n seriesIndex: slice.index,\n value: slice.value,\n text: `${value(slice.value)} (${share.format(total > 0 ? slice.value / total : 0)})`,\n x: cx + x,\n y: cy + y,\n }\n if (slice.data.color) item.color = slice.data.color\n return {\n index: position,\n label: slice.data.name,\n title: '',\n x: cx + x,\n area: { x: cx - outer, y: cy - outer, width: outer * 2, height: outer * 2 },\n items: [item],\n seriesIndex: slice.index,\n // A thin halo just outside the slice.\n mark: {\n d: arcPathStable({ ...geometry(slice, outer + 2, outer + 6), cornerRadius: 2 }),\n x: cx,\n y: cy,\n },\n }\n }\n\n const interaction: Interaction = {\n count: drawn.length,\n hitIndex: (position) => {\n const slice = drawn[position]\n return slice ? hitFor(slice, position) : null\n },\n hitTest(px, py) {\n const dx = px - cx\n const dy = py - cy\n const r = Math.hypot(dx, dy)\n if (r < inner - 2 || r > outer + HALO) return null\n const start = (options.startAngle ?? 0) * DEG\n const turn = Math.PI * 2\n // Clockwise angle from 12 o'clock, normalized into [start, start + turn).\n let angle = Math.atan2(dx, -dy)\n angle = start + ((((angle - start) % turn) + turn) % turn)\n const position = drawn.findIndex((s) => angle >= s.startAngle && angle < s.endAngle)\n return position === -1 ? null : hitFor(drawn[position] as Slice, position)\n },\n }\n ctx.onHitTest(interaction)\n\n const groups = slices.map((slice) =>\n h(\n 'g',\n groupAttrs(slice.data, slice.index),\n // The path keeps its arc, so new data sweeps slices around the center\n // (see `sweep`). An empty slice keeps its path, a line with no area in\n // the gap between its neighbors, to grow from there.\n arcNode('tc-slice', geometry(slice)),\n ),\n )\n\n const center = options.center\n const showCenter = inner > 0 && center !== false\n const centerValue = showCenter ? (center?.value ?? value(total)) : ''\n const centerLabel = showCenter ? center?.label : undefined\n\n return [\n h(\n 'g',\n { class: 'tc-pie', style: `transform:translate(${cx}px,${cy}px)` },\n total === 0 &&\n h('path', {\n class: 'tc-pie-track',\n d: arcPathStable({\n innerRadius: inner,\n outerRadius: outer,\n startAngle: 0,\n endAngle: Math.PI * 2,\n }),\n }),\n h(\n 'g',\n {\n class: 'tc-pie-slices',\n style: strokeGap > 0 ? `--tc-pie-gap:${strokeGap}px` : undefined,\n },\n groups,\n ),\n ),\n showCenter &&\n h(\n 'g',\n { class: 'tc-pie-center', 'aria-hidden': 'true' },\n h(\n 'text',\n {\n class: 'tc-pie-value',\n x: cx,\n y: cy,\n dy: centerLabel ? '0' : '0.35em',\n 'text-anchor': 'middle',\n },\n centerValue,\n ),\n centerLabel &&\n h(\n 'text',\n { class: 'tc-pie-label', x: cx, y: cy, dy: '1.6em', 'text-anchor': 'middle' },\n centerLabel,\n ),\n ),\n ]\n}\n\nfunction pieTable(options: PieOptions, ctx: RenderContext): DataTable {\n const { slices, total } = layoutSlices(options, ctx.hidden)\n const value = formatNumber(options.format, ctx.locale)\n const share = getNumberFormat(ctx.locale, { style: 'percent', maximumFractionDigits: 1 })\n return {\n columns: ['', 'Value', 'Share'],\n rows: slices.map((slice) => [\n slice.data.name,\n value(slice.value),\n share.format(total > 0 ? slice.value / total : 0),\n ]),\n }\n}\n\nfunction pieType(name: string, defaults: { inner: number; corner: number }): ChartType<PieOptions> {\n return {\n name,\n clean: cleanData(cleanItems),\n render: (options, ctx): ChildInput => {\n // Set here, not as the module loads: a module with side effects would\n // stay in every bundle that imports another chart type next to it.\n features.sweep = sweep\n return renderPie(options, ctx, defaults)\n },\n legend: (options) => legendItems(options.data),\n table: pieTable,\n valueLabels: { marks: 'slice' },\n }\n}\n\n/**\n * Pie chart: parts of a whole as slices, in data order, clockwise from the top.\n *\n * ```ts\n * new Chart('#el', { type: pie, data: [{ name: 'Direct', value: 42 }, { name: 'Search', value: 31 }] })\n * ```\n */\nexport const pie: ChartType<PieOptions> = pieType('pie', { inner: 0, corner: 0 })\n\n/** Donut chart: a pie with a hole showing the total (or your own `center`). */\nexport const donut: ChartType<PieOptions> = pieType('donut', { inner: 0.62, corner: 4 })\n","import type { ChartType, RenderContext } from '../chart.ts'\nimport { linearTicks } from '../components/axis.ts'\nimport { formatDetail, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n round,\n} from '../layout.ts'\nimport { linear } from '../scales/linear.ts'\nimport { type ChildInput, h } from '../vnode.ts'\nimport {\n type CartesianData,\n domainOf,\n type Label,\n labelKey,\n resolveLabels,\n seriesAttrs,\n seriesKey,\n seriesLegend,\n seriesTable,\n tickCount,\n} from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\n\n/** Options for the radial value axis. */\nexport interface RadialAxisOptions {\n /** Render the value labels along the first spoke. Defaults to `true`. */\n show?: boolean\n /** Value at the center. Defaults to `0` (or the data minimum when it is negative). */\n min?: number\n /** Value at the outer ring. Defaults to the niced data maximum. */\n max?: number\n /** Extend the domain to round values. Defaults to `true`. */\n nice?: boolean\n /** Approximate number of rings. Defaults to one per ~40px of radius. */\n ticks?: number\n format?: NumberFormat\n}\n\nexport interface RadarOptions {\n /** One spoke per label, one polygon per series. */\n data: CartesianData\n /** The radial value axis. */\n r?: RadialAxisOptions\n /** Format of the spoke labels (axis, tooltips and the table). */\n format?: (label: Label, index: number) => string\n /** Shape of the rings. Defaults to `'polygon'`. */\n grid?: 'polygon' | 'circle'\n /** Fill each polygon. Defaults to `true`. */\n fill?: boolean\n /** Draw a dot on every value. Defaults to `false`. */\n points?: boolean\n /** Dot radius in pixels. Defaults to `4`. */\n pointRadius?: number\n /**\n * Widest spoke label, in pixels: a longer one wraps at its spaces onto up\n * to three lines. Defaults to a quarter of the chart's width.\n */\n labelWidth?: number\n /** Extra space around the chart, in pixels. */\n padding?: InsetsInput\n}\n\n/** Space between the outer ring and the spoke labels. */\nconst LABEL_GAP = 8\n/** Pixels around the outer ring that still count as hovering it. */\nconst HOVER_SLOP = 8\n\n/** Smallest radius, as a share of the space, however long the labels. */\nconst MIN_RADIUS = 0.5\n/** Most lines a wrapped spoke label takes. */\nconst MAX_LINES = 3\n\n/** `text`, cut short with an ellipsis to fit `width` pixels. */\nfunction truncate(text: string, width: number, fontSize: number): string {\n if (estimateTextWidth(text, fontSize) <= width) return text\n let end = text.length\n while (end > 0 && estimateTextWidth(`${text.slice(0, end)}…`, fontSize) > width) end--\n return end > 0 ? `${text.slice(0, end).trimEnd()}…` : ''\n}\n\n/**\n * `text` split at its spaces into lines no wider than `width` pixels (a word\n * wider than that gets a line of its own), at most `MAX_LINES` of them: what\n * is left joins the last line.\n */\nfunction wrap(text: string, width: number, fontSize: number): string[] {\n const lines: string[] = []\n let line = ''\n for (const word of text.split(' ')) {\n const next = line ? `${line} ${word}` : word\n if (!line || estimateTextWidth(next, fontSize) <= width) line = next\n else {\n lines.push(line)\n line = word\n }\n }\n lines.push(line)\n if (lines.length > MAX_LINES)\n lines.splice(MAX_LINES - 1, lines.length, lines.slice(MAX_LINES - 1).join(' '))\n return lines\n}\n\n/** Text anchor of a spoke label on the side its spoke points to. */\nconst side = (sin: number): -1 | 0 | 1 => (sin > 0.1 ? 1 : sin < -0.1 ? -1 : 0)\n\n/**\n * The largest radius at which every spoke label still fits in `area`:\n * labels sit beyond the outer ring, on the side their spoke points to.\n */\nfunction fitRadius(\n area: { width: number; height: number },\n angles: readonly number[],\n labels: readonly (readonly string[])[],\n fontSize: number,\n): number {\n let radius = Math.min(area.width, area.height) / 2\n angles.forEach((angle, i) => {\n const sin = Math.sin(angle)\n const cos = Math.cos(angle)\n const lines = labels[i] ?? []\n const w = Math.max(0, ...lines.map((line) => estimateTextWidth(line, fontSize)))\n const height = blockHeight(lines.length, fontSize)\n const s = side(sin)\n // Horizontal: the label runs outwards from the spoke end (or is centered on it).\n const across = s === 0 ? w / 2 : w + LABEL_GAP\n if (Math.abs(sin) > 1e-6) radius = Math.min(radius, (area.width / 2 - across) / Math.abs(sin))\n // Vertical: the lines of text above the top spokes, below the bottom ones,\n // centered on the ones at the sides.\n if (Math.abs(cos) > 1e-6) {\n const along = (s === 0 ? height + LABEL_GAP : height / 2) / Math.abs(cos)\n radius = Math.min(radius, area.height / 2 / Math.abs(cos) - along)\n }\n })\n return Math.max(0, radius)\n}\n\n/** Height of `lines` lines of text, in pixels. */\nconst blockHeight = (lines: number, fontSize: number) =>\n fontSize * (1 + Math.max(0, lines - 1) * LINE_HEIGHT)\n\nfunction renderRadar(options: RadarOptions, ctx: RenderContext): ChildInput {\n const { width, height, fontSize, locale } = ctx\n const axis = options.r ?? {}\n const { fill = true, points = false, pointRadius = 4 } = options\n const series = options.data.series\n const labels = resolveLabels(options.data)\n const n = labels.length\n const visible = series.filter((s) => !ctx.hidden.has(seriesKey(s)))\n const formatLabel = options.format ?? ((label: Label) => String(label))\n const formatValue = formatDetail(axis.format, locale)\n\n const pad = insets(options.padding)\n const area = innerRect(width, height, {\n top: pad.top + LABEL_GAP,\n right: pad.right + LABEL_GAP,\n bottom: pad.bottom + LABEL_GAP,\n left: pad.left + LABEL_GAP,\n })\n const cx = area.x + area.width / 2\n const cy = area.y + area.height / 2\n const angles = labels.map((_, i) => (i / Math.max(1, n)) * Math.PI * 2)\n const texts = labels.map((label, i) => formatLabel(label, i))\n // Long labels wrap onto a few lines, then the radius fits them, but never\n // shrinks below a share of the space: lines that still do not fit are cut\n // short (the tooltip and the table keep the labels whole).\n const labelWidth = options.labelWidth ?? area.width / 4\n const wrapped = texts.map((text) => wrap(text, labelWidth, fontSize))\n const radius = Math.max(\n fitRadius(area, angles, wrapped, fontSize),\n (Math.min(area.width, area.height) / 2) * MIN_RADIUS,\n )\n const shown = wrapped.map((lines, i) => {\n const sin = Math.sin(angles[i] as number)\n const room = side(sin) === 0 ? area.width : area.width / 2 - radius * Math.abs(sin) - LABEL_GAP\n return lines.map((line) => truncate(line, room, fontSize))\n })\n\n const count = tickCount(axis, Math.max(2, Math.round(radius / 40)))\n const values = visible.flatMap((s) => s.values)\n const domain = domainOf(values, axis, true, count)\n const scale = linear(domain, [0, radius], { clamp: true })\n const ticks = linearTicks(scale, { count, format: axis.format, locale })\n\n /** Point at `r` pixels from the center along spoke `i`. */\n const at = (i: number, r: number): [number, number] => [\n cx + r * Math.sin(angles[i] as number),\n cy - r * Math.cos(angles[i] as number),\n ]\n /** A closed path through one radius per spoke (the same commands for any values). */\n const polygon = (radii: readonly number[]) =>\n `${radii.map((r, i) => `${i ? 'L' : 'M'}${at(i, r).map(round).join(',')}`).join('')}Z`\n const ring = (r: number) =>\n options.grid === 'circle'\n ? `M${round(cx)},${round(cy - r)}A${round(r)},${round(r)},0,1,1,${round(cx)},${round(cy + r)}A${round(r)},${round(r)},0,1,1,${round(cx)},${round(cy - r)}Z`\n : polygon(labels.map(() => r))\n /** Pixel radius of a value; missing values sit at the center. */\n const radiusOf = (v: number | null | undefined) =>\n v != null && Number.isFinite(v) ? scale(v) : 0\n\n const hitAt = (index: number): Hit => {\n const items: HitItem[] = []\n series.forEach((s, seriesIndex) => {\n if (ctx.hidden.has(seriesKey(s))) return\n const raw = s.values[index]\n const value = raw != null && Number.isFinite(raw) ? raw : null\n const [x, y] = at(index, radiusOf(value))\n const item: HitItem = {\n name: s.name,\n seriesIndex,\n value,\n text: value === null ? '–' : formatValue(value),\n x,\n y: value === null ? null : y,\n }\n if (s.color) item.color = s.color\n items.push(item)\n })\n const [x2, y2] = at(index, radius)\n return {\n index,\n label: labelKey(labels[index] as Label),\n title: texts[index] as string,\n x: x2,\n area: { x: cx - radius, y: cy - radius, width: radius * 2, height: radius * 2 },\n items,\n guide: { x1: cx, y1: cy, x2, y2 },\n }\n }\n\n const interaction: Interaction = {\n count: n,\n hitTest(px, py) {\n if (n === 0 || Math.hypot(px - cx, py - cy) > radius + HOVER_SLOP) return null\n // The nearest spoke by angle, clockwise from 12 o'clock.\n const angle = Math.atan2(px - cx, cy - py)\n const turn = (angle < 0 ? angle + Math.PI * 2 : angle) / (Math.PI * 2)\n return hitAt(Math.round(turn * n) % n)\n },\n hitIndex(index, seriesIndex) {\n if (index < 0 || index >= n) return null\n const hit = hitAt(index)\n if (seriesIndex !== undefined && hit.items.some((item) => item.seriesIndex === seriesIndex)) {\n hit.seriesIndex = seriesIndex\n }\n return hit\n },\n }\n ctx.onHitTest(interaction)\n\n const grid = h(\n 'g',\n { key: 'grid', class: 'tc-radar-grid', 'aria-hidden': 'true' },\n ticks\n .filter((tick) => tick.position > 0)\n .map((tick) =>\n h('path', { key: tick.value, class: 'tc-radar-ring', d: ring(tick.position) }),\n ),\n labels.map((label, i) => {\n const [x2, y2] = at(i, radius)\n return h('line', {\n key: labelKey(label),\n class: 'tc-radar-spoke',\n x1: round(cx),\n y1: round(cy),\n x2: round(x2),\n y2: round(y2),\n })\n }),\n )\n\n const groups = series.map((s, index) => {\n if (ctx.hidden.has(seriesKey(s))) return null\n const d = polygon(labels.map((_, i) => radiusOf(s.values[i])))\n return h(\n 'g',\n seriesAttrs(s, index),\n fill && h('path', { class: 'tc-area', d }),\n h('path', { class: 'tc-line', d }),\n points &&\n h(\n 'g',\n { class: 'tc-points' },\n labels.map((label, i) => {\n const v = s.values[i]\n if (v == null || !Number.isFinite(v)) return null\n const [x, y] = at(i, scale(v))\n return h('circle', {\n key: labelKey(label),\n class: 'tc-point',\n cx: round(x),\n cy: round(y),\n r: pointRadius,\n })\n }),\n ),\n )\n })\n\n const spokeLabels = h(\n 'g',\n { key: 'labels', class: 'tc-radar-labels', 'aria-hidden': 'true' },\n labels.map((label, i) => {\n const angle = angles[i] as number\n const s = side(Math.sin(angle))\n const cos = Math.cos(angle)\n const [x, y] = at(i, radius + LABEL_GAP)\n const [first = '', ...rest] = shown[i] ?? []\n // Above the top spokes, below the bottom ones, centered on the sides:\n // the first line moves up to leave room for the ones under it.\n const up = rest.length * LINE_HEIGHT\n const dy = s !== 0 ? `${round(0.35 - up / 2)}em` : cos > 0 ? `${round(-up)}em` : '0.71em'\n return h(\n 'text',\n {\n key: labelKey(label),\n class: 'tc-tick-label tc-radar-label',\n x: round(x),\n y: round(y),\n 'text-anchor': s > 0 ? 'start' : s < 0 ? 'end' : 'middle',\n dy,\n },\n first,\n rest.map((line, j) => h('tspan', { key: j, x: round(x), dy: `${LINE_HEIGHT}em` }, line)),\n )\n }),\n )\n\n const valueLabels =\n axis.show !== false &&\n h(\n 'g',\n { key: 'values', class: 'tc-radar-values', 'aria-hidden': 'true' },\n ticks\n .filter((tick) => tick.position > 0)\n .map((tick) =>\n h(\n 'text',\n {\n key: tick.value,\n class: 'tc-tick-label tc-radar-value',\n x: round(cx + 4),\n y: round(cy - tick.position),\n dy: '0.35em',\n },\n tick.label,\n ),\n ),\n )\n\n return [\n grid,\n // Series grow from the center: the transform origin is set here, in pixels.\n h(\n 'g',\n {\n key: 'series',\n class: 'tc-series-list tc-radar-series',\n style: `transform-origin:${round(cx)}px ${round(cy)}px`,\n },\n groups,\n ),\n spokeLabels,\n valueLabels,\n ]\n}\n\n/**\n * Radar (spider) chart: one spoke per label, the values of each series\n * joined into a polygon around the center. Good for comparing a few series\n * over the same handful of measures.\n *\n * ```ts\n * new Chart('#el', {\n * type: radar,\n * data: {\n * labels: ['Speed', 'Range', 'Comfort', 'Price', 'Safety'],\n * series: [{ name: 'Model A', values: [80, 60, 70, 40, 90] }],\n * },\n * })\n * ```\n */\nexport const radar: ChartType<RadarOptions> = {\n name: 'radar',\n clean: cleanData(cleanSeries),\n render: renderRadar,\n legend: (options) => seriesLegend(options.data),\n table: (options, ctx, limit) =>\n seriesTable(\n {\n data: options.data,\n ...(options.r?.format ? { y: { format: options.r.format } } : {}),\n ...(options.format ? { x: { format: options.format } } : {}),\n },\n ctx,\n limit,\n ),\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext } from '../chart.ts'\nimport { formatDetail, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n type Rect,\n round,\n} from '../layout.ts'\nimport type { LegendItem } from '../legend.ts'\nimport { type ChildInput, h } from '../vnode.ts'\nimport { cleanData, finite, isRecord, named, records, text } from './clean.ts'\n\n/** A node of the flow; nodes left out are made from the links. */\nexport interface SankeyNode {\n name: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`. Nodes\n * sharing a color form one legend entry, named after the first of them.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Start hidden (toggle it back from the legend, with every node of its color). */\n hidden?: boolean\n}\n\n/** A flow between two nodes, by name. */\nexport interface SankeyLink {\n from: string\n to: string\n /** Non-negative value; negative values count as zero. */\n value: number\n}\n\nexport interface SankeyData {\n /** Optional: sets the stacking order within a column, and colors. */\n nodes?: readonly SankeyNode[]\n links: readonly SankeyLink[]\n}\n\nexport interface SankeyOptions {\n data: SankeyData\n /** Width of the node bars in pixels. Defaults to `12`. */\n nodeWidth?: number\n /** Vertical gap between the nodes of a column in pixels. Defaults to `16`. */\n nodePadding?: number\n /** Format of the values (labels, tooltips and the table). */\n format?: NumberFormat\n /**\n * `'justify'` (default) puts every node without outgoing flows in the last\n * column; `'left'` leaves it in the column after its sources.\n */\n align?: 'justify' | 'left'\n /** Extra space around the diagram, in pixels. */\n padding?: InsetsInput\n}\n\ninterface Node {\n data: SankeyNode\n index: number\n /** Palette slot, 1-based: the node's position in its column. */\n slot: number\n column: number\n value: number\n x: number\n y: number\n height: number\n ins: Link[]\n outs: Link[]\n}\n\ninterface Link {\n data: SankeyLink\n index: number\n source: Node\n target: Node\n /** Top of the slice at the source and at the target. */\n sy: number\n ty: number\n width: number\n}\n\ninterface Layout {\n nodes: Node[]\n links: Link[]\n /** The columns' extent, between the label margins. */\n plot: Rect\n nodeWidth: number\n labels: NodeLabel[]\n}\n\n/** A node's label: the name and the value under it, cut to fit (empty when hidden). */\ninterface NodeLabel {\n side: 'left' | 'right'\n name: string\n value: string\n}\n\n/** Space between a node and its label. */\nconst LABEL_GAP = 8\n/** Largest share of the width one side's labels may take. */\nconst MAX_LABEL_SHARE = 0.3\n/** Pixels around a node that still count as hovering it. */\nconst HOVER_SLOP = 2\n\n/** `text`, cut short with an ellipsis to fit `width` pixels. */\nfunction truncate(text: string, width: number, fontSize: number): string {\n if (estimateTextWidth(text, fontSize) <= width) return text\n let end = text.length\n while (end > 0 && estimateTextWidth(`${text.slice(0, end)}…`, fontSize) > width) end--\n return end > 0 ? `${text.slice(0, end).trimEnd()}…` : ''\n}\n\n/** The color of a node for hover and tooltip swatches. */\nconst colorOf = (node: Node): string => node.data.color ?? `var(--tc-color-${node.slot})`\n\n/** The visible nodes and links, in data order, with their columns. */\nfunction graph(data: SankeyData, hidden: ReadonlySet<string>, justify: boolean) {\n const byName = new Map<string, Node>()\n const nodes: Node[] = []\n const node = (name: string, data?: SankeyNode): Node => {\n let found = byName.get(name)\n if (!found) {\n found = {\n data: data ?? { name },\n index: nodes.length,\n slot: 1,\n column: 0,\n value: 0,\n x: 0,\n y: 0,\n height: 0,\n ins: [],\n outs: [],\n }\n byName.set(name, found)\n nodes.push(found)\n }\n return found\n }\n const declared = new Map((data.nodes ?? []).map((n) => [n.name, n]))\n /** A legend key hides every node of its color, see `sankeyLegend`. */\n const isHidden = (name: string) => {\n const n = declared.get(name)\n return hidden.has(name) || (n?.color !== undefined && hidden.has(legendKey(data, n.color)))\n }\n const links: Link[] = []\n data.links.forEach((link, index) => {\n if (link.from === link.to || isHidden(link.from) || isHidden(link.to)) return\n const source = node(link.from, declared.get(link.from))\n const target = node(link.to, declared.get(link.to))\n const out: Link = { data: link, index, source, target, sy: 0, ty: 0, width: 0 }\n links.push(out)\n if (link.value <= 0) return\n source.outs.push(out)\n target.ins.push(out)\n })\n for (const n of nodes) {\n n.value = Math.max(\n n.outs.reduce((sum, l) => sum + l.data.value, 0),\n n.ins.reduce((sum, l) => sum + l.data.value, 0),\n )\n }\n // Column: the longest path from a source, passes bounded so cycles end.\n for (let pass = 0; pass < nodes.length; pass++) {\n let changed = false\n for (const link of links) {\n if (link.data.value > 0 && link.target.column <= link.source.column) {\n link.target.column = link.source.column + 1\n changed = true\n }\n }\n if (!changed) break\n }\n const last = nodes.reduce((max, n) => Math.max(max, n.column), 0)\n if (justify) for (const n of nodes) if (n.outs.length === 0) n.column = last\n // Stack order within a column: declared nodes first, then first appearance.\n const order = [...declared.keys()]\n nodes.sort((a, b) => {\n if (a.column !== b.column) return a.column - b.column\n const ia = order.indexOf(a.data.name)\n const ib = order.indexOf(b.data.name)\n if (ia !== -1 && ib !== -1) return ia - ib\n if (ia !== ib) return ia === -1 ? 1 : -1\n return a.index - b.index\n })\n const slots = new Map<number, number>()\n nodes.forEach((n, index) => {\n n.index = index\n const slot = (slots.get(n.column) ?? 0) + 1\n slots.set(n.column, slot)\n n.slot = ((slot - 1) % 8) + 1\n })\n return { nodes, links, columns: last + 1 }\n}\n\n/** Key of the legend entry of `color`: the first node that wears it. */\nconst legendKey = (data: SankeyData, color: string): string =>\n (data.nodes ?? []).find((n) => n.color === color)?.name ?? color\n\nfunction layout(options: SankeyOptions, ctx: RenderContext): Layout {\n const { width, height, fontSize, locale } = ctx\n const nodeWidth = Math.max(1, options.nodeWidth ?? 12)\n const nodePadding = Math.max(0, options.nodePadding ?? 16)\n const area = innerRect(width, height, insets(options.padding))\n const { nodes, links, columns } = graph(options.data, ctx.hidden, options.align !== 'left')\n const format = formatDetail(options.format, locale)\n\n // Labels take their room from the sides: the first column's to its left,\n // the last column's to its right, the rest to the right of their node.\n const texts = nodes.map((n) => [n.data.name, format(n.value)] as const)\n const widest = (match: (n: Node) => boolean) =>\n nodes.reduce((max, n, i) => {\n if (!match(n)) return max\n const [name, value] = texts[i] as readonly [string, string]\n return Math.max(max, estimateTextWidth(name, fontSize), estimateTextWidth(value, fontSize))\n }, 0)\n const cap = area.width * MAX_LABEL_SHARE\n const left =\n columns > 1\n ? Math.min(\n cap,\n widest((n) => n.column === 0),\n )\n : 0\n const right = Math.min(\n cap,\n widest((n) => n.column === columns - 1),\n )\n const plot: Rect = {\n x: area.x + (left ? left + LABEL_GAP : 0),\n y: area.y,\n width: Math.max(\n 0,\n area.width - (left ? left + LABEL_GAP : 0) - (right ? right + LABEL_GAP : 0),\n ),\n height: area.height,\n }\n const step = columns > 1 ? (plot.width - nodeWidth) / (columns - 1) : 0\n\n // Heights: one scale for every column, so values compare across them.\n const byColumn: Node[][] = Array.from({ length: columns }, () => [])\n for (const n of nodes) byColumn[n.column]?.push(n)\n const pad = byColumn.reduce(\n (min, col) => (col.length > 1 ? Math.min(min, plot.height / 2 / (col.length - 1)) : min),\n nodePadding,\n )\n let k = Number.POSITIVE_INFINITY\n for (const col of byColumn) {\n const sum = col.reduce((s, n) => s + n.value, 0)\n if (sum > 0) k = Math.min(k, (plot.height - (col.length - 1) * pad) / sum)\n }\n if (!Number.isFinite(k) || k < 0) k = 0\n byColumn.forEach((col, c) => {\n const total = col.reduce((s, n) => s + n.value * k, 0) + (col.length - 1) * pad\n let y = plot.y + (plot.height - total) / 2\n for (const n of col) {\n n.x = plot.x + (columns > 1 ? c * step : (plot.width - nodeWidth) / 2)\n n.y = y\n n.height = n.value * k\n y += n.height + pad\n }\n })\n // Slices: flows leave and enter in the order of the node at the other end.\n for (const n of nodes) {\n let y = n.y\n for (const link of [...n.outs].sort((a, b) => a.target.y - b.target.y)) {\n link.sy = y\n link.width = link.data.value * k\n y += link.width\n }\n y = n.y\n for (const link of [...n.ins].sort((a, b) => a.source.y - b.source.y)) {\n link.ty = y\n y += link.data.value * k\n }\n }\n\n const labels = nodes.map((n, i): NodeLabel => {\n const [name, value] = texts[i] as readonly [string, string]\n const side: 'left' | 'right' = n.column === 0 && columns > 1 ? 'left' : 'right'\n const room =\n side === 'left' ? left : n.column === columns - 1 ? right : step - nodeWidth - LABEL_GAP * 2\n // Crowded columns keep only the names: the value line would run into the next label.\n const col = byColumn[n.column] as Node[]\n const at = col.indexOf(n)\n const neighbours = [col[at - 1], col[at + 1]].filter((o): o is Node => !!o)\n const spacing = neighbours.reduce(\n (min, o) => Math.min(min, (n.height + o.height) / 2 + pad),\n Number.POSITIVE_INFINITY,\n )\n const showValue = spacing >= fontSize * (1 + LINE_HEIGHT)\n return {\n side,\n name: truncate(name, room, fontSize),\n value: showValue ? truncate(value, room, fontSize) : '',\n }\n })\n return { nodes, links, plot, nodeWidth, labels }\n}\n\n/** Path of a link: two cubic Béziers between the slices at its ends. */\nfunction linkPath(link: Link, nodeWidth: number): string {\n const x0 = link.source.x + nodeWidth\n const x1 = link.target.x\n const xm = (x0 + x1) / 2\n const { sy, ty, width } = link\n const p = (...v: number[]) => v.map(round).join(',')\n return `M${p(x0, sy)}C${p(xm, sy, xm, ty, x1, ty)}L${p(x1, ty + width)}C${p(xm, ty + width, xm, sy + width, x0, sy + width)}Z`\n}\n\n/** A point on a cubic Bézier with control points `a`, `b`, `c`, `d`. */\nconst cubic = (a: number, b: number, c: number, d: number, t: number): number => {\n const u = 1 - t\n return u * u * u * a + 3 * u * u * t * b + 3 * u * t * t * c + t * t * t * d\n}\n\n/** Whether `(px, py)` lies inside the ribbon of `link`. */\nfunction inLink(link: Link, nodeWidth: number, px: number, py: number): boolean {\n const x0 = link.source.x + nodeWidth\n const x1 = link.target.x\n if (px < Math.min(x0, x1) || px > Math.max(x0, x1) || x0 === x1) return false\n const xm = (x0 + x1) / 2\n // x(t) is monotone, so bisection finds the t under the pointer.\n let lo = 0\n let hi = 1\n for (let i = 0; i < 20; i++) {\n const mid = (lo + hi) / 2\n if (cubic(x0, xm, xm, x1, mid) < px === x1 > x0) lo = mid\n else hi = mid\n }\n const top = cubic(link.sy, link.sy, link.ty, link.ty, (lo + hi) / 2)\n return py >= top && py <= top + link.width\n}\n\nfunction renderSankey(options: SankeyOptions, ctx: RenderContext): ChildInput {\n const { nodes, links, plot, nodeWidth, labels } = layout(options, ctx)\n const drawn = links.filter((link) => link.data.value > 0)\n const formatValue = formatDetail(options.format, ctx.locale)\n\n const nodeMark = (n: Node) => ({\n d: `M0,0h${round(nodeWidth)}v${round(n.height)}h${round(-nodeWidth)}Z`,\n x: n.x,\n y: n.y,\n })\n const linkItem = (link: Link): HitItem => ({\n name: `${link.source.data.name} → ${link.target.data.name}`,\n seriesIndex: link.index,\n color: colorOf(link.source),\n value: link.data.value,\n text: formatValue(link.data.value),\n x: (link.source.x + nodeWidth + link.target.x) / 2,\n y: cubic(link.sy, link.sy, link.ty, link.ty, 0.5) + link.width / 2,\n })\n const hitNode = (n: Node, linkIndex?: number): Hit => {\n const own: HitItem = {\n name: n.data.name,\n seriesIndex: links.length + n.index,\n color: colorOf(n),\n value: n.value,\n text: formatValue(n.value),\n x: n.x + nodeWidth / 2,\n y: n.y + n.height / 2,\n }\n const flows = [...n.ins, ...n.outs].map(linkItem)\n const focused = flows.find((item) => item.seriesIndex === linkIndex)\n const link = focused && drawn.find((l) => l.index === linkIndex)\n return {\n index: n.index,\n label: n.data.name,\n title: '',\n x: own.x,\n area: plot,\n items: [own, ...flows],\n seriesIndex: focused ? linkIndex : own.seriesIndex,\n mark: link ? { d: linkPath(link, nodeWidth), x: 0, y: 0 } : nodeMark(n),\n }\n }\n const hitLink = (link: Link): Hit => {\n const item = linkItem(link)\n return {\n index: link.source.index,\n label: link.source.data.name,\n title: '',\n x: item.x,\n area: plot,\n items: [item],\n seriesIndex: link.index,\n mark: { d: linkPath(link, nodeWidth), x: 0, y: 0 },\n }\n }\n\n const interaction: Interaction = {\n count: nodes.length,\n hitTest(px, py) {\n const n = nodes.find(\n (n) =>\n px >= n.x - HOVER_SLOP &&\n px <= n.x + nodeWidth + HOVER_SLOP &&\n py >= n.y - HOVER_SLOP &&\n py <= n.y + n.height + HOVER_SLOP,\n )\n if (n) return hitNode(n)\n const link = drawn.find((l) => inLink(l, nodeWidth, px, py))\n return link ? hitLink(link) : null\n },\n hitIndex(index, seriesIndex) {\n const n = nodes[index]\n return n ? hitNode(n, seriesIndex) : null\n },\n }\n ctx.onHitTest(interaction)\n\n return [\n h(\n 'g',\n { key: 'links', class: 'tc-sankey-links' },\n drawn.map((link) =>\n h('path', {\n key: `${link.source.data.name}→${link.target.data.name}#${link.index}`,\n class: ['tc-series', `tc-series-${link.source.slot}`, 'tc-sankey-link'],\n style: { '--tc-series-color': link.source.data.color },\n d: linkPath(link, nodeWidth),\n }),\n ),\n ),\n h(\n 'g',\n { key: 'nodes', class: 'tc-sankey-nodes' },\n nodes.map((n) =>\n h(\n 'g',\n {\n key: n.data.name,\n class: ['tc-series', `tc-series-${n.slot}`],\n 'data-series': n.data.name,\n style: { '--tc-series-color': n.data.color },\n },\n h('rect', {\n class: 'tc-sankey-node',\n x: round(n.x),\n y: round(n.y),\n width: round(nodeWidth),\n height: round(n.height),\n }),\n ),\n ),\n ),\n h(\n 'g',\n { key: 'labels', class: 'tc-sankey-labels', 'aria-hidden': 'true' },\n nodes.map((n, i) => {\n const label = labels[i] as NodeLabel\n if (!label.name && !label.value) return null\n const x = round(label.side === 'left' ? n.x - LABEL_GAP : n.x + nodeWidth + LABEL_GAP)\n const y = round(n.y + n.height / 2)\n const anchor = label.side === 'left' ? 'end' : 'start'\n return h(\n 'g',\n { key: n.data.name, class: 'tc-sankey-label' },\n h(\n 'text',\n {\n class: 'tc-value-label tc-sankey-name',\n x,\n y,\n dy: label.value ? '-0.25em' : '0.35em',\n 'text-anchor': anchor,\n },\n label.name,\n ),\n label.value &&\n h(\n 'text',\n {\n class: 'tc-tick-label tc-sankey-value',\n x,\n y,\n dy: '0.95em',\n 'text-anchor': anchor,\n },\n label.value,\n ),\n )\n }),\n ),\n ]\n}\n\n/** One legend entry per custom color, named after the first node wearing it. */\nfunction sankeyLegend(options: SankeyOptions): LegendItem[] {\n const seen = new Map<string, LegendItem>()\n for (const n of options.data.nodes ?? []) {\n if (n.color && !seen.has(n.color)) {\n const item: LegendItem = { key: n.name, name: n.name, index: seen.size, color: n.color }\n if (n.hidden) item.hidden = true\n seen.set(n.color, item)\n }\n }\n return [...seen.values()]\n}\n\nfunction sankeyTable(options: SankeyOptions, ctx: RenderContext): DataTable {\n const { links } = graph(options.data, ctx.hidden, true)\n const value = formatDetail(options.format, ctx.locale)\n return {\n columns: ['From', 'To', 'Value'],\n rows: links.map((link) => [link.data.from, link.data.to, value(link.data.value)]),\n }\n}\n\n/** Nodes and links from users, APIs and JSON, in the shape the layout expects. */\nconst cleanSankey = (data: unknown): unknown => {\n const d = isRecord(data) ? data : {}\n return {\n ...d,\n nodes: Array.isArray(d.nodes) ? records(d.nodes, (r) => named(r)) : undefined,\n links: records(d.links, (r) => ({\n from: text(r.from),\n to: text(r.to),\n value: Math.max(0, finite(r.value) ?? 0),\n })),\n }\n}\n\n/**\n * Sankey diagram: flows between nodes, as ribbons whose width is their\n * value. Nodes are made from the links (or declared, to set their order and\n * colors) and placed in columns by the longest path from a source.\n *\n * ```ts\n * new Chart('#el', {\n * type: sankey,\n * data: {\n * links: [\n * { from: 'Wages', to: 'Income', value: 60 },\n * { from: 'Dividends', to: 'Income', value: 15 },\n * { from: 'Income', to: 'Rent', value: 30 },\n * { from: 'Income', to: 'Savings', value: 45 },\n * ],\n * },\n * })\n * ```\n */\nexport const sankey: ChartType<SankeyOptions> = {\n name: 'sankey',\n clean: cleanData(cleanSankey),\n render: renderSankey,\n legend: sankeyLegend,\n table: sankeyTable,\n}\n","/** SVG path of a circle of radius `r` around the origin (a path, so it can be a hover mark). */\nexport const circlePath = (r: number): string =>\n `M${r},0A${r},${r},0,1,1,${-r},0A${r},${r},0,1,1,${r},0Z`\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext } from '../chart.ts'\nimport { axis, axisSize, type Tick, thinTicks } from '../components/axis.ts'\nimport { grid } from '../components/grid.ts'\nimport { formatDetail, formatNumber } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n round,\n} from '../layout.ts'\nimport { extent } from '../scales/extent.ts'\nimport type { LinearScale } from '../scales/linear.ts'\nimport { circlePath } from '../shapes/circle.ts'\nimport { type ClassValue, h } from '../vnode.ts'\nimport {\n domainOf,\n markerShape,\n plotClip,\n plottable,\n tickCount,\n type ValueAxisOptions,\n valueScale,\n valueTicks,\n} from './cartesian.ts'\nimport { cleanData, finite, isRecord, named, records, text } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** A point of a scatter or bubble chart. */\nexport interface ScatterPoint {\n x: number\n y: number\n /** Bubble size; the circle area is proportional to it. */\n size?: number\n /** Name shown in the tooltip and table (e.g. a country). */\n label?: string\n}\n\nexport interface ScatterSeries {\n name: string\n points: readonly ScatterPoint[]\n /** Stable identity for keyed updates and legend toggles. Defaults to `name`. */\n id?: string\n /**\n * Custom color; overrides the palette slot via `--tc-series-color`.\n * Values that could inject CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the series group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface ScatterOptions {\n data: { series: readonly ScatterSeries[] }\n /** Horizontal value axis. */\n x?: ValueAxisOptions\n /** Vertical value axis. */\n y?: ValueAxisOptions\n /** Radius of points without a size, in pixels. Defaults to `4`. */\n radius?: number\n /** Radius range for bubbles (points with `size`). Defaults to `{ min: 4, max: 24 }`. */\n size?: { min?: number; max?: number }\n /** Extra space around the plot area, in pixels. */\n padding?: InsetsInput\n}\n\n/** Pointer distance (in pixels, beyond the radius) that still hits a point. */\nconst HIT_RADIUS = 24\nconst EDGE = 8\n\ninterface Placed {\n seriesIndex: number\n pointIndex: number\n point: ScatterPoint\n cx: number\n cy: number\n r: number\n}\n\n/** A point's bubble size, or `undefined` when it has none (or an invalid one). */\nconst sizeOf = (p: ScatterPoint): number | undefined =>\n p.size != null && Number.isFinite(p.size) && p.size > 0 ? p.size : undefined\n\nfunction renderScatter(options: ScatterOptions, ctx: RenderContext) {\n const { width, height, fontSize, locale } = ctx\n const xOptions = options.x ?? {}\n const yOptions = options.y ?? {}\n const radius = options.radius ?? 4\n const visible = options.data.series.filter((s) => !ctx.hidden.has(keyOf(s)))\n const points = visible.flatMap((s) => s.points)\n const sizes = points.map(sizeOf).filter((v): v is number => v !== undefined)\n const maxSize = extent(sizes)?.[1] ?? 0\n const rMin = options.size?.min ?? 4\n const rMax = options.size?.max ?? 24\n // Area-proportional bubbles: the radius grows with the square root of the size.\n const bubble = (size: number | undefined) =>\n size != null && size > 0 && maxSize > 0\n ? rMin + (rMax - rMin) * Math.sqrt(size / maxSize)\n : radius\n const overhang = Math.max(radius, sizes.length ? rMax : 0) + 2\n\n const countY = tickCount(yOptions, Math.max(2, Math.round(height / 60)))\n const countX = tickCount(xOptions, Math.max(2, Math.round(width / 80)))\n // Only points that can be plotted on both axes take part.\n const usable = (p: ScatterPoint) => plottable(p.x, xOptions) && plottable(p.y, yOptions)\n const shown = points.filter(usable)\n const xDomain = domainOf(\n shown.map((p) => p.x),\n xOptions,\n false,\n countX,\n )\n const yDomain = domainOf(\n shown.map((p) => p.y),\n yOptions,\n false,\n countY,\n )\n\n const showX = xOptions.show !== false\n const showY = yOptions.show !== false\n // Linear or logarithmic, as each axis asks (see valueScale).\n const ticksOf = (scale: LinearScale, axis: ValueAxisOptions, count: number) =>\n valueTicks(scale, axis, count, axis.format, locale)\n const probeY = ticksOf(valueScale(yDomain, [1, 0], yOptions), yOptions, countY)\n const probeX = ticksOf(valueScale(xDomain, [0, 1], xOptions), xOptions, countX)\n const half = (tick: Tick | undefined) =>\n showX && tick ? Math.ceil(estimateTextWidth(tick.label, fontSize) / 2) : 0\n const pad = insets(options.padding)\n const margins = {\n top:\n pad.top + Math.max(showY ? Math.ceil((fontSize * LINE_HEIGHT) / 2) : 0, overhang, EDGE / 2),\n right: pad.right + Math.max(half(probeX[probeX.length - 1]), overhang, EDGE),\n bottom:\n pad.bottom + Math.max(showX ? axisSize('bottom', probeX, fontSize) : 0, overhang, EDGE / 2),\n left:\n pad.left +\n Math.max(showY ? axisSize('left', probeY, fontSize) : 0, half(probeX[0]), overhang),\n }\n const area = innerRect(width, height, margins)\n const x = valueScale(xDomain, [area.x, area.x + area.width], xOptions)\n const y = valueScale(yDomain, [area.y + area.height, area.y], yOptions)\n // Thinned like the ticks of the other charts: on a log axis they crowd at the end of each decade.\n const xTicks = thinTicks(ticksOf(x, xOptions, countX), 'bottom', fontSize)\n const yTicks = thinTicks(ticksOf(y, yOptions, countY), 'left', fontSize, 4)\n\n // Every visible point in pixels, sorted by x for fast nearest-point lookups.\n const placed: Placed[] = []\n options.data.series.forEach((series, seriesIndex) => {\n if (ctx.hidden.has(keyOf(series))) return\n series.points.forEach((point, pointIndex) => {\n if (!usable(point)) return\n placed.push({\n seriesIndex,\n pointIndex,\n point,\n cx: x(point.x),\n cy: y(point.y),\n r: bubble(sizeOf(point)),\n })\n })\n })\n placed.sort((a, b) => a.cx - b.cx)\n\n const fx = formatDetail(xOptions.format, locale)\n const fy = formatDetail(yOptions.format, locale)\n const fs = formatNumber(undefined, locale)\n const hitFor = (p: Placed, index: number): Hit => {\n const series = options.data.series[p.seriesIndex] as ScatterSeries\n const sz = sizeOf(p.point)\n const size = sz === undefined ? '' : ` · ${fs(sz)}`\n const item: HitItem = {\n name: series.name,\n seriesIndex: p.seriesIndex,\n value: p.point.y,\n text: `${fx(p.point.x)}, ${fy(p.point.y)}${size}`,\n x: p.cx,\n y: p.cy,\n }\n if (series.color) item.color = series.color\n return {\n index,\n label: p.point.label ?? series.name,\n title: p.point.label ?? '',\n x: p.cx,\n area,\n items: [item],\n seriesIndex: p.seriesIndex,\n mark: { d: circlePath(round(p.r + 4)), x: p.cx, y: p.cy },\n }\n }\n\n const interaction: Interaction = {\n count: placed.length,\n hitIndex: (index) => {\n const p = placed[index]\n return p ? hitFor(p, index) : null\n },\n hitTest(px, py) {\n // Binary search the first point within reach on x, then scan the window.\n let lo = 0\n let hi = placed.length\n const reach = HIT_RADIUS + rMax\n while (lo < hi) {\n const mid = (lo + hi) >> 1\n if ((placed[mid] as Placed).cx < px - reach) lo = mid + 1\n else hi = mid\n }\n let best = -1\n let bestDistance = Number.POSITIVE_INFINITY\n for (let i = lo; i < placed.length; i++) {\n const p = placed[i] as Placed\n if (p.cx > px + reach) break\n const distance = Math.hypot(p.cx - px, p.cy - py) - p.r\n if (distance < bestDistance && distance <= HIT_RADIUS) {\n best = i\n bestDistance = distance\n }\n }\n return best === -1 ? null : hitFor(placed[best] as Placed, best)\n },\n }\n ctx.onHitTest(interaction)\n\n /** One path drawing a dot of `radius` at every point (two arcs each, or the series' shape). */\n const shape = markerShape(options)\n const dotsPath = (dots: readonly ScatterPoint[], slot: number) => {\n if (!dots.length) return null\n const r = round(radius)\n let d = ''\n for (const p of dots) {\n d += shape\n ? shape(slot, x(p.x), y(p.y), r)\n : `M${round(x(p.x) - radius)},${round(y(p.y))}a${r},${r},0,1,0,${2 * r},0a${r},${r},0,1,0,${-2 * r},0`\n }\n return h('path', { key: 'dots', class: ['tc-point tc-dots', shape && 'tc-marker'], d })\n }\n\n const background = []\n if (yOptions.grid !== false) background.push(grid({ direction: 'y', ticks: yTicks, area }))\n if (xOptions.grid) background.push(grid({ direction: 'x', ticks: xTicks, area }))\n\n // Dots may reach a little past the plot edges; bubbles are cut at them (like\n // Chart.js), as a big one there would cover the axis labels.\n const clip = plotClip(ctx, area, sizes.length ? 0 : overhang)\n const groups = options.data.series.map(\n (series, seriesIndex) =>\n !ctx.hidden.has(keyOf(series)) &&\n h(\n 'g',\n groupAttrs(series, seriesIndex),\n // Plain points share one path per series: thousands of circles would\n // each cost the browser style and layout work. The path keeps its\n // commands while the point count does, so new data morphs. Bubbles\n // stay circles: each is see-through over the others.\n dotsPath(\n series.points.filter((p) => usable(p) && sizeOf(p) === undefined),\n seriesIndex,\n ),\n series.points.map(\n (point, i) =>\n usable(point) &&\n sizeOf(point) !== undefined &&\n h('circle', {\n key: i,\n class: 'tc-point tc-bubble',\n cx: round(x(point.x)),\n cy: round(y(point.y)),\n r: round(bubble(sizeOf(point))),\n }),\n ),\n ),\n )\n\n return [\n h('defs', null, clip.def),\n background,\n h('g', { key: 'series', class: 'tc-series-list', 'clip-path': clip.url }, groups),\n showY && axis({ position: 'left', ticks: yTicks, area }),\n showX && axis({ position: 'bottom', ticks: xTicks, area }),\n ]\n}\n\nfunction scatterTable(\n options: ScatterOptions,\n ctx: RenderContext,\n limit: number = Number.POSITIVE_INFINITY,\n): DataTable {\n const fx = formatDetail(options.x?.format, ctx.locale)\n const fy = formatDetail(options.y?.format, ctx.locale)\n const fs = formatNumber(undefined, ctx.locale)\n const series = options.data.series.filter((s) => !ctx.hidden.has(keyOf(s)))\n const withSize = series.some((s) => s.points.some((p) => p.size != null))\n const withLabel = series.some((s) => s.points.some((p) => p.label != null))\n const total = series.reduce((sum, s) => sum + s.points.length, 0)\n let left = limit\n return {\n columns: ['', ...(withLabel ? ['Label'] : []), 'x', 'y', ...(withSize ? ['Size'] : [])],\n total,\n rows: series.flatMap((s) => {\n const take = s.points.slice(0, Math.max(0, left))\n left -= take.length\n return take.map((p) => [\n s.name,\n ...(withLabel ? [p.label ?? ''] : []),\n fx(p.x),\n fy(p.y),\n ...(withSize ? [sizeOf(p) === undefined ? '–' : fs(sizeOf(p) as number)] : []),\n ])\n }),\n }\n}\n\n/**\n * Scatter chart: points on two value axes; give points a `size` for a\n * bubble chart (area-proportional radii).\n *\n * ```ts\n * new Chart('#el', {\n * type: scatter,\n * data: { series: [{ name: 'Cities', points: [{ x: 12, y: 3.4 }, { x: 18, y: 5.1 }] }] },\n * })\n * ```\n */\nexport const scatter: ChartType<ScatterOptions> = {\n name: 'scatter',\n clean: cleanData((data) => ({\n ...(isRecord(data) ? data : {}),\n series: records(isRecord(data) && data.series, (s) => ({\n ...named(s),\n points: records(s.points, (p) => ({\n ...p,\n x: finite(p.x),\n y: finite(p.y),\n size: finite(p.size) ?? undefined,\n label: p.label == null ? undefined : text(p.label),\n })).filter((p) => p.x !== null && p.y !== null),\n })),\n })),\n render: renderScatter,\n legend: (options) => legendItems(options.data.series),\n table: scatterTable,\n valueLabels: { format: (options) => options.y?.format },\n}\n","import type { ChartType, RenderContext } from '../chart.ts'\nimport { fadeMask } from '../components/fade.ts'\nimport { formatNumber, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { type InsetsInput, innerRect, insets, round } from '../layout.ts'\nimport { linear } from '../scales/linear.ts'\nimport { barPath } from '../shapes/bar.ts'\nimport { circlePath } from '../shapes/circle.ts'\nimport { areaPath, type Curve, linePath, type Point } from '../shapes/path.ts'\nimport { h } from '../vnode.ts'\nimport { domainOf, type Label, labelKey } from './cartesian.ts'\nimport { cleanData, label, numbers } from './clean.ts'\n\nexport interface SparklineOptions {\n /** The values; `null` leaves a gap. */\n data: readonly (number | null | undefined)[]\n /** Labels for the tooltip, one per value (e.g. dates). */\n labels?: readonly Label[]\n /** Name shown in the tooltip. Defaults to `'Value'`. */\n name?: string\n /**\n * `'line'` (default), `'area'`, `'bar'`, or `'tristate'`: only the sign\n * counts, as a full bar up (win), down (loss) or a tick on the middle (draw).\n */\n variant?: 'line' | 'area' | 'bar' | 'tristate'\n /** Interpolation for lines and areas. Defaults to `'monotone'`. */\n curve?: Curve\n /** Dot on the last value. Defaults to `'last'`. */\n point?: 'last' | 'none'\n /** Mark the minimum and maximum values. */\n markers?: 'minmax' | 'none'\n /** Dot radius in pixels. Defaults to `3`. */\n pointRadius?: number\n /** Include zero in the value range. Defaults to `true` for areas and bars, `false` for lines. */\n zero?: boolean\n /** Format of values in the tooltip. */\n format?: NumberFormat\n /** Extra space around the plot, in pixels. */\n padding?: InsetsInput\n}\n\nfunction renderSparkline(options: SparklineOptions, ctx: RenderContext) {\n const {\n variant = 'line',\n curve = 'monotone',\n point = 'last',\n markers = 'none',\n pointRadius = 3,\n name = 'Value',\n } = options\n const values = options.data.map((v) => (v == null || !Number.isFinite(v) ? null : v))\n // (No log option on sparklines, so finite is all that matters here.)\n const count = values.length\n const dots = point === 'last' || markers === 'minmax'\n // Room for the stroke and dots so nothing is clipped at the edges.\n const overhang = dots ? pointRadius + 2 : 2\n const pad = insets(options.padding, 0)\n const area = innerRect(ctx.width, ctx.height, {\n top: pad.top + overhang,\n right: pad.right + overhang,\n bottom: pad.bottom + overhang,\n left: pad.left + overhang,\n })\n const tristate = variant === 'tristate'\n const zero = options.zero ?? variant !== 'line'\n // Tristate bars span half the height each way, whatever the magnitude.\n const domain: [number, number] = tristate ? [-1, 1] : domainOf(values, { nice: false }, zero, 2)\n\n const bars = variant === 'bar' || tristate\n const gap = 1\n const slot = count > 0 ? area.width / count : 0\n const xAt = (i: number) =>\n bars\n ? area.x + slot * i + slot / 2\n : area.x + (count > 1 ? (area.width * i) / (count - 1) : area.width / 2)\n const y = linear(domain, [area.y + area.height, area.y])\n const baseline = y(Math.min(Math.max(0, domain[0]), domain[1]))\n const points: Point[] = values.map((v, i) => (v === null ? null : [xAt(i), y(v)]))\n\n const format = formatNumber(options.format, ctx.locale)\n const labelOf = (i: number) => {\n const label = options.labels?.[i]\n return label === undefined ? '' : String(label)\n }\n // Where a value is drawn: a tristate bar ends at its sign, not its magnitude.\n const yOf = (v: number) => y(tristate ? Math.sign(v) : v)\n const hitFor = (i: number): Hit | null => {\n const value = values[i]\n if (value === undefined) return null\n const px = xAt(i)\n const item: HitItem = {\n name,\n seriesIndex: 0,\n value,\n text: value === null ? '–' : format(value),\n x: px,\n y: value === null ? null : yOf(value),\n }\n const hit: Hit = {\n index: i,\n label: labelKey(options.labels?.[i] ?? i + 1),\n title: labelOf(i),\n x: px,\n area,\n items: [item],\n }\n if (value !== null) hit.mark = { d: circlePath(pointRadius + 3), x: px, y: yOf(value) }\n return hit\n }\n const interaction: Interaction = {\n count,\n hitIndex: (i) => hitFor(i),\n hitTest(px, py) {\n if (count === 0 || py < area.y - overhang || py > area.y + area.height + overhang) return null\n const i = bars\n ? Math.floor((px - area.x) / slot)\n : Math.round(((px - area.x) / Math.max(1, area.width)) * (count - 1))\n return hitFor(Math.max(0, Math.min(count - 1, i)))\n },\n }\n ctx.onHitTest(interaction)\n\n const marks = []\n if (tristate) {\n const width = Math.max(1, slot - gap)\n marks.push(\n h('line', {\n class: 'tc-sparkline-zero',\n x1: area.x,\n x2: area.x + area.width,\n y1: round(baseline),\n y2: round(baseline),\n }),\n )\n values.forEach((v, i) => {\n if (v === null) return\n const sign = Math.sign(v)\n // A draw is a short tick centered on the middle line.\n const tick = Math.min(2, area.height / 2)\n const [from, to] =\n sign === 0 ? [baseline + tick / 2, baseline - tick / 2] : [baseline, y(sign)]\n marks.push(\n h('path', {\n key: i,\n class: [\n 'tc-bar',\n sign < 0 && 'tc-bar-negative',\n sign < 0 ? 'tc-tristate-loss' : sign > 0 ? 'tc-tristate-win' : 'tc-tristate-draw',\n ],\n d: barPath(xAt(i) - width / 2, width, from, to, sign === 0 ? 0 : Math.min(2, width / 2)),\n }),\n )\n })\n } else if (bars) {\n const width = Math.max(1, slot - gap)\n values.forEach((v, i) => {\n if (v === null) return\n marks.push(\n h('path', {\n key: i,\n class: ['tc-bar', v < 0 && 'tc-bar-negative'],\n d: barPath(xAt(i) - width / 2, width, baseline, y(v), Math.min(2, width / 2)),\n }),\n )\n })\n } else {\n if (variant === 'area') {\n marks.push(\n h('path', {\n class: 'tc-area tc-area-gradient',\n d: areaPath(points, baseline, { curve }),\n mask: `url(#${ctx.id}-fade)`,\n }),\n )\n }\n marks.push(h('path', { class: 'tc-line', d: linePath(points, { curve }) }))\n }\n\n const dotAt = (i: number, cls: string) => {\n const v = values[i]\n return v == null\n ? null\n : h('circle', {\n key: `${cls}-${i}`,\n class: ['tc-point', cls],\n cx: round(xAt(i)),\n cy: round(y(v)),\n r: pointRadius,\n })\n }\n const extremes = []\n if (markers === 'minmax') {\n let min = -1\n let max = -1\n values.forEach((v, i) => {\n if (v === null) return\n if (min === -1 || v < (values[min] as number)) min = i\n if (max === -1 || v > (values[max] as number)) max = i\n })\n if (min !== -1) extremes.push(dotAt(min, 'tc-point-min'))\n if (max !== -1 && max !== min) extremes.push(dotAt(max, 'tc-point-max'))\n }\n let last = -1\n if (point === 'last') {\n for (let i = count - 1; i >= 0; i--) {\n if (values[i] !== null) {\n last = i\n break\n }\n }\n }\n\n return [\n variant === 'area' && h('defs', null, fadeMask(`${ctx.id}-fade`)),\n h(\n 'g',\n { class: 'tc-series tc-series-1 tc-sparkline' },\n marks,\n extremes,\n last !== -1 && !bars && dotAt(last, 'tc-point-last'),\n ),\n ]\n}\n\n/**\n * Sparkline: a tiny line, area or bar chart without axes, for stat tiles.\n *\n * ```ts\n * new Chart('#el', { type: sparkline, data: [3, 5, 4, 7, 6], height: 40 })\n * ```\n */\nexport const sparkline: ChartType<SparklineOptions> = {\n name: 'sparkline',\n // The labels too: they come from outside like the values.\n clean: (options) => ({\n ...cleanData(numbers)(options),\n labels: Array.isArray(options.labels) ? options.labels.map(label) : undefined,\n }),\n render: renderSparkline,\n // Decorative by default: opt in with `keyboard: true`.\n keyboard: false,\n}\n","import type { ChartType } from './chart.ts'\nimport { area } from './charts/area.ts'\nimport { bar } from './charts/bar.ts'\nimport { candlestick } from './charts/candlestick.ts'\nimport { gauge } from './charts/gauge.ts'\nimport { heatmap } from './charts/heatmap.ts'\nimport { line } from './charts/line.ts'\nimport { parliament } from './charts/parliament.ts'\nimport { donut, pie } from './charts/pie.ts'\nimport { radar } from './charts/radar.ts'\nimport { sankey } from './charts/sankey.ts'\nimport { scatter } from './charts/scatter.ts'\nimport { sparkline } from './charts/sparkline.ts'\n\n/**\n * Every built-in chart type by its name, for charts declared in markup\n * (`<tabler-chart type=\"line\">`, `data-tc-chart=\"line\"`). Importing it\n * brings every type along: code that knows its types imports them directly.\n */\nexport const types: Readonly<Record<string, ChartType<never>>> = {\n line,\n area,\n bar,\n pie,\n donut,\n scatter,\n sparkline,\n gauge,\n heatmap,\n candlestick,\n radar,\n sankey,\n parliament,\n} as Record<string, ChartType<never>>\n","","import { version } from '../package.json'\n\n/** Version of the `@tabler/charts` package. */\nexport const VERSION: string = version\n\nexport type { DataTable } from './a11y.ts'\nexport { describeHit, tableContent } from './a11y.ts'\nexport type {\n BaseOptions,\n ChartConfig,\n ChartEvents,\n ChartType,\n RenderContext,\n ResolvedLegend,\n Size,\n} from './chart.ts'\nexport {\n buildChart,\n Chart,\n chartEvents,\n chartLabel,\n chartToString,\n renderContext,\n resolveLegend,\n resolveSize,\n} from './chart.ts'\nexport type { Annotation } from './charts/annotations.ts'\nexport type { AreaOptions } from './charts/area.ts'\nexport { area } from './charts/area.ts'\nexport type { BarOptions } from './charts/bar.ts'\nexport { bar } from './charts/bar.ts'\nexport type { Candle, CandlestickOptions } from './charts/candlestick.ts'\nexport { candlestick } from './charts/candlestick.ts'\nexport type {\n CartesianData,\n CartesianOptions,\n CategoryAxisOptions,\n Label,\n Series,\n ValueAxisOptions,\n} from './charts/cartesian.ts'\nexport {\n categoryInteraction,\n domainOf,\n seriesKey,\n seriesLegend,\n seriesTable,\n} from './charts/cartesian.ts'\nexport type { GaugeOptions, GaugeRing } from './charts/gauge.ts'\nexport { gauge } from './charts/gauge.ts'\nexport type { HeatmapOptions, HeatmapRange } from './charts/heatmap.ts'\nexport { heatmap } from './charts/heatmap.ts'\nexport type { LineOptions } from './charts/line.ts'\nexport { line } from './charts/line.ts'\nexport type { ParliamentOptions, ParliamentParty } from './charts/parliament.ts'\nexport { parliament } from './charts/parliament.ts'\nexport type { PieOptions, PieSlice } from './charts/pie.ts'\nexport { donut, pie } from './charts/pie.ts'\nexport type { RadarOptions, RadialAxisOptions } from './charts/radar.ts'\nexport { radar } from './charts/radar.ts'\nexport type { SankeyData, SankeyLink, SankeyNode, SankeyOptions } from './charts/sankey.ts'\nexport { sankey } from './charts/sankey.ts'\nexport type { ScatterOptions, ScatterPoint, ScatterSeries } from './charts/scatter.ts'\nexport { scatter } from './charts/scatter.ts'\nexport type { SparklineOptions } from './charts/sparkline.ts'\nexport { sparkline } from './charts/sparkline.ts'\nexport type { AxisOptions, AxisPosition, LinearTicksOptions, Tick } from './components/axis.ts'\nexport { axis, axisSize, bandTicks, linearTicks, thinTicks } from './components/axis.ts'\nexport type { GridOptions } from './components/grid.ts'\nexport { grid } from './components/grid.ts'\nexport { hoverOverlay, hoverUnderlay } from './components/hover.ts'\nexport type { Features } from './features.ts'\nexport { feature, features, register } from './features.ts'\nexport type { DateFormat, Locale, NumberFormat, NumberFormatOptions } from './format.ts'\nexport {\n formatDate,\n formatDetail,\n formatNumber,\n formatTicks,\n getDateFormat,\n getNumberFormat,\n stepPrecision,\n} from './format.ts'\nexport type { Hit, HitItem, HitTester, Interaction } from './interaction.ts'\nexport type { Insets, InsetsInput, Rect } from './layout.ts'\nexport { estimateTextWidth, innerRect, insets, LINE_HEIGHT } from './layout.ts'\nexport type { LegendItem, LegendOptions } from './legend.ts'\nexport { defaultHidden, legendContent } from './legend.ts'\nexport type {\n AfterRenderState,\n BeforeRenderState,\n ChartPlugin,\n PluginInstance,\n} from './plugin.ts'\nexport type { DownloadFormat, DownloadMenuOptions, DownloadOption } from './plugins/download.ts'\nexport {\n dataTable,\n defaultPlugins,\n download,\n highlight,\n keyboard,\n legend,\n pointer,\n sync,\n tooltip,\n} from './plugins/index.ts'\nexport { render } from './render/dom.ts'\nexport type { RenderToStringOptions } from './render/string.ts'\nexport { escapeAttr, escapeText, renderToString } from './render/string.ts'\nexport type { BandKey, BandScale, BandScaleOptions } from './scales/band.ts'\nexport { band, point } from './scales/band.ts'\nexport { extent } from './scales/extent.ts'\nexport type { LinearScale, LinearScaleOptions } from './scales/linear.ts'\nexport { linear } from './scales/linear.ts'\nexport { niceDomain, tickIncrement, tickStep, ticks } from './scales/ticks.ts'\nexport { cancel, flush, schedule } from './scheduler.ts'\nexport type { ArcOptions } from './shapes/arc.ts'\nexport { arcCentroid, arcPathStable, padAngleForGap } from './shapes/arc.ts'\nexport { barPath, hbarPath } from './shapes/bar.ts'\nexport type { Curve, PathOptions, Point } from './shapes/path.ts'\nexport { areaPath, linePath } from './shapes/path.ts'\nexport type { TooltipOptions, TooltipPlacement } from './tooltip.ts'\nexport { hitAnchor, placeTooltip, tooltipContent } from './tooltip.ts'\nexport type {\n Attrs,\n AttrValue,\n Child,\n ChildInput,\n ClassValue,\n Key,\n Props,\n StyleValue,\n VNode,\n} from './vnode.ts'\nexport { h, normalizeClass, normalizeStyle } from './vnode.ts'\n","/**\n * `@tabler/charts`: everything from `@tabler/charts/core`, with a `Chart`\n * that installs the built-in plugins (tooltip, legend, keyboard, …) and\n * every optional feature registered (time and log axes, decimation,\n * annotations, pattern fills, value labels, point shapes). The one exception\n * is the `download` menu's saver: `import '@tabler/charts/export'` adds it,\n * so charts that never offer a download do not carry the export code.\n */\n\nimport { annotationLayers, annotationValues } from './charts/annotations.ts'\nimport { dateLabels } from './charts/dates.ts'\nimport { logDomain, logTicks } from './charts/log-axis.ts'\nimport { patternFills } from './charts/patterns.ts'\nimport { markerPath, shapesStep } from './charts/point-shapes.ts'\nimport { timeAxis } from './charts/time-axis.ts'\nimport { labelsStep } from './charts/value-labels.ts'\nimport { addPost, register } from './features.ts'\nimport { hydrate } from './render/hydrate.ts'\nimport { morph } from './render/morph.ts'\nimport { log } from './scales/log.ts'\nimport { time, timePointScale } from './scales/time.ts'\nimport { lttb, lttbIndices } from './shapes/decimate.ts'\nimport { areaPath, linePath } from './shapes/path.ts'\n\n// Registered here, in the entry itself, so no bundler can shake it away.\nregister({\n time: { scale: time, points: timePointScale, axis: timeAxis },\n dates: dateLabels,\n log: { scale: log, domain: logDomain, ticks: logTicks },\n decimate: lttbIndices,\n line: { linePath, areaPath },\n annotations: { layers: annotationLayers, values: annotationValues },\n patterns: patternFills,\n 'point-shapes': markerPath,\n hydrate,\n morph,\n})\n\n// Steps that finish the content: shapes first, then the labels over them.\naddPost(shapesStep)\naddPost(labelsStep)\n\nexport { Chart } from './chart-default.ts'\nexport { types } from './chart-types.ts'\nexport * from './core.ts'\nexport type { DownloadOptions, ExportOptions, ExportTarget, ImageOptions } from './export-chart.ts'\nexport { downloadChart, exportImage, exportSVG } from './export-chart.ts'\nexport type { LogScaleOptions } from './scales/log.ts'\nexport type { TimeScale, TimeScaleOptions, TimeValue } from './scales/time.ts'\nexport { log, lttb, lttbIndices, time, timePointScale }\n","/**\n * `@tabler/charts-bootstrap`: a data API in the Bootstrap style. Charts are\n * declared in HTML and `init()` (or the CDN script, on its own) turns them\n * into charts.\n *\n * ```html\n * <div data-tc-chart=\"line\" data-tc-src=\"/api/sales.json\" data-tc-aspect-ratio=\"3\"></div>\n * <div data-tc-chart=\"bar\" data-tc-stacked=\"true\">\n * <script type=\"application/json\">{ \"labels\": [...], \"series\": [...] }</script>\n * </div>\n * ```\n *\n * `data-tc-chart` names the type; data comes from `data-tc-src` (a JSON URL),\n * an inline `<script type=\"application/json\">` or `data-tc-data`; every other\n * `data-tc-*` attribute is an option (`data-tc-aspect-ratio=\"3\"`), and\n * `data-tc-options` takes a JSON object for the rest.\n */\nimport { Chart, type ChartConfig, type ChartType, chartEvents, types } from '@tabler/charts'\n\n/** Every built-in chart type, by its `data-tc-chart` name. */\nexport { types }\n\nexport interface InitOptions {\n /** Extra or replacement chart types, merged over the built-in ones. */\n types?: Readonly<Record<string, ChartType<never>>>\n}\n\nconst SELECTOR = '[data-tc-chart]'\n/** Attributes that are not chart options. */\nconst RESERVED = new Set(['chart', 'src', 'data', 'options'])\n/** Options that are text, whatever it spells: a title \"2024\" is not a number. */\nconst TEXT = new Set(['title', 'description', 'locale', 'sync', 'id', 'class'])\n\nconst charts = new WeakMap<Element, Chart<object>>()\n/** Elements whose data is still loading, so a second init() does not fetch twice. */\nconst pending = new WeakSet<Element>()\n\n/** The chart created for an element by `init()`, if any; `O` types its options (e.g. `LineOptions`). */\nexport function getChart<O extends object = object>(element: Element): Chart<O> | undefined {\n return charts.get(element) as Chart<O> | undefined\n}\n\n/** Destroy the chart of an element (it can be initialized again later). */\nexport function dispose(element: Element): void {\n charts.get(element)?.destroy()\n charts.delete(element)\n}\n\n/** `\"true\"`, `\"3\"`, `'{\"a\":1}'` or plain text, as the value it spells. */\nfunction parseValue(text: string): unknown {\n if (text === 'true' || text === '') return true\n if (text === 'false') return false\n if (text !== '' && Number.isFinite(Number(text))) return Number(text)\n if (/^\\s*[[{]/.test(text)) return parseJson(text, 'a data-tc-* attribute')\n return text\n}\n\nfunction parseJson(text: string, what: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error) {\n throw new SyntaxError(\n `@tabler/charts-bootstrap: invalid JSON in ${what}: ${(error as Error).message}`,\n )\n }\n}\n\n/** Options from the element's `data-tc-*` attributes. */\nfunction optionsOf(element: HTMLElement): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n const json = element.dataset.tcOptions\n if (json) Object.assign(out, parseJson(json, 'data-tc-options'))\n for (const [key, value] of Object.entries(element.dataset)) {\n if (!key.startsWith('tc') || value === undefined) continue\n // dataset turns data-tc-aspect-ratio into tcAspectRatio.\n const name = key.charAt(2).toLowerCase() + key.slice(3)\n if (RESERVED.has(name)) continue\n out[name] =\n name === 'legend' && value === 'bottom'\n ? { position: 'bottom' }\n : name === 'tooltip' && value === 'light'\n ? { theme: 'light' }\n : name === 'download' && /^[a-z]/i.test(value) && !/^(true|false)$/.test(value)\n ? value.split(/[\\s,]+/).filter(Boolean)\n : TEXT.has(name)\n ? value\n : parseValue(value)\n }\n return out\n}\n\n/** Inline data: `data-tc-data` or a `<script type=\"application/json\">` child. */\nfunction inlineData(element: HTMLElement): unknown {\n const attr = element.dataset.tcData\n if (attr) return parseJson(attr, 'data-tc-data')\n const script = element.querySelector(':scope > script[type=\"application/json\"]')\n const text = script?.textContent?.trim()\n return text ? parseJson(text, 'the inline <script type=\"application/json\">') : undefined\n}\n\nfunction emit(element: Element, name: string, detail: unknown): void {\n element.dispatchEvent(new CustomEvent(`tc-${name}`, { detail, bubbles: true }))\n}\n\nfunction create(element: HTMLElement, type: ChartType<object>, data: unknown): Chart<object> {\n const config = { ...optionsOf(element), type, data } as ChartConfig<object>\n const chart = new Chart(element, config)\n for (const name of chartEvents) chart.on(name, (detail) => emit(element, name, detail))\n charts.set(element, chart)\n // The first render ran in the constructor, before anyone could listen.\n emit(element, 'render', { size: chart.size })\n return chart\n}\n\n/** Set up one element; returns its chart, or a promise while `data-tc-src` loads. */\nfunction setup(\n element: HTMLElement,\n known: Readonly<Record<string, ChartType<never>>>,\n): Chart<object> | Promise<Chart<object> | undefined> | undefined {\n const existing = charts.get(element)\n if (existing || pending.has(element)) return existing\n const name = element.dataset.tcChart ?? ''\n const type = known[name] as ChartType<object> | undefined\n if (!type) {\n const list = Object.keys(known).join(', ')\n throw new Error(`@tabler/charts-bootstrap: unknown chart type \"${name}\". Known types: ${list}.`)\n }\n const src = element.dataset.tcSrc\n if (!src) return create(element, type, inlineData(element) ?? [])\n\n pending.add(element)\n element.setAttribute('aria-busy', 'true')\n return fetch(src)\n .then((response) => {\n if (!response.ok) throw new Error(`${response.status} ${response.statusText}`.trim())\n return response.json()\n })\n .then(\n (data) => (element.isConnected ? create(element, type, data) : undefined),\n (error: unknown) => {\n emit(element, 'error', { error, src })\n console.error(`@tabler/charts-bootstrap: could not load ${src}:`, error)\n return undefined\n },\n )\n .finally(() => {\n pending.delete(element)\n element.removeAttribute('aria-busy')\n })\n}\n\n/**\n * Create a chart for every `[data-tc-chart]` in `root` (and `root` itself)\n * that does not have one yet. Resolves once charts with `data-tc-src` have\n * loaded; the ones with inline data exist as soon as `init()` returns.\n */\nexport function init(\n root: ParentNode = document,\n options: InitOptions = {},\n): Promise<Chart<object>[]> {\n const known = { ...types, ...options.types }\n const elements = [...root.querySelectorAll<HTMLElement>(SELECTOR)]\n if (root instanceof Element && root.matches(SELECTOR)) elements.unshift(root as HTMLElement)\n const made = elements.map((element) => {\n // One broken declaration (unknown type, bad JSON) must not stop the others.\n try {\n return setup(element, known)\n } catch (error) {\n emit(element, 'error', { error })\n console.error(error)\n return undefined\n }\n })\n return Promise.all(made).then((list) => list.filter((c): c is Chart<object> => c !== undefined))\n}\n\n/**\n * Keep `root` in sync: charts added later are initialized, charts removed\n * are destroyed. Returns a function that stops observing.\n */\nexport function observe(root: Element = document.body, options: InitOptions = {}): () => void {\n void init(root, options)\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n // A chart changing its own content (every hover, every update) adds no charts.\n const owner = (record.target as Element).closest?.(SELECTOR)\n if (owner && charts.has(owner)) continue\n for (const node of record.removedNodes) {\n if (!(node instanceof Element)) continue\n if (charts.has(node)) dispose(node)\n for (const inner of node.querySelectorAll(SELECTOR)) dispose(inner)\n }\n for (const node of record.addedNodes) {\n if (node instanceof Element && !node.isConnected) continue\n if (node instanceof Element) void init(node, options)\n }\n }\n })\n observer.observe(root, { childList: true, subtree: true })\n return () => observer.disconnect()\n}\n","/**\n * The CDN build (`dist/tabler-charts-bootstrap.min.js`): the library, the\n * chart stylesheet with the Bootstrap mapping, and the data API in one\n * classic script. On load it injects the styles and initializes every\n * `[data-tc-chart]`; everything is also on the `TablerCharts` global.\n *\n * ```html\n * <script src=\"https://cdn.jsdelivr.net/npm/@tabler/charts-bootstrap/dist/tabler-charts-bootstrap.min.js\"></script>\n * ```\n *\n * On the script tag, `data-no-styles` skips the styles (load them yourself)\n * and `data-observe` also initializes charts added later and destroys\n * removed ones.\n */\n// A script tag cannot import an entry: the download menu's saver comes along.\nimport '@tabler/charts/export'\nimport { init, observe } from './index.ts'\n\nif (typeof document !== 'undefined') {\n const script = document.currentScript\n if (!script?.hasAttribute('data-no-styles') && !document.getElementById('tc-styles')) {\n const style = document.createElement('style')\n style.id = 'tc-styles'\n style.textContent = __TC_PAGE_STYLES__\n // Under a strict CSP, the nonce of this script lets its styles in too.\n style.nonce = (script as HTMLScriptElement | null)?.nonce ?? ''\n // First in <head>, so the page's own CSS overrides it.\n document.head.prepend(style)\n }\n const observing = script?.hasAttribute('data-observe') ?? false\n const start = () => (observing ? observe(document.body) : void init(document))\n if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)\n else start()\n}\n\nexport * from '@tabler/charts'\nexport { dispose, getChart, init, observe, types } from './index.ts'\n"],"mappings":"2FAoBA,SAAgBoD,EAAO,EAAgC,EAAW,EAAW,CAE3E,IAAMC,EAAQ,GAA8B,CAC1C,IAAMC,EAAI,OAAOC,GAAU,SAAWA,EAAQA,IAAQC,GACtD,OAAO,OAAO,SAASF,CAAC,EAAKA,EAAeG,CAC9C,EACA,MAAO,CAAE,IAAKJ,EAAK,KAAK,EAAG,MAAOA,EAAK,OAAO,EAAG,OAAQA,EAAK,QAAQ,EAAG,KAAMA,EAAK,MAAM,CAAE,CAC9F,CAGA,SAAgBK,EAAU,EAAe,EAAgB,EAAuB,CAC9E,MAAO,CACL,EAAGC,EAAQ,KACX,EAAGA,EAAQ,IACX,MAAO,KAAK,IAAI,EAAGC,EAAQD,EAAQ,KAAOA,EAAQ,KAAK,EACvD,OAAQ,KAAK,IAAI,EAAGE,EAASF,EAAQ,IAAMA,EAAQ,MAAM,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