Getting started #
Wicket Oat is a UI component library for Apache Wicket, built on the Oat UI design system. It gives you styled, accessible, translated components that you use exactly like Wicket's own: plain Java classes, models, .properties files and Ajax, with no JavaScript framework and no CSS framework to learn.
Requirements #
- Java 17 or newer
- Apache Wicket 10.11 or newer (
wicket-coreandwicket-extensions) - Maven or Gradle
Add the dependency #
<dependency>
<groupId>dev.jbaby</groupId>
<artifactId>wicket-oat-core</artifactId>
<version>0.6.0</version>
</dependency>
Install it in your application #
Call WicketOats.install(this) in your application's init(). It adds Oat's CSS and JavaScript to every page, registers the themes, hooks the busy indicator into Ajax requests, and adds the one CSP source Oat needs.
public class MyApplication extends WebApplication {
@Override
protected void init() {
super.init();
WicketOats.install(this)
.setDefaultTheme(OatTheme.BUSINESS) // optional; null follows the browser
.setDensity(OatDensity.COMPACT); // optional; tighter spacing
}
}
install returns the settings, so the options chain. Call it after any getCspSettings().blocking().strict() or unsafeInline() of your own, since those reset the CSP directives it adds. A policy you turned off with disabled() or clear() stays off.
Your first page #
Extend OatAppLayout for a page with a top bar and a sidebar, and put the page content in <wicket:extend>:
public class DashboardPage extends OatAppLayout {
public DashboardPage() {
add(OatButton.onClick("hello", "Say hello", target ->
Oat.toast(target, "Hello from Wicket Oat!", OatVariant.SUCCESS)));
add(new OatAlert("note", "Your changes were saved.", OatVariant.SUCCESS));
}
@Override
protected IModel<List<MenuItem>> sidebarMenuItemsModel() {
return Model.ofList(List.of(
MenuItem.of("Dashboard", DashboardPage.class),
MenuItem.of("Customers", CustomersPage.class)));
}
}
<!-- DashboardPage.html -->
<html xmlns:wicket="http://wicket.apache.org">
<body>
<wicket:extend>
<h1>Dashboard</h1>
<a wicket:id="hello"></a>
<div wicket:id="note"></div>
</wicket:extend>
</body>
</html>
Most apps put the menu in a BasePage extends OatAppLayout that every page extends. You don't have to use OatAppLayout: every component also works on an ordinary WebPage, and OatHtml gives a base page of your own the theme and language.
Core concepts #
Components and behaviors #
Almost everything comes in two forms:
- A component renders its own markup.
new OatAlert("id", ...)on a<div wicket:id="id">gives you a complete alert. - A behavior styles a component you already have.
link.add(Oat.Behaviors.button())turns any WicketLinkinto an Oat button, keeping your own class and markup.
// A component: Oat renders the markup
add(new OatAlert("saved", "Saved!", OatVariant.SUCCESS));
// A behavior: your AjaxLink, Oat's look
add(new AjaxLink<Void>("refresh") {
@Override
public void onClick(AjaxRequestTarget target) { ... }
}.add(Oat.Behaviors.button().setVariant(OatVariant.SECONDARY)));
Use behaviors when a component already has its own base class, or when you need markup Oat's component doesn't render.
Constructors and lambda factories #
Every component is a plain Wicket component you create with new. Components driven by a callback, such as a button's click or a list's items, are abstract like Wicket's AjaxLink and ListView: override the method, or use the class's static factory, which takes a lambda instead, as Wicket's own AjaxLink.onClick(...) does:
// OatButton is abstract (onClick): the factory takes a lambda instead
add(OatButton.onClick("save", "Save", target -> save(target)));
// The same with a subclass
add(new OatButton("save", Model.of("Save")) {
@Override
public void onClick(AjaxRequestTarget target) { save(target); }
});
// List components fill each item from its object
add(OatAccordion.of("faq", Model.ofList(faqs), (item, faq) -> {
item.add(new Label("title", faq.question()));
item.add(new Label("content", faq.answer()));
}));
// Components without abstract methods: just the constructor
add(new OatBadge("status", "Paid", OatVariant.SUCCESS));
The factories are OatButton.onClick, OatSubmitButton.onSubmit, OatWizard.onFinish, OatLoginForm.signIn, and of(...) on OatAccordion, OatTabs, OatDropdown, OatButtonGroup, OatBreadcrumb, OatPagination, OatAvatarGroup and OatLazyLoadPanel. Oat.Components has the same ones in one place (Oat.Components.button(...), accordion(...), ...), and Oat.Behaviors creates the behaviors. Overridable hooks are named newXxx(id), as in Wicket, and setters taking a callback setOnXxx(...), such as OatCrud.setOnSave(...).
Ids passed to factories #
Many components ask you for a part of themselves: a dialog's content, a table's toolbar, a popover's content, a master-detail's detail. They pass you the id to use, and check that you used it:
table.setToolbar(id -> new SearchPanel(id, search)); // "toolbar"
dialog.setContent(new PersonFields(OatDialog.CONTENT_ID, person)); // "content"
popover = new OatPopover("note", "Quick note", id -> new NotePanel(id));
A wrong id fails at once with a message naming the expected one, instead of a puzzling markup error later.
Models and labels #
Oat's form fields follow Wicket's conventions:
- Leave out the model and a field takes it from a parent
CompoundPropertyModelby its id ("name"→person.name). - Leave out the label and it is looked up in the
.propertiesfiles by the same id (name=Full name), falling back to the id. - Pass either explicitly when you need to:
new OatTextField<>("name", "Full name", model).
Form<Person> form = new Form<>("form", new CompoundPropertyModel<>(person));
form.add(new OatTextField<String>("name").setRequired(true)); // label from name=..., value person.name
form.add(new OatEmailField("email"));
Labels and texts can be any IModel<String>, so a ResourceModel or a lambda model translates or updates them.
Variants #
Colors are one enum everywhere: OatVariant.DEFAULT, SECONDARY, SUCCESS, WARNING and DANGER. Oat styles them per component: buttons support SECONDARY and DANGER, badges all of them, alerts and toasts SUCCESS, WARNING and DANGER. Other variants render like DEFAULT.
Ajax and markup ids #
Components that you typically update render their own tag with a markup id: form fields, data tables, dialogs, lists. So target.add(component) re-renders them, for example a form after a failed submit to show inline errors:
form.add(OatSubmitButton.onSubmit("save", "Save",
target -> save(target), // the form is valid
target -> target.add(form))); // it isn't: show the errors
Fluent setters return the concrete type, so new OatNumberField<Integer>("age").setMin(0).setRequired(true) chains without casts.
App shell #
The layout #
OatAppLayout is an abstract WebPage with a top bar, a collapsible sidebar (a menu button on phones) and your page in the main area. It applies the current theme and density to <html>. Override these to fill it:
| Method | What it gives |
|---|---|
sidebarMenuItemsModel() | The sidebar's MenuItems |
appTitleModel() / appNameModel() | The browser title and the name in the top bar (or OatAppLayout.title / .name in your .properties) |
newTopNavExtra(id) | Anything on the right of the top bar, such as a user menu |
newSidebarFooter(id) | A footer under the sidebar, such as a theme switcher |
newMenuLink(id, item) | A menu entry's link: a BookmarkablePageLink by default, or e.g. an AjaxLink |
The constructors take nothing, PageParameters or a model, like any page.
<html> gets the page's lang from its locale, so screen readers pronounce the content in the right language, and the page starts with a "Skip to content" link, shown only while it has keyboard focus, that moves focus past the navigation to <main id="oat-main">. A base page of your own that doesn't extend OatAppLayout gets the theme, density and language from an OatHtml on its <html wicket:id="html">:
public abstract class BasePage extends WebPage {
protected BasePage() {
add(new OatHtml("html"));
}
}
The sidebar menu #
Links can be grouped into collapsible sections, open while one of their pages is shown, and carry a badge such as a count:
@Override
protected IModel<List<MenuItem>> sidebarMenuItemsModel() {
return Model.ofList(List.of(
MenuItem.of("Dashboard", DashboardPage.class),
MenuItem.group("Sales",
MenuItem.of("Orders", OrdersPage.class).withBadge(() -> orders.countOpen()),
MenuItem.of("Invoices", InvoicesPage.class)),
MenuItem.of("Settings", SettingsPage.class)));
}
- A badge is read on every render and hidden while it is
null, empty or zero. The sidebar has a markup id, sotarget.add(getSidebar())updates it over Ajax. - Pages the user isn't authorized to open are left out, and so is a group left empty.
- Groups can't contain groups. Labels can be
IModel<String>s, such as aResourceModel.
The user menu #
OatUserMenu fills the top bar's corner: the signed-in user's picture or initials and name open a menu with their name, a second line such as their email, links of yours and "Sign out". While nobody is signed in it is a "Sign in" link, or nothing:
@Override
protected Component newTopNavExtra(String id) {
OatUserMenu user = new OatUserMenu(id, () -> MySession.get().getUserName()); // null while signed out
user.setDetail(() -> MySession.get().getEmail());
user.setPicture(() -> MySession.get().getPictureUrl());
user.addLink("Profile", ProfilePage.class).setIcon("user");
user.setSignInPage(SignInPage.class);
return user;
}
- Sign out invalidates the session and shows the home page. Override
signOut(), e.g. to sign out of Spring Security too, andonSignedOut(), which goes to another page withsetResponsePage(...). It is a POST, refused with 403 Forbidden when the browser says another site's page sent it (Sec-Fetch-Site, which current browsers send), so another site can't sign users out. It works on a page left open after the session expired. - Signed in means the name isn't
null; overrideisSignedIn()for a user without a name. The models are read once per request. - Stateless: the menu opens in the browser and its links and form are stateless, so a sign-in page stays stateless, and the "Sign in" link hides on it. On phones the button shows only the picture; screen readers hear "Account: " and the name.
The picture is an OatAvatar, which shows the initials while it loads and if it can't be loaded; OatAvatar.initialsOf("Ada Lovelace") gives "AL".
Phone apps #
OatMobileLayout is a base page for phone-first apps: the content in <main> and an OatBottomNav under it, a tab bar fixed to the bottom of the screen with three to five tabs, each an icon above a short label:
public abstract class TimeOffPage extends OatMobileLayout {
@Override
protected IModel<List<BottomNavItem>> bottomNavItemsModel() {
return Model.ofList(List.of(
BottomNavItem.of("Today", TodayPage.class).withIcon(Icon.sprite("today")),
BottomNavItem.of("Team", TeamPage.class).withIcon(Icon.named("users"))
.withBadge(() -> requests.countOpen()),
BottomNavItem.of("Add absence", AddAbsencePage.class).withIcon(Icon.named("plus")).asPrimary()));
}
}
- Icons:
Icon.sprite("today")draws a symbol of an SVG sprite your page supplies,Icon.svg(...)writes trusted inline SVG, andIcon.named("users")uses one ofOatIcon's icons. Draw them withcurrentColor. - Current tab: the tab whose page is shown gets
aria-current="page"and the primary color;withActive(page -> ...)replaces the rule, e.g. for pages that belong to a tab. - Badges:
withBadge(...)shows a count, hidden whilenullor 0;target.add(getBottomNav())updates it. - Primary item:
asPrimary()makes one item a round Oat button showing only its icon, with its label for screen readers. - Wide screens: the bar shows up to 768px;
setAlwaysVisible(true)innewBottomNav(id, items)keeps it on wider screens. On an iPhone it keeps clear of the home indicator when the viewport meta tag hasviewport-fit=cover, asOatMobileLayout's does.
Without OatMobileLayout, put the bar on a <nav> with new OatBottomNav(id, items) and keep your content clear of it with padding-block-end: calc(var(--oat-bottom-nav-height) + env(safe-area-inset-bottom, 0px)).
Feedback messages #
Wicket's info(), success(), warn() and error() become Oat toasts or alerts:
// In your base page: every message as a toast, also during Ajax requests
add(Oat.Behaviors.feedbackToasts());
// Or as alerts in one place
add(new OatFeedbackPanel("feedback"));
// Then, anywhere:
success("Invoice sent.");
Both update themselves in Ajax requests, so a handler just calls success(...), with no target.add(...). Toasts also show session messages, so getSession().success(...) before setResponsePage(...) appears on the next page. Both leave out errors that a form field already shows next to itself (NotShownInlineFilter); pass your own IFeedbackMessageFilter to change that. To show a toast directly: Oat.toast(target, "Copied", OatVariant.SUCCESS).
Oat shows several toasts as a stack, the newest in front, until the pointer or the focus is on them. The messages of a request come in order of their level, so the most severe of them is in front.
A form's own messages, such as form.error("Please fix the errors."), show next to it with new OatFeedbackPanel("formFeedback", form). The form is the panel's fence, as with Wicket's FencedFeedbackPanel: a panel without a fence and the toasts leave its messages out, so each shows once. A panel without messages takes no space.
Busy buttons #
For slow actions, setBusyIndicator(true) on an OatButton, OatSubmitButton or OatDialog shows a spinner while the Ajax request runs and ignores further clicks, so the action can't run twice. Oat.Behaviors.ajaxBusy() does the same for any other Ajax link or button. It's off by default.
form.add(OatSubmitButton.onSubmit("pay", "Pay now", target -> pay(target)).setBusyIndicator(true));
Confirming an action #
One OatConfirmDialog per page can ask before any number of actions:
OatConfirmDialog confirm = new OatConfirmDialog("confirm"); // <div wicket:id="confirm"></div>
add(confirm);
add(OatButton.onClick("delete", "Delete", target ->
confirm.ask(target, "Delete invoice?", "This can't be undone.", t -> {
invoices.delete(invoice);
t.add(table);
})));
The action stays on the server until the user answers and runs at most once; Cancel or Escape closes the dialog without running it, and the server forgets it. The confirm button is a danger button by default (setConfirmVariant, setConfirmLabel).
Loading slow content #
OatLazyLoadPanel renders the page first and loads slow content right after, showing skeleton lines meanwhile:
add(OatLazyLoadPanel.of("revenue", id -> new RevenuePanel(id, reports.revenueThisYear()))
.setPlaceholder(SkeletonBehavior.Shape.LINE, 2));
The content loads 0.1 seconds after the page is shown. It extends Wicket's AjaxLazyLoadPanel; override isContentReady() to wait for background work, which is checked again every second (getUpdateInterval()). A page's lazy panels share one timer at the shortest interval of those still waiting, so keep it long.
Cookie consent #
add(new OatCookieConsent("cookies")
.setPolicyLink(PrivacyPage.class)
.setOnAnswer(accepted -> audit.log(accepted)));
// Before loading optional scripts, such as analytics:
if (OatCookieConsent.isAccepted()) { ... }
A card at the bottom asks once, with "Accept" and "Only necessary". The answer is stored for a year in the oat-cookie-consent cookie (HttpOnly, SameSite Lax, Secure on HTTPS), and the banner stays hidden once the user has answered.
Forms #
How fields work #
An Oat field is a panel around a Wicket form component: a label, the input, a hint and the inline error. You use it like the component it wraps:
Form<Person> form = new Form<>("form", new CompoundPropertyModel<>(person));
add(form);
OatTextField<String> name = new OatTextField<String>("name").setRequired(true);
name.add(StringValidator.maximumLength(50)); // validators go to the wrapped input
form.add(name);
form.add(new OatNumberField<Integer>("age").setMin(0));
form.add(new OatDropdownChoice<String>("country", Model.ofList(countries)));
form.add(OatSubmitButton.onSubmit("save", "Save", target -> save(target))); // the fields show their errors
<form wicket:id="form" class="vstack gap-4">
<div wicket:id="name"></div>
<div wicket:id="age"></div>
<div wicket:id="country"></div>
<footer class="hstack justify-end"><button wicket:id="save"></button></footer>
</form>
- Required fields get an asterisk and
aria-required. The browser's ownrequiredcheck is left off, so Wicket can show its translated message inline. - Errors show under the field, which gets
aria-invalidandaria-describedbypointing at the message; a hint shows there while there's no error. - After an Ajax submit a field shows an error that appeared, changed or went away by itself, with no
onErrorthat adds the form: it changes its message and error state in place, so the input keeps its focus and what was typed, and screen readers announce the message. Other Ajax requests leave the errors shown alone. - Behaviors: validators and Ajax form-component behaviors you
add(...)go to the wrapped input, as they only work there; other behaviors go to the field's own tag, as with any component.addToInput(...)puts any behavior on the input, such asAttributeModifier.replace("autocomplete", "email"). - The input: the wrapped
FormComponentis the field's childinput, so a test reaches it at"email:input", andgetInput()returns it, e.g. forsetNullValid(true)ornew EqualPasswordInputValidator(password.getInput(), repeat.getInput()). - Hints: pass an
IModel<String>label and a hint model:new OatTextField<>("iban", Model.of("IBAN"), model, Model.of("Starts with your country code.")).
The fields #
| Field | Value | Notes |
|---|---|---|
OatTextField, OatPasswordField, OatEmailField, OatUrlField, OatSearchField, OatTelField | String | HTML5 input types |
OatNumberField<N>, OatRangeField | a Number | setMin, setMax |
OatMoneyField, OatPercentField | BigDecimal | in the user's locale, see below |
OatDateField, OatDateTimeLocalField, OatTimeField | LocalDate, LocalDateTime, LocalTime | native pickers |
OatMonthField, OatWeekField | String | as the browser sends it: 2026-10, 2026-W41 |
OatDateRangeField | DateRange | two dates, either end open |
OatTextArea | String | |
OatCheckBox, OatSwitch | Boolean | a switch is a toggle-styled checkbox |
OatDropdownChoice, OatRadioChoice | one choice | setInline(true) for a row of radios |
OatCheckBoxMultipleChoice, OatListMultipleChoice | a Collection | |
OatTagInput | List<String> | free-form tags as chips |
OatAutoCompleteField<T> | T | looked up on the server as you type |
OatMultiSelectField<T> | List<T> | several values, chips |
OatFileUpload, OatFileDropzone | List<FileUpload> | a dropzone accepts dragged files |
OatColorField | String | |
OatCustomField<T> | T | your own input made of several inputs |
Addons and suggestions #
Single-input fields can show text before or after the input, and suggest values from a native <datalist> (anything else can still be typed):
form.add(new OatTextField<String>("website").setPrefix("https://"));
form.add(new OatNumberField<Integer>("weight").setSuffix("kg"));
form.add(new OatTextField<String>("type").setSuggestions(List.of("Call", "Meeting", "Email")));
Amounts and percentages #
OatMoneyField and OatPercentField edit a BigDecimal in the user's locale: 1.234,50 in German, 1,234.50 in English. The money field takes its decimals from the currency (2 for EUR, 0 for JPY), shows the symbol where the locale puts it, and rounds longer input half-even. A percentage of 19 means 19%.
form.add(new OatMoneyField("price").setCurrency(Currency.getInstance("EUR")).setMin(BigDecimal.ZERO));
form.add(new OatPercentField("taxRate"));
Dates and date ranges #
Date and time fields use the browser's pickers and bind to LocalDate, LocalDateTime and LocalTime. OatDateRangeField edits a DateRange(from, to): either end may be left open, setRequired(true) asks for both, and an end before the start is rejected.
form.add(new OatDateRangeField("delivery", Model.of("Delivery window"), deliveryModel).setRequired(true));
Looking values up on the server #
For choices too many for a dropdown, OatAutoCompleteField asks the server as the user types. On submit, the text must be one of the suggestions, and the field's value is that object:
form.add(new OatAutoCompleteField<Customer>("customer")
.setChoices(text -> customers.search(text)) // at most 10 shown; setMaxChoices(n)
.setDisplay(Customer::name));
setFreeText(text -> value) accepts other text too. For a short fixed list, setSuggestions(...) on a text field is simpler.
Choosing several values #
OatMultiSelectField shows the chosen values as chips with a remove button, and a search box under them that looks up more:
form.add(new OatMultiSelectField<User>("members", "Members", membersModel)
.setChoices(text -> users.search(text))
.setDisplay(User::name));
Choosing a suggestion adds it and empties the box, ready for the next one; chosen values aren't suggested again. Required means at least one. Chips added or removed are like typed input: they reach the model when the form is submitted, and form.clearInput() drops them, as an OatDialog does when it opens or is cancelled, so one dialog can edit one record after another.
Your own inputs #
OatCustomField gives an input made of several inputs (usually a FormComponentPanel) the Oat label, hint and inline errors, and points the aria-describedby and aria-invalid of every input inside at them:
form.add(new OatCustomField<Phone>("phone", "Phone", phoneModel, PhoneInput::new)); // (id, model) -> your input
Give each inner input its own aria-label, such as "Country code" and "Number".
Sections and layout #
OatFieldset is a titled section of a long form. It's a Wicket Border on a <fieldset>, so fields inside still inherit the form's CompoundPropertyModel, and its legend comes from the .properties file by id:
<fieldset wicket:id="billing">
<div wicket:id="street"></div>
<div wicket:id="city"></div>
</fieldset>
OatFieldset billing = new OatFieldset("billing").setDescription("Where the invoice goes.");
billing.add(Oat.Behaviors.row());
billing.add(new OatTextField<String>("street").add(Oat.Behaviors.col(8)),
new OatTextField<String>("city").add(Oat.Behaviors.col(4)));
form.add(billing);
The grid behaviors put Oat's 12-column grid on any component, including Oat fields; it drops to one column on narrow screens. See Layout.
Signing in #
OatLoginForm is a complete sign-in form. Implement signIn with your session or security framework:
add(new OatLoginForm("login") {
@Override
protected boolean signIn(String username, String password, boolean rememberMe) {
return AuthenticatedWebSession.get().signIn(username, password); // wicket-auth-roles
}
}.setRememberMe(true).setForgotPasswordLink(ResetPasswordPage.class));
A failed attempt says "Wrong username or password." without telling which was wrong, and clears the password. After a successful one the session gets a new id (against session fixation) and the user continues where they were going (onSignedIn(target) to change that). The fields carry autocomplete hints for password managers. Without a subclass: OatLoginForm.signIn("login", (username, password) -> ...).
Forms in dialogs #
OatDialog is a modal on the native <dialog> element with its own form, and works like Wicket's ModalDialog. Put fields in its content, and Confirm validates them; the dialog stays open to show errors, or closes after onConfirm:
OatDialog edit = new OatDialog("edit", Model.of("Edit person")) {
@Override
protected void onConfirm(AjaxRequestTarget target) {
people.save(person.getObject());
success("Saved."); // report an error on a field to stay open
}
@Override
protected void onClose(AjaxRequestTarget target) {
person.setObject(null); // saved, cancelled, Escape or the backdrop
}
};
edit.setContent(new PersonFields(OatDialog.CONTENT_ID, person));
add(edit);
// From any Ajax handler:
edit.open(target);
- The server knows whether the dialog is open (
isOpen()). Cancel, Escape and a click on the backdrop close it in the browser and tell the server, andonClose(target)runs once however it closed, also after a confirm orclose(target). target.add(dialog)re-renders it and keeps an open dialog open.open(content, target)sets content that is removed again when the dialog closes, e.g. the fields for the row that was clicked.- A dialog can sit inside a page's form: submitting that form leaves the dialog's fields out.
Inside a page's form, the dialog's buttons render as type="button", so Enter in a page field can't click them; NestedFormButtonBehavior does the same for an Ajax submit button of your own, and OatSubmitButton has it already. A dialog opened again in onConfirm, e.g. for the next record, stays open.
setCloseButton(true) adds an "×" in the header's corner, and setFooterVisible(false) leaves out Cancel and Confirm, e.g. for a dialog that only shows something. The content scrolls between the header and the buttons. Closed without confirming, the dialog shows its models again the next time, without input that wasn't confirmed.
setConfirmLabel, setConfirmVariant and setBusyIndicator adjust the confirm button. For a whole create/edit/delete screen, see CRUD.
Drawers #
OatDrawer is an OatDialog that slides in from an edge of the screen, for what supports the page: filters, a record's details, a form to edit a row. It opens, confirms and closes as a dialog does, and has the "×":
OatDrawer filters = new OatDrawer("filters", "Filters", "Filter orders") { // with a trigger button
@Override
protected void onConfirm(AjaxRequestTarget target) {
target.add(orders);
}
};
filters.setContent(new OrderFilterPanel(OatDialog.CONTENT_ID, filter)).setConfirmLabel(Model.of("Apply"));
add(filters);
add(new OatDrawer("details", Model.of("Details")).setFooterVisible(false).setSide(OatDrawer.Side.START));
setSide(START | END | BOTTOM) picks the edge, the end by default; start and end follow the text direction. A side drawer is as tall as the screen, a bottom one as wide, up to most of its height. Opening it focuses its first field.
Data tables #
OatDataTable #
OatDataTable is Wicket's DataTable with Oat styling and sortable headers that show the order (and set aria-sort). Sorting and paging re-render only the table over Ajax, like Wicket's AjaxFallbackDefaultDataTable, with plain links as the fallback without JavaScript. You give it columns and an ISortableDataProvider, as usual:
OatDataTable<Invoice, String> table = new OatDataTable<>("invoices", columns, provider, 10);
table.setToolbar(id -> new InvoiceSearchPanel(id, search));
table.setEmptyState(id -> new OatEmptyState(id, "No invoices found"));
add(table);
The table has a markup id, so target.add(table) re-renders it after an action. It is pageable like a DataTable (IPageableItems): setCurrentPage(...), getPageCount(), setItemsPerPage(...), and a navigator of your own can page it. addTopToolbar(...) and addBottomToolbar(...) add toolbars, and getTable() returns the inner DataTable.
Columns #
The columns in dev.jbaby.wicket.oat.components.table cover the common cells. Each takes a header model, an optional sort property and a lambda for the value:
List<IColumn<Invoice, String>> columns = new ArrayList<>();
columns.add(OatLinkColumn.toPage(Model.of("Number"), "number", Invoice::number,
InvoicePage.class, invoice -> new PageParameters().add("id", invoice.id())));
columns.add(OatLinkColumn.onClick(Model.of("Customer"), "customer", Invoice::customer,
(target, invoice) -> showCustomer(target, invoice)));
columns.add(new OatBadgeColumn<>(Model.of("Status"), "status", Invoice::status,
invoice -> invoice.status() == Status.PAID ? OatVariant.SUCCESS : OatVariant.SECONDARY));
columns.add(new OatNumberColumn<Invoice, String>(Model.of("Total"), "total", Invoice::total)
.setCurrency(Invoice::currency)); // €1,234.50, right-aligned
columns.add(new OatDateColumn<>(Model.of("Due"), "due", Invoice::due));
columns.add(new OatBooleanColumn<>(Model.of("Exported"), Invoice::exported));
| Column | Shows |
|---|---|
OatLinkColumn | a link to a page (toPage) or an Ajax action (onClick) |
OatBadgeColumn | the value as a badge, colored per row |
OatNumberColumn | locale-formatted, right-aligned; setFractionDigits, a fixed or per-row setCurrency |
OatDateColumn | any java.time value in the locale's style; setStyle, setPattern, setZone for Instants |
OatBooleanColumn | a read-only checkbox |
OatActionsColumn | a "⋯" menu of actions per row |
OatSelectionColumn | row checkboxes, see below |
OatRowDetailsColumn | a button that expands the row |
OatEditableColumn | a cell edited in place |
Wicket's own PropertyColumn and LambdaColumn work alongside them.
Row actions #
OatActionsColumn<Invoice, String> actions = new OatActionsColumn<>();
actions.addAction("Mark as paid", (target, invoice) -> { invoices.markPaid(invoice); target.add(table); })
.setVisibleWhen(invoice -> invoice.status() != Status.PAID);
actions.addAction("Delete", (target, invoice) -> confirm.ask(target, "Delete invoice?", null, t -> ...))
.setVariant(OatVariant.DANGER);
columns.add(actions);
Actions can show only for some rows, and a row without any shows no button. setVisibleWhen is checked again when an action is clicked: one the row no longer shows, e.g. after someone else changed the row, doesn't run, and the row's menu shows its current actions. That needs a row model that loads the row again, such as a LoadableDetachableModel from the provider's model(...); Model.of(row) keeps the row as it was rendered.
Selection and bulk actions #
IModel<Set<Invoice>> selected = new SetModel<>(new HashSet<>());
columns.add(0, new OatSelectionColumn<>(selected));
table.addBulkAction("Export", (target, rows) -> { exports.export(rows); table.clearSelection(target); });
table.addBulkAction(Model.of("Delete"), OatVariant.DANGER, (target, rows) -> confirm.ask(...));
While rows are selected, a bar above the table shows how many, the bulk actions and "Clear selection". The selection lasts across pages and sorting. It keeps the rows themselves, compared with equals, which suits records.
For entities, select by key, so the page keeps only their ids instead of serializing the entities. Give it a loader, and bulk actions get the selected rows loaded by their keys, with any Iterable the loader returns, as Spring Data's repositories do:
IModel<Set<Long>> selectedIds = new SetModel<>(new HashSet<>());
columns.add(0, new OatSelectionColumn<>(selectedIds, Invoice::getId, ids -> invoices.findAllById(ids)));
That also finds the rows a search hides at the time. Without the loader, new OatSelectionColumn<>(selectedIds, Invoice::getId) looks them up through the data provider, which reads every row and finds only those it returns.
Searching #
Have the provider read a search model, and in the search field's Ajax handler go back to the first page:
search.add(new AjaxFormComponentUpdatingBehavior("input") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
table.setCurrentPage(0);
target.add(table.getTable()); // only the rows, so the search field keeps its focus
}
});
Filter chips #
OatFilter is a row of chips above a list or table that chooses one value, such as a category or a status. Choosing a chip sets the model and runs onChange over Ajax:
add(OatFilter.onChange("status", status, Model.ofList(List.of(Status.values())), target -> {
table.setCurrentPage(0);
target.add(table.getTable());
}).setChoiceRenderer(new EnumChoiceRenderer<>(this)).setNullValid(true)); // a first "All" chip
The chips are the radio buttons of a Wicket RadioChoice in a <fieldset>, named by the id in your .properties or by setLabel(...), so the arrow keys move between them. Strings, numbers and enums are their own ids; give other values a renderer with an id, such as new ChoiceRenderer<>("name", "id"), so a chip stands for the same value when the choices change. It has a form of its own, so it works anywhere: in a page's form, in a table's search toolbar or in a drawer.
Row details #
columns.add(0, new OatRowDetailsColumn<>((id, order) -> new OrderLinesPanel(id, order)));
The arrow opens a full-width panel under the row, created the first time it's opened; open rows stay open across pages and sorting. They are remembered by equals, or by key like the selection: new OatRowDetailsColumn<>(details, expandedIds, Order::getId). The panel is rendered on a <div>, so wrap components that need another tag (an OatDescriptionList needs a <dl>) in a panel or fragment.
Editing in place #
columns.add(new OatEditableColumn<Line, String, Integer>(Model.of("Quantity"), "quantity",
Line::quantity, Line::setQuantity)
.setType(Integer.class)
.setRequired(true)
.addValidator(RangeValidator.minimum(1))
.setOnSave((target, line) -> { lines.save(line); target.add(totals); }));
The cell shows its value as a button. Clicking it or pressing Enter turns it into a field with Save and Cancel; Enter saves, Escape cancels. The text is converted to the column's type and validated; an invalid value shows its error under the field and isn't set. Focus goes back to the cell afterwards.
Choosing columns and exporting #
table.setColumnChooser(true); // a "Columns" popover to hide and show columns
table.setCsvExport("invoices.csv"); // "Export CSV"
- The column chooser lists the columns with a header text. Hidden columns are hidden with a class, so sorting and paging are unaffected;
setColumnVisible(index, false)hides one from code. - The CSV export writes every row, on every page, in the current sort order. It has the columns with a header and a value (any
IExportableColumn, which includes the Oat value columns), in UTF-8 with a byte order mark so spreadsheet apps read it correctly. Numbers stay plain (1234.5), dates are ISO 8601, and text a spreadsheet would run as a formula (=,+,-,@) is prefixed with'.OatCsvExport.write(...)gives you the same file elsewhere.
Paging other lists #
OatPagingNavigator and OatAjaxPagingNavigator render Wicket's navigators as Oat pagination, for any IPageable (DataView, PageableListView, DataTable, OatDataTable):
add(new OatAjaxPagingNavigator("navigator", dataView)); // the view or a parent needs a markup id
For a DataTable of your own, OatNavigationToolbar and OatHeadersToolbar (in components.table) are OatDataTable's paging row and column headers: over Ajax with plain links as the fallback, the headers with aria-sort:
table.addTopToolbar(new OatHeadersToolbar<>(table, provider));
table.addBottomToolbar(new OatNavigationToolbar(table));
CRUD #
OatCrud is a table of records with everything to manage them: "New" above it, Edit and Delete in every row's menu, an edit dialog, and a confirmation before deleting.
OatCrud<Customer, String> customers = new OatCrud<>("customers", columns, provider, 20)
.setEditor((id, customer) -> new CustomerFields(id, customer))
.setNewItem(Customer::new)
.setTitle(Customer::getName)
.setOnSave((target, customer) -> repository.save(customer))
.setOnDelete((target, customer) -> repository.delete(customer));
add(customers);
The editor is a panel of fields. It gets a CompoundPropertyModel over the record; pass it on to the panel, and fields named after properties bind by themselves:
public class CustomerFields extends Panel {
public CustomerFields(String id, IModel<Customer> customer) {
super(id, customer);
add(new OatTextField<String>("name").setRequired(true));
add(new OatEmailField("email"));
add(new OatDropdownChoice<String>("country", Model.ofList(COUNTRIES)));
}
}
- Saving: Save writes the fields to the record only when they are all valid, then calls the
setOnSavecallback; Cancel leaves the record as it was, and the dialog's fields and the record are dropped once it closes. Report an error on a field in that callback (nameField.error("Already taken")) to keep the dialog open. - Loading: a record to edit is loaded through the provider's
model(...), so aLoadableDetachableModelgivesonSavea fresh entity. - Options: "New" shows only with
setNewItem, Edit only with an editor, and Delete only withsetOnDelete.setSearch(id -> ...)puts a search field beside "New", andgetDataTable()gives the table for selection, the column chooser or CSV export.
Trees #
OatTree and OatTableTree are Wicket's NestedTree and TableTree, styled with Oat instead of Wicket's image themes. Children load only when their parent is expanded, through an ITreeProvider:
public class FolderProvider implements ITreeProvider<Folder> {
public Iterator<? extends Folder> getRoots() { return folders.roots().iterator(); }
public boolean hasChildren(Folder folder) { return folders.hasChildren(folder); }
public Iterator<? extends Folder> getChildren(Folder folder) { return folders.children(folder).iterator(); }
public IModel<Folder> model(Folder folder) { return new FolderModel(folder); }
public void detach() { }
}
A tree #
add(new OatTree<>("folders", new FolderProvider())
.setLabel(Folder::name)
.setIcon(folder -> folder.isEmpty() ? "file" : "folder")
.setOnSelect((target, folder) -> { files.show(folder); target.add(files); }));
With setOnSelect, labels become links and the selected node is marked with aria-current. Nodes are compared by the provider's models, so they need a meaningful equals.
A tree grid #
Put a TreeColumn among ordinary data table columns:
List<IColumn<Account, String>> columns = List.of(
new TreeColumn<>(Model.of("Account")),
new LambdaColumn<>(Model.of("Number"), Account::number),
new OatNumberColumn<Account, String>(Model.of("Balance"), Account::balance).setCurrency(EUR));
add(new OatTableTree<>("accounts", columns, new AccountProvider(), 50).setLabel(Account::name));
Rows are paged, headers sort with an ISortableTreeProvider, and an empty tree shows "Nothing to show". In both trees the expand buttons are real buttons with aria-expanded and an "Expand {name}" / "Collapse {name}" label, and focus stays on the button after a toggle. tree.expand(node) opens a node from code.
Page building blocks #
Page header #
OatPageHeader is a Border on a <header>: breadcrumb, title and subtitle on one side, and the tag's own content as the actions on the other.
<header wicket:id="pageHeader">
<div wicket:id="quickNote"></div>
<div wicket:id="newInvoice"></div>
</header>
OatPageHeader header = new OatPageHeader("pageHeader", Model.of(customer.getName()))
.setSubtitle("Customer since 2019")
.setBreadcrumb(List.of(MenuItem.of("Home", HomePage.class), MenuItem.of("Customers", CustomersPage.class)));
add(header);
header.add(new OatPopover("quickNote", "Quick note", id -> new QuickNotePanel(id, customer)));
header.add(newInvoiceButton);
A long breadcrumb can leave levels out: header.setBreadcrumbMaxItems(3) shows the first level, a "…" button whose menu has the ones in between, and the last ones, counting the page itself. See Breadcrumbs.
Key figures #
add(new OatStatCard("revenue", Model.of("Revenue"), () -> reports.revenue())
.setChange(() -> reports.revenueChange()) // +12.5% on a green badge
.setTrend(() -> reports.last12Months()) // a sparkline under the figure
.setHint(Model.of("vs. last year")));
setChange(model, false) is for figures where lower is better, so a fall shows green. Numbers follow the user's locale; pass a String model for amounts you format yourself.
Record details #
add(new OatDescriptionList("details", new CompoundPropertyModel<>(customer)) // on a <dl>
.addProperty("vatId") // label from the .properties file
.addItem("Billing email", Model.of(customer.getEmail()))
.addItem(Model.of("Status"), id -> new OatBadge(id, "Active", OatVariant.SUCCESS)));
Labels sit beside values, stacked on narrow screens. Numbers and dates follow the locale, and an empty value shows as "—".
Buttons and menus #
// A button for the usual action, joined to a menu of related ones
OatSplitButton newInvoice = new OatSplitButton("newInvoice", "New invoice", target -> ...);
newInvoice.addAction("New quote", target -> ...);
newInvoice.addAction("Archive customer", target -> ...).setVariant(OatVariant.DANGER);
// A button that opens a menu
add(OatDropdown.of("export", "Export", Model.ofList(formats), Format::label,
(target, format) -> export(target, format)));
// A button that opens a panel with any content, e.g. a small form
add(new OatPopover("filter", "Filter", id -> new FilterPanel(id, filter)));
OatButtonGroup joins buttons into one control. Buttons take setVariant, setStyle (outline, ghost) and setSize.
Tabs and accordions #
// Only the selected tab's panel is created; switching swaps it over Ajax
add(new OatTabbedPanel<>("tabs", List.of(
Oat.tab("Profile", ProfilePanel::new),
Oat.tab("Settings", SettingsPanel::new))));
OatTabs renders every panel up front and switches in the browser, for small static content. OatAccordion (or Oat.Behaviors.accordion() on your own <details> elements) shows sections that open one or several at a time.
Steps #
OatWizard fills a form in over several steps. Next validates the current step; Back and the numbers of finished steps go back without validating:
OatWizard wizard = new OatWizard("wizard") {
@Override
protected void onFinish(AjaxRequestTarget target) {
orders.place(order);
setResponsePage(OrderPlacedPage.class);
}
};
wizard.addStep("Customer", id -> new CustomerStep(id, order));
wizard.addStep("Items", id -> new ItemsStep(id, order));
wizard.addStep("Review", id -> new ReviewStep(id, order));
Each step is created when shown, so keep the data in an object all steps share. onNext(step, target) can check a step further and keep the user on it.
The wizard's numbered steps are an OatSteps, which also shows on its own where any process stands, such as an order. The steps before the current one are done, and setOnSelect(...) makes those links back:
add(new OatSteps("progress", List.of("Ordered", "Paid", "Shipped", "Delivered"), () -> order.stage().ordinal()));
List and details #
OatMasterDetail shows a list next to the selected item's details, one at a time on phones with a Back button:
OatMasterDetail<Customer> customers = new OatMasterDetail<>("customers", new Model<>());
customers.setMaster(id -> new CustomerList(id, customers)); // its links call customers.select(target, c)
customers.setDetail((id, customer) -> new CustomerPanel(id, customer));
Histories and notes #
add(new OatTimeline<>("history", () -> orders.history(order), Event::title, Event::at)
.setDescription(Event::details)
.setVariant(event -> event.isPayment() ? OatVariant.SUCCESS : OatVariant.DEFAULT));
OatMessageList<Note> notes = new OatMessageList<>("notes", () -> notesOf(customer), Note::author, Note::text, Note::at);
add(notes);
add(new OatMessageInput("addNote", (target, text) -> { save(customer, text); target.add(notes); }));
Messages show the author's avatar (initials by default), the time in the user's locale and the text with its line breaks.
Smaller pieces #
| Component | Use |
|---|---|
OatAlert | a message in the page, colored by variant |
OatBadge | a short label or count |
OatCard | a container with Oat's card styling |
OatAvatar, OatAvatarGroup | a picture or initials, singly or overlapping |
OatEmptyState | a placeholder for an empty list or search |
OatProgress, OatMeter | <progress> and <meter> |
OatSpinner, OatSkeleton | loading indicators |
OatBreadcrumb | a trail of links |
Behaviors such as Oat.Behaviors.tooltip(text), card(), badge() and alert() give your own components the same looks.
Counts and status dots #
OatIndicator puts a count or a status dot on a corner of what you put in its tag, such as unread messages on a link or a person's presence on their avatar. A count is hidden while it is 0, and target.add(indicator) updates it. OatStatus is the dot on its own, named for screen readers:
// <span wicket:id="inbox"><a wicket:id="link">Inbox</a></span>
add(new OatIndicator("inbox", () -> messages.countUnread()).setVariant(OatVariant.DANGER)
.add(new BookmarkablePageLink<>("link", InboxPage.class)));
// <span wicket:id="presence"><div wicket:id="avatar"></div></span>
add(OatIndicator.status("presence", () -> ada.isOnline() ? OatVariant.SUCCESS : OatVariant.SECONDARY,
() -> ada.isOnline() ? "Online" : "Away")
.add(new OatAvatar("avatar", "AL")));
// <span wicket:id="api"></span> API
add(new OatStatus("api", () -> api.isUp() ? OatVariant.SUCCESS : OatVariant.DANGER,
() -> api.isUp() ? "Online" : "Down"));
A link's own name doesn't include the count. To have it read when the link is focused too, describe the link by the badge: AttributeModifier.replace("aria-describedby", () -> inbox.getItem().getMarkupId()).
Ratings #
OatRatingField chooses a rating from one to five stars, and OatRating shows one, such as a product's average. The field's stars are radio buttons, so the arrow keys move between them and screen readers read "3 stars"; its model holds the number of stars, null while none is chosen. OatRating rounds to half a star and is read as "4.5 out of 5 stars". Both take setMax(n) for up to 10 stars:
form.add(new OatRatingField("rating", "How did we do?", Model.of()).setRequired(true));
// <span wicket:id="score"></span>
add(new OatRating("score", () -> reviews.averageFor(product)));
The stars use the theme's warning color; --oat-rating-color changes it.
Progress rings #
OatRadialProgress is a ring that fills up, with the percentage or a text of yours in the middle, as a progressbar for screen readers. Name it in the markup, and give it a variant for its color:
// <div wicket:id="storage" aria-label="Storage used"></div>
add(new OatRadialProgress("storage", () -> account.usedGigabytes(), () -> account.quotaGigabytes())
.setVariant(() -> account.isNearlyFull() ? OatVariant.DANGER : OatVariant.DEFAULT));
add(new OatRadialProgress("profile", Model.of(3), Model.of(5)).setText(Model.of("3/5")));
Navigation and lists #
Menu bar #
OatMenuBar commands = new OatMenuBar("commands") // on <nav wicket:id="commands" aria-label="Invoice">
.addAction("Save", target -> save(target))
.addLink("Reports", ReportsPage.class); // aria-current while on that page
commands.addMenu("Export")
.addAction("CSV", target -> exportCsv(target))
.addAction(Model.of("Delete all"), OatVariant.DANGER, target -> confirm.ask(...));
add(commands);
Breadcrumbs #
OatBreadcrumb brings its own markup, so its tag stays empty:
// <nav wicket:id="breadcrumb"></nav>
add(OatBreadcrumb.of("breadcrumb", Model.ofList(folders), (item, folder) ->
item.add(new BookmarkablePageLink<>("link", FolderPage.class, folder.parameters())
.add(new Label("label", folder.name()))))
.setMaxItems(3)); // the first, "…", and the last two
The last level is marked aria-current="page", or setCurrent(titleModel) ends the trail with the page itself as text. The <nav> is named "Breadcrumb" in the user's language; a second trail on a page gets a name of its own with setLabel(...) or an aria-label in the markup. A trail without levels isn't shown.
Context menu #
row.add(Oat.Behaviors.contextMenu()
.addAction("Open", target -> open(target, mail))
.addAction(Model.of("Delete"), OatVariant.DANGER, target -> delete(target, mail)));
Right-click, Shift+F10 or the Menu key opens it at the pointer or under the element. Arrow keys move through it, Escape closes it, and focus returns to the element. Give the element a tabindex if it isn't focusable already. It works inside an OatDialog, OatDrawer or OatPopover too.
Split layout #
add(new OatSplitLayout("inbox", id -> new MailList(id), id -> new MailView(id))
.setSplit(40)); // the first pane's starting share, 20-80
The first pane is resizable by dragging its corner (the browser's own resize handle, no script). setOrientation(VERTICAL) stacks the panes; below 768px they are always stacked. Each pane scrolls on its own.
Lists of things #
OatList shows rows the way a phone app lists things: a title and a line under it, with room for an avatar or icon in front and a badge or button at the end. With setOnClick(...) the whole row is a link, and buttons at the end stay clickable on their own:
add(new OatList<>("team", () -> people.all(), Person::name)
.setSubtitle(Person::role)
.setLeading((id, person) -> new OatAvatar(id, person.getObject().initials()))
.setTrailing((id, person) -> new OatBadge(id, person.getObject().status()))
.setOnClick((target, person) -> setResponsePage(PersonPage.class, PersonPage.parameters(person)))
.setEmptyState(id -> new OatEmptyState(id, "No one here yet")));
The parts in front and at the end are on a <div>, so a button goes in a Fragment or panel of yours, on a <button> tag. The rows are read once per request, and each row's model finds its row by position, as in a ListView; setReuseItems(true) keeps form fields in the rows across a failed validation.
Long lists #
OatLoadMoreList shows a batch of items and appends the next one with "Load more", without re-rendering the rest:
add(new OatLoadMoreList<>("mail", provider, 20, (id, mail) -> new MailRow(id, mail))
.setLoadOnScroll(true)); // load as the button comes into view
It keeps loaded rows in the page, so it suits hundreds of items rather than tens of thousands. Call reset(target) after the data changed.
Charts #
Charts are rendered as SVG on the server, with no JavaScript library. Each is a <figure> with a title, a legend from two series on, values on hover, and a "Data" disclosure with the numbers as a table, for screen readers and anyone who wants the exact values.
add(new OatColumnChart<>("monthly", () -> reports.monthly(), Month::label, Month::revenue)
.setTitle("Revenue per month")
.setCategoryHeader(Model.of("Month"))
.setValueFormat((value, locale) -> euros(value, locale)));
add(new OatLineChart<>("trend", () -> reports.monthly(), Month::label)
.addSeries("2026", Month::revenue)
.addSeries("2025", Month::lastYear));
add(new OatBarChart<>("customers", () -> reports.topCustomers(), Row::name, Row::revenue));
add(new OatDonutChart<>("regions", () -> reports.byRegion(), Region::name, Region::revenue));
add(new OatSparkline("orders", () -> reports.dailyOrders())); // on a <span>
| Chart | For |
|---|---|
OatBarChart | comparing categories, especially with long names; rankings |
OatColumnChart | a few ordered categories, such as months |
OatLineChart | change over time, up to three series |
OatDonutChart | a whole in at most six parts; the smallest beyond that become "Other" |
OatSparkline | a small trend without axes, e.g. in a stat card or table |
The colors come from a colorblind-safe palette with separate steps for light and dark themes. Override --oat-chart-1 to --oat-chart-8 in your CSS for your brand.
Icons #
OatIcon draws one of 64 Lucide icons inline, at the text's size and color:
add(new OatIcon("edit", "pencil")); // <svg wicket:id="edit"></svg>
add(new OatIcon("remove", "trash-2").setLabel("Delete")); // role="img" aria-label="Delete"
OatIcon.register("brand", "<path d=\"...\"/>"); // your own, 24x24
Without a label an icon is decorative and hidden from screen readers. OatIcon.names() lists them: arrows and chevrons, pencil, trash-2, plus, search, mail, bell, calendar, user, users, settings, download, upload, file, folder, chart-line and more.
Layout #
Wicket Oat uses Oat's CSS and no other CSS library. Oat styles plain HTML (<button>, <table>, <fieldset>, <details>, ...) by itself, and adds a small, fixed set of utility classes:
| Purpose | Classes |
|---|---|
| Stacks | vstack (a column), hstack (a wrapping row, items centered), both with a gap |
| Flexbox | flex, flex-col, items-center, justify-center, justify-between, justify-end |
| Gap | gap-1, gap-2, gap-4, gap-6 |
| Margin | mt-2, mt-4, mt-6, mt-8, mb-2, mb-4, mb-6, mb-8 |
| Padding, width | p-4, w-100 |
| Text | align-left, align-center, align-right, text-light, text-lighter |
| Lists and links | unstyled on a ul/ol (no bullets) or an a (no link styling) |
| Grid | container, row, col-1 ... col-12, offset-1 ... offset-6 |
The numbers are steps of Oat's spacing scale, and only these exist: there is no gap-3 or mt-5. The grid drops to one column on narrow screens. From Java, Oat.Behaviors.row(), col(span), col(span, offset), container(), hstack() and vstack() add the same classes, also to Oat fields.
<div class="row">
<article wicket:id="revenue" class="col-4"></article>
<article wicket:id="orders" class="col-4"></article>
<article wicket:id="average" class="col-4"></article>
</div>
For anything else, write your own CSS with Oat's variables (var(--space-4), var(--primary), var(--border), ...), so it follows the theme.
wicket-oat.css adds two things of its own: a <kbd> looks like a key to press, and oat-divider draws a line with a word in the middle, such as "or" between two ways to sign in:
<p>Press <kbd>Ctrl</kbd> + <kbd>K</kbd> to search.</p>
<div class="oat-divider">or</div>
Theming #
Themes #
Wicket Oat ships 19 themes: LIGHT, DARK, MIDNIGHT, NORD, EVERFOREST, TOKYO_NIGHT, ROSE_PINE_DAWN, ROYAL, CLAY, CATPPUCCIN_MOCHA, CATPPUCCIN_LATTE, MATERIAL, DAISY, ULTRAVIOLET, HALLOWEEN, XMAS, WIREFRAME, and BUSINESS / BUSINESS_DARK, a sober pair for line-of-business apps. OatAppLayout applies the user's theme as data-theme on <html>; the choice is kept in a cookie, so it outlives the session.
WicketOats.install(this)
.setDefaultTheme(OatTheme.LIGHT) // null follows the browser
.addTheme(new OatTheme("brand", "Brand", "🏷️")); // defined in your CSS
OatTheme.setCurrent(OatTheme.NORD); // during any request
add(new OatThemeSwitcher("themes")); // a picker for all themes, with stateless links
card.add(Oat.Behaviors.theme(OatTheme.LIGHT)); // one component pinned to a theme
A custom theme is a CSS block that overrides Oat's variables:
[data-theme="brand"] {
color-scheme: light;
--background: #fbfaf7;
--primary: #0b6e4f;
--primary-foreground: #ffffff;
}
To keep the choice elsewhere, such as in a user profile, pass an OatThemeStore to setThemeStore(...) (SessionThemeStore is built in). Without OatAppLayout, put an OatHtml on your <html wicket:id="html"> tag: add(new OatHtml("html")).
Density #
OatDensity.COMPACT tightens the spacing and uses smaller body text, for data-heavy apps:
WicketOats.install(this).setDensity(OatDensity.COMPACT); // the whole app
table.add(Oat.Behaviors.density(OatDensity.COMPACT)); // or one component
Translations #
The texts Wicket Oat renders itself (button labels, "Load more", validation messages, screen reader labels, ...) are Wicket resources in English, German, Spanish, French, Italian, Japanese, Dutch and Portuguese. They follow the component's locale, like Wicket's own messages.
To change a text or add a language, define its key in the properties of your page or of a base page, e.g. BasePage_de.properties:
OatDialog.confirm=Speichern
OatCrud.new=Neuer Kunde
A component's own properties are found before the application's, so to use MyApplication_de.properties instead, have Wicket search it first:
getResourceSettings().getStringResourceLoaders()
.add(0, new ClassStringResourceLoader(MyApplication.class));
Every key is in the library's .properties files next to its component; the key names start with the component's name, such as OatDataTable.selected.
Security and resources #
Content Security Policy #
Wicket Oat works under Wicket's default strict, nonce-based CSP. It renders no inline scripts or style attributes, and install adds just img-src data: (for icons in Oat's CSS). Add sources for your own content yourself:
getCspSettings().blocking().add(CSPDirective.IMG_SRC, "https://images.example.com");
The few components that need a script of their own (the context menu, inline editing, autocomplete lists in dialogs, loading on scroll, and form fields, dialogs, avatars and filter chips) share wicket-oat.js, which Wicket renders with the page's nonce and which only reads data- attributes. They need nothing added to the policy.
Resources #
install adds Oat's CSS and JavaScript to every page. The references are public (WicketOats.OAT_CSS, OAT_JS, THEMES_CSS, WICKET_OAT_CSS, WICKET_OAT_JS), so Wicket's resource replacement can swap them, e.g. for a CDN:
addResourceReplacement(WicketOats.OAT_JS,
new UrlResourceReference(Url.parse("https://cdn.example.com/oat.min.js")));
// Or add them only to the pages that use Oat:
WicketOats.install(this).setAddResources(false);
// in those pages' renderHead(IHeaderResponse response):
WicketOats.renderResources(response);
Other safeguards #
- Text is escaped everywhere; models never reach the page as raw HTML.
OatConfirmDialogkeeps the confirmed action on the server, so the browser can only run the action that was asked about, once, and forgets it when the user cancels.OatLoginFormgives the session a new id after signing in, against session fixation, and its error doesn't reveal whether the username exists.OatUserMenu's "Sign out" is refused when another site's page sends it. For all of an application's requests, add Wicket'sResourceIsolationRequestCycleListener.- The CSV export defuses spreadsheet formulas, and the cookie consent cookie is HttpOnly and SameSite.
Accessibility #
The components are built to work with a keyboard and screen readers without extra work:
- Forms: labels are real
<label>s or<legend>s; errors and hints are tied to their inputs witharia-describedbyandaria-invalid; required fields say so witharia-required. - Tables: sortable headers set
aria-sort; checkboxes, row actions and detail toggles have names such as "Select row", "Actions" or "Show details". - Menus and dialogs: dialogs use the native
<dialog>, which traps focus; menus work with the arrow keys and Escape and give focus back to what opened them. - Trees: expand buttons are
<button>s witharia-expanded; the selected node hasaria-current. - Charts: every chart has its numbers in a table; the plot is one image with the chart's title as its name.
- Icons are hidden from screen readers unless they have a label; status colors always come with text.
Testing #
Oat components are Wicket components, so WicketTester tests them. A few paths help:
// A field's input is its child "input"
FormTester form = tester.newFormTester("form");
form.setValue("name:input", "Ada");
form.submit();
// An OatDialog's form: "<dialog>:dialog:form", its fields in "content", its confirm button ":confirm"
FormTester dialogForm = tester.newFormTester("edit:dialog:form");
dialogForm.setValue("content:name:input", "Grace");
tester.executeAjaxEvent("edit:dialog:form:confirm", "click");
// Closing it in the browser (Cancel, Escape, the backdrop) is an Ajax "close" event
tester.executeAjaxEvent("edit:dialog", "close");
// Table rows are recreated on every render; find their components by type
List<AjaxCheckBox> rowChecks = new ArrayList<>();
page.visitChildren(AjaxCheckBox.class, (box, visit) -> rowChecks.add((AjaxCheckBox) box));
// Check a box as the browser would: a POST parameter, then its Ajax behavior
AjaxCheckBox first = rowChecks.get(1); // 0 is "select all"
tester.getRequest().getPostParameters().setParameterValue(first.getInputName(), "on");
tester.executeBehavior(first.getBehaviors(AjaxFormComponentUpdatingBehavior.class).get(0));
Install Wicket Oat in the tester's application as in your own, e.g. a MockApplication whose init() calls WicketOats.install(this); the busy indicator and the page resources depend on it. A data table's sorting and paging links are Ajax links, so tester.clickLink(...) runs them over Ajax.
In an OatWizard, a finished step's link is at "steps:list:items:0:link", and an OatRatingField is set like any field, to its number of stars: form.setValue("rating:input", "4").
A field shows the error of an Ajax submit without being re-rendered, so its message is in a script of the response, WicketOat.fieldFeedback(...). An OatUserMenu signs out with a form: tester.submitForm("user:dropdown:menu:signOut"). An OatFilter is chosen as the browser posts it: set the chip's value for the choice's input name, then fire "change" on "status:form:choice". A breadcrumb's levels are at "breadcrumb:list:items:0:link", numbered among all levels, also after a "…" menu.
Coding agents #
Wicket Oat ships an Agent Skill in the repository's wicket-oat/ folder: a SKILL.md and reference files describing every component and behavior. Copy it into your agent's skills folder, for example for Claude Code:
cp -r wicket-oat .claude/skills/wicket-oat
The agent then understands requests like "add an Oat data table of invoices with a search toolbar and a delete action".
Other agents #
For Codex, Cursor, Copilot, Gemini CLI and any other agent, paste these rules into the instructions file it reads in every session: AGENTS.md, CLAUDE.md or .github/copilot-instructions.md. They are what agents most often get wrong, and they are short because they load every time:
## Wicket Oat
- Wicket Oat components are Apache Wicket components: Java objects bound to models, each
attached to a tag in the page's HTML by `wicket:id` and rendered on the server. Do not
write React, Thymeleaf or JSP.
- Call `WicketOats.install(this)` in `WebApplication.init()`. Pages extend
`OatAppLayout` (sidebar and top bar) or `OatMobileLayout`, or put
`new OatHtml("html")` on `<html wicket:id="html">`.
- Give each component the tag its reference entry names (`OatButton` on `<a>` or
`<button>`). Most components bring their own inner markup, so the tag stays empty:
`<a wicket:id="save"></a>`.
- Use the lambda factories instead of anonymous subclasses:
`OatButton.onClick(id, label, target -> ...)`,
`OatSubmitButton.onSubmit(id, label, target -> ...)`. `OatButton` never submits a
form; `OatSubmitButton` does.
- Put a `CompoundPropertyModel` on the form; Oat fields take their model and their label
(from the page's `.properties` file) by id. After an Ajax submit the fields show and
clear their own errors, so don't add `target.add(form)`.
- Show messages with Wicket's `success(...)`/`error(...)` and
`Oat.Behaviors.feedbackToasts()` on the page or an `OatFeedbackPanel`;
`Oat.toast(target, ...)` is for a one-off toast.
- Style with semantic HTML and Oat's own classes only (`hstack`, `vstack`, `gap-2`,
`mt-4`, `row`, `col-6`); never Bootstrap or Tailwind classes. `Oat.Behaviors` styles
any Wicket component (`button()`, `badge(OatVariant.SUCCESS)`, `card()`).
- Write no inline styles, `<script>` blocks or `on*` handlers: Wicket's strict
Content-Security-Policy stays on. Put CSS in the application's stylesheet, using Oat's
variables (`var(--space-4)`, `var(--primary)`).
- An icon-only button needs an `aria-label` or a labelled `OatIcon`.
- Render every changed page in a `WicketTester` test (`tester.startPage(MyPage.class)`):
Wicket fails when a `wicket:id` is missing from the markup or from the Java.
- Docs: read https://danielbartl.github.io/wicket-oat/llms.txt, and the component's
entry in the components reference before using it.
The docs for agents follow the llms.txt convention: llms.txt has the same rules and links to the user guide and the references as Markdown, from the current release's tag, and llms-full.txt has all of them in one file. Without a rules file, a prompt like this gets an agent started: "Read https://danielbartl.github.io/wicket-oat/llms.txt, then add a delete confirmation to the invoices table."
What's new in 0.6.0 #
0.6.0 is a release of fixes, from a review of the whole library:
- Multi-select fields show the model's current value, so one dialog can edit one record after another without saving the first one's chips into the next. See Choosing several values.
- Sign out can't be sent from another site's page any more, in Firefox and Safari too. See The user menu.
- Row actions are checked against
setVisibleWhenagain when clicked. See Row actions. - Fields:
OatTagInput's text box has the label, hint and error for screen readers and submits text typed without Enter, and an upload's error no longer goes away on an unrelated Ajax request. - In dialogs: context menus work inside an
OatDialog,OatDrawerorOatPopover. - Tables and charts:
OatDateColumnshows everyjava.timevalue in every style instead of failing the page, anOatDonutChartcounts parts alike once, and the "select all" box no longer queries the data provider again. - Loading: lazy panels load 0.1 seconds after the page and check every second while they wait, instead of ten times a second, and loading on scroll keeps going when an Oat field comes before the list.
- Setup:
WicketOats.installleaves a turned-off CSP off, and the cookie consent works on Servlet 5 containers.
Upgrading from 0.5.x #
- Lazy loading:
OatLazyLoadPanel.getUpdateInterval()is a second, as in Wicket (it was 0.1 seconds). - Tag inputs:
OatTagInput's label, hint, error andsetPlaceholder(...)belong to its text box, a component now at"tags:taginput:text"in a test; the tags are still submitted in"tags:input". - Sign out answers 403 Forbidden when another site's page sends it.
- CSP:
WicketOats.installadds no source to a policy turned off withdisabled()orclear(). - Row actions need a row model that loads the row again for their check on click; their cells and buttons have markup ids.
- Fields of your own can point the
<label>elsewhere withBaseOatField.getLabelTarget().
The changelog lists every change.
Something missing or unclear? Open an issue on GitHub.