papegaaij commented on code in PR #1834: URL: https://github.com/apache/wicket/pull/1834#discussion_r4523020330
########## wicket-experimental/wicket-islands/npm/packages/react/src/index.tsx: ########## @@ -0,0 +1,239 @@ +/* + * 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 { QueryClientProvider, useMutation, useQuery, type UseMutationOptions, + type UseMutationResult, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query'; +import { createContext, useContext, useSyncExternalStore, type ComponentType } from 'react'; +import { createRoot } from 'react-dom/client'; +import type { FormBinding, FormState, IslandCallError, IslandContext, + IslandModule } from 'wicket-islands'; + +export { IslandCallError, cspNonce } from 'wicket-islands'; +export type { FormState, IslandCallErrorKind } from 'wicket-islands'; + +interface PropsStore<P> { + get(): P; + set(props: P): void; + subscribe(listener: () => void): () => void; +} + +function createPropsStore<P>(initial: P): PropsStore<P> { + let current = initial; + const listeners = new Set<() => void>(); + return { + get: () => current, + set(props) { + current = props; + listeners.forEach(listener => listener()); + }, + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + } + }; +} + +interface Binding { + context: IslandContext<unknown>; + props: PropsStore<unknown>; +} + +const BindingContext = createContext<Binding | null>(null); + +/** + * Makes a React component the client-side peer of a Wicket island. The component receives the + * island's props as its own props, and is re-rendered in place, keeping its state, whenever the + * server sends new ones. + * + * ```tsx + * export default defineIsland(TreasureBoard); + * ``` + */ +export function defineIsland<P extends object>(Component: ComponentType<P>): IslandModule<P> { + function IslandView({ binding }: { binding: Binding }) { + const props = useSyncExternalStore(binding.props.subscribe, binding.props.get) as P; + return ( + <QueryClientProvider client={binding.context.queryClient}> + <BindingContext.Provider value={binding}> + <Component {...props} /> + </BindingContext.Provider> + </QueryClientProvider> + ); + } + + return { + mount(root, context) { + const binding: Binding = { + context: context as IslandContext<unknown>, + props: createPropsStore<unknown>(context.props) + }; + const reactRoot = createRoot(root); + reactRoot.render(<IslandView binding={binding} />); + return { + update: props => binding.props.set(props), + unmount: () => reactRoot.unmount() + }; + } + }; +} + +/** + * What a component inside an island can use. + */ +export interface UseIsland<P> { + /** + * The island's current props. + */ + props: P; + + /** + * The key identifying the island across re-renders. + */ + key: string; + + /** + * Aborted when the island is unmounted. + */ + signal: AbortSignal; + + /** + * Calls the island on the server. The promise settles after every update the response carries + * has been applied, so the props are current when it does. + */ + call<R = unknown>(name: string, payload?: unknown): Promise<R>; +} + +/** + * Reads and writes the page's client store of the given name. Every island on the page using the + * same name shares the value; it is not sent to the server unless a call includes it. + * + * ```tsx + * const [hover, setHover] = useStore<Cell | null>('treasure-hover'); + * ``` + */ +export function useStore<S>(name: string): [S | undefined, (value: S) => void] { + const binding = useContext(BindingContext); + if (!binding) { + throw new Error('useStore() can only be used inside a component passed to defineIsland().'); + } + const store = binding.context.store<S>(name); + const value = useSyncExternalStore(store.subscribe, store.get); + return [value, store.set]; +} + +/** + * Fetches data with a call of the island, cached in the page's query client under + * `[name, payload]`. When the server marks `name` as stale (`invalidate(name)`), every island + * showing it fetches it again. + * + * ```tsx + * const scores = useIslandQuery<Score[]>('scores', { size }); + * ``` + */ +export function useIslandQuery<R>(name: string, payload?: unknown, + options?: Omit<UseQueryOptions<R, IslandCallError>, 'queryKey' | 'queryFn'> +): UseQueryResult<R, IslandCallError> { + const { call } = useIsland(); + return useQuery<R, IslandCallError>({ + ...options, + queryKey: payload === undefined ? [name] : [name, payload], Review Comment: Fixed in da6964b04b. `useIslandQuery` now caches under `context.queryKey(name, payload)` = `[name, scope, payload]`. The scope is `island:<key>` for a page-bound call and `handle:<handle>` or `endpoint:<url>` for a page-less one, so page-less results are still shared where they cannot differ. `invalidate(name)` still matches by prefix. Covered by a React test with two islands using the same query name. ########## 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()); + } + + /** + * @return the island type + */ + public final String getType() + { + 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. + * + * @param <Q> + * the request type + * @param <R> + * the result type + * @param name + * the name the client calls + * @param requestType + * the request type, {@link Void} for a call without payload + * @param resultType + * the result type + * @param handler + * the handler + * @return {@code this} + */ + public final <Q, R> Island<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. + * + * @param <Q> + * the request type + * @param name + * the name the client calls + * @param requestType + * the request type, {@link Void} for a call without payload + * @param handler + * the handler + * @return {@code this} + */ + public final <Q> Island<P> onCall(String name, Class<Q> requestType, + IslandCallConsumer<Q> handler) + { + island.addEndpoint(name, requestType, Void.class, IslandSupport.withoutResult(handler)); + return this; + } + + /** + * 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 Island<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 Island<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 Island<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() Review Comment: Fixed in da6964b04b: `canCallListenerAfterExpiry()` returns `true` only while the active `ListenerRequestHandler` targets the island's endpoint behavior. Other behaviors are refused on a recreated page again. `FormIslandTest.ajaxBehaviorIsNotInvokedOnAPageRecreatedAfterExpiry` fails against the old override. ########## 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() Review Comment: Fixed in da6964b04b, same change as on `Island` (see there). ########## 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); + } + + String getType() + { + return type; + } + + String getKey() + { + return key; + } + + IslandEndpointBehavior getBehavior() + { + return behavior; + } + + @SuppressWarnings("unchecked") + <Q, R> void addEndpoint(String name, Class<Q> requestType, Class<R> resultType, + IslandCallHandler<Q, R> handler) + { + Args.notEmpty(name, "name"); + Args.notNull(requestType, "requestType"); + Args.notNull(resultType, "resultType"); + Args.notNull(handler, "handler"); + endpoints.put(name, new Endpoint(requestType, (IslandCallHandler<Object, Object>)handler)); + } + + void addPageless(String name, String endpointId, IModel<? extends Serializable> context) + { + Args.notEmpty(name, "name"); + Args.notEmpty(endpointId, "endpointId"); + pageless.put(name, new Pageless(endpointId, context)); + } + + static <Q> IslandCallHandler<Q, Void> withoutResult(IslandCallConsumer<Q> consumer) + { + Args.notNull(consumer, "handler"); + return (request, call) -> { + consumer.handle(request, call); + return null; + }; + } + + Object invoke(String name, String payload, IslandCall call) + { + Endpoint endpoint = endpoints.get(name); + if (endpoint == null) + { + throw new IslandCallRejectedException("Unknown call '" + name + "'."); + } + + Object request = null; + if (endpoint.requestType() != Void.class) + { + if (payload != null) + { + request = serializer().fromJson(payload, endpoint.requestType()); + } + if (request == null) + { + throw new IslandCallRejectedException("The call has no payload."); + } + } + return endpoint.handler().handle(request, call); + } + + void onComponentTag(ComponentTag tag) + { + if (tag.isOpenClose()) + { + tag.setType(TagType.OPEN); + } + tag.put(Island.ATTR_TYPE, type); + tag.put(Island.ATTR_KEY, key); + } + + /** + * @param props + * the props + * @param form + * the JSON of the form state, {@code null} for an island that is no form component + * @return the body of the host element after any markup of its own: the state and the root + */ + String renderState(Object props, String form) + { + IIslandSerializer serializer = serializer(); + String state = "{\"props\":" + serializer.toJson(props) + ",\"calls\":" + + serializer.toJson(endpoints.keySet()) + ",\"ajax\":" + behavior.renderAttributes() + Review Comment: Fixed in da6964b04b. The state now carries a fixed set of plain values, `u`, `m` and `ch`, rendered through the serializer. `IslandRenderTest.stateStaysJsonWhenTheApplicationAddsCallListenersToEveryBehavior` adds global listeners and a precondition. As a consequence, listeners added to every behavior don't apply to island calls; listeners subscribed through `Wicket.Event` still fire. Dropping `c` also removes the default precondition, so a call is no longer skipped silently. ########## wicket-experimental/wicket-islands/npm/packages/vite-plugin/src/index.js: ########## @@ -0,0 +1,132 @@ +/* + * 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 path from 'node:path'; + +const TYPE_PATTERN = /^[A-Za-z0-9_-]+$/; +const ENTRY_PREFIX = 'virtual:wicket-island:'; +const RESOLVED_ENTRY_PREFIX = '\0wicket-island:'; +const PREAMBLE_ID = 'virtual:wicket-islands-preamble'; +const RESOLVED_PREAMBLE_ID = '\0wicket-islands-preamble'; +const DEV_PATH = '/@wicket-islands/'; + +/** + * Builds the islands of a Wicket application, one entry per island type, and serves them to a + * Wicket application running in development mode. + * + * Each island type becomes an input of the build named after the type, so Wicket finds its + * entry in the manifest. Its entry module imports the island's module, turns its default export + * into an island with the adapter's `defineIsland` when an adapter is given, and registers it with + * the runtime. In development, the entry for a type is served at `/@wicket-islands/<type>`. + * + * @param {import('./index').WicketIslandsOptions} options + * @returns {import('vite').Plugin} + */ +export default function wicketIslands(options) { + const islands = options.islands; + for (const type of Object.keys(islands)) { + if (!TYPE_PATTERN.test(type)) { + throw new Error(`Invalid island type '${type}': use letters, digits, '-' and '_'.`); + } + } + + let root = process.cwd(); + let serving = false; + + return { + name: 'wicket-islands', + + config(_config, env) { Review Comment: Fixed in da6964b04b: the plugin sets `base: './'` for builds unless the application sets one, and leaves the dev server alone. A new build test with an imported asset, a CSS `url()` and a lazily imported chunk with CSS fails without the change. -- 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]
