Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/import-chart-from-exploreda-chart-core-and-call.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"exploreda": minor
---

`exploreda/chart` now loads each chart type's code the first time a chart of that type draws, so a page downloads only the types it shows. To register types up front instead, import `Chart` from `exploreda/chart-core` and call `registerCharts`. Every chart type has its own `exploreda/charts/<type>` import, and with `chart-core` an unregistered type shows the import to add.
2 changes: 2 additions & 0 deletions apps/demo/src/docs/components/content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
import { LiveExample } from "../live/LiveExample";
import { SettingsReference } from "../reference/SettingsReference";
import {
ChartImportsTable,
ChartPropsReference,
StandaloneEditable,
StandaloneGallery,
Expand Down Expand Up @@ -343,6 +344,7 @@ export const mdxComponents: MDXComponents = {
// Blocks a page can use without importing them.
Callout,
CalcChain,
ChartImportsTable,
ChartPropsReference,
ChartQuestions,
ChartTypeList,
Expand Down
36 changes: 36 additions & 0 deletions apps/demo/src/docs/pages/standalone-charts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,42 @@ Import `exploreda/dist/chart.css` once. It styles only the charts:
- Leave them out to fill the parent element. Give the parent a height, or the chart takes 300 px.
- `height` includes the title line. Pass `title={false}` to give all of it to the plot.

## Load only the charts you use

`exploreda/chart` loads each chart type's code the first time a chart of that type draws. A page with a bar chart never downloads the 3D scatter or the note editor. Until a type's code arrives, which is one small request, the chart holds its box.

Two things load every type, because they can name any type:

- A `ChartSettings` panel or a settings button, once it opens, so its **Chart Type** list is complete.
- A Dashboard text config.

To have no request at all before a chart draws, import from `exploreda/chart-core` and register the types up front:

```tsx
import { Chart, registerCharts } from "exploreda/chart-core";
import { barChartDefinition } from "exploreda/charts/bar";
import { scatterPlotDefinition } from "exploreda/charts/scatter";
import "exploreda/dist/chart.css";

registerCharts(barChartDefinition, scatterPlotDefinition);

<Chart data={rows} config={{ type: "bar", field: "Region" }} />;
```

- Call `registerCharts` once, before the first chart draws, such as at the top of the module.
- With `chart-core`, a chart whose type isn't registered shows the two lines to add in its place.
- Map shapes load only when a map draws, with either entry.

What the example app's pages load up front, React included:

| Page | Entry | Up front |
| ---------------------------------------------------------------- | ---------------------- | -----------------------------------: |
| 34 charts covering all 27 types, with settings and a text config | `exploreda/chart` | 1,283 KB, the rest after first paint |
| A bar chart and a scatter plot | `exploreda/chart-core` | 1,425 KB |
| The first page, before types loaded on demand | `exploreda/chart` | 2,987 KB |

<ChartImportsTable />

## Every chart type

Each chart below is a `Chart` drawn from the same 48 sample rows, with the config under it.
Expand Down
40 changes: 40 additions & 0 deletions apps/demo/src/docs/standalone/StandaloneCharts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
ChartProps,
ChartSettingsProps,
} from "exploreda/chart";
import { CHART_IMPORTS } from "exploreda/docs-kit";
import { useEffect, useState, type ReactNode } from "react";
import { CodeFrame, HighlightedCode } from "../components/code";
import { Link } from "react-router-dom";
Expand Down Expand Up @@ -274,6 +275,45 @@ export function StandaloneText() {
);
}

/** Every chart type's import for `exploreda/chart-core`, in docs order. */
export function ChartImportsTable() {
const pages = catalogue.filter((page) => page.chartType);
return (
<div className="mt-5 overflow-x-auto rounded-lg border border-border">
<table className="w-full text-left text-sm" aria-label="Chart imports">
<thead className="bg-muted/40 text-xs text-muted-foreground">
<tr>
<th className="px-3 py-2 font-medium">Chart</th>
<th className="px-3 py-2 font-medium">Import from</th>
<th className="px-3 py-2 font-medium">Definition</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{pages.map((page) => {
const known =
CHART_IMPORTS[page.chartType as keyof typeof CHART_IMPORTS];
return (
<tr key={page.topic}>
<td className="px-3 py-1.5">
<Link className="text-docs-accent" to={docsPath(page.topic)}>
{page.title}
</Link>
</td>
<td className="whitespace-nowrap px-3 py-1.5 font-mono text-xs">
exploreda/charts/{known.entry}
</td>
<td className="whitespace-nowrap px-3 py-1.5 font-mono text-xs">
{known.name}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}

/** A link to the saved settings a chart type's docs page lists. */
function SettingsLink({ type }: { type: string }) {
const page = catalogue.find((item) => item.chartType === type);
Expand Down
11 changes: 11 additions & 0 deletions examples/standalone-charts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,14 @@ pnpm dev
`install-lib` packs the built library into `vendor/exploreda.tgz` and installs
it. Run it again after each library build. `pnpm build` type-checks the app
against the package's published types and builds it.

`index.html` uses `exploreda/chart`, which loads each chart type's code
when a chart of that type first draws. `lean.html` draws a bar chart and a
scatter plot through `exploreda/chart-core`, with only those two types
registered up front. After
`pnpm build`, `pnpm sizes` prints the JavaScript each page loads up front:

```
index.html up front 1,283 KB loaded on demand 2,756 KB
lean.html up front 1,425 KB loaded on demand 2,614 KB
```
12 changes: 12 additions & 0 deletions examples/standalone-charts/lean.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lean explorEDA charts</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/lean.tsx"></script>
</body>
</html>
3 changes: 2 additions & 1 deletion examples/standalone-charts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"install-lib": "pnpm run pack-lib && pnpm install --force",
"dev": "vite --host 127.0.0.1 --port 5480 --strictPort",
"build": "tsc --noEmit && vite build",
"preview": "vite preview --host 127.0.0.1 --port 5481 --strictPort"
"preview": "vite preview --host 127.0.0.1 --port 5481 --strictPort",
"sizes": "node scripts/sizes.mjs"
},
"dependencies": {
"exploreda": "file:vendor/exploreda.tgz",
Expand Down
28 changes: 28 additions & 0 deletions examples/standalone-charts/scripts/sizes.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Prints the JavaScript each page loads before it can draw: its entry chunk
// and every chunk that entry imports statically. Run after `pnpm build`.
import { readFileSync, statSync } from "node:fs";

const manifest = JSON.parse(readFileSync("dist/.vite/manifest.json", "utf8"));
const kb = (bytes) => `${Math.round(bytes / 1024).toLocaleString()} KB`;

function upFront(key, seen = new Set()) {
if (seen.has(key)) return seen;
seen.add(key);
for (const next of manifest[key].imports ?? []) upFront(next, seen);
return seen;
}

for (const [key, chunk] of Object.entries(manifest)) {
if (!chunk.isEntry) continue;
const files = [...upFront(key)].map((k) => manifest[k].file);
const bytes = files.reduce(
(sum, file) => sum + statSync(`dist/${file}`).size,
0
);
const lazy = Object.values(manifest)
.filter((c) => !files.includes(c.file) && c.file.endsWith(".js"))
.reduce((sum, c) => sum + statSync(`dist/${c.file}`).size, 0);
console.log(
`${key.padEnd(12)} up front ${kb(bytes).padStart(9)} loaded on demand ${kb(lazy)}`
);
}
49 changes: 49 additions & 0 deletions examples/standalone-charts/src/lean.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Chart, registerCharts } from "exploreda/chart-core";
import { barChartDefinition } from "exploreda/charts/bar";
import { scatterPlotDefinition } from "exploreda/charts/scatter";
import "exploreda/dist/chart.css";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { sales } from "./data";
import "./host.css";

// Only these two types reach the bundle.
registerCharts(barChartDefinition, scatterPlotDefinition);

function Lean() {
return (
<main>
<h1>Two chart types, nothing else</h1>
<div className="row" data-example="lean">
<div className="card">
<Chart
data={sales}
config={{ type: "bar", field: "Region" }}
height={280}
/>
</div>
<div className="card">
<Chart
data={sales}
config={{ type: "scatter", xField: "Price", yField: "Rating" }}
height={280}
/>
</div>
<div className="card">
{/* Not registered: the chart says which import to add. */}
<Chart
data={sales}
config={{ type: "line", xField: "Date" }}
height={280}
/>
</div>
</div>
</main>
);
}

createRoot(document.getElementById("root")!).render(
<StrictMode>
<Lean />
</StrictMode>
);
16 changes: 15 additions & 1 deletion examples/standalone-charts/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
import react from "@vitejs/plugin-react";
import { resolve } from "node:path";
import { defineConfig } from "vite";

export default defineConfig({ plugins: [react()] });
// Two pages: index.html loads chart types on demand through exploreda/chart;
// lean.html registers two types through exploreda/chart-core.
export default defineConfig({
plugins: [react()],
build: {
manifest: true,
rollupOptions: {
input: {
index: resolve(__dirname, "index.html"),
lean: resolve(__dirname, "lean.html"),
},
},
},
});
12 changes: 12 additions & 0 deletions packages/explorEDA/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,18 @@ this way. `config` also takes one chart's Dashboard text, such as
edit settings, or place a `ChartSettings` beside the chart. See [Standalone charts](https://exploreda.dev/docs/standalone-charts)
for the props and a config for each chart type.

`exploreda/chart` loads each chart type's code the first time a chart of
that type draws, so a page downloads only the types it shows. To register
types up front instead, with no request before the first draw, import from
`exploreda/chart-core`:

```tsx
import { Chart, registerCharts } from "exploreda/chart-core";
import { barChartDefinition } from "exploreda/charts/bar";

registerCharts(barChartDefinition);
```

## Read local files

`exploreda/readers` reads a local file into rows and field types. It reads
Expand Down
10 changes: 10 additions & 0 deletions packages/explorEDA/entries.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"ExplorEda": "src/components/ExplorEda.tsx",
"core": "src/charts/registry.ts",
"chart": "src/chart/index.ts",
"chart-core": "src/chart/core.ts",
"calculations": "src/lib/calculations/parser/semantics.ts",
"analysis": "src/analysis.ts",
"readers": "src/readers.ts",
Expand All @@ -24,6 +25,15 @@
"charts/scatter": "src/components/charts/ScatterPlot/definition.ts",
"charts/summary-table": "src/components/charts/SummaryTable/definition.ts",
"charts/three-d-scatter": "src/components/charts/ThreeDScatter/definition.ts",
"charts/composition": "src/components/charts/Composition/definition.ts",
"charts/hierarchy": "src/components/charts/Hierarchy/definition.ts",
"charts/scatter-matrix": "src/components/charts/ScatterMatrix/definition.ts",
"charts/waterfall": "src/components/charts/Waterfall/definition.ts",
"charts/donut": "src/components/charts/Donut/definition.ts",
"charts/funnel": "src/components/charts/Funnel/definition.ts",
"charts/retention": "src/components/charts/Retention/definition.ts",
"charts/timeline": "src/components/charts/Timeline/definition.ts",
"charts/joint-missingness": "src/components/charts/JointMissingness/definition.ts",
"docs-kit": "src/docsKit/index.ts"
}
}
8 changes: 8 additions & 0 deletions packages/explorEDA/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@
"require": "./dist/chart.cjs",
"import": "./dist/chart.js"
},
"./chart-core": {
"types": "./dist/chart-core.d.ts",
"require": "./dist/chart-core.cjs",
"import": "./dist/chart-core.js"
},
"./charts/*": {
"types": "./dist/charts/*.d.ts",
"require": "./dist/charts/*.cjs",
Expand Down Expand Up @@ -80,6 +85,9 @@
],
"chart": [
"./dist/chart.d.ts"
],
"chart-core": [
"./dist/chart-core.d.ts"
]
}
},
Expand Down
4 changes: 4 additions & 0 deletions packages/explorEDA/src/chart/Chart.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ import {
useDataLayerSnapshot,
} from "@/providers/DataLayerProvider";
import type { ChartSettings } from "@/types/ChartTypes";
import { registerAllCharts } from "@/charts/registerAllCharts";

// These tests draw charts; loading types on demand has its own test.
registerAllCharts();

// jsdom has no 2D canvas either; canvas charts skip their drawing.
HTMLCanvasElement.prototype.getContext = (() =>
Expand Down
24 changes: 23 additions & 1 deletion packages/explorEDA/src/chart/Chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
} from "react";
import { ChartErrorBoundary } from "./ChartErrorBoundary";
import { sortedText } from "./config";
import { useAllTypes } from "./typeLoading";
import { StandaloneProvider, type StandaloneProps } from "./StandaloneProvider";

export interface ChartProps extends StandaloneProps {
Expand Down Expand Up @@ -104,6 +105,24 @@ export function Chart({
onConfigChange={onConfigChange}
fields={fields}
chartId={id}
fallback={
// The chart's box, held while its type's code loads.
<div
className={[
"eda-standalone eda-standalone-loading",
props.className,
]
.filter(Boolean)
.join(" ")}
role="status"
aria-label="Loading chart"
style={{
width: props.width ?? "100%",
height: props.height ?? "100%",
...props.style,
}}
/>
}
>
<ChartBody
chartId={id}
Expand Down Expand Up @@ -244,8 +263,11 @@ function SettingsButton({
settings: ChartSettings;
name: string | undefined;
}) {
const [open, setOpen] = useState(false);
// The Chart Type list offers every type once settings open.
useAllTypes(open);
return (
<Popover>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
Expand Down
2 changes: 2 additions & 0 deletions packages/explorEDA/src/chart/ChartSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useDataLayer } from "@/providers/DataLayerProvider";
import { type CSSProperties, useId, useState } from "react";
import { ChartErrorBoundary } from "./ChartErrorBoundary";
import { sortedText } from "./config";
import { useAllTypes } from "./typeLoading";
import { StandaloneProvider, type StandaloneProps } from "./StandaloneProvider";

export interface ChartSettingsProps extends StandaloneProps {
Expand Down Expand Up @@ -56,6 +57,7 @@ function SettingsBody({
state.charts.find((chart) => chart.id === chartId)
);
const theme = useDataLayer((state) => state.theme);
useAllTypes();
const [layer, setLayer] = useState<HTMLDivElement | null>(null);
if (!settings) return null;
return (
Expand Down
Loading
Loading