This is an automated email from the ASF dual-hosted git repository. papegaaij pushed a commit to branch islands in repository https://gitbox.apache.org/repos/asf/wicket.git
commit 06357b3c4c95b367b5b658a6fecf2f846be25d66 Author: Emond Papegaaij <[email protected]> AuthorDate: Thu Nov 5 18:52:06 2026 +0100 Add the client store, form islands and page-less endpoints to Wicket Islands Islands could render props and receive page-bound calls, but could not share state with each other, take part in a Wicket form, or fetch data without the page lock. The client runtime keeps named client stores per page, shared by its islands without involving the server. FormIsland is a form component whose client-side peer edits its value: the value travels as JSON in a hidden input, is converted with the island serializer (JSON that does not fit the value type is a conversion error) and passes a sanitize hook, and the peer receives the form state, including the component's feedback messages; after an Ajax validation the island adds itself to the target. Ajax behaviors on a form island serialize the hidden input. Page-less endpoints are registered with the application together with a required authorization, made callable by an island with usePageless, and served outside the page lock to POST requests carrying the islands header from the same origin. The runtime keeps a TanStack Query client per page and applies the query keys the server invalidates, also from classic Ajax requests through IslandTargets; the React adapter adds useStore, useFormValue, useFormState, useIslandQuery and useIslandMutation. Island and FormIsland share their island support; IslandCall#getIsland() is replaced by getComponent(), as a call can come from either. Co-Authored-By: Claude Opus 5.5 <[email protected]> --- .../wicket-islands/npm/package-lock.json | 44 ++- .../wicket-islands/npm/package.json | 2 + .../wicket-islands/npm/packages/react/package.json | 1 + .../npm/packages/react/src/index.tsx | 118 ++++++- .../npm/packages/react/test/react.test.tsx | 129 +++++++- .../npm/packages/runtime/package.json | 3 + .../npm/packages/runtime/src/form.ts | 131 ++++++++ .../npm/packages/runtime/src/index.ts | 2 + .../npm/packages/runtime/src/runtime.ts | 84 ++++- .../npm/packages/runtime/src/store.ts | 74 +++++ .../npm/packages/runtime/src/types.ts | 24 +- .../npm/packages/runtime/test/runtime.test.ts | 138 ++++++++- .../npm/packages/runtime/test/wicket-fixture.ts | 24 +- .../wicket-islands/src/main/java/module-info.java | 1 + .../java/org/apache/wicket/islands/FormIsland.java | 345 +++++++++++++++++++++ .../wicket/islands/IPagelessAuthorization.java} | 31 +- .../apache/wicket/islands/IPagelessEndpoint.java} | 36 ++- .../java/org/apache/wicket/islands/Island.java | 125 +++----- .../org/apache/wicket/islands/IslandAnswer.java | 16 +- .../java/org/apache/wicket/islands/IslandCall.java | 13 +- .../wicket/islands/IslandEndpointBehavior.java | 19 +- .../org/apache/wicket/islands/IslandSettings.java | 53 +++- .../org/apache/wicket/islands/IslandSupport.java | 185 +++++++++++ .../org/apache/wicket/islands/IslandTargets.java | 48 +++ .../islands/{IslandCall.java => PagelessCall.java} | 55 ++-- .../wicket/islands/PagelessEndpointResource.java | 181 +++++++++++ .../apache/wicket/islands/PagelessEndpoints.java | 88 ++++++ .../org/apache/wicket/islands/FormIslandTest.java | 186 +++++++++++ .../apache/wicket/islands/FormIslandTestPage.html | 9 + .../apache/wicket/islands/FormIslandTestPage.java | 104 +++++++ .../org/apache/wicket/islands/IslandTestPage.html | 1 + .../org/apache/wicket/islands/IslandTestPage.java | 15 + .../wicket/islands/PagelessEndpointTest.java | 222 +++++++++++++ 33 files changed, 2333 insertions(+), 174 deletions(-) diff --git a/wicket-experimental/wicket-islands/npm/package-lock.json b/wicket-experimental/wicket-islands/npm/package-lock.json index 22a028156f..5944ee6d0e 100644 --- a/wicket-experimental/wicket-islands/npm/package-lock.json +++ b/wicket-experimental/wicket-islands/npm/package-lock.json @@ -11,6 +11,8 @@ "packages/vite-plugin" ], "devDependencies": { + "@tanstack/query-core": "^5.0.0", + "@tanstack/react-query": "^5.0.0", "@types/node": "^24.0.0", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", @@ -1029,6 +1031,38 @@ "dev": true, "license": "MIT" }, + "node_modules/@tanstack/query-core": { + "version": "5.106.1", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.106.1.tgz", + "integrity": "sha512-erYv/UACddcdgjOL2ixmFdK6tO/AVBeUcTCOtX2N51yZpDQ2U7KJ+xgB/bCNfsF3uoCDTqGHEEbDiFsIO9YUmQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.106.1", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.106.1.tgz", + "integrity": "sha512-ORDvJG/DSfmlFL9lQ8GDkE0VjtQbLeRDY7BL8xjKkQFGLfjFGfNWNuteWgPqA2gPJgLLuWfQ7IX0FlsHCJriyg==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.106.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@types/react": "^18 || ^19", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", @@ -1067,7 +1101,7 @@ "version": "19.3.0", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "csstype": "^3.2.2" @@ -1277,7 +1311,7 @@ "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/data-urls": { @@ -2197,6 +2231,7 @@ "version": "0.0.0", "license": "Apache-2.0", "peerDependencies": { + "@tanstack/react-query": "^5.0.0", "react": "^19.0.0", "react-dom": "^19.0.0", "wicket-islands": "0.0.0" @@ -2205,7 +2240,10 @@ "packages/runtime": { "name": "wicket-islands", "version": "0.0.0", - "license": "Apache-2.0" + "license": "Apache-2.0", + "peerDependencies": { + "@tanstack/query-core": "^5.0.0" + } }, "packages/vite-plugin": { "name": "vite-plugin-wicket-islands", diff --git a/wicket-experimental/wicket-islands/npm/package.json b/wicket-experimental/wicket-islands/npm/package.json index 72337d0871..f590153925 100644 --- a/wicket-experimental/wicket-islands/npm/package.json +++ b/wicket-experimental/wicket-islands/npm/package.json @@ -12,6 +12,8 @@ "test": "npm run typecheck && vitest run" }, "devDependencies": { + "@tanstack/query-core": "^5.0.0", + "@tanstack/react-query": "^5.0.0", "@types/node": "^24.0.0", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", diff --git a/wicket-experimental/wicket-islands/npm/packages/react/package.json b/wicket-experimental/wicket-islands/npm/packages/react/package.json index 93e4d37d6d..fead59be55 100644 --- a/wicket-experimental/wicket-islands/npm/packages/react/package.json +++ b/wicket-experimental/wicket-islands/npm/packages/react/package.json @@ -12,6 +12,7 @@ } }, "peerDependencies": { + "@tanstack/react-query": "^5.0.0", "react": "^19.0.0", "react-dom": "^19.0.0", "wicket-islands": "0.0.0" diff --git a/wicket-experimental/wicket-islands/npm/packages/react/src/index.tsx b/wicket-experimental/wicket-islands/npm/packages/react/src/index.tsx index 2e7ae45cc2..4de68ad115 100644 --- a/wicket-experimental/wicket-islands/npm/packages/react/src/index.tsx +++ b/wicket-experimental/wicket-islands/npm/packages/react/src/index.tsx @@ -15,12 +15,15 @@ * 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 { IslandContext, IslandModule } from 'wicket-islands'; +import type { FormBinding, FormState, IslandCallError, IslandContext, + IslandModule } from 'wicket-islands'; export { IslandCallError } from 'wicket-islands'; -export type { IslandCallErrorKind } from 'wicket-islands'; +export type { FormState, IslandCallErrorKind } from 'wicket-islands'; interface PropsStore<P> { get(): P; @@ -64,9 +67,11 @@ export function defineIsland<P extends object>(Component: ComponentType<P>): Isl function IslandView({ binding }: { binding: Binding }) { const props = useSyncExternalStore(binding.props.subscribe, binding.props.get) as P; return ( - <BindingContext.Provider value={binding}> - <Component {...props} /> - </BindingContext.Provider> + <QueryClientProvider client={binding.context.queryClient}> + <BindingContext.Provider value={binding}> + <Component {...props} /> + </BindingContext.Provider> + </QueryClientProvider> ); } @@ -112,6 +117,109 @@ export interface UseIsland<P> { 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], + queryFn: () => call<R>(name, payload) + }); +} + +/** + * Changes data with a call of the island, e.g. for optimistic updates with TanStack Query's + * mutation callbacks. + */ +export function useIslandMutation<Q, R = unknown>(name: string, + options?: Omit<UseMutationOptions<R, IslandCallError, Q>, 'mutationFn'> +): UseMutationResult<R, IslandCallError, Q> { + const { call } = useIsland(); + return useMutation<R, IslandCallError, Q>({ + ...options, + mutationFn: payload => call<R>(name, payload) + }); +} + +/** + * The value of a form island, and the function to change it. Changing it updates the hidden input + * Wicket submits with the form, and fires its input and change events. + * + * ```tsx + * const [player, setPlayer] = useFormValue<PlayerEntry>(); + * ``` + */ +export function useFormValue<T>(): [T | undefined, (value: T | undefined) => void] { + const form = formBinding('useFormValue'); + const value = useSyncExternalStore(form.subscribe, form.getValue) as T | undefined; + return [value, form.setValue as (value: T | undefined) => void]; +} + +/** + * What the server says about a form island: required, enabled, its label and its feedback + * messages, as of the last time Wicket rendered it. + */ +export function useFormState(): FormState { + const form = formBinding('useFormState'); + return useSyncExternalStore(form.subscribe, form.getState); +} + +function formBinding(hook: string): FormBinding<unknown> { + const binding = useContext(BindingContext); + if (!binding?.context.form) { + throw new Error(`${hook}() can only be used inside a form island.`); + } + return bound(binding.context.form); +} + +const boundBindings = new WeakMap<FormBinding<unknown>, FormBinding<unknown>>(); + +/** + * The binding with its methods bound, so they can be passed around; the same object every time, + * so hooks don't resubscribe on every render. + */ +function bound(form: FormBinding<unknown>): FormBinding<unknown> { + let result = boundBindings.get(form); + if (!result) { + result = { + getValue: () => form.getValue(), + setValue: value => form.setValue(value), + getState: () => form.getState(), + subscribe: listener => form.subscribe(listener) + }; + boundBindings.set(form, result); + } + return result; +} + /** * Gives a component anywhere inside an island access to it. */ diff --git a/wicket-experimental/wicket-islands/npm/packages/react/test/react.test.tsx b/wicket-experimental/wicket-islands/npm/packages/react/test/react.test.tsx index 682b573935..6aac8217eb 100644 --- a/wicket-experimental/wicket-islands/npm/packages/react/test/react.test.tsx +++ b/wicket-experimental/wicket-islands/npm/packages/react/test/react.test.tsx @@ -15,10 +15,12 @@ * limitations under the License. */ +import { QueryClient } from '@tanstack/react-query'; import { act, useState } from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { IslandContext, IslandInstance } from 'wicket-islands'; -import { defineIsland, useIsland } from '../src/index'; +import { IslandRuntime, type IslandContext, type IslandInstance } from 'wicket-islands'; +import { defineIsland, useFormState, useFormValue, useIsland, useIslandQuery, + useStore } from '../src/index'; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -38,20 +40,51 @@ function Counter({ title }: Props) { ); } +function Hover({ title }: Props) { + const [hover, setHover] = useStore<string>('hover'); + return <button id={`hover-${title}`} onClick={() => setHover(title)}>{hover ?? 'none'}</button>; +} + +function Scores({ title }: Props) { + const scores = useIslandQuery<string[]>('scores', { size: title }); + return <ol id="scores">{scores.data?.map(score => <li key={score}>{score}</li>)}</ol>; +} + +function Name() { + const [name, setName] = useFormValue<string>(); + const { errors } = useFormState(); + return ( + <div> + <input id="name" value={name ?? ''} onChange={event => setName(event.target.value)} /> + <span id="errors">{errors.join(', ')}</span> + </div> + ); +} + describe('defineIsland', () => { let root: HTMLElement; let context: IslandContext<Props>; let instance: IslandInstance<Props>; + let stores: IslandRuntime['stores']; + let queryClient: QueryClient; - beforeEach(() => { - root = document.createElement('div'); - document.body.appendChild(root); - context = { - props: { title: 'first' }, - key: 'k1', + function contextFor(props: Props): IslandContext<Props> { + return { + props, + key: props.title, signal: new AbortController().signal, + store: name => stores.get(name), + queryClient, call: vi.fn(() => Promise.resolve(undefined)) as IslandContext<Props>['call'] }; + } + + beforeEach(() => { + root = document.createElement('div'); + document.body.appendChild(root); + stores = new IslandRuntime().stores; + queryClient = new QueryClient(); + context = contextFor({ title: 'first' }); act(() => { instance = defineIsland(Counter).mount(root, context); }); @@ -88,6 +121,86 @@ describe('defineIsland', () => { expect(context.call).toHaveBeenCalledWith('save', { count: 1 }); }); + it('shares a store between islands', () => { + const [rootA, rootB] = [document.createElement('div'), document.createElement('div')]; + document.body.append(rootA, rootB); + act(() => { + defineIsland(Hover).mount(rootA, contextFor({ title: 'a' })); + defineIsland(Hover).mount(rootB, contextFor({ title: 'b' })); + }); + + act(() => { + rootA.querySelector<HTMLButtonElement>('#hover-a')!.click(); + }); + + expect(rootB.querySelector('#hover-b')?.textContent).toBe('a'); + rootA.remove(); + rootB.remove(); + }); + + it('edits the value of a form island', () => { + let value: unknown = 'Ann'; + let state = { required: true, enabled: true, label: 'Name', errors: ['Too short'] }; + const listeners = new Set<() => void>(); + const formRoot = document.createElement('div'); + document.body.appendChild(formRoot); + act(() => { + defineIsland(Name).mount(formRoot, { + ...contextFor({ title: 'f' }), + form: { + getValue: () => value, + setValue: next => { + value = next; + state = { ...state, errors: [] }; + listeners.forEach(listener => listener()); + }, + getState: () => state, + subscribe: listener => { + listeners.add(listener); + return () => listeners.delete(listener); + } + } + }); + }); + expect(formRoot.querySelector('#errors')?.textContent).toBe('Too short'); + + act(() => { + const input = formRoot.querySelector<HTMLInputElement>('#name')!; + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!; + setter.call(input, 'Annabel'); + input.dispatchEvent(new Event('input', { bubbles: true })); + }); + + expect(value).toBe('Annabel'); + expect(formRoot.querySelector<HTMLInputElement>('#name')!.value).toBe('Annabel'); + expect(formRoot.querySelector('#errors')?.textContent).toBe(''); + formRoot.remove(); + }); + + it('queries with island calls and refetches when the key is invalidated', async () => { + let round = 0; + const call = vi.fn(() => Promise.resolve([`score ${++round}`])); + const scoresRoot = document.createElement('div'); + document.body.appendChild(scoresRoot); + await act(async () => { + defineIsland(Scores).mount(scoresRoot, { + ...contextFor({ title: 'SMALL' }), + call: call as IslandContext<Props>['call'] + }); + }); + expect(call).toHaveBeenCalledWith('scores', { size: 'SMALL' }); + await act(() => vi.waitFor(() => + expect(scoresRoot.querySelector('#scores')?.textContent).toBe('score 1'))); + + await act(async () => { + await queryClient.invalidateQueries({ queryKey: ['scores'] }); + }); + + await act(() => vi.waitFor(() => + expect(scoresRoot.querySelector('#scores')?.textContent).toBe('score 2'))); + scoresRoot.remove(); + }); + it('unmounts the React root', () => { act(() => instance.unmount()); diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/package.json b/wicket-experimental/wicket-islands/npm/packages/runtime/package.json index d5594b3452..1c90b3571d 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/package.json +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/package.json @@ -6,5 +6,8 @@ "type": "module", "exports": { ".": "./src/index.ts" + }, + "peerDependencies": { + "@tanstack/query-core": "^5.0.0" } } diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/src/form.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/src/form.ts new file mode 100644 index 0000000000..0d42568ab8 --- /dev/null +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/form.ts @@ -0,0 +1,131 @@ +/* + * 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. + */ + +const SELECTOR_VALUE = ':scope > input[data-wicket-island-value]'; + +/** + * What the server says about a form island. + */ +export interface FormState { + readonly required: boolean; + readonly enabled: boolean; + readonly label: string | null; + + /** + * The feedback messages of the form island, e.g. validation errors. + */ + readonly errors: readonly string[]; +} + +/** + * The value of a form island, kept in the hidden input Wicket submits with the form. + */ +export interface FormBinding<T> { + /** + * The current value; the same object until it changes, as framework stores require. + */ + getValue(): T | undefined; + + /** + * Writes the value into the hidden input and fires its input and change events, so Wicket + * Ajax behaviors on the form island react as they would to any other form component. + */ + setValue(value: T | undefined): void; + + /** + * The current state; the same object until it changes. + */ + getState(): FormState; + + /** + * Notifies the listener of every change of the value or the state. + */ + subscribe(listener: () => void): () => void; +} + +/** + * The binding of a mounted form island. Its host can change when Wicket re-renders the island; + * {@link refresh} reads the value and state from the current host. + */ +export class HostFormBinding implements FormBinding<unknown> { + private value: unknown; + + private state: FormState; + + private readonly listeners = new Set<() => void>(); + + constructor(private readonly host: () => HTMLElement, state: () => FormState) { + this.readState = state; + this.state = state(); + this.value = parse(this.input().value); + } + + private readonly readState: () => FormState; + + getValue(): unknown { + return this.value; + } + + setValue(value: unknown): void { + const input = this.input(); + input.value = value === undefined ? '' : JSON.stringify(value); + this.value = value; + this.notify(); + input.dispatchEvent(new Event('input', { bubbles: true })); + input.dispatchEvent(new Event('change', { bubbles: true })); + } + + getState(): FormState { + return this.state; + } + + subscribe(listener: () => void): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + + refresh(): void { + this.value = parse(this.input().value); + this.state = this.readState(); + this.notify(); + } + + private input(): HTMLInputElement { + const input = this.host().querySelector<HTMLInputElement>(SELECTOR_VALUE); + if (!input) { + throw new Error(`Wicket Islands: form island ${this.host().id} has no value input.`); + } + return input; + } + + private notify(): void { + for (const listener of [...this.listeners]) { + listener(); + } + } +} + +function parse(json: string): unknown { + if (json === '') { + return undefined; + } + try { + return JSON.parse(json) as unknown; + } catch { + return undefined; + } +} diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts index f998422e16..9ae49eb723 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/index.ts @@ -19,6 +19,8 @@ import { IslandRuntime } from './runtime'; import type { IslandModule } from './types'; export { IslandRuntime } from './runtime'; +export type { FormBinding, FormState } from './form'; +export type { ClientStore } from './store'; export { IslandCallError } from './types'; export type { IslandCallErrorKind, IslandContext, IslandInstance, IslandModule } from './types'; diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts index 6f58bf235b..b8c0074aa5 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/runtime.ts @@ -17,6 +17,9 @@ 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'; @@ -30,11 +33,14 @@ 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'; interface IslandState { props: unknown; calls: string[]; ajax: WicketAjaxAttributes; + pageless?: Record<string, string>; + form?: FormState; } interface MountedIsland { @@ -44,6 +50,7 @@ interface MountedIsland { readonly abort: AbortController; host: HTMLElement; state: IslandState; + form?: HostFormBinding; instance?: IslandInstance<unknown>; } @@ -73,6 +80,25 @@ export class IslandRuntime { 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; @@ -147,6 +173,9 @@ export class IslandRuntime { 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)); } @@ -159,6 +188,7 @@ export class IslandRuntime { island.host = host; island.state = readState(host); island.instance?.update(island.state.props); + island.form?.refresh(); } private sweep(): void { @@ -186,6 +216,9 @@ export class IslandRuntime { }, 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> }; } @@ -195,6 +228,11 @@ export class IslandRuntime { 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, @@ -219,6 +257,45 @@ export class IslandRuntime { }); } + private async callPageless(url: string, payload: unknown): Promise<unknown> { + let response: Response; + try { + response = await fetch(url, { + method: 'POST', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json', [PAGELESS_HEADER]: '1' }, + body: payload === undefined ? '' : JSON.stringify(payload) + }); + } catch { + throw new IslandCallError('network', ['The call did not complete.']); + } + if (!response.ok) { + throw response.status === 403 + ? new IslandCallError('forbidden', ['The call is not allowed.']) + : new IslandCallError('error', [`The server answered ${response.status}.`]); + } + + let envelope: Envelope; + try { + envelope = await response.json() as Envelope; + } catch { + throw new IslandCallError('error', ['The server did not answer the call.']); + } + this.invalidate(envelope); + if (!envelope.ok) { + throw new IslandCallError(envelope.error?.kind ?? 'error', envelope.error?.messages ?? []); + } + return envelope.value; + } + + private invalidate(envelope: Envelope): void { + if (envelope.invalidate && envelope.invalidate.length > 0) { + for (const listener of this.invalidationListeners) { + listener(envelope.invalidate); + } + } + } + private receive(value: string): void { let envelope: Envelope; try { @@ -229,12 +306,7 @@ export class IslandRuntime { } this.sweep(); - - if (envelope.invalidate && envelope.invalidate.length > 0) { - for (const listener of this.invalidationListeners) { - listener(envelope.invalidate); - } - } + this.invalidate(envelope); if (envelope.call === undefined) { return; diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/src/store.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/src/store.ts new file mode 100644 index 0000000000..1ed52beab6 --- /dev/null +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/store.ts @@ -0,0 +1,74 @@ +/* + * 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. + */ + +/** + * A named value shared by the islands of a page, without a round trip to the server. + */ +export interface ClientStore<S> { + /** + * The current value, `undefined` until one is set. + */ + get(): S | undefined; + + /** + * Sets the value and notifies the subscribers when it changed. + */ + set(value: S): void; + + /** + * Notifies the listener of every change; returns the function that stops it. + */ + subscribe(listener: () => void): () => void; +} + +/** + * The stores of a page, by name. A store lives as long as the page in the browser, so it outlasts + * the islands that use it. + */ +export class ClientStores { + private readonly stores = new Map<string, ClientStore<unknown>>(); + + get<S>(name: string): ClientStore<S> { + let store = this.stores.get(name); + if (!store) { + store = createStore<unknown>(); + this.stores.set(name, store); + } + return store as ClientStore<S>; + } +} + +function createStore<S>(): ClientStore<S> { + let value: S | undefined; + const listeners = new Set<() => void>(); + return { + get: () => value, + set(next) { + if (Object.is(value, next)) { + return; + } + value = next; + for (const listener of [...listeners]) { + listener(); + } + }, + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + } + }; +} diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/src/types.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/src/types.ts index d943023f37..69b6c6b0e0 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/src/types.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/src/types.ts @@ -15,6 +15,10 @@ * limitations under the License. */ +import type { QueryClient } from '@tanstack/query-core'; +import type { FormBinding } from './form'; +import type { ClientStore } from './store'; + /** * The client-side half of an island: what a framework adapter provides for an island type. */ @@ -59,9 +63,27 @@ export interface IslandContext<P> { */ readonly signal: AbortSignal; + /** + * The value and form state of a form island; absent for other islands. + */ + readonly form?: FormBinding<unknown>; + + /** + * The query client of the page, shared by every island on the page. Query keys the server marks + * as stale are invalidated in it. + */ + readonly queryClient: QueryClient; + + /** + * The page's client store of the given name, shared by every island on the page. + */ + store<S>(name: string): ClientStore<S>; + /** * Calls the island on the server. The returned promise settles after every update the - * response carries has been applied: components, props of other islands, invalidations. + * response carries has been applied: components, props of other islands, invalidations. A + * name the island registered as page-less is called with a plain request instead, outside + * the page lock; its answer carries invalidations but no component updates. */ call<R = unknown>(name: string, payload?: unknown): Promise<R>; } diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts index 25510ee93e..aad47897bc 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/test/runtime.test.ts @@ -15,9 +15,9 @@ * limitations under the License. */ -import { beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { IslandCallError, IslandRuntime, type IslandContext, type IslandModule } from '../src/index'; -import { component, data, failRequest, host, requests, respond, setUpWicket } from './wicket-fixture'; +import { component, data, failRequest, formHost, host, requests, respond, setUpWicket } from './wicket-fixture'; interface Props { label: string; @@ -242,6 +242,140 @@ describe('IslandRuntime', () => { expect(charts.mounts).toHaveLength(1); }); + it('shares client stores between the islands of a page, beyond their lifetime', () => { + document.body.innerHTML += host('board2', 'board', 'k2', { label: 'two' }); + runtime.register('board', recorder.module()); + const [first, second] = recorder.mounts.map(mount => mount.context); + const seen: unknown[] = []; + second.store<string>('hover').subscribe(() => seen.push(second.store('hover').get())); + + first.store<string>('hover').set('cell'); + first.store<string>('hover').set('cell'); + + expect(second.store('hover').get()).toBe('cell'); + expect(seen).toEqual(['cell']); + + ignore(first.call('probe', {})); + respond(requests[0], component('panel', '<div id="panel"></div>')); + expect(recorder.unmounts).toBe(1); + expect(runtime.stores.get('hover').get()).toBe('cell'); + }); + + it('binds the value and state of a form island to its hidden input', () => { + document.body.innerHTML = `<form id="form"><div id="panel">${formHost('point1', 'board', 'k5', + { x: 1 }, { required: true, enabled: true, label: 'Point', errors: [] })}</div></form>`; + runtime.register('board', recorder.module()); + const form = recorder.context.form!; + const events: string[] = []; + document.getElementById('form')!.addEventListener('change', () => events.push('change')); + document.getElementById('form')!.addEventListener('input', () => events.push('input')); + + expect(form.getValue()).toEqual({ x: 1 }); + expect(form.getState().label).toBe('Point'); + + form.setValue({ x: 2 }); + + expect(document.querySelector<HTMLInputElement>('input[data-wicket-island-value]')!.value) + .toBe('{"x":2}'); + expect(form.getValue()).toEqual({ x: 2 }); + expect(events).toEqual(['input', 'change']); + }); + + it('reads the value and state of a re-rendered form island from its new host', () => { + document.body.innerHTML = `<div id="panel">${formHost('point1', 'board', 'k5', + { x: 1 }, { required: true, enabled: true, label: 'Point', errors: [] })}</div>`; + runtime.register('board', recorder.module()); + const form = recorder.context.form!; + let notified = 0; + form.subscribe(() => notified++); + ignore(recorder.context.call('probe', {})); + + respond(requests[0], component('panel', `<div id="panel">${formHost('point1', 'board', 'k5', + { x: 9 }, { required: true, enabled: true, label: 'Point', errors: ['Too far'] })}</div>`)); + + expect(recorder.mounts).toHaveLength(1); + expect(form.getValue()).toEqual({ x: 9 }); + expect(form.getState().errors).toEqual(['Too far']); + expect(notified).toBe(1); + }); + + it('gives islands that are no form components no form binding', () => { + runtime.register('board', recorder.module()); + + expect(recorder.context.form).toBeUndefined(); + }); + + describe('page-less calls', () => { + let fetched: { url: string; init: RequestInit }[]; + + function answer(status: number, body: unknown) { + fetched = []; + vi.stubGlobal('fetch', (url: string, init: RequestInit) => { + fetched.push({ url, init }); + return Promise.resolve(new Response(JSON.stringify(body), { status })); + }); + } + + beforeEach(() => { + document.body.innerHTML = `<div id="panel">${host('board1', 'board', 'k1', { label: 'one' }, + './call?board1', { scores: './wicket-islands-call/scores' })}</div>`; + runtime.register('board', recorder.module()); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it('posts the payload as JSON with the islands header, outside Wicket Ajax', async () => { + answer(200, { ok: true, value: [1, 2], invalidate: [] }); + + await expect(recorder.context.call('scores', { size: 'SMALL' })).resolves.toEqual([1, 2]); + + expect(requests).toHaveLength(0); + expect(fetched[0].url).toBe('./wicket-islands-call/scores'); + expect(fetched[0].init.method).toBe('POST'); + expect(fetched[0].init.body).toBe('{"size":"SMALL"}'); + expect((fetched[0].init.headers as Record<string, string>)['X-Wicket-Islands']).toBe('1'); + }); + + it('rejects a failed page-less call', async () => { + answer(200, { ok: false, error: { kind: 'invalid', messages: ['no'] }, invalidate: [] }); + + await expect(recorder.context.call('scores')).rejects.toMatchObject({ + kind: 'invalid', messages: ['no'] + }); + }); + + it('rejects a refused page-less call as forbidden', async () => { + answer(403, {}); + + await expect(recorder.context.call('scores')).rejects.toMatchObject({ kind: 'forbidden' }); + }); + + it('applies the invalidations of a page-less answer', async () => { + answer(200, { ok: true, value: null, invalidate: ['scores'] }); + const invalidated: string[][] = []; + runtime.onInvalidate(keys => invalidated.push([...keys])); + + await recorder.context.call('scores'); + + expect(invalidated).toEqual([['scores']]); + }); + }); + + it('invalidates the queries of the page under the keys the server names', () => { + runtime.register('board', recorder.module()); + const queries = runtime.queryClient.getQueryCache(); + runtime.queryClient.setQueryData(['scores', { size: 'SMALL' }], [1]); + runtime.queryClient.setQueryData(['other'], [2]); + ignore(recorder.context.call('probe', {})); + + respond(requests[0], data({ invalidate: ['scores'] })); + + expect(queries.find({ queryKey: ['scores', { size: 'SMALL' }] })?.state.isInvalidated).toBe(true); + expect(queries.find({ queryKey: ['other'] })?.state.isInvalidated).toBe(false); + }); + it('tells listeners which query keys were invalidated', () => { runtime.register('board', recorder.module()); const invalidated: string[][] = []; diff --git a/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts b/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts index 4d63d2dec9..1a2ddc08d7 100644 --- a/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts +++ b/wicket-experimental/wicket-islands/npm/packages/runtime/test/wicket-fixture.ts @@ -93,13 +93,29 @@ export function data(value: unknown): string { /** * The markup of an island host, as Island renders it. */ -export function host(id: string, type: string, key: string, props: unknown, url = `./call?${id}`): string { - const state = JSON.stringify({ - props, +export function host(id: string, type: string, key: string, props: unknown, url = `./call?${id}`, + pageless?: Record<string, string>): string { + return hostWith(id, type, key, { props, pageless }, '', url); +} + +/** + * The markup of a form island host, as FormIsland renders it. + */ +export function formHost(id: string, type: string, key: string, value: unknown, + form: { required: boolean; enabled: boolean; label: string | null; errors: string[] }): string { + const input = `<input type="hidden" data-wicket-island-value name="${id}" ` + + `value="${value === undefined ? '' : JSON.stringify(value).replace(/"/g, '"')}">`; + return hostWith(id, type, key, { props: { label: 'form' }, form }, input, `./call?${id}`); +} + +function hostWith(id: string, type: string, key: string, state: object, before: string, + url: string): string { + const json = JSON.stringify({ + ...state, calls: ['probe'], ajax: { u: url, m: 'POST', c: id, ch: `wicket-island-${id}|s` } }).replace(/</g, '\\u003c'); return `<div id="${id}" data-wicket-island="${type}" data-wicket-island-key="${key}">` + - `<script type="application/json" data-wicket-island-state>${state}</script>` + + before + `<script type="application/json" data-wicket-island-state>${json}</script>` + '<div data-wicket-island-root></div></div>'; } diff --git a/wicket-experimental/wicket-islands/src/main/java/module-info.java b/wicket-experimental/wicket-islands/src/main/java/module-info.java index 1157b6e8a2..98233b4083 100644 --- a/wicket-experimental/wicket-islands/src/main/java/module-info.java +++ b/wicket-experimental/wicket-islands/src/main/java/module-info.java @@ -15,6 +15,7 @@ * limitations under the License. */ module org.apache.wicket.islands { + requires static jakarta.servlet; requires org.slf4j; requires tools.jackson.databind; requires org.apache.wicket.util; diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/FormIsland.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/FormIsland.java new file mode 100644 index 0000000000..e2330b9fea --- /dev/null +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/FormIsland.java @@ -0,0 +1,345 @@ +/* + * 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.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); + 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() + { + if (updateOnValidation) + { + RequestCycle.get().find(AjaxRequestTarget.class).ifPresent(target -> target.add(this)); + } + } + + @Override + public void renderHead(IHeaderResponse response) + { + super.renderHead(response); + + island.renderHead(response); + } + + @Override + protected void onDetach() + { + if (props != null) + { + props.detach(); + } + super.onDetach(); + } +} diff --git a/wicket-experimental/wicket-islands/src/main/java/module-info.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IPagelessAuthorization.java similarity index 57% copy from wicket-experimental/wicket-islands/src/main/java/module-info.java copy to wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IPagelessAuthorization.java index 1157b6e8a2..a7e1f5710a 100644 --- a/wicket-experimental/wicket-islands/src/main/java/module-info.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IPagelessAuthorization.java @@ -14,16 +14,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -module org.apache.wicket.islands { - requires org.slf4j; - requires tools.jackson.databind; - requires org.apache.wicket.util; - requires org.apache.wicket.request; - requires org.apache.wicket.core; +package org.apache.wicket.islands; - exports org.apache.wicket.islands; - exports org.apache.wicket.islands.modules; - exports org.apache.wicket.islands.serializer; +/** + * Decides whether a page-less call may run. Every page-less endpoint is registered with one; there + * is no default that silently allows everything. + * + * @since 12.0.0 + */ +@FunctionalInterface +public interface IPagelessAuthorization +{ + /** + * Allows every call. Use it for endpoints serving public data, so that the decision is visible + * where the endpoint is registered. + */ + IPagelessAuthorization PERMIT_ALL = call -> true; - opens org.apache.wicket.islands.modules to tools.jackson.databind; + /** + * @param call + * the call + * @return whether the call may run + */ + boolean isAllowed(PagelessCall call); } diff --git a/wicket-experimental/wicket-islands/src/main/java/module-info.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IPagelessEndpoint.java similarity index 51% copy from wicket-experimental/wicket-islands/src/main/java/module-info.java copy to wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IPagelessEndpoint.java index 1157b6e8a2..7e55c1bedc 100644 --- a/wicket-experimental/wicket-islands/src/main/java/module-info.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IPagelessEndpoint.java @@ -14,16 +14,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -module org.apache.wicket.islands { - requires org.slf4j; - requires tools.jackson.databind; - requires org.apache.wicket.util; - requires org.apache.wicket.request; - requires org.apache.wicket.core; +package org.apache.wicket.islands; - exports org.apache.wicket.islands; - exports org.apache.wicket.islands.modules; - exports org.apache.wicket.islands.serializer; - - opens org.apache.wicket.islands.modules to tools.jackson.databind; +/** + * Handles the calls of a page-less endpoint. An endpoint is registered once with the application + * and serves every session, so it must be thread-safe and must not hold on to pages or + * components. + * + * @param <Q> + * the request type + * @param <R> + * the result type + * @see PagelessEndpoints + * @since 12.0.0 + */ +@FunctionalInterface +public interface IPagelessEndpoint<Q, R> +{ + /** + * @param request + * the request, deserialized from untrusted client input; {@code null} for an + * endpoint registered with request type {@link Void} + * @param call + * the call's context + * @return the result for the client + */ + R handle(Q request, PagelessCall call); } diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java index 537b1ebbd3..659fb75360 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/Island.java @@ -16,21 +16,12 @@ */ package org.apache.wicket.islands; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.concurrent.ThreadLocalRandom; -import java.util.regex.Pattern; - import org.apache.wicket.IGenericComponent; -import org.apache.wicket.islands.serializer.IIslandSerializer; 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.markup.parser.XmlTag.TagType; import org.apache.wicket.model.IModel; -import org.apache.wicket.util.io.IClusterable; -import org.apache.wicket.util.lang.Args; /** * A component whose body is rendered in the browser by a JavaScript framework component, its @@ -80,20 +71,7 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla */ public static final String ATTR_ROOT = "data-wicket-island-root"; - private static final Pattern TYPE_PATTERN = Pattern.compile("[A-Za-z0-9_-]+"); - - private record Endpoint(Class<?> requestType, IslandCallHandler<Object, Object> handler) - implements IClusterable - { - } - - private final String type; - - private final String key; - - private final Map<String, Endpoint> endpoints = new LinkedHashMap<>(); - - private final IslandEndpointBehavior endpointBehavior; + private final IslandSupport island; /** * @param id @@ -106,17 +84,9 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla public Island(String id, String type, IModel<P> props) { super(id, props); - 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); + island = new IslandSupport(type); setOutputMarkupId(true); - endpointBehavior = new IslandEndpointBehavior(); - add(endpointBehavior); + add(island.getBehavior()); } /** @@ -124,7 +94,7 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla */ public final String getType() { - return type; + return island.getType(); } /** @@ -132,7 +102,12 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla */ public final String getKey() { - return key; + return island.getKey(); + } + + final IslandSupport getIslandSupport() + { + return island; } /** @@ -152,15 +127,10 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla * the handler * @return {@code this} */ - @SuppressWarnings("unchecked") public final <Q, R> Island<P> onCall(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)); + island.addEndpoint(name, requestType, resultType, handler); return this; } @@ -180,34 +150,36 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla public final <Q> Island<P> onCall(String name, Class<Q> requestType, IslandCallConsumer<Q> handler) { - Args.notNull(handler, "handler"); - return onCall(name, requestType, Void.class, (request, call) -> { - handler.handle(request, call); - return null; - }); + island.addEndpoint(name, requestType, Void.class, IslandSupport.withoutResult(handler)); + return this; } - Object invoke(String name, String payload, IslandCall call) + /** + * 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) { - Endpoint endpoint = endpoints.get(name); - if (endpoint == null) - { - throw new IslandCallRejectedException("Unknown call '" + name + "'."); - } + return usePageless(endpointId, endpointId); + } - Object request = null; - if (endpoint.requestType() != Void.class) - { - if (payload != null) - { - request = getSerializer().fromJson(payload, endpoint.requestType()); - } - if (request == null) - { - throw new IslandCallRejectedException("The call has no payload."); - } - } - return endpoint.handler().handle(request, call); + /** + * 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); + return this; } /** @@ -225,25 +197,13 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla { super.onComponentTag(tag); - if (tag.isOpenClose()) - { - tag.setType(TagType.OPEN); - } - tag.put(ATTR_TYPE, type); - tag.put(ATTR_KEY, key); + island.onComponentTag(tag); } @Override public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) { - IIslandSerializer serializer = getSerializer(); - String state = "{\"props\":" + serializer.toJson(getModelObject()) + ",\"calls\":" + - serializer.toJson(endpoints.keySet()) + ",\"ajax\":" + - endpointBehavior.renderAttributes() + "}"; - - replaceComponentTagBody(markupStream, openTag, - "<script type=\"application/json\" " + ATTR_STATE + ">" + - IslandJson.escapeForScript(state) + "</script><div " + ATTR_ROOT + "></div>"); + replaceComponentTagBody(markupStream, openTag, island.renderState(getModelObject(), null)); } @Override @@ -251,11 +211,6 @@ public class Island<P> extends WebComponent implements IGenericComponent<P, Isla { super.renderHead(response); - IslandSettings.get().getModuleLoader().renderHead(type, response); - } - - private IIslandSerializer getSerializer() - { - return IslandSettings.get().getSerializer(); + island.renderHead(response); } } diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandAnswer.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandAnswer.java index bfba9e9e70..1d335ade09 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandAnswer.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandAnswer.java @@ -33,6 +33,10 @@ final class IslandAnswer { } + /** + * @param callId + * the id of the call, {@code null} for a page-less call, which is answered directly + */ static String success(IIslandSerializer serializer, String callId, Object value, List<String> invalidations) { @@ -49,10 +53,18 @@ final class IslandAnswer invalidations); } + /** + * @return an answer that only carries invalidations, for requests that are no island call + */ + static String invalidations(IIslandSerializer serializer, List<String> invalidations) + { + return "{\"invalidate\":" + serializer.toJson(invalidations) + "}"; + } + private static String answer(IIslandSerializer serializer, String callId, String outcome, List<String> invalidations) { - return "{\"call\":" + serializer.toJson(callId) + "," + outcome + ",\"invalidate\":" + - serializer.toJson(invalidations) + "}"; + String call = callId == null ? "" : "\"call\":" + serializer.toJson(callId) + ","; + return "{" + call + outcome + ",\"invalidate\":" + serializer.toJson(invalidations) + "}"; } } diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCall.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCall.java index 907ff9d7c2..c16d859a34 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCall.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCall.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; /** @@ -29,24 +30,24 @@ import org.apache.wicket.ajax.AjaxRequestTarget; */ public final class IslandCall { - private final Island<?> island; + private final Component component; private final AjaxRequestTarget target; private final List<String> invalidations = new ArrayList<>(); - IslandCall(Island<?> island, AjaxRequestTarget target) + IslandCall(Component component, AjaxRequestTarget target) { - this.island = island; + this.component = component; this.target = target; } /** - * @return the island that was called + * @return the island that was called: an {@link Island} or a {@link FormIsland} */ - public Island<?> getIsland() + public Component getComponent() { - return island; + return component; } /** diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandEndpointBehavior.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandEndpointBehavior.java index 0046fca296..f14621aa02 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandEndpointBehavior.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandEndpointBehavior.java @@ -19,6 +19,7 @@ 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; @@ -66,7 +67,8 @@ final class IslandEndpointBehavior extends AbstractDefaultAjaxBehavior @Override protected void respond(AjaxRequestTarget target) { - Island<?> island = (Island<?>)getComponent(); + 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(""); @@ -74,7 +76,7 @@ final class IslandEndpointBehavior extends AbstractDefaultAjaxBehavior String key = parameters.getParameterValue(PARAM_KEY).toString(""); IIslandSerializer serializer = IslandSettings.get().getSerializer(); - IslandCall call = new IslandCall(island, target); + IslandCall call = new IslandCall(component, target); List<String> invalidations = call.getInvalidations(); String answer; @@ -98,7 +100,7 @@ final class IslandEndpointBehavior extends AbstractDefaultAjaxBehavior } catch (IslandSerializationException e) { - LOG.debug("Island call '{}' on {} failed to (de)serialize", name, island.getPath(), e); + LOG.debug("Island call '{}' on {} failed to (de)serialize", name, component.getPath(), e); answer = IslandAnswer.failure(serializer, callId, "invalid", List.of(detail(e, "The call's payload or result could not be converted.")), invalidations); @@ -114,7 +116,7 @@ final class IslandEndpointBehavior extends AbstractDefaultAjaxBehavior } catch (RuntimeException e) { - LOG.error("Island call '{}' on {} failed", name, island.getPath(), e); + LOG.error("Island call '{}' on {} failed", name, component.getPath(), e); answer = IslandAnswer.failure(serializer, callId, "error", List.of(detail(e, "The call failed on the server.")), invalidations); } @@ -122,6 +124,15 @@ final class IslandEndpointBehavior extends AbstractDefaultAjaxBehavior target.addData(IslandAnswer.DATA_NAME, answer); } + private static IslandSupport supportOf(Component component) + { + if (component instanceof Island<?> island) + { + return island.getIslandSupport(); + } + return ((FormIsland<?, ?>)component).getIslandSupport(); + } + private static String detail(RuntimeException e, String message) { return Application.get().usesDevelopmentConfig() ? message + " " + e : message; diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java index 1d8ffd40e1..5215e48ebf 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSettings.java @@ -18,6 +18,9 @@ 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; @@ -56,6 +59,11 @@ public class IslandSettings */ 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; @@ -75,9 +83,14 @@ public class IslandSettings private ResourceReference assets; + private ResourceReference endpoints; + + private final PagelessEndpoints pagelessEndpoints = new PagelessEndpoints(); + /** - * Installs the settings in an application, mounts the resource serving the built files and - * registers the listener that answers island calls failing before they reach their island. + * 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 @@ -98,9 +111,32 @@ public class IslandSettings return new IslandAssetResource(settings::getManifestModuleLoader); } }; + settings.endpoints = new ResourceReference(IslandSettings.class, "endpoints") + { + private static final long serialVersionUID = 1L; + + @Override + public IResource getResource() + { + return new PagelessEndpointResource(); + } + }; application.setMetaData(KEY, settings); application.mountResource(MOUNT_PATH, settings.assets); + application.mountResource(ENDPOINT_PATH, settings.endpoints); application.getRequestCycleListeners().add(new IslandCallFailureListener()); + application.getAjaxRequestTargetListeners().add(new AjaxRequestTarget.IListener() + { + @Override + public void updateAjaxAttributes(AbstractDefaultAjaxBehavior behavior, + AjaxRequestAttributes attributes) + { + if (behavior.getComponent() instanceof FormIsland) + { + attributes.setSerializeRecursively(true); + } + } + }); return settings; } @@ -120,6 +156,19 @@ public class IslandSettings return settings; } + /** + * @return the page-less endpoints of the application + */ + public PagelessEndpoints getPagelessEndpoints() + { + return pagelessEndpoints; + } + + ResourceReference getEndpointReference() + { + return endpoints; + } + /** * @return the serializer for props, call payloads and results */ diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java new file mode 100644 index 0000000000..075133085f --- /dev/null +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandSupport.java @@ -0,0 +1,185 @@ +/* + * 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.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; +import java.util.regex.Pattern; + +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.parser.XmlTag.TagType; +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 + { + } + + private final String type; + + private final String key; + + private final Map<String, Endpoint> endpoints = new LinkedHashMap<>(); + + private final Map<String, String> 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) + { + Args.notEmpty(name, "name"); + Args.notEmpty(endpointId, "endpointId"); + pageless.put(name, endpointId); + } + + 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() + + ",\"pageless\":" + serializer.toJson(pagelessUrls()) + + (form != null ? ",\"form\":" + form : "") + "}"; + return "<script type=\"application/json\" " + Island.ATTR_STATE + ">" + + IslandJson.escapeForScript(state) + "</script><div " + Island.ATTR_ROOT + "></div>"; + } + + private Map<String, String> pagelessUrls() + { + Map<String, String> urls = new LinkedHashMap<>(); + pageless.forEach((name, id) -> { + PageParameters parameters = new PageParameters(); + parameters.set(0, id); + urls.put(name, RequestCycle.get() + .urlFor(IslandSettings.get().getEndpointReference(), parameters) + .toString()); + }); + return urls; + } + + void renderHead(IHeaderResponse response) + { + IslandSettings.get().getModuleLoader().renderHead(type, response); + } + + static IIslandSerializer serializer() + { + return IslandSettings.get().getSerializer(); + } +} diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandTargets.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandTargets.java new file mode 100644 index 0000000000..dc49e71295 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandTargets.java @@ -0,0 +1,48 @@ +/* + * 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.core.request.handler.IPartialPageRequestHandler; + +/** + * What an Ajax request that is not an island call can send to the islands of the page. + * + * @since 12.0.0 + */ +public final class IslandTargets +{ + private IslandTargets() + { + } + + /** + * Marks client-side query keys as stale, so every island on the page that shows data under one + * of them fetches it again, e.g. after a classic form submit changed that data. + * + * @param target + * the target of the current Ajax request + * @param keys + * the query keys + */ + public static void invalidate(IPartialPageRequestHandler target, String... keys) + { + target.addData(IslandAnswer.DATA_NAME, + IslandAnswer.invalidations(IslandSettings.get().getSerializer(), List.of(keys))); + } +} diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCall.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessCall.java similarity index 59% copy from wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCall.java copy to wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessCall.java index 907ff9d7c2..21b9c07a36 100644 --- a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/IslandCall.java +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessCall.java @@ -20,56 +20,61 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.Session; +import org.apache.wicket.request.http.WebRequest; /** - * The context of one island call, handed to its handler. + * The context of one page-less call, handed to its endpoint and authorization. A page-less call + * has no page and no Ajax request target: it runs outside the page lock, in parallel with other + * requests of the session. * * @since 12.0.0 */ -public final class IslandCall +public final class PagelessCall { - private final Island<?> island; + private final String endpoint; - private final AjaxRequestTarget target; + private final WebRequest request; private final List<String> invalidations = new ArrayList<>(); - IslandCall(Island<?> island, AjaxRequestTarget target) + PagelessCall(String endpoint, WebRequest request) { - this.island = island; - this.target = target; + this.endpoint = endpoint; + this.request = request; } /** - * @return the island that was called + * @return the id the endpoint is registered under */ - public Island<?> getIsland() + public String getEndpoint() { - return island; + return endpoint; } /** - * The target of the Ajax request the call travels in. Components added to it are updated on the - * client before the call's result is delivered, also when the call is rejected. - * - * @return the Ajax request target + * @return the request */ - public AjaxRequestTarget getTarget() + public WebRequest getRequest() { - return target; + return request; } /** - * Creates the exception that rejects this call. Throw it: - * - * <pre> - * throw call.reject("The game is over."); - * </pre> + * @return the session of the request + */ + public Session getSession() + { + return Session.get(); + } + + /** + * Creates the exception that rejects this call. Throw it. * * @param messages * the messages for the client * @return the exception to throw + * @see IslandCall#reject(String...) */ public IslandCallRejectedException reject(String... messages) { @@ -77,14 +82,14 @@ public final class IslandCall } /** - * Marks client-side query keys as stale, so every island on the page that shows data under one - * of them fetches it again. + * Marks client-side query keys as stale. * * @param keys * the query keys * @return {@code this} + * @see IslandCall#invalidate(String...) */ - public IslandCall invalidate(String... keys) + public PagelessCall invalidate(String... keys) { Collections.addAll(invalidations, keys); return this; diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpointResource.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpointResource.java new file mode 100644 index 0000000000..5547b892f6 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpointResource.java @@ -0,0 +1,181 @@ +/* + * 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.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. + */ +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"; + + 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 answer = answer(id, registration, new PagelessCall(id, request), 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) + { + LOG.debug("Page-less call '{}' failed to (de)serialize", id, e); + return IslandAnswer.failure(serializer, null, "invalid", + List.of(detail(e, "The call's payload or result could not be converted.")), + invalidations); + } + catch (AuthorizationException e) + { + return IslandAnswer.failure(serializer, null, "forbidden", + List.of("The call is not allowed."), invalidations); + } + catch (ReplaceHandlerException e) + { + throw e; + } + catch (RuntimeException e) + { + LOG.error("Page-less call '{}' failed", id, e); + return IslandAnswer.failure(serializer, null, "error", + List.of(detail(e, "The call failed on the server.")), invalidations); + } + } + + private static String read(HttpServletRequest request) throws IOException + { + try (InputStream in = request.getInputStream()) + { + byte[] bytes = in.readNBytes(MAX_PAYLOAD + 1); + if (bytes.length > MAX_PAYLOAD) + { + throw new IOException("The payload exceeds " + MAX_PAYLOAD + " bytes."); + } + return new String(bytes, StandardCharsets.UTF_8); + } + } + + private static String detail(RuntimeException e, String message) + { + return Application.get().usesDevelopmentConfig() ? message + " " + e : message; + } +} diff --git a/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpoints.java b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpoints.java new file mode 100644 index 0000000000..fa040ca14a --- /dev/null +++ b/wicket-experimental/wicket-islands/src/main/java/org/apache/wicket/islands/PagelessEndpoints.java @@ -0,0 +1,88 @@ +/* + * 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.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +import org.apache.wicket.util.lang.Args; + +/** + * The page-less endpoints of an application. An island makes one callable by its client-side peer + * with {@code usePageless}. + * + * <pre> + * IslandSettings.install(this).getPagelessEndpoints().register("scores", ScoreQuery.class, + * new ScoresEndpoint(highScores), IPagelessAuthorization.PERMIT_ALL); + * </pre> + * + * @since 12.0.0 + */ +public final class PagelessEndpoints +{ + private static final Pattern ID_PATTERN = Pattern.compile("[A-Za-z0-9_-]+"); + + record Registration(Class<?> requestType, IPagelessEndpoint<Object, ?> endpoint, + IPagelessAuthorization authorization) + { + } + + private final Map<String, Registration> registrations = new ConcurrentHashMap<>(); + + PagelessEndpoints() + { + } + + /** + * Registers an endpoint. + * + * @param <Q> + * the request type + * @param id + * the id of the endpoint; letters, digits, '-' and '_' + * @param requestType + * the request type, {@link Void} for calls without payload + * @param endpoint + * the endpoint + * @param authorization + * decides which calls may run, {@link IPagelessAuthorization#PERMIT_ALL} for all + * @return {@code this} + */ + @SuppressWarnings("unchecked") + public <Q> PagelessEndpoints register(String id, Class<Q> requestType, + IPagelessEndpoint<Q, ?> endpoint, IPagelessAuthorization authorization) + { + Args.notNull(id, "id"); + if (!ID_PATTERN.matcher(id).matches()) + { + throw new IllegalArgumentException("Invalid endpoint id '" + id + + "': use letters, digits, '-' and '_'"); + } + Args.notNull(requestType, "requestType"); + Args.notNull(endpoint, "endpoint"); + Args.notNull(authorization, "authorization"); + registrations.put(id, + new Registration(requestType, (IPagelessEndpoint<Object, ?>)endpoint, authorization)); + return this; + } + + Registration get(String id) + { + return registrations.get(id); + } +} diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/FormIslandTest.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/FormIslandTest.java new file mode 100644 index 0000000000..026ff54d97 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/FormIslandTest.java @@ -0,0 +1,186 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; +import org.apache.wicket.islands.FormIslandTestPage.Point; +import org.apache.wicket.util.tester.FormTester; +import org.apache.wicket.util.tester.TagTester; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * A {@link FormIsland} taking part in a form. + */ +class FormIslandTest extends IslandTestCase +{ + private static final Pattern STATE = Pattern.compile( + "<script type=\"application/json\" data-wicket-island-state>(.*?)</script>", Pattern.DOTALL); + + private FormIslandTestPage page; + + @BeforeEach + void render() + { + page = tester.startPage(FormIslandTestPage.class); + } + + @Test + @SuppressWarnings("unchecked") + void rendersTheValueAndTheFormState() + { + TagTester host = tester.getTagByWicketId("point"); + assertEquals("test-island", host.getAttribute(Island.ATTR_TYPE)); + assertNull(host.getAttribute("name")); + + assertEquals("{\"x\":1,\"y\":2}", valueInput().getAttribute("value")); + assertEquals(page.island.getInputName(), valueInput().getAttribute("name")); + + Map<String, Object> state = state(); + assertEquals(Map.of("max", 9), state.get("props")); + Map<String, Object> form = (Map<String, Object>)state.get("form"); + assertEquals(Boolean.TRUE, form.get("required")); + assertEquals(Boolean.TRUE, form.get("enabled")); + assertEquals("Point", form.get("label")); + assertEquals(List.of(), form.get("errors")); + } + + @Test + void submittedValueReachesTheModel() + { + FormTester form = tester.newFormTester("form"); + form.setValue("point", "{\"x\":3,\"y\":4}"); + form.submit(); + + assertEquals(new Point(3, 4), page.value.getObject()); + } + + @Test + void submittedValueIsSanitized() + { + FormTester form = tester.newFormTester("form"); + form.setValue("point", "{\"x\":30,\"y\":4}"); + form.submit(); + + assertEquals(new Point(9, 4), page.value.getObject()); + } + + @Test + void malformedValueIsAConversionErrorAndKeptForTheUser() + { + FormTester form = tester.newFormTester("form"); + form.setValue("point", "{\"x\":3,\"admin\":true}"); + form.submit(); + + assertEquals(new Point(1, 2), page.value.getObject()); + assertEquals(List.of("The value is not valid."), errors()); + assertEquals("{\"x\":3,\"admin\":true}", valueInput().getAttribute("value")); + } + + @Test + void requiredValueIsChecked() + { + FormTester form = tester.newFormTester("form"); + form.setValue("point", ""); + form.submit(); + + assertEquals(1, errors().size()); + assertTrue(errors().get(0).contains("Point"), errors().toString()); + } + + @Test + void validatorMessagesReachThePeer() + { + FormTester form = tester.newFormTester("form"); + form.setValue("point", "{\"x\":5,\"y\":5}"); + form.submit(); + + assertEquals(List.of("Not on the diagonal"), errors()); + tester.assertErrorMessages("Not on the diagonal"); + } + + @Test + void ajaxSubmitUpdatesTheIsland() + { + FormTester form = tester.newFormTester("form"); + form.setValue("point", "{\"x\":5,\"y\":5}"); + form.submit("submit"); + tester.executeAjaxEvent("form:submit", "click"); + + tester.assertComponentOnAjaxResponse(page.island); + assertTrue(tester.getLastResponseAsString().contains("Not on the diagonal")); + } + + @Test + void ajaxBehaviorsSendTheHiddenInput() + { + AjaxFormComponentUpdatingBehavior behavior = page.island + .getBehaviors(AjaxFormComponentUpdatingBehavior.class) + .get(0); + String script = behavior.getCallbackScript().toString(); + assertTrue(script.contains("\"sr\":true"), script); + + tester.getRequest().getPostParameters().setParameterValue(page.island.getInputName(), + "{\"x\":7,\"y\":8}"); + tester.executeBehavior(behavior); + + assertEquals(1, page.updates); + assertEquals(new Point(7, 8), page.value.getObject()); + tester.assertComponentOnAjaxResponse(page.island); + } + + @Test + @SuppressWarnings("unchecked") + void disabledIslandTellsThePeer() + { + page.island.setEnabled(false); + tester.startPage(page); + + assertNull(tester.getTagByWicketId("point").getAttribute("disabled")); + assertEquals(Boolean.FALSE, ((Map<String, Object>)state().get("form")).get("enabled")); + } + + private TagTester valueInput() + { + TagTester input = TagTester.createTagByName(tester.getLastResponseAsString(), "input"); + assertTrue(input.hasAttribute(FormIsland.ATTR_VALUE)); + return input; + } + + @SuppressWarnings("unchecked") + private Map<String, Object> state() + { + Matcher matcher = STATE.matcher(tester.getLastResponseAsString()); + assertTrue(matcher.find(), tester.getLastResponseAsString()); + return JSON.readValue(matcher.group(1), Map.class); + } + + @SuppressWarnings("unchecked") + private List<String> errors() + { + return (List<String>)((Map<String, Object>)state().get("form")).get("errors"); + } +} diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/FormIslandTestPage.html b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/FormIslandTestPage.html new file mode 100644 index 0000000000..602b503418 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/FormIslandTestPage.html @@ -0,0 +1,9 @@ +<html xmlns:wicket="http://wicket.apache.org"> +<body> + <div wicket:id="feedback"></div> + <form wicket:id="form"> + <div wicket:id="point"></div> + <button wicket:id="submit">Save</button> + </form> +</body> +</html> diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/FormIslandTestPage.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/FormIslandTestPage.java new file mode 100644 index 0000000000..ee91a75b91 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/FormIslandTestPage.java @@ -0,0 +1,104 @@ +/* + * 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.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; +import org.apache.wicket.ajax.markup.html.form.AjaxButton; +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.model.Model; +import org.apache.wicket.validation.ValidationError; + +/** + * A page with a form island in a form. + */ +public class FormIslandTestPage extends WebPage +{ + private static final long serialVersionUID = 1L; + + public record Point(int x, int y) implements Serializable + { + } + + public record PickerProps(int max) implements Serializable + { + } + + final Model<Point> value = Model.of(new Point(1, 2)); + + final FormIsland<Point, PickerProps> island; + + final FeedbackPanel feedback; + + int updates; + + public FormIslandTestPage() + { + feedback = new FeedbackPanel("feedback"); + feedback.setOutputMarkupId(true); + add(feedback); + + Form<Void> form = new Form<>("form"); + add(form); + + island = new FormIsland<>("point", "test-island", value, Point.class, + Model.of(new PickerProps(9))) + { + private static final long serialVersionUID = 1L; + + @Override + protected Point sanitize(Point point) + { + return new Point(Math.min(point.x(), 9), Math.min(point.y(), 9)); + } + }; + island.setRequired(true); + island.setLabel(Model.of("Point")); + island.add(validatable -> { + if (validatable.getValue().x() == validatable.getValue().y()) + { + validatable.error(new ValidationError("Not on the diagonal")); + } + }); + island.add(new AjaxFormComponentUpdatingBehavior("change") + { + private static final long serialVersionUID = 1L; + + @Override + protected void onUpdate(AjaxRequestTarget target) + { + updates++; + } + }); + form.add(island); + + form.add(new AjaxButton("submit") + { + private static final long serialVersionUID = 1L; + + @Override + protected void onError(AjaxRequestTarget target) + { + target.add(feedback); + } + }); + } +} diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.html b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.html index 28b05c7a68..dece66ccf5 100644 --- a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.html +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.html @@ -2,5 +2,6 @@ <body> <span wicket:id="label"></span> <div wicket:id="island"/> + <a wicket:id="invalidate">invalidate</a> </body> </html> diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.java index e59b4caa49..9daa0a66fa 100644 --- a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.java +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/IslandTestPage.java @@ -16,6 +16,8 @@ */ package org.apache.wicket.islands; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; @@ -70,6 +72,19 @@ public class IslandTestPage extends WebPage island.onCall("boom", Void.class, (request, call) -> { throw new IllegalStateException("secret detail"); }); + island.usePageless("echo"); + island.usePageless("sum", "echo"); add(island); + + add(new AjaxLink<Void>("invalidate") + { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) + { + IslandTargets.invalidate(target, "totals", "scores"); + } + }); } } diff --git a/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/PagelessEndpointTest.java b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/PagelessEndpointTest.java new file mode 100644 index 0000000000..179a5cb9a8 --- /dev/null +++ b/wicket-experimental/wicket-islands/src/test/java/org/apache/wicket/islands/PagelessEndpointTest.java @@ -0,0 +1,222 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.wicket.islands.IslandTestPage.Add; +import org.apache.wicket.islands.IslandTestPage.Sum; +import org.apache.wicket.mock.MockWebResponse; +import org.apache.wicket.protocol.http.mock.MockHttpServletRequest; +import org.apache.wicket.protocol.http.servlet.ServletWebRequest; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.request.resource.IResource; +import org.junit.jupiter.api.Test; + +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; + +/** + * Page-less endpoints. + */ +class PagelessEndpointTest extends IslandTestCase +{ + @Override + protected void configureIslands(IslandSettings settings) + { + super.configureIslands(settings); + settings.getPagelessEndpoints() + .register("echo", Add.class, (add, call) -> { + if (add.amount() < 0) + { + throw call.reject("negative"); + } + call.invalidate("totals"); + return new Sum(add.amount() * 2); + }, IPagelessAuthorization.PERMIT_ALL) + .register("secret", Void.class, (none, call) -> "secret", call -> false) + .register("boom", Void.class, (none, call) -> { + throw new IllegalStateException("broken"); + }, IPagelessAuthorization.PERMIT_ALL); + } + + @Test + @SuppressWarnings("unchecked") + void answersWithTheResultAndInvalidations() + { + MockWebResponse response = post("echo", "{\"amount\":21}", "same-origin"); + + Map<String, Object> answer = JSON.readValue(response.getBinaryResponse(), Map.class); + assertEquals(Boolean.TRUE, answer.get("ok")); + assertEquals(Map.of("total", 42), answer.get("value")); + assertEquals(List.of("totals"), answer.get("invalidate")); + assertTrue(response.getContentType().startsWith("application/json")); + } + + @Test + void rejectedCallIsInvalid() + { + assertEquals("invalid", error(answer(post("echo", "{\"amount\":-1}", null))).get("kind")); + } + + @Test + void malformedPayloadIsInvalid() + { + assertEquals("invalid", error(answer(post("echo", "{\"amount\":", null))).get("kind")); + } + + @Test + void deniedCallIsForbidden() + { + assertEquals("forbidden", error(answer(post("secret", "", null))).get("kind")); + } + + @Test + void failingEndpointIsAnError() + { + assertEquals("error", error(answer(post("boom", "", null))).get("kind")); + } + + @Test + void unknownEndpointIsNotFound() + { + assertEquals(404, post("nothing", "", null).getStatus()); + } + + @Test + void crossSiteRequestIsRefused() + { + assertEquals(403, post("echo", "{\"amount\":1}", "cross-site").getStatus()); + assertEquals(403, post("echo", "{\"amount\":1}", "same-site").getStatus()); + } + + @Test + void requestWithoutTheHeaderIsRefused() + { + assertEquals(403, send("echo", "POST", "{\"amount\":1}", null, false).getStatus()); + } + + @Test + void getIsRefused() + { + assertEquals(405, send("echo", "GET", "", null, true).getStatus()); + } + + @Test + @SuppressWarnings("unchecked") + void islandStateHoldsTheUrlsOfItsPagelessCalls() + { + tester.startPage(IslandTestPage.class); + + Matcher matcher = Pattern.compile( + "data-wicket-island-state>(.*?)</script>", Pattern.DOTALL) + .matcher(tester.getLastResponseAsString()); + assertTrue(matcher.find()); + Map<String, String> pageless = (Map<String, String>)JSON + .readValue(matcher.group(1), Map.class) + .get("pageless"); + assertEquals(List.of("echo", "sum"), List.copyOf(pageless.keySet())); + assertTrue(pageless.get("echo").endsWith("wicket-islands-call/echo"), pageless.toString()); + assertEquals(pageless.get("echo"), pageless.get("sum")); + } + + @Test + void classicAjaxRequestSendsInvalidations() + { + tester.startPage(IslandTestPage.class); + + tester.clickLink("invalidate"); + + assertTrue(tester.getLastResponseAsString() + .contains("<data name=\"wicket-islands\"><![CDATA[{\"invalidate\":[\"totals\",\"scores\"]}]]></data>"), + tester.getLastResponseAsString()); + } + + private MockWebResponse post(String id, String body, String fetchSite) + { + return send(id, "POST", body, fetchSite, true); + } + + private MockWebResponse send(String id, String method, String body, String fetchSite, + boolean header) + { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + MockHttpServletRequest http = new MockHttpServletRequest(tester.getApplication(), + tester.getHttpSession(), tester.getServletContext()) + { + @Override + public ServletInputStream getInputStream() + { + ByteArrayInputStream in = new ByteArrayInputStream(bytes); + return new ServletInputStream() + { + @Override + public int read() + { + return in.read(); + } + + @Override + public boolean isFinished() + { + return in.available() == 0; + } + + @Override + public boolean isReady() + { + return true; + } + + @Override + public void setReadListener(ReadListener listener) + { + } + }; + } + }; + http.setMethod(method); + if (header) + { + http.addHeader(PagelessEndpointResource.HEADER, "1"); + } + if (fetchSite != null) + { + http.addHeader("Sec-Fetch-Site", fetchSite); + } + MockWebResponse response = new MockWebResponse(); + new PagelessEndpointResource().respond(new IResource.Attributes( + new ServletWebRequest(http, ""), response, new PageParameters().set(0, id))); + return response; + } + + @SuppressWarnings("unchecked") + private static Map<String, Object> answer(MockWebResponse response) + { + assertTrue(response.getStatus() == null || response.getStatus() == 200, + "status " + response.getStatus()); + return JSON.readValue(response.getBinaryResponse(), Map.class); + } +}
