io.devbench.uibuilder.components.form.UIBuilderFormRegistry Maven / Gradle / Ivy
/*
*
* Copyright © 2018 Webvalto Ltd.
*
* Licensed 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 io.devbench.uibuilder.components.form;
import org.jetbrains.annotations.NotNull;
import org.jsoup.nodes.Element;
import java.io.Serializable;
import java.util.Optional;
public final class UIBuilderFormRegistry {
private static UIBuilderFormSetProvider formSetProvider = new UIBuilderFormSetVaadinSessionProvider();
private UIBuilderFormRegistry() {
throw new UnsupportedOperationException();
}
public static void setFormSetProvider(UIBuilderFormSetProvider formSetProvider) {
UIBuilderFormRegistry.formSetProvider = formSetProvider;
}
static void register(UIBuilderForm> form) {
formSetProvider.getFormSet().add(form);
}
static void updateFormTree() {
formSetProvider.getFormSet().forEach(form -> Optional.ofNullable(form.getRawElement())
.ifPresent(rawElement -> findParentFormElement(rawElement)
.ifPresent(parentFormRawElement -> getByRawElement(parentFormRawElement)
.ifPresent(form::setParentForm))));
}
@SuppressWarnings("unused")
public static Optional> getById(@NotNull String formId, Class itemClass) {
return getById(formId);
}
@SuppressWarnings("unchecked")
public static Optional> getById(@NotNull String formId) {
for (UIBuilderForm> form : formSetProvider.getFormSet()) {
if (isFormIdMatch(form, formId)) {
return Optional.of((UIBuilderForm) form);
}
}
return Optional.empty();
}
private static boolean isFormIdMatch(@NotNull UIBuilderForm form, @NotNull String id) {
return form.getId().map(id::equals).orElse(false);
}
@SuppressWarnings("unchecked")
private static Optional> getByRawElement(Element element) {
for (UIBuilderForm> form : formSetProvider.getFormSet()) {
if (element.equals(form.getRawElement())) {
return Optional.of((UIBuilderForm) form);
}
}
return Optional.empty();
}
private static Optional findParentFormElement(@NotNull Element element) {
Element e = element;
while ((e = e.parent()) != null) {
if (UIBuilderForm.TAG_NAME.equals(e.tagName())) {
return Optional.of(e);
}
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
static UIBuilderForm findTopMostForm(@NotNull UIBuilderForm> childForm) {
UIBuilderForm> currentForm = childForm;
while (currentForm.getParentForm() != null) {
currentForm = currentForm.getParentForm();
}
return (UIBuilderForm) currentForm;
}
}