@lexical/react
Version:
This package provides Lexical components and hooks for React applications.
73 lines (67 loc) • 2.11 kB
JavaScript
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import { Component } from 'react';
import { jsx } from 'react/jsx-runtime';
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// React error boundaries must be class components. This one stays private: the
// exported LexicalErrorBoundary is a function component so that its props keep
// the variance that lets it satisfy the (single-argument `onError`) boundary
// prop accepted by RichTextPlugin/PlainTextPlugin.
class ErrorBoundary extends Component {
state = {
hasError: false
};
static getDerivedStateFromError() {
return {
hasError: true
};
}
componentDidCatch(error, info) {
this.props.onError(error instanceof Error ? error : new Error(String(error), {
cause: error
}), info);
}
render() {
return this.state.hasError ? this.props.fallback : this.props.children;
}
}
/**
* An error boundary used by {@link RichTextPlugin} and {@link PlainTextPlugin}
* to isolate failures thrown while rendering decorator nodes. It renders
* `fallback` in place of the failed subtree and forwards the error (coerced to
* an `Error`) along with the React {@link ErrorInfo} to the `onError` callback.
* When `fallback` is omitted a small default message is shown; pass
* `fallback={null}` to render nothing.
*
* @returns The wrapped `children`, or the fallback if an error is caught.
*/
function LexicalErrorBoundary({
children,
fallback,
onError
}) {
return /*#__PURE__*/jsx(ErrorBoundary, {
fallback: fallback === undefined ? /*#__PURE__*/jsx("div", {
style: {
border: '1px solid #f00',
color: '#f00',
padding: '8px'
},
children: "An error was thrown."
}) : fallback,
onError: onError,
children: children
});
}
export { LexicalErrorBoundary };