---
evidence/sites/docs/pages/index.md
---
---
sidebar_position: 1
title: What is Evidence? | Evidence Docs
description: Evidence is an open source framework for building data products with SQL - things like reports, decision-support tools, and customer-facing/embedded reporting. It's a code-driven alternative to drag-and-drop BI tools.
hide_title: true
og:
image: /img/how-it-works.png
---
# What is Evidence?
Evidence is an open source framework for building data products with SQL - things like reports, decision-support tools, and embedded dashboards. It's a code-driven alternative to drag-and-drop BI tools.
This docs site is an Evidence app.
Install Evidence with the [VSCode Extension](vscode:extension/Evidence.evidence-vscode), or see other [installation options](/install-evidence).
## How does Evidence work?
Evidence renders a BI website from markdown files:
1. [Data sources](/core-concepts/data-sources) can include data warehouses, flat files and non-SQL data sources
1. [SQL statements](/core-concepts/queries) inside markdown files run queries against data sources
1. [Charts and components](/core-concepts/components) are rendered using these query results
1. [Templated pages](/core-concepts/templated-pages) generate many pages from a single markdown template
1. [Loops](/core-concepts/loops) and [If / Else](/core-concepts/if-else) statements allow control of what is displayed to users
## Pre-requisites
To use Evidence you need to know SQL. A knowledge of [basic markdown syntax](/reference/markdown) is also helpful.
## Getting help
If you're trying out Evidence, and need some support we'd love to hear from you.
- Message us on Slack
- Open an issue on Github
- See all the charts and components.
If there's **anything** you find difficult in the docs, please [open an issue](https://github.com/evidence-dev/evidence/issues/new/choose) or reach out to us on Slack.
---
evidence/sites/docs/pages/guides/index.md
---
---
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/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
![chart-elements-one](/img/chart-elements-one.png)
#### Horizontal Chart (`swapXY=true`)
![chart-elements-two](/img/chart-elements-two.png)
---
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/guides/usql-migration-guide/index.md
---
---
title: Universal SQL Migration Guide
sidebar_position: 3
description: Migrate your < v24 Evidence app to Universal SQL (v24+)
---
Universal SQL is Evidence's latest release, and fundamentally changes how Evidence queries data in order to bring support for three big new features:
1. **Multiple Data Sources:** Combine data from multiple databases, flat files like CSVs, and even non-SQL data sources like Google Sheets - and query them all with SQL
2. **Inputs and Filters:** Use input components to dynamically update your queries and charts based on user input. Filter data using parameterized queries rather than Javascript filter syntax
3. **Adapter Plugins:** Create your own adapter to enable connecting to any data source
This is a big release and contains several breaking changes. This guide will help you migrate your existing apps to USQL.
The following sections explain what is changing in Evidence with Universal SQL. To jump straight to the migration steps, [click here](#migration-steps).
## Do I need to migrate my app?
- If your `@evidence-dev/evidence` package version is `< v24` then it has not yet been migrated, and we encourage you to do so as soon as is practical
- `v23` will continue to be supported for now (sunset date TBC) and will receive critical bugfixes during this period
- If you're unsure what you need to do, or if you need help, [reach out to us on Slack](https://slack.evidence.dev) in the `#migration` channel
## Breaking Changes
- Existing data source connections will need to be reconfigured
- Queries to your data source will need to be moved to the new `sources` directory (details below)
- Queries in markdown files and in the `queries` directory are now written in DuckDB SQL
- Deprecated syntax:
- `{data.my_query}`. Use `{my_query}` instead
- Declaring variables from queries in `<script>` tags using `let my_var = ` or `var my_var = `. Use `$: my_var` instead
## How Universal SQL Works
- Universal SQL introduces a new data loading step (called `run sources`) - you write queries against multiple data sources, and Evidence will combine them all into the same format so you can query across them using SQL
- Once your sources are loaded, they can be queried using DuckDB SQL syntax, either directly on your markdown page, or by writing a `.sql` file in your `queries` directory and referencing it in the frontmatter of your markdown file
- These DuckDB SQL queries run in your browser and can be changed on the fly by interactive user input (e.g., filters, dropdowns) using parameterized queries (e.g., `where customer_id = '${inputs.customer}'`)
## Change to Project Structure
To support multiple data sources, USQL introduces a new `sources` directory, which contains one folder per data source. Each data source folder includes connection configuration files (defined in YAML, but configurable via the settings UI of your project in your browser).
If you already have a `sources` directory in your project (e.g., for `.sql` files or `.csv` files), it will need to be renamed to `queries`. This functions in the same way as before, but the `.sql` files use DuckDB SQL syntax and the queries run in the browser rather than during the build step.
Queries in your markdown files will use DuckDB SQL syntax and will also run in the browser.
#### Pre-USQL Basic Project Structure
```bash
+-- .evidence
+-- pages/
| `-- index.md
+-- sources/
| `-- a_query.sql
| `-- another_query.sql
```
#### USQL Basic Project Structure
```bash
+-- .evidence
+-- pages/
| `-- index.md
+-- queries/
| `-- a_query.sql
| `-- another_query.sql
+-- sources/
| `-- my_source/
| `-- connection.yaml
| `-- connection.options.yaml
| `-- source_query.sql
```
Optional folders for `components`, `static`, and `partials` still work as they did before.
## Overview of Changes you will need to make
**Recommendations**
We recommend creating a backup of your project before starting the migration.
- Use new template project scaffold
- Migrate queries to new project folder structure
- Update on-page queries to use DuckDB syntax
- (Suggested) Refactor `.filter()` statements to take advantage of SQL-based filtering
- (If necessary) Update deprecated syntax
- (If necessary) Reinstall any custom plugins
- (If necessary) Reinstall any custom external dependencies (non-evidence libraries)
- (If necessary) Update `.gitignore` to include `**/connection.options.yaml` - only needed if you do not start from a fresh Universal SQL template
## Migration Steps
**VS Code Migration Command**
We have created a VSCode extension command to assist with migration. This will aid significantly with the migration process. Steps for VS Code are shown here. If you prefer to complete the steps manually, see the next section below.
### Using the VS Code Migration Command
This migration command covers most situations, but there may be edge cases where you will need to make adjustments or fix query syntax.
**Troubleshooting**
Issues and errors in the migration command can be related to npm or NodeJS versions - if in doubt, update to the latest LTS versions (see [system requirements](/guides/system-requirements))
1. Ensure you have the Evidence VS Code extension version `1.4.1` or higher installed
2. Open the Evidence project you want to migrate. If your project is within a monorepo, for this migration open only the Evidence project folder as the "workspace" in VS Code - otherwise the migration command will not be able to run
3. Open the command palette (`Cmd`/`Ctrl` + `Shift` + `P`)
4. Type `Evidence: Migrate Project to USQL` and select that command
5. Follow the prompts in VS Code. You will be asked to provide a name for your data source. This will appear as a folder within the `sources` directory in your project (e.g., you could use `needful_things` if using the Evidence demo database)
6. The command should run quickly - no more than a few minutes. If it's taking longer, try cancelling and starting again or [reach out on Slack in the #migration channel for assistance](https://slack.evidence.dev). When the command has finished running, you will have a migrated project.
7. Click `Start Evidence` to run the server, or use the commands below:
```shell
npm install
npm run sources
npm run dev
```
**Notes:**
- `npm run sources` is a new step introduced by USQL. This step runs the queries against your data sources and loads the data into Evidence
- It is normal to see errors in your terminal at this stage - you need to configure your data source to avoid these (see next step)
8. Configure your data source in the Settings menu
- In your browser, click the 3-dot menu at the top right of the page and click Settings
- In the Data Sources section, click to add a new connection
- Select the data source type your app uses and provide the name you set when going through the VS Code prompts earlier (e.g., `needful_things` to continue the example from above)
- Click to test your connection
- Click to confirm the changes
9. Navigate back to the home page in your browser and refresh the page
10. The page should now be working. The migration command covers most situations, but not all - you may need to fix a few remaining issues. If you still see errors, they may be related to query chaining or SQL syntax. See the Special Situations section below for information which may help. If you need assistance tracking down the issues, please [reach out on Slack](https://slack.evidence.dev) in the `#migration` channel
### Completing the Migration Steps Manually
The easiest way to migrate your app is to create a app using the latest version of the template, and copy over your markdown pages and queries. These steps will guide you through doing that in the same project so that you can track the changes in version control.
1. In your Evidence project directory, create a new folder called `_legacy_project`
2. Copy all of the files from your existing project into the `_legacy_project` folder - this will serve as a backup, and you will need to reference these in the following steps to copy content back into your project
3. Create another folder called `temporary`
4. Scaffold a new project into this `temporary` folder using the latest version of the template
- CLI: `npx degit evidence-dev/template temporary`
- This step is required because `degit` only works in an empty folder
- After this step, you should have a new evidence project in your `temporary` directory
5. Move all of the files from this `temporary` folder into the root of your project. Then delete the `temporary` folder
- Now you should have a `_legacy_project` folder and a new Evidence project in the same workspace
6. Set up your new `sources` directory
- In the new `sources` folder, delete any demo data folders so that the folder is empty - you won't need any of those
- Create a new folder in your `sources/` directory, with a name for your existing data source (e.g., `sources/my-data-source/`)
7. Copy files from `_legacy_project` into your new project. Make sure to **copy** rather than **move** the files. If the folder already exists in the new project, replace the contents with the contents from `_legacy_project`:
- Folders to copy from `_legacy_project` to your new project
- `pages/` -> `pages/`
- `components/` -> `components/`
- `partials/` -> `partials/`
- `static/` -> `static/`
- `sources` folder
- If `_legacy_project` has a `sources` directory, copy the contents of that folder into the `sources/my-data-source` folder in your new project
- Files in the root of `_legacy_project`
- Any data files in the root of your old project should be copied into your `sources/my-data-source` folder. This includes files with these extensions:
- `.duckdb`
- `.db`
- `.sqlite`
- `.sqlite3`
- `.csv`
- `.parquet`
6. Set up your `queries` directory
- If a `queries` directory does not exist in your new project, create that folder now (in the root of your project)
- If you don't have any `.sql` files in your `sources/my-data-source` directory, you can move to the next step and leave the `queries` folder empty
- For each `.sql` file in your `sources/my-data-source` directory, create a file in `queries` with the same name (e.g., `sources/my-data-source/my-query.sql` --> `queries/my-query.sql`)
- Write this query into each `.sql` file you created in `queries`: `select * from [my-data-source].[my-query]`
8. Migrate queries in your markdown files
- Changes to make in each markdown file:
- If you have frontmatter that references `sources`, change the name from `sources` to `queries`
- For each inline query in the file:
- Create a `.sql` file in your data source folder using the same name as the query (e.g., `sources/my-data-source/my-query.sql`) and paste in the contents of the query
- In your markdown file, replace the contents of the query with `select * from [my-data-source].[my-query]`
- If your query is a chained query, check that the reference will still work, and adjust as necessary
- If you run into duplicate query names across pages, you will need to create unique names and ensure they are referenced correctly on your markdown page
9. Update templated page syntax
- On each templated page, you can replace `$page.params.my_param` with `params.my_param`
- The old reference will continue to work but will be phased out in the future in favour of this simpler syntax
10. Run the commands below:
```shell
npm install
npm run sources
npm run dev
```
**Notes:**
- `npm run sources` is a new step introduced by USQL. This step runs the queries against your data sources
- It is normal to see errors in your terminal at this stage - you need to configure your data source to avoid these (see next step)
11. Configure your data source in the Settings menu
- Click the 3-dot menu at the top right of the page and click Settings
- In the Data Sources section, click to add a new connection
- Select the data source type your app uses and provide a name for your data source. This will appear as a folder within the `sources` directory in your project (e.g., you could use `needful_things` if using the Evidence demo database)
- Click to test your connection
- Click to confirm the changes
12. Navigate back to the home page in your browser and refresh the page
13. The page should now be working. If you still see errors, they may be related to query chaining or SQL syntax. See the Special Situations section below for information which may help. If you need assistance tracking down the issues, please [reach out on Slack](https://slack.evidence.dev) in the `#migration` channel
## Deployment Changes
### Evidence Cloud
1. Copy environment variables for your app from your local dev environment (Settings page > Deployment)
![env vars](/img/settings-vars.png)
2. Update the environment variables for your Evidence Cloud app by pasting the environment variables from Step 1
![cloud vars](/img/cloud-settings-edit.png)
3. Click to redeploy your app
### Self-Hosting
You will need to update 2 things in your deployment setup to complete the migration to USQL:
1. Update your environment variables
- See links in the Resources section for Netlify and Vercel docs
- Find the new environment variables in your app's settings menu in your browser (click 3-dot menu at top right > Settings) - then scroll down to Deployment and select your deployment provider
- Copy your variables and change them in the configuration for your deployment provider
2. Update the build command
- USQL introduces the new `run sources` step to load data into your app from your data sources
- Replace the build command in your deployment provider to `npm run sources && npm run build:strict`
- See Netlify and Vercel docs in the Resources section
## Special Situations to Migrate
### Script Tags & Javascript References
If you use a script tag on a markdown page, you will need to change any variable declarations of of `let` or `var` to `$:`.
The reason for this change relates to how the new query engine updates query results - because queries run in the browser and can change based on input, you need to use a reactive variable declaration (that's what `$:` means), which can update itself when the data is instantiated, and when it changes.
The good news is that most of what you currently include in a script tag should be able to be migrated to USQL by using parameterized SQL queries.
For example:
#### Before - Using `let`
```html
<script>
let filtered_data = my_query.filter(d => d.column === $page.params.my_variable);
</script>
```
#### After - Using `$:`
```html
<script>
$: filtered_data = my_query.filter(d => d.column === $page.params.my_variable);
</script>
```
#### Ideal - Refactor to SQL Query in USQL
````html
```filtered_data
select * from my_table
where column = '${params.my_variable}'
```
````
### Query Chaining
Our migration steps do not take into account query chaining. In some cases, chained queries will continue to work as normal. In other cases, you will need to make adjustments.
Query chaining is not supported in the `sources` directory, but is still supported in `queries` and on your markdown pages.
This means that any query chains included in `sources` will need to be replaced with actual references to the tables you need.
If you use the VS Code migration command, chained queries found on markdown pages are left on the page rather than being moved to the `sources` directory like other queries. This is because we assume that most chained queries are simple enough for the syntax of your source database to match with the DuckDB syntax they will need to move to. In some cases, the syntax will not line up and you will need to make an adjustment.
### Evidence Plugins
If your app includes an Evidence plugin (e.g., [Evidence Labs](https://labs.evidence.dev)):
1. Find the `evidence.plugins.yaml` file in your `_legacy_project` folder and copy the line(s) containing the plugin(s) you're using
2. Paste those lines into the `evidence.plugins.yaml` file in your new project
3. Install the plugin(s) in your project. E.g.,:
```shell
npm install --save @evidence-dev/labs
```
### External Package Dependencies
If your project includes external packages installed via npm, you will need to reinstall those packages so that they are reflected in your `package.json`
```bash
npm install
```
## Common Syntax Change Examples
- In DuckDB, double quotes are used to reference columns. If you have double quotes in your queries for strings, you will need to change to single quotes
- `date_trunc` - in DuckDB, the date part is the first argument to the function and is passed as a string, whereas in some other dialects it is the second argument and is passed as a keyword
- `safe_divide` - in DuckDB you can use `number / nullif(other_number, 0) as divided_number` rather than `safe_divide(number, other_number)`
- You may need to change how you cast columns to other types. In DuckDB, you can use the `::type` syntax like so: `select order_time::date as order_date`
## Resources
- [#migration Slack channel](https://slack.evidence.dev)
- [DuckDB SQL Syntax Reference](https://duckdb.org/docs/sql/statements/select)
- [Netlify: Modify Environment Variables](https://docs.netlify.com/environment-variables/get-started/#modify-and-delete-environment-variables)
- [Netlify: Set your Build Command](https://docs.netlify.com/configure-builds/overview/#set-the-build-command)
- [Vercel: Environment Variables](https://vercel.com/docs/projects/environment-variables)
- [Vercel: Build Configurations](https://vercel.com/docs/deployments/configure-a-build)
---
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/components/index.md
---
---
title: "Components"
sidebar_position: 2
sidebar_link: false
---
---
evidence/sites/docs/pages/components/value/index.md
---
---
title: Value
sidebar_position: 1
---
The Value component accepts a query and displays a formatted value inline in text.
By default, `Value` will display the value from the first row of the first column of the referenced data.
```markdown
```
## Specifying Rows and Columns
Optionally supply a `column` and/or a `row` argument to display other values from `data`.
**Row Index**
`row` is zero-indexed, so `row=0` displays the first row.
```markdown
```
## Example
**Markdown:**
```markdown
The most recent month of data began ,
when there were orders.
```
**Results:**
![summary-sentence](/img/tutorial-img/needful-things-value-in-text-nowindow.png)
## Adding a Placeholder
Override errors with the optional `placeholder` argument. This is useful for drafting reports _before_ writing your queries.
```markdown
```
Sales in the last fiscal year were , a change of vs. the prior year.
## Formatting Values
Evidence supports a variety of formats - see [value formatting](/core-concepts/formatting) and the `fmt` prop below for more info.
## Aggregated Values
Values support basic aggregations such as, `min`, `max`, `median`, `sum`, `avg`
```sql orders
SELECT
email, item, sales
FROM
needful_things.orders
```
```markdown
```
## Customize Color Values
```markdown
```
## Red Negative Values
```sql NegativeSales
SELECT
MAX(sales)*-1 as max_sales
FROM
needful_things.orders
```
If the value is negative, the font color will automatically change to red, overriding any color specified by the color prop.
```markdown
```
## Options
Query name, wrapped in curly braces
Column to pull values from
Row number to display. 0 is the first row.
Text to display in place of an error
Format to use for the value ([see available formats](/core-concepts/formatting))
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.).
Adds aggregation to query, column name required.
Specifies the font color of the Value.
Conditionally sets the font color to red based on whether the selected value is less than 0
---
evidence/sites/docs/pages/components/sankey-diagram/index.md
---
---
title: Sankey Diagram
sidebar_position: 1
---
The SankeyDiagram component accepts a query and displays a flow from one set of values to another.
To display a flow with multiple levels, like these examples, see [Mutli-level](#multi-level) below.
```sql simple_sankey
select 'products' as source, 'profits' as target, 100 as amount, 0.67 as percent
union all
select 'products' as source, 'expenses' as target, 50 as amount, 0.33 as percent
union all
select 'services' as source, 'profits' as target, 25 as amount, 0.50 as percent
union all
select 'services' as source, 'expenses' as target, 25 as amount, 0.50 as percent
```
```sql traffic_data
select 'google' as source, 'all_traffic' as target, 100 as count
union all
select 'direct' as source, 'all_traffic' as target, 50 as count
union all
select 'facebook' as source, 'all_traffic' as target, 25 as count
union all
select 'bing' as source, 'all_traffic' as target, 25 as count
union all
select 'tiktok' as source, 'all_traffic' as target, 25 as count
union all
select 'twitter' as source, 'all_traffic' as target, 25 as count
union all
select 'linkedin' as source, 'all_traffic' as target, 25 as count
union all
select 'pinterest' as source, 'all_traffic' as target, 25 as count
union all
select 'all_traffic' as source, '/' as target, 50 as count
union all
select 'all_traffic' as source, '/docs' as target, 150 as count
union all
select 'all_traffic' as source, '/blog' as target, 25 as count
union all
select 'all_traffic' as source, '/about' as target, 75 as count
```
```svelte
```
## Vertical
```svelte
```
# Echarts Options String
```svelte
```
# Node Depth Override
```sql apple_income_statement
select 'iphone' as source, 'product revenue' as target, 51 as amount_usd
union all
select 'mac' as source, 'product revenue' as target, 10 as amount_usd
union all
select 'ipad' as source, 'product revenue' as target, 8 as amount_usd
union all
select 'wearables and home' as source, 'product revenue' as target, 9 as amount_usd
union all
select 'services revenue' as source, 'revenue' as target, 20 as amount_usd
union all
select 'product revenue' as source, 'revenue' as target, 78 as amount_usd
union all
select 'revenue' as source, 'gross profit' as target, 43 as amount_usd
union all
select 'gross profit' as source, 'operating profit' as target, 30 as amount_usd
union all
select 'gross profit' as source, 'operating expenses' as target, 13 as amount_usd
union all
select 'revenue' as source, 'cost of revenue' as target, 55 as amount_usd
```
The value labels can be formatted using the `valueFmt` option.
```svelte
```
### `nodeLabels=full`
```svelte
```
## Link Labels
### `linkLabels=full` (default)
Requires `percentCol` to show percentage beside value
```svelte
```
### `linkLabels=value`
```svelte
```
### `linkLabels=percent`
```svelte
```
## Custom Color Palette
```svelte
```
## Link Colors
### `linkColor=grey` (default)
```svelte
```
### `linkColor=source`
```svelte
```
### `linkColor=target`
```svelte
```
### `linkColor=gradient`
```svelte
```
## Multi-level
The syntax for multi-level sankey diagrams is the same, but the
underlying query must represent all the levels using the same
`sourceCol` and `targetCol`, so it is necessary to `union`
each level together. `sourceCol` nodes on the next level will be linked to `targetCol` nodes in the previous level with the same name.
For example, here is the source for the visuals above.
```svelte
```sql traffic_source
select
channel as source,
'all_traffic' as target,
count(user_id) as count
from events.web_events
group by 1,2
union all
select
'all_traffic' as source,
page_route as target,
count(user_id) as count
from events.web_events
group by 1, 2
```
```
## Options
### Data
Query name, wrapped in curly braces
Column to use for the source of the diagram
Column to use for the target of the diagram
Column to use for the value of the diagram
Column to use for the percent labels of the diagram
Manual adjustment to location of each node `{{'services revenue': 2}}`
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.).
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
### Formatting & Styling
Format to use for `valueCol` ([see available formats](/core-concepts/formatting))
Layout direction of the nodes in the diagram.
Whether the nodes are sorted by size in the diagram
Controls the horizontal alignment of nodes in the diagram. When orient is vertical, nodeAlign controls vertical alignment.
The gap between any two rectangles in each column of the the diagram.
The node width of rectangle in the diagram.
Border color. Only accepts a single color.
Border Width. It should be a natural number.
Array of custom colours to use for the chart. E.g., `{['#cf0d06','#eb5752','#e88a87']}`
Color to use for the links between nodes in the diagram
### Chart
Chart title. Appears at top left of chart.
Chart subtitle. Appears just under title.
Adds labels to the nodes of the diagram
Adds labels to the links between nodes
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.
### Custom Echarts Options
Custom Echarts options to override the default options. See [reference page](/components/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
---
evidence/sites/docs/pages/components/details/index.md
---
---
title: Details
sidebar_position: 1
---
The details component allows you to add a collapsible section to your markdown. This is useful for adding additional information that you don't want to be visible by default.
## Default state
Definition of metrics in Solutions Targets
### Time to Proposal
Average number of days it takes to create a proposal for a customer
*Calculation:*
Sum of the number of days it took to create each proposal, divided by the number of proposals created
*Source:*
Hubspot
````markdown
Definition of metrics in Solutions Targets
### Time to Proposal
Average number of days it takes to create a proposal for a customer
*Calculation:*
Sum of the number of days it took to create each proposal, divided by the number of proposals created
*Source:*
Hubspot
````
## Expanded state
Definition of metrics in Solutions Targets
### Time to Proposal
Average number of days it takes to create a proposal for a customer
*Calculation:*
Sum of the number of days it took to create each proposal, divided by the number of proposals created
*Source:*
Hubspot
```markdown
Definition of metrics in Solutions Targets
### Time to Proposal
Average number of days it takes to create a proposal for a customer
*Calculation:*
Sum of the number of days it took to create each proposal, divided by the number of proposals created
*Source:*
Hubspot
```
## Options
The text shown next to the triangle icon.
Whether expanded by default.
---
evidence/sites/docs/pages/components/bubble-chart/index.md
---
---
title: Bubble Chart
sidebar_position: 1
queries:
- price_vs_volume.sql
---
```markdown
```
## Examples
### Default
```markdown
```
### Multi-Series
```markdown
```
## Options
### Data
### Formatting & Styling
### Axes
### Chart
### Custom Echarts Options
### Interactivity
## Annotations
Bubble charts can include [annotations](/components/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```markdown
```
---
evidence/sites/docs/pages/components/echarts-options/index.md
---
---
sidebar_position: 98
title: ECharts Options
---
`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={{
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
```markdown
My Link Button
```
## Options
Renders a button that, when clicked, navigates to the specified URL. It can accept either a full external link (e.g. `https://google.com`) or link to another page within your evidence app (e.g. `/sales/performance`).
---
evidence/sites/docs/pages/components/download-data/index.md
---
---
title: Download Data
sidebar_position: 1
---
```categories
select category, sum(sales) as sales from needful_things.orders
group by all
order by sales desc
```
The Download Data component allows you to place a link on your page to download a specified dataset to CSV.
```svelte
```
## Examples
### Custom Text
```svelte
```
### Custom Query ID
```svelte
```
## Options
Query name, wrapped in curly braces
Whether link is visible. If using as part of a custom component, you can pass a variable representing the hover state of your component to control visibility.
Label to show on the link
Label to include as the start of the CSV filename. If no queryID is supplied, "evidence_download" is used.
---
evidence/sites/docs/pages/components/slider/index.md
---
---
title: Slider
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
````
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 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.
Sets the length of the slider. Options are "medium", large" or "full". A empty string of any other strings will not result in default size.
---
evidence/sites/docs/pages/components/scatter-plot/index.md
---
---
title: Scatter Plot
sidebar_position: 1
queries:
- price_vs_volume.sql
---
```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/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/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/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/bar-chart/index.md
---
---
title: Bar Chart
sidebar_position: 1
queries:
- orders_by_month.sql
- orders_by_category_2021.sql
- orders_by_item_all_time.sql
- categories_by_channel.sql
---
```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/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/big-link/index.md
---
---
title: Big Link
sidebar_position: 1
---
My Big Link
```markdown
My Big Link
```
## Options
Renders a link that, when clicked, navigates to the specified URL. It can accept either a full external link (e.g. `https://google.com`) or link to another page within your evidence app (e.g. `/sales/performance`).
---
evidence/sites/docs/pages/components/dropdown/index.md
---
---
title: Dropdown
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.
````markdown
Selected: {inputs.category_multi_selectAllByDefault.value}
````
# Dropdown
## Options
# 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/modal/index.md
---
---
title: Modal
sidebar_position: 1
---
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
```markdown
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
```
## Styling
Modals support markdown in the body, but you need to leave whitespace between the text and the modal tags.
**bold** and _italic_ text is supported.
```markdown
**bold** and _italic_ text is supported.
```
## Including Components
```sql orders_by_month
select order_month, sum(sales) as sales_usd0k from needful_things.orders
group by all
```
You can include components inside a Modal, like charts or tables:
```svelte
```
## Options
---
evidence/sites/docs/pages/components/heatmap/index.md
---
---
title: Heatmap
sidebar_position: 1
---
```orders
select category, dayname(order_datetime) as day, dayofweek(order_datetime) as day_num, count(*) as order_count from needful_things.orders
group by all
order by category, day_num
```
```markdown
```
## Data Structure
Heatmap requires your data to contain 2 categorical columns (1 for the x-axis and 1 for the y-axis) and 1 numeric column.
#### Example
```sql example
SELECT 'West' as region, 'A' as product, 120 as sales
UNION ALL
SELECT 'West', 'B', 200
UNION ALL
SELECT 'West', 'C', 150
UNION ALL
SELECT 'East', 'A', 110
UNION ALL
SELECT 'East', 'B', 315
UNION ALL
SELECT 'East', 'C', 450
```
### Unpivoting your Data
If you have data spread across columns, you can use the `UNPIVOT` feature in your SQL query to prepare the data for the heatmap.
#### Example
If you have a query result called `region_sales`:
```sql region_sales
SELECT 'West' as region, 120 as "A", 200 as "B", 150 as "C"
UNION ALL
SELECT 'East', 110, 315, 450
```
You can use `UNPIVOT` like so:
```sql
UNPIVOT ${region_sales}
on COLUMNS(* EXCLUDE(region))
INTO
NAME product
VALUE sales
```
Which will return this table, which can be passed into the Heatmap:
```sql region_sales_unpivoted
SELECT 'West' as region, 'A' as product, 120 as sales
UNION ALL
SELECT 'West', 'B', 200
UNION ALL
SELECT 'West', 'C', 150
UNION ALL
SELECT 'East', 'A', 110
UNION ALL
SELECT 'East', 'B', 315
UNION ALL
SELECT 'East', 'C', 450
order by region desc, product
```
**Note on Date Columns**
Heatmap currently only works with string columns. If you would like to use a date column, cast it to a string in your SQL query before passing it into the Heatmap
## Examples
### Basic Heatmap
```markdown
```
### Custom Color Scale
```svelte
```
### Rotated Labels
```item_state
select item, state, count(1) as orders from needful_things.orders
group by all
order by state asc, item asc
```
Content of the First Tab
You can use **markdown** here too!
Content of the Second Tab
Here's a [link](https://www.google.com)
```markdown
Content of the First Tab
You can use **markdown** here too!
Content of the Second Tab
Here's a [link](https://www.google.com)
```
## Examples
### Custom Color
Content of the First Tab
Content of the Second Tab
```markdown
Content of the First Tab
Content of the Second Tab
```
### Persist Selected Tab to URL
Click Second id Tab and notice the the url updates!
Refresh the page and the tab you selected persists!
```markdown
Click Second id Tab and notice the the url updates!
Refresh the page and the tab you selected persists!
```
# Tabs
## Options
Unique Id for this set of tabs. When set, the selected tab is included in the URL so it can be shared.
Color for the active tab.
# Tab
## Options
Label for the tab
Unique Id for this tab. Only needed if 2 tabs have the same label (not recommended).
---
evidence/sites/docs/pages/components/sparkline/index.md
---
---
title: Sparkline
sidebar_position: 1
---
```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
```
```html
```
## Options
### Data
Query name, wrapped in curly braces
Categorical column to use for the x-axis
Numeric column to use for the y-axis
Chart type for sparkline
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
Color to use for the visualization. For area sparklines, choose the color for the line and the area color will be automatically appplied in a lighter shade.
Format to use for value column ([see available formats](/core-concepts/formatting))
Format to use for date column ([see available formats](/core-concepts/formatting))
### Axes
Whether to truncate the y-axis to enhance visibility
### Sizing
Height of sparkline in pixels
Width of sparkline in pixels
### Interactivity
Turn on or off tooltip behaviour on hover. If off, chart will be a staticly rendered SVG (better for page performance). If on, you will be able to see dates/values when hovering over the sparkline
Group name to connect this sparkline to other charts for synchronized tooltip hovering. Charts with the same `connectGroup` name will become connected
---
evidence/sites/docs/pages/components/all-components/index.md
---
---
sidebar_position: 0
title: All Components
hide_title: false
hide_table_of_contents: false
description: A list of all the components available in the Evidence library.
---
## Data Components
### [Mixed Type Charts](/components/mixed-type-charts)
Bar and Line
### [Annotations](/components/annotations)
Reference Line - y-axis
Reference Line - x-axis
Reference Area - x-axis
Reference Area - y-axis
Reference Area - Box
### Maps
Area Map
Point Map
Bubble Map
Base Map
US Map
### [Custom ECharts](/components/custom-echarts)
Custom ECharts Treemap
Custom ECharts Funnel
Custom ECharts Pie Chart
Custom ECharts Donut Chart
Advanced ECharts Example
## UI Components
### [Accordion](/components/accordion)
### [Alert](/components/alert)
### [Details](/components/details)
### [Grid](/components/grid)
### [Modal](/components/modal)
### [Tabs](/components/tabs)
## Input Components
### [Button Group](/components/button-group)
### [Dropdown](/components/dropdown)
### [TextInput](/components/text-input)
### [DateRange](/components/date-range)
---
evidence/sites/docs/pages/components/big-value/index.md
---
---
title: Big Value
sidebar_position: 1
queries:
- orders_with_comparisons.sql
---
Big Value displays a large value, and can be configured to include a comparison and a sparkline.
```markdown
```
## Examples
### Default
```markdown
```
### Comparisons
```markdown
```
### Multiple cards
Multiple cards will align themselves into a row.
```markdown
```
### Linking to other pages
The link property makes the Value component clickable, allowing navigation to other pages.
```html
```
### Non-Delta Comparisons
```html
```
### Sparkline
```html
```
## Options
### Data
Used to navigate to other pages. Can be a full external link like `https://google.com` or an internal link like `/sales/performance`
### Comparison Options
### Sparkline
---
evidence/sites/docs/pages/components/funnel-chart/index.md
---
---
title: Funnel Chart
sidebar_position: 1
---
```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/text-input/index.md
---
---
title: Text Input
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
---
evidence/sites/docs/pages/components/last-refreshed/index.md
---
---
title: Last Refreshed
sidebar_position: 1
---
Displays the last time the data was refreshed. This component is useful for showing users how up-to-date the data is.
```markdown
```
## Examples
### Alternative Prefix
```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/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/index/index.md
---
---
title: "Components"
sidebar_position: 2
sidebar_link: false
---
---
evidence/sites/docs/pages/components/data-table/index.md
---
---
title: Data Table
sidebar_position: 1
---
## Examples
### Displaying All Columns in Query
```orders_summary
select * from needful_things.orders
order by id
limit 100
```
```svelte
```
### Selecting Specific Columns
```svelte
```
### Custom Column Formatting
You can use the `fmt` prop to format your columns using [built-in format names or Excel format codes](/core-concepts/formatting/)
```svelte
```
#### Formatting Driven by Another Column
```country_summary_fmts
select *,
case
when country in ('Austria', 'Ukraine') then 'eur'
when country = 'Sweden' then 'sek'
when country = 'Vietnam' then '"₫"#,##0'
else 'usd' end as custom_format
from ${country_summary}
```
This example includes a `custom_format` column, which contains a different currency format code for many of the rows.
```svelte
```
### Search
```svelte
```
### Sort
```svelte
```
### Deltas
```sql country_summary
select date '2020-04-30' as date, 87 as value_usd, 0.0234 as yoy, 'Austria' as country, 'B' as category, 100384 as country_id, 'AT' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/AT.png' as flag, 'https://www.google.ca/search?q=austria' as country_url
union all
select date '2020-05-01' as date, 95 as value_usd, 0.0534 as yoy, 'Australia' as country, 'C' as category, 104942 as country_id, 'AU' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/AU.png' as flag, 'https://www.google.ca/search?q=australia' as country_url
union all
select date '2020-05-02' as date, 163 as value_usd, 0.0264 as yoy, 'Brazil' as country, 'A' as category, 100842 as country_id, 'BR' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/BR.png' as flag, 'https://www.google.ca/search?q=brazil' as country_url
union all
select date '2020-05-03' as date, 174 as value_usd, 0.0727 as yoy, 'Canada' as country, 'A' as category, 104975 as country_id, 'CA' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/CA.png' as flag, 'https://www.google.ca/search?q=canada' as country_url
union all
select date '2020-05-04' as date, 214 as value_usd, -0.1223 as yoy, 'Chile' as country, 'B' as category, 100644 as country_id, 'CL' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/CL.png' as flag, 'https://www.google.ca/search?q=chile' as country_url
union all
select date '2020-05-05' as date, 342 as value_usd, 0.0124 as yoy, 'Denmark' as country, 'B' as category, 102948 as country_id, 'DK' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/DK.png' as flag, 'https://www.google.ca/search?q=denmark' as country_url
union all
select date '2020-05-06' as date, 331 as value_usd, 0.0252 as yoy, 'Estonia' as country, 'D' as category, 102495 as country_id, 'EE' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/EE.png' as flag, 'https://www.google.ca/search?q=estonia' as country_url
union all
select date '2020-05-07' as date, 98 as value_usd, 0.0754 as yoy, 'Finland' as country, 'B' as category, 104962 as country_id, 'FI' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/FI.png' as flag, 'https://www.google.ca/search?q=finland' as country_url
union all
select date '2020-05-08' as date, 128 as value_usd, -0.0246 as yoy, 'Ghana' as country, 'C' as category, 100599 as country_id, 'GH' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/GH.png' as flag, 'https://www.google.ca/search?q=ghana' as country_url
union all
select date '2020-05-09' as date, 153 as value_usd, 0.0447 as yoy, 'Honduras' as country, 'D' as category, 102494 as country_id, 'HN' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/HN.png' as flag, 'https://www.google.ca/search?q=honduras' as country_url
union all
select date '2020-05-10' as date, 384 as value_usd, -0.0255 as yoy, 'India' as country, 'A' as category, 101948 as country_id, 'IN' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/IN.png' as flag, 'https://www.google.ca/search?q=india' as country_url
union all
select date '2020-05-11' as date, 234 as value_usd, 0.0855 as yoy, 'Ireland' as country, 'B' as category, 100987 as country_id, 'IE' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/IE.png' as flag, 'https://www.google.ca/search?q=ireland' as country_url
union all
select date '2020-05-12' as date, 67 as value_usd, 0.0635 as yoy, 'Jamaica' as country, 'C' as category, 101248 as country_id, 'JM' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/JM.png' as flag, 'https://www.google.ca/search?q=jamaica' as country_url
union all
select date '2020-05-13' as date, 125 as value_usd, -0.0232 as yoy, 'Kenya' as country, 'C' as category, 101947 as country_id, 'KE' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/KE.png' as flag, 'https://www.google.ca/search?q=kenya' as country_url
union all
select date '2020-05-14' as date, 118 as value_usd, -0.0343 as yoy, 'Lebanon' as country, 'D' as category, 108849 as country_id, 'LB' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/LB.png' as flag, 'https://www.google.ca/search?q=lebanon' as country_url
union all
select date '2020-05-15' as date, 263 as value_usd, 0.0883 as yoy, 'Mexico' as country, 'B' as category, 100763 as country_id, 'MX' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/MX.png' as flag, 'https://www.google.ca/search?q=mexico' as country_url
union all
select date '2020-05-16' as date, 211 as value_usd, 0.0395 as yoy, 'Nigeria' as country, 'A' as category, 100837 as country_id, 'NG' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/NG.png' as flag, 'https://www.google.ca/search?q=nigeria' as country_url
union all
select date '2020-05-17' as date, 192 as value_usd, 0.0234 as yoy, 'Oman' as country, 'D' as category, 100993 as country_id, 'OM' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/OM.png' as flag, 'https://www.google.ca/search?q=oman' as country_url
union all
select date '2020-05-18' as date, 59 as value_usd, 0.0828 as yoy, 'Philippines' as country, 'D' as category, 104128 as country_id, 'PH' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/PH.png' as flag, 'https://www.google.ca/search?q=philippines' as country_url
union all
select date '2020-05-19' as date, 113 as value_usd, 0.0554 as yoy, 'Qatar' as country, 'C' as category, 100181 as country_id, 'QA' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/QA.png' as flag, 'https://www.google.ca/search?q=qatar' as country_url
union all
select date '2020-05-20' as date, 190 as value_usd, 0.0134 as yoy, 'Romania' as country, 'A' as category, 101384 as country_id, 'RO' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/RO.png' as flag, 'https://www.google.ca/search?q=romania ! startups' as country_url
union all
select date '2020-05-21' as date, 190 as value_usd, -0.0554 as yoy, 'Sweden' as country, 'B' as category, 101847 as country_id, 'SE' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/SE.png' as flag, 'https://www.google.ca/search?q=sweden' as country_url
union all
select date '2020-05-22' as date, 248 as value_usd, 0.0254 as yoy, 'Thailand' as country, 'C' as category, 104837 as country_id, 'TH' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/TH.png' as flag, 'https://www.google.ca/search?q=thailand' as country_url
union all
select date '2020-05-23' as date, 168 as value_usd, 0.0294 as yoy, 'Ukraine' as country, 'C' as category, 101938 as country_id, 'UA' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/UA.png' as flag, 'https://www.google.ca/search?q=ukraine' as country_url
union all
select date '2020-05-24' as date, 101 as value_usd, 0.0234 as yoy, 'Vietnam' as country, 'A' as category, 104948 as country_id, 'VN' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/VN.png' as flag, 'https://www.google.ca/search?q=vietnam' as country_url
union all
select date '2020-05-25' as date, 67 as value_usd, 0.0294 as yoy, 'Yemen' as country, 'B' as category, 100774 as country_id, 'YE' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/YE.png' as flag, 'https://www.google.ca/search?q=yemen' as country_url
union all
select date '2020-05-26' as date, 100 as value_usd, 0.011 as yoy, 'Zimbabwe' as country, 'A' as category, 100337 as country_id, 'ZW' as country_code, 'https://flaglog.com/codes/standardized-rectangle-120px/ZW.png' as flag, 'https://www.google.ca/search?q=zimbabwe' as country_url
```
```svelte
```
### Sparklines
Sparklines require an array inside a cell of your table. You can create an array using the `array_agg()` function in DuckDB syntax. Below is an example query using this function, and the resulting DataTable.
```sql categories
WITH monthly_sales AS (
SELECT
category,
DATE_TRUNC('month', order_datetime) AS date,
SUM(sales) AS monthly_sales
FROM
needful_things.orders
GROUP BY
category, DATE_TRUNC('month', order_datetime)
)
SELECT
category,
sum(monthly_sales) as total_sales,
ARRAY_AGG({'date': date, 'sales': monthly_sales}) AS sales
FROM
monthly_sales
GROUP BY
category
order by total_sales desc
```
```svelte
```
### Bar Chart Column
```svelte
```
### Total Row
Default total aggregation is `sum`
```svelte
```
#### Using Built-in Aggregation Functions
```country_example
select * from ${countries}
limit 5
```
```svelte
```
#### Custom Colors
When you pass a custom color to `colorScale`, Evidence will create a color palette for you, starting at white (or black, depending on the selected theme) and ending at the color you provided. See examples further down the page to see how to specify a custom color palette with multiple colors.
```orders_by_category
select order_month as month, category, sum(sales) as sales_usd0k, count(1) as num_orders_num0,
sum(sales) / count(1) as aov_usd2
from needful_things.orders
group by all
```
```svelte
```
### Custom Color Palettes
```numbers
select 'A' as name, 1 as number
union all
select 'B',2
union all
select 'C',3
union all
select 'D',4
union all
select 'E',5
union all
select 'F',6
union all
select 'G',7
union all
select 'H',8
union all
select 'I',9
union all
select 'J',10
order by number asc
```
#### Diverging Scale
```svelte
```
#### Heatmap
```svelte
```
#### Color Breakpoints
Use `colorBreakpoints` or `colorMid`/`colorMin`/`colorMax` to control which values are assigned to which sections of the color scale
```svelte
```
#### Create Scale from Another Column
The `number` column in this example has a color scale defined by the `scale_defining_number` column, rather than by its own values.
```numbers_othercol
select 'A' as name, 1 as number, 2 as scale_defining_number, 'usd' as fmt
union all
select 'B',2,10,'eur'
union all
select 'C',3,30,'num0'
union all
select 'D',4,20,'pct'
union all
select 'E',5,10,'usd'
union all
select 'F',6,5,'pct'
union all
select 'G',7,1,'pct'
union all
select 'H',8,44,'eur'
union all
select 'I',9,4,'#,##0.00"kg"'
union all
select 'J',10,55, 'usd'
order by number asc
```
```svelte
```
### Red Negatives
```negatives
select 'A' as name, -5 as number,0 as status
union all
select 'B', -4 as number, 1 as status
union all
select 'C', -3 as number, 2 as status
union all
select 'D', -2 as number,0
union all
select 'E', -1 as number,1
union all
select 'F', 0 as number,1
union all
select 'G', 1 as number,2
union all
select 'H', 2 as number,2
union all
select 'I', 3 as number,0
union all
select 'J', 4 as number,0
order by number asc
```
```svelte
```
### Including Images
You can include images by indicating either an absolute path e.g. `https://www.example.com/images/image.png` or a relative path e.g. `/images/image.png`. For relative paths, see [storing static files in a static folder](/reference/markdown/#storing-images-and-static-files).
In this example, `flag` is either an absolute path or a relative path to the image.
```svelte
```
### Link Columns
#### Link Column with Unique Labels
```svelte
```
#### Link Column with Consistent String Label
```svelte
```
### HTML Content
```sql html_in_table
select 'Bold text' as "HTML in Table", 0 as row_number union all
select 'Italic text', 1 union all
select 'Link', 2 union all
select '', 3 union all
select 'Inline Code is supported', 4
order by row_number
```
````markdown
```sql html_in_table
select 'Bold text' as "HTML in Table", 0 as row_number union all
select 'Italic text', 1 union all
select 'Link', 2 union all
select '', 3 union all
select 'Inline Code is supported', 4
order by row_number
```
````
To apply styling to most HTML tags, you should add the `class=markdown` attribute to the tag in your column. This will apply the same styling as the markdown renderer.
### Row Links
#### External Links
This example includes a column `country_url` which contains a country name as a search term in Google (e.g., `https://google.ca/search?q=canada`)
Click on a row to navigate using the row link:
```svelte
```
#### Link to Pages in Your App
In this example, the SQL query contains a column with links to parameterized pages in the app. Below is an example of the SQL that could be used to generate such links:
```sql
select
category,
'/parameterized-pages/' || category as category_link,
sum(sales) as sales_usd0
from needful_things.orders
group by 1
```
You can then use the `link` property of the DataTable to use your link column as a row link (`category_link` in this example):
```svelte
```
By default, the link column of your table is hidden. If you would like it to be displayed in the table, you can use `showLinkCol=true`.
### Styling
#### Row Shading + Row Lines
```svelte
```
#### Row Shading + No Row Lines
```svelte
```
#### No Lines or Shading
```svelte
```
### Column Alignment
```svelte
```
### Custom Column Titles
```svelte
```
### Raw Column Names
```svelte
```
### Groups - Accordion
#### Without subtotals
```orders
select state, category, item, count(1) as orders, sum(sales) as sales, if(random() > 0.3, 1, -1) * 0.1 * random() as growth from needful_things.orders
group by all
limit 25
```
```svelte
```
#### With Subtotals
```svelte
```
#### Closed by Default
```svelte
```
#### With Configured Columns
```svelte
```
### Groups - Section
#### Without subtotals
```svelte
```
#### With Subtotals
```svelte
```
#### With Configured Columns
```svelte
```
### Column Groups
```sql countries
SELECT 'United States' as country, 'North America' as continent, 22996 as gdp_usd, 0.017 as gdp_growth, 0.025 as interest_rate, 0.085 as inflation_rate, 0.037 as jobless_rate, -16.7 as gov_budget, 137.2 as debt_to_gdp, -3.6 as current_account, 332.4 as population
UNION ALL
SELECT 'China', 'Asia', 17734, 0.004, 0.0365, 0.027, 0.054, -3.7, 66.8, 1.8, 1412.6
UNION ALL
SELECT 'Japan', 'Asia', 4937, 0.002, -0.001, 0.026, 0.026, -12.6, 266.2, 3.2, 125.31
UNION ALL
SELECT 'Germany', 'Europe', 4223, 0.017, 0.005, 0.079, 0.055, -3.7, 69.3, 7.4, 83.16
UNION ALL
SELECT 'United Kingdom', 'Europe', 3187, 0.029, 0.0175, 0.101, 0.038, -6, 95.9, -2.6, 67.53
UNION ALL
SELECT 'India', 'Asia', 3173, 0.135, 0.054, 0.0671, 0.078, -9.4, 73.95, -1.7, 1380
UNION ALL
SELECT 'France', 'Europe', 2937, 0.042, 0.005, 0.058, 0.074, -6.5, 112.9, 0.4, 67.63
UNION ALL
SELECT 'Italy', 'Europe', 2100, 0.047, 0.005, 0.084, 0.079, -7.2, 150.8, 2.5, 59.24
UNION ALL
SELECT 'Canada', 'North America', 1991, 0.029, 0.025, 0.076, 0.049, -4.7, 117.8, 0.1, 38.44
UNION ALL
SELECT 'South Korea', 'Asia', 1799, 0.029, 0.025, 0.057, 0.029, -6.1, 42.6, 3.5, 51.74
UNION ALL
SELECT 'Russia', 'Europe', 1776, -0.04, 0.08, 0.151, 0.039, 0.8, 18.2, 6.8, 145.55
UNION ALL
SELECT 'Brazil', 'South America', 1609, 0.032, 0.1375, 0.1007, 0.091, -4.5, 80.27, -1.8, 213.32
```
```svelte
```
### Wrap Titles
```svelte
```
# DataTable
## Options
Query name, wrapped in curly braces
Number of rows to show in the table before paginating results. Use `rows=all` to show all rows in the table.
Background color of the header row
Font color of the header row
Show a total row at the bottom of the table, defaults to sum of all numeric columns
Background color of the total row
Font color of the total row
Turns on or off row index numbers
Turns on or off borders at the bottom of each row
Shades every second row in light grey
Background color of the table
Enable sort for each column - click the column title to sort
Column to sort by on initial page load. Sort direction is asc if unspecified. Can only sort by one column using this prop. If you need multi-column sort, use the order by clause in your sql in combination with this prop.
Add a search bar to the top of your table
Enable download data button below the table on hover
Enable auto-formatting of column titles. Turn off to show raw SQL column names
Wrap column titles
Enable a more compact table view that allows more content vertically and horizontally
Makes each row of your table a clickable link. Accepts the name of a column containing the link to use for each row in your table
Whether to show the column supplied to the `link` prop
Helper for writing DataTable syntax with many columns. When set to true, markdown for the DataTable including each `Column` contained within the query will be generated and displayed below the table.
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.).
### Groups
Groups allow you to create sections within your table, increasing the density of the content you're displaying. Groups are currently limited to 1 level, but will be expanded in future versions.
Column to use to create groups. Note that groups are currently limited to a single group column.
How the groups are shown in the table. Can be accordion (expand/collapse) or section (group column values are merged across rows)
Whether to show aggregated totals for the groups
Specify an override format to use in the subtotal row ([see available formats](/core-concepts/formatting)). Custom strings or values are unformatted by default.
[groupType=accordion] Whether to show the accordions as open on page load
[groupType=accordion] Background color for the accordion row
[groupType=section] Background color for the subtotal row
[groupType=section] Font color for the subtotal row
[groupType=section] Where the group label will appear in its cell
# Column
Use the `Column` component to choose specific columns to display in your table, and to apply options to specific columns. If you don't supply any columns to the table, it will display all columns from your query result.
## Options
Column id (from SQL query)
Override title of column
Align column text
Format the values in the column ([see available formats](/core-concepts/formatting))
Column to use to format values in this column. This is used to achieve different value formats by row. The fmtColumn should contain strings of format codes - either Evidence built-in formats or Excel codes.
Specify an aggregation function to use for the total row. Accepts predefined functions, custom strings or values
Specify an override format to use in the total row ([see available formats](/core-concepts/formatting)). Custom strings or values are unformatted by default.
Column to use as the weight values for weighted mean aggregation. If not specified, a weight of 1 for each value will be used and the result will be the same as the `mean` aggregation.
Wrap column text
Wrap column title
Lets you specify how to treat the content within a column. See below for contentType-specific options.
Group name to display above a group of columns. Columns with the same group name will get a shared header above them
Conditionally sets the font color to red based on whether the selected value is less than 0
### Images
`contentType=image`
Height of image in pixels
Width of image in pixels
Alt text for image
### Links
`contentType=link`
Text to display for link
Whether to open link in new tab
### Deltas
`contentType=delta`
Whether to show the up/down delta arrow symbol
If present, negative comparison values appear in green, and positive values appear in red.
Whether to show the delta value. Set this to false to show only the delta arrow indicator.
Start of the range for 'neutral' values, which appear in grey font with a dash instead of an up/down arrow. By default, neutral is not applied to any values.
End of the range for 'neutral' values, which appear in grey font with a dash instead of an up/down arrow. By default, neutral is not applied to any values.
Whether to display the delta as a 'chip', with a background color and border.
### Sparklines
`contentType=sparkline`
`contentType=sparkarea`
`contentType=sparkbar`
Column within an array cell to use as the x-axis for the spark viz. Arrays can be created inside a query using the `array_agg()` function from DuckDB
Column within an array cell to use as the y-axis for the spark viz. Arrays can be created inside a query using the `array_agg()` function from DuckDB
Whether to truncate the y-axis
Height of the spark viz. Making the viz taller will increase the height of the full table row
Width of the spark viz
Color of the spark viz
### Bar Chart Column
`contentType=bar`
Color of the bars. Affects positive bars only. See `negativeBarColor` to change color of negative bars
Color of negative bars
Whether to hide the data labels on the bars
Background color for bar chart
### Conditional Formatting (Color Scales)
`contentType=colorscale`
Color to use for the scale
Set a minimum for the scale. Any values below that minimum will appear in the lowest color on the scale
Set a midpoint for the scale
Set a maximum for the scale. Any values above that maximum will appear in the highest color on the scale
Array of numbers to use as breakpoints for each color in your color scale. Should line up with the colors you provide in `colorScale`
Column to use to define the color scale range. Values in this column will have their cell color determined by the value in the scaleColumn
### HTML
`contentType=html`
To apply styling to HTML tags, you will need to add the `class=markdown` attribute **to the HTML tag in your column**. This will apply the same styling as the markdown renderer. E.g., `Code`
---
evidence/sites/docs/pages/components/custom-echarts/index.md
---
---
sidebar_position: 98
title: Custom ECharts
---
Our chart library is based on [ECharts](https://echarts.apache.org/examples/en/index.html), a powerful and flexible open source JavaScript chart library. We use many of the features in ECharts, and combine them with custom data transformation, logic, and theming.
## `` Component
If you would like to create a fully custom chart, you can use our built-in `` component. This component accepts a JavaScript object containing a chart configuration. To test this out, you can find an example on the [ECharts example page](https://echarts.apache.org/examples/en/index.html) and paste the option object into the Evidence `` component.
This will let you create a chart that matches Evidence theming, but gives you access to the [full suite](https://echarts.apache.org/en/option.html#title) of ECharts features.
The downside of this approach is that `` 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/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
```
## 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/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/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/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/delta/index.md
---
---
sidebar_position: 1
title: Delta
---
```sql growth
select 0.366 as positive, -0.366 as negative
```
````markdown
````
#### Neutral*
*Values are not defined as neutral until you define a range using the `neutralMin` and `neutralMax` props
```markdown
```
### Symbol Position
#### Symbol on Left
```html
```
#### Symbol on Left in Chip
```html
```
## Options
Query name, wrapped in curly braces
Column to pull values from
Row number to display. 0 is the first row.
Pass a specific value to the component (e.g., value=100). Overridden by the data/column props.
Format to use for the value ([see available formats](/core-concepts/formatting))
If true, negative comparison values appear in green, and positive values appear in red.
Whether to show the up/down delta arrow symbol
Whether to show the value. Set this to false to show only the delta arrow indicator.
Text to display after the delta symbol and value
Start of the range for 'neutral' values, which appear in grey font with a dash instead of an up/down arrow. By default, neutral is not applied to any values.
End of the range for 'neutral' values, which appear in grey font with a dash instead of an up/down arrow. By default, neutral is not applied to any values.
Whether to display the delta as a 'chip', with a background color and border.
Whether to display the delta symbol to the left or right of the value
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.).
---
evidence/sites/docs/pages/components/point-map/index.md
---
---
title: Point Map
sidebar_position: 1
---
```html
```
```sql la_locations
select *, 'https://www.google.com/search?q=' || point_name as link_col from la_locations
```
## Examples
### Custom Basemap
You can add a different basemap by passing in a basemap URL. You can find examples here: https://leaflet-extras.github.io/leaflet-providers/preview/
**Note:** you need to wrap the url in curly braces and backticks to avoid the curly braces in the URL being read as variables on your page
```svelte
```
### Custom Tooltip
#### `tooltipType=hover`
```svelte
```
#### With clickable link and `tooltipType=click`
```svelte
```
### Custom Color Palette
```svelte
```
### Custom Styling
```svelte
```
### Link Drilldown
Pass in a `link` column to enable navigation on click of the point. These can be absolute or relative URLs
```svelte
```
### Use Map as Input
Use the `name` prop to set an input name for the map - when a point is clicked, it will set the input value to that row of data
```svelte
```
*Click a point on the map to see the input value get updated:*
#### Selected value for `{inputs.my_point_map}`:
{JSON.stringify(inputs.my_point_map, null, 2)}
#### Selected value for `{inputs.my_point_map.point_name}`:
{inputs.my_point_map.point_name}
```filtered_locations
select * from ${la_locations}
where point_name = '${inputs.my_point_map.point_name}' OR '${inputs.my_point_map.point_name}' = 'true'
```
#### Filtered Data
### Legends
```grouped_locations
SELECT
*,
CASE
WHEN id BETWEEN 0 AND 4 THEN 'Hotels'
WHEN id BETWEEN 5 AND 9 THEN 'Restaurants'
WHEN id BETWEEN 10 AND 14 THEN 'Golf Courses'
WHEN id BETWEEN 15 AND 19 THEN 'Shops'
WHEN id BETWEEN 20 AND 24 THEN 'Bars'
WHEN id BETWEEN 25 AND 29 THEN 'Entertainment'
WHEN id BETWEEN 30 AND 34 THEN 'Banks'
END AS Category
FROM la_locations
```
#### Categorical Legend
```svelte
```
#### Custom Colors
Set custom legend colors using the `colorPalette` prop to match the number of categories; excess categorical options will default to standard colors.
```svelte
```
#### Scalar Legend
```svelte
```
#### Custom Colors
Define scalar legend colors using the `colorPalette` prop, allowing specified colors to create a gradient based on the range of values.
```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
# 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/base-map/index.md
---
---
title: Base Map
sidebar_position: 1
---
```html
```
```sql la_zip_sales
select *, 'https://www.google.com/search?q=' || zip_code as link_col from la_zip_sales
where zip_code <> 90704
```
```sql la_locations
select *, 'https://www.google.com/search?q=' || point_name as link_col from la_locations
```
## Overview
The BaseMap component provides a flexible and extensible way to create maps with multiple layers. This component serves as the foundation for AreaMap, PointMap, and BubbleMap.
Within BaseMap, you can add layers using the following components:
- ``
- ``
- ``
## Examples
See the pages for [Area Map](/components/area-map), [Point Map](/components/point-map), and [Bubble Map](/components/bubble-map) for examples specific to those layers. The same options can be applied to the layer components within BaseMap.
### Adding Multiple Layers
```svelte
```
### Custom Basemap
You can add a different basemap by passing in a basemap URL. You can find examples here: https://leaflet-extras.github.io/leaflet-providers/preview/
```markdown
```
## Options
### Data
### Formatting & Styling
### Chart
### Custom Echarts Options
### Interactivity
---
evidence/sites/docs/pages/components/custom-components/component-queries.md
---
# Component Queries
Component queries allow you to run SQL queries in your component code.
Component queries transform how we build data visualizations. Instead of passing data down through props from parent pages, components become self-contained units that can request exactly what they need. This independence makes components more reusable and easier to maintain, as all the logic for both fetching and displaying data lives in one place.
## Static Queries
Static queries are "static" because the SQL string they run cannot change throughout the component's lifecycle. They are defined once when your component is created, and are executed when `QueryLoad` is mounted.
Here's how to create a component that fetches and displays information about tables in your database:
```html title="components/TableList.svelte"
<script>
import { buildQuery } from '@evidence-dev/component-utilities/buildQuery';
import { QueryLoad } from '@evidence-dev/core-components';
const query = buildQuery(
'SELECT * FROM information_schema.tables',
);
{#each tables as table}
{table.table_name}
{/each}
```
### The Query Loader
The `QueryLoad` component manages the entire lifecycle of your query execution. It handles:
- Executing your query against DuckDB
- Managing loading states
- Handling any errors that occur
- Delivering results to your component
```html
```
The `let:loaded` directive creates a new variable containing your query results. Using a descriptive name (like `tableData` or `salesMetrics`) makes your code more maintainable than the generic `loaded`.
## Dynamic Queries
For queries that change based on user input or component state, you need dynamic queries. This allows you to create interactive components.
Here's an example that lets users control how many rows to display:
```html title="components/DynamicTableList.svelte"
<script>
import { QueryLoad } from '@evidence-dev/core-components';
import { getQueryFunction } from '@evidence-dev/component-utilities/buildQuery';
import { Query } from '@evidence-dev/sdk/usql';
// This will hold our current query result
let query;
// Create a reactive query function
const queryFunction = Query.createReactive({
execFn: getQueryFunction(),
callback: v => query = v
});
// These values will control our query
let limit = 10;
let schemaName = 'public';
// This reactive statement runs whenever limit or schemaName change
$: queryFunction(`
SELECT *
FROM information_schema.tables
WHERE table_schema = '${schemaName}'
LIMIT ${limit}
`);
{#each tables as table}
{table.table_name}
{/each}
```
Let's understand how this works:
### Query State Management
1. First, we create a variable to hold our query result:
```javascript
let query;
```
This will be updated every time our query executes with new parameters.
2. Next, we create a reactive query function:
```javascript
const queryFunction = Query.createReactive({
execFn: getQueryFunction(),
callback: v => query = v
});
```
This sets up an environment that can execute queries and update our component's state.
3. Finally, we use Svelte's reactive declarations to run our query:
```javascript
$: queryFunction(`SELECT * FROM ... LIMIT ${limit}`);
```
The `$:` syntax tells Svelte to re-run this statement whenever `limit` changes, creating a connection between your component's state and your query.
## Error Handling
When working with queries, things can sometimes go wrong. Maybe a query is malformed, or perhaps it's trying to access a table that doesn't exist. The `QueryLoad` component helps you handle these situations gracefully through its error slot:
```html
Unable to load data
{error.message}
Please check your query and try again.
{#each tables as table}
{table.table_name}
{/each}
```
When a query fails, Evidence:
1. Captures the error information
2. Prevents the main content from rendering
3. Makes the error details available through `let:error`
4. Displays your error handling content
---
evidence/sites/docs/pages/components/custom-components/index.md
---
---
sidebar_position: 99
title: Custom Components
---
Custom components allow you to extend the functionality of Evidence, as well as to make your code more reusable.
In Evidence, you can build your own components and use them anywhere in your app. This is made possible through Svelte, the JavaScript framework Evidence is built on. These components can include the charts used for visualization, custom components created completely from scratch, or adaptations of existing UI components such as the header, sidebar, menu, etc.
[Evidence Labs](https://labs.evidence.dev) contains several good examples of custom components.
Below is a **short guide** on building a simple component in Evidence.
For a fuller guide, Svelte offers a really great interactive tutorial that you can complete in your browser in about an hour: [Svelte Tutorial](https://svelte.dev/tutorial/basics)
**Built a great component?**
Let us know in our [Slack community](https://slack.evidence.dev)!
We'd love to see what you've built, and may add generally applicable components to Evidence Labs, or the Evidence component library!
## Example custom component
If you were creating a component called ``, which included some text and a BarChart, to use in `index.md`, you could do so like this:
Add a folder called `components/` in the root of your project. This is where Evidence looks for your Svelte components:
### Folder structure
```bash
.
|-- pages/
| `-- index.md
`-- components/
`-- Hello.svelte
```
`Hello.svelte` is your component. Add the following code to these two files:
### File contents
````html title="index.md"
```sql sales_by_country
select 'Canada' as country, 100 as sales_usd
union all
select 'USA' as country, 200 as sales_usd
union all
select 'UK' as country, 300 as sales_usd
```
````
```html title="Hello.svelte"
<script>
export let myData;
import { BarChart } from '@evidence-dev/core-components';
</script>
Here is a BarChart in a Component, with some accompanying text. Components stored in the
/components/ folder will be included in your app.
```
## Building your own component: Checklist
If you're building a component, here are some things to keep in mind.
In your markdown file:
1. **Pass any data as props** if you need to access query results in the component
In the custom component:
1. **Use Svelte (HTML + extra features) syntax** in this component - it will not support Markdown
1. **Use the `/components/` folder** for your .svelte files
1. **`export` any props you want to use** in the component
1. **Import any [Evidence components](https://github.com/evidence-dev/evidence/tree/main/sites/example-project/src/components)** you want to use in the custom component
## Optional: Publishing Your Components as a Plugin
If you have built custom components that you would like other Evidence users to be able to use in their apps, you can publish them as an Evidence plugin. See the [Plugin section](/plugins/create-component-plugin/) for more details.
## Utility Functions
Evidence provides a collection of helpful utility functions to use within custom components, for things like error handling, data manipulation, and value formatting.
To use these utilities, you must import them explicitly in the script tag portion of your component. The import line for each utlity function is included for reference below:
### Error Handling
#### checkInputs `checkInputs(data, reqCols, optCols)`
Accepts a dataset and list of columns, and returns an error if the dataset is empty, required columns are missing, or referenced columns do not exist in the data
```javascript
import checkInputs from '@evidence-dev/component-utilities/checkInputs';
```
- `data`: the query result you need to check
- `reqCols`: a list of columns that are required for your component (e.g., x or y for a chart)
- `optCols`: a list of optional columns
#### ErrorChart ``
A component used to display an error state on the page
```javascript
import { ErrorChart } from '@evidence-dev/core-components';
```
- `error`: the error message to display
- `chartType`: the title that appears at the top of the error component
### Data Manipulation
#### getDistinctValues `getDistinctValues(data, column)`
Returns an array of distinct values from a specified column in a dataset
```javascript
import getDistinctValues from '@evidence-dev/component-utilities/getDistinctValues';
```
- `data`: query result to pull the values from
- `column`: name of column to use
#### getDistinctCount `getDistinctCount(data, column)`
Returns the count of distinct values in a column
```javascript
import getDistinctCount from '@evidence-dev/component-utilities/getDistinctCount';
```
- `data`: query result to pull the values from
- `column`: name of column to use
#### getSortedData `getSortedData(data, col, isAsc)`
Returns the original dataset, sorted by the specific column and direction
```javascript
import getSortedData from '@evidence-dev/component-utilities/getSortedData';
```
- `data`: query result to pull the values from
- `col`: name of column to sort
- `isAsc`: if true, will sort ascending; otherwise, descending
#### getColumnSummary `getColumnSummary(data, returnType = "object")`
Returns an object with information about each column (title, min, max, format, etc.)
```javascript
import getColumnSummary from '@evidence-dev/component-utilities/getColumnSummary';
```
- `data`: query result to summarize
- `returnType`: "object" or "array"
#### getCompletedData `getCompletedData(data, x, y, series, nullsZero = false, fillX = false)`
Returns the original dataset with rows filled in as needed to complete a continuous number series
```javascript
import getCompletedData from '@evidence-dev/component-utilities/getCompletedData';
```
- `data`: query result which requires completed data
- `x`: name of column for x-axis
- `y`: name of column for y-axis
- `series`: name of column for series
- `nullsZero`: if true, will treat nulls as zeroes; otherwise, will leave as nulls
- `fillX`: if true, will find the smallest increment in the x-axis values and create rows as needed to create a continous series
### Value & Label Formatting
#### formatValue `formatValue(value, columnFormat = undefined, columnUnitSummary = undefined)`
Returns a formatted value
```javascript
import { formatValue } from '@evidence-dev/component-utilities/formatting';
```
- `value`: value to format
- `columnFormat`: a format object for column being formatted (can be obtained from the `getColumnSummary` function)
- `columnUnitSummary`: an object containing the extents of the column, used for unit summary formatting like "M" or "B" (can be obtained from the `getColumnSummary` function)
#### fmt `fmt(value, format)`
Simpler version of the `formatValue` function which does not require a format object
```javascript
import { fmt } from '@evidence-dev/component-utilities/formatting';
```
- `value`: value to be formatted
- `format`: a string representing a format tag name or an Excel-style format code
#### formatTitle `formatTitle(column, columnFormat)`
Returns a formatted column title (with proper letter casing)
```javascript
import formatTitle from '@evidence-dev/component-utilities/formatTitle';
```
- `column`: name of column to be formatted
- `columnFormat`: a format object for column being formatted (can be obtained from the `getColumnSummary` function)
## Adding Queries
Custom components can execute queries rather than requiring data to be passed to them. See [component queries](./component-queries) for details
---
evidence/sites/docs/pages/components/us-map/index.md
---
---
title: US Map
sidebar_position: 1
queries:
- state_population.sql
---
```html
```
## Examples
### Color Scales
`colorScale=info`
````html
````
`colorScale=positive`
````html
````
`colorScale=negative`
````html
````
### Custom Color Scale
```svelte
```
### Legend
#### Default
```html
```
#### With Filter
````svelte
````
### Links
```html
```
### State Abbreviations
```html
```
## Options
### Data
Query name, wrapped in curly braces
Column to be used as the name for each state
If true, map will look for two letter abbreviations rather than full names
Column to be used as the value determining the colour of each state
Colour scale to be used. To use a custom color palette, see the `colorPalette` prop
Custom color palette to use for setting state colors. Overrides `colorScale`. E.g., `{['#cf0d06','#eb5752','#e88a87']}`
Minimum value for the colour scale. Anything below the minimum will be shown in the same colour as the min value
Maximum value for the colour scale. Anything above the maximum will be shown in the same colour as the max value
Title appearing above the map. Is included when you click to save the map image
Subtitle appearing just above the map. Is included when you click to save the map image
Column containing links. When supplied, allows you to click each state on the map and navigate to the link
Format to use for values ([see available formats](/core-concepts/formatting))
Whether to show a legend at the top of the map
Whether to include filter controls on the legend. Can only be used when legend = true
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.).
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/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/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
---
evidence/sites/docs/pages/components/bubble-map/index.md
---
---
title: Bubble Map
sidebar_position: 1
---
```html
```
```sql la_locations
select *, 'https://www.google.com/search?q=' || point_name as link_col from la_locations
```
## Examples
### Custom Basemap
You can add a different basemap by passing in a basemap URL. You can find examples here: https://leaflet-extras.github.io/leaflet-providers/preview/
**Note:** you need to wrap the url in curly braces and backticks to avoid the curly braces in the URL being read as variables on your page
```svelte
### Custom Tooltip
#### `tooltipType=hover`
```svelte
```
#### With clickable link and `tooltipType=click`
```svelte
```
### Custom Color Palette
```svelte
```
### Custom Styling
```svelte
```
### Max Bubble Size
```svelte
```
### Link Drilldown
Pass in a `link` column to enable navigation on click of the point. These can be absolute or relative URLs
```svelte
```
### Use Map as Input
Use the `name` prop to set an input name for the map - when a point is clicked, it will set the input value to that row of data
```svelte
```
*Click a point on the map to see the input value get updated:*
#### Selected value for `{inputs.my_point_map}`:
{JSON.stringify(inputs.my_point_map, null, 2)}
#### Selected value for `{inputs.my_point_map.point_name}`:
{inputs.my_point_map.point_name}
```filtered_locations
select * from ${la_locations}
where point_name = '${inputs.my_point_map.point_name}' OR '${inputs.my_point_map.point_name}' = 'true'
```
#### Filtered Data
### Legends
```grouped_locations
SELECT
*,
CASE
WHEN id BETWEEN 0 AND 4 THEN 'Hotels'
WHEN id BETWEEN 5 AND 9 THEN 'Restaurants'
WHEN id BETWEEN 10 AND 14 THEN 'Golf Courses'
WHEN id BETWEEN 15 AND 19 THEN 'Shops'
WHEN id BETWEEN 20 AND 24 THEN 'Bars'
WHEN id BETWEEN 25 AND 29 THEN 'Entertainment'
WHEN id BETWEEN 30 AND 34 THEN 'Banks'
END AS Category
FROM la_locations
```
#### Categorical Legend
```svelte
```
#### Custom Colors
Set custom legend colors using the `colorPalette` prop to match the number of categories; excess categorical options will default to standard colors.
```svelte
```
#### Scalar Legend
```svelte
```
#### Custom Colors
Define scalar legend colors using the `colorPalette` prop, allowing specified colors to create a gradient based on the range of values.
This is a default alert
This is a informational alert
This is a successful alert
This is a warning alert
This is a dangerous alert
```markdown
This is a default alert
This is a informational alert
This is a successful alert
This is a warning alert
This is a dangerous alert
```
## Options
Changes the color of the alert
---
evidence/sites/docs/pages/components/mixed-type-charts/index.md
---
---
title: Mixed-Type Charts
sidebar_position: 1
---
The easiest way to create mixed-type charts is setting up [a secondary y-axis in `LineChart`](/components/line-chart#secondary-axis-with-bar) or a [secondary axis in `BarChart`](/components/bar-chart#secondary-axis-with-line)
You can combine multiple chart types inside a single `` tag to create mixed-type charts.
## Examples
### Mixed-Type Chart
This example uses multiple y columns and multiple series types (bar and line)
```markdown
```
Because x is the first column in the dataset, an explicit `x` prop is not required.
This structure also gives you control over the individual series on your chart. For example, if you have a single series running through a component, you can override props specifically for that series. Since the FDA acronym was not fully capitalized above, you can rename that specific series inside the `` primitive:
```markdown
```
# Chart ``
```markdown
Insert primitives here
```
## 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
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 series (groups) in a multi-series chart
Format to use for x column ([see available formats](/core-concepts/formatting))
Format to use for y column ([see available formats](/core-concepts/formatting))
Whether to use a log scale for the y-axis
Base to use when log scale is enabled
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.).
## Chart
Swap the x and y axes to create a horizontal 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.
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
Whether to scale the y-axis to fit your data. yMin and yMax take precedence over yScale
JavaScript object to add or override chart configuration settings (see Custom Charts page)
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"}}`
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/).
# Line ``
```markdown
```
## Options
Column(s) to use for the y-axis of the chart. Can be different than the y supplied to Chart
Column to use as the series (groups) in a multi-series chart. Can be different than the series supplied to Chart
Name to show in legend for a single series (to override column name)
Color to override default series color. Only accepts a single color.
% of the full color that should be rendered, with remainder being transparent
Options to show breaks in a line (dashed or dotted)
Thickness of line (in pixels)
Turn on/off markers (shapes rendered onto the points of a line)
Shape to use if markers=true
Size of each shape (in pixels)
Treatment of missing values in the dataset
JavaScript object to add or override chart configuration settings (see Custom Charts page)
# Area ``
```markdown
```
## Options
Column(s) to use for the y-axis of the chart. Can be different than the y supplied to Chart
Column to use as the series (groups) in a multi-series chart. Can be different than the series supplied to Chart
Name to show in legend for a single series (to override column name)
Color to override default series color. Only accepts a single color.
% of the full color that should be rendered, with remainder being transparent
Show line on top of the area
Treatment of missing values in the dataset
JavaScript object to add or override chart configuration settings (see Custom Charts page)
# Bar ``
```markdown
```
## Options
Column to use for the y-axis of the chart
Name to show in legend for a single series (to override column name)
Grouping method to use for multi-series charts
Name for an individual stack. If separate Bar components are used with different stackNames, the chart will show multiple stacks
Color to override default series color. Only accepts a single color.
% of the full color that should be rendered, with remainder being transparent
Width of line surrounding each bar
Color to use for outline if outlineWidth > 0
JavaScript object to add or override chart configuration settings (see Custom Charts page)
# Scatter ``
```markdown
```
## Options
Column to use for the y-axis of the chart
Name to show in legend for a single series (to override column name)
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
JavaScript object to add or override chart configuration settings (see Custom Charts page)
# Bubble ``
```markdown
```
## Options
Column to use for the y-axis of the chart
Column to use to scale the size of the bubbles
Name to show in legend for a single series (to override column name)
Options for which shape to use for bubble points
Minimum bubble size
Maximum bubble size
% 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
JavaScript object to add or override chart configuration settings (see Custom Charts page)
# Hist ``
```markdown
```
## Options
Column which contains the data you want to summarize
Color to override default series color
% of the full color that should be rendered, with remainder being transparent
JavaScript object to add or override chart configuration settings (see Custom Charts page)
### Interactivity
Group name to connect this chart to other charts for synchronized tooltip hovering. Charts with the same `connectGroup` name will become connected
## Annotations
Mixed type charts can include [annotations](/components/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/checkbox/index.md
---
---
title: Checkbox
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 defaultValue property will set the initial checked 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
````
# Checkbox
## Options
Name of the checkbox, used to reference the selected value elsewhere as `{inputs.name.value}`
Value to use when checkbox is first loaded. True value for checked, false for unchecked
---
evidence/sites/docs/pages/components/annotations/index.md
---
---
title: Annotations
sidebar_position: 1
queries:
- orders_by_month.sql
- orders_by_category_2021.sql
---
Annotations help you add important context directly within a chart - highlight important dates, time periods, or specific points on a chart to make it easier for your audience to pull insights from the information.
## At a glance
Evidence currently offers 4 types of annotations, which can be defined inline or with a dataset:
- [`ReferenceLine`](#reference-line): draw a line on a chart (e.g. sales target, launch dates, linear regression)
- [`ReferenceArea`](#reference-area): highlight an area on a chart (e.g. holiday shopping periods, metric control ranges)
- [`ReferencePoint`](#reference-point): highlight specific points on a chart (e.g. anomalies, points of interest)
- [`Callout`](#callout): draw attention to data (e.g. data trend explanation)
Callout
Data trending up here
```html
Callout
Data trending up here
```
# Reference Line
Reference lines allow you to add lines to a chart to provide additional context within the visualization. These lines can be produced by providing a specific value (`y=50` or `x='2020-03-14'`) or by providing a dataset (e.g., `date`, `event_name`).
If you provide coordinates for `[x, y]` and `[x2, y2]`, you can create sloped lines between points.
When a dataset is provided, `ReferenceLine` can generate multiple lines - one for each row in the dataset. This can be helpful for plotting things like important milestones, launch dates, or experiment start dates.
## Examples
### Y-axis Defined Inline
```html
```
### X-axis Defined Inline
```html
```
### Y-axis Multiple Lines
```html
```
### X-axis from Data
```sql multiple_dates
select '2019-12-05'::date as start_date, '2020-02-05'::date as end_date, 'Campaign 1' as campaign_name union all
select '2020-07-14'::date, '2020-09-14'::date, 'Campaign 2' union all
select '2021-04-14'::date, '2021-06-14'::date, 'Campaign 3'
```
```html
```
### Sloped Line Inline
```html
```
### Linear Regression from Data
```sql orders_by_state
select
state,
sum(sales) as sales,
count(*) as num_orders
from orders
group by all
```
```sql regression
WITH
coeffs AS (
SELECT
regr_slope(num_orders, sales) AS slope,
regr_intercept(num_orders, sales) AS intercept,
regr_r2(num_orders, sales) AS r_squared
FROM ${orders_by_state}
)
SELECT
min(sales) AS x,
max(sales) AS x2,
min(sales) * slope + intercept AS y,
max(sales) * slope + intercept AS y2,
'Best Fit (y = ' || ROUND(slope, 2) || 'x + ' || ROUND(intercept, 2) || ', R^2 = ' || ROUND(r_squared, 3) || ')' AS label
FROM coeffs, ${orders_by_state}
GROUP BY slope, intercept, r_squared
```
```html
```
````markdown
```sql orders_by_state
select
state,
sum(sales) as sales,
count(*) as num_orders
from orders
group by all
```
```sql regression
WITH
coeffs AS (
SELECT
regr_slope(num_orders, sales) AS slope,
regr_intercept(num_orders, sales) AS intercept,
regr_r2(num_orders, sales) AS r_squared
FROM ${orders_by_state}
)
SELECT
min(sales) AS x,
max(sales) AS x2,
min(sales) * slope + intercept AS y,
max(sales) * slope + intercept AS y2,
'Best Fit (y = ' || ROUND(slope, 2) || 'x + ' || ROUND(intercept, 2) || ', R^2 = ' || ROUND(r_squared, 3) || ')' AS label
FROM coeffs, ${orders_by_state}
GROUP BY slope, intercept, r_squared
```
````
### Custom Styling
```html
```
### Label Positions
```html
```
### Colours
```html
```
## Options
A reference line can be produced by defining values inline or by supplying a dataset, and the required props are different for each of those cases.
### Defining Values Inline
This table shows how you combine `x`, `y`, `x2`, and `y2` to create different types of lines:
```sql xy_config_table
select 5 as x, null as y, null as x2, null as y2, 'Vertical line at x=5' as Result union all
select null, 100, null, null, 'Horizontal line at y=100' union all
select 5, 100, null, null, 'Vertical line at x=5 (ignores y)' union all
select 5, 100, 10, 200, 'Sloped line from [5, 100] to [10, 200]' union all
select 5, 100, null, 200, 'Vertical line from [5, 100] to [5, 200]' union all
select 5, 100, 10, null, 'Horizontal line from [5, 100] to [10, 100]'
order by 2 nulls first, 1 nulls first, 3 nulls first, 4 nulls first
```
If you provide `[x, y]` and `[x2, y2]`, coordinates must fall within the chart's boundaries in order for the line to be drawn.
### Supplying a Dataset
```sql xy_data_table
select 'x_col' as x, null as y, null as x2, null as y2, 'Vertical lines at values in x_col' as Result union all
select null, 'y_col', null, null, 'Horizontal lines at values in y_col' union all
select 'x_col', 'y_col', null, null, 'Vertical lines at x_col (ignores y_col)' union all
select 'x_col', 'y_col', 'x2_col', 'y2_col', 'Sloped Lines from [x_col, y_col] to [x2_col, y2_col]'
order by 2 nulls first, 1 nulls first, 3 nulls first, 4 nulls first
```
If you provide `[x, y]` and `[x2, y2]`, coordinates must fall within the chart's boundaries in order for lines to be drawn.
### Styling
# Reference Area
Reference areas allow you to add highlighted ranges to a chart. These ranges can be:
- Along the x-axis (e.g., recession date ranges)
- Along the y-axis (e.g., control threshold for a metric)
- Both (e.g, highlighting a specific series of points in the middle of the chart)
Reference areas can be produced by defining the x and y-axis values inline (e.g., `xMin='2020-03-14' xMax='2020-06-30'`) or by supplying a dataset (e.g., `start_date`, `end_date`, `name`).
When a dataset is provided, `ReferenceArea` can generate multiple areas - one for each row in the dataset.
## Examples
### X-axis Defined Inline
```html
```
### Y-axis Defined Inline
```html
```
### X-axis from Data
```html
```
### Bar Chart
```html
```
#### Continuous Axis Bar Charts
On a continous x-axis (dates or numbers), the reference area will start and stop at the exact point on the x-axis. This means it will appear in the middle of whichever bar is at that point. If you would prefer to see the area cover the full bar, there are 2 ways to achieve this:
1. Add a buffer on either side of the range you want to highlight (e.g., instead of ending the area at `2020-07-01`, end it at `2020-07-15`)
2. Change your x-axis to categorical data (using `xType=category`). If using a date axis, you may also want to retain the axis label formatting for dates - to achieve this, you can use the `xFmt` prop (e.g., `xFmt=mmm`)
### Reference Area Box
```html
```
### Labels
```html
```
#### Label Overlaps
Reference areas appear behind chart gridlines, including reference area labels. If you are seeing an overlap between the gridlines and the reference area label, you can avoi this by turning gridlines off (`yGridlines=false`).
### Colours
```html
```
## Options
A reference area can be produced by defining values inline or by supplying a dataset, and the required props are different for each of those cases.
### Defining Values Inline
- At least 1 of `xMin`, `xMax`, `yMin`, or `yMax` is required to plot an area.
### Supplying a Dataset
- At least 1 of `xMin`, `xMax`, `yMin`, or `yMax` is required to plot an area.
### Styling
# Reference Point
Reference points allow you to add labels on certain points to emphasize them in the chart. They can be produced by providing a specific x/y coordinate (e.g. `x="2021-05-01"` `y=11012`) or by providing a dataset (e.g. `anomalies`, `points`).
When a dataset is provided, `ReferencePoint` will generate multiple points - one for each row in the dataset. This can be helpful for plotting a large number of points with a succinct syntax.
## Examples
### Defined Point
```html
```
### Points from Data
```sales_drops
select
month,
sales,
concat('Sales dropped $', round(abs(sales_diff))::int::text) as label
from (
select
month,
sales,
sales - lag(sales) over (order by month) as sales_diff
from ${orders_by_month}
)
where sales_diff < -2000
```
```html
```
### Custom Styling
```html
```
### Label Positions
```html
```
#### Multiline label
A label with
line breaks in it
to allow longer text
```html
A label with
line breaks in it
to allow longer text
```
### Colours
```html
```
## Options
### Defining Values Inline
### Supplying a Dataset
### Styling
# Callout
Callouts are very similar to reference points, just with different default styling to optimize them for slightly different use cases. Callouts allow you to add a long label somewhere on a chart to describe a trend or provide insight on the data. They can be produced by providing a specific x/y coordinate (e.g. `x="2021-05-01"` `y=11012`) or by providing a dataset (e.g. `anomalies`, `points`).
When a dataset is provided, `Callout` will generate multiple points - one for each row in the dataset. This can be helpful for plotting a large number of points with a succinct syntax.
## Examples
### Defined Point
```html
```
### Points from Data
```sales_drops
select
month,
sales,
concat('Sales dropped $', round(abs(sales_diff))::int::text) as label
from (
select
month,
sales,
sales - lag(sales) over (order by month) as sales_diff
from ${orders_by_month}
)
where sales_diff < -2000
```
```html
```
### Custom Styling
```html
```
### Label Positions
```html
```
#### Multiline label
Callout
with
line
breaks
```html
Callout
with
line
breaks
```
### Colours
```html
```
## Options
### Defining Values Inline
### Supplying a Dataset
### Styling
---
evidence/sites/docs/pages/components/accordion/index.md
---
---
title: Accordion
sidebar_position: 1
---
This is the first item's accordion body.
You can use **markdown** here too!
Make sure to include an empty line after the component if you want to use markdown.
This is the second item's accordion body with bold text.
This is the third item's accordion body.
```markdown
This is the first item's accordion body.
You can use **markdown** here too!
Make sure to include an empty line after the component if you want to use markdown.
This is the second item's accordion body with bold text.
This is the third item's accordion body.
```
## Examples
### Single Accordion
Content 1
Content 2
Content 3
```markdown
Content 1
Content 2
Content 3
```
### Overriding Styles
Use the `class` options to override the styles on the accordion.
Content 1
Content 2
Content 3
```markdown
Content 1
Content 2
Content 3
```
### Title Slot
Pass components into the accordion title by using the slot `title`.
```growth
select 0.366 as positive, -0.366 as negative
```
Custom Title
Content 1
Content 2
Content 3
```markdown
Custom Title
Content 1
Content 2
Content 3
```
## Options
### Accordion
Pass custom classes to control the styling of the accordion body. Supports [tailwind classes](https://tailwindcss.com).
### AccordionItem
Pass custom classes to control the styling of an accordion item. Supports [tailwind classes](https://tailwindcss.com).
---
evidence/sites/docs/pages/components/grid/index.md
---
---
title: Grid
sidebar_position: 1
---
```sql orders_by_category
select order_month, count(1) as orders from needful_things.orders
group by all
```
```svelte
```
## Group Component
To include multiple items inside one grid cell, use the `Group` component to wrap the items you want to include in that cell.
For example:
Some text
```html
Some text
```
This will stack "some text" above the bar chart, rather than giving it it's own cell.
## Options
---
evidence/sites/docs/pages/components/dimension-grid/index.md
---
---
title: Dimension Grid
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}`
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/area-map/index.md
---
---
title: Area Map
sidebar_position: 1
---
```svelte
```
```sql la_zip_sales
select *, 'https://www.google.com/search?q=' || zip_code as link_col from la_zip_sales
where zip_code <> 90704
```
## Examples
### Custom Basemap
You can add a different basemap by passing in a basemap URL. You can find examples here: https://leaflet-extras.github.io/leaflet-providers/preview/
**Note:** you need to wrap the url in curly braces and backticks to avoid the curly braces in the URL being read as variables on your page
```svelte
```
### Using an Online GeoJSON
```sql orders_by_state
select state, count(*) as orders
from orders
where state != 'Alaska' and state != 'Hawaii'
group by state
```
```svelte
```
#### With clickable link and `tooltipType=click`
```svelte
```
### Custom Styling
```svelte
```
### Custom Color Palette
```svelte
```
### Link Drilldown
Pass in a `link` column to enable navigation on click of the point. These can be absolute or relative URLs
```svelte
```
### Use Map as Input
Use the `name` prop to set an input name for the map - when a point is clicked, it will set the input value to that row of data
```svelte
```
*Click an area on the map to see the input value get updated:*
#### Selected value for `{inputs.my_area_map}`:
{JSON.stringify(inputs.my_area_map, null, 2)}
#### Selected value for `{inputs.my_area_map.zip_code}`:
{inputs.my_area_map.zip_code}
```filtered_areas
select * from ${la_zip_sales}
where zip_code = ${inputs.my_area_map.zip_code} OR ${inputs.my_area_map.zip_code} = true
```
#### Filtered Data
### Legends
```sql grouped_locations
SELECT
*,
CASE
WHEN id BETWEEN 0 AND 500 THEN 'Hotels'
WHEN id BETWEEN 501 AND 1000 THEN 'Restaurants'
WHEN id BETWEEN 1001 AND 1500 THEN 'Golf Courses'
WHEN id BETWEEN 1501 AND 2000 THEN 'Shops'
WHEN id BETWEEN 2001 AND 2500 THEN 'Bars'
WHEN id BETWEEN 2501 AND 3000 THEN 'Entertainment'
WHEN id BETWEEN 3001 AND 4000 THEN 'Banks'
END AS Category
FROM la_zip_sales
WHERE zip_code <> 90704
ORDER BY 1;
```
#### Categorical Legend
```svelte
```
#### Custom Colors
Set custom legend colors using the `colorPalette` prop to match the number of categories; excess categorical options will default to standard colors.
```svelte
```
#### Scalar Legend
```svelte
```
#### Custom Colors
Define scalar legend colors using the `colorPalette` prop, allowing specified colors to create a gradient based on the range of values.
```svelte
```
## Options
### Data
### Formatting & Styling
### Axes
### Chart
### Custom Echarts Options
### Interactivity
## Annotations
Line charts can include [annotations](/components/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/area-chart/index.md
---
---
title: 'Area Chart'
sidebar_position: 1
queries:
- orders_by_month.sql
- orders_by_category_2021.sql
---
```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/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
---
evidence/sites/docs/pages/components/date-range/index.md
---
---
title: Date Range
sidebar_position: 1
queries:
- orders_by_day.sql
---
Creates a date picker that can be used to filter a query.
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
````
### 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 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 Range 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'`
---
evidence/sites/docs/pages/motivation/index.md
---
---
sidebar_position: 2
title: Motivation
description: It's still too difficult to build high quality data products. We give you the tools to deliver production-quality data products that feel more like the New York Times' data journalism than a drag-and-drop dashboard.
og:
image: /img/how-it-works.png
---
We think it's still too difficult to build high quality data products. Businesses are stuck with BI software that delivers slow and clunky outputs, and analysts are stuck manually configuring reports.
Our mission is to give you the tools to deliver production-quality data products that look and feel more like the New York Times' data journalism than a drag-and-drop dashboard.
Evidence combines the best of modern web frameworks with the best parts of BI:
- **Code-driven workflows:** Use your IDE, version control, and CI/CD tools
- **First-class text support:** Add context, explanation and insight to your reports
- **Programmatic features:** Use loops, conditionals, and templated pages to generate content from data
- **High performance:** Evidence apps are fast, reliable, and scalable
- **Lightweight setup:** Install locally and start building reports in just a few minutes
To get started, [install Evidence](/install-evidence).
---
evidence/sites/docs/pages/core-concepts/index.md
---
---
title: "Core Concepts"
sidebar_position: 1
sidebar_link: false
---
---
evidence/sites/docs/pages/core-concepts/filters/index.md
---
---
title: Filters
sidebar_position: 9
description: Filters dynamically change what data is returned by a query. Filters take the input that a user provides via a component, and use it to change the query.
---
Filters dynamically change what data is returned by a query. Filters take the input that a user provides via a component, and use it to change the query.
The below example uses the Evidence [``](/components/dropdown) component.
## Examples
### Filtering a query with a dropdown
![Filtering a Query](/img/filters-queries.png)
````markdown
```sql unique_items
select
item
from needful_things.orders
group by 1
```
```sql orders_by_month
select
date_trunc('month', order_date) as month,
sum(sales) as sales_usd
from needful_things.orders
where item = '${inputs.selected_item.value}'
group by 1
```
````
## Filtering a query with a default value
![Filtering a Query](/img/filters-default.png)
The `%` character can be used as a wildcard in SQL. It will return all items when the user selects "All Items" from this dropdown.
Note also the use of the `like` operator in the `where` clause.
````markdown
```sql items
select
item
from needful_things.orders
group by 1
```
```sql orders_by_month
select
date_trunc('month', order_date) as month,
sum(sales) as sales_usd
from needful_things.orders
where item like '${inputs.selected_item.value}'
group by 1
```
````
---
evidence/sites/docs/pages/core-concepts/query-functions/index.md
---
---
title: Query Functions
sidebar_position: 11
description: Query functions allow you to operate on query results with SQL-like syntax.
---
```sql orders
SELECT id, order_datetime, first_name, last_name, sales, category, item FROM orders
```
Query functions allow you to operate on query results with SQL-like syntax.
**Warning**
Query functions are experimental and may change in the future
The supported query functions are:
- [``.where()``](#where)
- [`.groupBy()`](#groupby)
- [`.limit()`](#limit)
- [`.offset()`](#offset)
- [`.agg()`](#agg)
## Where
``.where(`sqlStatement`)``
Filters rows in the query based on the provided condition.
```markdown
100`)} />
```
#### Parameters
### Iterating through a query
````markdown
```sql categories
SELECT DISTINCT category FROM orders
```
```sql orders_by_category
SELECT
category,
item,
sum(sales) as total_sales
FROM orders
group by all
```
{#each categories as category}
{/each}
````
```sql categories
SELECT DISTINCT category FROM orders
```
```sql orders_by_category
SELECT
category,
item,
sum(sales) as total_sales
FROM orders
group by all
```
{#each categories as category}
{/each}
## GroupBy
``.groupBy([columns], withRowCount = true)``
Groups rows by the specified columns and optionally includes a row count.
```markdown
```
#### Parameters
## Limit
``.limit(limit)``
Limits the number of rows returned by the query.
```markdown
```
#### Parameters
## Offset
``.offset(offset)``
Skips a specified number of rows in the query result.
```markdown
```
#### Parameters
## Agg
``.agg({aggObj})``
Adds aggregation operations to the query (e.g., `sum`, `avg`, `min`, `max`, `median`). Used in conjunction with [`groupBy`](#groupby).
```markdown
```
#### Parameters
Configuration object where keys are aggregation functions (`sum`, `avg`, `min`, `max`, `median`) and values are column specifications.
---
evidence/sites/docs/pages/core-concepts/data-sources/index.md
---
---
sidebar_position: 3
title: Data Sources
description: Connect a data source in order to run queries.
---
## Overview of Data Sources
Evidence extracts all data sources into a common storage format (called Parquet) to enable querying across multiple data sources using SQL.
- To query against your data sources, you first need to extract the data into Parquet, using `npm run sources`
- Supported sources including SQL databases, flat data files (CSV etc), and non-SQL data sources (e.g. APIs)
![Universal SQL Data Source Architecture](/img/usql-architecture.png)
More information about the architecture design can be found in [this article](https://evidence.dev/blog/why-we-built-usql).
## Connect your Data Sources
To connect your local development environment to a database:
1. Run your evidence app with `npm run dev`
1. Navigate to [localhost:3000/settings](http://localhost:3000/settings)
1. Select your data source, name it, and enter required credentials
1. (If required) Open the `connections.yaml` file inside `/sources/[source_name]` and add any additional configuration options
1. (If required) Add [source queries](#configure-source-queries)
1. Rerun sources with `npm run sources`
Evidence will save your credentials locally, and run a test query to confirm that it can connect.
Connections to databases in production are managed via [environment variables](/reference/cli#environment-variables)
## Configure Source Queries
For SQL data sources, choose which data to extract by adding .sql files to the `/sources/[source_name]/` folder.
**N.B: These queries use the data source's native SQL dialect.**
```code
.-- sources/
`-- my_source/
|-- connection.yaml
`-- my_source_query.sql
```
Each of these .sql files will create a table that can be queried in Evidence as `[my_source].[my_source_query]`.
**Non-SQL data sources**
For non-SQL data sources, configuring the data extracted is achieved in other ways. Refer to the documentation for the specific data source for details.
## Run Sources
You can extract data from configured sources in Evidence using `npm run sources`. Sources will also rerun automatically if you have the dev server running and you make changes to your source queries or source configuration.
### Working with Large Sources
In dev mode, if you have large sources which take a while to run, it can be helpful to only run the sources which have changed. There are a few ways to accomplish this:
- If your dev server is running, any changes you make to source queries will only re-run the queries which have changed
- Run a modified sources command to specify the source you want to run:
- `npm run sources -- --changed` run only the sources with changed queries
- `npm run sources -- --sources my_source` run `my_source` only
- `npm run sources -- --sources my_source --queries query_one,query_two` run `my_source.query_one` and `my_source.query_two` only
### Increase Process Memory
If you are working with large data sources (~1M+ rows), your `npm run sources` process may run out of memory, with an error similar to this:
```code
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
```
One way to circumvent this is to increase the amount of memory allocated to the process. The below command increases the memory to 4GB (the number is measured in MB), but you can set it arbitrarily up to the RAM of your machine
#### Mac OS / Linux
```code
NODE_OPTIONS="--max-old-space-size=4096" npm run sources
```
#### Windows
```code
set NODE_OPTIONS=--max-old-space-size=4096 && npm run sources
```
### Build Time Variables
You can pass variables to your source queries at build time using environment variables of the format `EVIDENCE_VAR__variable_name=value`.
`.env`
```bash
EVIDENCE_VAR__client_id=123
```
Then in your **source queries**, you can access the variable using `${}` syntax:
```sql
select * from customers
where client_id = ${client_id}
```
This will interpolate the value of `client_id` into the query:
```sql
select * from customers
where client_id = 123
```
Note that these variables are only accessible in source queries, not in file queries or queries in markdown files.
## Supported data sources
Evidence supports:
- [BigQuery](#bigquery)
- [Snowflake](#snowflake)
- [Redshift](#redshift)
- [PostgreSQL](#postgresql)
- [Timescale](#postgresql)
- [Trino](#trino)
- [Microsoft SQL Server](#microsoft-sql-server)
- [MySQL](#mysql)
- [SQLite](#sqlite)
- [DuckDB](#duckdb)
- [MotherDuck](#motherduck)
- [Databricks](#databricks)
- [Cube](#cube)
- [Google Sheets](#google-sheets)
- [CSV](#csv-files)
- [Parquet](#csv-files)
- & More
We're adding new connectors regularly. [Create a GitHub issue](https://github.com/evidence-dev/evidence/issues) or [send us a message in Slack](https://slack.evidence.dev) if you'd like to use Evidence with a database that isn't currently supported.
The source code for Evidence's connectors is available [on GitHub](https://github.com/evidence-dev/evidence/tree/main/packages)
## Data source specific info
All databases can be connected via the UI settings page as described above. Where relevant, additional information is provided below.
### BigQuery
Evidence supports connecting to Google BigQuery by using the gcloud CLI, a [service account](https://cloud.google.com/iam/docs/service-accounts) and a JSON key, or an OAuth access token.
#### Logging in with the gcloud CLI
If you have the [gcloud CLI](https://cloud.google.com/sdk/gcloud) installed, you can log in to BigQuery using the following command:
```bash
gcloud auth application-default login
```
Evidence will use the credentials stored by the gcloud CLI to connect to BigQuery.
> *Note: Since gcloud requires browser access, this method is only available when developing locally.*
#### Create a Service Account Key
1. [Go to the Service Account Page](https://console.cloud.google.com/projectselector/iam-admin/serviceaccounts/create?supportedpurview=project) and click on your project
2. Add a name for your service account, then click Create
3. Assign your service account a role for BigQuery (scroll down the role dropdown to find BigQuery roles).
1. **BigQuery User** should work for most use cases.
1. **BigQuery Data Viewer** may be required (depending on your organization's permissions settings in Google Cloud).
1. Reach out to us if you run into issues or need help with BigQuery permissions.
4. Click Continue, then click Done. You should see a table of users.
5. Click on the email address for the service account you just created, then click the **Keys** tab
6. Click Add Key, then Create New Key, then Create
7. Google will download a JSON Key File to your computer
#### Logging in with an OAuth access token
If you have an access token but can't download the gcloud CLI on the device you're deploying on and don't want to use a service account, you can use an OAuth access token.
An OAuth access token can be generated by running the following command on a device with the gcloud CLI installed:
```bash
gcloud auth application-default print-access-token
```
> *Note: This token will expire after 1 hour.*
Now you can copy the access token and use it in your Evidence app.
### Snowflake
Evidence supports connecting to Snowflake using a [Snowflake Account](https://docs.snowflake.com/en/user-guide/api-authentication), [Key-Pair Authentication](https://docs.snowflake.com/en/user-guide/key-pair-auth.html), [Browser-Based SSO](https://docs.snowflake.com/en/user-guide/admin-security-fed-auth-use#label-browser-based-sso), or [Native SSO through Okta](https://docs.snowflake.com/en/user-guide/admin-security-fed-auth-use#label-native-sso-okta). All Snowflake column names will be converted to lowercase in Evidence.
#### Snowflake Account
The Snowflake Account authentication method uses your Snowflake username and password to authenticate. If you don't have access to these, you will need to use one of the other authentication methods.
#### Key-Pair Authentication
The Key-Pair Authentication method uses a public/private key pair to authenticate. To use this method, you will need to [generate a public/private key pair](https://docs.snowflake.com/en/user-guide/key-pair-auth.html#label-generating-a-key-pair) and upload the public key to Snowflake.
#### Browser-Based SSO
The Browser-Based SSO method uses a browser-based SSO flow to authenticate. To use this method, you will need to [connect an SSO provider](https://docs.snowflake.com/en/user-guide/admin-security-fed-auth-configure-idp) to your Snowflake account.
#### Native SSO through Okta
The Native SSO through Okta method uses Okta to authenticate. To use this method, you will need to have an Okta account with MFA disabled connected to your Snowflake account.
### Redshift
The Redshift connector uses the Postgres connector under the hood, so configuration options are similar.
### PostgreSQL
Some databases can be connected by using the Postgres connector, including Timescale.
#### SSL
To connect to a Postgres database using SSL, you may need to modify the SSL settings used. Once you have selected a PostgreSQL data connection type, you can set the SSL value as follows:
- `false`: Don't connect using SSL (default)
- `true`: Connect using SSL, validating the SSL certificates. Self-signed certificates will fail using this approach.
- `no-verify`: Connect using SSL, but don't validate the certificates.
Other SSL options will require the use of a custom connection string. Evidence uses the node-postgres package to manage these connections, and the details of additional SSL options via the connection string can be found at the [package documentation](https://node-postgres.com/features/ssl).
One scenario might be a Postgres platform that issues a self-signed certificate for the database connection, but provides a CA certificate to validate that self-signed certificate. In this scenario you could use a CONNECTION STRING value as follows:
```markdown
postgresql://{user}:{password}@{host}:{port}/{database}?sslmode=require&sslrootcert=/path/to/file/ca-certificate.crt
```
Replace the various `{properties}` as needed, and replace `/path/to/file/ca-certificate.crt` with the path and filename of your certificate.
Currently the UI does not support adding ssl with client certificates as authentication method. If you want to use this, you need to manually change your connection.yaml to:
```yaml
name: mydatabase
type: postgres
options:
host: example.myhost.com
port: 5432
database: mydatabase
ssl:
sslmode: require
```
and your connection.options.yaml to:
```yaml
user: "USERNAME_AS_BASE64"
ssl:
rejectUnauthorized: true
key: "USER_KEY_AS_BASE64"
cert: "USER_CERT_AS_BASE64"
```
Here you encode the full user key and cert file as base64 and put them in the correct options. If you do not want to verify the server certificate, for example because you have a self signed certificate, then change rejectUnauthorized to false.
### Trino
#### Supported Authentication Types
While Trino supports multiple [authentication types](https://trino.io/docs/current/security/authentication-types.html), the connector does currently only support the password based ones. Behind the scenes, the connector is using [Basic access authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) for communicating with Trino.
#### HTTPS
To connect to a Trino installation that is accessible via HTTPS, you need to set the SSL option to `true` and the port to `443`/`8443` (unless you are using a non standard port for HTTPS, in which case you should use that instead).
#### Starburst Quickstart
[Starburst](https://www.starburst.io/), the company behind Trino, offers a SAAS solution where they run Trino for you. Once you have signed up and created a Trino cluster, you should be able to connect Evidence with the following configuration:
Host: `-.galaxy.starburst.io`
Port: `443`
User: `/accountadmin`
SSL: `true`
Password: The password you use to login to your Starburst account
Alternatively, you can also create a service account at `https://.galaxy.starburst.io/service-accounts` and use this to connect.
### Microsoft SQL Server
#### Trust Server Certificate
The `trustServerCertificate` option indicates whether the channel will be encrypted while bypassing walking the certificate chain to validate trust. This option is disabled by default.
#### Encrypt
The `encrypt` option indicates whether SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed. Necessary for Azure databases.
#### Connection Timeout
The `connection_timeout` option indicates the connection timeout limit, in milliseconds. It defaults to 15000 ms.
#### Request Timeout
The `request_timeout` option indicates the time, in milliseconds, that a query can run before it is terminated. It defaults to 15000 ms.
### MySQL
#### SSL
SSL options are:
- `false` (default)
- `true`
- `Amazon RDS`
- A credentials object
### SQLite
SQLite is a local file-based database. The SQLite file should be stored in the directory `sources/[your_source_name]/`.
### DuckDB
DuckDB is a local file-based database. If using a persistent database, it should be stored in the directory `sources/[your_source_name]/`.
See the [DuckDB docs](https://duckdb.org/docs/guides/index) for more information.
### MotherDuck
[Motherduck](https://motherduck.com) is a cloud-based DuckDB database.
To connect to MotherDuck, you will need a [service token](https://motherduck.com/docs/authenticating-to-motherduck/#authentication-using-a-service-token).
### Databricks
Databricks is a cloud-based data lake. Evidence supports connecting to Databricks using a [personal access token](https://docs.databricks.com/en/dev-tools/auth.html#generate-a-token).
### Cube
Cube offers semantic layer for your data. You can connect using the [Cube SQL API](https://cube.dev/docs/product/apis-integrations/sql-api).
Cube's API is PostgreSQL compatible, so you can use the Evidence PostgreSQL connector to connect to Cube.
You can find the credentials to connect to Cube on the BI Integrations page under the SQL API Connection tab (you may need to enable the SQL API first).
### Google Sheets
The Google Sheets data source is a plugin, you first need to [install the plugin](https://github.com/evidence-dev/datasources/tree/main/gsheets#adding-the-adapter-to-evidence).
Adding data from Google Sheets requires a a [service account](https://cloud.google.com/iam/docs/service-accounts).
To create a service account, see the [BigQuery instructions](#bigquery).
1. Create a service account, and download the JSON key file
2. Give the service account access to your Google Sheet by sharing the sheet with the service account's email address.
4. Add the JSON key file to your Evidence app via the [Settings page](http://localhost:3000/settings)
5. In the connections.yaml file, add the sheet id (which can be found in the URL of the Google Sheet, after `https://docs.google.com/spreadsheets/d/`).
```yaml
name: [your_source_name]
type: gsheets
options: {}
sheets:
[your_workbook_name]: [your_sheet_id]
```
Query the sheet using the following syntax:
```sql
select * from [your_source_name].[your_workbook_name]_[your_tab_name]
```
Where `[your_tab_name]` is the name of the tab in your Google Sheet, with spaces replaced by underscores.
### CSV files
In Evidence, you can query local CSV files directly in SQL.
Get started by selecting the `CSV` connector on the Settings page in your app, naming it and then clicking "confirm changes".
Then copy any CSV files you want to query into `sources/[your_csv_source_name]/`. Your source names and csv files can only contain letters, numbers and underscores eg `/my_source/my_csv_2024.csv`
The section below applies to both CSV and Parquet files.
#### How to Query a CSV File
Evidence looks for CSV files stored in a `sources/[your_csv_source_name]/` folder in the root of your Evidence project. You can query them using this syntax:
```sql
select * from your_csv_source_name.csv_file_name
```
#### Source Options
You can add [DuckDB source options](https://duckdb.org/docs/data/csv/overview.html) that are passed in as arguments to the `read_csv()` function.
Ensure there are no spaces in your source options you pass, and to use double quotes when passing strings
```sql source_options
select 'header=false' as "Option String", 'Reads the first line as the first row of data' as "Outcome", 0 as row_num UNION ALL
select 'delim="|"', 'Use "|" characters as delimiters when reading the csv', 1 UNION ALL
select 'header=false,delim="|"', 'Use both of these options', 2
order by row_num
```
## Troubleshooting
If you need help with connecting to your data, please feel free to [send us a message in Slack](https://slack.evidence.dev).
---
evidence/sites/docs/pages/core-concepts/themes/index.md
---
---
sidebar_position: 10
hide_table_of_contents: false
title: Themes
description: Customize the appearance of your Evidence application in light and dark mode using the theming system.
sidebar_badge: New
---
Customize the appearance of your Evidence application in light and dark mode.
# Appearance Modes
Evidence supports three appearance modes: light, dark, and system. By default, new Evidence apps use the system mode and allow users to switch to light or dark via the appearance switcher.
When the appearance is `system`, the user's preferred appearance from their operating system is used.
The default appearance configuration is listed below, as well as in the [Evidence Template](https://github.com/evidence-dev/templates/blob/main/evidence.config.yaml).
```yaml
appearance:
default: system
switcher: true
```
## Options
## Migration
To enable dark mode in an Evidence application created before themes was released, add the the following to your `evidence.config.yaml`:
```yaml
appearance:
default: system
switcher: true
```
# Theme
The theme configuration defines the colors used by your app.
The theme consists of 3 elements that define colors for different purposes:
- [Color palettes](#color-palettes) configure colors for charts with different data series (e.g. [Bar Charts](/components/bar-chart/#props-colorPalette)).
- [Color scales](#color-scales) configure color ranges for charts with continuous data (e.g. [Heatmaps](/components/heatmap/#props-colorScale)).
- [Colors](#colors) configure colors of UI elements (e.g. background, text, inputs).
You can pass any valid CSS color values to these properties (hexadecimal, RGB, HSL, named CSS colors, etc).
The default theme configuration is listed below, as well as in the [Evidence Template](https://github.com/evidence-dev/templates/blob/main/evidence.config.yaml).
```yaml
theme:
colorPalettes:
default:
light:
- "#236aa4"
- "#45a1bf"
- "#a5cdee"
- "#8dacbf"
- "#85c7c6"
- "#d2c6ac"
- "#f4b548"
- "#8f3d56"
- "#71b9f4"
- "#46a485"
dark:
- "#236aa4"
- "#45a1bf"
- "#a5cdee"
- "#8dacbf"
- "#85c7c6"
- "#d2c6ac"
- "#f4b548"
- "#8f3d56"
- "#71b9f4"
- "#46a485"
colorScales:
default:
light:
- "#ADD8E6"
- "#00008B"
dark:
- "#ADD8E6"
- "#00008B"
colors:
primary:
light: "#2563eb"
dark: "#3b82f6"
accent:
light: "#c2410c"
dark: "#fdba74"
base:
light: "#ffffff"
dark: "#09090b"
info:
light: "#0284c7"
dark: "#38bdf8"
positive:
light: "#16a34a"
dark: "#4ade80"
warning:
light: "#f8c900"
dark: "#fbbf24"
negative:
light: "#dc2626"
dark: "#f87171"
```
## Color Palettes
You can modify the default chart color palette, or create a custom palette for individual charts via their `colorPalette` prop.
Color palettes can have any number of colors listed. If a chart has more series than there are colors in a color palette, the colors will be reused.
### Default Color Palette
The `default` color palette is used by all series-based charts (e.g. [Bar Charts](/components/bar-chart/#props-colorPalette), [Line Charts](/components/line-chart/#props-colorPalette)).
You can configure the default color palette for light and dark mode individually (different colors for each):
```yaml
theme:
colorPalettes:
default:
light:
- "#1d4ed8"
- "#0f766e"
- "#a16207"
- "#c2410c"
- "#7e22ce"
dark:
- "#93c5fd"
- "#5eead4"
- "#fde047"
- "#fdba74"
- "#d8b4fe"
```
...or together (same colors for both):
```yaml
theme:
colorPalettes:
default:
- "#3b82f6"
- "#14b8a6"
- "#eab308"
- "#f97316"
- "#a855f7"
```
### Custom Color Palettes
You can define your own custom color palettes in the same way, just replace `default` with your color palette's name:
```yaml
theme:
colorPalettes:
myCustomPalette:
light:
- "#e11d48"
- "#be185d"
- "#6d28d9"
dark:
- "#fb7185"
- "#f9a8d4"
- "#c4b5fd"
```
Then use it in the `colorPalette` prop
```markdown
```
### Props
The `colorPalette` prop accepted by many components accepts a color palette in several different formats to reduce the friction of theming your app.
1. **Use a color palette name from your theme.** Its configured light and dark values will be used.
```markdown
```
2. **Use a list of color names from your theme.** Their configured light and dark values will be used.
```markdown
```
3. **Use a list of colors (e.g. hex codes).** They will be automatically converted to similar colors for dark mode.
```markdown
```
4. **Use a list of pairs of colors** to explicitly define light and dark mode values. The first column will be used when your application is in light mode, and the second when its in dark mode.
```markdown
```
## Color Scales
You can modify the default chart color palette, or create a custom palette for individual charts via their `colorScale` prop.
Color scales can have any number of colors listed. The colors will be blended into a gradient for values to interpolate from.
### Default Color Scale
The `default` color scale is used by charts that represent continuous data.
You can configure the default color palette for light and dark mode individually (different colors for each):
```yaml
theme:
colorScales:
default:
light:
- "#0d9488"
- "#4f46e5"
dark:
- "#5eead4"
- "#a5b4fc"
```
...or together (same colors for both):
```yaml
theme:
colorScales:
default:
- "#eab308"
- "#22c55e"
```
### Custom Color Scales
You can define your own custom color scales in the same way, just replace `default` with your color scale's name:
```yaml
theme:
colorScales:
myCustomScale:
light:
- "#f97316"
- "#ef4444"
dark:
- "#fdba74"
- "#fb7185"
```
Then use it in the `colorScale` prop
```markdown
```
### Props
The `colorScale` prop accepted by many components accepts a color scale in several different formats to reduce the friction of theming your app.
1. **Use a color scale name from your theme.** Its configured light and dark values will be used.
```markdown
```
2. **Use a list of color names from your theme.** Their configured light and dark values will be used.
```markdown
```
3. **Use a list of colors (e.g. hex codes).** They will be automatically converted to similar colors for dark mode.
```markdown
```
4. **Use a list of pairs of colors** to explicitly define light and dark mode values. The first column will be used when your application is in light mode, and the second when its in dark mode.
```markdown
```
## Colors
Evidence uses a fixed set of color "tokens" for all UI elements in the entire application. This allows you to create a customized look and feel with only a couple lines of configuration.
```sql color_tokens
select 'primary' as 'color', 'Represents your project/brand' as 'purpose', 'Logo color, buttons, links, DimensionGrid' as 'where-its-used' union all
select 'accent', 'Focuses your attention', 'Map selected state (Chart selected state coming soon!)' union all
select 'base', 'The base color of your application', 'Background and text colors' union all
select 'info', 'Provide information', 'Alerts, annotations' union all
select 'positive', 'Indicate something is good', 'Alerts, annotations, Delta indicator' union all
select 'warning', 'Warn readers', 'Alerts, annotations' union all
select 'negative', 'Indicate something is bad', 'Alerts, annotations, Delta indicator'
```
You can modify existing color tokens, or create your own to use in charts and other UI elements.
### Overriding Colors
You can override a color for light and dark mode individually (different colors for each):
```yaml
theme:
colors:
primary:
light: "#dc2626"
dark: "#f87171"
accent:
light: "#7c3aed"
dark: "#a78bfa"
```
...or together (same colors for both):
```yaml
theme:
colors:
primary: "#ef4444"
accent: "#a855f7"
```
### Defining Your Own Colors
You can define your own custom colors in the same way, just replace the color name with your custom color's name:
```yaml
theme:
colors:
myColor: "#10b981"
myOtherColor:
light: "#c026d3"
dark: "#f472b6"
```
Then use them in component props
```markdown
Tab 1 contentTab 2 content
```
```markdown
```
### Props
The color props accepted by many components (e.g. [`fillColor`](/components/bar-chart/#props-fillColor), [`labelColor`](/components/annotations/#props-labelColor)) accept a color in several different formats to reduce the friction of theming your app.
1. **Use a color name from your theme.** Its configured light and dark values will be used.
```markdown
```
2. **Use a single color (e.g. hex code).** It will be automatically converted to a similar color for dark mode.
```markdown
```
3. **Use a pair of colors** to explicitly define light and dark mode values. The first color will be used when your application is in light mode, and the second when its in dark mode.
```markdown
```
## Advanced
The [colors listed above](/core-concepts/themes/#colors) are the bare minimum you should configure to theme your application. If you need more control, there are other colors you can customize.
```sql advanced_color_tokens
select 'primary-content' as 'color', 'Text color used on top of a primary background' as 'where-its-used', 'A readable shade of primary' as default union all
select 'accent-content', 'Text color used on top of an accent background', 'A readable shade of accent' union all
select 'base-100', 'Page background color', 'Alias of `base`' union all
select 'base-200', 'Secondary page background color', 'A shade of base-100' union all
select 'base-300', 'Tertiary page background color', 'A shade of base-100' union all
select 'base-content-muted', 'Muted text color', 'A shade of base-100' union all
select 'base-content', 'Body text color', 'A shade of base-100' union all
select 'base-heading', 'Header text color', 'A shade of base-100' union all
select 'info-content', 'Text color used on top of an info background', 'A readable shade of info' union all
select 'positive-content', 'Text color used on top of a positive background', 'A readable shade of positive' union all
select 'warning-content', 'Text color used on top of a warning background', 'A readable shade of warning' union all
select 'negative-content', 'Text color used on top of a negative background', 'A readable shade of negative'
```
These colors are included in the [Tailwind](https://tailwindcss.com) configuration for your Evidence application, so you can use them in your own HTML elements or custom Svelte components.
Hello!
```markdown
Hello!
```
## Custom Styles
Evidence uses [Tailwind CSS](https://tailwindcss.com) to style Evidence components and markdown, and you can use Tailwind to add your own styles.
To style with Tailwind you add *classes* to HTML elements. You can use any HTML element in your markdown.
For more information on using Tailwind, see the [Tailwind documentation](https://tailwindcss.com/docs).
Tailwind removes styling from HTML elements by default, so should add your own styles to ``, `` etc.
### Using the Evidence Default Styles in Custom HTML
Adding the `markdown` class to an element will style it the same as Evidence markdown, e.g. ``.
### Examples
#### Customize Fonts
This is the default text style, which is used when you write text in a markdown file.
This red italic serif text is defined inside a HTML p (paragraph) element.
This is primary colored text using a monospace font, and a custom top margin.
```markdown
This is the default text style, which is used when you write text in a markdown file.
This red italic serif text is defined inside a HTML p (paragraph) element.
This is primary colored text using a monospace font, and a custom top margin.
```
---
evidence/sites/docs/pages/core-concepts/queries/index.md
---
---
sidebar_position: 4
title: SQL Queries
description: Markdown code fences run SQL queries, and return the results as data for components.
---
## Inline Queries
Evidence runs markdown code fences as SQL queries. These queries use the [DuckDB dialect](https://duckdb.org/docs/sql/introduction).
If you have a data source called `needful_things`, you run a query against it like this:
````markdown
```sql sales_by_category
select
category, sum(sales) as sales
from needful_things.orders
group by 1
```
````
When you open a page in dev mode, Evidence runs all of the queries on the page. In dev mode, Evidence monitors the contents of your SQL blocks, and reloads the page as necessary to reflect any changes you've made to your queries.
You include SQL queries in your page using a markdown code fence (starting and ending with 3 backticks). Evidence requires a query name to be supplied directly after the first 3 backticks.
### Using Query Results
Reference a query in a component using `data={query_name}`
For example, if your query name was `sales_by_category`:
```markdown
```
## Query Chaining
Reference other queries by writing the query name inside `${ }`.
For example, if you want to reference a query named `sales_by_item`, you would write `${sales_by_item}` into your SQL query, you would write:
````sql
```sql sales_by_item
select
item,
sum(sales) as sales
from needful_things.orders
group by 1
```
```sql average_sales
select
avg(sales) as average_sales
from ${sales_by_item}
```
````
Below is the compiled SQL that's sent to the database for `average_sales`:
```sql
select
avg(sales) as average_sales
from (
select
item,
sum(sales) as sales
from needful_things.orders
group by 1
)
```
### View Compiled SQL
You can choose whether you want to see the compiled or written SQL inside the query viewer:
![compiled-written-toggle](/img/compiled-written-toggle.gif)
### Ordering and Circular References
The order that queries appear on the page doesn't matter to the SQL compiler. You can reference queries that appear before or after the query that you are authoring.
Some SQL dialects require sub-queries to be aliased, including Postgres and MySQL. E.g. `from ${sales_by_item} as sales_by_item`.
The SQL compiler detects circular and missing references. If a query includes either a circular reference or a missing reference, Evidence will display an error that looks like a syntax error in a normal SQL query. Queries with compiler errors are not sent to your database.
![circular-error-single](/img/circular-error-single.png)
## SQL File Queries
Evidence also has support for queries outside the markdown, which is especially useful when you have a query that is being used on more than one page.
### Basic Usage
To use sql file queries, you need to place them in the `queries` directory, and then reference them in your [frontmatter](/reference/markdown/#frontmatter).
An example setup could be:
```
my-evidence-project/
pages/
my_page.md
queries/
my_file_query.sql
some_category/
my_category_file_query.sql
```
These queries can then be used on `my_page.md` with the following [frontmatter](/reference/markdown/#frontmatter)
```yaml
---
queries:
- q4_data: my_file_query.sql
- q4_sales_reps: some_category/my_category_file_query.sql
---
```
In your evidence file, you can now reference `q4_data` and `q4_sales_reps` the same way you would use any other query.
Optionally, you can omit the query name, and the filename will be used instead; these queries will be available at `my_file_query` and `some_category_my_category_file_query` (note that `/` became `_`).
```yaml
---
queries:
- my_file_query.sql
- some_category/my_category_file_query.sql
---
```
### Advanced Usage
#### File Query Chaining
SQL file queries can [depend on other query files](/core-concepts/queries/#query-chaining), but they will all need to be referenced in the files you use them in. For example, if `my_file_query` depends on `some_category_my_category_file_query`, then you will have to have them both in your [frontmatter](/reference/markdown/#frontmatter), as shown above.
## Query Parameters
Queries can accept parameters, which might be from an input component such as a [Dropdown](/components/dropdown), or from a URL parameter on a [template page](/core-concepts/templated-pages).
````markdown
```sql sales_by_month
select
date_trunc('month', date) as month,
sum(sales) as sales
from needful_things.orders
where category = '${inputs.category}'
group by 1
```
````
There are two types of parameters you can use in queries:
- **Input parameters** from components: `'${inputs.parameter_name}'`
- **URL parameters** from [templated pages](/core-concepts/templated-pages): `'${params.parameter_name}'`
---
evidence/sites/docs/pages/core-concepts/formatting/index.md
---
---
sidebar_position: 6
title: 'Value Formatting'
description: 'Number and date formatting options in Evidence'
---
The easiest way to format numbers and dates in Evidence is through component props. You can pass in any of the following:
- [Excel-style format codes](#excel-format-codes) (e.g., `fmt='$#,##0.0'`)
- Evidence's [built-in formats](#built-in-formats) (e.g., `fmt=usd2k`)
- [Custom defined formats](#custom-formats)
For example, you can use the `fmt` prop to format values inside a Value component:
```html
```
Within charts, you can format individual columns using `xFmt` and `yFmt` (and `sizeFmt` for bubble charts):
```html
```
In the example above, `xFmt` is passing in an Excel-style code to format the dates and `yFmt` is referencing a built-in format ([see the full list](#built-in-formats) of supported tags below, or [create your own](#custom-formats)).
**Date formatting**
Formatting does not apply to the date axis of a chart. For example, if you set `xFmt` to `m/d/yy`, you will only see that formatting reflected in your chart tooltips and annotations. This is to ensure that the chart axis labels have the correct spacing.
#### Reusable Formats
For a more reusable approach, you can use [SQL format tags](#sql-format-tags), which let you define formats within your SQL. This guarantees that your columns will be formatted in the same way wherever they are used in Evidence.
You can also create your own [custom formats](#custom-formats), which are format codes you can reuse across your project.
#### Formatting Directly in Markdown
If you need to format values outside of components, [the format function](#format-function) can be used directly. For example, when using [expressions](/core-concepts/syntax#expressions) it is not possible to use component props or format tags.
## Excel Format Codes
Evidence supports [Excel-style custom format codes](https://support.microsoft.com/en-us/office/number-format-codes-5026bbd6-04bc-48cd-bf33-80f18b4eae68), which can be passed directly to a component prop, the [format function](#format-function), or saved as a [custom format code](#custom-formats) that you want to reuse.
**Strings inside formats codes**
Some Excel format codes include strings: use double-quotes for the string, and single-quotes to surround the whole format code.
E.g., `fmt = '#,##0.00 "mpg"'`
## Built-in Formats
Evidence supports a variety of date/time, number, percentage, and currency formats. You can find the full list of formats below.
### Auto-Formatting
Wherever you see `auto` listed beside a format, that means Evidence will automatically format your value based on the context it is in.
For example, Evidence automatically formats large numbers into shortened versions based on the size of the median number in a column (e.g., 4,000,000 → 4M).
You can choose to handle these numbers differently by choosing a specific format code. For example, if Evidence is formatting a column as millions, but you want to see all numbers in thousands, you could use the `num0k` format, which will show all numbers in the column in thousands with 0 decimal places.
### Dates
```sql date_formats
select 'ddd' as format_name, 'ddd' as format_code, '2022-01-09 12:45' as example_input, 'Sun' as example_output, 0 as row_num union all
select 'dddd', 'dddd', '2022-01-09 12:45', 'Sunday', 1 union all
select 'mmm', 'mmm', '2022-01-09 12:45', 'Jan', 2 union all
select 'mmmm', 'mmmm', '2022-01-09 12:45', 'January', 3 union all
select 'yyyy', 'yyyy', '2022-01-09 12:45', '2022', 4 union all
select 'shortdate', 'mmm d/yy', '2022-01-09 12:45', 'Jan 9/22', 5 union all
select 'longdate', 'mmmm d, yyyy', '2022-01-09 12:45', 'January 9, 2022', 6 union all
select 'fulldate', 'dddd mmmm d, yyyy', '2022-01-09 12:45', 'Sunday January 9, 2022', 7 union all
select 'mdy', 'm/d/y', '2022-01-09 12:45', '1/9/22', 8 union all
select 'dmy', 'd/m/y', '2022-01-09 12:45', '9/1/22', 9 union all
select 'hms', 'H:MM:SS AM/PM', '2022-01-09 12:45', '11:45:03 AM', 10
order by row_num
```
### Currencies
Supported currencies:
```sql currency_formats
select 'usd' as code, 'United States Dollar' as currency, 0 as row_num union all
select 'aud', 'Australian Dollar', 1 union all
select 'brl', 'Brazilian Real', 2 union all
select 'cad', 'Canadian Dollar', 3 union all
select 'cny', 'Renminbi', 4 union all
select 'eur', 'Euro', 5 union all
select 'gbp', 'Pound Sterling', 6 union all
select 'jpy', 'Japanese Yen', 7 union all
select 'inr', 'Indian Rupee', 8 union all
select 'krw', 'South Korean Won', 9 union all
select 'ngn', 'Nigerian Naira', 10 union all
select 'rub', 'Russian Ruble', 11 union all
select 'sek', 'Swedish Krona', 12
order by row_num
```
In order to use currency tags, use the currency code, optionally appended with:
- a number indicating the number of decimal places to show (0-2)
- a letter indication the order of magnitude to show ("","k", "m", "b")
For example, the available tags for USD are:
```sql usd_formats
select 'usd' as format_name, 'auto' as format_code, 412.17 as example_input, '$412' as example_output, 0 as row_num union all
select 'usd0', '$#,##0', '7043.123', '$7,043', 1 union all
select 'usd1', '$#,##0.0', '7043.123', '$7,043.1', 2 union all
select 'usd2', '$#,##0.00', '7043.123', '$7,043.12', 3 union all
select 'usd0k', '$#,##0,"k"', '64301.12', '$64k', 4 union all
select 'usd1k', '$#,##0.0,"k"', '64301.12', '$64.3k', 5 union all
select 'usd2k', '$#,##0.00,"k"', '64301.12', '$64.30k', 6 union all
select 'usd0m', '$#,##0,,"M"', '4564301.12', '$5M', 7 union all
select 'usd1m', '$#,##0.0,,"M"', '4564301.12', '$4.6M', 8 union all
select 'usd2m', '$#,##0.00,,"M"', '4564301.12', '$4.56M', 9 union all
select 'usd0b', '$#,##0,,,"B"', '9784564301.12', '$10B', 10 union all
select 'usd1b', '$#,##0.0,,,"B"', '9784564301.12', '$9.8B', 11 union all
select 'usd2b', '$#,##0.00,,,"B"', '9784564301.12', '$9.78B', 12
order by row_num
```
### Numbers
The default number format (when no `fmt` is specified) automatically handles decimal places and summary units (in the same way that `usd` does for currency).
```sql number_formats
select 'num0' as format_name, '#,##0' as format_code, '11.23168' as example_input, '11' as example_output, 0 as row_num union all
select 'num1', '#,##0.0', '11.23168', '11.2', 1 union all
select 'num2', '#,##0.00', '11.23168', '11.23', 2 union all
select 'num3', '#,##0.000', '11.23168', '11.232', 3 union all
select 'num4', '#,##0.0000', '11.23168', '11.2317', 4 union all
select 'num0k', '#,##0,"k"', '64201', '64k', 5 union all
select 'num1k', '#,##0.0,"k"', '64201', '64.2k', 6 union all
select 'num2k', '#,##0.00,"k"', '64201', '64.20k', 7 union all
select 'num0m', '#,##0,,"M"', '42539483', '43M', 8 union all
select 'num1m', '#,##0.0,,"M"', '42539483', '42.5M', 9 union all
select 'num2m', '#,##0.00,,"M"', '42539483', '42.54M', 10 union all
select 'num0b', '#,##0,,,"B"', '1384937584', '1B', 11 union all
select 'num1b', '#,##0.0,,,"B"', '1384937584', '1.4B', 12 union all
select 'num2b', '#,##0.00,,,"B"', '1384937584', '1.38B', 13 union all
select 'id', '0', '921594675', '921594675', 14 union all
select 'fract', '# ?/?', '0.25', '1/4', 15 union all
select 'mult', '#,##0.0"x"', '5.32', '5.3x', 16 union all
select 'mult0', '#,##0"x"', '5.32', '5x', 17 union all
select 'mult1', '#,##0.0"x"', '5.32', '5.3x', 18 union all
select 'mult2', '#,##0.00"x"', '5.32', '5.32x', 19 union all
select 'sci', '0.00E+0', '16546.1561', '1.65E+4', 20
order by row_num
```
### Percentages
```sql percentage_formats
select 'pct' as format_name, 'auto' as format_code, 0.731 as example_input, '73.1%' as example_output, 0 as row_num union all
select 'pct0', '#,##0%', 0.731, '73%', 1 union all
select 'pct1', '#,##0.0%', 0.731, '73.1%', 2 union all
select 'pct2', '#,##0.00%', 0.731, '73.10%', 3 union all
select 'pct3', '#,##0.000%', 0.731, '73.100%', 4
order by row_num
```
## Custom Formats
Custom formats can be added in the Value Formatting Section of the Evidence Settings.
With custom formats, you define the format you want to use (using [Excel style custom format codes](https://support.microsoft.com/en-us/office/number-format-codes-5026bbd6-04bc-48cd-bf33-80f18b4eae68)), and give the format a name (e.g., `mydate`). That format name will now be accessible in any place you can format your data in Evidence. For example:
```html
```
## SQL Format Tags
SQL format tags let you define formats for your columns within your SQL query. This ensures that columns are formatted in the same way wherever they are used.
A **format tag** is appended to your column name with an underscore: for example, to append the percentage format to a column named `growth`, it would be `growth_pct`.
Formatting can be configured in the Value Formatting Section of the Evidence Settings.
Format tags are case-insensitive, so `growth_pct` and `GROWTH_PCT` are equivalent.
### Title Formatting
When creating a table, Evidence formats column titles based on the name of the column and its format tag. Format tags that do not add to the meaning of the column name are not printed as part of the title. All columns are printed with proper casing.
#### Examples
```sql title_formats
select 'sales_usd' as column_name, 'Sales ($)' as formatted_title, 0 as row_num union all
select 'customer_id', 'Customer ID', 1 union all
select 'growth_pct', 'Growth', 2 union all
select 'customer_number_num2k', 'Customer Number', 3
order by row_num
```
## Format Function
The format function is used to format expressions within markdown. This is useful when you cannot use a component.
The syntax is:
```javascript
{fmt(expression, formatCode)}
```
`formatCode` can be any one of the following:
- An Excel-style format code (e.g., `$#,##0.0`)
- A built-in Evidence format (e.g., `eur`)
- A custom-defined format code (see section above on custom formats)
### Example
In the below example, we return a value from a calculation. In this situtation we cannot use the `Value` component, which only accepts a single row. Instead we use the `Format` function to format the result.
````markdown
```sql sales_per_year
select
date_part('year', order_datetime) AS year,
sum(sales) AS total_sales
from needful_things.orders
group by year
order by year desc
```
Sales are {fmt(sales_per_year[0].total_sales - sales_per_year[1].total_sales, '+#,##0;-#,##0')} vs last year.
````
---
evidence/sites/docs/pages/core-concepts/components/index.md
---
---
sidebar_position: 5
title: Components
description: Components are used to display charts and other visual elements
---
## What are Components?
Evidence has a built in [component library](/components/all-components) to create charts and other visual elements.
Components use angle brackets (`<.../>`) to wrap the component name, like HTML syntax. Data from a query, and configuration options are passed in as properties, or "props":
```html
```
![Category Bar Chart](/img/category-chart.png)
## Showing Values in Text
The simplest component is the `` component. It displays a single value from a query. It can be used to put automatically updated values in text.
````markdown
```sql orders
SELECT
'2021-01-01' AS date,
100 AS num_orders
```
The number of orders yesterday was .
````
Above, we've passed in the query data `orders` in curly braces `{ }`, and specified the column we want to display `num_orders` in the `column` prop.
For more information on the `Value` component, see the [Value docs](/components/value).
## Charts
Our chart library has a flexible, declarative API that lets you add default chart types, or create your own.
While our library offers a lot of customizable features, we include sensible defaults that look good out of the box.
### Props and defaults
At a minimum, all charts require a data prop, but for other props Evidence has default assumptions to reduce the amount of configuration required.
**Data**
- All charts require a data prop, which should contain a query result wrapped in `{...}` (e.g., `data={query_name}`)
**x and y**
- All x-y coordinate (AKA Cartesian) charts require `x` and `y` columns to create the axes and scales for the chart
- `y` can accept multiple columns, but can only plot on a single axis at this time.
- We have built-in assumptions to make writing the chart code easier:
- If you don't supply `x`, the first column in the dataset is assumed to be `x`
- If you don't supply `y`, any numerical columns that you have not already assigned to the chart are assumed to be `y`
**Multiple Series**
- To plot multiple series (or groups) on your chart, you can do one of the following (or both):
- Include a `series` column, which contains category or group names (e.g, `series=country`)
- Include multiple `y` columns - each column will be treated as an individual series (e.g., `y={["y1", "y2"]}`)
### Annotations
Charts can include [annotations](/components/annotations) using the `ReferenceLine` and `ReferenceArea` components. These components are used within a chart component like so:
```html
```
## Custom Components
You can also build your own reusable data viz or UI components in Evidence. See [the Custom Component Guide](/components/custom-components) for more details.
---
evidence/sites/docs/pages/core-concepts/pages/index.md
---
---
sidebar_position: 2
title: Pages
description: Evidence renders markdown files into web pages.
---
Evidence renders markdown files into web pages. When developing, the markdown file `/pages/example.md` is rendered at [localhost:3000/example](http://localhost:3000/example).
Evidence instantly reloads pages when their markdown files are edited and saved.
## File Based Routing
The URL to access a page is determined by the path to the markdown file in the `/pages` directory:
- `pages/index.md` is the homepage
- `pages/weekly-sales.md` creates the `/weekly-sales` page
- `pages/marketing/attribution.md` creates the `/marketing/attribution` page
This allows you to organize your pages in a way that makes sense for your users, for example:
- by department
- by product
- by customer
- by time period
## Templated Pages
- `pages/customers/[customer].md` creates a page for each customer using the `[customer].md` template. See [templated pages](/core-concepts/templated-pages) for details.
## Frontmatter
You can include page metadata, such as a title, using [frontmatter](/reference/markdown#frontmatter).
---
evidence/sites/docs/pages/core-concepts/if-else/index.md
---
---
title: If / Else
sidebar_position: 8
description: Control what is displayed using data with conditional logic.
---
Programmatically control what is displayed using data through `{#if}` and `{:else}` blocks.
## If and Else Statements
Conditionals are useful for managing information overload, and ensuring that your reporting is consistently showing actionable information.
Conditionals allow you to show a section of your document if a condition is met. You can optionally include `{:else}` and `{:else if}` blocks inside of your `{#if}...{/if}` blocks.
```javascript
{#if condition}
Display some content.
{:else if another condition}
Another thing instead.
{:else }
Something completely different.
{/if}
```
## Example
Hide a table if it is empty.
```javascript
{#if query_name.length !== 0}
{/if}
```
## Another Example
Imagine creating reports to encourage sales leaders "up-sell" low margin customers, but only when there were enough low-margin customers to do that work in-bulk. This could be done using a conditional.
```javascript
{#if low_margin_customers.length > 15}
The following customers are generating low margins.
Consider re-allocating an account management call block to up-sell these customers.
{:else }
There are fewer than fifteen low margin customers, which is not enough to fill a call block.
{/if}
```
---
evidence/sites/docs/pages/core-concepts/loops/index.md
---
---
title: Loops
sidebar_position: 7
description: Create repeating elements by looping through data.
---
Create repeating elements by looping through data with `{#each}` blocks. Note that curly braces `{...}` execute JavaScript expressions in Evidence.
## Each Loops
Loops enable you to iterate over the rows in a query result, and reference the row using an alias of your choosing. They are similar to for loops in Python.
```markdown
{#each query_name as alias}
{alias.column_name}
{/each}
```
If you have more content than you would like to loop over on a single page, consider using a [templated page](/core-concepts/templated-pages).
## Example
Imagine you were creating a report on the performance of your organization's cities. You could use a loop to generate a section of your report for each city. When a new city appears in your query results, a new section will appear in your report.
The following table is being returned by the query `location_summary`
```sql location_summary
SELECT 1 as id, 'New York' as name, 9000 as sales_usd, 0.60 as gross_margin_pct UNION ALL
SELECT 2, 'Los Angeles', 5000, 0.45 UNION ALL
SELECT 3, 'Toronto', 4000, 0.70
```
By using an `{#each}` block, we can iterate over each of the rows in `location_summary`, and reference the current row with the alias `city`. Here we'll create a header, and a paragraph for each of the three locations.
```markdown
Daily sales:
{#each location_summary as city}
## {city.name}
in sales at a gross margin.
{/each}
```
Which would result in the following output
> Daily sales:
>
> ** New York **
>
> $9,000 in sales at a 60% gross margin.
>
> ** Los Angeles **
>
> $5,000 in sales at a 45% gross margin.
>
> ** Toronto **
>
> $4,000 in sales at a 70% gross margin.
---
evidence/sites/docs/pages/core-concepts/exports/index.md
---
---
title: Exports
description: Export data to PDF, CSV, images and using copy-paste.
sidebar_position: 12
---
Evidence supports exporting data and reports to PDF, images, CSVs and using copy-paste.
All of these options are available in both `dev` and `prod` environments.
## PDF
Evidence supports exporting individual pages to PDFs.
Open the option menu in the top-right of the page, and select "Export PDF".
This will open a dialog where you can adjust the format and save.
The PDF reflects the current state of the page - for example if queries are shown, then they will be included in the PDF.
## CSV
Data can be exported as CSV files, using the "Download Data" option in the bottom right of a component.
To see the download option, hover over the component. The following components support CSV downloads:
- Query results
- Tables
- Chart components
The for chart components, the CSV downloaded will match the query that was used in the component.
## Image (PNG)
Charts can be exported as `.png` files, using the "Download image" option in the bottom right of a component.
To see the download option, hover over the component.
## Copy-Paste
You can copy content from Evidence pages and paste it into other applications that support rich text, such as email, Google Docs, and Microsoft Word.
Cmd+A (Mac) or Ctrl+A (Windows) will select all content in the page, excluding the header, footer and sidebar.
---
evidence/sites/docs/pages/core-concepts/syntax/index.md
---
---
title: Syntax
description: Extended markdown with additional functionality.
sidebar_position: 1
---
Evidence reports are written in **Evidence-flavored Markdown** - an extension of markdown that includes SQL queries, data viz components, and programmatic features.
If you're not familiar with markdown, it's a simple text-based syntax - you've used markdown if you've written comments in Github or typed a message in Slack.
## Markdown
Evidence supports almost all Markdown syntax. See [Markdown Reference](/reference/markdown).
```markdown
---
title: Evidence uses Markdown
---
Markdown can be used to write expressively in text.
- it supports lists,
- **bolding**, _italics_ and `inline code`,
- links to [external sites](https://google.com) and other [Evidence pages](/another/page)
## Images 🖼️
Evidence looks for images in your `static` folder, e.g. `static/my-logo.png`.
![Company Logo](/my-logo.png)
```
## SQL
Code fences in Evidence markdown files run inline queries and return data. These code fences run the [DuckDB SQL](https://duckdb.org/docs/sql/introduction) dialect. [More on Queries](/core-concepts/queries).
````markdown
```sql orders_by_month
select
date_trunc('month', order_datetime) as order_month,
count(*) as number_of_orders,
sum(sales) as sales_usd
from needful_things.orders
group by 1, order by 1 desc
```
````
## Components
Evidence has a built in [component library](/components/all-components) to create charts and other visual elements. [More on Components](/core-concepts/components).
```markdown
```
![Line Chart](/img/syntax-line-chart.png)
## Loops
Create repeating elements by looping through data. [More on Loops](/core-concepts/loops).
```markdown
{#each orders_by_month as month}
- There were orders in .
{/each}
```
## If / Else
Control what is displayed using data through if and else statements. [More on If / Else](/core-concepts/if-else).
```javascript
{#if orders_by_month[0].sales_usd > orders_by_month[1].sales_usd}
Sales are up month-over-month.
{:else}
Sales are down vs last month. See [category detail](/sales-by-category).
{/if}
```
## Page Variables
There are a number of variables available to access information about the current page. These are particularly useful when creating templated pages and filters. They use the syntax `{$...}`
```markdown
The current page path is: {$page.route.id}
```
## Frontmatter
Use frontmatter to reference SQL queries, configure how titles, breadcrumbs and the sidebar are displayed, and to set open graph metadata for link previews on X, LinkedIn, Slack, Facebook etc.
See the [Frontmatter Reference](/reference/markdown#frontmatter).
```markdown
---
title: Evidence uses Markdown
description: Evidence uses Markdown to write expressively in text.
og:
image: /my-social-image.png
queries:
- orders_by_month.sql
---
```
## Expressions
Curly braces execute JavaScript expressions.
```markdown
2 + 2 = {2 + 2}
There are {orders.length} months of data.
There were {orders_by_month[0].number_of_orders} orders last month.
```
## Code Fences in Other Languages
It can be useful to include code that isn't SQL, eg for documentation or examples.
If a code fence is named one of the [reserved language names](https://github.com/evidence-dev/evidence/blob/main/packages/lib/preprocess/src/utils/supportedLanguages.cjs), such as `python` or `r`, the code fence will render a code block. The code is _not_ executed.
````markdown
```python
names = ["Alice", "Bob", "Charlie"]
for name in names:
print("Hello, " + name)
```
````
## Partials
Partials allow you to reuse chunks of Evidence markdown. [More on Partials](/reference/markdown#partials).
`./pages/index.md`
```markdown
{@partial "my-first-partial.md"}
And some content specific to this page.
```
`./partials/my-first-partial.md`
```markdown
# This is my first partial
This is some content in the partial.
```
---
evidence/sites/docs/pages/core-concepts/templated-pages/index.md
---
---
title: Templated Pages
description: Use a single file as a template for many pages with different data.
sidebar_position: 10
---
Templated pages allow you to use a single markdown file as a template for many pages with different data. For example:
1. `customers/[customer].md` -> One page per customer
1. `countries/[country].md` -> One page per country
1. `weekly-reports/week-[week_num].md` -> One page per time period
1. `categories/[category]/[product].md` -> One page per product [nested](#nesting-templated-pages) in its category
In example 1 above, www.example.com/customers/acme would display information for Acme, while www.example.com/customers/contoso would display information for Contoso.
A useful reference can be found in the [Needful Things example app](https://github.com/evidence-dev/demo/tree/main/pages/operations/pick_lists).
## Quickstart: VS Code Extension
1. **Create a [SQL file query](/core-concepts/queries/#sql-file-queries) in your queries folder**. It should return:
- **One row per page** you want to generate
- **A column containing a unique name or id** for each page
- **Other columns containing data you want** to use in the pages
2. **Run `Evidence: Create Templated Pages from Query`** in the the Command Palette (Ctrl/Cmd+Shift+P).
3. **Enter the column name that contains your unique id** into the box that appears.
Evidence will automatically create a templated page that changes for each unique id, and an index page containing links for each page.
E.g. if your query was called `customers.sql` and contained a unique column called `customer` then the following files would be created:
```code title="Example Files Created"
pages/
`-- customers/
|-- [customer].md
`-- index.md
```
This serves as a helpful starting point, and you will likely want to customize the code in the newly created files.
## Full Guide of Concepts
### Declaring a templated page
A templated page is created by adding square brackets round a file name `[parameter_name].md` or folder name `[parameter_name]`.
The following are equivalent:
- `pages/customers/[customer].md`
- `pages/customers/[customer]/index.md`
The string inside the square brackets becomes a [parameter](#using-page-parameters) you can reference in the page, with the parameter value as text that replaces the parameter name in the URL.
### Using page parameters
The parameter passed in the URL can be used in the page. For example, if the URL is `/customers/acme`, the parameter value is `acme`, and you access it in markdown as follows:
```javascript
{params.customer}
```
Parameters can be used in queries to filter query results (e.g. a for specific customer)
````sql
```sql customers
select
sum(sales) as sales_usd
from needful_things.orders
where first_name = '${params.customer}'
group by 1
```
````
Adding this to a `` component:
```javascript
```
### Generating templated pages
So far, we've created the template for a set of pages, but haven't specified what specific pages to create, or to put it another way, what values we want the parameter to take.
For a page to be built, there must be links to it somewhere in your app.
Whilst you could add markdown style links for each parameter value, it is easier to programmatically generate them. Two easy options are:
#### 1. With a `` and the `link` prop
Create a link per row in the SQL query and pass it to the ``.
````markdown
```sql customers
select
customer_name,
'/customers/' || customer_name as customer_link,
sum(sales) as sales_usd
from needful_things.orders
group by 1
```
````
#### 2. With an `{#each}` loop
````markdown
```sql customers
select
customer_name,
sum(sales) as sales_usd
from needful_things.orders
group by 1
```
{#each customers as customer}
- [{customer.customer_name}](/customers/{customer.customer_name})
{/each}
````
### Nesting templated pages
Creating folders with parameters can be useful when nesting inside templated pages:
```
pages/
`-- customers/
`-- [customer]/
|-- index.md
`-- [branch].md
```
Now `index.md` would be rendered if you navigate to www.example.com/customers/acme, and `[branch].md` would be rendered if you navigate to www.example.com/customers/acme/south.
## Complete Example Code
See a complete example using a table to generate a templated page for each customer.
`index.md`
````markdown
# Customers
```sql customers
select
first_name,
'/customers/' || first_name as customer_link,
sum(sales) as sales_usd
from needful_things.orders
group by 1
```
````
`customers/[customer].md`
````markdown
# {params.customer}
```sql customers
select
sum(sales) as sales_usd
from needful_things.orders
where first_name = '${params.customer}'
group by 1
```
{params.customer} bought items worth .
````
---
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:
![Evidence landing page](/img/getting-started/evidence_landing.png)
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:
![New page in Evidence](/img/getting-started/new_page.png)
### 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](https://docs.evidence.dev/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:
![alt text](https://evidence.dev/brand-assets/wordmark-black.png)
This is an image inserted using HTML:
```
Here's how it will look when rendered in the browser:
![Markdown rendered in Evidence.](/img/getting-started/markdown_html.png)
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.
![The Evidence settings page.](/img/getting-started/duck_db.png)
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:
![Add new source](/img/getting-started/my_query_summary_grey_box.png)
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-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/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**:
![Add new source](/img/getting-started/add_new_source.png)
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:
![Add new source](/img/getting-started/add_new_source2.png)
You can read about various configuration options for CSV files [here](https://docs.evidence.dev/core-concepts/data-sources/#csv-files). For now, leave this blank, and hit **Confirm Changes**:
![Add new source](/img/getting-started/add_new_source_confirm_changes.png)
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/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/plugins/index.md
---
---
title: Plugins
sidebar_position: 4
sidebar_link: false
---
---
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.plugins.yaml` to register it in your project.
```yaml
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/create-source-plugin/index.md
---
---
title: Create Data Source Plugin
description: Walkthrough on 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/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/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.plugins.yaml` to register it in your project.
```yaml
components:
@evidence-dev/core-components: {}
databases:
@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.
The easiest way to get started is from the example component library [**on GitHub**](https://github.com/evidence-dev/labs), 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 2 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/reference/index.md
---
---
sidebar_position: 5
sidebar_link: false
---
---
evidence/sites/docs/pages/reference/markdown/index.md
---
---
title: Markdown
hide_title: true
sidebar_position: 1
description: Evidence supports most markdown syntax. Below are some of the most common markdown features.
---
# Markdown Reference
Evidence supports most markdown syntax. Below are some of the most common markdown features. For more details, check out [Markdown Guide](https://www.markdownguide.org/cheat-sheet/).
## Text Paragraphs
```markdown
This is a paragraph. It can be as long as you want.
Add line breaks by leaving a blank line between paragraphs.
```
## Text Styles
```markdown
**Bold** text is wrapped in double asterisks
_Italic_ text is wrapped in single asterisks
~~Strikethrough~~ text is wrapped in double tildes
`Inline code` is wrapped in backticks
```
## Lists
```markdown
- This is a unordered list
- It uses dashes
- To indicate items
1. This is an ordered list
1. It uses numbers to indicate order
1. The numbers you type don't matter, they will be automatically numbered
```
## Headers
```markdown
# H1 Header
## H2 Header
### H3 Header
#### H4 Header
##### H5 Header
###### H6 Header
```
## Links
```markdown
[External link](https://google.com)
[Internal link](another/page/)
```
## Images
```markdown
![An online image](https://i.imgur.com/xyI27iZ.gif)
![An image stored in the project's static folder](/my-image.png)
```
#### Storing Images and Static Files
Evidence looks for images in the `/static` folder in the root of your project. Create it if it doesn't exist.
```
+-- pages/
| `-- index.md
`-- static/
`-- my-image.png
```
## Code Fences
In Evidence, most code fences execute SQL queries and display the results in a table.
````markdown
This code fence will execute a SQL query and display the results:
```sql orders
SELECT *
FROM needful_things.orders
WHERE category = 'Sinister Toys'
```
````
The exception is if you use one of the [reserved language names](https://github.com/evidence-dev/evidence/blob/main/packages/lib/preprocess/src/utils/supportedLanguages.cjs), which will render the code in a code block.
````markdown
```python
names = ["Alice", "Bob", "Charlie"]
for name in names:
print("Hello, " + name)
```
```r
names <- c("Alice", "Bob", "Charlie")
for (name in names) {
print(paste("Hello, ", name))
}
```
````
## Tables
```markdown
| Column 1 | Column 2 | Column 3 |
| -------- | -------- | -------- |
| Row 1 | Row 1 | Row 1 |
| Row 2 | Row 2 | Row 2 |
```
To display data in a table, use a [Data Table](/components/data-table) instead.
## Blockquotes
```markdown
> This is a blockquote
>
> It can span multiple lines
>
> > And can be nested
```
> This is a blockquote
>
> It can span multiple lines
>
> > And can be nested
## Horizontal Rule
```markdown
Below is a horizontal rule
---
```
Below is a horizontal rule
---
## Frontmatter
Frontmatter does not support Javascript statements at this time; and things may behave unexpectedly if wrapped in `{}`
To attach metadata (e.g. a title) to your page, you can use Frontmatter. Note that frontmatter _must_ appear as the first thing in your page; no content can come before it, or it won't be loaded properly.
Frontmatter is formatted like this:
```markdown
---
title: Evidence Docs
---
```
You can put whatever data you would like here, and it uses a [yaml syntax](https://yaml.org/), but some properties are special:
Specify a query that returns a column named breadcrumb. The query can use `${params.my_param}` to reference the URL parameters for the page.
E.g.
`breadcrumb: "select customer_name as breadcrumb from customers_table where customer_id = ${params.customer_id}"`
Anything outside of these values won't do anything on their own, but they will be accessible as [variables](/core-concepts/syntax/#expressions) on the page.
## Partials
Partials do not support live reload, or hot module replacement. You will need to refresh the page when you change a partial.
`./pages/index.md`
```markdown
{@partial "my-first-partial.md"}
And some content specific to this page.
```
`./partials/my-first-partial.md`
```markdown
# This is my first partial
This is some content in the partial.
```
Evidence supports re-using chunks of Evidence markdown using Partials.
Partials are placed in the `./partials` folder, and can be referenced in your markdown with `{@partial "path/to/partial.md"}` (do not include the `/partial` folder in the path).
---
evidence/sites/docs/pages/reference/layouts/index.md
---
---
sidebar_position: 4
hide_table_of_contents: false
title: Layouts
description: Customize the layout of your app by overwriting or modifying the default layout.
---
Customize the layout of your app by overwriting or modifying the default layout.
## Custom Layout
Evidence will use any `+layout.svelte` file in the `/pages` directory to override the default layout.
Creating a Custom Layout
The recommended approach is to copy and edit the default layout file
```bash
cp .evidence/template/src/pages/+layout.svelte pages
```
This file can also be found in the [Evidence GitHub repo](https://github.com/evidence-dev/evidence/blob/main/sites/example-project/src/pages/+layout.svelte).
You can customize the `EvidenceDefaultLayout` with the options below, or replace the contents of the file with an entirely new layout. If you include a `+layout.svelte` file in a directory, markdown files in that directory (and its subdirectories) will use this layout file instead of the default layout.
You can also add your own HTML elements to the default page layout.
## Examples
### Hide sidebar on all pages
```html
```
### Add a custom logo
With a logo file in `./static/my-logo.png`.
```html
```
## Options
The `EvidenceDefaultLayout` component includes a number of features on every page that can be removed or customized via props
### Page Settings
App title that will replace the Evidence Logo.
Link to an image which will replace the Evidence logo. This will also override any app title in the header. If the image is in your project's static directory, the link should be relative to the static directory.
Name of the home page in the sidebar.
Sets the width of the app content to the full width of the screen.
Sets the width of the app content in pixels. The default layout is about 1,280 px wide.
Display a subtle link to the Evidence website at the bottom of the sidebar.
### Hide Elements
Removes the option to show queries when the app is deployed. Has no effect in development.
Hides the sidebar navigation
Hides the page header
Hides the breadcrumbs which appear at the top of the page
Hides the table of contents (on-page links at top right of page)
### Social Links & Search
Link to a Github Repo which will appear in the header using the Github Logo
Link to an X (Twitter) profile which will appear in the header using the X Logo
Link to a Bluesky profile which will appear in the header using the Bluesky Logo
Link to a slack community which will appear in the header using the slack Logo
Object containing Algolia docsearch credentials
---
evidence/sites/docs/pages/reference/cli/index.md
---
---
sidebar_position: 1
title: CLI
hide_title: true
description: Commands to start, install, develop, and build Evidence apps from the command line.
---
# CLI Reference
## Commands
```sql commands
select 'npx degit evidence-dev/template my-project' as "CLI", 'Evidence: New Evidence Project' as "VS Code", 'Create a new project from the template' as "Description", 0 as row_num UNION ALL
select 'npm run sources' as "CLI", 'Evidence: Run Sources' as "VS Code", 'Extract data from sources' as "Description", 1 as row_num UNION ALL
select 'npm run dev' as "CLI", 'Evidence: Start Server' as "VS Code", 'Start the development server in the current directory' as "Description", 2 as row_num UNION ALL
select 'npm run build' as "CLI", 'Evidence: Build' as "VS Code", 'Build the app for production' as "Description", 3 as row_num UNION ALL
select 'npm run build:strict' as "CLI", 'Evidence: Built Strict' as "VS Code", 'Build, but fails on query or component errors' as "Description", 4 as row_num UNION ALL
select 'npm run preview' as "CLI", 'N/A' as "VS Code", 'Preview the built site' as "Description", 5 as row_num UNION ALL
select 'Ctrl / Cmd + C' as "CLI", 'Evidence: Stop Server' as "VS Code", 'Stop the dev server (when running)' as "Description", 6 as row_num UNION ALL
select 'r' as "CLI", 'N/A' as "VS Code", 'Restart the dev server (when running)' as "Description", 7 as row_num
ORDER BY row_num
```
## Options
Append flags with an extra `--` after the command to modify behavior.
For example, `npm run dev -- --port 4000` will start the development server on port 4000.
Some of the most common are:
```sql options
select 'sources' as "Command", '--changed' as "Flag", 'Run sources whose queries have changed' as "Description", null as "Detail", 0 as row_num UNION ALL
select 'sources' as "Command", '--sources [source_name]' as "Flag", 'Run sources from the specified sources' as "Description", 'Seperate with commas --sources source1,source2' as "Detail", 1 as row_num UNION ALL
select 'sources' as "Command", '--queries [query_name]' as "Flag", 'Run the specified queries' as "Description", 'Seperate with commas' as "Detail", 2 as row_num UNION ALL
select 'sources' as "Command", '--debug' as "Flag", 'Show debug output' as "Description", null as "Detail", 3 as row_num UNION ALL
select 'dev' as "Command", '--open [path]' as "Flag", 'Open browser to path on startup' as "Description", 'Default --open / opens in root of the project' as "Detail", 4 as row_num UNION ALL
select 'dev' as "Command", '--host [host]' as "Flag", 'Specify hostname' as "Description", '--host 0.0.0.0 can be helpful in containers' as "Detail", 5 as row_num UNION ALL
select 'dev' as "Command", '--port ' as "Flag", 'Specify port' as "Description", 'Automatically increment if default 3000 is in use' as "Detail", 6 as row_num
ORDER BY row_num
```
Evidence's `dev` and `build` commands run using Vite, and so support [Vite's options](https://vitejs.dev/guide/cli.html#options).
Evidence's `preview` command runs using `npx serve` and supports [Serve's options](https://github.com/vercel/serve/blob/main/source/utilities/cli.ts#L30)
## Environment Variables
You can set environment variables to configure Evidence in production. Most of these are used to set database credentials securely.
The format of environment variables for database credentials is `EVIDENCE_SOURCE__[source_name]__[variable_name]`.
You can copy all your current environment variable values from the settings page at [localhost:3000/settings](http://localhost:3000/settings).
N.B. Environment variables are **case sensitive**, so you should preserve the case specified in the settings page.
### .env Files
Evidence will read in environment variables from a `.env` file in the root of your project. This is useful for local development.
### Environment Variables in Source Queries
Environment variables to be used in source queries should be prefixed with `EVIDENCE_VAR__` (note the double underscore). They can be used in source queries with `${EVIDENCE_VAR__variable_name}`.
```bash
EVIDENCE_VAR__customer_name="Acme Corporation"
```
```bash
select *
from orders
where customer_name = '${customer_name}'
```
The quotes would be omitted if the variable was not a string.
### Environment Variables in Pages
Environment variables to be used in pages should be prefixed with `VITE_`. They can be accessed with `import.meta.env.VITE_variable_name`.
`.env`
```bash
VITE_customer_attribute=premium
```
`index.md`
```svelte
<script>
const customer_attribute = import.meta.env.VITE_customer_attribute;
</script>
{#if customer_attribute === 'premium'}
Premium content
{:else if customer_attribute === 'free'}
Free content
{/if}
```
---
evidence/sites/docs/pages/deployment/index.md
---
---
title: "Deployment"
sidebar_position: 3
sidebar_link: false
---
---
evidence/sites/docs/pages/deployment/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/base-paths) 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/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`.
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
{@partial "evidence-cloud.md"}
### 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/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
{@partial "evidence-cloud.md"}
### 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/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. The easiest way to deploy Evidence is on Evidence Cloud.
---
# 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 Evidence Cloud, cloud services like AWS, Azure, Netlify or Vercel, or your own infrastructure.
You can also configure Evidence as a [Single Page App (SPA)](/deployment/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.
## Evidence Cloud
The easiest way to deploy Evidence is on [Evidence Cloud](/deployment/evidence-cloud). Evidence Cloud is free for public apps, and has paid plans for private apps.
## Self-host
You can also self-host Evidence anywhere suitable for hosting static sites. See guides for:
- [AWS Amplify](/deployment/aws-amplify)
- [Azure Static Apps](/deployment/azure-static-apps)
- [Cloudflare Pages](/deployment/cloudflare-pages)
- [Firebase](/deployment/firebase)
- [GitHub Pages](/deployment/github-pages)
- [GitLab Pages](/deployment/gitlab-pages)
- [Hugging Face Spaces](/deployment/hugging-face-spaces)
- [Netlify](/deployment/netlify)
- [Vercel](/deployment/vercel)
## 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/environments).
---
evidence/sites/docs/pages/deployment/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
{@partial "evidence-cloud.md"}
### 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/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
{@partial "evidence-cloud.md"}
### 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/evidence-cloud/index.md
---
---
sidebar_position: 2
hide_table_of_contents: false
title: Evidence Cloud
description: Evidence Cloud is the easiest way to deploy Evidence apps. It's maintained by the Evidence team, and allows you to securely host Evidence apps without having to worry about maintaining your own infrastructure.
og:
image: /img/deployment/deploy-evidence-cloud.png
---
Evidence Cloud is the easiest way to host Evidence apps. It's maintained by the Evidence team, and allows you to securely host Evidence apps without having to worry about maintaining your own infrastructure.
- **Easy to set up:** Deploy in 5 minutes without configuring any infrastructure.
- **Secure:** Manage access for users in your team.
- **Organizational domain:** Host your app at `[organisation].evidence.app`.
- **Scheduled refreshes:** Daily (or more frequent) data updates to your app.
- **Re-build on push:** Merge to your target branch to rebuild your app.
- **Custom domains:** Add a custom domain to your app.
- **Cloud execution engine:** Offload heavy queries to our Cloud SQL engine for faster performance.
## Prerequisites
- A GitHub account
- An Evidence project pushed to GitHub (optional)
## Deploy Evidence to Evidence Cloud
1. Go to Evidence Cloud and login with GitHub
1. Choose an option to get started:
1. **If you have an existing Evidence project:** click `Add Project`
1. **If you don't have a Evidence project yet:** select `Start from our templates`, and choose evidence-dev/template.
1. Deploy your project
- Repository: Choose the GitHub repository containing your Evidence project
- Branch: Edit if required
- Domain: Choose the subdomain you want to deploy to
- (Optional) Root directory: Edit to point to your Evidence directory if you are using a monorepo
- Authentication: None, Email and Password (Paid plans only), or SSO (Paid plans only)
1. Set your environment variables
- **If you are deploying an existing project**, click "Paste Environment Variables"
- Navigate to the settings page and use the **Copy All** button to copy them to your clipboard, then paste them into the Environment Variables section. Click **Save**.
- Alternatively, you can find credentials in `connection.options.yaml` files in your `/sources/your_source` directory, and enter them in KEY=VALUE format on separate lines.
- 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.
- **If you are deploying from a template**, click "Use Template Environment Variables"
1. Click `Deploy your project`
Your app will be deployed to https://[your-subdomain].evidence.app
## Domains, Authentication and Scheduling
### Authentication
Evidence Cloud Team and Enterprise plans support private apps with auth. If you need to configure an SSO provider, reach out to our team on [Slack](https://slack.evidence.dev).
### Custom Domains
Evidence Cloud Enterprise plans support custom domains. Reach out to our team on [Slack](https://slack.evidence.dev) to set your domain up.
### Data Refresh
To adjust your deployment schedule, select your app in [Evidence Cloud](https://evidence.app), click **Schedule**, and adjust the schedule.
Community Plan sites can be refreshed daily. More frequent refreshes are available on the Team and Enterprise plans.
## Frequently Asked Questions
### Features
- Pushes to your target branch.
- Clicking the `Redeploy` button in the UI.
- You can set up a regularly scheduled refresh on some of our plans.
You can set up data refreshes as regularly as you need on the Team and Enterprise plans.
Each viewer account is provided with a unique login to access the app. You can manage viewers in the Evidence Cloud UI.
Yes! Our Free plan allows you to create public sites.
Alongside your `main` branch, set up a secondary app targeting a development branch (e.g. `dev`) whenever you merge changes into `dev`, you will get a preview. When you are ready to release changes, merge these into `main`.
You can set up different database credentials for development deployments, which allows
you to use development data before it is in your production db.
### Pricing
Evidence Cloud's Free tier offers unlimited public apps. For authentication and scheduled updates, [paid plans](https://evidence.dev/cloud) are available.
Email us: [archie@evidence.dev](mailto:archie@evidence.dev), or reach out on Evidence Cloud chat.
### Account Management
Give them access to your [Github repository](https://docs.github.com/en/organizations/managing-user-access-to-your-organizations-repositories/managing-repository-roles/managing-an-individuals-access-to-an-organization-repository). All Evidence Cloud plans come with unlimited developer accounts.
We support GitHub by default. If your team needs another git provider, reach out on [Slack](https://slack.evidence.dev).
### Troubleshooting
Clone the git repository to your local machine (the repo URL is shown in the cloud UI), make edits to the code and/or database settings, and merge the edits to your target branch.
Most builds will be completed in under 2 minutes, and you can track progress in the build logs. The initial deployment may take longer as we provision your account.
Evidence will not deploy sites with errors to prevent users from seeing broken reports. Usually, this is caused by an error with your code. Enter `npm run build` in your editor to test if the build succeeds locally. If you are still having issues, reach out on [Slack](https://slack.evidence.dev).
As a default, a failed chart or query will not throw an error. To prevent failed charts or queries from building successfully, edit the build command in `package.json` to `"build": "evidence build:strict"`.
---
evidence/sites/docs/pages/deployment/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
{@partial "evidence-cloud.md"}
### 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/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
{@partial "evidence-cloud.md"}
### 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/environments/index.md
---
---
sidebar_position: 7
hide_table_of_contents: false
title: Environments
---
## 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/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
{@partial "evidence-cloud.md"}
### 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/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
{@partial "evidence-cloud.md"}
### 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/rendering-modes/index.md
---
---
sidebar_position: 5
hide_table_of_contents: false
title: Rendering Modes
---
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** (in which case you may want to combine this with Evidence's Cloud Execution Engine)
## Comparison
## Enabling SPA Mode
Note: To deploy an SPA mode app on Evidence Cloud, you currently need to deploy on a private site, using the Cloud Execution Engine.
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/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-components) 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 Cloud
Deploying apps with custom base paths is supported in Evidence Cloud's [Enterprise plan](https://evidence.dev/cloud).
---
evidence/sites/docs/pages/deployment/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
{@partial "evidence-cloud.md"}
### 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**
![netlify-add-build-hook](/img/netlify-add-build-hook.png)
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**
![netlify-github-new-secret](/img/netlify-github-new-secret.png)
- Add the build hook URL as the secret value
![netlify-github-secret](/img/netlify-github-secret.png)
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/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 the [VSCode Extension](vscode:extension/Evidence.evidence-vscode).
## VSCode Extension
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
If you run into any issues, [reach out in Slack.](https://slack.evidence.dev)
## Other Options
```shell
npx degit evidence-dev/template my-project
cd my-project
npm install
npm run sources
npm run dev
```
```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).
---