-
Notifications
You must be signed in to change notification settings - Fork 67
/
react.dart
2124 lines (1784 loc) · 85.1 KB
/
react.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013-2016, the Clean project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// ignore_for_file: deprecated_member_use_from_same_package
/// A Dart library for building UI using ReactJS.
library react;
import 'package:meta/meta.dart';
import 'package:react/react_client/bridge.dart';
import 'package:react/react_client/js_backed_map.dart';
import 'package:react/src/prop_validator.dart';
import 'package:react/src/typedefs.dart';
import 'package:react/react_client.dart';
import 'package:react/react_client/react_interop.dart';
import 'package:react/src/context.dart';
import 'package:react/src/react_client/component_registration.dart' as registration_utils;
import 'package:react/src/react_client/private_utils.dart' show validateJsApi, validateJsApiThenReturn;
export 'package:react/src/context.dart';
export 'package:react/src/prop_validator.dart';
export 'package:react/src/react_client/event_helpers.dart';
export 'package:react/react_client/react_interop.dart' show forwardRef2, createRef, memo2;
export 'package:react/src/react_client/lazy.dart' show lazy;
export 'package:react/src/react_client/synthetic_event_wrappers.dart' hide NonNativeDataTransfer;
export 'package:react/src/react_client/synthetic_data_transfer.dart' show SyntheticDataTransfer;
/// A React component declared using a function that takes in [props] and returns rendered output.
///
/// See <https://reactjs.org/docs/components-and-props.html#function-and-class-components>.
///
/// [props] is typed as [JsBackedMap] so that dart2js can optimize props accesses.
typedef DartFunctionComponent = /*ReactNode*/ dynamic Function(JsBackedMap props);
/// The callback to a React forwardRef component. See [forwardRef2] for more details.
///
/// [props] is typed as [JsBackedMap] so that dart2js can optimize props accesses.
///
/// In the current JS implementation, the ref argument to [React.forwardRef] is usually a JsRef object no matter the input ref type,
/// but according to React the ref argument can be any ref type: https://github.com/facebook/flow/blob/master@%7B2020-09-08%7D/lib/react.js#L305
/// and not just a ref object, so we type [ref] as dynamic here.
typedef DartForwardRefFunctionComponent = /*ReactNode*/ dynamic Function(JsBackedMap props, dynamic ref);
typedef ComponentFactory<T extends Component> = T Function();
typedef ComponentRegistrar = ReactComponentFactoryProxy Function(ComponentFactory componentFactory,
[Iterable<String> skipMethods]);
typedef ComponentRegistrar2 = ReactDartComponentFactoryProxy2 Function(
ComponentFactory<Component2> componentFactory, {
Iterable<String> skipMethods,
Component2BridgeFactory? bridgeFactory,
});
typedef FunctionComponentRegistrar = ReactDartFunctionComponentFactoryProxy
Function(DartFunctionComponent componentFactory, {String? displayName});
/// Fragment component that allows the wrapping of children without the necessity of using
/// an element that adds an additional layer to the DOM (div, span, etc).
///
/// See: <https://reactjs.org/docs/fragments.html>
var Fragment = ReactJsComponentFactoryProxy(React.Fragment);
/// [Suspense] lets you display a fallback UI until its children have finished loading.
///
/// Like [Fragment], [Suspense] does not render any visible UI.
/// It lets you specify a loading indicator in case some components in
/// the tree below it are not yet ready to render.
/// [Suspense] currently works with:
/// - Components that use React.lazy
/// - (dynamic imports, not currently implemented in dart)
///
/// Example Usage:
/// ```
/// render() {
/// return react.div({}, [
/// Header({}),
/// react.Suspense({'fallback': LoadingIndicator({})}, [
/// LazyBodyComponent({}),
/// NotALazyComponent({})
/// ]),
/// Footer({}),
/// ]);
/// }
/// ```
///
/// In the above example, [Suspense] will display the `LoadingIndicator` until
/// `LazyBodyComponent` is loaded. It will not display for `Header` or `Footer`.
///
/// However, any "lazy" descendant components in `LazyBodyComponent` and
/// `NotALazyComponent` will trigger the closest ancestor [Suspense].
///
/// See: <https://react.dev/reference/react/Suspense>
var Suspense = ReactJsComponentFactoryProxy(React.Suspense);
/// StrictMode is a tool for highlighting potential problems in an application.
///
/// StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.
///
/// See: <https://reactjs.org/docs/strict-mode.html>
var StrictMode = ReactJsComponentFactoryProxy(React.StrictMode);
// -------------------------------------------------------------------------------------------------------------------
// [1] While these fields are always initialized upon mount immediately after the class is instantiated,
// since they're not passed into a Dart constructor, they can't be initialized during instantiation,
// forcing us to make them either `late` or nullable.
//
// Since we want them to be non-nullable, we'll opt for `late`.
//
// These fields only haven't been initialized:
// - for mounting component instances:
// - in component class constructors (which we don't encourage)
// - in component class field initializers (except for lazy `late` ones)
// - in "static" lifecycle methods like `getDerivedStateFromProps` and `defaultProps`
//
// So, this shouldn't pose a problem for consumers.
// -------------------------------------------------------------------------------------------------------------------
/// Top-level ReactJS [Component class](https://reactjs.org/docs/react-component.html)
/// which provides the [ReactJS Component API](https://reactjs.org/docs/react-component.html#reference)
///
/// __Deprecated. The Component base class only supports unsafe lifecycle methods,
/// which React JS will remove support for in a future major version.
/// Migrate components to [Component2], which only supports safe lifecycle methods.__
@Deprecated(
'The Component base class only supports unsafe lifecycle methods, which React JS will remove support for in a future major version.'
' Migrate components to Component2, which only supports safe lifecycle methods.')
abstract class Component {
Map? _context;
/// A private field that backs [props], which is exposed via getter/setter so
/// it can be overridden in strong mode.
///
/// Necessary since the `@virtual` annotation within the meta package
/// [doesn't work for overriding fields](https://github.com/dart-lang/sdk/issues/27452).
///
/// TODO: Switch back to a plain field once this issue is fixed.
late Map _props; // [1]
/// A private field that backs [state], which is exposed via getter/setter so
/// it can be overridden in strong mode.
///
/// Necessary since the `@virtual` annotation within the meta package
/// [doesn't work for overriding fields](https://github.com/dart-lang/sdk/issues/27452).
///
/// TODO: Switch back to a plain field once this issue is fixed.
Map _state = {};
/// A private field that backs [ref], which is exposed via getter/setter so
/// it can be overridden in strong mode.
///
/// Necessary since the `@virtual` annotation within the meta package
/// [doesn't work for overriding fields](https://github.com/dart-lang/sdk/issues/27452).
///
/// TODO: Switch back to a plain field once this issue is fixed.
late RefMethod _ref; // [1]
/// The React context map of this component, passed down from its ancestors' [getChildContext] value.
///
/// Only keys declared in this component's [contextKeys] will be present.
///
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
@experimental
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
dynamic get context => _context;
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
@experimental
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
set context(dynamic value) => _context = value as Map;
/// ReactJS [Component] props.
///
/// Related: [state]
// ignore: unnecessary_getters_setters
Map get props => _props;
set props(Map value) => _props = value;
/// ReactJS [Component] state.
///
/// Related: [props]
// ignore: unnecessary_getters_setters
Map get state => _state;
set state(Map value) => _state = value;
/// __DEPRECATED.__
///
/// Support for String `ref`s will be removed in a future major release when `Component` is removed.
///
/// Instead, use [createRef] or a [ref callback](https://react.dev/reference/react-dom/components/common#ref-callback).
@Deprecated(
'Only supported in the deprecated Component, and not Component2. Use createRef or a ref callback instead.')
RefMethod get ref => _ref;
/// __DEPRECATED.__
///
/// Support for String `ref`s will be removed in a future major release when `Component` is removed.
///
/// Instead, use [createRef] or a [ref callback](https://react.dev/reference/react-dom/components/common#ref-callback).
@Deprecated(
'Only supported in the deprecated Component, and not Component2. Use createRef or a ref callback instead.')
set ref(RefMethod value) => _ref = value;
late void Function() _jsRedraw; // [1]
late dynamic _jsThis; // [1]
final List<SetStateCallback> _setStateCallbacks = [];
final List<StateUpdaterCallback> _transactionalSetStateCallbacks = [];
/// The List of callbacks to be called after the component has been updated from a call to [setState].
List get setStateCallbacks => _setStateCallbacks;
/// The List of transactional `setState` callbacks to be called before the component updates.
List get transactionalSetStateCallbacks => _transactionalSetStateCallbacks;
/// The JavaScript [`ReactComponent`](https://reactjs.org/docs/react-api.html#reactdom.render)
/// instance of this `Component` returned by [render].
dynamic get jsThis => _jsThis;
/// Allows the [ReactJS `displayName` property](https://reactjs.org/docs/react-component.html#displayname)
/// to be set for debugging purposes.
// This return type is nullable since Component2's override will return null in certain cases.
String? get displayName => runtimeType.toString();
static dynamic _defaultRef(String _) => null;
initComponentInternal(Map props, void Function() _jsRedraw, [RefMethod? ref, dynamic _jsThis, Map? context]) {
this._jsRedraw = _jsRedraw;
this.ref = ref ?? _defaultRef;
this._jsThis = _jsThis;
_initContext(context);
_initProps(props);
}
/// Initializes context
_initContext(Map? context) {
/// [context]'s and [nextContext]'ss typings were loosened from Map to dynamic to support the new context API in [Component2]
/// which extends from [Component]. Only "legacy" context APIs are supported in [Component] - which means
/// it will still be expected to be a Map.
this.context = {...?context};
nextContext = {...?context};
}
_initProps(Map props) {
this.props = Map.from(props);
nextProps = this.props;
}
initStateInternal() {
state = Map.from(getInitialState());
// Call `transferComponentState` to get state also to `_prevState`
transferComponentState();
}
/// Private reference to the value of [context] for the upcoming render cycle.
///
/// Useful for ReactJS lifecycle methods [shouldComponentUpdateWithContext] and [componentWillUpdateWithContext].
///
/// > __DEPRECATED - DO NOT USE__
/// >
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
Map? nextContext;
/// Private reference to the value of [state] for the upcoming render cycle.
///
/// Useful for ReactJS lifecycle methods [shouldComponentUpdate], [componentWillUpdate] and [componentDidUpdate].
Map? _nextState;
/// Reference to the value of [context] from the previous render cycle, used internally for proxying
/// the ReactJS lifecycle method.
///
/// __DO NOT set__ from anywhere outside react-dart lifecycle internals.
///
/// > __DEPRECATED - DO NOT USE__
/// >
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
Map? prevContext;
/// Reference to the value of [state] from the previous render cycle, used internally for proxying
/// the ReactJS lifecycle method and [componentDidUpdate].
///
/// Not available after [componentDidUpdate] is called.
///
/// __DO NOT set__ from anywhere outside react-dart lifecycle internals.
Map? prevState;
/// Public getter for [_nextState].
///
/// If `null`, then [_nextState] is equal to [state] - which is the value that will be returned.
Map get nextState => _nextState ?? state;
/// Reference to the value of [props] for the upcoming render cycle.
///
/// Used internally for proxying ReactJS lifecycle methods [shouldComponentUpdate], [componentWillReceiveProps], and
/// [componentWillUpdate] as well as the context-specific variants.
///
/// __DO NOT set__ from anywhere outside react-dart lifecycle internals.
Map? nextProps;
/// Transfers `Component` [_nextState] to [state], and [state] to [prevState].
///
/// > __DEPRECATED.__
/// >
/// > This was never designed for public consumption, and there will be no replacement implementation in `Component2`.
/// >
/// > Will be removed when `Component` is removed in a future major release.
@Deprecated('For internal use only.')
void transferComponentState() {
prevState = state;
if (_nextState != null) {
state = _nextState!;
}
_nextState = Map.from(state);
}
/// Force a call to [render] by calling [setState], which effectively "redraws" the `Component`.
///
/// Optionally accepts a [callback] that gets called after the component updates.
void redraw([Function()? callback]) {
setState({}, callback);
}
/// Triggers a rerender with new state obtained by shallow-merging [newState] into the current [state].
///
/// Optionally accepts a [callback] that gets called after the component updates.
///
/// Also allows [newState] to be used as a transactional `setState` callback.
///
/// See: <https://reactjs.org/docs/react-component.html#setstate>
void setState(covariant dynamic newState, [Function()? callback]) {
if (newState is Map) {
_nextState!.addAll(newState);
} else if (newState is StateUpdaterCallback) {
_transactionalSetStateCallbacks.add(newState);
} else if (newState != null) {
throw ArgumentError(
'setState expects its first parameter to either be a Map or a `TransactionalSetStateCallback`.');
}
if (callback != null) _setStateCallbacks.add(callback);
_jsRedraw();
}
/// Set [_nextState] to provided [newState] value and force a re-render.
///
/// Optionally accepts a callback that gets called after the component updates.
///
/// See: <https://reactjs.org/docs/react-component.html#setstate>
@Deprecated('Use setState instead.')
void replaceState(Map? newState, [Function()? callback]) {
final nextState = newState == null ? {} : Map.from(newState);
_nextState = nextState;
if (callback != null) _setStateCallbacks.add(callback);
_jsRedraw();
}
/// ReactJS lifecycle method that is invoked once, both on the client and server, immediately before the initial
/// rendering occurs.
///
/// If you call [setState] within this method, [render] will see the updated state and will be executed only once
/// despite the [state] value change.
///
/// See: <https://reactjs.org/docs/react-component.html#mounting-componentwillmount>
void componentWillMount() {}
/// ReactJS lifecycle method that is invoked once, only on the client _(not on the server)_, immediately after the
/// initial rendering occurs.
///
/// At this point in the lifecycle, you can access any [ref]s to the children of the root node.
///
/// The [componentDidMount] method of child `Component`s is invoked _before_ that of parent `Component`.
///
/// See: <https://reactjs.org/docs/react-component.html#mounting-componentdidmount>
void componentDidMount() {}
/// ReactJS lifecycle method that is invoked when a `Component` is receiving [newProps].
///
/// This method is not called for the initial [render].
///
/// Use this as an opportunity to react to a prop transition before [render] is called by updating the [state] using
/// [setState]. The old props can be accessed via [props].
///
/// Calling [setState] within this function will not trigger an additional [render].
///
/// See: <https://reactjs.org/docs/react-component.html#updating-componentwillreceiveprops>
/// > __UNSUPPORTED IN COMPONENT2__
/// >
/// > This will be completely removed alongside the Component class;
/// > switching to [Component2.getDerivedStateFromProps] is the path forward.
void componentWillReceiveProps(Map newProps) {}
/// > __UNSUPPORTED IN COMPONENT2__
/// >
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
/// >
/// > This will be completely removed alongside the Component class.
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
void componentWillReceivePropsWithContext(Map newProps, dynamic nextContext) {}
/// ReactJS lifecycle method that is invoked before rendering when [nextProps] or [nextState] are being received.
///
/// Use this as an opportunity to return `false` when you're certain that the transition to the new props and state
/// will not require a component update.
///
/// See: <https://reactjs.org/docs/react-component.html#updating-shouldcomponentupdate>
bool shouldComponentUpdate(Map nextProps, Map nextState) => true;
/// > __DEPRECATED - DO NOT USE__
/// >
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
/// >
/// > This will be completely removed alongside the Component class.
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
// ignore: avoid_returning_null
bool? shouldComponentUpdateWithContext(Map nextProps, Map nextState, Map? nextContext) => null;
/// ReactJS lifecycle method that is invoked immediately before rendering when [nextProps] or [nextState] are being
/// received.
///
/// This method is not called for the initial [render].
///
/// Use this as an opportunity to perform preparation before an update occurs.
///
/// __Note__: Choose either this method or [componentWillUpdateWithContext]. They are both called at the same time so
/// using both provides no added benefit.
///
/// See: <https://reactjs.org/docs/react-component.html#updating-componentwillupdate>
///
/// > __UNSUPPORTED IN COMPONENT2__
/// >
/// > Due to the release of getSnapshotBeforeUpdate in ReactJS 16,
/// > componentWillUpdate is no longer the method used to check the state
/// > and props before a re-render. Both the Component class and
/// > componentWillUpdate will be removed alongside Component.
/// > Use Component2 and Component2.getSnapshotBeforeUpdate instead.
/// >
/// > This will be completely removed alongside the Component class.
void componentWillUpdate(Map nextProps, Map nextState) {}
/// > __DEPRECATED - DO NOT USE__
/// >
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
/// >
/// > This will be completely removed alongside the Component class.
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
void componentWillUpdateWithContext(Map nextProps, Map nextState, Map? nextContext) {}
/// ReactJS lifecycle method that is invoked immediately after the `Component`'s updates are flushed to the DOM.
///
/// This method is not called for the initial [render].
///
/// Use this as an opportunity to operate on the root node (DOM) when the `Component` has been updated as a result
/// of the values of [prevProps] / [prevState].
///
/// See: <https://reactjs.org/docs/react-component.html#updating-componentdidupdate>
void componentDidUpdate(Map prevProps, Map prevState) {}
/// ReactJS lifecycle method that is invoked immediately before a `Component` is unmounted from the DOM.
///
/// Perform any necessary cleanup in this method, such as invalidating timers or cleaning up any DOM `Element`s that
/// were created in [componentDidMount].
///
/// See: <https://reactjs.org/docs/react-component.html#unmounting-componentwillunmount>
void componentWillUnmount() {}
/// Returns a Map of context to be passed to descendant components.
///
/// Only keys present in [childContextKeys] will be used; all others will be ignored.
///
/// > __DEPRECATED - DO NOT USE__
/// >
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
/// >
/// > This will be completely removed alongside the Component class.
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
Map<String, dynamic> getChildContext() => const {};
/// The keys this component uses in its child context map (returned by [getChildContext]).
///
/// __This method is called only once, upon component registration.__
///
/// > __DEPRECATED - DO NOT USE__
/// >
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
/// >
/// > This will be completely removed alongside the Component class.
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
Iterable<String> get childContextKeys => const [];
/// The keys of context used by this component.
///
/// __This method is called only once, upon component registration.__
///
/// > __DEPRECATED - DO NOT USE__
/// >
/// > This API was never stable in any version of ReactJS, and was replaced with a new, incompatible context API
/// > in ReactJS 16.
/// >
/// > This will be completely removed alongside the Component class.
@Deprecated('This legacy, unstable context API is only supported in the deprecated Component, and not Component2.'
' Instead, use Component2.context, Context.Consumer, or useContext.')
Iterable<String> get contextKeys => const [];
/// Invoked once before the `Component` is mounted. The return value will be used as the initial value of [state].
///
/// See: <https://reactjs.org/docs/react-component.html#getinitialstate>
Map getInitialState() => {};
/// Invoked once and cached when [registerComponent] is called. Values in the mapping will be set on [props]
/// if that prop is not specified by the parent component.
///
/// This method is invoked before any instances are created and thus cannot rely on [props]. In addition, be aware
/// that any complex objects returned by `getDefaultProps` will be shared across instances, not copied.
///
/// See: <https://reactjs.org/docs/react-component.html#getdefaultprops>
Map getDefaultProps() => {};
/// __Required.__
///
/// When called, it should examine [props] and [state] and return a [ReactNode].
///
/// See: <https://legacy.reactjs.org/docs/react-component.html#render>
/*ReactNode*/ dynamic render();
}
/// Top-level ReactJS [Component class](https://reactjs.org/docs/react-component.html)
/// which provides the [ReactJS Component API](https://reactjs.org/docs/react-component.html#reference).
///
/// Differences from the deprecated [Component]:
///
/// 1. "JS-backed maps" - uses the JS React component's props / state objects maps under the hood
/// instead of copying them into Dart Maps. Benefits:
/// - Improved performance
/// - Props/state key-value pairs are visible to React, and show up in the Dev Tools
/// - Easier to maintain the JS-Dart interop and add new features
/// - Easier to interop with JS libraries like react-redux
///
/// 2. Supports the new lifecycle methods introduced in React 16
/// (See method doc comments for more info)
/// - [getDerivedStateFromProps]
/// - [getSnapshotBeforeUpdate]
/// - [componentDidCatch]
/// - [getDerivedStateFromError]
///
/// 3. Drops support for "unsafe" lifecycle methods deprecated in React 16
/// (See method doc comments for migration instructions)
/// - [componentWillMount]
/// - [componentWillReceiveProps]
/// - [componentWillUpdate]
///
/// 4. Supports React 16 [context]
abstract class Component2 implements Component {
/// Accessed once and cached when instance is created. The [contextType] property on a class can be assigned
/// a [ReactContext] object created by [React.createContext]. This lets you consume the nearest current value of
/// that Context using [context].
///
/// __Example__:
///
/// var MyContext = createContext('test');
///
/// class MyClass extends react.Component2 {
/// @override
/// final contextType = MyContext;
///
/// render() {
/// return react.span({}, [
/// '${this.context}', // Outputs: 'test'
/// ]);
/// }
/// }
///
/// See: <https://reactjs.org/docs/context.html#classcontexttype>
Context? get contextType => null;
/// Invoked once and cached when [registerComponent] is called. Values in the mapping will be set on [props]
/// if that prop is not specified by the parent component.
///
/// This method is invoked before any instances are created and thus cannot rely on [props]. In addition, be aware
/// that any complex objects returned by `defaultProps` will be shared across instances, not copied.
///
/// __Example__:
///
/// // ES6 component
/// Component.defaultProps = {
/// count: 0
/// };
///
/// // Dart component
/// @override
/// get defaultProps => {'count': 0};
///
/// See: <https://reactjs.org/docs/react-without-es6.html#declaring-default-props>
/// See: <https://reactjs.org/docs/react-component.html#defaultprops>
Map get defaultProps => const {};
/// Invoked once before the `Component` is mounted. The return value will be used as the initial value of [state].
///
/// __Example__:
///
/// // ES6 component
/// constructor() {
/// this.state = {count: 0};
/// }
///
/// // Dart component
/// @override
/// get initialState => {'count': 0};
///
/// See: <https://reactjs.org/docs/react-without-es6.html#setting-the-initial-state>
/// See: <https://reactjs.org/docs/react-component.html#constructor>
Map get initialState => const {};
/// The context value from the [contextType] assigned to this component.
/// The value is passed down from the provider of the same [contextType].
/// You can reference [context] in any of the lifecycle methods including the render function.
///
/// If you need multiple context values, consider using multiple consumers instead.
/// Read more: https://reactjs.org/docs/context.html#consuming-multiple-contexts
///
/// This only has a value when [contextType] is set.
///
/// __Example__:
///
/// var MyContext = createContext('test');
///
/// class MyClass extends react.Component2 {
/// @override
/// final contextType = MyContext;
///
/// render() {
/// return react.span({}, [
/// '${this.context}', // Outputs: 'test'
/// ]);
/// }
/// }
///
/// See: <https://reactjs.org/docs/context.html#classcontexttype>
@override
dynamic context;
@override
late Map props; // [1]
@override
late Map state; // [1]
@override
@Deprecated('Only supported in the deprecated Component, and not in Component2. See doc comment for more info.')
get _jsThis => throw _unsupportedError('_jsThis');
@override
@Deprecated('Only supported in the deprecated Component, and not in Component2. See doc comment for more info.')
set _jsThis(_) => throw _unsupportedError('_jsThis');
/// The JavaScript [`ReactComponent`](https://reactjs.org/docs/react-api.html#reactdom.render)
/// instance of this `Component` returned by [render].
@override
late ReactComponent jsThis; // [1]
/// Allows the [ReactJS `displayName` property](https://reactjs.org/docs/react-component.html#displayname)
/// to be set for debugging purposes.
///
/// In DDC, this will be the class name, but in dart2js it will be null unless
/// overridden, since using runtimeType can lead to larger dart2js output.
///
/// This will result in the dart2js name being `ReactDartComponent2` (the
/// name of the proxying JS component defined in _dart_helpers.js).
@override
String? get displayName {
String? value;
assert(() {
value = runtimeType.toString();
return true;
}());
return value;
}
Component2Bridge get _bridge => Component2Bridge.forComponent(this)!;
/// Triggers a rerender with new state obtained by shallow-merging [newState] into the current [state].
///
/// Optionally accepts a [callback] that gets called after the component updates.
///
/// To use a transactional `setState` callback, check out [setStateWithUpdater].
///
/// See: <https://reactjs.org/docs/react-component.html#setstate>
@override
void setState(Map? newState, [SetStateCallback? callback]) {
_bridge.setState(this, newState, callback);
}
/// Triggers a rerender with new state obtained by shallow-merging
/// the return value of [updater] into the current [state].
///
/// Optionally accepts a [callback] that gets called after the component updates.
///
/// See: <https://reactjs.org/docs/react-component.html#setstate>
void setStateWithUpdater(StateUpdaterCallback updater, [SetStateCallback? callback]) {
_bridge.setStateWithUpdater(this, updater, callback);
}
/// Causes [render] to be called, skipping [shouldComponentUpdate].
///
/// > See: <https://reactjs.org/docs/react-component.html#forceupdate>
void forceUpdate([SetStateCallback? callback]) {
_bridge.forceUpdate(this, callback);
}
/// ReactJS lifecycle method that is invoked once, only on the client _(not on the server)_, immediately after the
/// initial rendering occurs.
///
/// At this point in the lifecycle, you can access any [ref]s to the children of the root node.
///
/// The [componentDidMount] method of child `Component`s is invoked _before_ that of parent `Component`.
///
/// See: <https://reactjs.org/docs/react-component.html#mounting-componentdidmount>
@override
void componentDidMount() {}
/// ReactJS lifecycle method that is invoked before rendering when new props ([nextProps]) are received.
///
/// It should return a new `Map` that will be merged into the existing component [state],
/// or `null` to do nothing.
///
/// __Important Caveats:__
///
/// * __Unlike [componentWillReceiveProps], this method is called before first mount, and re-renders.__
///
/// * __[prevState] will be `null`__ when this lifecycle method is called before first mount.
/// If you need to make use of [prevState], be sure to make your logic null-aware to avoid runtime exceptions.
///
/// * __This method is effectively `static`__ _(since it is static in the JS layer)_,
/// so using instance members like [props], [state] or `ref` __will not work.__
///
/// This is different than the [componentWillReceiveProps] method that it effectively replaces.
///
/// If your logic requires access to instance members - consider using [getSnapshotBeforeUpdate] instead.
///
/// __Example__:
///
/// @override
/// getDerivedStateFromProps(Map nextProps, Map prevState) {
/// if (prevState['someMirroredValue'] != nextProps['someValue']) {
/// return {
/// someMirroredValue: nextProps.someValue
/// };
/// }
/// return null;
/// }
///
/// > Deriving state from props should be used with caution since it can lead to more verbose implementations
/// that are less approachable by others.
/// >
/// > [Consider recommended alternative solutions first!](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#preferred-solutions)
///
/// See: <https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops>
Map? getDerivedStateFromProps(Map nextProps, Map prevState) => null;
/// ReactJS lifecycle method that is invoked before rendering when [nextProps] and/or [nextState] are being received.
///
/// Use this as an opportunity to return `false` when you're certain that the transition to the new props and state
/// will not require a component update.
///
/// See: <https://reactjs.org/docs/react-component.html#shouldcomponentupdate>
@override
bool shouldComponentUpdate(Map nextProps, Map nextState) => true;
/// ReactJS lifecycle method that is invoked immediately after re-rendering
/// when new props and/or state values are committed.
///
/// This method is not called for the initial [render].
///
/// Use this as an opportunity to perform preparation before an update occurs.
///
/// __Example__:
///
/// @override
/// getSnapshotBeforeUpdate(Map prevProps, Map prevState) {
/// // Previous props / state can be analyzed and compared to this.props or
/// // this.state, allowing the opportunity perform decision logic.
/// // Are we adding new items to the list?
/// // Capture the scroll position so we can adjust scroll later.
///
/// if (prevProps.list.length < props.list.length) {
/// // The return value from getSnapshotBeforeUpdate is passed into
/// // componentDidUpdate's third parameter (which is new to React 16).
///
/// final list = _listRef;
/// return list.scrollHeight - list.scrollTop;
/// }
///
/// return null;
/// }
///
/// @override
/// componentDidUpdate(Map prevProps, Map prevState, dynamic snapshot) {
/// // If we have a snapshot value, we've just added new items.
/// // Adjust scroll so these new items don't push the old ones out of view.
/// //
/// // (snapshot here is the value returned from getSnapshotBeforeUpdate)
/// if (snapshot !== null) {
/// final list = _listRef;
/// list.scrollTop = list.scrollHeight - snapshot;
/// }
/// }
///
/// See: <https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate>
dynamic getSnapshotBeforeUpdate(Map prevProps, Map prevState) {}
/// ReactJS lifecycle method that is invoked immediately after the `Component`'s updates are flushed to the DOM.
///
/// This method is not called for the initial [render].
///
/// Use this as an opportunity to operate on the root node (DOM) when the `Component` has been updated as a result
/// of the values of [prevProps] / [prevState].
///
/// __Note__: React 16 added a third parameter to `componentDidUpdate`, which
/// is a custom value returned from [getSnapshotBeforeUpdate]. If a
/// value is not returned from [getSnapshotBeforeUpdate], the [snapshot]
/// parameter in `componentDidUpdate` will be null.
///
/// See: <https://reactjs.org/docs/react-component.html#componentdidupdate>
@override
void componentDidUpdate(Map prevProps, Map prevState, [dynamic snapshot]) {}
/// ReactJS lifecycle method that is invoked immediately before a `Component` is unmounted from the DOM.
///
/// Perform any necessary cleanup in this method, such as invalidating timers or cleaning up any DOM `Element`s that
/// were created in [componentDidMount].
///
/// See: <https://reactjs.org/docs/react-component.html#componentwillunmount>
@override
void componentWillUnmount() {}
/// ReactJS lifecycle method that is invoked after an [error] is thrown by a descendant.
///
/// Use this method primarily for logging errors, but because it takes
/// place after the commit phase side-effects are permitted.
///
/// __Note__: This method, along with [getDerivedStateFromError] will only
/// be called if `skipMethods` in [registerComponent2] is overridden with
/// a list that includes the names of these methods. Otherwise, in order to prevent every
/// component from being an "error boundary", [componentDidCatch] and
/// [getDerivedStateFromError] will be ignored.
///
/// See: <https://reactjs.org/docs/react-component.html#componentdidcatch>
void componentDidCatch(dynamic error, ReactErrorInfo info) {}
/// ReactJS lifecycle method that is invoked after an [error] is thrown by a descendant.
///
/// Use this method to capture the [error] and update component [state] accordingly by
/// returning a new `Map` value that will be merged into the current [state].
///
/// __This method is effectively `static`__ _(since it is static in the JS layer)_,
/// so using instance members like [props], [state] or `ref` __will not work.__
///
/// __Note__: This method, along with [componentDidCatch] will only
/// be called if `skipMethods` in [registerComponent2] is overridden with
/// a list that includes the names of these methods. Otherwise, in order to prevent every
/// component from being an error boundary, [componentDidCatch] and
/// [getDerivedStateFromError] will be ignored.
///
/// See: <https://reactjs.org/docs/react-component.html#static-getderivedstatefromerror>
Map? getDerivedStateFromError(dynamic error) => null;
/// Allows usage of PropValidator functions to check the validity of a prop within the props passed to it.
///
/// The second argument (`info`) contains metadata about the prop specified by the key.
/// `propName`, `componentName`, `location` and `propFullName` are available.
///
/// When an invalid value is provided for a prop, a warning will be shown in the JavaScript console.
///
/// For performance reasons, propTypes is only checked in development mode.
///
/// Simple Example:
///
/// ```
/// @override
/// get propTypes => {
/// 'name': (Map props, info) {
/// if (props['name'].length > 20) {
/// return ArgumentError('(${props['name']}) is too long. 'name' has a max length of 20 characters.');
/// }
/// },
/// };
/// ```
///
/// Example of 2 props being dependent:
///
/// ```
/// @override
/// get propTypes => {
/// 'someProp': (Map props, info) {
/// if (props[info.propName] == true && props['anotherProp'] == null) {
/// return ArgumentError('If (${props[info.propName]}) is true. You must have a value for "anotherProp".');
/// }
/// },
/// 'anotherProp': (Map props, info) {
/// if (props[info.propName] != null && props['someProp'] != true) {
/// return ArgumentError('You must set "someProp" to true to use $[info.propName].');
/// }
/// },
/// };
/// ```
///
/// See: <https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes>
Map<String, PropValidator<Never>> get propTypes => {};
/// Examines [props] and [state] and returns a [ReactNode].
///
/// This method is __required__ for class components.
///
/// The function should be _pure_, meaning that it should not modify component [state],
/// it returns the same result each time it is invoked, and it does not directly interact
/// with browser / DOM apis.
///
/// If you need to interact with the browser / DOM apis, perform your work in [componentDidMount]
/// or the other lifecycle methods instead. Keeping `render` pure makes components easier to think about.
///
/// See: <https://legacy.reactjs.org/docs/react-component.html#render>
@override
/*ReactNode*/ dynamic render();
// ******************************************************************************************************************
//
// Deprecated members
//
// ******************************************************************************************************************
/// Deprecated. Will be removed when [Component] is removed in a future major release.
///
/// Replace calls to this method with either:
///
/// - [forceUpdate] (preferred) - forces rerender and bypasses [shouldComponentUpdate]
/// - `setState({})` - same behavior as this method: causes rerender but goes through [shouldComponentUpdate]
///
/// See: <https://reactjs.org/docs/react-component.html#forceupdate>
@override
@Deprecated('Use forceUpdate or setState({}) instead. Will be removed when Component is removed.')
void redraw([SetStateCallback? callback]) {
setState({}, callback);
}
// ******************************************************************************************************************
//
// Deprecated and unsupported lifecycle methods
//
// These should all throw and be annotated with @mustCallSuper so that any consumer overrides don't silently fail.
//
// ******************************************************************************************************************
UnsupportedError _unsupportedLifecycleError(String memberName) =>
UnsupportedError('Component2 drops support for the lifecycle method $memberName.'
' See doc comment on Component2.$memberName for migration instructions.');
/// Invoked once before the `Component` is mounted. The return value will be used as the initial value of [state].
///
/// See: <https://reactjs.org/docs/react-component.html#getinitialstate>
///
/// > __DEPRECATED - DO NOT USE__
/// >
/// > Use the [initialState] getter instead.
@override
@mustCallSuper
@Deprecated('Only supported in the deprecated Component, and not in Component2. See doc comment for more info.')
Map getInitialState() => throw _unsupportedLifecycleError('getInitialState');
/// Invoked once and cached when [registerComponent] is called. Values in the mapping will be set on [props]
/// if that prop is not specified by the parent component.
///
/// This method is invoked before any instances are created and thus cannot rely on [props]. In addition, be aware
/// that any complex objects returned by `getDefaultProps` will be shared across instances, not copied.
///
/// See: <https://reactjs.org/docs/react-component.html#getdefaultprops>
///