Utility functions missing from Vaadin 14+, for your Kotlin-based projects.
The jar is in Maven Central, so it's easy to add this library to your project.
Gradle:
repositories {
mavenCentral()
}
dependencies {
api("com.github.mvysny.karibu-tools:karibu-tools:x.y")
}Note: for Vaadin 23+, depend on
karibu-tools-23instead, to bring some additional utilities.
See the tag above for the latest version.
A set of general Vaadin utilities applicable to all components.
- Retrieve the
VaadinVersion.getproperty to get the Vaadin version such as 14.7.0 - call
VaadinVersion.flowto obtain the Vaadin Flowflow-server.jarversion: for example 2.6.7 for Vaadin 14.6.8.
- Call
component.fireEvent()to fire any event on the component (a shortcut toComponentUtil.fireEvent()). - Call
ClickNotifier.serverClick()to notify all click listeners (to fire aClickEvent).
- Call
Component.findAncestor()orComponent.findAncestorOrSelf()to discover component's ancestor which satisfies given predicate. - call
Component.removeFromParent()to remove the component from its parent. - call
Component.isNestedIn(potentialAncestor: Component)to discover whether a component is nested within given potential ancestor. - query
Component.isAttached()to see whether this component is currently attached to an UI. Already implemented in newer Vaadin. - call
HasOrderedComponents<*>.insertBefore()to insert a component before given component. - query
HasComponents.hasChildrento see whether a component has any children. Component.walk()will return anIterable<Component>which walks the component child tree, depth-first: first the component, then its descendants, then its next sibling.
- get/set
component.textAlignto read/write thetext-alignCSS property - get/set
component.tooltipto read/write the hovering tooltip (thetitleCSS property) - call
Component.addContextMenuListener()to add the right-click context listener to a component. Also causes the right-click browser menu not to be shown on this component. - query
UI.currentViewLocationto return the location of the currently shown view. - call
div.addClassNames2(" foo bar baz")to add multiple class names. Vote for flow #11709.- also
div.removeClassNames2()anddiv.setClassNames2()
- also
component.placeholderunifies the various component placeholders, usually shown when there's no value selected. Vote for flow #4068.component.captionunifies component captions. Caption is displayed directly on the component (e.g. the Button text), while label is displayed next to the component in a layout (e.g. form layout).component.labelunifies component labels. Takes advantage ofHasLabelin newer Vaadin.- Use
LabelWrapperif you need to add a label on top of a component which doesn't support labels, and you can't nest the component in aFormLayout. component.ariaLabelgets/sets thearia-labelattribute. SeeHasAriaLabelin Vaadin 23+ for more details. Since 0.17.
- call
ClassList.toggleto set or remove given CSS class. - call
Element.setOrRemoveAttributeto set an attribute to given value, or remove the attribute if the value is null. Element.insertBefore()to insert a child element before another child. A counterpart for JavaScript DOMNode.insertBefore().Element.textRecursively2returns all the text recursively present in the element. Vote for flow #3668.Element.getVirtualChildren()Returns all virtual child elements added viaElement.appendVirtualChild.StateNode.elementreturnsElementfor thatStateNode.Element.getChildrenInSlot("prefix")will return all child elements nested in theprefixslot.Element.clearSlot("prefix")will remove all child elements nested in theprefixslot.
Navigating:
- Call
navigateTo<AdminRoute>()ornavigateTo(AdminRoute::class)ornavigateTo(DocumentRoute::class, 25L). - Call
navigateTo(String)to navigate anywhere within the app. Supports query parameters as well:""(empty string) - the root view.foo/bar- navigates to a viewfoo/25- navigates to a view with parametersfoo/25?token=bar- any view with parameters and query parameters?token=foo- the root view with query parameters
- Call
navigateTo(getRouteUrl(AdminRoute::class, "lang=en"))to navigate toadmin?lang=en. - To obtain the route class from
AfterNavigationEvent, queryevent.routeClass - To obtain the route class from a
Location, calllocation.getRouteClass()
QueryParameters:
-
call
queryParameters["foo"]to obtain the value of the?foo=barquery parameter. -
call
queryParameters.getValues("foo")to get all values of thefooquery parameter. -
call the
QueryParameters("foo=bar")factory method to parse the query part of the URL to the VaadinQueryParametersclass. -
RouterLink.targetallows you to setAnchorTargetValue, e.g.AnchorTargetValue.BLANK. Since 0.16 -
RouterLink.setOpenInNewTab()opens the router link in new browser tab/window (sets target toAnchorTargetValue.BLANK). Since 0.16 -
Anchor.target_clears up the Anchor mess by adding yet another property :-D Since 0.16 -
Anchor.setOpenInNewTab()opens the anchor in new browser tab/window (sets target toAnchorTargetValue.BLANK). Since 0.16
In order to properly display LocalDate and LocalDateTime on client's machine, you need
to fetch the browser's TimeZone first. You can achieve that simply by calling BrowserTimeZone.fetch(),
for example when the Vaadin UI is being initialized.
fetch() will request the information from
the browser and will store it into the session. Afterwards, simply
call BrowserTimeZone.get to get the browser's time zone instantly.
- Call
BrowserTimeZone.currentDateTimeto get the current date time at browser's current time zone.
The following functions are applicable to any field that edits text, e.g.
TextField, TextArea, EmailField:
- Call
field.selectAll()to select all text within the field. - Call
field.selectNone()to select no text - Call
field.setCursorLocation()to place the cursor at given character - Call
field.select(range)to select a range within the text.
- Use
dataProvider.fetchAll()to fetch all items provided by this data provider as an eager list. Careful with larger data! - Use
Person::name.asc/Person::name.descto create aQuerySortOrderwhich is useful with DataProvider'sQuery.sortOrdersorGrid.sort().
- Use
Grid.refresh()to callDataProvider.refreshAll() - Selection:
- Check
Grid.isMultiSelectto see whether a grid is configured as multi-select. - Check
Grid.isSingleSelectto see whether a grid is configured as single-select. Grid.isSelectionEmptyreturns true if there's nothing selected in the grid.Grid.selectionModeallows you to read/write the current selection mode.Grid.isSelectionAllowedreturns false ifGrid.SelectionMode.NONEis currently set.
- Check
- Multitude overloaded
Grid.addColumnFor()which allow you to create a column using given converter or renderer to format a value. Allows both for passing inKPropertyor a property by name. For example,grid.addColumnFor(Person::name)will create a sortable column displaying a name of a person, setting the column header to "Name". - Multitude overloaded
TreeGrid.addHierarchyColumnFor()which allow you to create a column using given converter or renderer to format a value. Allows both for passing inKPropertyor a property by name. For example,grid.addHierarchyColumnFor(Person::name)will create a sortable column displaying a name of a person, setting the column header to "Name". Grid.getColumnBy(Person::name)retrieves a column created viagrid.addColumnFor(Person::name).HeaderRow.getCell(Person::name)retrieves header cell for given column.- Similarly,
FooterRow.getCell(Person::name)retrieves footer cell for given column. HeaderCell.component/FooterCell.componentsets or returns a component set to given cell.grid.sort()sorts the grid:grid.sort(nameColumn.asc)sorts ascending by given column;grid.sort(Person::name.asc)sorts ascending by column created viagrid.addColumnFor(Person::name)
treeGrid.getRootItems()will fetch the root itemstreeGrid.expandAll()will expand all nodes; may invoke massive data loading.column.header2returns the header set via thesetHeader()function.basicRenderer.valueProviderreturns theValueProviderset to the renderer.ItemClickEvent.isDoubleClick
Make sure you use these imports:
import com.vaadin.flow.component.Key.*Then:
button.addClickShortcut(Alt + Ctrl + KEY_C)clicks the button when Alt+Ctrl+C is pressed.button.addFocusShortcut(Alt + Ctrl + KEY_C)focuses the button when Alt+Ctrl+C is pressed.route.addShortcut(Alt + Ctrl + KEY_C) { println("Foo") }will cause Vaadin to run given block when Alt+Ctrl+C is pressed. Ideal targets are therefore: routes (for creating a route-wide shortcut), modal dialogs, root layouts, UI.textField.onEnter { println("Enter") }is called when ENTER is pressed while the TextField is focused. (since 0.16)
Make sure to read the Safe JavaScript Keyboard shortcuts article before designing shortcuts for your app.
- Call
MenuBar.close()to close the submenu popup. Vote for #5742. - Call
MenuBar.addIconItem()andSubMenu.addIconItem()to add items with icons. Vote for #2688. Since 0.17.
icon.iconNameprovides a type-safe access to setting icons.icon.setIcon(VaadinIcon)adds the missing API of setting icons.
To use custom icons with Vaadin 14+, see Custom Icons With Vaadin 14.
getAllDialogs()will return all dialogs attached to the UI. There may be closed dialogs since they are cleaned up lately by Vaadin.dialog.center()centers the dialog within the screen. Vote for #220dialog.requestClose()honors listeners registered viaaddDialogCloseActionListener().
button.setPrimary()adds theButtonVariant.LUMO_PRIMARYtheme.
notification.getText()returns the text set to the notification. Vote for #2446.notification.addCloseButton()adds a close button, which makes the notification closeable by the user (and the duration of0starts making sense). Vote for #438.
PageConfigurator is now deprecated, the suggestion is to use BootstrapListener but there
are no utility methods to add meta tags etc! Therefore we introduce the following utility methods (see examples below):
Element.addMetaTag()(since 0.5) adds a<meta name="foo" content="baz">element to the html head.
class MyServiceInitListener : VaadinServiceInitListener {
override fun serviceInit(event: ServiceInitEvent) {
event.addBootstrapListener {
it.document.head().addMetaTag("apple-mobile-web-app-capable", "yes")
it.document.head().addMetaTag("apple-mobile-web-app-status-bar-style", "black")
}
}
}Upload.isEnabled(since 0.5) allows you to enable or disable the upload component. Vote for #2182Upload.clear()(since 0.6) clears the list of uploaded files. Present asUpload.clearFileList()in newer Vaadin.
AbstractLogin.setErrorMessage(title: String?, message: String?)(since 0.5) shows an error message and setssetError(true). Vote for issue #1525
setItemLabelGenerator()sets the item label generator. Since 0.6. Implemented in newer Vaadin.
The HtmlSpan component (since 0.6) has an advantage over Vaadin-provided Html -
it will accept any HTML snippet and will set it as an innerHTML to a <span> element.
- Implemented
ComboBoxVariant,addThemeVariants()andremoveThemeVariants(). Only applicable to Vaadin 14, since Vaadin 22+ has built-in support for these functions. ComboBox.isSmalltoggles thesmallthemeComboBox.isHelperAboveFieldtoggles thehelper-above-fieldthemeComboBox.textAligntoggles thealign-left/align-center/align-righttheme.ComboBox.dropdownWidthsets a custom dropdown popup overlay width to e.g.100pxor30em. See+vote for Issue #2331.ComboBox.prefixComponentsets a custom prefix component. Already available in Vaadin 24+, but handy for Vaadin 23 and lower.
DatePicker.prefixComponentsets a custom prefix component. Already available in Vaadin 24+, but handy for Vaadin 23 and lower.
- Implemented
SelectVariant,addThemeVariants()andremoveThemeVariants().- Already available in Vaadin 23.1+, but handy for Vaadin 14.
Select.isSmalltoggles thesmallthemeSelect.isHelperAboveFieldtoggles thehelper-above-fieldthemeSelect.textAligntoggles thealign-left/align-center/align-righttheme.Select.prefixComponentsets a custom prefix component. Already available in Vaadin 24+, but handy for Vaadin 23 and lower.
ListBox.setItemLabelGenerator()sets the label generator. Present in newer Vaadin, both inListBoxandMultiSelectListBox.
Validator.isValid("foo")will run the validator on given value and will return either true or false, depending on whether the value passed or not. (since 0.16)rangeValidatorOf("must be 0 or greater", 0, null)accepts nulls for min/max. (since 0.16)
Since 0.18; depend on karibu-tools-23 to gain access to these utility functions.
- Use
Tab.indexto obtain the index of the tab. Tab.ownerreturns theTabsowning this tabTab.ownerTabSheetreturns theTabSheetowning this tab.Tab.contents/TabSheet.getComponent()returns the contents component of given tab (TabSheet only)TabSheet.tabCountreturns the number of the tabsTabSheet.removeAll()removes all tabsTabSheet.tabsreturns aList<Tab>of all tabsTabSheet.getTab()returnsTabfor its content component (TabSheet only)TabSheet.findTabContaining()returnsTabwhich transitively contains given component.
Java: use TabSheetsKt.getTab() etc.
Licensed under Apache 2.0
Copyright 2021-2022 Martin Vysny
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this software 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.
See Contributing.