react/scripts/shared/evalToString.js
Andrew Clark 77c4ac2ce8
[useFormState] Allow sync actions (#27571)
Updates useFormState to allow a sync function to be passed as an action.

A form action is almost always async, because it needs to talk to the
server. But since we support client-side actions, too, there's no reason
we can't allow sync actions, too.

I originally chose not to allow them to keep the implementation simpler
but it's not really that much more complicated because we already
support this for actions passed to startTransition. So now it's
consistent: anywhere an action is accepted, a sync client function is a
valid input.
2023-10-31 23:32:31 -04:00

56 lines
1.6 KiB
JavaScript

/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
function evalStringConcat(ast) {
switch (ast.type) {
case 'StringLiteral':
case 'Literal': // ESLint
return ast.value;
case 'BinaryExpression': // `+`
if (ast.operator !== '+') {
throw new Error('Unsupported binary operator ' + ast.operator);
}
return evalStringConcat(ast.left) + evalStringConcat(ast.right);
default:
throw new Error('Unsupported type ' + ast.type);
}
}
exports.evalStringConcat = evalStringConcat;
function evalStringAndTemplateConcat(ast, args) {
switch (ast.type) {
case 'StringLiteral':
return ast.value;
case 'BinaryExpression': // `+`
if (ast.operator !== '+') {
throw new Error('Unsupported binary operator ' + ast.operator);
}
return (
evalStringAndTemplateConcat(ast.left, args) +
evalStringAndTemplateConcat(ast.right, args)
);
case 'TemplateLiteral': {
let elements = [];
for (let i = 0; i < ast.quasis.length; i++) {
const elementNode = ast.quasis[i];
if (elementNode.type !== 'TemplateElement') {
throw new Error('Unsupported type ' + ast.type);
}
elements.push(elementNode.value.cooked);
}
args.push(...ast.expressions);
return elements.join('%s');
}
default:
// Anything that's not a string is interpreted as an argument.
args.push(ast);
return '%s';
}
}
exports.evalStringAndTemplateConcat = evalStringAndTemplateConcat;