Add error boundary to latex code (#8822)

* Add error boundary to latex code

* Add test
This commit is contained in:
Daniel Espino García 2025-05-06 09:48:36 +02:00 committed by GitHub
parent 2a0ec47278
commit d27c56af88
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 68 additions and 14 deletions

View file

@ -2,9 +2,11 @@
// See LICENSE.txt for license information.
import React, {useCallback} from 'react';
import {useIntl} from 'react-intl';
import {Platform, ScrollView, Text, View} from 'react-native';
import {SafeAreaView, type Edge} from 'react-native-safe-area-context';
import ErrorBoundary from '@components/markdown/error_boundary';
import MathView from '@components/math_view';
import {useTheme} from '@context/theme';
import useAndroidHardwareBackHandler from '@hooks/android_back_handler';
@ -60,6 +62,7 @@ const getStyleSheet = makeStyleSheetFromTheme((theme: Theme) => {
});
const Latex = ({componentId, content}: Props) => {
const intl = useIntl();
const theme = useTheme();
const style = getStyleSheet(theme);
const lines = splitLatexCodeInLines(content);
@ -93,20 +96,27 @@ const Latex = ({componentId, content}: Props) => {
contentContainerStyle={style.scrollCode}
horizontal={true}
>
{lines.map((latexCode) => (
<View
style={style.code}
key={latexCode}
>
<MathView
math={latexCode}
onError={onErrorMessage}
renderError={onRenderErrorMessage}
resizeMode={'cover'}
style={style.mathStyle}
/>
</View>
))}
<ErrorBoundary
error={intl.formatMessage({id: 'markdown.latex.error', defaultMessage: 'Latex render error'})}
theme={theme}
>
<>
{lines.map((latexCode) => (
<View
style={style.code}
key={latexCode}
>
<MathView
math={latexCode}
onError={onErrorMessage}
renderError={onRenderErrorMessage}
resizeMode={'cover'}
style={style.mathStyle}
/>
</View>
))}
</>
</ErrorBoundary>
</ScrollView>
</ScrollView>
</SafeAreaView>

View file

@ -0,0 +1,44 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {screen} from '@testing-library/react-native';
import React from 'react';
import MathView from '@components/math_view';
import {renderWithIntl} from '@test/intl-test-helper';
import Latex from './index';
import type {AvailableScreens} from '@typings/screens/navigation';
// Mock the MathView component to simulate errors
jest.mock('@components/math_view', () => {
return {
__esModule: true,
default: jest.fn(() => null),
};
});
describe('Latex', () => {
const baseProps = {
componentId: 'test-screen' as AvailableScreens,
content: '\\frac{1}{2}',
};
const renderComponent = (props = {}) => {
return renderWithIntl(
<Latex
{...baseProps}
{...props}
/>,
);
};
it('should render error message when MathView throws an error', () => {
jest.mocked(MathView).mockImplementation(() => {
throw new Error('Test error');
});
renderComponent();
expect(screen.getByText('Latex render error')).toBeTruthy();
});
});