Search in sources :

Example 1 with JsonCodec

use of com.vaadin.flow.internal.JsonCodec in project flow by vaadin.

the class UidlWriter method encodeExecuteJavaScript.

private static JsonArray encodeExecuteJavaScript(PendingJavaScriptInvocation invocation) {
    List<Object> parametersList = invocation.getInvocation().getParameters();
    Stream<Object> parameters = parametersList.stream();
    String expression = invocation.getInvocation().getExpression();
    if (invocation.isSubscribed()) {
        StateNode owner = invocation.getOwner();
        List<ReturnChannelRegistration> channels = new ArrayList<>();
        ReturnChannelRegistration successChannel = createReturnValueChannel(owner, channels, invocation::complete);
        ReturnChannelRegistration errorChannel = createReturnValueChannel(owner, channels, invocation::completeExceptionally);
        // Inject both channels as new parameters
        parameters = Stream.concat(parameters, Stream.of(successChannel, errorChannel));
        int successIndex = parametersList.size();
        int errorIndex = successIndex + 1;
        /*
             * Run the original expression wrapped in a function to capture any
             * return statement. Pass the return value through Promise.resolve
             * which resolves regular values immediately and waits for thenable
             * values. Call either of the handlers once the promise completes.
             * If the expression throws synchronously, run the error handler.
             */
        // @formatter:off
        expression = "try{" + "Promise.resolve((function(){" + expression + "})()).then($" + successIndex + ",function(error){$" + errorIndex + "(''+error)})" + "}catch(error){" + "$" + errorIndex + "(''+error)" + "}";
    // @formatter:on
    }
    // [argument1, argument2, ..., script]
    return Stream.concat(parameters.map(JsonCodec::encodeWithTypeInfo), Stream.of(Json.create(expression))).collect(JsonUtils.asArray());
}
Also used : JsonCodec(com.vaadin.flow.internal.JsonCodec) ReturnChannelRegistration(com.vaadin.flow.internal.nodefeature.ReturnChannelRegistration) StateNode(com.vaadin.flow.internal.StateNode) ArrayList(java.util.ArrayList) JsonObject(elemental.json.JsonObject)

Aggregations

JsonCodec (com.vaadin.flow.internal.JsonCodec)1 StateNode (com.vaadin.flow.internal.StateNode)1 ReturnChannelRegistration (com.vaadin.flow.internal.nodefeature.ReturnChannelRegistration)1 JsonObject (elemental.json.JsonObject)1 ArrayList (java.util.ArrayList)1