papegaaij commented on code in PR #1834: URL: https://github.com/apache/wicket/pull/1834#discussion_r4523024089
########## 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); + } + } + + private attach(host: HTMLElement): void { + const key = host.getAttribute(ATTR_KEY); + const type = host.getAttribute(ATTR_TYPE); + if (!key || !type) { + return; + } + + const existing = this.mounted.get(key); + if (existing) { + if (existing.host !== host && !existing.host.isConnected) { + this.transfer(existing, host); + } + return; + } + + const module = this.modules.get(type); + if (!module) { + return; + } + + const island: MountedIsland = { + type, + key, + host, + root: findRoot(host), + state: readState(host), + abort: new AbortController() + }; + if (island.state.form) { + island.form = new HostFormBinding(() => island.host, () => island.state.form!); + } + this.mounted.set(key, island); + island.instance = module.mount(island.root, this.createContext(island)); + } + + /** + * Moves a mounted island into the host Wicket rendered in place of its old one. + */ + private transfer(island: MountedIsland, host: HTMLElement): void { + findRoot(host).replaceWith(island.root); Review Comment: Documented in da6964b04b, in the `Island` class Javadoc. ########## 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); + } + } + + private attach(host: HTMLElement): void { + const key = host.getAttribute(ATTR_KEY); + const type = host.getAttribute(ATTR_TYPE); + if (!key || !type) { + return; + } + + const existing = this.mounted.get(key); + if (existing) { + if (existing.host !== host && !existing.host.isConnected) { + this.transfer(existing, host); + } + return; + } + + const module = this.modules.get(type); + if (!module) { + return; + } + + const island: MountedIsland = { + type, + key, + host, + root: findRoot(host), + state: readState(host), + abort: new AbortController() + }; + if (island.state.form) { + island.form = new HostFormBinding(() => island.host, () => island.state.form!); + } + this.mounted.set(key, island); + island.instance = module.mount(island.root, this.createContext(island)); + } + + /** + * Moves a mounted island into the host Wicket rendered in place of its old one. + */ + private transfer(island: MountedIsland, host: HTMLElement): void { + findRoot(host).replaceWith(island.root); + island.host = host; + island.state = readState(host); + island.instance?.update(island.state.props); + island.form?.refresh(); + } + + private sweep(): void { + for (const island of [...this.mounted.values()]) { + if (!island.host.isConnected) { + this.unmount(island); + } + } + } + + private unmount(island: MountedIsland): void { + this.mounted.delete(island.key); + island.abort.abort(); + try { + island.instance?.unmount(); + } catch (e) { + console.error(`Wicket Islands: unmounting island ${island.type} failed`, e); + } + } + + private createContext(island: MountedIsland): IslandContext<unknown> { + return { + get props() { + return island.state.props; + }, + key: island.key, + signal: island.abort.signal, + form: island.form, + queryClient: this.queryClient, + store: name => this.stores.get(name), + call: <R>(name: string, payload?: unknown) => this.call(island, name, payload) as Promise<R> + }; + } + + private call(island: MountedIsland, name: string, payload: unknown): Promise<unknown> { + if (island.abort.signal.aborted) { + return Promise.reject(new IslandCallError('error', ['The island is no longer mounted.'])); + } + + const pageless = island.state.pageless?.[name]; + if (pageless) { + return this.callPageless(pageless, payload); Review Comment: Fixed in da6964b04b: the page-less `fetch` gets the island's signal, and an aborted call rejects with the same "no longer mounted" error as a page-bound one. Covered by a runtime test. ########## 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); + } + } + + private attach(host: HTMLElement): void { + const key = host.getAttribute(ATTR_KEY); + const type = host.getAttribute(ATTR_TYPE); + if (!key || !type) { + return; + } + + const existing = this.mounted.get(key); + if (existing) { + if (existing.host !== host && !existing.host.isConnected) { + this.transfer(existing, host); + } + return; + } + + const module = this.modules.get(type); + if (!module) { + return; + } + + const island: MountedIsland = { + type, + key, + host, + root: findRoot(host), + state: readState(host), + abort: new AbortController() + }; + if (island.state.form) { + island.form = new HostFormBinding(() => island.host, () => island.state.form!); + } + this.mounted.set(key, island); + island.instance = module.mount(island.root, this.createContext(island)); + } + + /** + * Moves a mounted island into the host Wicket rendered in place of its old one. + */ + private transfer(island: MountedIsland, host: HTMLElement): void { + findRoot(host).replaceWith(island.root); + island.host = host; + island.state = readState(host); + island.instance?.update(island.state.props); + island.form?.refresh(); + } + + private sweep(): void { + for (const island of [...this.mounted.values()]) { + if (!island.host.isConnected) { + this.unmount(island); + } + } + } + + private unmount(island: MountedIsland): void { + this.mounted.delete(island.key); + island.abort.abort(); + try { + island.instance?.unmount(); + } catch (e) { + console.error(`Wicket Islands: unmounting island ${island.type} failed`, e); + } + } + + private createContext(island: MountedIsland): IslandContext<unknown> { + return { + get props() { + return island.state.props; + }, + key: island.key, + signal: island.abort.signal, + form: island.form, + queryClient: this.queryClient, + store: name => this.stores.get(name), + call: <R>(name: string, payload?: unknown) => this.call(island, name, payload) as Promise<R> + }; + } + + private call(island: MountedIsland, name: string, payload: unknown): Promise<unknown> { + if (island.abort.signal.aborted) { + return Promise.reject(new IslandCallError('error', ['The island is no longer mounted.'])); + } + + const pageless = island.state.pageless?.[name]; + if (pageless) { + return this.callPageless(pageless, payload); + } + + const id = String(++this.callSequence); + const parameters: Record<string, string> = { + [PARAM_CALL]: name, + [PARAM_CALL_ID]: id, + [PARAM_KEY]: island.key + }; + if (payload !== undefined) { + parameters[PARAM_PAYLOAD] = JSON.stringify(payload); + } + + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject }); + const ajax = island.state.ajax; + this.api!.Ajax.ajax({ + ...ajax, + ep: parameters, + fh: [...(ajax.fh ?? []), () => this.fail(id, 'network', Review Comment: Fixed in da6964b04b. The failure handler now reads the status: 403 is `forbidden`, any other status is `error` ("The server answered N."), and no status means `network`. An answer that cannot be parsed is `error`. The precondition case is gone with `c` (see the comment on `renderState`). ########## 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 && Review Comment: Fixed in da6964b04b: queries retry only after a `network` failure, and page-bound queries don't refetch when the window regains focus. Page-less ones keep TanStack's default. ########## wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/modules/ViteManifestModuleLoader.java: ########## @@ -0,0 +1,156 @@ +/* + * 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.modules; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import org.apache.wicket.Application; +import org.apache.wicket.WicketRuntimeException; +import org.apache.wicket.markup.head.CssHeaderItem; +import org.apache.wicket.markup.head.IHeaderResponse; +import org.apache.wicket.markup.head.JavaScriptHeaderItem; +import org.apache.wicket.markup.head.JavaScriptReferenceType; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.request.resource.ResourceReference; +import org.apache.wicket.util.lang.Args; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Loads island modules from a Vite production build on the classpath. + * <p> + * The build's output directory is expected under a base path on the classpath, with Vite's + * manifest in it. Each island type is an input of the build whose name is the island type; its + * entry module and style sheets are rendered from the manifest, and served by an + * {@link IslandAssetResource} mounted under the given reference. + * + * @since 12.0.0 + */ +public class ViteManifestModuleLoader implements IIslandModuleLoader +{ + private static final Logger LOG = LoggerFactory.getLogger(ViteManifestModuleLoader.class); + + private final String basePath; + + private final String manifestFile; + + private final ResourceReference assets; + + private volatile ViteManifest manifest; + + private volatile boolean manifestMissing; + + /** + * @param basePath + * the classpath location of the build's output directory, ending in a slash + * @param manifestFile + * the manifest, relative to the base path + * @param assets + * the mounted reference of the {@link IslandAssetResource} serving the files; the + * path of a file is passed as its indexed parameters + */ + public ViteManifestModuleLoader(String basePath, String manifestFile, ResourceReference assets) + { + this.basePath = Args.notEmpty(basePath, "basePath"); + this.manifestFile = Args.notEmpty(manifestFile, "manifestFile"); + this.assets = Args.notNull(assets, "assets"); + } + + /** + * @return the classpath location of the build's output directory + */ + public String getBasePath() + { + return basePath; + } + + /** + * @return the manifest, {@code null} if there is no build on the classpath + */ + public ViteManifest getManifest() + { + if (manifest == null && !manifestMissing) Review Comment: Fixed in da6964b04b: in development mode the manifest is read again when its last-modified time changes. Deployment mode still reads it once. ########## 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) Review Comment: Fixed in da6964b04b: `usePageless` throws an `IllegalArgumentException` for an id that isn't registered. That surfaces when the island is set up, before it renders. ########## wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java: ########## @@ -0,0 +1,293 @@ +/* + * 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 org.apache.wicket.Application; +import org.apache.wicket.MetaDataKey; +import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; +import org.apache.wicket.islands.modules.IIslandModuleLoader; +import org.apache.wicket.islands.modules.IslandAssetResource; +import org.apache.wicket.islands.modules.ViteDevServerModuleLoader; +import org.apache.wicket.islands.modules.ViteManifestModuleLoader; +import org.apache.wicket.islands.serializer.IIslandSerializer; +import org.apache.wicket.islands.serializer.JacksonIslandSerializer; +import org.apache.wicket.protocol.http.WebApplication; +import org.apache.wicket.request.resource.IResource; +import org.apache.wicket.request.resource.ResourceReference; +import org.apache.wicket.util.lang.Args; + +/** + * Application-wide settings for islands. Install them once, in + * {@link WebApplication#init()}: + * + * <pre> + * IslandSettings.install(this).setDevServerUrl("http://localhost:5173"); + * </pre> + * + * @since 12.0.0 + */ +public class IslandSettings +{ + /** + * The default classpath location of the Vite build. + */ + public static final String DEFAULT_BASE_PATH = "META-INF/wicket-islands/"; + + /** + * The default location of the Vite manifest, relative to the base path. + */ + public static final String DEFAULT_MANIFEST_FILE = ".vite/manifest.json"; + + /** + * The path the built files are served under. + */ + public static final String MOUNT_PATH = "wicket-islands"; + + /** + * The path page-less endpoints are served under. + */ + public static final String ENDPOINT_PATH = "wicket-islands-call"; + + private static final MetaDataKey<IslandSettings> KEY = new MetaDataKey<>() + { + private static final long serialVersionUID = 1L; + }; + + private IIslandSerializer serializer = new JacksonIslandSerializer(); + + private String basePath = DEFAULT_BASE_PATH; + + private String manifestFile = DEFAULT_MANIFEST_FILE; + + private String devServerUrl; + + private IIslandModuleLoader moduleLoader; + + private volatile ViteManifestModuleLoader manifestModuleLoader; + + private ResourceReference assets; + + private ResourceReference endpoints; + + private final PagelessEndpoints pagelessEndpoints = new PagelessEndpoints(); + + private IIslandHandleStore handleStore = new SessionHandleStore(); + + /** + * Installs the settings in an application, mounts the resource serving the built files, + * registers the listener that answers island calls failing before they reach their island, and + * makes Ajax behaviors on a {@link FormIsland} send the hidden input holding its value. + * + * @param application + * the application + * @return the settings, for further configuration + */ + public static IslandSettings install(WebApplication application) Review Comment: Fixed in da6964b04b: a second `install` returns the settings already installed and registers nothing again. -- 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]
