Skip to content

Commit ac3e705

Browse files
authored
[compiler][playground] (2/N) Config override panel (facebook#34344)
<!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please provide enough information so that others can review your pull request. The three fields below are mandatory. Before submitting a pull request, please make sure the following is done: 1. Fork [the repository](https://github.com/facebook/react) and create your branch from `main`. 2. Run `yarn` in the repository root. 3. If you've fixed a bug or added code that should be tested, add tests! 4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch TestName` is helpful in development. 5. Run `yarn test --prod` to test in the production environment. It supports the same options as `yarn test`. 6. If you need a debugger, run `yarn test --debug --watch TestName`, open `chrome://inspect`, and press "Inspect". 7. Format your code with [prettier](https://github.com/prettier/prettier) (`yarn prettier`). 8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only check changed files. 9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`). 10. If you haven't already, complete the CLA. Learn more about contributing: https://reactjs.org/docs/how-to-contribute.html --> ## Summary Part 2 of adding a "Config Override" panel to the React compiler playground. Added sync from the config editor (still only accessible with the "showConfig" param) to the main source code editor. Adding a valid config to the editor will add/replace the `@OVERRIDE` pragma above the source code. Additionally refactored the old implementation to remove `useEffect`s and unnecessary renders. Realized upon testing that the user experience is quite jarring, planning to add a `sync` button in the next PR to fix this. ## How did you test this change? <!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes the user interface. How exactly did you verify that your PR solves the issue you wanted to solve? If you leave this empty, your PR will very likely be closed. --> https://github.com/user-attachments/assets/a71b1b5f-0539-4c00-8d5c-22426f0280f9
1 parent 8e60cb7 commit ac3e705

File tree

9 files changed

+161
-65
lines changed

9 files changed

+161
-65
lines changed

compiler/apps/playground/components/Editor/ConfigEditor.tsx

Lines changed: 32 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -6,52 +6,51 @@
66
*/
77

88
import MonacoEditor, {loader, type Monaco} from '@monaco-editor/react';
9-
import {parseConfigPragmaAsString} from 'babel-plugin-react-compiler';
109
import type {editor} from 'monaco-editor';
1110
import * as monaco from 'monaco-editor';
12-
import parserBabel from 'prettier/plugins/babel';
13-
import * as prettierPluginEstree from 'prettier/plugins/estree';
14-
import * as prettier from 'prettier/standalone';
15-
import {useState, useEffect} from 'react';
11+
import {useState} from 'react';
1612
import {Resizable} from 're-resizable';
17-
import {useStore} from '../StoreContext';
13+
import {useStore, useStoreDispatch} from '../StoreContext';
1814
import {monacoOptions} from './monacoOptions';
15+
import {
16+
generateOverridePragmaFromConfig,
17+
updateSourceWithOverridePragma,
18+
} from '../../lib/configUtils';
1919

2020
loader.config({monaco});
2121

2222
export default function ConfigEditor(): JSX.Element {
2323
const [, setMonaco] = useState<Monaco | null>(null);
2424
const store = useStore();
25+
const dispatchStore = useStoreDispatch();
2526

26-
// Parse string-based override config from pragma comment and format it
27-
const [configJavaScript, setConfigJavaScript] = useState('');
27+
const handleChange: (value: string | undefined) => void = async value => {
28+
if (value === undefined) return;
2829

29-
useEffect(() => {
30-
const pragma = store.source.substring(0, store.source.indexOf('\n'));
31-
const configString = `(${parseConfigPragmaAsString(pragma)})`;
30+
try {
31+
const newPragma = await generateOverridePragmaFromConfig(value);
32+
const updatedSource = updateSourceWithOverridePragma(
33+
store.source,
34+
newPragma,
35+
);
3236

33-
prettier
34-
.format(configString, {
35-
semi: true,
36-
parser: 'babel-ts',
37-
plugins: [parserBabel, prettierPluginEstree],
38-
})
39-
.then(formatted => {
40-
setConfigJavaScript(formatted);
41-
})
42-
.catch(error => {
43-
console.error('Error formatting config:', error);
44-
setConfigJavaScript('({})'); // Return empty object if not valid for now
45-
//TODO: Add validation and error handling for config
37+
// Update the store with both the new config and updated source
38+
dispatchStore({
39+
type: 'updateFile',
40+
payload: {
41+
source: updatedSource,
42+
config: value,
43+
},
4644
});
47-
console.log('Config:', configString);
48-
}, [store.source]);
49-
50-
const handleChange: (value: string | undefined) => void = value => {
51-
if (!value) return;
52-
53-
// TODO: Implement sync logic to update pragma comments in the source
54-
console.log('Config changed:', value);
45+
} catch (_) {
46+
dispatchStore({
47+
type: 'updateFile',
48+
payload: {
49+
source: store.source,
50+
config: value,
51+
},
52+
});
53+
}
5554
};
5655

5756
const handleMount: (
@@ -81,12 +80,11 @@ export default function ConfigEditor(): JSX.Element {
8180
<MonacoEditor
8281
path={'config.js'}
8382
language={'javascript'}
84-
value={configJavaScript}
83+
value={store.config}
8584
onMount={handleMount}
8685
onChange={handleChange}
8786
options={{
8887
...monacoOptions,
89-
readOnly: true,
9088
lineNumbers: 'off',
9189
folding: false,
9290
renderLineHighlight: 'none',

compiler/apps/playground/components/Editor/EditorImpl.tsx

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import {
4848
import {transformFromAstSync} from '@babel/core';
4949
import {LoggerEvent} from 'babel-plugin-react-compiler/dist/Entrypoint';
5050
import {useSearchParams} from 'next/navigation';
51+
import {parseAndFormatConfig} from '../../lib/configUtils';
5152

5253
function parseInput(
5354
input: string,
@@ -315,9 +316,17 @@ export default function Editor(): JSX.Element {
315316
});
316317
mountStore = defaultStore;
317318
}
318-
dispatchStore({
319-
type: 'setStore',
320-
payload: {store: mountStore},
319+
320+
parseAndFormatConfig(mountStore.source).then(config => {
321+
dispatchStore({
322+
type: 'setStore',
323+
payload: {
324+
store: {
325+
...mountStore,
326+
config,
327+
},
328+
},
329+
});
321330
});
322331
});
323332

compiler/apps/playground/components/Editor/Input.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {useStore, useStoreDispatch} from '../StoreContext';
1717
import {monacoOptions} from './monacoOptions';
1818
// @ts-expect-error TODO: Make TS recognize .d.ts files, in addition to loading them with webpack.
1919
import React$Types from '../../node_modules/@types/react/index.d.ts';
20+
import {parseAndFormatConfig} from '../../lib/configUtils.ts';
2021

2122
loader.config({monaco});
2223

@@ -79,13 +80,17 @@ export default function Input({errors, language}: Props): JSX.Element {
7980
});
8081
}, [monaco, language]);
8182

82-
const handleChange: (value: string | undefined) => void = value => {
83+
const handleChange: (value: string | undefined) => void = async value => {
8384
if (!value) return;
8485

86+
// Parse and format the config
87+
const config = await parseAndFormatConfig(value);
88+
8589
dispatchStore({
8690
type: 'updateFile',
8791
payload: {
8892
source: value,
93+
config,
8994
},
9095
});
9196
};

compiler/apps/playground/components/StoreContext.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ type ReducerAction =
5656
type: 'updateFile';
5757
payload: {
5858
source: string;
59+
config?: string;
5960
};
6061
};
6162

@@ -66,10 +67,11 @@ function storeReducer(store: Store, action: ReducerAction): Store {
6667
return newStore;
6768
}
6869
case 'updateFile': {
69-
const {source} = action.payload;
70+
const {source, config} = action.payload;
7071
const newStore = {
7172
...store,
7273
source,
74+
config,
7375
};
7476
return newStore;
7577
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
import parserBabel from 'prettier/plugins/babel';
9+
import prettierPluginEstree from 'prettier/plugins/estree';
10+
import * as prettier from 'prettier/standalone';
11+
import {parseConfigPragmaAsString} from '../../../packages/babel-plugin-react-compiler/src/Utils/TestUtils';
12+
13+
/**
14+
* Parse config from pragma and format it with prettier
15+
*/
16+
export async function parseAndFormatConfig(source: string): Promise<string> {
17+
const pragma = source.substring(0, source.indexOf('\n'));
18+
let configString = parseConfigPragmaAsString(pragma);
19+
if (configString !== '') {
20+
configString = `(${configString})`;
21+
}
22+
23+
try {
24+
const formatted = await prettier.format(configString, {
25+
semi: true,
26+
parser: 'babel-ts',
27+
plugins: [parserBabel, prettierPluginEstree],
28+
});
29+
return formatted;
30+
} catch (error) {
31+
console.error('Error formatting config:', error);
32+
return ''; // Return empty string if not valid for now
33+
}
34+
}
35+
36+
function extractCurlyBracesContent(input: string): string {
37+
const startIndex = input.indexOf('{');
38+
const endIndex = input.lastIndexOf('}');
39+
if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) {
40+
throw new Error('No outer curly braces found in input');
41+
}
42+
return input.slice(startIndex, endIndex + 1);
43+
}
44+
45+
function cleanContent(content: string): string {
46+
return content
47+
.replace(/[\r\n]+/g, ' ')
48+
.replace(/\s+/g, ' ')
49+
.trim();
50+
}
51+
52+
/**
53+
* Generate a the override pragma comment from a formatted config object string
54+
*/
55+
export async function generateOverridePragmaFromConfig(
56+
formattedConfigString: string,
57+
): Promise<string> {
58+
const content = extractCurlyBracesContent(formattedConfigString);
59+
const cleanConfig = cleanContent(content);
60+
61+
// Format the config to ensure it's valid
62+
await prettier.format(`(${cleanConfig})`, {
63+
semi: false,
64+
parser: 'babel-ts',
65+
plugins: [parserBabel, prettierPluginEstree],
66+
});
67+
68+
return `// @OVERRIDE:${cleanConfig}`;
69+
}
70+
71+
/**
72+
* Update the override pragma comment in source code.
73+
*/
74+
export function updateSourceWithOverridePragma(
75+
source: string,
76+
newPragma: string,
77+
): string {
78+
const firstLineEnd = source.indexOf('\n');
79+
const firstLine = source.substring(0, firstLineEnd);
80+
81+
const pragmaRegex = /^\/\/\s*@/;
82+
if (firstLineEnd !== -1 && pragmaRegex.test(firstLine.trim())) {
83+
return newPragma + source.substring(firstLineEnd);
84+
} else {
85+
return newPragma + '\n' + source;
86+
}
87+
}

compiler/apps/playground/lib/defaultStore.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@ export default function MyApp() {
1515

1616
export const defaultStore: Store = {
1717
source: index,
18+
config: '',
1819
};
1920

2021
export const emptyStore: Store = {
2122
source: '',
23+
config: '',
2224
};

compiler/apps/playground/lib/stores/store.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {defaultStore} from '../defaultStore';
1717
*/
1818
export interface Store {
1919
source: string;
20+
config?: string;
2021
}
2122
export function encodeStore(store: Store): string {
2223
return compressToEncodedURIComponent(JSON.stringify(store));
@@ -65,5 +66,14 @@ export function initStoreFromUrlOrLocalStorage(): Store {
6566
const raw = decodeStore(encodedSource);
6667

6768
invariant(isValidStore(raw), 'Invalid Store');
69+
70+
// Add config property if missing for backwards compatibility
71+
if (!('config' in raw)) {
72+
return {
73+
...raw,
74+
config: '',
75+
};
76+
}
77+
6878
return raw;
6979
}

compiler/packages/babel-plugin-react-compiler/src/Utils/TestUtils.ts

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -255,11 +255,16 @@ function parseConfigStringAsJS(
255255

256256
console.log('OVERRIDE:', parsedConfig);
257257

258+
const environment = parseConfigPragmaEnvironmentForTest(
259+
'',
260+
defaults.environment ?? {},
261+
);
262+
258263
const options: Record<keyof PluginOptions, unknown> = {
259264
...defaultOptions,
260265
panicThreshold: 'all_errors',
261266
compilationMode: defaults.compilationMode,
262-
environment: defaults.environment ?? defaultOptions.environment,
267+
environment,
263268
};
264269

265270
// Apply parsed config, merging environment if it exists
@@ -269,22 +274,9 @@ function parseConfigStringAsJS(
269274
...parsedConfig.environment,
270275
};
271276

272-
// Apply complex defaults for environment flags that are set to true
273-
const environmentConfig: Partial<Record<keyof EnvironmentConfig, unknown>> =
274-
{};
275-
for (const [key, value] of Object.entries(mergedEnvironment)) {
276-
if (hasOwnProperty(EnvironmentConfigSchema.shape, key)) {
277-
if (value === true && key in testComplexConfigDefaults) {
278-
environmentConfig[key] = testComplexConfigDefaults[key];
279-
} else {
280-
environmentConfig[key] = value;
281-
}
282-
}
283-
}
284-
285277
// Validate environment config
286278
const validatedEnvironment =
287-
EnvironmentConfigSchema.safeParse(environmentConfig);
279+
EnvironmentConfigSchema.safeParse(mergedEnvironment);
288280
if (!validatedEnvironment.success) {
289281
CompilerError.invariant(false, {
290282
reason: 'Invalid environment configuration in config pragma',
@@ -294,10 +286,6 @@ function parseConfigStringAsJS(
294286
});
295287
}
296288

297-
if (validatedEnvironment.data.enableResetCacheOnSourceFileChanges == null) {
298-
validatedEnvironment.data.enableResetCacheOnSourceFileChanges = false;
299-
}
300-
301289
options.environment = validatedEnvironment.data;
302290
}
303291

@@ -308,9 +296,7 @@ function parseConfigStringAsJS(
308296
}
309297

310298
if (hasOwnProperty(defaultOptions, key)) {
311-
if (value === true && key in testComplexPluginOptionDefaults) {
312-
options[key] = testComplexPluginOptionDefaults[key];
313-
} else if (key === 'target' && value === 'donotuse_meta_internal') {
299+
if (key === 'target' && value === 'donotuse_meta_internal') {
314300
options[key] = {
315301
kind: value,
316302
runtimeModule: 'react',

compiler/packages/babel-plugin-react-compiler/src/index.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,7 @@ export {
4848
printReactiveFunction,
4949
printReactiveFunctionWithOutlined,
5050
} from './ReactiveScopes';
51-
export {
52-
parseConfigPragmaForTests,
53-
parseConfigPragmaAsString,
54-
} from './Utils/TestUtils';
51+
export {parseConfigPragmaForTests} from './Utils/TestUtils';
5552
declare global {
5653
let __DEV__: boolean | null | undefined;
5754
}

0 commit comments

Comments
 (0)