-
Notifications
You must be signed in to change notification settings - Fork 46.2k
/
ReactControlledComponent.js
77 lines (67 loc) · 1.95 KB
/
ReactControlledComponent.js
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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import invariant from 'shared/invariant';
import {
getInstanceFromNode,
getFiberCurrentPropsFromNode,
} from './EventPluginUtils';
// Use to restore controlled state after a change event has fired.
let restoreImpl = null;
let restoreTarget = null;
let restoreQueue = null;
function restoreStateOfTarget(target) {
// We perform this translation at the end of the event loop so that we
// always receive the correct fiber here
const internalInstance = getInstanceFromNode(target);
if (!internalInstance) {
// Unmounted
return;
}
invariant(
typeof restoreImpl === 'function',
'setRestoreImplementation() needs to be called to handle a target for controlled ' +
'events. This error is likely caused by a bug in React. Please file an issue.',
);
const props = getFiberCurrentPropsFromNode(internalInstance.stateNode);
restoreImpl(internalInstance.stateNode, internalInstance.type, props);
}
export function setRestoreImplementation(
impl: (domElement: Element, tag: string, props: Object) => void,
): void {
restoreImpl = impl;
}
export function enqueueStateRestore(target: EventTarget): void {
if (restoreTarget) {
if (restoreQueue) {
restoreQueue.push(target);
} else {
restoreQueue = [target];
}
} else {
restoreTarget = target;
}
}
export function needsStateRestore(): boolean {
return restoreTarget !== null || restoreQueue !== null;
}
export function restoreStateIfNeeded() {
if (!restoreTarget) {
return;
}
const target = restoreTarget;
const queuedTargets = restoreQueue;
restoreTarget = null;
restoreQueue = null;
restoreStateOfTarget(target);
if (queuedTargets) {
for (let i = 0; i < queuedTargets.length; i++) {
restoreStateOfTarget(queuedTargets[i]);
}
}
}