|
| 1 | +# Embedded analytics <a href="https://github.com/observablehq/framework/pull/1637" class="observablehq-version-badge" data-version="prerelease" title="Added in #1637"></a> |
| 2 | + |
| 3 | +In addition to generating full-page apps, Framework can generate modules to embed analytics — such as individual charts or tables, or coordinated interactive views — in external applications. Embedded modules take full advantage of Framework’s polyglot, baked data architecture for instant page loads. |
| 4 | + |
| 5 | +Embedded modules are vanilla JavaScript, and behave identically when embedded in an external application as on a Framework page. As always, you can load data from a [data loader](./data-loaders) using [`FileAttachment`](./files), and you can [import](./imports) [self-hosted](./imports#self-hosting-of-npm-imports) local modules and libraries from npm; file and import resolutions are baked into the generated code at build time so that imported modules “just work”. |
| 6 | + |
| 7 | +Embedded modules are often written as component functions that return DOM elements. These functions can take options (or “props”), and typically load their own data. For example, below is a simple `chart.js` module that exports a `Chart` function that renders a scatterplot of global surface temperature data. |
| 8 | + |
| 9 | +```js run=false |
| 10 | +import {FileAttachment} from "npm:@observablehq/stdlib"; |
| 11 | +import * as Plot from "npm:@observablehq/plot"; |
| 12 | + |
| 13 | +export async function Chart() { |
| 14 | + const gistemp = await FileAttachment("./lib/gistemp.csv").csv({typed: true}); |
| 15 | + return Plot.plot({ |
| 16 | + y: {grid: true}, |
| 17 | + color: {scheme: "burd"}, |
| 18 | + marks: [ |
| 19 | + Plot.dot(gistemp, {x: "Date", y: "Anomaly", stroke: "Anomaly"}), |
| 20 | + Plot.ruleY([0]) |
| 21 | + ] |
| 22 | + }); |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +<div class="note"> |
| 27 | + |
| 28 | +When Framework builds your app, any transitive static imports are preloaded automatically when the embedded module is imported. This ensures optimal performance by avoiding long request chains. |
| 29 | + |
| 30 | +</div> |
| 31 | + |
| 32 | +## Embedding modules |
| 33 | + |
| 34 | +To allow a module to be embedded in an external application, declare the module’s path in your [config file](./config) using the [**dynamicPaths** option](./config#dynamic-paths). For example, to embed a single component named `chart.js`: |
| 35 | + |
| 36 | +```js run=false |
| 37 | +export default { |
| 38 | + dynamicPaths: [ |
| 39 | + "/chart.js" |
| 40 | + ] |
| 41 | +}; |
| 42 | +``` |
| 43 | + |
| 44 | +Or for [parameterized routes](./params), name the component `product-[id]/chart.js`, then load a list of product identifiers from a database with a SQL query: |
| 45 | + |
| 46 | +```js run=false |
| 47 | +import postgres from "postgres"; |
| 48 | + |
| 49 | +const sql = postgres(); // Note: uses psql environment variables |
| 50 | + |
| 51 | +export default { |
| 52 | + async *dynamicPaths() { |
| 53 | + for await (const {id} of sql`SELECT id FROM products`.cursor()) { |
| 54 | + yield `/product-${id}/chart.js`; |
| 55 | + } |
| 56 | + } |
| 57 | +}; |
| 58 | +``` |
| 59 | + |
| 60 | +An embedded component can be imported into a vanilla web application like so: |
| 61 | + |
| 62 | +```html run=false |
| 63 | +<script type="module"> |
| 64 | +
|
| 65 | +import {Chart} from "https://my-workspace.observablehq.cloud/my-app/chart.js"; |
| 66 | +
|
| 67 | +document.body.append(await Chart()); |
| 68 | +
|
| 69 | +</script> |
| 70 | +``` |
| 71 | + |
| 72 | +<div class="note"> |
| 73 | + |
| 74 | +The code above assumes the Framework app is called “my-app” and that it’s deployed to Observable Cloud in the workspace named “my-workspace”. |
| 75 | + |
| 76 | +</div> |
| 77 | + |
| 78 | +<div class="note"> |
| 79 | + |
| 80 | +If the external (host) application is on a different origin than the Framework app — for example, if the host application is on example.com and the Framework app is on app.example.com — then you will need to [enable CORS](https://enable-cors.org/) on app.example.com or use a proxy to forward requests from example.com to app.example.com for same-origin serving. |
| 81 | + |
| 82 | +</div> |
| 83 | + |
| 84 | +In React, you can do something similar using [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) and [`useEffect`](https://react.dev/reference/react/useEffect) and [`useRef`](https://react.dev/reference/react/useRef) hooks: |
| 85 | + |
| 86 | +```jsx run=false |
| 87 | +import {useEffect, useRef} from "react"; |
| 88 | + |
| 89 | +export function EmbedChart() { |
| 90 | + const ref = useRef(null); |
| 91 | + |
| 92 | + useEffect(() => { |
| 93 | + let parent = ref.current, child; |
| 94 | + import("https://my-workspace.observablehq.cloud/my-app/chart.js") |
| 95 | + .then(({Chart}) => Chart()) |
| 96 | + .then((chart) => parent?.append((child = chart))); |
| 97 | + return () => ((parent = null), child?.remove()); |
| 98 | + }, []); |
| 99 | + |
| 100 | + return <div ref={ref} />; |
| 101 | +} |
| 102 | +``` |
| 103 | +
|
| 104 | +<div class="tip"> |
| 105 | +
|
| 106 | +Since both dynamic import and the imported component are async, the code above is careful to clean up the effect and avoid race conditions. |
| 107 | +
|
| 108 | +</div> |
| 109 | +
|
| 110 | +<div class="tip"> |
| 111 | +
|
| 112 | +You can alternatively embed Framework pages using [iframe embeds](https://observablehq.observablehq.cloud/framework-example-responsive-iframe/). |
| 113 | +
|
| 114 | +</div> |
| 115 | +
|
| 116 | +## Developing modules |
| 117 | +
|
| 118 | +To develop your component, you can import it into a Framework page like normal, giving you instant reactivity as you make changes to the component or its data. |
| 119 | +
|
| 120 | +```js echo |
| 121 | +import {Chart} from "./chart.js"; |
| 122 | +``` |
| 123 | +
|
| 124 | +To instantiate the imported component, simply call the function: |
| 125 | +
|
| 126 | +```js echo |
| 127 | +Chart() |
| 128 | +``` |
| 129 | +
|
| 130 | +A Framework page can serve as live documentation for your component: you can describe and demonstrate all the states and options for your component, and review the behavior visually. |
0 commit comments