### Clone and install dependencies
Source: https://github.com/observablehq/framework/blob/main/docs/contributing.md
Initial setup commands to clone the repository and install required packages using Yarn.
```sh
git clone git@github.com:observablehq/framework.git
cd framework
yarn
```
--------------------------------
### Configure project themes
Source: https://github.com/observablehq/framework/blob/main/docs/config.md
Examples of setting the theme option in the configuration file.
```js
theme: "light"
```
```js
theme: "dark"
```
```js
theme: "dashboard"
```
```js
theme: ["air", "near-midnight", "alt", "wide"]
```
--------------------------------
### Download and Run Elasticsearch
Source: https://github.com/observablehq/framework/blob/main/examples/loader-elasticsearch/README.md
Commands to download and start an Elasticsearch instance on macOS. Ensure you follow the security setup instructions provided in the output.
```bash
curl -O https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-8.14.1-darwin-x86_64.tar.gz
gunzip -c elasticsearch-8.14.1-darwin-x86_64.tar.gz | tar xopf -
cd elasticsearch-8.14.1
./bin/elasticsearch
```
--------------------------------
### Toggle Input Examples
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/toggle.md
Examples demonstrating the usage and customization of the Toggle input.
```APIDOC
## Toggle Input Usage Examples
### Basic Toggle
```javascript
const mute = view(Inputs.toggle({label: "Mute"}));
```
### Toggle with Initial Value
```javascript
const mute = view(Inputs.toggle({label: "Mute", value: true}));
```
### Toggle with Custom Values
```javascript
const binary = view(Inputs.toggle({label: "Binary", values: [1, 0]}));
```
### Toggle with HTML Label
```javascript
const fancy = view(Inputs.toggle({label: html`Fancy `}));
```
### Disabled Toggle
```javascript
const frozen = view(Inputs.toggle({label: "Frozen", value: true, disabled: true}));
```
```
--------------------------------
### Start local preview server
Source: https://github.com/observablehq/framework/blob/main/docs/contributing.md
Launches the local development server for live previewing changes.
```sh
yarn dev
```
--------------------------------
### Example Source File Structure
Source: https://github.com/observablehq/framework/blob/main/docs/imports.md
Illustrates a typical source file structure before the build process.
```ini
.
├─ src
│ ├─ chart.js
│ └─ index.md
└─ …
```
--------------------------------
### Install Dependencies
Source: https://github.com/observablehq/framework/blob/main/docs/data-loaders.md
Command to install project dependencies from a requirements file.
```sh
pip install -r requirements.txt
```
--------------------------------
### Serve static site
Source: https://github.com/observablehq/framework/blob/main/docs/contributing.md
Example command to serve the generated static site using http-server.
```sh
http-server docs/.observablehq/dist
```
--------------------------------
### Example: Convert D3 Zoomable Sunburst Notebook
Source: https://github.com/observablehq/framework/blob/main/docs/convert.md
This example demonstrates converting a specific Observable notebook, D3's 'Zoomable sunburst', into Markdown format. It shows the typical command structure with a notebook URL.
```sh
npm run observable convert "https://observablehq.com/@d3/zoomable-sunburst"
```
--------------------------------
### Clone Observable Framework Repository
Source: https://github.com/observablehq/framework/blob/main/examples/README.md
Use this command to clone the Observable Framework repository to your local machine. After cloning, navigate to the desired example directory and install dependencies.
```sh
git clone git@github.com:observablehq/framework.git
```
--------------------------------
### Configure environment variables
Source: https://github.com/observablehq/framework/blob/main/examples/loader-snowflake/src/index.md
Example content for a .env file to store Snowflake credentials.
```text
SNOWFLAKE_ACCOUNT="XXX"
SNOWFLAKE_DATABASE="XXX"
SNOWFLAKE_ROLE="XXX"
SNOWFLAKE_SCHEMA="XXX"
SNOWFLAKE_USERNAME="XXX"
SNOWFLAKE_WAREHOUSE="XXX"
SNOWFLAKE_PASSWORD="XXX"
```
--------------------------------
### Define project configuration
Source: https://github.com/observablehq/framework/blob/main/docs/config.md
Example of a basic configuration file setting the app title and page structure.
```js
export default {
title: "My awesome app",
pages: [
{name: "Getting ever more awesome", path: "/getting-awesome"},
{name: "Being totally awesome", path: "/being-awesome"},
{name: "Staying as awesome as ever", path: "/staying-awesome"}
]
};
```
--------------------------------
### Environment variable configuration
Source: https://github.com/observablehq/framework/blob/main/examples/loader-google-bigquery/src/index.md
Example content for a .env file to store BigQuery credentials.
```text
BQ_PROJECT_ID="123456789-abc"
BQ_CLIENT_EMAIL="xxx@yyy.iam.gserviceaccount.com"
BQ_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nxxxxxxxxxx-----END PRIVATE KEY-----\n"
```
--------------------------------
### Initialize canvas context
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/button.md
Sets up the drawing context for the animation example.
```js
const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
context.fillStyle = getComputedStyle(canvas).color;
```
--------------------------------
### Example Output File Structure
Source: https://github.com/observablehq/framework/blob/main/docs/imports.md
Shows the resulting output directory structure after the Framework build, including rewritten import paths with content hashes.
```ini
.
├─ dist
│ ├─ _import
│ │ └─ chart.c79c2048.js
│ ├─ _observablehq
│ │ └─ … # additional assets
│ └─ index.html
└─ …
```
--------------------------------
### Install dependencies
Source: https://github.com/observablehq/framework/blob/main/examples/loader-census/src/index.md
Install the required npm packages for shapefile processing and conversion.
```sh
npm install shapefile topojson-client topojson-server topojson-simplify
```
--------------------------------
### Start Development Server with npm
Source: https://github.com/observablehq/framework/blob/main/docs/getting-started.md
Initiate the local development server using npm. This command allows you to preview your app in the browser and enables live updates as you edit files.
```bash
npm run dev
```
--------------------------------
### Configure environment variables
Source: https://github.com/observablehq/framework/blob/main/examples/loader-github/src/index.md
Example format for the .env file used to store the GitHub personal access token.
```text
GITHUB_TOKEN="github_pat_XXX"
```
--------------------------------
### Example Runtime Error
Source: https://github.com/observablehq/framework/blob/main/docs/data-loaders.md
This is an example of a runtime error message that may be displayed when a data loader fails during preview.
```text
RuntimeError: Unable to load file: quakes.csv
```
--------------------------------
### Preview Built App Locally
Source: https://github.com/observablehq/framework/blob/main/docs/getting-started.md
Serve the built application locally using `npx http-server dist`. This command starts a static HTTP server in the `dist` directory.
```bash
npx http-server dist
```
--------------------------------
### Initialize Animation Variables
Source: https://github.com/observablehq/framework/blob/main/docs/reactivity.md
Setup initial state for an animation cell.
```js
const clicks = view(Inputs.button("Click", {label: "Run cell"}));
const colors = ["#4269d0", "#efb118", "#ff725c", "#6cc5b0"];
const duration = 2000;
```
--------------------------------
### Example Output of Notebook Conversion
Source: https://github.com/observablehq/framework/blob/main/docs/convert.md
This output illustrates the result of the `convert` command, showing the successful download of notebook files and associated data, such as Markdown and JSON.
```text
┌ observable convert
│
◇ Downloaded zoomable-sunburst.md in 443ms
│
◇ Downloaded flare-2.json in 288ms
│
└ 1 notebook converted; 2 files written
```
--------------------------------
### Inputs.table Configuration Example
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/table.md
Demonstrates various configuration options for the Inputs.table function, including setting column widths, alignment, number of rows, maximum width, and layout.
```APIDOC
## POST /observablehq/framework/table
### Description
This example shows how to configure the `Inputs.table` function with specific options for column widths, alignment, row count, and layout.
### Method
POST
### Endpoint
/observablehq/framework/table
### Parameters
#### Request Body
- **data** (object) - The data to display in the table.
- **options** (object) - Configuration options for the table.
- **width** (object | number) - Specifies the width of the table or individual columns. Can be an object with column names as keys and widths as values, or a single number for the total table width.
- **align** (object) - Specifies the text alignment for cells in individual columns. Keys are column names, values can be 'left', 'right', or 'center'.
- **rows** (number) - The maximum number of rows to display. Defaults to 11.5.
- **maxWidth** (number) - The maximum width of the table in pixels.
- **layout** (string) - The CSS `table-layout` property. Defaults to 'fixed' for tables with 12 or fewer columns.
- **multiple** (boolean) - Allows multiple rows to be selected. Defaults to true.
### Request Example
```json
{
"data": "penguins",
"options": {
"width": {
"culmen_length_mm": 140,
"culmen_depth_mm": 140,
"flipper_length_mm": 140
},
"align": {
"culmen_length_mm": "right",
"culmen_depth_mm": "center",
"flipper_length_mm": "left"
},
"rows": 18,
"maxWidth": 840,
"multiple": false,
"layout": "fixed"
}
}
```
### Response
#### Success Response (200)
- **table** (object) - The rendered table element.
#### Response Example
```json
{
"table": "
"
}
```
```
--------------------------------
### Observable Framework Project Initialization Output
Source: https://github.com/observablehq/framework/blob/main/docs/getting-started.md
This is an example of the output you will see when creating a new Observable Framework project. It shows the prompts and default selections for creating the app, followed by next steps.
```bash
┌ observable create
│
◆ Welcome to Observable Framework! 👋 This command will help you create a new
│ app. When prompted, you can press Enter to accept the default value.
│
│ Want help? https://observablehq.com/framework/getting-started
│
◇ Where should we create your project?
│ ./hello-framework
│
◇ What should we title your app?
│ Hello Framework
│
◇ Include sample files to help you get started?
│ Yes, include sample files
│
◇ Install dependencies?
│ Yes, via npm
│
◇ Initialize a git repository?
│ Yes
│
◇ Installed! 🎉
│
◇ Next steps… ──────────╮
│ │
│ cd hello-framework │
│ npm run dev │
│ │
├────────────────────────╯
│
└ Problems? https://github.com/observablehq/framework/discussions
```
--------------------------------
### Advanced TeX mathematical examples
Source: https://github.com/observablehq/framework/blob/main/docs/lib/tex.md
Additional examples demonstrating complex mathematical notation using the TeX fenced code block syntax.
```tex
c = \pm\sqrt{a^2 + b^2}
```
```tex
\Delta E^*_{00} = \sqrt{
\Big(\frac{\Delta L'}{k_LS_L}\Big)^2 +
\Big(\frac{\Delta C'}{k_CS_C}\Big)^2 +
\Big(\frac{\Delta H'}{k_HS_H}\Big)^2 +
R_T
\frac{\Delta C'}{k_CS_C}
\frac{\Delta H'}{k_HS_H}}
```
```tex
\def\f#1#2{#1f(#2)}
\f\relax{x} = \int_{-\infty}^\infty
\f\hat\xi\,e^{2 \pi i \xi x}
\,d\xi
```
--------------------------------
### Execute addition function
Source: https://github.com/observablehq/framework/blob/main/test/output/build/typescript/index.html
Examples of calling the addition function with different argument types.
```javascript
add(1, 3)
```
```typescript
add(1 as number, 3)
```
--------------------------------
### File Input with Options (Label, Accept, Required)
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/file.md
This example shows how to configure the file input with a label, specify accepted file extensions using the `accept` option, and make the input required using the `required` option.
```APIDOC
## File Input with Options
### Description
This snippet demonstrates configuring the file input with specific options. It includes a user-friendly label, restricts accepted file types (e.g., `.csv`), and ensures a file is selected before proceeding by setting `required: true`.
### Method
```
view(Inputs.file({label: "CSV file", accept: ".csv", required: true}))
```
### Endpoint
N/A (Client-side component)
### Parameters
#### Options
- **label** (string) - Optional - A label to display for the file input.
- **accept** (string) - Optional - Specifies the file types the server accepts (e.g., ".csv", ".json,.txt").
- **required** (boolean) - Optional - If true, a file must be selected for the input to be considered valid.
### Request Example
```json
{
"example": "view(Inputs.file({label: \"CSV file\", accept: \".csv\", required: true}))"
}
```
### Response
#### Success Response (200)
- **csvfile** (Object) - An object representing the selected CSV file, with methods for parsing its content.
#### Response Example
```json
{
"example": "csvfile.csv({typed: true})"
}
```
```
--------------------------------
### Import Vega-Lite
Source: https://github.com/observablehq/framework/blob/main/docs/lib/vega-lite.md
Explicitly import Vega, Vega-Lite, and the Vega-Lite API. This setup is required before constructing charts.
```js
import * as vega from "npm:vega";
import * as vegaLite from "npm:vega-lite";
import * as vegaLiteApi from "npm:vega-lite-api";
const vl = vegaLiteApi.register(vega, vegaLite);
```
--------------------------------
### Start Development Server on a Specific Port
Source: https://github.com/observablehq/framework/blob/main/docs/getting-started.md
Run the development server using npm on a custom port (e.g., 4321). This is useful if the default port 3000 is already in use.
```bash
npm run dev -- --port 4321
```
--------------------------------
### Configure Table with Preselected Rows and Multiple Selection
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/table.md
This example demonstrates how to preselect multiple rows using the `value` option and enabling multiple row selection with `multiple: true`.
```javascript
Inputs.table(penguins, {
value: [1, 3, 7, 9].map((i) => penguins[i]),
multiple: true
})
```
--------------------------------
### Configure data loader interpreters
Source: https://github.com/observablehq/framework/blob/main/docs/config.md
Default interpreter configuration and examples for adding or disabling interpreters.
```js
{
".js": ["node", "--no-warnings=ExperimentalWarning"],
".ts": ["tsx"],
".py": ["python3"],
".r": ["Rscript"],
".R": ["Rscript"],
".rs": ["rust-script"]
".go": ["go", "run"],
".java": ["java"],
".jl": ["julia"],
".php": ["php"],
".sh": ["sh"],
".exe": []
}
```
```js
export default {
interpreters: {
".pl": ["perl"],
".scpt": ["osascript"]
}
};
```
```js
export default {
interpreters: {
".rs": null
}
};
```
--------------------------------
### Download and Run Kibana
Source: https://github.com/observablehq/framework/blob/main/examples/loader-elasticsearch/README.md
Commands to download and start a Kibana instance on macOS. This is used to manage and visualize Elasticsearch data.
```bash
curl -O https://artifacts.elastic.co/downloads/kibana/kibana-8.14.1-darwin-x86_64.tar.gz
gunzip -c kibana-8.14.1-darwin-x86_64.tar.gz | tar xopf -
cd kibana-8.14.1
./bin/kibana
```
--------------------------------
### Apply theme via front matter
Source: https://github.com/observablehq/framework/blob/main/docs/config.md
Example of applying a theme to an individual page using YAML front matter.
```yaml
---
theme: [glacier, slate]
---
```
--------------------------------
### Run Development Server on Port 80 with Remote Access
Source: https://github.com/observablehq/framework/blob/main/docs/getting-started.md
Start the development server with administrative privileges, allowing it to run on port 80 and accept remote connections. Requires sudo.
```bash
sudo npm run dev -- --host 0.0.0.0 --port 80
```
--------------------------------
### Create a New Observable Framework App
Source: https://github.com/observablehq/framework/blob/main/docs/getting-started.md
Use this command to scaffold a new Observable Framework project. It will prompt you for project details and set up the necessary files and dependencies. Ensure Node.js 18 or later is installed.
```bash
npx @observablehq/framework@latest create
```
--------------------------------
### Import and Register Files in Observable Framework
Source: https://github.com/observablehq/framework/blob/main/test/output/build/params2/index.html
This snippet demonstrates the initial setup for an Observable Framework project. It imports necessary functions and registers a JSON data file, then defines an asynchronous module for analytics.
```javascript
import {define} from "./\_observablehq/client.00000001.js"; import {registerFile} from "./\_observablehq/stdlib.00000003.js"; registerFile("./code/data.json", {"name":"./code/data.json","mimeType":"application/json","path":"./\_file/code/data.015abd7f.json","lastModified":/\* ts \*\/1706742000000,"size":7}); define({id: "d2a99c55", body: async () => { const {} = await import("./\_import/code/analytics.0d826e00.js"); }});
```
--------------------------------
### Placeholder for Zip File Access
Source: https://github.com/observablehq/framework/blob/main/test/input/build/archives.posix/zip.md
This is a commented-out example showing how one might access a zip file. It is not active code and requires uncommenting and potential further implementation.
```javascript
// await FileAttachment("dynamic.zip")
```
--------------------------------
### Folder-based Routing Example
Source: https://github.com/observablehq/framework/blob/main/docs/project-structure.md
Demonstrates how pages within folders are mapped to nested URL routes. The 'index.md' file in a folder serves as the index page for that route.
```ini
.
├─ src
│ ├─ missions
│ │ ├─ index.md
│ │ ├─ apollo.md
│ │ └─ gemini.md
│ └─ index.md
└─ ⋯
```
--------------------------------
### Data Loader in Python
Source: https://github.com/observablehq/framework/blob/main/docs/getting-started.md
Write data loaders in Python to fetch and process data. This example fetches hourly forecast data from the weather.gov API and outputs it as JSON.
```python
import json
import requests
import sys
longitude = -122.47
latitude = 37.80
station = requests.get(f"https://api.weather.gov/points/{latitude},{longitude}").json()
forecast = requests.get(station["properties"]["forecastHourly"]).json()
json.dump(forecast, sys.stdout)
```
--------------------------------
### Configure Table Layout and Appearance
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/table.md
Use the `width`, `align`, `rows`, `maxWidth`, and `layout` options to control the table's dimensions, column alignment, and overall layout. This example sets fixed column widths and a maximum table width.
```javascript
Inputs.table(penguins, {
width: {
culmen_length_mm: 140,
culmen_depth_mm: 140,
flipper_length_mm: 140
},
align: {
culmen_length_mm: "right",
culmen_depth_mm: "center",
flipper_length_mm: "left"
},
rows: 18,
maxWidth: 840,
multiple: false,
layout: "fixed"
})
```
--------------------------------
### Use vlresize for Responsive Chart
Source: https://github.com/observablehq/framework/blob/main/examples/vega-responsive/src/index.md
Shows how to use the imported `vlresize` function to render a responsive Vega-Lite chart with specified constraints. This example applies a maximum width to the chart, ensuring it scales appropriately within the defined bounds.
```javascript
vlresize({
"height": 250,
"data": {"url": "https://vega.github.io/vega-lite/data/cars.json"},
"mark": "bar",
"encoding": {
"x": {"field": "Cylinders"},
"y": {"aggregate": "count", "title": "Number of cars"}
}
}, {
maxWidth: 960 - 16 * 2
})
```
--------------------------------
### DOT graph examples
Source: https://github.com/observablehq/framework/blob/main/docs/lib/dot.md
Various examples of DOT graph definitions.
```dot
graph { n0 -- n1 -- n2 -- n3 -- n0 }
```
```dot
digraph { x -> y -> z }
```
```dot
digraph G {
subgraph cluster_0 {
a0 -> a1 -> a2 -> a3
label = "process #1"
color = lightblue
}
subgraph cluster_1 {
b0 -> b1 -> b2 -> b3
label = "process #2"
color = orange
}
start -> a0
start -> b0
a1 -> b3
b2 -> a3
a3 -> a0
a3 -> end
b3 -> end
start [shape = diamond]
end [shape = square]
}
```
--------------------------------
### Initialize a new project
Source: https://github.com/observablehq/framework/blob/main/docs/index.md
Use this command to scaffold a new Observable Framework project in your local environment.
```bash
npx "@observablehq/framework@latest" create
```
--------------------------------
### Markdown Footnote Syntax Example
Source: https://github.com/observablehq/framework/blob/main/examples/markdown-it-footnote/src/index.md
Example of referencing footnotes within Markdown content using the [^label] syntax. Footnotes are defined separately.
```markdown
Here is a footnote reference,[^1] and another.[^longnote]
```
--------------------------------
### Navigate to Project Directory
Source: https://github.com/observablehq/framework/blob/main/docs/getting-started.md
Change into your newly created Observable Framework project directory. This is the first step after initializing a new project.
```bash
cd hello-framework
```
--------------------------------
### FileAttachment .href
Source: https://github.com/observablehq/framework/blob/main/docs/files.md
Get the resolved absolute URL of the file using `file.href`.
```APIDOC
## FileAttachment .href
In addition to the above, you can get the resolved absolute URL of the file using `file.href`:
```js echo
FileAttachment("volcano.json").href
```
```
--------------------------------
### Basic Project Structure
Source: https://github.com/observablehq/framework/blob/main/docs/project-structure.md
Illustrates a simple project with two Markdown files in the source root, which will be compiled into corresponding HTML pages.
```ini
.
├─ src
│ ├─ hello.md
│ └─ index.md
└─ ⋯
```
```ini
.
├─ dist
│ ├─ _observablehq
│ │ └─ ⋯ # additional assets
│ ├─ hello.html
│ └─ index.html
└─ ⋯
```
--------------------------------
### Get spatial connection endpoints
Source: https://github.com/observablehq/framework/blob/main/examples/eia/src/index.md
Filters active connections and maps them to geographic coordinates.
```js
// Gets lat/lon endpoints between balancing authorities
const eiaConnRefSpatial = eiaConnRef
.filter((d) => d["Active Connection"] == "Yes")
.map((d) => ({
connection: `${d["BA Code"]}-${d["Directly Interconnected BA Code"]}`,
location1: locations.get(d["BA Code"]),
location2: locations.get(d["Directly Interconnected BA Code"])
}));
```
--------------------------------
### Initialize deck.gl instance
Source: https://github.com/observablehq/framework/blob/main/examples/us-dams/src/index.md
Creates the deck.gl instance and handles cleanup on invalidation.
```js
const deckInstance = new DeckGL({
container,
initialViewState,
controller: true,
effects
});
// clean up if this code re-runs
invalidation.then(() => {
deckInstance.finalize();
container.innerHTML = "";
});
```
--------------------------------
### Get File URL
Source: https://github.com/observablehq/framework/blob/main/docs/files.md
Retrieve the resolved absolute URL of a file using the href property.
```js
FileAttachment("volcano.json").href
```
--------------------------------
### Initialize Deck.gl Instance
Source: https://github.com/observablehq/framework/blob/main/examples/us-dams/src/by-state.md
Creates the main DeckGL instance and ensures proper cleanup on invalidation.
```js
const deckInstance = new DeckGL({
container,
initialViewState,
controller: true,
});
// Replace (instead of overlay) map on re-run
invalidation.then(() => {
deckInstance.finalize();
container.innerHTML = "";
});
```
--------------------------------
### Define initial view state
Source: https://github.com/observablehq/framework/blob/main/examples/us-dams/src/index.md
Sets the starting camera position and zoom levels for the map.
```js
const initialViewState = {
longitude: -100,
latitude: 36,
zoom: 4.1,
minZoom: 3,
maxZoom: 7,
pitch: 45,
bearing: 20
};
```
--------------------------------
### Set initial value
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/range.md
Defines the starting value for the range input using the value option.
```js
const z = view(Inputs.range([0, 255], {step: 1, value: 0}));
```
```js
z
```
--------------------------------
### Project Structure and Build Output
Source: https://github.com/observablehq/framework/blob/main/docs/data-loaders.md
Visual representation of project source and build directories.
```ini
.
├─ src
│ ├─ index.md
│ └─ quakes.json.sh
└─ …
```
```ini
.
├─ dist
│ ├─ _file
│ │ └─ quakes.99da78d9.json
│ ├─ _observablehq
│ │ └─ … # additional assets
│ └─ index.html
└─ …
```
```ini
.
├─ src
│ ├─ index.md
│ └─ quakes.zip
└─ …
```
```ini
.
├─ dist
│ ├─ _file
│ │ └─ quakes
│ │ └─ 2021.e5f2eb94.csv
│ ├─ _observablehq
│ │ └─ … # additional assets
│ └─ index.html
└─ …
```
--------------------------------
### Define Perl Data Loader with Shebang
Source: https://github.com/observablehq/framework/blob/main/docs/data-loaders.md
Example of a Perl script configured as an executable data loader.
```perl
#!/usr/bin/env perl
print("Hello World\n");
```
--------------------------------
### Initialize DuckDBClient with Parquet File
Source: https://github.com/observablehq/framework/blob/main/docs/lib/duckdb.md
Create a DuckDB client by loading a Parquet file (Gaia Star Catalog sample) into a named table 'gaia'. Supports various file formats like CSV, TSV, JSON, Arrow, and Parquet.
```js
const db = DuckDBClient.of({gaia: FileAttachment("gaia-sample.parquet")});
```
--------------------------------
### Basic Addition Function
Source: https://github.com/observablehq/framework/blob/main/test/output/fenced-code-options.html
A simple JavaScript function for adding two numbers. No specific setup is required.
```javascript
function add(a, b) {
return a + b;
}
```
--------------------------------
### Get Elasticsearch CA Fingerprint
Source: https://github.com/observablehq/framework/blob/main/examples/loader-elasticsearch/README.md
Command to retrieve the CA fingerprint for Elasticsearch, required for TLS configuration.
```bash
openssl x509 -fingerprint -sha256 -noout -in ./elasticsearch-8.14.1/config/certs/http_ca.crt
```
--------------------------------
### Importing Node packages
Source: https://github.com/observablehq/framework/blob/main/docs/imports.md
Import installed packages from node_modules using bare specifiers or specific entry points.
```js
import confetti from "canvas-confetti";
```
```js
import * as Arrow from "apache-arrow";
```
```js
import mime from "mime/lite";
```
--------------------------------
### Import Local Module and Display
Source: https://github.com/observablehq/framework/blob/main/test/input/build/imports/foo/foo.md
Imports a module from a local 'foo bar.js' file and displays it.
```js
import {foobar} from "./foo%20bar.js";
display(foobar);
```
--------------------------------
### Implement custom search index
Source: https://github.com/observablehq/framework/blob/main/docs/config.md
Example of adding external links to the search index using an async generator.
```js
export default {
search: {
async *index() {
yield {
path: "https://example.com",
title: "Example",
text: "This is an example of an external link."
};
}
}
};
```
--------------------------------
### Project file structure and routing
Source: https://github.com/observablehq/framework/blob/main/docs/files.md
Visual representation of source file organization and the resulting distribution structure after build.
```ini
.
├─ src
│ ├─ index.md
│ └─ quakes.csv
└─ …
```
```ini
.
├─ dist
│ ├─ _file
│ │ └─ quakes.e5f2eb94.csv
│ ├─ _observablehq
│ │ └─ … # additional assets
│ └─ index.html
└─ …
```
--------------------------------
### Disable table of contents in front matter
Source: https://github.com/observablehq/framework/blob/main/docs/config.md
Example of disabling the table of contents using YAML front matter.
```yaml
---
toc: false
---
```
--------------------------------
### Configure markdown-it-footnote Plugin
Source: https://github.com/observablehq/framework/blob/main/examples/markdown-it-footnote/src/index.md
Register the markdown-it-footnote plugin in your observablehq.config.js file. Ensure markdown-it-footnote is installed via npm or Yarn.
```javascript
import MarkdownItFootnote from "markdown-it-footnote";
export default {
root: "src",
markdownIt: (md) => md.use(MarkdownItFootnote)
};
```
--------------------------------
### Build App with npm
Source: https://github.com/observablehq/framework/blob/main/docs/getting-started.md
Run the `npm run build` command to generate the `dist` directory for your application. This directory contains the static files ready for deployment.
```bash
npm run build
```
--------------------------------
### Define custom stylesheet
Source: https://github.com/observablehq/framework/blob/main/docs/config.md
Example of a custom CSS file that imports default styles and overrides CSS custom properties.
```css
@import url("observablehq:default.css");
@import url("observablehq:theme-air.css");
:root {
--theme-foreground-focus: green;
}
```
--------------------------------
### Create and Activate Virtual Environments
Source: https://github.com/observablehq/framework/blob/main/docs/data-loaders.md
Commands to initialize and activate Python virtual environments using venv or uv.
```sh
python3 -m venv .venv
```
```sh
uv venv
```
```sh
source .venv/bin/activate
```
```sh
.venv\Scripts\activate
```
--------------------------------
### Create a PostgreSQL connection helper
Source: https://github.com/observablehq/framework/blob/main/examples/loader-postgres/src/index.md
Provides a wrapper for the postgres package to manage connections and environment variables.
```ts
import "dotenv/config";
import type {Row, Sql} from "postgres";
import postgres from "postgres";
const {POSTGRES_URL} = process.env;
if (!POSTGRES_URL) throw new Error("missing POSTGRES_URL");
// Warning: you may wish to specify a self-signed certificate rather than
// disabling certificate verification via rejectUnauthorized: false as below.
// See https://github.com/porsager/postgres/blob/master/README.md#ssl for more.
export async function run(f: (sql: Sql) => Promise): Promise {
const sql = postgres(POSTGRES_URL!, {ssl: {rejectUnauthorized: false}});
try {
return await f(sql);
} finally {
await sql.end();
}
}
```
--------------------------------
### Build static site
Source: https://github.com/observablehq/framework/blob/main/docs/contributing.md
Generates the static site files into the dist directory.
```sh
yarn docs:build
```
--------------------------------
### Rust Script with Dependencies
Source: https://github.com/observablehq/framework/blob/main/examples/loader-rust-to-json/src/index.md
This Rust script uses `rust-script` and declares its dependencies in a `cargo` block. Ensure these dependencies are installed before running.
```rust
#!/usr/bin/env rust-script
//! Since Framework uses rust-script, we can define dependencies here.
//!
//! ```cargo
//! [dependencies]
//! serde = { version = "1.0.203", features = ["derive"] }
//! serde_json = "1.0.117"
//! rand = "0.8.5"
//! rayon = "1.10.0"
//! ```
```
--------------------------------
### Register Markdown-it Plugin
Source: https://github.com/observablehq/framework/blob/main/docs/config.md
Register custom markdown-it plugins, such as markdown-it-footnote. Ensure the plugin is installed via npm or yarn before registering.
```javascript
import MarkdownItFootnote from "markdown-it-footnote";
export default {
markdownIt: (md) => md.use(MarkdownItFootnote)
};
```
--------------------------------
### Initialize sql.js Directly
Source: https://github.com/observablehq/framework/blob/main/docs/lib/sqlite.md
If you prefer to use sql.js directly, import and initialize it. This allows for more control over the initialization process.
```javascript
import initSqlJs from "npm:sql.js";
const SQLite = await initSqlJs({locateFile: (name) => import.meta.resolve("npm:sql.js/dist/") + name});
```
--------------------------------
### Instantiate DuckDBClient with No Extensions
Source: https://github.com/observablehq/framework/blob/main/docs/lib/duckdb.md
Create a DuckDBClient instance that will not load any extensions, even if they are configured. Pass an empty array to the `extensions` option.
```javascript
const simpledb = DuckDBClient.of({}, {extensions: []});
```
--------------------------------
### Markdown Footnote Definition Example
Source: https://github.com/observablehq/framework/blob/main/examples/markdown-it-footnote/src/index.md
Defines footnotes in Markdown using the [^label]: content syntax. Multi-paragraph footnotes are supported with indentation.
```markdown
[^1]: Here is the footnote.
[^longnote]: Here's one with multiple blocks.
Subsequent paragraphs are indented to show that they
belong to the previous footnote.
```
--------------------------------
### Lodash Defaults Example
Source: https://github.com/observablehq/framework/blob/main/docs/lib/lodash.md
Use the `_.defaults` function to assign default properties to an object. Properties that already exist in the first object are not overwritten.
```javascript
_.defaults({a: 1}, {a: 3, b: 2})
```
--------------------------------
### Create a basic file input
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/file.md
Initializes a file input component. The value resolves to null until a file is selected.
```javascript
const file = view(Inputs.file());
```
```javascript
file
```
--------------------------------
### Display project file structure
Source: https://github.com/observablehq/framework/blob/main/examples/hello-world/src/index.md
Visual representation of the standard directory layout for an Observable Framework project.
```ini
.
├─ src
│ └─ index.md
├─ observablehq.config.js
└─ package.json
```
--------------------------------
### Apply custom style via front matter
Source: https://github.com/observablehq/framework/blob/main/docs/config.md
Example of applying a custom stylesheet to an individual page using YAML front matter.
```yaml
---
style: custom-style.css
---
```
--------------------------------
### Import and execute sum function
Source: https://github.com/observablehq/framework/blob/main/test/output/build/typescript/index.html
Demonstrates importing a module and calling the exported function.
```javascript
import {sum} from "./sum.js";
```
```javascript
sum(1, 2)
```
--------------------------------
### Creating DOM Content with JavaScript
Source: https://github.com/observablehq/framework/blob/main/docs/javascript.md
Demonstrates creating DOM nodes directly using JavaScript. This example requires imagination for the actual chart implementation.
```javascript
document.createTextNode("[insert chart here]") // some imagination required
```
--------------------------------
### Create File Handle
Source: https://github.com/observablehq/framework/blob/main/docs/files.md
Use FileAttachment with a file path to get a file handle. The path is relative to the calling code's source file.
```javascript
FileAttachment("volcano.json")
```
--------------------------------
### Register CSV and JSON Files
Source: https://github.com/observablehq/framework/blob/main/test/output/build/fetches/foo.html
Register local CSV and JSON files with their metadata. This is typically done once at the start of a project to make data available.
```javascript
import {define} from "./\_observablehq/client.00000001.js"; import {registerFile} from "./\_observablehq/stdlib.00000003.js"; registerFile("./foo/foo-data.csv", {"name":"./foo/foo-data.csv","mimeType":"text/csv","path":"./\_file/foo/foo-data.24ef4634.csv","lastModified":/\* ts \*/1706742000000,"size":72}); registerFile("./foo/foo-data.json", {"name":"./foo/foo-data.json","mimeType":"application/json","path":"./\_file/foo/foo-data.67358ed8.json","lastModified":/\* ts \*/1706742000000,"size":10});
```
--------------------------------
### View project directory structure
Source: https://github.com/observablehq/framework/blob/main/docs/project-structure.md
A typical layout for an Observable Framework project showing the source root and configuration files.
```ini
.
├─ src # source root
│ ├─ .observablehq
│ │ ├─ cache # data loader cache
│ │ └─ deploy.json # deployment metadata
│ ├─ components
│ │ └─ dotmap.js # shared JavaScript module
│ ├─ data
│ │ └─ quakes.csv.ts # data loader
│ ├─ index.md # home page
│ └─ quakes.md # page
├─ .gitignore
├─ README.md
├─ observablehq.config.js # app configuration
├─ package.json # node package dependencies
└─ yarn.lock # node package lockfile
```
--------------------------------
### Import TopoJSON server and simplify
Source: https://github.com/observablehq/framework/blob/main/docs/lib/topojson.md
Import libraries for manipulating and simplifying topologies.
```js
import {topology} from "npm:topojson-server";
import {presimplify, simplify} from "npm:topojson-simplify";
```
--------------------------------
### Generate Random Integer with JSR
Source: https://github.com/observablehq/framework/blob/main/test/input/build/jsr/index.md
Imports and uses random number generation functions from the @std/random package. Ensure the package is correctly installed or available in your environment.
```js
import {randomIntegerBetween, randomSeeded} from "jsr:@std/random";
const prng = randomSeeded(1n);
display(randomIntegerBetween(1, 10, {prng}));
```
--------------------------------
### Load Apache Arrow Data using FileAttachment
Source: https://github.com/observablehq/framework/blob/main/examples/loader-arrow/src/index.md
Loads an Apache Arrow file using FileAttachment and parses it into an Arrow table. Ensure 'apache-arrow' is installed.
```javascript
const samples = FileAttachment("./data/samples.arrow").arrow();
```
--------------------------------
### Import Modules and Display Content
Source: https://github.com/observablehq/framework/blob/main/test/input/build/imports/foo/foo.md
Imports D3, a local bar module, and a top-level module, then displays them. Also shows how to reference a FileAttachment.
```js
import * as d3 from "npm:d3";
import {bar} from "../bar/bar.js";
import {top} from "/top.js";
display(bar);
display(top);
FileAttachment("/top.js");
```
--------------------------------
### Initialize and configure a Leaflet map
Source: https://github.com/observablehq/framework/blob/main/docs/lib/leaflet.md
Create a map container, set the initial view, add a tile layer, and place a marker with a popup.
```js
const div = display(document.createElement("div"));
div.style = "height: 400px;";
const map = L.map(div)
.setView([51.505, -0.09], 13);
L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: '© OpenStreetMap '
})
.addTo(map);
L.marker([51.5, -0.09])
.addTo(map)
.bindPopup("A nice popup indicating a point of interest.")
.openPopup();
```
--------------------------------
### Convert a Notebook using npm
Source: https://github.com/observablehq/framework/blob/main/docs/convert.md
Use this command to convert a single Observable notebook to Markdown within an existing project. Ensure you have the project set up.
```sh
npm run observable convert
```
--------------------------------
### Force Rebuild Specific Data Loader
Source: https://github.com/observablehq/framework/blob/main/docs/data-loaders.md
To rebuild a specific data loader, delete its corresponding output file from the cache. This example shows how to rebuild 'src/quakes.csv'.
```sh
rm -f src/.observablehq/cache/quakes.csv
```
--------------------------------
### Create a basic textarea
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/textarea.md
Initializes a standard multi-line text input with an empty string as the default value.
```js
const text = view(Inputs.textarea());
```
```js
text
```
--------------------------------
### jQuery UI CSS Import
Source: https://github.com/observablehq/framework/blob/main/docs/lib/jquery-ui.md
Link to the base jQuery UI CSS theme. This should be included in your HTML or project setup to style the UI elements correctly.
```html
```
--------------------------------
### Generate and Output Parquet Data
Source: https://github.com/observablehq/framework/blob/main/examples/loader-parquet/src/index.md
Generates a daily random walk dataset and writes it to standard output as an Apache Parquet file. Requires `apache-arrow` and `parquet-wasm` to be installed.
```javascript
import * as Arrow from "apache-arrow";
import * as Parquet from "parquet-wasm";
// Generate a daily random walk as parallel arrays of {date, value}.
const date = [];
const value = [];
const start = new Date("2022-01-01");
const end = new Date("2023-01-01");
for (let currentValue = 0, currentDate = start; currentDate < end; ) {
date.push(currentDate);
value.push(currentValue);
(currentDate = new Date(currentDate)), currentDate.setUTCDate(currentDate.getUTCDate() + 1);
currentValue += Math.random() - 0.5;
}
// Construct an Apache Arrow table from the parallel arrays.
const table = Arrow.tableFromArrays({date, value});
// Output the Apache Arrow table as a Parquet table to standard out.
const parquetTable = Parquet.Table.fromIPCStream(Arrow.tableToIPC(table, "stream"));
const parquetBuilder = new Parquet.WriterPropertiesBuilder().setCompression(Parquet.Compression.ZSTD).build();
const parquetData = Parquet.writeParquet(parquetTable, parquetBuilder);
process.stdout.write(parquetData);
```
--------------------------------
### Create a text file input
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/file.md
Initializes a file input for text files, requiring a selection and providing a label.
```javascript
const textfile = view(Inputs.file({label: "Text file", accept: ".txt", required: true}));
```
--------------------------------
### Query Databricks with TypeScript
Source: https://github.com/observablehq/framework/blob/main/examples/loader-databricks/src/index.md
Use this data loader to query Databricks and retrieve 100 rows from the nyctaxi sample dataset. Ensure you have installed `@databricks/sql`, `d3-dsv`, and `dotenv`.
```javascript
import {csvFormat} from "d3-dsv";
import {executeStatement} from "./databricks.js";
process.stdout.write(csvFormat(await executeStatement("SELECT * FROM samples.nyctaxi.trips LIMIT 100")));
```
--------------------------------
### Import Arquero Library
Source: https://github.com/observablehq/framework/blob/main/docs/lib/arquero.md
Import the Arquero library for use in Markdown. Available by default as `aq`.
```javascript
import * as aq from "npm:arquero";
```
--------------------------------
### Define environment variables in .env
Source: https://github.com/observablehq/framework/blob/main/examples/loader-postgres/src/index.md
Configuration format for local database authentication credentials.
```text
POSTGRES_URL="postgres://USERNAME:PASSWORD@HOST.example.com:5432/DATABASE"
```
--------------------------------
### Get GeoTIFF image and raster data
Source: https://github.com/observablehq/framework/blob/main/examples/geotiff/src/index.md
Retrieve the image object and raster values from the parsed GeoTIFF data. Promises are implicitly awaited across code blocks.
```javascript
const image = await sfctmp.getImage();
const [values] = await image.readRasters();
```
--------------------------------
### Get Single Row with db.queryRow
Source: https://github.com/observablehq/framework/blob/main/docs/lib/sqlite.md
Retrieve a single row from the database using `db.queryRow`. This is useful for queries that are expected to return only one result, such as fetching the SQLite version.
```javascript
db.queryRow(`SELECT sqlite_version()`)
```
--------------------------------
### Manage Date Range Selection
Source: https://github.com/observablehq/framework/blob/main/examples/mortgage-rates/src/index.md
Manages the start and end dates for the displayed data range using a mutable state. Initializes with the last 53 weeks of data.
```javascript
const defaultStartEnd = [pmms.at(-53).date, pmms.at(-1).date];
const startEnd = Mutable(defaultStartEnd);
const setStartEnd = (se) => startEnd.value = (se ?? defaultStartEnd);
const getStartEnd = () => startEnd.value;
```
--------------------------------
### Display a basic table
Source: https://github.com/observablehq/framework/blob/main/docs/inputs/table.md
Renders a table from the provided data using default settings.
```js
Inputs.table(penguins)
```