diff --git a/.changeset/chart-lazy.md b/.changeset/chart-lazy.md new file mode 100644 index 0000000000..d53160f83c --- /dev/null +++ b/.changeset/chart-lazy.md @@ -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 diff --git a/docs/src/content/components/Chart.md b/docs/src/content/components/Chart.md index 8c515f898f..6e2ab40ecf 100644 --- a/docs/src/content/components/Chart.md +++ b/docs/src/content/components/Chart.md @@ -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 + +``` + +- 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 + +``` + +:::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. diff --git a/docs/src/content/guides/state.md b/docs/src/content/guides/state.md index 0c9f22fa21..1aba222c78 100644 --- a/docs/src/content/guides/state.md +++ b/docs/src/content/guides/state.md @@ -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`) }); ``` diff --git a/docs/src/examples/components/Chart/lazy.svelte b/docs/src/examples/components/Chart/lazy.svelte new file mode 100644 index 0000000000..ead6cb3190 --- /dev/null +++ b/docs/src/examples/components/Chart/lazy.svelte @@ -0,0 +1,26 @@ + + + +
+ {#each series as data, i (i)} +
+ + {#snippet placeholder()} +
+ Loading chart {i + 1}… +
+ {/snippet} +
+
+ {/each} +
diff --git a/packages/layerchart/src/lib/attachments/nearViewport.ts b/packages/layerchart/src/lib/attachments/nearViewport.ts new file mode 100644 index 0000000000..2c2833ee1b --- /dev/null +++ b/packages/layerchart/src/lib/attachments/nearViewport.ts @@ -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 { + 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(); + }; +} diff --git a/packages/layerchart/src/lib/bench/LazyBench.svelte b/packages/layerchart/src/lib/bench/LazyBench.svelte new file mode 100644 index 0000000000..c763a791ac --- /dev/null +++ b/packages/layerchart/src/lib/bench/LazyBench.svelte @@ -0,0 +1,10 @@ + + +{#each { length: count }, i (i)} +
+ +
+{/each} diff --git a/packages/layerchart/src/lib/bench/lazy.svelte.bench.ts b/packages/layerchart/src/lib/bench/lazy.svelte.bench.ts new file mode 100644 index 0000000000..4b49baeb62 --- /dev/null +++ b/packages/layerchart/src/lib/bench/lazy.svelte.bench.ts @@ -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 }); + }); +}); diff --git a/packages/layerchart/src/lib/components/Chart/Chart.base.svelte b/packages/layerchart/src/lib/components/Chart/Chart.base.svelte index f8e30fac48..b3731c0ab8 100644 --- a/packages/layerchart/src/lib/components/Chart/Chart.base.svelte +++ b/packages/layerchart/src/lib/components/Chart/Chart.base.svelte @@ -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 { @@ -52,6 +54,8 @@ let { ssr = false, + lazy: lazyProp, + placeholder, pointerEvents = true, width, height, @@ -512,13 +516,38 @@ let TransformContext = $state(); let BrushContext = $state(); + 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)); } }); @@ -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; @@ -548,6 +577,7 @@ {#if ssr === true || typeof window !== 'undefined'}
- {#if !needsMeasure || chartState.isMeasured} + {#if active && (!needsMeasure || chartState.isMeasured)} {#if transform && TransformContext} {@const { @@ -598,6 +628,8 @@ {:else} {@render inner()} {/if} + {:else} + {@render placeholder?.()} {/if}
{/if} diff --git a/packages/layerchart/src/lib/components/Chart/Chart.canvas.svelte b/packages/layerchart/src/lib/components/Chart/Chart.canvas.svelte index 2af82863ca..ff810d8b5c 100644 --- a/packages/layerchart/src/lib/components/Chart/Chart.canvas.svelte +++ b/packages/layerchart/src/lib/components/Chart/Chart.canvas.svelte @@ -3,6 +3,7 @@ ChartProps, ChartPropsWithoutHTML, ChartResizeDetail, + ChartLazyProp, PreservedChartConfig, LayerChartInternalMeta, } from './Chart.shared.svelte.js'; diff --git a/packages/layerchart/src/lib/components/Chart/Chart.html.svelte b/packages/layerchart/src/lib/components/Chart/Chart.html.svelte index 2a7b01cc24..966ac36ca1 100644 --- a/packages/layerchart/src/lib/components/Chart/Chart.html.svelte +++ b/packages/layerchart/src/lib/components/Chart/Chart.html.svelte @@ -3,6 +3,7 @@ ChartProps, ChartPropsWithoutHTML, ChartResizeDetail, + ChartLazyProp, PreservedChartConfig, LayerChartInternalMeta, } from './Chart.shared.svelte.js'; diff --git a/packages/layerchart/src/lib/components/Chart/Chart.lazy.svelte.test.ts b/packages/layerchart/src/lib/components/Chart/Chart.lazy.svelte.test.ts new file mode 100644 index 0000000000..6f229ba33f --- /dev/null +++ b/packages/layerchart/src/lib/components/Chart/Chart.lazy.svelte.test.ts @@ -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); + }); +}); diff --git a/packages/layerchart/src/lib/components/Chart/Chart.shared.svelte.ts b/packages/layerchart/src/lib/components/Chart/Chart.shared.svelte.ts index 544b2864df..0a8ade3fb6 100644 --- a/packages/layerchart/src/lib/components/Chart/Chart.shared.svelte.ts +++ b/packages/layerchart/src/lib/components/Chart/Chart.shared.svelte.ts @@ -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; @@ -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 diff --git a/packages/layerchart/src/lib/components/Chart/Chart.svelte b/packages/layerchart/src/lib/components/Chart/Chart.svelte index 430965d44c..270fd00dca 100644 --- a/packages/layerchart/src/lib/components/Chart/Chart.svelte +++ b/packages/layerchart/src/lib/components/Chart/Chart.svelte @@ -3,6 +3,7 @@ ChartProps, ChartPropsWithoutHTML, ChartResizeDetail, + ChartLazyProp, PreservedChartConfig, LayerChartInternalMeta, } from './Chart.shared.svelte.js'; diff --git a/packages/layerchart/src/lib/components/Chart/Chart.svg.svelte b/packages/layerchart/src/lib/components/Chart/Chart.svg.svelte index be3ce27f4e..092a6151bb 100644 --- a/packages/layerchart/src/lib/components/Chart/Chart.svg.svelte +++ b/packages/layerchart/src/lib/components/Chart/Chart.svg.svelte @@ -3,6 +3,7 @@ ChartProps, ChartPropsWithoutHTML, ChartResizeDetail, + ChartLazyProp, PreservedChartConfig, LayerChartInternalMeta, } from './Chart.shared.svelte.js'; diff --git a/packages/layerchart/src/lib/components/Chart/ChartCore.svelte b/packages/layerchart/src/lib/components/Chart/ChartCore.svelte index 6f35ed6580..bd706fbfbe 100644 --- a/packages/layerchart/src/lib/components/Chart/ChartCore.svelte +++ b/packages/layerchart/src/lib/components/Chart/ChartCore.svelte @@ -3,6 +3,7 @@ ChartProps, ChartPropsWithoutHTML, ChartResizeDetail, + ChartLazyProp, PreservedChartConfig, LayerChartInternalMeta, } from './Chart.shared.svelte.js'; diff --git a/packages/layerchart/src/lib/states/settings.svelte.ts b/packages/layerchart/src/lib/states/settings.svelte.ts index 490c99e4ad..b24ff1999e 100644 --- a/packages/layerchart/src/lib/states/settings.svelte.ts +++ b/packages/layerchart/src/lib/states/settings.svelte.ts @@ -1,11 +1,14 @@ import type { LayerContext } from '$lib/contexts/layer.js'; import type { ChartViewProp } from '$lib/views/view.js'; +import type { ChartLazyProp } from '$lib/components/Chart/Chart.shared.svelte.js'; export type SettingsOptions = { layer?: LayerContext; debug?: boolean; /** The `view` of every chart that doesn't set its own (ex. `isometric`) */ view?: ChartViewProp | null; + /** The `lazy` of every chart that doesn't set its own (ex. `true` for a page of many charts) */ + lazy?: ChartLazyProp; }; /** Global settings context for charts */ @@ -13,12 +16,14 @@ export class Settings { layer: LayerContext; debug: boolean; view: ChartViewProp | null; + lazy: ChartLazyProp; constructor(options: SettingsOptions = {}) { this.layer = $state(options.layer ?? 'svg'); this.debug = $state(options.debug ?? false); // Raw: a view carries functions and components, which needn't be proxied this.view = $state.raw(options.view ?? null); + this.lazy = $state.raw(options.lazy ?? false); } } diff --git a/packages/layerchart/src/lib/tests/LazyChartsHarness.svelte b/packages/layerchart/src/lib/tests/LazyChartsHarness.svelte new file mode 100644 index 0000000000..e183ac36fa --- /dev/null +++ b/packages/layerchart/src/lib/tests/LazyChartsHarness.svelte @@ -0,0 +1,28 @@ + + +{#each { length: count }, i (i)} +
+ + {#snippet placeholder()} +
Loading…
+ {/snippet} +
+
+{/each}