Skip to content
Open
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
36 changes: 36 additions & 0 deletions docs/src/content/components/Chart.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,42 @@ Most of what a chart can do is configured on `Chart`, and each part has its own
| [Geo](/docs/guides/geo) | `geo` |
| [Isometric](/docs/guides/isometric) | `view` |

## 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.
- A chart that is already on screen builds immediately, without an empty first frame.
- 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`, a lazy chart that comes into view while an `await` elsewhere on the page is still pending can stall 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>
48 changes: 48 additions & 0 deletions packages/layerchart/src/lib/attachments/nearViewport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { Attachment } from 'svelte/attachments';

export type NearViewportOptions = {
/** How far outside the viewport counts as near, as a CSS margin. Defaults to `'200px'`. */
rootMargin?: string;
/** Passed to the `IntersectionObserver` */
threshold?: number | number[];
};

/**
* Calls `onNear` once, with the element, when it's on screen or comes within `rootMargin` of it.
*
* An element already on screen is reported immediately, in the same flush it attaches in, rather
* than at the observer's first (asynchronous) report — so whatever it reveals doesn't paint empty
* for a frame. Elements attaching together all read their position before any of them reacts, so
* the browser lays out once for all of them. A hidden element (no box) waits for the observer, and
* so is reported when it's shown.
*/
export function nearViewport(
onNear: (node: HTMLElement) => void,
options: NearViewportOptions = {}
): Attachment<HTMLElement> {
return (node) => {
const rect = node.getBoundingClientRect();
if (
(rect.width > 0 || rect.height > 0) &&
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= window.innerHeight &&
rect.left <= window.innerWidth
) {
onNear(node);
return;
}

const observer = new IntersectionObserver(
(entries) => {
if (entries.some((e) => e.isIntersecting)) {
observer.disconnect();
onNear(node);
}
},
{ rootMargin: options.rootMargin ?? '200px', threshold: options.threshold }
);
observer.observe(node);
return () => observer.disconnect();
};
}
10 changes: 10 additions & 0 deletions packages/layerchart/src/lib/bench/LazyBench.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<script lang="ts">
import LineChart from '../components/charts/LineChart/LineChart.svelte';
let { data, count, lazy }: { data: any[]; count: number; lazy: boolean } = $props();
</script>

{#each { length: count }, i (i)}
<div style="height: 300px">
<LineChart {data} x="date" y="value" {lazy} />
</div>
{/each}
18 changes: 18 additions & 0 deletions packages/layerchart/src/lib/bench/lazy.svelte.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { describe, bench, afterEach } from 'vitest';
import { render, cleanup } from 'vitest-browser-svelte';
import LazyBench from './LazyBench.svelte';
import { generateTimeSeriesData } from './generateData.js';

afterEach(() => cleanup());

describe('50 stacked LineCharts (≈3 on screen)', () => {
const data = generateTimeSeriesData(500);
bench('eager', () => {
cleanup();
render(LazyBench, { data, count: 50, lazy: false });
});
bench('lazy', () => {
cleanup();
render(LazyBench, { data, count: 50, lazy: true });
});
});
40 changes: 36 additions & 4 deletions packages/layerchart/src/lib/components/Chart/Chart.base.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
expandBandBrushDomain,
} from '$lib/states/brush.svelte.js';

import { nearViewport } from '$lib/attachments/nearViewport.js';

import TooltipContext from '../tooltip/TooltipContext.svelte';

let {
Expand All @@ -52,6 +54,8 @@

let {
ssr = false,
lazy: lazyProp,
placeholder,
pointerEvents = true,
width,
height,
Expand Down Expand Up @@ -512,13 +516,38 @@
let TransformContext = $state<typeof import('../TransformContext.svelte').default>();
let BrushContext = $state<typeof import('../BrushContext.svelte').default>();

const lazy = $derived(lazyProp ?? settings.lazy);
/**
* Whether the subtree may be built. Latched — once a lazy chart has been near the viewport it
* stays built, so scrolling back past it doesn't tear down and rebuild its marks.
*/
let activated = $state(untrack(() => !lazy));
const active = $derived(!lazy || activated);

/**
* Builds a lazy chart once its container nears the viewport.
*
* Measures the element it's handed rather than leaving that to the measure effect below: under
* `experimental.async`, an activation that lands while another batch is pending (ex. an `await`
* elsewhere on the page) reads `ref` as it was before that batch, `undefined`, and the chart
* would never build.
*/
function activate(node: HTMLElement) {
if (needsMeasure) {
chartState._containerWidth = node.clientWidth;
chartState._containerHeight = node.clientHeight;
chartState.isMeasured = true;
}
activated = true;
}

$effect(() => {
if (transform && !TransformContext) {
if (transform && active && !TransformContext) {
import('../TransformContext.svelte').then((m) => (TransformContext = m.default));
}
});
$effect(() => {
if (brush && !BrushContext) {
if (brush && active && !BrushContext) {
import('../BrushContext.svelte').then((m) => (BrushContext = m.default));
}
});
Expand All @@ -538,7 +567,7 @@
* Reading the element here costs one layout per chart and gets them the real numbers first time.
*/
$effect(() => {
if (!needsMeasure || !ref) return;
if (!needsMeasure || !active || !ref) return;
chartState._containerWidth = ref.clientWidth;
chartState._containerHeight = ref.clientHeight;
chartState.isMeasured = true;
Expand All @@ -548,6 +577,7 @@
{#if ssr === true || typeof window !== 'undefined'}
<div
bind:this={ref}
{@attach lazy && !activated ? nearViewport(activate, lazy === true ? undefined : lazy) : null}
style:position
style:top={position === 'absolute' ? 0 : null}
style:right={position === 'absolute' ? 0 : null}
Expand All @@ -562,7 +592,7 @@
class={['lc-root-container', className]}
{...restProps}
>
{#if !needsMeasure || chartState.isMeasured}
{#if active && (!needsMeasure || chartState.isMeasured)}
{#if transform && TransformContext}
<!-- Lazy-load TransformContext only when transform is enabled -->
{@const {
Expand Down Expand Up @@ -598,6 +628,8 @@
{:else}
{@render inner()}
{/if}
{:else}
{@render placeholder?.()}
{/if}
</div>
{/if}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
ChartProps,
ChartPropsWithoutHTML,
ChartResizeDetail,
ChartLazyProp,
PreservedChartConfig,
LayerChartInternalMeta,
} from './Chart.shared.svelte.js';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
ChartProps,
ChartPropsWithoutHTML,
ChartResizeDetail,
ChartLazyProp,
PreservedChartConfig,
LayerChartInternalMeta,
} from './Chart.shared.svelte.js';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { render } from 'vitest-browser-svelte';
import { flushSync } from 'svelte';

import LazyChartsHarness from '$lib/tests/LazyChartsHarness.svelte';

const built = (i: number) =>
document.querySelector(`[data-chart="${i}"] .lc-root-container svg`) != null;
const placeholderShown = (i: number) =>
document.querySelector(`[data-chart="${i}"] .lc-root-container .placeholder`) != null;

describe('Chart lazy', () => {
// Tests scroll the page — start each at the top, where chart 0 is on screen
beforeEach(() => window.scrollTo(0, 0));

it('builds on-screen charts in the first flush and defers the rest', () => {
render(LazyChartsHarness, { count: 20, lazy: true });
flushSync();
expect(built(0)).toBe(true);
expect(built(19)).toBe(false);
// The container is still laid out, so the page doesn't shift once it builds
const container = document.querySelector('[data-chart="19"] .lc-root-container')!;
expect(container.getBoundingClientRect().height).toBe(300);
});

it('builds a chart once it scrolls near the viewport, and keeps it', async () => {
render(LazyChartsHarness, { count: 20, lazy: true });
document.querySelector('[data-chart="19"]')!.scrollIntoView();
await expect.poll(() => built(19)).toBe(true);
window.scrollTo(0, 0);
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
expect(built(19)).toBe(true);
});

it('builds everything when not lazy', () => {
render(LazyChartsHarness, { count: 20, lazy: false });
flushSync();
expect(built(19)).toBe(true);
});

it('renders the placeholder until the chart is built', async () => {
render(LazyChartsHarness, { count: 20, lazy: true });
flushSync();
expect(placeholderShown(0)).toBe(false);
expect(placeholderShown(19)).toBe(true);
document.querySelector('[data-chart="19"]')!.scrollIntoView();
await expect.poll(() => built(19)).toBe(true);
expect(placeholderShown(19)).toBe(false);
});

it('defaults to the `lazy` setting', () => {
render(LazyChartsHarness, { count: 20, settingsLazy: true });
flushSync();
expect(built(0)).toBe(true);
expect(built(19)).toBe(false);
});

it('lets a chart opt out of the `lazy` setting', () => {
render(LazyChartsHarness, { count: 20, settingsLazy: true, lazy: false });
flushSync();
expect(built(19)).toBe(true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import type BrushContext from '../BrushContext.svelte';
import type { ChartChildrenProps } from '../ChartChildren/ChartChildren.shared.svelte.js';
import type { SeriesData } from '../charts/types.js';

export type ChartLazyProp = boolean | { rootMargin?: string; threshold?: number | number[] };

export type ChartResizeDetail = {
width: number;
height: number;
Expand Down Expand Up @@ -92,6 +94,25 @@ export type ChartPropsWithoutHTML<
*/
ssr?: boolean;

/**
* Defer building the chart until its container scrolls near the viewport. The container is
* laid out immediately (so the page doesn't shift); marks, axes, and interaction contexts are
* created the first time it intersects, and stay once created.
*
* Pass an object to tune the observer — `rootMargin` (default `'200px'`) starts building
* before the chart is on screen. Defaults to the `lazy` setting (see `setSettings`).
*
* @default false
*/
lazy?: ChartLazyProp;

/**
* Rendered inside the container until the chart is built — while a `lazy` chart waits to come
* into view, and in its server-rendered markup. The container is already sized, so `h-full`
* fills the space the chart will take.
*/
placeholder?: Snippet;

/**
* Whether to allow pointer events via CSS.
* Set this to `false` to set `pointer-events: none;` on all components, disabling
Expand Down
1 change: 1 addition & 0 deletions packages/layerchart/src/lib/components/Chart/Chart.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
ChartProps,
ChartPropsWithoutHTML,
ChartResizeDetail,
ChartLazyProp,
PreservedChartConfig,
LayerChartInternalMeta,
} from './Chart.shared.svelte.js';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
ChartProps,
ChartPropsWithoutHTML,
ChartResizeDetail,
ChartLazyProp,
PreservedChartConfig,
LayerChartInternalMeta,
} from './Chart.shared.svelte.js';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
ChartProps,
ChartPropsWithoutHTML,
ChartResizeDetail,
ChartLazyProp,
PreservedChartConfig,
LayerChartInternalMeta,
} from './Chart.shared.svelte.js';
Expand Down
Loading
Loading