Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CPLAT-3093 Add ErrorBoundary Component #266

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions lib/over_react.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export 'src/component/abstract_transition.dart';
export 'src/component/abstract_transition_props.dart';
export 'src/component/aria_mixin.dart';
export 'src/component/callback_typedefs.dart';
export 'src/component/error_boundary.dart';
export 'src/component/dom_components.dart';
export 'src/component/dummy_component.dart';
export 'src/component/prop_mixins.dart';
Expand Down
129 changes: 129 additions & 0 deletions lib/src/component/error_boundary.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import 'package:meta/meta.dart';
import 'package:over_react/over_react.dart';

// ignore: uri_has_not_been_generated
part 'error_boundary.over_react.g.dart';

// TODO: Need to type the second argument once react-dart implements bindings for the ReactJS "componentStack".
typedef _ComponentDidCatchCallback(Error error, /*ComponentStack*/dynamic componentStack);

// TODO: Need to type the second argument once react-dart implements bindings for the ReactJS "componentStack".
typedef ReactElement _FallbackUiRenderer(Error error, /*ComponentStack*/dynamic componentStack);

/// A higher-order component that will catch ReactJS errors anywhere within the child component tree and
/// display a fallback UI instead of the component tree that crashed.
///
/// Optionally, use the [ErrorBoundaryProps.onComponentDidCatch]
/// to send error / stack trace information to a logging endpoint for your application.
///
/// > __NOTE: This component does not yet do any of this__.
/// >
/// > It will begin providing the boundary / fallback UI behavior once support
/// for ReactJS 16 is released in over_react version 3.0.0
@Factory()
// ignore: undefined_identifier
UiFactory<ErrorBoundaryProps> ErrorBoundary = $ErrorBoundary;

@Props()
class _$ErrorBoundaryProps extends UiProps {
/// An optional callback that will be called with an [Error] and a `ComponentStack`
/// containing information about which component in the tree threw the error when
/// the `componentDidCatch` lifecycle method is called.
///
/// This callback can be used to log component errors like so:
///
/// (ErrorBoundary()
/// ..onComponentDidCatch = (error, componentStack) {
/// // It is up to you to implement the service / thing that calls the service.
/// logComponentStackToAService(error, componentStack);
/// }
/// )(
/// // The rest of your component tree
/// )
///
/// > See: <https://reactjs.org/docs/react-component.html#componentdidcatch>
_ComponentDidCatchCallback onComponentDidCatch;

/// A renderer that will be used to render "fallback" UI instead of the child
/// component tree that crashed.
///
/// > Default: [ErrorBoundaryComponent._renderDefaultFallbackUI]
_FallbackUiRenderer fallbackUIRenderer;
}

@State()
class _$ErrorBoundaryState extends UiState {
/// Whether the tree that the [ErrorBoundary] is wrapping around threw an error.
///
/// When `true`, fallback UI will be rendered using [ErrorBoundaryProps.fallbackUIRenderer].
bool hasError;
}

@Component(isWrapper: true)
class ErrorBoundaryComponent<T extends ErrorBoundaryProps, S extends ErrorBoundaryState>
extends UiStatefulComponent<T, S> {
Error _error;
/*ComponentStack*/dynamic _componentStack;

@override
Map getDefaultProps() => (newProps()
..fallbackUIRenderer = _renderDefaultFallbackUI
);

@override
Map getInitialState() => (newState()
..hasError = false
);

@mustCallSuper
/*@override*/
S getDerivedStateFromError(_) {
return newState()..hasError = true;
}

@mustCallSuper
/*@override*/
void componentDidCatch(Error error, /*ComponentStack*/dynamic componentStack) {
_error = error;
_componentStack = componentStack;

if (props.onComponentDidCatch != null) {
props.onComponentDidCatch(error, componentStack);
}
}

@override
render() => state.hasError
? props.fallbackUIRenderer(_error, _componentStack)
: props.children.single;

// TODO: Make this fallback UI more useful.
ReactElement _renderDefaultFallbackUI(_, __) {
return Dom.h3()('Something went wrong.');
}

@mustCallSuper
@override
void validateProps([Map appliedProps]) {
super.validateProps(appliedProps);
final children = domProps(appliedProps).children;

if (children.length > 1) {
aaronlademann-wf marked this conversation as resolved.
Show resolved Hide resolved
throw new PropError.value(children, 'children', 'ErrorBoundary accepts only a single child.');
} else if (!isValidElement(children.single)) {
throw new PropError.value(children, 'children', 'ErrorBoundary accepts only a single ReactComponent child.');
}
}
}

// ignore: mixin_of_non_class, undefined_class
class ErrorBoundaryProps extends _$ErrorBoundaryProps with _$ErrorBoundaryPropsAccessorsMixin {
// ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value
static const PropsMeta meta = $metaForErrorBoundaryProps;
}

// ignore: mixin_of_non_class, undefined_class
class ErrorBoundaryState extends _$ErrorBoundaryState with _$ErrorBoundaryStateAccessorsMixin {
// ignore: undefined_identifier, undefined_class, const_initialized_with_non_constant_value
static const StateMeta meta = $metaForErrorBoundaryState;
}
96 changes: 96 additions & 0 deletions test/over_react/component/error_boundary_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Copyright 2019 Workiva Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

@Timeout(const Duration(seconds: 2))
library error_boundary_test;

import 'package:over_react/over_react.dart';
import 'package:over_react_test/over_react_test.dart';
import 'package:test/test.dart';

void main() {
group('ErrorBoundary', () {
TestJacket<ErrorBoundaryComponent> jacket;
ReactElement dummyChild;

setUp(() {
dummyChild = Dom.div()('hi there');
});

tearDown(() {
jacket = null;
dummyChild = null;
});

// TODO: Add tests that exercise the actual ReactJS 16 error lifecycle methods once implemented.

test('initializes with the expected default prop values', () {
jacket = mount(ErrorBoundary()(dummyChild));

expect(ErrorBoundary(jacket.getProps()).fallbackUIRenderer(null, null), const isInstanceOf<ReactElement>());
});

test('initializes with the expected initial state values', () {
jacket = mount(ErrorBoundary()(dummyChild));

expect(jacket.getDartInstance().state.hasError, isFalse);
});

group('renders', () {
test('its child when `state.error` is false', () {
jacket = mount(ErrorBoundary()(dummyChild));
expect(jacket.getDartInstance().state.hasError, isFalse, reason: 'test setup sanity check');

expect(jacket.getNode().text, 'hi there');
});

group('fallback UI when `state.error` is true', () {
test('', () {
jacket = mount(ErrorBoundary()(dummyChild));
final component = jacket.getDartInstance();
component.setState(component.newState()..hasError = true);

expect(jacket.getNode(), hasNodeName('H3'));
expect(jacket.getNode().text, 'Something went wrong.');
});

// TODO: Update this test to assert the error / component stack values passed to the callback once the actual ReactJS 16 error lifecycle methods are implemented.
test('and props.fallbackUIRenderer is set', () {
ReactElement _fallbackUIRenderer(_, __) {
return Dom.h4()('Something super not awesome just happened.');
}

jacket = mount((ErrorBoundary()..fallbackUIRenderer = _fallbackUIRenderer)(dummyChild));
final component = jacket.getDartInstance();
component.setState(component.newState()..hasError = true);

expect(jacket.getNode(), hasNodeName('H4'));
expect(jacket.getNode().text, 'Something super not awesome just happened.');
});
});
});

group('throws a PropError when', () {
test('more than one child is provided', () {
expect(() => mount(ErrorBoundary()(dummyChild, dummyChild)),
throwsPropError_Value([dummyChild, dummyChild], 'children'));
});

test('an invalid child is provided', () {
expect(() => mount(ErrorBoundary()('oh hai')),
throwsPropError_Value(['oh hai'], 'children'));
});
});
});
}
2 changes: 2 additions & 0 deletions test/over_react_component_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import 'package:test/test.dart';

import 'over_react/component/abstract_transition_test.dart' as abstract_transition_test;
import 'over_react/component/dom_components_test.dart' as dom_components_test;
import 'over_react/component/error_boundary_test.dart' as error_boundary_test;
import 'over_react/component/prop_mixins_test.dart' as prop_mixins_test;
import 'over_react/component/resize_sensor_test.dart' as resize_sensor_test;

Expand All @@ -35,6 +36,7 @@ void main() {
enableTestMode();

abstract_transition_test.main();
error_boundary_test.main();
dom_components_test.main();
prop_mixins_test.main();
resize_sensor_test.main();
Expand Down