himynameisdave/svelte-frappe-charts
关于
📈 Svelte bindings for frappe-charts.
数据与分析实测星标增长
- 24小时
- 0
- 7天
- 0
- 15天
- 0
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文Makes it easy to use frappe-charts in your Svelte project: line, bar, horizontal bar, mixed axis, pie, donut, percentage and heatmap charts as one typed, reactive <Chart> component.
- Installation
- Usage
- Chart types
- Props
- Updating a chart
- Events
- Methods
- Theming
- TypeScript
- Server rendering
- Migrating from 2.x
- Contributing
Installation
bun add svelte-frappe-charts
npm install svelte-frappe-charts
pnpm add svelte-frappe-charts
Requires Svelte 5.59.2 or newer in the 5.x line. frappe-charts v2 comes along as a dependency, and its stylesheet is injected for you, so there is nothing else to install or import.
Usage
<script>
import Chart from 'svelte-frappe-charts';
let data = {
labels: ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'],
datasets: [{ values: [10, 12, 3, 9, 8, 15, 9] }],
};
</script>
<Chart
{data}
type="line"
/>
Every option of frappe-charts' configuration is a prop of the same name.
Chart types
type |
Draws | data |
|---|---|---|
"line" (default) |
One line per dataset | { labels, datasets } |
"bar" |
Grouped bars. barOptions={{ stacked: true }} stacks them |
{ labels, datasets } |
"bar" + barOptions.horizontal |
Horizontal bars | { labels, datasets } |
"axis-mixed" |
Bars and lines together, chosen per dataset with chartType |
{ labels, datasets } |
"pie" |
One slice per label | { labels, datasets } |
"donut" |
A ring with a total, or your own text, in the middle | { labels, datasets } |
"percentage" |
One bar split by share | { labels, datasets } |
"heatmap" |
A calendar of days, colored by count | { dataPoints, start, end } |
<!-- Horizontal, stacked bars -->
<Chart
{data}
type="bar"
barOptions={{ horizontal: true, stacked: true }}
/>
<!-- Bars and a line on the same axes -->
<Chart
type="axis-mixed"
data={{
labels: ['Jan', 'Feb', 'Mar'],
datasets: [
{ name: 'Online', chartType: 'bar', values: [42, 48, 39] },
{ name: 'Target', chartType: 'line', values: [60, 62, 64] },
],
yMarkers: [{ label: 'Goal', value: 70 }],
}}
/>
<!-- Donut -->
<Chart
type="donut"
data={{ labels: ['Apples', 'Pears', 'Plums'], datasets: [{ values: [42, 27, 18] }] }}
center={{ label: 'Crates' }}
legendPosition="right"
/>
<!-- Heatmap -->
<Chart
type="heatmap"
data={{
dataPoints: { '2026-01-05': 3, '2026-01-20': 9 },
start: new Date(2026, 0, 1),
end: new Date(2026, 11, 31),
}}
countLabel="commits"
startSubDomain="Monday"
/>
Props
Which props a chart accepts depends on type. With TypeScript, a prop that does not belong to the chart type is a compile error.
Every chart
| Prop | Type | Notes |
|---|---|---|
data |
object | Required. See Chart types |
type |
string | Defaults to "line" |
title |
string |
|
height |
number | "100%" |
"100%" fills the wrapper element; give it a height with style |
colors |
string[] |
Named colors ("blue"), hex, or any CSS color |
animate |
boolean |
Default on |
disableEntryAnimation |
boolean |
|
showLegend |
boolean |
Default on |
truncateLegends |
boolean |
Default on |
measures |
{ margins, paddings } |
|
class, style |
string |
Applied to the element the chart is drawn into |
Line, bar and mixed charts
| Prop | Notes |
|---|---|
axisOptions |
xAxisMode, yAxisMode, xIsSeries, xAxisType: "time", xOffset, xAxisLabelRotation, yAxisRange, shortenYAxisNumbers, numberFormatter, hideXAxis, hideYAxis, xAxisTitle, yAxisTitle |
barOptions |
horizontal, stacked, spaceRatio, radius, gap, maxWidth, labelWidth |
lineOptions |
showDots, dotSize, trailingDot, hideDotBorder, hideLine, spline, stepped, dashed, regionFill, heatline, showGaps, spanGaps. A dataset can override them with its own lineOptions |
tooltipOptions |
formatTooltipX, formatTooltipY, placement |
valuesOverPoints |
Print each value above its point or bar |
isNavigable |
Select points by click or arrow keys. See Events |
onClick |
Called with { index, label, values } when the plot is clicked |
data also takes yMarkers, xMarkers, yRegions and xRegions, and each dataset takes name, chartType, lineOptions and per-bar colors.
Pie, donut and percentage charts
| Prop | Charts | Notes |
|---|---|---|
maxSlices, maxLegendPoints |
all three | Slices past maxSlices are merged into "Rest" |
tooltipOptions.formatTooltipY |
all three | Formats slice values in tooltips and the legend |
startAngle, clockWise |
pie, donut | |
legendPosition |
pie, donut | "bottom" (default), "left" or "right" |
onClick |
pie, donut | Called with { index, label, value } |
hoverRadio |
pie | |
strokeWidth, center |
donut | center={{ value, label }} |
barOptions.height |
percentage |
Heatmaps
countLabel, legendLabels, locale, startSubDomain, discreteDomains, radius.
Updating a chart
data is reactive. Assign a new object, or mutate $state in place, and the chart animates to the new shape:
<script>
import Chart from 'svelte-frappe-charts';
let data = $state({
labels: ['Sun', 'Mon', 'Tues'],
datasets: [{ values: [10, 12, 3] }],
});
function addDay() {
data.labels.push('Wed');
data.datasets[0].values.push(9);
}
function replace() {
data = { labels: ['Fri', 'Sat', 'Sun'], datasets: [{ values: [300, 380, 275] }] };
}
</script>
<Chart
{data}
type="line"
/>
<button onclick={addDay}>Add a day</button>
<button onclick={replace}>Replace everything</button>
Every other prop is reactive too. frappe-charts reads its options once, so when one of them changes the chart is destroyed and drawn again with the new options. Props are compared by value: passing an equal object or array again does not rebuild anything.
On axis charts, adding or removing y markers or regions and renaming a visible legend entry also redraw the chart. Changing values still uses frappe-charts' update animation.
Datasets shorter than labels are filled with zeros. An empty yMarkers or yRegions list is the same as leaving it out.
Events
Set isNavigable on a line, vertical bar or mixed chart to let people select a point by clicking it or with the arrow keys. ondataselect is called with the selected point:
<script>
import Chart from 'svelte-frappe-charts';
let data = {
labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
datasets: [{ values: [300, 250, 720, 560, 370, 610, 690] }],
};
let selected = $state();
</script>
<Chart
{data}
type="bar"
isNavigable
ondataselect={(point) => (selected = point)}
/>
{#if selected}
<p>{selected.label}: {selected.values.join(', ')}</p>
{/if}
point is { index, label, values }, with one value per dataset.
onClick works without isNavigable on line, vertical bar, mixed, pie and donut charts. It is frappe-charts' own option, so it keeps frappe's capital C.
Methods
Keep a reference to the component with bind:this to call these:
<script>
import Chart from 'svelte-frappe-charts';
let chart;
</script>
<Chart
bind:this={chart}
{data}
title="Visits"
/>
<button onclick={() => chart.addDataPoint('Wed', [30])}>Add data point</button>
<button onclick={() => chart.exportChart()}>Export</button>
| Method | Does |
|---|---|
addDataPoint(label, values, index?) |
Inserts a point, at the end by default. values has one entry per dataset |
removeDataPoint(index?) |
Removes a point, the last one by default |
updateDataset(values, index?) |
Replaces the values of one dataset, the first by default |
updateDatasets(datasets) |
Replaces the values of every dataset |
getDataPoint(index?) |
Returns { index, label, values } or undefined. Defaults to the selection |
setCurrentDataPoint(index) |
Selects a point on a navigable chart, which fires ondataselect |
exportChart() |
Downloads the chart as an SVG file named after its title |
getChart() |
Returns the frappe-charts instance, for anything not wrapped here |
The first six apply to line, vertical bar and mixed charts. Pie, donut and percentage charts also support addDataPoint and removeDataPoint. Changes made through these methods live in the chart. The next change to the data prop replaces them.
Theming
frappe-charts reads its text, grid and tooltip colors from CSS custom properties, so a dark mode is a few lines of CSS:
@media (prefers-color-scheme: dark) {
.chart-container {
--charts-label-color: #c9d1d9;
--charts-axis-line-color: #30363d;
--charts-tooltip-bg: #161b22;
--charts-tooltip-title: #f0f6fc;
--charts-tooltip-label: #c9d1d9;
--charts-tooltip-value: #f0f6fc;
--charts-legend-label: #c9d1d9;
}
}
The full list: --charts-label-color, --charts-muted-color, --charts-axis-line-color, --charts-grid-dasharray, --charts-stroke-width, --charts-hover-band, --charts-dataset-circle-stroke, --charts-dataset-circle-stroke-width, --charts-legend-label, --charts-legend-value, --charts-tooltip-bg, --charts-tooltip-border, --charts-tooltip-title, --charts-tooltip-label and --charts-tooltip-value.
In a component with scoped styles, reach the chart with :global(.chart-container), or set the properties on an element around it.
TypeScript
The package ships its own types, including the frappe-charts options that upstream leaves untyped. They work with TypeScript 6 and TypeScript 7.
import Chart, {
type AxisChartData,
type ChartProps,
type DataPoint,
type FrappeChart,
} from 'svelte-frappe-charts';
const data: AxisChartData = { labels: ['Mon'], datasets: [{ values: [1] }] };
// Props are a union keyed on `type`, so this is a compile error: a pie chart has no lineOptions.
const props: ChartProps = {
type: 'pie',
data: { labels: ['Apples'], datasets: [{ values: [1] }] },
lineOptions: { spline: true },
};
Also exported: ChartOptions, ChartType, AxisChartOptions, PieChartOptions, DonutChartOptions, PercentageChartOptions, HeatmapOptions, AggregationChartData, HeatmapData, AxisDataset, AxisOptions, BarOptions, LineOptions, TooltipOptions, SlicePoint, and the marker and region types.
Server rendering
The component is safe to render on the server, for example with SvelteKit. It renders an empty element there and draws the chart once it mounts in the browser.
The package also carries precompiled builds for setups that do not compile .svelte files from node_modules. Bundlers pick the right one through the package's exports; there is nothing to configure.
Migrating from 2.x
3.0 moves to frappe-charts v2 and Svelte 5 runes.
Requirements
- Svelte 5.59.2 or newer in the 5.x line is required. Svelte 4 projects should stay on
svelte-frappe-charts@2. - The UMD and CommonJS builds in
lib/are gone. The package is ESM only.
Component API
on:data-selectis now theondataselectprop, and it receives{ index, label, values }instead of a DOM event:- <Chart {data} isNavigable on:data-select={(event) => select(event.index)} /> + <Chart {data} isNavigable ondataselect={(point) => select(point.index)} />datais required. It used to default to an empty chart.The wrapper no longer sets its own defaults; frappe-charts' apply. Set these to keep the old look:
height={300}(now 240) andmaxSlices={3}(now 20).Props other than
dataare now reactive. Changing one redraws the chart; before, the change was ignored.The chart is destroyed when the component unmounts.
New:
updateDataset,updateDatasets,getDataPoint,setCurrentDataPointandgetChartmethods,classandstyleprops, and types for every option.
frappe-charts v1 to v2
- Dots on lines are hidden by default.
lineOptions.hideDotsis gone; uselineOptions={{ showDots: true }}to show them. - Axis chart tooltips sit beside the pointer by default.
tooltipOptions={{ placement: 'top' }}puts them back above the point. - New chart types and options:
"donut"charts, horizontal bars,xMarkers,xRegions, axis titles, label rotation,legendPosition,onClick, and more. See the frappe-charts release notes.
Contributing
Issues and pull requests are greatly welcome!
The repository uses Bun (1.4.4 or newer) and Node 22 or newer.
bun install
bun run dev # playground with every chart type
bun run lint # oxlint, type-aware
bun run format # oxfmt-style formatting through `bun fmt`
bun run check # svelte-check on TypeScript 7
bun run test # unit tests, and component tests in headless Chromium
bun run build # dist/: svelte-package output + precompiled bundle
bun run test:package # checks the packed tarball from a consumer project
The component tests need a Chromium for Playwright: bunx playwright install chromium.
✌️Created by Dave. Licenced under MIT.
探索相关项目
加载中…