Chart
A self-developed SVG chart component (no third-party chart engine) supporting line / bar / horizontal-bar / pie / area / donut / stacked-bar / radar / polar-area, plus series-level combo and dual axis. Data updates redraw automatically, and animations are disabled under prefers-reduced-motion; options.tooltip optionally enables the built-in hover overlay (the native <title> is used by default).
Line Chart
Line chart (default)
The default is type="line". An array [{label, value}] is a single series; hovering over a data point shows its value (native <title>).
Bar Chart
Bar chart
type="bar" renders grouped bars.
Horizontal Bar Chart
Horizontal bar chart (value axis at the bottom, categories on the left)
type="horizontal-bar" puts the value axis at the bottom (tick labels centered under the vertical grid lines), pins category labels to the left edge, and grows bars from the plot's left edge to the right — a good fit for rankings with many or long category names. The data format is identical to type="bar" (array single series / object multi-series); multiple series are grouped top-to-bottom inside each category row, and legend / colors / <title> hover work the same as vertical bars. When rows are too tight the category labels are thinned vertically (labels only — never the data).
Geometry stays orthogonal to writing direction: RTL is not mirrored (svg { direction: ltr } is pinned), so bars always grow left-to-right visually. Horizontal bars do not participate in combo or dual axis (single value-axis semantics); series-level type / yAxisIndex are ignored.
Pie Chart
Pie chart
type="pie" renders sectors, with the tooltip showing the percentage.
Donut Chart
Donut chart
type="donut" uses the same data format as the pie chart, with the middle hollowed out into a ring; the tooltip also shows percentages.
Area Chart
Area chart (smooth + legend)
type="area" fills a semi-transparent area between the line and the baseline (still readable with multiple series overlaid), and supports options.smooth for smooth curves.
Area chart (gradient fill)
With options.gradient (default false), the area fill fades vertically from the series color at the line (35% opacity at the top) to transparent at the baseline, keeping the visual focus on the data line.
Stacked Bar Chart
Stacked bar chart
type="stacked-bar" stacks multiple series from bottom to top into a single bar; the bar height equals the category total, and the y-axis ticks are computed from the totals.
Radar Chart
Radar chart (radarShape + max scale)
type="radar" reuses labels as dimension names (the same data shape as line/bar, zero migration cost). options.max sets a global unified scale (defaults to the series max passed through nice ticks); options.radarShape (default polygon, concentric polygons) can be set to circle for concentric-ring grid. Hovering a vertex shows "dimension: value"; legend and colors match the other chart types.
Polar Area Chart
Polar area chart (rose)
type="polar-area" renders equal-angle sectors whose radius encodes the value (the maximum fills the full radius); concentric reference rings provide a radial magnitude cue. Unlike the pie chart's "share" mental model, the tooltip shows the raw value instead of a percentage. Single series takes series[0] (same data format as pie/donut).
Combo Chart
Combo chart (bar + line series-level mixing)
Combo has no dedicated type value: the top-level type acts as the default series type, and series[].type (bar / line / area) overrides it per series; missing/invalid values fall back to the top-level type. All series share one category axis, and line/area points align to band centers (unlike a pure line chart's endpoint alignment); the draw order is fixed to bar → area → line; colors and legend follow the series declaration order.
Dual Axis
Dual-axis combo (right axis + alignTicks)
Dual axis is axis configuration, not a chart type: the right axis renders when a second entry exists in the options.yAxis array AND both sides have series bound via series[].yAxisIndex (name is the axis title rendered at the top; if either side has no bound series a single axis is rendered — no empty axis), and series[].yAxisIndex (0 left, default / 1 right) binds each series; it can be combined with line / bar / combo freely. With dual axes, ticks are force-aligned (alignTicks): the secondary axis recomputes its nice ticks anchored to the primary axis' segment count, so left/right tick lines align horizontally — eliminating the misaligned-ticks misreading. Note the two axes have different units, so readings on the same line are not comparable across axes. yAxis is ignored by stacked-bar / pie-family / radar (single-axis semantics).
Multiple Series + Legend
Multi-series line (smooth + legend)
The object format {labels, series:[{name, data}]} supports multiple series; the legend is shown by default for multiple series, and options.smooth enables smooth curves.
Dense Categories (Automatic Thinning / Rotation)
36 days of daily requests (default: horizontal, thinned)
Same data · xLabelRotate: 90 (vertical, more labels fit)
The same 36 days laid out two ways, and the trade-offs:
- Default (horizontal + thinning): when the spacing cannot fit the widest label, a stride k is derived from the label width plus gap versus the category spacing, and every k-th label is rendered (
autoSkipsemantics), keeping the endpoints when there is spare room. Fastest to read horizontally, but it skips (the 36 days above show 12 labels). xLabelRotate(slanted / vertical): 0–90 degrees, default 0; when > 0 each label is rotated clockwise around its tick anchor — the first character sits under the tick and the text slants down-right (90° is vertical). Rotation shrinks the horizontal footprint (≈ label width×cosθ + line height×sinθ; at 90° just one line height), so more labels fit: the 36 days above show 18 labels at 90° (~1.5× the default), and longer labels gain more.- The two combine:
xLabelRotateonly supplies the angle while thinning guarantees no pile-up — the stride is recomputed from the rotated footprint and labels keep being skipped while spacing is short. For short labels (e.g.09-01) a 45° slant still projects ≈0.7 of the width, so the gain is limited; 45° mainly helps long labels (e.g.2026-09-01). - Cost: rotation lifts the plot area — the bottom padding is
10 + widest label×sinθ + line height(for 90° driven by the label width), and the right padding must cover the rightmost label's horizontal projection; the plot gets shorter, so fewer y ticks are readable. Non-numeric angles fall back to 0; out-of-range values are clamped to 0–90.
Custom Hover Overlay (opt-in)
options.tooltip + tooltipFormatter (JS property channel)
Hover a bar: the overlay shows the custom text ("series | category: value k")
Taking over the overlay (oas-chart-tooltip + preventDefault)
Hover a bar: the host calls preventDefault(), the built-in overlay stays hidden and the reading lands here
const chart = document.querySelector('oas-chart')
chart.setAttribute('options', '{"tooltip":true}') // attribute channel
chart.tooltipFormatter = (ctx) => `${ctx.seriesName} | ${ctx.label}: ${ctx.value} k`
chart.addEventListener('oas-chart-tooltip', (e) => {
e.preventDefault() // take over: no built-in overlay
console.log(e.detail) // { label, value, seriesName, seriesIndex, percent? }
})- Zero overlay by default:
options.tooltipdefaults tofalse, so only the native<title>is used and no overlay node is created inside the shadow root. When enabled the component creates a singleton overlay (part="tooltip", inverse tokens--oas-tooltip-bg/--oas-tooltip-color, readable in dark mode); it hides on data redraw and page scroll, and is destroyed on disconnect. - Text: defaults to
seriesName · label: value, with the percentage appended for pie/donut (e.g.Share · R&D: 35 (35%));tooltipFormatteroverrides it and its return value is written as plain text (never parsed as HTML). A function cannot be expressed in an attribute —tooltipFormatteris property-only. - Takeover:
oas-chart-tooltipis dispatched before the built-in overlay is shown (detailis the context{ label, value, seriesName?, seriesIndex, percent? };percentis provided by the pie family only). CallingpreventDefault()suppresses the built-in overlay so the host can render its own. - Coverage: line/area dots, bars, horizontal bars, stacked segments, pie/donut sectors, radar vertices, polar sectors. The overlay is a pointer-only visual enhancement: the accessible name is still the container
aria-labeland values remain in the native<title>.
Empty Data
Empty data placeholder
No data / invalid JSON shows an empty state placeholder without errors.
Data channel contract
data / options accept both channels:
- Attribute channel: write a JSON string in HTML (e.g.
data='[{...}]'); the component parses it withJSON.parse. - Property channel: assign an object/array from JS (
el.data = [{...}]), avoiding serialization; the property is parsed in the setter and takes precedence over the attribute.
Reflection behavior differs (the two components read data differently — follow these rules):
oas-table'scolumns/datasetters reflect back to the attribute — after a property assignment,getAttribute('columns')/getAttribute('data')read back the corresponding JSON string (attribute and property stay in sync as one source of truth).oas-chart'sdata(andoptions) setter only writes internal state and does not reflect — after a property assignment the attribute still holds the old/empty value, so read through theel.dataproperty (the getter returns the last assigned parsed result); do not read back withgetAttribute('data').
Exception: if
oas-table'scolumnscontain function fields (such asrender, which JSON serialization would drop), the setter takes a pure in-memory path without reflecting — read those columns via theel.columnsproperty.
API
oas-chart
Attributes
| Attribute | Description | Type | Default |
|---|---|---|---|
aria-label | Chart description (falls back to locale by type) | — | — |
data | Data. Array single-series [{label, value}] or object multi-series {labels, series:[{name, data, type?, yAxisIndex?}]} (series-level type / yAxisIndex for combo and dual-axis) | unknown | — |
options | Config: smooth (smoothing), colors (series palette), showLegend, gradient (area-chart vertical gradient fill, default false), max (radar global scale), radarShape (radar grid polygon/circle, default polygon), xLabelRotate (x-axis category label rotation 0–90, default 0 = horizontal + width-based auto-thinning; >0 slants/verticals the labels, still thinned by rotated footprint as a backstop), yAxis (dual-axis array; dual axis requires the second entry AND series bound on both sides via yAxisIndex, otherwise single axis), tooltip (opt-in built-in hover overlay, default false = native <title> only, no overlay node in the shadow root) | unknown | — |
type | Chart type: line / bar / horizontal-bar / pie / area / donut / stacked-bar / radar / polar-area (combo has no type value — override per series via series.type; horizontal bars put the value axis at the bottom with category labels on the left edge and do not take part in combo or dual axis) | ChartType | line |
Property (JS property; see each row for attribute reflection)
| Property | Description | Type | Default |
|---|---|---|---|
tooltipFormatter | Custom hover text: (ctx: { label, value, seriesName?, seriesIndex, percent? }) => string; the string is written as plain text. Set null to restore the default text. A function cannot be expressed in an attribute, so this is property-only | ((ctx: ChartTooltipContext) => string) | null | — |
Events
| Event | Description |
|---|---|
oas-chart-tooltip | Dispatched before the built-in overlay is shown (only when options.tooltip is on), detail: { label, value, seriesName?, seriesIndex, percent? }; preventDefault() takes over and suppresses the default overlay |
CSS Variables
| CSS Variable | Default |
|---|---|
--oas-tooltip-bg | var(--oas-color-text-primary) |
--oas-tooltip-color | var(--oas-color-bg) |
data / options also support the property channel (JS objects, taking precedence over attributes).
Boundaries
- Data updates redraw the SVG (same pattern as qrcode), without rebuilding nodes
- Empty / invalid data → empty state placeholder
- Every data point carries a native
<title>hover hint; with the defaultoptions.tooltip: falsethe shadow root holds zero overlay nodes (zero orphaned overlays). When enabled it is a singleton overlay (part="tooltip") that hides on data redraw / page scroll and is destroyed on disconnect — still no orphans - Horizontal bars (
type="horizontal-bar") share thebardata contract, with the value axis at the bottom and category labels on the left edge; RTL is not mirrored (geometry is orthogonal to writing direction); they do not participate in combo or dual axis, and series-leveltype/yAxisIndexare ignored; with too many categories (>~50) the bars overlap into a solid band (same contract as vertical bars) — aggregate or thin the data instead tooltipFormatteris property-only (a function cannot be expressed in an attribute); its return value is written as plain text and never parsed as HTML. A throwing formatter or a non-string return falls back to the default text without breaking hover- When x-axis category labels are dense (spacing cannot fit the widest label) they are auto-thinned by available width (line/area keep the endpoints with priority; bars thin by width and keep them only when clipped); thinning only affects labels (data points are never thinned) and never rotates or adds an ellipsis — use
options.xLabelRotate(0–90) for slanted/vertical labels, which still thin by rotated footprint as a backstop; horizontal labels align inward (start/end) only when they overflow the viewBox, and neighbors that would collide with them are removed by their own widths (bar / combo / stacked included; unclipped labels stay centered on their bar groups), so nothing is clipped - Animations are pure CSS (wrapped in
@media (prefers-reduced-motion: no-preference)), auto-disabled under reduced-motion, with no JS timers; zero orphaned overlays - Radar uses one global scale (
options.maxor nice ticks); per-dimension scales are not supported yet — normalize your data first if needed (e.g. a 0–100 score) - Polar-area renders no sectors when all values are 0 (same as pie); the radius scale tops at the maximum value
- Combo only allows mixing
bar/line/area(one cartesian coordinate system); other type values silently fall back to the top-level type - Series-level
type/yAxisIndexis consumed only by cartesian types (line / bar / area / combo);stacked-bar/pie/donut/radar/polar-areaignore series-level overrides and always render per the top-leveltype - Declaring a second
options.yAxisentry without bindings on both sides (nothing bound right, or everything bound right leaving the left axis empty) renders a single axis — no zero-tick fake axis (unused axis titles included) - Y-axis ticks use the
1 / 2 / 2.5 / 5 / 10 × 10^nnice-step sequence (shared by single axis / dual axis / radar / stacked bars). Label precision follows the step dynamically (e.g. 0.0025 keeps four decimals), so sub-integer ranges no longer degrade to whole steps or drop ticks. The range top rounds up to a nice step — a raw max of 90 tops at 100 and a dual-axis right max of 10 tops at 10 (visible change; the old ceil behavior was 92 / 12). Any range top may round up by nearly 2× (e.g. 133→200, 1206→2000); this is the trade-off of four fixed segments with a finite nice sequence — normalize data to nice boundaries first if a tighter top is required. Tick gutters are derived from the actual formatted labels on both the left axis and the dual right axis, so decimal labels never overflow the viewBox; steps ≥1e6 or <1e-4 use scientific notation (e.g.2.5E8,1E-5) to keep the axis column compact - Tick labels use
Intl.NumberFormat(locale-aware decimal separators). An invalid locale (e.g.zh_CNwith an underscore, any custom or non-ASCII name, or an empty string) falls back to a fixeden-USlocale (keeping SSR and client snapshots consistent) instead of breaking chart rendering. Scientific-notation glyphs (Arabic-Indic digits, exponent symbols, etc.) may vary across ICU and locale versions; the component only guarantees that they render legibly and does not pin exact glyphs, nor expose a public formatting API - Color mapping semantics: the pie family (pie / donut / polar-area) colors by category, cartesian types (line / bar / area / stacked-bar / radar / combo) color by series;
options.colorsoverrides in the same order; the default palette cycles through 8 colors (primary / success / warning / danger / purple / cyan / magenta / geekblue) and wraps only after 8 - Text inside the chart svg is pinned to
direction: ltr(coordinate semantics are orthogonal to writing direction): a hostdir=rtlneither flips text anchors nor mirrors geometry