` requires data to be included in the configuration object, which can be difficult depending on the type of chart you need. If you would like to use specialized ECharts features, but retain the data management you get with Evidence charts, we recommend building a [mixed-type chart](/components/charts/mixed-type-charts) and passing in an `options` object for the specific features you need.
## How to Build the Configuration
To create a JavaScript object in an Evidence markdown page, you need to add a `<script>` tag. Any objects or variables you create in that script tag are then accessible by the rest of your page using curly braces. For example, if you create a variable named `myVar`, you can show the contents of that variable in your markdown using `{myVar}`.
## Examples
### Simple Treemap
[Link to ECharts example](https://echarts.apache.org/examples/en/editor.html?c=treemap-simple)
ECharts requires the data object to have a specific format. For example in the treemap chart show below it expects the columns to be called “name” and “value”. The `test_data` query in the code below renames the fields from the original query so ECharts can use them.
```sql sales_by_country
select 'Canada' as country, 100 as sales
union all
select 'US' as country, 250 as sales
union all
select 'UK' as country, 130 as sales
union all
select 'Australia' as country, 95 as sales
```
```sql test_data
select country as name, sales as value
from ${sales_by_country}
```
````markdown
```sql sales_by_country
select 'Canada' as country, 100 as sales
union all
select 'US' as country, 250 as sales
union all
select 'UK' as country, 130 as sales
union all
select 'Australia' as country, 95 as sales
```
```sql test_data
select country as name, sales as value
from ${sales_by_country}
```
````
### Funnel Chart
[Link to ECharts example](https://echarts.apache.org/examples/en/editor.html?c=funnel)
ECharts requires the data object to have a specific format. For example in the funnel chart show below it expects the columns to be called “name” and “value”. The `funnel_data` query in the code below renames the fields from the original query so ECharts can use them.
```sql funnel_stages
select 'Emailed' as stage, 129 as count
union all
select 'Meeting' as stage, 86 as count
union all
select 'Proposal' as stage, 65 as count
union all
select 'Signed' as stage, 44 as count
```
```sql funnel_data
select stage as name, count as value
from ${funnel_stages}
```
````markdown
```sql funnel_stages
select 'Emailed' as stage, 129 as count
union all
select 'Meeting' as stage, 86 as count
union all
select 'Proposal' as stage, 65 as count
union all
select 'Signed' as stage, 44 as count
```
```sql funnel_data
select stage as name, count as value
from ${funnel_stages}
```
````
### Pie Chart
[Link to ECharts example](https://echarts.apache.org/examples/en/editor.html?c=pie-simple)
ECharts requires the data object to have a specific format. For example in the pie chart show below it expects the columns to be called “name” and “value”. The `pie_data` query in the code below renames the fields from the original query so ECharts can use them.
```sql pie_query
select 'Apple' as pie, 60 as count
union all
select 'Blueberry' as pie, 70 as count
union all
select 'Cherry' as pie, 40 as count
union all
select 'Pecan' as pie, 35 as count
```
```sql pie_data
select pie as name, count as value
from ${pie_query}
```
````markdown
```sql pie_query
select 'Apple' as pie, 60 as count
union all
select 'Blueberry' as pie, 70 as count
union all
select 'Cherry' as pie, 40 as count
union all
select 'Pecan' as pie, 35 as count
```
```sql pie_data
select pie as name, count as value
from ${pie_query}
```
````
### Donut Chart
[Link to ECharts example](https://echarts.apache.org/examples/en/editor.html?c=pie-doughnut)
ECharts requires the data object to have a specific format. For example in the donut chart show below it expects the columns to be called “name” and “value”. The `donut_data` query in the code below renames the fields from the original query so ECharts can use them.
```sql donut_query
select 'Glazed' as donut, 213 as count
union all
select 'Cruller' as donut, 442 as count
union all
select 'Jelly-filled' as donut, 321 as count
union all
select 'Cream-filled' as donut, 350 as count
```
```sql donut_data
select donut as name, count as value
from ${donut_query}
```
````markdown
```sql donut_query
select 'Glazed' as donut, 213 as count
union all
select 'Cruller' as donut, 442 as count
union all
select 'Jelly-filled' as donut, 321 as count
union all
select 'Cream-filled' as donut, 350 as count
```
```sql donut_data
select donut as name, count as value
from ${donut_query}
```
````
### Advanced Chart
[Link to ECharts example](https://echarts.apache.org/examples/en/editor.html?c=scatter-anscombe-quartet)
```markdown
<script>
const dataAll = [
[
[10.0, 8.04],
[8.0, 6.95],
[13.0, 7.58],
[9.0, 8.81],
[11.0, 8.33],
[14.0, 9.96],
[6.0, 7.24],
[4.0, 4.26],
[12.0, 10.84],
[7.0, 4.82],
[5.0, 5.68]
],
[
[10.0, 9.14],
[8.0, 8.14],
[13.0, 8.74],
[9.0, 8.77],
[11.0, 9.26],
[14.0, 8.1],
[6.0, 6.13],
[4.0, 3.1],
[12.0, 9.13],
[7.0, 7.26],
[5.0, 4.74]
],
[
[10.0, 7.46],
[8.0, 6.77],
[13.0, 12.74],
[9.0, 7.11],
[11.0, 7.81],
[14.0, 8.84],
[6.0, 6.08],
[4.0, 5.39],
[12.0, 8.15],
[7.0, 6.42],
[5.0, 5.73]
],
[
[8.0, 6.58],
[8.0, 5.76],
[8.0, 7.71],
[8.0, 8.84],
[8.0, 8.47],
[8.0, 7.04],
[8.0, 5.25],
[19.0, 12.5],
[8.0, 5.56],
[8.0, 7.91],
[8.0, 6.89]
]
];
const markLineOpt = {
animation: false,
label: {
formatter: 'y = 0.5 * x + 3',
align: 'right'
},
lineStyle: {
type: 'solid'
},
tooltip: {
formatter: 'y = 0.5 * x + 3'
},
data: [
[
{
coord: [0, 3],
symbol: 'none'
},
{
coord: [20, 13],
symbol: 'none'
}
]
]
};
let options = {
title: {
text: "Anscombe's quartet",
left: 'center',
top: 0
},
grid: [
{ left: '7%', top: '7%', width: '38%', height: '38%' },
{ right: '7%', top: '7%', width: '38%', height: '38%' },
{ left: '7%', bottom: '7%', width: '38%', height: '38%' },
{ right: '7%', bottom: '7%', width: '38%', height: '38%' }
],
tooltip: {
formatter: 'Group {a}: ({c})'
},
xAxis: [
{ gridIndex: 0, min: 0, max: 20 },
{ gridIndex: 1, min: 0, max: 20 },
{ gridIndex: 2, min: 0, max: 20 },
{ gridIndex: 3, min: 0, max: 20 }
],
yAxis: [
{ gridIndex: 0, min: 0, max: 15 },
{ gridIndex: 1, min: 0, max: 15 },
{ gridIndex: 2, min: 0, max: 15 },
{ gridIndex: 3, min: 0, max: 15 }
],
toolbox: {
show: true,
feature: {
saveAsImage: {
show: true
}
}
},
series: [
{
name: 'I',
type: 'scatter',
xAxisIndex: 0,
yAxisIndex: 0,
data: dataAll[0],
markLine: markLineOpt
},
{
name: 'II',
type: 'scatter',
xAxisIndex: 1,
yAxisIndex: 1,
data: dataAll[1],
markLine: markLineOpt
},
{
name: 'III',
type: 'scatter',
xAxisIndex: 2,
yAxisIndex: 2,
data: dataAll[2],
markLine: markLineOpt
},
{
name: 'IV',
type: 'scatter',
xAxisIndex: 3,
yAxisIndex: 3,
data: dataAll[3],
markLine: markLineOpt
}
]
};
</script>
```
---
evidence/sites/docs/pages/components/charts/line-chart/index.md
---
---
title: Line Chart
description: Display how one or more metrics vary over time. Line charts are suitable for plotting a large number of data points on the same chart.
sidebar_position: 1
---
Use line charts to display how one or more metrics vary over time. Line charts are suitable for plotting a large number of data points on the same chart.
```sql orders_by_month
select order_month as month, sum(sales) as sales_usd0k, count(1) as orders from needful_things.orders
group by all
```
```sql orders_by_category
select category, order_month as month, sum(sales) as sales_usd0k, count(1) as orders from needful_things.orders
group by all
```
```svelte
```
## Examples
### Line
```svelte
```
### Multi-Series Line
```markdown
```
### Multi-Series Line with Steps
```svelte
```
### Multiple y Columns
```svelte
```
### Secondary y Axis
```markdown
```
### Secondary Axis with Bar
```markdown
```
### Value Labels
```markdown
```
### Custom Color Palette
```markdown
```
### Markers
#### Default
```svelte
```
#### `markerShape=emptyCircle`
```svelte
```
## Options
### Data
### Formatting & Styling
### Axes
### Chart
### Custom Echarts Options
### Interactivity
## Annotations
Line charts can include [annotations](/components/charts/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/charts/echarts-options/index.md
---
---
sidebar_position: 999
title: ECharts Options
description: Evidence charts are based on ECharts. Pass options to ECharts directly using the echartsOptions property.
---
Evidence charts are based on ECharts. Pass options to ECharts directly using the echartsOptions property.
`echartsOptions` allow you to customize your chart with any combination of eCharts config options. Many config combinations can result in "broken" looking charts. Proceed with caution, and test your charts, particularly at different screen widths.
ECharts settings are specified in config object. Evidence generates this config for you through the props you pass to your chart.
If you can't get your chart to look "just right" with standard chart , you can use `echartsOptions` to customize your chart by adding or overriding the eCharts config directly.
## ECharts Options Object
The options object is passed as follows. **Note the double curly braces.**
```markdown
```
See the [eCharts docs](https://echarts.apache.org/en/option.html) for a full reference of config options.
Note that LLMs such as ChatGPT and GitHub Copilot are reasonably good at generating eCharts options if you explain what you are trying to achieve.
## Series Options Object
Often if you are making custom changes to a chart, you will need to adjust options within ECharts' `series`. When you have a multi-series chart, each series shows up separately in the ECharts configuration generated by Evidence.
For example, if you have a stacked bar with 4 series, this is what the underlying config object might look like:
```javascript
series: [
{type: 'bar', barWidth: 5, name: 'Canada', data: [200,5525,222,444,666]},
{type: 'bar', barWidth: 5, name: 'US', data: [1200,1555,1222,4144,6616]},
{type: 'bar', barWidth: 5, name: 'UK', data: [2060,525,262,4844,4666]},
{type: 'bar', barWidth: 5, name: 'Australia', data: [2200,5555,2252,8444,3666]}
]
```
If you wanted to add a custom border to the bars with `echartsOptions`, you would need to manually repeat for each series. E.g.,
```html
```
With `seriesOptions`, you can specify the changes once and have them applied to all series in the chart, like so:
```country_sales
select 'Canada' as country, 2020 as year, 100 as sales
union all
select 'Canada' as country, 2021 as year, 150 as sales
union all
select 'Canada' as country, 2022 as year, 200 as sales
union all
select 'Canada' as country, 2023 as year, 250 as sales
union all
select 'US' as country, 2020 as year, 200 as sales
union all
select 'US' as country, 2021 as year, 350 as sales
union all
select 'US' as country, 2022 as year, 400 as sales
union all
select 'US' as country, 2023 as year, 450 as sales
```
```svelte
```
## Print ECharts Config
You can print the current eCharts config for a chart by adding `printEchartsConfig=true` to the chart. This will print the full config just below the chart.
This includes both any default Evidence config and any `echartsOptions` you have specified, and so can be useful for debugging.
```svelte
```
## Example Configs
### Customize the Legend Position
```svelte
echartsOptions={{
legend: {
right: 'right',
top: 'middle',
align: 'auto',
orient: 'vertical',
padding: 7,
borderColor: '#ccc',
borderWidth: 1,
},
grid: {
right: '120px'
}
}}
```
### Add Data Zoom
```svelte
echartsOptions={{
dataZoom: [
{
start: 0,
end: 100,
},
],
grid: {
bottom: '50px',
},
}}
```
### Add Series Labels Next to Chart
params.seriesName,
offset: [0, 0], // [x, y] offset from the end of the line
}
},
{
endLabel: {
show: true,
formatter: (params) => params.seriesName,
offset: [0, 0], // [x, y] offset from the end of the line
}
}
],
grid: {
right: '50px',
top: '10px'
}
}}
/>
```svelte
echartsOptions={{
series: [
{
endLabel: {
show: true,
formatter: (params) => params.seriesName,
offset: [0, 0], // [x, y] offset from the end of the line
}
},
{
endLabel: {
show: true,
formatter: (params) => params.seriesName,
offset: [0, 0], // [x, y] offset from the end of the line
}
}
],
grid: {
right: '50px',
top: '10px'
}
}}
```
### Add Axis Pointer to Tooltip
```svelte
echartsOptions={{
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
}}
```
---
evidence/sites/docs/pages/components/charts/scatter-plot/index.md
---
---
title: Scatter Plot
description: Show the correlation between two metrics for categorical values, or a set of samples.
sidebar_position: 1
queries:
- price_vs_volume.sql
---
Use scatter plots to show the correlation between two metrics for categorical values, or a set of samples.
```markdown
```
## Examples
### Default
```markdown
```
### Multi-Series
```markdown
```
## Options
### Data
Query name, wrapped in curly braces
Column to use for the x-axis of the chart
Column(s) to use for the y-axis of the chart
Column to use as the series (groups) in a multi-series chart
Whether to apply default sort to your data. Default is x ascending for number and date x-axes, and y descending for category x-axes
Column to use as the title for each tooltip. Typically, this is a name to identify each point.
Sets behaviour for empty datasets. Can throw an error, a warning, or allow empty. When set to 'error', empty datasets will block builds in `build:strict`. Note this only applies to initial page load - empty datasets caused by input component changes (dropdowns, etc.) are allowed.
Text to display when an empty dataset is received - only applies when `emptySet` is 'warn' or 'pass', or when the empty dataset is a result of an input component change (dropdowns, etc.).
### Formatting & Styling
Format to use for x column ([see available formats](/core-concepts/formatting))
Format to use for y column ([see available formats](/core-concepts/formatting))
Options for which shape to use for scatter points
Change size of all points on the chart
% of the full color that should be rendered, with remainder being transparent
Color to override default series color. Only accepts a single color.
Width of line surrounding each shape
Color to use for outline if outlineWidth > 0
Array of custom colours to use for the chart. E.g., `{['#cf0d06','#eb5752','#e88a87']}`
Apply a specific color to each series in your chart. Unspecified series will receive colors from the built-in palette as normal. Note the double curly braces required in the syntax `seriesColors={{"Canada": "red", "US": "blue"}}`
Apply a specific order to the series in a multi-series chart.
### Axes
Whether to use a log scale for the y-axis
Base to use when log scale is enabled
Name to show under x-axis. If 'true', formatted column name is used. Only works with swapXY=false
Name to show beside y-axis. If 'true', formatted column name is used.
Turns on/off gridlines extending from x-axis tick marks (vertical lines when swapXY=false)
Turns on/off gridlines extending from y-axis tick marks (horizontal lines when swapXY=false)
Turns on/off value labels on the x-axis
Turns on/off value labels on the y-axis
Turns on/off thick axis line (line appears at y=0)
Turns on/off thick axis line (line appears directly alongside the y-axis labels)
Turns on/off tick marks for each of the x-axis labels
Turns on/off tick marks for each of the y-axis labels
Starting value for the x-axis
Maximum value for the x-axis
Starting value for the y-axis
Maximum value for the y-axis
### Chart
Chart title. Appears at top left of chart.
Chart subtitle. Appears just under title.
Turns legend on or off. Legend appears at top center of chart.
Minimum height of the chart area (excl. header and footer) in pixels. Adjusting the height affects all viewport sizes and may impact the mobile UX.
Which chart renderer type (canvas or SVG) to use. See ECharts' [documentation on renderers](https://echarts.apache.org/handbook/en/best-practices/canvas-vs-svg).
### Custom Echarts Options
Custom Echarts options to override the default options. See [reference page](/components/charts/echarts-options) for available options.
Custom Echarts options to override the default options for all series in the chart. This loops through the series to apply the settings rather than having to specify every series manually using `echartsOptions` See [reference page](/components/charts/echarts-options) for available options.
Helper prop for custom chart development - inserts a code block with the current echarts config onto the page so you can see the options used and debug your custom options
### Interactivity
Group name to connect this chart to other charts for synchronized tooltip hovering. Charts with the same `connectGroup` name will become connected
## Annotations
Scatter plots can include [annotations](/components/charts/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/charts/calendar-heatmap/index.md
---
---
title: Calendar Heatmap
description: Display how a single metric varies over weeks and months in a familar GitHub-style format
sidebar_position: 5
queries:
- orders_by_day.sql
- orders_by_day_2021.sql
---
Use calendar heatmaps to display how a single metric varies over weeks and months.
```markdown
```
## Examples
### Multi-Year
```markdown
```
### Custom Color Scale
```markdown
```
### Without Year Label
```markdown
```
## Options
### Data
### Formatting & Styling
### Chart
### Custom Echarts Options
### Interactivity
---
evidence/sites/docs/pages/components/charts/bar-chart/index.md
---
---
title: Bar Chart
description: Compare a metric across a small number of categories.
sidebar_position: 1
queries:
- orders_by_month.sql
- orders_by_category_2021.sql
- orders_by_item_all_time.sql
- categories_by_channel.sql
---
Use bar or column charts to compare a metric across categories. Bar charts are best with a small number of categories and series, and should generally start at 0.
```markdown
```
## Examples
### Default
```markdown
```
### Stacked
```markdown
```
### 100% Stacked
```markdown
```
### Grouped
```markdown
```
### Horizontal
```markdown
```
### Horizontal Stacked
```markdown
```
### Horizontal 100% Stacked
```markdown
```
### Horizontal Grouped
```markdown
```
### Value Labels
```markdown
```
### Custom Color Palette
```markdown
```
### Secondary / Dual y Axis
```markdown
```
### Secondary / Dual Axis with Line
```markdown
```
## Options
### Data
### Formatting & Styling
### Value Labels
### Axes
### Chart
### Custom Echarts Options
### Interactivity
## Annotations
```sql target_data
select 8333 as target, '100k ARR' as name
```
Bar charts can include [annotations](/components/charts/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/charts/box-plot/index.md
---
---
title: Box Plot
description: Summarize the distribution and range of a metric around the median value.
sidebar_position: 1
queries:
- sales_distribution_by_channel.sql
---
Use box plots to summarize the distribution and range of a metric around the median value.
```markdown
```
## Data Structure
The BoxPlot component requires pre-aggregated data, with one row per box you would like to display. There are 2 ways to pass in the values needed to construct the box:
**1. Explicitly define each value (e.g., `min`, `intervalBottom`, `midpoint`, `intervalTop`, `max`)**
```sql boxplot
select
channel as name,
first_quartile as intervalBottom,
median as midpoint,
third_quartile as intervalTop
from ${sales_distribution_by_channel}
```
This example table excludes whiskers which would be defined with `min` and `max` columns
**2. Define a `midpoint` and a `confidenceInterval` - this will add the interval to the midpoint to get the max, and subtract to get the min**
```sql boxplot_with_confidence_interval
select
channel as name,
median as midpoint,
20 as confidence_interval
from ${sales_distribution_by_channel}
```
## Examples
### Basic Box Plot
```markdown
```
### Horizontal Box Plot
```markdown
```
### Box Plot with Whiskers
```markdown
```
### Box Plot with Custom Colors
```markdown
```
## Options
### Data
### Formatting & Styling
### Axes
### Chart
### Custom Echarts Options
### Interactivity
## Annotations
Box plots can include [annotations](/components/charts/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/charts/funnel-chart/index.md
---
---
title: Funnel Chart
description: Display how a single metric changes across a series of stages. Funnel charts are widely used for visualizing conversion.
sidebar_position: 6
---
Use funnel charts to display a single metric across a series of stages. Funnel charts are widely used for visualizing conversion.
```sql funnel_data
select * from (
select 150 as customers, 'Show' as stage, 1 as stage_id
union all
select 102 as customers, 'Click' as stage, 2 as stage_id
union all
select 49 as customers, 'Visit' as stage, 3 as stage_id
union all
select 40 as customers, 'Inquiry' as stage, 4 as stage_id
union all
select 14 as customers, 'Order' as stage, 5 as stage_id
) order by stage_id asc
```
```markdown
```
## Examples
### Ascending
```markdown
```
### Alignment
```markdown
```
### Show Percent Label
```markdown
```
## Options
### Data
### Formatting & Styling
### Chart
### Custom Echarts Options
### Interactivity
---
evidence/sites/docs/pages/components/charts/area-chart/index.md
---
---
title: 'Area Chart'
description: Track how a metric with multiple series changes over time, or a continuous range.
sidebar_position: 1
queries:
- orders_by_month.sql
- orders_by_category_2021.sql
---
Use area charts to track how a metric with multiple series changes over time, or a continuous range. Area charts emphasize changes in the sum of series over the individual series.
```markdown
```
## Examples
### Area
```markdown
```
### Stacked
```markdown
```
### 100% Stacked
```markdown
```
### Stepped Line
```markdown
```
### Y-Axis Formatting
```markdown
```
### Labels
```markdown
```
## Options
### Data
### Formatting & Styling
### Value Labels
### Axes
### Chart
### Custom Echarts Options
### Interactivity
## Annotations
Area charts can include [annotations](/components/charts/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/charts/histogram/index.md
---
---
title: Histogram
description: Display the distribution of a metric along a continuous range, aggregated into buckets.
sidebar_position: 1
---
Use histograms to display the distribution of a metric along a continuous range, aggregated into buckets.
```sql orders
select * from needful_things.orders limit 1000
```
```sql orders_week
select * from needful_things.orders limit 10000
```
```markdown
```
## Examples
### Histogram
```markdown
```
## Options
### Data
Query name, wrapped in curly braces
Column which contains the data you want to summarize
Sets behaviour for empty datasets. Can throw an error, a warning, or allow empty. When set to 'error', empty datasets will block builds in `build:strict`. Note this only applies to initial page load - empty datasets caused by input component changes (dropdowns, etc.) are allowed.
Text to display when an empty dataset is received - only applies when `emptySet` is 'warn' or 'pass', or when the empty dataset is a result of an input component change (dropdowns, etc.).
### Formatting & Styling
Format to use for x column ([see available formats](/core-concepts/formatting))
Color to override default series color
% of the full color that should be rendered, with remainder being transparent
Array of custom colours to use for the chart. E.g., `{['#cf0d06','#eb5752','#e88a87']}`
### Axes
Name to show under x-axis. If 'true', formatted column name is used. Only works with swapXY=false
Name to show beside y-axis. If 'true', formatted column name is used.
Turns on/off gridlines extending from x-axis tick marks (vertical lines when swapXY=false)
Turns on/off gridlines extending from y-axis tick marks (horizontal lines when swapXY=false)
Turns on/off value labels on the x-axis
Turns on/off value labels on the y-axis
Turns on/off thick axis line (line appears at y=0)
Turns on/off thick axis line (line appears directly alongside the y-axis labels)
Turns on/off tick marks for each of the x-axis labels
Turns on/off tick marks for each of the y-axis labels
Starting value for the y-axis
Maximum value for the y-axis
### Chart
Chart title. Appears at top left of chart.
Chart subtitle. Appears just under title.
Turns legend on or off. Legend appears at top center of chart.
Minimum height of the chart area (excl. header and footer) in pixels. Adjusting the height affects all viewport sizes and may impact the mobile UX.
Which chart renderer type (canvas or SVG) to use. See ECharts' [documentation on renderers](https://echarts.apache.org/handbook/en/best-practices/canvas-vs-svg).
### Custom Echarts Options
Custom Echarts options to override the default options. See [reference page](/components/charts/echarts-options) for available options.
Custom Echarts options to override the default options for all series in the chart. This loops through the series to apply the settings rather than having to specify every series manually using `echartsOptions` See [reference page](/components/charts/echarts-options) for available options.
Helper prop for custom chart development - inserts a code block with the current echarts config onto the page so you can see the options used and debug your custom options
### Interactivity
Group name to connect this chart to other charts for synchronized tooltip hovering. Charts with the same `connectGroup` name will become connected
## Annotations
Histograms can include [annotations](/components/charts/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/inputs/index.md
---
---
title: Inputs
sidebar_link: false
sidebar_position: 4
---
---
evidence/sites/docs/pages/components/inputs/dropdown/index.md
---
---
title: Dropdown
description: Display a dropdown menu with a options from a query or hardcoded options.
sidebar_position: 1
---
Creates a dropdown menu with a list of options that can be selected. The selected option can be used to filter queries or in markdown.
To see how to filter a query using a dropdown, see [Filters](/core-concepts/filters).
```sql categories
select distinct category as category_name, upper(left(category, 3)) as abbrev from needful_things.orders
```
Selected: {inputs.category1.value}
````markdown
Selected: {inputs.category1.value}
````
## Examples
### Dropdown using Options from a Query
Selected: {inputs.category2.value}
````markdown
````
Selected: {inputs.category2.value}
### With a Title
Selected: {inputs.category3.value}
````markdown
Selected: {inputs.category3.value}
````
### With a Default Value
Selected: {inputs.category4.value}
````markdown
Selected: {inputs.category4.value}
````
### With Hardcoded Options
Selected: {inputs.hardcoded.value}
````markdown
Selected: {inputs.hardcoded.value}
````
### Alternative Labels
This example uses a column called `abbrev`, which contains an alternate label for each category
Selected: {inputs.category_abbrev.value}
````markdown
````
Selected: {inputs.category_abbrev.value}
### Multi-Select
When using multi-select dropdowns, you need to use an alternative SQL expression:
`where column_name IN ${inputs.my_input.value}`
Note:
- The use of the IN operator
- No single quotes used around the `${}`
Selected: {inputs.category_multi.value}
````markdown
Selected: {inputs.category_multi.value}
````
### Filtering a Query
```sql order_history
select id, order_datetime, category, item, sales from needful_things.orders
limit 100
```
Starting with this table of orders:
````markdown
```sql order_history
select id, order_datetime, category, item, sales from needful_things.orders
limit 100
```
````
Use this input to filter the results:
```sql orders_filtered
select * from ${order_history}
where category in ${inputs.category.value}
```
Filtered Row Count: {orders_filtered.length}
````markdown
```sql filtered_query
select *
from source_name.table
where column_name like '${inputs.name_of_dropdown.value}'
```
Filtered Row Count: {orders_filtered.length}
````
### Multiple defaultValues
Selected: {inputs.category_multi_default.value}
````svelte
Selected: {inputs.category_multi_default.value}
````
### Select all by Default Value with Multiple
Select and return all values in the dropdown list, requires "multiple" prop.
Selected: {inputs.category_multi_selectAllByDefault.value}
````markdown
Selected: {inputs.category_multi_selectAllByDefault.value}
````
# Dropdown
## Options
Adds an info icon with description tooltip on hover
# DropdownOption
## Options
The DropdownOption component can be used to manually add options to a dropdown. This is useful to add a default option, or to add options that are not in a query.
---
evidence/sites/docs/pages/components/inputs/checkbox/index.md
---
---
title: Checkbox
description: Display a toggleable box for a boolean value.
sidebar_position: 1
---
Creates a checkbox with toggleable input. The Title and Name attributes can be defined, enabling the passing of true and false values.
````markdown
````
### Checkbox using Default Value
Defining the checked property will set the initial checkbox value with true and false.
Selected Value: {inputs.name_of_checkbox}
```markdown
Selected Value: {inputs.name_of_checkbox}
```
```sql orders
select
COUNT(*) as records_count
from needful_things.orders
WHERE not ${inputs.exclude_low_value} -- When True, Do not evaluate the next condition
OR (
${inputs.exclude_low_value} -- Input is set to false
AND sales < 10 -- Apply this condition
)
```
````markdown
```sql orders
select
COUNT(*) as records_count
from needful_things.orders
WHERE not ${inputs.exclude_low_value} -- When True, Do not evaluate the next condition
OR (
${inputs.exclude_low_value} -- Input is set to false
AND sales < 10 -- Apply this condition
)
```
````
# Checkbox
## Options
Name of the checkbox, used to reference the selected value elsewhere as `{inputs.name.value}`
Label for the checkbox. If undefined, will default to small checkbox
Initial value for checkbox. True value for checked, false for unchecked
Adds an info icon with description tooltip on hover
---
evidence/sites/docs/pages/components/inputs/text-input/index.md
---
---
title: Text Input
description: Display a text box for freeform text input, useful for searching or filtering.
sidebar_position: 1
---
Creates a text input that can be used to filter or search
To see how to filter a query using a text input, see [Filters](/core-concepts/filters).
Selected: {inputs.text_input_name}
````markdown
Selected: {inputs.text_input_name}
````
## Examples
### Basic Text Input
Selected: {inputs.name_of_input}
````markdown
Selected: {inputs.name_of_input}
````
### With Title
Selected: {inputs.text_input2}
````markdown
Selected: {inputs.text_input2}
````
### With Placeholder
Selected: {inputs.text_input3}
````markdown
Selected: {inputs.text_input3}
````
### With Default Text Prefilled
Selected: {inputs.text_input4}
````markdown
Selected: {inputs.text_input4}
````
### Fuzzy Finding (Searching)
`TextInput` provides an easy-to-use shortcut for [fuzzy finding](https://duckdb.org/docs/sql/functions/char#text-similarity-functions). Note that this is different than `LIKE`, as it does not require a direct substring, and is useful in situtations where spelling may be unknown, like names.
You can reference it by using the syntax `{inputs.your_input_name.search('column_name')}`, and it returns a number between 0 and 1.
## Usage
Assuming you had some TextInput `first_name_search`:
```sql
SELECT * FROM users
ORDER BY {inputs.first_name_search.search('first_name')}
LIMIT 10 -- Optionally limit to only show the 10 closest results
```
becomes
```sql
SELECT * FROM users
ORDER BY damerau_levenshtein(first_name, '{inputs.first_name_search}')
LIMIT 10 -- Optionally limit to only show the 10 closest results
```
## Options
Name of the text input, used to reference the selected value elsewhere as `{inputs.name.value}`
Title displayed above the text input
Alternative placeholder text displayed in the text input
Hide the component when the report is printed
Adds an info icon with description tooltip on hover
---
evidence/sites/docs/pages/components/inputs/date-range/index.md
---
---
title: Date Range
sidebar_position: 1
description: Display a date picker for selecting a range of dates.
queries:
- orders_by_day.sql
---
Creates a date picker that can be used to filter a query.
Includes a set of preset ranges for quick selection of common date ranges. These are relative to the supplied end date.
To see how to filter a query using an input component, see [Filters](/core-concepts/filters).
From {inputs.date_range_name.start} to {inputs.date_range_name.end}
````markdown
From {inputs.date_range_name.start} to {inputs.date_range_name.end}
````
## Examples
### Using Date Range from a Query
From {inputs.date_range_from_query.start} to {inputs.date_range_from_query.end}
````markdown
From {inputs.date_range_from_query.start} to {inputs.date_range_from_query.end}
````
### Manually Specifying a Range
```markdown
```
### With a Title
```markdown
```
### Visible During Print / Export
````markdown
````
### Filtering a Query
```sql filtered_query
select
*
from ${orders_by_day}
where day between '${inputs.range_filtering_a_query.start}' and '${inputs.range_filtering_a_query.end}'
```
````markdown
```sql filtered_query
select
*
from ${orders_by_day}
where day between '${inputs.range_filtering_a_query.start}' and '${inputs.range_filtering_a_query.end}'
```
````
### Customizing Single Preset Ranges
```svelte
```
### Customizing Multiple Preset Ranges
````svelte
````
### Default Value for Preset Ranges
````svelte
````
## Options
Title to display in the Date Range component
Customize "Select a Range" drop down, by including present range options. **Range options**: `'Last 7 Days'` `'Last 30 Days'` `'Last 90 Days'` `'Last 365 Days'` `'Last 3 Months'` `'Last 6 Months'` `'Last 12 Months'` `'Last Month'` `'Last Year'` `'Month to Date'` `'Month to Today'` `'Year to Date'` `'Year to Today'` `'All Time'`
Accepts preset in string format to apply default value in Date Range picker. **Range options**: `'Last 7 Days'` `'Last 30 Days'` `'Last 90 Days'` `'Last 365 Days'` `'Last 3 Months'` `'Last 6 Months'` `'Last 12 Months'` `'Last Month'` `'Last Year'` `'Month to Date'` `'Month to Today'` `'Year to Date'` `'Year to Today'` `'All Time'`
Adds an info icon with description tooltip on hover
---
evidence/sites/docs/pages/components/inputs/button-group/index.md
---
---
title: Button Group
description: Display a group of single-select buttons for quick filtering using a small set of options.
sidebar_position: 1
queries:
- categories.sql
---
Creates a group of single-select buttons for quick filtering
To see how to filter a query using a Button Group, see [Filters](/core-concepts/filters).
## Examples
### Button Group using Options from a Query
Selected: {inputs.category_picker}
```markdown
Selected: {inputs.category_picker}
```
### With a Title
Selected: {inputs.category_selector}
```markdown
Selected: {inputs.category_selector}
```
### With a Default Value
Selected: {inputs.selected_button1}
````markdown
Selected: {inputs.selected_button1}
````
### With Hardcoded Options
Selected: {inputs.hardcoded_options}
````markdown
Selected: {inputs.hardcoded_options}
````
### With Hardcoded Options and Default Value
Selected: {inputs.hardcoded_options_default}
````markdown
Selected: {inputs.hardcoded_options_default}
````
### Alternative Labels
Selected: {inputs.alternative_labels_selector}
````markdown
Selected: {inputs.alternative_labels_selector}
````
### Filtering a Query
```sql filtered_query
select
category, item, sum(sales) as total_sales
from needful_things.orders
where category like '${inputs.category_button_group}'
group by all
```
````markdown
````
### Style Buttons as Tabs
Selected: {inputs.buttons_as_tabs}
```markdown
Selected: {inputs.buttons_as_tabs}
```
### Style Buttons as Tabs: With Hardcoded Options
Selected: {inputs.button_tabs_hardcoded_options}
````markdown
Selected: {inputs.button_tabs_hardcoded_options}
````
# ButtonGroup
## Options
Adds an info icon with description tooltip on hover. Appears next to title.
# ButtonGroupItem
The ButtonGroupItem component can be used to manually add options to a button group. This is useful if you want to add a default option, or if you want to add options that are not in a query.
## Options
---
evidence/sites/docs/pages/components/inputs/slider/index.md
---
---
title: Slider
description: Display a linear input to select a value from a range.
sidebar_position: 1
---
Creates a Slider input with default min, max and step values
````markdown
````
Min and Max values can be defined, the step property and define the incremental value of the slider
````markdown
````
showMaxMin property can hide the Max and Min values with false, by default showMaxMin is true
````markdown
````
showInput property can show the input field with true, by default showInput is false
````markdown
````
The default size of the slider can be altered with the size property using; medium, large or full
````markdown
````
````markdown
````
````markdown
````
````sql flight_data
SELECT
CAST(fare AS INT) AS fare,
CAST((SELECT MAX(fare) FROM flights) AS INT) AS max_fare,
FROM flights
LIMIT 100
````
## Specifying Dynamic Columns
Supply data with a specified column name to define the slider's min and max values. The slider's range will be calculated based on the column's minimum and maximum values.
````markdown
````
Supply data with specified column names for minColumn, maxColumn, and/or defaultValue. The first row’s value in each of these columns will determine the minimum, maximum, or default value, respectively.
````markdown
````
# Slider
## Options
name of the slider, used to reference the selected value elsewhere as `{inputs.name}`
Sets the initial value of the silder
Sets the minimum value on the slider. Negative Values accepted.
Sets the maximum value on the slider. This value must be larger than the min.
Defines the incremental value of the slider
Hides or shows min and max value markers on slider.
Hides or shows the input field on the slider.
Delays updating the input value (in milliseconds) after the slider changes.
Sets the length of the slider
Adds an info icon with description tooltip on hover
---
evidence/sites/docs/pages/components/inputs/dimension-grid/index.md
---
---
title: Dimension Grid
description: Display an interactive grid of one dimensional columns to filter by many dimensions simultaneously.
sidebar_position: 1
---
Dimension grid produces an interactive grid of one dimension tables, one for each string column in the source table. The dimension grid can can also be used as an input.
```orders
select state, category, item, channel, sales from needful_things.orders
```
```monthly_sales
select
order_month,
sum(sales) as sales_usd0
from needful_things.orders
where ${inputs.selected_dimensions}
group by all
```
````markdown
````
## Examples
### Basic Usage
```html
```
### As an Input
Dimension grid produces a condition for all of the selected dimensions which is suitable for referencing directly in a `where` or `filter` clause. For example `airline = 'Air Canada' and plane = '747`. Where no dimensions have been selected, DimensionGrid returns `true`.
````html
```sql filtered_query
select *
from source_name.table
where ${inputs.selected_dimensions}
```
````
### Multi Select
Using the multiple prop, Dimension grid can filter by multiple rows in the same column. Default value is false
```monthly_sales_multi
select
order_month,
sum(sales) as sales_usd0
from needful_things.orders
where ${inputs.multi_dimensions}
group by all
```
````html
```monthly_sales_multi
select
order_month,
sum(sales) as sales_usd0
from needful_things.orders
where ${inputs.multi_dimensions}
group by all
```
````
## Options
Query name, wrapped in curly braces
SQL aggregate which could be applied to `data` e.g. 'sum(sales)'
Name of the dimension grid, used to reference the selected value elsewhere as `{inputs.name}`
Title for the dimension grid
Subtitle - appears under the title
Label for the metric
Sets format for the value [(see available formats)](/core-concepts/formatting)
Maximum number of rows to include in each table
Allows for multiple rows in a column to be selected and filtered
---
evidence/sites/docs/pages/components/inputs/date-input/index.md
---
---
title: Date Input
sidebar_position: 1
description: Display a date picker for selecting a singledate or a range of dates.
queries:
- orders_by_day.sql
---
A date input component allows the user to select a date or a range of dates. The selected dates can be used as inputs to queries or components.
To see how to filter a query using an input component, see [Filters](/core-concepts/filters).
```sql filtered_query
select
*
from ${orders_by_day}
where day > '${inputs.date_filtering_a_query.value}'
```
````markdown
```sql filtered_query
select
*
from ${orders_by_day}
where day > '${inputs.range_filtering_a_query.value}'
```
````
## Examples
### Using Date Input from a Query
The Date selected can be accessed through the `inputs.[name].value`
Date Selected: {inputs.date_input_from_query.value}
````markdown
Date Selected: {inputs.date_input_from_query.value}
````
### With a Title
```markdown
```
## Date Range
Creates a date picker for selecting a date range to filter queries, with selectable preset date options.
### Filtering a Query with Range Calendar
The Date selected can be accessed through the `inputs.[name].start` & `inputs.[name].end`
```sql filtered_query_ranged
select
*
from ${orders_by_day}
where day between '${inputs.range_filtering_a_query.start}' and '${inputs.range_filtering_a_query.end}'
```
````markdown
```sql filtered_query_ranged
select
*
from ${orders_by_day}
where day between '${inputs.range_filtering_a_query.start}' - '${inputs.range_filtering_a_query.end}'
```
````
### Default Value for Preset Ranges
````svelte
````
### Customizing Single Preset Ranges
```svelte
```
### Customizing Multiple Preset Ranges
````svelte
````
### Manually Specifying a Range
```markdown
```
## Options
Title to display in the Date Input component
Customize "Select a Range" drop down, by including present range options. **Range options**: `'Last 7 Days'` `'Last 30 Days'` `'Last 90 Days'` `'Last 3 Months'` `'Last 6 Months'` `'Last 12 Months'` `'Last Month'` `'Last Year'` `'Month to Date'` `'Year to Date'` `'All Time'`
Accepts preset in string format to apply default value in Date Input picker. **Range options**: `'Last 7 Days'` `'Last 30 Days'` `'Last 90 Days'` `'Last 3 Months'` `'Last 6 Months'` `'Last 12 Months'` `'Last Month'` `'Last Year'` `'Month to Date'` `'Year to Date'` `'All Time'`
Adds an info icon with description tooltip on hover
---
evidence/sites/docs/pages/components/all-components/index.md
---
---
sidebar_position: 0
title: All Components
hide_title: false
hide_table_of_contents: false
description: An index of the components available in the Evidence library.
---
Evidence is a library for creating reports in markdown and SQL. It uses ECharts for charts, Leaflet for maps, and Shadcn for UI components.
## Data
### [Big Value](/components/data/big-value)
### [Data Table](/components/data/data-table)
## Charts
### [Line](/components/charts/line-chart)
Line Chart - Single Series
Line Chart - Multiple Series
Line Chart - Multiple Y Columns
### [Area](/components/charts/area-chart)
Area Chart
Stacked Area Chart
100% Stacked Area Chart
### [Bar](/components/charts/bar-chart)
Bar Chart
Stacked Bar Chart
100% Stacked Bar Chart
Grouped Bar Chart
Horizontal Bar Chart
Horizontal Stacked Bar Chart
Horizontal 100% Stacked Bar Chart
Horizontal Grouped Bar Chart
Long Bar Chart
### [Scatter](/components/charts/scatter-plot)
Scatter Plot
Scatter Plot - Multiple Series
### [Bubble](/components/charts/bubble-chart)
Bubble Chart
Bubble Chart - Multiple Series
### [Funnel](/components/charts/funnel-chart)
Funnel Default
Funnel Side Aligned
### [Sankey](/components/charts/sankey-diagram)
Default Sankey
Vertical Sankey
### [Heatmap](/components/charts/heatmap)
Basic Heatmap
Customized Heatmap
### [Calendar Heatmap](/components/charts/calendar-heatmap)
Default Calendar Heatmap
Multi-year Calendar Heatmap
### [Histogram](/components/charts/histogram)
Default Histogram
### [Box Plot](/components/charts/box-plot)
Default Box Plot
Horizontal Box Plot
### [Mixed Type Charts](/components/charts/mixed-type-charts)
Bar and Line
### [Annotations](/components/charts/annotations)
Reference Line - y-axis
Reference Line - x-axis
Reference Area - x-axis
Reference Area - y-axis
Reference Area - Box
### [Custom ECharts](/components/charts/custom-echarts)
Custom ECharts Treemap
Custom ECharts Funnel
Custom ECharts Pie Chart
Custom ECharts Donut Chart
Advanced ECharts Example
## Inputs
### [Button Group](/components/inputs/button-group)
### [Dropdown](/components/inputs/dropdown)
### [TextInput](/components/inputs/text-input)
### [DateRange](/components/inputs/date-range)
### [Dimension Grid](/components/inputs/dimension-grid)
## UI
### [Accordion](/components/ui/accordion)
### [Alert](/components/ui/alert)
### [Details](/components/ui/details)
### [Grid](/components/ui/grid)
### [Modal](/components/ui/modal)
### [Tabs](/components/ui/tabs)
## Maps
### [Area Map](/components/maps/area-map)
### [Point Map](/components/maps/point-map)
### [Bubble Map](/components/maps/bubble-map)
### [Base Map](/components/maps/base-map)
### [US Map](/components/maps/us-map)
---
evidence/sites/docs/pages/install-evidence/index.md
---
---
sidebar_position: 3
hide_table_of_contents: false
title: Install Evidence
description: Install Evidence with the VSCode Extension, from the command line, alongside dbt, or using Codespaces.
---
The easiest way to get started with Evidence is to use Evidence Studio, our AI-powered web IDE.
Get Started
```shell
npx degit evidence-dev/template my-project
cd my-project
npm install
npm run sources
npm run dev
```
1. Install Evidence from the VSCode Marketplace
2. Open the Command Palette (`Ctrl/Cmd + Shift + P`) and enter `Evidence: New Evidence Project`
3. Click `Start Evidence` in the bottom status bar
- This will install required dependencies and start the Evidence server
- You should see a browser window open automatically with your app preview
- On Windows, this step can take a couple of minutes the first time
4. Make changes to a markdown file and **save the file** to see the updates in your browser window
The template app running in your browser contains a tutorial on how to use Evidence.
Install VSCode Extension
```shell
cd path/to/your/dbt/project
npx degit evidence-dev/template reports
npm --prefix ./reports install
npm --prefix ./reports run sources
npm --prefix ./reports run dev
```
You can install Evidence inside your dbt project, inside a folder called `reports`, to create a [monorepo](https://github.com/archiewood/analytics_monorepo).
This allows changes across your modelling layer (in `/models`) and your reporting layer (in `reports`) in the same commits.
This currently needs to be done from the terminal, rather than from the dbt Cloud UI.
Create Evidence Codespace
**Note:** Codespaces is much faster on the Desktop app. After the Codespace has booted, select the hamburger menu → Open in VS Code Desktop.
## System Requirements
See [system requirements page](/guides/system-requirements).
## Updating Evidence
See [updating your app](/guides/updating-your-app).
---
If you run into any issues, [reach out in Slack.](https://slack.evidence.dev)
---
evidence/sites/docs/pages/build-your-first-app/index.md
---
---
sidebar_position: 4
hide_table_of_contents: false
title: Build Your First App
description: A 10 minute guide to building your first Evidence app.
---
This is a guided tutorial to help you build your first Evidence app. If you'd prefer to learn how Evidence works, start with the [Syntax](/core-concepts/syntax).
**By the end of this 10 minute guide, you will be able to:**
- Create and edit a page in Evidence
- Write a query on demo data
- Create a table
- Create a chart
- Connect a new CSV data source
## Prerequisites
Please ensure that you have already installed Evidence: [Install Evidence](/install-evidence).
If you are new to web development, start with the [Basics](#basics).
If you are familiar with running a server at `localhost`, and writing pages in Markdown, skip to [Working with data](#working-with-data).
## Basics
### 1. Start Evidence
Evidence can be started from VSCode, or from the Command Line. Both will work for this tutorial. If you're unsure, start with VSCode:
Click `Start Evidence` in the bottom status bar:
From the root of your project directory:
```bash
npm run dev
```
If you chose a different setup during [Install Evidence](/install-evidence#other-options), use the command that matches your setup.
Your browser should open automatically. If it doesn't, open your browser and navigate to `localhost:3000` in the address bar. You should see your Evidence app:

You have now started Evidence in a **local development server** on your own machine.
### 2. Add a new page
Go back to VSCode (or your file editor of choice) and open the `src/pages` directory. Right-click on the `pages` directory and select `New File`. Name the file `new-page.md`, or a name of your choice.
Add the following to the file and save it (`Ctrl+S` or `Cmd+S`):
```markdown
## Hello Evidence
This is a new page in Evidence.
```
Refresh Evidence in your browser. You should see your new page in the sidebar:

### 3. Write Markdown
Make some more changes to the page. You'll see them reflected "live" in the browser, immediately after saving. There is no need to restart the server.
This is called **hot reloading** (HMR), and it allows you to see your changes in real-time as you are building your page.
Evidence pages are `.md` files, and are written in a popular language called Markdown. You can learn more about Markdown [here](/reference/markdown).
You can also insert HTML directly into your page if you need more control.
Here are some examples of Markdown and HTML to try:
```markdown
## Hello Evidence
This is a new page in Evidence.
### This is a lower level header
This is some *italic* and **bold** text.
This is a [link](https://evidence.dev).
This is an image inserted using Markdown:

This is an image inserted using HTML:
```
Here's how it will look when rendered in the browser:

Now that you know how to create and edit pages, let's move on to working with data.
## Working with data
### 4. Understand data sources and queries
Navigate to `localhost:3000/settings` in your browser.
Here you'll find our demo dataset, `needful_things`. It is a [DuckDB](https://duckdb.org) database, which is one of many databases that Evidence supports.

Later in this tutorial you will learn how to add a new data source. For now, we will use `needful_things` to write a **source query**.
A data source in Evidence always consists of at least 2 types of files, but may have more.
1. A **connection.yaml** file. Any non-secret configuration needed to connect to your data source will be saved here. This file is automatically generated when you create a new data source via the `/settings` page.
2. **Source queries** allow you to filter and transform your data source before using it on a page. You may not need all of the tables from `needful_things`, or you may only need a few columns from a certain table. Your source query should be written in the dialect of SQL that matches your data source. A single data source can have multiple source queries.
3. (Sometimes) A **connection.options.yaml** file. Any secret credentials needed to connect to your data source will be saved here (base64 encoded). This file is automatically generated when you create a new data source via the `/settings` page.
4. (Sometimes) A **data file** itself. In our example, all of our data sits within a file called `needful_things.duckdb`.
You will see this reflected in the folder structure for each data source under the `sources` folder:
```code
sources/
`-- needful_things/
|-- connection.yaml
|-- needful_things.duckdb
`-- orders.sql
```
There is no `connection.options.yaml` file in this case, as the duckdb data source does not have any secret credentials.
### 5. Set up a source query
Add a new `.sql` file to the `sources/needful_things` directory. Name it `my_query.sql`, or a name of your choice.
In this file, write a query to select all columns from the `orders` table:
**my_query.sql**
```sql
select * from orders
```
Save the file. Later, you'll be able to refer to this data source as `needful_things.my_query`.
### 6. Run sources
Once you have configured source queries, you need to **run sources** to actually execute them.
If your dev server is running, sources will run automatically if you make changes to your queries.
If your data source itself has changed, or if you are building pages [for deployment](/deployment/overview), you may need to run sources manually from the Command Line:
```bash
npm run sources
```
**What does it mean to run sources?**
Data from various sources and formats (i.e. Snowflake, a Postgres database, and a CSV) normally cannot be queried and joined using the same syntax or SQL dialect. Evidence transforms queries from all data sources to create one unified **data cache**, which can then be used within your pages.
Learn more at at Core Concepts > [Data Sources](/core-concepts/data-sources).
### 7. Set up a Markdown Query
In order to make data from the data cache available for use on pages, you must create a **Markdown query** for it.
Clean up everything from your page, and add the following to create a Markdown query named `my_query_summary`:
**new-page.md**
````markdown
## Hello Evidence
### Orders Table
```my_query_summary
select * from needful_things.my_query
```
````
Refresh, and you'll see a grey box that looks like this:

If you don't see the box, click the 3-dot menu at the top right of the page and select Show Queries. You can hide or show queries on any Evidence-generated page, including this one.
We'll use this data in the next section!
**What is the difference between a Source Query and a Markdown Query?**
A **source query** is run directly against your data source, and must be written in the dialect of SQL that matches it. Running sources populates the data cache, which is not directly accesible by components. Sources can be run manually.
A **Markdown query** is written in the DuckDB dialect, and is run against the data cache. Markdown queries run with every page load, and their outputs are directly accessible by components within your pages.
To learn more about Markdown queries, including how to reuse them across pages, take a look at Core Concepts > [Markdown Queries](/core-concepts/queries).
## Adding components
### 8. Create a Data Table
One simple way to display data is with a [Data Table](/components/data/data-table). Add a `DataTable` component that uses `my_query_summary` as its data source:
**new-page.md**
````markdown
## Hello Evidence
### Orders Table
```my_query_summary
select * from needful_things.my_query
```
````
Refresh the page in your browser, and you should now see:
```my_query_summary
select * from needful_things.orders
```
Very nice - you just made your first Evidence component. Let's refine things a bit.
The Markdown query isn't doing much at the moment. It's simply displaying all 10,000 records and all columns. We can make it more useful.
Let's say we want to pull the 100 most recent orders, in order to send these customers a discount code. Change the Markdown query to:
````markdown
```my_query_summary_top100
select
order_datetime,
first_name,
last_name,
email
from needful_things.my_query
order by order_datetime desc
limit 100
```
````
Now refresh, and notice that your table has changed to show only the most recent 100 orders, with only the table columns you specified:
```my_query_summary_top100
select
order_datetime,
first_name,
last_name,
email
from needful_things.orders
order by order_datetime desc
limit 100
```
You can further select or rename the columns that appear in your table by specifying them in the `DataTable` component:
```markdown
```
This will display:
A Data Table is a built-in **component** of Evidence, and there are many more. To see a full list of components, take a look at the left-hand sidebar, or go to [All Components](/components/all-components).
### 9. Create a Bar Chart
Next, let's visualize orders over the past year using a [Bar Chart](/components/charts/bar-chart). Add the following to your page. Notice that we are creating a new Markdown query called `orders_by_month`:
````markdown
### Orders by Month
```orders_by_month
select order_month, count(*) as orders from needful_things.my_query
group by order_month order by order_month desc
limit 12
```
````
And you should see:
```orders_by_month
select order_month, count(*) as orders from needful_things.orders
group by order_month order by order_month desc
limit 12
```
### 10. Connect a new CSV data source
Go to `localhost:3000/settings`, and select **Add new source**:

Choose **CSV** as the source type, and upload a CSV file of your choice.
Here, we'll use [**us_alt_fuel_stations.csv**](https://catalog.data.gov/dataset/alternative-fueling-station-locations-422f2/resource/341957d8-daf6-4a38-ab1d-8ec1bc21cfb9) - a public data source on EV charging stations across the US.
Select Source Type: **CSV**, and give your source a name. Hit Confirm:

You can read about various configuration options for CSV files [here](/core-concepts/data-sources#csv-files). For now, leave this blank, and hit **Confirm Changes**:

You should now see your new source under the sources folder. Copy your CSV file into it:
```code
sources/
`-- ev_stations/
|-- connection.yaml
|-- connection.options.yaml
`-- us_alt_fuel_stations.csv
```
That's it! You've set up a new data source. If you'd like to use it, try adding the following Markdown Query and the [USMap](/components/maps/us-map) component:
````markdown
### EV Map
```ev_map
select State, count(*) AS ev_station_count from ev_stations.us_alt_fuel_stations
where State not in ('CA')
group by State order by ev_station_count desc
```
````
And you should see:
```ev_map
select
State,
count(*) AS ev_station_count
from ev_stations.us_alt_fuel_stations
where State not in ('CA')
group by State order by ev_station_count desc
```
That's it! You now know the basics of setting up data sources, writing queries, and creating components in Evidence.
## Next steps
- Explore other components: [All Components](/components/all-components)
- Learn how to deploy your Evidence app: [Deployment](/deployment/overview)
- Learn more about writing and organizing Markdown queries: [SQL Queries](/core-concepts/queries)
### Help and support
If you need help, or have corrections and suggestions for this tutorial, please join the [Evidence Slack community](https://slack.evidence.dev).
---
evidence/sites/docs/pages/guides/index.md
---
---
title: Guides
sidebar_position: 6
sidebar_link: false
---
---
evidence/sites/docs/pages/guides/system-requirements/index.md
---
---
title: System Requirements
sidebar_position: 5
description: Evidence requires Node.js, NPM, and Git
---
Evidence requires Node.js ≥18.13, 20 or 22, and NPM 7 or above.
Check your versions with `node -v` and `npm -v`
**Note:** if you are installing NodeJS for the first time, be sure to install the LTS version.
Download Node.js + NPM (LTS version)
### Updating
Update to the latest npm version with `npm install -g npm@latest`
## Git
Evidence requires git. If you do not already have git installed, you can follow the [instructions here.](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
We also recommend signing up for [GitHub](https://github.com)
---
evidence/sites/docs/pages/guides/best-practices/index.md
---
---
title: Best Practices
sidebar_position: 3
description: Tips for building performant data apps with Evidence
---
Evidence is a very flexible and open-ended tool that allows you to build almost any kind of data app. However, to get the best out of Evidence, here are some principles:
1. [Only source the data you need](#1-only-source-the-data-you-need)
2. [Sort your source queries](#2-sort-your-source-queries)
3. [Change props, not components](#3-change-props-not-components)
4. [Avoid large markdown queries](#4-avoid-large-markdown-queries)
## Source Performance
### 1. Only source the data you need
**Best Practice:** Pre-aggregate data in your source queries, only select the columns and rows you need.
Every time you rebuild Evidence, it re-caches all the data from your sources.
This can:
- Be time-consuming and expensive to cache.
- Cause longer load times for your app, as the data comes over the network.
It's best to only source the data you need.
### 2. Sort your source queries
**Best Practice:** Sort your source queries. Prioritize columns that appear in `where` clauses in your markdown queries.
The cache in Evidence is composed of parquet files. After running `npm run sources`, you can inspect these files in `.evidence/template/static/data`.
Sorted queries lead to better compression in parquet files, resulting in faster source build times, lower likelyhood of hitting memory limits, and faster query times in your app.
If your source queries are sorted, the client-side query engine is able to take advantage of [Projection Pushdown](https://duckdb.org/2021/06/25/querying-parquet.html#automatic-filter--projection-pushdown) i.e. only loading the rows it needs.
## Interactive Performance
### 3. Change props, not components
**Best Practice:** Use inputs to change props or change queries, not whole components.
If you swap out components (for example using `{#if}` blocks), Evidence will re-render the entire component. This can cause a jerky transition as the component is re-rendered.
#### Don't do this
The entire component is re-rendered when the dropdown changes:
````svelte
```sql categories
select * from categories
```
```sql products
select * from products
```
{#if inputs.chart_picker.value == "categories"}
{:else}
{/if}
````
#### Do this
Instead, change which query the component uses with a [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator):
````svelte
```sql categories
select * from categories
```
```sql products
select * from products
```
````
### 4. Avoid large markdown queries
**Best Practice:** Do not return more than ~100,000 rows from queries on your page. Aggregate data in your markdown queries or source queries if needed.
Browsers have limited memory, and large datasets can cause slowdowns, increased rendering times and crashes. It's unlikely that you are attempting to visualize 100,000 datapoints on a webpage (an average desktop display only has ~1M pixels) so you can aggregate the data in your markdown queries, or even in you source queries.
---
evidence/sites/docs/pages/guides/updating-your-app/index.md
---
---
title: Updating Your App
sidebar_position: 3
description: Update your app using the CLI or the VS Code extension.
---
When new versions of Evidence are released, we post release notes in [Slack](https://slack.evidence.dev). You can also take a look at our pull requests on GitHub to see which changes are being made.
We recommend updating regularly to get the latest features and bug fixes. Evidence's is being actively developed, and major releases may introduce breaking changes. We therefore recommend testing updates by running your app in development mode.
## CLI
Run `npm install @evidence-dev/evidence@latest @evidence-dev/core-components@latest`.
## VS Code
Open the command palette and run `Evidence: Update to Latest Version`
## Getting Help
If you run into any problems with updates, reach out on [Slack](https://slack.evidence.dev) or email .
---
evidence/sites/docs/pages/guides/chart-cheat-sheet/index.md
---
---
title: Chart Cheat Sheet
sidebar_position: 3
description: A quick reference to the elements of an Evidence Chart.
---
## Chart Elements

#### Horizontal Chart (`swapXY=true`)

---
evidence/sites/docs/pages/guides/troubleshooting/index.md
---
---
title: Troubleshooting
sidebar_position: 2
description: Join the Evidence Slack Community for troubleshooting and support
---
**Running into Problems?**
- Join the [Evidence Community](https://slack.evidence.dev) to get help with issues and discuss feature ideas.
- Check out the list of [open issues in our GitHub Repo](https://github.com/evidence-dev/evidence/issues)
- If you have a specific question and cannot go through Slack or GitHub, please email
## Checking Version Numbers
```sql commands
select 'npm view @evidence-dev/evidence version' as "Command", 'Check Evidence version' as "Description" UNION ALL
select 'node -v' as "Command", 'Check NodeJS version' as "Description"
```
Run these commands in your terminal to see which versions your app is using
# Common Issues
## Installation
### Not able to run `npm install`
This is often related to the version of NodeJS your app is using. See [system requirements](/guides/system-requirements) for more information
### Installation taking a long time
On Windows, the initial installation can take up to a few minutes. If it has been longer than 10 minutes and your app hasn't started, [reach out in the Slack community for help](https://slack.evidence.dev)
## Data Sources
### Data is not available for querying
Ensure that you've done the following:
- Add `.sql` files to your `sources/my-source` directory to define which data to bring into Evidence (does not apply to the CSV connector, which does not require `.sql` files)
- Run `npm run sources` to load the data
To check whether your data has been successfully loaded into your app, go to the `/explore/schema` page to see which data is in your app.
### Failure in `npm run sources`
If you're having problems loading data with `npm run sources`, try using `npm run sources -- --debug` to display additional logs
## Page Loading
If you are running into a problem on your page, but are not seeing a clear error message, try looking in your browser console to see if there is additional information available.
To open your browser console:
- Right click anywhere on your page
- Click "Inspect" - the browser dev tools pane should open
- Click the "Console" tab - this will display warnings and errors generated by your page
This is helpful information to provide when asking questions in slack or creating issues on Github.
## Deployment
If you have issues when building or deploying your app, try running `npm run build` locally to see if the behaviour is the same as in your deployment environment.
If the build works locally, but not in your deployment environment, check that the NodeJS version used in your deployment environment fits within the [system requirements](/guides/system-requirements).
# Known Issues
See [our open Github issues](https://github.com/evidence-dev/evidence/issues) for a full list of known issues
---
evidence/sites/docs/pages/deployment/index.md
---
---
title: "Deployment"
sidebar_position: 3
sidebar_link: false
---
---
evidence/sites/docs/pages/deployment/self-host/index.md
---
---
sidebar_position: 4
title: Self Host
sidebar_link: false
---
---
evidence/sites/docs/pages/deployment/self-host/cloudflare-pages/index.md
---
---
sidebar_position: 4
title: Cloudflare Pages
description: Deploy Evidence to Cloudflare Pages by linking to a Git repository. Pages supports auth via Cloudflare Access and custom domains.
og:
image: /img/deployment/deploy-cloudflare-pages.png
---
Cloudflare is a popular CDN and DNS provider that also offers a static site hosting service called [Cloudflare Pages](https://pages.cloudflare.com). Cloudflare Pages can deploy Evidence apps from a Git repository.
## Prerequisites
- A Cloudflare account
- An Evidence project pushed to a Git service like GitHub or GitLab
## Deploy Evidence to Cloudflare Pages
1. Navigate to the Cloudflare dashboard
1. Select **Workers & Pages** from the left-hand menu, and select **Create**
1. There are two tabs: **Workers** and **Pages** - choose **Pages**
1. Select **Connect to Git**, and choose GitHub or GitLab
1. Select Repository
- Authenticate with your Git provider
- Choose the repository to deploy from
- You may need to configure repository access permissions
1. Set up builds and deployments
- Choose a production branch
- Set the build command: `npm run sources && npm run build`
- Set the build output directory: `/build`
1. (Optionally select the root path containing your Evidence project if using a monorepo)
1. Add environment variables
- Click **Add variable**
- With your Evidence dev server running, go to the settings page and copy each of the environment variables
- Paste them into the Cloudflare Pages environment variables section
1. Click **Save and Deploy**
Your app will be deployed to a URL like `https://[repo-name].pages.dev`. It can take a few minutes for the site to be available after deployment.
## Domains, Authentication and Scheduling
### Authentication
By default, your app will be public.
Authentication can be configured with [Cloudflare Access](https://developers.cloudflare.com/cloudflare-one/identity/access).
Workers & Pages > [Your app] > Settings > General > Access Policy > Manage
You will need to set up access groups and policies to control access to your app. A one time PIN code can be configured for user login.
## Custom Domains
Cloudflare Pages supports custom domains.
Workers & Pages > [Your app] > Custom Domains > Set up a custom domain
## Data refresh
Cloudflare Pages does not have built in functionality for data refresh.
---
evidence/sites/docs/pages/deployment/self-host/hugging-face-spaces/index.md
---
---
sidebar_position: 4
title: Hugging Face Spaces
description: Deploy Evidence to Hugging Face Spaces from a GitHub repository. Spaces can be private to your org, and can use Github Actions for data refresh.
og:
image: /img/deployment/deploy-hugging-face-spaces.png
---
Hugging Face is an open-source platform for machine learning and artificial intelligence that provides tools and models for building, training, and deploying AI applications. [Hugging Face Spaces](https://huggingface.co/spaces) is a service that allows you to deploy machine learning models as web applications. Hugging Face Spaces can deploy Evidence apps from a Git repository.
## Prerequisites
- A Hugging Face account
- An Evidence project pushed to a Git service like GitHub
## Deploy Evidence to Hugging Face Spaces
1. Navigate to the Hugging Face Spaces
1. Select **Create new Space**
- Choose a name
- Space SDK: `Static`
- Static template: `Blank`
- Choose a visibility: `Public` or `Private` depending on your needs
1. Create a new [Access Tokens](https://huggingface.co/settings/tokens)
- Token Type: `Fine-grained`
- Name: e.g. `Evidence`
- Repositories Permissions: Choose the space you just created, and select `Read access to contents of selected repos` and `Write access to contents/settings of selected repos`
- Select Create Token, and save it somewhere safe
1. Add secrets to your GitHub repo: Settings > Secrets and variables > Actions
- Firstly add your Hugging Face Tokent as a secret named `HUGGINGFACE_TOKEN`
- With your Evidence dev server running, go to the settings page and copy each of the environment variables
- Alternatively, you can find credentials in `connection.options.yaml` files in your `/sources/your_source` directory. The key format used should be `EVIDENCE_SOURCE__[your_source]__[option_name]` (Note the casing matches your source names, and the double underscores). Note that the values are base64 encoded, and will need to be decoded.
1. Create the deploy workflow file: `.github/workflows/deploy.yml`, update the repo name and space name, and merge it into your main branch
```yaml
name: Deploy to Hugging Face Space on Merge
on:
push:
branches:
- main
workflow_dispatch:
jobs:
build_and_deploy:
runs-on: ubuntu-latest
steps:
# Checkout the repository
- uses: actions/checkout@v4
# Install dependencies and build the project
- run: npm ci && npm run sources && npm run build
env:
EVIDENCE_SOURCE__taxi__project_id: ${{ secrets.EVIDENCE_SOURCE__TAXI__PROJECT_ID }}
EVIDENCE_SOURCE__taxi__client_email: ${{ secrets.EVIDENCE_SOURCE__TAXI__CLIENT_EMAIL }}
EVIDENCE_SOURCE__taxi__private_key: ${{ secrets.EVIDENCE_SOURCE__TAXI__PRIVATE_KEY }}
# Deploy to Hugging Face Space
- name: Install Hugging Face CLI
run: pip install huggingface-hub
- name: Authenticate with Hugging Face
run: huggingface-cli login --token "${{ secrets.HUGGINGFACE_TOKEN }}"
- name: Deploy to Hugging Face Space
run: |
# Update to use your repo
huggingface-cli upload [your-username]/[your-space-name] ./build --repo-type=space
```
Your app will be deployed to a URL like `https://[your-username]-[your-space-name].static.hf.space/`
## Domains, Authentication and Scheduling
### Authentication
If you chose a private space, only members of your Hugging Face organization will be able to access the space.
### Custom Domains
Custom domains are not supported for Hugging Face Spaces.
### Data refresh
You can adjust the schedule for your deployment using the workflow file by adding a `schedule` trigger with a cron expression.
```yaml
on:
push:
branches: 'main'
schedule:
# This is every 10 minutes
- cron: '*/10 * * * *'
```
---
evidence/sites/docs/pages/deployment/self-host/aws-amplify/index.md
---
---
sidebar_position: 4
title: AWS Amplify
breadcrumb: "select 'AWS Amplify' as breadcrumb"
description: Deploy Evidence to AWS Amplify by linking to a Git repository. Amplify supports global passwords for authentication and custom domains.
og:
image: /img/deployment/deploy-aws-amplify.png
---
[AWS Amplify](https://aws.amazon.com/amplify) is an AWS service that allows you to create full stack web and mobile apps. Amplify can deploy Evidence apps by linking to a Git repository.
## Prerequisites
- An AWS account
- An Evidence project pushed to a Git service like GitHub, GitLab, or Bitbucket.
## Deploy Evidence to AWS Amplify
1. Login to the AWS Console
2. Navigate to AWS Amplify, and select **Deploy an app** / **Create new app**
3. **Choose source code provider**
- Select your source code provider (GitHub, Bitbucket, CodeCommit, GitLab).
- Click **Next**.
- Install and authorize the Amplify app on your repository via your Git provider.
4. **Add repository and branch**
- Use the search box to find the repository containing your Evidence project.
- Select the branch you want to deploy,
- (Optionally select the folder containing your Evidence project if using a monorepo).
- Click **Next**.
5. **App settings**
- Edit the frontend build command:
```code
npm run sources && npm run build
```
- Edit the build output directory: `build`
- Open the **Advanced settings** section
- Build image: `Custom build image`
- Reference: `public.ecr.aws/docker/library/node:20-bookworm`
- Click to add new **Environment variables**
- Copy your environment variables from the Evidence settings page: http://localhost:3000/settings/#deploy
- Alternatively, you can find credentials in `connection.options.yaml` files in your `/sources/your_source` directory. The key format used should be `EVIDENCE_SOURCE__[your_source]__[option_name]` (Note the casing matches your source names, and the double underscores). Note that the values are base64 encoded, and will need to be decoded.
- Click **Next**
6. **Review**
- Review your settings and click **Save and deploy**
Your app will be deployed to https://[branch-name]-[app-id].amplifyapp.com
## Domains, Authentication and Scheduling
### Authentication
Your deployed app will be public by default.
#### Global password
It is possible to set a global site password using AWS Amplify from the console:
Hosting > Access control > Manage access.
#### Cognito
It is also possible to set up auth via [Cognito](https://docs.amplify.aws/react/build-a-backend/auth).
### Custom domains
Your app will be deployed to https://[branch-name]-[app-id].amplifyapp.com
You can set a custom domain using AWS Amplify from the console:
Hosting > Custom domains > Add domain.
### Data refresh
You can manually refresh your data using AWS Amplify from the console:
[your-app] > Deployments > Redeploy this version.
---
evidence/sites/docs/pages/deployment/self-host/github-pages/index.md
---
---
sidebar_position: 4
title: GitHub Pages
description: Deploy Evidence to GitHub Pages from a GitHub repo. GitHub Pages can be private to your org, support custom domains, and using Actions for data refresh.
og:
image: /img/deployment/deploy-github-pages.png
---
GitHub Pages is a static site hosting service that publishes a website from HTML, CSS, and JavaScript files from a repository on GitHub. It optionally runs a build process to create these files. GitHub Pages can deploy Evidence apps from a GitHub repository.
**Base Path**
GitHub Pages serves sites at subpaths of github.io by default, e.g. `https://[username].github.io/your-app`, so you will need to adjust the [base path](/deployment/configuration/base-paths) AND the [build directory](/deployment/configuration/base-paths#configuring-the-build-directory-in-packagejson) for your app, unless using a custom domain.
## Prerequisites
- A GitHub account
- An Evidence project pushed to GitHub
## Deploy Evidence to GitHub Pages
1. Adjust the [base path](/deployment/configuration/base-paths) for your app to match the name of your GitHub repository.
- If your repo is stored at `https://github.com/username/my-evidence-app`, your base path should be `/my-evidence-app`.
```yaml
# evidence.config.yaml
deployment:
basePath: /my-evidence-app
```
```json
// package.json
"scripts": {
"build": "EVIDENCE_BUILD_DIR=./build/my-evidence-app evidence build",
}
```
1. Add secrets to your GitHub repo: Settings > Secrets and variables > Actions
- With your Evidence dev server running, go to the settings page and copy each of the environment variables
- Alternatively, you can find credentials in `connection.options.yaml` files in your `/sources/your_source` directory. The key format used should be `EVIDENCE_SOURCE__[your_source]__[option_name]` (Note the casing matches your source names, and the double underscores). Note that the values are base64 encoded, and will need to be decoded.
1. From your GitHub repository, click the **Settings** tab, and then click **Pages** in the Code and automation section.
1. Under **Source**, select **GitHub Actions**
1. Directly underneath, where it says "Use a suggested workflow, browse all workflows or create your own", click **Create your own**, and use the following workflow file, naming it `deploy.yml` or similar.
```yaml
name: Deploy to GitHub Pages
on:
push:
branches: 'main' # or whichever branch you want to deploy from
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- name: Install dependencies
run: npm install
- name: build
env:
BASE_PATH: '/${{ github.event.repository.name }}'
## Add and uncomment any environment variables here
## EVIDENCE_SOURCE__my_source__username: ${{ secrets.EVIDENCE_SOURCE__MY_SOURCE__USERNAME }}
## EVIDENCE_SOURCE__my_source__private_key: ${{ secrets.EVIDENCE_SOURCE__MY_SOURCE__PRIVATE_KEY }}
run: |
npm run sources
npm run build
- name: Upload Artifacts
uses: actions/upload-pages-artifact@v3
with:
path: 'build/${{ github.event.repository.name }}'
deploy:
needs: build
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy
id: deployment
uses: actions/deploy-pages@v4
```
1. Click **Commit changes**, either directly to your branch, or create a PR and merge it to your specified branch.
1. The deploy workflow will run, you can see the progress in the **Actions** tab.
Your app should be available at `https://[username].github.io/[your-app]`.
## Domains, Authentication and Scheduling
### Authentication
You can set up a private GitHub Pages site by setting the visibility of the repo to **Private**. This requires a GitHub Enterprise account.
This will mean only GitHub users with access to the repo will be able to access the site.
### Custom domains
You can add a custom domain to your GitHub Pages site. If you do this, you _do not_ need to adjust the base path for your app, as it does not need to be served from a subpath.
You can adjust the domain at:
[your repo] > Settings Tab > Pages > Custom domain
### Data refresh
You can adjust the schedule for your deployment using the workflow file by adding a `schedule` trigger with a cron expression.
```yaml
on:
push:
branches: 'main'
schedule:
# This is every 10 minutes
- cron: '*/10 * * * *'
```
---
evidence/sites/docs/pages/deployment/self-host/azure-static-apps/index.md
---
---
sidebar_position: 4
title: Azure Static Apps
description: Deploy Evidence to Azure Static Apps by linking a Git repository. Static Apps support global passwords, Entra ID, custom domains, and GitHub Actions for refresh.
og:
image: /img/deployment/deploy-azure-static-apps.png
---
[Azure Static Apps](https://learn.microsoft.com/en-us/azure/static-web-apps) is a Microsoft Azure service that allows you to deploy static websites and web apps to Azure. Azure Static Apps can deploy Evidence apps by linking to a Git repository.
## Prerequisites
- A Microsoft Azure account
- An Evidence project pushed to a Git service like GitHub or Azure DevOps
## Deploy Evidence to Azure Static Apps
1. In the Azure Portal, select **Create a Resource** and choose **Static Web App**
1. Basics
- Choose a subscription, and resource group for the app
- Choose a name for the app
- Choose a plan type: Free, Standard or Dedicated
- Choose a source code provider: GitHub, Azure DevOps or Other
- Authenticate with your Git provider
- Choose a repository, and branch to deploy from
- Build presets: `Custom`
- Output location `/build`
1. Deployment configuration
- Choose either a deployment token, or (recommended) GitHub to deploy your code
1. Advanced and Tags: No changes needed
1. Review and create: Click Create
1. This will create add a new workflow file in your repository, e.g. `.github/workflows/azure-static-web-apps-thankful-hill-01fbff51e.yml`
1. Add secrets to your GitHub repo: Settings > Secrets and variables > Actions
- With your Evidence dev server running, go to the settings page and copy each of the environment variables into the GitHub secrets
- Alternatively, you can find credentials in `connection.options.yaml` files in your `/sources/your_source` directory. The key format used should be `EVIDENCE_SOURCE__[your_source]__[option_name]` (Note the casing matches your source names, and the double underscores). Note that the values are base64 encoded, and will need to be decoded.
1. In your git repo, edit this file's "Build and Deploy" step, adding `app_build_command: "npm run sources && npm run build"`, and environment variables to reference the secrets
```yaml
- name: Build And Deploy
id: builddeploy
uses: Azure/static-web-apps-deploy@v1
with:
...
# Add this line
app_build_command: "npm run sources && npm run build"
###### End of Repository/Build Configurations ######
env:
# Add and uncomment your environment variables here
# Note that GitHub capitalizes the names of secrets, but Evidence requires the casing to match your source and option names
# EVIDENCE_SOURCE__my_source__username: ${{ secrets.EVIDENCE_SOURCE__MY_SOURCE__USERNAME }}
# EVIDENCE_SOURCE__my_source__private_key: ${{ secrets.EVIDENCE_SOURCE__MY_SOURCE__PRIVATE_KEY }}
```
1. Commit and push this change, and your app will deploy.
Your app will be available at `https://[random-word-12345].azurestaticapps.net`
## Domains, Authentication and Scheduling
### Authentication
You can add a global site password to your app:
[your-app] > Settings > Configuration > Password protection > Protect both staging and production environments
You can also configure other authentication providers, such as Microsoft Entra ID, or GitHub. See the [official docs](https://learn.microsoft.com/en-us/azure/static-web-apps/authentication-authorization#set-up-sign-in) for more information.
### Custom Domains
You can add a custom domain to your Azure Static App as follows:
[your-app] > Settings > Custom domains > Add > Custom domain on other DNS
### Data Refresh
To add a deployment schedule, modify the workflow file in your repository, adding a `schedule` trigger.
```yaml
on:
push:
branches: 'main'
schedule:
- cron: '0 0 * * *' # This is midnight every day
```
Also delete the `if` line from the `build_and_deploy_job` step:
```yaml
build_and_deploy_job:
if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed') # delete this line
```
---
evidence/sites/docs/pages/deployment/self-host/netlify/index.md
---
---
sidebar_position: 4
hide_table_of_contents: false
title: Netlify
description: Deploy Evidence to Netlify by linking to a Git repository. Netlify supports custom domains, global passwords, and GitHub Actions for data refresh.
og:
image: /img/deployment/deploy-netlify.png
---
[Netlify](https://www.netlify.com) is a cloud platform for building and deploying web apps and frontend sites. Netlify can deploy Evidence apps from a Git repository.
**Netlify URL Lowercasing**
All URLs on Netlify are converted to lowercase. This can cause issues if you're using `{params.my_param}` to filter data in your markdown. It's recommended to use lowercase any time you're using a URL parameter to filter data, like this:
```sql
SELECT * FROM source_name.my_table
WHERE LOWER(my_column) = LOWER('${params.my_param}')
```
Netlify lets you host a public version of your app for free, or you can create and host a password-protected version with Netlify's $15/month plan.
## Prerequisites
- An Evidence project pushed to a Git service like GitHub, GitLab, or Bitbucket.
- A Netlify account.
## Deploy Evidence to Netlify
1. From the Netlify dashboard, select **Add new site > Import an existing project**
1. Choose your Git provider (GitHub, GitLab, Bitbucket, Azure DevOps)
1. Select the repository containing your Evidence project
1. In the build settings
- **Build command**: `npm run sources && npm run build`
- **Publish directory**: `build`
1. In the environment variables
- Click **New variable**
- With your Evidence dev server running, go to the settings page and copy each of the environment variables
- Alternatively, you can find credentials in `connection.options.yaml` files in your `/sources/your_source` directory. The key format used should be `EVIDENCE_SOURCE__[your_source]__[option_name]` (Note the casing matches your source names, and the double underscores). Note that the values are base64 encoded, and will need to be decoded.
- Paste them into the Netlify environment variables section
1. (If using a monorepo) edit the base directory to point to your Evidence project
1. Click **Deploy [your-site-name]**
Your app will be available at `https://[your-site-name].netlify.app`.
## Domains, Authentication and Scheduling
### Authentication
#### Global password
Setting a global password requires a Netlify paid plan ($15/month).
Follow the directions provided by Netlify to set up a password for your site:
Netlify Dashboard >> [your-site] >> Site configuration >> Access & security >> Visitor access >> Configure site protection >> Basic password protection
#### OAuth
Netlify only supports OAuth via GitHub, GitLab, and Bitbucket.
Netlify Dashboard >> [your-site] >> Site configuration >> Access & security >> OAuth
### Custom domains
Your app will be deployed to https://[your-site-name].netlify.app
You can set a custom domain using Netlify from the console:
Netlify Dashboard >> [your-site] >> Domain management >> Add a domain
### Data refresh
#### Schedule updates using Build Hooks
If you want your site to update on a regular schedule, you can use GitHub Actions (or another similar service) to schedule regular calls to a [Netlify build hook](https://docs.netlify.com/configure-builds/build-hooks).
1. Create a [Netlify build hook](https://docs.netlify.com/configure-builds/build-hooks) in **Site configuration > Build & deploy > Continuous deployment > Build hooks**

This will give you a URL that GitHub will use to trigger builds
2. Add `NETLIFY_BUILD_HOOK` to your Github Repo's Secrets
- In your GitHub repo, go to Settings > Secrets > Actions and click **New repository secret**

- Add the build hook URL as the secret value

3. Add a schedule file to your project
- Create a new directory in your project called `.github`
- Within that directory, create another called `workflows`
- Add a new file in `.github/workflows` called `main.yml`
4. Add the following text to the `main.yml` file you just created. Be sure that the spacing and indentation is exactly as presented here, as it will impact whether the action runs correctly
```yaml
name: Schedule Netlify Build
on:
workflow_dispatch:
schedule:
- cron: '0 10 * * *' # Once a day around 6am ET (10am UTC)
jobs:
build:
name: Request Netlify Webhook
runs-on: ubuntu-latest
steps:
- name: POST to Build Hook
env:
BUILD_HOOK: ${{ secrets.NETLIFY_BUILD_HOOK }}
run: curl -X POST -d {} $BUILD_HOOK
```
5. See your GitHub Actions run in the **Actions** tab of your GitHub repo
---
evidence/sites/docs/pages/deployment/self-host/vercel/index.md
---
---
sidebar_position: 4
hide_table_of_contents: false
title: Vercel
description: Deploy Evidence to Vercel by linking to a Git repository. Vercel supports custom domains, global passwords, and GitHub Actions for data refresh.
og:
image: /img/deployment/deploy-vercel.png
---
[Vercel](https://vercel.com) is a cloud platform that allows you to simply deploy web applications. Vercel can deploy Evidence apps from a Git repository.
Vercel lets you host a public version of your app for free, or you can create and host a password-protected version with Vercel's $150/month pro plan.
## Prerequisites
- An Evidence project pushed to a Git service like GitHub, GitLab, or Bitbucket.
- A Vercel account.
## Deploy Evidence to Vercel
1. From the Vercel dashboard, select **Add new... Project**
1. Import the Git repository containing your Evidence project.
1. Edit the build and output settings:
- **Build command**: `npm run sources && npm run build`
- **Output directory**: `build`
1. (If using a monorepo) edit the root directory to point to your Evidence project
1. Edit the environment variables:
- With your Evidence dev server running, use the **Copy All** button on the settings page
- Paste them into the Vercel environment variables section, (they will automatically populate all the fields)
- Alternatively, you can find credentials in `connection.options.yaml` files in your `/sources/your_source` directory. The key format used should be `EVIDENCE_SOURCE__[your_source]__[option_name]` (Note the casing matches your source names, and the double underscores). Note that the values are base64 encoded, and will need to be decoded.
1. Click **Deploy**
Your app will be deployed to https://[project-name].vercel.app
## Domains, Authentication and Scheduling
### Authentication
Your deployed app will be public by default.
#### Global password
This requires a Vercel paid plan with [advanced deployment protection](https://vercel.com/docs/security/deployment-protection#advanced-deployment-protection), starting at $150/month.
Vercel Dashboard > [your-project] > Settings > Deployment Protection > Password protection
### Custom domains
Your app will be deployed to https://[project-name].vercel.app
You can set a custom domain using Vercel from the console:
Vercel Dashboard > [your-project] > Settings > Domains
### Data refresh
Your project will be automatically built when you push to your repository, refreshing your data.
#### Schedule updates using Deploy Hooks
If you want your site to update on a specific schedule, you can use GitHub Actions (or another similar service) to schedule regular calls to a [Vercel deploy hook](https://vercel.com/docs/concepts/git/deploy-hooks).
1. Create a [Vercel deploy hook](https://vercel.com/docs/concepts/git/deploy-hooks).
This will give you a URL that GitHub will use to trigger builds
2. Add `VERCEL_DEPLOY_HOOK` to your Github Repo's Secrets
- In your GitHub repo, go to Settings > Secrets > Actions and click **New repository secret** and create a secret, `VERCEL_DEPLOY_HOOK`, with the URL from step 1.
3. Add a schedule file to your project
- Create a new directory in your project called `.github`
- Within that directory, create another called `workflows`
- Add a new file in `.github/workflows` called `main.yml`
4. Add the following text to the `main.yml` file you just created. Be sure that the indentation in your `main.yml` matches the below.
```yaml
name: Schedule Vercel Deploy
on:
workflow_dispatch:
schedule:
- cron: '0 10 * * *' # Once a day around 6am ET (10am UTC)
jobs:
build:
name: Request Vercel Webhook
runs-on: ubuntu-latest
steps:
- name: POST to Deploy Hook
env:
BUILD_HOOK: ${{ secrets.VERCEL_DEPLOY_HOOK }}
run: curl -X POST -d {} $BUILD_HOOK
```
5. See your GitHub Actions run in the **Actions** tab of your GitHub repo
---
evidence/sites/docs/pages/deployment/self-host/windows-iis/index.md
---
---
sidebar_position: 4
hide_table_of_contents: false
title: Windows IIS
description: Deploy Evidence to a Windows IIS server.
---
Windows IIS server is a part of any Windows Server operating system and is also available in the Windows Desktop business versions. This makes IIS a readily available static site server.
## Prerequisites
- A Windows desktop or server operating system with the Internet Information Services feature enabled. The following sub-features are required:
- Web Management Tools > IIS Management Console
- World Wide Web Services > Common HTTP Features:
- Default Document
- Static Content
- Performance Features > Static Content Compression
- A built Evidence project to copy to the IIS server
## Deploy Evidence to IIS
1. Open the IIS Manager
2. Add a new website
3. Copy the files from the Evidence build folder to the Physical Path of the new website
4. Check permissions
- Make sure the permissions are set correctly on the Physical Path folder
- Make sure the Application Pool is running under a user that has access to the Physical Path folder
## Setting MIME-Types
Evidence uses .arrow files to load data into the static site. IIS does not know these file-types so we need to make it aware of them.
1. Click on your website
2. In the main window click on "MIME Types"
3. In the Action pane on the right click "Add" and add the following "MIME types"
- Extension: .arrow
- MIME Type: application/vnd.apache.arrow.file
- Extension: .arrows (note the '*s*' at the end)
- MIME Type: application/vnd.apache.arrow.stream
## Start IIS
You should now be able to start IIS and browse to your website. You can update your site by copying the new build files to your website's Physical Path.
---
evidence/sites/docs/pages/deployment/self-host/gitlab-pages/index.md
---
---
sidebar_position: 4
title: GitLab Pages
description: Deploy Evidence to GitLab Pages from a GitLab repo. GitLab Pages can be private to your org, support custom domains, and GitLab CI/CD for data refresh.
og:
image: /img/deployment/deploy-gitlab-pages.png
---
[GitLab Pages](https://docs.gitlab.com/ee/user/project/pages) is a service that allows you to host static websites and single-page apps. Evidence apps can be deployed to GitLab Pages by pushing your Evidence project to a GitLab repository and enabling Pages for the repository.
## Prerequisites
- A [GitLab](https://gitlab.com) account
- An Evidence project pushed to a GitLab repository
## Deploy Evidence to GitLab Pages
1. In GitLab, navigate to your Evidence project repository.
1. Add credentials as environment variables
- Navigate to **Settings > CI/CD > Variables**
- Click **Add Variable**, and use **Masked** visibility
- Navigate to your Evidence project and go to the settings page and copy each of the environment variables keys and values
- Alternatively, you can find credentials in `connection.options.yaml` files in your `/sources/your_source` directory. The key format used should be `EVIDENCE_SOURCE__[your_source]__[option_name]` (Note the casing matches your source names, and the double underscores). Note that the values are base64 encoded, and will need to be decoded.
1. Return to your GitLab project, and select **Deploy > Pages** in the left sidebar.
1. Get started with GitLab Pages
- Build image: `node:22`
- The application files are in the `public` folder: `true` (we'll change this in Evidence later)
- Installation steps: `npm ci`
- Build steps:
- `npm run sources`
- `npm run build`
- `cp -r build public`
- Add a commit message, and click **Commit**
Your app will be available at `https://[your-repo]-[hexcode].gitlab.io/`. It will be only accessible to your account by default.
## Domains, Authentication and Scheduling
### Authentication
GitLab pages are only accessible to your account by default. To make it public, you can change the visibility at:
Settings > General > Visibility, project features and permissions > Pages
### Custom domains
You can add a custom domain by navigating to:
Settings > Pages > Domains > New domain
### Data refresh
You can add a pipeline schedule to refresh your data by navigating to:
Build > Pipeline schedule > Create a new pipeline schedule
---
evidence/sites/docs/pages/deployment/self-host/firebase/index.md
---
---
sidebar_position: 4
title: Firebase
description: Deploy Evidence to Firebase Hosting by linking to a Git repository. Hosting supports custom domains and GitHub Actions for data refresh.
og:
image: /img/deployment/deploy-firebase.png
---
[Firebase Hosting](https://firebase.google.com/products/hosting) is a GCP service that allows you to host static websites and single-page apps. Firebase Hosting can deploy Evidence apps by linking to a Git repository.
## Prerequisites
- A GCP account
- An Evidence project pushed to Git service like GitHub, GitLab, or Bitbucket.
## Deploy Evidence to Firebase
**Firebase CLI**
The Firebase CLI is somewhat buggy, so you sometimes need to try the commands multiple times for them to succeed.
1. From the Firebase console, click **Create a project**.
- Enter a project name, accept the terms of service, and click **Continue**.
- Choose whether to enable Google Analytics (not required), and click **Create project**.
1. In the terminal, install the Firebase CLI:
```bash
npm install -g firebase-tools
```
1. Log in to Firebase, and authenticate via the browser:
```bash
firebase login
```
1. Initialize Firebase Hosting in your project:
```bash
firebase init hosting
```
- Select `Use an existing project`
- Select a default Firebase project for this directory: Select project you created
- What do you want to use as your public directory? `build`
- Configure as a single-page app (rewrite all URLs to /index.html)? `No`
- (If asked) File build/index.html already exists. Overwrite? `No`
- Set up automatic builds and deploys with GitHub? `Yes`
- Select a GitHub repository to connect to this project: Type your repo name
- Set up the workflow to run a build script before every deploy? `Yes`
- What script should be run before every deploy? `npm ci && npm run sources && npm run build`
- Set up automatic deployment to your site's live channel when a PR is merged? `Yes`
- What is the name of the GitHub branch associated with your site's live channel? `main`
1. Add secrets to your GitHub repo: Settings > Secrets and variables > Actions
- With your Evidence dev server running, go to the settings page and copy each of the environment variables
- Alternatively, you can find credentials in `connection.options.yaml` files in your `/sources/your_source` directory. The key format used should be `EVIDENCE_SOURCE__[your_source]__[option_name]` (Note the casing matches your source names, and the double underscores). Note that the values are base64 encoded, and will need to be decoded.
- Add each of them as secrets to your GitHub repo
1. Build your app locally (if you haven't already):
```bash
npm i && npm run sources && npm run build
```
1. Deploy your app for the first time
```bash
firebase deploy --only hosting
```
1. Edit `firebase-hosting-merge.yml` and `firebase-hosting-pull-request.yml` to add your environment variables as GitHub secrets (note that GitHub capitalizes the names of secrets)
```yaml
- run: npm ci && npm run sources && npm run build
env:
EVIDENCE_SOURCE__my_source__username: ${{ secrets.EVIDENCE_SOURCE__MY_SOURCE__USERNAME }}
EVIDENCE_SOURCE__my_source__private_key: ${{ secrets.EVIDENCE_SOURCE__MY_SOURCE__PRIVATE_KEY }}
```
1. Commit and push these newly created files: `firebase.json`, `.firebaserc`,`firebase-hosting-merge.yml`, `firebase-hosting-pull-request.yml`.
1. Update your GitHub workflow settings to allow Workflows to Read and write permissions. This is required for the Pull Request preview GitHub Action to work. [your repo] > Settings > Actions > General > Workflow permissions
Your app should now be live on Firebase Hosting at `https://.web.app`.
## Domains, Authentication and Scheduling
### Authentication
Firebase Authentication is _not_ a suitable authentication for static apps on Firebase Hosting.
### Custom domains
You can set up a custom domain on Firebase Hosting.
[Firebase dashboard](https://console.firebase.google.com/u/0/) > [your project] > Hosting (in the left sidebar) > Domains > Add custom domain
### Data refresh
To adjust your deployment schedule, modify the workflow file in your repository, adding a `schedule` trigger.
```yaml
on:
schedule:
- cron: '0 0 * * *' # This is midnight every day
```
---
evidence/sites/docs/pages/deployment/configuration/index.md
---
---
title: Configuration
sidebar_position: 99
sidebar_link: false
---
---
evidence/sites/docs/pages/deployment/configuration/environments/index.md
---
---
sidebar_position: 7
hide_table_of_contents: false
title: Environments
description: Configure multiple environments for developing and testing your app, using different database credentials if needed.
---
## What are environments?
In software engineering, _environments_ are used to develop and test code without impacting end users.
> “Production” (prod) refers to the environment that end users interact with, while “development” (dev) is the environment engineers write code in. This allows engineers to work iteratively when writing and testing new code in development, and once they are confident in these changes, deploy their code to production.
Data warehouses often also use separate environments – the _production_ environment refers to the data end users can access.
## Typical data environment configurations
There are three typical ways that data teams separate their data environments:
1. **Separate databases** _(Bigquery - projects)_: Each environment has its own database, but with the same schemas and tables in each database. This is the most common way to separate environments.
2. **Separate schemas** _(Bigquery - datasets)_: Each environment has its own schema, with schemas hosted on the same database.
3. **Separate accounts** _(Bigquery - clusters/instances/organizations)_: Each environment has its own account. This is less common.
## Setting up Evidence to use different environments
You can configure both your dev and prod environments using [environment variables](/reference/cli#environment-variables). Using `.env` files at the project root is supported.
### Dev environment
Add your dev database credentials for your dev environment via the **settings page**. If you are running Evidence locally, typically at [http://localhost:3000/settings](http://localhost:3000/settings).
### Prod environment
Add your prod database credentials as environment variables. The specific instructions depend on how you are deploying Evidence. Instructions can be be found in the deployment section of the settings page of your app running locally.
If you are using separate schemas, you will need to add the optional `schema` parameter to your credentials in dev, and an environment variable in prod. This is only currently supported for Postgres.
---
evidence/sites/docs/pages/deployment/configuration/rendering-modes/index.md
---
---
sidebar_position: 5
hide_table_of_contents: false
title: Rendering Modes
description: Evidence supports rendering using Static Site Generation (Default) or Single Page App (SPA) mode.
---
Evidence supports two rendering modes:
1. Static Site Generation (Default)
2. Single Page App (SPA)
```sql rendering_modes
select 'Content Rendering' as rendering_mode, 'Pre-rendered at build time' as static_site_generation, 'Rendered on the client side' as single_page_app, 1 as row_number union all
select 'Page Generation', 'Each page generated ahead of time', 'Only one HTML file generated', 2 union all
select 'Built Output', 'All pages have corresponding HTML files', 'Pages rendered on the fly using JavaScript', 3 union all
select 'Build Duration', 'Slower due to building all pages', 'Fast as only one page is built', 4 union all
select 'Performance', 'Fast page loads', 'Slower page loads', 5 union all
select 'SEO', 'Rich SEO for all pages', 'Generic SEO for your whole app', 6
order by row_number
```
## Choosing a Rendering Mode
You should generally only use the SPA rendering mode if one of the following is true:
- **You have a large number of pages**, >1000+ is a good rule of thumb
- **You want to update your data frequently**, so short build times are desirable
- **Your data sources are large**
## Comparison
## Enabling SPA Mode
SPA rendering mode is disabled by default.
To enable SPA rendering mode:
1. Update the build and preview scripts in `package.json`:
```json
"build": "VITE_EVIDENCE_SPA=true evidence build",
"preview": "VITE_EVIDENCE_SPA=true evidence preview",
```
2. Add svelte adapter-static as a dev dependency:
```bash
npm install --save-dev @sveltejs/adapter-static
```
3. Add a `svelte.config.js` file to the root of your project containing the following:
```javascript
import adapter from '@sveltejs/adapter-static';
/** @type {import("@sveltejs/kit").Config} */
export default {
kit: {
adapter: adapter({
fallback: 'index.html'
})
},
};
```
4. If self-hosting an SPA it is important to redirect all URLs to index.html. For example in an NGINX server block you would put:
```code
root /path/to/your/project/build/;
location / {
try_files $uri $uri/ $uri.html /index.html;
}
```
---
evidence/sites/docs/pages/deployment/configuration/base-paths/index.md
---
---
title: Base Paths
sidebar_position: 6
description: Evidence supports serving your app from a subdirectory, for example https://acme.com/analytics.
---
Evidence supports serving your app from a subdirectory. For example, you can serve your app from `https://acme.com/analytics`.
This can be useful for embedded reporting, where you want to use the root domain for your main app and serve Evidence reports from a subdirectory.
## Configuring the Base Path
Add the following to `evidence.config.yaml` at the project root:
```yaml
deployment:
basePath: /my-base-path
```
**All links in your markdown files will be automatically adjusted** to include the base path.
The base path must:
- Start with a `/`
- **Not** end with a `/`
- Be a valid URL path
Your `pages/index.md` file will be served from `https://my-domain.com/my-base-path`, and other pages will be served relative to this path.
## Configuring the Build Directory in `package.json`
Evidence builds your app to the `build` directory, rather than to `build/my-base-path`.
To modify the build directory, set the `EVIDENCE_BUILD_DIR` environment variable in `package.json`
```json
"build": "EVIDENCE_BUILD_DIR=./build/my-base-path evidence build"
```
This is required to use the `npm run preview` command, or else the preview will not run correctly.
## Custom Components
[Custom components](/components/custom/custom-component) links are **not automatically adjusted** to include the base path. Links should be adjusted using the `addBasePath` utility function, which adjusts relative links to include the base path.
For example:
`CustomLink.svelte`:
```svelte
<script>
export let link;
import { addBasePath } from '@evidence-dev/sdk/utils/svelte';
</script>
My Component
```
---
evidence/sites/docs/pages/deployment/overview/index.md
---
---
sidebar_position: 1
hide_table_of_contents: false
title: Overview
hide_title: true
description: Evidence is a static site generator, so can be deployed to any static site host.
---
# Deployment Overview
In production, Evidence generates [static sites](https://www.netlify.com/blog/2020/04/14/what-is-a-static-site-generator-and-3-ways-to-find-the-best-one) by default. This means it doesn't run queries against your database when someone visits your site, but queries and pre-builds all pages as HTML beforehand.
Static sites are very versatile, and so you can host your Evidence app using cloud services like AWS, Azure, Netlify or Vercel, or your own infrastructure.
You can also configure Evidence as a [Single Page App (SPA)](/deployment/configuration/rendering-modes). In SPA mode Evidence will not pre-build all the pages in your application. This can be preferrable if your app has many pages (>1,000) causing long build times.
## Self-host
You can self-host Evidence anywhere suitable for hosting static sites. See guides for:
- [AWS Amplify](/deployment/self-host/aws-amplify)
- [Azure Static Apps](/deployment/self-host/azure-static-apps)
- [Cloudflare Pages](/deployment/self-host/cloudflare-pages)
- [Firebase](/deployment/self-host/firebase)
- [GitHub Pages](/deployment/self-host/github-pages)
- [GitLab Pages](/deployment/self-host/gitlab-pages)
- [Hugging Face Spaces](/deployment/self-host/hugging-face-spaces)
- [Netlify](/deployment/self-host/netlify)
- [Vercel](/deployment/self-host/vercel)
- [Windows IIS](/deployment/self-host/windows-iis)
## Build Process
Evidence doesn't run new queries each time someone visits one of your reports.
Instead, Evidence runs your queries once, at build time, and statically generates _all_ of the pages in your app. This includes all possible permutations of any paramaterized pages.
You can schedule (or trigger) regular builds of your site to keep it up-to-date with your data warehouse.
This has two benefits for you and your users:
1. If something goes wrong with your SQL, Evidence just stops building your app, and continues to serve older results.
2. Your site will be exceptionally fast. Under most conditions, pages will load in milliseconds.
## Build Commands
Ensure that your build environment aligns with the [system requirements](/guides/system-requirements)
### Build
The command `npm run build` will build a static version of your reports and place them in the `build` directory.
### Build:Strict
The command `npm run build:strict` is a much less permissive build command. Use this to ensure you never deploy a broken report.
This command will fail if:
- **Any SQL query fails.** A successful query returning no rows is _not_ a failure
- **Any component renders an error state.** A component passed a valid query returning no rows _will_ fail - you can avoid this with an [`{#if}` statement](/core-concepts/if-else) if needed.
## Storing Credentials
In production, Evidence expects to find your database credentials in **environment variables**.
To find the environment variables that you'll need to set for your app:
1. Run your app in development mode
1. Visit the [settings page](http://localhost:3000/settings)
1. Open the deployment panel, and select your deployment target
For details on how to use different data for different environments, see [Environments](/deployment/configuration/environments).
---
evidence/sites/docs/pages/plugins/index.md
---
---
title: Plugins
sidebar_position: 4
sidebar_link: false
---
---
evidence/sites/docs/pages/plugins/create-source-plugin/index.md
---
---
title: Create Data Source Plugin
description: How to create a data source plugin for Evidence
sidebar_position: 4
---
To see a working example of a data source plugin, the [Evidence postgres source plugin](https://github.com/evidence-dev/evidence/tree/main/packages/datasources/postgres) is a good
reference.
## Get started
To get started, go to [the data source template repo](https://github.com/evidence-dev/datasource-template) and click to "Use This Template". Then, follow the directions in the `README` in that repo.
## Options Specification
Evidence Datasources must provide an `options` export; this is used to
build UI and validation to ensure an excellent UX for Evidence users.
Options can have the following fields:
Name or Title of the option
Control to show
Secret values are placed in `connection.options.yaml`, which is not source controlled
Displays value in UI elements (e.g. for usernames, that should not be source controlled but are not 'secret'. Otherwise the field will display as ∙∙∙)
Disables saving a field, useful for credential files
Indicates that the field should get its value from another field if it is available, useful for credential files. Formatted as a [json path](https://www.npmjs.com/package/@astronautlabs/jsonpath)
If true, the input is disabled and the value can only come from a reference
If `type` is `file`, set how it should be parsed. It will then be available to `references`
Description of the option, shown as a hint in UI
See [children](#children)
Indicates that the user must provide this option
Available options for `select` type
Determines behavior of `children`
Default Value
### Children
Many datasources have variable configuration (e.g. if ssl is enabled for postgres, then an ssl mode can be selected), and Evidence
options support this workflow.
Consider this partial postgres ssl option:
```javascript
ssl: {
type: 'boolean',
// ...
nest: true,
children: {
[true]: {
sslmode: {
// ...
}
}
}
},
```
`ssl.children` is a record of possible values to an additional set of options that are exposed then the values match.
In this example, the `sslmode` option is only displayed when `ssl` is true.
The resulting type of this option is:
```typescript
{ ssl: false } | { ssl: { sslmode: string } }
```
In cases where you want a flat object, rather than a nested object; set `nest` to false.
This would produce
```typescript
{ ssl: false } | { ssl: true, sslmode: string }
```
## Promoting Your Plugin
If you are building a plugin for other Evidence users, [let us know in Slack](https://slack.evidence.dev) and we can share it with the community.
---
evidence/sites/docs/pages/plugins/component-plugins/index.md
---
---
sidebar_position: 1
hide_table_of_contents: false
title: Component Plugins
description: Evidence includes a plugin system which can be used to add components and data sources to your app.
---
Evidence includes a plugin system which can be used to add components and data sources to your app.
All Evidence projects include the Evidence `core-components` plugin by default. `core-components` has everything you need to build most use cases.
Component plugins are Svelte component packages which include one or more additional components which you can use in your markdown. Once you have installed and registered a component plugin, the included components will be available to use in your markdown files.
To use a plugin, you need to **install** and **register** it in your project.
## Installing Component Plugins
```bash
npm install @acme/charting
```
## Registering Component Plugins
Once the plugin is installed, add it to `evidence.config.yaml` to register it in your project.
```yaml
plugins:
components:
@evidence-dev/core-components: {}
@acme/charting: {}
```
### Component Aliases
If a plugin provides a component that you want to reference with another name, you can set up `aliases` when registering the component.
In this example, the `@acme/charting` plugin provides some component `LongNameForAChart`. After setting up `aliases`, it will be made available in the Evidence markdown as `AcmeChart`
```yaml
components:
@acme/charting:
aliases:
LongNameForAChart: AcmeChart
```
### Component Overrides
Component plugins have the ability to override components from other plugins (e.g. you want to replace the built-in `LineChart` with a chart from a plugin).
Overrides are specified in an `overrides` list. In the example below, Evidence's built-in `LineChart` will be overridden by the `LineChart` component from the `@acme/charting` plugin:
```yaml
components:
@evidence-dev/core-components: {}
@acme/charting:
overrides:
- LineChart
```
If you want to replace `LineChart` with a component named `CustomLineChart`, apply an alias to `CustomLineChart` first:
```yaml
components:
@evidence-dev/core-components: {}
@acme/charting:
aliases:
CustomLineChart: LineChart # Rename CustomLineChart
overrides:
- LineChart # Override LineChart with the now renamed CustomLineChart
```
### (Advanced) Using generic Svelte component libraries
If you want to use a Svelte component library that is _not_ an Evidence component plugin, you can use the `provides` field to
manually document the components that the library provides.
```yaml
components:
@evidence-dev/core-components: {}
carbon-components-svelte:
provides:
- Button
- CodeSnippet
```
The components provided **must** be named exports, e.g. `import {ComponentName} from 'package';`, _not_ `import ComponentName from 'package/ComponentName.svelte;`.
---
evidence/sites/docs/pages/plugins/source-plugins/index.md
---
---
sidebar_position: 2
hide_table_of_contents: false
title: Data Source Plugins
description: Source plugins enable you to add new data source types to your app.
---
Evidence includes a plugin system which can be used to add components and data sources to your app.
Source plugins enable you to add new data source types to your app. Once you have installed and registered a source plugin, you will be able to configure any associated connection settings in the settings UI.
To use a plugin, you need to **install** and **register** it in your project.
## Installing Source Plugins
```bash
npm install @cool-new-db/evidence-source-plugin
```
## Registering Source Plugins
Once the plugin is installed, add it to `evidence.config.yaml` to register it in your project.
```yaml
plugins:
components:
@evidence-dev/core-components: {}
datasources:
@cool-new-db/evidence-source-plugin
```
## Configuring Source Plugins
Restart the development server after installing and registering the plugin, then visit `localhost:3000/settings`.
---
evidence/sites/docs/pages/plugins/create-component-plugin/index.md
---
---
title: Create Component Plugin
description: You can create a component plugin to publish your own custom components for use across multiple Evidence apps.
sidebar_position: 3
---
You can build a component plugin to publish your own custom components, or to make existing open source component libraries easily available for Evidence users.
Evidence Labs is deprecated and should not be used as a plugin in your Evidence app. This section of the documentation will be updated in the future.
An example component library [Evidence Labs](https://github.com/evidence-dev/labs) is available on GitHub, with a live demo of the components [here](https://labs.evidence.dev).
## Basic Steps
1. Clone the [Evidence Labs example repo](https://github.com/evidence-dev/labs)
2. Add your components to the `src/lib` directory in place of the existing components
3. Add pages in the `pages` directory to show your components, in place of the existing pages
4. Set up component exporting (see section below)
5. Test that your components work by running the dev server with `npm run dev` and inspecting the pages you created
6. Edit the name in `package.json` from `@evidence-dev/labs` to `your-plugin-name` and set the version to `0.0.1`
7. Publish to npm with `npm publish` (You will need to be logged in to an [npm](https://www.npmjs.com/signup) account)
8. Install your plugin by following [the steps here](/plugins/component-plugins)
9. Make changes to your plugin and republish with `npm publish` - *note that you need to bump the version number in `package.json` each time you do this*
## Component Exporting
Plugins must "export" their components to make them available to your Evidence apps.
There are two ways to set up component exporting in your plugin:
1. [Module Exports](#module-exports) (recommended)
2. [Manifest](#manifest) - this method can be used in cases when a large component library already exists
*Note that these are mutually exclusive, and the manifest takes priority.*
### Module Exports
When writing a plugin from scratch, this is the preferred method.
#### Steps
1. Add the following to each component in your plugin to "flag" the component as something that should be imported as part of the plugin (at the top of the component's `.svelte` file)
```html title="ComponentOne.svelte"
<script context="module">
export const evidenceInclude = true;
</script>
```
2. Add an `index.js` file to the `src/lib` directory
3. Add one line to `index.js` per component in your plugin. This will export the components, making them available in Evidence:
```javascript title="index.js"
export {default as ComponentOne} from "./ComponentOne";
export {default as ComponentTwo} from "./ComponentTwo";
```
### Manifest
If you would prefer not to flag each individual component file, another approach is to maintain an `evidence.manifest.yaml` file. The structure of the file is a single array of component names.
#### Steps
1. Add an `evidence.manifest.yaml` to your `src/lib` directory
2. Add a line to the file for each component in your plugin:
```yaml title="evidence.manifest.yaml"
components:
- ComponentOne
- ComponentTwo
```
3. Add an `index.js` file to the `src/lib` directory
4. Add one line to `index.js` per component in your plugin. This will export the components, making them available in Evidence:
```javascript title="index.js"
export {default as ComponentOne} from "./ComponentOne";
export {default as ComponentTwo} from "./ComponentTwo";
```
## Promoting Your Plugin
If you are building a plugin for other Evidence users, [let us know in Slack](https://slack.evidence.dev) and we can share it with the community.
---
evidence/sites/docs/pages/[...route]/og.png/+server.js
---
import {html as toReactNode} from 'satori-html';
import SocialCard from '$lib/SocialCard.svelte';
export const prerender = true;
import fs from 'fs';
import path from 'path';
import satori from 'satori';
import {Resvg} from '@resvg/resvg-js';
const fontDataTight = fs.readFileSync(path.join(process.cwd(), 'src/components', 'InterTight-SemiBold.ttf'));
const fontData = fs.readFileSync(path.join(process.cwd(), 'src/components', 'Inter_24pt-Regular.ttf'));
const fontDataMono = fs.readFileSync(path.join(process.cwd(), 'src/components', 'GT-America-Mono-Regular.otf'));
const height = 630;
const width = 1200;
/** @type {import('./$types').RequestHandler} */
export const GET = async ({url, fetch}) => {
// Fetch the pages manifest
const manifestRes = await fetch('/api/pagesManifest.json');
let tree = await manifestRes.json();
let parent = undefined;
// Get the frontmatter for the route by getting the route recursively using split('/') (trimming the /og.png)
const route = url.pathname.replace('/og.png', '');
let frontMatter = undefined;
for (const part of route.split('/').slice(1)) {
parent = tree;
tree = tree.children[part];
frontMatter = tree.frontMatter;
}
const title = frontMatter?.title || undefined;
const description = frontMatter?.description || undefined;
const category = parent?.frontMatter?.title || undefined;
const result = SocialCard.render({title, description, category});
const element = toReactNode(`${result.html}`);
const svg = await satori(element, {
height,
width,
fonts: [
{
name: 'Inter',
data: await fontData,
style: 'normal'
},
{
name: 'InterTight',
data: await fontDataTight,
style: 'normal'
},
{
name: 'GTAmericaMono',
data: await fontDataMono,
style: 'normal'
},
]
});
const resvg = new Resvg(svg, {
fitTo: {
mode: 'width',
value: width
}
});
const image = resvg.render();
const imageBuffer = await image.asPng();
return new Response(imageBuffer, {
headers: {
'Content-Type': 'image/png'
}
});
};
---