Skip to content
Open
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
16 changes: 16 additions & 0 deletions compiler/packages/babel-plugin-react-compiler/src/HIR/Globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,22 @@ const TYPED_GLOBALS: Array<[string, BuiltInType]> = [
true,
),
],
[
'IntersectionObserver',
addFunction(
DEFAULT_SHAPES,
[],
{
positionalParams: [Effect.Freeze, Effect.Read],
restParam: null,
returnType: {kind: 'Object', shapeId: BuiltInObjectId},
calleeEffect: Effect.Read,
returnValueKind: ValueKind.Mutable,
},
null,
true,
),
],
// TODO: rest of Global objects
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -455,11 +455,14 @@ function validateNoRefAccessInRenderImpl(
break;
}
case 'MethodCall':
case 'NewExpression':
case 'CallExpression': {
const callee =
instr.value.kind === 'CallExpression'
? instr.value.callee
: instr.value.property;
: instr.value.kind === 'NewExpression'
? instr.value.callee
: instr.value.property;
const hookKind = getHookKindForType(fn.env, callee.identifier.type);
let returnType: RefAccessType = {kind: 'None'};
const fnType = env.get(callee.identifier.id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,65 @@ const tests: CompilerTestCases = {
],
};

const refsTests: CompilerTestCases = {
valid: [
{
name: 'Allows ref-reading callbacks passed to IntersectionObserver',
filename: 'test.tsx',
code: normalizeIndent`
import {useCallback, useMemo, useRef} from 'react';

type IntersectionCallback = (isIntersecting: boolean) => void;

function useIntersectionObserver(
options: Partial<IntersectionObserverInit>,
) {
const callbacks = useRef(new Map<string, IntersectionCallback>());

const onIntersect = useCallback(
(entries: ReadonlyArray<IntersectionObserverEntry>) => {
entries.forEach(entry =>
callbacks.current.get(entry.target.id)?.(entry.isIntersecting),
);
},
[],
);

return useMemo(
() => new IntersectionObserver(onIntersect, options),
[onIntersect, options],
);
}
`,
},
],
invalid: [
{
name: 'Reports ref-reading callbacks passed to unknown constructors',
filename: 'test.tsx',
code: normalizeIndent`
import {useCallback, useMemo, useRef} from 'react';

function useUnknownObserver(Ctor) {
const ref = useRef(null);
const onChange = useCallback(() => {
return ref.current;
}, []);

return useMemo(() => new Ctor(onChange), [Ctor, onChange]);
}
`,
errors: [
{
message: /Cannot access refs during render/,
},
],
},
],
};

const eslintTester = new ESLintTesterV8({
parser: require.resolve('@typescript-eslint/parser-v5'),
});
eslintTester.run('react-compiler', allRules['immutability'].rule, tests);
eslintTester.run('react-compiler refs', allRules['refs'].rule, refsTests);