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
54 changes: 42 additions & 12 deletions src/components/Charts/SkiaWebChart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,22 @@ import variables from '@styles/variables';
import type {TranslationPaths} from '@src/languages/types';
import viewRef from '@src/types/utils/viewRef';

import type {ComponentType} from 'react';
import type {ComponentType, LazyExoticComponent} from 'react';

import * as Sentry from '@sentry/react-native';
import {WithSkiaWeb} from '@shopify/react-native-skia/lib/module/web';
import React, {useRef, useState} from 'react';
import {LoadSkiaWeb} from '@shopify/react-native-skia/lib/module/web';
import React, {lazy, Suspense, useRef, useState} from 'react';
import {ErrorBoundary} from 'react-error-boundary';
import {View} from 'react-native';

import isSkiaWebSupported from './isSkiaWebSupported';
import useIsSkiaSurfaceUnavailable from './useIsSkiaSurfaceUnavailable';

type ChartLoader<TProps> = () => Promise<{default: ComponentType<TProps>}>;

type SkiaWebChartProps<TProps> = {
/** Lazily imports the Skia-backed chart component to render. */
getComponent: () => Promise<{default: ComponentType<TProps>}>;
getComponent: ChartLoader<TProps>;

/** Props forwarded to the lazily-loaded chart component. */
componentProps: TProps;
Expand All @@ -45,6 +47,35 @@ type ChartUnavailableProps = {
*/
const locateCanvasKitFile = (file: string) => (file === 'canvaskit.wasm' ? __CANVASKIT_WASM_URL__ : `/${file}`);

/**
* One lazy component per chart loader, kept for the session. A lazy component renders without suspending only once
* its own load has resolved, so one created per mount (as `WithSkiaWeb` does) suspends on every mount, and production
* React commits the fallback for a few frames even when the chart's code and CanvasKit are already loaded.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- each loader renders a chart with its own props, so the map holds every props type
const lazyCharts = new Map<ChartLoader<any>, LazyExoticComponent<ComponentType<any>>>();

function getLazyChart<TProps>(getComponent: ChartLoader<TProps>) {
const cachedChart = lazyCharts.get(getComponent);
if (cachedChart) {
return cachedChart as LazyExoticComponent<ComponentType<TProps>>;
}

const LazyChart = lazy(async () => {
try {
// The glue mutates `opts` into the module object, so give each load its own object rather than sharing one.
await LoadSkiaWeb({locateFile: locateCanvasKitFile});
return await getComponent();
} catch (error) {
// React keeps a lazy component's rejection for good, so drop it and let the next mount retry the load.
lazyCharts.delete(getComponent);
throw error;
}
});
lazyCharts.set(getComponent, LazyChart);
return LazyChart;
}

function ChartUnavailable({description = 'common.webGLNotSupported'}: ChartUnavailableProps) {
const styles = useThemeStyles();
const {translate} = useLocalize();
Expand Down Expand Up @@ -97,7 +128,7 @@ const logSkiaLoadError = (error: Error, info: {componentStack?: string | null})
};

/**
* Shared web wrapper around `WithSkiaWeb` for the chart entry points (Pie/Line/Bar and the Victory
* Shared web wrapper that loads CanvasKit and the chart's code for the chart entry points (Pie/Line/Bar and the Victory
* renderer). When the environment can't provide a usable WebGL/Skia surface it shows an "unable to
* display chart" empty state instead of mounting Skia, avoiding the CanvasKit GL-init crash (see `isSkiaWebSupported`).
* If CanvasKit itself fails to load or link, the error boundary degrades to the same empty state.
Expand Down Expand Up @@ -130,6 +161,8 @@ function SkiaWebChart<TProps extends object>({getComponent, componentProps}: Ski
</View>
);

const LazyChart = getLazyChart(getComponent);

return (
<View
ref={viewRef(containerRef)}
Expand All @@ -139,13 +172,10 @@ function SkiaWebChart<TProps extends object>({getComponent, componentProps}: Ski
FallbackComponent={ChartFailedToLoad}
onError={logSkiaLoadError}
>
{/* The glue mutates `opts` into the module object, so give each mount its own object rather than sharing one. */}
<WithSkiaWeb
opts={{locateFile: locateCanvasKitFile}}
getComponent={getComponent}
componentProps={componentProps}
fallback={fallback}
/>
<Suspense fallback={fallback}>
{/* eslint-disable-next-line react-hooks/static-components -- getLazyChart returns the same component for a loader on every render, so its state is never reset */}
<LazyChart {...componentProps} />
</Suspense>
</ErrorBoundary>
</View>
);
Expand Down
163 changes: 131 additions & 32 deletions tests/unit/components/Charts/SkiaWebChart.test.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import {render, screen} from '@testing-library/react-native';
import {act, render, screen} from '@testing-library/react-native';

import ActivityIndicator from '@components/ActivityIndicator';
import ChartReveal, {useReportChartLoading} from '@components/Charts/components/ChartReveal';
import SkiaWebChart from '@components/Charts/SkiaWebChart';
import isSkiaWebSupported from '@components/Charts/SkiaWebChart/isSkiaWebSupported';
import {getCartesianChartHeight} from '@components/Charts/utils/chartHeights';

import type {ComponentType} from 'react';

import * as Sentry from '@sentry/react-native';
import {WithSkiaWeb} from '@shopify/react-native-skia/lib/module/web';
import {LoadSkiaWeb} from '@shopify/react-native-skia/lib/module/web';
import React from 'react';
import {View} from 'react-native';

import waitForBatchedUpdatesWithAct from '../../../utils/waitForBatchedUpdatesWithAct';

jest.mock('@components/Charts/SkiaWebChart/isSkiaWebSupported', () => jest.fn());

jest.mock('@shopify/react-native-skia/lib/module/web', () => ({WithSkiaWeb: jest.fn(() => null)}));
jest.mock('@shopify/react-native-skia/lib/module/web', () => ({LoadSkiaWeb: jest.fn()}));

jest.mock('@sentry/react-native', () => ({captureException: jest.fn(), setUser: jest.fn()}));

Expand All @@ -34,18 +38,38 @@ jest.mock('@components/Icon', () => ({
const CHART_LOADING_HEIGHT = getCartesianChartHeight();

const mockIsSkiaWebSupported = jest.mocked(isSkiaWebSupported);
const mockWithSkiaWeb = jest.mocked(WithSkiaWeb);
const mockLoadSkiaWeb = jest.mocked(LoadSkiaWeb);
const mockCaptureException = jest.mocked(Sentry.captureException);

function LoadedChart() {
return <View testID="loaded-chart" />;
}

function ReadyChart() {
useReportChartLoading(false);
return null;
return <View testID="ready-chart" />;
}

describe('SkiaWebChart', () => {
const getComponent = () => Promise.resolve({default: () => null});
// SkiaWebChart keeps one lazy component per loader for the session, so each test makes its own loader to start uncached.
function createChartLoader(Chart: ComponentType = LoadedChart) {
return jest.fn(() => Promise.resolve({default: Chart}));
}

// Holds the next CanvasKit load open until the test settles it.
function deferSkiaLoad() {
let resolve = () => {};
let reject: (error: Error) => void = () => {};
mockLoadSkiaWeb.mockReturnValueOnce(
new Promise<void>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
}),
);
return {resolve: () => resolve(), reject: (error: Error) => reject(error)};
}

const renderRevealedChart = () => (
describe('SkiaWebChart', () => {
const renderRevealedChart = (getComponent: ReturnType<typeof createChartLoader>) => (
<ChartReveal
loadingHeight={CHART_LOADING_HEIGHT}
isCardMeasured
Expand All @@ -57,37 +81,44 @@ describe('SkiaWebChart', () => {
</ChartReveal>
);

beforeEach(() => {
mockLoadSkiaWeb.mockResolvedValue(undefined);
});

afterEach(() => {
jest.clearAllMocks();
});

it('should show the unable-to-display empty state without mounting Skia when WebGL is unsupported', () => {
// Given a browser without WebGL
mockIsSkiaWebSupported.mockReturnValue(false);
const getComponent = createChartLoader();

// When the chart mounts
render(
<SkiaWebChart
getComponent={getComponent}
componentProps={{}}
/>,
);

// Then the empty state shows and neither CanvasKit nor the chart's code loads, because CanvasKit crashes when it
// initializes without a GL surface
expect(screen.getByText('common.unableToDisplayChart')).toBeTruthy();
expect(screen.getByText('common.webGLNotSupported')).toBeTruthy();
expect(mockWithSkiaWeb).not.toHaveBeenCalled();
expect(mockLoadSkiaWeb).not.toHaveBeenCalled();
expect(getComponent).not.toHaveBeenCalled();
});

it('should show the failed-to-load message under a reveal without holding its spinner', () => {
it('should show the failed-to-load message under a reveal without holding its spinner', async () => {
// Given a chart under a reveal whose spinner is up while Skia loads
mockIsSkiaWebSupported.mockReturnValue(true);
mockWithSkiaWeb.mockImplementation(({fallback}) => <View>{fallback}</View>);
const {rerender} = render(renderRevealedChart());
const skiaLoad = deferSkiaLoad();
render(renderRevealedChart(createChartLoader()));

// When CanvasKit fails to load. React logs caught render errors to console.error, so mock it to keep the test output clean.
mockWithSkiaWeb.mockImplementation(() => {
throw new Error('CanvasKit initialized without its bindings');
});
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
rerender(renderRevealedChart());
await act(async () => skiaLoad.reject(new Error('CanvasKit initialized without its bindings')));

// Then the message replaces the spinner in the same render, because the hold waits for a Skia draw this state never makes
expect(screen.UNSAFE_queryByType(ActivityIndicator)).toBeNull();
Expand All @@ -96,78 +127,146 @@ describe('SkiaWebChart', () => {
consoleErrorSpy.mockRestore();
});

it('should hold the reveal spinner when the chart was still loading Skia at mount', () => {
it('should hold the reveal spinner when the chart was still loading Skia at mount', async () => {
// Given a browser with WebGL where Skia has not loaded yet, so the chart shows its fallback under a reveal
mockIsSkiaWebSupported.mockReturnValue(true);
mockWithSkiaWeb.mockImplementation(({fallback}) => <View>{fallback}</View>);
const {rerender} = render(renderRevealedChart());
const skiaLoad = deferSkiaLoad();
render(renderRevealedChart(createChartLoader(ReadyChart)));

// When Skia loads and the chart reports it is ready
mockWithSkiaWeb.mockImplementation(() => <ReadyChart />);
rerender(renderRevealedChart());
await act(async () => skiaLoad.resolve());

// Then the spinner the fallback put up stays for the hold, because taking it down before Skia draws would show an empty card
expect(screen.getByTestId('ready-chart')).toBeTruthy();
expect(screen.UNSAFE_queryByType(ActivityIndicator)).not.toBeNull();
});

it('should mount Skia when WebGL is supported', () => {
it('should mount the chart once Skia loads when WebGL is supported', async () => {
// Given a browser with WebGL
mockIsSkiaWebSupported.mockReturnValue(true);

// When the chart mounts for the first time and its loads settle
render(
<SkiaWebChart
getComponent={createChartLoader()}
componentProps={{}}
/>,
);

await waitForBatchedUpdatesWithAct();

// Then CanvasKit has loaded and the chart replaces the fallback, since the chart draws with Skia and cannot render
// before CanvasKit is ready
expect(screen.getByTestId('loaded-chart')).toBeTruthy();
expect(mockLoadSkiaWeb).toHaveBeenCalled();
});

it('should render an already loaded chart without its fallback when it mounts again', async () => {
// Given a chart whose code and CanvasKit finished loading on an earlier mount
mockIsSkiaWebSupported.mockReturnValue(true);
const getComponent = createChartLoader();
const {unmount} = render(
<SkiaWebChart
getComponent={getComponent}
componentProps={{}}
/>,
);
await waitForBatchedUpdatesWithAct();
unmount();

// When the same chart mounts again, as it does when the Spend view switches back to that chart type
render(
<SkiaWebChart
getComponent={getComponent}
componentProps={{}}
/>,
);

// Then the chart is there on the first render and nothing loads again. A lazy component created per mount suspends
// here instead, which production React shows as a spinner flash on every view switch.
expect(screen.getByTestId('loaded-chart')).toBeTruthy();
expect(screen.UNSAFE_queryByType(ActivityIndicator)).toBeNull();
expect(getComponent).toHaveBeenCalledTimes(1);
});

it('should load the chart again on the next mount after a load fails', async () => {
// Given a chart whose first CanvasKit load failed, a result React would otherwise keep for the rest of the session.
// React logs caught render errors to console.error, so mock it to keep the test output clean.
mockIsSkiaWebSupported.mockReturnValue(true);
mockLoadSkiaWeb.mockRejectedValueOnce(new Error('Failed to fetch canvaskit.wasm'));
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
const getComponent = createChartLoader();
const {unmount} = render(
<SkiaWebChart
getComponent={getComponent}
componentProps={{}}
/>,
);
await waitForBatchedUpdatesWithAct();
expect(screen.getByText('common.chartFailedToLoad')).toBeTruthy();
unmount();

// When the chart mounts again
render(
<SkiaWebChart
getComponent={getComponent}
componentProps={{}}
/>,
);

expect(mockWithSkiaWeb).toHaveBeenCalled();
// Then it retries the load and shows the chart
await waitForBatchedUpdatesWithAct();
expect(screen.getByTestId('loaded-chart')).toBeTruthy();
expect(mockLoadSkiaWeb).toHaveBeenCalledTimes(2);

consoleErrorSpy.mockRestore();
});

it('should point CanvasKit at the versioned wasm URL emitted by the build', () => {
it('should point CanvasKit at the versioned wasm URL emitted by the build', async () => {
// Given a browser that supports WebGL
mockIsSkiaWebSupported.mockReturnValue(true);

// When the chart mounts Skia
render(
<SkiaWebChart
getComponent={getComponent}
getComponent={createChartLoader()}
componentProps={{}}
/>,
);
await waitForBatchedUpdatesWithAct();

// Then the glue is told to fetch `canvaskit.wasm` from the build-time `__CANVASKIT_WASM_URL__` define rather
// than the unversioned `/canvaskit.wasm`, so this bundle's glue can never be paired with another release's
// binary (https://github.com/Expensify/App/issues/102042). Any other file keeps its root-relative default.
const opts = mockWithSkiaWeb.mock.calls.at(0)?.[0].opts;
const opts = mockLoadSkiaWeb.mock.calls.at(0)?.[0];
expect(opts?.locateFile?.('canvaskit.wasm')).toBe(__CANVASKIT_WASM_URL__);
expect(opts?.locateFile?.('canvaskit.wasm')).not.toBe('/canvaskit.wasm');
expect(opts?.locateFile?.('other.bin')).toBe('/other.bin');
});

it('should degrade to the failed-to-load empty state and report a warning when CanvasKit fails to load', () => {
it('should degrade to the failed-to-load empty state and report a warning when CanvasKit fails to load', async () => {
// Given a browser that supports WebGL but where CanvasKit throws while loading, as it does when the
// glue and wasm binary are from different releases or the 8 MB download fails
mockIsSkiaWebSupported.mockReturnValue(true);
const loadError = new Error('CanvasKit initialized without its bindings');
mockWithSkiaWeb.mockImplementation(() => {
throw loadError;
});
mockLoadSkiaWeb.mockRejectedValueOnce(loadError);
// React logs caught render errors to console.error. Mock it to keep the test output clean.
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});

// When the chart mounts
render(
<SkiaWebChart
getComponent={getComponent}
getComponent={createChartLoader()}
componentProps={{}}
/>,
);

// Then the error boundary shows the "unable to display chart" state with the load-failure explanation
// instead of the WebGL one, and the failure is reported to Sentry as a handled warning under a single
// fingerprint so it stays visible without becoming a crash
expect(screen.getByText('common.unableToDisplayChart')).toBeTruthy();
await waitForBatchedUpdatesWithAct();
expect(screen.getByText('common.chartFailedToLoad')).toBeTruthy();
expect(screen.getByText('common.unableToDisplayChart')).toBeTruthy();
expect(screen.queryByText('common.webGLNotSupported')).toBeNull();
expect(mockCaptureException).toHaveBeenCalledWith(loadError, expect.objectContaining({level: 'warning', fingerprint: ['skia-web-chart-load-failure']}));

Expand Down
Loading