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-9347 Add memo for function components #613

Merged
merged 4 commits into from
Jul 30, 2020
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
55 changes: 31 additions & 24 deletions lib/over_react.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,34 +15,38 @@
/// Base classes for UI components and related utilities.
library over_react;

export 'package:react/react.dart' show
SyntheticEvent,
SyntheticAnimationEvent,
SyntheticClipboardEvent,
SyntheticKeyboardEvent,
SyntheticFocusEvent,
SyntheticFormEvent,
SyntheticDataTransfer,
SyntheticMouseEvent,
SyntheticTouchEvent,
SyntheticTransitionEvent,
SyntheticUIEvent,
SyntheticWheelEvent,
TypedSnapshot;
export 'package:react/react.dart'
show
SyntheticEvent,
SyntheticAnimationEvent,
SyntheticClipboardEvent,
SyntheticKeyboardEvent,
SyntheticFocusEvent,
SyntheticFormEvent,
SyntheticDataTransfer,
SyntheticMouseEvent,
SyntheticTouchEvent,
SyntheticTransitionEvent,
SyntheticUIEvent,
SyntheticWheelEvent,
TypedSnapshot;

export 'package:react/react_client/js_backed_map.dart' show JsBackedMap;

export 'package:react/react_client.dart' show setClientConfiguration, ReactElement, ReactComponentFactoryProxy;
export 'package:react/react_client.dart'
show setClientConfiguration, ReactElement, ReactComponentFactoryProxy;
export 'package:react/react_client/react_interop.dart' show ReactErrorInfo, Ref;

export 'src/component/_deprecated/abstract_transition.dart';
export 'src/component/_deprecated/abstract_transition_props.dart';
export 'src/component/aria_mixin.dart';
export 'src/component/callback_typedefs.dart';
export 'src/component/_deprecated/error_boundary.dart';
export 'src/component/_deprecated/error_boundary_mixins.dart' hide LegacyErrorBoundaryApi;
export 'src/component/_deprecated/error_boundary_mixins.dart'
hide LegacyErrorBoundaryApi;
export 'src/component/dom_components.dart';
export 'src/component/error_boundary_api.dart' show defaultErrorBoundaryLoggerName;
export 'src/component/error_boundary_api.dart'
show defaultErrorBoundaryLoggerName;
export 'src/component/ref_util.dart';
export 'src/component/fragment_component.dart';
export 'src/component/strictmode_component.dart';
Expand All @@ -52,13 +56,15 @@ export 'src/component/prop_typedefs.dart';
export 'src/component/pure_component_mixin.dart';
export 'src/component/_deprecated/resize_sensor.dart';
export 'src/component_declaration/annotations.dart';
export 'src/component_declaration/builder_helpers.dart' hide GeneratedErrorMessages;
export 'src/component_declaration/component_base_2.dart' show
registerComponent2,
registerAbstractComponent2,
UiComponent2,
UiStatefulComponent2,
UiStatefulMixin2;
export 'src/component_declaration/builder_helpers.dart'
hide GeneratedErrorMessages;
export 'src/component_declaration/component_base_2.dart'
show
registerComponent2,
registerAbstractComponent2,
UiComponent2,
UiStatefulComponent2,
UiStatefulMixin2;
export 'src/component_declaration/built_redux_component.dart';
export 'src/component_declaration/flux_component.dart';
export 'src/component_declaration/function_component.dart';
Expand All @@ -74,6 +80,7 @@ export 'src/util/hoc.dart';
export 'src/util/handler_chain_util.dart';
export 'src/util/key_constants.dart';
export 'src/util/map_util.dart';
export 'src/util/memo.dart';
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only code change. The other changes are from ddev format

export 'src/util/pretty_print.dart';
export 'src/util/prop_errors.dart';
export 'src/util/prop_key_util.dart';
Expand Down
60 changes: 37 additions & 23 deletions lib/src/component_declaration/component_type_checking.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ library over_react.component_declaration.component_type_checking;
import 'dart:js_util';

import 'package:meta/meta.dart';
import 'package:over_react/src/component_declaration/component_base.dart' show UiFactory;
import 'package:over_react/src/component_declaration/annotations.dart' as annotations show Component2;
import 'package:over_react/src/component_declaration/component_base.dart'
show UiFactory;
import 'package:over_react/src/component_declaration/annotations.dart'
as annotations show Component2;
import 'package:over_react/src/util/react_wrappers.dart';
import 'package:over_react/src/util/string_util.dart';
import 'package:react/react_client.dart';
Expand All @@ -29,14 +31,15 @@ import 'package:react/react_client/react_interop.dart';
// Component type registration and internal type metadata management
// ----------------------------------------------------------------------


// ignore: deprecated_member_use
Expando<ReactDartComponentFactoryProxy> _typeAliasToFactory = Expando<ReactDartComponentFactoryProxy>();
Expando<ReactComponentFactoryProxy> _typeAliasToFactory =
Expando<ReactComponentFactoryProxy>();

/// Registers a type alias for the specified factory, so that [getComponentTypeFromAlias] can be
/// called with [typeAlias] to retrieve [factory]'s [ReactClass] type.
// ignore: deprecated_member_use
void registerComponentTypeAlias(ReactDartComponentFactoryProxy factory, dynamic typeAlias) {
void registerComponentTypeAlias(
ReactComponentFactoryProxy factory, dynamic typeAlias) {
if (typeAlias != null) {
_typeAliasToFactory[typeAlias] = factory;
}
Expand All @@ -50,27 +53,33 @@ const String _componentTypeMetaKey = '_componentTypeMeta';
/// the component type of the specified [factory].
///
/// This meta is retrievable via [getComponentTypeMeta].
void setComponentTypeMeta(ReactComponentFactoryProxy factory, {
void setComponentTypeMeta(
ReactComponentFactoryProxy factory, {
@required ReactComponentFactoryProxy parentType,
bool isWrapper = false,
bool isHoc = false,
}) {
// ignore: argument_type_not_assignable
setProperty(factory.type, _componentTypeMetaKey, ComponentTypeMeta(
parentType: parentType,
isWrapper: isWrapper,
isHoc: isHoc,
));
setProperty(
factory.type,
_componentTypeMetaKey,
ComponentTypeMeta(
parentType: parentType,
isWrapper: isWrapper,
isHoc: isHoc,
));
}

/// Returns the [ComponentTypeMeta] associated with the component type [type] in [setComponentTypeMeta],
/// or `const ComponentTypeMeta.none()` if there is no associated meta.
ComponentTypeMeta getComponentTypeMeta(dynamic type) {
assert(isPotentiallyValidComponentType(type) &&
'`type` should be a valid component type (and not null or a type alias).' is String);
'`type` should be a valid component type (and not null or a type alias).'
is String);

if (type is! String) {
return getProperty(type, _componentTypeMetaKey) ?? const ComponentTypeMeta.none();
return getProperty(type, _componentTypeMetaKey) ??
const ComponentTypeMeta.none();
}

return const ComponentTypeMeta.none();
Expand Down Expand Up @@ -122,11 +131,8 @@ class ComponentTypeMeta {
// ignore: deprecated_member_use
final ReactComponentFactoryProxy parentType;

ComponentTypeMeta({
@required this.parentType,
this.isWrapper = false,
this.isHoc = false
});
ComponentTypeMeta(
{@required this.parentType, this.isWrapper = false, this.isHoc = false});

const ComponentTypeMeta.none()
: this.isWrapper = false,
Expand Down Expand Up @@ -202,7 +208,8 @@ bool isPotentiallyValidComponentType(dynamic type) {
/// getParentTypes(getComponentTypeFromAlias(C)); // [B, A].map(getTypeFromAlias)
Iterable<dynamic> getParentTypes(dynamic type) sync* {
assert(isPotentiallyValidComponentType(type) &&
'`type` should be a valid component type (and not null or a type alias).' is String);
'`type` should be a valid component type (and not null or a type alias).'
is String);

var currentType = type;
dynamic parentType;
Expand All @@ -226,10 +233,8 @@ Iterable<dynamic> getParentTypes(dynamic type) sync* {
/// * [String] tag name (DOM components only)
///
/// > Related: [isValidElementOfType]
bool isComponentOfType(ReactElement instance, dynamic typeAlias, {
bool traverseWrappers = true,
bool matchParentTypes = true
}) {
bool isComponentOfType(ReactElement instance, dynamic typeAlias,
{bool traverseWrappers = true, bool matchParentTypes = true}) {
if (instance == null) {
return false;
}
Expand Down Expand Up @@ -293,3 +298,12 @@ void enforceMinimumComponentVersionFor(ReactComponentFactoryProxy component) {
'''));
}
}

/// Validates that a [ReactComponentFactoryProxy]'s component is a function component.
void enforceFunctionComponent(ReactComponentFactoryProxy component) {
if (component is ReactDartFunctionComponentFactoryProxy) return;

throw ArgumentError(unindent('''
The UiFactory provided should be for a function component.
'''));
}
4 changes: 4 additions & 0 deletions lib/src/component_declaration/function_component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import 'package:meta/meta.dart';
import 'package:over_react/over_react.dart';
import 'package:react/react.dart' as react;

import 'component_type_checking.dart';

export 'component_type_checking.dart'
show isComponentOfType, isValidElementOfType;

Expand Down Expand Up @@ -132,6 +134,8 @@ UiFactory<TProps> uiFunction<TProps extends UiProps>(
return builder..componentFactory = factory;
}

registerComponentTypeAlias(factory, _uiFactory);

return _uiFactory;
}

Expand Down
94 changes: 94 additions & 0 deletions lib/src/util/memo.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright 2020 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.

library over_react.memo;

import 'package:over_react/src/component_declaration/component_type_checking.dart';
import 'package:react/react_client/react_interop.dart' as react_interop;
import 'package:react/react_client.dart';
import 'package:over_react/component_base.dart';

/// A [higher order component](https://reactjs.org/docs/higher-order-components.html) for function components
/// that behaves similar to the way [`React.PureComponent`](https://reactjs.org/docs/react-api.html#reactpurecomponent)
/// does for class-based components.
///
/// If your function component renders the same result given the same props, you can wrap it in a call to
/// `memo` for a performance boost in some cases by memoizing the result. This means that React will skip
/// rendering the component, and reuse the last rendered result.
///
/// > __NOTE:__ This should only be used to wrap function components.
///
/// ```dart
/// import 'package:over_react/over_react.dart' as react;
///
/// UiFactory<UiProps> MemoExample = memo<UiProps>(uiFunction(
/// (props) {
/// // render using props
/// },
/// FunctionComponentConfig(),
/// ));
/// ```
///
/// `memo` only affects props changes. If your function component wrapped in `memo` has a
/// `useState` or `useContext` Hook in its implementation, it will still rerender when `state` or `context` change.
///
/// By default it will only shallowly compare complex objects in the props map.
/// If you want control over the comparison, you can also provide a custom comparison
/// function to the [areEqual] argument as shown in the example below.
///
/// ```dart
/// import 'package:over_react/over_react.dart' as react;
///
/// UiFactory<MemoWithComparisonProps> MemoWithComparison = memo<MemoWithComparisonProps>(uiFunction(
/// (props) {
/// // render using props
/// },
/// $MemoWithComparisonConfig, // ignore: undefined_identifier
/// ), areEqual: (prevProps, nextProps) {
/// // Do some custom comparison logic to return a bool based on prevProps / nextProps
/// });
/// ```
///
/// > __This method only exists as a performance optimization.__
/// >
/// > Do not rely on it to “prevent” a render, as this can lead to bugs.
///
/// See: <https://reactjs.org/docs/react-api.html#reactmemo>.
UiFactory<TProps> memo<TProps extends UiProps>(UiFactory<TProps> factory,
{bool Function(TProps prevProps, TProps nextProps) areEqual,
String displayName}) {
enforceFunctionComponent(factory().componentFactory);

ReactComponentFactoryProxy hoc;
if (areEqual != null) {
bool wrapProps(Map prevProps, Map nextProps) {
final tPrevProps = factory(prevProps);
final tNextProps = factory(nextProps);
return areEqual(tPrevProps, tNextProps);
}

hoc = react_interop.memo(factory().componentFactory, areEqual: wrapProps);
} else {
hoc = react_interop.memo(factory().componentFactory);
}

setComponentTypeMeta(hoc,
isHoc: true, parentType: factory().componentFactory);

TProps forwardedFactory([Map props]) {
return factory(props)..componentFactory = hoc;
}

return forwardedFactory;
}
3 changes: 1 addition & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,4 @@ dependency_overrides:
react:
git:
url: https://github.com/cleandart/react-dart.git
ref: 5.5.0-wip

ref: 5.5.0-wip
Loading