Skip to content

Commit

Permalink
[flow] add local type annotations in DevTools
Browse files Browse the repository at this point in the history
  • Loading branch information
kassens committed Jan 5, 2023
1 parent bd08780 commit 2353823
Show file tree
Hide file tree
Showing 48 changed files with 226 additions and 137 deletions.
4 changes: 2 additions & 2 deletions packages/react-devtools-core/src/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const hook: ?DevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;

let savedComponentFilters: Array<ComponentFilter> = getDefaultComponentFilters();

function debug(methodName: string, ...args) {
function debug(methodName: string, ...args: Array<mixed>) {
if (__DEBUG__) {
console.log(
`%c[core/backend] %c${methodName}`,
Expand Down Expand Up @@ -276,7 +276,7 @@ export function connectToDevTools(options: ?ConnectOptions) {
scheduleRetry();
}

function handleMessage(event) {
function handleMessage(event: MessageEvent) {
let data;
try {
if (typeof event.data === 'string') {
Expand Down
9 changes: 5 additions & 4 deletions packages/react-devtools-core/src/standalone.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,12 @@ let bridge: FrontendBridge | null = null;
let store: Store | null = null;
let root = null;

const log = (...args) => console.log('[React DevTools]', ...args);
log.warn = (...args) => console.warn('[React DevTools]', ...args);
log.error = (...args) => console.error('[React DevTools]', ...args);
const log = (...args: Array<mixed>) => console.log('[React DevTools]', ...args);
log.warn = (...args: Array<mixed>) => console.warn('[React DevTools]', ...args);
log.error = (...args: Array<mixed>) =>
console.error('[React DevTools]', ...args);

function debug(methodName: string, ...args) {
function debug(methodName: string, ...args: Array<mixed>) {
if (__DEBUG__) {
console.log(
`%c[core/standalone] %c${methodName}`,
Expand Down
2 changes: 1 addition & 1 deletion packages/react-devtools-extensions/src/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function welcome(event) {

window.addEventListener('message', welcome);

function setup(hook) {
function setup(hook: any) {
if (hook == null) {
// DevTools didn't get injected into this page (maybe b'c of the contentType).
return;
Expand Down
2 changes: 1 addition & 1 deletion packages/react-devtools-shared/src/backend/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import type {ComponentFilter} from '../types';
import {isSynchronousXHRSupported} from './utils';
import type {BrowserTheme} from 'react-devtools-shared/src/devtools/views/DevTools';

const debug = (methodName, ...args) => {
const debug = (methodName: string, ...args: Array<string>) => {
if (__DEBUG__) {
console.log(
`%cAgent %c${methodName}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ export function attach(
return ((internalInstanceToIDMap.get(internalInstance): any): number);
}

function areEqualArrays(a, b) {
function areEqualArrays(a: Array<any>, b: Array<any>) {
if (a.length !== b.length) {
return false;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/react-devtools-shared/src/backend/legacy/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type {InternalInstance} from './renderer';

export function decorate(object: Object, attr: string, fn: Function): Function {
const old = object[attr];
object[attr] = function(instance: InternalInstance) {
object[attr] = function(this: any, instance: InternalInstance) {
return fn.call(this, old, arguments);
};
return old;
Expand All @@ -34,7 +34,7 @@ export function restoreMany(source: Object, olds: Object): void {
}
}

export function forceUpdate(instance: InternalInstance): void {
export function forceUpdate(this: any, instance: InternalInstance): void {
if (typeof instance.forceUpdate === 'function') {
instance.forceUpdate();
} else if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ export function createProfilingHooks({
}
}

function markAndClear(markName) {
function markAndClear(markName: string) {
// This method won't be called unless these functions are defined, so we can skip the extra typeof check.
((performanceTarget: any): Performance).mark(markName);
((performanceTarget: any): Performance).clearMarks(markName);
Expand Down
34 changes: 18 additions & 16 deletions packages/react-devtools-shared/src/backend/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -2546,7 +2546,7 @@ export function attach(
// We don't patch any methods so there is no cleanup.
}

function rootSupportsProfiling(root) {
function rootSupportsProfiling(root: any) {
if (root.memoizedInteractions != null) {
// v16 builds include this field for the scheduler/tracing API.
return true;
Expand Down Expand Up @@ -2610,15 +2610,15 @@ export function attach(
}
}

function getUpdatersList(root): Array<SerializedElement> | null {
function getUpdatersList(root: any): Array<SerializedElement> | null {
return root.memoizedUpdaters != null
? Array.from(root.memoizedUpdaters)
.filter(fiber => getFiberIDUnsafe(fiber) !== null)
.map(fiberToSerializedElement)
: null;
}

function handleCommitFiberUnmount(fiber) {
function handleCommitFiberUnmount(fiber: any) {
// If the untrackFiberSet already has the unmounted Fiber, this means we've already
// recordedUnmount, so we don't need to do it again. If we don't do this, we might
// end up double-deleting Fibers in some cases (like Legacy Suspense).
Expand All @@ -2630,7 +2630,7 @@ export function attach(
}
}

function handlePostCommitFiberRoot(root) {
function handlePostCommitFiberRoot(root: any) {
if (isProfiling && rootSupportsProfiling(root)) {
if (currentCommitProfilingMetadata !== null) {
const {effectDuration, passiveEffectDuration} = getEffectDurations(
Expand All @@ -2644,7 +2644,7 @@ export function attach(
}
}

function handleCommitFiberRoot(root, priorityLevel) {
function handleCommitFiberRoot(root: any, priorityLevel: void | number) {
const current = root.current;
const alternate = current.alternate;

Expand Down Expand Up @@ -2805,18 +2805,18 @@ export function attach(
}
}

function getDisplayNameForFiberID(id) {
function getDisplayNameForFiberID(id: number) {
const fiber = idToArbitraryFiberMap.get(id);
return fiber != null ? getDisplayNameForFiber(((fiber: any): Fiber)) : null;
}

function getFiberForNative(hostInstance) {
function getFiberForNative(hostInstance: NativeType) {
return renderer.findFiberByHostInstance(hostInstance);
}

function getFiberIDForNative(
hostInstance,
findNearestUnfilteredAncestor = false,
hostInstance: NativeType,
findNearestUnfilteredAncestor: boolean = false,
) {
let fiber = renderer.findFiberByHostInstance(hostInstance);
if (fiber != null) {
Expand All @@ -2832,7 +2832,7 @@ export function attach(

// This function is copied from React and should be kept in sync:
// https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberTreeReflection.js
function assertIsMounted(fiber) {
function assertIsMounted(fiber: Fiber) {
if (getNearestMountedFiber(fiber) !== fiber) {
throw new Error('Unable to find node on an unmounted component.');
}
Expand Down Expand Up @@ -3712,7 +3712,7 @@ export function attach(
};
}

function logElementToConsole(id) {
function logElementToConsole(id: number) {
const result = isMostRecentlyInspectedElementCurrent(id)
? mostRecentlyInspectedElement
: inspectElementRaw(id);
Expand Down Expand Up @@ -4149,7 +4149,7 @@ export function attach(
// null (do nothing)
const forceErrorForFiberIDs = new Map();

function shouldErrorFiberAccordingToMap(fiber) {
function shouldErrorFiberAccordingToMap(fiber: any) {
if (typeof setErrorHandler !== 'function') {
throw new Error(
'Expected overrideError() to not get called for earlier React versions.',
Expand Down Expand Up @@ -4185,7 +4185,7 @@ export function attach(
return status;
}

function overrideError(id, forceError) {
function overrideError(id: number, forceError: boolean) {
if (
typeof setErrorHandler !== 'function' ||
typeof scheduleUpdate !== 'function'
Expand Down Expand Up @@ -4214,12 +4214,12 @@ export function attach(

const forceFallbackForSuspenseIDs = new Set();

function shouldSuspendFiberAccordingToSet(fiber) {
function shouldSuspendFiberAccordingToSet(fiber: any) {
const maybeID = getFiberIDUnsafe(((fiber: any): Fiber));
return maybeID !== null && forceFallbackForSuspenseIDs.has(maybeID);
}

function overrideSuspense(id, forceFallback) {
function overrideSuspense(id: number, forceFallback: boolean) {
if (
typeof setSuspenseHandler !== 'function' ||
typeof scheduleUpdate !== 'function'
Expand Down Expand Up @@ -4317,7 +4317,9 @@ export function attach(
return true;
}

function updateTrackedPathStateAfterMount(mightSiblingsBeOnTrackedPath) {
function updateTrackedPathStateAfterMount(
mightSiblingsBeOnTrackedPath: boolean,
) {
// updateTrackedPathStateBeforeMount() told us whether to match siblings.
// Now that we're entering siblings, let's use that information.
mightBeOnTrackedPath = mightSiblingsBeOnTrackedPath;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,11 @@ export default class Overlay {
}
}

function findTipPos(dims, bounds, tipSize) {
function findTipPos(
dims: Box,
bounds: Box,
tipSize: {height: number, width: number},
) {
const tipHeight = Math.max(tipSize.height, 20);
const tipWidth = Math.max(tipSize.width, 60);
const margin = 5;
Expand Down Expand Up @@ -314,7 +318,7 @@ function findTipPos(dims, bounds, tipSize) {
};
}

function boxWrap(dims, what, node) {
function boxWrap(dims: any, what: string, node: HTMLElement) {
assign(node.style, {
borderTopWidth: dims[what + 'Top'] + 'px',
borderLeftWidth: dims[what + 'Left'] + 'px',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export default function setupHighlighter(
registerListenersOnWindow(window);
}

function registerListenersOnWindow(window) {
function registerListenersOnWindow(window: any) {
// This plug-in may run in non-DOM environments (e.g. React Native).
if (window && typeof window.addEventListener === 'function') {
window.addEventListener('click', onClick, true);
Expand Down Expand Up @@ -66,7 +66,7 @@ export default function setupHighlighter(
iframesListeningTo = new Set();
}

function removeListenersOnWindow(window) {
function removeListenersOnWindow(window: any) {
// This plug-in may run in non-DOM environments (e.g. React Native).
if (window && typeof window.removeEventListener === 'function') {
window.removeEventListener('click', onClick, true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,15 @@ export default function ContextMenu({children, id}: Props): React.Node {
}, []);

useEffect(() => {
const showMenuFn = ({data, pageX, pageY}) => {
const showMenuFn = ({
data,
pageX,
pageY,
}: {
data: any,
pageX: number,
pageY: number,
}) => {
setState({data, isVisible: true, pageX, pageY});
};
const hideMenuFn = () => setState(HIDDEN_STATE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default function ContextMenuItem({
}: Props): React.Node {
const {hideMenu} = useContext<RegistryContextType>(RegistryContext);

const handleClick = event => {
const handleClick = (event: any) => {
onClick();
hideMenu();
};
Expand Down
4 changes: 2 additions & 2 deletions packages/react-devtools-shared/src/devtools/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* @flow
*/

import type {Thenable} from 'shared/ReactTypes';
import type {ReactContext, Thenable} from 'shared/ReactTypes';

import * as React from 'react';
import {createContext} from 'react';
Expand Down Expand Up @@ -63,7 +63,7 @@ const Rejected = 2;
const ReactCurrentDispatcher = (React: any)
.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;

function readContext(Context) {
function readContext(Context: ReactContext<null>) {
const dispatcher = ReactCurrentDispatcher.current;
if (dispatcher === null) {
throw new Error(
Expand Down
6 changes: 3 additions & 3 deletions packages/react-devtools-shared/src/devtools/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import type {
} from 'react-devtools-shared/src/bridge';
import UnsupportedBridgeOperationError from 'react-devtools-shared/src/UnsupportedBridgeOperationError';

const debug = (methodName, ...args) => {
const debug = (methodName: string, ...args: Array<string>) => {
if (__DEBUG__) {
console.log(
`%cStore %c${methodName}`,
Expand Down Expand Up @@ -1146,7 +1146,7 @@ export default class Store extends EventEmitter<{
debug(`Remove root ${id}`);
}

const recursivelyDeleteElements = elementID => {
const recursivelyDeleteElements = (elementID: number) => {
const element = this._idToElement.get(elementID);
this._idToElement.delete(elementID);
if (element) {
Expand Down Expand Up @@ -1431,7 +1431,7 @@ export default class Store extends EventEmitter<{
// but the downstream errors they cause will be reported as bugs.
// For example, https://github.com/facebook/react/issues/21402
// Emitting an error event allows the ErrorBoundary to show the original error.
_throwAndEmitError(error: Error) {
_throwAndEmitError(error: Error): empty {
this.emit('error', error);

// Throwing is still valuable for local development
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ export default function ComponentSearchInput(props: Props): React.Node {
const {searchIndex, searchResults, searchText} = useContext(TreeStateContext);
const dispatch = useContext(TreeDispatcherContext);

const search = text => dispatch({type: 'SET_SEARCH_TEXT', payload: text});
const search = (text: string) =>
dispatch({type: 'SET_SEARCH_TEXT', payload: text});
const goToNextResult = () => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'});
const goToPreviousResult = () =>
dispatch({type: 'GO_TO_PREVIOUS_SEARCH_RESULT'});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default function InspectedElementSuspenseToggle({

const isSuspended = state !== null;

const toggleSuspense = (path, value) => {
const toggleSuspense = (path: any, value: boolean) => {
const rendererID = store.getRendererIDForElement(id);
if (rendererID !== null) {
bridge.send('overrideSuspense', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export default function KeyValue({
paddingLeft: `${(depth - 1) * 0.75}rem`,
};

const overrideValue = (newPath, newValue) => {
const overrideValue = (newPath: Array<string | number>, newValue: any) => {
if (hookID != null) {
newPath = parseHookPathForEdit(newPath);
}
Expand All @@ -156,7 +156,7 @@ export default function KeyValue({
}
};

const deletePath = pathToDelete => {
const deletePath = (pathToDelete: Array<string | number>) => {
if (hookID != null) {
pathToDelete = parseHookPathForEdit(pathToDelete);
}
Expand All @@ -173,7 +173,10 @@ export default function KeyValue({
}
};

const renamePath = (oldPath, newPath) => {
const renamePath = (
oldPath: Array<string | number>,
newPath: Array<string | number>,
) => {
if (newPath[newPath.length - 1] === '') {
// Deleting the key suggests an intent to delete the whole path.
if (canDeletePaths) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default function NewArrayValue({

// This is a bit of an unusual usage of the EditableName component,
// but otherwise it acts the way we want for a new Array entry.
const overrideName = (oldPath, newPath) => {
const overrideName = (oldPath: any, newPath) => {
const value = newPath[newPath.length - 1];

let parsedValue;
Expand Down
Loading

0 comments on commit 2353823

Please sign in to comment.