papegaaij commented on code in PR #1834: URL: https://github.com/apache/wicket/pull/1834#discussion_r4523021943
########## wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/FormIsland.java: ########## @@ -0,0 +1,374 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.wicket.islands; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.feedback.FeedbackMessage; +import org.apache.wicket.islands.serializer.IslandSerializationException; +import org.apache.wicket.markup.ComponentTag; +import org.apache.wicket.markup.MarkupStream; +import org.apache.wicket.markup.head.IHeaderResponse; +import org.apache.wicket.markup.html.form.FormComponent; +import org.apache.wicket.model.IModel; +import org.apache.wicket.request.cycle.RequestCycle; +import org.apache.wicket.util.lang.Args; +import org.apache.wicket.util.string.Strings; +import org.apache.wicket.validation.ValidationError; + +/** + * An island that is a form component: its client-side peer edits a value of type {@code T}, which + * takes part in the form like the value of any other form component, with conversion, validators, + * {@code required}, feedback messages, and normal and Ajax submits. + * <p> + * The value travels as JSON in a hidden input inside the host element. The peer reads and writes + * it through its adapter (e.g. {@code useFormValue()} in React), which also fires + * <code>input</code> and <code>change</code> events, so Ajax behaviors on this component work as + * on any other. Besides its own props, the peer gets the form state: whether the value is + * required, whether the component is enabled, its label, and its feedback messages. + * <p> + * <strong>The submitted value comes from the browser and is untrusted.</strong> It is converted + * into {@code T} by the island serializer, so it can only hold what {@code T} declares, and it is + * validated like any other input. A value that is markup, such as the HTML of a rich text + * editor, must be sanitized before it is ever rendered without escaping; override + * {@link #sanitize(Object)} to apply a sanitizer of your choice. Wicket bundles none. + * <p> + * After an Ajax request that validated it, a form island adds itself to the request target, so + * its feedback messages reach the peer; see {@link #setUpdateOnValidation(boolean)}. + * + * @param <T> + * the type of the value + * @param <P> + * the type of the props + * @since 12.0.0 + */ +public class FormIsland<T, P> extends FormComponent<T> +{ + private static final long serialVersionUID = 1L; + + /** + * The attribute marking the hidden input that holds the value. + */ + public static final String ATTR_VALUE = "data-wicket-island-value"; + + private final IslandSupport island; + + private final Class<T> valueType; + + private final IModel<P> props; + + private boolean updateOnValidation = true; + + /** + * Creates a form island without props of its own. + * + * @param id + * the component id + * @param type + * the island type, naming the client-side module; letters, digits, '-' and '_' + * @param model + * the model of the value + * @param valueType + * the type of the value, which submitted JSON is converted into + */ + public FormIsland(String id, String type, IModel<T> model, Class<T> valueType) + { + this(id, type, model, valueType, null); + } + + /** + * @param id + * the component id + * @param type + * the island type, naming the client-side module; letters, digits, '-' and '_' + * @param model + * the model of the value + * @param valueType + * the type of the value, which submitted JSON is converted into + * @param props + * the model of the props, {@code null} for none + */ + public FormIsland(String id, String type, IModel<T> model, Class<T> valueType, + IModel<P> props) + { + super(id, model); + this.valueType = Args.notNull(valueType, "valueType"); + setType(valueType); + this.props = props; + island = new IslandSupport(type); + setOutputMarkupId(true); + setEscapeModelStrings(false); + add(island.getBehavior()); + } + + /** + * @return the island type + */ + public final String getIslandType() + { + return island.getType(); + } + + /** + * @return the key identifying this island instance across re-renders + */ + public final String getKey() + { + return island.getKey(); + } + + final IslandSupport getIslandSupport() + { + return island; + } + + /** + * Registers a call that returns a result. + * + * @see Island#onCall(String, Class, Class, IslandCallHandler) + */ + public final <Q, R> FormIsland<T, P> onCall(String name, Class<Q> requestType, + Class<R> resultType, IslandCallHandler<Q, R> handler) + { + island.addEndpoint(name, requestType, resultType, handler); + return this; + } + + /** + * Registers a call that returns no result. + * + * @see Island#onCall(String, Class, IslandCallConsumer) + */ + public final <Q> FormIsland<T, P> onCall(String name, Class<Q> requestType, + IslandCallConsumer<Q> handler) + { + island.addEndpoint(name, requestType, Void.class, IslandSupport.withoutResult(handler)); + return this; + } + + /** + * @param updateOnValidation + * whether this island adds itself to the Ajax request target after it was validated, + * so its peer receives its feedback messages; {@code true} by default + * @return {@code this} + */ + public FormIsland<T, P> setUpdateOnValidation(boolean updateOnValidation) + { + this.updateOnValidation = updateOnValidation; + return this; + } + + /** + * Converts the submitted JSON into the value with the island serializer, and passes it through + * {@link #sanitize(Object)}. JSON that does not match the value type is a conversion error. + */ + @Override + public void convertInput() + { + String input = getInput(); + if (Strings.isEmpty(input)) + { + setConvertedInput(null); + return; + } + try + { + setConvertedInput(sanitize(IslandSupport.serializer().fromJson(input, valueType))); + } + catch (IslandSerializationException e) + { + error(new ValidationError().addKey("FormIsland.ConversionError") + .setVariable("label", getLabel() != null ? getLabel().getObject() : getId()) + .setMessage("The value is not valid.")); + } + } + + /** + * Gives a subclass the chance to clean a submitted value before it is validated and reaches + * the model, e.g. by running HTML through a sanitizer. Returns the value unchanged by default. + * + * @param value + * the value converted from the submitted JSON, never {@code null} + * @return the value to use + */ + protected T sanitize(T value) + { + return value; + } + + @Override + protected String getModelValue() + { + T value = getModelObject(); + return value == null ? "" : IslandSupport.serializer().toJson(value); + } + + /** + * Makes a page-less endpoint callable by the client-side peer under the endpoint's id. + * + * @param endpointId + * the id the endpoint is registered under in {@link PagelessEndpoints} + * @return {@code this} + */ + public final FormIsland<T, P> usePageless(String endpointId) + { + return usePageless(endpointId, endpointId); + } + + /** + * Makes a page-less endpoint callable by the client-side peer under the given name. The peer + * calls it like any other call; it runs outside the page lock and cannot update components. + * + * @param name + * the name the client calls + * @param endpointId + * the id the endpoint is registered under in {@link PagelessEndpoints} + * @return {@code this} + */ + public final FormIsland<T, P> usePageless(String name, String endpointId) + { + island.addPageless(name, endpointId, null); + return this; + } + + /** + * Makes a page-less endpoint callable by the client-side peer under the given name, with a + * handle for the given context. The context is read when the island renders and kept on the + * server, in the {@link IslandSettings#getHandleStore() handle store}; the client only holds the + * handle and sends it with each call, and the endpoint reads the context with + * {@link PagelessCall#getHandle(Class)}. Use it for context the client must not choose, such as + * the record the page shows. The handle is reissued when the context changes. + * <p> + * <strong>A handle is not an authorization mechanism.</strong> The endpoint still checks that + * the session may access the context. + * + * @param name + * the name the client calls + * @param endpointId + * the id the endpoint is registered under in {@link PagelessEndpoints} + * @param context + * the context of the calls; small, serializable and with a meaningful + * {@code equals} + * @return {@code this} + */ + public final FormIsland<T, P> usePageless(String name, String endpointId, + IModel<? extends Serializable> context) + { + island.addPageless(name, endpointId, Args.notNull(context, "context")); + return this; + } + + /** + * Lets calls reach a page Wicket recreated after the original expired. The recreated island has + * a new key, so the call is answered as expired instead of being handled. + */ + @Override + public boolean canCallListenerAfterExpiry() + { + return true; + } + + @Override + protected void onComponentTag(ComponentTag tag) + { + super.onComponentTag(tag); + + tag.remove("name"); + island.onComponentTag(tag); + } + + /** + * Leaves the host element as it is: the peer learns from the form state that the island is + * disabled. + */ + @Override + protected void onDisabled(ComponentTag tag) + { + } + + @Override + public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) + { + String value = "<input type=\"hidden\" " + ATTR_VALUE + " name=\"" + + Strings.escapeMarkup(getInputName()) + "\" value=\"" + Strings.escapeMarkup(getValue()) + + "\">"; + replaceComponentTagBody(markupStream, openTag, + value + island.renderState(props != null ? props.getObject() : null, renderFormState())); + } + + private String renderFormState() + { + List<String> errors = new ArrayList<>(); + for (FeedbackMessage message : getFeedbackMessages().toList()) + { + message.markRendered(); + errors.add(String.valueOf(message.getMessage())); + } + Map<String, Object> state = new LinkedHashMap<>(); + state.put("required", isRequired()); + state.put("enabled", isEnabledInHierarchy()); + state.put("label", getLabel() != null ? getLabel().getObject() : null); + state.put("errors", errors); + return IslandSupport.serializer().toJson(state); + } + + @Override + protected void onValid() + { + super.onValid(); + addToAjaxTarget(); + } + + @Override + protected void onInvalid() + { + super.onInvalid(); + addToAjaxTarget(); + } + + private void addToAjaxTarget() Review Comment: Fixed in da6964b04b with the first direction. After Ajax validation the form island sends its form state as a data entry (`{"form":{key, state}}`, rendered in `onBeforeRespond` unless the request re-renders the island anyway), and the runtime applies it without touching the value. A re-render the application asks for still replaces value and state. Reproduced and verified in the browser with 3823a287ec: the task board now validates the description live, and `TaskBoardSeleniumTest.typingInTheDescriptionWhileItIsValidatedLosesNothing` types during the round trips. It fails against the old re-render and passes now. ########## wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts: ########## @@ -0,0 +1,367 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { IslandCallError, type IslandCallErrorKind, type IslandContext, type IslandInstance, + type IslandModule } from './types'; +import { QueryClient } from '@tanstack/query-core'; +import { HostFormBinding, type FormState } from './form'; +import { ClientStores } from './store'; +import { TOPIC_AJAX_CALL_DATA, TOPIC_AJAX_CALL_DONE, TOPIC_DOM_NODE_ADDED, wicket, + type WicketAjaxAttributes, type WicketApi } from './wicket'; + +const ATTR_TYPE = 'data-wicket-island'; +const ATTR_KEY = 'data-wicket-island-key'; +const SELECTOR_STATE = ':scope > script[data-wicket-island-state]'; +const SELECTOR_ROOT = ':scope > [data-wicket-island-root]'; + +const DATA_NAME = 'wicket-islands'; +const PARAM_CALL = 'island-call'; +const PARAM_CALL_ID = 'island-call-id'; +const PARAM_PAYLOAD = 'island-payload'; +const PARAM_KEY = 'island-key'; +const PAGELESS_HEADER = 'X-Wicket-Islands'; +const HANDLE_HEADER = 'X-Wicket-Islands-Handle'; + +interface IslandState { + props: unknown; + calls: string[]; + ajax: WicketAjaxAttributes; + pageless?: Record<string, PagelessCall>; + form?: FormState; +} + +/** + * A page-less endpoint as the island state names it: its URL, and the handle standing for the + * context the server keeps for the island's calls. + */ +interface PagelessCall { + url: string; + handle?: string; +} + +interface MountedIsland { + readonly type: string; + readonly key: string; + readonly root: HTMLElement; + readonly abort: AbortController; + host: HTMLElement; + state: IslandState; + form?: HostFormBinding; + instance?: IslandInstance<unknown>; +} + +interface PendingCall { + resolve(value: unknown): void; + reject(error: IslandCallError): void; +} + +interface Envelope { + call?: string; + ok?: boolean; + value?: unknown; + error?: { kind: IslandCallErrorKind; messages: string[] }; + invalidate?: string[]; +} + +/** + * Finds island hosts in the page, mounts the module registered for their type, keeps them alive + * when Wicket re-renders them, unmounts them when they are gone, and carries their calls. + */ +export class IslandRuntime { + private readonly modules = new Map<string, IslandModule<unknown>>(); + + private readonly mounted = new Map<string, MountedIsland>(); + + private readonly pending = new Map<string, PendingCall>(); + + private readonly invalidationListeners = new Set<(keys: readonly string[]) => void>(); + + readonly stores = new ClientStores(); + + readonly queryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: (failures, error) => failures < 2 && error instanceof IslandCallError && + (error.kind === 'network' || error.kind === 'error') + } + } + }); + + constructor() { + this.onInvalidate(keys => { + for (const key of keys) { + void this.queryClient.invalidateQueries({ queryKey: [key] }); + } + }); + } + + private api?: WicketApi; + + private callSequence = 0; + + register(type: string, module: IslandModule<unknown>): void { + this.modules.set(type, module); + this.connect(); + this.scan(document.documentElement); + } + + /** + * Listens to the query keys the server marks as stale. + */ + onInvalidate(listener: (keys: readonly string[]) => void): () => void { + this.invalidationListeners.add(listener); + return () => this.invalidationListeners.delete(listener); + } + + private connect(): void { + if (this.api) { + return; + } + const api = wicket(); + this.api = api; + api.Event.subscribe(TOPIC_DOM_NODE_ADDED, + (_event, element: Element) => this.scan(element)); + api.Event.subscribe(TOPIC_AJAX_CALL_DATA, + (_event, _attributes: unknown, name: string, value: string) => { + if (name === DATA_NAME) { + this.receive(value); + } + }); + api.Event.subscribe(TOPIC_AJAX_CALL_DONE, () => this.sweep()); + } + + private scan(element: Element): void { + const hosts: Element[] = []; + if (element.matches(`[${ATTR_TYPE}]`)) { + hosts.push(element); + } + hosts.push(...element.querySelectorAll(`[${ATTR_TYPE}]`)); + for (const host of hosts) { + this.attach(host as HTMLElement); Review Comment: Fixed in da6964b04b: each host is attached in its own `try`, and a failure is logged with the host's id. A module whose `mount` throws is removed from `mounted` again, so a later registration can mount it. Both cases are covered by runtime tests. ########## wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandEndpointBehavior.java: ########## @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.wicket.islands; + +import java.util.List; + +import org.apache.wicket.Application; +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; +import org.apache.wicket.ajax.AjaxChannel; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; +import org.apache.wicket.authorization.AuthorizationException; +import org.apache.wicket.islands.serializer.IIslandSerializer; +import org.apache.wicket.islands.serializer.IslandSerializationException; +import org.apache.wicket.request.IRequestParameters; +import org.apache.wicket.request.RequestHandlerExecutor.ReplaceHandlerException; +import org.apache.wicket.request.cycle.RequestCycle; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Receives the page-bound calls of an island and answers each with a data entry carrying the + * result or the failure. + */ +final class IslandEndpointBehavior extends AbstractDefaultAjaxBehavior +{ + private static final long serialVersionUID = 1L; + + private static final Logger LOG = LoggerFactory.getLogger(IslandEndpointBehavior.class); + + static final String PARAM_CALL = "island-call"; + + static final String PARAM_CALL_ID = "island-call-id"; + + static final String PARAM_PAYLOAD = "island-payload"; + + static final String PARAM_KEY = "island-key"; + + @Override + protected void updateAjaxAttributes(AjaxRequestAttributes attributes) + { + super.updateAjaxAttributes(attributes); + attributes.setMethod(AjaxRequestAttributes.Method.POST); + attributes.setChannel(new AjaxChannel("wicket-island-" + getComponent().getMarkupId())); + } + + CharSequence renderAttributes() + { + return renderAjaxAttributes(getComponent()); + } + + @Override + protected void respond(AjaxRequestTarget target) + { + Component component = getComponent(); + IslandSupport island = supportOf(component); + IRequestParameters parameters = RequestCycle.get().getRequest().getPostParameters(); + String callId = parameters.getParameterValue(PARAM_CALL_ID).toString(""); + String name = parameters.getParameterValue(PARAM_CALL).toString(""); + String payload = parameters.getParameterValue(PARAM_PAYLOAD).toOptionalString(); + String key = parameters.getParameterValue(PARAM_KEY).toString(""); + + IIslandSerializer serializer = IslandSettings.get().getSerializer(); + IslandCall call = new IslandCall(component, target); + List<String> invalidations = call.getInvalidations(); + + String answer; + if (!island.getKey().equals(key)) + { + answer = IslandAnswer.failure(serializer, callId, "expired", + List.of(IslandAnswer.EXPIRED_MESSAGE), invalidations); + target.addData(IslandAnswer.DATA_NAME, answer); + return; + } + + try + { + Object result = island.invoke(name, payload, call); + answer = IslandAnswer.success(serializer, callId, result, invalidations); + } + catch (IslandCallRejectedException e) + { + answer = IslandAnswer.failure(serializer, callId, "invalid", e.getMessages(), + invalidations); + } + catch (IslandSerializationException e) Review Comment: Fixed in da6964b04b: `IslandAnswer.success` turns a serialization failure of the result into an `IllegalStateException`, which is answered as `error` and logged at ERROR. Only a payload that cannot be converted is still `invalid`. ########## wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpointResource.java: ########## @@ -0,0 +1,193 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.wicket.islands; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import java.util.List; + +import org.apache.wicket.Application; +import org.apache.wicket.authorization.AuthorizationException; +import org.apache.wicket.islands.serializer.IIslandSerializer; +import org.apache.wicket.islands.serializer.IslandSerializationException; +import org.apache.wicket.request.RequestHandlerExecutor.ReplaceHandlerException; +import org.apache.wicket.request.http.WebRequest; +import org.apache.wicket.request.resource.AbstractResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import jakarta.servlet.http.HttpServletRequest; + +/** + * Serves the page-less endpoints. It only accepts a <code>POST</code> with the header the client + * runtime sends, which a cross-site form cannot send and a cross-origin script cannot send without + * a CORS preflight that is never granted, and refuses a request whose <code>Sec-Fetch-Site</code> + * is not <code>same-origin</code>. These checks apply whether or not the application uses + * resource isolation for its pages. + * <p> + * A call made with a handle the session does not know, for example one issued before the session + * expired, is answered as expired. + */ +final class PagelessEndpointResource extends AbstractResource +{ + private static final long serialVersionUID = 1L; + + private static final Logger LOG = LoggerFactory.getLogger(PagelessEndpointResource.class); + + static final String HEADER = "X-Wicket-Islands"; + + static final String HANDLE_HEADER = "X-Wicket-Islands-Handle"; + + private static final int MAX_PAYLOAD = 1024 * 1024; + + @Override + protected ResourceResponse newResourceResponse(Attributes attributes) + { + ResourceResponse response = new ResourceResponse(); + response.disableCaching(); + + WebRequest request = (WebRequest)attributes.getRequest(); + HttpServletRequest http = (HttpServletRequest)request.getContainerRequest(); + if (!"POST".equals(http.getMethod())) + { + response.setError(405); + return response; + } + String fetchSite = request.getHeader("Sec-Fetch-Site"); + if (request.getHeader(HEADER) == null || + (fetchSite != null && !"same-origin".equals(fetchSite))) + { + response.setError(403); + return response; + } + + String id = attributes.getParameters().get(0).toString(""); + PagelessEndpoints.Registration registration = IslandSettings.get() + .getPagelessEndpoints() + .get(id); + if (registration == null) + { + response.setError(404); + return response; + } + + String body; + try + { + body = read(http); + } + catch (IOException e) + { + response.setError(400); + return response; + } + + String handleHeader = request.getHeader(HANDLE_HEADER); + Serializable handle = handleHeader == null ? null + : IslandSettings.get().getHandleStore().resolve(id, handleHeader); + String answer = handleHeader != null && handle == null + ? IslandAnswer.failure(IslandSettings.get().getSerializer(), null, "expired", + List.of("The page this call belongs to has expired."), List.of()) + : answer(id, registration, new PagelessCall(id, request, handle), body); + response.setContentType("application/json"); + response.setTextEncoding("UTF-8"); + response.setWriteCallback(new WriteCallback() + { + @Override + public void writeData(Attributes attributes) throws IOException + { + attributes.getResponse().write(answer.getBytes(StandardCharsets.UTF_8)); + } + }); + return response; + } + + private static String answer(String id, PagelessEndpoints.Registration registration, + PagelessCall call, String body) + { + IIslandSerializer serializer = IslandSettings.get().getSerializer(); + List<String> invalidations = call.getInvalidations(); + try + { + if (!registration.authorization().isAllowed(call)) + { + return IslandAnswer.failure(serializer, null, "forbidden", + List.of("The call is not allowed."), invalidations); + } + Object request = null; + if (registration.requestType() != Void.class) + { + if (!body.isEmpty()) + { + request = serializer.fromJson(body, registration.requestType()); + } + if (request == null) + { + throw new IslandCallRejectedException("The call has no payload."); + } + } + Object value = registration.endpoint().handle(request, call); + return IslandAnswer.success(serializer, null, value, invalidations); + } + catch (IslandCallRejectedException e) + { + return IslandAnswer.failure(serializer, null, "invalid", e.getMessages(), invalidations); + } + catch (IslandSerializationException e) Review Comment: Fixed in da6964b04b, the same way as in `IslandEndpointBehavior`. ########## wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/FormIsland.java: ########## @@ -0,0 +1,374 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.wicket.islands; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.feedback.FeedbackMessage; +import org.apache.wicket.islands.serializer.IslandSerializationException; +import org.apache.wicket.markup.ComponentTag; +import org.apache.wicket.markup.MarkupStream; +import org.apache.wicket.markup.head.IHeaderResponse; +import org.apache.wicket.markup.html.form.FormComponent; +import org.apache.wicket.model.IModel; +import org.apache.wicket.request.cycle.RequestCycle; +import org.apache.wicket.util.lang.Args; +import org.apache.wicket.util.string.Strings; +import org.apache.wicket.validation.ValidationError; + +/** + * An island that is a form component: its client-side peer edits a value of type {@code T}, which + * takes part in the form like the value of any other form component, with conversion, validators, + * {@code required}, feedback messages, and normal and Ajax submits. + * <p> + * The value travels as JSON in a hidden input inside the host element. The peer reads and writes + * it through its adapter (e.g. {@code useFormValue()} in React), which also fires + * <code>input</code> and <code>change</code> events, so Ajax behaviors on this component work as + * on any other. Besides its own props, the peer gets the form state: whether the value is + * required, whether the component is enabled, its label, and its feedback messages. + * <p> + * <strong>The submitted value comes from the browser and is untrusted.</strong> It is converted + * into {@code T} by the island serializer, so it can only hold what {@code T} declares, and it is + * validated like any other input. A value that is markup, such as the HTML of a rich text + * editor, must be sanitized before it is ever rendered without escaping; override + * {@link #sanitize(Object)} to apply a sanitizer of your choice. Wicket bundles none. + * <p> + * After an Ajax request that validated it, a form island adds itself to the request target, so + * its feedback messages reach the peer; see {@link #setUpdateOnValidation(boolean)}. + * + * @param <T> + * the type of the value + * @param <P> + * the type of the props + * @since 12.0.0 + */ +public class FormIsland<T, P> extends FormComponent<T> +{ + private static final long serialVersionUID = 1L; + + /** + * The attribute marking the hidden input that holds the value. + */ + public static final String ATTR_VALUE = "data-wicket-island-value"; + + private final IslandSupport island; + + private final Class<T> valueType; + + private final IModel<P> props; + + private boolean updateOnValidation = true; + + /** + * Creates a form island without props of its own. + * + * @param id + * the component id + * @param type + * the island type, naming the client-side module; letters, digits, '-' and '_' + * @param model + * the model of the value + * @param valueType + * the type of the value, which submitted JSON is converted into + */ + public FormIsland(String id, String type, IModel<T> model, Class<T> valueType) + { + this(id, type, model, valueType, null); + } + + /** + * @param id + * the component id + * @param type + * the island type, naming the client-side module; letters, digits, '-' and '_' + * @param model + * the model of the value + * @param valueType + * the type of the value, which submitted JSON is converted into + * @param props + * the model of the props, {@code null} for none + */ + public FormIsland(String id, String type, IModel<T> model, Class<T> valueType, + IModel<P> props) + { + super(id, model); + this.valueType = Args.notNull(valueType, "valueType"); + setType(valueType); + this.props = props; + island = new IslandSupport(type); + setOutputMarkupId(true); + setEscapeModelStrings(false); + add(island.getBehavior()); + } + + /** + * @return the island type + */ + public final String getIslandType() + { + return island.getType(); + } + + /** + * @return the key identifying this island instance across re-renders + */ + public final String getKey() + { + return island.getKey(); + } + + final IslandSupport getIslandSupport() + { + return island; + } + + /** + * Registers a call that returns a result. + * + * @see Island#onCall(String, Class, Class, IslandCallHandler) + */ + public final <Q, R> FormIsland<T, P> onCall(String name, Class<Q> requestType, + Class<R> resultType, IslandCallHandler<Q, R> handler) + { + island.addEndpoint(name, requestType, resultType, handler); + return this; + } + + /** + * Registers a call that returns no result. + * + * @see Island#onCall(String, Class, IslandCallConsumer) + */ + public final <Q> FormIsland<T, P> onCall(String name, Class<Q> requestType, + IslandCallConsumer<Q> handler) + { + island.addEndpoint(name, requestType, Void.class, IslandSupport.withoutResult(handler)); + return this; + } + + /** + * @param updateOnValidation + * whether this island adds itself to the Ajax request target after it was validated, + * so its peer receives its feedback messages; {@code true} by default + * @return {@code this} + */ + public FormIsland<T, P> setUpdateOnValidation(boolean updateOnValidation) + { + this.updateOnValidation = updateOnValidation; + return this; + } + + /** + * Converts the submitted JSON into the value with the island serializer, and passes it through + * {@link #sanitize(Object)}. JSON that does not match the value type is a conversion error. + */ + @Override + public void convertInput() + { + String input = getInput(); + if (Strings.isEmpty(input)) + { + setConvertedInput(null); + return; + } + try + { + setConvertedInput(sanitize(IslandSupport.serializer().fromJson(input, valueType))); Review Comment: Fixed in da6964b04b: `sanitize` is skipped for a `null` value. `FormIslandTest.nullValueIsNotSanitizedAndFailsRequired` covers it. ########## wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java: ########## @@ -0,0 +1,254 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.wicket.islands; + +import java.io.Serializable; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; +import java.util.regex.Pattern; + +import org.apache.wicket.csp.ContentSecurityPolicySettings; +import org.apache.wicket.islands.serializer.IIslandSerializer; +import org.apache.wicket.markup.ComponentTag; +import org.apache.wicket.markup.head.IHeaderResponse; +import org.apache.wicket.markup.head.MetaDataHeaderItem; +import org.apache.wicket.markup.parser.XmlTag.TagType; +import org.apache.wicket.model.IModel; +import org.apache.wicket.protocol.http.WebApplication; +import org.apache.wicket.request.cycle.RequestCycle; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.util.io.IClusterable; +import org.apache.wicket.util.lang.Args; + +/** + * What every island has, whatever component it is: its type and key, its calls and the behavior + * receiving them, and the rendering of its host element. + */ +final class IslandSupport implements IClusterable +{ + private static final long serialVersionUID = 1L; + + private static final Pattern TYPE_PATTERN = Pattern.compile("[A-Za-z0-9_-]+"); + + private record Endpoint(Class<?> requestType, IslandCallHandler<Object, Object> handler) + implements IClusterable + { + } + + /** + * A page-less endpoint the island calls, with the context of its handle and the handle last + * issued for it. + */ + private static final class Pageless implements IClusterable + { + private static final long serialVersionUID = 1L; + + private final String endpointId; + + private final IModel<? extends Serializable> context; + + private Serializable issuedFor; + + private String handle; + + private Pageless(String endpointId, IModel<? extends Serializable> context) + { + this.endpointId = endpointId; + this.context = context; + } + + private String handle() + { + if (context == null) + { + return null; + } + Serializable current = Args.notNull(context.getObject(), "context"); + IIslandHandleStore store = IslandSettings.get().getHandleStore(); + if (handle == null || !current.equals(issuedFor) || + store.resolve(endpointId, handle) == null) + { + handle = store.issue(endpointId, current); + issuedFor = current; + } + return handle; + } + } + + private final String type; + + private final String key; + + private final Map<String, Endpoint> endpoints = new LinkedHashMap<>(); + + private final Map<String, Pageless> pageless = new LinkedHashMap<>(); + + private final IslandEndpointBehavior behavior = new IslandEndpointBehavior(); + + IslandSupport(String type) + { + Args.notNull(type, "type"); + if (!TYPE_PATTERN.matcher(type).matches()) + { + throw new IllegalArgumentException("Invalid island type '" + type + + "': use letters, digits, '-' and '_'"); + } + this.type = type; + key = Long.toString(ThreadLocalRandom.current().nextLong() & Long.MAX_VALUE, 36); Review Comment: Fixed in da6964b04b. The key now comes from the application's secure random supplier (12 bytes, url-base64). The repeater behavior is documented in the `Island` Javadoc, with `ReuseIfModelsEqualStrategy` as the way to keep islands. ########## wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java: ########## @@ -0,0 +1,253 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.wicket.islands; + +import java.io.Serializable; + +import org.apache.wicket.IGenericComponent; +import org.apache.wicket.markup.ComponentTag; +import org.apache.wicket.markup.MarkupStream; +import org.apache.wicket.markup.head.IHeaderResponse; +import org.apache.wicket.markup.html.WebComponent; +import org.apache.wicket.model.IModel; +import org.apache.wicket.util.lang.Args; + +/** + * A component whose body is rendered in the browser by a JavaScript framework component, its + * client-side peer. + * <p> + * The island renders an empty host element that names its type. The client-side runtime mounts + * the framework component registered for that type into it, and hands it the island's props: the + * object of the island's model, converted to JSON. Calls registered with {@code onCall} can be + * invoked by the peer; they run on the server in the context of this component, under the page + * lock, and travel as Wicket Ajax requests, so a handler can update other components through + * {@link IslandCall#getTarget()}. + * <p> + * <strong>The props are written into the page, where the user can read them.</strong> The model + * should hold an explicit projection made for the client, never a domain object with fields the + * user must not see. The JSON is escaped for the <code><script></code> element it is + * written into. + * <p> + * <strong>Call payloads come from the browser and are untrusted.</strong> A request type should + * contain only what the interaction may change; the handler validates it and applies it to the + * server-side state. + * + * @param <P> + * the type of the props + * @since 12.0.0 + */ +public class Island<P> extends WebComponent implements IGenericComponent<P, Island<P>> +{ + private static final long serialVersionUID = 1L; + + /** + * The attribute holding the island type. + */ + public static final String ATTR_TYPE = "data-wicket-island"; + + /** + * The attribute holding the island key, which identifies the island across re-renders. + */ + public static final String ATTR_KEY = "data-wicket-island-key"; + + /** + * The attribute marking the script element holding the island's state. + */ + public static final String ATTR_STATE = "data-wicket-island-state"; + + /** + * The attribute marking the element the client-side peer is mounted into. + */ + public static final String ATTR_ROOT = "data-wicket-island-root"; + + private final IslandSupport island; + + /** + * @param id + * the component id + * @param type + * the island type, naming the client-side module; letters, digits, '-' and '_' + * @param props + * the model of the props + */ + public Island(String id, String type, IModel<P> props) + { + super(id, props); + island = new IslandSupport(type); + setOutputMarkupId(true); + add(island.getBehavior()); Review Comment: Fixed in da6964b04b. An island without page-bound calls renders no Ajax attributes, and its endpoint behavior's stateless hint is `true`, so the page stays stateless (`IslandRenderTest.islandWithoutPageBoundCallsLeavesThePageStateless`). With a handle the session is still bound, as issuing one needs it. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
