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/chart-lazy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'layerchart': minor
---

feat(Chart): Add `lazy` to build a chart only once its container nears the viewport, with a `placeholder` snippet shown until then and a `lazy` setting to make it the default for every chart
4 changes: 4 additions & 0 deletions .github/workflows/update-generated.yml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ jobs:
env:
BASE_URL: http://localhost:3002

# Again, now the screenshot index has each example's height (measured as screenshots are taken)
- name: Add example heights to the catalog
run: pnpm --filter docs generate:catalog

- name: Save changes
run: |
mkdir -p /tmp/generated
Expand Down
2 changes: 1 addition & 1 deletion bundle-analyzer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"@sveltejs/vite-plugin-svelte": "^7.1.2",
"layerchart": "workspace:*",
"rollup-plugin-visualizer": "^7.0.1",
"svelte": "5.57.1",
"svelte": "5.60.0",
"tsx": "^4.22.4",
"typescript": "^6.0.3",
"vite": "^8.0.16"
Expand Down
6 changes: 3 additions & 3 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"test:visual:update": "node scripts/visual-snapshot.mjs capture snapshots/baseline.json --repeat 3",
"generate:api": "layerstack-docs generate-api ../packages/layerchart/src/lib/components generated/api && layerstack-docs generate-api ../packages/webgl/src/lib/components generated/api/webgl",
"generate:screenshots": "layerstack-docs generate-screenshots src/examples/components static/screenshots",
"generate:catalog": "layerstack-docs generate-catalog ../packages/layerchart/src/lib/components src/examples/components src/examples/catalog && layerstack-docs generate-catalog ../packages/webgl/src/lib/components src/examples/components src/examples/catalog/webgl",
"generate:catalog": "layerstack-docs generate-catalog ../packages/layerchart/src/lib/components src/examples/components src/examples/catalog --screenshots static/screenshots && layerstack-docs generate-catalog ../packages/webgl/src/lib/components src/examples/components src/examples/catalog/webgl --screenshots static/screenshots",
"generate:stackblitz": "layerstack-docs generate-stackblitz src static/stackblitz-files.json static/remote-sources.json --source src/lib/utils/data.ts=lib/utils/data.ts --source src/lib/utils/sports.ts=lib/utils/sports.ts --remote data.remote.ts=lib/data.remote.ts --remote geo.remote.ts=lib/geo.remote.ts --remote graph.remote.ts=lib/graph.remote.ts",
"generate:releases": "layerstack-docs generate-releases techniq/layerchart generated/releases",
"generate:all": "pnpm generate:api && pnpm generate:screenshots && pnpm generate:catalog && pnpm generate:stackblitz && pnpm generate:releases"
Expand All @@ -38,7 +38,7 @@
"@iconify-json/vscode-icons": "^1.2.53",
"@jsquash/webp": "^1.5.0",
"@layerchart/webgl": "workspace:*",
"@layerstack/docs": "1.0.0-next.11",
"@layerstack/docs": "1.0.0-next.12",
"@layerstack/svelte-actions": "1.0.1-next.21",
"@layerstack/svelte-state": "0.1.0-next.26",
"@layerstack/svelte-table": "1.0.1-next.21",
Expand Down Expand Up @@ -99,7 +99,7 @@
"runed": "^0.37.1",
"shapefile": "^0.6.6",
"solar-calculator": "^0.3.0",
"svelte": "5.57.1",
"svelte": "5.60.0",
"svelte-check": "^4.5.0",
"svelte-ux": "2.0.0-next.22",
"tailwindcss": "^4.3.0",
Expand Down
36 changes: 36 additions & 0 deletions docs/src/content/components/Chart.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,42 @@ To fit and then adjust, pass a function. It is given the size that fits:

The padding grows as soon as a label needs more room, but only shrinks once the labels have settled, so a domain animating or zooming through shorter labels doesn't nudge the plot on every frame. Until the axes have measured — including while server rendering — an `'auto'` side uses the default padding. A legend below the chart keeps its room under a fitted bottom axis.

## Lazy rendering

A page of many charts pays to build all of them up front, including the ones far below the fold. Set `lazy` to build a chart only once its container comes near the viewport:

```svelte
<LineChart {data} x="date" y="value" lazy />
```

- The container renders right away at its full size, so nothing shifts when the chart builds. Size it as you would any chart.
- The first chart on screen builds immediately, without an empty first frame. Others that arrive together (every chart on screen at load, or a fast scroll past several) follow one at a time as the browser is idle, rather than all building in one long task that blocks the page.
- The others build once they come within `200px` of the viewport. Pass `lazy={{ rootMargin: '600px' }}` to start sooner. `threshold` is also accepted.
- Once built, a chart stays built. Scrolling away keeps its tooltip, brush, and zoom state.
- A chart in a hidden container (ex. an inactive tab) builds when it's shown.
- With `ssr`, the server renders the empty container (and any `placeholder`).

### Placeholder

The `placeholder` snippet renders inside the container until the chart is built, for example a loading state. The container already has the chart's size, so `h-full` fills it.

:example{ component="Chart" name="lazy" showCode }

### Every chart on a page

Set `lazy` in [settings](/docs/guides/state#settings-global-defaults) to make it the default for every chart below. Charts that set their own `lazy`, including `false`, keep it.

```svelte
<script>
import { setSettings } from 'layerchart';
setSettings({ lazy: true });
</script>
```

:::note
With Svelte's `experimental.async`, use Svelte 5.60.0 or later. In earlier versions, a lazy chart that comes into view while an `await` elsewhere on the page is still pending builds much more slowly than usual ([sveltejs/svelte#19408](https://github.com/sveltejs/svelte/issues/19408)), and before 5.58.1 it could freeze the page ([sveltejs/svelte#18997](https://github.com/sveltejs/svelte/issues/18997)).
:::

## Text selection

Charts are treated as interactive widgets: `user-select: none` is applied to the root container (`.lc-root-container`) so dragging to brush, pan, or zoom never selects axis labels or surrounding page text. Since `user-select` inherits, this covers the whole chart.
Expand Down
3 changes: 2 additions & 1 deletion docs/src/content/guides/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ Global settings control defaults across all charts in the component tree. Set th

setSettings({
layer: 'svg', // default Layer type: 'svg' | 'canvas' | 'html'
debug: false
debug: false,
lazy: false // build charts only near the viewport (see Chart's `lazy`)
});
</script>
```
Expand Down
26 changes: 26 additions & 0 deletions docs/src/examples/components/Chart/lazy.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<script lang="ts">
import { AreaChart } from 'layerchart';
import { createDateSeries } from '$lib/utils/data.js';

const series = Array.from({ length: 100 }, () =>
createDateSeries({ count: 60, min: 20, max: 100, value: 'integer' })
);
export { series as data };
</script>

<!-- Scroll the list: each chart builds as it comes into view, showing its placeholder until then -->
<div class="h-[400px] overflow-auto grid gap-4 pr-2">
{#each series as data, i (i)}
<div class="h-[120px] shrink-0">
<AreaChart {data} x="date" y="value" lazy axis={false} grid={false}>
{#snippet placeholder()}
<div
class="h-full grid place-items-center rounded bg-surface-content/5 text-sm text-surface-content/50"
>
Loading chart {i + 1}…
</div>
{/snippet}
</AreaChart>
</div>
{/each}
</div>
168 changes: 86 additions & 82 deletions docs/src/lib/components/Example.svelte
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
<script lang="ts" module>
import type { ComponentCatalog } from '@layerstack/docs/catalog';

/** Each component's example catalog, loaded on demand (as a component's page loads its own) */
const catalogs = import.meta.glob<ComponentCatalog>('/src/examples/catalog/**/*.json', {
import: 'default'
});
</script>

<script lang="ts">
import type { SvelteComponent } from 'svelte';
import { slide } from 'svelte/transition';
Expand Down Expand Up @@ -47,7 +56,6 @@
const settings = getSettings();
import { movable } from '$lib/actions/movable';
import { nativeWebGLExamples, webglExamples } from 'virtual:webgl-examples';
import LayerSetting from '$lib/components/LayerSetting.svelte';

let {
// The page's component: its folder under `src/examples/components` (ex. `Points`)
Expand Down Expand Up @@ -78,33 +86,21 @@
// Cache context at init time — getContext() must be called during component initialization
const examplesCtx = examples.get();

// Use $state + $effect to break potential infinite reactivity loops during HMR
let loadedExample = $state<{ component: any; source: string } | undefined>(undefined);

$effect(() => {
const loadedExample = $derived.by((): { component: any; source: string } | undefined => {
const current = examplesCtx?.current;
let next: typeof example;
if (path) {
// Path-based example
const resolvedPath = resolveExamplePath(
path,
page.url.pathname,
page.url.pathname.startsWith('/docs/guides/') ? 'guides' : 'components'
);
next = current?.['__path__']?.[resolvedPath];
return current?.['__path__']?.[resolvedPath];
} else if (component && name) {
// Component/name-based example
next = current?.[component]?.[name];
} else {
next = undefined;
return current?.[component]?.[name];
}
// Only assign if the reference actually changed to avoid unnecessary downstream reactivity
// Untrack both the read and write to prevent this effect from depending on its own output
untrack(() => {
if (loadedExample !== next) {
loadedExample = next;
}
});
return undefined;
});

/**
Expand All @@ -118,14 +114,23 @@
: undefined
);
let webglExample = $state<{ component: any; source: string } | undefined>(undefined);
/** The WebGL version didn't load: show LayerChart's instead (drawn with Canvas) */
let webglFailed = $state(false);
$effect(() => {
const load = loadWebGL;
webglExample = undefined;
webglFailed = false;
if (!load) return;
let current = true;
load().then((loaded) => {
if (current) webglExample = loaded;
});
load().then(
(loaded) => {
if (current) webglExample = loaded;
},
(error) => {
console.error(`Couldn't load the WebGL version of ${component}/${name}`, error);
if (current) webglFailed = true;
}
);
return () => {
current = false;
};
Expand All @@ -135,8 +140,35 @@
const nativeWebGL = $derived(
!!component && !!name && !path && nativeWebGLExamples.has(`${component}/${name}`)
);
/** Drawn with Canvas while the layer is `webgl`: no WebGL version (or not loaded yet) */
const canvasInstead = $derived(settings.layer === 'webgl' && !webglExample && !nativeWebGL);
/**
* Waiting on this example's WebGL version: draw nothing until it's here, rather than LayerChart's
* version that it replaces (built twice, and drawn with Canvas in between)
*/
const loadingWebGL = $derived(!!loadWebGL && !webglExample && !webglFailed);

/**
* The example's height from its component's catalog (measured by `generate:screenshots`), to hold
* its space while its WebGL version loads so the page doesn't jump when it arrives. Only read
* while one's loading. On a component's page its catalog is already loaded, so this lands before
* the first paint.
*/
let heldHeight = $state<number>();
$effect(() => {
heldHeight = undefined;
if (!loadingWebGL || !component || !name) return;
const catalogPath = [
`/src/examples/catalog/${component}.json`,
`/src/examples/catalog/webgl/${component}.json`
].find((path) => path in catalogs);
if (!catalogPath) return;
let current = true;
catalogs[catalogPath]().then((catalog) => {
if (current) heldHeight = catalog.examples.find((e) => e.name === name)?.height;
});
return () => {
current = false;
};
});

/**
* Code beside the preview rather than below it. Only offered with room for both, and
Expand Down Expand Up @@ -236,29 +268,6 @@
return true;
});

let sentinelEl = $state<HTMLElement | null>(null);
let intersected = $state(false);
const lazy = $derived(!isDetailPage);
let isVisible = $derived(!lazy || intersected);

$effect(() => {
if (!lazy || !sentinelEl) return;

const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
intersected = true;
observer.disconnect();
}
},
{ rootMargin: '200px' }
);
observer.observe(sentinelEl);
return () => observer.disconnect();
});

// $inspect({ component, name, isVisible, intersected, lazy, example });

let svgUnavailable = $state(false);
let svgUnavailableTimer: ReturnType<typeof setTimeout>;

Expand Down Expand Up @@ -341,49 +350,44 @@
style:width={!split && containerWidth ? `${containerWidth}px` : undefined}
style:view-transition-name={viewTransitionName}
>
{#if isVisible}
<svelte:boundary>
{#if sandbox.live}
<!--
<svelte:boundary>
{#if sandbox.live}
<!--
Edited: render the user's source instead of the shipped component. Each
build mounts hidden in here and is swapped in once it has rendered, so
the shipped component stays up until the first one is ready.
-->
<div
class={cls('relative', sandbox.error && 'opacity-40')}
{@attach sandbox.preview}
></div>
{/if}
{#if !sandbox.showing && example}
{#if canvasInstead}
<LayerSetting layer="canvas">
<example.component bind:this={ref} />
</LayerSetting>
{:else}
<example.component bind:this={ref} />
{/if}
<div
class={cls('relative', sandbox.error && 'opacity-40')}
{@attach sandbox.preview}
></div>
{/if}
{#if !sandbox.showing && example}
{#if loadingWebGL}
<!-- Its space, until its WebGL version is here -->
<div style:height={heldHeight ? `${heldHeight}px` : undefined}></div>
{:else}
<example.component bind:this={ref} />
{/if}
{#snippet failed(error, reset)}
<div class="border border-danger rounded-md bg-danger/5 p-4 text-sm">
<div class="font-semibold text-danger mb-2">
Example error{#if component && name}: {component}/{name}{/if}
</div>
<pre
class="text-danger/80 whitespace-pre-wrap break-words overflow-auto max-h-60">{error}</pre>
<Button variant="outline" color="danger" size="sm" class="mt-2" on:click={reset}
>Retry</Button
>
{/if}
{#snippet failed(error, reset)}
<div class="border border-danger rounded-md bg-danger/5 p-4 text-sm">
<div class="font-semibold text-danger mb-2">
Example error{#if component && name}: {component}/{name}{/if}
</div>
{/snippet}
{#snippet pending()}
<div class="min-h-80 flex items-center justify-center text-surface-content/30">
Loading...
</div>
{/snippet}
</svelte:boundary>
{:else}
<div bind:this={sentinelEl} class="min-h-80"></div>
{/if}
<pre
class="text-danger/80 whitespace-pre-wrap break-words overflow-auto max-h-60">{error}</pre>
<Button variant="outline" color="danger" size="sm" class="mt-2" on:click={reset}
>Retry</Button
>
</div>
{/snippet}
{#snippet pending()}
<div class="min-h-80 flex items-center justify-center text-surface-content/30">
Loading...
</div>
{/snippet}
</svelte:boundary>

<!-- Beside the code, the pane divider sets the width instead. -->
{#if canResize && !split}
Expand Down
20 changes: 0 additions & 20 deletions docs/src/lib/components/LayerSetting.svelte

This file was deleted.

2 changes: 1 addition & 1 deletion docs/src/lib/components/PageHeader.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
icon?: Component<{ class?: string }>;
} = $props();

// TODO: `setSettings({...})` or just use default?
// The docs layout's settings (`setSettings` in `routes/docs/+layout.svelte`)
const settings = getSettings();
const layerOrder = ['svg', 'canvas', 'html', 'webgl'];
const layerLabels: Record<string, string> = { webgl: 'WebGL' };
Expand Down
Loading
Loading