@tabler/charts-bootstrap 0.2.0 → 0.4.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.
@@ -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","round","cleanData","round","cleanData","round","cleanData","LABEL_GAP","HOVER_SLOP","truncate","round","cleanData","layout","round","cleanData","round","cleanData","round","cleanData","round","cleanData","exports","insets","value","fallback","side","key","v","mirrorSides","sides","rtl","innerRect","width","height","margins","isWide","code","charWidth","char","estimateTextWidth","text","fontSize","em","i","point","ASCII","_","round$1","LINE_HEIGHT","SVG_NS$2","SHAPE","TEXT$1","STOP","GROUP","SHAPES$1","rootOf","target","el","svg","transformOf","style","ox","oy","inline","live","copy","tag","props","declarations","name","transform","liveChildren","copies","child","twin","legendLayer","container","legend","items","doc","patterned","box","g","item","swatch","n","color","slot","fill","hidden","dot","label","bottom","margin","exportSVG","options","animation","chartStyle","total","wrap","title","background","rect","exportImage","type","scale","quality","markup","image","canvas","context","resolve","reject","blob","downloadChart","format","link","features","register","added","steps","addPost","step","config","content","interaction","ctx","each","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","symbols","notation","compactDisplay","own","digitsOf","small","large","exp","scaled","parts","digits","part","compactOf","o","formatDetail","stepPrecision","abs","hasPrecision","formatTicks","fmt","epsilon","formatDate","df","E10","E5","E2","tickSpec","start","stop","count","power","error","factor","i1","i2","inc","ticks","reverse","index","tickIncrement","tickStep","niceDomain","lo","hi","prev","linearTicks","d0","d1","bandTicks","isHorizontal","position","thinTicks","gap","sizes","tick","fitsBetween","j","span","sum","size","first","fits","kept","tail","axisSize","tickSize","tickPadding","labels","max","axis","area","line","horizontal","sign","offset","edge","tickLine","grid","direction","p","band","domain","range","paddingInner","paddingOuter","align","inner","r0","r1","bandwidth","at","px","pixel","raw","padding","extent","values","min","linear","k","mid","clamp","rMin","rMax","dMin","dMax","finite","optional","isRecord","list","numbers","x","records","fix","named","r","cleanSeries","data","d","s","cleanData$1","cleanItems","keyOf","legendItems","entry","groupAttrs","labelKey","seriesKey","seriesLegend","resolveLabels","plottable","isTimeAxis","l","toMs$1","labelFormatter","valueScale","valueTicks","markerShape","shapes","patterns","tickCount","auto","valueDomain","zeroDefault","override","extra","domainOf","pad","nlo","nhi","notesFeature","valueAxis","layout","of","finishLayout","overhang","plot","keys","time","y","xTicks","yTicks","flip","xOptions","notes","categories","present","plotClip","cartesianLayout","yOptions","showY","showX","timed","probeY","countX","labelAt","xAxis","edgeLabels","halfLine","edgeWidth","firstLabel","lastLabel","edgeX","valueWidth","halfStep","overflow","end","clipId","bleed","seriesAttrs","series","dash","categoryInteraction","anchor","markAt","formatLabel","formatValue","hitAt","center","empty","seriesIndex","hit","py","mark","seriesTable","limit","all","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","shape","a0","a1","w","spots","after","before","top","near","far","spot","dateLabels","utc","log","base","safe","ln","logBase","untransform","t0","t1","decades","keep","m","logDomain","niced","logTicks","hitKey","toChartPoint","clientX","clientY","sx","sy","legendContent","off","defaultHidden","NAME_RE","EVENT_RE","isValidTag","isValidAttr","SVG_NS$1","HTML_NS","rendered","roots","render","vnode","replace","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","parentInSvg","inSvg","escapeAttr","childInSvg","TEXT_RE","ATTR_RE","TEXT_RE_G","ATTR_RE_G","ENTITIES","replaceEntity","listeners","seen","observer","getObserver","entries","contentRect","observeResize","listener","ro","queue","pending$2","requestFrame","callback","run","task","schedule","flush","flushHooks","cancel","ran","later","uid","nextId","resolveSize","measured","measuredWidth","ratio","renderContent","id","onHitTest","renderContext","measuredFontSize","cleanData","assertType","resolveLegend","option","chartLabel","names","shown","countNodes","c","isStatic","composeChart","still","underlay","overlay","extraAttrs","descId","fills","buildChart","chartToString","chartEvents","mounted","Chart$1","#cfg","#onResize","followsHeight","changed","#measured","#font","#markResizing","#schedule","#handlers","#unobserve","#plugins","#destroyed","#current","#source","#hovered","#hit","#cache","#resizeTimer","#toggled","#adopt","#rtl","defaultPlugins","element","#measure","plugin","reserved","cfg","#measureFontSize","source","#setHover","event","#hiddenSet","stale","#content","#refreshHighlight","adopted","#compose","hiddenKey","under","over","layer","handler","set","force","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","cal","interval","primary","above","tz","main","upper","timePointScale","stamps","valid","positions","ms","down","timeAxis","points","probe","overlaps","contains","outer","valueLabels","spec","pie","cell","stacked","marks","share","candidates","reach","along","room","slim","sliceFits","other","radius","depth","labelsStep","matches","hydrateElement","current","texts","created","hydrate","running","tween","origin","duration","draw","state","begin","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","#n","rounded","#xy","x2","y2","emit$1","path","curve","move","dedupe","monotone","xm","tangents","h0","h1","s0","s1","endTangent","dx","isValid","linePath","areaPath","baseline","baseAt","NAMES","DEFAULT_FORMATS","download","chart","host","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","table","caption","corner","headers","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","bounds","left","fitsRight","fitsLeft","rawX","right","waiting","placeAll","measure","tooltip","tip","turns","turn","clip","Chart","fadeMask","stackSeries","percent","nullAsZero","up","lastUp","lastDown","row","segment","stackBounds","stacks","seriesPoints","connectNulls","renderLines","pointRadius","filled","decimate","fillStyle","gradient","fadeId","stack","seg","pts","drawn","bottoms","areas","dots","cx","cy","round","barPath","sweep","rr","hbarPath","hgt","length","horizontalLayout","probeValues","showValues","showCategories","probeCategories","edgeLabel","bar","maxBarWidth","groupPadding","orientation","isLine","lineKeys","stackHidden","layoutOptions","slots","order","columns","barWidth","groupWidth","slotAt","barLeft","across","negative","away","paths","bodyPath","asCartesian","pick","candlestick","maxCandleWidth","cartesian","paint","candle","candles","EPSILON","PI","HALF_PI$1","TAU","DEG","asin","acos","intersect","x3","y3","x10","y10","x32","y32","cornerTangents","rc","cw","x01","y01","x11","y11","x00","y00","dy","d2","D","cx0","cy0","cx1","cy1","dx0","dy0","dx1","dy1","sector","da","a01","a11","a00","a10","da0","da1","ap","rp","rc0","rc1","p0","p1","oc","bx","by","cos","kc","lc","arcCentroid","padAngleForGap","innerRadius","outerRadius","angleOf","arcPathStable","arc","ring","ccw","delta","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","rectPath","EMPTY","shade","rangeKey","rangeOf","ranges","slotColor","renderHeatmap","dataMin","dataMax","stops","bySeries","u","pct","rowTicks","halfColumn","cellW","cellH","cellX","cellY","valueAt","column","painted","heatmapLegend","heatmap","MAX_SEATS","partiesOf","party","seatCounts","parties","taken","wanted","distribute","counts","layoutSeats","closed","radiiOf","pitchOf","capacity","pitch","seats","spacing","angle","seat","renderParliament","seatsOf","vacant","circle","parliamentTable","parliament","groupSlices","maxSlices","slice","groupLegend","slices","segmentsOf","segments","renderPercentageBar","boxes","percentageBarTable","percentageBar","layoutSlices","renderPie","defaults","strokeGap","pieTable","pieType","donut","truncate$1","word","sin","fitRadius","angles","blockHeight","renderRadar","labelWidth","wrapped","polygon","radiusOf","spokeLabels","rest","radar","truncate","colorOf","graph","justify","byName","nodes","declared","isHidden","legendKey","links","pass","ia","ib","layout$1","nodeWidth","nodePadding","widest","match","cap","byColumn","col","showValue","linkEnds","linkPath","ty","cubic","inLink","renderSankey","nodeMark","linkItem","hitNode","linkIndex","flows","hitLink","sankeyLegend","sankeyTable","sankey","circlePath","sizeOf","renderScatter","maxSize","bubble","countY","usable","xDomain","yDomain","ticksOf","probeX","half","pointIndex","fx","fy","fs","sz","bestDistance","distance","dotsPath","scatterTable","withSize","withLabel","take","scatter","renderSparkline","variant","markers","tristate","zero","bars","xAt","labelOf","yOf","dotAt","extremes","sparkline","sized","squarify","sorted","short","largest","t2","worst","edges","tx","tw","th","trail","fit","chars","cut","renderTreemap","tiles","tile","treemapTable","walk","cleanNodes","treemap","types","SELECTOR","RESERVED","TEXT","charts","pending","getChart","dispose","parseValue","parseJson","what","optionsOf","json","inlineData","attr","emit","detail","setup","known","existing","src","response","init","root","elements","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/shapes/rect.ts","../../core/src/charts/heatmap.ts","../../core/src/charts/parliament.ts","../../core/src/charts/others.ts","../../core/src/charts/percentage-bar.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/charts/treemap.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/** Swap the left and right of `sides` in a right-to-left chart. */\nexport const mirrorSides = <T extends { left: number; right: number }>(\n sides: T,\n rtl: boolean | undefined,\n): T => (rtl ? { ...sides, left: sides.right, right: sides.left } : sides)\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 mirrorSides,\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 /** Run the categories from the right. Defaults to the chart's `rtl`. */\n reverse?: 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 // The axis beside the plot: on the right in a right-to-left chart.\n const side = ctx.rtl ? 'right' : 'left'\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' : side, ticks: yTicks, area }),\n ]\n const categories = ((xOptions.show !== false && plot.labels.length > 0) || xOptions.line) && [\n axis({ position: flip ? side : '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 // Right to left, the sides are worked out as their mirror image, then swapped.\n const rtl = ctx.rtl === true\n const reverse = xOptions.reverse ?? rtl\n const pad = mirrorSides(insets(options.padding), rtl)\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 // The label at the value axis' end of the plot, and the one at the other end.\n const edgeWidth = (last: boolean) =>\n showX ? estimateTextWidth(edgeLabels[last ? edgeLabels.length - 1 : 0] ?? '', fontSize) : 0\n const firstLabel = edgeWidth(reverse !== rtl)\n const lastLabel = edgeWidth(reverse === rtl)\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 ...mirrorSides(sides, rtl),\n }\n const area = innerRect(width, height, margins)\n\n const end = area.x + area.width\n const x = xAxis.scale(reverse ? [end, area.x] : [area.x, end])\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 reversed: x.range[1] < x.range[0],\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 /** Categories run from the right: the left arrow key goes to the next one. */\n reversed?: boolean\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> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' }\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 /** Lay the chart out right to left (the `rtl` option, resolved). */\n rtl?: boolean\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 * Mirror the layout for right-to-left pages: the value axis on the right\n * and categories running from the right (`x.reverse` overrides the latter).\n * `'auto'` follows the `direction` of the container (left to right in SSR).\n * The legend, the tooltip and the download menu read right to left with it.\n * Cartesian charts, heatmaps, sparklines and sankey diagrams. Defaults to `false`.\n */\n rtl?: boolean | 'auto'\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 rtl?: boolean,\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 rtl,\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 rtl: boolean = config.rtl === true,\n): RenderContext {\n return {\n rtl,\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 rtl: boolean = config.rtl === true,\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 rtl && 'tc-rtl',\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 rtl: boolean\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 /** The resolved `rtl` option, read with the font size (`'auto'` asks the container). */\n #rtl = false\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 /**\n * Whether the chart is laid out right to left: the `rtl` option, with\n * `'auto'` read from the container (together with the font size).\n */\n get rtl(): boolean {\n const cfg = this.#cfg\n if (this.#font === undefined) {\n this.#rtl =\n cfg.rtl === 'auto'\n ? typeof getComputedStyle === 'function' &&\n getComputedStyle(this.element).direction === 'rtl'\n : cfg.rtl === true\n this.#font = cfg.fontSize ?? this.#measureFontSize()\n }\n return this.#rtl\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 const rtl = this.rtl\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 cache.rtl !== rtl\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 rtl,\n )\n cache = {\n cfg,\n width: size.width,\n height: size.height,\n hidden: hiddenKey,\n fontSize,\n rtl,\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 content.rtl,\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 // (They run down the pixels on a reversed range.)\n const down = range[1] < range[0]\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 !== down) a = mid + 1\n else b = mid\n }\n const prev = a - 1\n return prev >= 0 &&\n Math.abs(pixel - (positions[prev] as number)) < Math.abs((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 // Sideways, bars grow to the right, or to the left in a right-to-left chart.\n const side = ctx.rtl ? -sign : sign\n candidates.push(\n horizontal ? at(item.x - side * 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 + side * 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 // In the corner the chart starts from: the left one, right to left.\n el.dir = chart.rtl ? 'rtl' : ''\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 // Arrows follow the screen: categories from the right swap them.\n if (interaction.reversed && /^Arrow(L|R)/.test(key))\n key = key === 'ArrowLeft' ? 'ArrowRight' : 'ArrowLeft'\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 // A right-to-left chart reads right to left, whatever the page around it.\n el.dir = chart.rtl ? 'rtl' : ''\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 (the other way round with `rtl`), vertically centered on the\n * 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 rtl = false,\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 // The side read first, unless only the other one has room.\n const side = (rtl ? fitsLeft || !fitsRight : fitsLeft && !fitsRight) ? 'left' : 'right'\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 const { rtl } = chart\n tip.dir = rtl ? 'rtl' : ''\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 12,\n rtl,\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, mirrorSides } 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, rtl } = ctx\n const overhang = layout.overhang ?? 0\n // Right to left, the sides are worked out as their mirror image, then swapped.\n const pad = mirrorSides(insets(options.padding), rtl)\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 = mirrorSides(\n {\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 rtl,\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 // Values grow away from the categories: to the left when those are on the right.\n const end = area.x + area.width\n const y = value.scale(rtl ? [end, area.x] : [area.x, end])\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 // Grouped bars follow the categories: from the right when those are reversed.\n const slotAt = (slot: number) => (x.range[1] < x.range[0] ? columns - 1 - slot : slot)\n const barLeft = (seriesIndex: number, i: number) =>\n x.at(i) + offset + (stacks ? 0 : slotAt(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[slotAt(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 // on the side it grows to (in pixels: up, right, or left when mirrored).\n const away = Math.sign(y(seg.y1) - y(seg.y0))\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 { round } from '../layout.ts'\n\n/** A rounded rectangle as path data (the hover ring of a cell or a tile). */\nexport function rectPath(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","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 {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n mirrorSides,\n round,\n} from '../layout.ts'\nimport { band } from '../scales/band.ts'\nimport { extent } from '../scales/extent.ts'\nimport { rectPath } from '../shapes/rect.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\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 // Right to left, the sides are worked out as their mirror image, then swapped.\n const { rtl } = ctx\n const pad = mirrorSides(insets(options.padding, 0), rtl)\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(\n width,\n height,\n mirrorSides(\n {\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 rtl,\n ),\n )\n const end = area.x + area.width\n const x = band(\n labels.map((_, i) => i),\n rtl ? [end, area.x] : [area.x, end],\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: rectPath(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 reversed: rtl === true,\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 column = Math.min(labels.length - 1, Math.floor((px - area.x) / (x.step || 1)))\n const i = rtl ? labels.length - 1 - column : column\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: rtl ? 'right' : '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 // biome-ignore lint/complexity/useMathMinMax: the ternary also turns a NaN `total` into 0, Math.max would not\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 { LegendItem } from '../legend.ts'\nimport { keyOf, type Named } from './named.ts'\n\n/** Legend key of the slice that groups the rest. */\nconst OTHERS = '__others__'\n\n/** A slice or segment with its size, in color slot `index` (past the data for the rest). */\nexport interface Grouped<T> {\n data: T\n index: number\n value: number\n}\n\n/**\n * The slices of the data in its order: every entry, or with more of them\n * than `maxSlices`, the largest ones and one slice for the rest (in the\n * color of the slots past the palette), named by `label`. `maxSlices` is nine\n * by default (the eight palette colors and the rest) and zero never groups.\n * Hidden entries count here, so hiding one does not pull another out of the\n * rest.\n */\nexport function groupSlices<T extends Named & { value: number }>(\n data: readonly T[],\n maxSlices: number | undefined,\n label = 'Others',\n): Grouped<T>[] {\n const all = data.map((entry, index) => ({\n data: entry,\n index,\n value: Math.max(0, entry.value || 0),\n }))\n const max = Number.isFinite(maxSlices) && (maxSlices as number) >= 0 ? maxSlices : 9\n const limit = max ? Math.max(1, Math.round(max)) : Number.POSITIVE_INFINITY\n if (all.length <= limit) return all\n const kept = new Set(\n [...all].sort((a, b) => b.value - a.value || a.index - b.index).slice(0, limit - 1),\n )\n const value = all.reduce((sum, slice) => (kept.has(slice) ? sum : sum + slice.value), 0)\n return [\n ...all.filter((slice) => kept.has(slice)),\n { data: { name: label, id: OTHERS, value } as T, index: Math.max(8, all.length), value },\n ]\n}\n\n/** Legend entries of the slices as drawn, the rest included. */\nexport function groupLegend<T extends Named>(slices: readonly Grouped<T>[]): LegendItem[] {\n return slices.map(({ data, index }) => {\n const item: LegendItem = { key: keyOf(data), name: data.name, index }\n if (data.color) item.color = data.color\n if (data.hidden) item.hidden = true\n return item\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 { type ChildInput, type ClassValue, h } from '../vnode.ts'\nimport { cleanItems } from './clean.ts'\nimport { groupAttrs, keyOf } from './named.ts'\nimport { type Grouped, groupLegend, groupSlices } from './others.ts'\n\n/** One segment of a percentage bar. */\nexport interface PercentageBarSegment {\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 segment group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface PercentageBarOptions {\n data: readonly PercentageBarSegment[]\n /**\n * Order of the segments along the bar: as in the data (`'data'`, the\n * default) or the largest first (`'size'`). Colors follow the data either\n * way, and the segment of the rest always comes last.\n */\n order?: 'data' | 'size'\n /**\n * The most segments drawn, the one for the rest included: with more entries\n * than that, the largest `maxSlices - 1` keep a segment of their own and\n * the others share one, named by `othersLabel`, at the end of the bar.\n * Defaults to `9` (the eight palette colors and the rest); `0` never\n * groups.\n */\n maxSlices?: number\n /** Name of the segment that groups the rest. Defaults to `'Others'`. */\n othersLabel?: string\n /** Space between segments in pixels, drawn as surface. Defaults to `2`. */\n gap?: number\n /** Corner radius of the segments. Defaults to `4`. */\n radius?: number\n /** Format of the values (tooltip, table). */\n format?: NumberFormat\n /** Extra space around the bar, in pixels. */\n padding?: InsetsInput\n}\n\n/** Height of the chart when neither `height` nor `aspectRatio` is set: a strip. */\nconst HEIGHT = 16\n\ntype Segment = Grouped<PercentageBarSegment>\n\n/** The segments of the data: nine at most by default, the one for the rest included. */\nconst group = (options: PercentageBarOptions): Segment[] =>\n groupSlices(options.data, options.maxSlices, options.othersLabel)\n\n/** The visible segments in their order along the bar, and their sum. */\nfunction segmentsOf(\n options: PercentageBarOptions,\n hidden: ReadonlySet<string>,\n): { segments: Segment[]; total: number } {\n const count = options.data.length\n const segments = group(options).filter((segment) => !hidden.has(keyOf(segment.data)))\n if (options.order === 'size') {\n // (The rest stays last, whatever its size.)\n segments.sort(\n (a, b) =>\n Number(a.index >= count) - Number(b.index >= count) ||\n b.value - a.value ||\n a.index - b.index,\n )\n }\n return { segments, total: segments.reduce((sum, segment) => sum + segment.value, 0) }\n}\n\nfunction renderPercentageBar(options: PercentageBarOptions, ctx: RenderContext): ChildInput {\n const { width, height, locale } = ctx\n const gap = Math.max(0, options.gap ?? 2)\n const radius = Math.max(0, options.radius ?? 4)\n const area = innerRect(width, height, insets(options.padding, 0))\n const { segments, total } = segmentsOf(options, ctx.hidden)\n const drawn = segments.filter((segment) => segment.value > 0)\n\n // Every segment gives up half a gap on each side but the ends of the bar.\n let offset = area.x\n const boxes = drawn.map((segment, position) => {\n const length = (segment.value / total) * area.width\n const left = position === 0 ? 0 : gap / 2\n const right = position === drawn.length - 1 ? 0 : gap / 2\n const box = {\n x: offset + left,\n y: area.y,\n width: Math.max(0, length - left - right),\n height: area.height,\n }\n offset += length\n return box\n })\n\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n const hitFor = (position: number): Hit => {\n const segment = drawn[position] as Segment\n const box = boxes[position] as (typeof boxes)[number]\n const x = box.x + box.width / 2\n const item: HitItem = {\n name: segment.data.name,\n seriesIndex: segment.index,\n value: segment.value,\n text: `${value(segment.value)} (${share.format(segment.value / total)})`,\n x,\n y: box.y + box.height / 2,\n box,\n }\n if (segment.data.color) item.color = segment.data.color\n const n = round\n return {\n index: position,\n label: segment.data.name,\n title: '',\n x,\n area,\n items: [item],\n seriesIndex: segment.index,\n // A ring just inside the hovered segment.\n mark: {\n d: `M${n(box.x + 1)},${n(box.y + 1)}h${n(box.width - 2)}v${n(box.height - 2)}h${n(2 - box.width)}Z`,\n x: 0,\n y: 0,\n },\n }\n }\n\n const interaction: Interaction = {\n count: drawn.length,\n hitIndex: (position) => (drawn[position] ? hitFor(position) : null),\n hitTest(px, py) {\n if (py < area.y || py > area.y + area.height) return null\n const position = boxes.findIndex(\n (box) => px >= box.x - gap / 2 && px <= box.x + box.width + gap / 2,\n )\n return position < 0 ? null : hitFor(position)\n },\n }\n ctx.onHitTest(interaction)\n\n return h(\n 'g',\n { class: 'tc-percentage-bar' },\n // Empty: the track alone, so the chart keeps its place.\n drawn.length === 0 &&\n h('rect', {\n key: 'track',\n class: 'tc-percentage-bar-track',\n x: round(area.x),\n y: round(area.y),\n width: round(area.width),\n height: round(area.height),\n rx: round(Math.min(radius, area.width / 2, area.height / 2)),\n }),\n segments.map((segment) => {\n const box = boxes[drawn.indexOf(segment)]\n return h(\n 'g',\n groupAttrs(segment.data, segment.index),\n box &&\n h('rect', {\n class: 'tc-segment',\n x: round(box.x),\n y: round(box.y),\n width: round(box.width),\n height: round(box.height),\n rx: round(Math.min(radius, box.width / 2, box.height / 2)),\n }),\n )\n }),\n )\n}\n\nfunction percentageBarTable(options: PercentageBarOptions, ctx: RenderContext): DataTable {\n const { segments, total } = segmentsOf(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: segments.map((segment) => [\n segment.data.name,\n value(segment.value),\n share.format(total > 0 ? segment.value / total : 0),\n ]),\n }\n}\n\n/**\n * Percentage bar: parts of a whole as segments of one horizontal bar, each as\n * wide as its share (a donut's ring unrolled, for a strip under a number).\n * The chart is a strip 16 pixels tall unless `height` or `aspectRatio` is set.\n *\n * ```ts\n * new Chart('#el', {\n * type: percentageBar,\n * data: [{ name: 'Paid', value: 62 }, { name: 'Open', value: 27 }, { name: 'Overdue', value: 11 }],\n * })\n * ```\n */\nexport const percentageBar: ChartType<PercentageBarOptions> = {\n name: 'percentage-bar',\n // (The options come with the whole config: its size is defaulted here.)\n clean: (options) => {\n const config = options as PercentageBarOptions & { height?: unknown; aspectRatio?: unknown }\n return {\n ...config,\n data: cleanItems(config.data),\n height: config.height ?? (config.aspectRatio ? undefined : HEIGHT),\n }\n },\n render: renderPercentageBar,\n legend: (options) => groupLegend(group(options)),\n table: percentageBarTable,\n valueLabels: { marks: 'cell' },\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 } from './named.ts'\nimport { groupLegend, groupSlices } from './others.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 /**\n * The most slices drawn, the one for the rest included: with more entries\n * than that, the largest `maxSlices - 1` keep a slice of their own and the\n * others share one, named by `othersLabel`, after them. Defaults to `9`\n * (the eight palette colors and the rest); `0` never groups.\n */\n maxSlices?: number\n /** Name of the slice that groups the rest. Defaults to `'Others'`. */\n othersLabel?: string\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 = groupSlices(options.data, options.maxSlices, options.othersLabel).filter(\n (slice) => !hidden.has(keyOf(slice.data)),\n )\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) =>\n groupLegend(groupSlices(options.data, options.maxSlices, options.othersLabel)),\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 mirrorSides,\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 // Right to left, the layout is worked out as its mirror image, then flipped.\n const { rtl } = ctx\n const area = innerRect(width, height, mirrorSides(insets(options.padding), rtl))\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 const x = plot.x + (columns > 1 ? c * step : (plot.width - nodeWidth) / 2)\n n.x = rtl ? width - x - nodeWidth : x\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 if (rtl) plot.x = width - plot.x - plot.width\n return { nodes, links, plot, nodeWidth, labels }\n}\n\n/** The x of a link's ends: the facing edges of its source and its target. */\nconst linkEnds = (link: Link, nodeWidth: number): [number, number] =>\n link.source.x > link.target.x\n ? [link.source.x, link.target.x + nodeWidth]\n : [link.source.x + nodeWidth, link.target.x]\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, x1] = linkEnds(link, nodeWidth)\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, x1] = linkEnds(link, nodeWidth)\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} ${ctx.rtl ? '←' : '→'} ${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 // The label's side is the one of the left-to-right layout: mirrored with it.\n const before = (label.side === 'left') !== (ctx.rtl === true)\n const x = round(before ? n.x - LABEL_GAP : n.x + nodeWidth + LABEL_GAP)\n const y = round(n.y + n.height / 2)\n const anchor = before ? '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 mirrorSides,\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; `reverse` runs it from the right (the default with `rtl`). */\n x?: ValueAxisOptions & { reverse?: boolean }\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 // Right to left, the sides are worked out as their mirror image, then swapped.\n const { rtl } = ctx\n const reverse = xOptions.reverse ?? rtl === true\n // The x tick at the value axis' end of the plot, and the one at the other end.\n const near = reverse === (rtl === true) ? 0 : probeX.length - 1\n const pad = mirrorSides(insets(options.padding), rtl)\n const margins = mirrorSides(\n {\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 - near]), 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[near]), overhang),\n },\n rtl,\n )\n const area = innerRect(width, height, margins)\n const end = area.x + area.width\n const x = valueScale(xDomain, reverse ? [end, area.x] : [area.x, end], 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: rtl ? 'right' : '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 // Right to left, the values run from the right: value `i` takes the place of its mirror.\n const place = (i: number) => (ctx.rtl ? count - 1 - i : i)\n const xAt = (i: number) =>\n bars\n ? area.x + slot * place(i) + slot / 2\n : area.x + (count > 1 ? (area.width * place(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 reversed: ctx.rtl === true,\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(place(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 { 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 { estimateTextWidth, type InsetsInput, innerRect, insets, round } from '../layout.ts'\nimport { rectPath } from '../shapes/rect.ts'\nimport { type ChildInput, type ClassValue, h } from '../vnode.ts'\nimport { cleanData, finite, isRecord, list, named } from './clean.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** A tile of a treemap, or a group of them. */\nexport interface TreemapNode {\n name: string\n /** Size of the tile; a negative value is zero. A group is as large as its `children`. */\n value?: number\n /** Tiles (or groups) inside this one; they share its color. */\n children?: readonly TreemapNode[]\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 group (top level) or the tile. */\n class?: ClassValue\n /** Start hidden (top level; toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface TreemapOptions {\n /** Tiles, or groups of tiles; each top-level entry takes a palette color and a legend entry. */\n data: readonly TreemapNode[]\n /** Space between tiles in pixels. Defaults to `2`. */\n gap?: number\n /** Corner radius of the tiles. Defaults to `3`. */\n radius?: number\n /** Names (and values, where they fit) written in the tiles. Defaults to `true`. */\n labels?: boolean\n /** Format of the values (tiles, tooltip, table). */\n format?: NumberFormat\n /** Extra space around the chart, in pixels. */\n padding?: InsetsInput\n}\n\n/** Levels of nesting read from the data, and the most nodes: enough for any chart, few enough to draw. */\nconst MAX_DEPTH = 8\nconst MAX_NODES = 5000\n\n/** Space between a tile's edge and its text. */\nconst INSET = 6\n\n/** A node with its size worked out. */\ninterface Sized {\n node: TreemapNode\n value: number\n children?: Sized[]\n}\n\ninterface Tile {\n node: TreemapNode\n key: string\n /** Position of the top-level ancestor in `data` (the color slot). */\n top: number\n /** Names of the ancestors, outermost first. */\n trail: readonly string[]\n value: number\n x: number\n y: number\n width: number\n height: number\n}\n\nfunction sized(nodes: readonly TreemapNode[]): Sized[] {\n return nodes.map((node) => {\n if (node.children?.length) {\n const children = sized(node.children)\n return { node, children, value: children.reduce((sum, child) => sum + child.value, 0) }\n }\n return { node, value: Math.max(0, node.value ?? 0) }\n })\n}\n\n/** The top-level entries with their sizes and color slots, without the hidden ones. */\nfunction visible(options: TreemapOptions, hidden: ReadonlySet<string>) {\n return sized(options.data)\n .map((entry, index) => ({ entry, index }))\n .filter(({ entry }) => !hidden.has(keyOf(entry.node)))\n}\n\n/**\n * Squarified layout (Bruls, Huizing, van Wijk): `items`, largest first, fill\n * the rectangle in rows along its shorter side, each row closed as soon as\n * another item would make its tiles less square.\n */\nfunction squarify(\n items: readonly Sized[],\n x: number,\n y: number,\n w: number,\n hgt: number,\n place: (item: Sized, x: number, y: number, w: number, hgt: number) => void,\n): void {\n const sorted = items.filter((item) => item.value > 0).sort((a, b) => b.value - a.value)\n let left = sorted.reduce((sum, item) => sum + item.value, 0)\n let i = 0\n while (i < sorted.length && w > 0 && hgt > 0) {\n const short = Math.min(w, hgt)\n // Pixels of area per unit of value in what is left of the rectangle.\n const k = (w * hgt) / left\n const largest = (sorted[i] as Sized).value\n let sum = 0\n let best = Number.POSITIVE_INFINITY\n let j = i\n for (; j < sorted.length; j++) {\n const next = sum + (sorted[j] as Sized).value\n // Thickness of the row squared: its worst tile is the largest or the smallest.\n const t2 = ((next * k) / short) ** 2\n const worst = Math.max(t2 / ((sorted[j] as Sized).value * k), (largest * k) / t2)\n if (worst > best) break\n best = worst\n sum = next\n }\n const thickness = (sum * k) / short\n let offset = 0\n for (; i < j; i++) {\n const item = sorted[i] as Sized\n const length = (item.value * k) / thickness\n if (w >= hgt) place(item, x, y + offset, thickness, length)\n else place(item, x + offset, y, length, thickness)\n offset += length\n }\n if (w >= hgt) {\n x += thickness\n w -= thickness\n } else {\n y += thickness\n hgt -= thickness\n }\n left -= sum\n }\n}\n\n/** Half gaps left around a tile on its left, top, right and bottom side. */\ntype Edges = readonly [number, number, number, number]\n\n/**\n * The tiles of `items` in a rectangle, groups laid out inside their own.\n * The gap is cut from the tiles after they are placed, so it does not change\n * their arrangement: half of it on every side (a whole one between any two\n * neighbors), none at the edge of the chart. `edges` are the half gaps of\n * the rectangle itself.\n */\nfunction layout(\n items: readonly Sized[],\n x: number,\n y: number,\n w: number,\n hgt: number,\n gap: number,\n out: Tile[],\n edges: Edges,\n top?: { index: number; key: string; trail: readonly string[] },\n slots?: readonly number[],\n): void {\n squarify(items, x, y, w, hgt, (item, tx, ty, tw, th) => {\n const index = top?.index ?? (slots?.[items.indexOf(item)] as number)\n const key = top ? `${top.key}/${keyOf(item.node)}` : keyOf(item.node)\n const trail = top?.trail ?? []\n // A side on the border of the rectangle takes its half gap (none at the chart's edge), the others one.\n const near = 0.01\n const sides: Edges = [\n tx - x < near ? edges[0] : 1,\n ty - y < near ? edges[1] : 1,\n x + w - tx - tw < near ? edges[2] : 1,\n y + hgt - ty - th < near ? edges[3] : 1,\n ]\n if (item.children) {\n layout(item.children, tx, ty, tw, th, gap, out, sides, {\n index,\n key,\n trail: [...trail, item.node.name],\n })\n } else {\n const half = gap / 2\n out.push({\n node: item.node,\n key,\n top: index,\n trail,\n value: item.value,\n x: tx + sides[0] * half,\n y: ty + sides[1] * half,\n width: Math.max(0, tw - (sides[0] + sides[2]) * half),\n height: Math.max(0, th - (sides[1] + sides[3]) * half),\n })\n }\n })\n}\n\n/** `text` cut to `width` pixels with an ellipsis, or `''` when not even a few letters fit. */\nfunction fit(text: string, width: number, fontSize: number): string {\n if (estimateTextWidth(text, fontSize) <= width) return text\n const chars = [...text]\n while (chars.length > 2) {\n chars.pop()\n const cut = `${chars.join('').trimEnd()}…`\n if (estimateTextWidth(cut, fontSize) <= width) return cut\n }\n return ''\n}\n\nfunction renderTreemap(options: TreemapOptions, ctx: RenderContext): ChildInput {\n const { width, height, fontSize, locale } = ctx\n const gap = Math.max(0, options.gap ?? 2)\n const radius = Math.max(0, options.radius ?? 3)\n const area = innerRect(width, height, insets(options.padding, 0))\n const entries = visible(options, ctx.hidden)\n const total = entries.reduce((sum, { entry }) => sum + entry.value, 0)\n\n const tiles: Tile[] = []\n layout(\n entries.map(({ entry }) => entry),\n area.x,\n area.y,\n area.width,\n area.height,\n gap,\n tiles,\n [0, 0, 0, 0],\n undefined,\n entries.map(({ index }) => index),\n )\n\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n const hitFor = (tile: Tile, index: number): Hit => {\n const x = tile.x + tile.width / 2\n const item: HitItem = {\n name: tile.node.name,\n seriesIndex: tile.top,\n value: tile.value,\n text: `${value(tile.value)} (${share.format(total > 0 ? tile.value / total : 0)})`,\n x,\n y: tile.y + tile.height / 2,\n }\n const color = tile.node.color ?? options.data[tile.top]?.color\n if (color) item.color = color\n return {\n index,\n label: [...tile.trail, tile.node.name].join(' › '),\n title: tile.trail.join(' › '),\n x,\n area,\n items: [item],\n seriesIndex: tile.top,\n // A ring just inside the hovered tile.\n mark: {\n d: rectPath(tile.x + 1, tile.y + 1, tile.width - 2, tile.height - 2, radius - 1),\n x: 0,\n y: 0,\n },\n }\n }\n\n const interaction: Interaction = {\n count: tiles.length,\n hitIndex: (index) => {\n const tile = tiles[index]\n return tile ? hitFor(tile, index) : null\n },\n hitTest(px, py) {\n const index = tiles.findIndex(\n (tile) =>\n px >= tile.x - gap / 2 &&\n px <= tile.x + tile.width + gap / 2 &&\n py >= tile.y - gap / 2 &&\n py <= tile.y + tile.height + gap / 2,\n )\n return index < 0 ? null : hitFor(tiles[index] as Tile, index)\n },\n }\n ctx.onHitTest(interaction)\n\n const groups = entries.map(({ entry, index }) =>\n h(\n 'g',\n groupAttrs(entry.node, index),\n tiles\n .filter((tile) => tile.top === index)\n .map((tile) =>\n h('rect', {\n key: tile.key,\n class: ['tc-tile', tile.trail.length > 0 && tile.node.class],\n x: round(tile.x),\n y: round(tile.y),\n width: round(tile.width),\n height: round(tile.height),\n rx: round(Math.min(radius, tile.width / 2, tile.height / 2)),\n // A tile inside a group may have a color of its own.\n style: tile.trail.length > 0 ? { '--tc-series-color': tile.node.color } : undefined,\n }),\n ),\n ),\n )\n\n // Names where a few letters fit, values below where there is a second line.\n const line = fontSize * 1.3\n const labels =\n options.labels !== false &&\n tiles.flatMap((tile) => {\n const room = tile.width - INSET * 2\n const name = tile.height >= line + INSET ? fit(tile.node.name, room, fontSize) : ''\n if (!name) return []\n const text = value(tile.value)\n const x = round(tile.x + INSET)\n const y = tile.y + INSET + fontSize * 0.85\n return [\n h('text', { key: tile.key, class: 'tc-treemap-label', x, y: round(y) }, name),\n tile.height >= line * 2 + INSET * 1.5 &&\n estimateTextWidth(text, fontSize) <= room &&\n h(\n 'text',\n {\n key: `${tile.key}/value`,\n class: 'tc-treemap-label tc-treemap-value',\n x,\n y: round(y + line),\n },\n text,\n ),\n ]\n })\n\n return [\n h('g', { class: 'tc-treemap-tiles' }, groups),\n labels && h('g', { class: 'tc-treemap-labels', 'aria-hidden': 'true' }, labels),\n ]\n}\n\nfunction treemapTable(options: TreemapOptions, ctx: RenderContext, limit: number): DataTable {\n const entries = visible(options, ctx.hidden)\n const total = entries.reduce((sum, { entry }) => sum + entry.value, 0)\n const value = formatNumber(options.format, ctx.locale)\n const share = getNumberFormat(ctx.locale, { style: 'percent', maximumFractionDigits: 1 })\n const rows: string[][] = []\n const walk = (items: readonly Sized[], trail: readonly string[]) => {\n for (const item of items) {\n const path = [...trail, item.node.name]\n if (item.children) walk(item.children, path)\n else {\n rows.push([\n path.join(' › '),\n value(item.value),\n share.format(total > 0 ? item.value / total : 0),\n ])\n }\n }\n }\n walk(\n entries.map(({ entry }) => entry),\n [],\n )\n const table: DataTable = { columns: ['', 'Value', 'Share'], rows }\n if (rows.length > limit) {\n table.rows = rows.slice(0, limit)\n table.total = rows.length\n }\n return table\n}\n\n/** Nodes with text for names and finite values, at most `MAX_DEPTH` deep and `MAX_NODES` in all. */\nfunction cleanNodes(data: unknown, depth = 0, budget = { left: MAX_NODES }): TreemapNode[] {\n const nodes: TreemapNode[] = []\n for (const r of list(data)) {\n if (!isRecord(r) || budget.left <= 0) continue\n budget.left--\n const children =\n depth < MAX_DEPTH && Array.isArray(r.children)\n ? cleanNodes(r.children, depth + 1, budget)\n : undefined\n nodes.push({ ...named(r), value: finite(r.value) ?? 0, children } as unknown as TreemapNode)\n }\n return nodes\n}\n\n/**\n * Treemap: parts of a whole as tiles, each as large as its value, laid out\n * as close to squares as they go with the largest in the top left corner.\n * Entries with `children` are groups: their tiles stay together and share\n * the group's color.\n *\n * ```ts\n * new Chart('#el', {\n * type: treemap,\n * data: [\n * { name: 'Search', value: 42 },\n * { name: 'Social', children: [{ name: 'Video', value: 18 }, { name: 'Posts', value: 9 }] },\n * ],\n * })\n * ```\n */\nexport const treemap: ChartType<TreemapOptions> = {\n name: 'treemap',\n clean: cleanData((data) => cleanNodes(data)),\n render: renderTreemap,\n legend: (options) => legendItems(options.data),\n table: treemapTable,\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 { percentageBar } from './charts/percentage-bar.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'\nimport { treemap } from './charts/treemap.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 treemap,\n 'percentage-bar': percentageBar,\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 { PercentageBarOptions, PercentageBarSegment } from './charts/percentage-bar.ts'\nexport { percentageBar } from './charts/percentage-bar.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 { TreemapNode, TreemapOptions } from './charts/treemap.ts'\nexport { treemap } from './charts/treemap.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":"A,2FAoBA,SAAgByD,EAAOC,EAAgCC,EAAW,EAAW,CAE3E,IAAMC,EAAQC,GAA8B,CAC1C,IAAMC,EAAI,OAAOJ,GAAU,SAAWA,EAAQA,IAAQG,GACtD,OAAO,OAAO,SAASC,CAAC,EAAKA,EAAeH,CAC9C,EACA,MAAO,CAAE,IAAKC,EAAK,KAAK,EAAG,MAAOA,EAAK,OAAO,EAAG,OAAQA,EAAK,QAAQ,EAAG,KAAMA,EAAK,MAAM,CAAE,CAC9F,CAGA,IAAaG,GACXC,EACAC,IACOA,EAAM,CAAE,GAAGD,EAAO,KAAMA,EAAM,MAAO,MAAOA,EAAM,IAAK,EAAIA,EAGpE,SAAgBE,EAAUC,EAAeC,EAAgBC,EAAuB,CAC9E,MAAO,CACL,EAAGA,EAAQ,KACX,EAAGA,EAAQ,IACX,MAAO,KAAK,IAAI,EAAGF,EAAQE,EAAQ,KAAOA,EAAQ,KAAK,EACvD,OAAQ,KAAK,IAAI,EAAGD,EAASC,EAAQ,IAAMA,EAAQ,MAAM,CAC3D,CACF,CAIA,IASMC,EAAUC,GACdA,GAAQ,OACPA,GAAQ,MACNA,GAAQ,OAAUA,GAAQ,OAC1BA,GAAQ,OAAUA,GAAQ,OAC1BA,GAAQ,OAAUA,GAAQ,OAC1BA,GAAQ,OAAUA,GAAQ,OAC3BA,GAAQ,QAGZ,SAASC,EAAUC,EAAsB,CAO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AAO,aACxB,GAAM1sB,aAAgB,QACtB,CAAImrB,GAAO,IAAInrB,CAAI,GAAGsrB,GAAQtrB,CAAI,EAClC,IAAK,IAAM7M,KAAS6M,EAAK,iBAAiBgrB,EAAQ,EAAGM,GAAQn4B,CAAK,CADhC,CAGpC,IAAK,IAAM6M,KAAQ0sB,EAAO,WACpB1sB,aAAgB,SAAW,CAACA,EAAK,aACjCA,aAAgB,SAAcqsB,GAAKrsB,EAAMlW,CAAO,CAHtD,CAKF,CACF,CAAC,EAED,OADAgY,EAAS,QAAQwqB,EAAM,CAAE,UAAW,GAAM,QAAS,EAAK,CAAC,MAC5CxqB,EAAS,WAAW,CACnC,CCtLA,GAAI,OAAO,SAAa,IAAa,CACnC,IAAM8qB,EAAS,SAAS,cACxB,GAAI,CAACA,GAAQ,aAAa,gBAAgB,GAAK,CAAC,SAAS,eAAe,WAAW,EAAG,CACpF,IAAMjlC,EAAQ,SAAS,cAAc,OAAO,EAC5CA,EAAM,GAAK,YACXA,EAAM,YAAA;i2pBAENA,EAAM,MAASilC,GAAqC,OAAS,GAE7D,SAAS,KAAK,QAAQjlC,CAAK,CAC7B,CACA,IAAMklC,EAAYD,GAAQ,aAAa,cAAc,GAAK,GACpDp9B,MAAeq9B,EAAYJ,GAAQ,SAAS,IAAI,EAAI,KAAKJ,GAAK,QAAQ,EACxE,SAAS,aAAe,UAAW,SAAS,iBAAiB,mBAAoB78B,CAAK,EACrFA,EAAM,CACb,C"}
1
+ {"version":3,"file":"tabler-charts-bootstrap.min.js","names":["SVG_NS","SVG_NS","pending","cleanData","Chart","round","SVG_NS","TEXT","SHAPES","round","round","round","EDGE","toMs","HOVER_SLOP","SVG_NS","groups","rangeKey","rangeOf","SVG_NS","ZOOM_STEP","WHEEL_SPEED","WHEEL_SPEED_PINCH","SVG_NS","toMs","round","toMs","GAP","round","round","GAP","MIN_RADIUS","round","DAY","calendar","toMs","round","round","prepare","emit","round","pending","CoreChart","round","to2","round","DAY","rangeOf","round","ratioOf","round","INSET","round","HALF_PI","sweepArcs","FLOOR","EMPTY","round","round","FLOOR","circlePath","round","round","round","LABEL_GAP","HOVER_SLOP","truncate","round","HOVER_SLOP","toMs","layout","round","round","round","round","exports","features","register","added","swatchShape","config","steps","addPost","step","content","interaction","ctx","each","feature","name","found","hitKey","hit","toChartPoint","svg","clientX","clientY","width","height","rect","sx","sy","h","tag","props","children","attrs","key","value","cls","normalizeClass","style","normalizeStyle","out","flattenChildren","result","item","UNSAFE","prop","v","input","child","text","last","legendContent","items","hidden","shape","off","defaultHidden","NAME_RE","EVENT_RE","isValidTag","isValidAttr","SVG_NS$4","rendered","roots","render","container","vnode","replace","prev","canPatch","patchElement","namespaceFor","el","createElement","parent","childNamespace","createNode","ns","doc","setAttr","childNs","node","next","patchNode","patchAttrs","patchChildren","update","oldNodes","keyed","unkeyed","matched","used","cursor","i","candidate","anchor","HTML_ROOTS","VOID","renderToString","options","escapeText","renderNode","parentInSvg","inSvg","escapeAttr","childInSvg","TEXT_RE","ATTR_RE","TEXT_RE_G","ATTR_RE_G","ENTITIES","replaceEntity","char","listeners","seen","observer","getObserver","entries","target","contentRect","observeResize","listener","ro","queue","pending$2","requestFrame","callback","run","task","error","schedule","flush","flushHooks","cancel","count","ran","later","cursorValue","uid","nextId","resolveSize","measured","measuredWidth","ratio","chartModel","models","prepare","model","renderContent","renderContext","size","id","fontSize","rtl","cleanData$1","assertType","POSITIONS","resolveLegend","option","show","asked","chartLabel","names","shown","countNodes","n","c","isStatic","composeChart","still","underlay","overlay","extraAttrs","descId","patterns","fills","renderChart","base","buildChart","chartToString","chartEvents","ROOT","computed","mounted","Chart$1","#cfg","#onResize","followsHeight","changed","#measured","#font","#markResizing","#schedule","#handlers","#unobserve","#plugins","#destroyed","#current","#source","#hovered","#hit","#cache","#resizeTimer","#toggled","#adopt","#rtl","defaultPlugins","element","#measure","plugin","beside","legend","within","reserved","cfg","#measureFontSize","source","index","seriesIndex","#setHover","x","y","event","entry","#hiddenSet","data","stale","#content","#refreshHighlight","adopted","#compose","hiddenKey","cache","under","over","layer","extra","handler","set","force","rerender","px","insets","fallback","side","mirrorSides","sides","innerRect","margins","plotFrame","padding","pad","m","area","end","reverse","isWide","code","charWidth","estimateTextWidth","em","point","ASCII","_","round$1","LINE_HEIGHT","SVG_NS$2","SHAPE","TEXT$1","STOP","GROUP","SHAPES$1","rootOf","transformOf","ox","oy","inline","live","copy","declarations","transform","liveChildren","copies","twin","legendLayer","patterned","box","g","swatch","color","slot","fill","dot","label","exportSVG","animation","chartStyle","totalWidth","total","at","left","top","wrap","move","title","background","exportImage","type","scale","quality","markup","image","canvas","context","resolve","reject","blob","seriesRows","chart","series","s","hits","order","a","b","rows","date","tableRows","table","exportCSV","delimiter","cell","safe","row","downloadChart","format","link","numberCache","dateCache","cached","create","cacheKey","locale","getNumberFormat","getDateFormat","unsignedZero","formatNumber","compactSymbols","formatCompact","SYMBOLS","nf","symbols","notation","compactDisplay","own","digitsOf","small","large","exp","scaled","parts","digits","part","compactOf","o","formatDetail","stepPrecision","abs","hasPrecision","formatTicks","fmt","epsilon","formatDate","df","E10","E5","E2","tickSpec","start","stop","power","factor","i1","i2","inc","ticks","tickIncrement","tickStep","niceDomain","lo","hi","linearTicks","d0","d1","bandTicks","isHorizontal","position","thinTicks","gap","sizes","tick","fitsBetween","j","span","sum","first","fits","kept","tail","axisSize","tickSize","tickPadding","rotate","labels","max","axisTitleSize","axisTitle","reach","sign","axis","line","horizontal","offset","edge","tickLine","grid","direction","p","band","domain","range","paddingInner","paddingOuter","align","inner","r0","r1","bandwidth","pixel","raw","extent","values","min","linear","k","mid","clamp","rMin","rMax","dMin","dMax","finite","optional","isRecord","list","numbers","records","fix","named","r","cleanSeries","d","cleanData","cleanItems","keyOf","legendItems","groupAttrs","labelKey","windowed","seriesKey","hasY2","seriesAxes","second","y2","seriesScale","layout","seriesLegend","resolveLabels","plottable","isTimeAxis","l","toMs$1","labelFormatter","valueScale","valueTicks","markerShape","shapes","pointMark","cx","cy","tickCount","auto","valueDomain","zeroDefault","override","domainOf","nlo","nhi","notesFeature","valueAxis","which","of","finishLayout","overhang","plot","keys","time","xTicks","yTicks","y2Ticks","flip","xOptions","turned","opposite","notes","categories","seconds","titles","present","plotClip","able","cartesianLayout","yOptions","showY","showX","timed","probeY","y2Options","value2","showY2","countX","labelAt","xAxis","edgeLabels","allX","halfLine","edgeWidth","firstLabel","lastLabel","edgeX","valueWidth","value2Width","halfStep","overflow","both","clipId","bleed","seriesAttrs","dash","categoryInteraction","markAt","formatLabel","axisOf","axes","formats","yAxis","cursorText","cursorAt","py","hitAt","center","empty","mark","seriesTable","limit","all","categoryCount","viewRange","view","low","viewWindow","cut","from","TYPES","SVG_NS$1","plotTools","host","vertical","along","locate","inside","groups$1","configOf","isBrush","rangeKey$1","countOf","rangeOf$2","whole","aligners","flow","aligns","brush","natural","space","passed","rangeText","labelKeys","candle","setRange","was","wasEnd","mapRange","to","installBrush","onPlot","cartesian","on","least","group","joined","leave","join","pass","others","other","given","pending","drawn","mine","spaces","nodes","clearMark","drawMark","length","ends","press","pointer","dragged","indexAt","onPointerEnd","onPointerDown","mode","onPointerMove","now","moved","by","shift","onClickCapture","onDoubleClick","onKey","arrow","rest","BUTTONS","installZoom","zoom","fine","edges","zoomBy","active","panBy","reset","pointers","selection","controls","addedClass","clearSelection","drawSelection","previous","before","after","onWheel","sideways","delta","onControl","renderControls","button","icon","path","disabled","state","categorySpan","scales","f","pair","cleanAnnotations","isPair","annotationValues","annotations","annotationLayers","bands","lines","x0","x1","y0","y1","geometry","pointOf","isPoint","dots","placed","obstacles","apart","t","clearOfLabels","clear","spot","w","spots","a0","a1","near","far","dateLabels","utc","endLabelTexts","endLabelRoom","endLabelLayer","floor","ceiling","endLabels","texts","points","log","ln","logBase","untransform","t0","t1","decades","keep","logDomain","niced","logTicks","TILES","SLOTS","patternDefs","patternVars","vars","patternFills","SHAPES","markerPath","markerClip","SEPARATOR","textWidth","onRight","sliceLabels","right","room","above","radius","column","sin","cos","SECOND","MINUTE","HOUR","DAY$2","MONTH","YEAR","INTERVALS","calendar$1","get","unit","make","mo","mi","weekday","chooseInterval","years","toMs","FORMATS","cal","interval","primary","tz","main","upper","timePointScale","stamps","valid","positions","ms","down","timeAxis","probe","overlaps","contains","outer","wanted","valueLabels","spec","pie","stacked","isLabelled","marks","share","candidates","slim","sliceFits","depth","labelsStep","matches","hydrateElement","current","created","hydrate","running","tween","origin","duration","draw","begin","NUMBER","native","morph","lttbIndices","threshold","runs","sampleRun","budget","bucketSize","bucket","nextStart","nextEnd","avgX","avgY","rangeStart","rangeEnd","ax","ay","best","bestArea","lttb","precision","prepare$1","curve","dedupe","emit$1","xy","monotone","STEPS","xm","tangents","x2","h0","h1","s0","s1","endTangent","dx","isValid","linePath","areaPath","baseline","baseAt","bottom","back","NAMES","DEFAULT_FORMATS","download","toggle","menu","setOpen","open","onOutside","isOpen","onClick","onBlur","remove","seriesGroup","halo","hoverUnderlay","crosshair","hoverOverlay","hoverValue","hgt","listening","listenPointer","local","overControl","onLeave","onMove","highlight","tableContent","caption","corner","headers","head","cells","describeHit","enabled","keyboard","region","announce","go","handle","focused","isChart","onFocus","MIRROR","BESIDE","START","adopt","bound","place","put","marginTop","marginBottom","groups","indexes","passing","indexOf","sync","self","ref","idle","pending$1","drain","tasks","scheduleIdle","cancelIdle","dataTable","maxRows","visible","note","same","hitAnchor","tooltipContent","placeTooltip","bounds","fitsRight","fitsLeft","rawX","waiting","placeAll","measure","tooltip","tip","turns","turn","clip","Chart","fadeMask","stackSeries","percent","nullAsZero","up","lastUp","lastDown","segment","stackBounds","stacks","seriesPoints","connectNulls","renderLines","pointRadius","filled","decimate","fillStyle","scaleOf","baselineOf","stackOf","stack","gradient","fadeId","seg","pts","bottoms","areas","cuts","forward","round","rounded","barPath","sweep","rr","hbarPath","horizontalLayout","probeValues","showValues","showCategories","probeCategories","edgeLabel","bar","maxBarWidth","groupPadding","orientation","isLine","lineKeys","onY2","stackHidden","inStack","layoutOptions","slots","stackColumn","columns","barWidth","groupWidth","slotAt","barLeft","across","negative","away","paths","rectPath","DAY$1","DIVERGING","MAX_DAYS","stamp","dayOf","dateOf","day","seriesOf","cleanCalendar","rangeOf$1","weekStart","fromMs","weeks","monthStart","months","single","gridStart","renderCalendar","levels","dates","month","dayName","year","shortYear","totals","byDay","days","e","dataMin","dataMax","diverging","stops","level","shade","u","scaleText","high","rowLabels","multi","bandLabels","yearWidth","scaleHeight","bandY","cellX","weekdays","scaleY","lowWidth","highWidth","swatches","scaleWidth","scaleX","naturalSize","fixed","ratioOf$1","heightOf","calendarLegend","calendarTable","rowValues","sorted","calendar","autoRatio","bodyPath","asCartesian","pick","candlestick","maxCandleWidth","paint","candles","fit","chars","stagesOf","shadeOf","edgeY","stagePath","dy","tn","tf","renderFunnel","stages","short","header","columnX","stage","colorOf","hitFor","rate","dividers","inset","amount","funnelTable","funnel","EPSILON","PI","HALF_PI$1","TAU","DEG","asin","acos","intersect","x3","y3","x10","y10","x32","y32","cornerTangents","rc","cw","x01","y01","x11","y11","x00","y00","d2","D","cx0","cy0","cx1","cy1","dx0","dy0","dx1","dy1","sector","da","a01","a11","a00","a10","da0","da1","ap","rp","rc0","rc1","p0","p1","oc","bx","kc","lc","arcCentroid","padAngleForGap","innerRadius","outerRadius","angleOf","arcPathStable","arc","ring","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","centerValue","gaugeTable","gauge","EMPTY$1","rangeKey","rangeOf","ranges","slotColor","renderHeatmap","bySeries","pct","rowTicks","halfColumn","cellW","cellH","cellY","valueAt","painted","heatmapLegend","heatmap","fitView","SVG_NS","ICONS","mapInteraction","win","isMap","zoomOn","onMap","frame","setView","toChart","toMapPoint","animateTo","eased","animate","select","selected","zoomIn","zoomOut","EMPTY","heatScale","selectedOf","LINE_CURVE","RADIANS","maps","addMap","parsePath","command","args","relative","parsed","shapesOf","map","largest","xi","yi","xj","yj","circlePath$1","renderMap","valued","tx","ty","clipped","projection","project","lng","lat","markers","marker","firstMarker","mx","my","regions","raised","chosen","byName","barX","selectable","mapTable","ratioOf","cleanMap","MAX_SEATS","partiesOf","party","seatCounts","parties","taken","distribute","counts","layoutSeats","closed","radiiOf","pitchOf","capacity","pitch","seats","spacing","angle","seat","renderParliament","seatsOf","vacant","circle","parliamentTable","parliament","groupSlices","maxSlices","slice","groupLegend","slices","withSlices","slicesLegend","segmentsOf","segments","renderPercentageBar","boxes","boxWidth","percentageBarTable","percentageBar","layoutSlices","renderPie","defaults","labelled","strokeGap","pieTable","pieType","donut","truncate$1","word","fitRadius","angles","blockHeight","renderRadar","formatValue","labelWidth","wrapped","polygon","radiusOf","spokeLabels","radar","DAY","bars","nth","valueFormat","annotationsOf","rangeAxis","renderRangeBar","showRows","nearest","distance","rangeBarTable","rangeBar","truncate","graph","justify","declared","isHidden","legendKey","links","ia","ib","layout$1","nodeWidth","nodePadding","widest","match","cap","byColumn","col","showValue","linkEnds","linkPath","cubic","inLink","renderSankey","nodeMark","linkMark","linkItem","hitNode","linkIndex","flows","hitLink","sankeyLegend","sankeyTable","sankey","circlePath","sizeOf","xText","renderScatter","maxSize","bubble","countY","usable","xDomain","yDomain","ticksOf","probeX","half","halfBand","pointIndex","fx","fy","fs","sz","bestDistance","dotsPath","scatterTable","withSize","withLabel","take","scatter","renderSparkline","variant","tristate","zero","xAt","labelOf","yOf","dotAt","extremes","sparkline","sized","stopsOf","byValue","walk","squarify","t2","worst","tw","th","trail","renderTreemap","tiles","tile","treemapTable","cleanNodes","treemap","types","SELECTOR","RESERVED","TEXT","charts","getChart","dispose","parseValue","parseJson","what","optionsOf","json","inlineData","attr","emit","detail","setup","known","existing","src","response","init","root","elements","made","observe","record","owner","script","observing"],"sources":["../../core/src/features.ts","../../core/src/interaction.ts","../../core/src/vnode.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/layout.ts","../../core/src/export-chart.ts","../../core/src/export.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/view.ts","../../core/src/plugins/plot.ts","../../core/src/plugins/brush.ts","../../core/src/plugins/zoom.ts","../../core/src/zoom.ts","../../core/src/charts/annotations.ts","../../core/src/charts/dates.ts","../../core/src/charts/end-labels.ts","../../core/src/scales/log.ts","../../core/src/charts/log-axis.ts","../../core/src/charts/patterns.ts","../../core/src/charts/point-shapes.ts","../../core/src/charts/slice-labels.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/shapes/rect.ts","../../core/src/charts/calendar.ts","../../core/src/charts/candlestick.ts","../../core/src/charts/fit.ts","../../core/src/charts/funnel.ts","../../core/src/shapes/arc.ts","../../core/src/render/sweep.ts","../../core/src/charts/gauge.ts","../../core/src/charts/heatmap.ts","../../core/src/charts/map-view.ts","../../core/src/plugins/map.ts","../../core/src/charts/heat.ts","../../core/src/charts/map.ts","../../core/src/charts/parliament.ts","../../core/src/charts/others.ts","../../core/src/charts/percentage-bar.ts","../../core/src/charts/pie.ts","../../core/src/charts/radar.ts","../../core/src/charts/range-bar.ts","../../core/src/charts/sankey.ts","../../core/src/shapes/circle.ts","../../core/src/charts/scatter.ts","../../core/src/charts/sparkline.ts","../../core/src/charts/treemap.ts","../../core/src/chart-types.ts","../../core/package.json","../../core/src/core.ts","../../core/src/index.ts","../src/index.ts","../src/cdn.ts"],"sourcesContent":["import type { ChartConfig, RenderContext } from './chart.ts'\nimport type { annotationLayers, annotationValues } from './charts/annotations.ts'\nimport type { dateLabels } from './charts/dates.ts'\nimport type { endLabels } from './charts/end-labels.ts'\nimport type { logDomain, logTicks } from './charts/log-axis.ts'\nimport type { patternFills } from './charts/patterns.ts'\nimport type { markerClip, markerPath } from './charts/point-shapes.ts'\nimport type { sliceLabels } from './charts/slice-labels.ts'\nimport type { timeAxis } from './charts/time-axis.ts'\nimport type { viewWindow } from './charts/view.ts'\nimport type { downloadChart } from './export-chart.ts'\nimport type { Interaction } from './interaction.ts'\nimport type { ChartPlugin } from './plugin.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`, `/end-labels`, `/slice-labels`, `/zoom`) 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 (installed by a chart whose type has `sweep`). */\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 /** Names and last values at the end of lines, behind `endLabels`. */\n 'end-labels'?: typeof endLabels\n /** Names beside the slices of a pie, behind its `labels`. */\n 'slice-labels'?: typeof sliceLabels\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 /** The same shapes for legend and tooltip swatches, as CSS shapes. */\n swatch?: typeof markerClip\n /**\n * Behind `view` and `zoom` in cartesian charts: the window of categories a\n * chart type draws, and what the `zoom()` plugin installs on a chart.\n */\n zoom?: { window: typeof viewWindow; install: ChartPlugin['install'] }\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/**\n * Inline style that gives the swatch of a legend or tooltip entry the point\n * shape of its color slot (the stylesheet applies it when points are drawn).\n */\nexport type SwatchShape = (slot: number) => Record<string, string | number> | undefined\n\n/** The swatch shapes of a chart, if it has point shapes (`shapes`, or `patterns: true`). */\nexport const swatchShape = (config: ChartConfig<object>): SwatchShape | undefined =>\n (config.shapes ?? config.patterns === true) ? features.swatch : undefined\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","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 /** 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 /** The shape that marks the hit; a crosshair when left out. */\n highlight?: Highlight\n /**\n * The value under the pointer on the value axis (cartesian charts, for a\n * hit from the pointer): what `crosshair: { value: true }` shows.\n */\n cursor?: HitCursor\n}\n\n/** The value under the pointer, read off the value axis. */\nexport interface HitCursor {\n value: number\n /** The value formatted like the axis, with the precision of a pixel. */\n text: string\n /** Where the pointer is along the value axis, in chart pixels. */\n position: number\n /** The side of the plot the value axis is on. */\n side: 'left' | 'right' | 'bottom'\n /** The axis is hidden (`y.show: false`): the value is written inside the plot. */\n inside?: boolean\n}\n\n/**\n * The one shape drawn to mark a hit, in chart pixels:\n *\n * - `crosshair`: a vertical line through the category across the plot, and\n * a dot on every value (point charts);\n * - `band`: the category's band behind the series (bars);\n * - `spoke`: a line from `x1, y1` to `x2, y2` (a radar spoke), and a dot on\n * every value; keyboard tooltips anchor on the value itself;\n * - `halo`: path data `d` drawn translated by `x` / `y` in the color of the\n * hit's series (a ring around a pie slice); `under` draws it below the\n * chart instead of above, so it never covers the labels.\n */\nexport type Highlight =\n | { kind: 'crosshair' }\n | { kind: 'band'; x: number; y: number; width: number; height: number }\n | { kind: 'spoke'; x1: number; y1: number; x2: number; y2: number }\n | { kind: 'halo'; d: string; x?: number; y?: number; under?: boolean }\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 * Categories fill a grid column by column, this many to a column (the days\n * of a calendar in weeks): left and right move by a column, up and down by one.\n */\n rows?: number\n /** Categories run from the right: the left arrow key goes to the next one. */\n reversed?: boolean\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","/**\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","import type { SwatchShape } from './features.ts'\nimport { 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 /**\n * Where the legend goes: above or below the chart, or beside it (`'left'`,\n * `'right'`, mirrored in a right-to-left chart) with its entries stacked\n * and the chart in the remaining width. `'auto'` puts it on the right when\n * the chart keeps two thirds of the container that way, and below\n * otherwise. Defaults to `'top'`.\n */\n position?: 'top' | 'bottom' | 'left' | 'right' | 'auto'\n /**\n * Keep the legend inside the chart's `height`: a legend above or below the\n * chart takes its height from the plot, so a chart with `height: 240` is\n * 240 pixels tall with its legend (cards in a row stay the same size).\n * Only with a `height` in pixels. Defaults to `false`: the legend adds to it.\n */\n withinHeight?: boolean\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 * `shape` gives the swatches the point shapes of their slots.\n */\nexport function legendContent(\n items: readonly LegendItem[],\n hidden: ReadonlySet<string>,\n shape?: SwatchShape,\n): 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 // A map, so values from data cannot inject CSS (see normalizeStyle).\n style: { '--tc-series-color': item.color, ...shape?.(item.index) },\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\nconst namespaceFor = (parent: Element, tag: string): string =>\n tag === 'svg' ? SVG_NS : childNamespace(parent)\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> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' }\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 { type Features, 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 /** Keys of legend entries (series) currently hidden. */\n hidden: ReadonlySet<string>\n /** Lay the chart out right to left (the `rtl` option, resolved). */\n rtl?: boolean\n}\n\n/** What a chart type's `table()` sees: no size, since a table has none. */\nexport type TableContext = Pick<RenderContext, 'locale' | 'hidden' | 'rtl'>\n\n/**\n * What a chart type renders for one size: the content of the root `<svg>`,\n * and how pointer and keyboard map to its data (none, when left out).\n */\nexport interface RenderResult {\n content: ChildInput\n interaction?: Interaction\n}\n\n/**\n * A chart type plugin (`line`, `bar`, …). Works out its model from the chart\n * options and renders it into the content of the root `<svg>`.\n *\n * `M` is the chart model, what `prepare()` works out from the options alone\n * (the options themselves for a type without `prepare()`): `render()`,\n * `legend()`, `table()` and `height()` all read it, so a type groups or sorts\n * its data once per config, not once for each of them. `ChartType<never>`\n * stands for any chart type.\n */\nexport interface ChartType<\n O extends object = object,\n M extends object = [O] extends [never] ? object : O,\n> {\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 /**\n * The chart model of the (cleaned) options: whatever the legend, the table\n * and every render share. It knows neither the size nor the hidden series\n * (the legend that hides them reads it). Called once per config.\n */\n prepare?(options: O): M\n /** The chart content for a size: bare content, or with its interaction. */\n render(model: M, context: RenderContext): ChildInput | RenderResult\n /**\n * Height in pixels at a width, for a type whose proportions are not one\n * ratio (parts of it keep their size as it narrows). Asked when `height`\n * is not set; `undefined` leaves it to `aspectRatio`.\n */\n height?(model: M, width: number): number | undefined\n /** Entries for the legend (series, slices); charts without it get no legend. */\n legend?(model: M): 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?(model: M, context: TableContext, 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 /**\n * How the chart's marks turn to new data in the DOM, where CSS cannot\n * animate them (arcs sweeping to their new angles). A chart in the page\n * installs it; it is part of the type, not of a module that loads, so it\n * ships only with the types that use it.\n */\n readonly sweep?: Features['sweep']\n readonly valueLabels?: {\n marks?: 'slice' | 'cell'\n format?(model: M): NumberFormat | undefined\n }\n /**\n * Plugins the chart type brings along (the zoom of a map), installed after\n * the default ones when a chart is created with this type.\n */\n readonly plugins?: readonly ChartPlugin[]\n}\n\nexport type { DataTable, LegendItem }\n\nexport interface CrosshairOptions {\n /** A line through the pointer, and the value under it on the value axis. Defaults to `false`. */\n value?: boolean\n}\n\n/** Whether the chart shows the value under the pointer on its value axis. */\nexport const cursorValue = (config: BaseOptions): boolean =>\n typeof config.crosshair === 'object' && config.crosshair?.value === true\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 * Mirror the layout for right-to-left pages: the value axis on the right\n * and categories running from the right (`x.reverse` overrides the latter).\n * `'auto'` follows the `direction` of the container (left to right in SSR).\n * The legend, the tooltip and the download menu read right to left with it.\n * Cartesian charts, heatmaps, sparklines, sankey diagrams and percentage\n * bars. Defaults to `false`.\n */\n rtl?: boolean | 'auto'\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 /**\n * Show a vertical crosshair on hover (point charts). `{ value: true }` also\n * draws a line through the pointer across the plot, with the value there\n * written on the value axis (line, area, bar and candlestick charts; on the\n * first axis of a chart with two). Defaults to `true`.\n */\n crosshair?: boolean | CrosshairOptions\n /**\n * Draw a dot on every value of the hovered category (point charts).\n * `false` leaves the crosshair and the tooltip. Defaults to `true`.\n */\n activePoints?: 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 (`overMarks: true` keeps the labels of a line\n * where it crosses the bars). A series' own `valueLabels` overrides this for\n * that series, and each label carries its series classes\n * (`tc-series tc-series-{n}`). Needs `@tabler/charts/value-labels` on the\n * core (`@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', 'csv']`), 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 &\n O & { type: ChartType<O, object> }\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 : ((options as Partial<ChartConfig>).type?.height?.(\n chartModel(options as ChartConfig),\n width,\n ) ?? width / ratio)\n return { width, height: Math.max(0, Math.round(height)) }\n}\n\n/** Chart models by the config they were worked out from. */\nconst models = /* @__PURE__ */ new WeakMap<object, object>()\n\n/**\n * The chart model of a config: what its type's `prepare()` works out from\n * it, once per config object, or the config itself for a type without one.\n */\nexport function chartModel(config: ChartConfig<object>): object {\n const { prepare } = config.type\n if (!prepare) return config\n const model = models.get(config) ?? prepare(config)\n models.set(config, model)\n return model\n}\n\n/** Run the chart type's `render()` for a config and context, and the optional steps after it. */\nfunction renderContent(config: ChartConfig<object>, ctx: RenderContext): RenderResult {\n const out = config.type.render(chartModel(config), ctx)\n // Bare content has no `content` of its own (nodes, lists and text do not).\n const result =\n (out as RenderResult | null)?.content !== undefined\n ? (out as RenderResult)\n : { content: out as ChildInput }\n // Optional features finish the content (point shapes, value labels).\n if (features.post) result.content = features.post(config, result.content, result.interaction, ctx)\n return result\n}\n\n/** What a render context is made for, besides the config. */\nexport interface ContextOptions {\n size: Size\n /** Id prefix of the chart. */\n id: string\n hidden: ReadonlySet<string>\n /** Measured font size, used when the config sets none. */\n fontSize?: number\n /** The resolved `rtl` option; by default `rtl: true` in the config. */\n rtl?: boolean\n}\n\n/** Render context for a config and size. */\nexport function renderContext<O extends object>(\n config: ChartConfig<O>,\n { size, id, hidden, fontSize, rtl = config.rtl === true }: ContextOptions,\n): RenderContext {\n return {\n rtl,\n width: size.width,\n height: size.height,\n fontSize: config.fontSize ?? fontSize ?? DEFAULT_FONT_SIZE,\n locale: config.locale,\n id,\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\nconst POSITIONS: readonly unknown[] = ['top', 'bottom', 'left', 'right', 'auto']\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: NonNullable<LegendOptions['position']>\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?.(chartModel(config)) ?? []\n const option = config.legend\n const show = option === undefined ? items.length >= 2 : option !== false && items.length > 0\n const asked = typeof option === 'object' ? option.position : undefined\n const position = asked && POSITIONS.includes(asked) ? asked : '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 = resolveLegend(config)\n .items.map((item) => item.name)\n .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 rtl: boolean = config.rtl === true,\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 rtl && 'tc-rtl',\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/** A chart built without the DOM: its root `<svg>`, and how it answers interaction. */\nexport interface BuiltChart {\n svg: VNode\n interaction?: Interaction\n}\n\n/**\n * Build a chart for a size: a pure function of the config and size, shared\n * by the DOM chart and server-side rendering. `buildChart()` keeps the svg.\n */\nexport function renderChart<O extends object>(\n config: ChartConfig<O>,\n size: Size,\n id: string = config.id ?? 'tc',\n): BuiltChart {\n assertType(config)\n const base: ChartConfig<object> = cleanData(config)\n const hidden = defaultHidden(resolveLegend(base).items)\n const { content, interaction } = renderContent(base, renderContext(base, { size, id, hidden }))\n return { svg: composeChart(base, size, id, isStatic(base, content), content), interaction }\n}\n\n/** Build the VNode tree of a chart for a size (see `renderChart()`). */\nexport function buildChart<O extends object>(\n config: ChartConfig<O>,\n size: Size,\n id?: string,\n): VNode {\n return renderChart(config, size, id).svg\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(renderChart(config, size).svg)\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/** The handlers of each event: a `Map` that knows which event its key names. */\ninterface Handlers extends Map<keyof ChartEvents, Set<Handler<never>>> {\n get<K extends keyof ChartEvents>(name: K): Set<Handler<ChartEvents[K]>> | undefined\n set<K extends keyof ChartEvents>(name: K, handlers: Set<Handler<ChartEvents[K]>>): this\n}\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 rtl: boolean\n content: ChildInput\n /** Whether the content renders without transitions. */\n still: boolean\n}\n\n/** The chart's own svg in its container. */\nconst ROOT = ':scope > svg.tc-chart'\n\n/** The computed style of an element, where there is one (not on the server). */\nconst computed = (el: Element): CSSStyleDeclaration | undefined =>\n typeof getComputedStyle === 'function' ? getComputedStyle(el) : undefined\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: HTMLElement\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() as Handlers\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 /** The resolved `rtl` option, read with the font size (`'auto'` asks the container). */\n #rtl = false\n\n constructor(\n target: HTMLElement | string,\n config: ChartConfig<O>,\n defaultPlugins: readonly ChartPlugin[] = [],\n ) {\n const element =\n typeof target === 'string' ? document.querySelector<HTMLElement>(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)\n this.element = element\n this.#cfg = cleanData(config)\n this.id = config.id ?? nextId()\n this.#adopt = element.querySelector(ROOT)\n this.#measure()\n this.#unobserve = observeResize(element, this.#onResize)\n try {\n for (const plugin of [\n ...defaultPlugins,\n ...(config.type.plugins ?? []),\n ...(config.plugins ?? []),\n ]) {\n this.#plugins.push(plugin.install(this))\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 // A legend beside the chart takes its width (it reads its own layout only then).\n let beside = 0\n for (const plugin of this.#plugins) beside += plugin.reservedWidth?.() ?? 0\n if (beside && measured.width) measured = { ...measured, width: measured.width - beside }\n const { height, legend } = this.#cfg\n // A height in pixels covers the legend when asked to (`legend.withinHeight`).\n const within =\n Number.isFinite(height) && typeof legend === 'object' && legend?.withinHeight === true\n let reserved = 0\n if (within || (height === 'container' && measured.height)) {\n for (const plugin of this.#plugins) reserved += plugin.reservedHeight?.() ?? 0\n }\n if (reserved && !within) {\n measured = { ...measured, height: (measured.height as number) - reserved }\n }\n const size = resolveSize(this.#cfg, measured)\n if (within) size.height = Math.max(0, size.height - Math.round(reserved))\n return size\n }\n\n /**\n * Whether the chart is laid out right to left: the `rtl` option, with\n * `'auto'` read from the container (together with the font size).\n */\n get rtl(): boolean {\n const cfg = this.#cfg\n if (this.#font === undefined) {\n this.#rtl =\n cfg.rtl === 'auto' ? computed(this.element)?.direction === 'rtl' : cfg.rtl === true\n this.#font = cfg.fontSize ?? this.#measureFontSize()\n }\n return this.#rtl\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: ChartConfig<object> = cfg\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 const rtl = this.rtl\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 cache.rtl !== rtl\n if (!cache || stale) {\n if (cfg.type.sweep) features.sweep = cfg.type.sweep\n const { content, interaction } = renderContent(\n cfg,\n renderContext(cfg, { size, id: this.id, hidden, fontSize, rtl }),\n )\n this.#current = interaction\n cache = {\n cfg,\n width: size.width,\n height: size.height,\n hidden: hiddenKey,\n fontSize,\n rtl,\n content,\n still: isStatic(cfg, 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: ChartConfig<object> = this.#cfg\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 content.rtl,\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)\n return () => {\n set.delete(handler)\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) 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) {\n // The same category, elsewhere along the values: only the value under the pointer moved.\n if (\n hit?.cursor &&\n cursorValue(this.#cfg) &&\n hit.cursor.position !== this.#hit?.cursor?.position\n ) {\n this.#hit = hit\n if (rerender) this.#schedule()\n }\n return\n }\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(ROOT)\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 const value = Number.parseFloat(\n computed(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\n const style = computed(el)\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(event)\n }\n}\n","/** 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/** Swap the left and right of `sides` in a right-to-left chart. */\nexport const mirrorSides = <T extends { left: number; right: number }>(\n sides: T,\n rtl: boolean | undefined,\n): T => (rtl ? { ...sides, left: sides.right, right: sides.left } : sides)\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/**\n * Space around a box by reading direction: `start` is the side the chart is\n * read from (the left, or the right in a right-to-left chart), `end` the other.\n */\nexport interface FrameInsets {\n top: number\n bottom: number\n start: number\n end: number\n}\n\n/** A plot area placed for the chart's reading direction. */\nexport interface PlotFrame {\n /** Where the data is drawn. */\n area: Rect\n /** The start side, where the axis beside the plot sits. */\n side: 'left' | 'right'\n /** The plot's horizontal range, from the end side when `reverse` (by default in a right-to-left chart). */\n range(reverse?: boolean): [number, number]\n}\n\n/**\n * Place the plot area of a chart with axes. `margins` gets the padding by\n * reading direction and returns the space each side needs, so a chart type\n * works its margins out once, whichever way the chart is read.\n */\nexport function plotFrame(\n size: { width: number; height: number; rtl?: boolean },\n padding: InsetsInput | undefined,\n margins: (padding: FrameInsets) => FrameInsets,\n): PlotFrame {\n const { width, height, rtl } = size\n const pad = insets(padding)\n const m = margins({\n ...pad,\n start: rtl ? pad.right : pad.left,\n end: rtl ? pad.left : pad.right,\n })\n const area = innerRect(width, height, {\n ...m,\n left: rtl ? m.end : m.start,\n right: rtl ? m.start : m.end,\n })\n const end = area.x + area.width\n return {\n area,\n side: rtl ? 'right' : 'left',\n range: (reverse = rtl) => (reverse ? [end, area.x] : [area.x, end]),\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, or its data as CSV\n * (`exportSVG()`, `exportImage()`, `exportCSV()`, `downloadChart()` of\n * `@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, chartModel } 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 CSVOptions {\n /** Separator of the values. Defaults to `','`. */\n delimiter?: string\n}\n\nexport interface DownloadOptions extends ImageOptions, CSVOptions {\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' | 'csv'\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(container: Element): { svg: Element; box: DOMRect } | 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 return { svg: g, box }\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 totalWidth = width\n let total = height\n if (legend) {\n // Chart and legend where the page shows them (above, below or beside),\n // with the gap between them, in one image as large as both.\n const { box } = legend\n const at = svg.getBoundingClientRect()\n const left = Math.min(at.left, box.left)\n const top = Math.min(at.top, box.top)\n const wrap = doc.createElementNS(SVG_NS, 'g')\n wrap.append(...Array.from(copy.childNodes))\n const move = (el: Element, x: number, y: number) => {\n if (x || y) el.setAttribute('transform', `translate(${round(x)} ${round(y)})`)\n }\n move(wrap, at.left - left, at.top - top)\n move(legend.svg, box.left - left, box.top - top)\n copy.append(wrap, legend.svg)\n totalWidth = round(Math.max(at.left + width, box.right) - left)\n total = round(Math.max(at.top + height, box.bottom) - top)\n }\n copy.setAttribute('width', String(totalWidth))\n copy.setAttribute('height', String(total))\n copy.setAttribute('viewBox', `0 0 ${totalWidth} ${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/** The rows of a chart with `{ labels, series }` data, values as they are. */\nfunction seriesRows(chart: Chart<object>): string[][] | undefined {\n const { config, interaction } = chart\n const { data, x } = config as {\n data?: { labels?: readonly unknown[]; series?: unknown }\n x?: { type?: string }\n }\n const series = data?.series\n if (!interaction || !Array.isArray(series) || !series.every((s) => Array.isArray(s?.values))) {\n return undefined\n }\n // From the hits, as the tooltip has them: the hidden series are left out.\n const hits = Array.from({ length: interaction.count }, (_, i) => interaction.hitIndex(i))\n const names = new Map<number, string>()\n for (const hit of hits)\n for (const item of hit?.items ?? []) names.set(item.seriesIndex, item.name)\n const order = [...names.keys()].sort((a, b) => a - b)\n const rows = [['', ...order.map((index) => names.get(index) as string)]]\n for (const hit of hits) {\n if (!hit) continue\n const label = data?.labels?.[hit.index]\n const date =\n label instanceof Date\n ? label\n : x?.type === 'time' && typeof hit.label === 'number' && new Date(hit.label)\n rows.push([\n date && Number.isFinite(date.getTime()) ? date.toISOString() : String(hit.label),\n ...order.map((index) => {\n const value = hit.items.find((item) => item.seriesIndex === index)?.value\n return value == null ? '' : String(value)\n }),\n ])\n }\n return rows\n}\n\n/** The rows of any other chart: the text of its data table, every row of it. */\nfunction tableRows(chart: Chart<object>): string[][] {\n const { config } = chart\n const model = chartModel(config)\n const hidden = new Set(\n (config.type.legend?.(model) ?? [])\n .map((item) => item.key)\n .filter((key) => chart.isHidden(key)),\n )\n const table = config.type.table?.(\n model,\n { locale: config.locale, hidden, rtl: chart.rtl },\n Number.POSITIVE_INFINITY,\n )\n if (!table) throw new Error('@tabler/charts: this chart type has no data for a CSV.')\n return [table.columns, ...table.rows]\n}\n\n/**\n * The chart's data as CSV (RFC 4180): one row per category with a column per\n * visible series, as in the chart's data table but with every row. Line,\n * area, bar, heatmap and radar charts give plain values (numbers without\n * their format, dates in ISO 8601, gaps empty); the other types give the\n * text of their table. Text that a spreadsheet would run as a formula (`=`,\n * `+`, `-` or `@` first) is prefixed with `'`. Takes the rendered chart\n * itself, not its element.\n *\n * ```ts\n * const csv = exportCSV(chart)\n * ```\n */\nexport function exportCSV(chart: Chart<object>, options: CSVOptions = {}): string {\n if (!chart?.config?.type) {\n throw new Error('@tabler/charts: exportCSV() takes the chart, not its element.')\n }\n const delimiter = options.delimiter ?? ','\n const cell = (text: string): string => {\n // No formulas from the data: only numbers may start with a sign.\n const safe = /^[=+\\-@\\t\\r]/.test(text) && !Number.isFinite(Number(text)) ? `'${text}` : text\n return safe.includes(delimiter) || /[\"\\r\\n]/.test(safe) ? `\"${safe.replace(/\"/g, '\"\"')}\"` : safe\n }\n return (seriesRows(chart) ?? tableRows(chart))\n .map((row) => row.map(cell).join(delimiter))\n .join('\\r\\n')\n}\n\n/**\n * Save the chart as a file: PNG by default, SVG, JPEG or WebP, or its data\n * as CSV (which needs the chart itself, not its element).\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 === 'csv'\n ? // With a byte order mark, so spreadsheets read it as UTF-8.\n new Blob([`${exportCSV(target as Chart<object>, options)}`], {\n type: 'text/csv;charset=utf-8',\n })\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","/**\n * Standalone entry: `import { exportSVG, exportImage, downloadChart } from '@tabler/charts/export'`\n * saves a rendered chart as a standalone SVG or an image, and `exportCSV`\n * gives its data as CSV. 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, exportCSV, 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 CSVOptions,\n DownloadOptions,\n ExportOptions,\n ExportTarget,\n ImageOptions,\n} from './export-chart.ts'\nexport { downloadChart, exportCSV, exportImage, exportSVG }\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 /** Turn the labels of an axis below the plot 90°, reading bottom to top. */\n rotate?: 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; rotate?: boolean } = {},\n): number {\n const { tickSize = 0, tickPadding = 8, rotate } = options\n if (ticks.length === 0) return 0\n // Beside the plot (and turned below it), labels are as wide as their text: a little slack\n // covers fonts wider than the estimate, so they do not touch the chart's edge.\n const labels =\n isHorizontal(position) && !rotate\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/** Space between the tick labels and the axis title. */\nconst TITLE_GAP = 6\n\n/** Pixels an axis title adds to the axis (for margins): none without a title. */\nexport const axisTitleSize = (title: string | undefined, fontSize: number): number =>\n title ? Math.ceil(fontSize * LINE_HEIGHT) + TITLE_GAP : 0\n\n/**\n * Render the title of an axis as `<text class=\"tc-axis-title tc-axis-title-{position}\">`,\n * past the labels of `ticks` and centered on the plot: along the axis at the\n * bottom, turned 90° beside the plot to read away from it (bottom to top on\n * the left, top to bottom on the right).\n */\nexport function axisTitle(\n position: 'right' | 'bottom' | 'left',\n ticks: readonly Tick[],\n area: Rect,\n title: string,\n fontSize: number,\n rotate?: boolean,\n): VNode {\n const reach = axisSize(position, ticks, fontSize, { rotate }) + TITLE_GAP\n const sign = position === 'left' ? -1 : 1\n const side = reach + (fontSize * LINE_HEIGHT) / 2\n return h(\n 'text',\n {\n key: `axis-title-${position}`,\n class: `tc-axis-title tc-axis-title-${position}`,\n transform:\n position === 'bottom'\n ? `translate(${round(area.x + area.width / 2)},${round(area.y + area.height + reach)})`\n : `translate(${round(position === 'left' ? area.x - side : area.x + area.width + side)},${round(area.y + area.height / 2)}) rotate(${sign * 90})`,\n dy: position === 'bottom' ? '0.71em' : '0.32em',\n 'text-anchor': 'middle',\n 'aria-hidden': 'true',\n },\n title,\n )\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, rotate } = 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 = rotate\n ? { transform: 'rotate(-90)', x: -offset, dy: '0.32em', 'text-anchor': 'end' }\n : 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, TableContext } from '../chart.ts'\nimport {\n axis,\n axisSize,\n axisTitle,\n axisTitleSize,\n bandTicks,\n linearTicks,\n type Tick,\n thinTicks,\n} from '../components/axis.ts'\nimport { grid } from '../components/grid.ts'\nimport { type Features, feature, features } from '../features.ts'\nimport { formatDetail, formatTicks, type NumberFormat } from '../format.ts'\nimport type { Hit, HitCursor, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n LINE_HEIGHT,\n type PlotFrame,\n plotFrame,\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'\nimport type { Zoomable } from './view.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 /**\n * Dash the line only from this label on (a forecast, provisional figures):\n * it stays solid up to the label and takes `dash` (`'5 4'` when left out)\n * after it. Line and area charts.\n */\n dashFrom?: Label\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 /**\n * Value axis of the series: `'y2'` draws it against the second axis\n * (options in `y2`), on the right of the plot (on the left in a\n * right-to-left chart), and leaves it out of stacks. Line, area and\n * vertical bar charts. Defaults to `'y'`.\n */\n axis?: 'y' | 'y2'\n /** Extra classes on the series group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n /**\n * Write values on this series' marks, whatever the chart's `valueLabels`\n * says: `true` labels it even when the chart option is off, `false` leaves\n * it out. Needs `@tabler/charts/value-labels` on the core.\n */\n valueLabels?: 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 /**\n * Title of the axis (e.g. a unit), beside its labels: turned 90° on the\n * left of the plot, or on the right in a right-to-left chart.\n */\n title?: string\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 /** Title of the axis, below its labels. */\n title?: string\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 * Turn the labels 90°, reading bottom to top, so that many or long\n * categories all keep their label. Categories along the bottom only: not\n * on a time axis, nor in horizontal bars.\n */\n rotate?: boolean\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 /** Run the categories from the right. Defaults to the chart's `rtl`. */\n reverse?: boolean\n}\n\nexport interface CartesianOptions extends Zoomable {\n data: CartesianData\n y?: ValueAxisOptions\n /**\n * The second value axis, for series with `axis: 'y2'` (it is drawn only\n * when a series uses it). Its labels and title stand on the other side of\n * the plot; the grid lines follow `y`.\n */\n y2?: 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 /** Default for `y2.zero`. Defaults to `zero`. */\n zero2?: 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 /** Scale of the second value axis, when a series uses it. */\n y2?: LinearScale\n /** Whether categories run along y. */\n horizontal: boolean\n xTicks: Tick[]\n yTicks: Tick[]\n /** Ticks of the second value axis (with `y2`). */\n y2Ticks?: 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\n/**\n * The options a chart type draws: the ones given, or only the categories of\n * their `view` (`prepare()` of the chart types that can be zoomed).\n */\nexport const windowed = <O extends Zoomable>(options: O): O =>\n options.view || options.zoom ? feature('zoom').window(options) : options\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/**\n * Whether the chart draws a second value axis: a series asks for it with\n * `axis: 'y2'`, and the values run along y (not in horizontal bars).\n */\nexport const hasY2 = (options: CartesianOptions): boolean =>\n (options as { orientation?: unknown }).orientation !== 'horizontal' &&\n options.data.series.some((s) => s.axis === 'y2')\n\n/**\n * The value axis a series is read on: a function giving each series'\n * axis options, and whether it is the second one.\n */\nexport function seriesAxes(\n options: CartesianOptions,\n): (series: Series | undefined) => { second: boolean; axis: ValueAxisOptions } {\n const second = hasY2(options)\n const y = { second: false, axis: options.y ?? {} }\n const y2 = { second: true, axis: options.y2 ?? {} }\n return (series) => (second && series?.axis === 'y2' ? y2 : y)\n}\n\n/** The scale of a series: the second one for series on `y2`. */\nexport const seriesScale = (\n layout: Pick<CartesianLayout, 'y' | 'y2'>,\n series: Series | undefined,\n): LinearScale => (layout.y2 && series?.axis === 'y2' ? layout.y2 : layout.y)\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: TableContext,\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/**\n * A point of the series in color slot `slot`: a circle, or the slot's marker\n * when the chart has point shapes (see `markerShape`).\n */\nexport function pointMark(\n shape: ReturnType<typeof markerShape>,\n slot: number,\n key: string | number,\n cls: ClassValue,\n cx: number,\n cy: number,\n r: number,\n): VNode {\n return shape\n ? h('path', { key, class: [cls, 'tc-marker'], d: shape(slot, cx, cy, r) })\n : h('circle', { key, class: cls, cx, cy, r })\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 /** Only the series of this axis (`y` or `y2`); every series when not set. */\n which?: 'y' | 'y2',\n): {\n scale(range: [number, number]): LinearScale\n ticks(scale: LinearScale): Tick[]\n probe: Tick[]\n} {\n const second = which === 'y2'\n const axis = (second ? options.y2 : options.y) ?? {}\n const count = tickCount(axis, Math.max(2, auto))\n let domain: [number, number]\n if (second) {\n const own = options.data.series.filter((s) => s.axis === 'y2')\n const shown = own.filter((s) => !ctx.hidden.has(seriesKey(s)))\n // With all its series hidden, the axis keeps its scale instead of jumping to 0…1.\n const values = (shown.length ? shown : own).flatMap((s) => s.values)\n domain = domainOf(values, axis, layout.zero2 ?? layout.zero, count)\n } else {\n const data =\n which === 'y'\n ? { ...options.data, series: options.data.series.filter((s) => s.axis !== 'y2') }\n : options.data\n domain = valueDomain(\n data,\n axis,\n layout.zero,\n count,\n ctx.hidden,\n layout.values,\n notesFeature(options)?.values(options.annotations),\n )\n }\n const format = second ? axis.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`. The value axis (the\n * category axis when `horizontal`) sits on the start `side`.\n */\nexport function finishLayout(\n options: CartesianOptions,\n ctx: RenderContext,\n side: PlotFrame['side'],\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, y2Ticks, horizontal: flip } = plot\n const xOptions = options.x ?? {}\n const rotate = turned(options, !flip && !time && xOptions.show !== false)\n // The second value axis stands on the other side.\n const opposite = side === 'left' ? 'right' : 'left'\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' : side, ticks: yTicks, area }),\n ]\n const categories = ((xOptions.show !== false && plot.labels.length > 0) || xOptions.line) && [\n axis({\n position: flip ? side : 'bottom',\n ticks: xTicks,\n area,\n line: xOptions.line === true,\n rotate,\n }),\n ]\n // Titles stand past the labels of their axis, or at the plot's edge when it is hidden.\n const seconds = !!y2Ticks &&\n options.y2?.show !== false && [axis({ position: opposite, ticks: y2Ticks, area })]\n const title = (\n text: string | undefined,\n position: 'left' | 'right' | 'bottom',\n ticks: readonly Tick[] | false,\n ) =>\n !!text &&\n axisTitle(position, ticks || [], area, text, ctx.fontSize, position === 'bottom' && rotate)\n const titles = [\n title(options.y?.title, flip ? 'bottom' : side, !!values && yTicks),\n title(xOptions.title, flip ? side : 'bottom', xTicks),\n !!y2Ticks && title(options.y2?.title, opposite, !!seconds && y2Ticks),\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([\n notes?.over,\n flip ? categories : values,\n flip ? values : categories,\n seconds,\n ...titles,\n ]),\n clip: plotClip(ctx, area, overhang),\n }\n}\n\n/** Whether the category labels are turned 90° (`x.rotate`), when the axis can take it. */\nconst turned = (options: CartesianOptions, able: boolean): boolean =>\n able && options.x?.rotate === true\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 rtl = ctx.rtl === true\n const reverse = xOptions.reverse ?? rtl\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 auto = Math.round(height / TICK_SPACING)\n const second = hasY2(options)\n const value = valueAxis(options, ctx, layout, auto, second ? 'y' : undefined)\n const probeY = value.probe\n const y2Options = options.y2 ?? {}\n const value2 = second ? valueAxis(options, ctx, layout, auto, 'y2') : null\n const showY2 = !!value2 && y2Options.show !== false\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 const rotate = turned(options, showX && !timed)\n // Every label, to measure the longest when they are turned.\n const allX: Tick[] = rotate\n ? labels.map((_, i) => ({ value: i, position: 0, label: labelAt(i) }))\n : []\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 // The label at the value axis' end of the plot, and the one at the other end.\n const edgeWidth = (last: boolean) =>\n rotate\n ? fontSize * LINE_HEIGHT\n : showX\n ? estimateTextWidth(edgeLabels[last ? edgeLabels.length - 1 : 0] ?? '', fontSize)\n : 0\n const firstLabel = edgeWidth(reverse !== rtl)\n const lastLabel = edgeWidth(reverse === rtl)\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 =\n (showY ? axisSize('left', probeY, fontSize) : 0) + axisTitleSize(yOptions.title, fontSize)\n // The second axis takes the end side (measured as the right, then mirrored).\n const value2Width = value2\n ? (showY2 ? axisSize('right', value2.probe, fontSize) : 0) +\n axisTitleSize(y2Options.title, fontSize)\n : 0\n const { area, side, range } = plotFrame(ctx, options.padding, (pad) => {\n const sides = (halfStep: number) => {\n const overflow = (label: number) =>\n edgeX ? Math.ceil(label / 2) : Math.max(0, Math.ceil(label / 2 - halfStep))\n return {\n start: pad.start + Math.max(valueWidth, overflow(firstLabel), overhang, showY ? 0 : EDGE),\n end: pad.end + Math.max(value2Width, overflow(lastLabel), overhang, EDGE),\n }\n }\n const steps = Math.max(1, labels.length) * 2\n let both = sides((width - pad.start - pad.end - valueWidth - value2Width) / steps)\n if (!edgeX) both = sides((width - both.start - both.end) / steps)\n return {\n top: pad.top + Math.max(showY || showY2 ? 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 (rotate\n ? axisSize('bottom', allX, fontSize, { rotate })\n : showX\n ? axisSize('bottom', [probeY[0] as Tick], fontSize)\n : showY\n ? halfLine\n : 0) + axisTitleSize(xOptions.title, fontSize),\n overhang,\n EDGE / 2,\n ),\n ...both,\n }\n })\n\n const x = xAxis.scale(range(reverse))\n const y = value.scale([area.y + area.height, area.y])\n const y2 = value2?.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 // Turned labels take the height of their letters along the axis, and little air between them.\n const xTicks = showX\n ? rotate\n ? thinTicks(xAxis.ticks(x), 'left', fontSize / LINE_HEIGHT, 2)\n : thinTicks(xAxis.ticks(x), 'bottom', fontSize)\n : []\n const plot: Omit<CartesianLayout, 'background' | 'foreground' | 'clip'> = {\n area,\n labels,\n x,\n y,\n horizontal: false,\n xTicks,\n yTicks,\n }\n if (value2 && y2) {\n plot.y2 = y2\n plot.y2Ticks = thinTicks(value2.ticks(y2), 'right', fontSize, 4)\n }\n\n return finishLayout(options, ctx, side, overhang, plot, keys, xAxis.time)\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 axisOf = seriesAxes(options)\n // Each series reads its values like its axis: bounds (log) and format.\n const axes = data.series.map((s) => axisOf(s).axis)\n const formats = axes.map((axis) => formatDetail(axis.format, ctx.locale))\n // The value under the pointer, on the first value axis, a pixel precise.\n const yAxis = options.y ?? {}\n const [d0, d1] = layout.y.domain\n const [r0, r1] = layout.y.range\n const cursorText =\n yAxis.scale === 'log' || r0 === r1\n ? formatDetail(yAxis.format, ctx.locale)\n : formatTicks(Math.abs((d1 - d0) / (r1 - r0)), yAxis.format, ctx.locale)\n const cursorAt = (px: number, py: number): HitCursor | undefined => {\n const position = horizontal ? px : py\n const lo = Math.min(r0, r1)\n const hi = Math.max(r0, r1)\n const value = layout.y.invert(position)\n if (position < lo || position > hi || !Number.isFinite(value)) return undefined\n const cursor: HitCursor = {\n value,\n text: cursorText(value),\n position,\n side: horizontal ? 'bottom' : ctx.rtl ? 'right' : 'left',\n }\n if (yAxis.show === false) cursor.inside = true\n return cursor\n }\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, axes[seriesIndex]) ? 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 ? '–' : (formats[seriesIndex] as (v: number) => string)(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.highlight = horizontal\n ? { kind: 'band', x: area.x, y: start, width: area.width, height: x.bandwidth }\n : { kind: 'band', x: start, y: area.y, width: x.bandwidth, height: area.height }\n }\n return hit\n }\n\n return {\n count: labels.length,\n reversed: x.range[1] < x.range[0],\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 const cursor = cursorAt(px, py)\n if (cursor) hit.cursor = cursor\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: TableContext,\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 axisOf = seriesAxes(options)\n const series = options.data.series.filter((s) => !ctx.hidden.has(seriesKey(s)))\n const formats = series.map((s) => formatDetail(axisOf(s).axis.format, ctx.locale))\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) => {\n const v = s.values[i]\n return v == null || !Number.isFinite(v) ? '–' : (formats[n] as (v: number) => string)(v)\n }),\n ]),\n }\n}\n","import {\n type CartesianData,\n type Label,\n labelKey,\n resolveLabels,\n type Series,\n} from './cartesian.ts'\nimport { finite } from './clean.ts'\n\n/**\n * The categories a chart shows, as indexes into its labels, both included.\n * A side left out runs to that end of the data.\n */\nexport interface ViewWindow {\n /** Index of the first category shown. Defaults to `0`. */\n start?: number\n /** Index of the last category shown. Defaults to the last one. */\n end?: number\n}\n\nexport interface ZoomOptions {\n /** Zoom with the wheel (and a pinch on a trackpad). Defaults to `true`. */\n wheel?: boolean\n /** Show the zoom in, zoom out and reset buttons. Defaults to `true`. */\n controls?: boolean\n /** The fewest categories a reader can zoom in to. Defaults to `2`. */\n min?: number\n /** Names of the buttons, for a page in another language. */\n labels?: { in?: string; out?: string; reset?: string }\n}\n\n/** The options of a chart that can show a window of its categories. */\nexport interface Zoomable {\n /**\n * Let the reader zoom along the categories: with the wheel, by dragging\n * over a range, with a pinch, the buttons or the `+`, `-` and `0` keys;\n * Shift with a drag, the wheel or an arrow key moves the range. The range\n * shown lives in `view`. Needs `import '@tabler/charts/zoom'`.\n */\n zoom?: boolean | ZoomOptions\n /**\n * The range of categories shown; the value axis follows the values in it.\n * Set it to show a part of the data, read it from `chart.config.view`\n * after a zoom. Needs `import '@tabler/charts/zoom'`.\n */\n view?: ViewWindow | undefined\n /**\n * Make the chart a brush: it shows all its data with a range marked on\n * it, which the reader moves, resizes by its ends or draws again, and\n * which charts in the same `sync` group take as their `view` (matched by\n * label). Zooming one of them moves the range too. The range lives in\n * `selection`. `min` is the fewest categories it can cover (2 by\n * default). The brush and the charts of its group add to their\n * `padding` so that their plots start and end together; `align: false`\n * leaves them as they are. Needs `import '@tabler/charts/zoom'`.\n */\n brush?: boolean | { min?: number; align?: boolean }\n /** The range marked on a brush; everything when left out. */\n selection?: ViewWindow | undefined\n}\n\ntype Windowed = Zoomable & {\n data: CartesianData | readonly unknown[]\n x?: { format?: (label: Label, index: number) => string }\n}\n\n/** How many categories the data of a chart has (candles, or labels). */\nexport const categoryCount = (data: Windowed['data']): number =>\n Array.isArray(data) ? data.length : resolveLabels(data as CartesianData).length\n\n/** The first and last index of a view over `count` categories, within the data. */\nexport function viewRange(view: ViewWindow | undefined, count: number): [number, number] {\n const last = Math.max(0, count - 1)\n const within = (value: number, low: number) => Math.min(last, Math.max(low, Math.round(value)))\n const start = within(finite(view?.start) ?? 0, 0)\n return [start, within(finite(view?.end) ?? last, start)]\n}\n\n/**\n * The options of a chart with only the categories of its `view`: the chart\n * type then draws them like any other data, so axes, stacks, tooltips and\n * the table all follow the range shown.\n */\nexport function viewWindow<O extends object>(options: O): O {\n const { data, view, x } = options as Windowed\n const [start, end] = viewRange(view, categoryCount(data))\n if (start === 0 && end >= categoryCount(data) - 1) return options\n const cut = <T>(list: readonly T[]): T[] => list.slice(start, end + 1)\n const out = { ...options } as Windowed\n // A custom format still gets the index of the label in the whole data.\n const format = x?.format\n if (format) out.x = { ...x, format: (label, index) => format(label, index + start) }\n if (Array.isArray(data)) {\n out.data = cut(data)\n return out as O\n }\n const all = data as CartesianData\n const labels = resolveLabels(all)\n const keys = labels.map(labelKey)\n out.data = {\n ...all,\n labels: cut(labels),\n series: all.series.map((series): Series => {\n const next = { ...series, values: cut(series.values) }\n // A line dashed from a label before the range is dashed all along.\n const from = series.dashFrom == null ? -1 : keys.indexOf(labelKey(series.dashFrom))\n if (from >= 0 && from < start) next.dashFrom = labels[start] as Label\n return next\n }),\n }\n return out as O\n}\n","import type { Chart } from '../chart.ts'\nimport { toChartPoint } from '../interaction.ts'\nimport type { Rect } from '../layout.ts'\n\nexport type Point = [number, number]\n\n/** The chart types whose categories can be zoomed and brushed. */\nexport const TYPES: ReadonlySet<string> = new Set(['line', 'area', 'bar', 'candlestick'])\n\n/** How far a pointer has to move, in pixels, before a press becomes a drag and stops being a click. */\nexport const DRAG_THRESHOLD = 4\nexport const SVG_NS = 'http://www.w3.org/2000/svg'\n\n/** The plot of a chart: its area and how its categories run, in chart pixels. */\nexport interface Plot {\n area: Rect\n /** Whether the categories run along y (horizontal bars). */\n vertical: boolean\n reversed: boolean\n /** The pixels from one category to the next. */\n step: number\n /** Where the category at an index (of what is drawn) stands along its axis. */\n at(index: number): number | undefined\n}\n\n/** What the zoom and the brush read of a chart: its svg, its plot, and where a pointer is on it. */\nexport interface PlotTools {\n /** The svg of the chart, once it is drawn. */\n svg(): Element | null\n plot(): Plot | undefined\n /** A point of the screen in chart pixels (kept on the plot), and whether it is on the plot. */\n locate(x: number, y: number): { at: Point; inside: boolean } | undefined\n /** Whether an event happened on the plot of the chart, not on a control over it. */\n onPlot(event: MouseEvent): boolean\n}\n\nexport function plotTools(chart: Chart<object>): PlotTools {\n const host = chart.element\n const svg = () => host.querySelector(':scope > svg.tc-chart')\n /** The plot area and the direction of its categories, in chart pixels. */\n const plot = (): Plot | undefined => {\n const interaction = chart.interaction\n const hit = interaction?.hitIndex(0)\n if (!hit || !interaction) return undefined\n const vertical = hit.axis === 'y'\n const along = (h: typeof hit) => (vertical ? (h.y as number) : h.x)\n const last = interaction.count - 1\n const end = interaction.hitIndex(last)\n // The pixels from one category to the next (the whole plot for a single one).\n const step =\n (end && last > 0 && Math.abs(along(end) - along(hit)) / last) ||\n (vertical ? hit.area.height : hit.area.width) ||\n 1\n return {\n area: hit.area,\n vertical,\n reversed: !!interaction.reversed,\n step,\n at: (index) => {\n const at = interaction.hitIndex(index)\n return at ? along(at) : undefined\n },\n }\n }\n /** A point of the screen in chart pixels, and whether it is on the plot. */\n const locate = (x: number, y: number): { at: Point; inside: boolean } | undefined => {\n const el = svg()\n const area = plot()?.area\n if (!el || !area) return undefined\n const { width, height } = chart.size\n const p = toChartPoint(el, x, y, width, height)\n const inside =\n p.x >= area.x && p.x <= area.x + area.width && p.y >= area.y && p.y <= area.y + area.height\n const within = (value: number, low: number, size: number) =>\n Math.min(low + size, Math.max(low, value))\n return {\n at: [within(p.x, area.x, area.width), within(p.y, area.y, area.height)],\n inside,\n }\n }\n /** Whether an event happened on the plot of the chart, not on a control over it. */\n const onPlot = (event: MouseEvent) =>\n (event.target as Element | null)?.closest?.('svg.tc-chart') === svg() &&\n !!locate(event.clientX, event.clientY)?.inside\n return { svg, plot, locate, onPlot }\n}\n","import type { Chart } from '../chart.ts'\nimport { type CartesianData, labelKey, resolveLabels } from '../charts/cartesian.ts'\nimport { finite } from '../charts/clean.ts'\nimport { categoryCount, type ViewWindow, viewRange, type Zoomable } from '../charts/view.ts'\nimport { type InsetsInput, insets } from '../layout.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { DRAG_THRESHOLD, type Point, plotTools, SVG_NS, TYPES } from './plot.ts'\n\ntype Range = [number, number]\ntype Config = Zoomable & {\n data: CartesianData | readonly { x: never }[]\n sync?: string\n padding?: InsetsInput\n}\n\n/** The charts of each `sync` group that can pass a range on. */\nconst groups = /* @__PURE__ */ new Map<string, Set<Chart<object>>>()\n\nconst configOf = (chart: Chart<object>) => chart.config as unknown as Config\nconst isBrush = (chart: Chart<object>) => !!configOf(chart).brush\n/** The option a chart keeps its range in: the mark of a brush, the view of any other chart. */\nconst rangeKey = (chart: Chart<object>) => (isBrush(chart) ? 'selection' : 'view')\nconst countOf = (chart: Chart<object>) => categoryCount(configOf(chart).data)\nconst rangeOf = (chart: Chart<object>): Range =>\n viewRange(configOf(chart)[rangeKey(chart)], countOf(chart))\nconst whole = (chart: Chart<object>, [start, end]: Range) =>\n start === 0 && end >= countOf(chart) - 1\n\n/** How each chart of a group with a brush lines its plot up with the others. */\nconst aligners = /* @__PURE__ */ new WeakMap<Chart<object>, (drawn?: boolean) => void>()\n/** What that adds to the padding of a chart, before and after its plot. */\nconst extra = /* @__PURE__ */ new WeakMap<Chart<object>, number[]>()\n/** Whether the categories of a chart run along y; `undefined` before it has a plot. */\nconst flow = (chart: Chart<object>) => plotTools(chart).plot()?.vertical\n/** Whether a chart takes part: every zoomable chart, but a brush with `align: false`. */\nconst aligns = (chart: Chart<object>) => {\n const { brush } = configOf(chart)\n return TYPES.has(chart.config.type.name) && !(typeof brush === 'object' && brush.align === false)\n}\n/** The space before and after the plot of a chart along its categories, without what was added. */\nfunction natural(chart: Chart<object>, vertical: boolean): number[] | undefined {\n const area = plotTools(chart).plot()?.area\n if (!area) return undefined\n const { width, height } = chart.size\n const spaces = vertical\n ? [area.y, height - area.y - area.height]\n : [area.x, width - area.x - area.width]\n return spaces.map((space, i) => space - (extra.get(chart)?.[i] ?? 0))\n}\n\n/**\n * The range each chart last passed on or was given, so that only a range\n * that changed is passed on, and never back to where it came from.\n */\nconst passed = /* @__PURE__ */ new WeakMap<Chart<object>, string>()\nconst rangeText = (chart: Chart<object>) => `${rangeKey(chart)} ${rangeOf(chart)}`\n\n/** The keys of a chart's labels, in order, once per data. */\nconst keys = /* @__PURE__ */ new WeakMap<object, (string | number)[]>()\nfunction labelKeys(chart: Chart<object>): (string | number)[] {\n const { data } = configOf(chart)\n let list = keys.get(data)\n if (!list) {\n const labels = Array.isArray(data)\n ? data.map((candle) => candle.x)\n : resolveLabels(data as CartesianData)\n list = labels.map(labelKey)\n keys.set(data, list)\n }\n return list\n}\n\n/** Sets the range of a chart, when it is not the one it has. */\nfunction setRange(chart: Chart<object>, [start, end]: Range): void {\n const [was, wasEnd] = rangeOf(chart)\n if (start === was && end === wasEnd) return\n // Everything is no range at all, so data that grows later stays in it.\n const range: ViewWindow | undefined = whole(chart, [start, end]) ? undefined : { start, end }\n chart.update({ [rangeKey(chart)]: range } as never)\n}\n\n/** The range of `from` in the categories of `to`: the same labels, or else the same indexes. */\nfunction mapRange(from: Chart<object>, to: Chart<object>, range: Range): Range | undefined {\n if (whole(from, range)) return undefined\n const source = labelKeys(from)\n const target = labelKeys(to)\n const at = (index: number) => {\n const found = target.indexOf(source[index] as string | number)\n return found < 0 ? index : found\n }\n return viewRange({ start: at(range[0]), end: at(range[1]) }, target.length)\n}\n\n/** What a press on a brush does: move the range, move one of its ends, or draw a new one. */\ninterface Press {\n from: Point\n range: Range\n /** The end that follows the pointer (`0` the start, `1` the end), all of it, or a new range. */\n mode: 0 | 1 | 'move' | 'new'\n /** The category a new range starts at. */\n index: number\n}\n\n/**\n * The brush (`brush: true`): a chart that shows all its data with a range\n * marked on it. Dragging the range moves it, dragging one of its ends\n * resizes it, dragging elsewhere draws a new one, a double click (or `0`)\n * marks everything, and Shift with an arrow key moves it by one category.\n * Charts in the same `sync` group take the range as their `view`, and a\n * chart of the group that is zoomed moves the range of the brush. Like the\n * zoom it keeps no state: the range lives in the `selection` option.\n */\nexport const installBrush: ChartPlugin['install'] = (chart) => {\n const host = chart.element\n if (typeof host.addEventListener !== 'function') return {}\n const doc = host.ownerDocument\n const { svg, plot, locate, onPlot } = plotTools(chart)\n const cartesian = () => TYPES.has(chart.config.type.name)\n const on = () => cartesian() && isBrush(chart)\n const least = () => {\n const { brush } = configOf(chart)\n const min = typeof brush === 'object' ? finite(brush.min) : null\n return Math.max(0, Math.min(countOf(chart), Math.round(min ?? 2)) - 1)\n }\n /** Marks the categories from `start` to `end`, kept within the data and the smallest range. */\n const mark = (start: number, end: number) => {\n const last = Math.max(0, countOf(chart) - 1)\n const size = Math.min(last, Math.max(least(), end - start))\n const from = Math.min(last - size, Math.max(0, start))\n setRange(chart, [from, from + size])\n }\n\n // -- The group: ranges passed between a brush and the charts it drives -------\n\n let group: Set<Chart<object>> | undefined\n let joined: string | undefined\n const leave = () => {\n group?.delete(chart)\n if (joined && group?.size === 0 && groups.get(joined) === group) groups.delete(joined)\n group = undefined\n }\n const join = () => {\n const name = cartesian() ? configOf(chart).sync : undefined\n if (name === joined && group) return\n leave()\n joined = name\n if (!name) return\n group = groups.get(name) ?? new Set()\n group.add(chart)\n groups.set(name, group)\n }\n /** Gives a range that changed to the other side: a brush to the charts, a chart to the brushes. */\n const pass = () => {\n join()\n if (!group) return\n const range = rangeOf(chart)\n const key = rangeText(chart)\n const first = !passed.has(chart)\n if (key === passed.get(chart)) return\n passed.set(chart, key)\n const others = [...group].filter((other) => isBrush(other) !== isBrush(chart))\n if (first && whole(chart, range)) {\n // A chart that starts with everything has nothing to say: it takes the\n // range the other side already has.\n for (const other of others) {\n const given = mapRange(other, chart, rangeOf(other))\n if (given) return setRange(chart, given)\n }\n return\n }\n for (const other of others) {\n setRange(other, mapRange(chart, other, range) ?? [0, countOf(other) - 1])\n // What a chart was given is not news to pass back. A brush passes it on,\n // to the other charts it drives.\n if (!isBrush(other)) passed.set(other, rangeText(other))\n }\n }\n\n // -- The plots of a brush and its charts start and end together -----------------\n\n /** The padding the chart was given, and the one set here in its place. */\n let own = configOf(chart).padding\n let given = own\n /** What the padding set here adds, until the chart is drawn with it. */\n let pending: number[] | undefined\n const align = (drawn?: boolean) => {\n const changed = configOf(chart).padding !== given\n // What is measured is the chart as drawn: a chart waits for its own render.\n if (!drawn && (pending || changed)) return\n if (changed) {\n own = configOf(chart).padding\n given = own\n extra.delete(chart)\n } else if (pending) extra.set(chart, pending)\n pending = undefined\n const added = extra.get(chart) ?? [0, 0]\n const vertical = aligns(chart) ? plot()?.vertical : undefined\n let next = [0, 0]\n if (vertical !== undefined && group) {\n // The widest space of the group on each side, as long as it has a brush.\n const all = [...group].filter((other) => aligns(other) && flow(other) === vertical)\n const mine = natural(chart, vertical)\n if (mine && all.some(isBrush)) {\n const spaces = all.map((other) => natural(other, vertical))\n next = mine.map((space, i) =>\n Math.max(0, ...spaces.map((other) => (other ? (other[i] as number) - space : 0))),\n )\n }\n }\n if (next.every((space, i) => Math.abs(space - (added[i] as number)) < 0.5)) return\n pending = next\n const base = insets(own)\n const [a, b] = vertical ? (['top', 'bottom'] as const) : (['left', 'right'] as const)\n given = next.some(Boolean)\n ? { ...base, [a]: base[a] + (next[0] as number), [b]: base[b] + (next[1] as number) }\n : own\n chart.update({ padding: given } as never)\n }\n aligners.set(chart, align)\n\n // -- The mark and its two ends, drawn over the plot ---------------------------\n\n let nodes: [SVGGElement, SVGRectElement, SVGRectElement, SVGRectElement] | undefined\n const clearMark = () => {\n nodes?.[0].remove()\n nodes = undefined\n }\n const drawMark = () => {\n const el = svg()\n const p = plot()\n if (!on() || !el || !p) {\n clearMark()\n return\n }\n if (!nodes) {\n const rect = (name: string) => {\n const node = doc.createElementNS(SVG_NS, 'rect')\n node.setAttribute('class', name)\n return node\n }\n const g = doc.createElementNS(SVG_NS, 'g')\n g.setAttribute('class', 'tc-brush')\n nodes = [g, rect('tc-brush-selection'), rect('tc-brush-handle'), rect('tc-brush-handle')]\n g.append(nodes[1], nodes[2], nodes[3])\n }\n // (A render takes the nodes out with the old content.)\n if (nodes[0].parentNode !== el) el.append(nodes[0])\n const [start, end] = rangeOf(chart)\n const low = p.vertical ? p.area.y : p.area.x\n const length = p.vertical ? p.area.height : p.area.width\n const within = (value: number) => Math.min(low + length, Math.max(low, value))\n // Half a step past the first and the last category, kept on the plot.\n const a = p.at(start) ?? low\n const b = p.at(end) ?? low + length\n const from = within(Math.min(a, b) - p.step / 2)\n const to = within(Math.max(a, b) + p.step / 2)\n const box = (node: SVGRectElement, at: number, size: number) => {\n const attrs = p.vertical\n ? { x: p.area.x, y: at, width: p.area.width, height: size }\n : { x: at, y: p.area.y, width: size, height: p.area.height }\n for (const [name, value] of Object.entries(attrs)) node.setAttribute(name, `${value}`)\n }\n box(nodes[1], from, to - from)\n // The ends: the one at the start of the data first, wherever it is drawn.\n const ends = a <= b ? [from, to] : [to, from]\n box(nodes[2], (ends[0] as number) - 3, 6)\n box(nodes[3], (ends[1] as number) - 3, 6)\n }\n\n // -- Input ---------------------------------------------------------------------\n\n let press: Press | undefined\n let pointer: number | undefined\n /** Whether the pointer that is down has moved: the click that ends a drag is no click. */\n let dragged = false\n\n const indexAt = ([x, y]: Point) => chart.interaction?.hitTest(x, y)?.index\n const onPointerEnd = (event: PointerEvent) => {\n if (event.pointerId !== pointer) return\n press = undefined\n pointer = undefined\n doc.removeEventListener('pointerup', onPointerEnd)\n doc.removeEventListener('pointercancel', onPointerEnd)\n }\n const onPointerDown = (event: PointerEvent) => {\n if (!on() || press || !onPlot(event)) return\n if (event.pointerType === 'mouse' && event.button !== 0) return\n const at = locate(event.clientX, event.clientY)?.at\n const index = at && indexAt(at)\n if (!at || index === undefined) return\n const target = event.target as Element\n const mode =\n target === nodes?.[2] ? 0 : target === nodes?.[3] ? 1 : target === nodes?.[1] ? 'move' : 'new'\n press = { from: at, range: rangeOf(chart), mode, index }\n pointer = event.pointerId\n dragged = false\n doc.addEventListener('pointerup', onPointerEnd)\n doc.addEventListener('pointercancel', onPointerEnd)\n }\n const onPointerMove = (event: PointerEvent) => {\n const p = plot()\n const now = press && event.pointerId === pointer && locate(event.clientX, event.clientY)?.at\n if (!press || !now || !p) return\n const i = p.vertical ? 1 : 0\n if (!dragged) {\n // A press that barely moves is a click: it reaches the chart as one.\n if (Math.abs(now[i] - press.from[i]) < DRAG_THRESHOLD) return\n dragged = true\n // The chart keeps getting the moves of this pointer when it leaves the\n // plot. Capturing throws for a pointer made in a script.\n try {\n svg()?.setPointerCapture(event.pointerId)\n } catch {\n // The drag still works while the pointer stays over the chart.\n }\n }\n // The highlight and the tooltip stay out of a drag.\n event.stopPropagation()\n chart.clearHighlight()\n const [start, end] = press.range\n const index = indexAt(now)\n if (press.mode === 'move') {\n const moved = (now[i] - press.from[i]) / p.step\n const by = Math.round(p.reversed ? -moved : moved)\n const last = Math.max(0, countOf(chart) - 1)\n const shift = Math.min(last - end, Math.max(-start, by))\n mark(start + shift, end + shift)\n } else if (index === undefined) {\n return\n } else if (press.mode === 'new') {\n mark(Math.min(press.index, index), Math.max(press.index, index))\n } else if (press.mode === 0) {\n mark(Math.min(index, end - least()), end)\n } else {\n mark(start, Math.max(index, start + least()))\n }\n }\n /** The click that ends a drag is not a click on the chart. */\n const onClickCapture = (event: MouseEvent) => {\n if (dragged) event.stopPropagation()\n dragged = false\n }\n const onDoubleClick = (event: MouseEvent) => {\n if (on() && onPlot(event)) mark(0, countOf(chart) - 1)\n }\n const onKey = (event: KeyboardEvent) => {\n if (event.target !== svg() || !on()) return\n const { key } = event\n const arrow = key === 'ArrowLeft' ? -1 : key === 'ArrowRight' ? 1 : 0\n const [start, end] = rangeOf(chart)\n if (key === '0') mark(0, countOf(chart) - 1)\n else if (event.shiftKey && arrow) {\n const by = plot()?.reversed ? -arrow : arrow\n const last = Math.max(0, countOf(chart) - 1)\n const shift = Math.min(last - end, Math.max(-start, by))\n mark(start + shift, end + shift)\n } else return\n // (Shift with an arrow moves the range, not the highlight.)\n event.stopPropagation()\n event.preventDefault()\n }\n\n // Moves and keys are taken on their way down, like the zoom's.\n host.addEventListener('pointermove', onPointerMove, true)\n host.addEventListener('click', onClickCapture, true)\n host.addEventListener('keydown', onKey, true)\n host.addEventListener('pointerdown', onPointerDown)\n host.addEventListener('dblclick', onDoubleClick)\n\n return {\n svgAttrs: () => (on() ? { 'data-zoom-axis': plot()?.vertical ? 'y' : 'x' } : undefined),\n afterRender() {\n drawMark()\n pass()\n // The plots of the group follow each other, whichever chart was drawn.\n for (const other of group ?? [chart]) aligners.get(other)?.(other === chart)\n },\n destroy() {\n host.removeEventListener('pointermove', onPointerMove, true)\n host.removeEventListener('click', onClickCapture, true)\n host.removeEventListener('keydown', onKey, true)\n host.removeEventListener('pointerdown', onPointerDown)\n host.removeEventListener('dblclick', onDoubleClick)\n doc.removeEventListener('pointerup', onPointerEnd)\n doc.removeEventListener('pointercancel', onPointerEnd)\n clearMark()\n const rest = group\n leave()\n // Without this chart the others may have nothing left to line up with.\n for (const other of rest ?? []) aligners.get(other)?.()\n },\n }\n}\n","import { finite } from '../charts/clean.ts'\nimport { categoryCount, viewRange, type Zoomable, type ZoomOptions } from '../charts/view.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { DRAG_THRESHOLD, type Point, plotTools, SVG_NS, TYPES } from './plot.ts'\n\n/** One step of a button or a key. */\nconst ZOOM_STEP = 2\n/** How much one unit of wheel movement magnifies; a pinch on a trackpad comes with `ctrlKey` and smaller numbers. */\nconst WHEEL_SPEED = 0.002\nconst WHEEL_SPEED_PINCH = 0.01\nconst BUTTONS = [\n ['in', 'Zoom in', 'M12 5v14M5 12h14'],\n ['out', 'Zoom out', 'M5 12h14'],\n [\n 'reset',\n 'Reset zoom',\n 'M20 11a8.1 8.1 0 0 0-15.5-2M4 5v4h4M4 13a8.1 8.1 0 0 0 15.5 2M20 19v-4h-4',\n ],\n] as const\n\n/** A press on the plot: where it started, what was shown then, and what it does. */\ninterface Press {\n from: Point\n range: [number, number]\n pan: boolean\n}\n\n/**\n * Zoom along the categories of line, area, bar and candlestick charts\n * (`zoom: true`): the wheel and a pinch magnify around the pointer, a drag\n * over the plot picks the range to show, the buttons and the `+`, `-` and\n * `0` keys zoom in, out and back to everything, and Shift with a drag, the\n * wheel or an arrow key moves the range. It keeps no state: the range shown\n * lives in the `view` option, which the chart types cut their data to.\n * `@tabler/charts/zoom` registers it; the `zoom()` plugin installs it.\n */\nexport const installZoom: ChartPlugin['install'] = (chart) => {\n const host = chart.element\n if (typeof host.addEventListener !== 'function') return {}\n const doc = host.ownerDocument\n const config = () => chart.config as unknown as Zoomable & { data: never }\n // (A chart that is a brush shows everything: it is not zoomed itself.)\n const on = () => TYPES.has(chart.config.type.name) && !!config().zoom && !config().brush\n const options = (): ZoomOptions => {\n const { zoom } = config()\n return typeof zoom === 'object' ? zoom : {}\n }\n const count = () => categoryCount(config().data)\n const range = () => viewRange(config().view, count())\n /** The fewest categories shown, less one: the smallest distance from start to end. */\n const least = () => Math.max(0, Math.min(count(), Math.round(finite(options().min) ?? 2)) - 1)\n const { svg, plot, locate, onPlot } = plotTools(chart)\n /**\n * The range the chart was last drawn with. Its hits count from there,\n * and a few events can come before the next range is drawn.\n */\n let drawn: [number, number] = [0, 0]\n /** The index, in the whole data, of the category at a point of the plot. */\n const indexAt = ([x, y]: Point): number | undefined => {\n const hit = chart.interaction?.hitTest(x, y)\n return hit ? drawn[0] + hit.index : undefined\n }\n\n /**\n * The range as fractions of categories, with the whole categories it\n * stands for: small steps of the wheel add up instead of rounding away.\n */\n let fine: { a: number; b: number; start: number; end: number } | undefined\n const edges = (): Point => {\n const [start, end] = range()\n if (fine?.start !== start || fine.end !== end) fine = { a: start, b: end, start, end }\n return [fine.a, fine.b]\n }\n /** Shows the categories from `a` to `b`, kept within the data and the smallest range. */\n const show = (a: number, b: number): boolean => {\n const last = Math.max(0, count() - 1)\n const size = Math.min(last, Math.max(least(), b - a))\n // A range that had to grow or shrink keeps its middle.\n a += (b - a - size) / 2\n a = Math.min(last - size, Math.max(0, a))\n b = a + size\n let start = Math.round(a)\n let end = Math.round(b)\n if (end - start < least()) {\n end = Math.min(last, start + least())\n start = end - least()\n }\n const [was, wasEnd] = range()\n fine = { a, b, start, end }\n if (start === was && end === wasEnd) return false\n // Everything is no view at all, so data that grows later stays in sight.\n chart.update({ view: start === 0 && end === last ? undefined : { start, end } } as never)\n return true\n }\n /** Magnifies by a factor around a category, which stays where it is. */\n const zoomBy = (factor: number, anchor?: number): boolean => {\n const [a, b] = edges()\n // Without a pointer, around the category in focus, or else the middle.\n const active = chart.active\n const center = anchor ?? (active ? drawn[0] + active.index : (a + b) / 2)\n return show(center - (center - a) / factor, center + (b - center) / factor)\n }\n const panBy = (categories: number): boolean => {\n const [a, b] = edges()\n const last = Math.max(0, count() - 1)\n const by = Math.min(last - b, Math.max(-a, categories))\n return show(a + by, b + by)\n }\n const reset = () => show(0, count() - 1)\n\n /** Pointers that are down on the plot, with where each was last seen. */\n const pointers = new Map<number, Point>()\n let press: Press | undefined\n /** Whether the pointers that are down have moved: the click that ends a drag is no click. */\n let dragged = false\n let selection: SVGRectElement | undefined\n let controls: HTMLElement | undefined\n const addedClass = !host.classList.contains('tc-container')\n\n const clearSelection = () => {\n selection?.remove()\n selection = undefined\n }\n /** The rectangle over the categories of a drag, across the plot. */\n const drawSelection = (from: Point, to: Point) => {\n const el = svg()\n const p = plot()\n if (!el || !p) return\n if (!selection) {\n selection = doc.createElementNS(SVG_NS, 'rect')\n selection.setAttribute('class', 'tc-zoom-selection')\n }\n if (selection.parentNode !== el) el.append(selection)\n const i = p.vertical ? 1 : 0\n const low = Math.min(from[i], to[i])\n const size = Math.abs(from[i] - to[i])\n const box = p.vertical\n ? { x: p.area.x, y: low, width: p.area.width, height: size }\n : { x: low, y: p.area.y, width: size, height: p.area.height }\n for (const [name, value] of Object.entries(box)) selection.setAttribute(name, `${value}`)\n }\n\n const onPointerEnd = (event: PointerEvent) => {\n const last = pointers.get(event.pointerId)\n pointers.delete(event.pointerId)\n if (press && !press.pan && dragged && last && event.type === 'pointerup') {\n const from = indexAt(press.from)\n const to = indexAt(last)\n if (from !== undefined && to !== undefined && from !== to)\n show(Math.min(from, to), Math.max(from, to))\n }\n if (pointers.size === 0) {\n press = undefined\n clearSelection()\n doc.removeEventListener('pointerup', onPointerEnd)\n doc.removeEventListener('pointercancel', onPointerEnd)\n }\n }\n const onPointerDown = (event: PointerEvent) => {\n if (!on() || !onPlot(event) || (event.pointerType === 'mouse' && event.button !== 0)) return\n const at = locate(event.clientX, event.clientY)?.at\n if (!at) return\n if (pointers.size === 0) {\n dragged = false\n press = { from: at, range: drawn, pan: event.shiftKey }\n } else {\n // A second finger: a pinch, not a range.\n press = undefined\n clearSelection()\n }\n pointers.set(event.pointerId, at)\n doc.addEventListener('pointerup', onPointerEnd)\n doc.addEventListener('pointercancel', onPointerEnd)\n }\n /** One pointer picks a range (or moves it, with Shift), two pinch. */\n const onPointerMove = (event: PointerEvent) => {\n const previous = pointers.get(event.pointerId)\n const now = locate(event.clientX, event.clientY)?.at\n const p = plot()\n if (!previous || !now || !p) return\n const i = p.vertical ? 1 : 0\n if (!dragged) {\n // A press that barely moves is a click: it reaches the chart as one.\n if (pointers.size === 1 && Math.abs(now[i] - previous[i]) < DRAG_THRESHOLD) return\n dragged = true\n // The chart keeps getting the moves of this pointer when it leaves\n // the plot. Capturing throws for a pointer made in a script.\n try {\n svg()?.setPointerCapture(event.pointerId)\n } catch {\n // The drag still works while the pointer stays over the chart.\n }\n }\n // The highlight and the tooltip stay out of a drag.\n event.stopPropagation()\n chart.clearHighlight()\n pointers.set(event.pointerId, now)\n if (pointers.size > 1) {\n const other = [...pointers].find(([id]) => id !== event.pointerId)?.[1]\n if (!other) return\n const before = Math.abs(previous[i] - other[i])\n const after = Math.abs(now[i] - other[i])\n if (before > 0 && after > 0)\n zoomBy(after / before, indexAt([(now[0] + other[0]) / 2, (now[1] + other[1]) / 2]))\n } else if (press?.pan) {\n const [start, end] = press.range\n const moved = (now[i] - press.from[i]) / p.step\n const by = Math.round(p.reversed ? moved : -moved)\n const last = Math.max(0, count() - 1)\n const shift = Math.min(last - end, Math.max(-start, by))\n show(start + shift, end + shift)\n } else if (press) {\n drawSelection(press.from, now)\n }\n }\n const onWheel = (event: WheelEvent) => {\n if (!on() || options().wheel === false || !onPlot(event)) return\n const p = plot()\n const at = locate(event.clientX, event.clientY)?.at\n if (!p || !at) return\n const [a, b] = edges()\n const sideways = event.shiftKey || Math.abs(event.deltaX) > Math.abs(event.deltaY)\n const delta = sideways ? event.deltaX || event.deltaY : event.deltaY\n const changed = sideways\n ? panBy((p.reversed ? -delta : delta) / p.step)\n : zoomBy(Math.exp(-delta * (event.ctrlKey ? WHEEL_SPEED_PINCH : WHEEL_SPEED)), indexAt(at))\n // At the end of the data, or with everything shown, the page scrolls on.\n const moved = fine && (fine.a !== a || fine.b !== b)\n if (changed || moved) event.preventDefault()\n }\n const onDoubleClick = (event: MouseEvent) => {\n if (on() && onPlot(event)) reset()\n }\n /** The click that ends a drag is not a click on the chart. */\n const onClickCapture = (event: MouseEvent) => {\n if (dragged) event.stopPropagation()\n dragged = false\n }\n const onKey = (event: KeyboardEvent) => {\n if (event.target !== svg() || !on()) return\n const { key } = event\n const arrow = key === 'ArrowLeft' ? -1 : key === 'ArrowRight' ? 1 : 0\n if (key === '+' || key === '=') zoomBy(ZOOM_STEP)\n else if (key === '-') zoomBy(1 / ZOOM_STEP)\n else if (key === '0') reset()\n else if (event.shiftKey && arrow) panBy(plot()?.reversed ? -arrow : arrow)\n else return\n // (Shift with an arrow moves the range, not the highlight.)\n event.stopPropagation()\n event.preventDefault()\n }\n const onControl = (event: MouseEvent) => {\n const value = (event.target as Element).closest('button')?.value\n if (value === 'reset') reset()\n else if (value) zoomBy(value === 'in' ? ZOOM_STEP : 1 / ZOOM_STEP)\n }\n\n // Moves and keys are taken on their way down, so a drag never reaches\n // the highlight and Shift with an arrow never moves it.\n host.addEventListener('pointermove', onPointerMove, true)\n host.addEventListener('click', onClickCapture, true)\n host.addEventListener('keydown', onKey, true)\n host.addEventListener('pointerdown', onPointerDown)\n // (Not passive: the wheel must be kept from scrolling the page.)\n host.addEventListener('wheel', onWheel, { passive: false })\n host.addEventListener('dblclick', onDoubleClick)\n\n /** The zoom buttons, laid over a corner of the chart. */\n const renderControls = () => {\n if (!on() || options().controls === false) {\n controls?.remove()\n controls = undefined\n return\n }\n if (!controls) {\n controls = doc.createElement('div')\n controls.className = 'tc-zoom'\n for (const [value, , d] of BUTTONS) {\n const button = doc.createElement('button')\n button.type = 'button'\n button.className = 'tc-download-toggle'\n button.value = value\n const icon = doc.createElementNS(SVG_NS, 'svg')\n icon.setAttribute('viewBox', '0 0 24 24')\n icon.setAttribute('width', '16')\n icon.setAttribute('height', '16')\n icon.setAttribute('aria-hidden', 'true')\n const path = doc.createElementNS(SVG_NS, 'path')\n path.setAttribute('d', d)\n icon.append(path)\n button.append(icon)\n controls.append(button)\n }\n controls.addEventListener('click', onControl)\n host.classList.add('tc-container')\n }\n if (!controls.isConnected) host.append(controls)\n controls.dir = chart.rtl ? 'rtl' : ''\n const [start, end] = range()\n const whole = start === 0 && end >= count() - 1\n const disabled = { in: end - start <= least(), out: whole, reset: whole }\n const labels = options().labels\n for (const [i, button] of [...controls.querySelectorAll('button')].entries()) {\n const [value, name] = BUTTONS[i] as (typeof BUTTONS)[number]\n button.setAttribute('aria-label', labels?.[value] ?? name)\n button.disabled = disabled[value]\n }\n }\n\n return {\n // The stylesheet leaves the page only the scroll across the\n // categories, so a finger can drag along them.\n svgAttrs: () => (on() ? { 'data-zoom-axis': plot()?.vertical ? 'y' : 'x' } : undefined),\n afterRender() {\n // (Other chart types have data of other shapes.)\n if (on()) drawn = range()\n // A render in the middle of a drag takes the rectangle out with the old content.\n if (selection) svg()?.append(selection)\n renderControls()\n },\n destroy() {\n host.removeEventListener('pointermove', onPointerMove, true)\n host.removeEventListener('click', onClickCapture, true)\n host.removeEventListener('keydown', onKey, true)\n host.removeEventListener('pointerdown', onPointerDown)\n host.removeEventListener('wheel', onWheel)\n host.removeEventListener('dblclick', onDoubleClick)\n doc.removeEventListener('pointerup', onPointerEnd)\n doc.removeEventListener('pointercancel', onPointerEnd)\n clearSelection()\n controls?.remove()\n if (controls && addedClass) host.classList.remove('tc-container')\n },\n }\n}\n","/**\n * Standalone entry: `import '@tabler/charts/zoom'` enables `view` (a range\n * of categories), `zoom: true` and `brush: true` in line, area, bar and\n * candlestick charts.\n * The default `Chart` then needs nothing else; on the core, add the plugin:\n *\n * ```ts\n * import { Chart, zoom } from '@tabler/charts/core'\n * import '@tabler/charts/zoom'\n * new Chart(el, { type: line, data, zoom: true, plugins: [zoom()] })\n * ```\n */\nimport { viewWindow } from './charts/view.ts'\nimport { register } from './features.ts'\nimport type { ChartPlugin } from './plugin.ts'\nimport { installBrush } from './plugins/brush.ts'\nimport { installZoom } from './plugins/zoom.ts'\n\n/** The zoom and the brush of a chart, as one plugin. */\nconst install: ChartPlugin['install'] = (chart) => {\n const parts = [installZoom(chart), installBrush(chart)]\n return {\n svgAttrs: (config) => parts[0]?.svgAttrs?.(config) ?? parts[1]?.svgAttrs?.(config),\n afterRender(state) {\n for (const part of parts) part.afterRender?.(state)\n },\n destroy() {\n for (const part of parts) part.destroy?.()\n },\n }\n}\n\nregister({ zoom: { window: viewWindow, install } })\n\nexport type { ViewWindow, Zoomable, ZoomOptions } from './charts/view.ts'\nexport { viewRange } from './charts/view.ts'\nexport { installBrush, installZoom, viewWindow }\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 * With both a single `x` and a single `y` it is a point: a dot at that\n * category and value, with its label beside it.\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 the point, 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 /**\n * The dashes of the line: dash and gap length in pixels, or a full\n * `stroke-dasharray` such as `'6 3'`; `0` draws it solid. Sets\n * `--tc-annotation-dash`. Defaults to `'4 3'`.\n */\n dash?: number | string\n /**\n * Draw the label on a background (the surface color), so it reads where\n * it crosses lines and points. Defaults to `false`.\n */\n labelBackground?: boolean\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 /** Where a point annotation (a single `x` and a single `y`) lands; `undefined` off the plot. */\n const pointOf = (a: Annotation): readonly [number, number] | undefined => {\n if (a.x === undefined || a.y === undefined || isPair(a.x) || isPair(a.y)) return undefined\n const along = categorySpan(scales, a.x)\n const v = scales.value(a.y)\n if (!along || !Number.isFinite(v)) return undefined\n const c = (along[0] + along[1]) / 2\n const [px, py] = horizontal ? [v, c] : [c, v]\n return inside(px, x0, x1) && inside(py, y0, y1) ? [px, py] : undefined\n }\n const isPoint = (a: Annotation) =>\n a.x !== undefined && a.y !== undefined && !isPair(a.x) && !isPair(a.y)\n const dots = annotations.map(pointOf)\n const shapes = annotations.map((a) => (isPoint(a) ? undefined : geometry(a)))\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 DOT = 4\n dots.forEach((p, i) => {\n if (p) obstacles.push([i, [p[0] - DOT, p[1] - DOT, p[0] + DOT, p[1] + DOT]])\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: [\n 'tc-annotation',\n isPoint(a)\n ? 'tc-annotation-point'\n : a.y !== undefined\n ? 'tc-annotation-y'\n : 'tc-annotation-x',\n a.class,\n ],\n style: {\n '--tc-annotation-color': a.color,\n '--tc-annotation-dash': Number.isFinite(a.dash) ? `${a.dash}px` : a.dash,\n },\n })\n /** The label at a spot ([left edge, baseline]), on its background when asked for. */\n const labelAt = (spot: [number, number], w: number): VNode[] => {\n const size = fontSize * 0.92\n const text = h(\n 'text',\n { class: 'tc-annotation-label', x: round(spot[0]), y: round(spot[1]) },\n a.label,\n )\n return a.labelBackground\n ? [\n h('rect', {\n class: 'tc-annotation-label-bg',\n x: round(spot[0] - 3),\n y: round(spot[1] - size),\n width: round(w + 6),\n height: round(size * 1.35),\n rx: 2,\n }),\n text,\n ]\n : [text]\n }\n const end = a.position !== 'start'\n\n const dot = dots[index]\n if (dot) {\n const [px, py] = dot\n let text: VNode[] | undefined\n if (a.label) {\n const w = estimateTextWidth(a.label, fontSize * 0.92)\n const off = DOT + pad\n const mid = py + fontSize * 0.35\n // Beside the dot, then above or below it, then at its corners.\n const spots: [number, number][] = [\n [px + off, mid],\n [px - off - w, mid],\n [px - w / 2, py - off],\n [px - w / 2, py + off + fontSize * 0.8],\n [px + off, py + off + fontSize * 0.8],\n [px + off, py - off],\n [px - off - w, py + off + fontSize * 0.8],\n [px - off - w, py - off],\n ]\n const box = ([x, y]: [number, number]): Box => [x, y - fontSize, x + w, y + fontSize * 0.25]\n const within = (s: [number, number]) => s[0] >= x0 && s[0] + w <= x1\n // A label with no room in the plot is left out: the dot stays.\n const spot =\n spots.find((s) => within(s) && clear(box(s), index)) ??\n spots.find((s) => within(s) && clearOfLabels(box(s)))\n if (spot) {\n placed.push(box(spot))\n text = labelAt(spot, w)\n }\n }\n lines.push(\n h(\n 'g',\n attrs(),\n h('circle', { class: 'tc-annotation-dot', cx: round(px), cy: round(py), r: DOT }),\n text,\n ),\n )\n return\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[] | 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 = labelAt(spot, w)\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","/**\n * End labels: each line named at its end, with its last value, in a column\n * past the edge of the plot. Labels of lines that end close together are\n * moved apart, and a thin line in the series color joins a moved label to\n * its point, so a chart reads without its legend.\n */\nimport type { RenderContext } from '../chart.ts'\nimport { formatDetail, formatNumber, type NumberFormat } from '../format.ts'\nimport { estimateTextWidth, insets, LINE_HEIGHT, type Rect, round } from '../layout.ts'\nimport type { Point } from '../shapes/path.ts'\nimport { h, type VNode } from '../vnode.ts'\nimport { type CartesianOptions, plottable, seriesAxes, seriesKey } from './cartesian.ts'\n\nexport interface EndLabelOptions {\n /** Format of the values. Defaults to the format of the series' value axis. */\n format?: NumberFormat\n /** Write the last value after the name. Defaults to `true`. */\n value?: boolean\n}\n\n/** The text of one label: the series (by index), its name and its last value. */\nexport interface EndLabelText {\n index: number\n key: string\n name: string\n value: string\n /** The series' own color, if it has one. */\n color?: string\n}\n\n/** Space between a point and its label (the joining line runs through it), and between name and value. */\nconst LEAD = 14\nconst GAP = 6\n\n/** The labels of a chart: one per visible series that has a value. */\nfunction endLabelTexts(\n options: CartesianOptions & { endLabels?: boolean | EndLabelOptions },\n ctx: RenderContext,\n): EndLabelText[] {\n const own: EndLabelOptions = typeof options.endLabels === 'object' ? options.endLabels : {}\n const axisOf = seriesAxes(options)\n return options.data.series.flatMap((series, index) => {\n const { axis } = axisOf(series)\n const last = series.values.filter((v) => plottable(v, axis)).pop()\n if (last == null || ctx.hidden.has(seriesKey(series))) return []\n const format = own.format\n ? formatNumber(own.format, ctx.locale)\n : formatDetail(axis.format, ctx.locale)\n return {\n index,\n key: seriesKey(series),\n name: series.name,\n value: own.value === false ? '' : format(last),\n color: series.color,\n }\n })\n}\n\nconst width = (label: EndLabelText, fontSize: number): number => {\n // The value is set in a heavier weight: a little wider than estimated.\n const value = label.value ? GAP + estimateTextWidth(label.value, fontSize) * 1.06 : 0\n return estimateTextWidth(label.name, fontSize) + value\n}\n\n/** Width the labels need beside the plot, in pixels (0 without labels). */\nconst endLabelRoom = (labels: readonly EndLabelText[], fontSize: number): number =>\n labels.length ? Math.ceil(LEAD + Math.max(...labels.map((label) => width(label, fontSize)))) : 0\n\n/**\n * The labels layer: every label beside the `point` its line ends at, on the\n * left of the plot when the lines run that way (`left`). `overhang` is what\n * the marks take beyond the plot's edge.\n */\nfunction endLabelLayer(\n labels: readonly (EndLabelText & { point: readonly [number, number] | null })[],\n area: Rect,\n left: boolean,\n fontSize: number,\n overhang: number,\n): VNode | null {\n const step = Math.ceil(fontSize * LINE_HEIGHT)\n const placed = labels\n .flatMap((label) => (label.point ? { ...label, point: label.point, y: label.point[1] } : []))\n .sort((a, b) => a.point[1] - b.point[1])\n if (!placed.length) return null\n // Top to bottom, each a line below the one before; then back up from the bottom of the plot.\n let floor = area.y\n for (const label of placed) {\n label.y = Math.max(label.y, floor)\n floor = label.y + step\n }\n let ceiling = Math.max(area.y + area.height, (placed[0]?.y ?? 0) + (placed.length - 1) * step)\n for (const label of placed.slice().reverse()) {\n label.y = Math.min(label.y, ceiling)\n ceiling = label.y - step\n }\n const sign = left ? -1 : 1\n const edge = left ? area.x - overhang : area.x + area.width + overhang\n const at = edge + sign * LEAD\n return h(\n 'g',\n { key: 'end-labels', class: 'tc-end-labels', 'aria-hidden': 'true' },\n placed.map((label) => {\n const [px, py] = label.point\n const moved = Math.abs(label.y - py) > 1\n return h(\n 'g',\n {\n key: label.key,\n class: ['tc-end-label', 'tc-series', `tc-series-${label.index + 1}`],\n // A map, so values from data cannot inject CSS (see normalizeStyle).\n style: { '--tc-series-color': label.color },\n },\n // From past the point's dot to just before the text.\n moved &&\n h('path', {\n class: 'tc-end-label-line',\n d: `M${round(px + sign * (overhang + 2))},${round(py)}L${round(at - sign * 3)},${round(label.y)}`,\n }),\n h(\n 'text',\n {\n class: 'tc-end-label-text',\n style: `transform:translate(${round(at)}px,${round(label.y)}px)`,\n 'text-anchor': left ? 'end' : 'start',\n dy: '0.35em',\n },\n left\n ? [\n label.value && h('tspan', { class: 'tc-end-label-value' }, label.value),\n h('tspan', { dx: label.value ? GAP : undefined }, label.name),\n ]\n : [\n label.name,\n label.value && h('tspan', { class: 'tc-end-label-value', dx: GAP }, label.value),\n ],\n ),\n )\n }),\n )\n}\n\ntype Options = CartesianOptions & { endLabels?: boolean | EndLabelOptions }\n\n/**\n * The end labels of a line chart: its `options` with room for the labels\n * beside the plot (on the side the lines end at), and the `layer` that\n * draws them once the points of every series (`null` for gaps) and the plot\n * area are known. `overhang` is what the marks take beyond the plot's edge.\n */\nexport function endLabels<O extends Options>(\n options: O,\n ctx: RenderContext,\n overhang: number,\n): { options: O; layer: (points: readonly (readonly Point[])[], area: Rect) => VNode | null } {\n const texts = endLabelTexts(options, ctx)\n const left = options.x?.reverse ?? ctx.rtl === true\n const side = left ? 'left' : 'right'\n const pad = insets(options.padding)\n return {\n options: {\n ...options,\n padding: { ...pad, [side]: pad[side] + endLabelRoom(texts, ctx.fontSize) },\n },\n layer: (points, area) =>\n endLabelLayer(\n texts.map((label) => ({\n ...label,\n point: (points[label.index] ?? []).filter((p) => p != null).pop() ?? null,\n })),\n area,\n left,\n ctx.fontSize,\n overhang,\n ),\n }\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","/**\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 (`markerClip`).\n */\nimport type { PostStep } from '../features.ts'\nimport { round } from '../layout.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/**\n * Inline style for the legend or tooltip swatch of slot `slot`: its marker as\n * a CSS shape (`--tc-shape`, a `clip-path`) in a box without rounded corners;\n * `undefined` for the slots that stay a circle.\n */\nexport function markerClip(slot: number): Record<string, string | number> | undefined {\n if (!SHAPES[slot]?.length) return undefined\n // In percent of the box: a radius of 35.7% keeps the largest shape (the star) inside.\n const points = markerPath(slot, 50, 50, 35.7).slice(1, -1).replace(/,/g, '% ').replace(/L/g, '%,')\n return {\n // The square is not cut from the swatch's box but set a little into it.\n '--tc-shape': slot === 1 ? 'inset(10% round 1px)' : `polygon(${points}%)`,\n '--tc-shape-radius': 0,\n }\n}\n\n/**\n * @deprecated Points are drawn in their shapes as the chart renders: this\n * step leaves the content as it is. It will be removed in the next major.\n */\nexport const shapesStep: PostStep = (_config, content) => content\n","/**\n * Slice labels: every slice of a pie or donut named beside the chart, with\n * its share, in a column on the side the slice is on. A thin line joins each\n * label to its slice; labels of neighboring slices are moved apart so none\n * overlap, and the pie gets smaller to leave them room.\n */\nimport { estimateTextWidth, LINE_HEIGHT, type Rect, round } from '../layout.ts'\nimport { h, type VNode } from '../vnode.ts'\n\nexport interface SliceLabelOptions {\n /** What follows the name: the slice's share of the whole (the default), its value, or nothing. */\n value?: 'share' | 'value' | false\n}\n\n/** One label: the slice (by key and color slot), its texts, and the angle of its middle. */\nexport interface SliceLabel {\n key: string\n index: number\n name: string\n /** Text after the name; empty for the name alone. */\n value: string\n /** Middle of the slice, in radians clockwise from 12 o'clock. */\n angle: number\n /** Size of the slice: when there is no room for every label, the smallest go first. */\n weight: number\n}\n\n/** How far past the slice a line bends, how far it then runs sideways, and the space before the text. */\nconst ELBOW = 12\nconst RUN = 12\nconst GAP = 6\n/** How far into the slice a line starts. */\nconst INSIDE = 6\n/** The smallest radius a pie is worth labelling at: below it the labels are left out. */\nconst MIN_RADIUS = 32\nconst SEPARATOR = ' — '\n\nconst textWidth = (label: SliceLabel, fontSize: number): number =>\n // The name is set in a heavier weight: a little wider than estimated.\n estimateTextWidth(label.name, fontSize) * 1.08 +\n (label.value ? estimateTextWidth(SEPARATOR + label.value, fontSize) : 0)\n\nconst onRight = (label: SliceLabel): boolean => Math.sin(label.angle) >= 0\n\n/**\n * The slice labels of a pie drawn in `area`: the smaller area left for the\n * pie itself, and the `layer` that draws the labels once its center and\n * radius are known. `null` when the chart is too small to label.\n */\nexport function sliceLabels(\n labels: readonly SliceLabel[],\n area: Rect,\n fontSize: number,\n): { area: Rect; layer: (cx: number, cy: number, radius: number) => VNode } | null {\n const step = Math.ceil(fontSize * LINE_HEIGHT)\n // A column holds a label per line of the chart's height: the smallest slices go without.\n const lines = Math.max(1, Math.floor(area.height / step))\n const sides = [false, true].map((right) =>\n labels\n .filter((label) => onRight(label) === right)\n .sort((a, b) => b.weight - a.weight)\n .slice(0, lines),\n ) as [SliceLabel[], SliceLabel[]]\n const room = sides.map((side) =>\n side.length\n ? Math.ceil(ELBOW + RUN + GAP + Math.max(...side.map((label) => textWidth(label, fontSize))))\n : 0,\n ) as [number, number]\n const above = ELBOW + Math.ceil(step / 2)\n const inner: Rect = {\n x: area.x + room[0],\n y: area.y + above,\n width: area.width - room[0] - room[1],\n height: area.height - above * 2,\n }\n if (Math.min(inner.width, inner.height) / 2 < MIN_RADIUS) return null\n\n return {\n area: inner,\n layer: (cx, cy, radius) =>\n h(\n 'g',\n { key: 'slice-labels', class: 'tc-slice-labels', 'aria-hidden': 'true' },\n sides.flatMap((side, s) => {\n const sign = s ? 1 : -1\n const placed = side\n .map((label) => ({ label, y: cy - Math.cos(label.angle) * (radius + ELBOW) }))\n .sort((a, b) => a.y - b.y)\n // Top to bottom, each a line below the one before; then back up from the bottom.\n let floor = area.y + step / 2\n for (const item of placed) {\n item.y = Math.max(item.y, floor)\n floor = item.y + step\n }\n let ceiling = area.y + area.height - step / 2\n for (const item of placed.slice().reverse()) {\n item.y = Math.min(item.y, ceiling)\n ceiling = item.y - step\n }\n const column = cx + sign * (radius + ELBOW + RUN)\n return placed.map(({ label, y }) => {\n const sin = Math.sin(label.angle)\n const cos = Math.cos(label.angle)\n const from = radius - INSIDE\n return h(\n 'g',\n {\n key: label.key,\n class: ['tc-slice-label', 'tc-series', `tc-series-${label.index + 1}`],\n },\n // From inside the slice out to the label's line, then along it to the text.\n h('path', {\n class: 'tc-slice-label-line',\n d: `M${round(cx + sin * from)},${round(cy - cos * from)}L${round(cx + sin * (radius + ELBOW))},${round(y)}H${round(column)}`,\n }),\n h(\n 'text',\n {\n class: 'tc-slice-label-text',\n style: `transform:translate(${round(column + sign * GAP)}px,${round(y)}px)`,\n 'text-anchor': s ? 'start' : 'end',\n dy: '0.35em',\n },\n h('tspan', { class: 'tc-slice-label-name' }, label.name),\n label.value && SEPARATOR + label.value,\n ),\n )\n })\n }),\n ),\n }\n}\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 // (They run down the pixels on a reversed range.)\n const down = range[1] < range[0]\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 !== down) a = mid + 1\n else b = mid\n }\n const prev = a - 1\n return prev >= 0 &&\n Math.abs(pixel - (positions[prev] as number)) < Math.abs((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. One\n * that would cover a mark of another series is left out too, unless\n * `overMarks` lets the labels of points lie over the bars they cross.\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 * Let the label of a point lie over a bar or a cell when it has no free\n * place (a line over bars): every point keeps its label. Labels still\n * never cover each other. Defaults to `false`.\n */\n overMarks?: boolean\n}\n\n/** Space between a mark and its label, and around labels. */\nconst GAP = 4\n\ninterface Placed {\n key: string\n series: number\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 `valueLabels` of each series: `true`, `false`, or anything else for the chart's. */\nconst own = (config: ChartConfig<object>): unknown[] => {\n const series = (config as { data?: { series?: unknown } }).data?.series\n return Array.isArray(series) ? series.map((s) => s?.valueLabels) : []\n}\n\n/** Whether a chart has labels: on the chart, or on one of its series. */\nconst wanted = (config: ChartConfig<object>): boolean =>\n !!config.valueLabels || own(config).includes(true)\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 // A series' own `valueLabels` wins over the chart's.\n const series = own(config)\n const isLabelled = (index: number): boolean => {\n const on = series[index]\n return typeof on === 'boolean' ? on : !!option\n }\n const items: [string, HitItem, Hit][] = []\n // Marks a label must not cover: every bar and cell but its own, labelled or not.\n const marks: Rect[] = []\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 (item.box) marks.push(item.box)\n if (!isLabelled(item.seriesIndex)) continue\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 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 series: item.seriesIndex,\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 // Sideways, bars grow to the right, or to the left in a right-to-left chart.\n const side = ctx.rtl ? -sign : sign\n candidates.push(\n horizontal ? at(item.x - side * 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 + side * 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 slim = (p: Placed): Rect => ({ ...p.box, x: p.box.x + 5, width: p.box.width - 10 })\n const fits = (p: Placed, over = false) =>\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 (over || !marks.some((mark) => mark !== box && overlaps(mark, slim(p))))\n // A free place first; with `overMarks`, a point's label may then lie over a bar.\n const spot =\n candidates.find((p) => fits(p)) ??\n (options.overMarks && !box && !pie ? candidates.find((p) => fits(p, true)) : undefined)\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: [\n 'tc-value-label',\n 'tc-series',\n `tc-series-${p.series + 1}`,\n p.inside && 'tc-value-label-inside',\n ],\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 interaction && wanted(config) ? [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/** Writes a coordinate pair, rounded to `precision` decimals. */\ntype XY = (x: number, y: number) => string\n\nfunction pair(precision: number): XY {\n const k = 10 ** Math.max(0, Math.min(12, Math.floor(precision)))\n const n = (value: number): number => Math.round(value * k) / k || 0\n return (x, y) => `${n(x)},${n(y)}`\n}\n\n/** Monotone tangents break on zero-length segments, so coincident points are dropped. */\nconst prepare = (input: readonly Pt[], curve: Curve): readonly Pt[] =>\n curve === 'monotone' ? dedupe(input) : input\n\n/**\n * Path commands through `points` with a curve. The first point is a move\n * when `move` is true, otherwise a line (continuing an existing subpath).\n */\nfunction emit(xy: XY, points: readonly Pt[], curve: Curve, move: boolean): string {\n const first = points[0]\n if (!first) return ''\n const start = (move ? 'M' : 'L') + xy(first[0], first[1])\n if (curve === 'monotone') return start + monotone(xy, points)\n const t = STEPS[curve]\n if (t !== undefined) return start + step(xy, points, t)\n let d = start\n for (let i = 1; i < points.length; i++) {\n const p = points[i] as Pt\n d += `L${xy(p[0], p[1])}`\n }\n return d\n}\n\n/** Where a step curve turns between two points, as a share of the way. */\nconst STEPS: Partial<Record<Curve, number>> = { step: 0.5, 'step-before': 0, 'step-after': 1 }\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(xy: XY, points: readonly Pt[], t: number): string {\n let d = ''\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) d += `L${xy(x0, y1)}L${xy(x1, y1)}`\n else if (t >= 1) d += `L${xy(x1, y0)}L${xy(x1, y1)}`\n else {\n const xm = x0 * (1 - t) + x1 * t\n d += `L${xy(xm, y0)}L${xy(xm, y1)}`\n // The next horizontal run continues from here, so only the last point is needed.\n if (i === points.length - 1) d += `L${xy(x1, y1)}`\n }\n }\n return d\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(xy: XY, points: readonly Pt[]): string {\n const n = points.length\n if (n < 2) return ''\n if (n === 2) {\n const p = points[1] as Pt\n return `L${xy(p[0], p[1])}`\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 let d = ''\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 d += `C${xy(x0 + dx, y0 + dx * (tangents[i - 1] as number))},${xy(\n x1 - dx,\n y1 - dx * (tangents[i] as number),\n )},${xy(x1, y1)}`\n }\n return d\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 xy = pair(precision)\n let d = ''\n for (const run of runs(points)) {\n const drawn = prepare(\n run.map((i) => points[i] as Pt),\n curve,\n )\n d += emit(xy, drawn, curve, true)\n if (drawn.length === 1) d += 'Z'\n }\n return 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 xy = pair(precision)\n let d = ''\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 d += emit(\n xy,\n prepare(\n run.map((i) => points[i] as Pt),\n curve,\n ),\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 d += `${emit(xy, prepare(bottom, back), back, false)}Z`\n }\n return 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' | 'csv'\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 /** Separator of the values in a CSV file. Defaults to `','`. */\n delimiter?: string\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> = {\n png: 'PNG',\n svg: 'SVG',\n jpeg: 'JPEG',\n webp: 'WebP',\n csv: 'CSV',\n}\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 (`'csv'` adds the data as a\n * CSV file). Shown with the `download` 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 // In the corner the chart starts from: the left one, right to left.\n el.dir = chart.rtl ? 'rtl' : ''\n host.classList.add('tc-container')\n if (!el.isConnected) host.appendChild(el)\n },\n destroy: remove,\n }\n },\n }\n}\n","import type { Highlight, Hit } from '../interaction.ts'\nimport { estimateTextWidth, LINE_HEIGHT, 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/** A halo around the hit, in the color of its series. */\nfunction halo(hit: Hit, mark: Extract<Highlight, { kind: 'halo' }>): VNode | undefined {\n const item = hit.items.find((i) => i.seriesIndex === hit.seriesIndex) ?? hit.items[0]\n return (\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 ?? 0)}px,${round(mark.y ?? 0)}px)`,\n }),\n )\n )\n}\n\n/**\n * Hover marks drawn below the series: the band behind the hovered category\n * (bars), a crosshair through it (point charts; a spoke in radars), or a\n * halo that asks to stay `under` the chart (sankey flows).\n */\nexport function hoverUnderlay(hit: Hit, crosshair = true): VNode {\n const { area, highlight: mark = { kind: 'crosshair' } } = hit\n const line = (x1: number, y1: number, x2: number, y2: number) =>\n crosshair &&\n h('line', { class: 'tc-crosshair', x1: round(x1), x2: round(x2), y1: round(y1), y2: round(y2) })\n return h(\n 'g',\n { class: 'tc-hover', 'aria-hidden': 'true' },\n mark.kind === 'halo'\n ? mark.under && halo(hit, mark)\n : mark.kind === 'band'\n ? h('rect', {\n class: 'tc-hover-band',\n x: round(mark.x),\n y: round(mark.y),\n width: round(mark.width),\n height: round(mark.height),\n })\n : mark.kind === 'spoke'\n ? line(mark.x1, mark.y1, mark.x2, mark.y2)\n : line(hit.x, area.y, hit.x, area.y + area.height),\n )\n}\n\n/**\n * Hover marks drawn above the series: a halo (pie slices), or an active dot\n * on every value of point charts (of the series' `shape`, if given);\n * `points: false` leaves the dots out.\n */\nexport function hoverOverlay(\n hit: Hit,\n radius = 4,\n shape?: (slot: number, x: number, y: number, r: number) => string,\n points = true,\n): VNode {\n const mark = hit.highlight\n return h(\n 'g',\n { class: 'tc-hover', 'aria-hidden': 'true' },\n mark?.kind === 'halo'\n ? !mark.under && halo(hit, mark)\n : points &&\n mark?.kind !== '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\n/**\n * The value under the pointer (`hit.cursor`): a line through it across the\n * plot and the value in a tag on the value axis, drawn above the axes. Nothing\n * for a hit without one (keyboard, charts without a value axis).\n */\nexport function hoverValue(hit: Hit, fontSize: number): VNode | undefined {\n const { cursor, area } = hit\n if (!cursor) return undefined\n const { position: at, side, inside } = cursor\n const right = area.x + area.width\n const bottom = area.y + area.height\n const padX = 4\n const w = estimateTextWidth(cursor.text, fontSize) + padX * 2\n const hgt = Math.round(fontSize * LINE_HEIGHT) + 2\n // Where the tick labels of the axis are, or just inside the plot when it is hidden.\n const gap = 8 - padX\n let x: number\n let y: number\n if (side === 'bottom') {\n x = Math.min(Math.max(at - w / 2, area.x), right - w)\n y = inside ? bottom - hgt - 2 : bottom + gap\n } else {\n y = Math.min(Math.max(at - hgt / 2, area.y - hgt / 2), bottom - hgt / 2)\n if (side === 'left') x = inside ? area.x + 2 : area.x - gap - w\n else x = inside ? right - w - 2 : right + gap\n }\n return h(\n 'g',\n { class: 'tc-hover tc-crosshair-value', 'aria-hidden': 'true' },\n h(\n 'line',\n side === 'bottom'\n ? {\n class: 'tc-crosshair',\n x1: round(at),\n x2: round(at),\n y1: round(area.y),\n y2: round(bottom),\n }\n : {\n class: 'tc-crosshair',\n x1: round(area.x),\n x2: round(right),\n y1: round(at),\n y2: round(at),\n },\n ),\n h('rect', {\n class: 'tc-crosshair-tag',\n x: round(x),\n y: round(y),\n width: round(w),\n height: hgt,\n rx: 3,\n }),\n h(\n 'text',\n {\n class: 'tc-crosshair-label',\n x: round(x + w / 2),\n y: round(y + hgt / 2),\n dy: '0.32em',\n 'text-anchor': 'middle',\n },\n cursor.text,\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, the zoom of a map) are not\n // the chart: 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,.tc-map-zoom')\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)\n el.addEventListener('pointerdown', onMove)\n el.addEventListener('pointerleave', onLeave)\n el.addEventListener('click', onClick)\n return () => {\n listening.delete(chart)\n el.removeEventListener('pointermove', onMove)\n el.removeEventListener('pointerdown', onMove)\n el.removeEventListener('pointerleave', onLeave)\n el.removeEventListener('click', onClick)\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 { cursorValue } from '../chart.ts'\nimport { markerShape } from '../charts/cartesian.ts'\nimport { hoverOverlay, hoverUnderlay, hoverValue } 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 * `activePoints: false` the crosshair; `crosshair: { value: true }` adds the\n * value under the pointer on the value axis.\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: [\n hoverOverlay(hit, 4, markerShape(config), config.activePoints !== false),\n cursorValue(config) && hoverValue(hit, chart.fontSize),\n ],\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 // Arrows follow the screen: categories from the right swap them.\n if (interaction.reversed && /^Arrow(L|R)/.test(key))\n key = key === 'ArrowLeft' ? 'ArrowRight' : 'ArrowLeft'\n // In a grid a column is `rows` categories away, and Up/Down walk a column.\n let column = interaction.rows ?? 1\n if (interaction.rows && /^Arrow(U|D)/.test(key)) {\n key = key === 'ArrowUp' ? 'ArrowLeft' : 'ArrowRight'\n column = 1\n }\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 + column), focused)\n return true\n case 'ArrowLeft':\n go(index === undefined ? last : Math.max(0, index - column), 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 { swatchShape } from '../features.ts'\nimport { legendContent } from '../legend.ts'\nimport type { ChartPlugin } from '../plugin.ts'\nimport { render } from '../render/dom.ts'\n\n/** The side a legend beside the chart takes in a right-to-left chart. */\nconst MIRROR: Record<string, string | undefined> = { left: 'right', right: 'left' }\n\n/**\n * Classes on the container of a legend beside the chart, and of one before\n * it. A class rather than `:has()` in the stylesheet: a selector such as\n * `:where(:has(> .tc-legend…))` matches any element, so the browser checks it\n * again on every change to the page (a hover, a tooltip), which stalls a page\n * of charts.\n */\nconst BESIDE = 'tc-legend-beside'\nconst START = 'tc-legend-start'\n\n/**\n * An HTML legend (`.tc-legend`) with toggle buttons, above, below or beside 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 host.classList.remove(BESIDE, START)\n }\n\n /** Whether the legend follows the SVG in the container (below it, or beside it at the end). */\n let after = false\n const side = () => {\n const position = el?.dataset.position\n return position === 'left' || position === 'right'\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 (after) {\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 /** Put the legend at `position`: beside the chart it comes first on the container's start side. */\n const put = (position: string) => {\n if (!el) return\n el.dataset.position = position\n after =\n position === 'bottom' ||\n (side() && (position === 'right') !== (getComputedStyle(host).direction === 'rtl'))\n place()\n // The container lays a legend beside the chart out in two columns (style.css).\n host.classList.toggle(BESIDE, side())\n host.classList.toggle(START, side() && !after)\n }\n\n /** Space between the chart and a legend beside it. */\n const gap = () => Number.parseFloat(getComputedStyle(host).columnGap) || 0\n\n return {\n beforeRender({ config, 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 // A right-to-left chart reads right to left, whatever the page around it.\n el.dir = chart.rtl ? 'rtl' : ''\n render(el, legendContent(legend.items, hidden, swatchShape(config)), adopt)\n adopt = null\n const { position } = legend\n const beside = position === 'auto' ? 'right' : position\n // Beside the chart, sides swap in a right-to-left chart.\n put((chart.rtl && MIRROR[beside]) || beside)\n // Beside the chart when it keeps two thirds of the container, else below it.\n if (position === 'auto' && (el.offsetWidth + gap()) * 3 > host.clientWidth) put('bottom')\n },\n // With its margin: the gap to the chart is taken from the container too.\n reservedHeight() {\n if (!el?.isConnected || side()) 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 reservedWidth() {\n return el?.isConnected && side() ? el.offsetWidth + gap() : 0\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, chartModel } 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>, 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 chartModel(config),\n { locale: config.locale, hidden, rtl: chart.rtl },\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 // After a legend below or beside (after) the chart.\n const after = host.querySelector(':scope > svg.tc-chart + .tc-legend') ?? 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, 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, hidden))\n } else {\n cancelIdle(key)\n update(config, hidden)\n }\n },\n destroy: remove,\n }\n },\n }\n}\n","import type { SwatchShape } from './features.ts'\nimport 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.highlight?.kind === 'spoke' && 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/**\n * Default tooltip content: the category title and one row per series\n * (`shape` gives their swatches the point shapes of their slots).\n */\nexport function tooltipContent(hit: Hit, options: TooltipOptions = {}, shape?: SwatchShape): 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, ...shape?.(item.seriesIndex) },\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 (the other way round with `rtl`), vertically centered on the\n * 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 rtl = false,\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 // The side read first, unless only the other one has room.\n const side = (rtl ? fitsLeft || !fitsRight : fitsLeft && !fitsRight) ? 'left' : 'right'\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 { swatchShape } from '../features.ts'\nimport 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\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 const { rtl } = chart\n tip.dir = rtl ? 'rtl' : ''\n render(tip, tooltipContent(hit, options, swatchShape(chart.config)))\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.highlight?.kind === 'spoke' ? 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 12,\n rtl,\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 { features } from '../features.ts'\nimport 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/**\n * Zoom along the categories of line, area, bar and candlestick charts,\n * behind `zoom: true`. The code comes with `import '@tabler/charts/zoom'`\n * (before the chart is created); without it the plugin does nothing.\n */\nexport const zoom = (): ChartPlugin => ({\n name: 'zoom',\n install: (chart) => features.zoom?.install(chart) ?? {},\n})\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(), zoom()]\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: HTMLElement | 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, RenderResult } 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 { h, type VNode } from '../vnode.ts'\nimport {\n type CartesianOptions,\n cartesianLayout,\n categoryInteraction,\n labelKey,\n markerShape,\n plottable,\n pointMark,\n resolveLabels,\n type Series,\n seriesAttrs,\n seriesAxes,\n seriesKey,\n seriesLegend,\n seriesScale,\n seriesTable,\n windowed,\n} from './cartesian.ts'\nimport { cleanData, cleanSeries } from './clean.ts'\nimport type { EndLabelOptions } from './end-labels.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 * Name each line at its end: the series name and its last value beside the\n * last point, past the edge of the plot, moved apart where lines end close\n * together (a thin line then joins a label to its point). Needs\n * `@tabler/charts/end-labels` on the core. Defaults to `false`.\n */\n endLabels?: boolean | EndLabelOptions\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): RenderResult {\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 axisOf = seriesAxes(options)\n // Series on the second axis keep out of the stacks.\n const seconds = series.filter((s) => axisOf(s).second).map(seriesKey)\n const stacks = stacked\n ? stackSeries(series, count, {\n percent: stacked === 'percent',\n nullAsZero: true,\n hidden: seconds.length ? new Set([...ctx.hidden, ...seconds]) : ctx.hidden,\n })\n : null\n // End labels stand past the end of the lines: the plot leaves them room there.\n const ends = options.endLabels ? feature('end-labels')(options, ctx, overhang) : null\n const layout = cartesianLayout(ends?.options ?? options, ctx, {\n scale: 'point',\n zero: filled || stacks !== null,\n zero2: filled,\n overhang,\n ...(stacks ? { values: stackBounds(stacks) } : {}),\n ...(stacked === 'percent' ? { tickFormat: { style: 'percent' } } : {}),\n })\n const { x, labels } = layout\n const scaleOf = (index: number) => seriesScale(layout, series[index])\n // Areas grow from zero, or from the bottom of the plot when zero is out of view.\n const baselineOf = (index: number) => {\n const y = scaleOf(index)\n return y(Math.min(Math.max(0, y.domain[0]), y.domain[1]))\n }\n // (series left out of the stacks have empty rows there)\n const stackOf = (index: number) => (!axisOf(series[index]).second && stacks?.[index]) || null\n const interaction = categoryInteraction(layout, options, ctx, (seriesIndex, i, v) => {\n const stack = stackOf(seriesIndex)\n return { x: x.at(i), y: scaleOf(seriesIndex)(stack ? (stack[i]?.y1 ?? 0) : v) }\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 const y = scaleOf(index)\n // Stacked series draw their running total.\n const stack = stackOf(index)\n if (stack) return stack.map((seg, i): Point => (seg ? [x.at(i), y(seg.y1)] : null))\n const axis = axisOf(s).axis\n return seriesPoints(\n s,\n labels.length,\n (i) => x.at(i),\n y,\n connectNulls,\n (v) => plottable(v, axis),\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 = stackOf(index)\n if (!stack) return baselineOf(index)\n const y = scaleOf(index)\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 shape = markerShape(options)\n const keys = labels.map(labelKey)\n /** Clip paths that cut the lines with `dashFrom` in two. */\n const cuts: VNode[] = []\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 const d = linePath(pts, { curve })\n // The same path twice, each clipped to its side of the label: the curve stays whole.\n const from = s.dashFrom == null ? -1 : keys.indexOf(labelKey(s.dashFrom))\n const cut = from > 0 && from < keys.length - 1\n const { dash = '5 4' } = s\n if (cut) {\n const at = round(x.at(from))\n // Everything on one side of the label, far beyond the plot.\n const side = (part: string, before: boolean) =>\n h(\n 'clipPath',\n { key: `${part}-${seriesKey(s)}`, id: `${ctx.id}-${part}-${index}` },\n h('rect', { x: before ? at - 1e5 : at, y: -1e5, width: 1e5, height: 2e5 }),\n )\n const forward = x.at(0) <= at\n cuts.push(side('solid', forward), side('dashed', !forward))\n }\n return h(\n 'g',\n seriesAttrs(cut ? { ...s, dash: undefined } : s, index),\n h('path', {\n key: 'line',\n class: 'tc-line',\n d,\n 'clip-path': cut ? `url(#${ctx.id}-solid-${index})` : undefined,\n }),\n cut &&\n h('path', {\n key: 'dashed',\n class: 'tc-line tc-line-dashed',\n d,\n 'clip-path': `url(#${ctx.id}-dashed-${index})`,\n // A map, so values from data cannot inject CSS (see normalizeStyle).\n style: { '--tc-series-dash': Number.isFinite(dash) ? `${dash}px` : dash },\n }),\n dots.length > 0 &&\n h(\n 'g',\n { class: 'tc-points' },\n dots.map(([cx, cy]) =>\n pointMark(shape, index, cx, 'tc-point', round(cx), round(cy), pointRadius),\n ),\n ),\n )\n })\n\n const content = [\n h('defs', { key: 'defs' }, layout.clip.def, gradient && fadeMask(fadeId), cuts),\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 // Where each line ends: its last point (the running total in a stack).\n ends?.layer(all, layout.area),\n ]\n return { content, interaction }\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 prepare: windowed,\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, windowed } 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 prepare: windowed,\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, axisTitleSize, bandTicks, type Tick, thinTicks } from '../components/axis.ts'\nimport { estimateTextWidth, plotFrame } 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 } = ctx\n const overhang = layout.overhang ?? 0\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 { area, side, range } = plotFrame(ctx, options.padding, (pad) => ({\n top: pad.top + Math.max(overhang, EDGE / 2),\n bottom:\n pad.bottom +\n Math.max(\n (showValues ? axisSize('bottom', probeValues, fontSize) : 0) +\n axisTitleSize(yOptions.title, fontSize),\n overhang,\n EDGE / 2,\n ),\n start:\n pad.start +\n Math.max(\n (showCategories ? axisSize('left', probeCategories, fontSize) : 0) +\n axisTitleSize(xOptions.title, fontSize),\n edgeLabel(probeValues[0]),\n overhang,\n EDGE,\n ),\n end: pad.end + Math.max(edgeLabel(probeValues[probeValues.length - 1]), overhang, EDGE),\n }))\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 // Values grow away from the categories, from the start side.\n const y = value.scale(range())\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 side,\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 seriesAxes,\n seriesKey,\n seriesLegend,\n seriesScale,\n seriesTable,\n windowed,\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 prepare: windowed,\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 axisOf = seriesAxes(options)\n const onY2 = (index: number) => axisOf(series[index]).second\n // Bars on the second axis stand beside the stack, in a column of their own.\n const apart = series.filter((_, index) => isLine(index) || onY2(index)).map(seriesKey)\n const stackHidden = apart.length ? new Set([...ctx.hidden, ...apart]) : ctx.hidden\n const stacks = stacked\n ? stackSeries(series, count, { percent: stacked === 'percent', hidden: stackHidden })\n : null\n const inStack = (index: number) => !!stacks && !isLine(index) && !onY2(index)\n\n const layoutOptions: CartesianLayoutOptions = {\n scale: 'band',\n zero: true,\n paddingInner: groupPadding,\n paddingOuter: groupPadding / 2,\n // Bars and areas on the second axis grow from zero too, lines need not.\n zero2: series.some((s, index) => onY2(index) && s.type !== 'line'),\n ...(stacks\n ? {\n values: [\n ...stackBounds(stacks),\n ...series.flatMap((s, index) => (isLine(index) && !onY2(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, labels } = layout\n const scaleOf = (index: number) => seriesScale(layout, series[index])\n\n // The column of each bar series in its group: a stack takes one column\n // for all its series. Hidden series keep their color slot but give up their place.\n const slots = new Map<number, number>()\n let used = 0\n let stackColumn = -1\n series.forEach((s, index) => {\n if (ctx.hidden.has(seriesKey(s)) || isLine(index)) return\n if (!inStack(index)) slots.set(index, used++)\n else {\n if (stackColumn < 0) stackColumn = used++\n slots.set(index, stackColumn)\n }\n })\n const order = [...slots.keys()]\n const columns = Math.max(1, used)\n\n const barWidth = Math.max(\n 0,\n Math.min(maxBarWidth, (x.bandwidth - gap * (columns - 1)) / columns),\n )\n const groupWidth = barWidth * columns + gap * (columns - 1)\n const offset = (x.bandwidth - groupWidth) / 2\n // Grouped bars follow the categories: from the right when those are reversed.\n const slotAt = (slot: number) => (x.range[1] < x.range[0] ? columns - 1 - slot : slot)\n const barLeft = (seriesIndex: number, i: number) =>\n x.at(i) + offset + slotAt(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 (inStack(seriesIndex)) return stacks?.[seriesIndex]?.[i] ?? null\n const s = series[seriesIndex]\n const v = s?.values[i]\n return plottable(v, axisOf(s).axis) ? { 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 if (!inStack(index)) continue\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 const interaction = categoryInteraction(\n layout,\n options,\n ctx,\n (seriesIndex, i, v) => {\n const y = scaleOf(seriesIndex)\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 // The column under the pointer, gaps included, so thin bars are easy to hit.\n const column = slotAt(\n Math.floor((across - (x.at(i) + offset) + gap / 2) / (barWidth + gap)),\n )\n if (column === stackColumn) {\n // The segment under the pointer, within the stack (gaps included).\n return order.find((index) => {\n if (!inStack(index)) return false\n const seg = segment(index, i)\n if (!seg) return false\n const y = scaleOf(index)\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 const seriesIndex = order.find((index) => slots.get(index) === column)\n return seriesIndex !== undefined && segment(seriesIndex, i) ? seriesIndex : undefined\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 y = scaleOf(index)\n const negative = seg.y1 < seg.y0\n // Leave a surface-colored gap where this segment sits on another one,\n // on the side it grows to (in pixels: up, right, or left when mirrored).\n const away = Math.sign(y(seg.y1) - y(seg.y0))\n const inner = seg.y0 === 0 ? 0 : away * gap\n const rounded = !inStack(index) || (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 lines = series.map((s, index) => {\n if (!paths) return null\n if (!isLine(index) || ctx.hidden.has(seriesKey(s))) return null\n const y = scaleOf(index)\n const axis = axisOf(s).axis\n const baseline = y(Math.min(Math.max(0, y.domain[0]), y.domain[1]))\n const points = labels.map((_, i): Point => {\n const v = s.values[i]\n if (!plottable(v, axis)) 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 const content = [\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 return { content, interaction }\n },\n legend: (options) => seriesLegend(options.data),\n table: (options, ctx, limit) => seriesTable(options, ctx, limit),\n}\n","import { round } from '../layout.ts'\n\n/** A rounded rectangle as path data (the hover ring of a cell or a tile). */\nexport function rectPath(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","import type { ChartType, DataTable, LegendItem, RenderContext } from '../chart.ts'\nimport { axis, axisSize, type Tick, thinTicks } from '../components/axis.ts'\nimport { type DateFormat, formatDate, formatNumber, 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 { rectPath } from '../shapes/rect.ts'\nimport { type ClassValue, h, type StyleValue, type VNode } from '../vnode.ts'\nimport { cleanData, finite, isRecord, named, records } from './clean.ts'\nimport { keyOf, legendItems } from './named.ts'\n\n/** One day's value. Several entries on the same day add up. */\nexport interface CalendarEntry {\n /** The day: a `Date`, a timestamp, or anything `new Date()` reads (`'2026-10-26'`). */\n date: Date | string | number\n /** `null` leaves the day empty (drawn faded, like a day without data). */\n value: number | null\n}\n\n/** A kind of activity (commits, reviews …), with its own legend entry. */\nexport interface CalendarSeries {\n name: string\n values: readonly CalendarEntry[]\n /** Stable identity for keyed updates. Defaults to `name`. */\n id?: string\n /**\n * Custom color of the legend and tooltip swatch. Values that could inject\n * CSS (`;`, quotes, `url()` …) are ignored, so colors from user data are safe.\n */\n color?: string\n /** Extra classes on the legend entry. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface CalendarData {\n series: readonly CalendarSeries[]\n}\n\nexport interface CalendarOptions {\n /** Days and their values, as one list or as several series that add up (the legend filters them). */\n data: CalendarData | readonly CalendarEntry[]\n /** First day shown (at most ten years before `to`). Defaults to the first day in the data, or the start of the `weeks` window. */\n from?: Date | string | number\n /** Last day shown. Defaults to the last day in the data. */\n to?: Date | string | number\n /** Number of week columns ending with the week of `to`, when `from` is not set (e.g. `12`). */\n weeks?: number\n /** First day of the week: `0` Sunday … `6` Saturday. Defaults to `1` (Monday). */\n weekStart?: number\n /** Read the dates in UTC instead of local time. */\n utc?: boolean\n /** Value shown as empty. Defaults to the smaller of `0` and the data minimum. */\n min?: number\n /** Value shown with the full color. Defaults to the data maximum. */\n max?: number\n /** Number of shades between empty and the full color (the steps of the scale). Defaults to `4`. */\n levels?: number\n /**\n * A scale through two or more colors (any CSS color, including\n * `var(--tc-…)`) from `min` to `max` in `levels` steps, instead of one hue.\n * `'diverging'` is two hues around a neutral middle, for values with a sign\n * (changes, balances): the middle sits on `mid`, `0` by default, and the\n * two ends are equally far from it unless `min` or `max` is set.\n * Values that could inject CSS are ignored, as for series colors.\n */\n colors?: 'diverging' | readonly string[]\n /** Value placed on the middle color of `colors`. Defaults to `0` for `'diverging'`, else halfway. */\n mid?: number\n /** Space between cells in pixels, drawn as surface. Defaults to `2`. */\n gap?: number\n /** Corner radius of the cells. Defaults to `2`. */\n radius?: number\n /** Format of the values (tooltip, table). */\n format?: NumberFormat\n /** Format of the day in the tooltip and the table. Defaults to e.g. \"Oct 26, 2026\". */\n dateFormat?: DateFormat\n /** Month names above the columns where a month begins. */\n x?: { show?: boolean; format?: (date: Date) => string }\n /** Weekday names on the left. */\n y?: { show?: boolean; format?: (date: Date) => string }\n /**\n * The low-to-high scale below the grid: `false` hides it, an object names\n * its ends (defaults `'Less'` and `'More'`; with `colors`, the values at the ends).\n */\n scale?: boolean | { low?: string; high?: string }\n /** Extra space around the grid, in pixels. */\n padding?: InsetsInput\n}\n\nconst DAY = 86_400_000\n/** `colors: 'diverging'`: two hues around a neutral middle. */\nconst DIVERGING = ['var(--tc-color-1)', 'var(--tc-grid-color)', 'var(--tc-color-8)']\nconst MONDAY = 1\n/** Most days drawn (ten years): a range from junk dates stays finite. */\nconst MAX_DAYS = 3660\n\n/** A timestamp from a date value, or `null` for anything that is not a date. */\nconst stamp = (v: unknown): number | null =>\n typeof v === 'string' || typeof v === 'number' || v instanceof Date\n ? finite(new Date(v as string | number | Date).getTime())\n : null\n\n/** Days since the epoch of the calendar day `ms` falls in, in UTC or local time. */\nconst dayOf = (ms: number, utc: boolean): number => {\n const d = new Date(ms)\n return Math.floor((utc ? ms : Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())) / DAY)\n}\n\n/** The calendar day as a date at UTC midnight (format it with `timeZone: 'UTC'`). */\nconst dateOf = (day: number): Date => new Date(day * DAY)\n\n/** Weekday of a day number, `0` Sunday … `6` Saturday (day 0 was a Thursday). */\nconst weekday = (day: number): number => (((day + 4) % 7) + 7) % 7\n\n/** Series of the data, which may be one plain list of entries. */\nconst seriesOf = (data: CalendarOptions['data']): readonly CalendarSeries[] =>\n Array.isArray(data)\n ? [{ name: '', values: data as readonly CalendarEntry[] }]\n : (data as CalendarData).series\n\n/** Series with their entries as `[day, value]`, every date valid. */\nconst cleanCalendar = (data: unknown): unknown => {\n const d = Array.isArray(data)\n ? { series: [{ name: '', values: data }] }\n : isRecord(data)\n ? data\n : {}\n return {\n ...d,\n series: records(d.series, (s) => ({\n ...named(s),\n values: records(s.values, (e) => ({ date: stamp(e.date), value: finite(e.value) })).filter(\n (e) => e.date !== null,\n ),\n })),\n }\n}\n\n/** A stretch of the range drawn as one grid of weeks: the whole range, or twelve months of it. */\ninterface Band {\n /** First and last day drawn. */\n start: number\n end: number\n /** The day in the top left corner: the start of `start`'s week. */\n gridStart: number\n columns: number\n}\n\ninterface Range {\n /** First day drawn, and how many days from it. */\n from: number\n count: number\n bands: Band[]\n /** Columns of the widest band. */\n columns: number\n /** First day of the week, `0` Sunday … `6` Saturday. */\n weekStart: number\n /** Row of a day: its weekday counted from `weekStart`. */\n row(day: number): number\n}\n\n/**\n * The days drawn: `from` … `to`, else the data (every series, so hiding one\n * keeps the grid). More than a year (and than 53 weeks) is split into bands\n * of twelve months from the first month, so a fiscal year from April is one band.\n */\nfunction rangeOf(options: CalendarOptions): Range {\n const utc = options.utc === true\n const weekStart = ((Math.floor(finite(options.weekStart) ?? MONDAY) % 7) + 7) % 7\n const row = (day: number) => (weekday(day) - weekStart + 7) % 7\n let first = Number.POSITIVE_INFINITY\n let last = Number.NEGATIVE_INFINITY\n for (const s of seriesOf(options.data))\n for (const e of s.values) {\n const ms = stamp(e.date)\n if (ms === null) continue\n const day = dayOf(ms, utc)\n if (day < first) first = day\n if (day > last) last = day\n }\n const toMs = stamp(options.to)\n const fromMs = stamp(options.from)\n const to = toMs !== null ? dayOf(toMs, utc) : last\n const weeks = finite(options.weeks)\n let from =\n fromMs !== null\n ? dayOf(fromMs, utc)\n : weeks !== null && weeks > 0 && Number.isFinite(to)\n ? to - row(to) - (Math.min(MAX_DAYS / 7, Math.floor(weeks)) - 1) * 7\n : first\n if (to - from >= MAX_DAYS) from = to - MAX_DAYS + 1\n const count = Number.isFinite(from) && Number.isFinite(to) && to >= from ? to - from + 1 : 0\n const bands: Band[] = []\n if (count) {\n const d = dateOf(from)\n const y = d.getUTCFullYear()\n const m = d.getUTCMonth()\n /** The first day of the month `months` after the range's first month. */\n const monthStart = (months: number) => Math.floor(Date.UTC(y, m + months, 1) / DAY)\n // A year or less (up to the same date a year on) is one band, and so are\n // 53 weeks: the last year of a contribution graph.\n const single =\n to < Math.floor(Date.UTC(y + 1, m, d.getUTCDate()) / DAY) ||\n to + (6 - row(to)) - (from - row(from)) < 53 * 7\n for (let start = from, k = 1; start <= to; k++) {\n const end = single ? to : Math.min(to, monthStart(k * 12) - 1)\n const gridStart = start - row(start)\n bands.push({ start, end, gridStart, columns: (end + (6 - row(end)) - gridStart + 1) / 7 })\n start = end + 1\n }\n }\n return {\n from,\n count,\n bands,\n columns: bands.reduce((max, band) => Math.max(max, band.columns), 0),\n weekStart,\n row,\n }\n}\n\n/** Space between two bands, in pixels. */\nconst BAND_GAP = 10\n\nfunction renderCalendar(options: CalendarOptions, ctx: RenderContext) {\n const { width, height, fontSize, locale } = ctx\n const { radius = 2, utc = false } = options\n const levels = Math.min(64, Math.max(1, Math.floor(finite(options.levels) ?? 4)))\n const series = seriesOf(options.data)\n const visible = series.filter((s) => !ctx.hidden.has(keyOf(s)))\n const value = formatNumber(options.format, locale)\n const dates = { timeZone: 'UTC' as const }\n const title = formatDate(\n options.dateFormat ?? { year: 'numeric', month: 'short', day: 'numeric', ...dates },\n locale,\n )\n const month = options.x?.format ?? formatDate({ month: 'short', ...dates }, locale)\n const dayName = options.y?.format ?? formatDate({ weekday: 'short', ...dates }, locale)\n const year = formatDate({ year: 'numeric', ...dates }, locale)\n const shortYear = formatDate({ year: '2-digit', ...dates }, locale)\n\n // Values by day, per series and in total (the shade), over the visible series.\n const totals = new Map<number, number | null>()\n const byDay = visible.map((s) => {\n const days = new Map<number, number | null>()\n for (const e of s.values) {\n const ms = stamp(e.date)\n if (ms === null) continue\n const day = dayOf(ms, utc)\n const v = finite(e.value)\n days.set(day, v === null ? (days.get(day) ?? null) : (days.get(day) ?? 0) + v)\n totals.set(day, v === null ? (totals.get(day) ?? null) : (totals.get(day) ?? 0) + v)\n }\n return days\n })\n\n const { from, count, bands, columns, weekStart, row } = rangeOf(options)\n\n // Shades: `levels` steps from empty (at or below `min`) to the full color (at `max`).\n let dataMin = 0\n let dataMax = 0\n for (const v of totals.values()) {\n if (v === null) continue\n if (v < dataMin) dataMin = v\n if (v > dataMax) dataMax = v\n }\n let lo = finite(options.min) ?? dataMin\n let hi = Math.max(finite(options.max) ?? dataMax, lo)\n // A color scale instead of one hue: `levels` steps through its colors.\n const diverging = options.colors === 'diverging'\n const stops = diverging\n ? DIVERGING\n : Array.isArray(options.colors) && options.colors.length >= 2\n ? (options.colors as readonly string[])\n : undefined\n const mid = finite(options.mid) ?? (diverging ? 0 : null)\n if (diverging && mid !== null) {\n // The ends are equally far from the middle, so both hues mean the same distance.\n const reach = Math.max(hi - mid, mid - lo)\n if (finite(options.min) === null) lo = mid - reach\n if (finite(options.max) === null) hi = mid + reach\n }\n /** Position of a value on the scale, 0…1 (through `mid` when it lies inside). */\n const position = (v: number) => {\n const t =\n stops && mid !== null && lo < mid && mid < hi\n ? v <= mid\n ? ((v - lo) / (mid - lo)) * 0.5\n : 0.5 + ((v - mid) / (hi - mid)) * 0.5\n : hi > lo\n ? (v - lo) / (hi - lo)\n : v > lo\n ? 1\n : 0\n return Math.min(1, Math.max(0, t))\n }\n const level = (v: number) =>\n stops\n ? Math.round(position(v) * levels)\n : v <= lo\n ? 0\n : Math.min(levels, Math.ceil(position(v) * levels) || levels)\n const shade = (step: number): StyleValue => {\n if (!stops) return `--tc-heat:${round((step / levels) * 100)}%`\n const at = (step / levels) * (stops.length - 1)\n const k = Math.min(stops.length - 2, Math.floor(at))\n const u = round((at - k) * 100)\n return {\n '--tc-cell-fill':\n u <= 0\n ? stops[k]\n : u >= 100\n ? stops[k + 1]\n : `color-mix(in oklab,${stops[k + 1]} ${u}%,${stops[k]})`,\n }\n }\n\n // Margins: weekday names on the left, months on top, the scale below.\n const pad = insets(options.padding, 0)\n const showX = options.x?.show !== false && count > 0\n const showY = options.y?.show !== false && count > 0\n const scale = options.scale !== false && count > 0\n const scaleText = typeof options.scale === 'object' ? options.scale : {}\n const low = scaleText.low ?? (stops ? value(lo) : 'Less')\n const high = scaleText.high ?? (stops ? value(hi) : 'More')\n // Day 3 (4 January 1970) was a Sunday: the row's weekday, on a date of that weekday.\n const rowLabels = Array.from({ length: 7 }, (_, r) => dayName(dateOf(3 + ((weekStart + r) % 7))))\n const left = showY\n ? axisSize(\n 'left',\n rowLabels.map((label, r) => ({ value: r, position: 0, label })),\n fontSize,\n )\n : 0\n const top = showX ? axisSize('top', [{ value: 0, position: 0, label: 'M' }], fontSize) : 0\n // Bands are named by their years, in the corner over the weekday names.\n const multi = bands.length > 1\n const bandLabels = bands.map((band) => {\n const a = dateOf(band.start)\n const b = dateOf(band.end)\n return a.getUTCFullYear() === b.getUTCFullYear() ? year(a) : `${year(a)}–${shortYear(b)}`\n })\n const named = multi && showX\n const yearWidth = named\n ? Math.ceil(bandLabels.reduce((max, l) => Math.max(max, estimateTextWidth(l, fontSize)), 0)) + 8\n : 0\n const scaleHeight = scale ? Math.ceil(fontSize * LINE_HEIGHT) + 6 : 0\n const area = innerRect(width, height, {\n top: pad.top,\n right: pad.right,\n bottom: pad.bottom + scaleHeight,\n left: pad.left + Math.max(left, yearWidth),\n })\n // Square cells, as large as the columns and the seven rows of every band allow.\n const n = bands.length\n const room = area.height - n * top - (n - 1) * BAND_GAP\n const step = columns ? Math.max(0, Math.min(area.width / columns, room / (7 * n))) : 0\n // (On a phone the days are a few pixels: the gap is at most a quarter of one.)\n const gap = Math.max(0, Math.min(finite(options.gap) ?? 2, step / 4))\n const cell = Math.max(0, step - gap)\n /** Top of the cells of band `k`, below its month names. */\n const bandY = (k: number) => area.y + k * (top + step * 7 + BAND_GAP) + top\n const cellX = (c: number) => area.x + c * step + gap / 2\n const grid = {\n x: area.x,\n y: area.y,\n width: step * columns,\n height: n ? bandY(n - 1) + step * 7 - area.y : 0,\n }\n /** Band, column and row of a day of the range. */\n const place = (day: number) => {\n const k = Math.max(\n 0,\n bands.findIndex((band) => day <= band.end),\n )\n const c = Math.floor((day - (bands[k] as Band).gridStart) / 7)\n return { x: cellX(c), y: bandY(k) + row(day) * step + gap / 2 }\n }\n\n const hitAt = (i: number, seriesIndex?: number): Hit | null => {\n if (i < 0 || i >= count) return null\n const day = from + i\n const at = place(day)\n const x = at.x + cell / 2\n const y = at.y + cell / 2\n const box = { x: at.x, y: at.y, width: cell, height: cell }\n const items: HitItem[] = visible.map((s, k) => {\n const v = byDay[k]?.get(day) ?? null\n return {\n name: s.name,\n seriesIndex: series.indexOf(s),\n value: v,\n text: v === null ? '–' : value(v),\n x,\n y,\n box,\n color: s.color,\n }\n })\n return {\n index: i,\n label: dateOf(day).toISOString().slice(0, 10),\n title: title(dateOf(day)),\n x,\n area: grid,\n items,\n seriesIndex,\n highlight: {\n kind: 'halo',\n d: rectPath(box.x - 2, box.y - 2, cell + 4, cell + 4, radius + 2),\n },\n }\n }\n\n const interaction: Interaction = {\n count,\n // Arrow keys walk the grid: left and right by a week, up and down by a day.\n rows: 7,\n hitIndex: hitAt,\n hitTest(px, py) {\n if (!step || px < grid.x) return null\n const c = Math.floor((px - grid.x) / step)\n for (let k = 0; k < n; k++) {\n const band = bands[k] as Band\n const r = Math.floor((py - bandY(k)) / step)\n if (py < bandY(k) || r > 6 || c >= band.columns) continue\n const day = band.gridStart + c * 7 + r\n return day < band.start || day > band.end ? null : hitAt(day - from)\n }\n return null\n },\n }\n\n const cells: VNode[] = []\n for (let day = from; day < from + count; day++) {\n const v = totals.get(day) ?? null\n const at = place(day)\n cells.push(\n h('rect', {\n key: day,\n class: ['tc-cell', v === null && 'tc-cell-empty'],\n x: round(at.x),\n y: round(at.y),\n width: round(cell),\n height: round(cell),\n rx: round(Math.min(radius, cell / 2)),\n style: v === null ? undefined : shade(level(v)),\n }),\n )\n }\n\n // A month is named over the first column whose week starts in it (the\n // first column by the band's first day, which may be later in its week).\n const axes = bands.map((band, k) => {\n const months: Tick[] = []\n for (let c = 0; c < band.columns; c++) {\n const start = Math.max(band.start, band.gridStart + c * 7)\n const m = dateOf(start).getUTCMonth()\n if (c === 0 || m !== dateOf(Math.max(band.start, start - 7)).getUTCMonth()) {\n months.push({\n value: start,\n position: area.x + c * step + step / 2,\n label: month(dateOf(start)),\n })\n }\n }\n const weekdays: Tick[] = rowLabels.map((label, r) => ({\n value: r,\n position: bandY(k) + r * step + step / 2,\n label,\n }))\n const rect = { x: area.x, y: bandY(k), width: step * band.columns, height: step * 7 }\n return h(\n 'g',\n { key: `band-${band.start}`, class: 'tc-calendar-band' },\n showX && axis({ position: 'top', ticks: thinTicks(months, 'top', fontSize), area: rect }),\n showY && axis({ position: 'left', ticks: thinTicks(weekdays, 'left', fontSize), area: rect }),\n named &&\n h(\n 'text',\n {\n class: 'tc-tick-label tc-calendar-year',\n x: round(area.x - 8),\n y: round(bandY(k) - 8),\n 'text-anchor': 'end',\n 'aria-hidden': 'true',\n },\n bandLabels[k],\n ),\n )\n })\n\n // The scale, right-aligned below the grid: \"Less\", one swatch per shade, \"More\".\n const swatch = Math.min(cell, fontSize)\n const scaleY = grid.y + grid.height + 6 + swatch / 2\n const lowWidth = estimateTextWidth(low, fontSize)\n const highWidth = estimateTextWidth(high, fontSize)\n const swatches = levels + 1\n const scaleWidth = lowWidth + 6 + swatches * (swatch + gap) + 6 + highWidth\n const scaleX = Math.max(area.x, area.x + grid.width - scaleWidth)\n\n const content = [\n h('g', { key: 'cells', class: 'tc-calendar-cells' }, cells),\n axes,\n scale &&\n h(\n 'g',\n { key: 'scale', class: 'tc-calendar-scale', 'aria-hidden': 'true' },\n h(\n 'text',\n { class: 'tc-tick-label', x: round(scaleX), y: round(scaleY), dy: '0.32em' },\n low,\n ),\n Array.from({ length: swatches }, (_, k) =>\n h('rect', {\n key: k,\n class: 'tc-cell',\n x: round(scaleX + lowWidth + 6 + k * (swatch + gap)),\n y: round(scaleY - swatch / 2),\n width: round(swatch),\n height: round(swatch),\n rx: round(Math.min(radius, swatch / 2)),\n style: shade(k),\n }),\n ),\n h(\n 'text',\n {\n class: 'tc-tick-label',\n x: round(scaleX + lowWidth + 6 + swatches * (swatch + gap) + 6),\n y: round(scaleY),\n dy: '0.32em',\n },\n high,\n ),\n ),\n ]\n return { content, interaction }\n}\n\n/**\n * Size of the grid with its names and scale at the size of a contribution\n * graph (13 pixel days, 12 pixel text): `fixed` is the part of the height\n * that stays as the days shrink (the month names, the scale).\n */\nfunction naturalSize(options: CalendarOptions) {\n const { bands, columns } = rangeOf(options)\n const n = bands.length\n if (!n) return undefined\n const top = options.x?.show === false ? 0 : 23\n const left = options.y?.show === false ? 0 : 36\n const fixed = n * top + (n - 1) * BAND_GAP + (options.scale === false ? 0 : 21)\n return {\n left,\n fixed,\n rows: 7 * n,\n columns,\n width: left + columns * 13,\n height: fixed + n * 7 * 13,\n }\n}\n\n/**\n * Width to height of the chart, so a year is a low strip of small squares\n * instead of filling a chart half as tall as wide.\n */\nfunction ratioOf(options: CalendarOptions): number | undefined {\n const size = naturalSize(options)\n // (A few weeks alone would be taller than wide: not below the usual 2.)\n return size && Math.max(2, round(size.width / size.height))\n}\n\n/**\n * Height for a width narrower than the contribution graph (a phone): the\n * names and the scale keep their size there, so the ratio alone would leave\n * the days no room. Your own `aspectRatio` is kept.\n */\nfunction heightOf(\n options: CalendarOptions & { aspectRatio?: number; autoRatio?: number },\n width: number,\n): number | undefined {\n const size = naturalSize(options)\n if (!size || options.aspectRatio !== options.autoRatio || width >= size.width) return undefined\n const days = (Math.max(0, width - size.left) / size.columns) * size.rows\n // (Not taller than the usual half of the width, which a few weeks alone get.)\n return Math.min(width / 2, size.fixed + days)\n}\n\n/** Legend: the series (kinds of activity), when the data has them. */\nconst calendarLegend = (options: CalendarOptions): LegendItem[] =>\n Array.isArray(options.data) ? [] : legendItems(seriesOf(options.data))\n\n/** Table: one row per day of the range, one column per visible series. */\nfunction calendarTable(options: CalendarOptions, ctx: RenderContext, limit: number): DataTable {\n const series = seriesOf(options.data).filter((s) => !ctx.hidden.has(keyOf(s)))\n const utc = options.utc === true\n const value = formatNumber(options.format, ctx.locale)\n const title = formatDate(\n options.dateFormat ?? { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' },\n ctx.locale,\n )\n // Every day with an entry, in order (the grid's blank days say nothing).\n const days = new Map<number, (number | null)[]>()\n series.forEach((s, k) => {\n for (const e of s.values) {\n const ms = stamp(e.date)\n if (ms === null) continue\n const day = dayOf(ms, utc)\n const rowValues = days.get(day) ?? series.map(() => null)\n const v = finite(e.value)\n if (v !== null) rowValues[k] = (rowValues[k] ?? 0) + v\n days.set(day, rowValues)\n }\n })\n const sorted = [...days.keys()].sort((a, b) => a - b)\n return {\n columns: ['', ...series.map((s) => s.name)],\n total: sorted.length,\n rows: sorted\n .slice(0, limit)\n .map((day) => [\n title(dateOf(day)),\n ...(days.get(day) ?? []).map((v) => (v === null ? '–' : value(v))),\n ]),\n }\n}\n\n/**\n * Calendar: a contribution-style heatmap of days, one column per week and\n * one row per weekday, shaded in `levels` steps of one hue by the day's\n * value (`--tc-heat-color`), with month and weekday names and a low-to-high\n * scale; `colors` shades through a scale of colors instead, `'diverging'`\n * for values with a sign. Several series add up per day and the legend filters them.\n *\n * ```ts\n * new Chart('#el', {\n * type: calendar,\n * data: [{ date: '2026-10-26', value: 3 }, { date: '2026-10-27', value: 0 }],\n * weeks: 12,\n * })\n * ```\n */\nexport const calendar: ChartType<CalendarOptions> = {\n name: 'calendar',\n // (The options come with the whole config: its proportions are defaulted here.)\n clean: (options) => {\n const config = cleanData(cleanCalendar)(options) as CalendarOptions & {\n aspectRatio?: number\n autoRatio?: number\n }\n // The ratio set here follows the range; one of your own is kept.\n if (config.aspectRatio !== undefined && config.aspectRatio !== config.autoRatio) return config\n const autoRatio = ratioOf(config)\n return { ...config, aspectRatio: autoRatio, autoRatio }\n },\n render: renderCalendar,\n height: heightOf,\n legend: calendarLegend,\n table: calendarTable,\n valueLabels: { marks: 'cell', format: (options) => options.format },\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 windowed,\n} from './cartesian.ts'\nimport { cleanData, finite, label, records } from './clean.ts'\nimport type { Zoomable } from './view.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 extends Zoomable {\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 prepare: windowed,\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\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 const content = [\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 return { content, interaction }\n },\n table: (options, ctx, limit) => seriesTable(asCartesian(options), ctx, limit),\n}\n","import { estimateTextWidth } from '../layout.ts'\n\n/** `text` cut to `width` pixels with an ellipsis, or `''` when not even a few letters fit. */\nexport function fit(text: string, width: number, fontSize: number): string {\n if (estimateTextWidth(text, fontSize) <= width) return text\n const chars = [...text]\n while (chars.length > 2) {\n chars.pop()\n const cut = `${chars.join('').trimEnd()}…`\n if (estimateTextWidth(cut, fontSize) <= width) return cut\n }\n return ''\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext, RenderResult } from '../chart.ts'\nimport { formatNumber, getNumberFormat, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { estimateTextWidth, type InsetsInput, innerRect, insets, round } from '../layout.ts'\nimport { type ClassValue, h } from '../vnode.ts'\nimport { cleanData, finite, named, records } from './clean.ts'\nimport { fit } from './fit.ts'\nimport { keyOf } from './named.ts'\n\n/** One stage of a funnel. */\nexport interface FunnelStage {\n name: string\n /** How many reached the stage. Stages without a number, or with a negative one, are left out. */\n value: number\n /** Stable identity for keyed updates. Defaults to `name`. */\n id?: string\n /**\n * Custom color, drawn as it is instead of the stage's shade of `--tc-funnel-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 stage's shape. */\n class?: ClassValue\n}\n\nexport interface FunnelOptions {\n /** Stages in the order of the process; they are drawn as they come, not sorted. */\n data: readonly FunnelStage[]\n /** Name, value and share of the first stage written above every stage. Defaults to `true`. */\n labels?: boolean\n /** Radius of the top corners of the stages. Defaults to `4`. */\n radius?: number\n /** Format of the values (labels, tooltip, table). */\n format?: NumberFormat\n /** Extra space around the chart, in pixels. */\n padding?: InsetsInput\n}\n\n/** Space between a column's left edge and its text (none in the first column). */\nconst INSET = 10\n\n/** Share of the full color in the first stage; the last one takes all of it. */\nconst PALEST = 0.3\n\nconst COLOR = 'var(--tc-funnel-color,var(--tc-color-1))'\n\n/** A stage with its conversion rates, `0…1` (`1` for the first stage). */\ninterface Stage {\n data: FunnelStage\n value: number\n ofFirst: number\n ofPrevious: number\n}\n\nconst share = (value: number, of: number): number => (of > 0 ? value / of : 0)\n\nfunction stagesOf(options: FunnelOptions): Stage[] {\n const first = options.data[0]?.value ?? 0\n return options.data.map((data, i) => ({\n data,\n value: data.value,\n ofFirst: i === 0 ? 1 : share(data.value, first),\n ofPrevious: i === 0 ? 1 : share(data.value, (options.data[i - 1] as FunnelStage).value),\n }))\n}\n\n/** Share of the full color in stage `i` of `count`: paler where the funnel is wide. */\nconst shadeOf = (i: number, count: number): number =>\n round((count > 1 ? PALEST + ((1 - PALEST) * i) / (count - 1) : 1) * 100)\n\n/** Corner of radius `r` that takes at most half of either edge it sits on. */\nconst corner = (r: number, edgeX: number, edgeY: number): number =>\n Math.max(0, Math.min(r, edgeX / 2, edgeY / 2))\n\n/**\n * A stage from `x0` to `x1`, standing on `floor`: its top runs from its own\n * height `y0` to the next stage's `y1`, with both top corners rounded.\n */\nfunction stagePath(\n x0: number,\n x1: number,\n y0: number,\n y1: number,\n floor: number,\n radius: number,\n): string {\n const dx = x1 - x0\n const dy = y1 - y0\n const near = corner(radius, dx, floor - y0)\n const far = corner(radius, dx, floor - y1)\n // How far along the sloped top each corner reaches.\n const tn = dx > 0 ? near / dx : 0\n const tf = dx > 0 ? far / dx : 0\n const n = round\n return (\n `M${n(x0)},${n(y0 + near)}Q${n(x0)},${n(y0)},${n(x0 + dx * tn)},${n(y0 + dy * tn)}` +\n `L${n(x1 - dx * tf)},${n(y1 - dy * tf)}Q${n(x1)},${n(y1)},${n(x1)},${n(y1 + far)}` +\n `L${n(x1)},${n(floor)}L${n(x0)},${n(floor)}Z`\n )\n}\n\nfunction renderFunnel(options: FunnelOptions, ctx: RenderContext): RenderResult {\n const { width, height, fontSize, locale } = ctx\n const radius = Math.max(0, options.radius ?? 4)\n const area = innerRect(width, height, insets(options.padding, 0))\n const stages = stagesOf(options)\n const count = stages.length\n if (count === 0) return { content: null }\n\n const value = formatNumber(options.format, locale)\n const percent = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n // For columns too narrow for the whole value: \"31K\" says more than nothing.\n const short =\n typeof options.format === 'function'\n ? value\n : formatNumber({ ...options.format, notation: 'compact' }, locale)\n\n // Three lines of text above the shapes: name, value, share of the first stage.\n const line = fontSize * 1.3\n const header = options.labels === false ? 0 : Math.min(area.height, line * 3 + 8)\n const floor = area.y + area.height\n const plot = area.height - header\n const column = area.width / count\n const columnX = (i: number) => area.x + i * column\n // Every stage is measured against the largest, so a funnel that only loses fills the plot.\n const max = Math.max(0, ...stages.map((stage) => stage.value))\n const top = (v: number) => floor - (max > 0 ? (v / max) * plot : 0)\n\n const colorOf = (i: number): string =>\n (stages[i] as Stage).data.color ??\n `color-mix(in oklab,${COLOR} ${shadeOf(i, count)}%,var(--tc-surface))`\n\n const hitFor = (i: number): Hit => {\n const stage = stages[i] as Stage\n const x = columnX(i) + column / 2\n const items: HitItem[] = [\n {\n name: stage.data.name,\n seriesIndex: 0,\n value: stage.value,\n text: value(stage.value),\n x,\n y: top(stage.value),\n color: colorOf(i),\n },\n ]\n // Conversion rates as notes below the value: no swatch, no value label.\n const rate = (seriesIndex: number, of: Stage, v: number) =>\n items.push({\n name: `of ${of.data.name}`,\n seriesIndex,\n value: v,\n text: percent.format(v),\n x,\n y: null,\n color: 'transparent',\n })\n if (i > 0) rate(1, stages[0] as Stage, stage.ofFirst)\n // The second stage's previous one is the first: the same rate again.\n if (i > 1) rate(2, stages[i - 1] as Stage, stage.ofPrevious)\n return {\n index: i,\n label: stage.data.name,\n title: '',\n x,\n area,\n // The whole column is highlighted, as it is the whole hit area.\n highlight: { kind: 'band', x: columnX(i), y: area.y, width: column, height: area.height },\n items,\n }\n }\n\n const interaction: Interaction = {\n count,\n hitIndex: (i) => (i >= 0 && i < count ? hitFor(i) : null),\n hitTest(px, py) {\n if (px < area.x || px > area.x + area.width || py < area.y || py > floor) return null\n return hitFor(Math.min(count - 1, Math.floor((px - area.x) / (column || 1))))\n },\n }\n\n const dividers = stages.slice(1).map((stage, i) =>\n h('line', {\n key: keyOf(stage.data),\n class: 'tc-grid-line tc-funnel-divider',\n x1: round(columnX(i + 1)),\n x2: round(columnX(i + 1)),\n y1: round(area.y),\n y2: round(floor),\n }),\n )\n\n const shapes = stages.map((stage, i) =>\n h('path', {\n key: keyOf(stage.data),\n class: ['tc-funnel-stage', stage.data.class],\n 'data-series': stage.data.name,\n // The last stage stays level: a slope would draw a loss the data does not report.\n d: stagePath(\n columnX(i),\n columnX(i + 1),\n top(stage.value),\n top((stages[i + 1] ?? stage).value),\n floor,\n radius,\n ),\n // A map, so values from data cannot inject CSS (see normalizeStyle).\n style: {\n '--tc-funnel-color': stage.data.color,\n '--tc-funnel-shade': `${stage.data.color ? 100 : shadeOf(i, count)}%`,\n },\n }),\n )\n\n const labels =\n header >= line * 3 &&\n stages.flatMap((stage, i) => {\n const inset = i === 0 ? 0 : INSET\n const room = column - inset - INSET\n const x = round(columnX(i) + inset)\n const y = area.y + fontSize * 0.85\n const key = keyOf(stage.data)\n const fits = (text: string) => estimateTextWidth(text, fontSize) <= room\n const name = fit(stage.data.name, room, fontSize)\n const whole = value(stage.value)\n const amount = fits(whole) ? whole : short(stage.value)\n // Nothing to convert from at the top of the funnel.\n const rate = i > 0 ? percent.format(stage.ofFirst) : ''\n return [\n name && h('text', { key, class: 'tc-funnel-name', x, y: round(y) }, name),\n fits(amount) &&\n h(\n 'text',\n { key: `${key}/value`, class: 'tc-funnel-value', x, y: round(y + line) },\n amount,\n ),\n rate &&\n fits(rate) &&\n h(\n 'text',\n { key: `${key}/share`, class: 'tc-funnel-share', x, y: round(y + line * 2) },\n rate,\n ),\n ]\n })\n\n const content = [\n h('g', { class: 'tc-funnel-dividers', 'aria-hidden': 'true' }, dividers),\n h('g', { class: 'tc-funnel-stages' }, shapes),\n labels && h('g', { class: 'tc-funnel-labels', 'aria-hidden': 'true' }, labels),\n ]\n return { content, interaction }\n}\n\nfunction funnelTable(options: FunnelOptions, ctx: RenderContext, limit: number): DataTable {\n const value = formatNumber(options.format, ctx.locale)\n const percent = getNumberFormat(ctx.locale, { style: 'percent', maximumFractionDigits: 1 })\n const rows = stagesOf(options).map((stage) => [\n stage.data.name,\n value(stage.value),\n percent.format(stage.ofFirst),\n percent.format(stage.ofPrevious),\n ])\n const table: DataTable = { columns: ['', 'Value', 'Of first', 'Of previous'], rows }\n if (rows.length > limit) {\n table.rows = rows.slice(0, limit)\n table.total = rows.length\n }\n return table\n}\n\n/**\n * Stages with text for names. A stage that reports no number did not report\n * a zero, and the stage after it would be measured against it: such stages\n * are left out, as are negative counts.\n */\nconst cleanStages = (data: unknown): unknown =>\n records(data, (r) => ({ ...named(r), value: finite(r.value) })).filter(\n (stage) => stage.value !== null && stage.value >= 0,\n )\n\n/**\n * Funnel: how many get from one stage of a process to the next. Every stage\n * is a column with its name, its value and its share of the first stage on\n * top; the shapes below step down from each stage's height to the next, in\n * one color that deepens as the funnel narrows (`--tc-funnel-color`).\n *\n * ```ts\n * new Chart('#el', {\n * type: funnel,\n * data: [\n * { name: 'Visits', value: 12400 },\n * { name: 'Signups', value: 3100 },\n * { name: 'Purchases', value: 620 },\n * ],\n * })\n * ```\n */\nexport const funnel: ChartType<FunnelOptions> = {\n name: 'funnel',\n clean: cleanData(cleanStages),\n render: renderFunnel,\n table: funnelTable,\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, RenderResult } from '../chart.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 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): RenderResult {\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 highlight: { kind: 'halo', 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\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 const content = [\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 return { content, interaction }\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: renderGauge,\n sweep: sweepArcs,\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, plotFrame, round } from '../layout.ts'\nimport { band } from '../scales/band.ts'\nimport { extent } from '../scales/extent.ts'\nimport { rectPath } from '../shapes/rect.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\nfunction renderHeatmap(options: HeatmapOptions, ctx: RenderContext) {\n const { width, 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 { rtl } = ctx\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 { area, side, range } = plotFrame(ctx, options.padding, (pad) => {\n const halfColumn = (width - pad.start - pad.end - left) / Math.max(1, labels.length) / 2\n return {\n top: pad.top,\n bottom: pad.bottom + bottom,\n start: pad.start + left,\n end: pad.end + Math.max(0, Math.ceil(lastLabel / 2 - halfColumn)),\n }\n })\n const x = band(\n labels.map((_, i) => i),\n range(),\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 highlight: {\n kind: 'halo',\n d: rectPath(cellX(i) - 2, cellY(j) - 2, cellW + 4, cellH + 4, radius + 2),\n },\n }\n }\n\n const interaction: Interaction = {\n count: labels.length,\n reversed: rtl === true,\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 column = Math.min(labels.length - 1, Math.floor((px - area.x) / (x.step || 1)))\n const i = rtl ? labels.length - 1 - column : column\n const j = Math.min(rows.length - 1, Math.floor((py - area.y) / (y.step || 1)))\n return hitAt(i, j)\n },\n }\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 const content = [\n h('g', { class: 'tc-heatmap-cells' }, cells),\n showX && axis({ position: 'bottom', ticks: xTicks, area }),\n showY && axis({ position: side, ticks: yTicks, area }),\n ]\n return { content, interaction }\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 { finite } from './clean.ts'\n\n/** The part of a map in sight. */\nexport interface MapView {\n /** The top left corner, in the coordinates of the map file. */\n x: number\n y: number\n /** How many times the map is magnified; `1` shows all of it. */\n scale: number\n}\n\n/** Where the last render put the map, for the zoom to work from. */\nexport interface MapLayout {\n /** The room of the map in chart pixels. */\n x: number\n y: number\n width: number\n height: number\n /** Pixels per unit of the map when all of it is in sight. */\n k: number\n /** Size of the map file. */\n mapWidth: number\n mapHeight: number\n /** The most the map can be magnified. */\n max: number\n}\n\n/**\n * A view kept inside the zoom range and the map itself, so the map can never\n * be dragged out of sight; along a side where all of the map fits, it is centered.\n */\nexport function fitView(view: Partial<MapView> | undefined, layout: MapLayout): MapView {\n const scale = Math.min(layout.max, Math.max(1, finite(view?.scale) ?? 1))\n const unit = layout.k * scale\n const fit = (at: number | null, size: number, room: number): number => {\n const span = room / unit\n return span >= size ? (size - span) / 2 : Math.min(size - span, Math.max(0, at ?? 0))\n }\n return unit > 0\n ? {\n x: fit(finite(view?.x), layout.mapWidth, layout.width),\n y: fit(finite(view?.y), layout.mapHeight, layout.height),\n scale,\n }\n : { x: 0, y: 0, scale }\n}\n","import type { MapHit, MapInteraction, MapOptions } from '../charts/map.ts'\nimport { fitView, type MapView } from '../charts/map-view.ts'\nimport { toChartPoint } from '../interaction.ts'\nimport type { ChartPlugin } from '../plugin.ts'\n\ntype Point = [number, number]\n\n/** One step of a button, a key or a double click. */\nconst ZOOM_STEP = 2\nconst ZOOM_DURATION = 200\n/**\n * How much one unit of wheel movement magnifies. A pinch on a trackpad comes\n * as a wheel event with `ctrlKey` and much smaller numbers.\n */\nconst WHEEL_SPEED = 0.002\nconst WHEEL_SPEED_PINCH = 0.01\n/** How far a pointer has to move, in pixels, before a press becomes a drag and stops being a click. */\nconst DRAG_THRESHOLD = 4\nconst SVG_NS = 'http://www.w3.org/2000/svg'\nconst ICONS = ['M12 5v14M5 12h14', 'M5 12h14']\n\n/**\n * What makes a map more than a picture: with `zoom` it is magnified with its\n * buttons, the wheel, a double click, a pinch or the `+`, `-` and `0` keys,\n * and dragged around; with `select` a click (or Enter) selects a region. The\n * `map` chart type brings it along, so it needs no import of its own; it\n * keeps no state, the view and the selection live in the options.\n */\nexport function mapInteraction(): ChartPlugin {\n return {\n name: 'map',\n install(chart) {\n const host = chart.element\n if (typeof host.addEventListener !== 'function') return {}\n const doc = host.ownerDocument\n const win = doc.defaultView\n const options = () => chart.config as unknown as MapOptions & { animate?: boolean }\n const isMap = () => chart.config.type.name === 'map'\n const zoomOn = () => isMap() && !!options().zoom\n const layout = () => (chart.interaction as Partial<MapInteraction> | undefined)?.map\n const svg = () => host.querySelector(':scope > svg.tc-chart')\n /** Whether an event happened on the drawing, not on a control over it. */\n const onMap = (event: Event) =>\n (event.target as Element | null)?.closest?.('svg.tc-chart') === svg() && !!svg()\n\n let frame = 0\n /** Pointers that are down on the map, with where each was last seen. */\n const pointers = new Map<number, Point>()\n /** Whether the pointers that are down have moved the map: the click that ends a drag selects nothing. */\n let dragged = false\n let controls: HTMLElement | undefined\n const addedClass = !host.classList.contains('tc-container')\n\n const stop = () => win?.cancelAnimationFrame(frame)\n const current = (): MapView | undefined => {\n const l = layout()\n return l && fitView(options().view, l)\n }\n const setView = (view: MapView) => {\n const l = layout()\n if (l) chart.update({ view: fitView(view, l) } as never)\n }\n\n /** A point of the screen in chart pixels. */\n const toChart = (x: number, y: number): Point => {\n const el = svg()\n const { width, height } = chart.size\n const p = el ? toChartPoint(el, x, y, width, height) : { x: 0, y: 0 }\n return [p.x, p.y]\n }\n /** A point of the screen in the coordinates of the map. */\n const toMapPoint = (x: number, y: number): Point | null => {\n const l = layout()\n const view = current()\n if (!l || !view) return null\n const unit = l.k * view.scale\n const [cx, cy] = toChart(x, y)\n return [view.x + (cx - l.x) / unit, view.y + (cy - l.y) / unit]\n }\n\n /**\n * Moves to a view over a few frames. The corner and the size of the\n * view change at the same pace, which keeps the point being zoomed at in place.\n */\n const animateTo = (to: MapView) => {\n stop()\n const l = layout()\n const from = current()\n if (!l || !from) return\n const target = fitView(to, l)\n const still =\n options().animate === false ||\n !win?.requestAnimationFrame ||\n win.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n if (still) {\n setView(target)\n return\n }\n const start = performance.now()\n const step = (now: number) => {\n const t = Math.min((now - start) / ZOOM_DURATION, 1)\n const eased = 1 - (1 - t) ** 3\n const at = (a: number, b: number) => a + (b - a) * eased\n setView({\n x: at(from.x, target.x),\n y: at(from.y, target.y),\n scale: 1 / at(1 / from.scale, 1 / target.scale),\n })\n if (t < 1) frame = win.requestAnimationFrame(step)\n }\n frame = win.requestAnimationFrame(step)\n }\n\n /**\n * Magnifies by a factor around a point of the map, which stays where it\n * is on the screen. Without a point, around the middle of the view.\n */\n const zoomBy = (factor: number, anchor: Point | null, animate = false) => {\n const l = layout()\n const view = current()\n if (!l || !view || !(l.k > 0)) return\n const next = Math.min(l.max, Math.max(1, view.scale * factor))\n const unit = l.k * view.scale\n const [ax, ay] = anchor ?? [view.x + l.width / unit / 2, view.y + l.height / unit / 2]\n const target = {\n x: ax - ((ax - view.x) * view.scale) / next,\n y: ay - ((ay - view.y) * view.scale) / next,\n scale: next,\n }\n if (animate) animateTo(target)\n else {\n stop()\n setView(target)\n }\n }\n\n /** Selects the region of a hit, or takes it out when it is selected. */\n const select = (hit: MapHit | null) => {\n const o = options()\n const code = hit?.region\n if (!isMap() || !o.select || !code) return\n const selected = [...(o.selected ?? [])]\n const rest = selected.filter((other) => other !== code)\n const next =\n rest.length < selected.length\n ? rest\n : o.select === 'multiple'\n ? [...selected, code]\n : [code]\n chart.update({ selected: next } as never)\n o.onSelect?.(next, code)\n }\n\n const onPointerEnd = (event: PointerEvent) => {\n pointers.delete(event.pointerId)\n if (pointers.size === 0) {\n doc.removeEventListener('pointerup', onPointerEnd)\n doc.removeEventListener('pointercancel', onPointerEnd)\n // The cursor of a drag goes with the next render.\n if (dragged) chart.update({})\n }\n }\n const onPointerDown = (event: PointerEvent) => {\n if (!zoomOn() || !onMap(event) || (event.pointerType === 'mouse' && event.button !== 0))\n return\n if (pointers.size === 0) dragged = false\n pointers.set(event.pointerId, [event.clientX, event.clientY])\n stop()\n doc.addEventListener('pointerup', onPointerEnd)\n doc.addEventListener('pointercancel', onPointerEnd)\n }\n /** One pointer drags the map, two pinch it. */\n const onPointerMove = (event: PointerEvent) => {\n const previous = pointers.get(event.pointerId)\n const view = current()\n const l = layout()\n if (!previous || !view || !l) return\n const now: Point = [event.clientX, event.clientY]\n // A press that barely moves is a click, not a drag: until the pointer\n // has moved far enough the map stays put, and the click reaches the region.\n if (!dragged) {\n if (\n pointers.size === 1 &&\n Math.hypot(now[0] - previous[0], now[1] - previous[1]) < DRAG_THRESHOLD\n )\n return\n dragged = true\n // The map keeps getting the moves of this pointer when it leaves the\n // map. Capturing throws for a pointer the browser does not know,\n // which is what an event made in a script has.\n try {\n svg()?.setPointerCapture(event.pointerId)\n } catch {\n // The drag still works while the pointer stays over the map.\n }\n }\n // The highlight and the tooltip stay out of a drag.\n event.stopPropagation()\n chart.clearHighlight()\n pointers.set(event.pointerId, now)\n if (pointers.size === 1) {\n const unit = l.k * view.scale\n const [x0, y0] = toChart(previous[0], previous[1])\n const [x1, y1] = toChart(now[0], now[1])\n setView({ x: view.x - (x1 - x0) / unit, y: view.y - (y1 - y0) / unit, scale: view.scale })\n return\n }\n const other = [...pointers].find(([id]) => id !== event.pointerId)?.[1]\n if (!other) return\n const before = Math.hypot(previous[0] - other[0], previous[1] - other[1])\n const after = Math.hypot(now[0] - other[0], now[1] - other[1])\n if (before > 0 && after > 0)\n zoomBy(after / before, toMapPoint((now[0] + other[0]) / 2, (now[1] + other[1]) / 2))\n }\n const onWheel = (event: WheelEvent) => {\n const { zoom } = options()\n if (!zoomOn() || (typeof zoom === 'object' && zoom.wheel === false) || !onMap(event)) return\n // The page must not scroll while the wheel zooms the map.\n event.preventDefault()\n zoomBy(\n Math.exp(-event.deltaY * (event.ctrlKey ? WHEEL_SPEED_PINCH : WHEEL_SPEED)),\n toMapPoint(event.clientX, event.clientY),\n )\n }\n const onDoubleClick = (event: MouseEvent) => {\n if (zoomOn() && onMap(event))\n zoomBy(ZOOM_STEP, toMapPoint(event.clientX, event.clientY), true)\n }\n /** The click that ends a drag is not a click on the map. */\n const onClickCapture = (event: MouseEvent) => {\n if (dragged) event.stopPropagation()\n dragged = false\n }\n const onKey = (event: KeyboardEvent) => {\n if (event.target !== svg() || !isMap()) return\n const { key } = event\n if (zoomOn() && (key === '+' || key === '=')) zoomBy(ZOOM_STEP, null, true)\n else if (zoomOn() && key === '-') zoomBy(1 / ZOOM_STEP, null, true)\n else if (zoomOn() && key === '0') animateTo({ x: 0, y: 0, scale: 1 })\n else if (options().select && (key === 'Enter' || key === ' ') && chart.active)\n select(chart.active)\n else return\n event.preventDefault()\n }\n const onControl = (event: MouseEvent) => {\n const button = (event.target as Element).closest('button')\n if (button) zoomBy(button.value === 'in' ? ZOOM_STEP : 1 / ZOOM_STEP, null, true)\n }\n\n // Moves are taken on their way down, so a drag never reaches the highlight.\n host.addEventListener('pointermove', onPointerMove, true)\n host.addEventListener('click', onClickCapture, true)\n host.addEventListener('pointerdown', onPointerDown)\n // (Not passive: the wheel must be kept from scrolling the page.)\n host.addEventListener('wheel', onWheel, { passive: false })\n host.addEventListener('dblclick', onDoubleClick)\n host.addEventListener('keydown', onKey)\n const off = chart.on('click', ({ hit }) => select(hit))\n\n /** The zoom buttons, laid over a corner of the map. */\n const renderControls = () => {\n if (!zoomOn()) {\n controls?.remove()\n controls = undefined\n return\n }\n if (!controls) {\n controls = doc.createElement('div')\n controls.className = 'tc-map-zoom'\n for (const [i, d] of ICONS.entries()) {\n const button = doc.createElement('button')\n button.type = 'button'\n button.className = 'tc-download-toggle'\n button.value = i ? 'out' : 'in'\n const icon = doc.createElementNS(SVG_NS, 'svg')\n icon.setAttribute('viewBox', '0 0 24 24')\n icon.setAttribute('width', '16')\n icon.setAttribute('height', '16')\n icon.setAttribute('aria-hidden', 'true')\n const path = doc.createElementNS(SVG_NS, 'path')\n path.setAttribute('d', d)\n icon.append(path)\n button.append(icon)\n controls.append(button)\n }\n controls.addEventListener('click', onControl)\n host.classList.add('tc-container')\n }\n if (!controls.isConnected) host.append(controls)\n const { zoom } = options()\n const labels = typeof zoom === 'object' ? zoom.labels : undefined\n const view = current()\n const max = layout()?.max ?? 1\n const [zoomIn, zoomOut] = controls.querySelectorAll('button')\n if (zoomIn && zoomOut && view) {\n zoomIn.setAttribute('aria-label', labels?.in ?? 'Zoom in')\n zoomOut.setAttribute('aria-label', labels?.out ?? 'Zoom out')\n zoomIn.disabled = view.scale >= max\n zoomOut.disabled = view.scale <= 1\n }\n }\n\n return {\n // The stylesheet takes drags and pinches for a map that can be\n // magnified, so the page does not scroll or zoom under the finger.\n svgAttrs: () =>\n zoomOn() ? { 'data-zoom': dragged && pointers.size ? 'drag' : '' } : undefined,\n afterRender: renderControls,\n destroy() {\n stop()\n off()\n host.removeEventListener('pointermove', onPointerMove, true)\n host.removeEventListener('click', onClickCapture, true)\n host.removeEventListener('pointerdown', onPointerDown)\n host.removeEventListener('wheel', onWheel)\n host.removeEventListener('dblclick', onDoubleClick)\n host.removeEventListener('keydown', onKey)\n doc.removeEventListener('pointerup', onPointerEnd)\n doc.removeEventListener('pointercancel', onPointerEnd)\n controls?.remove()\n if (controls && addedClass) host.classList.remove('tc-container')\n },\n }\n },\n }\n}\n","import { round } from '../layout.ts'\nimport type { StyleValue } from '../vnode.ts'\n\n/** The shade of a mark without a value, and the pale end of the single hue. */\nexport const EMPTY = 'var(--tc-heat-empty,var(--tc-grid-color))'\n\n/** A scale that shades marks by value (map regions, treemap tiles). */\nexport interface HeatScale {\n /** Position of a value in the domain, 0…1 (through `mid` for a scale with a middle). */\n position(v: number): number\n /** How a mark at position `t` of the scale is painted: its style and the tooltip swatch. */\n paint(t: number): { style: StyleValue; color: string }\n}\n\n/**\n * The scale from `lo` to `hi`: through the `stops` when there are any (with\n * `mid` on the middle one), else one hue, `--tc-heat-color`, from `floor`\n * (its share at `lo`) to the full color.\n */\nexport function heatScale(\n lo: number,\n hi: number,\n mid: number | null,\n stops: readonly string[] | undefined,\n floor: number,\n): HeatScale {\n return {\n position(v) {\n const t =\n stops && mid !== null && lo < mid && mid < hi\n ? v <= mid\n ? ((v - lo) / (mid - lo)) * 0.5\n : 0.5 + ((v - mid) / (hi - mid)) * 0.5\n : hi > lo\n ? (v - lo) / (hi - lo)\n : v > lo\n ? 1\n : 0\n return Math.min(1, Math.max(0, t))\n },\n paint(t) {\n if (stops) {\n const at = t * (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 = round((floor + (1 - floor) * t) * 100)\n return {\n style: `--tc-heat:${pct}%`,\n color: `color-mix(in oklab,var(--tc-heat-color,var(--tc-color-1)) ${pct}%,${EMPTY})`,\n }\n },\n }\n}\n","import type { ChartType, DataTable, RenderContext, RenderResult, TableContext } from '../chart.ts'\nimport { formatNumber, type NumberFormat } from '../format.ts'\nimport type { Hit, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n round,\n} from '../layout.ts'\nimport { mapInteraction } from '../plugins/map.ts'\nimport { h, type VNode } from '../vnode.ts'\nimport { finite, isRecord, list, records, text } from './clean.ts'\nimport { EMPTY, heatScale } from './heat.ts'\nimport { fitView, type MapLayout, type MapView } from './map-view.ts'\n\nexport type { MapLayout, MapView }\n\n/** One region of a map (a country, a state …). */\nexport interface MapRegion {\n name: string\n /**\n * SVG path data in the coordinates of the map (`M`, `L`, `H`, `V` and `Z`,\n * absolute or relative; curves are drawn but not hit by the pointer).\n */\n path: string\n /** Too small for a shape at the scale of the map: `path` is a single point, drawn as a dot when it has a value. */\n point?: boolean\n}\n\n/** A map: shapes already projected into a `width` × `height` box, as the files in `@tabler/charts/maps/*` are. */\nexport interface MapData {\n width: number\n height: number\n /** How the shapes were projected, to place a marker by its coordinates. */\n projection?: { type: 'miller'; scale: number; translate: readonly number[] }\n /** Regions by their code, e.g. ISO 3166-1 alpha-2 for countries. */\n regions: Readonly<Record<string, MapRegion>>\n}\n\n/** A place on the map, by its coordinates. */\nexport interface MapMarker {\n /** Shown in the tooltip, and what a line refers to. */\n name?: string\n /** Latitude and longitude in degrees. */\n lat: number\n lng: number\n}\n\n/** A curve between two markers, by their names. */\nexport interface MapLine {\n from: string\n to: string\n}\n\nexport interface MapOptions {\n /** The map: a map file (`import { world } from '@tabler/charts/maps/world'`), or the name it was given with `addMap()`. */\n map: MapData | string\n /** A value per region code, e.g. `{ PL: 80, DE: 45 }`. Regions without one keep the empty shade. */\n data: Readonly<Record<string, number | null>>\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 * A continuous scale through two or more colors (any CSS color, including\n * `var(--tc-…)`), from `min` to `max`, instead of one hue (`--tc-heat-color`).\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 /** Places drawn as dots over the map. */\n markers?: readonly MapMarker[]\n /** Dashed curves between markers. */\n lines?: readonly MapLine[]\n /** Radius of the markers and of the regions drawn as a dot, in pixels. Defaults to `4`. */\n markerRadius?: number\n /** Format of the values (tooltip, scale, table). */\n format?: NumberFormat\n /**\n * The bar below the map with the lowest and the highest value: `false`\n * hides it, an object names its ends instead of the values.\n */\n scale?: boolean | { low?: string; high?: string }\n /** Extra space around the map, in pixels. */\n padding?: InsetsInput\n /**\n * Let the map be magnified with its buttons, the wheel, a double click, a\n * pinch or the `+` and `-` keys, and dragged around. An object sets the\n * most it magnifies (`max`, `8` by default), turns the wheel off\n * (`wheel: false`) and names the buttons (`labels`).\n */\n zoom?: boolean | { max?: number; wheel?: boolean; labels?: { in?: string; out?: string } }\n /**\n * The part of the map in sight. Zooming and dragging write it; set it\n * yourself to start on a part of the map, leave it out for the whole map.\n */\n view?: Partial<MapView>\n /**\n * Let regions be selected with a click (or Enter on the region the\n * keyboard is on): one at a time, or any number of them. A click on a\n * selected region takes it out again.\n */\n select?: 'single' | 'multiple'\n /** Codes of the selected regions. Selecting writes it; `onSelect` hears of it. */\n selected?: readonly string[]\n /** Called when a click or a key changes the selection, with the codes now selected and the one that changed. */\n onSelect?: (selected: string[], code: string) => void\n}\n\n/** A hit of a map: what it is on. */\nexport interface MapHit extends Hit {\n /** Code of the region, for a hit on a region. */\n region?: string\n /** Name of the marker, for a hit on a marker. */\n marker?: string\n}\n\n/** The interaction of a map, with where the map was drawn. */\nexport interface MapInteraction extends Interaction {\n map: MapLayout\n}\n\n/** The selected regions of the options that are allowed: one when only one can be selected. */\nexport const selectedOf = (options: MapOptions): readonly string[] =>\n options.select === 'multiple'\n ? (options.selected ?? [])\n : options.select === 'single'\n ? (options.selected ?? []).slice(0, 1)\n : []\n\n/** Share of the full color at the minimum, so the lowest value still stands out from a region without one. */\nconst FLOOR = 0.1\nconst MARKER = 'var(--tc-map-marker-color,var(--tc-color-1))'\n/** Slices of the scale's bar: enough to read as one smooth gradient. */\nconst SCALE_STEPS = 24\nconst SCALE_STEP = 5\nconst SCALE_HEIGHT = 8\n/** How far a line bends away from the straight one, as a share of its length. */\nconst LINE_CURVE = 0.2\nconst RADIANS = Math.PI / 180\n\nconst maps: Record<string, MapData> = {}\n\n/** Register a map under a name, so `map: 'world'` finds it (configs from JSON, `<tabler-chart>`, the data API). */\nexport function addMap(name: string, data: MapData): void {\n maps[name] = data\n}\n\nconst isMap = (v: unknown): v is MapData =>\n isRecord(v) && isRecord(v.regions) && (finite(v.width) ?? 0) > 0 && (finite(v.height) ?? 0) > 0\n\n/** A region ready to draw and to hit: its rings as flat `x, y` lists in map coordinates. */\ninterface Shape {\n code: string\n name: string\n path: string\n point: boolean\n rings: number[][]\n /** Bounds of the shape: left, top, right, bottom. */\n box: [number, number, number, number]\n /** Middle of the largest ring (the mainland), where the keyboard's tooltip sits. */\n x: number\n y: number\n}\n\n/** Rings of path data made of moves and straight lines. */\nfunction parsePath(d: string): number[][] {\n const rings: number[][] = []\n let ring: number[] = []\n let x = 0\n let y = 0\n for (const [, command = '', args = ''] of d.matchAll(/([MLHVZ])([^MLHVZ]*)/gi)) {\n const n = (args.match(/-?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[-+]?\\d+)?/gi) ?? []).map(Number)\n const relative = command >= 'a'\n const type = command.toUpperCase()\n if (type === 'Z') {\n if (ring.length) {\n x = ring[0] as number\n y = ring[1] as number\n }\n continue\n }\n const step = type === 'H' || type === 'V' ? 1 : 2\n for (let i = 0; i + step <= n.length; i += step) {\n const a = n[i] as number\n const b = n[i + 1] as number\n if (type === 'H') x = relative ? x + a : a\n else if (type === 'V') y = relative ? y + a : a\n else {\n x = relative ? x + a : a\n y = relative ? y + b : b\n }\n // A move starts a ring; the pairs after its first are lines.\n if (type === 'M' && i === 0) {\n ring = []\n rings.push(ring)\n }\n ring.push(x, y)\n }\n }\n return rings\n}\n\nconst parsed = new WeakMap<MapData, Map<string, Shape>>()\n\n/** The regions of a map, parsed once per map file. */\nfunction shapesOf(map: MapData): Map<string, Shape> {\n let shapes = parsed.get(map)\n if (shapes) return shapes\n shapes = new Map()\n for (const [code, region] of Object.entries(map.regions)) {\n if (!isRecord(region) || typeof region.path !== 'string') continue\n const rings = parsePath(region.path).filter((ring) => ring.every(Number.isFinite))\n const box: Shape['box'] = [\n Number.POSITIVE_INFINITY,\n Number.POSITIVE_INFINITY,\n Number.NEGATIVE_INFINITY,\n Number.NEGATIVE_INFINITY,\n ]\n let x = 0\n let y = 0\n let largest = -1\n for (const ring of rings) {\n let x0 = Number.POSITIVE_INFINITY\n let y0 = Number.POSITIVE_INFINITY\n let x1 = Number.NEGATIVE_INFINITY\n let y1 = Number.NEGATIVE_INFINITY\n for (let i = 0; i < ring.length; i += 2) {\n x0 = Math.min(x0, ring[i] as number)\n x1 = Math.max(x1, ring[i] as number)\n y0 = Math.min(y0, ring[i + 1] as number)\n y1 = Math.max(y1, ring[i + 1] as number)\n }\n box[0] = Math.min(box[0], x0)\n box[1] = Math.min(box[1], y0)\n box[2] = Math.max(box[2], x1)\n box[3] = Math.max(box[3], y1)\n const size = (x1 - x0) * (y1 - y0)\n if (size > largest) {\n largest = size\n x = (x0 + x1) / 2\n y = (y0 + y1) / 2\n }\n }\n if (largest < 0) continue\n shapes.set(code, {\n code,\n name: text(region.name) || code,\n path: region.path,\n point: region.point === true,\n rings,\n box,\n x,\n y,\n })\n }\n parsed.set(map, shapes)\n return shapes\n}\n\n/** Whether a point lies inside the rings (even-odd, so a hole is outside). */\nfunction inside(rings: readonly number[][], x: number, y: number): boolean {\n let hit = false\n for (const ring of rings) {\n for (let i = 0, j = ring.length - 2; i < ring.length; j = i, i += 2) {\n const xi = ring[i] as number\n const yi = ring[i + 1] as number\n const xj = ring[j] as number\n const yj = ring[j + 1] as number\n if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) hit = !hit\n }\n }\n return hit\n}\n\n/** Path of a circle, for the ring around a hovered dot. */\nconst circlePath = (x: number, y: number, r: number): string =>\n `M${round(x - r)} ${round(y)}a${r} ${r} 0 1 0 ${r * 2} 0a${r} ${r} 0 1 0 ${-r * 2} 0Z`\n\n/** What the pointer and the keyboard can land on. */\ninterface Entry {\n shape?: Shape\n marker?: { name: string; x: number; y: number }\n value: number | null\n}\n\nfunction renderMap(options: MapOptions, ctx: RenderContext): RenderResult {\n const { width, height, fontSize, locale } = ctx\n if (typeof options.map === 'string' && !maps[options.map]) {\n throw new Error(\n `[tabler-charts] Map \"${options.map}\" is not registered. Import it (e.g. from '@tabler/charts/maps/world') and call addMap('${options.map}', data).`,\n )\n }\n const map = typeof options.map === 'string' ? maps[options.map] : options.map\n if (!isMap(map)) return { content: null }\n const shapes = shapesOf(map)\n const data = options.data ?? {}\n const value = formatNumber(options.format, locale)\n const radius = Math.max(0, finite(options.markerRadius) ?? 4)\n\n // Regions with a value, in the order of the data (the order the keyboard walks).\n const entries: Entry[] = []\n const indexOf = new Map<Shape, number>()\n let dataMin = Number.POSITIVE_INFINITY\n let dataMax = Number.NEGATIVE_INFINITY\n for (const code of Object.keys(data)) {\n const shape = shapes.get(code)\n const v = finite(data[code])\n if (!shape || v === null) continue\n indexOf.set(shape, entries.length)\n entries.push({ shape, value: v })\n if (v < dataMin) dataMin = v\n if (v > dataMax) dataMax = v\n }\n const valued = entries.length\n\n // Color domain and the scale of colors.\n const lo = finite(options.min) ?? (valued ? Math.min(0, dataMin) : 0)\n const hi = finite(options.max) ?? (valued ? dataMax : 1)\n const stops = options.colors && options.colors.length >= 2 ? options.colors : undefined\n const mid = finite(options.mid)\n const { position, paint } = heatScale(lo, hi, mid, stops, FLOOR)\n\n // The map keeps its proportions, centered in the room above the scale.\n const pad = insets(options.padding, 0)\n const scale = options.scale !== false && valued > 0\n const scaleHeight = scale ? Math.ceil(fontSize * LINE_HEIGHT) + 8 : 0\n const area = innerRect(width, height, { ...pad, bottom: pad.bottom + scaleHeight })\n const zoom = typeof options.zoom === 'object' ? options.zoom : {}\n const layout: MapLayout = {\n ...area,\n k: Math.max(0, Math.min(area.width / map.width, area.height / map.height)),\n mapWidth: map.width,\n mapHeight: map.height,\n max: Math.max(1, finite(zoom.max) ?? 8),\n }\n const view = fitView(options.view, layout)\n // (`k` is pixels per unit of the map as it is drawn, magnified by the view.)\n const k = Math.round(layout.k * view.scale * 1e4) / 1e4\n const tx = round(area.x - view.x * k)\n const ty = round(area.y - view.y * k)\n const px = (x: number) => tx + x * k\n const py = (y: number) => ty + y * k\n // A magnified map is cut at the edges of its room.\n const clipped = view.scale > 1\n const selected = new Set(selectedOf(options))\n\n // Markers, placed with the projection the map file was made with.\n const { projection } = map\n const project =\n isRecord(projection) &&\n finite(projection.scale) !== null &&\n Array.isArray(projection.translate) &&\n projection.translate.slice(0, 2).every((n) => finite(n) !== null)\n ? (lng: number, lat: number): [number, number] => [\n px(lng * RADIANS * projection.scale + (projection.translate[0] as number)),\n py(\n (projection.translate[1] as number) -\n 1.25 * Math.log(Math.tan(Math.PI / 4 + 0.4 * lat * RADIANS)) * projection.scale,\n ),\n ]\n : undefined\n const markers: NonNullable<Entry['marker']>[] = []\n if (project && k > 0) {\n for (const marker of options.markers ?? []) {\n const [x, y] = project(marker.lng, marker.lat)\n if (Number.isFinite(x) && Number.isFinite(y)) markers.push({ name: marker.name ?? '', x, y })\n }\n }\n const firstMarker = entries.length\n for (const marker of markers) entries.push({ marker, value: null })\n // Regions without a value are not walked by the keyboard, but still name themselves on hover.\n const count = entries.length\n for (const shape of shapes.values()) {\n if (shape.point || indexOf.has(shape)) continue\n indexOf.set(shape, entries.length)\n entries.push({ shape, value: null })\n }\n\n const hitAt = (i: number): MapHit | null => {\n const entry = entries[i]\n if (!entry) return null\n const { shape, marker } = entry\n const dot = marker ?? (shape?.point ? { x: px(shape.x), y: py(shape.y) } : undefined)\n const x = dot?.x ?? px(shape?.x ?? 0)\n const y = dot?.y ?? py(shape?.y ?? 0)\n const name = marker?.name ?? shape?.name ?? ''\n const v = entry.value\n return {\n index: i,\n label: shape?.code ?? name,\n ...(shape ? { region: shape.code } : { marker: name }),\n // One row, \"■ Poland 80\": a region without a value and a marker only name themselves.\n title: '',\n x,\n area,\n items: [\n {\n name,\n seriesIndex: 0,\n value: v,\n text: v === null ? '' : value(v),\n x,\n y,\n color: marker ? MARKER : v === null ? EMPTY : paint(position(v)).color,\n },\n ],\n highlight: {\n kind: 'halo',\n d: dot\n ? circlePath(dot.x, dot.y, radius + 3)\n : (shape?.rings ?? [])\n .map((ring) => {\n let d = ''\n for (let p = 0; p < ring.length; p += 2)\n d += `${p ? 'L' : 'M'}${Math.round(px(ring[p] as number) * 10) / 10} ${Math.round(py(ring[p + 1] as number) * 10) / 10}`\n return `${d}Z`\n })\n .join(''),\n },\n }\n }\n\n const interaction: MapInteraction = {\n count,\n map: layout,\n hitIndex: hitAt,\n hitTest(x, y) {\n if (!(k > 0)) return null\n if (x < area.x || x > area.x + area.width || y < area.y || y > area.y + area.height)\n return null\n const near = (dot: { x: number; y: number }) => Math.hypot(dot.x - x, dot.y - y) <= radius + 4\n // What is drawn on top is hit first: markers, then dots, then shapes.\n for (let i = count - 1; i >= firstMarker; i--)\n if (near(entries[i]?.marker as { x: number; y: number })) return hitAt(i)\n for (let i = 0; i < valued; i++) {\n const shape = entries[i]?.shape as Shape\n if (shape.point && near({ x: px(shape.x), y: py(shape.y) })) return hitAt(i)\n }\n const mx = (x - tx) / k\n const my = (y - ty) / k\n for (const [shape, i] of indexOf) {\n const [x0, y0, x1, y1] = shape.box\n if (shape.point || mx < x0 || mx > x1 || my < y0 || my > y1) continue\n if (inside(shape.rings, mx, my)) return hitAt(i)\n }\n return null\n },\n }\n const regions: VNode[] = []\n // A selected shape goes in after the others, where nothing covers its outline.\n const raised: VNode[] = []\n const points: VNode[] = []\n for (const shape of shapes.values()) {\n const i = indexOf.get(shape)\n const v = i === undefined ? null : (entries[i]?.value ?? null)\n const style = v === null ? undefined : paint(position(v)).style\n const chosen = selected.has(shape.code) && 'tc-region-selected'\n if (!shape.point) {\n ;(chosen ? raised : regions).push(\n h('path', {\n key: shape.code,\n class: ['tc-region', v === null ? 'tc-region-empty' : 'tc-cell', chosen],\n 'data-region': shape.code,\n d: shape.path,\n style,\n }),\n )\n } else if (v !== null) {\n // A country too small for a shape says nothing without a value, so only then is it drawn.\n points.push(\n h('circle', {\n key: shape.code,\n class: ['tc-region tc-region-point tc-cell', chosen],\n 'data-region': shape.code,\n cx: round(px(shape.x)),\n cy: round(py(shape.y)),\n r: radius,\n style,\n }),\n )\n }\n }\n\n // Lines go in before the markers, so the markers sit on top of their ends.\n const byName = new Map(markers.map((marker) => [marker.name, marker]))\n const lines = (options.lines ?? []).flatMap((line, i) => {\n const from = byName.get(line.from)\n const to = byName.get(line.to)\n if (!from || !to) return []\n // A curve through a point pushed sideways from the middle of the line.\n const cx = (from.x + to.x) / 2 + (to.y - from.y) * LINE_CURVE\n const cy = (from.y + to.y) / 2 - (to.x - from.x) * LINE_CURVE\n return h('path', {\n key: `${line.from}›${line.to}›${i}`,\n class: 'tc-map-line',\n d: `M${round(from.x)} ${round(from.y)}Q${round(cx)} ${round(cy)} ${round(to.x)} ${round(to.y)}`,\n })\n })\n\n // The scale, centered below the map: the lowest value, a bar of the colors, the highest.\n const scaleText = typeof options.scale === 'object' ? options.scale : {}\n const low = scaleText.low ?? value(lo)\n const high = scaleText.high ?? value(hi)\n const lowWidth = estimateTextWidth(low, fontSize)\n const barWidth = SCALE_STEPS * SCALE_STEP\n const scaleWidth = lowWidth + 8 + barWidth + 8 + estimateTextWidth(high, fontSize)\n const scaleX = Math.round(area.x + Math.max(0, (area.width - scaleWidth) / 2))\n const barX = Math.round(scaleX + lowWidth + 8)\n const scaleY = area.y + area.height + 8 + (scaleHeight - 8) / 2\n\n const selectable = options.select === 'single' || options.select === 'multiple'\n const clip = `${ctx.id}-map`\n\n const content = [\n clipped &&\n h(\n 'clipPath',\n { key: 'clip', id: clip },\n h('rect', { x: area.x, y: area.y, width: area.width, height: area.height }),\n ),\n h(\n 'g',\n {\n key: 'map',\n class: ['tc-map', selectable && 'tc-map-selectable'],\n 'clip-path': clipped ? `url(#${clip})` : undefined,\n },\n k > 0 &&\n h(\n 'g',\n {\n key: 'regions',\n class: 'tc-map-regions',\n transform: `translate(${tx} ${ty}) scale(${k})`,\n },\n regions,\n raised,\n ),\n h('g', { key: 'points', class: 'tc-map-points' }, points),\n h('g', { key: 'lines', class: 'tc-map-lines' }, lines),\n h(\n 'g',\n { key: 'markers', class: 'tc-map-markers' },\n markers.map((marker, i) =>\n h('circle', {\n key: `${marker.name}›${i}`,\n class: 'tc-map-marker',\n 'data-marker': marker.name,\n cx: round(marker.x),\n cy: round(marker.y),\n r: radius,\n }),\n ),\n ),\n ),\n scale &&\n h(\n 'g',\n // (Crisp edges: the slices of the bar meet without a seam.)\n {\n key: 'scale',\n class: 'tc-map-scale',\n 'aria-hidden': 'true',\n 'shape-rendering': 'crispEdges',\n },\n h('text', { class: 'tc-tick-label', x: scaleX, y: round(scaleY), dy: '0.32em' }, low),\n Array.from({ length: SCALE_STEPS }, (_, s) =>\n h('rect', {\n key: s,\n class: 'tc-cell',\n x: barX + s * SCALE_STEP,\n y: round(scaleY - SCALE_HEIGHT / 2),\n width: SCALE_STEP,\n height: SCALE_HEIGHT,\n style: paint(s / (SCALE_STEPS - 1)).style,\n }),\n ),\n h(\n 'text',\n { class: 'tc-tick-label', x: barX + barWidth + 8, y: round(scaleY), dy: '0.32em' },\n high,\n ),\n ),\n ]\n return { content, interaction }\n}\n\n/** Table: one row per region with a value, in the order of the data. */\nfunction mapTable(options: MapOptions, ctx: TableContext, limit: number): DataTable {\n const map = typeof options.map === 'string' ? maps[options.map] : options.map\n const shapes = isMap(map) ? shapesOf(map) : undefined\n const value = formatNumber(options.format, ctx.locale)\n const rows: string[][] = []\n for (const [code, raw] of Object.entries(options.data ?? {})) {\n const v = finite(raw)\n const shape = shapes?.get(code)\n if (shape && v !== null) rows.push([shape.name, value(v)])\n }\n return { columns: ['', 'Value'], total: rows.length, rows: rows.slice(0, limit) }\n}\n\n/** Width to height of the map with its scale at a usual size, so the map fills the chart. */\nfunction ratioOf(options: MapOptions): number | undefined {\n const map = typeof options.map === 'string' ? maps[options.map] : options.map\n if (!isMap(map)) return undefined\n const scale = options.scale !== false && Object.keys(options.data ?? {}).length > 0\n return round(600 / ((600 * map.height) / map.width + (scale ? 23 : 0)))\n}\n\n/** Values that are finite numbers, markers with real coordinates, lines and colors that are text. */\nconst cleanMap = (options: MapOptions): MapOptions => {\n const o = options as unknown as Record<string, unknown>\n const data: Record<string, number> = {}\n if (isRecord(o.data))\n for (const [code, v] of Object.entries(o.data)) {\n const n = finite(v)\n if (n !== null) data[code] = n\n }\n return {\n ...options,\n map: typeof o.map === 'string' || isMap(o.map) ? o.map : (undefined as never),\n data,\n colors: list(o.colors).filter((c): c is string => typeof c === 'string' && c.trim() !== ''),\n markers: records(o.markers, (m) => ({\n lat: finite(m.lat) as number,\n lng: finite(m.lng) as number,\n ...(typeof m.name === 'string' ? { name: m.name } : {}),\n })).filter((m) => m.lat !== null && m.lng !== null),\n lines: records(o.lines, (l) => ({ from: text(l.from), to: text(l.to) })),\n select: o.select === 'single' || o.select === 'multiple' ? o.select : undefined,\n selected: list(o.selected).filter((code): code is string => typeof code === 'string'),\n view: isRecord(o.view) ? (o.view as Partial<MapView>) : undefined,\n onSelect: typeof o.onSelect === 'function' ? (o.onSelect as MapOptions['onSelect']) : undefined,\n }\n}\n\n/**\n * Map: the regions of a map file as SVG shapes, shaded by value from the\n * empty shade to the full color (`--tc-heat-color`, the cells of the\n * heatmap) or through a scale of `colors`, with markers placed by their\n * coordinates, lines between them and a bar of the scale. The shapes come\n * projected from the map file, so no geo library ships to the browser.\n *\n * ```ts\n * import { world } from '@tabler/charts/maps/world'\n *\n * new Chart('#el', {\n * type: map,\n * map: world,\n * data: { PL: 80, DE: 45, US: 100 },\n * })\n * ```\n */\nexport const map: ChartType<MapOptions> = {\n name: 'map',\n // (The options come with the whole config: its proportions are defaulted here.)\n clean: (options) => {\n const config = cleanMap(options) as MapOptions & {\n aspectRatio?: number\n autoRatio?: number\n }\n // The ratio set here follows the map; one of your own is kept.\n if (config.aspectRatio !== undefined && config.aspectRatio !== config.autoRatio) return config\n const autoRatio = ratioOf(config)\n return { ...config, aspectRatio: autoRatio, autoRatio }\n },\n render: renderMap,\n table: mapTable,\n // Zoom, drag and selection: at work only with `zoom` or `select`.\n plugins: [mapInteraction()],\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext, RenderResult } 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 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 // biome-ignore lint/complexity/useMathMinMax: the ternary also turns a NaN `total` into 0, Math.max would not\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): RenderResult {\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 highlight: { kind: 'halo', d },\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\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 const content = [\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 return { content, interaction }\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 { LegendItem } from '../legend.ts'\nimport { keyOf, type Named } from './named.ts'\n\n/** Legend key of the slice that groups the rest. */\nconst OTHERS = '__others__'\n\n/** A slice or segment with its size, in color slot `index` (past the palette for Others). */\nexport interface Grouped<T> {\n data: T\n index: number\n value: number\n /** Set on the one slice that groups the rest: Others. */\n others?: true\n}\n\n/** How a chart of parts of a whole groups its smallest parts into one: Others. */\nexport interface SliceGrouping {\n /**\n * The most slices (or segments) drawn, Others included: with more entries\n * than that, the largest `maxSlices - 1` keep one of their own and the rest\n * share Others, the last one. Defaults to `9` (the eight palette colors\n * and Others); `0` never groups.\n */\n maxSlices?: number\n /** Name of Others, the slice that groups the rest. Defaults to `'Others'`. */\n othersLabel?: string\n}\n\n/**\n * The slices of the data in its order: every entry, or with more of them\n * than `maxSlices`, the largest ones and one slice for the rest (in the\n * color of the slots past the palette), named by `label`. `maxSlices` is nine\n * by default (the eight palette colors and the rest) and zero never groups.\n * Hidden entries count here, so hiding one does not pull another out of the\n * rest.\n */\nexport function groupSlices<T extends Named & { value: number }>(\n data: readonly T[],\n maxSlices: number | undefined,\n label = 'Others',\n): Grouped<T>[] {\n const all = data.map((entry, index) => ({\n data: entry,\n index,\n value: Math.max(0, entry.value || 0),\n }))\n const max = Number.isFinite(maxSlices) && (maxSlices as number) >= 0 ? maxSlices : 9\n const limit = max ? Math.max(1, Math.round(max)) : Number.POSITIVE_INFINITY\n if (all.length <= limit) return all\n const kept = new Set(\n [...all].sort((a, b) => b.value - a.value || a.index - b.index).slice(0, limit - 1),\n )\n const value = all.reduce((sum, slice) => (kept.has(slice) ? sum : sum + slice.value), 0)\n return [\n ...all.filter((slice) => kept.has(slice)),\n {\n data: { name: label, id: OTHERS, value } as T,\n index: Math.max(8, all.length),\n value,\n others: true,\n },\n ]\n}\n\n/** Legend entries of the slices as drawn, the rest included. */\nexport function groupLegend<T extends Named>(slices: readonly Grouped<T>[]): LegendItem[] {\n return slices.map(({ data, index }) => {\n const item: LegendItem = { key: keyOf(data), name: data.name, index }\n if (data.color) item.color = data.color\n if (data.hidden) item.hidden = true\n return item\n })\n}\n\n/** What the options of a chart with grouped slices hold. */\ninterface Sliced<T> extends SliceGrouping {\n data: readonly T[]\n}\n\n/** A chart model of grouped slices: the options, with their slices as drawn. */\nexport type WithSlices<O extends Sliced<unknown>> = O & { slices: Grouped<O['data'][number]>[] }\n\n/** The chart model of a chart with grouped slices: the options and their slices, worked out once. */\nexport const withSlices = <T extends Named & { value: number }, O extends Sliced<T>>(\n options: O,\n): WithSlices<O> => ({\n ...options,\n slices: groupSlices(options.data as readonly T[], options.maxSlices, options.othersLabel),\n})\n\n/** Legend entries of a chart model of grouped slices. */\nexport const slicesLegend = <T extends Named>(model: {\n slices: readonly Grouped<T>[]\n}): LegendItem[] => groupLegend(model.slices)\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext, RenderResult, TableContext } 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 { type ClassValue, h } from '../vnode.ts'\nimport { cleanItems } from './clean.ts'\nimport { groupAttrs, keyOf } from './named.ts'\nimport {\n type Grouped,\n type SliceGrouping,\n slicesLegend,\n type WithSlices,\n withSlices,\n} from './others.ts'\n\n/** One segment of a percentage bar. */\nexport interface PercentageBarSegment {\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 segment group. */\n class?: ClassValue\n /** Start hidden (toggle it back from the legend). */\n hidden?: boolean\n}\n\nexport interface PercentageBarOptions extends SliceGrouping {\n data: readonly PercentageBarSegment[]\n /**\n * Order of the segments along the bar: as in the data (`'data'`, the\n * default) or the largest first (`'size'`). Colors follow the data either\n * way, and Others always comes last.\n */\n order?: 'data' | 'size'\n /** Space between segments in pixels, drawn as surface. Defaults to `2`. */\n gap?: number\n /** Corner radius of the segments. Defaults to `4`. */\n radius?: number\n /** Format of the values (tooltip, table). */\n format?: NumberFormat\n /** Extra space around the bar, in pixels. */\n padding?: InsetsInput\n}\n\n/** Height of the chart when neither `height` nor `aspectRatio` is set: a strip. */\nconst HEIGHT = 16\n\ntype Segment = Grouped<PercentageBarSegment>\n\n/**\n * The chart model of a percentage bar: its options, with the segments of the\n * data (nine at most by default, the one for the rest included).\n */\nexport type PercentageBarModel = WithSlices<PercentageBarOptions>\n\n/** The visible segments in their order along the bar, and their sum. */\nfunction segmentsOf(\n options: PercentageBarModel,\n hidden: ReadonlySet<string>,\n): { segments: Segment[]; total: number } {\n const segments = options.slices.filter((segment) => !hidden.has(keyOf(segment.data)))\n if (options.order === 'size') {\n // (Others stays last, whatever its size.)\n segments.sort(\n (a, b) => Number(!!a.others) - Number(!!b.others) || b.value - a.value || a.index - b.index,\n )\n }\n return { segments, total: segments.reduce((sum, segment) => sum + segment.value, 0) }\n}\n\nfunction renderPercentageBar(options: PercentageBarModel, ctx: RenderContext): RenderResult {\n const { width, height, locale } = ctx\n const gap = Math.max(0, options.gap ?? 2)\n const radius = Math.max(0, options.radius ?? 4)\n const area = innerRect(width, height, insets(options.padding, 0))\n const { segments, total } = segmentsOf(options, ctx.hidden)\n const drawn = segments.filter((segment) => segment.value > 0)\n\n // Every segment gives up half a gap on each side but the ends of the bar.\n let offset = area.x\n const boxes = drawn.map((segment, position) => {\n const length = (segment.value / total) * area.width\n const left = position === 0 ? 0 : gap / 2\n const right = position === drawn.length - 1 ? 0 : gap / 2\n const boxWidth = Math.max(0, length - left - right)\n const start = offset + left\n const box = {\n // Right to left, the bar starts from the right: every segment takes its mirror place.\n x: ctx.rtl ? area.x * 2 + area.width - start - boxWidth : start,\n y: area.y,\n width: boxWidth,\n height: area.height,\n }\n offset += length\n return box\n })\n\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n const hitFor = (position: number): Hit => {\n const segment = drawn[position] as Segment\n const box = boxes[position] as (typeof boxes)[number]\n const x = box.x + box.width / 2\n const item: HitItem = {\n name: segment.data.name,\n seriesIndex: segment.index,\n value: segment.value,\n text: `${value(segment.value)} (${share.format(segment.value / total)})`,\n x,\n y: box.y + box.height / 2,\n box,\n }\n if (segment.data.color) item.color = segment.data.color\n const n = round\n return {\n index: position,\n label: segment.data.name,\n title: '',\n x,\n area,\n items: [item],\n seriesIndex: segment.index,\n // A ring just inside the hovered segment.\n highlight: {\n kind: 'halo',\n d: `M${n(box.x + 1)},${n(box.y + 1)}h${n(box.width - 2)}v${n(box.height - 2)}h${n(2 - box.width)}Z`,\n },\n }\n }\n\n const interaction: Interaction = {\n count: drawn.length,\n reversed: ctx.rtl === true,\n hitIndex: (position) => (drawn[position] ? hitFor(position) : null),\n hitTest(px, py) {\n if (py < area.y || py > area.y + area.height) return null\n const position = boxes.findIndex(\n (box) => px >= box.x - gap / 2 && px <= box.x + box.width + gap / 2,\n )\n return position < 0 ? null : hitFor(position)\n },\n }\n\n const content = h(\n 'g',\n { class: 'tc-percentage-bar' },\n // Empty: the track alone, so the chart keeps its place.\n drawn.length === 0 &&\n h('rect', {\n key: 'track',\n class: 'tc-percentage-bar-track',\n x: round(area.x),\n y: round(area.y),\n width: round(area.width),\n height: round(area.height),\n rx: round(Math.min(radius, area.width / 2, area.height / 2)),\n }),\n segments.map((segment) => {\n const box = boxes[drawn.indexOf(segment)]\n return h(\n 'g',\n groupAttrs(segment.data, segment.index),\n box &&\n h('rect', {\n class: 'tc-segment',\n x: round(box.x),\n y: round(box.y),\n width: round(box.width),\n height: round(box.height),\n rx: round(Math.min(radius, box.width / 2, box.height / 2)),\n }),\n )\n }),\n )\n return { content, interaction }\n}\n\nfunction percentageBarTable(options: PercentageBarModel, ctx: TableContext): DataTable {\n const { segments, total } = segmentsOf(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: segments.map((segment) => [\n segment.data.name,\n value(segment.value),\n share.format(total > 0 ? segment.value / total : 0),\n ]),\n }\n}\n\n/**\n * Percentage bar: parts of a whole as segments of one horizontal bar, each as\n * wide as its share (a donut's ring unrolled, for a strip under a number).\n * The chart is a strip 16 pixels tall unless `height` or `aspectRatio` is set.\n *\n * ```ts\n * new Chart('#el', {\n * type: percentageBar,\n * data: [{ name: 'Paid', value: 62 }, { name: 'Open', value: 27 }, { name: 'Overdue', value: 11 }],\n * })\n * ```\n */\nexport const percentageBar: ChartType<PercentageBarOptions, PercentageBarModel> = {\n name: 'percentage-bar',\n // (The options come with the whole config: its size is defaulted here.)\n clean: (options) => {\n const config = options as PercentageBarOptions & { height?: unknown; aspectRatio?: unknown }\n return {\n ...config,\n data: cleanItems(config.data),\n height: config.height ?? (config.aspectRatio ? undefined : HEIGHT),\n }\n },\n prepare: withSlices,\n render: renderPercentageBar,\n legend: slicesLegend,\n table: percentageBarTable,\n valueLabels: { marks: 'cell' },\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext, RenderResult, TableContext } from '../chart.ts'\nimport { feature } 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 ClassValue, h } from '../vnode.ts'\nimport { cleanData, cleanItems } from './clean.ts'\nimport { groupAttrs, keyOf } from './named.ts'\nimport { type SliceGrouping, slicesLegend, type WithSlices, withSlices } from './others.ts'\nimport type { SliceLabelOptions } from './slice-labels.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 extends SliceGrouping {\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 * Name every slice beside the chart, with its share, joined to the slice\n * by a line: `true`, or `{ value: 'value' }` for the values and\n * `{ value: false }` for the names alone. The pie gets smaller to leave the\n * labels room; a chart too small for them goes without. Needs\n * `@tabler/charts/slice-labels` on the core.\n */\n labels?: boolean | SliceLabelOptions\n}\n\n/** The chart model of a pie: its options, with the slices as drawn (the rest grouped). */\nexport type PieModel = WithSlices<PieOptions>\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 model: PieModel,\n hidden: ReadonlySet<string>,\n): { slices: Slice[]; total: number } {\n const visible = model.slices.filter((slice) => !hidden.has(keyOf(slice.data)))\n const total = visible.reduce((sum, slice) => sum + slice.value, 0)\n let angle = (model.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: PieModel,\n ctx: RenderContext,\n defaults: { inner: number; corner: number },\n) {\n const { width, height, locale } = ctx\n const gap = options.gap ?? 2\n const { slices, total } = layoutSlices(options, ctx.hidden)\n const drawn = slices.filter((slice) => slice.value > 0)\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n const frame = innerRect(width, height, insets(options.padding, 0))\n const shown = options.labels === true ? 'share' : options.labels ? options.labels.value : false\n const labelled = options.labels\n ? feature('slice-labels')(\n drawn.map((slice) => ({\n key: keyOf(slice.data),\n index: slice.index,\n name: slice.data.name,\n value:\n shown === false\n ? ''\n : shown === 'value'\n ? value(slice.value)\n : share.format(slice.value / total),\n angle: (slice.startAngle + slice.endAngle) / 2,\n weight: slice.value,\n })),\n frame,\n ctx.fontSize,\n )\n : null\n const area = labelled?.area ?? frame\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 // 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\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 highlight: {\n kind: 'halo',\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\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 const content = [\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 labelled?.layer(cx, cy, outer),\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 return { content, interaction }\n}\n\nfunction pieTable(options: PieModel, ctx: TableContext): 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(\n name: string,\n defaults: { inner: number; corner: number },\n): ChartType<PieOptions, PieModel> {\n return {\n name,\n clean: cleanData(cleanItems),\n prepare: withSlices,\n render: (options, ctx): RenderResult => renderPie(options, ctx, defaults),\n sweep,\n legend: slicesLegend,\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, PieModel> = 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, PieModel> = pieType('donut', { inner: 0.62, corner: 4 })\n","import type { ChartType, RenderContext, RenderResult } 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 { h } from '../vnode.ts'\nimport {\n type CartesianData,\n domainOf,\n type Label,\n labelKey,\n markerShape,\n pointMark,\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): RenderResult {\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 highlight: { kind: 'spoke', 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\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 shape = markerShape(options)\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 pointMark(\n shape,\n index,\n labelKey(label),\n 'tc-point',\n round(x),\n round(y),\n 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 const content = [\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 return { content, interaction }\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, RenderResult, TableContext } from '../chart.ts'\nimport {\n axisSize,\n axisTitleSize,\n bandTicks,\n linearTicks,\n type Tick,\n thinTicks,\n} from '../components/axis.ts'\nimport { feature } from '../features.ts'\nimport { formatDetail, type Locale, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { estimateTextWidth, type InsetsInput, plotFrame } from '../layout.ts'\nimport { band } from '../scales/band.ts'\nimport { extent } from '../scales/extent.ts'\nimport { linear } from '../scales/linear.ts'\nimport { rectPath } from '../shapes/rect.ts'\nimport { type ClassValue, h } from '../vnode.ts'\nimport type { Annotation } from './annotations.ts'\nimport {\n type CartesianOptions,\n domainOf,\n EDGE,\n finishLayout,\n TICK_SPACING_X,\n tickCount,\n toMs,\n} from './cartesian.ts'\nimport { cleanData, finite, isRecord, label, list, named, records } from './clean.ts'\n\n/** Where a range starts or ends: a number, or a date (a `Date`, a timestamp, an ISO string) on a time axis. */\nexport type RangeValue = number | string | Date\n\n/** One range: a bar from `from` to `to`, in the row of its `name`. */\nexport interface RangeBarItem {\n /** The row of the range; ranges with the same name share a row. */\n name: string\n from: RangeValue\n to: RangeValue\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 /** Extra classes on the bar. */\n class?: ClassValue\n}\n\n/** Options for the axis the ranges run along (at the bottom). */\nexport interface RangeAxisOptions {\n /**\n * `'time'` reads `from` and `to` as dates or timestamps and draws\n * calendar-aware ticks. Needs `@tabler/charts/time` (included in\n * `@tabler/charts`). Defaults to `'linear'`: plain numbers.\n */\n type?: 'linear' | 'time'\n /** Align time ticks to UTC instead of local time (use it for SSR). */\n utc?: boolean\n /** Render the axis labels. Defaults to `true`. */\n show?: boolean\n /** Title of the axis, below its labels. */\n title?: string\n /** Render vertical grid lines. Defaults to `true`. */\n grid?: boolean\n /** Fixed lower bound; overrides the data. */\n min?: RangeValue\n /** Fixed upper bound. */\n max?: RangeValue\n /** Extend the domain to round tick values. Defaults to `true`. */\n nice?: boolean\n /** Approximate tick count. Defaults to one per ~80px of width. */\n ticks?: number\n /**\n * Format of the values (ticks, tooltip, table). On a time axis only a\n * function counts: it gets the timestamp in milliseconds.\n */\n format?: NumberFormat\n}\n\n/** Options for the axis of the rows (beside the plot). */\nexport interface RangeRowAxisOptions {\n /** Render the row names. Defaults to `true`. */\n show?: boolean\n /** Title of the axis, turned 90° beside the names. */\n title?: string\n /** Render a horizontal grid line through every row. Defaults to `false`. */\n grid?: boolean\n}\n\n/**\n * A reference line or band of a range bar chart: a moment or a value on the\n * range axis (`x: '2026-03-01'`), a period (`x: [from, to]`), a row\n * (`y: 'Design'`) or the rows from one to another (`y: ['Design', 'Testing']`).\n * With a single `x` and a single `y` it is a point in that row.\n */\nexport interface RangeBarAnnotation extends Omit<Annotation, 'x' | 'y'> {\n x?: RangeValue | readonly [RangeValue, RangeValue]\n y?: string | readonly [string, string]\n}\n\nexport interface RangeBarOptions {\n /** The ranges, top to bottom in the order their names first come. */\n data: readonly RangeBarItem[]\n /** The axis the ranges run along. */\n x?: RangeAxisOptions\n /** The axis of the rows. */\n y?: RangeRowAxisOptions\n /** Corner radius of the bars. Defaults to `4`. */\n radius?: number\n /** Maximum bar thickness in pixels; leftover row space stays empty. Defaults to `24`. */\n maxBarWidth?: number\n /** Share of each row left empty between bars, `0…1`. Defaults to `0.3`. */\n groupPadding?: number\n /** Reference lines and bands: today, a deadline, a freeze. Needs `@tabler/charts/annotations` on the core. */\n annotations?: readonly RangeBarAnnotation[]\n /** Extra space around the plot area, in pixels. */\n padding?: InsetsInput\n}\n\n/** A range that can be drawn: its item, its row and its ends in axis units (lower first). */\ninterface Bar {\n item: RangeBarItem\n key: string\n row: number\n from: number\n to: number\n}\n\n/** The chart model: the options, with the ranges that can be drawn and their rows. */\ninterface RangeBarModel extends RangeBarOptions {\n timed: boolean\n rows: readonly string[]\n bars: readonly Bar[]\n}\n\n/** The shortest bar drawn, in pixels: a range with no length (a milestone) still shows. */\nconst MIN_LENGTH = 2\n\n/** Pixels around the plot area that still count as hovering it. */\nconst HOVER_SLOP = 8\n\nconst DAY = 24 * 60 * 60 * 1000\n\n/** A value in axis units (milliseconds on a time axis), or `null` when it has no place there. */\nconst position = (value: unknown, timed: boolean): number | null => {\n if (!timed) return finite(value)\n const ms = toMs(value as RangeValue)\n return Number.isFinite(ms) ? ms : null\n}\n\nfunction prepare(options: RangeBarOptions): RangeBarModel {\n const timed = options.x?.type === 'time'\n const rows: string[] = []\n const index = new Map<string, number>()\n const seen = new Map<string, number>()\n const bars: Bar[] = []\n for (const item of options.data) {\n const a = position(item.from, timed)\n const b = position(item.to, timed)\n if (a === null || b === null) continue\n let row = index.get(item.name)\n if (row === undefined) {\n row = rows.length\n index.set(item.name, row)\n rows.push(item.name)\n }\n // Ranges that share a name (and have no id) still need keys of their own.\n const base = item.id ?? item.name\n const nth = seen.get(base) ?? 0\n seen.set(base, nth + 1)\n bars.push({\n item,\n key: nth ? `${base}/${nth}` : base,\n row,\n from: Math.min(a, b),\n to: Math.max(a, b),\n })\n }\n return { ...options, timed, rows, bars }\n}\n\n/** How the ends of the ranges read in tooltips and the table. */\nfunction valueFormat(model: RangeBarModel, locale: Locale): (value: number) => string {\n const { format, utc } = model.x ?? {}\n if (!model.timed) return formatDetail(format, locale)\n if (typeof format === 'function') return format\n const [lo, hi] = extent(model.bars.flatMap((bar) => [bar.from, bar.to])) ?? [0, 0]\n const date = feature('dates')([lo, hi], utc, locale)\n return (value) => date(value)\n}\n\n/**\n * The annotations as the cartesian layers read them: there `y` is a value\n * on the value axis and `x` a category, here `x` runs along the ranges and\n * `y` names rows.\n */\nfunction annotationsOf(model: RangeBarModel): Annotation[] {\n const at = (v: unknown) => position(v, model.timed)\n return list(model.annotations)\n .filter(isRecord)\n .flatMap((a) => {\n const { x, y, ...rest } = a as RangeBarAnnotation\n const out: Annotation = { ...rest }\n if (x !== undefined) {\n const ends = Array.isArray(x) ? x.map(at) : at(x)\n if (ends === null || (Array.isArray(ends) && (ends.length !== 2 || ends.includes(null)))) {\n return []\n }\n out.y = ends as number | [number, number]\n }\n // A row is marked as a whole (a band), unless a single `x` makes it a point.\n if (y !== undefined) {\n out.x = typeof y === 'string' && (x === undefined || Array.isArray(x)) ? [y, y] : y\n }\n return [out]\n })\n}\n\n/** The range axis before the plot is placed: its domain and the ticks of a scale over it. */\nfunction rangeAxis(\n model: RangeBarModel,\n ctx: RenderContext,\n extra: readonly number[],\n): { domain: [number, number]; ticks(range: readonly [number, number]): Tick[] } {\n const options = model.x ?? {}\n const count = tickCount(options, Math.max(2, Math.round(ctx.width / TICK_SPACING_X)))\n const values = [...model.bars.flatMap((bar) => [bar.from, bar.to]), ...extra]\n const min = position(options.min, model.timed)\n const max = position(options.max, model.timed)\n if (!model.timed) {\n const { format } = options\n const bounds = { ...(min === null ? {} : { min }), ...(max === null ? {} : { max }) }\n const domain = domainOf(values, { ...bounds, nice: options.nice !== false }, false, count)\n return {\n domain,\n ticks: (range) => linearTicks(linear(domain, range), { count, format, locale: ctx.locale }),\n }\n }\n\n const time = feature('time').scale\n const utc = options.utc === true\n let [lo, hi] = extent(values) ?? [0, DAY]\n // A single moment still needs a visible range: the day around it.\n if (lo === hi) {\n lo -= DAY / 2\n hi += DAY / 2\n }\n if (min !== null) lo = min\n if (max !== null) hi = max\n if (options.nice !== false) {\n // Twice: the wider domain may call for a longer tick interval, whose\n // boundaries are then the ones the axis should end on.\n for (let pass = 0; pass < 2; pass++) {\n const [nlo, nhi] = time([lo, hi], [0, 1], { utc }).nice(count).domain\n if (min === null) lo = nlo\n if (max === null) hi = nhi\n }\n }\n const domain: [number, number] = [lo, hi]\n const { format } = options\n return {\n domain,\n ticks(range) {\n const scale = time(domain, range, { utc })\n const text =\n typeof format === 'function'\n ? (date: Date) => format(date.getTime())\n : scale.tickFormat(count, ctx.locale)\n return scale\n .ticks(count)\n .map((date) => ({ value: date.getTime(), position: scale(date), label: text(date) }))\n },\n }\n}\n\nfunction renderRangeBar(model: RangeBarModel, ctx: RenderContext): RenderResult {\n const { radius = 4, maxBarWidth = 24, groupPadding = 0.3, rows, bars } = model\n const { fontSize } = ctx\n const xOptions = model.x ?? {}\n const yOptions = model.y ?? {}\n const annotations = annotationsOf(model)\n // Annotations on the range axis stay in view, like targets on a value axis.\n const marked = annotations.flatMap((a) => (a.y === undefined ? [] : a.y))\n const axis = rangeAxis(model, ctx, marked)\n const showValues = xOptions.show !== false\n const showRows = yOptions.show !== false && rows.length > 0\n\n const probe = axis.ticks([0, 1])\n const names: Tick[] = rows.map((name) => ({ value: name, position: 0, label: name }))\n const edgeLabel = (tick: Tick | undefined) =>\n showValues && tick ? Math.ceil(estimateTextWidth(tick.label, fontSize) / 2) : 0\n\n const { area, side, range } = plotFrame(ctx, model.padding, (pad) => ({\n top: pad.top + EDGE / 2,\n bottom:\n pad.bottom +\n Math.max(\n (showValues ? axisSize('bottom', probe, fontSize) : 0) +\n axisTitleSize(xOptions.title, fontSize),\n EDGE / 2,\n ),\n start:\n pad.start +\n Math.max(\n (showRows ? axisSize('left', names, fontSize) : 0) +\n axisTitleSize(yOptions.title, fontSize),\n edgeLabel(probe[0]),\n EDGE,\n ),\n end: pad.end + Math.max(edgeLabel(probe[probe.length - 1]), EDGE),\n }))\n\n const across = band(rows, [area.y, area.y + area.height], {\n paddingInner: groupPadding,\n paddingOuter: groupPadding / 2,\n })\n // The ranges run from the start side: from the right in a right-to-left chart.\n const along = linear(axis.domain, range())\n const valueTicks = thinTicks(axis.ticks(along.range), 'bottom', fontSize)\n const rowTicks = showRows ? thinTicks(bandTicks(across), 'left', fontSize) : []\n\n // The shared layers read categories as `x` and values as `y`, whichever way they run.\n const cartesian: CartesianOptions = {\n data: { series: [] },\n x: { show: yOptions.show !== false, grid: yOptions.grid === true, title: yOptions.title },\n y: { show: showValues, grid: xOptions.grid !== false, title: xOptions.title },\n annotations,\n }\n const layout = finishLayout(\n cartesian,\n ctx,\n side,\n 0,\n {\n area,\n labels: rows,\n x: across,\n y: along,\n horizontal: true,\n xTicks: rowTicks,\n yTicks: valueTicks,\n },\n rows,\n )\n\n const thickness = Math.max(1, Math.min(maxBarWidth, across.bandwidth))\n const top = (bar: Bar) => across.at(bar.row) + (across.bandwidth - thickness) / 2\n /** The bar's ends in pixels, left first. */\n const ends = (bar: Bar): [number, number] => {\n const a = along(bar.from)\n const b = along(bar.to)\n const lo = Math.min(a, b)\n const hi = Math.max(a, b)\n if (hi - lo >= MIN_LENGTH) return [lo, hi]\n const mid = (lo + hi) / 2\n return [mid - MIN_LENGTH / 2, mid + MIN_LENGTH / 2]\n }\n\n const text = valueFormat(model, ctx.locale)\n const hitFor = (i: number): Hit => {\n const bar = bars[i] as Bar\n const [lo, hi] = ends(bar)\n const y = top(bar)\n const item: HitItem = {\n name: bar.item.name,\n seriesIndex: 0,\n // The length of the range; value labels write the range itself.\n value: bar.to - bar.from,\n text: `${text(bar.from)} – ${text(bar.to)}`,\n // The end the bar runs to.\n x: ctx.rtl ? lo : hi,\n y: y + thickness / 2,\n box: { x: lo, y, width: hi - lo, height: thickness },\n }\n if (bar.item.color) item.color = bar.item.color\n return {\n index: i,\n label: bar.item.name,\n title: '',\n x: (lo + hi) / 2,\n y: across.at(bar.row) + across.bandwidth / 2,\n axis: 'y',\n area,\n items: [item],\n highlight: {\n kind: 'band',\n x: area.x,\n y: across.at(bar.row),\n width: area.width,\n height: across.bandwidth,\n },\n }\n }\n\n const interaction: Interaction = {\n count: bars.length,\n hitIndex: (i) => (i >= 0 && i < bars.length ? hitFor(i) : null),\n hitTest(px, py) {\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 // The bar under the pointer in its row (the one drawn last), or the nearest one there.\n const row = across.indexAt(py)\n let found = -1\n let nearest = Number.POSITIVE_INFINITY\n bars.forEach((bar, i) => {\n if (bar.row !== row) return\n const [lo, hi] = ends(bar)\n const distance = Math.max(lo - px, px - hi, 0)\n if (distance <= nearest) {\n nearest = distance\n found = i\n }\n })\n if (found < 0) return null\n const hit = hitFor(found)\n if (nearest === 0) hit.seriesIndex = 0\n return hit\n },\n }\n\n const marks = bars.map((bar) => {\n const [lo, hi] = ends(bar)\n return h('path', {\n key: bar.key,\n class: ['tc-bar', 'tc-bar-horizontal', 'tc-range-bar', bar.item.class],\n 'data-series': bar.item.name,\n // A path, not a rect, so it morphs between updates (d), in Safari too.\n d: rectPath(lo, top(bar), hi - lo, thickness, Math.max(0, radius)),\n // A map, so values from data cannot inject CSS (see normalizeStyle).\n style: { '--tc-series-color': bar.item.color },\n })\n })\n\n const content = [\n h('defs', { key: 'defs' }, layout.clip.def),\n layout.background,\n h(\n 'g',\n { key: 'series', class: 'tc-series-list tc-range-bars', 'clip-path': layout.clip.url },\n // One color slot for every range: a bar's own `color` sets it apart.\n h('g', { class: 'tc-series tc-series-1' }, marks),\n ),\n layout.foreground,\n ]\n return { content, interaction }\n}\n\nfunction rangeBarTable(model: RangeBarModel, ctx: TableContext, limit: number): DataTable {\n const text = valueFormat(model, ctx.locale)\n const { bars } = model\n const shown = bars.length > limit ? bars.slice(0, limit) : bars\n return {\n columns: ['', 'From', 'To'],\n total: bars.length,\n rows: shown.map((bar) => [bar.item.name, text(bar.from), text(bar.to)]),\n }\n}\n\n/** Ranges with text for names; ends that are no number or date are left for `prepare` to drop. */\nconst cleanRanges = (data: unknown): unknown =>\n records(data, (r) => ({ ...named(r), from: label(r.from), to: label(r.to) }))\n\n/**\n * Range bar (timeline) chart: one row per name with a bar from `from` to\n * `to`, along a time axis (a roadmap, a schedule) or a number axis (floating\n * bars: salary bands, temperature ranges). Ranges with the same name share\n * a row.\n *\n * ```ts\n * new Chart('#el', {\n * type: rangeBar,\n * data: [\n * { name: 'Research', from: '2026-01-05', to: '2026-02-10' },\n * { name: 'Design', from: '2026-02-01', to: '2026-03-15' },\n * ],\n * x: { type: 'time' },\n * })\n * ```\n */\nexport const rangeBar: ChartType<RangeBarOptions, RangeBarModel> = {\n name: 'range-bar',\n clean: cleanData(cleanRanges),\n prepare,\n render: renderRangeBar,\n table: rangeBarTable,\n}\n","import type { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext, RenderResult } from '../chart.ts'\nimport { formatDetail, type NumberFormat } from '../format.ts'\nimport type { Highlight, Hit, HitItem, Interaction } from '../interaction.ts'\nimport {\n estimateTextWidth,\n type InsetsInput,\n innerRect,\n insets,\n LINE_HEIGHT,\n mirrorSides,\n type Rect,\n round,\n} from '../layout.ts'\nimport type { LegendItem } from '../legend.ts'\nimport { 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 // Right to left, the layout is worked out as its mirror image, then flipped.\n const { rtl } = ctx\n const area = innerRect(width, height, mirrorSides(insets(options.padding), rtl))\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 const x = plot.x + (columns > 1 ? c * step : (plot.width - nodeWidth) / 2)\n n.x = rtl ? width - x - nodeWidth : x\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 if (rtl) plot.x = width - plot.x - plot.width\n return { nodes, links, plot, nodeWidth, labels }\n}\n\n/** The x of a link's ends: the facing edges of its source and its target. */\nconst linkEnds = (link: Link, nodeWidth: number): [number, number] =>\n link.source.x > link.target.x\n ? [link.source.x, link.target.x + nodeWidth]\n : [link.source.x + nodeWidth, link.target.x]\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, x1] = linkEnds(link, nodeWidth)\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, x1] = linkEnds(link, nodeWidth)\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): RenderResult {\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): Highlight => ({\n kind: 'halo',\n d: `M0,0h${round(nodeWidth)}v${round(n.height)}h${round(-nodeWidth)}Z`,\n x: n.x,\n y: n.y,\n under: true,\n })\n // Marks go under the chart: over it, a hovered flow would cover the labels on it.\n const linkMark = (link: Link): Highlight => ({\n kind: 'halo',\n d: linkPath(link, nodeWidth),\n under: true,\n })\n const linkItem = (link: Link): HitItem => ({\n name: `${link.source.data.name} ${ctx.rtl ? '←' : '→'} ${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 highlight: link ? linkMark(link) : 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 highlight: linkMark(link),\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\n const content = [\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 // The label's side is the one of the left-to-right layout: mirrored with it.\n const before = (label.side === 'left') !== (ctx.rtl === true)\n const x = round(before ? n.x - LABEL_GAP : n.x + nodeWidth + LABEL_GAP)\n const y = round(n.y + n.height / 2)\n const anchor = before ? '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 return { content, interaction }\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 {\n axis,\n axisSize,\n axisTitle,\n axisTitleSize,\n type Tick,\n thinTicks,\n} 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 { estimateTextWidth, type InsetsInput, LINE_HEIGHT, plotFrame, round } 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 /** A number on a value axis; on a category axis, the label the point stands at. */\n x: number | string\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 * Write values on this series' marks, whatever the chart's `valueLabels`\n * says: `true` labels it even when the chart option is off, `false` leaves\n * it out. Needs `@tabler/charts/value-labels` on the core.\n */\n valueLabels?: boolean\n}\n\nexport interface ScatterData {\n /**\n * Categories along x, in their order: the x axis then shows these names and\n * each point stands at the label its `x` names (points naming none are left\n * out). Without `labels`, points with a text `x` make the categories\n * themselves, in order of appearance.\n */\n labels?: readonly (string | number)[]\n series: readonly ScatterSeries[]\n}\n\nexport interface ScatterOptions {\n data: ScatterData\n /**\n * Horizontal value axis; `reverse` runs it from the right (the default with\n * `rtl`). Over categories only `show`, `title`, `grid` and `reverse` apply.\n */\n x?: ValueAxisOptions & { reverse?: boolean }\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/**\n * The categories of the x axis, or `null` when it is a value axis: `data.labels`,\n * else every `x` in order of appearance once any of them is text.\n */\nfunction categories(data: ScatterData): string[] | null {\n if (data.labels) return data.labels.map(String)\n if (!data.series.some((s) => s.points.some((p) => typeof p.x === 'string'))) return null\n return [...new Set(data.series.flatMap((s) => s.points.map((p) => String(p.x))))]\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\n/** An `x` as text for the tooltip and the table: the category's name, or the formatted number. */\nfunction xText(options: ScatterOptions, locale: RenderContext['locale']) {\n const format = formatDetail(options.x?.format, locale)\n const named = !!categories(options.data)\n return (value: number | string) =>\n named || typeof value === 'string' ? String(value) : format(value)\n}\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 const labels = categories(options.data)\n // Where each category stands (the first of two with one name).\n const index = new Map((labels ?? []).map((label, i) => [label, i] as const).reverse())\n // Only points that can be plotted on both axes take part.\n const usable = (p: ScatterPoint) =>\n (labels ? index.has(String(p.x)) : typeof p.x === 'number' && plottable(p.x, xOptions)) &&\n plottable(p.y, yOptions)\n const shown = points.filter(usable)\n const xDomain = domainOf(labels ? [] : shown.map((p) => p.x as number), xOptions, false, countX)\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: Tick[] = labels\n ? labels.map((label) => ({ value: label, position: 0, label }))\n : ticksOf(valueScale(xDomain, [0, 1], xOptions), xOptions, countX)\n // What an edge label needs beside the plot: half of it on a value axis, where\n // it is centered on the edge; over categories it has half a band of room first.\n const half = (tick: Tick | undefined, halfBand = 0) =>\n showX && tick\n ? Math.max(0, Math.ceil(estimateTextWidth(tick.label, fontSize) / 2 - halfBand))\n : 0\n const reverse = xOptions.reverse ?? ctx.rtl === true\n // The x tick on the start side of the plot, and the one on the end side.\n const near = reverse === (ctx.rtl === true) ? 0 : probeX.length - 1\n const valueWidth =\n (showY ? axisSize('left', probeY, fontSize) : 0) + axisTitleSize(yOptions.title, fontSize)\n const { area, side, range } = plotFrame(ctx, options.padding, (pad) => {\n const sides = (halfBand: number) => ({\n start: pad.start + Math.max(valueWidth, half(probeX[near], halfBand), overhang),\n end: pad.end + Math.max(half(probeX[probeX.length - 1 - near], halfBand), overhang, EDGE),\n })\n let both = sides(0)\n // The band depends on the margins, so they are worked out twice.\n if (labels?.length) both = sides((width - both.start - both.end) / (labels.length * 2))\n return {\n top:\n pad.top + Math.max(showY ? Math.ceil((fontSize * LINE_HEIGHT) / 2) : 0, overhang, EDGE / 2),\n bottom:\n pad.bottom +\n Math.max(\n (showX ? axisSize('bottom', probeX, fontSize) : 0) +\n axisTitleSize(xOptions.title, fontSize),\n overhang,\n EDGE / 2,\n ),\n ...both,\n }\n })\n const y = valueScale(yDomain, [area.y + area.height, area.y], yOptions)\n // Pixel of an `x`, and the ticks of its axis: a point stands in the middle of its category.\n let x: (value: number | string) => number\n let allX: Tick[]\n if (labels) {\n // Equal bands along the range (it runs backwards when reversed).\n const [from, to] = range(reverse)\n const at = (i: number) => from + ((to - from) * (i + 0.5)) / labels.length\n x = (value) => at(index.get(String(value)) as number)\n allX = labels.map((label, i) => ({ value: label, position: at(i), label }))\n } else {\n const scale = valueScale(xDomain, range(reverse), xOptions)\n x = (value) => scale(value as number)\n allX = ticksOf(scale, xOptions, countX)\n }\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(allX, '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 = xText(options, 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 highlight: { kind: 'halo', 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\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 const content = [\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: side, ticks: yTicks, area }),\n showX && axis({ position: 'bottom', ticks: xTicks, area }),\n !!yOptions.title && axisTitle(side, showY ? yTicks : [], area, yOptions.title, fontSize),\n !!xOptions.title && axisTitle('bottom', showX ? xTicks : [], area, xOptions.title, fontSize),\n ]\n return { content, interaction }\n}\n\nfunction scatterTable(\n options: ScatterOptions,\n ctx: RenderContext,\n limit: number = Number.POSITIVE_INFINITY,\n): DataTable {\n const fx = xText(options, 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). With `data.labels` (or a text `x`)\n * the points stand over named categories instead.\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 labels: isRecord(data) && Array.isArray(data.labels) ? data.labels.map(text) : undefined,\n series: records(isRecord(data) && data.series, (s) => ({\n ...named(s),\n points: records(s.points, (p) => ({\n ...p,\n x: typeof p.x === 'string' ? p.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, markerShape, pointMark } 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 // Right to left, the values run from the right: value `i` takes the place of its mirror.\n const place = (i: number) => (ctx.rtl ? count - 1 - i : i)\n const xAt = (i: number) =>\n bars\n ? area.x + slot * place(i) + slot / 2\n : area.x + (count > 1 ? (area.width * place(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) {\n hit.highlight = { kind: 'halo', d: circlePath(pointRadius + 3), x: px, y: yOf(value) }\n }\n return hit\n }\n const interaction: Interaction = {\n count,\n reversed: ctx.rtl === true,\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(place(Math.max(0, Math.min(count - 1, i))))\n },\n }\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 shape = markerShape(options)\n const dotAt = (i: number, cls: string) => {\n const v = values[i]\n return v == null\n ? null\n : pointMark(\n shape,\n 0,\n `${cls}-${i}`,\n ['tc-point', cls],\n round(xAt(i)),\n round(y(v)),\n 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 const content = [\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 return { content, interaction }\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 { DataTable } from '../a11y.ts'\nimport type { ChartType, RenderContext, RenderResult, TableContext } from '../chart.ts'\nimport { formatNumber, getNumberFormat, type NumberFormat } from '../format.ts'\nimport type { Hit, HitItem, Interaction } from '../interaction.ts'\nimport { estimateTextWidth, type InsetsInput, innerRect, insets, round } from '../layout.ts'\nimport { rectPath } from '../shapes/rect.ts'\nimport { type ClassValue, h } from '../vnode.ts'\nimport { cleanData, finite, isRecord, list, named } from './clean.ts'\nimport { fit } from './fit.ts'\nimport { type HeatScale, heatScale } from './heat.ts'\nimport { groupAttrs, keyOf, legendItems } from './named.ts'\n\n/** A tile of a treemap, or a group of them. */\nexport interface TreemapNode {\n name: string\n /** Size of the tile; a negative value is zero. A group is as large as its `children`. */\n value?: number\n /** Tiles (or groups) inside this one; they share its color. */\n children?: readonly TreemapNode[]\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 * Not used when the tiles are shaded by value.\n */\n color?: string\n /** Extra classes on the group (top level) or the tile. */\n class?: ClassValue\n /** Start hidden (top level; toggle it back from the legend, which there is none of when shaded by value). */\n hidden?: boolean\n}\n\nexport interface TreemapOptions {\n /** Tiles, or groups of tiles; each top-level entry takes a palette color and a legend entry. */\n data: readonly TreemapNode[]\n /**\n * `'value'` shades every tile in one hue, `--tc-heat-color`, lighter as\n * the value drops (as a heatmap does), with no legend; `'series'` (the\n * default) gives each top-level entry its palette color.\n */\n colorBy?: 'series' | 'value'\n /**\n * A continuous scale through two or more colors (any CSS color, including\n * `var(--tc-…)`), from `min` to `max`; the tiles are then colored by value\n * whatever `colorBy` says. Values that could inject CSS are ignored, as\n * for the colors of the nodes.\n */\n colors?: readonly string[]\n /** Value shown with the lightest shade (or the first color). Defaults to `0`. */\n min?: number\n /** Value shown with the full color (or the last color). Defaults to the largest tile. */\n max?: number\n /** Value placed on the middle color of `colors`. Defaults to halfway. */\n mid?: number\n /** Space between tiles in pixels. Defaults to `2`. */\n gap?: number\n /** Corner radius of the tiles. Defaults to `3`. */\n radius?: number\n /** Names (and values, where they fit) written in the tiles. Defaults to `true`. */\n labels?: boolean\n /** Format of the values (tiles, tooltip, table). */\n format?: NumberFormat\n /** Extra space around the chart, in pixels. */\n padding?: InsetsInput\n}\n\n/** Levels of nesting read from the data, and the most nodes: enough for any chart, few enough to draw. */\nconst MAX_DEPTH = 8\nconst MAX_NODES = 5000\n\n/** Space between a tile's edge and its text. */\nconst INSET = 6\n\n/** Share of the full color at the minimum, so the smallest tile still reads as a tile. */\nconst FLOOR = 0.08\n\n/** A node with its size worked out. */\nexport interface Sized {\n node: TreemapNode\n value: number\n children?: Sized[]\n}\n\ninterface Tile {\n node: TreemapNode\n key: string\n /** Position of the top-level ancestor in `data` (the color slot). */\n top: number\n /** Names of the ancestors, outermost first. */\n trail: readonly string[]\n value: number\n x: number\n y: number\n width: number\n height: number\n}\n\nfunction sized(nodes: readonly TreemapNode[]): Sized[] {\n return nodes.map((node) => {\n if (node.children?.length) {\n const children = sized(node.children)\n return { node, children, value: children.reduce((sum, child) => sum + child.value, 0) }\n }\n return { node, value: Math.max(0, node.value ?? 0) }\n })\n}\n\n/** The chart model of a treemap: its options, with every node's size worked out. */\nexport type TreemapModel = TreemapOptions & { sized: Sized[] }\n\n/** The stops of the `colors` scale, when there are enough of them. */\nconst stopsOf = (options: TreemapOptions): readonly string[] | undefined =>\n Array.isArray(options.colors) && options.colors.length >= 2 ? options.colors : undefined\n\n/** Whether the tiles are colored by their value, not by their group. */\nconst byValue = (options: TreemapOptions): boolean =>\n options.colorBy === 'value' || stopsOf(options) !== undefined\n\n/** The color scale of a treemap shaded by value, over every tile (hidden ones too, so it stays put). */\nfunction scale(options: TreemapModel): (v: number) => ReturnType<HeatScale['paint']> {\n let largest = 0\n const walk = (items: readonly Sized[]) => {\n for (const item of items) {\n if (item.children) walk(item.children)\n else largest = Math.max(largest, item.value)\n }\n }\n walk(options.sized)\n const { position, paint } = heatScale(\n finite(options.min) ?? 0,\n finite(options.max) ?? largest,\n finite(options.mid),\n stopsOf(options),\n FLOOR,\n )\n return (v) => paint(position(v))\n}\n\n/**\n * The top-level entries with their sizes and color slots, without the hidden\n * ones. Shaded by value there is no legend to hide them from, so `hidden` is\n * read from the data.\n */\nfunction visible(model: TreemapModel, hidden: ReadonlySet<string>) {\n const fixed = byValue(model)\n return model.sized\n .map((entry, index) => ({ entry, index }))\n .filter(({ entry }) => !hidden.has(keyOf(entry.node)) && !(fixed && entry.node.hidden))\n}\n\n/**\n * Squarified layout (Bruls, Huizing, van Wijk): `items`, largest first, fill\n * the rectangle in rows along its shorter side, each row closed as soon as\n * another item would make its tiles less square.\n */\nfunction squarify(\n items: readonly Sized[],\n x: number,\n y: number,\n w: number,\n hgt: number,\n place: (item: Sized, x: number, y: number, w: number, hgt: number) => void,\n): void {\n const sorted = items.filter((item) => item.value > 0).sort((a, b) => b.value - a.value)\n let left = sorted.reduce((sum, item) => sum + item.value, 0)\n let i = 0\n while (i < sorted.length && w > 0 && hgt > 0) {\n const short = Math.min(w, hgt)\n // Pixels of area per unit of value in what is left of the rectangle.\n const k = (w * hgt) / left\n const largest = (sorted[i] as Sized).value\n let sum = 0\n let best = Number.POSITIVE_INFINITY\n let j = i\n for (; j < sorted.length; j++) {\n const next = sum + (sorted[j] as Sized).value\n // Thickness of the row squared: its worst tile is the largest or the smallest.\n const t2 = ((next * k) / short) ** 2\n const worst = Math.max(t2 / ((sorted[j] as Sized).value * k), (largest * k) / t2)\n if (worst > best) break\n best = worst\n sum = next\n }\n const thickness = (sum * k) / short\n let offset = 0\n for (; i < j; i++) {\n const item = sorted[i] as Sized\n const length = (item.value * k) / thickness\n if (w >= hgt) place(item, x, y + offset, thickness, length)\n else place(item, x + offset, y, length, thickness)\n offset += length\n }\n if (w >= hgt) {\n x += thickness\n w -= thickness\n } else {\n y += thickness\n hgt -= thickness\n }\n left -= sum\n }\n}\n\n/** Half gaps left around a tile on its left, top, right and bottom side. */\ntype Edges = readonly [number, number, number, number]\n\n/**\n * The tiles of `items` in a rectangle, groups laid out inside their own.\n * The gap is cut from the tiles after they are placed, so it does not change\n * their arrangement: half of it on every side (a whole one between any two\n * neighbors), none at the edge of the chart. `edges` are the half gaps of\n * the rectangle itself.\n */\nfunction layout(\n items: readonly Sized[],\n x: number,\n y: number,\n w: number,\n hgt: number,\n gap: number,\n out: Tile[],\n edges: Edges,\n top?: { index: number; key: string; trail: readonly string[] },\n slots?: readonly number[],\n): void {\n squarify(items, x, y, w, hgt, (item, tx, ty, tw, th) => {\n const index = top?.index ?? (slots?.[items.indexOf(item)] as number)\n const key = top ? `${top.key}/${keyOf(item.node)}` : keyOf(item.node)\n const trail = top?.trail ?? []\n // A side on the border of the rectangle takes its half gap (none at the chart's edge), the others one.\n const near = 0.01\n const sides: Edges = [\n tx - x < near ? edges[0] : 1,\n ty - y < near ? edges[1] : 1,\n x + w - tx - tw < near ? edges[2] : 1,\n y + hgt - ty - th < near ? edges[3] : 1,\n ]\n if (item.children) {\n layout(item.children, tx, ty, tw, th, gap, out, sides, {\n index,\n key,\n trail: [...trail, item.node.name],\n })\n } else {\n const half = gap / 2\n out.push({\n node: item.node,\n key,\n top: index,\n trail,\n value: item.value,\n x: tx + sides[0] * half,\n y: ty + sides[1] * half,\n width: Math.max(0, tw - (sides[0] + sides[2]) * half),\n height: Math.max(0, th - (sides[1] + sides[3]) * half),\n })\n }\n })\n}\n\nfunction renderTreemap(options: TreemapModel, ctx: RenderContext): RenderResult {\n const { width, height, fontSize, locale } = ctx\n const gap = Math.max(0, options.gap ?? 2)\n const radius = Math.max(0, options.radius ?? 3)\n const area = innerRect(width, height, insets(options.padding, 0))\n const entries = visible(options, ctx.hidden)\n const total = entries.reduce((sum, { entry }) => sum + entry.value, 0)\n\n const tiles: Tile[] = []\n layout(\n entries.map(({ entry }) => entry),\n area.x,\n area.y,\n area.width,\n area.height,\n gap,\n tiles,\n [0, 0, 0, 0],\n undefined,\n entries.map(({ index }) => index),\n )\n\n const paint = byValue(options) ? scale(options) : undefined\n const value = formatNumber(options.format, locale)\n const share = getNumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 })\n const hitFor = (tile: Tile, index: number): Hit => {\n const x = tile.x + tile.width / 2\n const item: HitItem = {\n name: tile.node.name,\n seriesIndex: tile.top,\n value: tile.value,\n text: `${value(tile.value)} (${share.format(total > 0 ? tile.value / total : 0)})`,\n x,\n y: tile.y + tile.height / 2,\n }\n const color = paint\n ? paint(tile.value).color\n : (tile.node.color ?? options.data[tile.top]?.color)\n if (color) item.color = color\n return {\n index,\n label: [...tile.trail, tile.node.name].join(' › '),\n title: tile.trail.join(' › '),\n x,\n area,\n items: [item],\n seriesIndex: tile.top,\n // A ring just inside the hovered tile.\n highlight: {\n kind: 'halo',\n d: rectPath(tile.x + 1, tile.y + 1, tile.width - 2, tile.height - 2, radius - 1),\n },\n }\n }\n\n const interaction: Interaction = {\n count: tiles.length,\n hitIndex: (index) => {\n const tile = tiles[index]\n return tile ? hitFor(tile, index) : null\n },\n hitTest(px, py) {\n const index = tiles.findIndex(\n (tile) =>\n px >= tile.x - gap / 2 &&\n px <= tile.x + tile.width + gap / 2 &&\n py >= tile.y - gap / 2 &&\n py <= tile.y + tile.height + gap / 2,\n )\n return index < 0 ? null : hitFor(tiles[index] as Tile, index)\n },\n }\n\n const groups = entries.map(({ entry, index }) =>\n h(\n 'g',\n groupAttrs(entry.node, index),\n tiles\n .filter((tile) => tile.top === index)\n .map((tile) =>\n h('rect', {\n key: tile.key,\n class: ['tc-tile', paint && 'tc-tile-shaded', tile.trail.length > 0 && tile.node.class],\n x: round(tile.x),\n y: round(tile.y),\n width: round(tile.width),\n height: round(tile.height),\n rx: round(Math.min(radius, tile.width / 2, tile.height / 2)),\n // Shaded by its value, or in its group's color: a tile inside a group may have its own.\n style: paint\n ? paint(tile.value).style\n : tile.trail.length > 0\n ? { '--tc-series-color': tile.node.color }\n : undefined,\n }),\n ),\n ),\n )\n\n // Names where a few letters fit, values below where there is a second line.\n const line = fontSize * 1.3\n const labels =\n options.labels !== false &&\n tiles.flatMap((tile) => {\n const room = tile.width - INSET * 2\n const name = tile.height >= line + INSET ? fit(tile.node.name, room, fontSize) : ''\n if (!name) return []\n const text = value(tile.value)\n const x = round(tile.x + INSET)\n const y = tile.y + INSET + fontSize * 0.85\n return [\n h('text', { key: tile.key, class: 'tc-treemap-label', x, y: round(y) }, name),\n tile.height >= line * 2 + INSET * 1.5 &&\n estimateTextWidth(text, fontSize) <= room &&\n h(\n 'text',\n {\n key: `${tile.key}/value`,\n class: 'tc-treemap-label tc-treemap-value',\n x,\n y: round(y + line),\n },\n text,\n ),\n ]\n })\n\n const content = [\n h('g', { class: 'tc-treemap-tiles' }, groups),\n labels && h('g', { class: 'tc-treemap-labels', 'aria-hidden': 'true' }, labels),\n ]\n return { content, interaction }\n}\n\nfunction treemapTable(options: TreemapModel, ctx: TableContext, limit: number): DataTable {\n const entries = visible(options, ctx.hidden)\n const total = entries.reduce((sum, { entry }) => sum + entry.value, 0)\n const value = formatNumber(options.format, ctx.locale)\n const share = getNumberFormat(ctx.locale, { style: 'percent', maximumFractionDigits: 1 })\n const rows: string[][] = []\n const walk = (items: readonly Sized[], trail: readonly string[]) => {\n for (const item of items) {\n const path = [...trail, item.node.name]\n if (item.children) walk(item.children, path)\n else {\n rows.push([\n path.join(' › '),\n value(item.value),\n share.format(total > 0 ? item.value / total : 0),\n ])\n }\n }\n }\n walk(\n entries.map(({ entry }) => entry),\n [],\n )\n const table: DataTable = { columns: ['', 'Value', 'Share'], rows }\n if (rows.length > limit) {\n table.rows = rows.slice(0, limit)\n table.total = rows.length\n }\n return table\n}\n\n/** Nodes with text for names and finite values, at most `MAX_DEPTH` deep and `MAX_NODES` in all. */\nfunction cleanNodes(data: unknown, depth = 0, budget = { left: MAX_NODES }): TreemapNode[] {\n const nodes: TreemapNode[] = []\n for (const r of list(data)) {\n if (!isRecord(r) || budget.left <= 0) continue\n budget.left--\n const children =\n depth < MAX_DEPTH && Array.isArray(r.children)\n ? cleanNodes(r.children, depth + 1, budget)\n : undefined\n nodes.push({ ...named(r), value: finite(r.value) ?? 0, children } as unknown as TreemapNode)\n }\n return nodes\n}\n\n/**\n * Treemap: parts of a whole as tiles, each as large as its value, laid out\n * as close to squares as they go with the largest in the top left corner.\n * Entries with `children` are groups: their tiles stay together and share\n * the group's color. `colorBy: 'value'` shades the tiles in one hue instead\n * (`--tc-heat-color`), lighter as the value drops, and `colors` sets a scale\n * of colors for it.\n *\n * ```ts\n * new Chart('#el', {\n * type: treemap,\n * data: [\n * { name: 'Search', value: 42 },\n * { name: 'Social', children: [{ name: 'Video', value: 18 }, { name: 'Posts', value: 9 }] },\n * ],\n * })\n * ```\n */\nexport const treemap: ChartType<TreemapOptions, TreemapModel> = {\n name: 'treemap',\n clean: cleanData((data) => cleanNodes(data)),\n prepare: (options) => ({ ...options, sized: sized(options.data) }),\n render: renderTreemap,\n // Shaded by value there is one hue, and nothing for a legend to tell apart.\n legend: (options) => (byValue(options) ? [] : legendItems(options.data)),\n table: treemapTable,\n}\n","import type { ChartType } from './chart.ts'\nimport { area } from './charts/area.ts'\nimport { bar } from './charts/bar.ts'\nimport { calendar } from './charts/calendar.ts'\nimport { candlestick } from './charts/candlestick.ts'\nimport { funnel } from './charts/funnel.ts'\nimport { gauge } from './charts/gauge.ts'\nimport { heatmap } from './charts/heatmap.ts'\nimport { line } from './charts/line.ts'\nimport { map } from './charts/map.ts'\nimport { parliament } from './charts/parliament.ts'\nimport { percentageBar } from './charts/percentage-bar.ts'\nimport { donut, pie } from './charts/pie.ts'\nimport { radar } from './charts/radar.ts'\nimport { rangeBar } from './charts/range-bar.ts'\nimport { sankey } from './charts/sankey.ts'\nimport { scatter } from './charts/scatter.ts'\nimport { sparkline } from './charts/sparkline.ts'\nimport { treemap } from './charts/treemap.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 calendar,\n map,\n candlestick,\n radar,\n sankey,\n parliament,\n treemap,\n 'percentage-bar': percentageBar,\n funnel,\n 'range-bar': rangeBar,\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 BuiltChart,\n ChartConfig,\n ChartEvents,\n ChartType,\n ContextOptions,\n CrosshairOptions,\n RenderContext,\n RenderResult,\n ResolvedLegend,\n Size,\n TableContext,\n} from './chart.ts'\nexport {\n buildChart,\n Chart,\n chartEvents,\n chartLabel,\n chartModel,\n chartToString,\n renderChart,\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 {\n CalendarData,\n CalendarEntry,\n CalendarOptions,\n CalendarSeries,\n} from './charts/calendar.ts'\nexport { calendar } from './charts/calendar.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 { FunnelOptions, FunnelStage } from './charts/funnel.ts'\nexport { funnel } from './charts/funnel.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 {\n MapData,\n MapHit,\n MapLayout,\n MapLine,\n MapMarker,\n MapOptions,\n MapRegion,\n MapView,\n} from './charts/map.ts'\nexport { addMap, map } from './charts/map.ts'\nexport type { ParliamentOptions, ParliamentParty } from './charts/parliament.ts'\nexport { parliament } from './charts/parliament.ts'\nexport type { PercentageBarOptions, PercentageBarSegment } from './charts/percentage-bar.ts'\nexport { percentageBar } from './charts/percentage-bar.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 {\n RangeAxisOptions,\n RangeBarAnnotation,\n RangeBarItem,\n RangeBarOptions,\n RangeRowAxisOptions,\n RangeValue,\n} from './charts/range-bar.ts'\nexport { rangeBar } from './charts/range-bar.ts'\nexport type { SankeyData, SankeyLink, SankeyNode, SankeyOptions } from './charts/sankey.ts'\nexport { sankey } from './charts/sankey.ts'\nexport type { ScatterData, 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 { TreemapNode, TreemapOptions } from './charts/treemap.ts'\nexport { treemap } from './charts/treemap.ts'\nexport type { ViewWindow, ZoomOptions } from './charts/view.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, hoverValue } 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 {\n Highlight,\n Hit,\n HitCursor,\n HitItem,\n HitTester,\n Interaction,\n} 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 zoom,\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, end labels, slice labels, point shapes). The exceptions\n * are the `download` menu's saver and zoom: `import '@tabler/charts/export'`\n * and `import '@tabler/charts/zoom'` add them, so charts that never offer a\n * download or a zoom do not carry their code.\n */\n\nimport { annotationLayers, annotationValues } from './charts/annotations.ts'\nimport { dateLabels } from './charts/dates.ts'\nimport { endLabels } from './charts/end-labels.ts'\nimport { logDomain, logTicks } from './charts/log-axis.ts'\nimport { patternFills } from './charts/patterns.ts'\nimport { markerClip, markerPath } from './charts/point-shapes.ts'\nimport { sliceLabels } from './charts/slice-labels.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 'end-labels': endLabels,\n 'slice-labels': sliceLabels,\n patterns: patternFills,\n 'point-shapes': markerPath,\n swatch: markerClip,\n hydrate,\n morph,\n})\n\n// The step that finishes the content: value labels over the marks.\naddPost(labelsStep)\n\nexport { Chart } from './chart-default.ts'\nexport { types } from './chart-types.ts'\nexport * from './core.ts'\nexport type {\n CSVOptions,\n DownloadOptions,\n ExportOptions,\n ExportTarget,\n ImageOptions,\n} from './export-chart.ts'\nexport { downloadChart, exportCSV, 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' && /^(top|bottom|left|right|auto)$/.test(value)\n ? { position: value }\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 theme mapping, and the data API in one\n * classic script. The mapping reads Bootstrap's `--bs-*` variables and falls\n * back to Tabler's `--tblr-*`, so the same script fits both. 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 and zoom come along.\nimport '@tabler/charts/export'\nimport '@tabler/charts/zoom'\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 // Not now: the `TablerCharts` global is assigned when this script has run,\n // and a listener of the first `tc-render` must find it.\n else queueMicrotask(start)\n}\n\nexport * from '@tabler/charts'\nexport { dispose, getChart, init, observe, types } from './index.ts'\n"],"mappings":"A,2FAyEA,IAAa4E,EAAqB,CAAC,EAGnC,SAAgBC,EAASC,EAAuB,CAC9C,OAAO,OAAOF,EAAUE,CAAK,CAC/B,CASA,IAAaC,EAAeC,GACzBA,EAAO,QAAUA,EAAO,WAAa,GAAQJ,EAAS,OAAS,IAAA,GAU5DK,kBAAwB,IAAI,IAGlC,SAAgBC,EAAQC,EAAsB,CAC5CF,EAAM,IAAIE,CAAI,EACdP,EAAS,MAAQI,EAAQI,EAASC,EAAaC,IAAQ,CACrD,IAAK,IAAMC,KAAQN,EAAOG,EAAUG,EAAKP,EAAQI,EAASC,EAAaC,CAAG,EAC1E,OAAOF,CACT,CACF,CAGA,SAAgBI,EAAkCC,EAAmC,CACnF,IAAMC,EAAQd,EAASa,GACvB,GAAI,CAACC,EACH,MAAU,MACR,0CAA0CD,IAAS,QAAU,OAASA,EAAK,QAAQA,EAAK,EAC1F,EAEF,OAAOC,CACT,CCjBA,SAAgBC,EAAOC,EAAyB,CAC9C,OAAOA,EAAM,GAAGA,EAAI,MAAM,GA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